def _remove_heist(self, ctx, *, target: str):
"""Remove a target from the heist list"""
author = ctx.message.author
settings = self.check_server_settings(author.server)
if string.capwords(target) in settings["Targets"]:
await self.bot.say("Are you sure you want to remove {} from the list of "
"targets?".format(string.capwords(target)))
response = await self.bot.wait_for_message(timeout=15, author=author)
if response is None:
msg = "Canceling removal. You took too long."
elif response.content.title() == "Yes":
settings["Targets"].pop(string.capwords(target))
self.save_system()
msg = "{} was removed from the list of targets.".format(string.capwords(target))
else:
msg = "Canceling target removal."
else:
msg = "That target does not exist."
await self.bot.say(msg)
python类capwords()的实例源码
def patch_2220(self, path):
# Check if player data has the war game, and if not add it.
if "Theme" not in path or not path["Theme"]:
path["Theme"] = {"Jail": "jail", "OOB": "out on bail", "Police": "Police",
"Bail": "bail", "Crew": "crew", "Sentence": "sentence",
"Heist": "heist", "Vault": "vault"},
if "Banks" in path:
path["Targets"] = path.pop("Banks")
if "Theme" not in path["Config"]:
path["Config"]["Theme"] = "Heist"
if "Crew Output" not in path["Config"]:
path["Config"]["Crew Ouput"] = "None"
if "Bail Cost" in path["Config"]:
path["Config"].pop("Bail Cost")
for target in path["Targets"]:
path["Targets"][string.capwords(target)] = path["Targets"].pop(target)
self.save_system()
def jeopardy_start(self, ctx):
if self.jeopardy_active:
await self.bot.embed_reply(":no_entry: There's already a jeopardy game in progress")
return
self.jeopardy_active = True
categories = []
category_titles = []
self.jeopardy_board_output = ""
url = "http://jservice.io/api/random"
for i in range(6):
async with clients.aiohttp_session.get(url) as resp:
data = await resp.json()
categories.append(data[0]["category_id"])
for category in categories:
url = "http://jservice.io/api/category?id=" + str(category)
async with clients.aiohttp_session.get(url) as resp:
data = await resp.json()
category_titles.append(string.capwords(data["title"]))
self.jeopardy_board.append([category, False, False, False, False, False])
self.jeopardy_max_width = max(len(category_title) for category_title in category_titles)
for category_title in category_titles:
self.jeopardy_board_output += category_title.ljust(self.jeopardy_max_width) + " 200 400 600 800 1000\n"
await self.bot.embed_say(clients.code_block.format(self.jeopardy_board_output))
def _get_es_results(query: str, category: str, keyphrase: str, strict: bool) -> Response:
skill_search = es_search
if category:
skill_search = skill_search.query('match',
category=string.capwords(category)
.replace(' And ', ' & ')
.replace('Movies & Tv', 'Movies & TV'))
if keyphrase:
skill_search = skill_search.query('match', keyphrases=keyphrase)
if query:
operator = 'and' if strict else 'or'
skill_search = skill_search.query('multi_match',
query=query,
fields=['name', 'description', 'usages', 'keyphrases'],
minimum_should_match='50%',
operator=operator) \
.highlight('description', order='score', pre_tags=['*'], post_tags=['*']) \
.highlight('title', order='score', pre_tags=['*'], post_tags=['*']) \
.highlight('usages', order='score', pre_tags=['*'], post_tags=['*'])
return skill_search.execute()
def _extractNVMLErrorsAsClasses():
'''
Generates a hierarchy of classes on top of NVMLError class.
Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate
exceptions more easily.
NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass.
e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized
'''
this_module = sys.modules[__name__]
nvmlErrorsNames = filter(lambda x: x.startswith("NVML_ERROR_"), dir(this_module))
for err_name in nvmlErrorsNames:
# e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
err_val = getattr(this_module, err_name)
def gen_new(val):
def new(typ):
obj = NVMLError.__new__(typ, val)
return obj
return new
new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
new_error_class.__module__ = __name__
setattr(this_module, class_name, new_error_class)
NVMLError._valClassMapping[err_val] = new_error_class
def find_by_url(cls, song_url):
soup = cls.__get_soup(song_url)
og_title_tag = soup.find('meta', attrs={'property': cls.SONG_TITLE_META_OG_PROPERTY})
og_title = og_title_tag.get('content')
song_url_parts = song_url.split('/')
song_id = song_url_parts[4]
title, artist = og_title.split(' - ', 1)
title = capwords(title)
artist = capwords(artist)
song_dict = {
'song_id': song_id,
'title': title,
'artist': artist,
'url': song_url
}
return Song(**song_dict)
def title_case(title, minor_words=''):
if minor_words == '':
return capwords(title)
ignore_words = [w.lower() for w in minor_words.split()]
res = ''; words= title.split()
for i in range(len(words)):
if i == 0:
res += words[0].capitalize()
res += ' '
else:
w = words[i]
if w.lower() not in ignore_words:
res += w.capitalize()
else:
res += w.lower()
res += ' '
return res.strip()
def _extractNVMLErrorsAsClasses():
'''
Generates a hierarchy of classes on top of NVMLError class.
Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate
exceptions more easily.
NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass.
e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized
'''
this_module = sys.modules[__name__]
nvmlErrorsNames = filter(lambda x: x.startswith("NVML_ERROR_"), dir(this_module))
for err_name in nvmlErrorsNames:
# e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
err_val = getattr(this_module, err_name)
def gen_new(val):
def new(typ):
obj = NVMLError.__new__(typ, val)
return obj
return new
new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
new_error_class.__module__ = __name__
setattr(this_module, class_name, new_error_class)
NVMLError._valClassMapping[err_val] = new_error_class
def add_relation(self, colonist):
menu = tk.Menu(self)
for relationship_type in colonist.relationships:
if isinstance(colonist.relationships[relationship_type], dict):
menu_relations = tk.Menu(menu)
for relationship in colonist.relationships[relationship_type]:
if isinstance(colonist.relationships[relationship_type][relationship], list):
menu_sibling = tk.Menu(menu_relations)
for sibling in colonist.relationships[relationship_type][relationship]:
menu_sibling.add_command(label=capwords(sibling.get_name()))
if colonist.relationships[relationship_type][relationship]:
menu_relations.add_cascade(label=capwords(relationship), menu=menu_sibling)
else:
if colonist.relationships[relationship_type][relationship]:
menu_relations.add_command(label=capwords(relationship))
menu.add_cascade(label=capwords(relationship_type), menu=menu_relations)
self.add_cascade(label=colonist.get_name(), menu=menu)
def get_searches(self):
# Try to find both id and film title for each search result
elements = string.split(self.page, "<li>")
self.number_results = elements[-1]
if (elements[0] != ''):
for element in elements:
id = gutils.trim(element, "?codice=", "\">")
if id <> '':
self.ids.append(id)
title = self.capwords(gutils.convert_entities(gutils.trim(element, "<b>", "</b>")))
year = re.search('([[][0-9]{4}[]])', element)
if year:
year = year.group(0)
if year:
self.titles.append(title + ' ' + year)
else:
self.titles.append(title)
else:
self.number_results = 0
#
# Plugin Test
#
def title_case(title, minor_words=''):
if minor_words == '':
return capwords(title)
ignore_words = [w.lower() for w in minor_words.split()]
res = ''; words= title.split()
for i in range(len(words)):
if i == 0:
res += words[0].capitalize()
res += ' '
else:
w = words[i]
if w.lower() not in ignore_words:
res += w.capitalize()
else:
res += w.lower()
res += ' '
return res.strip()
def parseLine(self, line):
"""
Parse a log line creating necessary events.
:param line: The log line to be parsed
"""
m = self.getLineParts(line)
if not m:
return False
match, action, data, client, target = m
func = 'On%s' % string.capwords(action).replace(' ', '')
if hasattr(self, func):
func = getattr(self, func)
event = func(action, data, match)
if event:
self.queueEvent(event)
elif action in self._eventMap:
self.queueEvent(self.getEvent(self._eventMap[action], data=data, client=client, target=target))
else:
data = str(action) + ': ' + str(data)
self.queueEvent(self.getEvent('EVT_UNKNOWN', data=data, client=client, target=target))
def parse_line(self, line):
"""
Parse a log line creating necessary events.
:param line: The log line to be parsed
"""
m = self.getLineParts(line)
if not m:
return False
match, action, data, client, target = m
func = 'On%s' % string.capwords(action).replace(' ','')
if hasattr(self, func):
func = getattr(self, func)
event = func(action, data, match)
if event:
self.queueEvent(event)
elif action in self._eventMap:
self.queueEvent(self.getEvent(self._eventMap[action], data=data, client=client, target=target))
elif action in self._actionMap:
# addition for cod5 actionMapping
self.translateAction(action, data, match)
else:
self.queueEvent(self.getEvent('EVT_UNKNOWN', str(action) + ': ' + str(data), client, target))
def _extractNVMLErrorsAsClasses():
'''
Generates a hierarchy of classes on top of NVMLError class.
Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate
exceptions more easily.
NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass.
e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized
'''
this_module = sys.modules[__name__]
nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")]
for err_name in nvmlErrorsNames:
# e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
err_val = getattr(this_module, err_name)
def gen_new(val):
def new(typ):
obj = NVMLError.__new__(typ, val)
return obj
return new
new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
new_error_class.__module__ = __name__
setattr(this_module, class_name, new_error_class)
NVMLError._valClassMapping[err_val] = new_error_class
def extract_metadata_from_pdf(data):
stream = StringIO(data)
# get access token using refresh token.
resp = requests.post('https://api.mendeley.com/oauth/token',
data=('grant_type=refresh_token&refresh_token=%s'
'&redirect_uri=%s'
% (REFRESH_TOKEN, REDIRECT_URI)),
headers={
'Content-Type': 'application/x-www-form-urlencoded'
},
auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
).json()
access_token = resp['access_token']
# assert(resp['refresh_token'] == REFRESH_TOKEN)
# use access token to request paper metadata.
result = requests.post('https://api.mendeley.com/documents',
data=stream.read(),
headers={
'Authorization': 'Bearer %s' % access_token,
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="example.pdf"'
}).json()
result['title'] = string.capwords(result['title']) # convert to same title format.
return result
def cmdln():
"""Setup command line parser.
"""
cmdln = optparse.OptionParser(usage=USAGE, description=DESCR)
cmdln.add_option('-r', dest='recurse', action='store_true',
help='Recurse into subdirs')
cmdln.add_option('-s', dest='silent', action='store_true',
help='Silent mode')
cmdln.add_option('-n', dest='dryrun', action='store_true',
help='dry run/No-op mode (don\'t actually rename)')
cmdln.add_option('-L', dest='lower', action='store_true',
help='make Lower case (string.lower)')
cmdln.add_option('-U', dest='upper', action='store_true',
help='make Upper case (string.upper)')
cmdln.add_option('-C', dest='capwords', action='store_true',
help='Capitalize words (string.capwords)')
cmdln.add_option('-f', dest='fromchars', default='',
help='translate From FROMCHARS characters (requires -t)')
cmdln.add_option('-t', dest='tochars', default='',
help='translate To TOCHARS characters (requires -f)')
cmdln.add_option('-d', dest='delchars', default='',
help='Delete DELCHARS characters from file names')
cmdln.add_option('-l', dest='limitglob', default='*',
help='Limit file globbing to LIMITGLOB pattern')
opts, args = cmdln.parse_args(sys.argv[1:])
opts.stringfunc = lambda x: x
if opts.capwords: opts.stringfunc = string.capwords
if opts.upper: opts.stringfunc = string.upper
if opts.lower: opts.stringfunc = string.lower
error_checks(cmdln, args, opts)
return opts, args[0]
def func(self, x: Node.dict_indexable):
"""0 - len (floor(log(x)) with numbers)
1 - lower
2 - upper
3 - swapcase
4 - title
5 - capitalize
6 - capwords
7 - strip
8 - lstrip
9 - rstrip"""
if self.config == 0:
return self.len(x)
return Letters.settings[self.config-1](x)
def define(self, ctx, *, word : str):
"""Gives the definition of the word passed."""
# Check if we're suppressing @here and @everyone mentions
if self.settings.getServerStat(ctx.message.server, "SuppressMentions").lower() == "yes":
suppress = True
else:
suppress = False
if not word:
msg = 'Usage: `{}define [word]`'.format(ctx.prefix)
await self.bot.send_message(ctx.message.channel, msg)
return
url = "http://api.urbandictionary.com/v0/define?term={}".format(quote(word))
msg = 'I couldn\'t find a definition for "{}"...'.format(word)
r = requests.get(url, headers = {'User-agent': self.ua})
theJSON = r.json()["list"]
if len(theJSON):
# Got it - let's build our response
ourWord = theJSON[0]
msg = '__**{}:**__\n\n{}'.format(string.capwords(ourWord["word"]), ourWord["definition"])
if ourWord["example"]:
msg = '{}\n\n__Example(s):__\n\n*{}*'.format(msg, ourWord["example"])
# await self.bot.send_message(ctx.message.channel, msg)
# Check for suppress
if suppress:
msg = Nullify.clean(msg)
await Message.say(self.bot, msg, ctx.message.channel, ctx.message.author)
def randefine(self, ctx):
"""Gives a random word and its definition."""
url = "http://api.urbandictionary.com/v0/random"
r = requests.get(url, headers = {'User-agent': self.ua})
theJSON = r.json()["list"]
if len(theJSON):
# Got it - let's build our response
ourWord = theJSON[0]
msg = '__**{}:**__\n\n{}'.format(string.capwords(ourWord["word"]), ourWord["definition"])
if ourWord["example"]:
msg = '{}\n\n__Example(s):__\n\n*{}*'.format(msg, ourWord["example"])
# await self.bot.send_message(ctx.message.channel, msg)
await Message.say(self.bot, msg, ctx.message.channel, ctx.message.author)
def _callback_document_authors(self, request_id, results, exception):
if exception:
raise exception
file_id = self._document_items[request_id]
authors = set()
items = results.get('revisions', [])
if items:
for item in items:
authors.add(string.capwords(item['lastModifyingUser']['displayName']))
authors = list(authors)
authors.sort()
self._documents[file_id].authors = authors
item = self._documents[file_id]
self._write_to_cache(file_id + '_authors', self._documents[file_id].modifiedTime, authors)
def addHeader (self,key,value):
k=string.capwords(key,"-")
if k!="Accept-Encoding":
self.__headers[k]=value
def __getitem__ (self,key):
k=string.capwords(key,"-")
if self.__headers.has_key(k):
return self.__headers[k]
else:
return ""
def addHeader (self,key,value):
k=string.capwords(key,"-")
if k!="Transfer-Encoding":
self.__headers+=[(k,value)]
def addHeader (self,key,value):
k=string.capwords(key,"-")
if k!="Accept-Encoding":
self.__headers[k]=value
def __getitem__ (self,key):
k=string.capwords(key,"-")
if self.__headers.has_key(k):
return self.__headers[k]
else:
return ""
def _processFormal(self, elem, sessionID):
"""Process a <formal> AIML element.
<formal> elements process their contents recursively, and then
capitalize the first letter of each word of the result.
"""
response = ""
for e in elem[2:]:
response += self._processElement(e, sessionID)
return string.capwords(response)
# <gender>
def __setitem__(self, i, y):
self._regexIsDirty = True
# for each entry the user adds, we actually add three entrys:
super(type(self), self).__setitem__(
string.lower(i), string.lower(y)) # key = value
super(type(self), self).__setitem__(
string.capwords(i), string.capwords(y)) # Key = Value
super(type(self), self).__setitem__(
string.upper(i), string.upper(y)) # KEY = VALUE
def normalize(header):
return string.capwords(header.lower(), '-')
def to_camel_case(s):
"""Convert string to camel case."""
return (s[0].lower() + string.capwords(s, sep='_')
.replace('_', '')[1:] if s else s)
def cap_first_word(arg):
if type(arg) == str:
s = arg.strip()
return s[0].upper() + s[1:None]
if type(arg) == list:
return [string.capwords(arg[0])] + arg[1:None]
raise TypeError("Invalid type passed to function: " + type(arg))