repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
UMIACS/qav | qav/validators.py | IPAddressValidator.validate | def validate(self, value):
"""Return a boolean if the value is valid"""
try:
self._choice = IPAddress(value)
return True
except (ValueError, AddrFormatError):
self.error_message = '%s is not a valid IP address.' % value
return False | python | def validate(self, value):
"""Return a boolean if the value is valid"""
try:
self._choice = IPAddress(value)
return True
except (ValueError, AddrFormatError):
self.error_message = '%s is not a valid IP address.' % value
return False | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"_choice",
"=",
"IPAddress",
"(",
"value",
")",
"return",
"True",
"except",
"(",
"ValueError",
",",
"AddrFormatError",
")",
":",
"self",
".",
"error_message",
"=",
"'%s is not a valid IP address.'",
"%",
"value",
"return",
"False"
]
| Return a boolean if the value is valid | [
"Return",
"a",
"boolean",
"if",
"the",
"value",
"is",
"valid"
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L165-L172 | train |
UMIACS/qav | qav/validators.py | IPNetmaskValidator.validate | def validate(self, value):
"""Return a boolean if the value is a valid netmask."""
try:
self._choice = IPAddress(value)
except (ValueError, AddrFormatError):
self.error_message = '%s is not a valid IP address.' % value
return False
if self._choice.is_netmask():
return True
else:
self.error_message = '%s is not a valid IP netmask.' % value
return False | python | def validate(self, value):
"""Return a boolean if the value is a valid netmask."""
try:
self._choice = IPAddress(value)
except (ValueError, AddrFormatError):
self.error_message = '%s is not a valid IP address.' % value
return False
if self._choice.is_netmask():
return True
else:
self.error_message = '%s is not a valid IP netmask.' % value
return False | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"_choice",
"=",
"IPAddress",
"(",
"value",
")",
"except",
"(",
"ValueError",
",",
"AddrFormatError",
")",
":",
"self",
".",
"error_message",
"=",
"'%s is not a valid IP address.'",
"%",
"value",
"return",
"False",
"if",
"self",
".",
"_choice",
".",
"is_netmask",
"(",
")",
":",
"return",
"True",
"else",
":",
"self",
".",
"error_message",
"=",
"'%s is not a valid IP netmask.'",
"%",
"value",
"return",
"False"
]
| Return a boolean if the value is a valid netmask. | [
"Return",
"a",
"boolean",
"if",
"the",
"value",
"is",
"a",
"valid",
"netmask",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L177-L188 | train |
UMIACS/qav | qav/validators.py | URIValidator.validate | def validate(self, value):
'''Return a boolean indicating if the value is a valid URI'''
if self.blank and value == '':
return True
if URIValidator.uri_regex.match(value):
self._choice = value
return True
else:
self.error_message = '%s is not a valid URI' % value
return False | python | def validate(self, value):
'''Return a boolean indicating if the value is a valid URI'''
if self.blank and value == '':
return True
if URIValidator.uri_regex.match(value):
self._choice = value
return True
else:
self.error_message = '%s is not a valid URI' % value
return False | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"blank",
"and",
"value",
"==",
"''",
":",
"return",
"True",
"if",
"URIValidator",
".",
"uri_regex",
".",
"match",
"(",
"value",
")",
":",
"self",
".",
"_choice",
"=",
"value",
"return",
"True",
"else",
":",
"self",
".",
"error_message",
"=",
"'%s is not a valid URI'",
"%",
"value",
"return",
"False"
]
| Return a boolean indicating if the value is a valid URI | [
"Return",
"a",
"boolean",
"indicating",
"if",
"the",
"value",
"is",
"a",
"valid",
"URI"
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L203-L212 | train |
UMIACS/qav | qav/validators.py | HashValidator.validate | def validate(self, value):
"""Return a boolean if the choice is a number in the enumeration"""
if value in list(self.choices.keys()):
self._choice = value
return True
try:
self._choice = list(self.choices.keys())[int(value)]
return True
except (ValueError, IndexError):
self.error_message = '%s is not a valid choice.' % value
return False | python | def validate(self, value):
"""Return a boolean if the choice is a number in the enumeration"""
if value in list(self.choices.keys()):
self._choice = value
return True
try:
self._choice = list(self.choices.keys())[int(value)]
return True
except (ValueError, IndexError):
self.error_message = '%s is not a valid choice.' % value
return False | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"list",
"(",
"self",
".",
"choices",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"_choice",
"=",
"value",
"return",
"True",
"try",
":",
"self",
".",
"_choice",
"=",
"list",
"(",
"self",
".",
"choices",
".",
"keys",
"(",
")",
")",
"[",
"int",
"(",
"value",
")",
"]",
"return",
"True",
"except",
"(",
"ValueError",
",",
"IndexError",
")",
":",
"self",
".",
"error_message",
"=",
"'%s is not a valid choice.'",
"%",
"value",
"return",
"False"
]
| Return a boolean if the choice is a number in the enumeration | [
"Return",
"a",
"boolean",
"if",
"the",
"choice",
"is",
"a",
"number",
"in",
"the",
"enumeration"
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L354-L364 | train |
UMIACS/qav | qav/validators.py | IntegerValidator.validate | def validate(self, value):
"""
Return True if the choice is an integer; False otherwise.
If the value was cast successfully to an int, set the choice that will
make its way into the answers dict to the cast int value, not the
string representation.
"""
try:
int_value = int(value)
self._choice = int_value
return True
except ValueError:
self.error_message = '%s is not a valid integer.' % value
return False | python | def validate(self, value):
"""
Return True if the choice is an integer; False otherwise.
If the value was cast successfully to an int, set the choice that will
make its way into the answers dict to the cast int value, not the
string representation.
"""
try:
int_value = int(value)
self._choice = int_value
return True
except ValueError:
self.error_message = '%s is not a valid integer.' % value
return False | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"int_value",
"=",
"int",
"(",
"value",
")",
"self",
".",
"_choice",
"=",
"int_value",
"return",
"True",
"except",
"ValueError",
":",
"self",
".",
"error_message",
"=",
"'%s is not a valid integer.'",
"%",
"value",
"return",
"False"
]
| Return True if the choice is an integer; False otherwise.
If the value was cast successfully to an int, set the choice that will
make its way into the answers dict to the cast int value, not the
string representation. | [
"Return",
"True",
"if",
"the",
"choice",
"is",
"an",
"integer",
";",
"False",
"otherwise",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L369-L383 | train |
acutesoftware/virtual-AI-simulator | vais/build_internet.py | main | def main():
"""
generates a virtual internet, sets pages and runs web_users on it
"""
e = mod_env.Internet('VAIS - Load testing', 'Simulation of several websites')
e.create(800)
print(e)
#Create some users to browse the web and load test website
print(npc.web_users.params) | python | def main():
"""
generates a virtual internet, sets pages and runs web_users on it
"""
e = mod_env.Internet('VAIS - Load testing', 'Simulation of several websites')
e.create(800)
print(e)
#Create some users to browse the web and load test website
print(npc.web_users.params) | [
"def",
"main",
"(",
")",
":",
"e",
"=",
"mod_env",
".",
"Internet",
"(",
"'VAIS - Load testing'",
",",
"'Simulation of several websites'",
")",
"e",
".",
"create",
"(",
"800",
")",
"print",
"(",
"e",
")",
"#Create some users to browse the web and load test website",
"print",
"(",
"npc",
".",
"web_users",
".",
"params",
")"
]
| generates a virtual internet, sets pages and runs web_users on it | [
"generates",
"a",
"virtual",
"internet",
"sets",
"pages",
"and",
"runs",
"web_users",
"on",
"it"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/build_internet.py#L12-L21 | train |
mardix/Juice | juice/cli.py | create | def create(project, skel):
""" Create a new Project in the current directory """
app = project_name(project)
header("Create New Project ...")
print("- Project: %s " % app)
create_project(app, skel)
print("")
print("----- That's Juicy! ----")
print("")
print("- Your new project [ %s ] has been created" % app)
print("- Location: [ application/%s ]" % app)
print("")
print("> What's next?")
print("- Edit the config [ application/config.py ] ")
print("- If necessary edit and run the command [ juicy setup ]")
print("- Launch app on devlopment mode, run [ juicy serve %s ]" % app)
print("")
print("*" * 80) | python | def create(project, skel):
""" Create a new Project in the current directory """
app = project_name(project)
header("Create New Project ...")
print("- Project: %s " % app)
create_project(app, skel)
print("")
print("----- That's Juicy! ----")
print("")
print("- Your new project [ %s ] has been created" % app)
print("- Location: [ application/%s ]" % app)
print("")
print("> What's next?")
print("- Edit the config [ application/config.py ] ")
print("- If necessary edit and run the command [ juicy setup ]")
print("- Launch app on devlopment mode, run [ juicy serve %s ]" % app)
print("")
print("*" * 80) | [
"def",
"create",
"(",
"project",
",",
"skel",
")",
":",
"app",
"=",
"project_name",
"(",
"project",
")",
"header",
"(",
"\"Create New Project ...\"",
")",
"print",
"(",
"\"- Project: %s \"",
"%",
"app",
")",
"create_project",
"(",
"app",
",",
"skel",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"----- That's Juicy! ----\"",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"- Your new project [ %s ] has been created\"",
"%",
"app",
")",
"print",
"(",
"\"- Location: [ application/%s ]\"",
"%",
"app",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"> What's next?\"",
")",
"print",
"(",
"\"- Edit the config [ application/config.py ] \"",
")",
"print",
"(",
"\"- If necessary edit and run the command [ juicy setup ]\"",
")",
"print",
"(",
"\"- Launch app on devlopment mode, run [ juicy serve %s ]\"",
"%",
"app",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"*\"",
"*",
"80",
")"
]
| Create a new Project in the current directory | [
"Create",
"a",
"new",
"Project",
"in",
"the",
"current",
"directory"
]
| 7afa8d4238868235dfcdae82272bd77958dd416a | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/cli.py#L226-L246 | train |
mardix/Juice | juice/cli.py | deploy | def deploy(remote, assets_to_s3):
""" To DEPLOY your application """
header("Deploying...")
if assets_to_s3:
for mod in get_deploy_assets2s3_list(CWD):
_assets2s3(mod)
remote_name = remote or "ALL"
print("Pushing application's content to remote: %s " % remote_name)
hosts = get_deploy_hosts_list(CWD, remote or None)
git_push_to_master(cwd=CWD, hosts=hosts, name=remote_name)
print("Done!") | python | def deploy(remote, assets_to_s3):
""" To DEPLOY your application """
header("Deploying...")
if assets_to_s3:
for mod in get_deploy_assets2s3_list(CWD):
_assets2s3(mod)
remote_name = remote or "ALL"
print("Pushing application's content to remote: %s " % remote_name)
hosts = get_deploy_hosts_list(CWD, remote or None)
git_push_to_master(cwd=CWD, hosts=hosts, name=remote_name)
print("Done!") | [
"def",
"deploy",
"(",
"remote",
",",
"assets_to_s3",
")",
":",
"header",
"(",
"\"Deploying...\"",
")",
"if",
"assets_to_s3",
":",
"for",
"mod",
"in",
"get_deploy_assets2s3_list",
"(",
"CWD",
")",
":",
"_assets2s3",
"(",
"mod",
")",
"remote_name",
"=",
"remote",
"or",
"\"ALL\"",
"print",
"(",
"\"Pushing application's content to remote: %s \"",
"%",
"remote_name",
")",
"hosts",
"=",
"get_deploy_hosts_list",
"(",
"CWD",
",",
"remote",
"or",
"None",
")",
"git_push_to_master",
"(",
"cwd",
"=",
"CWD",
",",
"hosts",
"=",
"hosts",
",",
"name",
"=",
"remote_name",
")",
"print",
"(",
"\"Done!\"",
")"
]
| To DEPLOY your application | [
"To",
"DEPLOY",
"your",
"application"
]
| 7afa8d4238868235dfcdae82272bd77958dd416a | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/cli.py#L305-L318 | train |
drericstrong/pyedna | pyedna/calc_config.py | CalcConfig.write_relationships | def write_relationships(self, file_name, flat=True):
"""
This module will output the eDNA tags which are used inside each
calculation.
If flat=True, data will be written flat, like:
ADE1CA01, ADE1PI01, ADE1PI02
If flat=False, data will be written in the non-flat way, like:
ADE1CA01, ADE1PI01
ADE1CA01, ADE1PI02
:param file_name: the output filename to write the relationships,
which should include the '.csv' extension
:param flat: True or False
"""
with open(file_name, 'w') as writer:
if flat:
self._write_relationships_flat(writer)
else:
self._write_relationships_non_flat(writer) | python | def write_relationships(self, file_name, flat=True):
"""
This module will output the eDNA tags which are used inside each
calculation.
If flat=True, data will be written flat, like:
ADE1CA01, ADE1PI01, ADE1PI02
If flat=False, data will be written in the non-flat way, like:
ADE1CA01, ADE1PI01
ADE1CA01, ADE1PI02
:param file_name: the output filename to write the relationships,
which should include the '.csv' extension
:param flat: True or False
"""
with open(file_name, 'w') as writer:
if flat:
self._write_relationships_flat(writer)
else:
self._write_relationships_non_flat(writer) | [
"def",
"write_relationships",
"(",
"self",
",",
"file_name",
",",
"flat",
"=",
"True",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'w'",
")",
"as",
"writer",
":",
"if",
"flat",
":",
"self",
".",
"_write_relationships_flat",
"(",
"writer",
")",
"else",
":",
"self",
".",
"_write_relationships_non_flat",
"(",
"writer",
")"
]
| This module will output the eDNA tags which are used inside each
calculation.
If flat=True, data will be written flat, like:
ADE1CA01, ADE1PI01, ADE1PI02
If flat=False, data will be written in the non-flat way, like:
ADE1CA01, ADE1PI01
ADE1CA01, ADE1PI02
:param file_name: the output filename to write the relationships,
which should include the '.csv' extension
:param flat: True or False | [
"This",
"module",
"will",
"output",
"the",
"eDNA",
"tags",
"which",
"are",
"used",
"inside",
"each",
"calculation",
"."
]
| b8f8f52def4f26bb4f3a993ce3400769518385f6 | https://github.com/drericstrong/pyedna/blob/b8f8f52def4f26bb4f3a993ce3400769518385f6/pyedna/calc_config.py#L87-L107 | train |
tjcsl/cslbot | cslbot/commands/timeout.py | cmd | def cmd(send, msg, args):
"""Quiets a user, then unquiets them after the specified period of time.
Syntax: {command} <timespec> <nickname>
timespec is in the format: <number><unit>, where unit is s, m, h, or d.
"""
nickregex = args['config']['core']['nickregex']
setmode = args['handler'].connection.mode
channel = args['target']
with args['handler'].data_lock:
ops = args['handler'].opers[channel].copy()
if args['botnick'] not in ops:
send("Bot must be an op.")
return
time, user = msg.split(maxsplit=1)
if user == args['botnick']:
send("I won't put myself in timeout!")
return
if not re.match(nickregex, user):
send("%s is an invalid nick." % user)
return
time = parse_time(time)
if time is None:
send("Invalid unit.")
else:
if args['config']['feature']['networktype'] == 'unrealircd':
setmode(channel, " +b ~q:%s!*@*" % user)
defer_args = [channel, " -b ~q:%s!*@*" % user]
elif args['config']['feature']['networktype'] == 'atheme':
setmode(channel, " +q-v %s!*@* %s" % (user, user))
defer_args = [channel, " -q %s!*@*" % user]
else:
raise Exception("networktype undefined or unknown in config.cfg")
ident = args['handler'].workers.defer(time, True, setmode, *defer_args)
send("%s has been put in timeout, ident: %d" % (user, ident)) | python | def cmd(send, msg, args):
"""Quiets a user, then unquiets them after the specified period of time.
Syntax: {command} <timespec> <nickname>
timespec is in the format: <number><unit>, where unit is s, m, h, or d.
"""
nickregex = args['config']['core']['nickregex']
setmode = args['handler'].connection.mode
channel = args['target']
with args['handler'].data_lock:
ops = args['handler'].opers[channel].copy()
if args['botnick'] not in ops:
send("Bot must be an op.")
return
time, user = msg.split(maxsplit=1)
if user == args['botnick']:
send("I won't put myself in timeout!")
return
if not re.match(nickregex, user):
send("%s is an invalid nick." % user)
return
time = parse_time(time)
if time is None:
send("Invalid unit.")
else:
if args['config']['feature']['networktype'] == 'unrealircd':
setmode(channel, " +b ~q:%s!*@*" % user)
defer_args = [channel, " -b ~q:%s!*@*" % user]
elif args['config']['feature']['networktype'] == 'atheme':
setmode(channel, " +q-v %s!*@* %s" % (user, user))
defer_args = [channel, " -q %s!*@*" % user]
else:
raise Exception("networktype undefined or unknown in config.cfg")
ident = args['handler'].workers.defer(time, True, setmode, *defer_args)
send("%s has been put in timeout, ident: %d" % (user, ident)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"nickregex",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'nickregex'",
"]",
"setmode",
"=",
"args",
"[",
"'handler'",
"]",
".",
"connection",
".",
"mode",
"channel",
"=",
"args",
"[",
"'target'",
"]",
"with",
"args",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"ops",
"=",
"args",
"[",
"'handler'",
"]",
".",
"opers",
"[",
"channel",
"]",
".",
"copy",
"(",
")",
"if",
"args",
"[",
"'botnick'",
"]",
"not",
"in",
"ops",
":",
"send",
"(",
"\"Bot must be an op.\"",
")",
"return",
"time",
",",
"user",
"=",
"msg",
".",
"split",
"(",
"maxsplit",
"=",
"1",
")",
"if",
"user",
"==",
"args",
"[",
"'botnick'",
"]",
":",
"send",
"(",
"\"I won't put myself in timeout!\"",
")",
"return",
"if",
"not",
"re",
".",
"match",
"(",
"nickregex",
",",
"user",
")",
":",
"send",
"(",
"\"%s is an invalid nick.\"",
"%",
"user",
")",
"return",
"time",
"=",
"parse_time",
"(",
"time",
")",
"if",
"time",
"is",
"None",
":",
"send",
"(",
"\"Invalid unit.\"",
")",
"else",
":",
"if",
"args",
"[",
"'config'",
"]",
"[",
"'feature'",
"]",
"[",
"'networktype'",
"]",
"==",
"'unrealircd'",
":",
"setmode",
"(",
"channel",
",",
"\" +b ~q:%s!*@*\"",
"%",
"user",
")",
"defer_args",
"=",
"[",
"channel",
",",
"\" -b ~q:%s!*@*\"",
"%",
"user",
"]",
"elif",
"args",
"[",
"'config'",
"]",
"[",
"'feature'",
"]",
"[",
"'networktype'",
"]",
"==",
"'atheme'",
":",
"setmode",
"(",
"channel",
",",
"\" +q-v %s!*@* %s\"",
"%",
"(",
"user",
",",
"user",
")",
")",
"defer_args",
"=",
"[",
"channel",
",",
"\" -q %s!*@*\"",
"%",
"user",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"networktype undefined or unknown in config.cfg\"",
")",
"ident",
"=",
"args",
"[",
"'handler'",
"]",
".",
"workers",
".",
"defer",
"(",
"time",
",",
"True",
",",
"setmode",
",",
"*",
"defer_args",
")",
"send",
"(",
"\"%s has been put in timeout, ident: %d\"",
"%",
"(",
"user",
",",
"ident",
")",
")"
]
| Quiets a user, then unquiets them after the specified period of time.
Syntax: {command} <timespec> <nickname>
timespec is in the format: <number><unit>, where unit is s, m, h, or d. | [
"Quiets",
"a",
"user",
"then",
"unquiets",
"them",
"after",
"the",
"specified",
"period",
"of",
"time",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/timeout.py#L25-L61 | train |
textbook/atmdb | atmdb/client.py | TMDbClient._update_config | async def _update_config(self):
"""Update configuration data if required.
Notes:
Per `the documentation`_, this updates the API configuration
data *"every few days"*.
.. _the documentation:
http://docs.themoviedb.apiary.io/#reference/configuration
"""
if self.config['data'] is None or self.config_expired:
data = await self.get_data(self.url_builder('configuration'))
self.config = dict(data=data, last_update=datetime.now()) | python | async def _update_config(self):
"""Update configuration data if required.
Notes:
Per `the documentation`_, this updates the API configuration
data *"every few days"*.
.. _the documentation:
http://docs.themoviedb.apiary.io/#reference/configuration
"""
if self.config['data'] is None or self.config_expired:
data = await self.get_data(self.url_builder('configuration'))
self.config = dict(data=data, last_update=datetime.now()) | [
"async",
"def",
"_update_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
"[",
"'data'",
"]",
"is",
"None",
"or",
"self",
".",
"config_expired",
":",
"data",
"=",
"await",
"self",
".",
"get_data",
"(",
"self",
".",
"url_builder",
"(",
"'configuration'",
")",
")",
"self",
".",
"config",
"=",
"dict",
"(",
"data",
"=",
"data",
",",
"last_update",
"=",
"datetime",
".",
"now",
"(",
")",
")"
]
| Update configuration data if required.
Notes:
Per `the documentation`_, this updates the API configuration
data *"every few days"*.
.. _the documentation:
http://docs.themoviedb.apiary.io/#reference/configuration | [
"Update",
"configuration",
"data",
"if",
"required",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L44-L57 | train |
textbook/atmdb | atmdb/client.py | TMDbClient.find_movie | async def find_movie(self, query):
"""Retrieve movie data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches.
"""
params = OrderedDict([
('query', query), ('include_adult', False),
])
url = self.url_builder('search/movie', {}, params)
data = await self.get_data(url)
if data is None:
return
return [
Movie.from_json(item, self.config['data'].get('images'))
for item in data.get('results', [])
] | python | async def find_movie(self, query):
"""Retrieve movie data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches.
"""
params = OrderedDict([
('query', query), ('include_adult', False),
])
url = self.url_builder('search/movie', {}, params)
data = await self.get_data(url)
if data is None:
return
return [
Movie.from_json(item, self.config['data'].get('images'))
for item in data.get('results', [])
] | [
"async",
"def",
"find_movie",
"(",
"self",
",",
"query",
")",
":",
"params",
"=",
"OrderedDict",
"(",
"[",
"(",
"'query'",
",",
"query",
")",
",",
"(",
"'include_adult'",
",",
"False",
")",
",",
"]",
")",
"url",
"=",
"self",
".",
"url_builder",
"(",
"'search/movie'",
",",
"{",
"}",
",",
"params",
")",
"data",
"=",
"await",
"self",
".",
"get_data",
"(",
"url",
")",
"if",
"data",
"is",
"None",
":",
"return",
"return",
"[",
"Movie",
".",
"from_json",
"(",
"item",
",",
"self",
".",
"config",
"[",
"'data'",
"]",
".",
"get",
"(",
"'images'",
")",
")",
"for",
"item",
"in",
"data",
".",
"get",
"(",
"'results'",
",",
"[",
"]",
")",
"]"
]
| Retrieve movie data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches. | [
"Retrieve",
"movie",
"data",
"by",
"search",
"query",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L96-L116 | train |
textbook/atmdb | atmdb/client.py | TMDbClient.find_person | async def find_person(self, query):
"""Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches.
"""
url = self.url_builder(
'search/person',
dict(),
url_params=OrderedDict([
('query', query), ('include_adult', False)
]),
)
data = await self.get_data(url)
if data is None:
return
return [
Person.from_json(item, self.config['data'].get('images'))
for item in data.get('results', [])
] | python | async def find_person(self, query):
"""Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches.
"""
url = self.url_builder(
'search/person',
dict(),
url_params=OrderedDict([
('query', query), ('include_adult', False)
]),
)
data = await self.get_data(url)
if data is None:
return
return [
Person.from_json(item, self.config['data'].get('images'))
for item in data.get('results', [])
] | [
"async",
"def",
"find_person",
"(",
"self",
",",
"query",
")",
":",
"url",
"=",
"self",
".",
"url_builder",
"(",
"'search/person'",
",",
"dict",
"(",
")",
",",
"url_params",
"=",
"OrderedDict",
"(",
"[",
"(",
"'query'",
",",
"query",
")",
",",
"(",
"'include_adult'",
",",
"False",
")",
"]",
")",
",",
")",
"data",
"=",
"await",
"self",
".",
"get_data",
"(",
"url",
")",
"if",
"data",
"is",
"None",
":",
"return",
"return",
"[",
"Person",
".",
"from_json",
"(",
"item",
",",
"self",
".",
"config",
"[",
"'data'",
"]",
".",
"get",
"(",
"'images'",
")",
")",
"for",
"item",
"in",
"data",
".",
"get",
"(",
"'results'",
",",
"[",
"]",
")",
"]"
]
| Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches. | [
"Retrieve",
"person",
"data",
"by",
"search",
"query",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L118-L141 | train |
textbook/atmdb | atmdb/client.py | TMDbClient.get_movie | async def get_movie(self, id_):
"""Retrieve movie data by ID.
Arguments:
id_ (:py:class:`int`): The movie's TMDb ID.
Returns:
:py:class:`~.Movie`: The requested movie.
"""
url = self.url_builder(
'movie/{movie_id}',
dict(movie_id=id_),
url_params=OrderedDict(append_to_response='credits'),
)
data = await self.get_data(url)
if data is None:
return
return Movie.from_json(data, self.config['data'].get('images')) | python | async def get_movie(self, id_):
"""Retrieve movie data by ID.
Arguments:
id_ (:py:class:`int`): The movie's TMDb ID.
Returns:
:py:class:`~.Movie`: The requested movie.
"""
url = self.url_builder(
'movie/{movie_id}',
dict(movie_id=id_),
url_params=OrderedDict(append_to_response='credits'),
)
data = await self.get_data(url)
if data is None:
return
return Movie.from_json(data, self.config['data'].get('images')) | [
"async",
"def",
"get_movie",
"(",
"self",
",",
"id_",
")",
":",
"url",
"=",
"self",
".",
"url_builder",
"(",
"'movie/{movie_id}'",
",",
"dict",
"(",
"movie_id",
"=",
"id_",
")",
",",
"url_params",
"=",
"OrderedDict",
"(",
"append_to_response",
"=",
"'credits'",
")",
",",
")",
"data",
"=",
"await",
"self",
".",
"get_data",
"(",
"url",
")",
"if",
"data",
"is",
"None",
":",
"return",
"return",
"Movie",
".",
"from_json",
"(",
"data",
",",
"self",
".",
"config",
"[",
"'data'",
"]",
".",
"get",
"(",
"'images'",
")",
")"
]
| Retrieve movie data by ID.
Arguments:
id_ (:py:class:`int`): The movie's TMDb ID.
Returns:
:py:class:`~.Movie`: The requested movie. | [
"Retrieve",
"movie",
"data",
"by",
"ID",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L143-L161 | train |
textbook/atmdb | atmdb/client.py | TMDbClient.get_person | async def get_person(self, id_):
"""Retrieve person data by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
Returns:
:py:class:`~.Person`: The requested person.
"""
data = await self._get_person_json(
id_,
OrderedDict(append_to_response='movie_credits')
)
return Person.from_json(data, self.config['data'].get('images')) | python | async def get_person(self, id_):
"""Retrieve person data by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
Returns:
:py:class:`~.Person`: The requested person.
"""
data = await self._get_person_json(
id_,
OrderedDict(append_to_response='movie_credits')
)
return Person.from_json(data, self.config['data'].get('images')) | [
"async",
"def",
"get_person",
"(",
"self",
",",
"id_",
")",
":",
"data",
"=",
"await",
"self",
".",
"_get_person_json",
"(",
"id_",
",",
"OrderedDict",
"(",
"append_to_response",
"=",
"'movie_credits'",
")",
")",
"return",
"Person",
".",
"from_json",
"(",
"data",
",",
"self",
".",
"config",
"[",
"'data'",
"]",
".",
"get",
"(",
"'images'",
")",
")"
]
| Retrieve person data by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
Returns:
:py:class:`~.Person`: The requested person. | [
"Retrieve",
"person",
"data",
"by",
"ID",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L163-L177 | train |
textbook/atmdb | atmdb/client.py | TMDbClient._get_person_json | async def _get_person_json(self, id_, url_params=None):
"""Retrieve raw person JSON by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
url_params (:py:class:`dict`): Any additional URL parameters.
Returns:
:py:class:`dict`: The JSON data.
"""
url = self.url_builder(
'person/{person_id}',
dict(person_id=id_),
url_params=url_params or OrderedDict(),
)
data = await self.get_data(url)
return data | python | async def _get_person_json(self, id_, url_params=None):
"""Retrieve raw person JSON by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
url_params (:py:class:`dict`): Any additional URL parameters.
Returns:
:py:class:`dict`: The JSON data.
"""
url = self.url_builder(
'person/{person_id}',
dict(person_id=id_),
url_params=url_params or OrderedDict(),
)
data = await self.get_data(url)
return data | [
"async",
"def",
"_get_person_json",
"(",
"self",
",",
"id_",
",",
"url_params",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"url_builder",
"(",
"'person/{person_id}'",
",",
"dict",
"(",
"person_id",
"=",
"id_",
")",
",",
"url_params",
"=",
"url_params",
"or",
"OrderedDict",
"(",
")",
",",
")",
"data",
"=",
"await",
"self",
".",
"get_data",
"(",
"url",
")",
"return",
"data"
]
| Retrieve raw person JSON by ID.
Arguments:
id_ (:py:class:`int`): The person's TMDb ID.
url_params (:py:class:`dict`): Any additional URL parameters.
Returns:
:py:class:`dict`: The JSON data. | [
"Retrieve",
"raw",
"person",
"JSON",
"by",
"ID",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L179-L196 | train |
textbook/atmdb | atmdb/client.py | TMDbClient.get_random_popular_person | async def get_random_popular_person(self, limit=500):
"""Randomly select a popular person.
Notes:
Requires at least two API calls. May require three API calls
if the randomly-selected index isn't within the first page of
required data.
Arguments:
limit (:py:class:`int`, optional): How many of the most
popular people to make random choice from (defaults to top
``500``).
Returns:
:py:class:`~.Person`: A randomly-selected popular person.
"""
index = random.randrange(limit)
data = await self._get_popular_people_page()
if data is None:
return
if index >= len(data['results']):
# result is not on first page
page, index = self._calculate_page_index(index, data)
data = await self._get_popular_people_page(page)
if data is None:
return
json_data = data['results'][index]
details = await self._get_person_json(json_data['id'])
details.update(**json_data)
return Person.from_json(details, self.config['data'].get('images')) | python | async def get_random_popular_person(self, limit=500):
"""Randomly select a popular person.
Notes:
Requires at least two API calls. May require three API calls
if the randomly-selected index isn't within the first page of
required data.
Arguments:
limit (:py:class:`int`, optional): How many of the most
popular people to make random choice from (defaults to top
``500``).
Returns:
:py:class:`~.Person`: A randomly-selected popular person.
"""
index = random.randrange(limit)
data = await self._get_popular_people_page()
if data is None:
return
if index >= len(data['results']):
# result is not on first page
page, index = self._calculate_page_index(index, data)
data = await self._get_popular_people_page(page)
if data is None:
return
json_data = data['results'][index]
details = await self._get_person_json(json_data['id'])
details.update(**json_data)
return Person.from_json(details, self.config['data'].get('images')) | [
"async",
"def",
"get_random_popular_person",
"(",
"self",
",",
"limit",
"=",
"500",
")",
":",
"index",
"=",
"random",
".",
"randrange",
"(",
"limit",
")",
"data",
"=",
"await",
"self",
".",
"_get_popular_people_page",
"(",
")",
"if",
"data",
"is",
"None",
":",
"return",
"if",
"index",
">=",
"len",
"(",
"data",
"[",
"'results'",
"]",
")",
":",
"# result is not on first page",
"page",
",",
"index",
"=",
"self",
".",
"_calculate_page_index",
"(",
"index",
",",
"data",
")",
"data",
"=",
"await",
"self",
".",
"_get_popular_people_page",
"(",
"page",
")",
"if",
"data",
"is",
"None",
":",
"return",
"json_data",
"=",
"data",
"[",
"'results'",
"]",
"[",
"index",
"]",
"details",
"=",
"await",
"self",
".",
"_get_person_json",
"(",
"json_data",
"[",
"'id'",
"]",
")",
"details",
".",
"update",
"(",
"*",
"*",
"json_data",
")",
"return",
"Person",
".",
"from_json",
"(",
"details",
",",
"self",
".",
"config",
"[",
"'data'",
"]",
".",
"get",
"(",
"'images'",
")",
")"
]
| Randomly select a popular person.
Notes:
Requires at least two API calls. May require three API calls
if the randomly-selected index isn't within the first page of
required data.
Arguments:
limit (:py:class:`int`, optional): How many of the most
popular people to make random choice from (defaults to top
``500``).
Returns:
:py:class:`~.Person`: A randomly-selected popular person. | [
"Randomly",
"select",
"a",
"popular",
"person",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L198-L228 | train |
textbook/atmdb | atmdb/client.py | TMDbClient._get_popular_people_page | async def _get_popular_people_page(self, page=1):
"""Get a specific page of popular person data.
Arguments:
page (:py:class:`int`, optional): The page to get.
Returns:
:py:class:`dict`: The page data.
"""
return await self.get_data(self.url_builder(
'person/popular',
url_params=OrderedDict(page=page),
)) | python | async def _get_popular_people_page(self, page=1):
"""Get a specific page of popular person data.
Arguments:
page (:py:class:`int`, optional): The page to get.
Returns:
:py:class:`dict`: The page data.
"""
return await self.get_data(self.url_builder(
'person/popular',
url_params=OrderedDict(page=page),
)) | [
"async",
"def",
"_get_popular_people_page",
"(",
"self",
",",
"page",
"=",
"1",
")",
":",
"return",
"await",
"self",
".",
"get_data",
"(",
"self",
".",
"url_builder",
"(",
"'person/popular'",
",",
"url_params",
"=",
"OrderedDict",
"(",
"page",
"=",
"page",
")",
",",
")",
")"
]
| Get a specific page of popular person data.
Arguments:
page (:py:class:`int`, optional): The page to get.
Returns:
:py:class:`dict`: The page data. | [
"Get",
"a",
"specific",
"page",
"of",
"popular",
"person",
"data",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L230-L243 | train |
textbook/atmdb | atmdb/client.py | TMDbClient._calculate_page_index | def _calculate_page_index(index, data):
"""Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the format
``(page, index_in_page)``.
"""
if index > data['total_results']:
raise ValueError('index not in paged data')
page_length = len(data['results'])
return (index // page_length) + 1, (index % page_length) - 1 | python | def _calculate_page_index(index, data):
"""Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the format
``(page, index_in_page)``.
"""
if index > data['total_results']:
raise ValueError('index not in paged data')
page_length = len(data['results'])
return (index // page_length) + 1, (index % page_length) - 1 | [
"def",
"_calculate_page_index",
"(",
"index",
",",
"data",
")",
":",
"if",
"index",
">",
"data",
"[",
"'total_results'",
"]",
":",
"raise",
"ValueError",
"(",
"'index not in paged data'",
")",
"page_length",
"=",
"len",
"(",
"data",
"[",
"'results'",
"]",
")",
"return",
"(",
"index",
"//",
"page_length",
")",
"+",
"1",
",",
"(",
"index",
"%",
"page_length",
")",
"-",
"1"
]
| Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the format
``(page, index_in_page)``. | [
"Determine",
"the",
"location",
"of",
"a",
"given",
"index",
"in",
"paged",
"data",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L246-L261 | train |
tjcsl/cslbot | cslbot/commands/ipa.py | cmd | def cmd(send, msg, args):
"""Converts text into NATO form.
Syntax: {command} <text>
"""
if not msg:
send("NATO what?")
return
nato = gen_nato(msg)
if len(nato) > 100:
send("Your NATO is too long. Have you considered letters?")
else:
send(nato) | python | def cmd(send, msg, args):
"""Converts text into NATO form.
Syntax: {command} <text>
"""
if not msg:
send("NATO what?")
return
nato = gen_nato(msg)
if len(nato) > 100:
send("Your NATO is too long. Have you considered letters?")
else:
send(nato) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"NATO what?\"",
")",
"return",
"nato",
"=",
"gen_nato",
"(",
"msg",
")",
"if",
"len",
"(",
"nato",
")",
">",
"100",
":",
"send",
"(",
"\"Your NATO is too long. Have you considered letters?\"",
")",
"else",
":",
"send",
"(",
"nato",
")"
]
| Converts text into NATO form.
Syntax: {command} <text> | [
"Converts",
"text",
"into",
"NATO",
"form",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/ipa.py#L73-L86 | train |
tjcsl/cslbot | cslbot/commands/time.py | cmd | def cmd(send, msg, _):
"""Tells the time.
Syntax: {command}
"""
bold = '\x02'
if not msg:
msg = bold + "Date: " + bold + "%A, %m/%d/%Y" + bold + " Time: " + bold + "%H:%M:%S"
send(time.strftime(msg)) | python | def cmd(send, msg, _):
"""Tells the time.
Syntax: {command}
"""
bold = '\x02'
if not msg:
msg = bold + "Date: " + bold + "%A, %m/%d/%Y" + bold + " Time: " + bold + "%H:%M:%S"
send(time.strftime(msg)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"bold",
"=",
"'\\x02'",
"if",
"not",
"msg",
":",
"msg",
"=",
"bold",
"+",
"\"Date: \"",
"+",
"bold",
"+",
"\"%A, %m/%d/%Y\"",
"+",
"bold",
"+",
"\" Time: \"",
"+",
"bold",
"+",
"\"%H:%M:%S\"",
"send",
"(",
"time",
".",
"strftime",
"(",
"msg",
")",
")"
]
| Tells the time.
Syntax: {command} | [
"Tells",
"the",
"time",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/time.py#L24-L33 | train |
tjcsl/cslbot | cslbot/commands/highlight.py | cmd | def cmd(send, msg, args):
"""When a nick was last pinged.
Syntax: {command} [--channel #channel] [nick]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--channel', nargs='?', action=arguments.ChanParser)
parser.add_argument('nick', nargs='?', action=arguments.NickParser, default=args['nick'])
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if args['target'] == 'private':
send("You're always the highlight of your monologues!")
return
target = cmdargs.channels[0] if hasattr(cmdargs, 'channels') else args['target']
row = args['db'].query(Log).filter(Log.msg.ilike("%%%s%%" % cmdargs.nick), ~Log.msg.contains('%shighlight' % args['config']['core']['cmdchar']),
Log.target == target, Log.source != args['botnick'], Log.source != cmdargs.nick,
(Log.type == 'pubmsg') | (Log.type == 'privmsg') | (Log.type == 'action')).order_by(Log.time.desc()).first()
if row is None:
send("%s has never been pinged." % cmdargs.nick)
else:
time = row.time.strftime('%Y-%m-%d %H:%M:%S')
send("%s <%s> %s" % (time, row.source, row.msg)) | python | def cmd(send, msg, args):
"""When a nick was last pinged.
Syntax: {command} [--channel #channel] [nick]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--channel', nargs='?', action=arguments.ChanParser)
parser.add_argument('nick', nargs='?', action=arguments.NickParser, default=args['nick'])
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if args['target'] == 'private':
send("You're always the highlight of your monologues!")
return
target = cmdargs.channels[0] if hasattr(cmdargs, 'channels') else args['target']
row = args['db'].query(Log).filter(Log.msg.ilike("%%%s%%" % cmdargs.nick), ~Log.msg.contains('%shighlight' % args['config']['core']['cmdchar']),
Log.target == target, Log.source != args['botnick'], Log.source != cmdargs.nick,
(Log.type == 'pubmsg') | (Log.type == 'privmsg') | (Log.type == 'action')).order_by(Log.time.desc()).first()
if row is None:
send("%s has never been pinged." % cmdargs.nick)
else:
time = row.time.strftime('%Y-%m-%d %H:%M:%S')
send("%s <%s> %s" % (time, row.source, row.msg)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--channel'",
",",
"nargs",
"=",
"'?'",
",",
"action",
"=",
"arguments",
".",
"ChanParser",
")",
"parser",
".",
"add_argument",
"(",
"'nick'",
",",
"nargs",
"=",
"'?'",
",",
"action",
"=",
"arguments",
".",
"NickParser",
",",
"default",
"=",
"args",
"[",
"'nick'",
"]",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"if",
"args",
"[",
"'target'",
"]",
"==",
"'private'",
":",
"send",
"(",
"\"You're always the highlight of your monologues!\"",
")",
"return",
"target",
"=",
"cmdargs",
".",
"channels",
"[",
"0",
"]",
"if",
"hasattr",
"(",
"cmdargs",
",",
"'channels'",
")",
"else",
"args",
"[",
"'target'",
"]",
"row",
"=",
"args",
"[",
"'db'",
"]",
".",
"query",
"(",
"Log",
")",
".",
"filter",
"(",
"Log",
".",
"msg",
".",
"ilike",
"(",
"\"%%%s%%\"",
"%",
"cmdargs",
".",
"nick",
")",
",",
"~",
"Log",
".",
"msg",
".",
"contains",
"(",
"'%shighlight'",
"%",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'cmdchar'",
"]",
")",
",",
"Log",
".",
"target",
"==",
"target",
",",
"Log",
".",
"source",
"!=",
"args",
"[",
"'botnick'",
"]",
",",
"Log",
".",
"source",
"!=",
"cmdargs",
".",
"nick",
",",
"(",
"Log",
".",
"type",
"==",
"'pubmsg'",
")",
"|",
"(",
"Log",
".",
"type",
"==",
"'privmsg'",
")",
"|",
"(",
"Log",
".",
"type",
"==",
"'action'",
")",
")",
".",
"order_by",
"(",
"Log",
".",
"time",
".",
"desc",
"(",
")",
")",
".",
"first",
"(",
")",
"if",
"row",
"is",
"None",
":",
"send",
"(",
"\"%s has never been pinged.\"",
"%",
"cmdargs",
".",
"nick",
")",
"else",
":",
"time",
"=",
"row",
".",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
"send",
"(",
"\"%s <%s> %s\"",
"%",
"(",
"time",
",",
"row",
".",
"source",
",",
"row",
".",
"msg",
")",
")"
]
| When a nick was last pinged.
Syntax: {command} [--channel #channel] [nick] | [
"When",
"a",
"nick",
"was",
"last",
"pinged",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/highlight.py#L24-L49 | train |
tjcsl/cslbot | cslbot/helpers/backtrace.py | output_traceback | def output_traceback(ex):
"""Returns a tuple of a prettyprinted error message and string representation of the error."""
# Dump full traceback to console.
output = "".join(traceback.format_exc()).strip()
for line in output.split('\n'):
logging.error(line)
trace_obj = traceback.extract_tb(ex.__traceback__)[-1]
trace = [basename(trace_obj[0]), trace_obj[1]]
name = type(ex).__name__
output = str(ex).replace('\n', ' ')
msg = "%s in %s on line %s: %s" % (name, trace[0], trace[1], output)
return (msg, output) | python | def output_traceback(ex):
"""Returns a tuple of a prettyprinted error message and string representation of the error."""
# Dump full traceback to console.
output = "".join(traceback.format_exc()).strip()
for line in output.split('\n'):
logging.error(line)
trace_obj = traceback.extract_tb(ex.__traceback__)[-1]
trace = [basename(trace_obj[0]), trace_obj[1]]
name = type(ex).__name__
output = str(ex).replace('\n', ' ')
msg = "%s in %s on line %s: %s" % (name, trace[0], trace[1], output)
return (msg, output) | [
"def",
"output_traceback",
"(",
"ex",
")",
":",
"# Dump full traceback to console.",
"output",
"=",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
":",
"logging",
".",
"error",
"(",
"line",
")",
"trace_obj",
"=",
"traceback",
".",
"extract_tb",
"(",
"ex",
".",
"__traceback__",
")",
"[",
"-",
"1",
"]",
"trace",
"=",
"[",
"basename",
"(",
"trace_obj",
"[",
"0",
"]",
")",
",",
"trace_obj",
"[",
"1",
"]",
"]",
"name",
"=",
"type",
"(",
"ex",
")",
".",
"__name__",
"output",
"=",
"str",
"(",
"ex",
")",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
"msg",
"=",
"\"%s in %s on line %s: %s\"",
"%",
"(",
"name",
",",
"trace",
"[",
"0",
"]",
",",
"trace",
"[",
"1",
"]",
",",
"output",
")",
"return",
"(",
"msg",
",",
"output",
")"
]
| Returns a tuple of a prettyprinted error message and string representation of the error. | [
"Returns",
"a",
"tuple",
"of",
"a",
"prettyprinted",
"error",
"message",
"and",
"string",
"representation",
"of",
"the",
"error",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/backtrace.py#L28-L39 | train |
jlesquembre/autopilot | src/autopilot/main.py | release | def release(no_master, release_type):
'''Releases a new version'''
try:
locale.setlocale(locale.LC_ALL, '')
except:
print("Warning: Unable to set locale. Expect encoding problems.")
git.is_repo_clean(master=(not no_master))
config = utils.get_config()
config.update(utils.get_dist_metadata())
config['project_dir'] = Path(os.getcwd())
config['release_type'] = release_type
with tempfile.TemporaryDirectory(prefix='ap_tmp') as tmp_dir:
config['tmp_dir'] = tmp_dir
values = release_ui(config)
if type(values) is not str:
utils.release(project_name=config['project_name'], tmp_dir=tmp_dir,
project_dir=config['project_dir'],
pypi_servers=config['pypi_servers'], **values)
print('New release options:')
pprint.pprint(values)
else:
print(values) | python | def release(no_master, release_type):
'''Releases a new version'''
try:
locale.setlocale(locale.LC_ALL, '')
except:
print("Warning: Unable to set locale. Expect encoding problems.")
git.is_repo_clean(master=(not no_master))
config = utils.get_config()
config.update(utils.get_dist_metadata())
config['project_dir'] = Path(os.getcwd())
config['release_type'] = release_type
with tempfile.TemporaryDirectory(prefix='ap_tmp') as tmp_dir:
config['tmp_dir'] = tmp_dir
values = release_ui(config)
if type(values) is not str:
utils.release(project_name=config['project_name'], tmp_dir=tmp_dir,
project_dir=config['project_dir'],
pypi_servers=config['pypi_servers'], **values)
print('New release options:')
pprint.pprint(values)
else:
print(values) | [
"def",
"release",
"(",
"no_master",
",",
"release_type",
")",
":",
"try",
":",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"''",
")",
"except",
":",
"print",
"(",
"\"Warning: Unable to set locale. Expect encoding problems.\"",
")",
"git",
".",
"is_repo_clean",
"(",
"master",
"=",
"(",
"not",
"no_master",
")",
")",
"config",
"=",
"utils",
".",
"get_config",
"(",
")",
"config",
".",
"update",
"(",
"utils",
".",
"get_dist_metadata",
"(",
")",
")",
"config",
"[",
"'project_dir'",
"]",
"=",
"Path",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"config",
"[",
"'release_type'",
"]",
"=",
"release_type",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
"prefix",
"=",
"'ap_tmp'",
")",
"as",
"tmp_dir",
":",
"config",
"[",
"'tmp_dir'",
"]",
"=",
"tmp_dir",
"values",
"=",
"release_ui",
"(",
"config",
")",
"if",
"type",
"(",
"values",
")",
"is",
"not",
"str",
":",
"utils",
".",
"release",
"(",
"project_name",
"=",
"config",
"[",
"'project_name'",
"]",
",",
"tmp_dir",
"=",
"tmp_dir",
",",
"project_dir",
"=",
"config",
"[",
"'project_dir'",
"]",
",",
"pypi_servers",
"=",
"config",
"[",
"'pypi_servers'",
"]",
",",
"*",
"*",
"values",
")",
"print",
"(",
"'New release options:'",
")",
"pprint",
".",
"pprint",
"(",
"values",
")",
"else",
":",
"print",
"(",
"values",
")"
]
| Releases a new version | [
"Releases",
"a",
"new",
"version"
]
| ca5f36269ba0173bd29c39db6971dac57a58513d | https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/main.py#L55-L82 | train |
JIC-CSB/jicimagelib | jicimagelib/geometry.py | Point2D._set_types | def _set_types(self):
"""Make sure that x, y have consistent types and set dtype."""
# If we given something that is not an int or a float we raise
# a RuntimeError as we do not want to have to guess if the given
# input should be interpreted as an int or a float, for example the
# interpretation of the string "1" vs the interpretation of the string
# "1.0".
for c in (self.x, self.y):
if not ( isinstance(c, int) or isinstance(c, float) ):
raise(RuntimeError('x, y coords should be int or float'))
if isinstance(self.x, int) and isinstance(self.y, int):
self._dtype = "int"
else:
# At least one value is a float so promote both to float.
self.x = float(self.x)
self.y = float(self.y)
self._dtype = "float" | python | def _set_types(self):
"""Make sure that x, y have consistent types and set dtype."""
# If we given something that is not an int or a float we raise
# a RuntimeError as we do not want to have to guess if the given
# input should be interpreted as an int or a float, for example the
# interpretation of the string "1" vs the interpretation of the string
# "1.0".
for c in (self.x, self.y):
if not ( isinstance(c, int) or isinstance(c, float) ):
raise(RuntimeError('x, y coords should be int or float'))
if isinstance(self.x, int) and isinstance(self.y, int):
self._dtype = "int"
else:
# At least one value is a float so promote both to float.
self.x = float(self.x)
self.y = float(self.y)
self._dtype = "float" | [
"def",
"_set_types",
"(",
"self",
")",
":",
"# If we given something that is not an int or a float we raise",
"# a RuntimeError as we do not want to have to guess if the given",
"# input should be interpreted as an int or a float, for example the",
"# interpretation of the string \"1\" vs the interpretation of the string",
"# \"1.0\".",
"for",
"c",
"in",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"c",
",",
"int",
")",
"or",
"isinstance",
"(",
"c",
",",
"float",
")",
")",
":",
"raise",
"(",
"RuntimeError",
"(",
"'x, y coords should be int or float'",
")",
")",
"if",
"isinstance",
"(",
"self",
".",
"x",
",",
"int",
")",
"and",
"isinstance",
"(",
"self",
".",
"y",
",",
"int",
")",
":",
"self",
".",
"_dtype",
"=",
"\"int\"",
"else",
":",
"# At least one value is a float so promote both to float.",
"self",
".",
"x",
"=",
"float",
"(",
"self",
".",
"x",
")",
"self",
".",
"y",
"=",
"float",
"(",
"self",
".",
"y",
")",
"self",
".",
"_dtype",
"=",
"\"float\""
]
| Make sure that x, y have consistent types and set dtype. | [
"Make",
"sure",
"that",
"x",
"y",
"have",
"consistent",
"types",
"and",
"set",
"dtype",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/geometry.py#L70-L87 | train |
JIC-CSB/jicimagelib | jicimagelib/geometry.py | Point2D.magnitude | def magnitude(self):
"""Return the magnitude when treating the point as a vector."""
return math.sqrt( self.x * self.x + self.y * self.y ) | python | def magnitude(self):
"""Return the magnitude when treating the point as a vector."""
return math.sqrt( self.x * self.x + self.y * self.y ) | [
"def",
"magnitude",
"(",
"self",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"self",
".",
"x",
"*",
"self",
".",
"x",
"+",
"self",
".",
"y",
"*",
"self",
".",
"y",
")"
]
| Return the magnitude when treating the point as a vector. | [
"Return",
"the",
"magnitude",
"when",
"treating",
"the",
"point",
"as",
"a",
"vector",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/geometry.py#L95-L97 | train |
JIC-CSB/jicimagelib | jicimagelib/geometry.py | Point2D.unit_vector | def unit_vector(self):
"""Return the unit vector."""
return Point2D( self.x / self.magnitude, self.y / self.magnitude ) | python | def unit_vector(self):
"""Return the unit vector."""
return Point2D( self.x / self.magnitude, self.y / self.magnitude ) | [
"def",
"unit_vector",
"(",
"self",
")",
":",
"return",
"Point2D",
"(",
"self",
".",
"x",
"/",
"self",
".",
"magnitude",
",",
"self",
".",
"y",
"/",
"self",
".",
"magnitude",
")"
]
| Return the unit vector. | [
"Return",
"the",
"unit",
"vector",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/geometry.py#L100-L102 | train |
JIC-CSB/jicimagelib | jicimagelib/geometry.py | Point2D.astype | def astype(self, dtype):
"""Return a point of the specified dtype."""
if dtype == "int":
return Point2D( int( round(self.x, 0) ), int( round(self.y, 0) ) )
elif dtype == "float":
return Point2D( float(self.x), float(self.y))
else:
raise(RuntimeError("Invalid dtype: {}".format(dtype))) | python | def astype(self, dtype):
"""Return a point of the specified dtype."""
if dtype == "int":
return Point2D( int( round(self.x, 0) ), int( round(self.y, 0) ) )
elif dtype == "float":
return Point2D( float(self.x), float(self.y))
else:
raise(RuntimeError("Invalid dtype: {}".format(dtype))) | [
"def",
"astype",
"(",
"self",
",",
"dtype",
")",
":",
"if",
"dtype",
"==",
"\"int\"",
":",
"return",
"Point2D",
"(",
"int",
"(",
"round",
"(",
"self",
".",
"x",
",",
"0",
")",
")",
",",
"int",
"(",
"round",
"(",
"self",
".",
"y",
",",
"0",
")",
")",
")",
"elif",
"dtype",
"==",
"\"float\"",
":",
"return",
"Point2D",
"(",
"float",
"(",
"self",
".",
"x",
")",
",",
"float",
"(",
"self",
".",
"y",
")",
")",
"else",
":",
"raise",
"(",
"RuntimeError",
"(",
"\"Invalid dtype: {}\"",
".",
"format",
"(",
"dtype",
")",
")",
")"
]
| Return a point of the specified dtype. | [
"Return",
"a",
"point",
"of",
"the",
"specified",
"dtype",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/geometry.py#L148-L155 | train |
kodethon/KoDrive | kodrive/syncthing_factory.py | SyncthingClient.free | def free(self, local_path):
'''
Stop synchronization of local_path
'''
# Process local ~~~
# 1. Syncthing config
config = self.get_config()
# Check whether folders are still connected to this device
folder = st_util.find_folder_with_path(local_path, config)
self.delete_folder(local_path, config)
pruned = st_util.prune_devices(folder, config)
# Done processing st config, commit :)
self.set_config(config)
if pruned:
self.restart()
# 2. App config
dir_config = self.adapter.get_dir_config(local_path)
if not dir_config:
raise custom_errors.FileNotInConfig(local_path)
kodrive_config = self.adapter.get_config()
for key in kodrive_config['directories']:
d = kodrive_config['directories'][key]
if d['local_path'].rstrip('/') == local_path.rstrip('/'):
del kodrive_config['directories'][key]
break
# Done process app config, commit :)
self.adapter.set_config(kodrive_config)
# If the folder was shared, try remove data from remote
if dir_config['is_shared'] and dir_config['server']:
# Process remote ~~~
r_api_key = dir_config['api_key']
r_device_id = dir_config['device_id']
if dir_config['host']:
host = dir_config['host']
else:
host = self.devid_to_ip(r_device_id, False)
try:
# Create remote proxy to interact with remote
remote = SyncthingProxy(
r_device_id, host, r_api_key,
port=dir_config['port'] if 'port' in dir_config else None
)
except Exception as e:
return True
r_config = remote.get_config()
r_folder = st_util.find_folder_with_path(
dir_config['remote_path'], r_config
)
# Delete device id from folder
r_config = remote.get_config()
self_devid = self.get_device_id()
del_device = remote.delete_device_from_folder(
dir_config['remote_path'], self_devid, r_config
)
# Check to see if no other folder depends has this device
pruned = st_util.prune_devices(r_folder, r_config)
remote.set_config(r_config)
if pruned:
remote.restart()
return True | python | def free(self, local_path):
'''
Stop synchronization of local_path
'''
# Process local ~~~
# 1. Syncthing config
config = self.get_config()
# Check whether folders are still connected to this device
folder = st_util.find_folder_with_path(local_path, config)
self.delete_folder(local_path, config)
pruned = st_util.prune_devices(folder, config)
# Done processing st config, commit :)
self.set_config(config)
if pruned:
self.restart()
# 2. App config
dir_config = self.adapter.get_dir_config(local_path)
if not dir_config:
raise custom_errors.FileNotInConfig(local_path)
kodrive_config = self.adapter.get_config()
for key in kodrive_config['directories']:
d = kodrive_config['directories'][key]
if d['local_path'].rstrip('/') == local_path.rstrip('/'):
del kodrive_config['directories'][key]
break
# Done process app config, commit :)
self.adapter.set_config(kodrive_config)
# If the folder was shared, try remove data from remote
if dir_config['is_shared'] and dir_config['server']:
# Process remote ~~~
r_api_key = dir_config['api_key']
r_device_id = dir_config['device_id']
if dir_config['host']:
host = dir_config['host']
else:
host = self.devid_to_ip(r_device_id, False)
try:
# Create remote proxy to interact with remote
remote = SyncthingProxy(
r_device_id, host, r_api_key,
port=dir_config['port'] if 'port' in dir_config else None
)
except Exception as e:
return True
r_config = remote.get_config()
r_folder = st_util.find_folder_with_path(
dir_config['remote_path'], r_config
)
# Delete device id from folder
r_config = remote.get_config()
self_devid = self.get_device_id()
del_device = remote.delete_device_from_folder(
dir_config['remote_path'], self_devid, r_config
)
# Check to see if no other folder depends has this device
pruned = st_util.prune_devices(r_folder, r_config)
remote.set_config(r_config)
if pruned:
remote.restart()
return True | [
"def",
"free",
"(",
"self",
",",
"local_path",
")",
":",
"# Process local ~~~",
"# 1. Syncthing config",
"config",
"=",
"self",
".",
"get_config",
"(",
")",
"# Check whether folders are still connected to this device ",
"folder",
"=",
"st_util",
".",
"find_folder_with_path",
"(",
"local_path",
",",
"config",
")",
"self",
".",
"delete_folder",
"(",
"local_path",
",",
"config",
")",
"pruned",
"=",
"st_util",
".",
"prune_devices",
"(",
"folder",
",",
"config",
")",
"# Done processing st config, commit :)",
"self",
".",
"set_config",
"(",
"config",
")",
"if",
"pruned",
":",
"self",
".",
"restart",
"(",
")",
"# 2. App config",
"dir_config",
"=",
"self",
".",
"adapter",
".",
"get_dir_config",
"(",
"local_path",
")",
"if",
"not",
"dir_config",
":",
"raise",
"custom_errors",
".",
"FileNotInConfig",
"(",
"local_path",
")",
"kodrive_config",
"=",
"self",
".",
"adapter",
".",
"get_config",
"(",
")",
"for",
"key",
"in",
"kodrive_config",
"[",
"'directories'",
"]",
":",
"d",
"=",
"kodrive_config",
"[",
"'directories'",
"]",
"[",
"key",
"]",
"if",
"d",
"[",
"'local_path'",
"]",
".",
"rstrip",
"(",
"'/'",
")",
"==",
"local_path",
".",
"rstrip",
"(",
"'/'",
")",
":",
"del",
"kodrive_config",
"[",
"'directories'",
"]",
"[",
"key",
"]",
"break",
"# Done process app config, commit :)",
"self",
".",
"adapter",
".",
"set_config",
"(",
"kodrive_config",
")",
"# If the folder was shared, try remove data from remote ",
"if",
"dir_config",
"[",
"'is_shared'",
"]",
"and",
"dir_config",
"[",
"'server'",
"]",
":",
"# Process remote ~~~",
"r_api_key",
"=",
"dir_config",
"[",
"'api_key'",
"]",
"r_device_id",
"=",
"dir_config",
"[",
"'device_id'",
"]",
"if",
"dir_config",
"[",
"'host'",
"]",
":",
"host",
"=",
"dir_config",
"[",
"'host'",
"]",
"else",
":",
"host",
"=",
"self",
".",
"devid_to_ip",
"(",
"r_device_id",
",",
"False",
")",
"try",
":",
"# Create remote proxy to interact with remote",
"remote",
"=",
"SyncthingProxy",
"(",
"r_device_id",
",",
"host",
",",
"r_api_key",
",",
"port",
"=",
"dir_config",
"[",
"'port'",
"]",
"if",
"'port'",
"in",
"dir_config",
"else",
"None",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"True",
"r_config",
"=",
"remote",
".",
"get_config",
"(",
")",
"r_folder",
"=",
"st_util",
".",
"find_folder_with_path",
"(",
"dir_config",
"[",
"'remote_path'",
"]",
",",
"r_config",
")",
"# Delete device id from folder",
"r_config",
"=",
"remote",
".",
"get_config",
"(",
")",
"self_devid",
"=",
"self",
".",
"get_device_id",
"(",
")",
"del_device",
"=",
"remote",
".",
"delete_device_from_folder",
"(",
"dir_config",
"[",
"'remote_path'",
"]",
",",
"self_devid",
",",
"r_config",
")",
"# Check to see if no other folder depends has this device",
"pruned",
"=",
"st_util",
".",
"prune_devices",
"(",
"r_folder",
",",
"r_config",
")",
"remote",
".",
"set_config",
"(",
"r_config",
")",
"if",
"pruned",
":",
"remote",
".",
"restart",
"(",
")",
"return",
"True"
]
| Stop synchronization of local_path | [
"Stop",
"synchronization",
"of",
"local_path"
]
| 325fe5e5870b7d4eb121dcc7e93be64aa16e7988 | https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/syncthing_factory.py#L862-L941 | train |
kodethon/KoDrive | kodrive/syncthing_factory.py | SyncthingClient.tag | def tag(self, path, name):
'''
Change name associated with path
'''
if not path[len(path) - 1] == '/':
path += '/'
config = self.get_config()
folder = self.find_folder({
'path' : path
}, config)
if not folder:
raise custom_errors.FileNotInConfig(path)
old_name = folder['label']
folder['label'] = name
dir_config = self.adapter.get_dir_config(path)
dir_config['label'] = name
self.adapter.set_dir_config(dir_config)
self.set_config(config)
# self.restart
return old_name | python | def tag(self, path, name):
'''
Change name associated with path
'''
if not path[len(path) - 1] == '/':
path += '/'
config = self.get_config()
folder = self.find_folder({
'path' : path
}, config)
if not folder:
raise custom_errors.FileNotInConfig(path)
old_name = folder['label']
folder['label'] = name
dir_config = self.adapter.get_dir_config(path)
dir_config['label'] = name
self.adapter.set_dir_config(dir_config)
self.set_config(config)
# self.restart
return old_name | [
"def",
"tag",
"(",
"self",
",",
"path",
",",
"name",
")",
":",
"if",
"not",
"path",
"[",
"len",
"(",
"path",
")",
"-",
"1",
"]",
"==",
"'/'",
":",
"path",
"+=",
"'/'",
"config",
"=",
"self",
".",
"get_config",
"(",
")",
"folder",
"=",
"self",
".",
"find_folder",
"(",
"{",
"'path'",
":",
"path",
"}",
",",
"config",
")",
"if",
"not",
"folder",
":",
"raise",
"custom_errors",
".",
"FileNotInConfig",
"(",
"path",
")",
"old_name",
"=",
"folder",
"[",
"'label'",
"]",
"folder",
"[",
"'label'",
"]",
"=",
"name",
"dir_config",
"=",
"self",
".",
"adapter",
".",
"get_dir_config",
"(",
"path",
")",
"dir_config",
"[",
"'label'",
"]",
"=",
"name",
"self",
".",
"adapter",
".",
"set_dir_config",
"(",
"dir_config",
")",
"self",
".",
"set_config",
"(",
"config",
")",
"# self.restart",
"return",
"old_name"
]
| Change name associated with path | [
"Change",
"name",
"associated",
"with",
"path"
]
| 325fe5e5870b7d4eb121dcc7e93be64aa16e7988 | https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/syncthing_factory.py#L943-L969 | train |
tjcsl/cslbot | cslbot/commands/channels.py | cmd | def cmd(send, _, args):
"""Returns a listing of the current channels.
Syntax: {command}
"""
with args['handler'].data_lock:
channels = ", ".join(sorted(args['handler'].channels))
send(channels) | python | def cmd(send, _, args):
"""Returns a listing of the current channels.
Syntax: {command}
"""
with args['handler'].data_lock:
channels = ", ".join(sorted(args['handler'].channels))
send(channels) | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"with",
"args",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"channels",
"=",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"args",
"[",
"'handler'",
"]",
".",
"channels",
")",
")",
"send",
"(",
"channels",
")"
]
| Returns a listing of the current channels.
Syntax: {command} | [
"Returns",
"a",
"listing",
"of",
"the",
"current",
"channels",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/channels.py#L22-L30 | train |
tjcsl/cslbot | cslbot/commands/stock.py | cmd | def cmd(send, msg, args):
"""Gets a stock quote.
Syntax: {command} [symbol]
Powered by markit on demand (http://dev.markitondemand.com)
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('stock', nargs='?', default=random_stock())
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
send(gen_stock(cmdargs.stock)) | python | def cmd(send, msg, args):
"""Gets a stock quote.
Syntax: {command} [symbol]
Powered by markit on demand (http://dev.markitondemand.com)
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('stock', nargs='?', default=random_stock())
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
send(gen_stock(cmdargs.stock)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'stock'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"random_stock",
"(",
")",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"send",
"(",
"gen_stock",
"(",
"cmdargs",
".",
"stock",
")",
")"
]
| Gets a stock quote.
Syntax: {command} [symbol]
Powered by markit on demand (http://dev.markitondemand.com) | [
"Gets",
"a",
"stock",
"quote",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/stock.py#L48-L62 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/state.py | StateSerializer.get_elections | def get_elections(self, obj):
"""All elections in division."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = list(obj.elections.filter(election_day=election_day))
district = DivisionLevel.objects.get(name=DivisionLevel.DISTRICT)
for district in obj.children.filter(level=district):
elections.extend(
list(district.elections.filter(
election_day=election_day,
meta__isnull=False
))
)
return ElectionSerializer(elections, many=True).data | python | def get_elections(self, obj):
"""All elections in division."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = list(obj.elections.filter(election_day=election_day))
district = DivisionLevel.objects.get(name=DivisionLevel.DISTRICT)
for district in obj.children.filter(level=district):
elections.extend(
list(district.elections.filter(
election_day=election_day,
meta__isnull=False
))
)
return ElectionSerializer(elections, many=True).data | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"elections",
"=",
"list",
"(",
"obj",
".",
"elections",
".",
"filter",
"(",
"election_day",
"=",
"election_day",
")",
")",
"district",
"=",
"DivisionLevel",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"DivisionLevel",
".",
"DISTRICT",
")",
"for",
"district",
"in",
"obj",
".",
"children",
".",
"filter",
"(",
"level",
"=",
"district",
")",
":",
"elections",
".",
"extend",
"(",
"list",
"(",
"district",
".",
"elections",
".",
"filter",
"(",
"election_day",
"=",
"election_day",
",",
"meta__isnull",
"=",
"False",
")",
")",
")",
"return",
"ElectionSerializer",
"(",
"elections",
",",
"many",
"=",
"True",
")",
".",
"data"
]
| All elections in division. | [
"All",
"elections",
"in",
"division",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/state.py#L52-L67 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/state.py | StateSerializer.get_content | def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
division = obj
# In case of house special election,
# use parent division.
if obj.level.name == DivisionLevel.DISTRICT:
division = obj.parent
special = True if self.context.get('special') else False
return PageContent.objects.division_content(
election_day,
division,
special
) | python | def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
division = obj
# In case of house special election,
# use parent division.
if obj.level.name == DivisionLevel.DISTRICT:
division = obj.parent
special = True if self.context.get('special') else False
return PageContent.objects.division_content(
election_day,
division,
special
) | [
"def",
"get_content",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"division",
"=",
"obj",
"# In case of house special election,",
"# use parent division.",
"if",
"obj",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"division",
"=",
"obj",
".",
"parent",
"special",
"=",
"True",
"if",
"self",
".",
"context",
".",
"get",
"(",
"'special'",
")",
"else",
"False",
"return",
"PageContent",
".",
"objects",
".",
"division_content",
"(",
"election_day",
",",
"division",
",",
"special",
")"
]
| All content for a state's page on an election day. | [
"All",
"content",
"for",
"a",
"state",
"s",
"page",
"on",
"an",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/state.py#L69-L85 | train |
The-Politico/politico-civic-election-night | electionnight/management/commands/methods/bootstrap/executive_office.py | ExecutiveOffice.bootstrap_executive_office | def bootstrap_executive_office(self, election):
"""
For executive offices, create page content for the office.
For the president, create pages for each state result.
"""
division = election.race.office.jurisdiction.division
content_type = ContentType.objects.get_for_model(election.race.office)
PageContent.objects.get_or_create(
content_type=content_type,
object_id=election.race.office.pk,
election_day=election.election_day,
division=division,
)
if division.level == self.NATIONAL_LEVEL:
self.bootstrap_executive_office_states(election)
else:
# Create state governor page type
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label="government", model="office"
),
election_day=election.election_day,
division_level=self.STATE_LEVEL,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
)
generic_state_page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label="geography", model="division"
),
election_day=election.election_day,
division_level=DivisionLevel.objects.get(
name=DivisionLevel.STATE
),
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(
generic_state_page_type
),
object_id=generic_state_page_type.pk,
election_day=election.election_day,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(division),
object_id=division.pk,
election_day=election.election_day,
special_election=False,
) | python | def bootstrap_executive_office(self, election):
"""
For executive offices, create page content for the office.
For the president, create pages for each state result.
"""
division = election.race.office.jurisdiction.division
content_type = ContentType.objects.get_for_model(election.race.office)
PageContent.objects.get_or_create(
content_type=content_type,
object_id=election.race.office.pk,
election_day=election.election_day,
division=division,
)
if division.level == self.NATIONAL_LEVEL:
self.bootstrap_executive_office_states(election)
else:
# Create state governor page type
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label="government", model="office"
),
election_day=election.election_day,
division_level=self.STATE_LEVEL,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
)
generic_state_page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label="geography", model="division"
),
election_day=election.election_day,
division_level=DivisionLevel.objects.get(
name=DivisionLevel.STATE
),
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(
generic_state_page_type
),
object_id=generic_state_page_type.pk,
election_day=election.election_day,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(division),
object_id=division.pk,
election_day=election.election_day,
special_election=False,
) | [
"def",
"bootstrap_executive_office",
"(",
"self",
",",
"election",
")",
":",
"division",
"=",
"election",
".",
"race",
".",
"office",
".",
"jurisdiction",
".",
"division",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"election",
".",
"race",
".",
"office",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"content_type",
",",
"object_id",
"=",
"election",
".",
"race",
".",
"office",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division",
"=",
"division",
",",
")",
"if",
"division",
".",
"level",
"==",
"self",
".",
"NATIONAL_LEVEL",
":",
"self",
".",
"bootstrap_executive_office_states",
"(",
"election",
")",
"else",
":",
"# Create state governor page type",
"page_type",
",",
"created",
"=",
"PageType",
".",
"objects",
".",
"get_or_create",
"(",
"model_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"\"government\"",
",",
"model",
"=",
"\"office\"",
")",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division_level",
"=",
"self",
".",
"STATE_LEVEL",
",",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"page_type",
")",
",",
"object_id",
"=",
"page_type",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
")",
"generic_state_page_type",
",",
"created",
"=",
"PageType",
".",
"objects",
".",
"get_or_create",
"(",
"model_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"\"geography\"",
",",
"model",
"=",
"\"division\"",
")",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division_level",
"=",
"DivisionLevel",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"DivisionLevel",
".",
"STATE",
")",
",",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"generic_state_page_type",
")",
",",
"object_id",
"=",
"generic_state_page_type",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"division",
")",
",",
"object_id",
"=",
"division",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"special_election",
"=",
"False",
",",
")"
]
| For executive offices, create page content for the office.
For the president, create pages for each state result. | [
"For",
"executive",
"offices",
"create",
"page",
"content",
"for",
"the",
"office",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/methods/bootstrap/executive_office.py#L10-L63 | train |
tjcsl/cslbot | cslbot/commands/imdb.py | cmd | def cmd(send, msg, args):
"""Gets a random movie.
Syntax: {command}
"""
req = get('http://www.imdb.com/random/title')
html = fromstring(req.text)
name = html.find('head/title').text.split('-')[0].strip()
key = args['config']['api']['bitlykey']
send("%s -- %s" % (name, get_short(req.url, key))) | python | def cmd(send, msg, args):
"""Gets a random movie.
Syntax: {command}
"""
req = get('http://www.imdb.com/random/title')
html = fromstring(req.text)
name = html.find('head/title').text.split('-')[0].strip()
key = args['config']['api']['bitlykey']
send("%s -- %s" % (name, get_short(req.url, key))) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"req",
"=",
"get",
"(",
"'http://www.imdb.com/random/title'",
")",
"html",
"=",
"fromstring",
"(",
"req",
".",
"text",
")",
"name",
"=",
"html",
".",
"find",
"(",
"'head/title'",
")",
".",
"text",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"send",
"(",
"\"%s -- %s\"",
"%",
"(",
"name",
",",
"get_short",
"(",
"req",
".",
"url",
",",
"key",
")",
")",
")"
]
| Gets a random movie.
Syntax: {command} | [
"Gets",
"a",
"random",
"movie",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/imdb.py#L27-L38 | train |
adamziel/python_translate | python_translate/selector.py | PluralizationRules.get | def get(number, locale):
"""
Returns the plural position to use for the given locale and number.
@type number: int
@param number: The number
@type locale: str
@param locale: The locale
@rtype: int
@return: The plural position
"""
if locale == 'pt_BR':
# temporary set a locale for brazilian
locale = 'xbr'
if len(locale) > 3:
locale = locale.split("_")[0]
rule = PluralizationRules._rules.get(locale, lambda _: 0)
_return = rule(number)
if not isinstance(_return, int) or _return < 0:
return 0
return _return | python | def get(number, locale):
"""
Returns the plural position to use for the given locale and number.
@type number: int
@param number: The number
@type locale: str
@param locale: The locale
@rtype: int
@return: The plural position
"""
if locale == 'pt_BR':
# temporary set a locale for brazilian
locale = 'xbr'
if len(locale) > 3:
locale = locale.split("_")[0]
rule = PluralizationRules._rules.get(locale, lambda _: 0)
_return = rule(number)
if not isinstance(_return, int) or _return < 0:
return 0
return _return | [
"def",
"get",
"(",
"number",
",",
"locale",
")",
":",
"if",
"locale",
"==",
"'pt_BR'",
":",
"# temporary set a locale for brazilian",
"locale",
"=",
"'xbr'",
"if",
"len",
"(",
"locale",
")",
">",
"3",
":",
"locale",
"=",
"locale",
".",
"split",
"(",
"\"_\"",
")",
"[",
"0",
"]",
"rule",
"=",
"PluralizationRules",
".",
"_rules",
".",
"get",
"(",
"locale",
",",
"lambda",
"_",
":",
"0",
")",
"_return",
"=",
"rule",
"(",
"number",
")",
"if",
"not",
"isinstance",
"(",
"_return",
",",
"int",
")",
"or",
"_return",
"<",
"0",
":",
"return",
"0",
"return",
"_return"
]
| Returns the plural position to use for the given locale and number.
@type number: int
@param number: The number
@type locale: str
@param locale: The locale
@rtype: int
@return: The plural position | [
"Returns",
"the",
"plural",
"position",
"to",
"use",
"for",
"the",
"given",
"locale",
"and",
"number",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/selector.py#L242-L266 | train |
adamziel/python_translate | python_translate/selector.py | PluralizationRules.set | def set(rule, locale):
"""
Overrides the default plural rule for a given locale.
@type rule: str
@param rule: Callable
@type locale: str
@param locale: The locale
@raises: ValueError
"""
if locale == 'pt_BR':
# temporary set a locale for brazilian
locale = 'xbr'
if len(locale) > 3:
locale = locale.split("_")[0]
if not hasattr(rule, '__call__'):
raise ValueError('The given rule can not be called')
PluralizationRules._rules[locale] = rule | python | def set(rule, locale):
"""
Overrides the default plural rule for a given locale.
@type rule: str
@param rule: Callable
@type locale: str
@param locale: The locale
@raises: ValueError
"""
if locale == 'pt_BR':
# temporary set a locale for brazilian
locale = 'xbr'
if len(locale) > 3:
locale = locale.split("_")[0]
if not hasattr(rule, '__call__'):
raise ValueError('The given rule can not be called')
PluralizationRules._rules[locale] = rule | [
"def",
"set",
"(",
"rule",
",",
"locale",
")",
":",
"if",
"locale",
"==",
"'pt_BR'",
":",
"# temporary set a locale for brazilian",
"locale",
"=",
"'xbr'",
"if",
"len",
"(",
"locale",
")",
">",
"3",
":",
"locale",
"=",
"locale",
".",
"split",
"(",
"\"_\"",
")",
"[",
"0",
"]",
"if",
"not",
"hasattr",
"(",
"rule",
",",
"'__call__'",
")",
":",
"raise",
"ValueError",
"(",
"'The given rule can not be called'",
")",
"PluralizationRules",
".",
"_rules",
"[",
"locale",
"]",
"=",
"rule"
]
| Overrides the default plural rule for a given locale.
@type rule: str
@param rule: Callable
@type locale: str
@param locale: The locale
@raises: ValueError | [
"Overrides",
"the",
"default",
"plural",
"rule",
"for",
"a",
"given",
"locale",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/selector.py#L269-L292 | train |
tjcsl/cslbot | cslbot/commands/acronym.py | cmd | def cmd(send, msg, _):
"""Generates a meaning for the specified acronym.
Syntax: {command} <acronym>
"""
if not msg:
send("What acronym?")
return
words = get_list()
letters = [c for c in msg.lower() if c in string.ascii_lowercase]
output = " ".join([choice(words[c]) for c in letters])
if output:
send('%s: %s' % (msg, output.title()))
else:
send("No acronym found for %s" % msg) | python | def cmd(send, msg, _):
"""Generates a meaning for the specified acronym.
Syntax: {command} <acronym>
"""
if not msg:
send("What acronym?")
return
words = get_list()
letters = [c for c in msg.lower() if c in string.ascii_lowercase]
output = " ".join([choice(words[c]) for c in letters])
if output:
send('%s: %s' % (msg, output.title()))
else:
send("No acronym found for %s" % msg) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"What acronym?\"",
")",
"return",
"words",
"=",
"get_list",
"(",
")",
"letters",
"=",
"[",
"c",
"for",
"c",
"in",
"msg",
".",
"lower",
"(",
")",
"if",
"c",
"in",
"string",
".",
"ascii_lowercase",
"]",
"output",
"=",
"\" \"",
".",
"join",
"(",
"[",
"choice",
"(",
"words",
"[",
"c",
"]",
")",
"for",
"c",
"in",
"letters",
"]",
")",
"if",
"output",
":",
"send",
"(",
"'%s: %s'",
"%",
"(",
"msg",
",",
"output",
".",
"title",
"(",
")",
")",
")",
"else",
":",
"send",
"(",
"\"No acronym found for %s\"",
"%",
"msg",
")"
]
| Generates a meaning for the specified acronym.
Syntax: {command} <acronym> | [
"Generates",
"a",
"meaning",
"for",
"the",
"specified",
"acronym",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/acronym.py#L36-L51 | train |
brandjon/simplestruct | simplestruct/struct.py | MetaStruct.get_boundargs | def get_boundargs(cls, *args, **kargs):
"""Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments.
"""
boundargs = cls._signature.bind(*args, **kargs)
# Include default arguments.
for param in cls._signature.parameters.values():
if (param.name not in boundargs.arguments and
param.default is not param.empty):
boundargs.arguments[param.name] = param.default
return boundargs | python | def get_boundargs(cls, *args, **kargs):
"""Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments.
"""
boundargs = cls._signature.bind(*args, **kargs)
# Include default arguments.
for param in cls._signature.parameters.values():
if (param.name not in boundargs.arguments and
param.default is not param.empty):
boundargs.arguments[param.name] = param.default
return boundargs | [
"def",
"get_boundargs",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"boundargs",
"=",
"cls",
".",
"_signature",
".",
"bind",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"# Include default arguments.",
"for",
"param",
"in",
"cls",
".",
"_signature",
".",
"parameters",
".",
"values",
"(",
")",
":",
"if",
"(",
"param",
".",
"name",
"not",
"in",
"boundargs",
".",
"arguments",
"and",
"param",
".",
"default",
"is",
"not",
"param",
".",
"empty",
")",
":",
"boundargs",
".",
"arguments",
"[",
"param",
".",
"name",
"]",
"=",
"param",
".",
"default",
"return",
"boundargs"
]
| Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments. | [
"Return",
"an",
"inspect",
".",
"BoundArguments",
"object",
"for",
"the",
"application",
"of",
"this",
"Struct",
"s",
"signature",
"to",
"its",
"arguments",
".",
"Add",
"missing",
"values",
"for",
"default",
"fields",
"as",
"keyword",
"arguments",
"."
]
| f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/struct.py#L148-L159 | train |
brandjon/simplestruct | simplestruct/struct.py | Struct._asdict | def _asdict(self):
"""Return an OrderedDict of the fields."""
return OrderedDict((f.name, getattr(self, f.name))
for f in self._struct) | python | def _asdict(self):
"""Return an OrderedDict of the fields."""
return OrderedDict((f.name, getattr(self, f.name))
for f in self._struct) | [
"def",
"_asdict",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"(",
"f",
".",
"name",
",",
"getattr",
"(",
"self",
",",
"f",
".",
"name",
")",
")",
"for",
"f",
"in",
"self",
".",
"_struct",
")"
]
| Return an OrderedDict of the fields. | [
"Return",
"an",
"OrderedDict",
"of",
"the",
"fields",
"."
]
| f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/struct.py#L305-L308 | train |
brandjon/simplestruct | simplestruct/struct.py | Struct._replace | def _replace(self, **kargs):
"""Return a copy of this Struct with the same fields except
with the changes specified by kargs.
"""
fields = {f.name: getattr(self, f.name)
for f in self._struct}
fields.update(kargs)
return type(self)(**fields) | python | def _replace(self, **kargs):
"""Return a copy of this Struct with the same fields except
with the changes specified by kargs.
"""
fields = {f.name: getattr(self, f.name)
for f in self._struct}
fields.update(kargs)
return type(self)(**fields) | [
"def",
"_replace",
"(",
"self",
",",
"*",
"*",
"kargs",
")",
":",
"fields",
"=",
"{",
"f",
".",
"name",
":",
"getattr",
"(",
"self",
",",
"f",
".",
"name",
")",
"for",
"f",
"in",
"self",
".",
"_struct",
"}",
"fields",
".",
"update",
"(",
"kargs",
")",
"return",
"type",
"(",
"self",
")",
"(",
"*",
"*",
"fields",
")"
]
| Return a copy of this Struct with the same fields except
with the changes specified by kargs. | [
"Return",
"a",
"copy",
"of",
"this",
"Struct",
"with",
"the",
"same",
"fields",
"except",
"with",
"the",
"changes",
"specified",
"by",
"kargs",
"."
]
| f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/struct.py#L310-L317 | train |
comparnion/mysqldbhelper | mysqldbhelper/__init__.py | DatabaseConnection.get_one | def get_one(self, qry, tpl):
''' get a single from from a query
limit 1 is automatically added '''
self.cur.execute(qry + ' LIMIT 1', tpl)
result = self.cur.fetchone()
# unpack tuple if it has only
# one element
# TODO unpack results
if type(result) is tuple and len(result) == 1:
result = result[0]
return result | python | def get_one(self, qry, tpl):
''' get a single from from a query
limit 1 is automatically added '''
self.cur.execute(qry + ' LIMIT 1', tpl)
result = self.cur.fetchone()
# unpack tuple if it has only
# one element
# TODO unpack results
if type(result) is tuple and len(result) == 1:
result = result[0]
return result | [
"def",
"get_one",
"(",
"self",
",",
"qry",
",",
"tpl",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"qry",
"+",
"' LIMIT 1'",
",",
"tpl",
")",
"result",
"=",
"self",
".",
"cur",
".",
"fetchone",
"(",
")",
"# unpack tuple if it has only",
"# one element",
"# TODO unpack results",
"if",
"type",
"(",
"result",
")",
"is",
"tuple",
"and",
"len",
"(",
"result",
")",
"==",
"1",
":",
"result",
"=",
"result",
"[",
"0",
"]",
"return",
"result"
]
| get a single from from a query
limit 1 is automatically added | [
"get",
"a",
"single",
"from",
"from",
"a",
"query",
"limit",
"1",
"is",
"automatically",
"added"
]
| 9320df20b77b181fde277b33730954611d41846f | https://github.com/comparnion/mysqldbhelper/blob/9320df20b77b181fde277b33730954611d41846f/mysqldbhelper/__init__.py#L68-L78 | train |
comparnion/mysqldbhelper | mysqldbhelper/__init__.py | DatabaseConnection.get_all | def get_all(self, qry, tpl):
''' get all rows for a query '''
self.cur.execute(qry, tpl)
result = self.cur.fetchall()
return result | python | def get_all(self, qry, tpl):
''' get all rows for a query '''
self.cur.execute(qry, tpl)
result = self.cur.fetchall()
return result | [
"def",
"get_all",
"(",
"self",
",",
"qry",
",",
"tpl",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"qry",
",",
"tpl",
")",
"result",
"=",
"self",
".",
"cur",
".",
"fetchall",
"(",
")",
"return",
"result"
]
| get all rows for a query | [
"get",
"all",
"rows",
"for",
"a",
"query"
]
| 9320df20b77b181fde277b33730954611d41846f | https://github.com/comparnion/mysqldbhelper/blob/9320df20b77b181fde277b33730954611d41846f/mysqldbhelper/__init__.py#L81-L85 | train |
Genida/archan | src/archan/logging.py | Logger.set_level | def set_level(level):
"""
Set level of logging for all loggers.
Args:
level (int): level of logging.
"""
Logger.level = level
for logger in Logger.loggers.values():
logger.setLevel(level) | python | def set_level(level):
"""
Set level of logging for all loggers.
Args:
level (int): level of logging.
"""
Logger.level = level
for logger in Logger.loggers.values():
logger.setLevel(level) | [
"def",
"set_level",
"(",
"level",
")",
":",
"Logger",
".",
"level",
"=",
"level",
"for",
"logger",
"in",
"Logger",
".",
"loggers",
".",
"values",
"(",
")",
":",
"logger",
".",
"setLevel",
"(",
"level",
")"
]
| Set level of logging for all loggers.
Args:
level (int): level of logging. | [
"Set",
"level",
"of",
"logging",
"for",
"all",
"loggers",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L19-L28 | train |
Genida/archan | src/archan/logging.py | Logger.get_logger | def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'):
"""
Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``logging.getLogger``.
"""
if name not in Logger.loggers:
if Logger.level is None and level is None:
Logger.level = level = logging.ERROR
elif Logger.level is None:
Logger.level = level
elif level is None:
level = Logger.level
logger = logging.getLogger(name)
logger_handler = logging.StreamHandler()
logger_handler.setFormatter(LoggingFormatter(fmt=name + fmt))
logger.addHandler(logger_handler)
logger.setLevel(level)
Logger.loggers[name] = logger
return Logger.loggers[name] | python | def get_logger(name, level=None, fmt=':%(lineno)d: %(message)s'):
"""
Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``logging.getLogger``.
"""
if name not in Logger.loggers:
if Logger.level is None and level is None:
Logger.level = level = logging.ERROR
elif Logger.level is None:
Logger.level = level
elif level is None:
level = Logger.level
logger = logging.getLogger(name)
logger_handler = logging.StreamHandler()
logger_handler.setFormatter(LoggingFormatter(fmt=name + fmt))
logger.addHandler(logger_handler)
logger.setLevel(level)
Logger.loggers[name] = logger
return Logger.loggers[name] | [
"def",
"get_logger",
"(",
"name",
",",
"level",
"=",
"None",
",",
"fmt",
"=",
"':%(lineno)d: %(message)s'",
")",
":",
"if",
"name",
"not",
"in",
"Logger",
".",
"loggers",
":",
"if",
"Logger",
".",
"level",
"is",
"None",
"and",
"level",
"is",
"None",
":",
"Logger",
".",
"level",
"=",
"level",
"=",
"logging",
".",
"ERROR",
"elif",
"Logger",
".",
"level",
"is",
"None",
":",
"Logger",
".",
"level",
"=",
"level",
"elif",
"level",
"is",
"None",
":",
"level",
"=",
"Logger",
".",
"level",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"logger_handler",
".",
"setFormatter",
"(",
"LoggingFormatter",
"(",
"fmt",
"=",
"name",
"+",
"fmt",
")",
")",
"logger",
".",
"addHandler",
"(",
"logger_handler",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"Logger",
".",
"loggers",
"[",
"name",
"]",
"=",
"logger",
"return",
"Logger",
".",
"loggers",
"[",
"name",
"]"
]
| Return a logger.
Args:
name (str): name to pass to the logging module.
level (int): level of logging.
fmt (str): format string.
Returns:
logging.Logger: logger from ``logging.getLogger``. | [
"Return",
"a",
"logger",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L31-L56 | train |
Genida/archan | src/archan/logging.py | LoggingFormatter.format | def format(self, record):
"""Override default format method."""
if record.levelno == logging.DEBUG:
string = Back.WHITE + Fore.BLACK + ' debug '
elif record.levelno == logging.INFO:
string = Back.BLUE + Fore.WHITE + ' info '
elif record.levelno == logging.WARNING:
string = Back.YELLOW + Fore.BLACK + ' warning '
elif record.levelno == logging.ERROR:
string = Back.RED + Fore.WHITE + ' error '
elif record.levelno == logging.CRITICAL:
string = Back.BLACK + Fore.WHITE + ' critical '
else:
string = ''
return '{none}{string}{none} {super}'.format(
none=Style.RESET_ALL, string=string, super=super().format(record)) | python | def format(self, record):
"""Override default format method."""
if record.levelno == logging.DEBUG:
string = Back.WHITE + Fore.BLACK + ' debug '
elif record.levelno == logging.INFO:
string = Back.BLUE + Fore.WHITE + ' info '
elif record.levelno == logging.WARNING:
string = Back.YELLOW + Fore.BLACK + ' warning '
elif record.levelno == logging.ERROR:
string = Back.RED + Fore.WHITE + ' error '
elif record.levelno == logging.CRITICAL:
string = Back.BLACK + Fore.WHITE + ' critical '
else:
string = ''
return '{none}{string}{none} {super}'.format(
none=Style.RESET_ALL, string=string, super=super().format(record)) | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"if",
"record",
".",
"levelno",
"==",
"logging",
".",
"DEBUG",
":",
"string",
"=",
"Back",
".",
"WHITE",
"+",
"Fore",
".",
"BLACK",
"+",
"' debug '",
"elif",
"record",
".",
"levelno",
"==",
"logging",
".",
"INFO",
":",
"string",
"=",
"Back",
".",
"BLUE",
"+",
"Fore",
".",
"WHITE",
"+",
"' info '",
"elif",
"record",
".",
"levelno",
"==",
"logging",
".",
"WARNING",
":",
"string",
"=",
"Back",
".",
"YELLOW",
"+",
"Fore",
".",
"BLACK",
"+",
"' warning '",
"elif",
"record",
".",
"levelno",
"==",
"logging",
".",
"ERROR",
":",
"string",
"=",
"Back",
".",
"RED",
"+",
"Fore",
".",
"WHITE",
"+",
"' error '",
"elif",
"record",
".",
"levelno",
"==",
"logging",
".",
"CRITICAL",
":",
"string",
"=",
"Back",
".",
"BLACK",
"+",
"Fore",
".",
"WHITE",
"+",
"' critical '",
"else",
":",
"string",
"=",
"''",
"return",
"'{none}{string}{none} {super}'",
".",
"format",
"(",
"none",
"=",
"Style",
".",
"RESET_ALL",
",",
"string",
"=",
"string",
",",
"super",
"=",
"super",
"(",
")",
".",
"format",
"(",
"record",
")",
")"
]
| Override default format method. | [
"Override",
"default",
"format",
"method",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/logging.py#L62-L77 | train |
tjcsl/cslbot | cslbot/helpers/sql.py | Sql.log | def log(self, source: str, target: str, flags: int, msg: str, mtype: str) -> None:
"""Logs a message to the database.
| source: The source of the message.
| target: The target of the message.
| flags: Is the user a operator or voiced?
| msg: The text of the message.
| msg: The type of message.
| time: The current time (Unix Epoch).
"""
entry = Log(source=str(source), target=target, flags=flags, msg=msg, type=mtype, time=datetime.now())
with self.session_scope() as session:
session.add(entry)
session.flush() | python | def log(self, source: str, target: str, flags: int, msg: str, mtype: str) -> None:
"""Logs a message to the database.
| source: The source of the message.
| target: The target of the message.
| flags: Is the user a operator or voiced?
| msg: The text of the message.
| msg: The type of message.
| time: The current time (Unix Epoch).
"""
entry = Log(source=str(source), target=target, flags=flags, msg=msg, type=mtype, time=datetime.now())
with self.session_scope() as session:
session.add(entry)
session.flush() | [
"def",
"log",
"(",
"self",
",",
"source",
":",
"str",
",",
"target",
":",
"str",
",",
"flags",
":",
"int",
",",
"msg",
":",
"str",
",",
"mtype",
":",
"str",
")",
"->",
"None",
":",
"entry",
"=",
"Log",
"(",
"source",
"=",
"str",
"(",
"source",
")",
",",
"target",
"=",
"target",
",",
"flags",
"=",
"flags",
",",
"msg",
"=",
"msg",
",",
"type",
"=",
"mtype",
",",
"time",
"=",
"datetime",
".",
"now",
"(",
")",
")",
"with",
"self",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"session",
".",
"add",
"(",
"entry",
")",
"session",
".",
"flush",
"(",
")"
]
| Logs a message to the database.
| source: The source of the message.
| target: The target of the message.
| flags: Is the user a operator or voiced?
| msg: The text of the message.
| msg: The type of message.
| time: The current time (Unix Epoch). | [
"Logs",
"a",
"message",
"to",
"the",
"database",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/sql.py#L62-L76 | train |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_domains | def get_domains(self):
"""
Returns domains affected by operation.
@rtype: list
"""
if self.domains is None:
self.domains = list(
set(self.source.get_domains() + self.target.get_domains()))
return self.domains | python | def get_domains(self):
"""
Returns domains affected by operation.
@rtype: list
"""
if self.domains is None:
self.domains = list(
set(self.source.get_domains() + self.target.get_domains()))
return self.domains | [
"def",
"get_domains",
"(",
"self",
")",
":",
"if",
"self",
".",
"domains",
"is",
"None",
":",
"self",
".",
"domains",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"source",
".",
"get_domains",
"(",
")",
"+",
"self",
".",
"target",
".",
"get_domains",
"(",
")",
")",
")",
"return",
"self",
".",
"domains"
]
| Returns domains affected by operation.
@rtype: list | [
"Returns",
"domains",
"affected",
"by",
"operation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L46-L54 | train |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_messages | def get_messages(self, domain):
"""
Returns all valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'all' not in self.messages[domain]:
self._process_domain(domain)
return self.messages[domain]['all'] | python | def get_messages(self, domain):
"""
Returns all valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'all' not in self.messages[domain]:
self._process_domain(domain)
return self.messages[domain]['all'] | [
"def",
"get_messages",
"(",
"self",
",",
"domain",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"raise",
"ValueError",
"(",
"'Invalid domain: {0}'",
".",
"format",
"(",
"domain",
")",
")",
"if",
"domain",
"not",
"in",
"self",
".",
"messages",
"or",
"'all'",
"not",
"in",
"self",
".",
"messages",
"[",
"domain",
"]",
":",
"self",
".",
"_process_domain",
"(",
"domain",
")",
"return",
"self",
".",
"messages",
"[",
"domain",
"]",
"[",
"'all'",
"]"
]
| Returns all valid messages after operation.
@type domain: str
@rtype: dict | [
"Returns",
"all",
"valid",
"messages",
"after",
"operation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L56-L68 | train |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_new_messages | def get_new_messages(self, domain):
"""
Returns new valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'new' not in self.messages[domain]:
self._process_domain(domain)
return self.messages[domain]['new'] | python | def get_new_messages(self, domain):
"""
Returns new valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or 'new' not in self.messages[domain]:
self._process_domain(domain)
return self.messages[domain]['new'] | [
"def",
"get_new_messages",
"(",
"self",
",",
"domain",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"raise",
"ValueError",
"(",
"'Invalid domain: {0}'",
".",
"format",
"(",
"domain",
")",
")",
"if",
"domain",
"not",
"in",
"self",
".",
"messages",
"or",
"'new'",
"not",
"in",
"self",
".",
"messages",
"[",
"domain",
"]",
":",
"self",
".",
"_process_domain",
"(",
"domain",
")",
"return",
"self",
".",
"messages",
"[",
"domain",
"]",
"[",
"'new'",
"]"
]
| Returns new valid messages after operation.
@type domain: str
@rtype: dict | [
"Returns",
"new",
"valid",
"messages",
"after",
"operation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L70-L82 | train |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_obsolete_messages | def get_obsolete_messages(self, domain):
"""
Returns obsolete valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or \
'obsolete' not in self.messages[domain]:
self._process_domain(domain)
return self.messages[domain]['obsolete'] | python | def get_obsolete_messages(self, domain):
"""
Returns obsolete valid messages after operation.
@type domain: str
@rtype: dict
"""
if domain not in self.domains:
raise ValueError('Invalid domain: {0}'.format(domain))
if domain not in self.messages or \
'obsolete' not in self.messages[domain]:
self._process_domain(domain)
return self.messages[domain]['obsolete'] | [
"def",
"get_obsolete_messages",
"(",
"self",
",",
"domain",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"raise",
"ValueError",
"(",
"'Invalid domain: {0}'",
".",
"format",
"(",
"domain",
")",
")",
"if",
"domain",
"not",
"in",
"self",
".",
"messages",
"or",
"'obsolete'",
"not",
"in",
"self",
".",
"messages",
"[",
"domain",
"]",
":",
"self",
".",
"_process_domain",
"(",
"domain",
")",
"return",
"self",
".",
"messages",
"[",
"domain",
"]",
"[",
"'obsolete'",
"]"
]
| Returns obsolete valid messages after operation.
@type domain: str
@rtype: dict | [
"Returns",
"obsolete",
"valid",
"messages",
"after",
"operation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L84-L97 | train |
adamziel/python_translate | python_translate/operations.py | AbstractOperation.get_result | def get_result(self):
"""
Returns resulting catalogue
@rtype: MessageCatalogue
"""
for domain in self.domains:
if domain not in self.messages:
self._process_domain(domain)
return self.result | python | def get_result(self):
"""
Returns resulting catalogue
@rtype: MessageCatalogue
"""
for domain in self.domains:
if domain not in self.messages:
self._process_domain(domain)
return self.result | [
"def",
"get_result",
"(",
"self",
")",
":",
"for",
"domain",
"in",
"self",
".",
"domains",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"messages",
":",
"self",
".",
"_process_domain",
"(",
"domain",
")",
"return",
"self",
".",
"result"
]
| Returns resulting catalogue
@rtype: MessageCatalogue | [
"Returns",
"resulting",
"catalogue"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/operations.py#L99-L108 | train |
tjcsl/cslbot | cslbot/helpers/orm.py | setup_db | def setup_db(session, botconfig, confdir):
"""Sets up the database."""
Base.metadata.create_all(session.connection())
# If we're creating a fresh db, we don't need to worry about migrations.
if not session.get_bind().has_table('alembic_version'):
conf_obj = config.Config()
conf_obj.set_main_option('bot_config_path', confdir)
with resources.path('cslbot', botconfig['alembic']['script_location']) as script_location:
conf_obj.set_main_option('script_location', str(script_location))
command.stamp(conf_obj, 'head')
# Populate permissions table with owner.
owner_nick = botconfig['auth']['owner']
if not session.query(Permissions).filter(Permissions.nick == owner_nick).count():
session.add(Permissions(nick=owner_nick, role='owner')) | python | def setup_db(session, botconfig, confdir):
"""Sets up the database."""
Base.metadata.create_all(session.connection())
# If we're creating a fresh db, we don't need to worry about migrations.
if not session.get_bind().has_table('alembic_version'):
conf_obj = config.Config()
conf_obj.set_main_option('bot_config_path', confdir)
with resources.path('cslbot', botconfig['alembic']['script_location']) as script_location:
conf_obj.set_main_option('script_location', str(script_location))
command.stamp(conf_obj, 'head')
# Populate permissions table with owner.
owner_nick = botconfig['auth']['owner']
if not session.query(Permissions).filter(Permissions.nick == owner_nick).count():
session.add(Permissions(nick=owner_nick, role='owner')) | [
"def",
"setup_db",
"(",
"session",
",",
"botconfig",
",",
"confdir",
")",
":",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"session",
".",
"connection",
"(",
")",
")",
"# If we're creating a fresh db, we don't need to worry about migrations.",
"if",
"not",
"session",
".",
"get_bind",
"(",
")",
".",
"has_table",
"(",
"'alembic_version'",
")",
":",
"conf_obj",
"=",
"config",
".",
"Config",
"(",
")",
"conf_obj",
".",
"set_main_option",
"(",
"'bot_config_path'",
",",
"confdir",
")",
"with",
"resources",
".",
"path",
"(",
"'cslbot'",
",",
"botconfig",
"[",
"'alembic'",
"]",
"[",
"'script_location'",
"]",
")",
"as",
"script_location",
":",
"conf_obj",
".",
"set_main_option",
"(",
"'script_location'",
",",
"str",
"(",
"script_location",
")",
")",
"command",
".",
"stamp",
"(",
"conf_obj",
",",
"'head'",
")",
"# Populate permissions table with owner.",
"owner_nick",
"=",
"botconfig",
"[",
"'auth'",
"]",
"[",
"'owner'",
"]",
"if",
"not",
"session",
".",
"query",
"(",
"Permissions",
")",
".",
"filter",
"(",
"Permissions",
".",
"nick",
"==",
"owner_nick",
")",
".",
"count",
"(",
")",
":",
"session",
".",
"add",
"(",
"Permissions",
"(",
"nick",
"=",
"owner_nick",
",",
"role",
"=",
"'owner'",
")",
")"
]
| Sets up the database. | [
"Sets",
"up",
"the",
"database",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/orm.py#L36-L50 | train |
rchatterjee/pwmodels | src/pwmodel/readpw.py | Passwords.sumvalues | def sumvalues(self, q=0):
"""Sum of top q passowrd frequencies
"""
if q == 0:
return self._totalf
else:
return -np.partition(-self._freq_list, q)[:q].sum() | python | def sumvalues(self, q=0):
"""Sum of top q passowrd frequencies
"""
if q == 0:
return self._totalf
else:
return -np.partition(-self._freq_list, q)[:q].sum() | [
"def",
"sumvalues",
"(",
"self",
",",
"q",
"=",
"0",
")",
":",
"if",
"q",
"==",
"0",
":",
"return",
"self",
".",
"_totalf",
"else",
":",
"return",
"-",
"np",
".",
"partition",
"(",
"-",
"self",
".",
"_freq_list",
",",
"q",
")",
"[",
":",
"q",
"]",
".",
"sum",
"(",
")"
]
| Sum of top q passowrd frequencies | [
"Sum",
"of",
"top",
"q",
"passowrd",
"frequencies"
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/readpw.py#L255-L261 | train |
rchatterjee/pwmodels | src/pwmodel/readpw.py | Passwords.iterpws | def iterpws(self, n):
"""
Returns passwords in order of their frequencies.
@n: The numebr of passwords to return
Return: pwid, password, frequency
Every password is assigned an uniq id, for efficient access.
"""
for _id in np.argsort(self._freq_list)[::-1][:n]:
pw = self._T.restore_key(_id)
if self._min_pass_len <= len(pw) <= self._max_pass_len:
yield _id, pw, self._freq_list[_id] | python | def iterpws(self, n):
"""
Returns passwords in order of their frequencies.
@n: The numebr of passwords to return
Return: pwid, password, frequency
Every password is assigned an uniq id, for efficient access.
"""
for _id in np.argsort(self._freq_list)[::-1][:n]:
pw = self._T.restore_key(_id)
if self._min_pass_len <= len(pw) <= self._max_pass_len:
yield _id, pw, self._freq_list[_id] | [
"def",
"iterpws",
"(",
"self",
",",
"n",
")",
":",
"for",
"_id",
"in",
"np",
".",
"argsort",
"(",
"self",
".",
"_freq_list",
")",
"[",
":",
":",
"-",
"1",
"]",
"[",
":",
"n",
"]",
":",
"pw",
"=",
"self",
".",
"_T",
".",
"restore_key",
"(",
"_id",
")",
"if",
"self",
".",
"_min_pass_len",
"<=",
"len",
"(",
"pw",
")",
"<=",
"self",
".",
"_max_pass_len",
":",
"yield",
"_id",
",",
"pw",
",",
"self",
".",
"_freq_list",
"[",
"_id",
"]"
]
| Returns passwords in order of their frequencies.
@n: The numebr of passwords to return
Return: pwid, password, frequency
Every password is assigned an uniq id, for efficient access. | [
"Returns",
"passwords",
"in",
"order",
"of",
"their",
"frequencies",
"."
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/readpw.py#L263-L273 | train |
tjcsl/cslbot | cslbot/commands/cidr.py | cmd | def cmd(send, msg, args):
"""Gets a CIDR range.
Syntax: {command} <range>
"""
if not msg:
send("Need a CIDR range.")
return
try:
ipn = ip_network(msg)
except ValueError:
send("Not a valid CIDR range.")
return
send("%s - %s" % (ipn[0], ipn[-1])) | python | def cmd(send, msg, args):
"""Gets a CIDR range.
Syntax: {command} <range>
"""
if not msg:
send("Need a CIDR range.")
return
try:
ipn = ip_network(msg)
except ValueError:
send("Not a valid CIDR range.")
return
send("%s - %s" % (ipn[0], ipn[-1])) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Need a CIDR range.\"",
")",
"return",
"try",
":",
"ipn",
"=",
"ip_network",
"(",
"msg",
")",
"except",
"ValueError",
":",
"send",
"(",
"\"Not a valid CIDR range.\"",
")",
"return",
"send",
"(",
"\"%s - %s\"",
"%",
"(",
"ipn",
"[",
"0",
"]",
",",
"ipn",
"[",
"-",
"1",
"]",
")",
")"
]
| Gets a CIDR range.
Syntax: {command} <range> | [
"Gets",
"a",
"CIDR",
"range",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/cidr.py#L24-L38 | train |
nezhar/updatable | updatable/__init__.py | get_environment_requirements_list | def get_environment_requirements_list():
"""
Take the requirements list from the current running environment
:return: string
"""
requirement_list = []
requirements = check_output([sys.executable, '-m', 'pip', 'freeze'])
for requirement in requirements.split():
requirement_list.append(requirement.decode("utf-8"))
return requirement_list | python | def get_environment_requirements_list():
"""
Take the requirements list from the current running environment
:return: string
"""
requirement_list = []
requirements = check_output([sys.executable, '-m', 'pip', 'freeze'])
for requirement in requirements.split():
requirement_list.append(requirement.decode("utf-8"))
return requirement_list | [
"def",
"get_environment_requirements_list",
"(",
")",
":",
"requirement_list",
"=",
"[",
"]",
"requirements",
"=",
"check_output",
"(",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'freeze'",
"]",
")",
"for",
"requirement",
"in",
"requirements",
".",
"split",
"(",
")",
":",
"requirement_list",
".",
"append",
"(",
"requirement",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"return",
"requirement_list"
]
| Take the requirements list from the current running environment
:return: string | [
"Take",
"the",
"requirements",
"list",
"from",
"the",
"current",
"running",
"environment"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L24-L36 | train |
nezhar/updatable | updatable/__init__.py | parse_requirements_list | def parse_requirements_list(requirements_list):
"""
Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string
"""
req_list = []
for requirement in requirements_list:
requirement_no_comments = requirement.split('#')[0].strip()
# if matching requirement line (Thing==1.2.3), update dict, continue
req_match = re.match(
r'\s*(?P<package>[^\s\[\]]+)(?P<extras>\[\S+\])?==(?P<version>\S+)',
requirement_no_comments
)
if req_match:
req_list.append({
'package': req_match.group('package'),
'version': req_match.group('version'),
})
return req_list | python | def parse_requirements_list(requirements_list):
"""
Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string
"""
req_list = []
for requirement in requirements_list:
requirement_no_comments = requirement.split('#')[0].strip()
# if matching requirement line (Thing==1.2.3), update dict, continue
req_match = re.match(
r'\s*(?P<package>[^\s\[\]]+)(?P<extras>\[\S+\])?==(?P<version>\S+)',
requirement_no_comments
)
if req_match:
req_list.append({
'package': req_match.group('package'),
'version': req_match.group('version'),
})
return req_list | [
"def",
"parse_requirements_list",
"(",
"requirements_list",
")",
":",
"req_list",
"=",
"[",
"]",
"for",
"requirement",
"in",
"requirements_list",
":",
"requirement_no_comments",
"=",
"requirement",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"# if matching requirement line (Thing==1.2.3), update dict, continue",
"req_match",
"=",
"re",
".",
"match",
"(",
"r'\\s*(?P<package>[^\\s\\[\\]]+)(?P<extras>\\[\\S+\\])?==(?P<version>\\S+)'",
",",
"requirement_no_comments",
")",
"if",
"req_match",
":",
"req_list",
".",
"append",
"(",
"{",
"'package'",
":",
"req_match",
".",
"group",
"(",
"'package'",
")",
",",
"'version'",
":",
"req_match",
".",
"group",
"(",
"'version'",
")",
",",
"}",
")",
"return",
"req_list"
]
| Take a list and return a list of dicts with {package, versions) based on the requirements specs
:param requirements_list: string
:return: string | [
"Take",
"a",
"list",
"and",
"return",
"a",
"list",
"of",
"dicts",
"with",
"{",
"package",
"versions",
")",
"based",
"on",
"the",
"requirements",
"specs"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L39-L62 | train |
nezhar/updatable | updatable/__init__.py | get_pypi_package_data | def get_pypi_package_data(package_name, version=None):
"""
Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict
"""
pypi_url = 'https://pypi.org/pypi'
if version:
package_url = '%s/%s/%s/json' % (pypi_url, package_name, version, )
else:
package_url = '%s/%s/json' % (pypi_url, package_name, )
try:
response = requests.get(package_url)
except requests.ConnectionError:
raise RuntimeError('Connection error!')
# Package not available on pypi
if not response.ok:
return None
return response.json() | python | def get_pypi_package_data(package_name, version=None):
"""
Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict
"""
pypi_url = 'https://pypi.org/pypi'
if version:
package_url = '%s/%s/%s/json' % (pypi_url, package_name, version, )
else:
package_url = '%s/%s/json' % (pypi_url, package_name, )
try:
response = requests.get(package_url)
except requests.ConnectionError:
raise RuntimeError('Connection error!')
# Package not available on pypi
if not response.ok:
return None
return response.json() | [
"def",
"get_pypi_package_data",
"(",
"package_name",
",",
"version",
"=",
"None",
")",
":",
"pypi_url",
"=",
"'https://pypi.org/pypi'",
"if",
"version",
":",
"package_url",
"=",
"'%s/%s/%s/json'",
"%",
"(",
"pypi_url",
",",
"package_name",
",",
"version",
",",
")",
"else",
":",
"package_url",
"=",
"'%s/%s/json'",
"%",
"(",
"pypi_url",
",",
"package_name",
",",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"package_url",
")",
"except",
"requests",
".",
"ConnectionError",
":",
"raise",
"RuntimeError",
"(",
"'Connection error!'",
")",
"# Package not available on pypi",
"if",
"not",
"response",
".",
"ok",
":",
"return",
"None",
"return",
"response",
".",
"json",
"(",
")"
]
| Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict | [
"Get",
"package",
"data",
"from",
"pypi",
"by",
"the",
"package",
"name"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L65-L91 | train |
nezhar/updatable | updatable/__init__.py | get_package_update_list | def get_package_update_list(package_name, version):
"""
Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict
"""
package_version = semantic_version.Version.coerce(version)
# Get package and version data from pypi
package_data = get_pypi_package_data(package_name)
version_data = get_pypi_package_data(package_name, version)
# Current release specific information
current_release = ''
current_release_license = ''
# Latest release specific information
latest_release = ''
latest_release_license = ''
# Information about packages
major_updates = []
minor_updates = []
patch_updates = []
pre_releases = []
non_semantic_versions = []
if package_data:
latest_release = package_data['info']['version']
latest_release_license = package_data['info']['license'] if package_data['info']['license'] else ''
for release, info in package_data['releases'].items():
parsed_release = parse(release)
upload_time = None
if info:
upload_time = datetime.strptime(info[0]['upload_time'], "%Y-%m-%dT%H:%M:%S")
try:
# Get semantic version of package
release_version = semantic_version.Version.coerce(release)
if not parsed_release.is_prerelease:
# Place package in the appropriate semantic visioning list
if release_version in semantic_version.Spec(">=%s" % package_version.next_major()):
major_updates.append({
'version': release,
'upload_time': upload_time,
})
elif release_version in semantic_version.Spec(">=%s,<%s" % (package_version.next_minor(), package_version.next_major())):
minor_updates.append({
'version': release,
'upload_time': upload_time,
})
elif release_version in semantic_version.Spec(">=%s,<%s" % (package_version.next_patch(), package_version.next_minor())):
patch_updates.append({
'version': release,
'upload_time': upload_time,
})
else:
pre_releases.append({
'version': release,
'upload_time': upload_time
})
except ValueError:
# Keep track of versions that could not be recognized as semantic
non_semantic_versions.append({'version': release, 'upload_time': upload_time})
if version_data:
current_release = version_data['info']['version']
current_release_license = version_data['info']['license'] if version_data['info']['license'] else ''
# Get number of newer releases available for the given package
newer_releases = len(major_updates + minor_updates + patch_updates)
return {
'current_release': current_release,
'current_release_license': current_release_license,
'latest_release': latest_release,
'latest_release_license': latest_release_license,
'newer_releases': newer_releases,
'pre_releases': len(pre_releases),
'major_updates': sorted(major_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'minor_updates': sorted(minor_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'patch_updates': sorted(patch_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'pre_release_updates': sorted(pre_releases, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'non_semantic_versions': non_semantic_versions,
} | python | def get_package_update_list(package_name, version):
"""
Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict
"""
package_version = semantic_version.Version.coerce(version)
# Get package and version data from pypi
package_data = get_pypi_package_data(package_name)
version_data = get_pypi_package_data(package_name, version)
# Current release specific information
current_release = ''
current_release_license = ''
# Latest release specific information
latest_release = ''
latest_release_license = ''
# Information about packages
major_updates = []
minor_updates = []
patch_updates = []
pre_releases = []
non_semantic_versions = []
if package_data:
latest_release = package_data['info']['version']
latest_release_license = package_data['info']['license'] if package_data['info']['license'] else ''
for release, info in package_data['releases'].items():
parsed_release = parse(release)
upload_time = None
if info:
upload_time = datetime.strptime(info[0]['upload_time'], "%Y-%m-%dT%H:%M:%S")
try:
# Get semantic version of package
release_version = semantic_version.Version.coerce(release)
if not parsed_release.is_prerelease:
# Place package in the appropriate semantic visioning list
if release_version in semantic_version.Spec(">=%s" % package_version.next_major()):
major_updates.append({
'version': release,
'upload_time': upload_time,
})
elif release_version in semantic_version.Spec(">=%s,<%s" % (package_version.next_minor(), package_version.next_major())):
minor_updates.append({
'version': release,
'upload_time': upload_time,
})
elif release_version in semantic_version.Spec(">=%s,<%s" % (package_version.next_patch(), package_version.next_minor())):
patch_updates.append({
'version': release,
'upload_time': upload_time,
})
else:
pre_releases.append({
'version': release,
'upload_time': upload_time
})
except ValueError:
# Keep track of versions that could not be recognized as semantic
non_semantic_versions.append({'version': release, 'upload_time': upload_time})
if version_data:
current_release = version_data['info']['version']
current_release_license = version_data['info']['license'] if version_data['info']['license'] else ''
# Get number of newer releases available for the given package
newer_releases = len(major_updates + minor_updates + patch_updates)
return {
'current_release': current_release,
'current_release_license': current_release_license,
'latest_release': latest_release,
'latest_release_license': latest_release_license,
'newer_releases': newer_releases,
'pre_releases': len(pre_releases),
'major_updates': sorted(major_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'minor_updates': sorted(minor_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'patch_updates': sorted(patch_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'pre_release_updates': sorted(pre_releases, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
'non_semantic_versions': non_semantic_versions,
} | [
"def",
"get_package_update_list",
"(",
"package_name",
",",
"version",
")",
":",
"package_version",
"=",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"version",
")",
"# Get package and version data from pypi",
"package_data",
"=",
"get_pypi_package_data",
"(",
"package_name",
")",
"version_data",
"=",
"get_pypi_package_data",
"(",
"package_name",
",",
"version",
")",
"# Current release specific information",
"current_release",
"=",
"''",
"current_release_license",
"=",
"''",
"# Latest release specific information",
"latest_release",
"=",
"''",
"latest_release_license",
"=",
"''",
"# Information about packages",
"major_updates",
"=",
"[",
"]",
"minor_updates",
"=",
"[",
"]",
"patch_updates",
"=",
"[",
"]",
"pre_releases",
"=",
"[",
"]",
"non_semantic_versions",
"=",
"[",
"]",
"if",
"package_data",
":",
"latest_release",
"=",
"package_data",
"[",
"'info'",
"]",
"[",
"'version'",
"]",
"latest_release_license",
"=",
"package_data",
"[",
"'info'",
"]",
"[",
"'license'",
"]",
"if",
"package_data",
"[",
"'info'",
"]",
"[",
"'license'",
"]",
"else",
"''",
"for",
"release",
",",
"info",
"in",
"package_data",
"[",
"'releases'",
"]",
".",
"items",
"(",
")",
":",
"parsed_release",
"=",
"parse",
"(",
"release",
")",
"upload_time",
"=",
"None",
"if",
"info",
":",
"upload_time",
"=",
"datetime",
".",
"strptime",
"(",
"info",
"[",
"0",
"]",
"[",
"'upload_time'",
"]",
",",
"\"%Y-%m-%dT%H:%M:%S\"",
")",
"try",
":",
"# Get semantic version of package",
"release_version",
"=",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"release",
")",
"if",
"not",
"parsed_release",
".",
"is_prerelease",
":",
"# Place package in the appropriate semantic visioning list",
"if",
"release_version",
"in",
"semantic_version",
".",
"Spec",
"(",
"\">=%s\"",
"%",
"package_version",
".",
"next_major",
"(",
")",
")",
":",
"major_updates",
".",
"append",
"(",
"{",
"'version'",
":",
"release",
",",
"'upload_time'",
":",
"upload_time",
",",
"}",
")",
"elif",
"release_version",
"in",
"semantic_version",
".",
"Spec",
"(",
"\">=%s,<%s\"",
"%",
"(",
"package_version",
".",
"next_minor",
"(",
")",
",",
"package_version",
".",
"next_major",
"(",
")",
")",
")",
":",
"minor_updates",
".",
"append",
"(",
"{",
"'version'",
":",
"release",
",",
"'upload_time'",
":",
"upload_time",
",",
"}",
")",
"elif",
"release_version",
"in",
"semantic_version",
".",
"Spec",
"(",
"\">=%s,<%s\"",
"%",
"(",
"package_version",
".",
"next_patch",
"(",
")",
",",
"package_version",
".",
"next_minor",
"(",
")",
")",
")",
":",
"patch_updates",
".",
"append",
"(",
"{",
"'version'",
":",
"release",
",",
"'upload_time'",
":",
"upload_time",
",",
"}",
")",
"else",
":",
"pre_releases",
".",
"append",
"(",
"{",
"'version'",
":",
"release",
",",
"'upload_time'",
":",
"upload_time",
"}",
")",
"except",
"ValueError",
":",
"# Keep track of versions that could not be recognized as semantic",
"non_semantic_versions",
".",
"append",
"(",
"{",
"'version'",
":",
"release",
",",
"'upload_time'",
":",
"upload_time",
"}",
")",
"if",
"version_data",
":",
"current_release",
"=",
"version_data",
"[",
"'info'",
"]",
"[",
"'version'",
"]",
"current_release_license",
"=",
"version_data",
"[",
"'info'",
"]",
"[",
"'license'",
"]",
"if",
"version_data",
"[",
"'info'",
"]",
"[",
"'license'",
"]",
"else",
"''",
"# Get number of newer releases available for the given package",
"newer_releases",
"=",
"len",
"(",
"major_updates",
"+",
"minor_updates",
"+",
"patch_updates",
")",
"return",
"{",
"'current_release'",
":",
"current_release",
",",
"'current_release_license'",
":",
"current_release_license",
",",
"'latest_release'",
":",
"latest_release",
",",
"'latest_release_license'",
":",
"latest_release_license",
",",
"'newer_releases'",
":",
"newer_releases",
",",
"'pre_releases'",
":",
"len",
"(",
"pre_releases",
")",
",",
"'major_updates'",
":",
"sorted",
"(",
"major_updates",
",",
"key",
"=",
"lambda",
"x",
":",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"x",
"[",
"'version'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
",",
"'minor_updates'",
":",
"sorted",
"(",
"minor_updates",
",",
"key",
"=",
"lambda",
"x",
":",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"x",
"[",
"'version'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
",",
"'patch_updates'",
":",
"sorted",
"(",
"patch_updates",
",",
"key",
"=",
"lambda",
"x",
":",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"x",
"[",
"'version'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
",",
"'pre_release_updates'",
":",
"sorted",
"(",
"pre_releases",
",",
"key",
"=",
"lambda",
"x",
":",
"semantic_version",
".",
"Version",
".",
"coerce",
"(",
"x",
"[",
"'version'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
",",
"'non_semantic_versions'",
":",
"non_semantic_versions",
",",
"}"
]
| Return update information of a package from a given version
:param package_name: string
:param version: string
:return: dict | [
"Return",
"update",
"information",
"of",
"a",
"package",
"from",
"a",
"given",
"version"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L94-L183 | train |
nezhar/updatable | updatable/__init__.py | __list_package_updates | def __list_package_updates(package_name, version):
"""
Function used to list all package updates in console
:param package_name: string
:param version: string
"""
updates = get_package_update_list(package_name, version)
if updates['newer_releases'] or updates['pre_releases']:
print('%s (%s)' % (package_name, version))
__list_updates('Major releases', updates['major_updates'])
__list_updates('Minor releases', updates['minor_updates'])
__list_updates('Patch releases', updates['patch_updates'])
__list_updates('Pre releases', updates['pre_release_updates'])
__list_updates('Unknown releases', updates['non_semantic_versions'])
print("___") | python | def __list_package_updates(package_name, version):
"""
Function used to list all package updates in console
:param package_name: string
:param version: string
"""
updates = get_package_update_list(package_name, version)
if updates['newer_releases'] or updates['pre_releases']:
print('%s (%s)' % (package_name, version))
__list_updates('Major releases', updates['major_updates'])
__list_updates('Minor releases', updates['minor_updates'])
__list_updates('Patch releases', updates['patch_updates'])
__list_updates('Pre releases', updates['pre_release_updates'])
__list_updates('Unknown releases', updates['non_semantic_versions'])
print("___") | [
"def",
"__list_package_updates",
"(",
"package_name",
",",
"version",
")",
":",
"updates",
"=",
"get_package_update_list",
"(",
"package_name",
",",
"version",
")",
"if",
"updates",
"[",
"'newer_releases'",
"]",
"or",
"updates",
"[",
"'pre_releases'",
"]",
":",
"print",
"(",
"'%s (%s)'",
"%",
"(",
"package_name",
",",
"version",
")",
")",
"__list_updates",
"(",
"'Major releases'",
",",
"updates",
"[",
"'major_updates'",
"]",
")",
"__list_updates",
"(",
"'Minor releases'",
",",
"updates",
"[",
"'minor_updates'",
"]",
")",
"__list_updates",
"(",
"'Patch releases'",
",",
"updates",
"[",
"'patch_updates'",
"]",
")",
"__list_updates",
"(",
"'Pre releases'",
",",
"updates",
"[",
"'pre_release_updates'",
"]",
")",
"__list_updates",
"(",
"'Unknown releases'",
",",
"updates",
"[",
"'non_semantic_versions'",
"]",
")",
"print",
"(",
"\"___\"",
")"
]
| Function used to list all package updates in console
:param package_name: string
:param version: string | [
"Function",
"used",
"to",
"list",
"all",
"package",
"updates",
"in",
"console"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L186-L203 | train |
nezhar/updatable | updatable/__init__.py | __list_updates | def __list_updates(update_type, update_list):
"""
Function used to list package updates by update type in console
:param update_type: string
:param update_list: list
"""
if len(update_list):
print(" %s:" % update_type)
for update_item in update_list:
print(" -- %(version)s on %(upload_time)s" % update_item) | python | def __list_updates(update_type, update_list):
"""
Function used to list package updates by update type in console
:param update_type: string
:param update_list: list
"""
if len(update_list):
print(" %s:" % update_type)
for update_item in update_list:
print(" -- %(version)s on %(upload_time)s" % update_item) | [
"def",
"__list_updates",
"(",
"update_type",
",",
"update_list",
")",
":",
"if",
"len",
"(",
"update_list",
")",
":",
"print",
"(",
"\" %s:\"",
"%",
"update_type",
")",
"for",
"update_item",
"in",
"update_list",
":",
"print",
"(",
"\" -- %(version)s on %(upload_time)s\"",
"%",
"update_item",
")"
]
| Function used to list package updates by update type in console
:param update_type: string
:param update_list: list | [
"Function",
"used",
"to",
"list",
"package",
"updates",
"by",
"update",
"type",
"in",
"console"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L206-L216 | train |
nezhar/updatable | updatable/__init__.py | __updatable | def __updatable():
"""
Function used to output packages update information in the console
"""
# Add argument for console
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')
args = parser.parse_args()
# Get list of packages
if args.file:
packages = parse_requirements_list(args.file)
else:
packages = get_parsed_environment_package_list()
# Output updates
for package in packages:
__list_package_updates(package['package'], package['version']) | python | def __updatable():
"""
Function used to output packages update information in the console
"""
# Add argument for console
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', type=argparse.FileType(), default=None, help='Requirements file')
args = parser.parse_args()
# Get list of packages
if args.file:
packages = parse_requirements_list(args.file)
else:
packages = get_parsed_environment_package_list()
# Output updates
for package in packages:
__list_package_updates(package['package'], package['version']) | [
"def",
"__updatable",
"(",
")",
":",
"# Add argument for console",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
")",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Requirements file'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# Get list of packages",
"if",
"args",
".",
"file",
":",
"packages",
"=",
"parse_requirements_list",
"(",
"args",
".",
"file",
")",
"else",
":",
"packages",
"=",
"get_parsed_environment_package_list",
"(",
")",
"# Output updates",
"for",
"package",
"in",
"packages",
":",
"__list_package_updates",
"(",
"package",
"[",
"'package'",
"]",
",",
"package",
"[",
"'version'",
"]",
")"
]
| Function used to output packages update information in the console | [
"Function",
"used",
"to",
"output",
"packages",
"update",
"information",
"in",
"the",
"console"
]
| 654c70a40d9cabcfdd762acf82b49f66057438af | https://github.com/nezhar/updatable/blob/654c70a40d9cabcfdd762acf82b49f66057438af/updatable/__init__.py#L219-L236 | train |
tjcsl/cslbot | cslbot/hooks/url.py | handle | def handle(send, msg, args):
"""Get titles for urls.
Generate a short url. Get the page title.
"""
worker = args["handler"].workers
result = worker.run_pool(get_urls, [msg])
try:
urls = result.get(5)
except multiprocessing.TimeoutError:
worker.restart_pool()
send("Url regex timed out.", target=args["config"]["core"]["ctrlchan"])
return
for url in urls:
# Prevent botloops
if (args["db"].query(Urls).filter(Urls.url == url, Urls.time > datetime.now() - timedelta(seconds=10)).count() > 1):
return
if url.startswith("https://twitter.com"):
tid = url.split("/")[-1]
twitter_api = get_api(args["config"])
status = twitter_api.GetStatus(tid)
text = status.text.replace("\n", " / ")
send("** {} (@{}) on Twitter: {}".format(status.user.name, status.user.screen_name, text))
return
imgkey = args["config"]["api"]["googleapikey"]
title = urlutils.get_title(url, imgkey)
shortkey = args["config"]["api"]["bitlykey"]
short = urlutils.get_short(url, shortkey)
last = args["db"].query(Urls).filter(Urls.url == url).order_by(Urls.time.desc()).first()
if args["config"]["feature"].getboolean("linkread"):
if last is not None:
lasttime = last.time.strftime("%H:%M:%S on %Y-%m-%d")
send("Url %s previously posted at %s by %s -- %s" % (short, lasttime, last.nick, title))
else:
send("** %s - %s" % (title, short))
args["db"].add(Urls(url=url, title=title, nick=args["nick"], time=datetime.now())) | python | def handle(send, msg, args):
"""Get titles for urls.
Generate a short url. Get the page title.
"""
worker = args["handler"].workers
result = worker.run_pool(get_urls, [msg])
try:
urls = result.get(5)
except multiprocessing.TimeoutError:
worker.restart_pool()
send("Url regex timed out.", target=args["config"]["core"]["ctrlchan"])
return
for url in urls:
# Prevent botloops
if (args["db"].query(Urls).filter(Urls.url == url, Urls.time > datetime.now() - timedelta(seconds=10)).count() > 1):
return
if url.startswith("https://twitter.com"):
tid = url.split("/")[-1]
twitter_api = get_api(args["config"])
status = twitter_api.GetStatus(tid)
text = status.text.replace("\n", " / ")
send("** {} (@{}) on Twitter: {}".format(status.user.name, status.user.screen_name, text))
return
imgkey = args["config"]["api"]["googleapikey"]
title = urlutils.get_title(url, imgkey)
shortkey = args["config"]["api"]["bitlykey"]
short = urlutils.get_short(url, shortkey)
last = args["db"].query(Urls).filter(Urls.url == url).order_by(Urls.time.desc()).first()
if args["config"]["feature"].getboolean("linkread"):
if last is not None:
lasttime = last.time.strftime("%H:%M:%S on %Y-%m-%d")
send("Url %s previously posted at %s by %s -- %s" % (short, lasttime, last.nick, title))
else:
send("** %s - %s" % (title, short))
args["db"].add(Urls(url=url, title=title, nick=args["nick"], time=datetime.now())) | [
"def",
"handle",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"worker",
"=",
"args",
"[",
"\"handler\"",
"]",
".",
"workers",
"result",
"=",
"worker",
".",
"run_pool",
"(",
"get_urls",
",",
"[",
"msg",
"]",
")",
"try",
":",
"urls",
"=",
"result",
".",
"get",
"(",
"5",
")",
"except",
"multiprocessing",
".",
"TimeoutError",
":",
"worker",
".",
"restart_pool",
"(",
")",
"send",
"(",
"\"Url regex timed out.\"",
",",
"target",
"=",
"args",
"[",
"\"config\"",
"]",
"[",
"\"core\"",
"]",
"[",
"\"ctrlchan\"",
"]",
")",
"return",
"for",
"url",
"in",
"urls",
":",
"# Prevent botloops",
"if",
"(",
"args",
"[",
"\"db\"",
"]",
".",
"query",
"(",
"Urls",
")",
".",
"filter",
"(",
"Urls",
".",
"url",
"==",
"url",
",",
"Urls",
".",
"time",
">",
"datetime",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
")",
".",
"count",
"(",
")",
">",
"1",
")",
":",
"return",
"if",
"url",
".",
"startswith",
"(",
"\"https://twitter.com\"",
")",
":",
"tid",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"twitter_api",
"=",
"get_api",
"(",
"args",
"[",
"\"config\"",
"]",
")",
"status",
"=",
"twitter_api",
".",
"GetStatus",
"(",
"tid",
")",
"text",
"=",
"status",
".",
"text",
".",
"replace",
"(",
"\"\\n\"",
",",
"\" / \"",
")",
"send",
"(",
"\"** {} (@{}) on Twitter: {}\"",
".",
"format",
"(",
"status",
".",
"user",
".",
"name",
",",
"status",
".",
"user",
".",
"screen_name",
",",
"text",
")",
")",
"return",
"imgkey",
"=",
"args",
"[",
"\"config\"",
"]",
"[",
"\"api\"",
"]",
"[",
"\"googleapikey\"",
"]",
"title",
"=",
"urlutils",
".",
"get_title",
"(",
"url",
",",
"imgkey",
")",
"shortkey",
"=",
"args",
"[",
"\"config\"",
"]",
"[",
"\"api\"",
"]",
"[",
"\"bitlykey\"",
"]",
"short",
"=",
"urlutils",
".",
"get_short",
"(",
"url",
",",
"shortkey",
")",
"last",
"=",
"args",
"[",
"\"db\"",
"]",
".",
"query",
"(",
"Urls",
")",
".",
"filter",
"(",
"Urls",
".",
"url",
"==",
"url",
")",
".",
"order_by",
"(",
"Urls",
".",
"time",
".",
"desc",
"(",
")",
")",
".",
"first",
"(",
")",
"if",
"args",
"[",
"\"config\"",
"]",
"[",
"\"feature\"",
"]",
".",
"getboolean",
"(",
"\"linkread\"",
")",
":",
"if",
"last",
"is",
"not",
"None",
":",
"lasttime",
"=",
"last",
".",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S on %Y-%m-%d\"",
")",
"send",
"(",
"\"Url %s previously posted at %s by %s -- %s\"",
"%",
"(",
"short",
",",
"lasttime",
",",
"last",
".",
"nick",
",",
"title",
")",
")",
"else",
":",
"send",
"(",
"\"** %s - %s\"",
"%",
"(",
"title",
",",
"short",
")",
")",
"args",
"[",
"\"db\"",
"]",
".",
"add",
"(",
"Urls",
"(",
"url",
"=",
"url",
",",
"title",
"=",
"title",
",",
"nick",
"=",
"args",
"[",
"\"nick\"",
"]",
",",
"time",
"=",
"datetime",
".",
"now",
"(",
")",
")",
")"
]
| Get titles for urls.
Generate a short url. Get the page title. | [
"Get",
"titles",
"for",
"urls",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/url.py#L37-L77 | train |
The-Politico/politico-civic-election-night | electionnight/models/page_type.py | PageType.page_location_template | def page_location_template(self):
"""
Returns the published URL template for a page type.
"""
cycle = self.election_day.cycle.name
model_class = self.model_type.model_class()
if model_class == ElectionDay:
return "/{}/".format(cycle)
if model_class == Office:
# President
if self.jurisdiction:
if self.division_level.name == DivisionLevel.STATE:
return "/{}/president/{{state}}".format(cycle)
else:
return "/{}/president/".format(cycle)
# Governor
else:
return "/{}/{{state}}/governor/".format(cycle)
elif model_class == Body:
# Senate
if self.body.slug == "senate":
if self.jurisdiction:
if self.division_level.name == DivisionLevel.STATE:
return "/{}/senate/{{state}}/".format(cycle)
else:
return "/{}/senate/".format(cycle)
else:
return "/{}/{{state}}/senate/".format(cycle)
# House
else:
if self.jurisdiction:
if self.division_level.name == DivisionLevel.STATE:
return "/{}/house/{{state}}/".format(cycle)
else:
return "/{}/house/".format(cycle)
else:
return "/{}/{{state}}/house/".format(cycle)
elif model_class == Division:
return "/{}/{{state}}/".format(cycle)
else:
return "ORPHAN TYPE" | python | def page_location_template(self):
"""
Returns the published URL template for a page type.
"""
cycle = self.election_day.cycle.name
model_class = self.model_type.model_class()
if model_class == ElectionDay:
return "/{}/".format(cycle)
if model_class == Office:
# President
if self.jurisdiction:
if self.division_level.name == DivisionLevel.STATE:
return "/{}/president/{{state}}".format(cycle)
else:
return "/{}/president/".format(cycle)
# Governor
else:
return "/{}/{{state}}/governor/".format(cycle)
elif model_class == Body:
# Senate
if self.body.slug == "senate":
if self.jurisdiction:
if self.division_level.name == DivisionLevel.STATE:
return "/{}/senate/{{state}}/".format(cycle)
else:
return "/{}/senate/".format(cycle)
else:
return "/{}/{{state}}/senate/".format(cycle)
# House
else:
if self.jurisdiction:
if self.division_level.name == DivisionLevel.STATE:
return "/{}/house/{{state}}/".format(cycle)
else:
return "/{}/house/".format(cycle)
else:
return "/{}/{{state}}/house/".format(cycle)
elif model_class == Division:
return "/{}/{{state}}/".format(cycle)
else:
return "ORPHAN TYPE" | [
"def",
"page_location_template",
"(",
"self",
")",
":",
"cycle",
"=",
"self",
".",
"election_day",
".",
"cycle",
".",
"name",
"model_class",
"=",
"self",
".",
"model_type",
".",
"model_class",
"(",
")",
"if",
"model_class",
"==",
"ElectionDay",
":",
"return",
"\"/{}/\"",
".",
"format",
"(",
"cycle",
")",
"if",
"model_class",
"==",
"Office",
":",
"# President",
"if",
"self",
".",
"jurisdiction",
":",
"if",
"self",
".",
"division_level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"return",
"\"/{}/president/{{state}}\"",
".",
"format",
"(",
"cycle",
")",
"else",
":",
"return",
"\"/{}/president/\"",
".",
"format",
"(",
"cycle",
")",
"# Governor",
"else",
":",
"return",
"\"/{}/{{state}}/governor/\"",
".",
"format",
"(",
"cycle",
")",
"elif",
"model_class",
"==",
"Body",
":",
"# Senate",
"if",
"self",
".",
"body",
".",
"slug",
"==",
"\"senate\"",
":",
"if",
"self",
".",
"jurisdiction",
":",
"if",
"self",
".",
"division_level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"return",
"\"/{}/senate/{{state}}/\"",
".",
"format",
"(",
"cycle",
")",
"else",
":",
"return",
"\"/{}/senate/\"",
".",
"format",
"(",
"cycle",
")",
"else",
":",
"return",
"\"/{}/{{state}}/senate/\"",
".",
"format",
"(",
"cycle",
")",
"# House",
"else",
":",
"if",
"self",
".",
"jurisdiction",
":",
"if",
"self",
".",
"division_level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"return",
"\"/{}/house/{{state}}/\"",
".",
"format",
"(",
"cycle",
")",
"else",
":",
"return",
"\"/{}/house/\"",
".",
"format",
"(",
"cycle",
")",
"else",
":",
"return",
"\"/{}/{{state}}/house/\"",
".",
"format",
"(",
"cycle",
")",
"elif",
"model_class",
"==",
"Division",
":",
"return",
"\"/{}/{{state}}/\"",
".",
"format",
"(",
"cycle",
")",
"else",
":",
"return",
"\"ORPHAN TYPE\""
]
| Returns the published URL template for a page type. | [
"Returns",
"the",
"published",
"URL",
"template",
"for",
"a",
"page",
"type",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/models/page_type.py#L69-L109 | train |
tjcsl/cslbot | cslbot/commands/tjbash.py | cmd | def cmd(send, msg, _):
"""Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring]
"""
if not msg:
url = 'http://tjbash.org/random1.html'
params = {}
else:
targs = msg.split()
if len(targs) == 1 and targs[0].isnumeric():
url = 'http://tjbash.org/%s' % targs[0]
params = {}
else:
url = 'http://tjbash.org/search.html'
params = {'query': 'tag:%s' % '+'.join(targs)}
req = get(url, params=params)
doc = fromstring(req.text)
quotes = doc.find_class('quote-body')
if not quotes:
send("There were no results.")
return
quote = choice(quotes)
lines = [x.strip() for x in map(operator.methodcaller('strip'), quote.itertext())]
# Only send up to three lines.
for line in lines[:4]:
send(line)
tags = quote.getparent().find_class('quote-tags')
postid = quote.getparent().getparent().get('id').replace('quote-', '')
if tags:
tags = [x.text for x in tags[0].findall('.//a')]
send(" -- {} -- {}http://tjbash.org/{}".format(', '.join(tags), "continued: " if (len(lines) > 3) else "", postid))
else:
send(" -- http://tjbash.org/{}".format(postid)) | python | def cmd(send, msg, _):
"""Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring]
"""
if not msg:
url = 'http://tjbash.org/random1.html'
params = {}
else:
targs = msg.split()
if len(targs) == 1 and targs[0].isnumeric():
url = 'http://tjbash.org/%s' % targs[0]
params = {}
else:
url = 'http://tjbash.org/search.html'
params = {'query': 'tag:%s' % '+'.join(targs)}
req = get(url, params=params)
doc = fromstring(req.text)
quotes = doc.find_class('quote-body')
if not quotes:
send("There were no results.")
return
quote = choice(quotes)
lines = [x.strip() for x in map(operator.methodcaller('strip'), quote.itertext())]
# Only send up to three lines.
for line in lines[:4]:
send(line)
tags = quote.getparent().find_class('quote-tags')
postid = quote.getparent().getparent().get('id').replace('quote-', '')
if tags:
tags = [x.text for x in tags[0].findall('.//a')]
send(" -- {} -- {}http://tjbash.org/{}".format(', '.join(tags), "continued: " if (len(lines) > 3) else "", postid))
else:
send(" -- http://tjbash.org/{}".format(postid)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"if",
"not",
"msg",
":",
"url",
"=",
"'http://tjbash.org/random1.html'",
"params",
"=",
"{",
"}",
"else",
":",
"targs",
"=",
"msg",
".",
"split",
"(",
")",
"if",
"len",
"(",
"targs",
")",
"==",
"1",
"and",
"targs",
"[",
"0",
"]",
".",
"isnumeric",
"(",
")",
":",
"url",
"=",
"'http://tjbash.org/%s'",
"%",
"targs",
"[",
"0",
"]",
"params",
"=",
"{",
"}",
"else",
":",
"url",
"=",
"'http://tjbash.org/search.html'",
"params",
"=",
"{",
"'query'",
":",
"'tag:%s'",
"%",
"'+'",
".",
"join",
"(",
"targs",
")",
"}",
"req",
"=",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"doc",
"=",
"fromstring",
"(",
"req",
".",
"text",
")",
"quotes",
"=",
"doc",
".",
"find_class",
"(",
"'quote-body'",
")",
"if",
"not",
"quotes",
":",
"send",
"(",
"\"There were no results.\"",
")",
"return",
"quote",
"=",
"choice",
"(",
"quotes",
")",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"map",
"(",
"operator",
".",
"methodcaller",
"(",
"'strip'",
")",
",",
"quote",
".",
"itertext",
"(",
")",
")",
"]",
"# Only send up to three lines.",
"for",
"line",
"in",
"lines",
"[",
":",
"4",
"]",
":",
"send",
"(",
"line",
")",
"tags",
"=",
"quote",
".",
"getparent",
"(",
")",
".",
"find_class",
"(",
"'quote-tags'",
")",
"postid",
"=",
"quote",
".",
"getparent",
"(",
")",
".",
"getparent",
"(",
")",
".",
"get",
"(",
"'id'",
")",
".",
"replace",
"(",
"'quote-'",
",",
"''",
")",
"if",
"tags",
":",
"tags",
"=",
"[",
"x",
".",
"text",
"for",
"x",
"in",
"tags",
"[",
"0",
"]",
".",
"findall",
"(",
"'.//a'",
")",
"]",
"send",
"(",
"\" -- {} -- {}http://tjbash.org/{}\"",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"tags",
")",
",",
"\"continued: \"",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"3",
")",
"else",
"\"\"",
",",
"postid",
")",
")",
"else",
":",
"send",
"(",
"\" -- http://tjbash.org/{}\"",
".",
"format",
"(",
"postid",
")",
")"
]
| Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring] | [
"Finds",
"a",
"random",
"quote",
"from",
"tjbash",
".",
"org",
"given",
"search",
"criteria",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/tjbash.py#L29-L63 | train |
The-Politico/politico-civic-election-night | electionnight/viewsets/body.py | BodyMixin.get_queryset | def get_queryset(self):
"""
Returns a queryset of all bodies holding an election on a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except Exception:
raise APIException(
'No elections on {}.'.format(self.kwargs['date'])
)
body_ids = []
for election in date.elections.all():
body = election.race.office.body
if body:
body_ids.append(body.uid)
return Body.objects.filter(uid__in=body_ids) | python | def get_queryset(self):
"""
Returns a queryset of all bodies holding an election on a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs['date'])
except Exception:
raise APIException(
'No elections on {}.'.format(self.kwargs['date'])
)
body_ids = []
for election in date.elections.all():
body = election.race.office.body
if body:
body_ids.append(body.uid)
return Body.objects.filter(uid__in=body_ids) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"try",
":",
"date",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
")",
"except",
"Exception",
":",
"raise",
"APIException",
"(",
"'No elections on {}.'",
".",
"format",
"(",
"self",
".",
"kwargs",
"[",
"'date'",
"]",
")",
")",
"body_ids",
"=",
"[",
"]",
"for",
"election",
"in",
"date",
".",
"elections",
".",
"all",
"(",
")",
":",
"body",
"=",
"election",
".",
"race",
".",
"office",
".",
"body",
"if",
"body",
":",
"body_ids",
".",
"append",
"(",
"body",
".",
"uid",
")",
"return",
"Body",
".",
"objects",
".",
"filter",
"(",
"uid__in",
"=",
"body_ids",
")"
]
| Returns a queryset of all bodies holding an election on a date. | [
"Returns",
"a",
"queryset",
"of",
"all",
"bodies",
"holding",
"an",
"election",
"on",
"a",
"date",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/body.py#L9-L24 | train |
asphalt-framework/asphalt-sqlalchemy | asphalt/sqlalchemy/component.py | SQLAlchemyComponent.configure_engine | def configure_engine(cls, url: Union[str, URL, Dict[str, Any]] = None,
bind: Union[Connection, Engine] = None, session: Dict[str, Any] = None,
ready_callback: Union[Callable[[Engine, sessionmaker], Any], str] = None,
poolclass: Union[str, Pool] = None, **engine_args):
"""
Create an engine and selectively apply certain hacks to make it Asphalt friendly.
:param url: the connection url passed to :func:`~sqlalchemy.create_engine`
(can also be a dictionary of :class:`~sqlalchemy.engine.url.URL` keyword arguments)
:param bind: a connection or engine to use instead of creating a new engine
:param session: keyword arguments to :class:`~sqlalchemy.orm.session.sessionmaker`
:param ready_callback: callable (or a ``module:varname`` reference to one) called with two
arguments: the Engine and the sessionmaker when the component is started but before the
resources are added to the context
:param poolclass: the SQLAlchemy Pool class to use; passed to
:func:`~sqlalchemy.create_engine`
:param engine_args: keyword arguments passed to :func:`~sqlalchemy.create_engine`
"""
assert check_argument_types()
if bind is None:
if isinstance(url, dict):
url = URL(**url)
elif isinstance(url, str):
url = make_url(url)
elif url is None:
raise TypeError('both "url" and "bind" cannot be None')
if isinstance(poolclass, str):
poolclass = resolve_reference(poolclass)
# This is a hack to get SQLite to play nice with asphalt-sqlalchemy's juggling of
# connections between multiple threads. The same connection should, however, never be
# used in multiple threads at once.
if url.get_dialect().name == 'sqlite':
connect_args = engine_args.setdefault('connect_args', {})
connect_args.setdefault('check_same_thread', False)
bind = create_engine(url, poolclass=poolclass, **engine_args)
session = session or {}
session.setdefault('expire_on_commit', False)
ready_callback = resolve_reference(ready_callback)
return bind, sessionmaker(bind, **session), ready_callback | python | def configure_engine(cls, url: Union[str, URL, Dict[str, Any]] = None,
bind: Union[Connection, Engine] = None, session: Dict[str, Any] = None,
ready_callback: Union[Callable[[Engine, sessionmaker], Any], str] = None,
poolclass: Union[str, Pool] = None, **engine_args):
"""
Create an engine and selectively apply certain hacks to make it Asphalt friendly.
:param url: the connection url passed to :func:`~sqlalchemy.create_engine`
(can also be a dictionary of :class:`~sqlalchemy.engine.url.URL` keyword arguments)
:param bind: a connection or engine to use instead of creating a new engine
:param session: keyword arguments to :class:`~sqlalchemy.orm.session.sessionmaker`
:param ready_callback: callable (or a ``module:varname`` reference to one) called with two
arguments: the Engine and the sessionmaker when the component is started but before the
resources are added to the context
:param poolclass: the SQLAlchemy Pool class to use; passed to
:func:`~sqlalchemy.create_engine`
:param engine_args: keyword arguments passed to :func:`~sqlalchemy.create_engine`
"""
assert check_argument_types()
if bind is None:
if isinstance(url, dict):
url = URL(**url)
elif isinstance(url, str):
url = make_url(url)
elif url is None:
raise TypeError('both "url" and "bind" cannot be None')
if isinstance(poolclass, str):
poolclass = resolve_reference(poolclass)
# This is a hack to get SQLite to play nice with asphalt-sqlalchemy's juggling of
# connections between multiple threads. The same connection should, however, never be
# used in multiple threads at once.
if url.get_dialect().name == 'sqlite':
connect_args = engine_args.setdefault('connect_args', {})
connect_args.setdefault('check_same_thread', False)
bind = create_engine(url, poolclass=poolclass, **engine_args)
session = session or {}
session.setdefault('expire_on_commit', False)
ready_callback = resolve_reference(ready_callback)
return bind, sessionmaker(bind, **session), ready_callback | [
"def",
"configure_engine",
"(",
"cls",
",",
"url",
":",
"Union",
"[",
"str",
",",
"URL",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"bind",
":",
"Union",
"[",
"Connection",
",",
"Engine",
"]",
"=",
"None",
",",
"session",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"ready_callback",
":",
"Union",
"[",
"Callable",
"[",
"[",
"Engine",
",",
"sessionmaker",
"]",
",",
"Any",
"]",
",",
"str",
"]",
"=",
"None",
",",
"poolclass",
":",
"Union",
"[",
"str",
",",
"Pool",
"]",
"=",
"None",
",",
"*",
"*",
"engine_args",
")",
":",
"assert",
"check_argument_types",
"(",
")",
"if",
"bind",
"is",
"None",
":",
"if",
"isinstance",
"(",
"url",
",",
"dict",
")",
":",
"url",
"=",
"URL",
"(",
"*",
"*",
"url",
")",
"elif",
"isinstance",
"(",
"url",
",",
"str",
")",
":",
"url",
"=",
"make_url",
"(",
"url",
")",
"elif",
"url",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'both \"url\" and \"bind\" cannot be None'",
")",
"if",
"isinstance",
"(",
"poolclass",
",",
"str",
")",
":",
"poolclass",
"=",
"resolve_reference",
"(",
"poolclass",
")",
"# This is a hack to get SQLite to play nice with asphalt-sqlalchemy's juggling of",
"# connections between multiple threads. The same connection should, however, never be",
"# used in multiple threads at once.",
"if",
"url",
".",
"get_dialect",
"(",
")",
".",
"name",
"==",
"'sqlite'",
":",
"connect_args",
"=",
"engine_args",
".",
"setdefault",
"(",
"'connect_args'",
",",
"{",
"}",
")",
"connect_args",
".",
"setdefault",
"(",
"'check_same_thread'",
",",
"False",
")",
"bind",
"=",
"create_engine",
"(",
"url",
",",
"poolclass",
"=",
"poolclass",
",",
"*",
"*",
"engine_args",
")",
"session",
"=",
"session",
"or",
"{",
"}",
"session",
".",
"setdefault",
"(",
"'expire_on_commit'",
",",
"False",
")",
"ready_callback",
"=",
"resolve_reference",
"(",
"ready_callback",
")",
"return",
"bind",
",",
"sessionmaker",
"(",
"bind",
",",
"*",
"*",
"session",
")",
",",
"ready_callback"
]
| Create an engine and selectively apply certain hacks to make it Asphalt friendly.
:param url: the connection url passed to :func:`~sqlalchemy.create_engine`
(can also be a dictionary of :class:`~sqlalchemy.engine.url.URL` keyword arguments)
:param bind: a connection or engine to use instead of creating a new engine
:param session: keyword arguments to :class:`~sqlalchemy.orm.session.sessionmaker`
:param ready_callback: callable (or a ``module:varname`` reference to one) called with two
arguments: the Engine and the sessionmaker when the component is started but before the
resources are added to the context
:param poolclass: the SQLAlchemy Pool class to use; passed to
:func:`~sqlalchemy.create_engine`
:param engine_args: keyword arguments passed to :func:`~sqlalchemy.create_engine` | [
"Create",
"an",
"engine",
"and",
"selectively",
"apply",
"certain",
"hacks",
"to",
"make",
"it",
"Asphalt",
"friendly",
"."
]
| 5abb7d9977ee92299359b76496ff34624421de05 | https://github.com/asphalt-framework/asphalt-sqlalchemy/blob/5abb7d9977ee92299359b76496ff34624421de05/asphalt/sqlalchemy/component.py#L70-L113 | train |
Genida/archan | src/archan/cli.py | valid_file | def valid_file(value):
"""
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
"""
if not value:
raise argparse.ArgumentTypeError("'' is not a valid file path")
elif not os.path.exists(value):
raise argparse.ArgumentTypeError(
"%s is not a valid file path" % value)
elif os.path.isdir(value):
raise argparse.ArgumentTypeError(
"%s is a directory, not a regular file" % value)
return value | python | def valid_file(value):
"""
Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument.
"""
if not value:
raise argparse.ArgumentTypeError("'' is not a valid file path")
elif not os.path.exists(value):
raise argparse.ArgumentTypeError(
"%s is not a valid file path" % value)
elif os.path.isdir(value):
raise argparse.ArgumentTypeError(
"%s is a directory, not a regular file" % value)
return value | [
"def",
"valid_file",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"'' is not a valid file path\"",
")",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"value",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"%s is not a valid file path\"",
"%",
"value",
")",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"value",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"%s is a directory, not a regular file\"",
"%",
"value",
")",
"return",
"value"
]
| Check if given file exists and is a regular file.
Args:
value (str): path to the file.
Raises:
argparse.ArgumentTypeError: if not valid.
Returns:
str: original value argument. | [
"Check",
"if",
"given",
"file",
"exists",
"and",
"is",
"a",
"regular",
"file",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/cli.py#L35-L56 | train |
Genida/archan | src/archan/cli.py | valid_level | def valid_level(value):
"""Validation function for parser, logging level argument."""
value = value.upper()
if getattr(logging, value, None) is None:
raise argparse.ArgumentTypeError("%s is not a valid level" % value)
return value | python | def valid_level(value):
"""Validation function for parser, logging level argument."""
value = value.upper()
if getattr(logging, value, None) is None:
raise argparse.ArgumentTypeError("%s is not a valid level" % value)
return value | [
"def",
"valid_level",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"upper",
"(",
")",
"if",
"getattr",
"(",
"logging",
",",
"value",
",",
"None",
")",
"is",
"None",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"%s is not a valid level\"",
"%",
"value",
")",
"return",
"value"
]
| Validation function for parser, logging level argument. | [
"Validation",
"function",
"for",
"parser",
"logging",
"level",
"argument",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/cli.py#L59-L64 | train |
tylerbutler/engineer | engineer/plugins/core.py | PluginMixin.get_logger | def get_logger(cls, custom_name=None):
"""Returns a logger for the plugin."""
name = custom_name or cls.get_name()
return logging.getLogger(name) | python | def get_logger(cls, custom_name=None):
"""Returns a logger for the plugin."""
name = custom_name or cls.get_name()
return logging.getLogger(name) | [
"def",
"get_logger",
"(",
"cls",
",",
"custom_name",
"=",
"None",
")",
":",
"name",
"=",
"custom_name",
"or",
"cls",
".",
"get_name",
"(",
")",
"return",
"logging",
".",
"getLogger",
"(",
"name",
")"
]
| Returns a logger for the plugin. | [
"Returns",
"a",
"logger",
"for",
"the",
"plugin",
"."
]
| 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/plugins/core.py#L80-L83 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.all | def all(self, domain=None):
"""
Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages
"""
if domain is None:
return {k: dict(v) for k, v in list(self.messages.items())}
return dict(self.messages.get(domain, {})) | python | def all(self, domain=None):
"""
Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages
"""
if domain is None:
return {k: dict(v) for k, v in list(self.messages.items())}
return dict(self.messages.get(domain, {})) | [
"def",
"all",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"if",
"domain",
"is",
"None",
":",
"return",
"{",
"k",
":",
"dict",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"messages",
".",
"items",
"(",
")",
")",
"}",
"return",
"dict",
"(",
"self",
".",
"messages",
".",
"get",
"(",
"domain",
",",
"{",
"}",
")",
")"
]
| Gets the messages within a given domain.
If domain is None, it returns all messages.
@type id: The
@param id: message id
@rtype: dict
@return: A dict of messages | [
"Gets",
"the",
"messages",
"within",
"a",
"given",
"domain",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L56-L71 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.set | def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | python | def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"translation",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"translation",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"self",
".",
"add",
"(",
"{",
"id",
":",
"translation",
"}",
",",
"domain",
")"
]
| Sets a message translation. | [
"Sets",
"a",
"message",
"translation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L73-L81 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.has | def has(self, id, domain):
"""
Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return True
if self.fallback_catalogue is not None:
return self.fallback_catalogue.has(id, domain)
return False | python | def has(self, id, domain):
"""
Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return True
if self.fallback_catalogue is not None:
return self.fallback_catalogue.has(id, domain)
return False | [
"def",
"has",
"(",
"self",
",",
"id",
",",
"domain",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"if",
"self",
".",
"defines",
"(",
"id",
",",
"domain",
")",
":",
"return",
"True",
"if",
"self",
".",
"fallback_catalogue",
"is",
"not",
"None",
":",
"return",
"self",
".",
"fallback_catalogue",
".",
"has",
"(",
"id",
",",
"domain",
")",
"return",
"False"
]
| Checks if a message has a translation.
@rtype: bool
@return: true if the message has a translation, false otherwise | [
"Checks",
"if",
"a",
"message",
"has",
"a",
"translation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L83-L99 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.get | def get(self, id, domain='messages'):
"""
Gets a message translation.
@rtype: str
@return: The message translation
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return self.messages[domain][id]
if self.fallback_catalogue is not None:
return self.fallback_catalogue.get(id, domain)
return id | python | def get(self, id, domain='messages'):
"""
Gets a message translation.
@rtype: str
@return: The message translation
"""
assert isinstance(id, (str, unicode))
assert isinstance(domain, (str, unicode))
if self.defines(id, domain):
return self.messages[domain][id]
if self.fallback_catalogue is not None:
return self.fallback_catalogue.get(id, domain)
return id | [
"def",
"get",
"(",
"self",
",",
"id",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"(",
"str",
",",
"unicode",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"if",
"self",
".",
"defines",
"(",
"id",
",",
"domain",
")",
":",
"return",
"self",
".",
"messages",
"[",
"domain",
"]",
"[",
"id",
"]",
"if",
"self",
".",
"fallback_catalogue",
"is",
"not",
"None",
":",
"return",
"self",
".",
"fallback_catalogue",
".",
"get",
"(",
"id",
",",
"domain",
")",
"return",
"id"
]
| Gets a message translation.
@rtype: str
@return: The message translation | [
"Gets",
"a",
"message",
"translation",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L114-L130 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.replace | def replace(self, messages, domain='messages'):
"""
Sets translations for a given domain.
"""
assert isinstance(messages, (dict, CaseInsensitiveDict))
assert isinstance(domain, (str, unicode))
self.messages[domain] = CaseInsensitiveDict({})
self.add(messages, domain) | python | def replace(self, messages, domain='messages'):
"""
Sets translations for a given domain.
"""
assert isinstance(messages, (dict, CaseInsensitiveDict))
assert isinstance(domain, (str, unicode))
self.messages[domain] = CaseInsensitiveDict({})
self.add(messages, domain) | [
"def",
"replace",
"(",
"self",
",",
"messages",
",",
"domain",
"=",
"'messages'",
")",
":",
"assert",
"isinstance",
"(",
"messages",
",",
"(",
"dict",
",",
"CaseInsensitiveDict",
")",
")",
"assert",
"isinstance",
"(",
"domain",
",",
"(",
"str",
",",
"unicode",
")",
")",
"self",
".",
"messages",
"[",
"domain",
"]",
"=",
"CaseInsensitiveDict",
"(",
"{",
"}",
")",
"self",
".",
"add",
"(",
"messages",
",",
"domain",
")"
]
| Sets translations for a given domain. | [
"Sets",
"translations",
"for",
"a",
"given",
"domain",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L132-L140 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.add_catalogue | def add_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one.
The two catalogues must have the same locale.
@type id: The
@param id: message id
"""
assert isinstance(catalogue, MessageCatalogue)
if catalogue.locale != self.locale:
raise ValueError(
'Cannot add a catalogue for locale "%s" as the '
'current locale for this catalogue is "%s"' %
(catalogue.locale, self.locale))
for domain, messages in list(catalogue.all().items()):
self.add(messages, domain)
for resource in catalogue.resources:
self.add_resource(resource) | python | def add_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one.
The two catalogues must have the same locale.
@type id: The
@param id: message id
"""
assert isinstance(catalogue, MessageCatalogue)
if catalogue.locale != self.locale:
raise ValueError(
'Cannot add a catalogue for locale "%s" as the '
'current locale for this catalogue is "%s"' %
(catalogue.locale, self.locale))
for domain, messages in list(catalogue.all().items()):
self.add(messages, domain)
for resource in catalogue.resources:
self.add_resource(resource) | [
"def",
"add_catalogue",
"(",
"self",
",",
"catalogue",
")",
":",
"assert",
"isinstance",
"(",
"catalogue",
",",
"MessageCatalogue",
")",
"if",
"catalogue",
".",
"locale",
"!=",
"self",
".",
"locale",
":",
"raise",
"ValueError",
"(",
"'Cannot add a catalogue for locale \"%s\" as the '",
"'current locale for this catalogue is \"%s\"'",
"%",
"(",
"catalogue",
".",
"locale",
",",
"self",
".",
"locale",
")",
")",
"for",
"domain",
",",
"messages",
"in",
"list",
"(",
"catalogue",
".",
"all",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"add",
"(",
"messages",
",",
"domain",
")",
"for",
"resource",
"in",
"catalogue",
".",
"resources",
":",
"self",
".",
"add_resource",
"(",
"resource",
")"
]
| Merges translations from the given Catalogue into the current one.
The two catalogues must have the same locale.
@type id: The
@param id: message id | [
"Merges",
"translations",
"from",
"the",
"given",
"Catalogue",
"into",
"the",
"current",
"one",
".",
"The",
"two",
"catalogues",
"must",
"have",
"the",
"same",
"locale",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L154-L175 | train |
adamziel/python_translate | python_translate/translations.py | MessageCatalogue.add_fallback_catalogue | def add_fallback_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one
only when the translation does not exist.
This is used to provide default translations when they do not exist
for the current locale.
@type id: The
@param id: message id
"""
assert isinstance(catalogue, MessageCatalogue)
# detect circular references
c = self
while True:
if c.locale == catalogue.locale:
raise ValueError(
'Circular reference detected when adding a '
'fallback catalogue for locale "%s".' %
catalogue.locale)
c = c.parent
if c is None:
break
catalogue.parent = self
self.fallback_catalogue = catalogue
for resource in catalogue.resources:
self.add_resource(resource) | python | def add_fallback_catalogue(self, catalogue):
"""
Merges translations from the given Catalogue into the current one
only when the translation does not exist.
This is used to provide default translations when they do not exist
for the current locale.
@type id: The
@param id: message id
"""
assert isinstance(catalogue, MessageCatalogue)
# detect circular references
c = self
while True:
if c.locale == catalogue.locale:
raise ValueError(
'Circular reference detected when adding a '
'fallback catalogue for locale "%s".' %
catalogue.locale)
c = c.parent
if c is None:
break
catalogue.parent = self
self.fallback_catalogue = catalogue
for resource in catalogue.resources:
self.add_resource(resource) | [
"def",
"add_fallback_catalogue",
"(",
"self",
",",
"catalogue",
")",
":",
"assert",
"isinstance",
"(",
"catalogue",
",",
"MessageCatalogue",
")",
"# detect circular references",
"c",
"=",
"self",
"while",
"True",
":",
"if",
"c",
".",
"locale",
"==",
"catalogue",
".",
"locale",
":",
"raise",
"ValueError",
"(",
"'Circular reference detected when adding a '",
"'fallback catalogue for locale \"%s\".'",
"%",
"catalogue",
".",
"locale",
")",
"c",
"=",
"c",
".",
"parent",
"if",
"c",
"is",
"None",
":",
"break",
"catalogue",
".",
"parent",
"=",
"self",
"self",
".",
"fallback_catalogue",
"=",
"catalogue",
"for",
"resource",
"in",
"catalogue",
".",
"resources",
":",
"self",
".",
"add_resource",
"(",
"resource",
")"
]
| Merges translations from the given Catalogue into the current one
only when the translation does not exist.
This is used to provide default translations when they do not exist
for the current locale.
@type id: The
@param id: message id | [
"Merges",
"translations",
"from",
"the",
"given",
"Catalogue",
"into",
"the",
"current",
"one",
"only",
"when",
"the",
"translation",
"does",
"not",
"exist",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L177-L207 | train |
adamziel/python_translate | python_translate/translations.py | Translator.trans | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The domain for the message or null to use the default
@type locale: str
@param locale: The locale or null to use the default
@rtype: str
@return: Translated message
"""
if parameters is None:
parameters = {}
assert isinstance(parameters, dict)
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(locale)
if domain is None:
domain = 'messages'
msg = self.get_catalogue(locale).get(id, domain)
return self.format(msg, parameters) | python | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The domain for the message or null to use the default
@type locale: str
@param locale: The locale or null to use the default
@rtype: str
@return: Translated message
"""
if parameters is None:
parameters = {}
assert isinstance(parameters, dict)
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(locale)
if domain is None:
domain = 'messages'
msg = self.get_catalogue(locale).get(id, domain)
return self.format(msg, parameters) | [
"def",
"trans",
"(",
"self",
",",
"id",
",",
"parameters",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"parameters",
",",
"dict",
")",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"else",
":",
"self",
".",
"_assert_valid_locale",
"(",
"locale",
")",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"'messages'",
"msg",
"=",
"self",
".",
"get_catalogue",
"(",
"locale",
")",
".",
"get",
"(",
"id",
",",
"domain",
")",
"return",
"self",
".",
"format",
"(",
"msg",
",",
"parameters",
")"
]
| Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The domain for the message or null to use the default
@type locale: str
@param locale: The locale or null to use the default
@rtype: str
@return: Translated message | [
"Translates",
"the",
"given",
"message",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L266-L298 | train |
adamziel/python_translate | python_translate/translations.py | Translator.set_fallback_locales | def set_fallback_locales(self, locales):
"""
Sets the fallback locales.
@type locales: list[str]
@param locales: The falback locales
@raises: ValueError: If a locale contains invalid characters
"""
# needed as the fallback locales are linked to the already loaded
# catalogues
self.catalogues = {}
for locale in locales:
self._assert_valid_locale(locale)
self.fallback_locales = locales | python | def set_fallback_locales(self, locales):
"""
Sets the fallback locales.
@type locales: list[str]
@param locales: The falback locales
@raises: ValueError: If a locale contains invalid characters
"""
# needed as the fallback locales are linked to the already loaded
# catalogues
self.catalogues = {}
for locale in locales:
self._assert_valid_locale(locale)
self.fallback_locales = locales | [
"def",
"set_fallback_locales",
"(",
"self",
",",
"locales",
")",
":",
"# needed as the fallback locales are linked to the already loaded",
"# catalogues",
"self",
".",
"catalogues",
"=",
"{",
"}",
"for",
"locale",
"in",
"locales",
":",
"self",
".",
"_assert_valid_locale",
"(",
"locale",
")",
"self",
".",
"fallback_locales",
"=",
"locales"
]
| Sets the fallback locales.
@type locales: list[str]
@param locales: The falback locales
@raises: ValueError: If a locale contains invalid characters | [
"Sets",
"the",
"fallback",
"locales",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L366-L382 | train |
adamziel/python_translate | python_translate/translations.py | Translator.get_messages | def get_messages(self, locale=None):
"""
Collects all messages for the given locale.
@type locale: str|one
@param locale: Locale of translations, by default is current locale
@rtype: dict:
@return: dict indexed by catalog name
"""
if locale is None:
locale = self.locale
if locale not in self.catalogues:
self._load_catalogue(locale)
catalogues = [self.catalogues[locale]]
catalogue = catalogues[0]
while True:
catalogue = catalogue.fallback_catalogue
if catalogue is None:
break
catalogues.append(catalogue)
messages = {}
for catalogue in catalogues[::-1]:
recursive_update(messages, catalogue.all())
return messages | python | def get_messages(self, locale=None):
"""
Collects all messages for the given locale.
@type locale: str|one
@param locale: Locale of translations, by default is current locale
@rtype: dict:
@return: dict indexed by catalog name
"""
if locale is None:
locale = self.locale
if locale not in self.catalogues:
self._load_catalogue(locale)
catalogues = [self.catalogues[locale]]
catalogue = catalogues[0]
while True:
catalogue = catalogue.fallback_catalogue
if catalogue is None:
break
catalogues.append(catalogue)
messages = {}
for catalogue in catalogues[::-1]:
recursive_update(messages, catalogue.all())
return messages | [
"def",
"get_messages",
"(",
"self",
",",
"locale",
"=",
"None",
")",
":",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"if",
"locale",
"not",
"in",
"self",
".",
"catalogues",
":",
"self",
".",
"_load_catalogue",
"(",
"locale",
")",
"catalogues",
"=",
"[",
"self",
".",
"catalogues",
"[",
"locale",
"]",
"]",
"catalogue",
"=",
"catalogues",
"[",
"0",
"]",
"while",
"True",
":",
"catalogue",
"=",
"catalogue",
".",
"fallback_catalogue",
"if",
"catalogue",
"is",
"None",
":",
"break",
"catalogues",
".",
"append",
"(",
"catalogue",
")",
"messages",
"=",
"{",
"}",
"for",
"catalogue",
"in",
"catalogues",
"[",
":",
":",
"-",
"1",
"]",
":",
"recursive_update",
"(",
"messages",
",",
"catalogue",
".",
"all",
"(",
")",
")",
"return",
"messages"
]
| Collects all messages for the given locale.
@type locale: str|one
@param locale: Locale of translations, by default is current locale
@rtype: dict:
@return: dict indexed by catalog name | [
"Collects",
"all",
"messages",
"for",
"the",
"given",
"locale",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L425-L453 | train |
adamziel/python_translate | python_translate/translations.py | DebugTranslator.trans | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Throws RuntimeError whenever a message is missing
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(locale)
if domain is None:
domain = 'messages'
catalogue = self.get_catalogue(locale)
if not catalogue.has(id, domain):
raise RuntimeError(
"There is no translation for {0} in domain {1}".format(
id,
domain
)
)
msg = self.get_catalogue(locale).get(id, domain)
return self.format(msg, parameters) | python | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Throws RuntimeError whenever a message is missing
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(locale)
if domain is None:
domain = 'messages'
catalogue = self.get_catalogue(locale)
if not catalogue.has(id, domain):
raise RuntimeError(
"There is no translation for {0} in domain {1}".format(
id,
domain
)
)
msg = self.get_catalogue(locale).get(id, domain)
return self.format(msg, parameters) | [
"def",
"trans",
"(",
"self",
",",
"id",
",",
"parameters",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"else",
":",
"self",
".",
"_assert_valid_locale",
"(",
"locale",
")",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"'messages'",
"catalogue",
"=",
"self",
".",
"get_catalogue",
"(",
"locale",
")",
"if",
"not",
"catalogue",
".",
"has",
"(",
"id",
",",
"domain",
")",
":",
"raise",
"RuntimeError",
"(",
"\"There is no translation for {0} in domain {1}\"",
".",
"format",
"(",
"id",
",",
"domain",
")",
")",
"msg",
"=",
"self",
".",
"get_catalogue",
"(",
"locale",
")",
".",
"get",
"(",
"id",
",",
"domain",
")",
"return",
"self",
".",
"format",
"(",
"msg",
",",
"parameters",
")"
]
| Throws RuntimeError whenever a message is missing | [
"Throws",
"RuntimeError",
"whenever",
"a",
"message",
"is",
"missing"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L528-L553 | train |
adamziel/python_translate | python_translate/translations.py | DebugTranslator.transchoice | def transchoice(self, id, number, parameters=None, domain=None, locale=None):
"""
Raises a RuntimeError whenever a message is missing
@raises: RuntimeError
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(locale)
if domain is None:
domain = 'messages'
catalogue = self.get_catalogue(locale)
while not catalogue.defines(id, domain):
cat = catalogue.fallback_catalogue
if cat:
catalogue = cat
locale = catalogue.locale
else:
break
if not catalogue.has(id, domain):
raise RuntimeError(
"There is no translation for {0} in domain {1}".format(
id,
domain
)
)
parameters['count'] = number
msg = selector.select_message(
catalogue.get(
id,
domain
),
number,
locale
)
return self.format(msg, parameters) | python | def transchoice(self, id, number, parameters=None, domain=None, locale=None):
"""
Raises a RuntimeError whenever a message is missing
@raises: RuntimeError
"""
if parameters is None:
parameters = {}
if locale is None:
locale = self.locale
else:
self._assert_valid_locale(locale)
if domain is None:
domain = 'messages'
catalogue = self.get_catalogue(locale)
while not catalogue.defines(id, domain):
cat = catalogue.fallback_catalogue
if cat:
catalogue = cat
locale = catalogue.locale
else:
break
if not catalogue.has(id, domain):
raise RuntimeError(
"There is no translation for {0} in domain {1}".format(
id,
domain
)
)
parameters['count'] = number
msg = selector.select_message(
catalogue.get(
id,
domain
),
number,
locale
)
return self.format(msg, parameters) | [
"def",
"transchoice",
"(",
"self",
",",
"id",
",",
"number",
",",
"parameters",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"locale",
"=",
"None",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"{",
"}",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"else",
":",
"self",
".",
"_assert_valid_locale",
"(",
"locale",
")",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"'messages'",
"catalogue",
"=",
"self",
".",
"get_catalogue",
"(",
"locale",
")",
"while",
"not",
"catalogue",
".",
"defines",
"(",
"id",
",",
"domain",
")",
":",
"cat",
"=",
"catalogue",
".",
"fallback_catalogue",
"if",
"cat",
":",
"catalogue",
"=",
"cat",
"locale",
"=",
"catalogue",
".",
"locale",
"else",
":",
"break",
"if",
"not",
"catalogue",
".",
"has",
"(",
"id",
",",
"domain",
")",
":",
"raise",
"RuntimeError",
"(",
"\"There is no translation for {0} in domain {1}\"",
".",
"format",
"(",
"id",
",",
"domain",
")",
")",
"parameters",
"[",
"'count'",
"]",
"=",
"number",
"msg",
"=",
"selector",
".",
"select_message",
"(",
"catalogue",
".",
"get",
"(",
"id",
",",
"domain",
")",
",",
"number",
",",
"locale",
")",
"return",
"self",
".",
"format",
"(",
"msg",
",",
"parameters",
")"
]
| Raises a RuntimeError whenever a message is missing
@raises: RuntimeError | [
"Raises",
"a",
"RuntimeError",
"whenever",
"a",
"message",
"is",
"missing"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L555-L597 | train |
adamziel/python_translate | python_translate/translations.py | DebugTranslator.get_catalogue | def get_catalogue(self, locale):
"""
Reloads messages catalogue if requested after more than one second
since last reload
"""
if locale is None:
locale = self.locale
if locale not in self.catalogues or datetime.now() - self.last_reload > timedelta(seconds=1):
self._load_catalogue(locale)
self.last_reload = datetime.now()
return self.catalogues[locale] | python | def get_catalogue(self, locale):
"""
Reloads messages catalogue if requested after more than one second
since last reload
"""
if locale is None:
locale = self.locale
if locale not in self.catalogues or datetime.now() - self.last_reload > timedelta(seconds=1):
self._load_catalogue(locale)
self.last_reload = datetime.now()
return self.catalogues[locale] | [
"def",
"get_catalogue",
"(",
"self",
",",
"locale",
")",
":",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"self",
".",
"locale",
"if",
"locale",
"not",
"in",
"self",
".",
"catalogues",
"or",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"last_reload",
">",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
":",
"self",
".",
"_load_catalogue",
"(",
"locale",
")",
"self",
".",
"last_reload",
"=",
"datetime",
".",
"now",
"(",
")",
"return",
"self",
".",
"catalogues",
"[",
"locale",
"]"
]
| Reloads messages catalogue if requested after more than one second
since last reload | [
"Reloads",
"messages",
"catalogue",
"if",
"requested",
"after",
"more",
"than",
"one",
"second",
"since",
"last",
"reload"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/translations.py#L599-L611 | train |
tjcsl/cslbot | cslbot/helpers/reloader.py | do_reload | def do_reload(bot, target, cmdargs, server_send=None):
"""The reloading magic.
- First, reload handler.py.
- Then make copies of all the handler data we want to keep.
- Create a new handler and restore all the data.
"""
def send(msg):
if server_send is not None:
server_send("%s\n" % msg)
else:
do_log(bot.connection, bot.get_target(target), msg)
confdir = bot.handler.confdir
if cmdargs == 'pull':
# Permission checks.
if isinstance(target, irc.client.Event) and target.source.nick != bot.config['auth']['owner']:
bot.connection.privmsg(bot.get_target(target), "Nope, not gonna do it.")
return
if exists(join(confdir, '.git')):
send(misc.do_pull(srcdir=confdir))
else:
send(misc.do_pull(repo=bot.config['api']['githubrepo']))
# Reload config
importlib.reload(config)
bot.config = config.load_config(join(confdir, 'config.cfg'), send)
# Reimport helpers
errored_helpers = modutils.scan_and_reimport('helpers')
if errored_helpers:
send("Failed to load some helpers.")
for error in errored_helpers:
send("%s: %s" % error)
return False
if not load_modules(bot.config, confdir, send):
return False
# preserve data
data = bot.handler.get_data()
bot.shutdown_mp()
bot.handler = handler.BotHandler(bot.config, bot.connection, bot.channels, confdir)
bot.handler.set_data(data)
bot.handler.connection = bot.connection
bot.handler.channels = bot.channels
return True | python | def do_reload(bot, target, cmdargs, server_send=None):
"""The reloading magic.
- First, reload handler.py.
- Then make copies of all the handler data we want to keep.
- Create a new handler and restore all the data.
"""
def send(msg):
if server_send is not None:
server_send("%s\n" % msg)
else:
do_log(bot.connection, bot.get_target(target), msg)
confdir = bot.handler.confdir
if cmdargs == 'pull':
# Permission checks.
if isinstance(target, irc.client.Event) and target.source.nick != bot.config['auth']['owner']:
bot.connection.privmsg(bot.get_target(target), "Nope, not gonna do it.")
return
if exists(join(confdir, '.git')):
send(misc.do_pull(srcdir=confdir))
else:
send(misc.do_pull(repo=bot.config['api']['githubrepo']))
# Reload config
importlib.reload(config)
bot.config = config.load_config(join(confdir, 'config.cfg'), send)
# Reimport helpers
errored_helpers = modutils.scan_and_reimport('helpers')
if errored_helpers:
send("Failed to load some helpers.")
for error in errored_helpers:
send("%s: %s" % error)
return False
if not load_modules(bot.config, confdir, send):
return False
# preserve data
data = bot.handler.get_data()
bot.shutdown_mp()
bot.handler = handler.BotHandler(bot.config, bot.connection, bot.channels, confdir)
bot.handler.set_data(data)
bot.handler.connection = bot.connection
bot.handler.channels = bot.channels
return True | [
"def",
"do_reload",
"(",
"bot",
",",
"target",
",",
"cmdargs",
",",
"server_send",
"=",
"None",
")",
":",
"def",
"send",
"(",
"msg",
")",
":",
"if",
"server_send",
"is",
"not",
"None",
":",
"server_send",
"(",
"\"%s\\n\"",
"%",
"msg",
")",
"else",
":",
"do_log",
"(",
"bot",
".",
"connection",
",",
"bot",
".",
"get_target",
"(",
"target",
")",
",",
"msg",
")",
"confdir",
"=",
"bot",
".",
"handler",
".",
"confdir",
"if",
"cmdargs",
"==",
"'pull'",
":",
"# Permission checks.",
"if",
"isinstance",
"(",
"target",
",",
"irc",
".",
"client",
".",
"Event",
")",
"and",
"target",
".",
"source",
".",
"nick",
"!=",
"bot",
".",
"config",
"[",
"'auth'",
"]",
"[",
"'owner'",
"]",
":",
"bot",
".",
"connection",
".",
"privmsg",
"(",
"bot",
".",
"get_target",
"(",
"target",
")",
",",
"\"Nope, not gonna do it.\"",
")",
"return",
"if",
"exists",
"(",
"join",
"(",
"confdir",
",",
"'.git'",
")",
")",
":",
"send",
"(",
"misc",
".",
"do_pull",
"(",
"srcdir",
"=",
"confdir",
")",
")",
"else",
":",
"send",
"(",
"misc",
".",
"do_pull",
"(",
"repo",
"=",
"bot",
".",
"config",
"[",
"'api'",
"]",
"[",
"'githubrepo'",
"]",
")",
")",
"# Reload config",
"importlib",
".",
"reload",
"(",
"config",
")",
"bot",
".",
"config",
"=",
"config",
".",
"load_config",
"(",
"join",
"(",
"confdir",
",",
"'config.cfg'",
")",
",",
"send",
")",
"# Reimport helpers",
"errored_helpers",
"=",
"modutils",
".",
"scan_and_reimport",
"(",
"'helpers'",
")",
"if",
"errored_helpers",
":",
"send",
"(",
"\"Failed to load some helpers.\"",
")",
"for",
"error",
"in",
"errored_helpers",
":",
"send",
"(",
"\"%s: %s\"",
"%",
"error",
")",
"return",
"False",
"if",
"not",
"load_modules",
"(",
"bot",
".",
"config",
",",
"confdir",
",",
"send",
")",
":",
"return",
"False",
"# preserve data",
"data",
"=",
"bot",
".",
"handler",
".",
"get_data",
"(",
")",
"bot",
".",
"shutdown_mp",
"(",
")",
"bot",
".",
"handler",
"=",
"handler",
".",
"BotHandler",
"(",
"bot",
".",
"config",
",",
"bot",
".",
"connection",
",",
"bot",
".",
"channels",
",",
"confdir",
")",
"bot",
".",
"handler",
".",
"set_data",
"(",
"data",
")",
"bot",
".",
"handler",
".",
"connection",
"=",
"bot",
".",
"connection",
"bot",
".",
"handler",
".",
"channels",
"=",
"bot",
".",
"channels",
"return",
"True"
]
| The reloading magic.
- First, reload handler.py.
- Then make copies of all the handler data we want to keep.
- Create a new handler and restore all the data. | [
"The",
"reloading",
"magic",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/reloader.py#L50-L96 | train |
Xion/taipan | taipan/objective/methods.py | is_method | def is_method(arg):
"""Checks whether given object is a method."""
if inspect.ismethod(arg):
return True
if isinstance(arg, NonInstanceMethod):
return True
# Unfortunately, there is no disctinction between instance methods
# that are yet to become part of a class, and regular functions.
# We attempt to evade this little gray zone by relying on extremely strong
# convention (which is nevertheless _not_ enforced by the intepreter)
# that first argument of an instance method must be always named ``self``.
if inspect.isfunction(arg):
return _get_first_arg_name(arg) == 'self'
return False | python | def is_method(arg):
"""Checks whether given object is a method."""
if inspect.ismethod(arg):
return True
if isinstance(arg, NonInstanceMethod):
return True
# Unfortunately, there is no disctinction between instance methods
# that are yet to become part of a class, and regular functions.
# We attempt to evade this little gray zone by relying on extremely strong
# convention (which is nevertheless _not_ enforced by the intepreter)
# that first argument of an instance method must be always named ``self``.
if inspect.isfunction(arg):
return _get_first_arg_name(arg) == 'self'
return False | [
"def",
"is_method",
"(",
"arg",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"arg",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"arg",
",",
"NonInstanceMethod",
")",
":",
"return",
"True",
"# Unfortunately, there is no disctinction between instance methods",
"# that are yet to become part of a class, and regular functions.",
"# We attempt to evade this little gray zone by relying on extremely strong",
"# convention (which is nevertheless _not_ enforced by the intepreter)",
"# that first argument of an instance method must be always named ``self``.",
"if",
"inspect",
".",
"isfunction",
"(",
"arg",
")",
":",
"return",
"_get_first_arg_name",
"(",
"arg",
")",
"==",
"'self'",
"return",
"False"
]
| Checks whether given object is a method. | [
"Checks",
"whether",
"given",
"object",
"is",
"a",
"method",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/methods.py#L20-L35 | train |
UMIACS/qav | qav/questions.py | Question._ask | def _ask(self, answers):
""" Really ask the question.
We may need to populate multiple validators with answers here.
Then ask the question and insert the default value if
appropriate. Finally call the validate function to check all
validators for this question and returning the answer.
"""
if isinstance(self.validator, list):
for v in self.validator:
v.answers = answers
else:
self.validator.answers = answers
while(True):
q = self.question % answers
if not self.choices():
logger.warn('No choices were supplied for "%s"' % q)
return None
if self.value in answers:
default = Validator.stringify(answers[self.value])
answer = self._get_input("%s [%s]: " % (q, default))
if answer == '':
answer = answers[self.value]
else:
answer = self._get_input("%s: " % q)
# if we are in multiple mode and the answer is just the empty
# string (enter/return pressed) then we will just answer None
# to indicate we are done
if answer == '.' and self.multiple:
return None
if self.validate(answer):
return self.answer()
else:
if isinstance(self.validator, list):
for v in self.validator:
if v.error() != '':
print(v.error())
else:
print(self.validator.error()) | python | def _ask(self, answers):
""" Really ask the question.
We may need to populate multiple validators with answers here.
Then ask the question and insert the default value if
appropriate. Finally call the validate function to check all
validators for this question and returning the answer.
"""
if isinstance(self.validator, list):
for v in self.validator:
v.answers = answers
else:
self.validator.answers = answers
while(True):
q = self.question % answers
if not self.choices():
logger.warn('No choices were supplied for "%s"' % q)
return None
if self.value in answers:
default = Validator.stringify(answers[self.value])
answer = self._get_input("%s [%s]: " % (q, default))
if answer == '':
answer = answers[self.value]
else:
answer = self._get_input("%s: " % q)
# if we are in multiple mode and the answer is just the empty
# string (enter/return pressed) then we will just answer None
# to indicate we are done
if answer == '.' and self.multiple:
return None
if self.validate(answer):
return self.answer()
else:
if isinstance(self.validator, list):
for v in self.validator:
if v.error() != '':
print(v.error())
else:
print(self.validator.error()) | [
"def",
"_ask",
"(",
"self",
",",
"answers",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"for",
"v",
"in",
"self",
".",
"validator",
":",
"v",
".",
"answers",
"=",
"answers",
"else",
":",
"self",
".",
"validator",
".",
"answers",
"=",
"answers",
"while",
"(",
"True",
")",
":",
"q",
"=",
"self",
".",
"question",
"%",
"answers",
"if",
"not",
"self",
".",
"choices",
"(",
")",
":",
"logger",
".",
"warn",
"(",
"'No choices were supplied for \"%s\"'",
"%",
"q",
")",
"return",
"None",
"if",
"self",
".",
"value",
"in",
"answers",
":",
"default",
"=",
"Validator",
".",
"stringify",
"(",
"answers",
"[",
"self",
".",
"value",
"]",
")",
"answer",
"=",
"self",
".",
"_get_input",
"(",
"\"%s [%s]: \"",
"%",
"(",
"q",
",",
"default",
")",
")",
"if",
"answer",
"==",
"''",
":",
"answer",
"=",
"answers",
"[",
"self",
".",
"value",
"]",
"else",
":",
"answer",
"=",
"self",
".",
"_get_input",
"(",
"\"%s: \"",
"%",
"q",
")",
"# if we are in multiple mode and the answer is just the empty",
"# string (enter/return pressed) then we will just answer None",
"# to indicate we are done",
"if",
"answer",
"==",
"'.'",
"and",
"self",
".",
"multiple",
":",
"return",
"None",
"if",
"self",
".",
"validate",
"(",
"answer",
")",
":",
"return",
"self",
".",
"answer",
"(",
")",
"else",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"for",
"v",
"in",
"self",
".",
"validator",
":",
"if",
"v",
".",
"error",
"(",
")",
"!=",
"''",
":",
"print",
"(",
"v",
".",
"error",
"(",
")",
")",
"else",
":",
"print",
"(",
"self",
".",
"validator",
".",
"error",
"(",
")",
")"
]
| Really ask the question.
We may need to populate multiple validators with answers here.
Then ask the question and insert the default value if
appropriate. Finally call the validate function to check all
validators for this question and returning the answer. | [
"Really",
"ask",
"the",
"question",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L107-L146 | train |
UMIACS/qav | qav/questions.py | Question.ask | def ask(self, answers=None):
""" Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions.
"""
if answers is None:
answers = {}
_answers = {}
if self.multiple:
print((bold('Multiple answers are supported for this question. ' +
'Please enter a "." character to finish.')))
_answers[self.value] = []
answer = self._ask(answers)
while answer is not None:
_answers[self.value].append(answer)
answer = self._ask(answers)
else:
_answers[self.value] = self._ask(answers)
if isinstance(self.validator, list):
for v in self.validator:
_answers = dict(_answers, **v.hints())
else:
_answers = dict(_answers, **self.validator.hints())
for q in self._questions:
answers = dict(answers, **_answers)
_answers = dict(_answers, **q.ask(answers))
return _answers | python | def ask(self, answers=None):
""" Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions.
"""
if answers is None:
answers = {}
_answers = {}
if self.multiple:
print((bold('Multiple answers are supported for this question. ' +
'Please enter a "." character to finish.')))
_answers[self.value] = []
answer = self._ask(answers)
while answer is not None:
_answers[self.value].append(answer)
answer = self._ask(answers)
else:
_answers[self.value] = self._ask(answers)
if isinstance(self.validator, list):
for v in self.validator:
_answers = dict(_answers, **v.hints())
else:
_answers = dict(_answers, **self.validator.hints())
for q in self._questions:
answers = dict(answers, **_answers)
_answers = dict(_answers, **q.ask(answers))
return _answers | [
"def",
"ask",
"(",
"self",
",",
"answers",
"=",
"None",
")",
":",
"if",
"answers",
"is",
"None",
":",
"answers",
"=",
"{",
"}",
"_answers",
"=",
"{",
"}",
"if",
"self",
".",
"multiple",
":",
"print",
"(",
"(",
"bold",
"(",
"'Multiple answers are supported for this question. '",
"+",
"'Please enter a \".\" character to finish.'",
")",
")",
")",
"_answers",
"[",
"self",
".",
"value",
"]",
"=",
"[",
"]",
"answer",
"=",
"self",
".",
"_ask",
"(",
"answers",
")",
"while",
"answer",
"is",
"not",
"None",
":",
"_answers",
"[",
"self",
".",
"value",
"]",
".",
"append",
"(",
"answer",
")",
"answer",
"=",
"self",
".",
"_ask",
"(",
"answers",
")",
"else",
":",
"_answers",
"[",
"self",
".",
"value",
"]",
"=",
"self",
".",
"_ask",
"(",
"answers",
")",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"for",
"v",
"in",
"self",
".",
"validator",
":",
"_answers",
"=",
"dict",
"(",
"_answers",
",",
"*",
"*",
"v",
".",
"hints",
"(",
")",
")",
"else",
":",
"_answers",
"=",
"dict",
"(",
"_answers",
",",
"*",
"*",
"self",
".",
"validator",
".",
"hints",
"(",
")",
")",
"for",
"q",
"in",
"self",
".",
"_questions",
":",
"answers",
"=",
"dict",
"(",
"answers",
",",
"*",
"*",
"_answers",
")",
"_answers",
"=",
"dict",
"(",
"_answers",
",",
"*",
"*",
"q",
".",
"ask",
"(",
"answers",
")",
")",
"return",
"_answers"
]
| Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions. | [
"Ask",
"the",
"question",
"then",
"ask",
"any",
"sub",
"-",
"questions",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L148-L175 | train |
UMIACS/qav | qav/questions.py | Question.answer | def answer(self):
""" Return the answer for the question from the validator.
This will ultimately only be called on the first validator if
multiple validators have been added.
"""
if isinstance(self.validator, list):
return self.validator[0].choice()
return self.validator.choice() | python | def answer(self):
""" Return the answer for the question from the validator.
This will ultimately only be called on the first validator if
multiple validators have been added.
"""
if isinstance(self.validator, list):
return self.validator[0].choice()
return self.validator.choice() | [
"def",
"answer",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"return",
"self",
".",
"validator",
"[",
"0",
"]",
".",
"choice",
"(",
")",
"return",
"self",
".",
"validator",
".",
"choice",
"(",
")"
]
| Return the answer for the question from the validator.
This will ultimately only be called on the first validator if
multiple validators have been added. | [
"Return",
"the",
"answer",
"for",
"the",
"question",
"from",
"the",
"validator",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L195-L203 | train |
UMIACS/qav | qav/questions.py | Question.choices | def choices(self):
""" Print the choices for this question.
This may be a empty string and in the case of a list of validators
we will only show the first validator's choices.
"""
if isinstance(self.validator, list):
return self.validator[0].print_choices()
return self.validator.print_choices() | python | def choices(self):
""" Print the choices for this question.
This may be a empty string and in the case of a list of validators
we will only show the first validator's choices.
"""
if isinstance(self.validator, list):
return self.validator[0].print_choices()
return self.validator.print_choices() | [
"def",
"choices",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"validator",
",",
"list",
")",
":",
"return",
"self",
".",
"validator",
"[",
"0",
"]",
".",
"print_choices",
"(",
")",
"return",
"self",
".",
"validator",
".",
"print_choices",
"(",
")"
]
| Print the choices for this question.
This may be a empty string and in the case of a list of validators
we will only show the first validator's choices. | [
"Print",
"the",
"choices",
"for",
"this",
"question",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/questions.py#L205-L213 | train |
iansf/qj | qj/qj.py | _timing | def _timing(f, logs_every=100):
"""Decorator to time function calls and log the stats."""
@functools.wraps(f)
def wrap(*args, **kw):
"""The timer function."""
ts = _time.time()
result = f(*args, **kw)
te = _time.time()
qj._call_counts[f] += 1
qj._timings[f] += (te - ts)
count = qj._call_counts[f]
if count % logs_every == 0:
qj(x='%2.4f seconds' % (qj._timings[f] / count),
s='Average timing for %s across %d call%s' % (f, count, '' if count == 1 else 's'), _depth=2)
return result
return wrap | python | def _timing(f, logs_every=100):
"""Decorator to time function calls and log the stats."""
@functools.wraps(f)
def wrap(*args, **kw):
"""The timer function."""
ts = _time.time()
result = f(*args, **kw)
te = _time.time()
qj._call_counts[f] += 1
qj._timings[f] += (te - ts)
count = qj._call_counts[f]
if count % logs_every == 0:
qj(x='%2.4f seconds' % (qj._timings[f] / count),
s='Average timing for %s across %d call%s' % (f, count, '' if count == 1 else 's'), _depth=2)
return result
return wrap | [
"def",
"_timing",
"(",
"f",
",",
"logs_every",
"=",
"100",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"The timer function.\"\"\"",
"ts",
"=",
"_time",
".",
"time",
"(",
")",
"result",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"te",
"=",
"_time",
".",
"time",
"(",
")",
"qj",
".",
"_call_counts",
"[",
"f",
"]",
"+=",
"1",
"qj",
".",
"_timings",
"[",
"f",
"]",
"+=",
"(",
"te",
"-",
"ts",
")",
"count",
"=",
"qj",
".",
"_call_counts",
"[",
"f",
"]",
"if",
"count",
"%",
"logs_every",
"==",
"0",
":",
"qj",
"(",
"x",
"=",
"'%2.4f seconds'",
"%",
"(",
"qj",
".",
"_timings",
"[",
"f",
"]",
"/",
"count",
")",
",",
"s",
"=",
"'Average timing for %s across %d call%s'",
"%",
"(",
"f",
",",
"count",
",",
"''",
"if",
"count",
"==",
"1",
"else",
"'s'",
")",
",",
"_depth",
"=",
"2",
")",
"return",
"result",
"return",
"wrap"
]
| Decorator to time function calls and log the stats. | [
"Decorator",
"to",
"time",
"function",
"calls",
"and",
"log",
"the",
"stats",
"."
]
| 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L596-L611 | train |
iansf/qj | qj/qj.py | _catch | def _catch(f, exception_type):
"""Decorator to drop into the debugger if a function throws an exception."""
if not (inspect.isclass(exception_type)
and issubclass(exception_type, Exception)):
exception_type = Exception
@functools.wraps(f)
def wrap(*args, **kw):
try:
return f(*args, **kw)
except exception_type as e: # pylint: disable=broad-except
qj(e, 'Caught an exception in %s' % f, d=1, _depth=2)
return wrap | python | def _catch(f, exception_type):
"""Decorator to drop into the debugger if a function throws an exception."""
if not (inspect.isclass(exception_type)
and issubclass(exception_type, Exception)):
exception_type = Exception
@functools.wraps(f)
def wrap(*args, **kw):
try:
return f(*args, **kw)
except exception_type as e: # pylint: disable=broad-except
qj(e, 'Caught an exception in %s' % f, d=1, _depth=2)
return wrap | [
"def",
"_catch",
"(",
"f",
",",
"exception_type",
")",
":",
"if",
"not",
"(",
"inspect",
".",
"isclass",
"(",
"exception_type",
")",
"and",
"issubclass",
"(",
"exception_type",
",",
"Exception",
")",
")",
":",
"exception_type",
"=",
"Exception",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"except",
"exception_type",
"as",
"e",
":",
"# pylint: disable=broad-except",
"qj",
"(",
"e",
",",
"'Caught an exception in %s'",
"%",
"f",
",",
"d",
"=",
"1",
",",
"_depth",
"=",
"2",
")",
"return",
"wrap"
]
| Decorator to drop into the debugger if a function throws an exception. | [
"Decorator",
"to",
"drop",
"into",
"the",
"debugger",
"if",
"a",
"function",
"throws",
"an",
"exception",
"."
]
| 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L615-L627 | train |
iansf/qj | qj/qj.py | _annotate_fn_args | def _annotate_fn_args(stack, fn_opname, nargs, nkw=-1, consume_fn_name=True):
"""Add commas and equals as appropriate to function argument lists in the stack."""
kwarg_names = []
if nkw == -1:
if sys.version_info[0] < 3:
# Compute nkw and nargs from nargs for python 2.7
nargs, nkw = (nargs % 256, 2 * nargs // 256)
else:
if fn_opname == 'CALL_FUNCTION_KW':
if qj._DEBUG_QJ:
assert len(stack) and stack[-1].opname == 'LOAD_CONST'
if not len(stack) or stack[-1].opname != 'LOAD_CONST':
return
se = stack.pop()
kwarg_names = se.oparg_repr[::-1]
se.oparg_repr = ['']
nkw = len(kwarg_names)
nargs -= nkw
if qj._DEBUG_QJ:
assert nargs >= 0 and nkw > 0
else:
nkw = 0
for i in range(nkw):
se = stack.pop()
if se.stack_depth == 0 and (len(se.oparg_repr) == 0 or se.oparg_repr[0] == ''):
# Skip stack entries that don't have any effect on the stack
continue
if i % 2 == 1 and sys.version_info[0] < 3:
if qj._DEBUG_QJ:
assert se.opname == 'LOAD_CONST'
if se.opname == 'LOAD_CONST':
# kwargs are pairs of key=value in code
se.oparg_repr += ['=']
else:
pops = []
if se.opname.startswith('CALL_FUNCTION'):
_annotate_fn_args(stack[:], se.opname, se.oparg, -1, True)
pops = _collect_pops(stack, se.stack_depth - 1 if se.opname.startswith('CALL_FUNCTION') else 0, [], False)
if i > 1 and len(pops):
pops[-1].oparg_repr += [',']
if sys.version_info[0] >= 3:
target_se = pops[-1] if len(pops) else se
target_se.oparg_repr = [kwarg_names[i], '='] + target_se.oparg_repr
for i in range(nargs):
se = stack.pop()
if se.opname.startswith('CALL_FUNCTION'):
_annotate_fn_args(stack, se.opname, se.oparg, -1, True)
elif len(se.oparg_repr) and se.oparg_repr[0] in {']', '}', ')'}:
if (i > 0 or nkw > 0):
se.oparg_repr += [',']
else:
pops = _collect_pops(stack, se.stack_depth, [], False)
if (i > 0 or nkw > 0) and len(pops):
pops[-1].oparg_repr += [',']
if consume_fn_name:
_collect_pops(stack, -1, [], False) | python | def _annotate_fn_args(stack, fn_opname, nargs, nkw=-1, consume_fn_name=True):
"""Add commas and equals as appropriate to function argument lists in the stack."""
kwarg_names = []
if nkw == -1:
if sys.version_info[0] < 3:
# Compute nkw and nargs from nargs for python 2.7
nargs, nkw = (nargs % 256, 2 * nargs // 256)
else:
if fn_opname == 'CALL_FUNCTION_KW':
if qj._DEBUG_QJ:
assert len(stack) and stack[-1].opname == 'LOAD_CONST'
if not len(stack) or stack[-1].opname != 'LOAD_CONST':
return
se = stack.pop()
kwarg_names = se.oparg_repr[::-1]
se.oparg_repr = ['']
nkw = len(kwarg_names)
nargs -= nkw
if qj._DEBUG_QJ:
assert nargs >= 0 and nkw > 0
else:
nkw = 0
for i in range(nkw):
se = stack.pop()
if se.stack_depth == 0 and (len(se.oparg_repr) == 0 or se.oparg_repr[0] == ''):
# Skip stack entries that don't have any effect on the stack
continue
if i % 2 == 1 and sys.version_info[0] < 3:
if qj._DEBUG_QJ:
assert se.opname == 'LOAD_CONST'
if se.opname == 'LOAD_CONST':
# kwargs are pairs of key=value in code
se.oparg_repr += ['=']
else:
pops = []
if se.opname.startswith('CALL_FUNCTION'):
_annotate_fn_args(stack[:], se.opname, se.oparg, -1, True)
pops = _collect_pops(stack, se.stack_depth - 1 if se.opname.startswith('CALL_FUNCTION') else 0, [], False)
if i > 1 and len(pops):
pops[-1].oparg_repr += [',']
if sys.version_info[0] >= 3:
target_se = pops[-1] if len(pops) else se
target_se.oparg_repr = [kwarg_names[i], '='] + target_se.oparg_repr
for i in range(nargs):
se = stack.pop()
if se.opname.startswith('CALL_FUNCTION'):
_annotate_fn_args(stack, se.opname, se.oparg, -1, True)
elif len(se.oparg_repr) and se.oparg_repr[0] in {']', '}', ')'}:
if (i > 0 or nkw > 0):
se.oparg_repr += [',']
else:
pops = _collect_pops(stack, se.stack_depth, [], False)
if (i > 0 or nkw > 0) and len(pops):
pops[-1].oparg_repr += [',']
if consume_fn_name:
_collect_pops(stack, -1, [], False) | [
"def",
"_annotate_fn_args",
"(",
"stack",
",",
"fn_opname",
",",
"nargs",
",",
"nkw",
"=",
"-",
"1",
",",
"consume_fn_name",
"=",
"True",
")",
":",
"kwarg_names",
"=",
"[",
"]",
"if",
"nkw",
"==",
"-",
"1",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"# Compute nkw and nargs from nargs for python 2.7",
"nargs",
",",
"nkw",
"=",
"(",
"nargs",
"%",
"256",
",",
"2",
"*",
"nargs",
"//",
"256",
")",
"else",
":",
"if",
"fn_opname",
"==",
"'CALL_FUNCTION_KW'",
":",
"if",
"qj",
".",
"_DEBUG_QJ",
":",
"assert",
"len",
"(",
"stack",
")",
"and",
"stack",
"[",
"-",
"1",
"]",
".",
"opname",
"==",
"'LOAD_CONST'",
"if",
"not",
"len",
"(",
"stack",
")",
"or",
"stack",
"[",
"-",
"1",
"]",
".",
"opname",
"!=",
"'LOAD_CONST'",
":",
"return",
"se",
"=",
"stack",
".",
"pop",
"(",
")",
"kwarg_names",
"=",
"se",
".",
"oparg_repr",
"[",
":",
":",
"-",
"1",
"]",
"se",
".",
"oparg_repr",
"=",
"[",
"''",
"]",
"nkw",
"=",
"len",
"(",
"kwarg_names",
")",
"nargs",
"-=",
"nkw",
"if",
"qj",
".",
"_DEBUG_QJ",
":",
"assert",
"nargs",
">=",
"0",
"and",
"nkw",
">",
"0",
"else",
":",
"nkw",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"nkw",
")",
":",
"se",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"se",
".",
"stack_depth",
"==",
"0",
"and",
"(",
"len",
"(",
"se",
".",
"oparg_repr",
")",
"==",
"0",
"or",
"se",
".",
"oparg_repr",
"[",
"0",
"]",
"==",
"''",
")",
":",
"# Skip stack entries that don't have any effect on the stack",
"continue",
"if",
"i",
"%",
"2",
"==",
"1",
"and",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"if",
"qj",
".",
"_DEBUG_QJ",
":",
"assert",
"se",
".",
"opname",
"==",
"'LOAD_CONST'",
"if",
"se",
".",
"opname",
"==",
"'LOAD_CONST'",
":",
"# kwargs are pairs of key=value in code",
"se",
".",
"oparg_repr",
"+=",
"[",
"'='",
"]",
"else",
":",
"pops",
"=",
"[",
"]",
"if",
"se",
".",
"opname",
".",
"startswith",
"(",
"'CALL_FUNCTION'",
")",
":",
"_annotate_fn_args",
"(",
"stack",
"[",
":",
"]",
",",
"se",
".",
"opname",
",",
"se",
".",
"oparg",
",",
"-",
"1",
",",
"True",
")",
"pops",
"=",
"_collect_pops",
"(",
"stack",
",",
"se",
".",
"stack_depth",
"-",
"1",
"if",
"se",
".",
"opname",
".",
"startswith",
"(",
"'CALL_FUNCTION'",
")",
"else",
"0",
",",
"[",
"]",
",",
"False",
")",
"if",
"i",
">",
"1",
"and",
"len",
"(",
"pops",
")",
":",
"pops",
"[",
"-",
"1",
"]",
".",
"oparg_repr",
"+=",
"[",
"','",
"]",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">=",
"3",
":",
"target_se",
"=",
"pops",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"pops",
")",
"else",
"se",
"target_se",
".",
"oparg_repr",
"=",
"[",
"kwarg_names",
"[",
"i",
"]",
",",
"'='",
"]",
"+",
"target_se",
".",
"oparg_repr",
"for",
"i",
"in",
"range",
"(",
"nargs",
")",
":",
"se",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"se",
".",
"opname",
".",
"startswith",
"(",
"'CALL_FUNCTION'",
")",
":",
"_annotate_fn_args",
"(",
"stack",
",",
"se",
".",
"opname",
",",
"se",
".",
"oparg",
",",
"-",
"1",
",",
"True",
")",
"elif",
"len",
"(",
"se",
".",
"oparg_repr",
")",
"and",
"se",
".",
"oparg_repr",
"[",
"0",
"]",
"in",
"{",
"']'",
",",
"'}'",
",",
"')'",
"}",
":",
"if",
"(",
"i",
">",
"0",
"or",
"nkw",
">",
"0",
")",
":",
"se",
".",
"oparg_repr",
"+=",
"[",
"','",
"]",
"else",
":",
"pops",
"=",
"_collect_pops",
"(",
"stack",
",",
"se",
".",
"stack_depth",
",",
"[",
"]",
",",
"False",
")",
"if",
"(",
"i",
">",
"0",
"or",
"nkw",
">",
"0",
")",
"and",
"len",
"(",
"pops",
")",
":",
"pops",
"[",
"-",
"1",
"]",
".",
"oparg_repr",
"+=",
"[",
"','",
"]",
"if",
"consume_fn_name",
":",
"_collect_pops",
"(",
"stack",
",",
"-",
"1",
",",
"[",
"]",
",",
"False",
")"
]
| Add commas and equals as appropriate to function argument lists in the stack. | [
"Add",
"commas",
"and",
"equals",
"as",
"appropriate",
"to",
"function",
"argument",
"lists",
"in",
"the",
"stack",
"."
]
| 179864c62ed5d2d8a11b4e8c95328f68953cfa16 | https://github.com/iansf/qj/blob/179864c62ed5d2d8a11b4e8c95328f68953cfa16/qj/qj.py#L1299-L1357 | train |
Genida/archan | src/archan/plugins/checkers.py | CompleteMediation.generate_mediation_matrix | def generate_mediation_matrix(dsm):
"""
Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module has optional dependencies to itself.
- Framework has optional dependency to all framework items (-1),
and to nothing else.
- Core libraries have dependencies to framework.
Dependencies to other core libraries are tolerated.
- Application libraries have dependencies to framework.
Dependencies to other core or application libraries are tolerated.
No dependencies to application modules.
- Application modules have dependencies to framework and libraries.
Dependencies to other application modules
should be mediated over a broker.
Dependencies to data are tolerated.
- Data have no dependencies at all
(but framework/libraries would be tolerated).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to generate
the mediation matrix for.
"""
cat = dsm.categories
ent = dsm.entities
size = dsm.size[0]
if not cat:
cat = ['appmodule'] * size
packages = [e.split('.')[0] for e in ent]
# define and initialize the mediation matrix
mediation_matrix = [[0 for _ in range(size)]
for _ in range(size)]
for i in range(0, size):
for j in range(0, size):
if cat[i] == 'framework':
if cat[j] == 'framework':
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'corelib':
if (cat[j] in ('framework', 'corelib') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'applib':
if (cat[j] in ('framework', 'corelib', 'applib') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'appmodule':
# we cannot force an app module to import things from
# the broker if the broker itself did not import anything
if (cat[j] in ('framework', 'corelib',
'applib', 'broker', 'data') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'broker':
# we cannot force the broker to import things from
# app modules if there is nothing to be imported.
# also broker should be authorized to use third apps
if (cat[j] in (
'appmodule', 'corelib', 'framework') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'data':
if (cat[j] == 'framework' or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
else:
# mediation_matrix[i][j] = -2 # errors in the generation
raise DesignStructureMatrixError(
'Mediation matrix value NOT generated for %s:%s' % (
i, j))
return mediation_matrix | python | def generate_mediation_matrix(dsm):
"""
Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module has optional dependencies to itself.
- Framework has optional dependency to all framework items (-1),
and to nothing else.
- Core libraries have dependencies to framework.
Dependencies to other core libraries are tolerated.
- Application libraries have dependencies to framework.
Dependencies to other core or application libraries are tolerated.
No dependencies to application modules.
- Application modules have dependencies to framework and libraries.
Dependencies to other application modules
should be mediated over a broker.
Dependencies to data are tolerated.
- Data have no dependencies at all
(but framework/libraries would be tolerated).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to generate
the mediation matrix for.
"""
cat = dsm.categories
ent = dsm.entities
size = dsm.size[0]
if not cat:
cat = ['appmodule'] * size
packages = [e.split('.')[0] for e in ent]
# define and initialize the mediation matrix
mediation_matrix = [[0 for _ in range(size)]
for _ in range(size)]
for i in range(0, size):
for j in range(0, size):
if cat[i] == 'framework':
if cat[j] == 'framework':
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'corelib':
if (cat[j] in ('framework', 'corelib') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'applib':
if (cat[j] in ('framework', 'corelib', 'applib') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'appmodule':
# we cannot force an app module to import things from
# the broker if the broker itself did not import anything
if (cat[j] in ('framework', 'corelib',
'applib', 'broker', 'data') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'broker':
# we cannot force the broker to import things from
# app modules if there is nothing to be imported.
# also broker should be authorized to use third apps
if (cat[j] in (
'appmodule', 'corelib', 'framework') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'data':
if (cat[j] == 'framework' or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
else:
# mediation_matrix[i][j] = -2 # errors in the generation
raise DesignStructureMatrixError(
'Mediation matrix value NOT generated for %s:%s' % (
i, j))
return mediation_matrix | [
"def",
"generate_mediation_matrix",
"(",
"dsm",
")",
":",
"cat",
"=",
"dsm",
".",
"categories",
"ent",
"=",
"dsm",
".",
"entities",
"size",
"=",
"dsm",
".",
"size",
"[",
"0",
"]",
"if",
"not",
"cat",
":",
"cat",
"=",
"[",
"'appmodule'",
"]",
"*",
"size",
"packages",
"=",
"[",
"e",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"for",
"e",
"in",
"ent",
"]",
"# define and initialize the mediation matrix",
"mediation_matrix",
"=",
"[",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"size",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"size",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"if",
"cat",
"[",
"i",
"]",
"==",
"'framework'",
":",
"if",
"cat",
"[",
"j",
"]",
"==",
"'framework'",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"-",
"1",
"else",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"elif",
"cat",
"[",
"i",
"]",
"==",
"'corelib'",
":",
"if",
"(",
"cat",
"[",
"j",
"]",
"in",
"(",
"'framework'",
",",
"'corelib'",
")",
"or",
"ent",
"[",
"i",
"]",
".",
"startswith",
"(",
"packages",
"[",
"j",
"]",
"+",
"'.'",
")",
"or",
"i",
"==",
"j",
")",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"-",
"1",
"else",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"elif",
"cat",
"[",
"i",
"]",
"==",
"'applib'",
":",
"if",
"(",
"cat",
"[",
"j",
"]",
"in",
"(",
"'framework'",
",",
"'corelib'",
",",
"'applib'",
")",
"or",
"ent",
"[",
"i",
"]",
".",
"startswith",
"(",
"packages",
"[",
"j",
"]",
"+",
"'.'",
")",
"or",
"i",
"==",
"j",
")",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"-",
"1",
"else",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"elif",
"cat",
"[",
"i",
"]",
"==",
"'appmodule'",
":",
"# we cannot force an app module to import things from",
"# the broker if the broker itself did not import anything",
"if",
"(",
"cat",
"[",
"j",
"]",
"in",
"(",
"'framework'",
",",
"'corelib'",
",",
"'applib'",
",",
"'broker'",
",",
"'data'",
")",
"or",
"ent",
"[",
"i",
"]",
".",
"startswith",
"(",
"packages",
"[",
"j",
"]",
"+",
"'.'",
")",
"or",
"i",
"==",
"j",
")",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"-",
"1",
"else",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"elif",
"cat",
"[",
"i",
"]",
"==",
"'broker'",
":",
"# we cannot force the broker to import things from",
"# app modules if there is nothing to be imported.",
"# also broker should be authorized to use third apps",
"if",
"(",
"cat",
"[",
"j",
"]",
"in",
"(",
"'appmodule'",
",",
"'corelib'",
",",
"'framework'",
")",
"or",
"ent",
"[",
"i",
"]",
".",
"startswith",
"(",
"packages",
"[",
"j",
"]",
"+",
"'.'",
")",
"or",
"i",
"==",
"j",
")",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"-",
"1",
"else",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"elif",
"cat",
"[",
"i",
"]",
"==",
"'data'",
":",
"if",
"(",
"cat",
"[",
"j",
"]",
"==",
"'framework'",
"or",
"i",
"==",
"j",
")",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"-",
"1",
"else",
":",
"mediation_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"0",
"else",
":",
"# mediation_matrix[i][j] = -2 # errors in the generation",
"raise",
"DesignStructureMatrixError",
"(",
"'Mediation matrix value NOT generated for %s:%s'",
"%",
"(",
"i",
",",
"j",
")",
")",
"return",
"mediation_matrix"
]
| Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module has optional dependencies to itself.
- Framework has optional dependency to all framework items (-1),
and to nothing else.
- Core libraries have dependencies to framework.
Dependencies to other core libraries are tolerated.
- Application libraries have dependencies to framework.
Dependencies to other core or application libraries are tolerated.
No dependencies to application modules.
- Application modules have dependencies to framework and libraries.
Dependencies to other application modules
should be mediated over a broker.
Dependencies to data are tolerated.
- Data have no dependencies at all
(but framework/libraries would be tolerated).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to generate
the mediation matrix for. | [
"Generate",
"the",
"mediation",
"matrix",
"of",
"the",
"given",
"matrix",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L30-L127 | train |
Genida/archan | src/archan/plugins/checkers.py | EconomyOfMechanism.check | def check(self, dsm, simplicity_factor=2, **kwargs):
"""
Check economy of mechanism.
As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
simplicity_factor (int): simplicity factor.
Returns:
bool: True if economic, else False
"""
# economy_of_mechanism
economy_of_mechanism = False
message = ''
data = dsm.data
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = ['appmodule'] * dsm_size
dependency_number = 0
# evaluate Matrix(data)
for i in range(0, dsm_size):
for j in range(0, dsm_size):
if (categories[i] not in ('framework', 'corelib') and
categories[j] not in ('framework', 'corelib') and
data[i][j] > 0):
dependency_number += 1
# check comparison result
if dependency_number < dsm_size * simplicity_factor:
economy_of_mechanism = True
else:
message = ' '.join([
'Number of dependencies (%s)' % dependency_number,
'> number of rows (%s)' % dsm_size,
'* simplicity factor (%s) = %s' % (
simplicity_factor, dsm_size * simplicity_factor)])
return economy_of_mechanism, message | python | def check(self, dsm, simplicity_factor=2, **kwargs):
"""
Check economy of mechanism.
As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
simplicity_factor (int): simplicity factor.
Returns:
bool: True if economic, else False
"""
# economy_of_mechanism
economy_of_mechanism = False
message = ''
data = dsm.data
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = ['appmodule'] * dsm_size
dependency_number = 0
# evaluate Matrix(data)
for i in range(0, dsm_size):
for j in range(0, dsm_size):
if (categories[i] not in ('framework', 'corelib') and
categories[j] not in ('framework', 'corelib') and
data[i][j] > 0):
dependency_number += 1
# check comparison result
if dependency_number < dsm_size * simplicity_factor:
economy_of_mechanism = True
else:
message = ' '.join([
'Number of dependencies (%s)' % dependency_number,
'> number of rows (%s)' % dsm_size,
'* simplicity factor (%s) = %s' % (
simplicity_factor, dsm_size * simplicity_factor)])
return economy_of_mechanism, message | [
"def",
"check",
"(",
"self",
",",
"dsm",
",",
"simplicity_factor",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"# economy_of_mechanism",
"economy_of_mechanism",
"=",
"False",
"message",
"=",
"''",
"data",
"=",
"dsm",
".",
"data",
"categories",
"=",
"dsm",
".",
"categories",
"dsm_size",
"=",
"dsm",
".",
"size",
"[",
"0",
"]",
"if",
"not",
"categories",
":",
"categories",
"=",
"[",
"'appmodule'",
"]",
"*",
"dsm_size",
"dependency_number",
"=",
"0",
"# evaluate Matrix(data)",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"dsm_size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"dsm_size",
")",
":",
"if",
"(",
"categories",
"[",
"i",
"]",
"not",
"in",
"(",
"'framework'",
",",
"'corelib'",
")",
"and",
"categories",
"[",
"j",
"]",
"not",
"in",
"(",
"'framework'",
",",
"'corelib'",
")",
"and",
"data",
"[",
"i",
"]",
"[",
"j",
"]",
">",
"0",
")",
":",
"dependency_number",
"+=",
"1",
"# check comparison result",
"if",
"dependency_number",
"<",
"dsm_size",
"*",
"simplicity_factor",
":",
"economy_of_mechanism",
"=",
"True",
"else",
":",
"message",
"=",
"' '",
".",
"join",
"(",
"[",
"'Number of dependencies (%s)'",
"%",
"dependency_number",
",",
"'> number of rows (%s)'",
"%",
"dsm_size",
",",
"'* simplicity factor (%s) = %s'",
"%",
"(",
"simplicity_factor",
",",
"dsm_size",
"*",
"simplicity_factor",
")",
"]",
")",
"return",
"economy_of_mechanism",
",",
"message"
]
| Check economy of mechanism.
As first abstraction, number of dependencies between two modules
< 2 * the number of modules
(dependencies to the framework are NOT considered).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
simplicity_factor (int): simplicity factor.
Returns:
bool: True if economic, else False | [
"Check",
"economy",
"of",
"mechanism",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L216-L258 | train |
Genida/archan | src/archan/plugins/checkers.py | LeastCommonMechanism.check | def check(self, dsm, independence_factor=5, **kwargs):
"""
Check least common mechanism.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
independence_factor (int): if the maximum dependencies for one
module is inferior or equal to the DSM size divided by the
independence factor, then this criterion is verified.
Returns:
bool: True if least common mechanism, else False
"""
# leastCommonMechanismMatrix
least_common_mechanism = False
message = ''
# get the list of dependent modules for each module
data = dsm.data
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = ['appmodule'] * dsm_size
dependent_module_number = []
# evaluate Matrix(data)
for j in range(0, dsm_size):
dependent_module_number.append(0)
for i in range(0, dsm_size):
if (categories[i] != 'framework' and
categories[j] != 'framework' and
data[i][j] > 0):
dependent_module_number[j] += 1
# except for the broker if any and libs, check that threshold is not
# overlapped
# index of brokers
# and app_libs are set to 0
for index, item in enumerate(dsm.categories):
if item == 'broker' or item == 'applib':
dependent_module_number[index] = 0
if max(dependent_module_number) <= dsm_size / independence_factor:
least_common_mechanism = True
else:
maximum = max(dependent_module_number)
message = (
'Dependencies to %s (%s) > matrix size (%s) / '
'independence factor (%s) = %s' % (
dsm.entities[dependent_module_number.index(maximum)],
maximum, dsm_size, independence_factor,
dsm_size / independence_factor))
return least_common_mechanism, message | python | def check(self, dsm, independence_factor=5, **kwargs):
"""
Check least common mechanism.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
independence_factor (int): if the maximum dependencies for one
module is inferior or equal to the DSM size divided by the
independence factor, then this criterion is verified.
Returns:
bool: True if least common mechanism, else False
"""
# leastCommonMechanismMatrix
least_common_mechanism = False
message = ''
# get the list of dependent modules for each module
data = dsm.data
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = ['appmodule'] * dsm_size
dependent_module_number = []
# evaluate Matrix(data)
for j in range(0, dsm_size):
dependent_module_number.append(0)
for i in range(0, dsm_size):
if (categories[i] != 'framework' and
categories[j] != 'framework' and
data[i][j] > 0):
dependent_module_number[j] += 1
# except for the broker if any and libs, check that threshold is not
# overlapped
# index of brokers
# and app_libs are set to 0
for index, item in enumerate(dsm.categories):
if item == 'broker' or item == 'applib':
dependent_module_number[index] = 0
if max(dependent_module_number) <= dsm_size / independence_factor:
least_common_mechanism = True
else:
maximum = max(dependent_module_number)
message = (
'Dependencies to %s (%s) > matrix size (%s) / '
'independence factor (%s) = %s' % (
dsm.entities[dependent_module_number.index(maximum)],
maximum, dsm_size, independence_factor,
dsm_size / independence_factor))
return least_common_mechanism, message | [
"def",
"check",
"(",
"self",
",",
"dsm",
",",
"independence_factor",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
":",
"# leastCommonMechanismMatrix",
"least_common_mechanism",
"=",
"False",
"message",
"=",
"''",
"# get the list of dependent modules for each module",
"data",
"=",
"dsm",
".",
"data",
"categories",
"=",
"dsm",
".",
"categories",
"dsm_size",
"=",
"dsm",
".",
"size",
"[",
"0",
"]",
"if",
"not",
"categories",
":",
"categories",
"=",
"[",
"'appmodule'",
"]",
"*",
"dsm_size",
"dependent_module_number",
"=",
"[",
"]",
"# evaluate Matrix(data)",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"dsm_size",
")",
":",
"dependent_module_number",
".",
"append",
"(",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"dsm_size",
")",
":",
"if",
"(",
"categories",
"[",
"i",
"]",
"!=",
"'framework'",
"and",
"categories",
"[",
"j",
"]",
"!=",
"'framework'",
"and",
"data",
"[",
"i",
"]",
"[",
"j",
"]",
">",
"0",
")",
":",
"dependent_module_number",
"[",
"j",
"]",
"+=",
"1",
"# except for the broker if any and libs, check that threshold is not",
"# overlapped",
"# index of brokers",
"# and app_libs are set to 0",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"dsm",
".",
"categories",
")",
":",
"if",
"item",
"==",
"'broker'",
"or",
"item",
"==",
"'applib'",
":",
"dependent_module_number",
"[",
"index",
"]",
"=",
"0",
"if",
"max",
"(",
"dependent_module_number",
")",
"<=",
"dsm_size",
"/",
"independence_factor",
":",
"least_common_mechanism",
"=",
"True",
"else",
":",
"maximum",
"=",
"max",
"(",
"dependent_module_number",
")",
"message",
"=",
"(",
"'Dependencies to %s (%s) > matrix size (%s) / '",
"'independence factor (%s) = %s'",
"%",
"(",
"dsm",
".",
"entities",
"[",
"dependent_module_number",
".",
"index",
"(",
"maximum",
")",
"]",
",",
"maximum",
",",
"dsm_size",
",",
"independence_factor",
",",
"dsm_size",
"/",
"independence_factor",
")",
")",
"return",
"least_common_mechanism",
",",
"message"
]
| Check least common mechanism.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
independence_factor (int): if the maximum dependencies for one
module is inferior or equal to the DSM size divided by the
independence factor, then this criterion is verified.
Returns:
bool: True if least common mechanism, else False | [
"Check",
"least",
"common",
"mechanism",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L340-L391 | train |
Genida/archan | src/archan/plugins/checkers.py | LayeredArchitecture.check | def check(self, dsm, **kwargs):
"""
Check layered architecture.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if layered architecture else False, messages
"""
layered_architecture = True
messages = []
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = ['appmodule'] * dsm_size
for i in range(0, dsm_size - 1):
for j in range(i + 1, dsm_size):
if (categories[i] != 'broker' and
categories[j] != 'broker' and
dsm.entities[i].split('.')[0] != dsm.entities[j].split('.')[0]): # noqa
if dsm.data[i][j] > 0:
layered_architecture = False
messages.append(
'Dependency from %s to %s breaks the '
'layered architecture.' % (
dsm.entities[i], dsm.entities[j]))
return layered_architecture, '\n'.join(messages) | python | def check(self, dsm, **kwargs):
"""
Check layered architecture.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if layered architecture else False, messages
"""
layered_architecture = True
messages = []
categories = dsm.categories
dsm_size = dsm.size[0]
if not categories:
categories = ['appmodule'] * dsm_size
for i in range(0, dsm_size - 1):
for j in range(i + 1, dsm_size):
if (categories[i] != 'broker' and
categories[j] != 'broker' and
dsm.entities[i].split('.')[0] != dsm.entities[j].split('.')[0]): # noqa
if dsm.data[i][j] > 0:
layered_architecture = False
messages.append(
'Dependency from %s to %s breaks the '
'layered architecture.' % (
dsm.entities[i], dsm.entities[j]))
return layered_architecture, '\n'.join(messages) | [
"def",
"check",
"(",
"self",
",",
"dsm",
",",
"*",
"*",
"kwargs",
")",
":",
"layered_architecture",
"=",
"True",
"messages",
"=",
"[",
"]",
"categories",
"=",
"dsm",
".",
"categories",
"dsm_size",
"=",
"dsm",
".",
"size",
"[",
"0",
"]",
"if",
"not",
"categories",
":",
"categories",
"=",
"[",
"'appmodule'",
"]",
"*",
"dsm_size",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"dsm_size",
"-",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"dsm_size",
")",
":",
"if",
"(",
"categories",
"[",
"i",
"]",
"!=",
"'broker'",
"and",
"categories",
"[",
"j",
"]",
"!=",
"'broker'",
"and",
"dsm",
".",
"entities",
"[",
"i",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"!=",
"dsm",
".",
"entities",
"[",
"j",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
":",
"# noqa",
"if",
"dsm",
".",
"data",
"[",
"i",
"]",
"[",
"j",
"]",
">",
"0",
":",
"layered_architecture",
"=",
"False",
"messages",
".",
"append",
"(",
"'Dependency from %s to %s breaks the '",
"'layered architecture.'",
"%",
"(",
"dsm",
".",
"entities",
"[",
"i",
"]",
",",
"dsm",
".",
"entities",
"[",
"j",
"]",
")",
")",
"return",
"layered_architecture",
",",
"'\\n'",
".",
"join",
"(",
"messages",
")"
]
| Check layered architecture.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if layered architecture else False, messages | [
"Check",
"layered",
"architecture",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L414-L444 | train |
Genida/archan | src/archan/plugins/checkers.py | CodeClean.check | def check(self, dsm, **kwargs):
"""
Check code clean.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if code clean else False, messages
"""
logger.debug('Entities = %s' % dsm.entities)
messages = []
code_clean = True
threshold = kwargs.pop('threshold', 1)
rows, _ = dsm.size
for i in range(0, rows):
if dsm.data[i][0] > threshold:
messages.append(
'Number of issues (%d) in module %s '
'> threshold (%d)' % (
dsm.data[i][0], dsm.entities[i], threshold))
code_clean = False
return code_clean, '\n'.join(messages) | python | def check(self, dsm, **kwargs):
"""
Check code clean.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if code clean else False, messages
"""
logger.debug('Entities = %s' % dsm.entities)
messages = []
code_clean = True
threshold = kwargs.pop('threshold', 1)
rows, _ = dsm.size
for i in range(0, rows):
if dsm.data[i][0] > threshold:
messages.append(
'Number of issues (%d) in module %s '
'> threshold (%d)' % (
dsm.data[i][0], dsm.entities[i], threshold))
code_clean = False
return code_clean, '\n'.join(messages) | [
"def",
"check",
"(",
"self",
",",
"dsm",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Entities = %s'",
"%",
"dsm",
".",
"entities",
")",
"messages",
"=",
"[",
"]",
"code_clean",
"=",
"True",
"threshold",
"=",
"kwargs",
".",
"pop",
"(",
"'threshold'",
",",
"1",
")",
"rows",
",",
"_",
"=",
"dsm",
".",
"size",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"rows",
")",
":",
"if",
"dsm",
".",
"data",
"[",
"i",
"]",
"[",
"0",
"]",
">",
"threshold",
":",
"messages",
".",
"append",
"(",
"'Number of issues (%d) in module %s '",
"'> threshold (%d)'",
"%",
"(",
"dsm",
".",
"data",
"[",
"i",
"]",
"[",
"0",
"]",
",",
"dsm",
".",
"entities",
"[",
"i",
"]",
",",
"threshold",
")",
")",
"code_clean",
"=",
"False",
"return",
"code_clean",
",",
"'\\n'",
".",
"join",
"(",
"messages",
")"
]
| Check code clean.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if code clean else False, messages | [
"Check",
"code",
"clean",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L468-L491 | train |
tjcsl/cslbot | cslbot/commands/timeuntil.py | cmd | def cmd(send, msg, args):
"""Reports the difference between now and some specified time.
Syntax: {command} <time>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('date', nargs='*', action=arguments.DateParser)
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if not cmdargs.date:
send("Time until when?")
return
delta = dateutil.relativedelta.relativedelta(cmdargs.date, datetime.datetime.now())
diff = "%s is " % cmdargs.date.strftime("%x")
if delta.years:
diff += "%d years " % (delta.years)
if delta.months:
diff += "%d months " % (delta.months)
if delta.days:
diff += "%d days " % (delta.days)
if delta.hours:
diff += "%d hours " % (delta.hours)
if delta.minutes:
diff += "%d minutes " % (delta.minutes)
if delta.seconds:
diff += "%d seconds " % (delta.seconds)
diff += "away"
send(diff) | python | def cmd(send, msg, args):
"""Reports the difference between now and some specified time.
Syntax: {command} <time>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('date', nargs='*', action=arguments.DateParser)
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if not cmdargs.date:
send("Time until when?")
return
delta = dateutil.relativedelta.relativedelta(cmdargs.date, datetime.datetime.now())
diff = "%s is " % cmdargs.date.strftime("%x")
if delta.years:
diff += "%d years " % (delta.years)
if delta.months:
diff += "%d months " % (delta.months)
if delta.days:
diff += "%d days " % (delta.days)
if delta.hours:
diff += "%d hours " % (delta.hours)
if delta.minutes:
diff += "%d minutes " % (delta.minutes)
if delta.seconds:
diff += "%d seconds " % (delta.seconds)
diff += "away"
send(diff) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'date'",
",",
"nargs",
"=",
"'*'",
",",
"action",
"=",
"arguments",
".",
"DateParser",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"if",
"not",
"cmdargs",
".",
"date",
":",
"send",
"(",
"\"Time until when?\"",
")",
"return",
"delta",
"=",
"dateutil",
".",
"relativedelta",
".",
"relativedelta",
"(",
"cmdargs",
".",
"date",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"diff",
"=",
"\"%s is \"",
"%",
"cmdargs",
".",
"date",
".",
"strftime",
"(",
"\"%x\"",
")",
"if",
"delta",
".",
"years",
":",
"diff",
"+=",
"\"%d years \"",
"%",
"(",
"delta",
".",
"years",
")",
"if",
"delta",
".",
"months",
":",
"diff",
"+=",
"\"%d months \"",
"%",
"(",
"delta",
".",
"months",
")",
"if",
"delta",
".",
"days",
":",
"diff",
"+=",
"\"%d days \"",
"%",
"(",
"delta",
".",
"days",
")",
"if",
"delta",
".",
"hours",
":",
"diff",
"+=",
"\"%d hours \"",
"%",
"(",
"delta",
".",
"hours",
")",
"if",
"delta",
".",
"minutes",
":",
"diff",
"+=",
"\"%d minutes \"",
"%",
"(",
"delta",
".",
"minutes",
")",
"if",
"delta",
".",
"seconds",
":",
"diff",
"+=",
"\"%d seconds \"",
"%",
"(",
"delta",
".",
"seconds",
")",
"diff",
"+=",
"\"away\"",
"send",
"(",
"diff",
")"
]
| Reports the difference between now and some specified time.
Syntax: {command} <time> | [
"Reports",
"the",
"difference",
"between",
"now",
"and",
"some",
"specified",
"time",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/timeuntil.py#L28-L59 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.