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 |
---|---|---|---|---|---|---|---|---|---|---|---|
acutesoftware/virtual-AI-simulator | vais/run.py | main | def main():
"""
test program for VAIS.
Generates several planets and populates with animals and plants.
Then places objects and tests the sequences.
"""
print("|---------------------------------------------------")
print("| Virtual AI Simulator")
print("|---------------------------------------------------")
print("| ")
print("| r = rebuild planets c = create character")
print("| s = simulation o = create opponent")
print("| q = quit b = battle characters")
print("| ")
planets = load_planet_list()
show_planet_shortlist(planets)
print("|---------------------------------------------------")
cmd = input('| Enter choice ?' )
if cmd == 'r':
rebuild_planet_samples()
elif cmd == 'q':
exit(0)
elif cmd < str(len(planets)+1) and cmd > '0':
fname = planets[int(cmd) - 1]['name'] + '.txt'
print('viewing planet ' + fname)
view_world.display_map(fldr + os.sep + fname)
elif cmd == 'c':
c1 = create_character()
elif cmd == 'o':
c2 = create_character()
elif cmd == 'b':
run_simulation(c1, c2)
elif cmd == 's':
print('not implemented')
else:
print('invalid command ' + cmd)
main() | python | def main():
"""
test program for VAIS.
Generates several planets and populates with animals and plants.
Then places objects and tests the sequences.
"""
print("|---------------------------------------------------")
print("| Virtual AI Simulator")
print("|---------------------------------------------------")
print("| ")
print("| r = rebuild planets c = create character")
print("| s = simulation o = create opponent")
print("| q = quit b = battle characters")
print("| ")
planets = load_planet_list()
show_planet_shortlist(planets)
print("|---------------------------------------------------")
cmd = input('| Enter choice ?' )
if cmd == 'r':
rebuild_planet_samples()
elif cmd == 'q':
exit(0)
elif cmd < str(len(planets)+1) and cmd > '0':
fname = planets[int(cmd) - 1]['name'] + '.txt'
print('viewing planet ' + fname)
view_world.display_map(fldr + os.sep + fname)
elif cmd == 'c':
c1 = create_character()
elif cmd == 'o':
c2 = create_character()
elif cmd == 'b':
run_simulation(c1, c2)
elif cmd == 's':
print('not implemented')
else:
print('invalid command ' + cmd)
main() | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"|---------------------------------------------------\"",
")",
"print",
"(",
"\"| Virtual AI Simulator\"",
")",
"print",
"(",
"\"|---------------------------------------------------\"",
")",
"print",
"(",
"\"| \"",
")",
"print",
"(",
"\"| r = rebuild planets c = create character\"",
")",
"print",
"(",
"\"| s = simulation o = create opponent\"",
")",
"print",
"(",
"\"| q = quit b = battle characters\"",
")",
"print",
"(",
"\"| \"",
")",
"planets",
"=",
"load_planet_list",
"(",
")",
"show_planet_shortlist",
"(",
"planets",
")",
"print",
"(",
"\"|---------------------------------------------------\"",
")",
"cmd",
"=",
"input",
"(",
"'| Enter choice ?'",
")",
"if",
"cmd",
"==",
"'r'",
":",
"rebuild_planet_samples",
"(",
")",
"elif",
"cmd",
"==",
"'q'",
":",
"exit",
"(",
"0",
")",
"elif",
"cmd",
"<",
"str",
"(",
"len",
"(",
"planets",
")",
"+",
"1",
")",
"and",
"cmd",
">",
"'0'",
":",
"fname",
"=",
"planets",
"[",
"int",
"(",
"cmd",
")",
"-",
"1",
"]",
"[",
"'name'",
"]",
"+",
"'.txt'",
"print",
"(",
"'viewing planet '",
"+",
"fname",
")",
"view_world",
".",
"display_map",
"(",
"fldr",
"+",
"os",
".",
"sep",
"+",
"fname",
")",
"elif",
"cmd",
"==",
"'c'",
":",
"c1",
"=",
"create_character",
"(",
")",
"elif",
"cmd",
"==",
"'o'",
":",
"c2",
"=",
"create_character",
"(",
")",
"elif",
"cmd",
"==",
"'b'",
":",
"run_simulation",
"(",
"c1",
",",
"c2",
")",
"elif",
"cmd",
"==",
"'s'",
":",
"print",
"(",
"'not implemented'",
")",
"else",
":",
"print",
"(",
"'invalid command '",
"+",
"cmd",
")",
"main",
"(",
")"
]
| test program for VAIS.
Generates several planets and populates with animals and plants.
Then places objects and tests the sequences. | [
"test",
"program",
"for",
"VAIS",
".",
"Generates",
"several",
"planets",
"and",
"populates",
"with",
"animals",
"and",
"plants",
".",
"Then",
"places",
"objects",
"and",
"tests",
"the",
"sequences",
"."
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L14-L51 | train |
acutesoftware/virtual-AI-simulator | vais/run.py | load_planet_list | def load_planet_list():
"""
load the list of prebuilt planets
"""
planet_list = []
with open(fldr + os.sep + 'planet_samples.csv') as f:
hdr = f.readline()
for line in f:
#print("Building ", line)
name, num_seeds, width, height, wind, rain, sun, lava = parse_planet_row(line)
planet_list.append({'name':name, 'num_seeds':num_seeds, 'width':width, 'height':height, 'wind':wind, 'rain':rain, 'sun':sun, 'lava':lava})
return planet_list | python | def load_planet_list():
"""
load the list of prebuilt planets
"""
planet_list = []
with open(fldr + os.sep + 'planet_samples.csv') as f:
hdr = f.readline()
for line in f:
#print("Building ", line)
name, num_seeds, width, height, wind, rain, sun, lava = parse_planet_row(line)
planet_list.append({'name':name, 'num_seeds':num_seeds, 'width':width, 'height':height, 'wind':wind, 'rain':rain, 'sun':sun, 'lava':lava})
return planet_list | [
"def",
"load_planet_list",
"(",
")",
":",
"planet_list",
"=",
"[",
"]",
"with",
"open",
"(",
"fldr",
"+",
"os",
".",
"sep",
"+",
"'planet_samples.csv'",
")",
"as",
"f",
":",
"hdr",
"=",
"f",
".",
"readline",
"(",
")",
"for",
"line",
"in",
"f",
":",
"#print(\"Building \", line)",
"name",
",",
"num_seeds",
",",
"width",
",",
"height",
",",
"wind",
",",
"rain",
",",
"sun",
",",
"lava",
"=",
"parse_planet_row",
"(",
"line",
")",
"planet_list",
".",
"append",
"(",
"{",
"'name'",
":",
"name",
",",
"'num_seeds'",
":",
"num_seeds",
",",
"'width'",
":",
"width",
",",
"'height'",
":",
"height",
",",
"'wind'",
":",
"wind",
",",
"'rain'",
":",
"rain",
",",
"'sun'",
":",
"sun",
",",
"'lava'",
":",
"lava",
"}",
")",
"return",
"planet_list"
]
| load the list of prebuilt planets | [
"load",
"the",
"list",
"of",
"prebuilt",
"planets"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L53-L64 | train |
acutesoftware/virtual-AI-simulator | vais/run.py | create_character | def create_character():
"""
create a random character
"""
traits = character.CharacterCollection(character.fldr)
c = traits.generate_random_character()
print(c)
return c | python | def create_character():
"""
create a random character
"""
traits = character.CharacterCollection(character.fldr)
c = traits.generate_random_character()
print(c)
return c | [
"def",
"create_character",
"(",
")",
":",
"traits",
"=",
"character",
".",
"CharacterCollection",
"(",
"character",
".",
"fldr",
")",
"c",
"=",
"traits",
".",
"generate_random_character",
"(",
")",
"print",
"(",
"c",
")",
"return",
"c"
]
| create a random character | [
"create",
"a",
"random",
"character"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L100-L107 | train |
acutesoftware/virtual-AI-simulator | vais/run.py | run_simulation | def run_simulation(c1, c2):
"""
using character and planet, run the simulation
"""
print('running simulation...')
traits = character.CharacterCollection(character.fldr)
c1 = traits.generate_random_character()
c2 = traits.generate_random_character()
print(c1)
print(c2)
rules = battle.BattleRules(battle.rules_file)
b = battle.Battle(c1, c2, traits, rules, print_console='Yes')
print(b.status) | python | def run_simulation(c1, c2):
"""
using character and planet, run the simulation
"""
print('running simulation...')
traits = character.CharacterCollection(character.fldr)
c1 = traits.generate_random_character()
c2 = traits.generate_random_character()
print(c1)
print(c2)
rules = battle.BattleRules(battle.rules_file)
b = battle.Battle(c1, c2, traits, rules, print_console='Yes')
print(b.status) | [
"def",
"run_simulation",
"(",
"c1",
",",
"c2",
")",
":",
"print",
"(",
"'running simulation...'",
")",
"traits",
"=",
"character",
".",
"CharacterCollection",
"(",
"character",
".",
"fldr",
")",
"c1",
"=",
"traits",
".",
"generate_random_character",
"(",
")",
"c2",
"=",
"traits",
".",
"generate_random_character",
"(",
")",
"print",
"(",
"c1",
")",
"print",
"(",
"c2",
")",
"rules",
"=",
"battle",
".",
"BattleRules",
"(",
"battle",
".",
"rules_file",
")",
"b",
"=",
"battle",
".",
"Battle",
"(",
"c1",
",",
"c2",
",",
"traits",
",",
"rules",
",",
"print_console",
"=",
"'Yes'",
")",
"print",
"(",
"b",
".",
"status",
")"
]
| using character and planet, run the simulation | [
"using",
"character",
"and",
"planet",
"run",
"the",
"simulation"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/run.py#L109-L121 | train |
jmbeach/KEP.py | src/keppy/tag.py | Tag.name_replace | def name_replace(self, to_replace, replacement):
"""Replaces part of tag name with new value"""
self.name = self.name.replace(to_replace, replacement) | python | def name_replace(self, to_replace, replacement):
"""Replaces part of tag name with new value"""
self.name = self.name.replace(to_replace, replacement) | [
"def",
"name_replace",
"(",
"self",
",",
"to_replace",
",",
"replacement",
")",
":",
"self",
".",
"name",
"=",
"self",
".",
"name",
".",
"replace",
"(",
"to_replace",
",",
"replacement",
")"
]
| Replaces part of tag name with new value | [
"Replaces",
"part",
"of",
"tag",
"name",
"with",
"new",
"value"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/tag.py#L31-L33 | train |
tjcsl/cslbot | cslbot/commands/seen.py | cmd | def cmd(send, msg, args):
"""When a nick was last seen.
Syntax: {command} <nick>
"""
if not msg:
send("Seen who?")
return
cmdchar, ctrlchan = args['config']['core']['cmdchar'], args['config']['core']['ctrlchan']
last = get_last(args['db'], cmdchar, ctrlchan, msg)
if last is None:
send("%s has never shown their face." % msg)
return
delta = datetime.now() - last.time
# We only need second-level precision.
delta -= delta % timedelta(seconds=1)
output = "%s was last seen %s ago " % (msg, delta)
if last.type == 'pubmsg' or last.type == 'privmsg':
output += 'saying "%s"' % last.msg
elif last.type == 'action':
output += 'doing "%s"' % last.msg
elif last.type == 'part':
output += 'leaving and saying "%s"' % last.msg
elif last.type == 'nick':
output += 'nicking to %s' % last.msg
elif last.type == 'quit':
output += 'quiting and saying "%s"' % last.msg
elif last.type == 'kick':
output += 'kicking %s for "%s"' % last.msg.split(',')
elif last.type == 'topic':
output += 'changing topic to %s' % last.msg
elif last.type in ['pubnotice', 'privnotice']:
output += 'sending notice %s' % last.msg
elif last.type == 'mode':
output += 'setting mode %s' % last.msg
else:
raise Exception("Invalid type.")
send(output) | python | def cmd(send, msg, args):
"""When a nick was last seen.
Syntax: {command} <nick>
"""
if not msg:
send("Seen who?")
return
cmdchar, ctrlchan = args['config']['core']['cmdchar'], args['config']['core']['ctrlchan']
last = get_last(args['db'], cmdchar, ctrlchan, msg)
if last is None:
send("%s has never shown their face." % msg)
return
delta = datetime.now() - last.time
# We only need second-level precision.
delta -= delta % timedelta(seconds=1)
output = "%s was last seen %s ago " % (msg, delta)
if last.type == 'pubmsg' or last.type == 'privmsg':
output += 'saying "%s"' % last.msg
elif last.type == 'action':
output += 'doing "%s"' % last.msg
elif last.type == 'part':
output += 'leaving and saying "%s"' % last.msg
elif last.type == 'nick':
output += 'nicking to %s' % last.msg
elif last.type == 'quit':
output += 'quiting and saying "%s"' % last.msg
elif last.type == 'kick':
output += 'kicking %s for "%s"' % last.msg.split(',')
elif last.type == 'topic':
output += 'changing topic to %s' % last.msg
elif last.type in ['pubnotice', 'privnotice']:
output += 'sending notice %s' % last.msg
elif last.type == 'mode':
output += 'setting mode %s' % last.msg
else:
raise Exception("Invalid type.")
send(output) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Seen who?\"",
")",
"return",
"cmdchar",
",",
"ctrlchan",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'cmdchar'",
"]",
",",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
"last",
"=",
"get_last",
"(",
"args",
"[",
"'db'",
"]",
",",
"cmdchar",
",",
"ctrlchan",
",",
"msg",
")",
"if",
"last",
"is",
"None",
":",
"send",
"(",
"\"%s has never shown their face.\"",
"%",
"msg",
")",
"return",
"delta",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"last",
".",
"time",
"# We only need second-level precision.",
"delta",
"-=",
"delta",
"%",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"output",
"=",
"\"%s was last seen %s ago \"",
"%",
"(",
"msg",
",",
"delta",
")",
"if",
"last",
".",
"type",
"==",
"'pubmsg'",
"or",
"last",
".",
"type",
"==",
"'privmsg'",
":",
"output",
"+=",
"'saying \"%s\"'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"==",
"'action'",
":",
"output",
"+=",
"'doing \"%s\"'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"==",
"'part'",
":",
"output",
"+=",
"'leaving and saying \"%s\"'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"==",
"'nick'",
":",
"output",
"+=",
"'nicking to %s'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"==",
"'quit'",
":",
"output",
"+=",
"'quiting and saying \"%s\"'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"==",
"'kick'",
":",
"output",
"+=",
"'kicking %s for \"%s\"'",
"%",
"last",
".",
"msg",
".",
"split",
"(",
"','",
")",
"elif",
"last",
".",
"type",
"==",
"'topic'",
":",
"output",
"+=",
"'changing topic to %s'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"in",
"[",
"'pubnotice'",
",",
"'privnotice'",
"]",
":",
"output",
"+=",
"'sending notice %s'",
"%",
"last",
".",
"msg",
"elif",
"last",
".",
"type",
"==",
"'mode'",
":",
"output",
"+=",
"'setting mode %s'",
"%",
"last",
".",
"msg",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid type.\"",
")",
"send",
"(",
"output",
")"
]
| When a nick was last seen.
Syntax: {command} <nick> | [
"When",
"a",
"nick",
"was",
"last",
"seen",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/seen.py#L31-L69 | train |
tjcsl/cslbot | cslbot/commands/morse.py | cmd | def cmd(send, msg, args):
"""Converts text to morse code.
Syntax: {command} [text]
"""
if not msg:
msg = gen_word()
morse = gen_morse(msg)
if len(morse) > 100:
send("Your morse is too long. Have you considered Western Union?")
else:
send(morse) | python | def cmd(send, msg, args):
"""Converts text to morse code.
Syntax: {command} [text]
"""
if not msg:
msg = gen_word()
morse = gen_morse(msg)
if len(morse) > 100:
send("Your morse is too long. Have you considered Western Union?")
else:
send(morse) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"msg",
"=",
"gen_word",
"(",
")",
"morse",
"=",
"gen_morse",
"(",
"msg",
")",
"if",
"len",
"(",
"morse",
")",
">",
"100",
":",
"send",
"(",
"\"Your morse is too long. Have you considered Western Union?\"",
")",
"else",
":",
"send",
"(",
"morse",
")"
]
| Converts text to morse code.
Syntax: {command} [text] | [
"Converts",
"text",
"to",
"morse",
"code",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/morse.py#L23-L35 | train |
marrow/util | marrow/util/text.py | ellipsis | def ellipsis(text, length, symbol="..."):
"""Present a block of text of given length.
If the length of available text exceeds the requested length, truncate and
intelligently append an ellipsis.
"""
if len(text) > length:
pos = text.rfind(" ", 0, length)
if pos < 0:
return text[:length].rstrip(".") + symbol
else:
return text[:pos].rstrip(".") + symbol
else:
return text | python | def ellipsis(text, length, symbol="..."):
"""Present a block of text of given length.
If the length of available text exceeds the requested length, truncate and
intelligently append an ellipsis.
"""
if len(text) > length:
pos = text.rfind(" ", 0, length)
if pos < 0:
return text[:length].rstrip(".") + symbol
else:
return text[:pos].rstrip(".") + symbol
else:
return text | [
"def",
"ellipsis",
"(",
"text",
",",
"length",
",",
"symbol",
"=",
"\"...\"",
")",
":",
"if",
"len",
"(",
"text",
")",
">",
"length",
":",
"pos",
"=",
"text",
".",
"rfind",
"(",
"\" \"",
",",
"0",
",",
"length",
")",
"if",
"pos",
"<",
"0",
":",
"return",
"text",
"[",
":",
"length",
"]",
".",
"rstrip",
"(",
"\".\"",
")",
"+",
"symbol",
"else",
":",
"return",
"text",
"[",
":",
"pos",
"]",
".",
"rstrip",
"(",
"\".\"",
")",
"+",
"symbol",
"else",
":",
"return",
"text"
]
| Present a block of text of given length.
If the length of available text exceeds the requested length, truncate and
intelligently append an ellipsis. | [
"Present",
"a",
"block",
"of",
"text",
"of",
"given",
"length",
".",
"If",
"the",
"length",
"of",
"available",
"text",
"exceeds",
"the",
"requested",
"length",
"truncate",
"and",
"intelligently",
"append",
"an",
"ellipsis",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/text.py#L26-L40 | train |
tjcsl/cslbot | cslbot/commands/repost.py | cmd | def cmd(send, msg, args):
"""Reposts a url.
Syntax: {command}
"""
result = args['db'].query(Urls).order_by(func.random()).first()
send("%s" % result.url) | python | def cmd(send, msg, args):
"""Reposts a url.
Syntax: {command}
"""
result = args['db'].query(Urls).order_by(func.random()).first()
send("%s" % result.url) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"result",
"=",
"args",
"[",
"'db'",
"]",
".",
"query",
"(",
"Urls",
")",
".",
"order_by",
"(",
"func",
".",
"random",
"(",
")",
")",
".",
"first",
"(",
")",
"send",
"(",
"\"%s\"",
"%",
"result",
".",
"url",
")"
]
| Reposts a url.
Syntax: {command} | [
"Reposts",
"a",
"url",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/repost.py#L25-L32 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/office.py | OfficeSerializer.get_elections | def get_elections(self, obj):
"""All elections on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = Election.objects.filter(
race__office=obj,
election_day=election_day
)
return ElectionSerializer(elections, many=True).data | python | def get_elections(self, obj):
"""All elections on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = Election.objects.filter(
race__office=obj,
election_day=election_day
)
return ElectionSerializer(elections, many=True).data | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"elections",
"=",
"Election",
".",
"objects",
".",
"filter",
"(",
"race__office",
"=",
"obj",
",",
"election_day",
"=",
"election_day",
")",
"return",
"ElectionSerializer",
"(",
"elections",
",",
"many",
"=",
"True",
")",
".",
"data"
]
| All elections on an election day. | [
"All",
"elections",
"on",
"an",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/office.py#L49-L57 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/office.py | OfficeSerializer.get_content | def get_content(self, obj):
"""All content for office's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
return PageContent.objects.office_content(election_day, obj) | python | def get_content(self, obj):
"""All content for office's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
return PageContent.objects.office_content(election_day, obj) | [
"def",
"get_content",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"return",
"PageContent",
".",
"objects",
".",
"office_content",
"(",
"election_day",
",",
"obj",
")"
]
| All content for office's page on an election day. | [
"All",
"content",
"for",
"office",
"s",
"page",
"on",
"an",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/office.py#L59-L63 | train |
tjcsl/cslbot | cslbot/commands/cancel.py | cmd | def cmd(send, msg, args):
"""Cancels a deferred action with the given id.
Syntax: {command} <id>
"""
try:
args['handler'].workers.cancel(int(msg))
except ValueError:
send("Index must be a digit.")
return
except KeyError:
send("No such event.")
return
send("Event canceled.") | python | def cmd(send, msg, args):
"""Cancels a deferred action with the given id.
Syntax: {command} <id>
"""
try:
args['handler'].workers.cancel(int(msg))
except ValueError:
send("Index must be a digit.")
return
except KeyError:
send("No such event.")
return
send("Event canceled.") | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"try",
":",
"args",
"[",
"'handler'",
"]",
".",
"workers",
".",
"cancel",
"(",
"int",
"(",
"msg",
")",
")",
"except",
"ValueError",
":",
"send",
"(",
"\"Index must be a digit.\"",
")",
"return",
"except",
"KeyError",
":",
"send",
"(",
"\"No such event.\"",
")",
"return",
"send",
"(",
"\"Event canceled.\"",
")"
]
| Cancels a deferred action with the given id.
Syntax: {command} <id> | [
"Cancels",
"a",
"deferred",
"action",
"with",
"the",
"given",
"id",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/cancel.py#L22-L36 | train |
tjcsl/cslbot | cslbot/commands/roman.py | cmd | def cmd(send, msg, _):
"""Convert a number to the roman numeral equivalent.
Syntax: {command} [number]
"""
if not msg:
msg = randrange(5000)
elif not msg.isdigit():
send("Invalid Number.")
return
send(gen_roman(int(msg))) | python | def cmd(send, msg, _):
"""Convert a number to the roman numeral equivalent.
Syntax: {command} [number]
"""
if not msg:
msg = randrange(5000)
elif not msg.isdigit():
send("Invalid Number.")
return
send(gen_roman(int(msg))) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"if",
"not",
"msg",
":",
"msg",
"=",
"randrange",
"(",
"5000",
")",
"elif",
"not",
"msg",
".",
"isdigit",
"(",
")",
":",
"send",
"(",
"\"Invalid Number.\"",
")",
"return",
"send",
"(",
"gen_roman",
"(",
"int",
"(",
"msg",
")",
")",
")"
]
| Convert a number to the roman numeral equivalent.
Syntax: {command} [number] | [
"Convert",
"a",
"number",
"to",
"the",
"roman",
"numeral",
"equivalent",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/roman.py#L42-L53 | train |
tjcsl/cslbot | cslbot/commands/kill.py | cmd | def cmd(send, msg, args):
"""Kills somebody.
Syntax: {command} <victim>
"""
if not msg:
send("kill who?")
return
if msg.lower() == args['botnick'].lower():
send('%s is not feeling suicidal right now.' % msg)
else:
send('Die, %s!' % msg) | python | def cmd(send, msg, args):
"""Kills somebody.
Syntax: {command} <victim>
"""
if not msg:
send("kill who?")
return
if msg.lower() == args['botnick'].lower():
send('%s is not feeling suicidal right now.' % msg)
else:
send('Die, %s!' % msg) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"kill who?\"",
")",
"return",
"if",
"msg",
".",
"lower",
"(",
")",
"==",
"args",
"[",
"'botnick'",
"]",
".",
"lower",
"(",
")",
":",
"send",
"(",
"'%s is not feeling suicidal right now.'",
"%",
"msg",
")",
"else",
":",
"send",
"(",
"'Die, %s!'",
"%",
"msg",
")"
]
| Kills somebody.
Syntax: {command} <victim> | [
"Kills",
"somebody",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/kill.py#L22-L34 | train |
tjcsl/cslbot | cslbot/commands/help.py | cmd | def cmd(send, msg, args):
"""Gives help.
Syntax: {command} [command]
"""
cmdchar = args['config']['core']['cmdchar']
if msg:
if msg.startswith(cmdchar):
msg = msg[len(cmdchar):]
if len(msg.split()) > 1:
send("One argument only")
elif not command_registry.is_registered(msg):
send("Not a module.")
else:
doc = command_registry.get_command(msg).get_doc()
if doc is None:
send("No documentation found.")
else:
for line in doc.splitlines():
send(line.format(command=cmdchar + msg), target=args['nick'])
else:
modules = sorted(command_registry.get_enabled_commands())
cmdlist = (' %s' % cmdchar).join(modules)
send('Commands: %s%s' % (cmdchar, cmdlist), target=args['nick'], ignore_length=True)
send('%shelp <command> for more info on a command.' % cmdchar, target=args['nick']) | python | def cmd(send, msg, args):
"""Gives help.
Syntax: {command} [command]
"""
cmdchar = args['config']['core']['cmdchar']
if msg:
if msg.startswith(cmdchar):
msg = msg[len(cmdchar):]
if len(msg.split()) > 1:
send("One argument only")
elif not command_registry.is_registered(msg):
send("Not a module.")
else:
doc = command_registry.get_command(msg).get_doc()
if doc is None:
send("No documentation found.")
else:
for line in doc.splitlines():
send(line.format(command=cmdchar + msg), target=args['nick'])
else:
modules = sorted(command_registry.get_enabled_commands())
cmdlist = (' %s' % cmdchar).join(modules)
send('Commands: %s%s' % (cmdchar, cmdlist), target=args['nick'], ignore_length=True)
send('%shelp <command> for more info on a command.' % cmdchar, target=args['nick']) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"cmdchar",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'cmdchar'",
"]",
"if",
"msg",
":",
"if",
"msg",
".",
"startswith",
"(",
"cmdchar",
")",
":",
"msg",
"=",
"msg",
"[",
"len",
"(",
"cmdchar",
")",
":",
"]",
"if",
"len",
"(",
"msg",
".",
"split",
"(",
")",
")",
">",
"1",
":",
"send",
"(",
"\"One argument only\"",
")",
"elif",
"not",
"command_registry",
".",
"is_registered",
"(",
"msg",
")",
":",
"send",
"(",
"\"Not a module.\"",
")",
"else",
":",
"doc",
"=",
"command_registry",
".",
"get_command",
"(",
"msg",
")",
".",
"get_doc",
"(",
")",
"if",
"doc",
"is",
"None",
":",
"send",
"(",
"\"No documentation found.\"",
")",
"else",
":",
"for",
"line",
"in",
"doc",
".",
"splitlines",
"(",
")",
":",
"send",
"(",
"line",
".",
"format",
"(",
"command",
"=",
"cmdchar",
"+",
"msg",
")",
",",
"target",
"=",
"args",
"[",
"'nick'",
"]",
")",
"else",
":",
"modules",
"=",
"sorted",
"(",
"command_registry",
".",
"get_enabled_commands",
"(",
")",
")",
"cmdlist",
"=",
"(",
"' %s'",
"%",
"cmdchar",
")",
".",
"join",
"(",
"modules",
")",
"send",
"(",
"'Commands: %s%s'",
"%",
"(",
"cmdchar",
",",
"cmdlist",
")",
",",
"target",
"=",
"args",
"[",
"'nick'",
"]",
",",
"ignore_length",
"=",
"True",
")",
"send",
"(",
"'%shelp <command> for more info on a command.'",
"%",
"cmdchar",
",",
"target",
"=",
"args",
"[",
"'nick'",
"]",
")"
]
| Gives help.
Syntax: {command} [command] | [
"Gives",
"help",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/help.py#L23-L48 | train |
mardix/Juice | juice/decorators.py | plugin | def plugin(module, *args, **kwargs):
"""
Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def my_view(self):
return {}
return MyExtension
# Your view.py
@plugin(my_ext)
class Index(View):
pass
:param module: object
:param args:
:param kwargs:
:return:
"""
def wrap(f):
m = module(f, *args, **kwargs)
if inspect.isclass(m):
for k, v in m.__dict__.items():
if not k.startswith("__"):
setattr(f, k, v)
elif inspect.isfunction(m):
setattr(f, kls.__name__, m)
return f
return wrap | python | def plugin(module, *args, **kwargs):
"""
Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def my_view(self):
return {}
return MyExtension
# Your view.py
@plugin(my_ext)
class Index(View):
pass
:param module: object
:param args:
:param kwargs:
:return:
"""
def wrap(f):
m = module(f, *args, **kwargs)
if inspect.isclass(m):
for k, v in m.__dict__.items():
if not k.startswith("__"):
setattr(f, k, v)
elif inspect.isfunction(m):
setattr(f, kls.__name__, m)
return f
return wrap | [
"def",
"plugin",
"(",
"module",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"m",
"=",
"module",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"inspect",
".",
"isclass",
"(",
"m",
")",
":",
"for",
"k",
",",
"v",
"in",
"m",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"\"__\"",
")",
":",
"setattr",
"(",
"f",
",",
"k",
",",
"v",
")",
"elif",
"inspect",
".",
"isfunction",
"(",
"m",
")",
":",
"setattr",
"(",
"f",
",",
"kls",
".",
"__name__",
",",
"m",
")",
"return",
"f",
"return",
"wrap"
]
| Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def my_view(self):
return {}
return MyExtension
# Your view.py
@plugin(my_ext)
class Index(View):
pass
:param module: object
:param args:
:param kwargs:
:return: | [
"Decorator",
"to",
"extend",
"a",
"package",
"to",
"a",
"view",
".",
"The",
"module",
"can",
"be",
"a",
"class",
"or",
"function",
".",
"It",
"will",
"copy",
"all",
"the",
"methods",
"to",
"the",
"class"
]
| 7afa8d4238868235dfcdae82272bd77958dd416a | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/decorators.py#L23-L56 | train |
mardix/Juice | juice/decorators.py | template | def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
:param layout: The layout to use for that view
:param kwargs:
get pass to the TEMPLATE_CONTEXT
** on method that return a dict
page or layout are optional
:param page: The html page
:param layout: The layout to use for that view
:param kwargs:
get pass to the view as k/V
** on other methods that return other type, it doesn't apply
:return:
"""
pkey = "_template_extends__"
def decorator(f):
if inspect.isclass(f):
layout_ = layout or page
extends = kwargs.pop("extends", None)
if extends and hasattr(extends, pkey):
items = getattr(extends, pkey).items()
if "layout" in items:
layout_ = items.pop("layout")
for k, v in items:
kwargs.setdefault(k, v)
if not layout_:
layout_ = "layout.html"
kwargs.setdefault("brand_name", "")
kwargs["layout"] = layout_
setattr(f, pkey, kwargs)
setattr(f, "base_layout", kwargs.get("layout"))
f.g(TEMPLATE_CONTEXT=kwargs)
return f
else:
@functools.wraps(f)
def wrap(*args2, **kwargs2):
response = f(*args2, **kwargs2)
if isinstance(response, dict) or response is None:
response = response or {}
if page:
response.setdefault("template_", page)
if layout:
response.setdefault("layout_", layout)
for k, v in kwargs.items():
response.setdefault(k, v)
return response
return wrap
return decorator | python | def template(page=None, layout=None, **kwargs):
"""
Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
:param layout: The layout to use for that view
:param kwargs:
get pass to the TEMPLATE_CONTEXT
** on method that return a dict
page or layout are optional
:param page: The html page
:param layout: The layout to use for that view
:param kwargs:
get pass to the view as k/V
** on other methods that return other type, it doesn't apply
:return:
"""
pkey = "_template_extends__"
def decorator(f):
if inspect.isclass(f):
layout_ = layout or page
extends = kwargs.pop("extends", None)
if extends and hasattr(extends, pkey):
items = getattr(extends, pkey).items()
if "layout" in items:
layout_ = items.pop("layout")
for k, v in items:
kwargs.setdefault(k, v)
if not layout_:
layout_ = "layout.html"
kwargs.setdefault("brand_name", "")
kwargs["layout"] = layout_
setattr(f, pkey, kwargs)
setattr(f, "base_layout", kwargs.get("layout"))
f.g(TEMPLATE_CONTEXT=kwargs)
return f
else:
@functools.wraps(f)
def wrap(*args2, **kwargs2):
response = f(*args2, **kwargs2)
if isinstance(response, dict) or response is None:
response = response or {}
if page:
response.setdefault("template_", page)
if layout:
response.setdefault("layout_", layout)
for k, v in kwargs.items():
response.setdefault(k, v)
return response
return wrap
return decorator | [
"def",
"template",
"(",
"page",
"=",
"None",
",",
"layout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pkey",
"=",
"\"_template_extends__\"",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"f",
")",
":",
"layout_",
"=",
"layout",
"or",
"page",
"extends",
"=",
"kwargs",
".",
"pop",
"(",
"\"extends\"",
",",
"None",
")",
"if",
"extends",
"and",
"hasattr",
"(",
"extends",
",",
"pkey",
")",
":",
"items",
"=",
"getattr",
"(",
"extends",
",",
"pkey",
")",
".",
"items",
"(",
")",
"if",
"\"layout\"",
"in",
"items",
":",
"layout_",
"=",
"items",
".",
"pop",
"(",
"\"layout\"",
")",
"for",
"k",
",",
"v",
"in",
"items",
":",
"kwargs",
".",
"setdefault",
"(",
"k",
",",
"v",
")",
"if",
"not",
"layout_",
":",
"layout_",
"=",
"\"layout.html\"",
"kwargs",
".",
"setdefault",
"(",
"\"brand_name\"",
",",
"\"\"",
")",
"kwargs",
"[",
"\"layout\"",
"]",
"=",
"layout_",
"setattr",
"(",
"f",
",",
"pkey",
",",
"kwargs",
")",
"setattr",
"(",
"f",
",",
"\"base_layout\"",
",",
"kwargs",
".",
"get",
"(",
"\"layout\"",
")",
")",
"f",
".",
"g",
"(",
"TEMPLATE_CONTEXT",
"=",
"kwargs",
")",
"return",
"f",
"else",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrap",
"(",
"*",
"args2",
",",
"*",
"*",
"kwargs2",
")",
":",
"response",
"=",
"f",
"(",
"*",
"args2",
",",
"*",
"*",
"kwargs2",
")",
"if",
"isinstance",
"(",
"response",
",",
"dict",
")",
"or",
"response",
"is",
"None",
":",
"response",
"=",
"response",
"or",
"{",
"}",
"if",
"page",
":",
"response",
".",
"setdefault",
"(",
"\"template_\"",
",",
"page",
")",
"if",
"layout",
":",
"response",
".",
"setdefault",
"(",
"\"layout_\"",
",",
"layout",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"response",
".",
"setdefault",
"(",
"k",
",",
"v",
")",
"return",
"response",
"return",
"wrap",
"return",
"decorator"
]
| Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
:param layout: The layout to use for that view
:param kwargs:
get pass to the TEMPLATE_CONTEXT
** on method that return a dict
page or layout are optional
:param page: The html page
:param layout: The layout to use for that view
:param kwargs:
get pass to the view as k/V
** on other methods that return other type, it doesn't apply
:return: | [
"Decorator",
"to",
"change",
"the",
"view",
"template",
"and",
"layout",
"."
]
| 7afa8d4238868235dfcdae82272bd77958dd416a | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/decorators.py#L127-L190 | train |
marrow/util | marrow/util/object.py | merge | def merge(s, t):
"""Merge dictionary t into s."""
for k, v in t.items():
if isinstance(v, dict):
if k not in s:
s[k] = v
continue
s[k] = merge(s[k], v)
continue
s[k] = v
return s | python | def merge(s, t):
"""Merge dictionary t into s."""
for k, v in t.items():
if isinstance(v, dict):
if k not in s:
s[k] = v
continue
s[k] = merge(s[k], v)
continue
s[k] = v
return s | [
"def",
"merge",
"(",
"s",
",",
"t",
")",
":",
"for",
"k",
",",
"v",
"in",
"t",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"if",
"k",
"not",
"in",
"s",
":",
"s",
"[",
"k",
"]",
"=",
"v",
"continue",
"s",
"[",
"k",
"]",
"=",
"merge",
"(",
"s",
"[",
"k",
"]",
",",
"v",
")",
"continue",
"s",
"[",
"k",
"]",
"=",
"v",
"return",
"s"
]
| Merge dictionary t into s. | [
"Merge",
"dictionary",
"t",
"into",
"s",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/object.py#L51-L65 | train |
marrow/util | marrow/util/object.py | load_object | def load_object(target, namespace=None):
"""This helper function loads an object identified by a dotted-notation string.
For example:
# Load class Foo from example.objects
load_object('example.objects:Foo')
If a plugin namespace is provided simple name references are allowed. For example:
# Load the plugin named 'routing' from the 'web.dispatch' namespace
load_object('routing', 'web.dispatch')
Providing a namespace does not prevent full object lookup (dot-colon notation) from working.
"""
if namespace and ':' not in target:
allowable = dict((i.name, i) for i in pkg_resources.iter_entry_points(namespace))
if target not in allowable:
raise ValueError('Unknown plugin "' + target + '"; found: ' + ', '.join(allowable))
return allowable[target].load()
parts, target = target.split(':') if ':' in target else (target, None)
module = __import__(parts)
for part in parts.split('.')[1:] + ([target] if target else []):
module = getattr(module, part)
return module | python | def load_object(target, namespace=None):
"""This helper function loads an object identified by a dotted-notation string.
For example:
# Load class Foo from example.objects
load_object('example.objects:Foo')
If a plugin namespace is provided simple name references are allowed. For example:
# Load the plugin named 'routing' from the 'web.dispatch' namespace
load_object('routing', 'web.dispatch')
Providing a namespace does not prevent full object lookup (dot-colon notation) from working.
"""
if namespace and ':' not in target:
allowable = dict((i.name, i) for i in pkg_resources.iter_entry_points(namespace))
if target not in allowable:
raise ValueError('Unknown plugin "' + target + '"; found: ' + ', '.join(allowable))
return allowable[target].load()
parts, target = target.split(':') if ':' in target else (target, None)
module = __import__(parts)
for part in parts.split('.')[1:] + ([target] if target else []):
module = getattr(module, part)
return module | [
"def",
"load_object",
"(",
"target",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"and",
"':'",
"not",
"in",
"target",
":",
"allowable",
"=",
"dict",
"(",
"(",
"i",
".",
"name",
",",
"i",
")",
"for",
"i",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"namespace",
")",
")",
"if",
"target",
"not",
"in",
"allowable",
":",
"raise",
"ValueError",
"(",
"'Unknown plugin \"'",
"+",
"target",
"+",
"'\"; found: '",
"+",
"', '",
".",
"join",
"(",
"allowable",
")",
")",
"return",
"allowable",
"[",
"target",
"]",
".",
"load",
"(",
")",
"parts",
",",
"target",
"=",
"target",
".",
"split",
"(",
"':'",
")",
"if",
"':'",
"in",
"target",
"else",
"(",
"target",
",",
"None",
")",
"module",
"=",
"__import__",
"(",
"parts",
")",
"for",
"part",
"in",
"parts",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
"+",
"(",
"[",
"target",
"]",
"if",
"target",
"else",
"[",
"]",
")",
":",
"module",
"=",
"getattr",
"(",
"module",
",",
"part",
")",
"return",
"module"
]
| This helper function loads an object identified by a dotted-notation string.
For example:
# Load class Foo from example.objects
load_object('example.objects:Foo')
If a plugin namespace is provided simple name references are allowed. For example:
# Load the plugin named 'routing' from the 'web.dispatch' namespace
load_object('routing', 'web.dispatch')
Providing a namespace does not prevent full object lookup (dot-colon notation) from working. | [
"This",
"helper",
"function",
"loads",
"an",
"object",
"identified",
"by",
"a",
"dotted",
"-",
"notation",
"string",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/object.py#L68-L95 | train |
marrow/util | marrow/util/object.py | getargspec | def getargspec(obj):
"""An improved inspect.getargspec.
Has a slightly different return value from the default getargspec.
Returns a tuple of:
required, optional, args, kwargs
list, dict, bool, bool
Required is a list of required named arguments.
Optional is a dictionary mapping optional arguments to defaults.
Args and kwargs are True for the respective unlimited argument type.
"""
argnames, varargs, varkw, _defaults = None, None, None, None
if inspect.isfunction(obj) or inspect.ismethod(obj):
argnames, varargs, varkw, _defaults = inspect.getargspec(obj)
elif inspect.isclass(obj):
if inspect.ismethoddescriptor(obj.__init__):
argnames, varargs, varkw, _defaults = [], False, False, None
else:
argnames, varargs, varkw, _defaults = inspect.getargspec(obj.__init__)
elif hasattr(obj, '__call__'):
argnames, varargs, varkw, _defaults = inspect.getargspec(obj.__call__)
else:
raise TypeError("Object not callable?")
# Need test case to prove this is even possible.
# if (argnames, varargs, varkw, defaults) is (None, None, None, None):
# raise InspectionFailed()
if argnames and argnames[0] == 'self':
del argnames[0]
if _defaults is None:
_defaults = []
defaults = dict()
else:
# Create a mapping dictionary of defaults; this is slightly more useful.
defaults = dict()
_defaults = list(_defaults)
_defaults.reverse()
argnames.reverse()
for i, default in enumerate(_defaults):
defaults[argnames[i]] = default
argnames.reverse()
# del argnames[-len(_defaults):]
return argnames, defaults, True if varargs else False, True if varkw else False | python | def getargspec(obj):
"""An improved inspect.getargspec.
Has a slightly different return value from the default getargspec.
Returns a tuple of:
required, optional, args, kwargs
list, dict, bool, bool
Required is a list of required named arguments.
Optional is a dictionary mapping optional arguments to defaults.
Args and kwargs are True for the respective unlimited argument type.
"""
argnames, varargs, varkw, _defaults = None, None, None, None
if inspect.isfunction(obj) or inspect.ismethod(obj):
argnames, varargs, varkw, _defaults = inspect.getargspec(obj)
elif inspect.isclass(obj):
if inspect.ismethoddescriptor(obj.__init__):
argnames, varargs, varkw, _defaults = [], False, False, None
else:
argnames, varargs, varkw, _defaults = inspect.getargspec(obj.__init__)
elif hasattr(obj, '__call__'):
argnames, varargs, varkw, _defaults = inspect.getargspec(obj.__call__)
else:
raise TypeError("Object not callable?")
# Need test case to prove this is even possible.
# if (argnames, varargs, varkw, defaults) is (None, None, None, None):
# raise InspectionFailed()
if argnames and argnames[0] == 'self':
del argnames[0]
if _defaults is None:
_defaults = []
defaults = dict()
else:
# Create a mapping dictionary of defaults; this is slightly more useful.
defaults = dict()
_defaults = list(_defaults)
_defaults.reverse()
argnames.reverse()
for i, default in enumerate(_defaults):
defaults[argnames[i]] = default
argnames.reverse()
# del argnames[-len(_defaults):]
return argnames, defaults, True if varargs else False, True if varkw else False | [
"def",
"getargspec",
"(",
"obj",
")",
":",
"argnames",
",",
"varargs",
",",
"varkw",
",",
"_defaults",
"=",
"None",
",",
"None",
",",
"None",
",",
"None",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
":",
"argnames",
",",
"varargs",
",",
"varkw",
",",
"_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"obj",
")",
"elif",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"ismethoddescriptor",
"(",
"obj",
".",
"__init__",
")",
":",
"argnames",
",",
"varargs",
",",
"varkw",
",",
"_defaults",
"=",
"[",
"]",
",",
"False",
",",
"False",
",",
"None",
"else",
":",
"argnames",
",",
"varargs",
",",
"varkw",
",",
"_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"obj",
".",
"__init__",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'__call__'",
")",
":",
"argnames",
",",
"varargs",
",",
"varkw",
",",
"_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"obj",
".",
"__call__",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Object not callable?\"",
")",
"# Need test case to prove this is even possible.",
"# if (argnames, varargs, varkw, defaults) is (None, None, None, None):",
"# raise InspectionFailed()",
"if",
"argnames",
"and",
"argnames",
"[",
"0",
"]",
"==",
"'self'",
":",
"del",
"argnames",
"[",
"0",
"]",
"if",
"_defaults",
"is",
"None",
":",
"_defaults",
"=",
"[",
"]",
"defaults",
"=",
"dict",
"(",
")",
"else",
":",
"# Create a mapping dictionary of defaults; this is slightly more useful.",
"defaults",
"=",
"dict",
"(",
")",
"_defaults",
"=",
"list",
"(",
"_defaults",
")",
"_defaults",
".",
"reverse",
"(",
")",
"argnames",
".",
"reverse",
"(",
")",
"for",
"i",
",",
"default",
"in",
"enumerate",
"(",
"_defaults",
")",
":",
"defaults",
"[",
"argnames",
"[",
"i",
"]",
"]",
"=",
"default",
"argnames",
".",
"reverse",
"(",
")",
"# del argnames[-len(_defaults):]",
"return",
"argnames",
",",
"defaults",
",",
"True",
"if",
"varargs",
"else",
"False",
",",
"True",
"if",
"varkw",
"else",
"False"
]
| An improved inspect.getargspec.
Has a slightly different return value from the default getargspec.
Returns a tuple of:
required, optional, args, kwargs
list, dict, bool, bool
Required is a list of required named arguments.
Optional is a dictionary mapping optional arguments to defaults.
Args and kwargs are True for the respective unlimited argument type. | [
"An",
"improved",
"inspect",
".",
"getargspec",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/object.py#L253-L308 | train |
The-Politico/politico-civic-election-night | electionnight/viewsets/state.py | StateMixin.get_queryset | def get_queryset(self):
"""
Returns a queryset of all states holding a non-special election on
a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs["date"])
except Exception:
raise APIException(
"No elections on {}.".format(self.kwargs["date"])
)
division_ids = []
normal_elections = date.elections.filter()
if len(normal_elections) > 0:
for election in date.elections.all():
if election.division.level.name == DivisionLevel.STATE:
division_ids.append(election.division.uid)
elif election.division.level.name == DivisionLevel.DISTRICT:
division_ids.append(election.division.parent.uid)
return Division.objects.filter(uid__in=division_ids) | python | def get_queryset(self):
"""
Returns a queryset of all states holding a non-special election on
a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs["date"])
except Exception:
raise APIException(
"No elections on {}.".format(self.kwargs["date"])
)
division_ids = []
normal_elections = date.elections.filter()
if len(normal_elections) > 0:
for election in date.elections.all():
if election.division.level.name == DivisionLevel.STATE:
division_ids.append(election.division.uid)
elif election.division.level.name == DivisionLevel.DISTRICT:
division_ids.append(election.division.parent.uid)
return Division.objects.filter(uid__in=division_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\"",
"]",
")",
")",
"division_ids",
"=",
"[",
"]",
"normal_elections",
"=",
"date",
".",
"elections",
".",
"filter",
"(",
")",
"if",
"len",
"(",
"normal_elections",
")",
">",
"0",
":",
"for",
"election",
"in",
"date",
".",
"elections",
".",
"all",
"(",
")",
":",
"if",
"election",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"division_ids",
".",
"append",
"(",
"election",
".",
"division",
".",
"uid",
")",
"elif",
"election",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"division_ids",
".",
"append",
"(",
"election",
".",
"division",
".",
"parent",
".",
"uid",
")",
"return",
"Division",
".",
"objects",
".",
"filter",
"(",
"uid__in",
"=",
"division_ids",
")"
]
| Returns a queryset of all states holding a non-special election on
a date. | [
"Returns",
"a",
"queryset",
"of",
"all",
"states",
"holding",
"a",
"non",
"-",
"special",
"election",
"on",
"a",
"date",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/viewsets/state.py#L10-L32 | train |
adamziel/python_translate | python_translate/dumpers.py | FileDumper.get_relative_path | def get_relative_path(self, domain, locale):
"""
Gets the relative file path using the template.
@type domain: str
@param domain: The domain
@type locale: str
@param locale: The locale
@rtype: string
@return: The relative file path
"""
return self.relative_path_template.format(
domain=domain,
locale=locale,
extension=self.get_extension()
) | python | def get_relative_path(self, domain, locale):
"""
Gets the relative file path using the template.
@type domain: str
@param domain: The domain
@type locale: str
@param locale: The locale
@rtype: string
@return: The relative file path
"""
return self.relative_path_template.format(
domain=domain,
locale=locale,
extension=self.get_extension()
) | [
"def",
"get_relative_path",
"(",
"self",
",",
"domain",
",",
"locale",
")",
":",
"return",
"self",
".",
"relative_path_template",
".",
"format",
"(",
"domain",
"=",
"domain",
",",
"locale",
"=",
"locale",
",",
"extension",
"=",
"self",
".",
"get_extension",
"(",
")",
")"
]
| Gets the relative file path using the template.
@type domain: str
@param domain: The domain
@type locale: str
@param locale: The locale
@rtype: string
@return: The relative file path | [
"Gets",
"the",
"relative",
"file",
"path",
"using",
"the",
"template",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/dumpers.py#L112-L129 | train |
textbook/atmdb | atmdb/utils.py | _overlap | async def _overlap(items, overlap_attr, client=None, get_method=None):
"""Generic overlap implementation.
Arguments:
item (:py:class:`collections.abc.Sequence`): The objects to
find overlaps for.
overlap_attr (:py:class:`str`): The attribute of the items to use
as input for the overlap.
client (:py:class:`~.TMDbClient`, optional): The TMDb client
to extract additional information about the overlap.
get_method (:py:class:`str`, optional): The method of the
client to use for extracting additional information.
Returns:
:py:class:`list`: The relevant result objects.
"""
overlap = set.intersection(*(getattr(item, overlap_attr) for item in items))
if client is None or get_method is None:
return overlap
results = []
for item in overlap:
result = await getattr(client, get_method)(id_=item.id_)
results.append(result)
return results | python | async def _overlap(items, overlap_attr, client=None, get_method=None):
"""Generic overlap implementation.
Arguments:
item (:py:class:`collections.abc.Sequence`): The objects to
find overlaps for.
overlap_attr (:py:class:`str`): The attribute of the items to use
as input for the overlap.
client (:py:class:`~.TMDbClient`, optional): The TMDb client
to extract additional information about the overlap.
get_method (:py:class:`str`, optional): The method of the
client to use for extracting additional information.
Returns:
:py:class:`list`: The relevant result objects.
"""
overlap = set.intersection(*(getattr(item, overlap_attr) for item in items))
if client is None or get_method is None:
return overlap
results = []
for item in overlap:
result = await getattr(client, get_method)(id_=item.id_)
results.append(result)
return results | [
"async",
"def",
"_overlap",
"(",
"items",
",",
"overlap_attr",
",",
"client",
"=",
"None",
",",
"get_method",
"=",
"None",
")",
":",
"overlap",
"=",
"set",
".",
"intersection",
"(",
"*",
"(",
"getattr",
"(",
"item",
",",
"overlap_attr",
")",
"for",
"item",
"in",
"items",
")",
")",
"if",
"client",
"is",
"None",
"or",
"get_method",
"is",
"None",
":",
"return",
"overlap",
"results",
"=",
"[",
"]",
"for",
"item",
"in",
"overlap",
":",
"result",
"=",
"await",
"getattr",
"(",
"client",
",",
"get_method",
")",
"(",
"id_",
"=",
"item",
".",
"id_",
")",
"results",
".",
"append",
"(",
"result",
")",
"return",
"results"
]
| Generic overlap implementation.
Arguments:
item (:py:class:`collections.abc.Sequence`): The objects to
find overlaps for.
overlap_attr (:py:class:`str`): The attribute of the items to use
as input for the overlap.
client (:py:class:`~.TMDbClient`, optional): The TMDb client
to extract additional information about the overlap.
get_method (:py:class:`str`, optional): The method of the
client to use for extracting additional information.
Returns:
:py:class:`list`: The relevant result objects. | [
"Generic",
"overlap",
"implementation",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L77-L101 | train |
textbook/atmdb | atmdb/utils.py | _find_overlap | async def _find_overlap(queries, client, find_method, get_method,
overlap_function):
"""Generic find and overlap implementation.
Arguments
names (:py:class:`collections.abc.Sequence`): The queries of the
people to find overlaps for.
client (:py:class:`~.TMDbClient`): The TMDb client.
find_method (:py:class:`str`): The name of the client method to
use for finding candidates.
get_method (:py:class:`str`): The name of the client method to
use for getting detailed information on a candidate.
overlap_function (:py:class:`collections.abc.Callable`): The
function to call for the resulting overlap.
"""
results = []
for query in queries:
candidates = await getattr(client, find_method)(query)
if not candidates:
raise ValueError('no result found for {!r}'.format(query))
result = await getattr(client, get_method)(id_=candidates[0].id_)
results.append(result)
return await overlap_function(results, client) | python | async def _find_overlap(queries, client, find_method, get_method,
overlap_function):
"""Generic find and overlap implementation.
Arguments
names (:py:class:`collections.abc.Sequence`): The queries of the
people to find overlaps for.
client (:py:class:`~.TMDbClient`): The TMDb client.
find_method (:py:class:`str`): The name of the client method to
use for finding candidates.
get_method (:py:class:`str`): The name of the client method to
use for getting detailed information on a candidate.
overlap_function (:py:class:`collections.abc.Callable`): The
function to call for the resulting overlap.
"""
results = []
for query in queries:
candidates = await getattr(client, find_method)(query)
if not candidates:
raise ValueError('no result found for {!r}'.format(query))
result = await getattr(client, get_method)(id_=candidates[0].id_)
results.append(result)
return await overlap_function(results, client) | [
"async",
"def",
"_find_overlap",
"(",
"queries",
",",
"client",
",",
"find_method",
",",
"get_method",
",",
"overlap_function",
")",
":",
"results",
"=",
"[",
"]",
"for",
"query",
"in",
"queries",
":",
"candidates",
"=",
"await",
"getattr",
"(",
"client",
",",
"find_method",
")",
"(",
"query",
")",
"if",
"not",
"candidates",
":",
"raise",
"ValueError",
"(",
"'no result found for {!r}'",
".",
"format",
"(",
"query",
")",
")",
"result",
"=",
"await",
"getattr",
"(",
"client",
",",
"get_method",
")",
"(",
"id_",
"=",
"candidates",
"[",
"0",
"]",
".",
"id_",
")",
"results",
".",
"append",
"(",
"result",
")",
"return",
"await",
"overlap_function",
"(",
"results",
",",
"client",
")"
]
| Generic find and overlap implementation.
Arguments
names (:py:class:`collections.abc.Sequence`): The queries of the
people to find overlaps for.
client (:py:class:`~.TMDbClient`): The TMDb client.
find_method (:py:class:`str`): The name of the client method to
use for finding candidates.
get_method (:py:class:`str`): The name of the client method to
use for getting detailed information on a candidate.
overlap_function (:py:class:`collections.abc.Callable`): The
function to call for the resulting overlap. | [
"Generic",
"find",
"and",
"overlap",
"implementation",
"."
]
| cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L104-L127 | train |
jeffh/describe | describe/spec/containers.py | Example.before | def before(self, context):
"Invokes all before functions with context passed to them."
run.before_each.execute(context)
self._invoke(self._before, context) | python | def before(self, context):
"Invokes all before functions with context passed to them."
run.before_each.execute(context)
self._invoke(self._before, context) | [
"def",
"before",
"(",
"self",
",",
"context",
")",
":",
"run",
".",
"before_each",
".",
"execute",
"(",
"context",
")",
"self",
".",
"_invoke",
"(",
"self",
".",
"_before",
",",
"context",
")"
]
| Invokes all before functions with context passed to them. | [
"Invokes",
"all",
"before",
"functions",
"with",
"context",
"passed",
"to",
"them",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/containers.py#L175-L178 | train |
jeffh/describe | describe/spec/containers.py | Example.after | def after(self, context):
"Invokes all after functions with context passed to them."
self._invoke(self._after, context)
run.after_each.execute(context) | python | def after(self, context):
"Invokes all after functions with context passed to them."
self._invoke(self._after, context)
run.after_each.execute(context) | [
"def",
"after",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"_invoke",
"(",
"self",
".",
"_after",
",",
"context",
")",
"run",
".",
"after_each",
".",
"execute",
"(",
"context",
")"
]
| Invokes all after functions with context passed to them. | [
"Invokes",
"all",
"after",
"functions",
"with",
"context",
"passed",
"to",
"them",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/containers.py#L180-L183 | train |
riga/scinum | scinum.py | Number.repr | def repr(self, *args, **kwargs):
"""
Returns the unique string representation of the number.
"""
if not self.is_numpy:
text = "'" + self.str(*args, **kwargs) + "'"
else:
text = "{} numpy array, {} uncertainties".format(self.shape, len(self.uncertainties))
return "<{} at {}, {}>".format(self.__class__.__name__, hex(id(self)), text) | python | def repr(self, *args, **kwargs):
"""
Returns the unique string representation of the number.
"""
if not self.is_numpy:
text = "'" + self.str(*args, **kwargs) + "'"
else:
text = "{} numpy array, {} uncertainties".format(self.shape, len(self.uncertainties))
return "<{} at {}, {}>".format(self.__class__.__name__, hex(id(self)), text) | [
"def",
"repr",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"is_numpy",
":",
"text",
"=",
"\"'\"",
"+",
"self",
".",
"str",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"'\"",
"else",
":",
"text",
"=",
"\"{} numpy array, {} uncertainties\"",
".",
"format",
"(",
"self",
".",
"shape",
",",
"len",
"(",
"self",
".",
"uncertainties",
")",
")",
"return",
"\"<{} at {}, {}>\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"hex",
"(",
"id",
"(",
"self",
")",
")",
",",
"text",
")"
]
| Returns the unique string representation of the number. | [
"Returns",
"the",
"unique",
"string",
"representation",
"of",
"the",
"number",
"."
]
| 55eb6d8aa77beacee5a07443392954b8a0aad8cb | https://github.com/riga/scinum/blob/55eb6d8aa77beacee5a07443392954b8a0aad8cb/scinum.py#L585-L594 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election_day.py | ElectionDaySerializer.get_states | def get_states(self, obj):
"""States holding a non-special election on election day."""
return reverse(
'electionnight_api_state-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | python | def get_states(self, obj):
"""States holding a non-special election on election day."""
return reverse(
'electionnight_api_state-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | [
"def",
"get_states",
"(",
"self",
",",
"obj",
")",
":",
"return",
"reverse",
"(",
"'electionnight_api_state-election-list'",
",",
"request",
"=",
"self",
".",
"context",
"[",
"'request'",
"]",
",",
"kwargs",
"=",
"{",
"'date'",
":",
"obj",
".",
"date",
"}",
")"
]
| States holding a non-special election on election day. | [
"States",
"holding",
"a",
"non",
"-",
"special",
"election",
"on",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L12-L18 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election_day.py | ElectionDaySerializer.get_bodies | def get_bodies(self, obj):
"""Bodies with offices up for election on election day."""
return reverse(
'electionnight_api_body-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | python | def get_bodies(self, obj):
"""Bodies with offices up for election on election day."""
return reverse(
'electionnight_api_body-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | [
"def",
"get_bodies",
"(",
"self",
",",
"obj",
")",
":",
"return",
"reverse",
"(",
"'electionnight_api_body-election-list'",
",",
"request",
"=",
"self",
".",
"context",
"[",
"'request'",
"]",
",",
"kwargs",
"=",
"{",
"'date'",
":",
"obj",
".",
"date",
"}",
")"
]
| Bodies with offices up for election on election day. | [
"Bodies",
"with",
"offices",
"up",
"for",
"election",
"on",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L20-L26 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election_day.py | ElectionDaySerializer.get_executive_offices | def get_executive_offices(self, obj):
"""Executive offices up for election on election day."""
return reverse(
'electionnight_api_office-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | python | def get_executive_offices(self, obj):
"""Executive offices up for election on election day."""
return reverse(
'electionnight_api_office-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | [
"def",
"get_executive_offices",
"(",
"self",
",",
"obj",
")",
":",
"return",
"reverse",
"(",
"'electionnight_api_office-election-list'",
",",
"request",
"=",
"self",
".",
"context",
"[",
"'request'",
"]",
",",
"kwargs",
"=",
"{",
"'date'",
":",
"obj",
".",
"date",
"}",
")"
]
| Executive offices up for election on election day. | [
"Executive",
"offices",
"up",
"for",
"election",
"on",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L28-L34 | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election_day.py | ElectionDaySerializer.get_special_elections | def get_special_elections(self, obj):
"""States holding a special election on election day."""
return reverse(
'electionnight_api_special-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | python | def get_special_elections(self, obj):
"""States holding a special election on election day."""
return reverse(
'electionnight_api_special-election-list',
request=self.context['request'],
kwargs={'date': obj.date}
) | [
"def",
"get_special_elections",
"(",
"self",
",",
"obj",
")",
":",
"return",
"reverse",
"(",
"'electionnight_api_special-election-list'",
",",
"request",
"=",
"self",
".",
"context",
"[",
"'request'",
"]",
",",
"kwargs",
"=",
"{",
"'date'",
":",
"obj",
".",
"date",
"}",
")"
]
| States holding a special election on election day. | [
"States",
"holding",
"a",
"special",
"election",
"on",
"election",
"day",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L36-L42 | train |
dailymotion/cloudkey-py | cloudkey.py | normalize | def normalize(arg=None):
"""Normalizes an argument for signing purpose.
This is used for normalizing the arguments of RPC method calls.
:param arg: The argument to normalize
:return: A string representating the normalized argument.
.. doctest::
>>> from cloud.rpc import normalize
>>> normalize(['foo', 42, 'bar'])
'foo42bar'
>>> normalize({'yellow': 1, 'red': 2, 'pink' : 3})
'pink3red2yellow1'
>>> normalize(['foo', 42, {'yellow': 1, 'red': 2, 'pink' : 3}, 'bar'])
'foo42pink3red2yellow1bar'
>>> normalize(None)
''
>>> normalize([None, 1,2])
'12'
>>> normalize({2: [None, 1,2], 3: None, 4:5})
'212345'
"""
res = ''
t_arg = type(arg)
if t_arg in (list, tuple):
for i in arg:
res += normalize(i)
elif t_arg is dict:
keys = arg.keys()
keys.sort()
for key in keys:
res += '%s%s' % (normalize(key), normalize(arg[key]))
elif t_arg is unicode:
res = arg.encode('utf8')
elif t_arg is bool:
res = 'true' if arg else 'false'
elif arg != None:
res = str(arg)
return res | python | def normalize(arg=None):
"""Normalizes an argument for signing purpose.
This is used for normalizing the arguments of RPC method calls.
:param arg: The argument to normalize
:return: A string representating the normalized argument.
.. doctest::
>>> from cloud.rpc import normalize
>>> normalize(['foo', 42, 'bar'])
'foo42bar'
>>> normalize({'yellow': 1, 'red': 2, 'pink' : 3})
'pink3red2yellow1'
>>> normalize(['foo', 42, {'yellow': 1, 'red': 2, 'pink' : 3}, 'bar'])
'foo42pink3red2yellow1bar'
>>> normalize(None)
''
>>> normalize([None, 1,2])
'12'
>>> normalize({2: [None, 1,2], 3: None, 4:5})
'212345'
"""
res = ''
t_arg = type(arg)
if t_arg in (list, tuple):
for i in arg:
res += normalize(i)
elif t_arg is dict:
keys = arg.keys()
keys.sort()
for key in keys:
res += '%s%s' % (normalize(key), normalize(arg[key]))
elif t_arg is unicode:
res = arg.encode('utf8')
elif t_arg is bool:
res = 'true' if arg else 'false'
elif arg != None:
res = str(arg)
return res | [
"def",
"normalize",
"(",
"arg",
"=",
"None",
")",
":",
"res",
"=",
"''",
"t_arg",
"=",
"type",
"(",
"arg",
")",
"if",
"t_arg",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"for",
"i",
"in",
"arg",
":",
"res",
"+=",
"normalize",
"(",
"i",
")",
"elif",
"t_arg",
"is",
"dict",
":",
"keys",
"=",
"arg",
".",
"keys",
"(",
")",
"keys",
".",
"sort",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"res",
"+=",
"'%s%s'",
"%",
"(",
"normalize",
"(",
"key",
")",
",",
"normalize",
"(",
"arg",
"[",
"key",
"]",
")",
")",
"elif",
"t_arg",
"is",
"unicode",
":",
"res",
"=",
"arg",
".",
"encode",
"(",
"'utf8'",
")",
"elif",
"t_arg",
"is",
"bool",
":",
"res",
"=",
"'true'",
"if",
"arg",
"else",
"'false'",
"elif",
"arg",
"!=",
"None",
":",
"res",
"=",
"str",
"(",
"arg",
")",
"return",
"res"
]
| Normalizes an argument for signing purpose.
This is used for normalizing the arguments of RPC method calls.
:param arg: The argument to normalize
:return: A string representating the normalized argument.
.. doctest::
>>> from cloud.rpc import normalize
>>> normalize(['foo', 42, 'bar'])
'foo42bar'
>>> normalize({'yellow': 1, 'red': 2, 'pink' : 3})
'pink3red2yellow1'
>>> normalize(['foo', 42, {'yellow': 1, 'red': 2, 'pink' : 3}, 'bar'])
'foo42pink3red2yellow1bar'
>>> normalize(None)
''
>>> normalize([None, 1,2])
'12'
>>> normalize({2: [None, 1,2], 3: None, 4:5})
'212345' | [
"Normalizes",
"an",
"argument",
"for",
"signing",
"purpose",
"."
]
| 81334553e0737b87c66b12ad2f1eb8e26ef68a96 | https://github.com/dailymotion/cloudkey-py/blob/81334553e0737b87c66b12ad2f1eb8e26ef68a96/cloudkey.py#L92-L135 | train |
dailymotion/cloudkey-py | cloudkey.py | sign | def sign(shared_secret, msg):
"""Signs a message using a shared secret.
:param shared_secret: The shared secret used to sign the message
:param msg: The message to sign
:return: The signature as a string
.. doctest::
>>> from cloud.rpc import sign
>>> sign('sEcReT_KeY', 'hello world')
'5f048ebaf6f06576b60716dc8f815d85'
"""
if isinstance(msg, unicode):
msg = msg.encode('utf8')
return hashlib.md5(msg + shared_secret).hexdigest() | python | def sign(shared_secret, msg):
"""Signs a message using a shared secret.
:param shared_secret: The shared secret used to sign the message
:param msg: The message to sign
:return: The signature as a string
.. doctest::
>>> from cloud.rpc import sign
>>> sign('sEcReT_KeY', 'hello world')
'5f048ebaf6f06576b60716dc8f815d85'
"""
if isinstance(msg, unicode):
msg = msg.encode('utf8')
return hashlib.md5(msg + shared_secret).hexdigest() | [
"def",
"sign",
"(",
"shared_secret",
",",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"unicode",
")",
":",
"msg",
"=",
"msg",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"hashlib",
".",
"md5",
"(",
"msg",
"+",
"shared_secret",
")",
".",
"hexdigest",
"(",
")"
]
| Signs a message using a shared secret.
:param shared_secret: The shared secret used to sign the message
:param msg: The message to sign
:return: The signature as a string
.. doctest::
>>> from cloud.rpc import sign
>>> sign('sEcReT_KeY', 'hello world')
'5f048ebaf6f06576b60716dc8f815d85' | [
"Signs",
"a",
"message",
"using",
"a",
"shared",
"secret",
"."
]
| 81334553e0737b87c66b12ad2f1eb8e26ef68a96 | https://github.com/dailymotion/cloudkey-py/blob/81334553e0737b87c66b12ad2f1eb8e26ef68a96/cloudkey.py#L137-L153 | train |
louib/confirm | confirm/utils.py | config_parser_to_dict | def config_parser_to_dict(config_parser):
"""
Convert a ConfigParser to a dictionary.
"""
response = {}
for section in config_parser.sections():
for option in config_parser.options(section):
response.setdefault(section, {})[option] = config_parser.get(section, option)
return response | python | def config_parser_to_dict(config_parser):
"""
Convert a ConfigParser to a dictionary.
"""
response = {}
for section in config_parser.sections():
for option in config_parser.options(section):
response.setdefault(section, {})[option] = config_parser.get(section, option)
return response | [
"def",
"config_parser_to_dict",
"(",
"config_parser",
")",
":",
"response",
"=",
"{",
"}",
"for",
"section",
"in",
"config_parser",
".",
"sections",
"(",
")",
":",
"for",
"option",
"in",
"config_parser",
".",
"options",
"(",
"section",
")",
":",
"response",
".",
"setdefault",
"(",
"section",
",",
"{",
"}",
")",
"[",
"option",
"]",
"=",
"config_parser",
".",
"get",
"(",
"section",
",",
"option",
")",
"return",
"response"
]
| Convert a ConfigParser to a dictionary. | [
"Convert",
"a",
"ConfigParser",
"to",
"a",
"dictionary",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/utils.py#L18-L28 | train |
louib/confirm | confirm/utils.py | load_config_file | def load_config_file(config_file_path, config_file):
"""
Loads a config file, whether it is a yaml file or a .INI file.
:param config_file_path: Path of the configuration file, used to infer the file format.
:returns: Dictionary representation of the configuration file.
"""
if config_file_path.lower().endswith(".yaml"):
return yaml.load(config_file)
if any(config_file_path.lower().endswith(extension) for extension in INI_FILE_EXTENSIONS):
return load_config_from_ini_file(config_file)
# At this point we have to guess the format of the configuration file.
try:
return yaml.load(config_file)
except yaml.YAMLError:
pass
try:
return load_config_from_ini_file(config_file)
except:
pass
raise Exception("Could not load configuration file!") | python | def load_config_file(config_file_path, config_file):
"""
Loads a config file, whether it is a yaml file or a .INI file.
:param config_file_path: Path of the configuration file, used to infer the file format.
:returns: Dictionary representation of the configuration file.
"""
if config_file_path.lower().endswith(".yaml"):
return yaml.load(config_file)
if any(config_file_path.lower().endswith(extension) for extension in INI_FILE_EXTENSIONS):
return load_config_from_ini_file(config_file)
# At this point we have to guess the format of the configuration file.
try:
return yaml.load(config_file)
except yaml.YAMLError:
pass
try:
return load_config_from_ini_file(config_file)
except:
pass
raise Exception("Could not load configuration file!") | [
"def",
"load_config_file",
"(",
"config_file_path",
",",
"config_file",
")",
":",
"if",
"config_file_path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".yaml\"",
")",
":",
"return",
"yaml",
".",
"load",
"(",
"config_file",
")",
"if",
"any",
"(",
"config_file_path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"extension",
")",
"for",
"extension",
"in",
"INI_FILE_EXTENSIONS",
")",
":",
"return",
"load_config_from_ini_file",
"(",
"config_file",
")",
"# At this point we have to guess the format of the configuration file.",
"try",
":",
"return",
"yaml",
".",
"load",
"(",
"config_file",
")",
"except",
"yaml",
".",
"YAMLError",
":",
"pass",
"try",
":",
"return",
"load_config_from_ini_file",
"(",
"config_file",
")",
"except",
":",
"pass",
"raise",
"Exception",
"(",
"\"Could not load configuration file!\"",
")"
]
| Loads a config file, whether it is a yaml file or a .INI file.
:param config_file_path: Path of the configuration file, used to infer the file format.
:returns: Dictionary representation of the configuration file. | [
"Loads",
"a",
"config",
"file",
"whether",
"it",
"is",
"a",
"yaml",
"file",
"or",
"a",
".",
"INI",
"file",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/utils.py#L38-L63 | train |
Xion/taipan | taipan/collections/dicts.py | select | def select(keys, from_, strict=False):
"""Selects a subset of given dictionary, including only the specified keys.
:param keys: Iterable of keys to include
:param strict: Whether ``keys`` are required to exist in the dictionary.
:return: Dictionary whose keys are a subset of given ``keys``
:raise KeyError: If ``strict`` is True and one of ``keys`` is not found
in the dictionary.
"""
ensure_iterable(keys)
ensure_mapping(from_)
if strict:
return from_.__class__((k, from_[k]) for k in keys)
else:
existing_keys = set(keys) & set(iterkeys(from_))
return from_.__class__((k, from_[k]) for k in existing_keys) | python | def select(keys, from_, strict=False):
"""Selects a subset of given dictionary, including only the specified keys.
:param keys: Iterable of keys to include
:param strict: Whether ``keys`` are required to exist in the dictionary.
:return: Dictionary whose keys are a subset of given ``keys``
:raise KeyError: If ``strict`` is True and one of ``keys`` is not found
in the dictionary.
"""
ensure_iterable(keys)
ensure_mapping(from_)
if strict:
return from_.__class__((k, from_[k]) for k in keys)
else:
existing_keys = set(keys) & set(iterkeys(from_))
return from_.__class__((k, from_[k]) for k in existing_keys) | [
"def",
"select",
"(",
"keys",
",",
"from_",
",",
"strict",
"=",
"False",
")",
":",
"ensure_iterable",
"(",
"keys",
")",
"ensure_mapping",
"(",
"from_",
")",
"if",
"strict",
":",
"return",
"from_",
".",
"__class__",
"(",
"(",
"k",
",",
"from_",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"keys",
")",
"else",
":",
"existing_keys",
"=",
"set",
"(",
"keys",
")",
"&",
"set",
"(",
"iterkeys",
"(",
"from_",
")",
")",
"return",
"from_",
".",
"__class__",
"(",
"(",
"k",
",",
"from_",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"existing_keys",
")"
]
| Selects a subset of given dictionary, including only the specified keys.
:param keys: Iterable of keys to include
:param strict: Whether ``keys`` are required to exist in the dictionary.
:return: Dictionary whose keys are a subset of given ``keys``
:raise KeyError: If ``strict`` is True and one of ``keys`` is not found
in the dictionary. | [
"Selects",
"a",
"subset",
"of",
"given",
"dictionary",
"including",
"only",
"the",
"specified",
"keys",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L162-L180 | train |
Xion/taipan | taipan/collections/dicts.py | omit | def omit(keys, from_, strict=False):
"""Returns a subset of given dictionary, omitting specified keys.
:param keys: Iterable of keys to exclude
:param strict: Whether ``keys`` are required to exist in the dictionary
:return: Dictionary filtered by omitting ``keys``
:raise KeyError: If ``strict`` is True and one of ``keys`` is not found
in the dictionary
.. versionadded:: 0.0.2
"""
ensure_iterable(keys)
ensure_mapping(from_)
if strict:
remaining_keys = set(iterkeys(from_))
remove_subset(remaining_keys, keys) # raises KeyError if necessary
else:
remaining_keys = set(iterkeys(from_)) - set(keys)
return from_.__class__((k, from_[k]) for k in remaining_keys) | python | def omit(keys, from_, strict=False):
"""Returns a subset of given dictionary, omitting specified keys.
:param keys: Iterable of keys to exclude
:param strict: Whether ``keys`` are required to exist in the dictionary
:return: Dictionary filtered by omitting ``keys``
:raise KeyError: If ``strict`` is True and one of ``keys`` is not found
in the dictionary
.. versionadded:: 0.0.2
"""
ensure_iterable(keys)
ensure_mapping(from_)
if strict:
remaining_keys = set(iterkeys(from_))
remove_subset(remaining_keys, keys) # raises KeyError if necessary
else:
remaining_keys = set(iterkeys(from_)) - set(keys)
return from_.__class__((k, from_[k]) for k in remaining_keys) | [
"def",
"omit",
"(",
"keys",
",",
"from_",
",",
"strict",
"=",
"False",
")",
":",
"ensure_iterable",
"(",
"keys",
")",
"ensure_mapping",
"(",
"from_",
")",
"if",
"strict",
":",
"remaining_keys",
"=",
"set",
"(",
"iterkeys",
"(",
"from_",
")",
")",
"remove_subset",
"(",
"remaining_keys",
",",
"keys",
")",
"# raises KeyError if necessary",
"else",
":",
"remaining_keys",
"=",
"set",
"(",
"iterkeys",
"(",
"from_",
")",
")",
"-",
"set",
"(",
"keys",
")",
"return",
"from_",
".",
"__class__",
"(",
"(",
"k",
",",
"from_",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"remaining_keys",
")"
]
| Returns a subset of given dictionary, omitting specified keys.
:param keys: Iterable of keys to exclude
:param strict: Whether ``keys`` are required to exist in the dictionary
:return: Dictionary filtered by omitting ``keys``
:raise KeyError: If ``strict`` is True and one of ``keys`` is not found
in the dictionary
.. versionadded:: 0.0.2 | [
"Returns",
"a",
"subset",
"of",
"given",
"dictionary",
"omitting",
"specified",
"keys",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L188-L210 | train |
Xion/taipan | taipan/collections/dicts.py | filteritems | def filteritems(predicate, dict_):
"""Return a new dictionary comprising of items
for which ``predicate`` returns True.
:param predicate: Predicate taking a key-value pair, or None
.. versionchanged: 0.0.2
``predicate`` is now taking a key-value pair as a single argument.
"""
predicate = all if predicate is None else ensure_callable(predicate)
ensure_mapping(dict_)
return dict_.__class__(ifilter(predicate, iteritems(dict_))) | python | def filteritems(predicate, dict_):
"""Return a new dictionary comprising of items
for which ``predicate`` returns True.
:param predicate: Predicate taking a key-value pair, or None
.. versionchanged: 0.0.2
``predicate`` is now taking a key-value pair as a single argument.
"""
predicate = all if predicate is None else ensure_callable(predicate)
ensure_mapping(dict_)
return dict_.__class__(ifilter(predicate, iteritems(dict_))) | [
"def",
"filteritems",
"(",
"predicate",
",",
"dict_",
")",
":",
"predicate",
"=",
"all",
"if",
"predicate",
"is",
"None",
"else",
"ensure_callable",
"(",
"predicate",
")",
"ensure_mapping",
"(",
"dict_",
")",
"return",
"dict_",
".",
"__class__",
"(",
"ifilter",
"(",
"predicate",
",",
"iteritems",
"(",
"dict_",
")",
")",
")"
]
| Return a new dictionary comprising of items
for which ``predicate`` returns True.
:param predicate: Predicate taking a key-value pair, or None
.. versionchanged: 0.0.2
``predicate`` is now taking a key-value pair as a single argument. | [
"Return",
"a",
"new",
"dictionary",
"comprising",
"of",
"items",
"for",
"which",
"predicate",
"returns",
"True",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L215-L226 | train |
Xion/taipan | taipan/collections/dicts.py | starfilteritems | def starfilteritems(predicate, dict_):
"""Return a new dictionary comprising of keys and values
for which ``predicate`` returns True.
:param predicate: Predicate taking key and value, or None
.. versionchanged:: 0.0.2
Renamed ``starfilteritems`` for consistency with :func:`starmapitems`.
"""
ensure_mapping(dict_)
if predicate is None:
predicate = lambda k, v: all((k, v))
else:
ensure_callable(predicate)
return dict_.__class__((k, v) for k, v in iteritems(dict_)
if predicate(k, v)) | python | def starfilteritems(predicate, dict_):
"""Return a new dictionary comprising of keys and values
for which ``predicate`` returns True.
:param predicate: Predicate taking key and value, or None
.. versionchanged:: 0.0.2
Renamed ``starfilteritems`` for consistency with :func:`starmapitems`.
"""
ensure_mapping(dict_)
if predicate is None:
predicate = lambda k, v: all((k, v))
else:
ensure_callable(predicate)
return dict_.__class__((k, v) for k, v in iteritems(dict_)
if predicate(k, v)) | [
"def",
"starfilteritems",
"(",
"predicate",
",",
"dict_",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"if",
"predicate",
"is",
"None",
":",
"predicate",
"=",
"lambda",
"k",
",",
"v",
":",
"all",
"(",
"(",
"k",
",",
"v",
")",
")",
"else",
":",
"ensure_callable",
"(",
"predicate",
")",
"return",
"dict_",
".",
"__class__",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"dict_",
")",
"if",
"predicate",
"(",
"k",
",",
"v",
")",
")"
]
| Return a new dictionary comprising of keys and values
for which ``predicate`` returns True.
:param predicate: Predicate taking key and value, or None
.. versionchanged:: 0.0.2
Renamed ``starfilteritems`` for consistency with :func:`starmapitems`. | [
"Return",
"a",
"new",
"dictionary",
"comprising",
"of",
"keys",
"and",
"values",
"for",
"which",
"predicate",
"returns",
"True",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L229-L246 | train |
Xion/taipan | taipan/collections/dicts.py | filterkeys | def filterkeys(predicate, dict_):
"""Return a new dictionary comprising of keys
for which ``predicate`` returns True, and their corresponding values.
:param predicate: Predicate taking a dictionary key, or None
"""
predicate = bool if predicate is None else ensure_callable(predicate)
ensure_mapping(dict_)
return dict_.__class__((k, v) for k, v in iteritems(dict_) if predicate(k)) | python | def filterkeys(predicate, dict_):
"""Return a new dictionary comprising of keys
for which ``predicate`` returns True, and their corresponding values.
:param predicate: Predicate taking a dictionary key, or None
"""
predicate = bool if predicate is None else ensure_callable(predicate)
ensure_mapping(dict_)
return dict_.__class__((k, v) for k, v in iteritems(dict_) if predicate(k)) | [
"def",
"filterkeys",
"(",
"predicate",
",",
"dict_",
")",
":",
"predicate",
"=",
"bool",
"if",
"predicate",
"is",
"None",
"else",
"ensure_callable",
"(",
"predicate",
")",
"ensure_mapping",
"(",
"dict_",
")",
"return",
"dict_",
".",
"__class__",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"dict_",
")",
"if",
"predicate",
"(",
"k",
")",
")"
]
| Return a new dictionary comprising of keys
for which ``predicate`` returns True, and their corresponding values.
:param predicate: Predicate taking a dictionary key, or None | [
"Return",
"a",
"new",
"dictionary",
"comprising",
"of",
"keys",
"for",
"which",
"predicate",
"returns",
"True",
"and",
"their",
"corresponding",
"values",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L249-L257 | train |
Xion/taipan | taipan/collections/dicts.py | mapitems | def mapitems(function, dict_):
"""Return a new dictionary where the keys and values come from applying
``function`` to key-value pairs from given dictionary.
.. warning::
If ``function`` returns a key-value pair with the same key
more than once, it is undefined which value will be chosen
for that key in the resulting dictionary.
:param function: Function taking a key-value pair as a single argument,
and returning a new key-value pair; or None
(corresponding to identity function)
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
function = identity() if function is None else ensure_callable(function)
return dict_.__class__(imap(function, iteritems(dict_))) | python | def mapitems(function, dict_):
"""Return a new dictionary where the keys and values come from applying
``function`` to key-value pairs from given dictionary.
.. warning::
If ``function`` returns a key-value pair with the same key
more than once, it is undefined which value will be chosen
for that key in the resulting dictionary.
:param function: Function taking a key-value pair as a single argument,
and returning a new key-value pair; or None
(corresponding to identity function)
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
function = identity() if function is None else ensure_callable(function)
return dict_.__class__(imap(function, iteritems(dict_))) | [
"def",
"mapitems",
"(",
"function",
",",
"dict_",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"function",
"=",
"identity",
"(",
")",
"if",
"function",
"is",
"None",
"else",
"ensure_callable",
"(",
"function",
")",
"return",
"dict_",
".",
"__class__",
"(",
"imap",
"(",
"function",
",",
"iteritems",
"(",
"dict_",
")",
")",
")"
]
| Return a new dictionary where the keys and values come from applying
``function`` to key-value pairs from given dictionary.
.. warning::
If ``function`` returns a key-value pair with the same key
more than once, it is undefined which value will be chosen
for that key in the resulting dictionary.
:param function: Function taking a key-value pair as a single argument,
and returning a new key-value pair; or None
(corresponding to identity function)
.. versionadded:: 0.0.2 | [
"Return",
"a",
"new",
"dictionary",
"where",
"the",
"keys",
"and",
"values",
"come",
"from",
"applying",
"function",
"to",
"key",
"-",
"value",
"pairs",
"from",
"given",
"dictionary",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L273-L291 | train |
Xion/taipan | taipan/collections/dicts.py | starmapitems | def starmapitems(function, dict_):
"""Return a new dictionary where the keys and values come from applying
``function`` to the keys and values of given dictionary.
.. warning::
If ``function`` returns a key-value pair with the same key
more than once, it is undefined which value will be chosen
for that key in the resulting dictionary.
:param function: Function taking key and value as two arguments
and returning a new key-value pair, or None
(corresponding to identity function)
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
if function is None:
function = lambda k, v: (k, v)
else:
ensure_callable(function)
return dict_.__class__(starmap(function, iteritems(dict_))) | python | def starmapitems(function, dict_):
"""Return a new dictionary where the keys and values come from applying
``function`` to the keys and values of given dictionary.
.. warning::
If ``function`` returns a key-value pair with the same key
more than once, it is undefined which value will be chosen
for that key in the resulting dictionary.
:param function: Function taking key and value as two arguments
and returning a new key-value pair, or None
(corresponding to identity function)
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
if function is None:
function = lambda k, v: (k, v)
else:
ensure_callable(function)
return dict_.__class__(starmap(function, iteritems(dict_))) | [
"def",
"starmapitems",
"(",
"function",
",",
"dict_",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"if",
"function",
"is",
"None",
":",
"function",
"=",
"lambda",
"k",
",",
"v",
":",
"(",
"k",
",",
"v",
")",
"else",
":",
"ensure_callable",
"(",
"function",
")",
"return",
"dict_",
".",
"__class__",
"(",
"starmap",
"(",
"function",
",",
"iteritems",
"(",
"dict_",
")",
")",
")"
]
| Return a new dictionary where the keys and values come from applying
``function`` to the keys and values of given dictionary.
.. warning::
If ``function`` returns a key-value pair with the same key
more than once, it is undefined which value will be chosen
for that key in the resulting dictionary.
:param function: Function taking key and value as two arguments
and returning a new key-value pair, or None
(corresponding to identity function)
.. versionadded:: 0.0.2 | [
"Return",
"a",
"new",
"dictionary",
"where",
"the",
"keys",
"and",
"values",
"come",
"from",
"applying",
"function",
"to",
"the",
"keys",
"and",
"values",
"of",
"given",
"dictionary",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L294-L317 | train |
Xion/taipan | taipan/collections/dicts.py | mapkeys | def mapkeys(function, dict_):
"""Return a new dictionary where the keys come from applying ``function``
to the keys of given dictionary.
.. warning::
If ``function`` returns the same value for more than one key,
it is undefined which key will be chosen for the resulting dictionary.
:param function: Function taking a dictionary key,
or None (corresponding to identity function)
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
function = identity() if function is None else ensure_callable(function)
return dict_.__class__((function(k), v) for k, v in iteritems(dict_)) | python | def mapkeys(function, dict_):
"""Return a new dictionary where the keys come from applying ``function``
to the keys of given dictionary.
.. warning::
If ``function`` returns the same value for more than one key,
it is undefined which key will be chosen for the resulting dictionary.
:param function: Function taking a dictionary key,
or None (corresponding to identity function)
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
function = identity() if function is None else ensure_callable(function)
return dict_.__class__((function(k), v) for k, v in iteritems(dict_)) | [
"def",
"mapkeys",
"(",
"function",
",",
"dict_",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"function",
"=",
"identity",
"(",
")",
"if",
"function",
"is",
"None",
"else",
"ensure_callable",
"(",
"function",
")",
"return",
"dict_",
".",
"__class__",
"(",
"(",
"function",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"dict_",
")",
")"
]
| Return a new dictionary where the keys come from applying ``function``
to the keys of given dictionary.
.. warning::
If ``function`` returns the same value for more than one key,
it is undefined which key will be chosen for the resulting dictionary.
:param function: Function taking a dictionary key,
or None (corresponding to identity function)
.. versionadded:: 0.0.2 | [
"Return",
"a",
"new",
"dictionary",
"where",
"the",
"keys",
"come",
"from",
"applying",
"function",
"to",
"the",
"keys",
"of",
"given",
"dictionary",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L320-L336 | train |
Xion/taipan | taipan/collections/dicts.py | merge | def merge(*dicts, **kwargs):
"""Merges two or more dictionaries into a single one.
Optional keyword arguments allow to control the exact way
in which the dictionaries will be merged.
:param overwrite:
Whether repeated keys should have their values overwritten,
retaining the last value, as per given order of dictionaries.
This is the default behavior (equivalent to ``overwrite=True``).
If ``overwrite=False``, repeated keys are simply ignored.
Example::
>> merge({'a': 1}, {'a': 10, 'b': 2}, overwrite=True)
{'a': 10, 'b': 2}
>> merge({'a': 1}, {'a': 10, 'b': 2}, overwrite=False)
{'a': 1, 'b': 2}
:param deep:
Whether merging should proceed recursively, and cause
corresponding subdictionaries to be merged into each other.
By default, this does not happen (equivalent to ``deep=False``).
Example::
>> merge({'a': {'b': 1}}, {'a': {'c': 2}}, deep=False)
{'a': {'c': 2}}
>> merge({'a': {'b': 1}}, {'a': {'c': 2}}, deep=True)
{'a': {'b': 1, 'c': 2}}
:return: Merged dictionary
.. note:: For ``dict``\ s ``a`` and ``b``, ``merge(a, b)`` is equivalent
to ``extend({}, a, b)``.
.. versionadded:: 0.0.2
The ``overwrite`` keyword argument.
"""
ensure_argcount(dicts, min_=1)
dicts = list(imap(ensure_mapping, dicts))
ensure_keyword_args(kwargs, optional=('deep', 'overwrite'))
return _nary_dict_update(dicts, copy=True,
deep=kwargs.get('deep', False),
overwrite=kwargs.get('overwrite', True)) | python | def merge(*dicts, **kwargs):
"""Merges two or more dictionaries into a single one.
Optional keyword arguments allow to control the exact way
in which the dictionaries will be merged.
:param overwrite:
Whether repeated keys should have their values overwritten,
retaining the last value, as per given order of dictionaries.
This is the default behavior (equivalent to ``overwrite=True``).
If ``overwrite=False``, repeated keys are simply ignored.
Example::
>> merge({'a': 1}, {'a': 10, 'b': 2}, overwrite=True)
{'a': 10, 'b': 2}
>> merge({'a': 1}, {'a': 10, 'b': 2}, overwrite=False)
{'a': 1, 'b': 2}
:param deep:
Whether merging should proceed recursively, and cause
corresponding subdictionaries to be merged into each other.
By default, this does not happen (equivalent to ``deep=False``).
Example::
>> merge({'a': {'b': 1}}, {'a': {'c': 2}}, deep=False)
{'a': {'c': 2}}
>> merge({'a': {'b': 1}}, {'a': {'c': 2}}, deep=True)
{'a': {'b': 1, 'c': 2}}
:return: Merged dictionary
.. note:: For ``dict``\ s ``a`` and ``b``, ``merge(a, b)`` is equivalent
to ``extend({}, a, b)``.
.. versionadded:: 0.0.2
The ``overwrite`` keyword argument.
"""
ensure_argcount(dicts, min_=1)
dicts = list(imap(ensure_mapping, dicts))
ensure_keyword_args(kwargs, optional=('deep', 'overwrite'))
return _nary_dict_update(dicts, copy=True,
deep=kwargs.get('deep', False),
overwrite=kwargs.get('overwrite', True)) | [
"def",
"merge",
"(",
"*",
"dicts",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_argcount",
"(",
"dicts",
",",
"min_",
"=",
"1",
")",
"dicts",
"=",
"list",
"(",
"imap",
"(",
"ensure_mapping",
",",
"dicts",
")",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'deep'",
",",
"'overwrite'",
")",
")",
"return",
"_nary_dict_update",
"(",
"dicts",
",",
"copy",
"=",
"True",
",",
"deep",
"=",
"kwargs",
".",
"get",
"(",
"'deep'",
",",
"False",
")",
",",
"overwrite",
"=",
"kwargs",
".",
"get",
"(",
"'overwrite'",
",",
"True",
")",
")"
]
| Merges two or more dictionaries into a single one.
Optional keyword arguments allow to control the exact way
in which the dictionaries will be merged.
:param overwrite:
Whether repeated keys should have their values overwritten,
retaining the last value, as per given order of dictionaries.
This is the default behavior (equivalent to ``overwrite=True``).
If ``overwrite=False``, repeated keys are simply ignored.
Example::
>> merge({'a': 1}, {'a': 10, 'b': 2}, overwrite=True)
{'a': 10, 'b': 2}
>> merge({'a': 1}, {'a': 10, 'b': 2}, overwrite=False)
{'a': 1, 'b': 2}
:param deep:
Whether merging should proceed recursively, and cause
corresponding subdictionaries to be merged into each other.
By default, this does not happen (equivalent to ``deep=False``).
Example::
>> merge({'a': {'b': 1}}, {'a': {'c': 2}}, deep=False)
{'a': {'c': 2}}
>> merge({'a': {'b': 1}}, {'a': {'c': 2}}, deep=True)
{'a': {'b': 1, 'c': 2}}
:return: Merged dictionary
.. note:: For ``dict``\ s ``a`` and ``b``, ``merge(a, b)`` is equivalent
to ``extend({}, a, b)``.
.. versionadded:: 0.0.2
The ``overwrite`` keyword argument. | [
"Merges",
"two",
"or",
"more",
"dictionaries",
"into",
"a",
"single",
"one",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L355-L403 | train |
Xion/taipan | taipan/collections/dicts.py | extend | def extend(dict_, *dicts, **kwargs):
"""Extend a dictionary with keys and values from other dictionaries.
:param dict_: Dictionary to extend
Optional keyword arguments allow to control the exact way
in which ``dict_`` will be extended.
:param overwrite:
Whether repeated keys should have their values overwritten,
retaining the last value, as per given order of dictionaries.
This is the default behavior (equivalent to ``overwrite=True``).
If ``overwrite=False``, repeated keys are simply ignored.
Example::
>> foo = {'a': 1}
>> extend(foo, {'a': 10, 'b': 2}, overwrite=True)
{'a': 10, 'b': 2}
>> foo = {'a': 1}
>> extend(foo, {'a': 10, 'b': 2}, overwrite=False)
{'a': 1, 'b': 2}
:param deep:
Whether extending should proceed recursively, and cause
corresponding subdictionaries to be merged into each other.
By default, this does not happen (equivalent to ``deep=False``).
Example::
>> foo = {'a': {'b': 1}}
>> extend(foo, {'a': {'c': 2}}, deep=False)
{'a': {'c': 2}}
>> foo = {'a': {'b': 1}}
>> extend(foo, {'a': {'c': 2}}, deep=True)
{'a': {'b': 1, 'c': 2}}
:return: Extended ``dict_``
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
dicts = list(imap(ensure_mapping, dicts))
ensure_keyword_args(kwargs, optional=('deep', 'overwrite'))
return _nary_dict_update([dict_] + dicts, copy=False,
deep=kwargs.get('deep', False),
overwrite=kwargs.get('overwrite', True)) | python | def extend(dict_, *dicts, **kwargs):
"""Extend a dictionary with keys and values from other dictionaries.
:param dict_: Dictionary to extend
Optional keyword arguments allow to control the exact way
in which ``dict_`` will be extended.
:param overwrite:
Whether repeated keys should have their values overwritten,
retaining the last value, as per given order of dictionaries.
This is the default behavior (equivalent to ``overwrite=True``).
If ``overwrite=False``, repeated keys are simply ignored.
Example::
>> foo = {'a': 1}
>> extend(foo, {'a': 10, 'b': 2}, overwrite=True)
{'a': 10, 'b': 2}
>> foo = {'a': 1}
>> extend(foo, {'a': 10, 'b': 2}, overwrite=False)
{'a': 1, 'b': 2}
:param deep:
Whether extending should proceed recursively, and cause
corresponding subdictionaries to be merged into each other.
By default, this does not happen (equivalent to ``deep=False``).
Example::
>> foo = {'a': {'b': 1}}
>> extend(foo, {'a': {'c': 2}}, deep=False)
{'a': {'c': 2}}
>> foo = {'a': {'b': 1}}
>> extend(foo, {'a': {'c': 2}}, deep=True)
{'a': {'b': 1, 'c': 2}}
:return: Extended ``dict_``
.. versionadded:: 0.0.2
"""
ensure_mapping(dict_)
dicts = list(imap(ensure_mapping, dicts))
ensure_keyword_args(kwargs, optional=('deep', 'overwrite'))
return _nary_dict_update([dict_] + dicts, copy=False,
deep=kwargs.get('deep', False),
overwrite=kwargs.get('overwrite', True)) | [
"def",
"extend",
"(",
"dict_",
",",
"*",
"dicts",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"dicts",
"=",
"list",
"(",
"imap",
"(",
"ensure_mapping",
",",
"dicts",
")",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'deep'",
",",
"'overwrite'",
")",
")",
"return",
"_nary_dict_update",
"(",
"[",
"dict_",
"]",
"+",
"dicts",
",",
"copy",
"=",
"False",
",",
"deep",
"=",
"kwargs",
".",
"get",
"(",
"'deep'",
",",
"False",
")",
",",
"overwrite",
"=",
"kwargs",
".",
"get",
"(",
"'overwrite'",
",",
"True",
")",
")"
]
| Extend a dictionary with keys and values from other dictionaries.
:param dict_: Dictionary to extend
Optional keyword arguments allow to control the exact way
in which ``dict_`` will be extended.
:param overwrite:
Whether repeated keys should have their values overwritten,
retaining the last value, as per given order of dictionaries.
This is the default behavior (equivalent to ``overwrite=True``).
If ``overwrite=False``, repeated keys are simply ignored.
Example::
>> foo = {'a': 1}
>> extend(foo, {'a': 10, 'b': 2}, overwrite=True)
{'a': 10, 'b': 2}
>> foo = {'a': 1}
>> extend(foo, {'a': 10, 'b': 2}, overwrite=False)
{'a': 1, 'b': 2}
:param deep:
Whether extending should proceed recursively, and cause
corresponding subdictionaries to be merged into each other.
By default, this does not happen (equivalent to ``deep=False``).
Example::
>> foo = {'a': {'b': 1}}
>> extend(foo, {'a': {'c': 2}}, deep=False)
{'a': {'c': 2}}
>> foo = {'a': {'b': 1}}
>> extend(foo, {'a': {'c': 2}}, deep=True)
{'a': {'b': 1, 'c': 2}}
:return: Extended ``dict_``
.. versionadded:: 0.0.2 | [
"Extend",
"a",
"dictionary",
"with",
"keys",
"and",
"values",
"from",
"other",
"dictionaries",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L406-L456 | train |
Xion/taipan | taipan/collections/dicts.py | _nary_dict_update | def _nary_dict_update(dicts, **kwargs):
"""Implementation of n-argument ``dict.update``,
with flags controlling the exact strategy.
"""
copy = kwargs['copy']
res = dicts[0].copy() if copy else dicts[0]
if len(dicts) == 1:
return res
# decide what strategy to use when updating a dictionary
# with the values from another: {(non)recursive} x {(non)overwriting}
deep = kwargs['deep']
overwrite = kwargs['overwrite']
if deep:
dict_update = curry(_recursive_dict_update, overwrite=overwrite)
else:
if overwrite:
dict_update = res.__class__.update
else:
def dict_update(dict_, other):
for k, v in iteritems(other):
dict_.setdefault(k, v)
for d in dicts[1:]:
dict_update(res, d)
return res | python | def _nary_dict_update(dicts, **kwargs):
"""Implementation of n-argument ``dict.update``,
with flags controlling the exact strategy.
"""
copy = kwargs['copy']
res = dicts[0].copy() if copy else dicts[0]
if len(dicts) == 1:
return res
# decide what strategy to use when updating a dictionary
# with the values from another: {(non)recursive} x {(non)overwriting}
deep = kwargs['deep']
overwrite = kwargs['overwrite']
if deep:
dict_update = curry(_recursive_dict_update, overwrite=overwrite)
else:
if overwrite:
dict_update = res.__class__.update
else:
def dict_update(dict_, other):
for k, v in iteritems(other):
dict_.setdefault(k, v)
for d in dicts[1:]:
dict_update(res, d)
return res | [
"def",
"_nary_dict_update",
"(",
"dicts",
",",
"*",
"*",
"kwargs",
")",
":",
"copy",
"=",
"kwargs",
"[",
"'copy'",
"]",
"res",
"=",
"dicts",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"if",
"copy",
"else",
"dicts",
"[",
"0",
"]",
"if",
"len",
"(",
"dicts",
")",
"==",
"1",
":",
"return",
"res",
"# decide what strategy to use when updating a dictionary",
"# with the values from another: {(non)recursive} x {(non)overwriting}",
"deep",
"=",
"kwargs",
"[",
"'deep'",
"]",
"overwrite",
"=",
"kwargs",
"[",
"'overwrite'",
"]",
"if",
"deep",
":",
"dict_update",
"=",
"curry",
"(",
"_recursive_dict_update",
",",
"overwrite",
"=",
"overwrite",
")",
"else",
":",
"if",
"overwrite",
":",
"dict_update",
"=",
"res",
".",
"__class__",
".",
"update",
"else",
":",
"def",
"dict_update",
"(",
"dict_",
",",
"other",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"other",
")",
":",
"dict_",
".",
"setdefault",
"(",
"k",
",",
"v",
")",
"for",
"d",
"in",
"dicts",
"[",
"1",
":",
"]",
":",
"dict_update",
"(",
"res",
",",
"d",
")",
"return",
"res"
]
| Implementation of n-argument ``dict.update``,
with flags controlling the exact strategy. | [
"Implementation",
"of",
"n",
"-",
"argument",
"dict",
".",
"update",
"with",
"flags",
"controlling",
"the",
"exact",
"strategy",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L459-L484 | train |
Xion/taipan | taipan/collections/dicts.py | invert | def invert(dict_):
"""Return an inverted dictionary, where former values are keys
and former keys are values.
.. warning::
If more than one key maps to any given value in input dictionary,
it is undefined which one will be chosen for the result.
:param dict_: Dictionary to swap keys and values in
:return: Inverted dictionary
"""
ensure_mapping(dict_)
return dict_.__class__(izip(itervalues(dict_), iterkeys(dict_))) | python | def invert(dict_):
"""Return an inverted dictionary, where former values are keys
and former keys are values.
.. warning::
If more than one key maps to any given value in input dictionary,
it is undefined which one will be chosen for the result.
:param dict_: Dictionary to swap keys and values in
:return: Inverted dictionary
"""
ensure_mapping(dict_)
return dict_.__class__(izip(itervalues(dict_), iterkeys(dict_))) | [
"def",
"invert",
"(",
"dict_",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"return",
"dict_",
".",
"__class__",
"(",
"izip",
"(",
"itervalues",
"(",
"dict_",
")",
",",
"iterkeys",
"(",
"dict_",
")",
")",
")"
]
| Return an inverted dictionary, where former values are keys
and former keys are values.
.. warning::
If more than one key maps to any given value in input dictionary,
it is undefined which one will be chosen for the result.
:param dict_: Dictionary to swap keys and values in
:return: Inverted dictionary | [
"Return",
"an",
"inverted",
"dictionary",
"where",
"former",
"values",
"are",
"keys",
"and",
"former",
"keys",
"are",
"values",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L511-L524 | train |
tjcsl/cslbot | cslbot/commands/wikipath.py | cmd | def cmd(send, msg, args):
"""Find a path between two wikipedia articles.
Syntax: {command} [article] [article]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('first', nargs='?')
parser.add_argument('second', nargs='?')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if not cmdargs.first:
cmdargs.first = get_article()
else:
if not check_article(cmdargs.first):
send("%s isn't a valid wikipedia article, fetching a random one..." % cmdargs.first)
cmdargs.first = get_article()
if not cmdargs.second:
cmdargs.second = get_article()
else:
if not check_article(cmdargs.second):
send("%s isn't a valid wikipedia article, fetching a random one..." % cmdargs.second)
cmdargs.second = get_article()
path = gen_path(cmdargs)
if path:
send(path.replace('_', ' '))
else:
send("No path found between %s and %s. Do you need to add more links?" % (cmdargs.first.replace('_', ' '), cmdargs.second.replace('_', ' '))) | python | def cmd(send, msg, args):
"""Find a path between two wikipedia articles.
Syntax: {command} [article] [article]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('first', nargs='?')
parser.add_argument('second', nargs='?')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if not cmdargs.first:
cmdargs.first = get_article()
else:
if not check_article(cmdargs.first):
send("%s isn't a valid wikipedia article, fetching a random one..." % cmdargs.first)
cmdargs.first = get_article()
if not cmdargs.second:
cmdargs.second = get_article()
else:
if not check_article(cmdargs.second):
send("%s isn't a valid wikipedia article, fetching a random one..." % cmdargs.second)
cmdargs.second = get_article()
path = gen_path(cmdargs)
if path:
send(path.replace('_', ' '))
else:
send("No path found between %s and %s. Do you need to add more links?" % (cmdargs.first.replace('_', ' '), cmdargs.second.replace('_', ' '))) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'first'",
",",
"nargs",
"=",
"'?'",
")",
"parser",
".",
"add_argument",
"(",
"'second'",
",",
"nargs",
"=",
"'?'",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"if",
"not",
"cmdargs",
".",
"first",
":",
"cmdargs",
".",
"first",
"=",
"get_article",
"(",
")",
"else",
":",
"if",
"not",
"check_article",
"(",
"cmdargs",
".",
"first",
")",
":",
"send",
"(",
"\"%s isn't a valid wikipedia article, fetching a random one...\"",
"%",
"cmdargs",
".",
"first",
")",
"cmdargs",
".",
"first",
"=",
"get_article",
"(",
")",
"if",
"not",
"cmdargs",
".",
"second",
":",
"cmdargs",
".",
"second",
"=",
"get_article",
"(",
")",
"else",
":",
"if",
"not",
"check_article",
"(",
"cmdargs",
".",
"second",
")",
":",
"send",
"(",
"\"%s isn't a valid wikipedia article, fetching a random one...\"",
"%",
"cmdargs",
".",
"second",
")",
"cmdargs",
".",
"second",
"=",
"get_article",
"(",
")",
"path",
"=",
"gen_path",
"(",
"cmdargs",
")",
"if",
"path",
":",
"send",
"(",
"path",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
")",
"else",
":",
"send",
"(",
"\"No path found between %s and %s. Do you need to add more links?\"",
"%",
"(",
"cmdargs",
".",
"first",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
",",
"cmdargs",
".",
"second",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
")",
")"
]
| Find a path between two wikipedia articles.
Syntax: {command} [article] [article] | [
"Find",
"a",
"path",
"between",
"two",
"wikipedia",
"articles",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wikipath.py#L56-L87 | train |
Xion/taipan | taipan/collections/sets.py | remove_subset | def remove_subset(set_, subset):
"""Remove a subset from given set.
This is essentially an extension of :func:`set.remove`
to work with more than one set element.
:raise KeyError: If some element from ``subset`` is not present in ``set_``
.. versionadded:: 0.0.2
"""
ensure_set(set_)
ensure_iterable(subset)
for elem in subset:
set_.remove(elem) | python | def remove_subset(set_, subset):
"""Remove a subset from given set.
This is essentially an extension of :func:`set.remove`
to work with more than one set element.
:raise KeyError: If some element from ``subset`` is not present in ``set_``
.. versionadded:: 0.0.2
"""
ensure_set(set_)
ensure_iterable(subset)
for elem in subset:
set_.remove(elem) | [
"def",
"remove_subset",
"(",
"set_",
",",
"subset",
")",
":",
"ensure_set",
"(",
"set_",
")",
"ensure_iterable",
"(",
"subset",
")",
"for",
"elem",
"in",
"subset",
":",
"set_",
".",
"remove",
"(",
"elem",
")"
]
| Remove a subset from given set.
This is essentially an extension of :func:`set.remove`
to work with more than one set element.
:raise KeyError: If some element from ``subset`` is not present in ``set_``
.. versionadded:: 0.0.2 | [
"Remove",
"a",
"subset",
"from",
"given",
"set",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/sets.py#L36-L50 | train |
Xion/taipan | taipan/collections/sets.py | power | def power(set_):
"""Returns all subsets of given set.
:return: Powerset of given set, i.e. iterable containing all its subsets,
sorted by ascending cardinality.
"""
ensure_countable(set_)
result = chain.from_iterable(combinations(set_, r)
for r in xrange(len(set_) + 1))
return _harmonize_subset_types(set_, result) | python | def power(set_):
"""Returns all subsets of given set.
:return: Powerset of given set, i.e. iterable containing all its subsets,
sorted by ascending cardinality.
"""
ensure_countable(set_)
result = chain.from_iterable(combinations(set_, r)
for r in xrange(len(set_) + 1))
return _harmonize_subset_types(set_, result) | [
"def",
"power",
"(",
"set_",
")",
":",
"ensure_countable",
"(",
"set_",
")",
"result",
"=",
"chain",
".",
"from_iterable",
"(",
"combinations",
"(",
"set_",
",",
"r",
")",
"for",
"r",
"in",
"xrange",
"(",
"len",
"(",
"set_",
")",
"+",
"1",
")",
")",
"return",
"_harmonize_subset_types",
"(",
"set_",
",",
"result",
")"
]
| Returns all subsets of given set.
:return: Powerset of given set, i.e. iterable containing all its subsets,
sorted by ascending cardinality. | [
"Returns",
"all",
"subsets",
"of",
"given",
"set",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/sets.py#L73-L83 | train |
Xion/taipan | taipan/collections/sets.py | trivial_partition | def trivial_partition(set_):
"""Returns a parition of given set into 1-element subsets.
:return: Trivial partition of given set, i.e. iterable containing disjoint
1-element sets, each consisting of a single element
from given set
"""
ensure_countable(set_)
result = ((x,) for x in set_)
return _harmonize_subset_types(set_, result) | python | def trivial_partition(set_):
"""Returns a parition of given set into 1-element subsets.
:return: Trivial partition of given set, i.e. iterable containing disjoint
1-element sets, each consisting of a single element
from given set
"""
ensure_countable(set_)
result = ((x,) for x in set_)
return _harmonize_subset_types(set_, result) | [
"def",
"trivial_partition",
"(",
"set_",
")",
":",
"ensure_countable",
"(",
"set_",
")",
"result",
"=",
"(",
"(",
"x",
",",
")",
"for",
"x",
"in",
"set_",
")",
"return",
"_harmonize_subset_types",
"(",
"set_",
",",
"result",
")"
]
| Returns a parition of given set into 1-element subsets.
:return: Trivial partition of given set, i.e. iterable containing disjoint
1-element sets, each consisting of a single element
from given set | [
"Returns",
"a",
"parition",
"of",
"given",
"set",
"into",
"1",
"-",
"element",
"subsets",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/sets.py#L89-L99 | train |
tjcsl/cslbot | cslbot/commands/demorse.py | cmd | def cmd(send, msg, _):
"""Converts morse to ascii.
Syntax: {command} <text>
"""
demorse_codes = {
'.----': '1',
'-.--': 'y',
'..-': 'u',
'...': 's',
'-.-.': 'c',
'.-.-.': '+',
'--..--': ',',
'-.-': 'k',
'.--.': 'p',
'----.': '9',
'-----': '0',
' ': ' ',
'...--': '3',
'-....-': '-',
'...-..-': '$',
'..---': '2',
'.--.-.': '@',
'-...-': '=',
'-....': '6',
'...-': 'v',
'.----.': "'",
'....': 'h',
'.....': '5',
'....-': '4',
'.': 'e',
'.-.-.-': '.',
'-': 't',
'.-..': 'l',
'..': 'i',
'.-': 'a',
'-..-': 'x',
'-...': 'b',
'-.': 'n',
'.-..-.': '"',
'.--': 'w',
'-.--.-': ')',
'--...': '7',
'.-.': 'r',
'.---': 'j',
'---..': '8',
'--': 'm',
'-.-.-.': ';',
'-.-.--': '!',
'-..': 'd',
'-.--.': '(',
'..-.': 'f',
'---...': ':',
'-..-.': '/',
'..--.-': '_',
'.-...': '&',
'..--..': '?',
'--.': 'g',
'--..': 'z',
'--.-': 'q',
'---': 'o'
}
demorse = ""
if not msg:
send("demorse what?")
return
for word in msg.lower().split(" "):
for c in word.split():
if c in demorse_codes:
demorse += demorse_codes[c]
else:
demorse += "?"
demorse += " "
send(demorse) | python | def cmd(send, msg, _):
"""Converts morse to ascii.
Syntax: {command} <text>
"""
demorse_codes = {
'.----': '1',
'-.--': 'y',
'..-': 'u',
'...': 's',
'-.-.': 'c',
'.-.-.': '+',
'--..--': ',',
'-.-': 'k',
'.--.': 'p',
'----.': '9',
'-----': '0',
' ': ' ',
'...--': '3',
'-....-': '-',
'...-..-': '$',
'..---': '2',
'.--.-.': '@',
'-...-': '=',
'-....': '6',
'...-': 'v',
'.----.': "'",
'....': 'h',
'.....': '5',
'....-': '4',
'.': 'e',
'.-.-.-': '.',
'-': 't',
'.-..': 'l',
'..': 'i',
'.-': 'a',
'-..-': 'x',
'-...': 'b',
'-.': 'n',
'.-..-.': '"',
'.--': 'w',
'-.--.-': ')',
'--...': '7',
'.-.': 'r',
'.---': 'j',
'---..': '8',
'--': 'm',
'-.-.-.': ';',
'-.-.--': '!',
'-..': 'd',
'-.--.': '(',
'..-.': 'f',
'---...': ':',
'-..-.': '/',
'..--.-': '_',
'.-...': '&',
'..--..': '?',
'--.': 'g',
'--..': 'z',
'--.-': 'q',
'---': 'o'
}
demorse = ""
if not msg:
send("demorse what?")
return
for word in msg.lower().split(" "):
for c in word.split():
if c in demorse_codes:
demorse += demorse_codes[c]
else:
demorse += "?"
demorse += " "
send(demorse) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"demorse_codes",
"=",
"{",
"'.----'",
":",
"'1'",
",",
"'-.--'",
":",
"'y'",
",",
"'..-'",
":",
"'u'",
",",
"'...'",
":",
"'s'",
",",
"'-.-.'",
":",
"'c'",
",",
"'.-.-.'",
":",
"'+'",
",",
"'--..--'",
":",
"','",
",",
"'-.-'",
":",
"'k'",
",",
"'.--.'",
":",
"'p'",
",",
"'----.'",
":",
"'9'",
",",
"'-----'",
":",
"'0'",
",",
"' '",
":",
"' '",
",",
"'...--'",
":",
"'3'",
",",
"'-....-'",
":",
"'-'",
",",
"'...-..-'",
":",
"'$'",
",",
"'..---'",
":",
"'2'",
",",
"'.--.-.'",
":",
"'@'",
",",
"'-...-'",
":",
"'='",
",",
"'-....'",
":",
"'6'",
",",
"'...-'",
":",
"'v'",
",",
"'.----.'",
":",
"\"'\"",
",",
"'....'",
":",
"'h'",
",",
"'.....'",
":",
"'5'",
",",
"'....-'",
":",
"'4'",
",",
"'.'",
":",
"'e'",
",",
"'.-.-.-'",
":",
"'.'",
",",
"'-'",
":",
"'t'",
",",
"'.-..'",
":",
"'l'",
",",
"'..'",
":",
"'i'",
",",
"'.-'",
":",
"'a'",
",",
"'-..-'",
":",
"'x'",
",",
"'-...'",
":",
"'b'",
",",
"'-.'",
":",
"'n'",
",",
"'.-..-.'",
":",
"'\"'",
",",
"'.--'",
":",
"'w'",
",",
"'-.--.-'",
":",
"')'",
",",
"'--...'",
":",
"'7'",
",",
"'.-.'",
":",
"'r'",
",",
"'.---'",
":",
"'j'",
",",
"'---..'",
":",
"'8'",
",",
"'--'",
":",
"'m'",
",",
"'-.-.-.'",
":",
"';'",
",",
"'-.-.--'",
":",
"'!'",
",",
"'-..'",
":",
"'d'",
",",
"'-.--.'",
":",
"'('",
",",
"'..-.'",
":",
"'f'",
",",
"'---...'",
":",
"':'",
",",
"'-..-.'",
":",
"'/'",
",",
"'..--.-'",
":",
"'_'",
",",
"'.-...'",
":",
"'&'",
",",
"'..--..'",
":",
"'?'",
",",
"'--.'",
":",
"'g'",
",",
"'--..'",
":",
"'z'",
",",
"'--.-'",
":",
"'q'",
",",
"'---'",
":",
"'o'",
"}",
"demorse",
"=",
"\"\"",
"if",
"not",
"msg",
":",
"send",
"(",
"\"demorse what?\"",
")",
"return",
"for",
"word",
"in",
"msg",
".",
"lower",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
":",
"for",
"c",
"in",
"word",
".",
"split",
"(",
")",
":",
"if",
"c",
"in",
"demorse_codes",
":",
"demorse",
"+=",
"demorse_codes",
"[",
"c",
"]",
"else",
":",
"demorse",
"+=",
"\"?\"",
"demorse",
"+=",
"\" \"",
"send",
"(",
"demorse",
")"
]
| Converts morse to ascii.
Syntax: {command} <text> | [
"Converts",
"morse",
"to",
"ascii",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/demorse.py#L22-L96 | train |
tjcsl/cslbot | cslbot/commands/wai.py | cmd | def cmd(send, *_):
"""Gives a reason for something.
Syntax: {command}
"""
a = ["primary", "secondary", "tertiary", "hydraulic", "compressed", "required", "pseudo", "intangible", "flux"]
b = [
"compressor", "engine", "lift", "elevator", "irc bot", "stabilizer", "computer", "fwilson", "csl", "4506", "router", "switch", "thingy",
"capacitor"
]
c = [
"broke", "exploded", "corrupted", "melted", "froze", "died", "reset", "was seen by the godofskies", "burned", "corroded", "reversed polarity",
"was accidentallied", "nuked"
]
send("because %s %s %s" % ((choice(a), choice(b), choice(c)))) | python | def cmd(send, *_):
"""Gives a reason for something.
Syntax: {command}
"""
a = ["primary", "secondary", "tertiary", "hydraulic", "compressed", "required", "pseudo", "intangible", "flux"]
b = [
"compressor", "engine", "lift", "elevator", "irc bot", "stabilizer", "computer", "fwilson", "csl", "4506", "router", "switch", "thingy",
"capacitor"
]
c = [
"broke", "exploded", "corrupted", "melted", "froze", "died", "reset", "was seen by the godofskies", "burned", "corroded", "reversed polarity",
"was accidentallied", "nuked"
]
send("because %s %s %s" % ((choice(a), choice(b), choice(c)))) | [
"def",
"cmd",
"(",
"send",
",",
"*",
"_",
")",
":",
"a",
"=",
"[",
"\"primary\"",
",",
"\"secondary\"",
",",
"\"tertiary\"",
",",
"\"hydraulic\"",
",",
"\"compressed\"",
",",
"\"required\"",
",",
"\"pseudo\"",
",",
"\"intangible\"",
",",
"\"flux\"",
"]",
"b",
"=",
"[",
"\"compressor\"",
",",
"\"engine\"",
",",
"\"lift\"",
",",
"\"elevator\"",
",",
"\"irc bot\"",
",",
"\"stabilizer\"",
",",
"\"computer\"",
",",
"\"fwilson\"",
",",
"\"csl\"",
",",
"\"4506\"",
",",
"\"router\"",
",",
"\"switch\"",
",",
"\"thingy\"",
",",
"\"capacitor\"",
"]",
"c",
"=",
"[",
"\"broke\"",
",",
"\"exploded\"",
",",
"\"corrupted\"",
",",
"\"melted\"",
",",
"\"froze\"",
",",
"\"died\"",
",",
"\"reset\"",
",",
"\"was seen by the godofskies\"",
",",
"\"burned\"",
",",
"\"corroded\"",
",",
"\"reversed polarity\"",
",",
"\"was accidentallied\"",
",",
"\"nuked\"",
"]",
"send",
"(",
"\"because %s %s %s\"",
"%",
"(",
"(",
"choice",
"(",
"a",
")",
",",
"choice",
"(",
"b",
")",
",",
"choice",
"(",
"c",
")",
")",
")",
")"
]
| Gives a reason for something.
Syntax: {command} | [
"Gives",
"a",
"reason",
"for",
"something",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wai.py#L24-L39 | train |
Xion/taipan | taipan/lang.py | cast | def cast(type_, value, default=ABSENT):
"""Cast a value to given type, optionally returning a default, if provided.
:param type_: Type to cast the ``value`` into
:param value: Value to cast into ``type_``
:return: ``value`` casted to ``type_``.
If cast was unsuccessful and ``default`` was provided,
it is returned instead.
:raise AssertionError: When ``type_`` is not actually a Python type
:raise TypeError: When cast was unsuccessful and no ``default`` was given
"""
# ``type_`` not being a type would theoretically be grounds for TypeError,
# but since that kind of exception is a valid and expected outcome here
# in some cases, we use the closest Python has to compilation error instead
assert isinstance(type_, type)
# conunterintuitively, invalid conversions to numeric types
# would raise ValueError rather than the more appropriate TypeError,
# so we correct this inconsistency
to_number = issubclass(type_, Number)
exception = ValueError if to_number else TypeError
try:
return type_(value)
except exception as e:
if default is ABSENT:
if to_number:
# since Python 3 chains exceptions, we can supply slightly
# more relevant error message while still retaining
# the original information of ValueError as the cause
msg = ("cannot convert %r to %r" % (value, type_) if IS_PY3
else str(e))
raise TypeError(msg)
else:
raise
return type_(default) | python | def cast(type_, value, default=ABSENT):
"""Cast a value to given type, optionally returning a default, if provided.
:param type_: Type to cast the ``value`` into
:param value: Value to cast into ``type_``
:return: ``value`` casted to ``type_``.
If cast was unsuccessful and ``default`` was provided,
it is returned instead.
:raise AssertionError: When ``type_`` is not actually a Python type
:raise TypeError: When cast was unsuccessful and no ``default`` was given
"""
# ``type_`` not being a type would theoretically be grounds for TypeError,
# but since that kind of exception is a valid and expected outcome here
# in some cases, we use the closest Python has to compilation error instead
assert isinstance(type_, type)
# conunterintuitively, invalid conversions to numeric types
# would raise ValueError rather than the more appropriate TypeError,
# so we correct this inconsistency
to_number = issubclass(type_, Number)
exception = ValueError if to_number else TypeError
try:
return type_(value)
except exception as e:
if default is ABSENT:
if to_number:
# since Python 3 chains exceptions, we can supply slightly
# more relevant error message while still retaining
# the original information of ValueError as the cause
msg = ("cannot convert %r to %r" % (value, type_) if IS_PY3
else str(e))
raise TypeError(msg)
else:
raise
return type_(default) | [
"def",
"cast",
"(",
"type_",
",",
"value",
",",
"default",
"=",
"ABSENT",
")",
":",
"# ``type_`` not being a type would theoretically be grounds for TypeError,",
"# but since that kind of exception is a valid and expected outcome here",
"# in some cases, we use the closest Python has to compilation error instead",
"assert",
"isinstance",
"(",
"type_",
",",
"type",
")",
"# conunterintuitively, invalid conversions to numeric types",
"# would raise ValueError rather than the more appropriate TypeError,",
"# so we correct this inconsistency",
"to_number",
"=",
"issubclass",
"(",
"type_",
",",
"Number",
")",
"exception",
"=",
"ValueError",
"if",
"to_number",
"else",
"TypeError",
"try",
":",
"return",
"type_",
"(",
"value",
")",
"except",
"exception",
"as",
"e",
":",
"if",
"default",
"is",
"ABSENT",
":",
"if",
"to_number",
":",
"# since Python 3 chains exceptions, we can supply slightly",
"# more relevant error message while still retaining",
"# the original information of ValueError as the cause",
"msg",
"=",
"(",
"\"cannot convert %r to %r\"",
"%",
"(",
"value",
",",
"type_",
")",
"if",
"IS_PY3",
"else",
"str",
"(",
"e",
")",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"else",
":",
"raise",
"return",
"type_",
"(",
"default",
")"
]
| Cast a value to given type, optionally returning a default, if provided.
:param type_: Type to cast the ``value`` into
:param value: Value to cast into ``type_``
:return: ``value`` casted to ``type_``.
If cast was unsuccessful and ``default`` was provided,
it is returned instead.
:raise AssertionError: When ``type_`` is not actually a Python type
:raise TypeError: When cast was unsuccessful and no ``default`` was given | [
"Cast",
"a",
"value",
"to",
"given",
"type",
"optionally",
"returning",
"a",
"default",
"if",
"provided",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/lang.py#L76-L113 | train |
Xion/taipan | taipan/lang.py | is_identifier | def is_identifier(s):
"""Check whether given string is a valid Python identifier.
Note that this excludes language keywords, even though they exhibit
a general form of an identifier. See also :func:`has_identifier_form`.
:param s: String to check
:return: Whether ``s`` is a valid Python identifier
"""
ensure_string(s)
if not IDENTIFIER_FORM_RE.match(s):
return False
if is_keyword(s):
return False
# ``None`` is not part of ``keyword.kwlist`` in Python 2.x,
# so we need to check for it explicitly
if s == 'None' and not IS_PY3:
return False
return True | python | def is_identifier(s):
"""Check whether given string is a valid Python identifier.
Note that this excludes language keywords, even though they exhibit
a general form of an identifier. See also :func:`has_identifier_form`.
:param s: String to check
:return: Whether ``s`` is a valid Python identifier
"""
ensure_string(s)
if not IDENTIFIER_FORM_RE.match(s):
return False
if is_keyword(s):
return False
# ``None`` is not part of ``keyword.kwlist`` in Python 2.x,
# so we need to check for it explicitly
if s == 'None' and not IS_PY3:
return False
return True | [
"def",
"is_identifier",
"(",
"s",
")",
":",
"ensure_string",
"(",
"s",
")",
"if",
"not",
"IDENTIFIER_FORM_RE",
".",
"match",
"(",
"s",
")",
":",
"return",
"False",
"if",
"is_keyword",
"(",
"s",
")",
":",
"return",
"False",
"# ``None`` is not part of ``keyword.kwlist`` in Python 2.x,",
"# so we need to check for it explicitly",
"if",
"s",
"==",
"'None'",
"and",
"not",
"IS_PY3",
":",
"return",
"False",
"return",
"True"
]
| Check whether given string is a valid Python identifier.
Note that this excludes language keywords, even though they exhibit
a general form of an identifier. See also :func:`has_identifier_form`.
:param s: String to check
:return: Whether ``s`` is a valid Python identifier | [
"Check",
"whether",
"given",
"string",
"is",
"a",
"valid",
"Python",
"identifier",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/lang.py#L182-L203 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | normalize | def normalize(pw):
""" Lower case, and change the symbols to closest characters"""
pw_lower = pw.lower()
return ''.join(helper.L33T.get(c, c) for c in pw_lower) | python | def normalize(pw):
""" Lower case, and change the symbols to closest characters"""
pw_lower = pw.lower()
return ''.join(helper.L33T.get(c, c) for c in pw_lower) | [
"def",
"normalize",
"(",
"pw",
")",
":",
"pw_lower",
"=",
"pw",
".",
"lower",
"(",
")",
"return",
"''",
".",
"join",
"(",
"helper",
".",
"L33T",
".",
"get",
"(",
"c",
",",
"c",
")",
"for",
"c",
"in",
"pw_lower",
")"
]
| Lower case, and change the symbols to closest characters | [
"Lower",
"case",
"and",
"change",
"the",
"symbols",
"to",
"closest",
"characters"
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L441-L444 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | PwModel.qth_pw | def qth_pw(self, q):
"""
returns the qth most probable element in the dawg.
"""
return heapq.nlargest(q + 2, self._T.iteritems(),
key=operator.itemgetter(1))[-1] | python | def qth_pw(self, q):
"""
returns the qth most probable element in the dawg.
"""
return heapq.nlargest(q + 2, self._T.iteritems(),
key=operator.itemgetter(1))[-1] | [
"def",
"qth_pw",
"(",
"self",
",",
"q",
")",
":",
"return",
"heapq",
".",
"nlargest",
"(",
"q",
"+",
"2",
",",
"self",
".",
"_T",
".",
"iteritems",
"(",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")",
"[",
"-",
"1",
"]"
]
| returns the qth most probable element in the dawg. | [
"returns",
"the",
"qth",
"most",
"probable",
"element",
"in",
"the",
"dawg",
"."
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L142-L147 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | PcfgPw.prob | def prob(self, pw):
"""
Return the probability of pw under the Weir PCFG model.
P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}]
"""
tokens = self.pcfgtokensofw(pw)
S, tokens = tokens[0], tokens[1:]
l = len(tokens)
assert l % 2 == 0, "Expecting even number of tokens!. got {}".format(tokens)
p = float(self._T.get(S, 0.0)) / sum(v for k, v in self._T.items('__S__'))
for i, t in enumerate(tokens):
f = self._T.get(t, 0.0)
if f == 0:
return 0.0
if i < l / 2:
p /= f
else:
p *= f
# print pw, p, t, self._T.get(t)
return p | python | def prob(self, pw):
"""
Return the probability of pw under the Weir PCFG model.
P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}]
"""
tokens = self.pcfgtokensofw(pw)
S, tokens = tokens[0], tokens[1:]
l = len(tokens)
assert l % 2 == 0, "Expecting even number of tokens!. got {}".format(tokens)
p = float(self._T.get(S, 0.0)) / sum(v for k, v in self._T.items('__S__'))
for i, t in enumerate(tokens):
f = self._T.get(t, 0.0)
if f == 0:
return 0.0
if i < l / 2:
p /= f
else:
p *= f
# print pw, p, t, self._T.get(t)
return p | [
"def",
"prob",
"(",
"self",
",",
"pw",
")",
":",
"tokens",
"=",
"self",
".",
"pcfgtokensofw",
"(",
"pw",
")",
"S",
",",
"tokens",
"=",
"tokens",
"[",
"0",
"]",
",",
"tokens",
"[",
"1",
":",
"]",
"l",
"=",
"len",
"(",
"tokens",
")",
"assert",
"l",
"%",
"2",
"==",
"0",
",",
"\"Expecting even number of tokens!. got {}\"",
".",
"format",
"(",
"tokens",
")",
"p",
"=",
"float",
"(",
"self",
".",
"_T",
".",
"get",
"(",
"S",
",",
"0.0",
")",
")",
"/",
"sum",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_T",
".",
"items",
"(",
"'__S__'",
")",
")",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"f",
"=",
"self",
".",
"_T",
".",
"get",
"(",
"t",
",",
"0.0",
")",
"if",
"f",
"==",
"0",
":",
"return",
"0.0",
"if",
"i",
"<",
"l",
"/",
"2",
":",
"p",
"/=",
"f",
"else",
":",
"p",
"*=",
"f",
"# print pw, p, t, self._T.get(t)",
"return",
"p"
]
| Return the probability of pw under the Weir PCFG model.
P[{S -> L2D1Y3, L2 -> 'ab', D1 -> '1', Y3 -> '!@#'}] | [
"Return",
"the",
"probability",
"of",
"pw",
"under",
"the",
"Weir",
"PCFG",
"model",
".",
"P",
"[",
"{",
"S",
"-",
">",
"L2D1Y3",
"L2",
"-",
">",
"ab",
"D1",
"-",
">",
"1",
"Y3",
"-",
">",
"!"
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L206-L227 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | NGramPw._get_next | def _get_next(self, history):
"""Get the next set of characters and their probabilities"""
orig_history = history
if not history:
return helper.START
history = history[-(self._n-1):]
while history and not self._T.get(history):
history = history[1:]
kv = [(k, v) for k, v in self._T.items(history)
if not (k in reserved_words or k == history)]
total = sum(v for k, v in kv)
while total == 0 and len(history) > 0:
history = history[1:]
kv = [(k, v) for k, v in self._T.items(history)
if not (k in reserved_words or k == history)]
total = sum(v for k, v in kv)
assert total > 0, "Sorry there is no n-gram with {!r}".format(orig_history)
d = defaultdict(float)
total = self._T.get(history)
for k, v in kv:
k = k[len(history):]
d[k] += (v+1)/(total + N_VALID_CHARS-1)
return d | python | def _get_next(self, history):
"""Get the next set of characters and their probabilities"""
orig_history = history
if not history:
return helper.START
history = history[-(self._n-1):]
while history and not self._T.get(history):
history = history[1:]
kv = [(k, v) for k, v in self._T.items(history)
if not (k in reserved_words or k == history)]
total = sum(v for k, v in kv)
while total == 0 and len(history) > 0:
history = history[1:]
kv = [(k, v) for k, v in self._T.items(history)
if not (k in reserved_words or k == history)]
total = sum(v for k, v in kv)
assert total > 0, "Sorry there is no n-gram with {!r}".format(orig_history)
d = defaultdict(float)
total = self._T.get(history)
for k, v in kv:
k = k[len(history):]
d[k] += (v+1)/(total + N_VALID_CHARS-1)
return d | [
"def",
"_get_next",
"(",
"self",
",",
"history",
")",
":",
"orig_history",
"=",
"history",
"if",
"not",
"history",
":",
"return",
"helper",
".",
"START",
"history",
"=",
"history",
"[",
"-",
"(",
"self",
".",
"_n",
"-",
"1",
")",
":",
"]",
"while",
"history",
"and",
"not",
"self",
".",
"_T",
".",
"get",
"(",
"history",
")",
":",
"history",
"=",
"history",
"[",
"1",
":",
"]",
"kv",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_T",
".",
"items",
"(",
"history",
")",
"if",
"not",
"(",
"k",
"in",
"reserved_words",
"or",
"k",
"==",
"history",
")",
"]",
"total",
"=",
"sum",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"kv",
")",
"while",
"total",
"==",
"0",
"and",
"len",
"(",
"history",
")",
">",
"0",
":",
"history",
"=",
"history",
"[",
"1",
":",
"]",
"kv",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_T",
".",
"items",
"(",
"history",
")",
"if",
"not",
"(",
"k",
"in",
"reserved_words",
"or",
"k",
"==",
"history",
")",
"]",
"total",
"=",
"sum",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"kv",
")",
"assert",
"total",
">",
"0",
",",
"\"Sorry there is no n-gram with {!r}\"",
".",
"format",
"(",
"orig_history",
")",
"d",
"=",
"defaultdict",
"(",
"float",
")",
"total",
"=",
"self",
".",
"_T",
".",
"get",
"(",
"history",
")",
"for",
"k",
",",
"v",
"in",
"kv",
":",
"k",
"=",
"k",
"[",
"len",
"(",
"history",
")",
":",
"]",
"d",
"[",
"k",
"]",
"+=",
"(",
"v",
"+",
"1",
")",
"/",
"(",
"total",
"+",
"N_VALID_CHARS",
"-",
"1",
")",
"return",
"d"
]
| Get the next set of characters and their probabilities | [
"Get",
"the",
"next",
"set",
"of",
"characters",
"and",
"their",
"probabilities"
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L311-L333 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | NGramPw._gen_next | def _gen_next(self, history):
"""Generate next character sampled from the distribution of characters next.
"""
orig_history = history
if not history:
return helper.START
history = history[-(self._n-1):]
kv = [(k, v) for k, v in self._T.items(history)
if k not in reserved_words]
total = sum(v for k, v in kv)
while total == 0 and len(history) > 0:
history = history[1:]
kv = [(k, v) for k, v in self._T.items(history)
if k not in reserved_words]
total = sum(v for k, v in kv)
assert total > 0, "Sorry there is no n-gram with {!r}".format(orig_history)
_, sampled_k = list(helper.sample_following_dist(kv, 1, total))[0]
# print(">>>", repr(sampled_k), len(history))
return sampled_k[len(history)] | python | def _gen_next(self, history):
"""Generate next character sampled from the distribution of characters next.
"""
orig_history = history
if not history:
return helper.START
history = history[-(self._n-1):]
kv = [(k, v) for k, v in self._T.items(history)
if k not in reserved_words]
total = sum(v for k, v in kv)
while total == 0 and len(history) > 0:
history = history[1:]
kv = [(k, v) for k, v in self._T.items(history)
if k not in reserved_words]
total = sum(v for k, v in kv)
assert total > 0, "Sorry there is no n-gram with {!r}".format(orig_history)
_, sampled_k = list(helper.sample_following_dist(kv, 1, total))[0]
# print(">>>", repr(sampled_k), len(history))
return sampled_k[len(history)] | [
"def",
"_gen_next",
"(",
"self",
",",
"history",
")",
":",
"orig_history",
"=",
"history",
"if",
"not",
"history",
":",
"return",
"helper",
".",
"START",
"history",
"=",
"history",
"[",
"-",
"(",
"self",
".",
"_n",
"-",
"1",
")",
":",
"]",
"kv",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_T",
".",
"items",
"(",
"history",
")",
"if",
"k",
"not",
"in",
"reserved_words",
"]",
"total",
"=",
"sum",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"kv",
")",
"while",
"total",
"==",
"0",
"and",
"len",
"(",
"history",
")",
">",
"0",
":",
"history",
"=",
"history",
"[",
"1",
":",
"]",
"kv",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_T",
".",
"items",
"(",
"history",
")",
"if",
"k",
"not",
"in",
"reserved_words",
"]",
"total",
"=",
"sum",
"(",
"v",
"for",
"k",
",",
"v",
"in",
"kv",
")",
"assert",
"total",
">",
"0",
",",
"\"Sorry there is no n-gram with {!r}\"",
".",
"format",
"(",
"orig_history",
")",
"_",
",",
"sampled_k",
"=",
"list",
"(",
"helper",
".",
"sample_following_dist",
"(",
"kv",
",",
"1",
",",
"total",
")",
")",
"[",
"0",
"]",
"# print(\">>>\", repr(sampled_k), len(history))",
"return",
"sampled_k",
"[",
"len",
"(",
"history",
")",
"]"
]
| Generate next character sampled from the distribution of characters next. | [
"Generate",
"next",
"character",
"sampled",
"from",
"the",
"distribution",
"of",
"characters",
"next",
"."
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L335-L353 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | NGramPw.generate_pws_in_order | def generate_pws_in_order(self, n, filter_func=None, N_max=1e6):
"""
Generates passwords in order between upto N_max
@N_max is the maximum size of the priority queue will be tolerated,
so if the size of the queue is bigger than 1.5 * N_max, it will shrink
the size to 0.75 * N_max
@n is the number of password to generate.
**This function is expensive, and shuold be called only if necessary.
Cache its call as much as possible**
# TODO: Need to recheck how to make sure this is working.
"""
# assert alpha < beta, 'alpha={} must be less than beta={}'.format(alpha, beta)
states = [(-1.0, helper.START)]
# get the topk first
p_min = 1e-9 / (n**2) # max 1 million entries in the heap
ret = []
done = set()
already_added_in_heap = set()
while len(ret) < n and len(states) > 0:
# while n > 0 and len(states) > 0:
p, s = heapq.heappop(states)
if p < 0:
p = -p
if s in done: continue
assert s[0] == helper.START, "Broken s: {!r}".format(s)
if s[-1] == helper.END:
done.add(s)
clean_s = s[1:-1]
if filter_func is None or filter_func(clean_s):
ret.append((clean_s, p))
# n -= 1
# yield (clean_s, p)
else:
for c, f in self._get_next(s).items():
if (f*p < p_min or (s+c) in done or
(s+c) in already_added_in_heap):
continue
already_added_in_heap.add(s+c)
heapq.heappush(states, (-f*p, s+c))
if len(states) > N_max * 3 / 2:
print("Heap size: {}. ret={}. (expected: {}) s={!r}"
.format(len(states), len(ret), n, s))
print("The size of states={}. Still need={} pws. Truncating"
.format(len(states), n - len(ret)))
states = heapq.nsmallest(int(N_max * 3/4), states)
print("Done")
return ret | python | def generate_pws_in_order(self, n, filter_func=None, N_max=1e6):
"""
Generates passwords in order between upto N_max
@N_max is the maximum size of the priority queue will be tolerated,
so if the size of the queue is bigger than 1.5 * N_max, it will shrink
the size to 0.75 * N_max
@n is the number of password to generate.
**This function is expensive, and shuold be called only if necessary.
Cache its call as much as possible**
# TODO: Need to recheck how to make sure this is working.
"""
# assert alpha < beta, 'alpha={} must be less than beta={}'.format(alpha, beta)
states = [(-1.0, helper.START)]
# get the topk first
p_min = 1e-9 / (n**2) # max 1 million entries in the heap
ret = []
done = set()
already_added_in_heap = set()
while len(ret) < n and len(states) > 0:
# while n > 0 and len(states) > 0:
p, s = heapq.heappop(states)
if p < 0:
p = -p
if s in done: continue
assert s[0] == helper.START, "Broken s: {!r}".format(s)
if s[-1] == helper.END:
done.add(s)
clean_s = s[1:-1]
if filter_func is None or filter_func(clean_s):
ret.append((clean_s, p))
# n -= 1
# yield (clean_s, p)
else:
for c, f in self._get_next(s).items():
if (f*p < p_min or (s+c) in done or
(s+c) in already_added_in_heap):
continue
already_added_in_heap.add(s+c)
heapq.heappush(states, (-f*p, s+c))
if len(states) > N_max * 3 / 2:
print("Heap size: {}. ret={}. (expected: {}) s={!r}"
.format(len(states), len(ret), n, s))
print("The size of states={}. Still need={} pws. Truncating"
.format(len(states), n - len(ret)))
states = heapq.nsmallest(int(N_max * 3/4), states)
print("Done")
return ret | [
"def",
"generate_pws_in_order",
"(",
"self",
",",
"n",
",",
"filter_func",
"=",
"None",
",",
"N_max",
"=",
"1e6",
")",
":",
"# assert alpha < beta, 'alpha={} must be less than beta={}'.format(alpha, beta)",
"states",
"=",
"[",
"(",
"-",
"1.0",
",",
"helper",
".",
"START",
")",
"]",
"# get the topk first",
"p_min",
"=",
"1e-9",
"/",
"(",
"n",
"**",
"2",
")",
"# max 1 million entries in the heap ",
"ret",
"=",
"[",
"]",
"done",
"=",
"set",
"(",
")",
"already_added_in_heap",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"ret",
")",
"<",
"n",
"and",
"len",
"(",
"states",
")",
">",
"0",
":",
"# while n > 0 and len(states) > 0:",
"p",
",",
"s",
"=",
"heapq",
".",
"heappop",
"(",
"states",
")",
"if",
"p",
"<",
"0",
":",
"p",
"=",
"-",
"p",
"if",
"s",
"in",
"done",
":",
"continue",
"assert",
"s",
"[",
"0",
"]",
"==",
"helper",
".",
"START",
",",
"\"Broken s: {!r}\"",
".",
"format",
"(",
"s",
")",
"if",
"s",
"[",
"-",
"1",
"]",
"==",
"helper",
".",
"END",
":",
"done",
".",
"add",
"(",
"s",
")",
"clean_s",
"=",
"s",
"[",
"1",
":",
"-",
"1",
"]",
"if",
"filter_func",
"is",
"None",
"or",
"filter_func",
"(",
"clean_s",
")",
":",
"ret",
".",
"append",
"(",
"(",
"clean_s",
",",
"p",
")",
")",
"# n -= 1",
"# yield (clean_s, p)",
"else",
":",
"for",
"c",
",",
"f",
"in",
"self",
".",
"_get_next",
"(",
"s",
")",
".",
"items",
"(",
")",
":",
"if",
"(",
"f",
"*",
"p",
"<",
"p_min",
"or",
"(",
"s",
"+",
"c",
")",
"in",
"done",
"or",
"(",
"s",
"+",
"c",
")",
"in",
"already_added_in_heap",
")",
":",
"continue",
"already_added_in_heap",
".",
"add",
"(",
"s",
"+",
"c",
")",
"heapq",
".",
"heappush",
"(",
"states",
",",
"(",
"-",
"f",
"*",
"p",
",",
"s",
"+",
"c",
")",
")",
"if",
"len",
"(",
"states",
")",
">",
"N_max",
"*",
"3",
"/",
"2",
":",
"print",
"(",
"\"Heap size: {}. ret={}. (expected: {}) s={!r}\"",
".",
"format",
"(",
"len",
"(",
"states",
")",
",",
"len",
"(",
"ret",
")",
",",
"n",
",",
"s",
")",
")",
"print",
"(",
"\"The size of states={}. Still need={} pws. Truncating\"",
".",
"format",
"(",
"len",
"(",
"states",
")",
",",
"n",
"-",
"len",
"(",
"ret",
")",
")",
")",
"states",
"=",
"heapq",
".",
"nsmallest",
"(",
"int",
"(",
"N_max",
"*",
"3",
"/",
"4",
")",
",",
"states",
")",
"print",
"(",
"\"Done\"",
")",
"return",
"ret"
]
| Generates passwords in order between upto N_max
@N_max is the maximum size of the priority queue will be tolerated,
so if the size of the queue is bigger than 1.5 * N_max, it will shrink
the size to 0.75 * N_max
@n is the number of password to generate.
**This function is expensive, and shuold be called only if necessary.
Cache its call as much as possible**
# TODO: Need to recheck how to make sure this is working. | [
"Generates",
"passwords",
"in",
"order",
"between",
"upto",
"N_max"
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L361-L407 | train |
rchatterjee/pwmodels | src/pwmodel/models.py | HistPw.prob_correction | def prob_correction(self, f=1):
"""
Corrects the probability error due to truncating the distribution.
"""
total = {'rockyou': 32602160}
return f * self._T[TOTALF_W] / total.get(self._leak, self._T[TOTALF_W]) | python | def prob_correction(self, f=1):
"""
Corrects the probability error due to truncating the distribution.
"""
total = {'rockyou': 32602160}
return f * self._T[TOTALF_W] / total.get(self._leak, self._T[TOTALF_W]) | [
"def",
"prob_correction",
"(",
"self",
",",
"f",
"=",
"1",
")",
":",
"total",
"=",
"{",
"'rockyou'",
":",
"32602160",
"}",
"return",
"f",
"*",
"self",
".",
"_T",
"[",
"TOTALF_W",
"]",
"/",
"total",
".",
"get",
"(",
"self",
".",
"_leak",
",",
"self",
".",
"_T",
"[",
"TOTALF_W",
"]",
")"
]
| Corrects the probability error due to truncating the distribution. | [
"Corrects",
"the",
"probability",
"error",
"due",
"to",
"truncating",
"the",
"distribution",
"."
]
| e277411f8ebaf4ad1c208d2b035b4b68f7471517 | https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L481-L486 | train |
someones/jaweson | jaweson/serialisable.py | Serialisable.serialisable | def serialisable(cls, key, obj):
'''Determines what can be serialised and what shouldn't
'''
# ignore class method names
if key.startswith('_Serialisable'.format(cls.__name__)):
return False
if key in obj.__whitelist:
return True
# class variables will be prefixed with '_<cls.__name__>__variable'
# so let's remove these too
#if key.startswith('__'):
if '__' in key:
return False
# ignore our own class variables
#if key in ['_Serialisable__whitelist', '_Serialisable__blacklist']:
# return False
if key in obj.__blacklist:
return False
if callable(getattr(obj, key)):
return False
# check for properties
if hasattr(obj.__class__, key):
if isinstance(getattr(obj.__class__, key), property):
return False
return True | python | def serialisable(cls, key, obj):
'''Determines what can be serialised and what shouldn't
'''
# ignore class method names
if key.startswith('_Serialisable'.format(cls.__name__)):
return False
if key in obj.__whitelist:
return True
# class variables will be prefixed with '_<cls.__name__>__variable'
# so let's remove these too
#if key.startswith('__'):
if '__' in key:
return False
# ignore our own class variables
#if key in ['_Serialisable__whitelist', '_Serialisable__blacklist']:
# return False
if key in obj.__blacklist:
return False
if callable(getattr(obj, key)):
return False
# check for properties
if hasattr(obj.__class__, key):
if isinstance(getattr(obj.__class__, key), property):
return False
return True | [
"def",
"serialisable",
"(",
"cls",
",",
"key",
",",
"obj",
")",
":",
"# ignore class method names",
"if",
"key",
".",
"startswith",
"(",
"'_Serialisable'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
")",
":",
"return",
"False",
"if",
"key",
"in",
"obj",
".",
"__whitelist",
":",
"return",
"True",
"# class variables will be prefixed with '_<cls.__name__>__variable'",
"# so let's remove these too",
"#if key.startswith('__'):",
"if",
"'__'",
"in",
"key",
":",
"return",
"False",
"# ignore our own class variables",
"#if key in ['_Serialisable__whitelist', '_Serialisable__blacklist']:",
"# return False",
"if",
"key",
"in",
"obj",
".",
"__blacklist",
":",
"return",
"False",
"if",
"callable",
"(",
"getattr",
"(",
"obj",
",",
"key",
")",
")",
":",
"return",
"False",
"# check for properties",
"if",
"hasattr",
"(",
"obj",
".",
"__class__",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"getattr",
"(",
"obj",
".",
"__class__",
",",
"key",
")",
",",
"property",
")",
":",
"return",
"False",
"return",
"True"
]
| Determines what can be serialised and what shouldn't | [
"Determines",
"what",
"can",
"be",
"serialised",
"and",
"what",
"shouldn",
"t"
]
| 744c3ca0f3af86c48738e2d89ea69646f48cc013 | https://github.com/someones/jaweson/blob/744c3ca0f3af86c48738e2d89ea69646f48cc013/jaweson/serialisable.py#L36-L60 | train |
JIC-CSB/jicimagelib | jicimagelib/util/array.py | normalise | def normalise(array):
"""Return array normalised such that all values are between 0 and 1.
If all the values in the array are the same the function will return:
- np.zeros(array.shape, dtype=np.float) if the value is 0 or less
- np.ones(array.shape, dtype=np.float) if the value is greater than 0
:param array: numpy.array
:returns: numpy.array.astype(numpy.float)
"""
min_val = array.min()
max_val = array.max()
array_range = max_val - min_val
if array_range == 0:
# min_val == max_val
if min_val > 0:
return np.ones(array.shape, dtype=np.float)
return np.zeros(array.shape, dtype=np.float)
return (array.astype(np.float) - min_val) / array_range | python | def normalise(array):
"""Return array normalised such that all values are between 0 and 1.
If all the values in the array are the same the function will return:
- np.zeros(array.shape, dtype=np.float) if the value is 0 or less
- np.ones(array.shape, dtype=np.float) if the value is greater than 0
:param array: numpy.array
:returns: numpy.array.astype(numpy.float)
"""
min_val = array.min()
max_val = array.max()
array_range = max_val - min_val
if array_range == 0:
# min_val == max_val
if min_val > 0:
return np.ones(array.shape, dtype=np.float)
return np.zeros(array.shape, dtype=np.float)
return (array.astype(np.float) - min_val) / array_range | [
"def",
"normalise",
"(",
"array",
")",
":",
"min_val",
"=",
"array",
".",
"min",
"(",
")",
"max_val",
"=",
"array",
".",
"max",
"(",
")",
"array_range",
"=",
"max_val",
"-",
"min_val",
"if",
"array_range",
"==",
"0",
":",
"# min_val == max_val",
"if",
"min_val",
">",
"0",
":",
"return",
"np",
".",
"ones",
"(",
"array",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"return",
"np",
".",
"zeros",
"(",
"array",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"return",
"(",
"array",
".",
"astype",
"(",
"np",
".",
"float",
")",
"-",
"min_val",
")",
"/",
"array_range"
]
| Return array normalised such that all values are between 0 and 1.
If all the values in the array are the same the function will return:
- np.zeros(array.shape, dtype=np.float) if the value is 0 or less
- np.ones(array.shape, dtype=np.float) if the value is greater than 0
:param array: numpy.array
:returns: numpy.array.astype(numpy.float) | [
"Return",
"array",
"normalised",
"such",
"that",
"all",
"values",
"are",
"between",
"0",
"and",
"1",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L7-L27 | train |
JIC-CSB/jicimagelib | jicimagelib/util/array.py | reduce_stack | def reduce_stack(array3D, z_function):
"""Return 2D array projection of the input 3D array.
The input function is applied to each line of an input x, y value.
:param array3D: 3D numpy.array
:param z_function: function to use for the projection (e.g. :func:`max`)
"""
xmax, ymax, _ = array3D.shape
projection = np.zeros((xmax, ymax), dtype=array3D.dtype)
for x in range(xmax):
for y in range(ymax):
projection[x, y] = z_function(array3D[x, y, :])
return projection | python | def reduce_stack(array3D, z_function):
"""Return 2D array projection of the input 3D array.
The input function is applied to each line of an input x, y value.
:param array3D: 3D numpy.array
:param z_function: function to use for the projection (e.g. :func:`max`)
"""
xmax, ymax, _ = array3D.shape
projection = np.zeros((xmax, ymax), dtype=array3D.dtype)
for x in range(xmax):
for y in range(ymax):
projection[x, y] = z_function(array3D[x, y, :])
return projection | [
"def",
"reduce_stack",
"(",
"array3D",
",",
"z_function",
")",
":",
"xmax",
",",
"ymax",
",",
"_",
"=",
"array3D",
".",
"shape",
"projection",
"=",
"np",
".",
"zeros",
"(",
"(",
"xmax",
",",
"ymax",
")",
",",
"dtype",
"=",
"array3D",
".",
"dtype",
")",
"for",
"x",
"in",
"range",
"(",
"xmax",
")",
":",
"for",
"y",
"in",
"range",
"(",
"ymax",
")",
":",
"projection",
"[",
"x",
",",
"y",
"]",
"=",
"z_function",
"(",
"array3D",
"[",
"x",
",",
"y",
",",
":",
"]",
")",
"return",
"projection"
]
| Return 2D array projection of the input 3D array.
The input function is applied to each line of an input x, y value.
:param array3D: 3D numpy.array
:param z_function: function to use for the projection (e.g. :func:`max`) | [
"Return",
"2D",
"array",
"projection",
"of",
"the",
"input",
"3D",
"array",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L29-L42 | train |
JIC-CSB/jicimagelib | jicimagelib/util/array.py | map_stack | def map_stack(array3D, z_function):
"""Return 3D array where each z-slice has had the function applied to it.
:param array3D: 3D numpy.array
:param z_function: function to be mapped to each z-slice
"""
_, _, zdim = array3D.shape
return np.dstack([z_function(array3D[:,:,z]) for z in range(zdim)]) | python | def map_stack(array3D, z_function):
"""Return 3D array where each z-slice has had the function applied to it.
:param array3D: 3D numpy.array
:param z_function: function to be mapped to each z-slice
"""
_, _, zdim = array3D.shape
return np.dstack([z_function(array3D[:,:,z]) for z in range(zdim)]) | [
"def",
"map_stack",
"(",
"array3D",
",",
"z_function",
")",
":",
"_",
",",
"_",
",",
"zdim",
"=",
"array3D",
".",
"shape",
"return",
"np",
".",
"dstack",
"(",
"[",
"z_function",
"(",
"array3D",
"[",
":",
",",
":",
",",
"z",
"]",
")",
"for",
"z",
"in",
"range",
"(",
"zdim",
")",
"]",
")"
]
| Return 3D array where each z-slice has had the function applied to it.
:param array3D: 3D numpy.array
:param z_function: function to be mapped to each z-slice | [
"Return",
"3D",
"array",
"where",
"each",
"z",
"-",
"slice",
"has",
"had",
"the",
"function",
"applied",
"to",
"it",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L44-L51 | train |
JIC-CSB/jicimagelib | jicimagelib/util/array.py | check_dtype | def check_dtype(array, allowed):
"""Raises TypeError if the array is not of an allowed dtype.
:param array: array whose dtype is to be checked
:param allowed: instance or list of allowed dtypes
"""
if not hasattr(allowed, "__iter__"):
allowed = [allowed,]
if array.dtype not in allowed:
raise(TypeError(
"Invalid dtype {}. Allowed dtype(s): {}".format(array.dtype, allowed))) | python | def check_dtype(array, allowed):
"""Raises TypeError if the array is not of an allowed dtype.
:param array: array whose dtype is to be checked
:param allowed: instance or list of allowed dtypes
"""
if not hasattr(allowed, "__iter__"):
allowed = [allowed,]
if array.dtype not in allowed:
raise(TypeError(
"Invalid dtype {}. Allowed dtype(s): {}".format(array.dtype, allowed))) | [
"def",
"check_dtype",
"(",
"array",
",",
"allowed",
")",
":",
"if",
"not",
"hasattr",
"(",
"allowed",
",",
"\"__iter__\"",
")",
":",
"allowed",
"=",
"[",
"allowed",
",",
"]",
"if",
"array",
".",
"dtype",
"not",
"in",
"allowed",
":",
"raise",
"(",
"TypeError",
"(",
"\"Invalid dtype {}. Allowed dtype(s): {}\"",
".",
"format",
"(",
"array",
".",
"dtype",
",",
"allowed",
")",
")",
")"
]
| Raises TypeError if the array is not of an allowed dtype.
:param array: array whose dtype is to be checked
:param allowed: instance or list of allowed dtypes | [
"Raises",
"TypeError",
"if",
"the",
"array",
"is",
"not",
"of",
"an",
"allowed",
"dtype",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/util/array.py#L54-L64 | train |
tjcsl/cslbot | cslbot/helpers/control.py | handle_ctrlchan | def handle_ctrlchan(handler, msg, nick, send):
"""Handle the control channel."""
with handler.db.session_scope() as db:
parser = init_parser(send, handler, nick, db)
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
# FIXME: figure out a better way to allow non-commands without spamming the channel.
err_str = r"invalid choice: .* \(choose from 'quote', 'help', 'chanserv', 'cs', 'disable', 'enable', 'guard', 'unguard', 'show', 'accept', 'reject'\)"
if not re.match(err_str, str(e)):
send(str(e))
return
cmdargs.func(cmdargs) | python | def handle_ctrlchan(handler, msg, nick, send):
"""Handle the control channel."""
with handler.db.session_scope() as db:
parser = init_parser(send, handler, nick, db)
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
# FIXME: figure out a better way to allow non-commands without spamming the channel.
err_str = r"invalid choice: .* \(choose from 'quote', 'help', 'chanserv', 'cs', 'disable', 'enable', 'guard', 'unguard', 'show', 'accept', 'reject'\)"
if not re.match(err_str, str(e)):
send(str(e))
return
cmdargs.func(cmdargs) | [
"def",
"handle_ctrlchan",
"(",
"handler",
",",
"msg",
",",
"nick",
",",
"send",
")",
":",
"with",
"handler",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"db",
":",
"parser",
"=",
"init_parser",
"(",
"send",
",",
"handler",
",",
"nick",
",",
"db",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"# FIXME: figure out a better way to allow non-commands without spamming the channel.",
"err_str",
"=",
"r\"invalid choice: .* \\(choose from 'quote', 'help', 'chanserv', 'cs', 'disable', 'enable', 'guard', 'unguard', 'show', 'accept', 'reject'\\)\"",
"if",
"not",
"re",
".",
"match",
"(",
"err_str",
",",
"str",
"(",
"e",
")",
")",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"cmdargs",
".",
"func",
"(",
"cmdargs",
")"
]
| Handle the control channel. | [
"Handle",
"the",
"control",
"channel",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/control.py#L334-L346 | train |
tjcsl/cslbot | cslbot/commands/metro.py | cmd | def cmd(send, msg, args):
"""Provides Metro Info.
Syntax: {command}
"""
incidents = get_incidents(args['config']['api']['wmatakey'])
if not incidents:
send("No incidents found. Sure you picked the right metro system?")
return
for t, i in incidents.items():
send("%s:" % get_type(t))
for desc in i:
send(desc) | python | def cmd(send, msg, args):
"""Provides Metro Info.
Syntax: {command}
"""
incidents = get_incidents(args['config']['api']['wmatakey'])
if not incidents:
send("No incidents found. Sure you picked the right metro system?")
return
for t, i in incidents.items():
send("%s:" % get_type(t))
for desc in i:
send(desc) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"incidents",
"=",
"get_incidents",
"(",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'wmatakey'",
"]",
")",
"if",
"not",
"incidents",
":",
"send",
"(",
"\"No incidents found. Sure you picked the right metro system?\"",
")",
"return",
"for",
"t",
",",
"i",
"in",
"incidents",
".",
"items",
"(",
")",
":",
"send",
"(",
"\"%s:\"",
"%",
"get_type",
"(",
"t",
")",
")",
"for",
"desc",
"in",
"i",
":",
"send",
"(",
"desc",
")"
]
| Provides Metro Info.
Syntax: {command} | [
"Provides",
"Metro",
"Info",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/metro.py#L43-L56 | train |
The-Politico/politico-civic-election-night | electionnight/models/page_content.py | PageContent.page_location | def page_location(self):
"""
Returns the published URL for page.
"""
cycle = self.election_day.cycle.name
if self.content_type.model_class() == PageType:
print(self.content_object)
return self.content_object.page_location_template()
elif self.content_type.model_class() == Division:
if self.content_object.level.name == DivisionLevel.STATE:
if self.special_election:
# /{state}/special-election/{month-day}/
path = os.path.join(
self.content_object.slug,
"special-election",
self.election_day.special_election_datestring(),
)
else:
# /{state}/
path = self.content_object.slug
else:
# / National
path = ""
# Offices and Bodies
else:
if self.division.level.name == DivisionLevel.STATE:
if not self.content_object.body:
path = os.path.join(self.division.slug, "governor")
else:
path = os.path.join(
self.division.slug, self.content_object.slug
)
else:
path = self.content_object.slug
return (
os.sep + os.path.normpath(os.path.join(cycle, path)) + os.sep
) | python | def page_location(self):
"""
Returns the published URL for page.
"""
cycle = self.election_day.cycle.name
if self.content_type.model_class() == PageType:
print(self.content_object)
return self.content_object.page_location_template()
elif self.content_type.model_class() == Division:
if self.content_object.level.name == DivisionLevel.STATE:
if self.special_election:
# /{state}/special-election/{month-day}/
path = os.path.join(
self.content_object.slug,
"special-election",
self.election_day.special_election_datestring(),
)
else:
# /{state}/
path = self.content_object.slug
else:
# / National
path = ""
# Offices and Bodies
else:
if self.division.level.name == DivisionLevel.STATE:
if not self.content_object.body:
path = os.path.join(self.division.slug, "governor")
else:
path = os.path.join(
self.division.slug, self.content_object.slug
)
else:
path = self.content_object.slug
return (
os.sep + os.path.normpath(os.path.join(cycle, path)) + os.sep
) | [
"def",
"page_location",
"(",
"self",
")",
":",
"cycle",
"=",
"self",
".",
"election_day",
".",
"cycle",
".",
"name",
"if",
"self",
".",
"content_type",
".",
"model_class",
"(",
")",
"==",
"PageType",
":",
"print",
"(",
"self",
".",
"content_object",
")",
"return",
"self",
".",
"content_object",
".",
"page_location_template",
"(",
")",
"elif",
"self",
".",
"content_type",
".",
"model_class",
"(",
")",
"==",
"Division",
":",
"if",
"self",
".",
"content_object",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"if",
"self",
".",
"special_election",
":",
"# /{state}/special-election/{month-day}/",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"content_object",
".",
"slug",
",",
"\"special-election\"",
",",
"self",
".",
"election_day",
".",
"special_election_datestring",
"(",
")",
",",
")",
"else",
":",
"# /{state}/",
"path",
"=",
"self",
".",
"content_object",
".",
"slug",
"else",
":",
"# / National",
"path",
"=",
"\"\"",
"# Offices and Bodies",
"else",
":",
"if",
"self",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"if",
"not",
"self",
".",
"content_object",
".",
"body",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"division",
".",
"slug",
",",
"\"governor\"",
")",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"division",
".",
"slug",
",",
"self",
".",
"content_object",
".",
"slug",
")",
"else",
":",
"path",
"=",
"self",
".",
"content_object",
".",
"slug",
"return",
"(",
"os",
".",
"sep",
"+",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cycle",
",",
"path",
")",
")",
"+",
"os",
".",
"sep",
")"
]
| Returns the published URL for page. | [
"Returns",
"the",
"published",
"URL",
"for",
"page",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/models/page_content.py#L68-L104 | train |
pydanny-archive/dj-libcloud | djlibcloud/storage.py | LibCloudStorage._get_object | def _get_object(self, name):
"""Get object by its name. Return None if object not found"""
clean_name = self._clean_name(name)
try:
return self.driver.get_object(self.bucket, clean_name)
except ObjectDoesNotExistError:
return None | python | def _get_object(self, name):
"""Get object by its name. Return None if object not found"""
clean_name = self._clean_name(name)
try:
return self.driver.get_object(self.bucket, clean_name)
except ObjectDoesNotExistError:
return None | [
"def",
"_get_object",
"(",
"self",
",",
"name",
")",
":",
"clean_name",
"=",
"self",
".",
"_clean_name",
"(",
"name",
")",
"try",
":",
"return",
"self",
".",
"driver",
".",
"get_object",
"(",
"self",
".",
"bucket",
",",
"clean_name",
")",
"except",
"ObjectDoesNotExistError",
":",
"return",
"None"
]
| Get object by its name. Return None if object not found | [
"Get",
"object",
"by",
"its",
"name",
".",
"Return",
"None",
"if",
"object",
"not",
"found"
]
| dc485ed56a8dec9f5f200e1effb91f6113353aa4 | https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L108-L114 | train |
pydanny-archive/dj-libcloud | djlibcloud/storage.py | LibCloudStorage.delete | def delete(self, name):
"""Delete object on remote"""
obj = self._get_object(name)
if obj:
return self.driver.delete_object(obj) | python | def delete(self, name):
"""Delete object on remote"""
obj = self._get_object(name)
if obj:
return self.driver.delete_object(obj) | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"obj",
"=",
"self",
".",
"_get_object",
"(",
"name",
")",
"if",
"obj",
":",
"return",
"self",
".",
"driver",
".",
"delete_object",
"(",
"obj",
")"
]
| Delete object on remote | [
"Delete",
"object",
"on",
"remote"
]
| dc485ed56a8dec9f5f200e1effb91f6113353aa4 | https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L116-L120 | train |
pydanny-archive/dj-libcloud | djlibcloud/storage.py | LibCloudStorage.listdir | def listdir(self, path='/'):
"""Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being
directories, the second item being files.
"""
container = self._get_bucket()
objects = self.driver.list_container_objects(container)
path = self._clean_name(path)
if not path.endswith('/'):
path = "%s/" % path
files = []
dirs = []
# TOFIX: better algorithm to filter correctly
# (and not depend on google-storage empty folder naming)
for o in objects:
if path == '/':
if o.name.count('/') == 0:
files.append(o.name)
elif o.name.count('/') == 1:
dir_name = o.name[:o.name.index('/')]
if dir_name not in dirs:
dirs.append(dir_name)
elif o.name.startswith(path):
if o.name.count('/') <= path.count('/'):
# TOFIX : special case for google storage with empty dir
if o.name.endswith('_$folder$'):
name = o.name[:-9]
name = name[len(path):]
dirs.append(name)
else:
name = o.name[len(path):]
files.append(name)
return (dirs, files) | python | def listdir(self, path='/'):
"""Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being
directories, the second item being files.
"""
container = self._get_bucket()
objects = self.driver.list_container_objects(container)
path = self._clean_name(path)
if not path.endswith('/'):
path = "%s/" % path
files = []
dirs = []
# TOFIX: better algorithm to filter correctly
# (and not depend on google-storage empty folder naming)
for o in objects:
if path == '/':
if o.name.count('/') == 0:
files.append(o.name)
elif o.name.count('/') == 1:
dir_name = o.name[:o.name.index('/')]
if dir_name not in dirs:
dirs.append(dir_name)
elif o.name.startswith(path):
if o.name.count('/') <= path.count('/'):
# TOFIX : special case for google storage with empty dir
if o.name.endswith('_$folder$'):
name = o.name[:-9]
name = name[len(path):]
dirs.append(name)
else:
name = o.name[len(path):]
files.append(name)
return (dirs, files) | [
"def",
"listdir",
"(",
"self",
",",
"path",
"=",
"'/'",
")",
":",
"container",
"=",
"self",
".",
"_get_bucket",
"(",
")",
"objects",
"=",
"self",
".",
"driver",
".",
"list_container_objects",
"(",
"container",
")",
"path",
"=",
"self",
".",
"_clean_name",
"(",
"path",
")",
"if",
"not",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"path",
"=",
"\"%s/\"",
"%",
"path",
"files",
"=",
"[",
"]",
"dirs",
"=",
"[",
"]",
"# TOFIX: better algorithm to filter correctly",
"# (and not depend on google-storage empty folder naming)",
"for",
"o",
"in",
"objects",
":",
"if",
"path",
"==",
"'/'",
":",
"if",
"o",
".",
"name",
".",
"count",
"(",
"'/'",
")",
"==",
"0",
":",
"files",
".",
"append",
"(",
"o",
".",
"name",
")",
"elif",
"o",
".",
"name",
".",
"count",
"(",
"'/'",
")",
"==",
"1",
":",
"dir_name",
"=",
"o",
".",
"name",
"[",
":",
"o",
".",
"name",
".",
"index",
"(",
"'/'",
")",
"]",
"if",
"dir_name",
"not",
"in",
"dirs",
":",
"dirs",
".",
"append",
"(",
"dir_name",
")",
"elif",
"o",
".",
"name",
".",
"startswith",
"(",
"path",
")",
":",
"if",
"o",
".",
"name",
".",
"count",
"(",
"'/'",
")",
"<=",
"path",
".",
"count",
"(",
"'/'",
")",
":",
"# TOFIX : special case for google storage with empty dir",
"if",
"o",
".",
"name",
".",
"endswith",
"(",
"'_$folder$'",
")",
":",
"name",
"=",
"o",
".",
"name",
"[",
":",
"-",
"9",
"]",
"name",
"=",
"name",
"[",
"len",
"(",
"path",
")",
":",
"]",
"dirs",
".",
"append",
"(",
"name",
")",
"else",
":",
"name",
"=",
"o",
".",
"name",
"[",
"len",
"(",
"path",
")",
":",
"]",
"files",
".",
"append",
"(",
"name",
")",
"return",
"(",
"dirs",
",",
"files",
")"
]
| Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being
directories, the second item being files. | [
"Lists",
"the",
"contents",
"of",
"the",
"specified",
"path",
"returning",
"a",
"2",
"-",
"tuple",
"of",
"lists",
";",
"the",
"first",
"item",
"being",
"directories",
"the",
"second",
"item",
"being",
"files",
"."
]
| dc485ed56a8dec9f5f200e1effb91f6113353aa4 | https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L126-L158 | train |
JIC-CSB/jicimagelib | jicimagelib/io.py | AutoName.name | def name(cls, func):
"""Return auto generated file name."""
cls.count = cls.count + 1
fpath = '{}_{}{}'.format(cls.count, func.__name__, cls.suffix)
if cls.directory:
fpath = os.path.join(cls.directory, fpath)
return fpath | python | def name(cls, func):
"""Return auto generated file name."""
cls.count = cls.count + 1
fpath = '{}_{}{}'.format(cls.count, func.__name__, cls.suffix)
if cls.directory:
fpath = os.path.join(cls.directory, fpath)
return fpath | [
"def",
"name",
"(",
"cls",
",",
"func",
")",
":",
"cls",
".",
"count",
"=",
"cls",
".",
"count",
"+",
"1",
"fpath",
"=",
"'{}_{}{}'",
".",
"format",
"(",
"cls",
".",
"count",
",",
"func",
".",
"__name__",
",",
"cls",
".",
"suffix",
")",
"if",
"cls",
".",
"directory",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"directory",
",",
"fpath",
")",
"return",
"fpath"
]
| Return auto generated file name. | [
"Return",
"auto",
"generated",
"file",
"name",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/io.py#L32-L38 | train |
JIC-CSB/jicimagelib | jicimagelib/io.py | BFConvertWrapper.split_pattern | def split_pattern(self):
"""Pattern used to split the input file."""
patterns = []
for p in self.split_order:
patterns.append('_{}%{}'.format(p.capitalize(), p))
return ''.join(patterns) | python | def split_pattern(self):
"""Pattern used to split the input file."""
patterns = []
for p in self.split_order:
patterns.append('_{}%{}'.format(p.capitalize(), p))
return ''.join(patterns) | [
"def",
"split_pattern",
"(",
"self",
")",
":",
"patterns",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"split_order",
":",
"patterns",
".",
"append",
"(",
"'_{}%{}'",
".",
"format",
"(",
"p",
".",
"capitalize",
"(",
")",
",",
"p",
")",
")",
"return",
"''",
".",
"join",
"(",
"patterns",
")"
]
| Pattern used to split the input file. | [
"Pattern",
"used",
"to",
"split",
"the",
"input",
"file",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/io.py#L112-L117 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | World.pick_random_target | def pick_random_target(self):
"""
returns coords of a randomly generated starting position
mostly over to the right hand side of the world
"""
start_x = math.floor(self.grd.grid_height/2)
start_y = math.floor(self.grd.grid_width /2)
min_dist_from_x = 3
min_dist_from_y = 5
move_random_x = randint(1, math.floor(self.grd.grid_height/2))
move_random_y = randint(1, math.floor(self.grd.grid_width/2))
x = start_x + move_random_x - min_dist_from_x
y = start_y + move_random_y - min_dist_from_y
return [x,y] | python | def pick_random_target(self):
"""
returns coords of a randomly generated starting position
mostly over to the right hand side of the world
"""
start_x = math.floor(self.grd.grid_height/2)
start_y = math.floor(self.grd.grid_width /2)
min_dist_from_x = 3
min_dist_from_y = 5
move_random_x = randint(1, math.floor(self.grd.grid_height/2))
move_random_y = randint(1, math.floor(self.grd.grid_width/2))
x = start_x + move_random_x - min_dist_from_x
y = start_y + move_random_y - min_dist_from_y
return [x,y] | [
"def",
"pick_random_target",
"(",
"self",
")",
":",
"start_x",
"=",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"grid_height",
"/",
"2",
")",
"start_y",
"=",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"grid_width",
"/",
"2",
")",
"min_dist_from_x",
"=",
"3",
"min_dist_from_y",
"=",
"5",
"move_random_x",
"=",
"randint",
"(",
"1",
",",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"grid_height",
"/",
"2",
")",
")",
"move_random_y",
"=",
"randint",
"(",
"1",
",",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"grid_width",
"/",
"2",
")",
")",
"x",
"=",
"start_x",
"+",
"move_random_x",
"-",
"min_dist_from_x",
"y",
"=",
"start_y",
"+",
"move_random_y",
"-",
"min_dist_from_y",
"return",
"[",
"x",
",",
"y",
"]"
]
| returns coords of a randomly generated starting position
mostly over to the right hand side of the world | [
"returns",
"coords",
"of",
"a",
"randomly",
"generated",
"starting",
"position",
"mostly",
"over",
"to",
"the",
"right",
"hand",
"side",
"of",
"the",
"world"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L98-L111 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | World.expand_seed | def expand_seed(self, start_seed, num_iterations, val):
"""
takes a seed start point and grows out in random
directions setting cell points to val
"""
self.grd.set_tile(start_seed[0], start_seed[1], val)
cur_pos = [start_seed[0], start_seed[1]]
while num_iterations > 0: # don't use loop as it will hit boundaries often
num_iterations -= 1
for y in range(cur_pos[0]-randint(0,2), cur_pos[0] + randint(0,2)):
for x in range(cur_pos[1]-randint(0,2), cur_pos[1] + randint(0,2)):
if x < self.grd.grid_width and x >= 0 and y >= 0 and y < self.grd.grid_height:
#print(x,y,val)
if self.grd.get_tile(y,x) != val:
self.grd.set_tile(y, x, TERRAIN_LAND)
num_iterations -= 1
new_x = cur_pos[0] + randint(0,3)-2
new_y = cur_pos[1] + randint(0,3)-2
if new_x > self.grd.grid_width - 1:
new_x = 0
if new_y > self.grd.grid_height - 1:
new_y = 0
if new_x < 0:
new_x = self.grd.grid_width - 1
if new_y < 0:
new_y = self.grd.grid_height - 1
cur_pos = [new_y, new_x] | python | def expand_seed(self, start_seed, num_iterations, val):
"""
takes a seed start point and grows out in random
directions setting cell points to val
"""
self.grd.set_tile(start_seed[0], start_seed[1], val)
cur_pos = [start_seed[0], start_seed[1]]
while num_iterations > 0: # don't use loop as it will hit boundaries often
num_iterations -= 1
for y in range(cur_pos[0]-randint(0,2), cur_pos[0] + randint(0,2)):
for x in range(cur_pos[1]-randint(0,2), cur_pos[1] + randint(0,2)):
if x < self.grd.grid_width and x >= 0 and y >= 0 and y < self.grd.grid_height:
#print(x,y,val)
if self.grd.get_tile(y,x) != val:
self.grd.set_tile(y, x, TERRAIN_LAND)
num_iterations -= 1
new_x = cur_pos[0] + randint(0,3)-2
new_y = cur_pos[1] + randint(0,3)-2
if new_x > self.grd.grid_width - 1:
new_x = 0
if new_y > self.grd.grid_height - 1:
new_y = 0
if new_x < 0:
new_x = self.grd.grid_width - 1
if new_y < 0:
new_y = self.grd.grid_height - 1
cur_pos = [new_y, new_x] | [
"def",
"expand_seed",
"(",
"self",
",",
"start_seed",
",",
"num_iterations",
",",
"val",
")",
":",
"self",
".",
"grd",
".",
"set_tile",
"(",
"start_seed",
"[",
"0",
"]",
",",
"start_seed",
"[",
"1",
"]",
",",
"val",
")",
"cur_pos",
"=",
"[",
"start_seed",
"[",
"0",
"]",
",",
"start_seed",
"[",
"1",
"]",
"]",
"while",
"num_iterations",
">",
"0",
":",
"# don't use loop as it will hit boundaries often",
"num_iterations",
"-=",
"1",
"for",
"y",
"in",
"range",
"(",
"cur_pos",
"[",
"0",
"]",
"-",
"randint",
"(",
"0",
",",
"2",
")",
",",
"cur_pos",
"[",
"0",
"]",
"+",
"randint",
"(",
"0",
",",
"2",
")",
")",
":",
"for",
"x",
"in",
"range",
"(",
"cur_pos",
"[",
"1",
"]",
"-",
"randint",
"(",
"0",
",",
"2",
")",
",",
"cur_pos",
"[",
"1",
"]",
"+",
"randint",
"(",
"0",
",",
"2",
")",
")",
":",
"if",
"x",
"<",
"self",
".",
"grd",
".",
"grid_width",
"and",
"x",
">=",
"0",
"and",
"y",
">=",
"0",
"and",
"y",
"<",
"self",
".",
"grd",
".",
"grid_height",
":",
"#print(x,y,val)",
"if",
"self",
".",
"grd",
".",
"get_tile",
"(",
"y",
",",
"x",
")",
"!=",
"val",
":",
"self",
".",
"grd",
".",
"set_tile",
"(",
"y",
",",
"x",
",",
"TERRAIN_LAND",
")",
"num_iterations",
"-=",
"1",
"new_x",
"=",
"cur_pos",
"[",
"0",
"]",
"+",
"randint",
"(",
"0",
",",
"3",
")",
"-",
"2",
"new_y",
"=",
"cur_pos",
"[",
"1",
"]",
"+",
"randint",
"(",
"0",
",",
"3",
")",
"-",
"2",
"if",
"new_x",
">",
"self",
".",
"grd",
".",
"grid_width",
"-",
"1",
":",
"new_x",
"=",
"0",
"if",
"new_y",
">",
"self",
".",
"grd",
".",
"grid_height",
"-",
"1",
":",
"new_y",
"=",
"0",
"if",
"new_x",
"<",
"0",
":",
"new_x",
"=",
"self",
".",
"grd",
".",
"grid_width",
"-",
"1",
"if",
"new_y",
"<",
"0",
":",
"new_y",
"=",
"self",
".",
"grd",
".",
"grid_height",
"-",
"1",
"cur_pos",
"=",
"[",
"new_y",
",",
"new_x",
"]"
]
| takes a seed start point and grows out in random
directions setting cell points to val | [
"takes",
"a",
"seed",
"start",
"point",
"and",
"grows",
"out",
"in",
"random",
"directions",
"setting",
"cell",
"points",
"to",
"val"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L126-L152 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | World.denoise_grid | def denoise_grid(self, val, expand=1):
"""
for every cell in the grid of 'val' fill all cells
around it to de noise the grid
"""
updated_grid = [[self.grd.get_tile(y,x) \
for x in range(self.grd.grid_width)] \
for y in range(self.grd.grid_height)]
for row in range(self.grd.get_grid_height() - expand):
for col in range(self.grd.get_grid_width() - expand):
updated_grid[row][col] = self.grd.get_tile(row,col) # set original point
if self.grd.get_tile(row,col) == val:
for y in range(-expand, expand):
for x in range(-expand, expand):
new_x = col+x
new_y = row+y
if new_x < 0: new_x = 0
if new_y < 0: new_y = 0
if new_x > self.grd.get_grid_width() - 1: new_x = self.grd.get_grid_width() - 1
if new_y > self.grd.get_grid_height() - 1: new_y = self.grd.get_grid_height() - 1
# randomly NOT denoise to make interesting edges
if expand > 0:
if randint(1,expand * 2) > (expand+1):
updated_grid[new_y][new_x] = val
else:
updated_grid[new_y][new_x] = val
self.grd.replace_grid(updated_grid) | python | def denoise_grid(self, val, expand=1):
"""
for every cell in the grid of 'val' fill all cells
around it to de noise the grid
"""
updated_grid = [[self.grd.get_tile(y,x) \
for x in range(self.grd.grid_width)] \
for y in range(self.grd.grid_height)]
for row in range(self.grd.get_grid_height() - expand):
for col in range(self.grd.get_grid_width() - expand):
updated_grid[row][col] = self.grd.get_tile(row,col) # set original point
if self.grd.get_tile(row,col) == val:
for y in range(-expand, expand):
for x in range(-expand, expand):
new_x = col+x
new_y = row+y
if new_x < 0: new_x = 0
if new_y < 0: new_y = 0
if new_x > self.grd.get_grid_width() - 1: new_x = self.grd.get_grid_width() - 1
if new_y > self.grd.get_grid_height() - 1: new_y = self.grd.get_grid_height() - 1
# randomly NOT denoise to make interesting edges
if expand > 0:
if randint(1,expand * 2) > (expand+1):
updated_grid[new_y][new_x] = val
else:
updated_grid[new_y][new_x] = val
self.grd.replace_grid(updated_grid) | [
"def",
"denoise_grid",
"(",
"self",
",",
"val",
",",
"expand",
"=",
"1",
")",
":",
"updated_grid",
"=",
"[",
"[",
"self",
".",
"grd",
".",
"get_tile",
"(",
"y",
",",
"x",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"grd",
".",
"grid_width",
")",
"]",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"grd",
".",
"grid_height",
")",
"]",
"for",
"row",
"in",
"range",
"(",
"self",
".",
"grd",
".",
"get_grid_height",
"(",
")",
"-",
"expand",
")",
":",
"for",
"col",
"in",
"range",
"(",
"self",
".",
"grd",
".",
"get_grid_width",
"(",
")",
"-",
"expand",
")",
":",
"updated_grid",
"[",
"row",
"]",
"[",
"col",
"]",
"=",
"self",
".",
"grd",
".",
"get_tile",
"(",
"row",
",",
"col",
")",
"# set original point",
"if",
"self",
".",
"grd",
".",
"get_tile",
"(",
"row",
",",
"col",
")",
"==",
"val",
":",
"for",
"y",
"in",
"range",
"(",
"-",
"expand",
",",
"expand",
")",
":",
"for",
"x",
"in",
"range",
"(",
"-",
"expand",
",",
"expand",
")",
":",
"new_x",
"=",
"col",
"+",
"x",
"new_y",
"=",
"row",
"+",
"y",
"if",
"new_x",
"<",
"0",
":",
"new_x",
"=",
"0",
"if",
"new_y",
"<",
"0",
":",
"new_y",
"=",
"0",
"if",
"new_x",
">",
"self",
".",
"grd",
".",
"get_grid_width",
"(",
")",
"-",
"1",
":",
"new_x",
"=",
"self",
".",
"grd",
".",
"get_grid_width",
"(",
")",
"-",
"1",
"if",
"new_y",
">",
"self",
".",
"grd",
".",
"get_grid_height",
"(",
")",
"-",
"1",
":",
"new_y",
"=",
"self",
".",
"grd",
".",
"get_grid_height",
"(",
")",
"-",
"1",
"# randomly NOT denoise to make interesting edges",
"if",
"expand",
">",
"0",
":",
"if",
"randint",
"(",
"1",
",",
"expand",
"*",
"2",
")",
">",
"(",
"expand",
"+",
"1",
")",
":",
"updated_grid",
"[",
"new_y",
"]",
"[",
"new_x",
"]",
"=",
"val",
"else",
":",
"updated_grid",
"[",
"new_y",
"]",
"[",
"new_x",
"]",
"=",
"val",
"self",
".",
"grd",
".",
"replace_grid",
"(",
"updated_grid",
")"
]
| for every cell in the grid of 'val' fill all cells
around it to de noise the grid | [
"for",
"every",
"cell",
"in",
"the",
"grid",
"of",
"val",
"fill",
"all",
"cells",
"around",
"it",
"to",
"de",
"noise",
"the",
"grid"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L154-L183 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | World.add_mountains | def add_mountains(self):
"""
instead of the add_blocks function which was to produce
line shaped walls for blocking path finding agents, this
function creates more natural looking blocking areas like
mountains
"""
from noise import pnoise2
import random
random.seed()
octaves = (random.random() * 0.5) + 0.5
freq = 17.0 * octaves #
for y in range(self.grd.grid_height - 1):
for x in range(self.grd.grid_width - 1):
pixel = self.grd.get_tile(y,x)
if pixel == 'X': # denoise blocks of mountains
n = int(pnoise2(x/freq, y / freq, 1)*11+5)
if n < 1:
self.grd.set_tile(y, x, '#') | python | def add_mountains(self):
"""
instead of the add_blocks function which was to produce
line shaped walls for blocking path finding agents, this
function creates more natural looking blocking areas like
mountains
"""
from noise import pnoise2
import random
random.seed()
octaves = (random.random() * 0.5) + 0.5
freq = 17.0 * octaves #
for y in range(self.grd.grid_height - 1):
for x in range(self.grd.grid_width - 1):
pixel = self.grd.get_tile(y,x)
if pixel == 'X': # denoise blocks of mountains
n = int(pnoise2(x/freq, y / freq, 1)*11+5)
if n < 1:
self.grd.set_tile(y, x, '#') | [
"def",
"add_mountains",
"(",
"self",
")",
":",
"from",
"noise",
"import",
"pnoise2",
"import",
"random",
"random",
".",
"seed",
"(",
")",
"octaves",
"=",
"(",
"random",
".",
"random",
"(",
")",
"*",
"0.5",
")",
"+",
"0.5",
"freq",
"=",
"17.0",
"*",
"octaves",
"# ",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"grd",
".",
"grid_height",
"-",
"1",
")",
":",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"grd",
".",
"grid_width",
"-",
"1",
")",
":",
"pixel",
"=",
"self",
".",
"grd",
".",
"get_tile",
"(",
"y",
",",
"x",
")",
"if",
"pixel",
"==",
"'X'",
":",
"# denoise blocks of mountains",
"n",
"=",
"int",
"(",
"pnoise2",
"(",
"x",
"/",
"freq",
",",
"y",
"/",
"freq",
",",
"1",
")",
"*",
"11",
"+",
"5",
")",
"if",
"n",
"<",
"1",
":",
"self",
".",
"grd",
".",
"set_tile",
"(",
"y",
",",
"x",
",",
"'#'",
")"
]
| instead of the add_blocks function which was to produce
line shaped walls for blocking path finding agents, this
function creates more natural looking blocking areas like
mountains | [
"instead",
"of",
"the",
"add_blocks",
"function",
"which",
"was",
"to",
"produce",
"line",
"shaped",
"walls",
"for",
"blocking",
"path",
"finding",
"agents",
"this",
"function",
"creates",
"more",
"natural",
"looking",
"blocking",
"areas",
"like",
"mountains"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L198-L216 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | World.add_block | def add_block(self):
""" adds a random size block to the map """
row_max = self.grd.get_grid_height() - 15
if row_max < 2:
row_max = 2
row = randint(0, row_max)
col_max = self.grd.get_grid_width() - 10
if col_max < 2:
col_max = 2
col = randint(0, col_max)
direction = randint(1,19)-10
if direction > 0:
y_len = 10 * (math.floor(self.grd.get_grid_height() / 120) + 1)
x_len = 1 * (math.floor(self.grd.get_grid_width() / 200) + 1)
else:
y_len = 1 * (math.floor(self.grd.get_grid_height() / 200) + 1)
x_len = 10 * (math.floor(self.grd.get_grid_width() / 120) + 1)
print("Adding block to ", row, col, direction)
for r in range(row, row + y_len):
for c in range(col, col + x_len):
self.grd.set_tile(r,c,TERRAIN_BLOCKED) | python | def add_block(self):
""" adds a random size block to the map """
row_max = self.grd.get_grid_height() - 15
if row_max < 2:
row_max = 2
row = randint(0, row_max)
col_max = self.grd.get_grid_width() - 10
if col_max < 2:
col_max = 2
col = randint(0, col_max)
direction = randint(1,19)-10
if direction > 0:
y_len = 10 * (math.floor(self.grd.get_grid_height() / 120) + 1)
x_len = 1 * (math.floor(self.grd.get_grid_width() / 200) + 1)
else:
y_len = 1 * (math.floor(self.grd.get_grid_height() / 200) + 1)
x_len = 10 * (math.floor(self.grd.get_grid_width() / 120) + 1)
print("Adding block to ", row, col, direction)
for r in range(row, row + y_len):
for c in range(col, col + x_len):
self.grd.set_tile(r,c,TERRAIN_BLOCKED) | [
"def",
"add_block",
"(",
"self",
")",
":",
"row_max",
"=",
"self",
".",
"grd",
".",
"get_grid_height",
"(",
")",
"-",
"15",
"if",
"row_max",
"<",
"2",
":",
"row_max",
"=",
"2",
"row",
"=",
"randint",
"(",
"0",
",",
"row_max",
")",
"col_max",
"=",
"self",
".",
"grd",
".",
"get_grid_width",
"(",
")",
"-",
"10",
"if",
"col_max",
"<",
"2",
":",
"col_max",
"=",
"2",
"col",
"=",
"randint",
"(",
"0",
",",
"col_max",
")",
"direction",
"=",
"randint",
"(",
"1",
",",
"19",
")",
"-",
"10",
"if",
"direction",
">",
"0",
":",
"y_len",
"=",
"10",
"*",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"get_grid_height",
"(",
")",
"/",
"120",
")",
"+",
"1",
")",
"x_len",
"=",
"1",
"*",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"get_grid_width",
"(",
")",
"/",
"200",
")",
"+",
"1",
")",
"else",
":",
"y_len",
"=",
"1",
"*",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"get_grid_height",
"(",
")",
"/",
"200",
")",
"+",
"1",
")",
"x_len",
"=",
"10",
"*",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"grd",
".",
"get_grid_width",
"(",
")",
"/",
"120",
")",
"+",
"1",
")",
"print",
"(",
"\"Adding block to \"",
",",
"row",
",",
"col",
",",
"direction",
")",
"for",
"r",
"in",
"range",
"(",
"row",
",",
"row",
"+",
"y_len",
")",
":",
"for",
"c",
"in",
"range",
"(",
"col",
",",
"col",
"+",
"x_len",
")",
":",
"self",
".",
"grd",
".",
"set_tile",
"(",
"r",
",",
"c",
",",
"TERRAIN_BLOCKED",
")"
]
| adds a random size block to the map | [
"adds",
"a",
"random",
"size",
"block",
"to",
"the",
"map"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L220-L243 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | WorldSimulation.run | def run(self, num_runs, show_trails, log_file_base):
"""
Run each agent in the world for 'num_runs' iterations
Optionally saves grid results to file if base name is
passed to method.
"""
print("--------------------------------------------------")
print("Starting Simulation - target = ", self.agent_list[0].target_y, self.agent_list[0].target_x)
self.world.grd.set_tile(self.agent_list[0].target_y , self.agent_list[0].target_x , 'T')
self.highlight_cell_surroundings(self.agent_list[0].target_y, self.agent_list[0].target_x)
self.start_all_agents()
# save the agents results here
try:
with open (log_file_base + '__agents.txt', "w") as f:
f.write("Starting World = \n")
f.write(str(self.world.grd))
except Exception:
print('Cant save log results to ' + log_file_base)
for cur_run in range(0,num_runs):
print("WorldSimulation:run#", cur_run)
for num, agt in enumerate(self.agent_list):
if show_trails == 'Y':
if len(self.agent_list) == 1 or len(self.agent_list) > 9:
self.world.grd.set_tile(agt.current_y, agt.current_x, 'o')
else:
self.world.grd.set_tile(agt.current_y, agt.current_x, str(num))
agt.do_your_job()
self.world.grd.set_tile(agt.current_y, agt.current_x, 'A') # update the main world grid with agents changes
# save grid after each run if required
if log_file_base != 'N':
self.world.grd.save(log_file_base + '_' + str(cur_run) + '.log')
# save the agents results here
with open (log_file_base + '__agents.txt', "a") as f:
f.write("\nWorld tgt= [" + str(self.agent_list[0].target_y) + "," + str(self.agent_list[0].target_x) + "]\n")
f.write(str(self.world.grd))
f.write('\n\nAgent Name , starting, num Steps , num Climbs\n')
for num, agt in enumerate(self.agent_list):
res = agt.name + ' , [' + str(agt.start_y) + ', ' + str(agt.start_x) + '], '
res += str(agt.num_steps) + ' , ' + str(agt.num_climbs) + ' , '
res += ''.join([a for a in agt.results])
f.write(res + '\n') | python | def run(self, num_runs, show_trails, log_file_base):
"""
Run each agent in the world for 'num_runs' iterations
Optionally saves grid results to file if base name is
passed to method.
"""
print("--------------------------------------------------")
print("Starting Simulation - target = ", self.agent_list[0].target_y, self.agent_list[0].target_x)
self.world.grd.set_tile(self.agent_list[0].target_y , self.agent_list[0].target_x , 'T')
self.highlight_cell_surroundings(self.agent_list[0].target_y, self.agent_list[0].target_x)
self.start_all_agents()
# save the agents results here
try:
with open (log_file_base + '__agents.txt', "w") as f:
f.write("Starting World = \n")
f.write(str(self.world.grd))
except Exception:
print('Cant save log results to ' + log_file_base)
for cur_run in range(0,num_runs):
print("WorldSimulation:run#", cur_run)
for num, agt in enumerate(self.agent_list):
if show_trails == 'Y':
if len(self.agent_list) == 1 or len(self.agent_list) > 9:
self.world.grd.set_tile(agt.current_y, agt.current_x, 'o')
else:
self.world.grd.set_tile(agt.current_y, agt.current_x, str(num))
agt.do_your_job()
self.world.grd.set_tile(agt.current_y, agt.current_x, 'A') # update the main world grid with agents changes
# save grid after each run if required
if log_file_base != 'N':
self.world.grd.save(log_file_base + '_' + str(cur_run) + '.log')
# save the agents results here
with open (log_file_base + '__agents.txt', "a") as f:
f.write("\nWorld tgt= [" + str(self.agent_list[0].target_y) + "," + str(self.agent_list[0].target_x) + "]\n")
f.write(str(self.world.grd))
f.write('\n\nAgent Name , starting, num Steps , num Climbs\n')
for num, agt in enumerate(self.agent_list):
res = agt.name + ' , [' + str(agt.start_y) + ', ' + str(agt.start_x) + '], '
res += str(agt.num_steps) + ' , ' + str(agt.num_climbs) + ' , '
res += ''.join([a for a in agt.results])
f.write(res + '\n') | [
"def",
"run",
"(",
"self",
",",
"num_runs",
",",
"show_trails",
",",
"log_file_base",
")",
":",
"print",
"(",
"\"--------------------------------------------------\"",
")",
"print",
"(",
"\"Starting Simulation - target = \"",
",",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_y",
",",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_x",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_y",
",",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_x",
",",
"'T'",
")",
"self",
".",
"highlight_cell_surroundings",
"(",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_y",
",",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_x",
")",
"self",
".",
"start_all_agents",
"(",
")",
"# save the agents results here",
"try",
":",
"with",
"open",
"(",
"log_file_base",
"+",
"'__agents.txt'",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"Starting World = \\n\"",
")",
"f",
".",
"write",
"(",
"str",
"(",
"self",
".",
"world",
".",
"grd",
")",
")",
"except",
"Exception",
":",
"print",
"(",
"'Cant save log results to '",
"+",
"log_file_base",
")",
"for",
"cur_run",
"in",
"range",
"(",
"0",
",",
"num_runs",
")",
":",
"print",
"(",
"\"WorldSimulation:run#\"",
",",
"cur_run",
")",
"for",
"num",
",",
"agt",
"in",
"enumerate",
"(",
"self",
".",
"agent_list",
")",
":",
"if",
"show_trails",
"==",
"'Y'",
":",
"if",
"len",
"(",
"self",
".",
"agent_list",
")",
"==",
"1",
"or",
"len",
"(",
"self",
".",
"agent_list",
")",
">",
"9",
":",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"agt",
".",
"current_y",
",",
"agt",
".",
"current_x",
",",
"'o'",
")",
"else",
":",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"agt",
".",
"current_y",
",",
"agt",
".",
"current_x",
",",
"str",
"(",
"num",
")",
")",
"agt",
".",
"do_your_job",
"(",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"agt",
".",
"current_y",
",",
"agt",
".",
"current_x",
",",
"'A'",
")",
"# update the main world grid with agents changes",
"# save grid after each run if required",
"if",
"log_file_base",
"!=",
"'N'",
":",
"self",
".",
"world",
".",
"grd",
".",
"save",
"(",
"log_file_base",
"+",
"'_'",
"+",
"str",
"(",
"cur_run",
")",
"+",
"'.log'",
")",
"# save the agents results here",
"with",
"open",
"(",
"log_file_base",
"+",
"'__agents.txt'",
",",
"\"a\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"\\nWorld tgt= [\"",
"+",
"str",
"(",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_y",
")",
"+",
"\",\"",
"+",
"str",
"(",
"self",
".",
"agent_list",
"[",
"0",
"]",
".",
"target_x",
")",
"+",
"\"]\\n\"",
")",
"f",
".",
"write",
"(",
"str",
"(",
"self",
".",
"world",
".",
"grd",
")",
")",
"f",
".",
"write",
"(",
"'\\n\\nAgent Name , starting, num Steps , num Climbs\\n'",
")",
"for",
"num",
",",
"agt",
"in",
"enumerate",
"(",
"self",
".",
"agent_list",
")",
":",
"res",
"=",
"agt",
".",
"name",
"+",
"' , ['",
"+",
"str",
"(",
"agt",
".",
"start_y",
")",
"+",
"', '",
"+",
"str",
"(",
"agt",
".",
"start_x",
")",
"+",
"'], '",
"res",
"+=",
"str",
"(",
"agt",
".",
"num_steps",
")",
"+",
"' , '",
"+",
"str",
"(",
"agt",
".",
"num_climbs",
")",
"+",
"' , '",
"res",
"+=",
"''",
".",
"join",
"(",
"[",
"a",
"for",
"a",
"in",
"agt",
".",
"results",
"]",
")",
"f",
".",
"write",
"(",
"res",
"+",
"'\\n'",
")"
]
| Run each agent in the world for 'num_runs' iterations
Optionally saves grid results to file if base name is
passed to method. | [
"Run",
"each",
"agent",
"in",
"the",
"world",
"for",
"num_runs",
"iterations",
"Optionally",
"saves",
"grid",
"results",
"to",
"file",
"if",
"base",
"name",
"is",
"passed",
"to",
"method",
"."
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L259-L302 | train |
acutesoftware/virtual-AI-simulator | vais/worlds.py | WorldSimulation.highlight_cell_surroundings | def highlight_cell_surroundings(self, target_y, target_x):
"""
highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides
"""
#print('SELF_WORLD', self.world)
#print('target_y, target_x, self.world.grd.grid_height, self.world.grd.grid_width ', target_y, target_x, self.#world.grd.grid_height, self.world.grd.grid_width )
#exit(0)
if target_y < 1:
print("target too close to top")
if target_y > self.world.grd.grid_height - 1:
print("target too close to bottom")
if target_x < 1:
print("target too close to left")
if target_x < self.world.grd.grid_width:
print("target too close to right")
#valid_cells = ['\\', '-', '|', '/']
self.world.grd.set_tile(target_y - 1, target_x - 1, '\\')
self.world.grd.set_tile(target_y - 0, target_x - 1, '-')
self.world.grd.set_tile(target_y + 1, target_x - 1, '/')
self.world.grd.set_tile(target_y - 1, target_x - 0, '|')
self.world.grd.set_tile(target_y + 1, target_x - 0, '|')
self.world.grd.set_tile(target_y - 1, target_x + 1, '/')
self.world.grd.set_tile(target_y - 0, target_x + 1, '-')
self.world.grd.set_tile(target_y + 1, target_x + 1, '\\') | python | def highlight_cell_surroundings(self, target_y, target_x):
"""
highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides
"""
#print('SELF_WORLD', self.world)
#print('target_y, target_x, self.world.grd.grid_height, self.world.grd.grid_width ', target_y, target_x, self.#world.grd.grid_height, self.world.grd.grid_width )
#exit(0)
if target_y < 1:
print("target too close to top")
if target_y > self.world.grd.grid_height - 1:
print("target too close to bottom")
if target_x < 1:
print("target too close to left")
if target_x < self.world.grd.grid_width:
print("target too close to right")
#valid_cells = ['\\', '-', '|', '/']
self.world.grd.set_tile(target_y - 1, target_x - 1, '\\')
self.world.grd.set_tile(target_y - 0, target_x - 1, '-')
self.world.grd.set_tile(target_y + 1, target_x - 1, '/')
self.world.grd.set_tile(target_y - 1, target_x - 0, '|')
self.world.grd.set_tile(target_y + 1, target_x - 0, '|')
self.world.grd.set_tile(target_y - 1, target_x + 1, '/')
self.world.grd.set_tile(target_y - 0, target_x + 1, '-')
self.world.grd.set_tile(target_y + 1, target_x + 1, '\\') | [
"def",
"highlight_cell_surroundings",
"(",
"self",
",",
"target_y",
",",
"target_x",
")",
":",
"#print('SELF_WORLD', self.world)",
"#print('target_y, target_x, self.world.grd.grid_height, self.world.grd.grid_width ', target_y, target_x, self.#world.grd.grid_height, self.world.grd.grid_width )",
"#exit(0)",
"if",
"target_y",
"<",
"1",
":",
"print",
"(",
"\"target too close to top\"",
")",
"if",
"target_y",
">",
"self",
".",
"world",
".",
"grd",
".",
"grid_height",
"-",
"1",
":",
"print",
"(",
"\"target too close to bottom\"",
")",
"if",
"target_x",
"<",
"1",
":",
"print",
"(",
"\"target too close to left\"",
")",
"if",
"target_x",
"<",
"self",
".",
"world",
".",
"grd",
".",
"grid_width",
":",
"print",
"(",
"\"target too close to right\"",
")",
"#valid_cells = ['\\\\', '-', '|', '/'] ",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"-",
"1",
",",
"target_x",
"-",
"1",
",",
"'\\\\'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"-",
"0",
",",
"target_x",
"-",
"1",
",",
"'-'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"+",
"1",
",",
"target_x",
"-",
"1",
",",
"'/'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"-",
"1",
",",
"target_x",
"-",
"0",
",",
"'|'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"+",
"1",
",",
"target_x",
"-",
"0",
",",
"'|'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"-",
"1",
",",
"target_x",
"+",
"1",
",",
"'/'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"-",
"0",
",",
"target_x",
"+",
"1",
",",
"'-'",
")",
"self",
".",
"world",
".",
"grd",
".",
"set_tile",
"(",
"target_y",
"+",
"1",
",",
"target_x",
"+",
"1",
",",
"'\\\\'",
")"
]
| highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides | [
"highlights",
"the",
"cells",
"around",
"a",
"target",
"to",
"make",
"it",
"simpler",
"to",
"see",
"on",
"a",
"grid",
".",
"Currently",
"assumes",
"the",
"target",
"is",
"within",
"the",
"boundary",
"by",
"1",
"on",
"all",
"sides"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/worlds.py#L304-L332 | train |
tjcsl/cslbot | cslbot/commands/botspam.py | cmd | def cmd(send, _, args):
"""Abuses the bot.
Syntax: {command}
"""
def lenny_send(msg):
send(gen_lenny(msg))
key = args['config']['api']['bitlykey']
cmds = [lambda: gen_fortune(lenny_send), lambda: gen_urban(lenny_send, args['db'], key)]
choice(cmds)() | python | def cmd(send, _, args):
"""Abuses the bot.
Syntax: {command}
"""
def lenny_send(msg):
send(gen_lenny(msg))
key = args['config']['api']['bitlykey']
cmds = [lambda: gen_fortune(lenny_send), lambda: gen_urban(lenny_send, args['db'], key)]
choice(cmds)() | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"def",
"lenny_send",
"(",
"msg",
")",
":",
"send",
"(",
"gen_lenny",
"(",
"msg",
")",
")",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"cmds",
"=",
"[",
"lambda",
":",
"gen_fortune",
"(",
"lenny_send",
")",
",",
"lambda",
":",
"gen_urban",
"(",
"lenny_send",
",",
"args",
"[",
"'db'",
"]",
",",
"key",
")",
"]",
"choice",
"(",
"cmds",
")",
"(",
")"
]
| Abuses the bot.
Syntax: {command} | [
"Abuses",
"the",
"bot",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/botspam.py#L39-L51 | train |
rraadd88/rohan | rohan/dandage/io_seqs.py | hamming_distance | def hamming_distance(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
# print(s1,s2)
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(el1 != el2 for el1, el2 in zip(s1.upper(), s2.upper())) | python | def hamming_distance(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
# print(s1,s2)
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(el1 != el2 for el1, el2 in zip(s1.upper(), s2.upper())) | [
"def",
"hamming_distance",
"(",
"s1",
",",
"s2",
")",
":",
"# print(s1,s2)",
"if",
"len",
"(",
"s1",
")",
"!=",
"len",
"(",
"s2",
")",
":",
"raise",
"ValueError",
"(",
"\"Undefined for sequences of unequal length\"",
")",
"return",
"sum",
"(",
"el1",
"!=",
"el2",
"for",
"el1",
",",
"el2",
"in",
"zip",
"(",
"s1",
".",
"upper",
"(",
")",
",",
"s2",
".",
"upper",
"(",
")",
")",
")"
]
| Return the Hamming distance between equal-length sequences | [
"Return",
"the",
"Hamming",
"distance",
"between",
"equal",
"-",
"length",
"sequences"
]
| b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_seqs.py#L131-L136 | train |
tjcsl/cslbot | cslbot/commands/lmgtfy.py | cmd | def cmd(send, msg, args):
"""Explain things.
Syntax: {command} <text>
"""
if not msg:
send("Explain What?")
return
msg = msg.replace(' ', '+')
msg = 'http://lmgtfy.com/?q=%s' % msg
key = args['config']['api']['bitlykey']
send(get_short(msg, key)) | python | def cmd(send, msg, args):
"""Explain things.
Syntax: {command} <text>
"""
if not msg:
send("Explain What?")
return
msg = msg.replace(' ', '+')
msg = 'http://lmgtfy.com/?q=%s' % msg
key = args['config']['api']['bitlykey']
send(get_short(msg, key)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Explain What?\"",
")",
"return",
"msg",
"=",
"msg",
".",
"replace",
"(",
"' '",
",",
"'+'",
")",
"msg",
"=",
"'http://lmgtfy.com/?q=%s'",
"%",
"msg",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"send",
"(",
"get_short",
"(",
"msg",
",",
"key",
")",
")"
]
| Explain things.
Syntax: {command} <text> | [
"Explain",
"things",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/lmgtfy.py#L23-L35 | train |
tjcsl/cslbot | cslbot/helpers/misc.py | split_msg | def split_msg(msgs: List[bytes], max_len: int) -> Tuple[str, List[bytes]]:
"""Splits as close to the end as possible."""
msg = ""
while len(msg.encode()) < max_len:
if len(msg.encode()) + len(msgs[0]) > max_len:
return msg, msgs
char = msgs.pop(0).decode()
# If we have a space within 15 chars of the length limit, split there to avoid words being broken up.
if char == " " and len(msg.encode()) > max_len - 15:
return msg, msgs
msg += char
return msg, msgs | python | def split_msg(msgs: List[bytes], max_len: int) -> Tuple[str, List[bytes]]:
"""Splits as close to the end as possible."""
msg = ""
while len(msg.encode()) < max_len:
if len(msg.encode()) + len(msgs[0]) > max_len:
return msg, msgs
char = msgs.pop(0).decode()
# If we have a space within 15 chars of the length limit, split there to avoid words being broken up.
if char == " " and len(msg.encode()) > max_len - 15:
return msg, msgs
msg += char
return msg, msgs | [
"def",
"split_msg",
"(",
"msgs",
":",
"List",
"[",
"bytes",
"]",
",",
"max_len",
":",
"int",
")",
"->",
"Tuple",
"[",
"str",
",",
"List",
"[",
"bytes",
"]",
"]",
":",
"msg",
"=",
"\"\"",
"while",
"len",
"(",
"msg",
".",
"encode",
"(",
")",
")",
"<",
"max_len",
":",
"if",
"len",
"(",
"msg",
".",
"encode",
"(",
")",
")",
"+",
"len",
"(",
"msgs",
"[",
"0",
"]",
")",
">",
"max_len",
":",
"return",
"msg",
",",
"msgs",
"char",
"=",
"msgs",
".",
"pop",
"(",
"0",
")",
".",
"decode",
"(",
")",
"# If we have a space within 15 chars of the length limit, split there to avoid words being broken up.",
"if",
"char",
"==",
"\" \"",
"and",
"len",
"(",
"msg",
".",
"encode",
"(",
")",
")",
">",
"max_len",
"-",
"15",
":",
"return",
"msg",
",",
"msgs",
"msg",
"+=",
"char",
"return",
"msg",
",",
"msgs"
]
| Splits as close to the end as possible. | [
"Splits",
"as",
"close",
"to",
"the",
"end",
"as",
"possible",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/misc.py#L258-L269 | train |
intuition-io/insights | insights/plugins/messaging.py | RedisProtocol.check | def check(self, order, sids):
''' Check if a message is available '''
payload = "{}"
#TODO store hashes {'intuition': {'id1': value, 'id2': value}}
# Block self.timeout seconds on self.channel for a message
raw_msg = self.client.blpop(self.channel, timeout=self.timeout)
if raw_msg:
_, payload = raw_msg
msg = json.loads(payload.replace("'", '"'), encoding='utf-8')
for sid in msg.keys():
#TODO Harmonize lower() and upper() symbols
if sid.lower() in map(str.lower, sids):
print('ordering {} of {}'.format(msg[sid], sid))
#order(sid.upper(), msg[sid])
order(sid, msg[sid])
else:
print('skipping unknown symbol {}'.format(sid)) | python | def check(self, order, sids):
''' Check if a message is available '''
payload = "{}"
#TODO store hashes {'intuition': {'id1': value, 'id2': value}}
# Block self.timeout seconds on self.channel for a message
raw_msg = self.client.blpop(self.channel, timeout=self.timeout)
if raw_msg:
_, payload = raw_msg
msg = json.loads(payload.replace("'", '"'), encoding='utf-8')
for sid in msg.keys():
#TODO Harmonize lower() and upper() symbols
if sid.lower() in map(str.lower, sids):
print('ordering {} of {}'.format(msg[sid], sid))
#order(sid.upper(), msg[sid])
order(sid, msg[sid])
else:
print('skipping unknown symbol {}'.format(sid)) | [
"def",
"check",
"(",
"self",
",",
"order",
",",
"sids",
")",
":",
"payload",
"=",
"\"{}\"",
"#TODO store hashes {'intuition': {'id1': value, 'id2': value}}",
"# Block self.timeout seconds on self.channel for a message",
"raw_msg",
"=",
"self",
".",
"client",
".",
"blpop",
"(",
"self",
".",
"channel",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"if",
"raw_msg",
":",
"_",
",",
"payload",
"=",
"raw_msg",
"msg",
"=",
"json",
".",
"loads",
"(",
"payload",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"for",
"sid",
"in",
"msg",
".",
"keys",
"(",
")",
":",
"#TODO Harmonize lower() and upper() symbols",
"if",
"sid",
".",
"lower",
"(",
")",
"in",
"map",
"(",
"str",
".",
"lower",
",",
"sids",
")",
":",
"print",
"(",
"'ordering {} of {}'",
".",
"format",
"(",
"msg",
"[",
"sid",
"]",
",",
"sid",
")",
")",
"#order(sid.upper(), msg[sid])",
"order",
"(",
"sid",
",",
"msg",
"[",
"sid",
"]",
")",
"else",
":",
"print",
"(",
"'skipping unknown symbol {}'",
".",
"format",
"(",
"sid",
")",
")"
]
| Check if a message is available | [
"Check",
"if",
"a",
"message",
"is",
"available"
]
| a4eae53a1886164db96751d2b0964aa2acb7c2d7 | https://github.com/intuition-io/insights/blob/a4eae53a1886164db96751d2b0964aa2acb7c2d7/insights/plugins/messaging.py#L45-L62 | train |
tjcsl/cslbot | cslbot/commands/botsnack.py | cmd | def cmd(send, msg, args):
"""Causes the bot to snack on something.
Syntax: {command} [object]
"""
if not msg:
send("This tastes yummy!")
elif msg == args['botnick']:
send("wyang says Cannibalism is generally frowned upon.")
else:
send("%s tastes yummy!" % msg.capitalize()) | python | def cmd(send, msg, args):
"""Causes the bot to snack on something.
Syntax: {command} [object]
"""
if not msg:
send("This tastes yummy!")
elif msg == args['botnick']:
send("wyang says Cannibalism is generally frowned upon.")
else:
send("%s tastes yummy!" % msg.capitalize()) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"This tastes yummy!\"",
")",
"elif",
"msg",
"==",
"args",
"[",
"'botnick'",
"]",
":",
"send",
"(",
"\"wyang says Cannibalism is generally frowned upon.\"",
")",
"else",
":",
"send",
"(",
"\"%s tastes yummy!\"",
"%",
"msg",
".",
"capitalize",
"(",
")",
")"
]
| Causes the bot to snack on something.
Syntax: {command} [object] | [
"Causes",
"the",
"bot",
"to",
"snack",
"on",
"something",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/botsnack.py#L22-L33 | train |
Yipit/pyeqs | pyeqs/queryset.py | QuerySet.next | def next(self):
"""
Provide iteration capabilities
Use a small object cache for performance
"""
if not self._cache:
self._cache = self._get_results()
self._retrieved += len(self._cache)
# If we don't have any other data to return, we just
# stop the iteration.
if not self._cache:
raise StopIteration()
# Consuming the cache and updating the "cursor"
return self._cache.pop(0) | python | def next(self):
"""
Provide iteration capabilities
Use a small object cache for performance
"""
if not self._cache:
self._cache = self._get_results()
self._retrieved += len(self._cache)
# If we don't have any other data to return, we just
# stop the iteration.
if not self._cache:
raise StopIteration()
# Consuming the cache and updating the "cursor"
return self._cache.pop(0) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_cache",
":",
"self",
".",
"_cache",
"=",
"self",
".",
"_get_results",
"(",
")",
"self",
".",
"_retrieved",
"+=",
"len",
"(",
"self",
".",
"_cache",
")",
"# If we don't have any other data to return, we just",
"# stop the iteration.",
"if",
"not",
"self",
".",
"_cache",
":",
"raise",
"StopIteration",
"(",
")",
"# Consuming the cache and updating the \"cursor\"",
"return",
"self",
".",
"_cache",
".",
"pop",
"(",
"0",
")"
]
| Provide iteration capabilities
Use a small object cache for performance | [
"Provide",
"iteration",
"capabilities"
]
| 2e385c0a5d113af0e20be4d9393add2aabdd9565 | https://github.com/Yipit/pyeqs/blob/2e385c0a5d113af0e20be4d9393add2aabdd9565/pyeqs/queryset.py#L87-L103 | train |
tjcsl/cslbot | cslbot/commands/throw.py | cmd | def cmd(send, msg, args):
"""Throw something.
Syntax: {command} <object> [at <target>]
"""
users = get_users(args)
if " into " in msg and msg != "into":
match = re.match('(.*) into (.*)', msg)
if match:
msg = 'throws %s into %s' % (match.group(1), match.group(2))
send(msg, 'action')
else:
return
elif " at " in msg and msg != "at":
match = re.match('(.*) at (.*)', msg)
if match:
msg = 'throws %s at %s' % (match.group(1), match.group(2))
send(msg, 'action')
else:
return
elif msg:
msg = 'throws %s at %s' % (msg, choice(users))
send(msg, 'action')
else:
send("Throw what?")
return | python | def cmd(send, msg, args):
"""Throw something.
Syntax: {command} <object> [at <target>]
"""
users = get_users(args)
if " into " in msg and msg != "into":
match = re.match('(.*) into (.*)', msg)
if match:
msg = 'throws %s into %s' % (match.group(1), match.group(2))
send(msg, 'action')
else:
return
elif " at " in msg and msg != "at":
match = re.match('(.*) at (.*)', msg)
if match:
msg = 'throws %s at %s' % (match.group(1), match.group(2))
send(msg, 'action')
else:
return
elif msg:
msg = 'throws %s at %s' % (msg, choice(users))
send(msg, 'action')
else:
send("Throw what?")
return | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"users",
"=",
"get_users",
"(",
"args",
")",
"if",
"\" into \"",
"in",
"msg",
"and",
"msg",
"!=",
"\"into\"",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'(.*) into (.*)'",
",",
"msg",
")",
"if",
"match",
":",
"msg",
"=",
"'throws %s into %s'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
"send",
"(",
"msg",
",",
"'action'",
")",
"else",
":",
"return",
"elif",
"\" at \"",
"in",
"msg",
"and",
"msg",
"!=",
"\"at\"",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'(.*) at (.*)'",
",",
"msg",
")",
"if",
"match",
":",
"msg",
"=",
"'throws %s at %s'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
"send",
"(",
"msg",
",",
"'action'",
")",
"else",
":",
"return",
"elif",
"msg",
":",
"msg",
"=",
"'throws %s at %s'",
"%",
"(",
"msg",
",",
"choice",
"(",
"users",
")",
")",
"send",
"(",
"msg",
",",
"'action'",
")",
"else",
":",
"send",
"(",
"\"Throw what?\"",
")",
"return"
]
| Throw something.
Syntax: {command} <object> [at <target>] | [
"Throw",
"something",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/throw.py#L26-L52 | train |
delvelabs/easyinject | easyinject/injector.py | Injector.wrap | def wrap(self, function):
"""
Wraps a function so that all unspecified arguments will be injected if
possible. Specified arguments always have precedence.
"""
func = inspect.getfullargspec(function)
needed_arguments = func.args + func.kwonlyargs
@wraps(function)
def wrapper(*args, **kwargs):
arguments = kwargs.copy()
missing_arguments = needed_arguments - arguments.keys()
for arg in missing_arguments:
try:
arguments[arg] = self._get_argument(arg)
except KeyError:
pass
return function(*args, **arguments)
return wrapper | python | def wrap(self, function):
"""
Wraps a function so that all unspecified arguments will be injected if
possible. Specified arguments always have precedence.
"""
func = inspect.getfullargspec(function)
needed_arguments = func.args + func.kwonlyargs
@wraps(function)
def wrapper(*args, **kwargs):
arguments = kwargs.copy()
missing_arguments = needed_arguments - arguments.keys()
for arg in missing_arguments:
try:
arguments[arg] = self._get_argument(arg)
except KeyError:
pass
return function(*args, **arguments)
return wrapper | [
"def",
"wrap",
"(",
"self",
",",
"function",
")",
":",
"func",
"=",
"inspect",
".",
"getfullargspec",
"(",
"function",
")",
"needed_arguments",
"=",
"func",
".",
"args",
"+",
"func",
".",
"kwonlyargs",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"arguments",
"=",
"kwargs",
".",
"copy",
"(",
")",
"missing_arguments",
"=",
"needed_arguments",
"-",
"arguments",
".",
"keys",
"(",
")",
"for",
"arg",
"in",
"missing_arguments",
":",
"try",
":",
"arguments",
"[",
"arg",
"]",
"=",
"self",
".",
"_get_argument",
"(",
"arg",
")",
"except",
"KeyError",
":",
"pass",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"arguments",
")",
"return",
"wrapper"
]
| Wraps a function so that all unspecified arguments will be injected if
possible. Specified arguments always have precedence. | [
"Wraps",
"a",
"function",
"so",
"that",
"all",
"unspecified",
"arguments",
"will",
"be",
"injected",
"if",
"possible",
".",
"Specified",
"arguments",
"always",
"have",
"precedence",
"."
]
| 3373890732221032db0ca2e842923a835106a4e9 | https://github.com/delvelabs/easyinject/blob/3373890732221032db0ca2e842923a835106a4e9/easyinject/injector.py#L48-L67 | train |
delvelabs/easyinject | easyinject/injector.py | Injector.call | def call(self, func, *args, **kwargs):
"""
Calls a specified function using the provided arguments and injectable
arguments.
If the function must be called multiple times, it may be best to use
wrap().
"""
wrapped = self.wrap(func)
return wrapped(*args, **kwargs) | python | def call(self, func, *args, **kwargs):
"""
Calls a specified function using the provided arguments and injectable
arguments.
If the function must be called multiple times, it may be best to use
wrap().
"""
wrapped = self.wrap(func)
return wrapped(*args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"wrapped",
"=",
"self",
".",
"wrap",
"(",
"func",
")",
"return",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Calls a specified function using the provided arguments and injectable
arguments.
If the function must be called multiple times, it may be best to use
wrap(). | [
"Calls",
"a",
"specified",
"function",
"using",
"the",
"provided",
"arguments",
"and",
"injectable",
"arguments",
"."
]
| 3373890732221032db0ca2e842923a835106a4e9 | https://github.com/delvelabs/easyinject/blob/3373890732221032db0ca2e842923a835106a4e9/easyinject/injector.py#L97-L106 | train |
JIC-CSB/jicimagelib | jicimagelib/image.py | Image.png | def png(self):
"""Return png string of image."""
use_plugin('freeimage')
with TemporaryFilePath(suffix='.png') as tmp:
safe_range_im = 255 * normalise(self)
imsave(tmp.fpath, safe_range_im.astype(np.uint8))
with open(tmp.fpath, 'rb') as fh:
return fh.read() | python | def png(self):
"""Return png string of image."""
use_plugin('freeimage')
with TemporaryFilePath(suffix='.png') as tmp:
safe_range_im = 255 * normalise(self)
imsave(tmp.fpath, safe_range_im.astype(np.uint8))
with open(tmp.fpath, 'rb') as fh:
return fh.read() | [
"def",
"png",
"(",
"self",
")",
":",
"use_plugin",
"(",
"'freeimage'",
")",
"with",
"TemporaryFilePath",
"(",
"suffix",
"=",
"'.png'",
")",
"as",
"tmp",
":",
"safe_range_im",
"=",
"255",
"*",
"normalise",
"(",
"self",
")",
"imsave",
"(",
"tmp",
".",
"fpath",
",",
"safe_range_im",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
")",
"with",
"open",
"(",
"tmp",
".",
"fpath",
",",
"'rb'",
")",
"as",
"fh",
":",
"return",
"fh",
".",
"read",
"(",
")"
]
| Return png string of image. | [
"Return",
"png",
"string",
"of",
"image",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L86-L93 | train |
JIC-CSB/jicimagelib | jicimagelib/image.py | MicroscopyImage.is_me | def is_me(self, s, c, z, t):
"""Return True if arguments match my meta data.
:param s: series
:param c: channel
:param z: zslice
:param t: timepoint
:returns: :class:`bool`
"""
if (self.series == s
and self.channel == c
and self.zslice == z
and self.timepoint == t):
return True
return False | python | def is_me(self, s, c, z, t):
"""Return True if arguments match my meta data.
:param s: series
:param c: channel
:param z: zslice
:param t: timepoint
:returns: :class:`bool`
"""
if (self.series == s
and self.channel == c
and self.zslice == z
and self.timepoint == t):
return True
return False | [
"def",
"is_me",
"(",
"self",
",",
"s",
",",
"c",
",",
"z",
",",
"t",
")",
":",
"if",
"(",
"self",
".",
"series",
"==",
"s",
"and",
"self",
".",
"channel",
"==",
"c",
"and",
"self",
".",
"zslice",
"==",
"z",
"and",
"self",
".",
"timepoint",
"==",
"t",
")",
":",
"return",
"True",
"return",
"False"
]
| Return True if arguments match my meta data.
:param s: series
:param c: channel
:param z: zslice
:param t: timepoint
:returns: :class:`bool` | [
"Return",
"True",
"if",
"arguments",
"match",
"my",
"meta",
"data",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L137-L151 | train |
JIC-CSB/jicimagelib | jicimagelib/image.py | MicroscopyImage.in_zstack | def in_zstack(self, s, c, t):
"""Return True if I am in the zstack.
:param s: series
:param c: channel
:param t: timepoint
:returns: :class:`bool`
"""
if (self.series == s
and self.channel == c
and self.timepoint == t):
return True
return False | python | def in_zstack(self, s, c, t):
"""Return True if I am in the zstack.
:param s: series
:param c: channel
:param t: timepoint
:returns: :class:`bool`
"""
if (self.series == s
and self.channel == c
and self.timepoint == t):
return True
return False | [
"def",
"in_zstack",
"(",
"self",
",",
"s",
",",
"c",
",",
"t",
")",
":",
"if",
"(",
"self",
".",
"series",
"==",
"s",
"and",
"self",
".",
"channel",
"==",
"c",
"and",
"self",
".",
"timepoint",
"==",
"t",
")",
":",
"return",
"True",
"return",
"False"
]
| Return True if I am in the zstack.
:param s: series
:param c: channel
:param t: timepoint
:returns: :class:`bool` | [
"Return",
"True",
"if",
"I",
"am",
"in",
"the",
"zstack",
"."
]
| fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L153-L165 | train |
jeffh/describe | describe/spec/coordinator.py | SpecCoordinator.find_specs | def find_specs(self, directory):
"""Finds all specs in a given directory. Returns a list of
Example and ExampleGroup instances.
"""
specs = []
spec_files = self.file_finder.find(directory)
for spec_file in spec_files:
specs.extend(self.spec_finder.find(spec_file.module))
return specs | python | def find_specs(self, directory):
"""Finds all specs in a given directory. Returns a list of
Example and ExampleGroup instances.
"""
specs = []
spec_files = self.file_finder.find(directory)
for spec_file in spec_files:
specs.extend(self.spec_finder.find(spec_file.module))
return specs | [
"def",
"find_specs",
"(",
"self",
",",
"directory",
")",
":",
"specs",
"=",
"[",
"]",
"spec_files",
"=",
"self",
".",
"file_finder",
".",
"find",
"(",
"directory",
")",
"for",
"spec_file",
"in",
"spec_files",
":",
"specs",
".",
"extend",
"(",
"self",
".",
"spec_finder",
".",
"find",
"(",
"spec_file",
".",
"module",
")",
")",
"return",
"specs"
]
| Finds all specs in a given directory. Returns a list of
Example and ExampleGroup instances. | [
"Finds",
"all",
"specs",
"in",
"a",
"given",
"directory",
".",
"Returns",
"a",
"list",
"of",
"Example",
"and",
"ExampleGroup",
"instances",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/coordinator.py#L16-L24 | train |
Xion/taipan | taipan/functional/combinators.py | flip | def flip(f):
"""Flip the order of positonal arguments of given function."""
ensure_callable(f)
result = lambda *args, **kwargs: f(*reversed(args), **kwargs)
functools.update_wrapper(result, f, ('__name__', '__module__'))
return result | python | def flip(f):
"""Flip the order of positonal arguments of given function."""
ensure_callable(f)
result = lambda *args, **kwargs: f(*reversed(args), **kwargs)
functools.update_wrapper(result, f, ('__name__', '__module__'))
return result | [
"def",
"flip",
"(",
"f",
")",
":",
"ensure_callable",
"(",
"f",
")",
"result",
"=",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"f",
"(",
"*",
"reversed",
"(",
"args",
")",
",",
"*",
"*",
"kwargs",
")",
"functools",
".",
"update_wrapper",
"(",
"result",
",",
"f",
",",
"(",
"'__name__'",
",",
"'__module__'",
")",
")",
"return",
"result"
]
| Flip the order of positonal arguments of given function. | [
"Flip",
"the",
"order",
"of",
"positonal",
"arguments",
"of",
"given",
"function",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L35-L41 | train |
Xion/taipan | taipan/functional/combinators.py | compose | def compose(*fs):
"""Creates composition of the functions passed in.
:param fs: One-argument functions, with the possible exception of last one
that can accept arbitrary arguments
:return: Function returning a result of functions from ``fs``
applied consecutively to the argument(s), in reverse order
"""
ensure_argcount(fs, min_=1)
fs = list(imap(ensure_callable, fs))
if len(fs) == 1:
return fs[0]
if len(fs) == 2:
f1, f2 = fs
return lambda *args, **kwargs: f1(f2(*args, **kwargs))
if len(fs) == 3:
f1, f2, f3 = fs
return lambda *args, **kwargs: f1(f2(f3(*args, **kwargs)))
fs.reverse()
def g(*args, **kwargs):
x = fs[0](*args, **kwargs)
for f in fs[1:]:
x = f(x)
return x
return g | python | def compose(*fs):
"""Creates composition of the functions passed in.
:param fs: One-argument functions, with the possible exception of last one
that can accept arbitrary arguments
:return: Function returning a result of functions from ``fs``
applied consecutively to the argument(s), in reverse order
"""
ensure_argcount(fs, min_=1)
fs = list(imap(ensure_callable, fs))
if len(fs) == 1:
return fs[0]
if len(fs) == 2:
f1, f2 = fs
return lambda *args, **kwargs: f1(f2(*args, **kwargs))
if len(fs) == 3:
f1, f2, f3 = fs
return lambda *args, **kwargs: f1(f2(f3(*args, **kwargs)))
fs.reverse()
def g(*args, **kwargs):
x = fs[0](*args, **kwargs)
for f in fs[1:]:
x = f(x)
return x
return g | [
"def",
"compose",
"(",
"*",
"fs",
")",
":",
"ensure_argcount",
"(",
"fs",
",",
"min_",
"=",
"1",
")",
"fs",
"=",
"list",
"(",
"imap",
"(",
"ensure_callable",
",",
"fs",
")",
")",
"if",
"len",
"(",
"fs",
")",
"==",
"1",
":",
"return",
"fs",
"[",
"0",
"]",
"if",
"len",
"(",
"fs",
")",
"==",
"2",
":",
"f1",
",",
"f2",
"=",
"fs",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"f1",
"(",
"f2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"if",
"len",
"(",
"fs",
")",
"==",
"3",
":",
"f1",
",",
"f2",
",",
"f3",
"=",
"fs",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"f1",
"(",
"f2",
"(",
"f3",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
")",
"fs",
".",
"reverse",
"(",
")",
"def",
"g",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"x",
"=",
"fs",
"[",
"0",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"f",
"in",
"fs",
"[",
"1",
":",
"]",
":",
"x",
"=",
"f",
"(",
"x",
")",
"return",
"x",
"return",
"g"
]
| Creates composition of the functions passed in.
:param fs: One-argument functions, with the possible exception of last one
that can accept arbitrary arguments
:return: Function returning a result of functions from ``fs``
applied consecutively to the argument(s), in reverse order | [
"Creates",
"composition",
"of",
"the",
"functions",
"passed",
"in",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L44-L73 | train |
Xion/taipan | taipan/functional/combinators.py | merge | def merge(arg, *rest, **kwargs):
"""Merge a collection, with functions as items, into a single function
that takes a collection and maps its items through corresponding functions.
:param arg: A collection of functions, such as list, tuple, or dictionary
:param default: Optional default function to use for items
within merged function's arguments that do not have
corresponding functions in ``arg``
Example with two-element tuple::
>> dict_ = {'Alice': -5, 'Bob': 4}
>> func = merge((str.upper, abs))
>> dict(map(func, dict_.items()))
{'ALICE': 5, 'BOB': 4}
Example with a dictionary::
>> func = merge({'id': int, 'name': str.split})
>> data = [
{'id': '1', 'name': "John Doe"},
{'id': '2', 'name': "Anne Arbor"},
]
>> list(map(func, data))
[{'id': 1, 'name': ['John', 'Doe']},
{'id': 2, 'name': ['Anne', 'Arbor']}]
:return: Merged function
.. versionadded:: 0.0.2
"""
ensure_keyword_args(kwargs, optional=('default',))
has_default = 'default' in kwargs
if has_default:
default = ensure_callable(kwargs['default'])
# if more than one argument was given, they must all be functions;
# result will be a function that takes multiple arguments (rather than
# a single collection) and returns a tuple
unary_result = True
if rest:
fs = (ensure_callable(arg),) + tuple(imap(ensure_callable, rest))
unary_result = False
else:
fs = arg
if is_mapping(fs):
if has_default:
return lambda arg_: fs.__class__((k, fs.get(k, default)(arg_[k]))
for k in arg_)
else:
return lambda arg_: fs.__class__((k, fs[k](arg_[k]))
for k in arg_)
else:
ensure_sequence(fs)
if has_default:
# we cannot use ``izip_longest(fs, arg_, fillvalue=default)``,
# because we want to terminate the generator
# only when ``arg_`` is exhausted (not when just ``fs`` is)
func = lambda arg_: fs.__class__(
(fs[i] if i < len(fs) else default)(x)
for i, x in enumerate(arg_))
else:
# we cannot use ``izip(fs, arg_)`` because it would short-circuit
# if ``arg_`` is longer than ``fs``, rather than raising
# the required ``IndexError``
func = lambda arg_: fs.__class__(fs[i](x)
for i, x in enumerate(arg_))
return func if unary_result else lambda *args: func(args) | python | def merge(arg, *rest, **kwargs):
"""Merge a collection, with functions as items, into a single function
that takes a collection and maps its items through corresponding functions.
:param arg: A collection of functions, such as list, tuple, or dictionary
:param default: Optional default function to use for items
within merged function's arguments that do not have
corresponding functions in ``arg``
Example with two-element tuple::
>> dict_ = {'Alice': -5, 'Bob': 4}
>> func = merge((str.upper, abs))
>> dict(map(func, dict_.items()))
{'ALICE': 5, 'BOB': 4}
Example with a dictionary::
>> func = merge({'id': int, 'name': str.split})
>> data = [
{'id': '1', 'name': "John Doe"},
{'id': '2', 'name': "Anne Arbor"},
]
>> list(map(func, data))
[{'id': 1, 'name': ['John', 'Doe']},
{'id': 2, 'name': ['Anne', 'Arbor']}]
:return: Merged function
.. versionadded:: 0.0.2
"""
ensure_keyword_args(kwargs, optional=('default',))
has_default = 'default' in kwargs
if has_default:
default = ensure_callable(kwargs['default'])
# if more than one argument was given, they must all be functions;
# result will be a function that takes multiple arguments (rather than
# a single collection) and returns a tuple
unary_result = True
if rest:
fs = (ensure_callable(arg),) + tuple(imap(ensure_callable, rest))
unary_result = False
else:
fs = arg
if is_mapping(fs):
if has_default:
return lambda arg_: fs.__class__((k, fs.get(k, default)(arg_[k]))
for k in arg_)
else:
return lambda arg_: fs.__class__((k, fs[k](arg_[k]))
for k in arg_)
else:
ensure_sequence(fs)
if has_default:
# we cannot use ``izip_longest(fs, arg_, fillvalue=default)``,
# because we want to terminate the generator
# only when ``arg_`` is exhausted (not when just ``fs`` is)
func = lambda arg_: fs.__class__(
(fs[i] if i < len(fs) else default)(x)
for i, x in enumerate(arg_))
else:
# we cannot use ``izip(fs, arg_)`` because it would short-circuit
# if ``arg_`` is longer than ``fs``, rather than raising
# the required ``IndexError``
func = lambda arg_: fs.__class__(fs[i](x)
for i, x in enumerate(arg_))
return func if unary_result else lambda *args: func(args) | [
"def",
"merge",
"(",
"arg",
",",
"*",
"rest",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'default'",
",",
")",
")",
"has_default",
"=",
"'default'",
"in",
"kwargs",
"if",
"has_default",
":",
"default",
"=",
"ensure_callable",
"(",
"kwargs",
"[",
"'default'",
"]",
")",
"# if more than one argument was given, they must all be functions;",
"# result will be a function that takes multiple arguments (rather than",
"# a single collection) and returns a tuple",
"unary_result",
"=",
"True",
"if",
"rest",
":",
"fs",
"=",
"(",
"ensure_callable",
"(",
"arg",
")",
",",
")",
"+",
"tuple",
"(",
"imap",
"(",
"ensure_callable",
",",
"rest",
")",
")",
"unary_result",
"=",
"False",
"else",
":",
"fs",
"=",
"arg",
"if",
"is_mapping",
"(",
"fs",
")",
":",
"if",
"has_default",
":",
"return",
"lambda",
"arg_",
":",
"fs",
".",
"__class__",
"(",
"(",
"k",
",",
"fs",
".",
"get",
"(",
"k",
",",
"default",
")",
"(",
"arg_",
"[",
"k",
"]",
")",
")",
"for",
"k",
"in",
"arg_",
")",
"else",
":",
"return",
"lambda",
"arg_",
":",
"fs",
".",
"__class__",
"(",
"(",
"k",
",",
"fs",
"[",
"k",
"]",
"(",
"arg_",
"[",
"k",
"]",
")",
")",
"for",
"k",
"in",
"arg_",
")",
"else",
":",
"ensure_sequence",
"(",
"fs",
")",
"if",
"has_default",
":",
"# we cannot use ``izip_longest(fs, arg_, fillvalue=default)``,",
"# because we want to terminate the generator",
"# only when ``arg_`` is exhausted (not when just ``fs`` is)",
"func",
"=",
"lambda",
"arg_",
":",
"fs",
".",
"__class__",
"(",
"(",
"fs",
"[",
"i",
"]",
"if",
"i",
"<",
"len",
"(",
"fs",
")",
"else",
"default",
")",
"(",
"x",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"arg_",
")",
")",
"else",
":",
"# we cannot use ``izip(fs, arg_)`` because it would short-circuit",
"# if ``arg_`` is longer than ``fs``, rather than raising",
"# the required ``IndexError``",
"func",
"=",
"lambda",
"arg_",
":",
"fs",
".",
"__class__",
"(",
"fs",
"[",
"i",
"]",
"(",
"x",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"arg_",
")",
")",
"return",
"func",
"if",
"unary_result",
"else",
"lambda",
"*",
"args",
":",
"func",
"(",
"args",
")"
]
| Merge a collection, with functions as items, into a single function
that takes a collection and maps its items through corresponding functions.
:param arg: A collection of functions, such as list, tuple, or dictionary
:param default: Optional default function to use for items
within merged function's arguments that do not have
corresponding functions in ``arg``
Example with two-element tuple::
>> dict_ = {'Alice': -5, 'Bob': 4}
>> func = merge((str.upper, abs))
>> dict(map(func, dict_.items()))
{'ALICE': 5, 'BOB': 4}
Example with a dictionary::
>> func = merge({'id': int, 'name': str.split})
>> data = [
{'id': '1', 'name': "John Doe"},
{'id': '2', 'name': "Anne Arbor"},
]
>> list(map(func, data))
[{'id': 1, 'name': ['John', 'Doe']},
{'id': 2, 'name': ['Anne', 'Arbor']}]
:return: Merged function
.. versionadded:: 0.0.2 | [
"Merge",
"a",
"collection",
"with",
"functions",
"as",
"items",
"into",
"a",
"single",
"function",
"that",
"takes",
"a",
"collection",
"and",
"maps",
"its",
"items",
"through",
"corresponding",
"functions",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L76-L145 | train |
Xion/taipan | taipan/functional/combinators.py | and_ | def and_(*fs):
"""Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments
"""
ensure_argcount(fs, min_=1)
fs = list(imap(ensure_callable, fs))
if len(fs) == 1:
return fs[0]
if len(fs) == 2:
f1, f2 = fs
return lambda *args, **kwargs: (
f1(*args, **kwargs) and f2(*args, **kwargs))
if len(fs) == 3:
f1, f2, f3 = fs
return lambda *args, **kwargs: (
f1(*args, **kwargs) and f2(*args, **kwargs) and f3(*args, **kwargs))
def g(*args, **kwargs):
for f in fs:
if not f(*args, **kwargs):
return False
return True
return g | python | def and_(*fs):
"""Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments
"""
ensure_argcount(fs, min_=1)
fs = list(imap(ensure_callable, fs))
if len(fs) == 1:
return fs[0]
if len(fs) == 2:
f1, f2 = fs
return lambda *args, **kwargs: (
f1(*args, **kwargs) and f2(*args, **kwargs))
if len(fs) == 3:
f1, f2, f3 = fs
return lambda *args, **kwargs: (
f1(*args, **kwargs) and f2(*args, **kwargs) and f3(*args, **kwargs))
def g(*args, **kwargs):
for f in fs:
if not f(*args, **kwargs):
return False
return True
return g | [
"def",
"and_",
"(",
"*",
"fs",
")",
":",
"ensure_argcount",
"(",
"fs",
",",
"min_",
"=",
"1",
")",
"fs",
"=",
"list",
"(",
"imap",
"(",
"ensure_callable",
",",
"fs",
")",
")",
"if",
"len",
"(",
"fs",
")",
"==",
"1",
":",
"return",
"fs",
"[",
"0",
"]",
"if",
"len",
"(",
"fs",
")",
"==",
"2",
":",
"f1",
",",
"f2",
"=",
"fs",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"(",
"f1",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"and",
"f2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"if",
"len",
"(",
"fs",
")",
"==",
"3",
":",
"f1",
",",
"f2",
",",
"f3",
"=",
"fs",
"return",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"(",
"f1",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"and",
"f2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"and",
"f3",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"def",
"g",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"f",
"in",
"fs",
":",
"if",
"not",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"False",
"return",
"True",
"return",
"g"
]
| Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments | [
"Creates",
"a",
"function",
"that",
"returns",
"true",
"for",
"given",
"arguments",
"iff",
"every",
"given",
"function",
"evalutes",
"to",
"true",
"for",
"those",
"arguments",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/combinators.py#L162-L191 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.