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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cozy/python_cozy_management | cozy_management/ssl.py | make_links | def make_links(current_cn):
'''
Create symlink for nginx
'''
if not os.path.isfile(CURRENT_CERTIFICATE_PATH):
target = '{}/{}.crt'.format(CERTIFICATES_PATH, current_cn)
print 'Create symlink {} -> {}'.format(CURRENT_CERTIFICATE_PATH,
tar... | python | def make_links(current_cn):
'''
Create symlink for nginx
'''
if not os.path.isfile(CURRENT_CERTIFICATE_PATH):
target = '{}/{}.crt'.format(CERTIFICATES_PATH, current_cn)
print 'Create symlink {} -> {}'.format(CURRENT_CERTIFICATE_PATH,
tar... | [
"def",
"make_links",
"(",
"current_cn",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"CURRENT_CERTIFICATE_PATH",
")",
":",
"target",
"=",
"'{}/{}.crt'",
".",
"format",
"(",
"CERTIFICATES_PATH",
",",
"current_cn",
")",
"print",
"'Create symlink... | Create symlink for nginx | [
"Create",
"symlink",
"for",
"nginx"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L310-L324 | train |
assamite/creamas | creamas/core/simulation.py | Simulation.create | def create(self, agent_cls=None, n_agents=10, agent_kwargs={},
env_cls=Environment, env_kwargs={}, callback=None, conns=0,
log_folder=None):
"""A convenience function to create simple simulations.
Method first creates environment, then instantiates agents into it
w... | python | def create(self, agent_cls=None, n_agents=10, agent_kwargs={},
env_cls=Environment, env_kwargs={}, callback=None, conns=0,
log_folder=None):
"""A convenience function to create simple simulations.
Method first creates environment, then instantiates agents into it
w... | [
"def",
"create",
"(",
"self",
",",
"agent_cls",
"=",
"None",
",",
"n_agents",
"=",
"10",
",",
"agent_kwargs",
"=",
"{",
"}",
",",
"env_cls",
"=",
"Environment",
",",
"env_kwargs",
"=",
"{",
"}",
",",
"callback",
"=",
"None",
",",
"conns",
"=",
"0",
... | A convenience function to create simple simulations.
Method first creates environment, then instantiates agents into it
with give arguments, and finally creates simulation for the
environment.
:param agent_cls:
class for agents, or list of classes. If list, then **n_agents*... | [
"A",
"convenience",
"function",
"to",
"create",
"simple",
"simulations",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L28-L101 | train |
assamite/creamas | creamas/core/simulation.py | Simulation._init_step | def _init_step(self):
"""Initialize next step of simulation to be run.
"""
self._age += 1
self.env.age = self._age
self._log(logging.INFO, "")
self._log(logging.INFO, "\t***** Step {:0>4} *****". format(self.age))
self._log(logging.INFO, "")
self._agents_t... | python | def _init_step(self):
"""Initialize next step of simulation to be run.
"""
self._age += 1
self.env.age = self._age
self._log(logging.INFO, "")
self._log(logging.INFO, "\t***** Step {:0>4} *****". format(self.age))
self._log(logging.INFO, "")
self._agents_t... | [
"def",
"_init_step",
"(",
"self",
")",
":",
"self",
".",
"_age",
"+=",
"1",
"self",
".",
"env",
".",
"age",
"=",
"self",
".",
"_age",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"\"\"",
")",
"self",
".",
"_log",
"(",
"logging",
".",
... | Initialize next step of simulation to be run. | [
"Initialize",
"next",
"step",
"of",
"simulation",
"to",
"be",
"run",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L186-L196 | train |
assamite/creamas | creamas/core/simulation.py | Simulation._finalize_step | def _finalize_step(self):
"""Finalize simulation step after all agents have acted for the current
step.
"""
t = time.time()
if self._callback is not None:
self._callback(self.age)
t2 = time.time()
self._step_processing_time += t2 - t
self._log(... | python | def _finalize_step(self):
"""Finalize simulation step after all agents have acted for the current
step.
"""
t = time.time()
if self._callback is not None:
self._callback(self.age)
t2 = time.time()
self._step_processing_time += t2 - t
self._log(... | [
"def",
"_finalize_step",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"_callback",
"is",
"not",
"None",
":",
"self",
".",
"_callback",
"(",
"self",
".",
"age",
")",
"t2",
"=",
"time",
".",
"time",
"(",
")",
... | Finalize simulation step after all agents have acted for the current
step. | [
"Finalize",
"simulation",
"step",
"after",
"all",
"agents",
"have",
"acted",
"for",
"the",
"current",
"step",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L198-L211 | train |
assamite/creamas | creamas/core/simulation.py | Simulation.async_step | def async_step(self):
"""Progress simulation by running all agents once asynchronously.
"""
assert len(self._agents_to_act) == 0
self._init_step()
t = time.time()
aiomas.run(until=self.env.trigger_all())
self._agents_to_act = []
self._step_processing_time ... | python | def async_step(self):
"""Progress simulation by running all agents once asynchronously.
"""
assert len(self._agents_to_act) == 0
self._init_step()
t = time.time()
aiomas.run(until=self.env.trigger_all())
self._agents_to_act = []
self._step_processing_time ... | [
"def",
"async_step",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"self",
".",
"_init_step",
"(",
")",
"t",
"=",
"time",
".",
"time",
"(",
")",
"aiomas",
".",
"run",
"(",
"until",
"=",
"self",
".",
"... | Progress simulation by running all agents once asynchronously. | [
"Progress",
"simulation",
"by",
"running",
"all",
"agents",
"once",
"asynchronously",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L220-L229 | train |
assamite/creamas | creamas/core/simulation.py | Simulation.steps | def steps(self, n):
"""Progress simulation with given amount of steps.
Can not be called when some of the agents have not acted for the
current step.
:param int n: amount of steps to run
"""
assert len(self._agents_to_act) == 0
for _ in range(n):
sel... | python | def steps(self, n):
"""Progress simulation with given amount of steps.
Can not be called when some of the agents have not acted for the
current step.
:param int n: amount of steps to run
"""
assert len(self._agents_to_act) == 0
for _ in range(n):
sel... | [
"def",
"steps",
"(",
"self",
",",
"n",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"self",
".",
"step",
"(",
")"
] | Progress simulation with given amount of steps.
Can not be called when some of the agents have not acted for the
current step.
:param int n: amount of steps to run | [
"Progress",
"simulation",
"with",
"given",
"amount",
"of",
"steps",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L231-L241 | train |
assamite/creamas | creamas/core/simulation.py | Simulation.step | def step(self):
"""Progress simulation with a single step.
Can not be called when some of the agents have not acted for the
current step.
"""
assert len(self._agents_to_act) == 0
self.next()
while len(self._agents_to_act) > 0:
self.next() | python | def step(self):
"""Progress simulation with a single step.
Can not be called when some of the agents have not acted for the
current step.
"""
assert len(self._agents_to_act) == 0
self.next()
while len(self._agents_to_act) > 0:
self.next() | [
"def",
"step",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
"==",
"0",
"self",
".",
"next",
"(",
")",
"while",
"len",
"(",
"self",
".",
"_agents_to_act",
")",
">",
"0",
":",
"self",
".",
"next",
"(",
")"
] | Progress simulation with a single step.
Can not be called when some of the agents have not acted for the
current step. | [
"Progress",
"simulation",
"with",
"a",
"single",
"step",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L243-L252 | train |
assamite/creamas | creamas/core/simulation.py | Simulation.end | def end(self, folder=None):
"""End the simulation and destroy the current simulation environment.
"""
ret = self.env.destroy(folder=folder)
self._end_time = time.time()
self._log(logging.DEBUG, "Simulation run with {} steps took {:.3f}s to"
" complete, while act... | python | def end(self, folder=None):
"""End the simulation and destroy the current simulation environment.
"""
ret = self.env.destroy(folder=folder)
self._end_time = time.time()
self._log(logging.DEBUG, "Simulation run with {} steps took {:.3f}s to"
" complete, while act... | [
"def",
"end",
"(",
"self",
",",
"folder",
"=",
"None",
")",
":",
"ret",
"=",
"self",
".",
"env",
".",
"destroy",
"(",
"folder",
"=",
"folder",
")",
"self",
".",
"_end_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_log",
"(",
"logging",... | End the simulation and destroy the current simulation environment. | [
"End",
"the",
"simulation",
"and",
"destroy",
"the",
"current",
"simulation",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L282-L291 | train |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.get_unique_record | def get_unique_record(self, sql, parameters = None, quiet = False, locked = False):
'''I use this pattern a lot. Return the single record corresponding to the query.'''
results = self.execute_select(sql, parameters = parameters, quiet = quiet, locked = locked)
assert(len(results) == 1)
r... | python | def get_unique_record(self, sql, parameters = None, quiet = False, locked = False):
'''I use this pattern a lot. Return the single record corresponding to the query.'''
results = self.execute_select(sql, parameters = parameters, quiet = quiet, locked = locked)
assert(len(results) == 1)
r... | [
"def",
"get_unique_record",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"locked",
"=",
"False",
")",
":",
"results",
"=",
"self",
".",
"execute_select",
"(",
"sql",
",",
"parameters",
"=",
"parameters",
",",
... | I use this pattern a lot. Return the single record corresponding to the query. | [
"I",
"use",
"this",
"pattern",
"a",
"lot",
".",
"Return",
"the",
"single",
"record",
"corresponding",
"to",
"the",
"query",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L167-L171 | train |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.run_transaction | def run_transaction(self, command_list, do_commit=True):
'''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the e... | python | def run_transaction(self, command_list, do_commit=True):
'''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the e... | [
"def",
"run_transaction",
"(",
"self",
",",
"command_list",
",",
"do_commit",
"=",
"True",
")",
":",
"pass",
"for",
"c",
"in",
"command_list",
":",
"if",
"c",
".",
"find",
"(",
"\";\"",
")",
"!=",
"-",
"1",
"or",
"c",
".",
"find",
"(",
"\"\\\\G\"",
... | This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful
if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur
if the entity is tied to table not specified in the list of commands. Perfor... | [
"This",
"can",
"be",
"used",
"to",
"stage",
"multiple",
"commands",
"and",
"roll",
"back",
"the",
"transaction",
"if",
"an",
"error",
"occurs",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"remove",
"multiple",
"records",
"in",
"multiple",
"tabl... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L327-L347 | train |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.callproc | def callproc(self, procname, parameters=(), quiet=False, expect_return_value=False):
"""Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character.
"""
self.... | python | def callproc(self, procname, parameters=(), quiet=False, expect_return_value=False):
"""Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character.
"""
self.... | [
"def",
"callproc",
"(",
"self",
",",
"procname",
",",
"parameters",
"=",
"(",
")",
",",
"quiet",
"=",
"False",
",",
"expect_return_value",
"=",
"False",
")",
":",
"self",
".",
"procedures_run",
"+=",
"1",
"i",
"=",
"0",
"errcode",
"=",
"0",
"caughte",
... | Calls a MySQL stored procedure procname and returns the return values. This uses DictCursor.
To get return values back out of a stored procedure, prefix the parameter with a @ character. | [
"Calls",
"a",
"MySQL",
"stored",
"procedure",
"procname",
"and",
"returns",
"the",
"return",
"values",
".",
"This",
"uses",
"DictCursor",
".",
"To",
"get",
"return",
"values",
"back",
"out",
"of",
"a",
"stored",
"procedure",
"prefix",
"the",
"parameter",
"wi... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L462-L514 | train |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.t_insert_dict_if_new | def t_insert_dict_if_new(self, tblname, d, PKfields, fields=None):
'''A version of insertDictIfNew for transactions. This does not call commit.'''
SQL, values = self._insert_dict_if_new_inner(tblname, d, PKfields, fields=fields)
if SQL != False:
self.execute_select(SQL, parameters=va... | python | def t_insert_dict_if_new(self, tblname, d, PKfields, fields=None):
'''A version of insertDictIfNew for transactions. This does not call commit.'''
SQL, values = self._insert_dict_if_new_inner(tblname, d, PKfields, fields=fields)
if SQL != False:
self.execute_select(SQL, parameters=va... | [
"def",
"t_insert_dict_if_new",
"(",
"self",
",",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=",
"None",
")",
":",
"SQL",
",",
"values",
"=",
"self",
".",
"_insert_dict_if_new_inner",
"(",
"tblname",
",",
"d",
",",
"PKfields",
",",
"fields",
"=... | A version of insertDictIfNew for transactions. This does not call commit. | [
"A",
"version",
"of",
"insertDictIfNew",
"for",
"transactions",
".",
"This",
"does",
"not",
"call",
"commit",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L538-L544 | train |
Kortemme-Lab/klab | klab/db/mysql.py | DatabaseInterface.create_insert_dict_string | def create_insert_dict_string(self, tblname, d, PKfields=[], fields=None, check_existing = False):
'''The main function of the insert_dict functions.
This creates and returns the SQL query and parameters used by the other functions but does not insert any data into the database.
Simple fu... | python | def create_insert_dict_string(self, tblname, d, PKfields=[], fields=None, check_existing = False):
'''The main function of the insert_dict functions.
This creates and returns the SQL query and parameters used by the other functions but does not insert any data into the database.
Simple fu... | [
"def",
"create_insert_dict_string",
"(",
"self",
",",
"tblname",
",",
"d",
",",
"PKfields",
"=",
"[",
"]",
",",
"fields",
"=",
"None",
",",
"check_existing",
"=",
"False",
")",
":",
"if",
"type",
"(",
"PKfields",
")",
"==",
"type",
"(",
"\"\"",
")",
... | The main function of the insert_dict functions.
This creates and returns the SQL query and parameters used by the other functions but does not insert any data into the database.
Simple function for inserting a dictionary whose keys match the fieldnames of tblname. The function returns two values,... | [
"The",
"main",
"function",
"of",
"the",
"insert_dict",
"functions",
".",
"This",
"creates",
"and",
"returns",
"the",
"SQL",
"query",
"and",
"parameters",
"used",
"by",
"the",
"other",
"functions",
"but",
"does",
"not",
"insert",
"any",
"data",
"into",
"the",... | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/mysql.py#L649-L687 | train |
ronhanson/python-tbx | tbx/bytes.py | bytes_to_int | def bytes_to_int(byte_array, big_endian=True, signed=False):
"""
Converts a byte array to an integer.
"""
if six.PY3:
order = 'little'
if big_endian:
order = 'big'
return int.from_bytes(byte_array, byteorder=order, signed=signed)
else:
length = len(byte_ar... | python | def bytes_to_int(byte_array, big_endian=True, signed=False):
"""
Converts a byte array to an integer.
"""
if six.PY3:
order = 'little'
if big_endian:
order = 'big'
return int.from_bytes(byte_array, byteorder=order, signed=signed)
else:
length = len(byte_ar... | [
"def",
"bytes_to_int",
"(",
"byte_array",
",",
"big_endian",
"=",
"True",
",",
"signed",
"=",
"False",
")",
":",
"if",
"six",
".",
"PY3",
":",
"order",
"=",
"'little'",
"if",
"big_endian",
":",
"order",
"=",
"'big'",
"return",
"int",
".",
"from_bytes",
... | Converts a byte array to an integer. | [
"Converts",
"a",
"byte",
"array",
"to",
"an",
"integer",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L20-L48 | train |
ronhanson/python-tbx | tbx/bytes.py | ip_to_bytes | def ip_to_bytes(ip_str, big_endian=True):
"""
Converts an IP given as a string to a byte sequence
"""
if big_endian:
code = '>L'
else:
code = '<L'
return bytes(struct.unpack(code, socket.inet_aton(ip_str))[0]) | python | def ip_to_bytes(ip_str, big_endian=True):
"""
Converts an IP given as a string to a byte sequence
"""
if big_endian:
code = '>L'
else:
code = '<L'
return bytes(struct.unpack(code, socket.inet_aton(ip_str))[0]) | [
"def",
"ip_to_bytes",
"(",
"ip_str",
",",
"big_endian",
"=",
"True",
")",
":",
"if",
"big_endian",
":",
"code",
"=",
"'>L'",
"else",
":",
"code",
"=",
"'<L'",
"return",
"bytes",
"(",
"struct",
".",
"unpack",
"(",
"code",
",",
"socket",
".",
"inet_aton"... | Converts an IP given as a string to a byte sequence | [
"Converts",
"an",
"IP",
"given",
"as",
"a",
"string",
"to",
"a",
"byte",
"sequence"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L169-L177 | train |
assamite/creamas | creamas/logging.py | ObjectLogger.get_file | def get_file(self, attr_name):
'''Return absolute path to logging file for obj's attribute.'''
return os.path.abspath(os.path.join(self.folder, "{}.log"
.format(attr_name))) | python | def get_file(self, attr_name):
'''Return absolute path to logging file for obj's attribute.'''
return os.path.abspath(os.path.join(self.folder, "{}.log"
.format(attr_name))) | [
"def",
"get_file",
"(",
"self",
",",
"attr_name",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"folder",
",",
"\"{}.log\"",
".",
"format",
"(",
"attr_name",
")",
")",
")"
] | Return absolute path to logging file for obj's attribute. | [
"Return",
"absolute",
"path",
"to",
"logging",
"file",
"for",
"obj",
"s",
"attribute",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L115-L118 | train |
assamite/creamas | creamas/logging.py | ObjectLogger.log_attr | def log_attr(self, level, attr_name):
'''Log attribute to file and pass the message to underlying logger.
:param int level: logging level
:param str attr_name: attribute's name to be logged
'''
msg = self.write(attr_name)
self.log(level, msg) | python | def log_attr(self, level, attr_name):
'''Log attribute to file and pass the message to underlying logger.
:param int level: logging level
:param str attr_name: attribute's name to be logged
'''
msg = self.write(attr_name)
self.log(level, msg) | [
"def",
"log_attr",
"(",
"self",
",",
"level",
",",
"attr_name",
")",
":",
"msg",
"=",
"self",
".",
"write",
"(",
"attr_name",
")",
"self",
".",
"log",
"(",
"level",
",",
"msg",
")"
] | Log attribute to file and pass the message to underlying logger.
:param int level: logging level
:param str attr_name: attribute's name to be logged | [
"Log",
"attribute",
"to",
"file",
"and",
"pass",
"the",
"message",
"to",
"underlying",
"logger",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L120-L127 | train |
assamite/creamas | creamas/logging.py | ObjectLogger.write | def write(self, attr_name, prefix=None):
'''Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: mes... | python | def write(self, attr_name, prefix=None):
'''Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: mes... | [
"def",
"write",
"(",
"self",
",",
"attr_name",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_folder",
"is",
"None",
":",
"return",
"separator",
"=",
"\"\\t\"",
"attr",
"=",
"getattr",
"(",
"self",
".",
"obj",
",",
"attr_name",
")",
"if",... | Write attribute's value to a file.
:param str attr_name:
Attribute's name to be logged
:param str prefix:
Optional. Attribute's name that is prefixed to logging message,
defaults to ``None``.
:returns: message written to file
:rtype: str | [
"Write",
"attribute",
"s",
"value",
"to",
"a",
"file",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/logging.py#L133-L163 | train |
adaptive-learning/proso-apps | proso/func.py | is_lambda | def is_lambda(fun):
"""
Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
i... | python | def is_lambda(fun):
"""
Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
i... | [
"def",
"is_lambda",
"(",
"fun",
")",
":",
"return",
"isinstance",
"(",
"fun",
",",
"type",
"(",
"LAMBDA",
")",
")",
"and",
"fun",
".",
"__name__",
"==",
"LAMBDA",
".",
"__name__"
] | Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
is_lambda(lambda_fun)
)
... | [
"Check",
"whether",
"the",
"given",
"function",
"is",
"a",
"lambda",
"function",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/func.py#L4-L33 | train |
adaptive-learning/proso-apps | proso/func.py | fixed_point | def fixed_point(is_zero, plus, minus, f, x):
"""
Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs +... | python | def fixed_point(is_zero, plus, minus, f, x):
"""
Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs +... | [
"def",
"fixed_point",
"(",
"is_zero",
",",
"plus",
",",
"minus",
",",
"f",
",",
"x",
")",
":",
"@",
"memo_Y",
"def",
"_fixed_point",
"(",
"fixed_point_fun",
")",
":",
"def",
"__fixed_point",
"(",
"collected",
",",
"new",
")",
":",
"diff",
"=",
"minus",... | Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs + ys,
... minus=lambda xs, ys: [x for x in xs i... | [
"Get",
"the",
"least",
"fixed",
"point",
"when",
"it",
"can",
"be",
"computed",
"piecewise",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/func.py#L44-L83 | train |
adaptive-learning/proso-apps | proso/func.py | memo_Y | def memo_Y(f):
"""
Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
... | python | def memo_Y(f):
"""
Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
... | [
"def",
"memo_Y",
"(",
"f",
")",
":",
"sub",
"=",
"{",
"}",
"def",
"Yf",
"(",
"*",
"args",
")",
":",
"hashable_args",
"=",
"tuple",
"(",
"[",
"repr",
"(",
"x",
")",
"for",
"x",
"in",
"args",
"]",
")",
"if",
"args",
":",
"if",
"hashable_args",
... | Memoized Y combinator.
.. testsetup::
from proso.func import memo_Y
.. testcode::
@memo_Y
def fib(f):
def inner_fib(n):
if n > 1:
return f(n - 1) + f(n - 2)
else:
return n
return inner_fib... | [
"Memoized",
"Y",
"combinator",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/func.py#L86-L122 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | install | def install(application, default_content_type, encoding=None):
"""
Install the media type management settings.
:param tornado.web.Application application: the application to
install a :class:`.ContentSettings` object into.
:param str|NoneType default_content_type:
:param str|NoneType encodi... | python | def install(application, default_content_type, encoding=None):
"""
Install the media type management settings.
:param tornado.web.Application application: the application to
install a :class:`.ContentSettings` object into.
:param str|NoneType default_content_type:
:param str|NoneType encodi... | [
"def",
"install",
"(",
"application",
",",
"default_content_type",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"settings",
"=",
"application",
".",
"settings",
"[",
"SETTINGS_KEY",
"]",
"except",
"KeyError",
":",
"settings",
"=",
"application",
".",
... | Install the media type management settings.
:param tornado.web.Application application: the application to
install a :class:`.ContentSettings` object into.
:param str|NoneType default_content_type:
:param str|NoneType encoding:
:returns: the content settings instance
:rtype: sprockets.mixi... | [
"Install",
"the",
"media",
"type",
"management",
"settings",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L127-L146 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | get_settings | def get_settings(application, force_instance=False):
"""
Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:r... | python | def get_settings(application, force_instance=False):
"""
Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:r... | [
"def",
"get_settings",
"(",
"application",
",",
"force_instance",
"=",
"False",
")",
":",
"try",
":",
"return",
"application",
".",
"settings",
"[",
"SETTINGS_KEY",
"]",
"except",
"KeyError",
":",
"if",
"not",
"force_instance",
":",
"return",
"None",
"return",... | Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:rtype: sprockets.mixins.mediatype.content.ContentSettings | [
"Retrieve",
"the",
"media",
"type",
"settings",
"for",
"a",
"application",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L149-L166 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | add_binary_content_type | def add_binary_content_type(application, content_type, pack, unpack):
"""
Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
... | python | def add_binary_content_type(application, content_type, pack, unpack):
"""
Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
... | [
"def",
"add_binary_content_type",
"(",
"application",
",",
"content_type",
",",
"pack",
",",
"unpack",
")",
":",
"add_transcoder",
"(",
"application",
",",
"handlers",
".",
"BinaryContentHandler",
"(",
"content_type",
",",
"pack",
",",
"unpack",
")",
")"
] | Add handler for a binary content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param pack: function that packs a dictionary to a byte string.
``pack(dict) -> bytes``
:param unpack: function that takes a byte string ... | [
"Add",
"handler",
"for",
"a",
"binary",
"content",
"type",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L169-L182 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | add_text_content_type | def add_text_content_type(application, content_type, default_encoding,
dumps, loads):
"""
Add handler for a text content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param str default_encoding... | python | def add_text_content_type(application, content_type, default_encoding,
dumps, loads):
"""
Add handler for a text content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param str default_encoding... | [
"def",
"add_text_content_type",
"(",
"application",
",",
"content_type",
",",
"default_encoding",
",",
"dumps",
",",
"loads",
")",
":",
"parsed",
"=",
"headers",
".",
"parse_content_type",
"(",
"content_type",
")",
"parsed",
".",
"parameters",
".",
"pop",
"(",
... | Add handler for a text content type.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to add
:param str default_encoding: encoding to use when one is unspecified
:param dumps: function that dumps a dictionary to a string.
``dumps(di... | [
"Add",
"handler",
"for",
"a",
"text",
"content",
"type",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L185-L207 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | add_transcoder | def add_transcoder(application, transcoder, content_type=None):
"""
Register a transcoder for a specific content type.
:param tornado.web.Application application: the application to modify
:param transcoder: object that translates between :class:`bytes` and
:class:`object` instances
:param ... | python | def add_transcoder(application, transcoder, content_type=None):
"""
Register a transcoder for a specific content type.
:param tornado.web.Application application: the application to modify
:param transcoder: object that translates between :class:`bytes` and
:class:`object` instances
:param ... | [
"def",
"add_transcoder",
"(",
"application",
",",
"transcoder",
",",
"content_type",
"=",
"None",
")",
":",
"settings",
"=",
"get_settings",
"(",
"application",
",",
"force_instance",
"=",
"True",
")",
"settings",
"[",
"content_type",
"or",
"transcoder",
".",
... | Register a transcoder for a specific content type.
:param tornado.web.Application application: the application to modify
:param transcoder: object that translates between :class:`bytes` and
:class:`object` instances
:param str content_type: the content type to add. If this is
unspecified o... | [
"Register",
"a",
"transcoder",
"for",
"a",
"specific",
"content",
"type",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L210-L243 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | set_default_content_type | def set_default_content_type(application, content_type, encoding=None):
"""
Store the default content type for an application.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to default to
:param str|None encoding: encoding to use when... | python | def set_default_content_type(application, content_type, encoding=None):
"""
Store the default content type for an application.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to default to
:param str|None encoding: encoding to use when... | [
"def",
"set_default_content_type",
"(",
"application",
",",
"content_type",
",",
"encoding",
"=",
"None",
")",
":",
"settings",
"=",
"get_settings",
"(",
"application",
",",
"force_instance",
"=",
"True",
")",
"settings",
".",
"default_content_type",
"=",
"content... | Store the default content type for an application.
:param tornado.web.Application application: the application to modify
:param str content_type: the content type to default to
:param str|None encoding: encoding to use when one is unspecified | [
"Store",
"the",
"default",
"content",
"type",
"for",
"an",
"application",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L246-L257 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | ContentMixin.get_response_content_type | def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | python | def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | [
"def",
"get_response_content_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_best_response_match",
"is",
"None",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"acceptable",
"=",
"headers",
".... | Figure out what content type will be used in the response. | [
"Figure",
"out",
"what",
"content",
"type",
"will",
"be",
"used",
"in",
"the",
"response",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L287-L307 | train |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | ContentMixin.send_response | def send_response(self, body, set_content_type=True):
"""
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
"""
s... | python | def send_response(self, body, set_content_type=True):
"""
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
"""
s... | [
"def",
"send_response",
"(",
"self",
",",
"body",
",",
"set_content_type",
"=",
"True",
")",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"handler",
"=",
"settings",
"[",
"self",
".",
"get_... | Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True` | [
"Serialize",
"and",
"send",
"body",
"in",
"the",
"response",
"."
] | c034e04f674201487a8d6ce9f8ce36f3f5de07d8 | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L344-L359 | train |
assamite/creamas | creamas/nx.py | connections_from_graph | def connections_from_graph(env, G, edge_data=False):
"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
... | python | def connections_from_graph(env, G, edge_data=False):
"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
... | [
"def",
"connections_from_graph",
"(",
"env",
",",
"G",
",",
"edge_data",
"=",
"False",
")",
":",
"if",
"not",
"issubclass",
"(",
"G",
".",
"__class__",
",",
"(",
"Graph",
",",
"DiGraph",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Graph structure must be ... | Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironment` or
:class:`... | [
"Create",
"connections",
"for",
"agents",
"in",
"the",
"given",
"environment",
"from",
"the",
"given",
"NetworkX",
"graph",
"structure",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L22-L74 | train |
assamite/creamas | creamas/nx.py | graph_from_connections | def graph_from_connections(env, directed=False):
"""Create NetworkX graph from agent connections in a given environment.
:param env:
Environment where the agents live. The environment must be derived from
:class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironme... | python | def graph_from_connections(env, directed=False):
"""Create NetworkX graph from agent connections in a given environment.
:param env:
Environment where the agents live. The environment must be derived from
:class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironme... | [
"def",
"graph_from_connections",
"(",
"env",
",",
"directed",
"=",
"False",
")",
":",
"G",
"=",
"DiGraph",
"(",
")",
"if",
"directed",
"else",
"Graph",
"(",
")",
"conn_list",
"=",
"env",
".",
"get_connections",
"(",
"data",
"=",
"True",
")",
"for",
"ag... | Create NetworkX graph from agent connections in a given environment.
:param env:
Environment where the agents live. The environment must be derived from
:class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironment` or
:class:`~creamas.ds.DistributedEnvironmen... | [
"Create",
"NetworkX",
"graph",
"from",
"agent",
"connections",
"in",
"a",
"given",
"environment",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L77-L109 | train |
assamite/creamas | creamas/nx.py | _addrs2nodes | def _addrs2nodes(addrs, G):
"""Map agent addresses to nodes in the graph.
"""
for i, n in enumerate(G.nodes()):
G.node[n]['addr'] = addrs[i] | python | def _addrs2nodes(addrs, G):
"""Map agent addresses to nodes in the graph.
"""
for i, n in enumerate(G.nodes()):
G.node[n]['addr'] = addrs[i] | [
"def",
"_addrs2nodes",
"(",
"addrs",
",",
"G",
")",
":",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"G",
".",
"nodes",
"(",
")",
")",
":",
"G",
".",
"node",
"[",
"n",
"]",
"[",
"'addr'",
"]",
"=",
"addrs",
"[",
"i",
"]"
] | Map agent addresses to nodes in the graph. | [
"Map",
"agent",
"addresses",
"to",
"nodes",
"in",
"the",
"graph",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L112-L116 | train |
assamite/creamas | creamas/nx.py | _edges2conns | def _edges2conns(G, edge_data=False):
"""Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.... | python | def _edges2conns(G, edge_data=False):
"""Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.... | [
"def",
"_edges2conns",
"(",
"G",
",",
"edge_data",
"=",
"False",
")",
":",
"cm",
"=",
"{",
"}",
"for",
"n",
"in",
"G",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"if",
"edge_data",
":",
"cm",
"[",
"n",
"[",
"1",
"]",
"[",
"'addr'",
"]"... | Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.
:returns:
A dictionary where ke... | [
"Create",
"a",
"mapping",
"from",
"graph",
"edges",
"to",
"agent",
"connections",
"to",
"be",
"created",
"."
] | 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L119-L143 | train |
adaptive-learning/proso-apps | proso_user/views.py | profile | def profile(request, status=200):
"""
Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (onl... | python | def profile(request, status=200):
"""
Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (onl... | [
"def",
"profile",
"(",
"request",
",",
"status",
"=",
"200",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"if",
"request",
".",
"GET",
".",
"get",
"(",
"\"username\"",
",",
"False",
")",
":",
"try",
":",
"user_profile",
"=",
"User",
... | Get the user's profile. If the user has no assigned profile, the HTTP 404
is returned. Make a POST request to modify the user's profile.
GET parameters:
html
turn on the HTML version of the API
username:
username of user (only for users with public profile)
stats... | [
"Get",
"the",
"user",
"s",
"profile",
".",
"If",
"the",
"user",
"has",
"no",
"assigned",
"profile",
"the",
"HTTP",
"404",
"is",
"returned",
".",
"Make",
"a",
"POST",
"request",
"to",
"modify",
"the",
"user",
"s",
"profile",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L22-L89 | train |
adaptive-learning/proso-apps | proso_user/views.py | signup | def signup(request):
"""
Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
... | python | def signup(request):
"""
Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
... | [
"def",
"signup",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'user_signup.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"signup",
".",
"__doc__",
")",
"elif",
"request",
".",
"... | Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
password_check:
... | [
"Create",
"a",
"new",
"user",
"with",
"the",
"given",
"credentials",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L243-L282 | train |
adaptive-learning/proso-apps | proso_user/views.py | session | def session(request):
"""
Get the information about the current session or modify the current session.
GET parameters:
html
turn on the HTML version of the API
POST parameters:
locale:
client's locale
time_zone:
client's time zone
display_width:
... | python | def session(request):
"""
Get the information about the current session or modify the current session.
GET parameters:
html
turn on the HTML version of the API
POST parameters:
locale:
client's locale
time_zone:
client's time zone
display_width:
... | [
"def",
"session",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
".",
"id",
"is",
"None",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'There is no user available to create a session.'",
")",
",",
"'error_type'",
... | Get the information about the current session or modify the current session.
GET parameters:
html
turn on the HTML version of the API
POST parameters:
locale:
client's locale
time_zone:
client's time zone
display_width:
width of the client's display
... | [
"Get",
"the",
"information",
"about",
"the",
"current",
"session",
"or",
"modify",
"the",
"current",
"session",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L288-L338 | train |
adaptive-learning/proso-apps | proso_user/views.py | initmobile_view | def initmobile_view(request):
"""
Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password
"""
if 'username' in request.GET and 'password' in request.GET:
... | python | def initmobile_view(request):
"""
Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password
"""
if 'username' in request.GET and 'password' in request.GET:
... | [
"def",
"initmobile_view",
"(",
"request",
")",
":",
"if",
"'username'",
"in",
"request",
".",
"GET",
"and",
"'password'",
"in",
"request",
".",
"GET",
":",
"username",
"=",
"request",
".",
"GET",
"[",
"'username'",
"]",
"password",
"=",
"request",
".",
"... | Create lazy user with a password. Used from the Android app.
Also returns csrf token.
GET parameters:
username:
user's name
password:
user's password | [
"Create",
"lazy",
"user",
"with",
"a",
"password",
".",
"Used",
"from",
"the",
"Android",
"app",
".",
"Also",
"returns",
"csrf",
"token",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views.py#L341-L370 | train |
truveris/py-mdstat | mdstat/disk.py | parse_device_disk | def parse_device_disk(token):
"""Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
So... | python | def parse_device_disk(token):
"""Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
So... | [
"def",
"parse_device_disk",
"(",
"token",
")",
":",
"name",
",",
"token",
"=",
"token",
".",
"split",
"(",
"\"[\"",
",",
"1",
")",
"number",
",",
"flags",
"=",
"token",
".",
"split",
"(",
"\"]\"",
",",
"1",
")",
"return",
"name",
",",
"{",
"\"numbe... | Parse a single disk from the header line.
Each disks has at least a device name and a unique number in its array,
after that could follow a list of special flags:
(W) write-mostly
(S) spare disk
(F) faulty disk
(R) replacement disk
Some are mutually exclusive (e.g. can't... | [
"Parse",
"a",
"single",
"disk",
"from",
"the",
"header",
"line",
"."
] | 881af99d1168694d2f38e606af377ef6cabe2297 | https://github.com/truveris/py-mdstat/blob/881af99d1168694d2f38e606af377ef6cabe2297/mdstat/disk.py#L6-L27 | train |
adaptive-learning/proso-apps | proso/list.py | group_by | def group_by(what, by):
"""
Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, ... | python | def group_by(what, by):
"""
Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, ... | [
"def",
"group_by",
"(",
"what",
",",
"by",
")",
":",
"return",
"proso",
".",
"dict",
".",
"group_keys_by_values",
"(",
"{",
"x",
":",
"by",
"(",
"x",
")",
"for",
"x",
"in",
"what",
"}",
")"
] | Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, 5, 7, 9], True: [0, 2, 4, 6, 8]}
... | [
"Take",
"a",
"list",
"and",
"apply",
"the",
"given",
"function",
"on",
"each",
"its",
"value",
"then",
"group",
"the",
"values",
"by",
"the",
"function",
"results",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/list.py#L25-L46 | train |
mardix/Mocha | mocha/cli.py | copy_resource_dir | def copy_resource_dir(src, dest):
"""
To copy package data directory to destination
"""
package_name = "mocha"
dest = (dest + "/" + os.path.basename(src)).rstrip("/")
if pkg_resources.resource_isdir(package_name, src):
if not os.path.isdir(dest):
os.makedirs(dest)
for... | python | def copy_resource_dir(src, dest):
"""
To copy package data directory to destination
"""
package_name = "mocha"
dest = (dest + "/" + os.path.basename(src)).rstrip("/")
if pkg_resources.resource_isdir(package_name, src):
if not os.path.isdir(dest):
os.makedirs(dest)
for... | [
"def",
"copy_resource_dir",
"(",
"src",
",",
"dest",
")",
":",
"package_name",
"=",
"\"mocha\"",
"dest",
"=",
"(",
"dest",
"+",
"\"/\"",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
".",
"rstrip",
"(",
"\"/\"",
")",
"if",
"pkg_resou... | To copy package data directory to destination | [
"To",
"copy",
"package",
"data",
"directory",
"to",
"destination"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L71-L84 | train |
mardix/Mocha | mocha/cli.py | init | def init():
""" Setup Mocha in the current directory """
mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))
header("Initializing Mocha ...")
if os.path.isfile(mochapyfile):
print("WARNING: It seems like Mocha is already setup!")
print("*" * 80)
else:
print("")
... | python | def init():
""" Setup Mocha in the current directory """
mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))
header("Initializing Mocha ...")
if os.path.isfile(mochapyfile):
print("WARNING: It seems like Mocha is already setup!")
print("*" * 80)
else:
print("")
... | [
"def",
"init",
"(",
")",
":",
"mochapyfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CWD",
",",
"\"brew.py\"",
")",
")",
"header",
"(",
"\"Initializing Mocha ...\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",... | Setup Mocha in the current directory | [
"Setup",
"Mocha",
"in",
"the",
"current",
"directory"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L154-L178 | train |
mardix/Mocha | mocha/cli.py | add_view | def add_view(name, no_template):
""" Create a new view and template page """
app_dest = APPLICATION_DIR
viewsrc = "%s/create-view/view.py" % SKELETON_DIR
tplsrc = "%s/create-view/template.jade" % SKELETON_DIR
viewdest_dir = os.path.join(app_dest, "views")
viewdest = os.path.join(viewdest_dir, "... | python | def add_view(name, no_template):
""" Create a new view and template page """
app_dest = APPLICATION_DIR
viewsrc = "%s/create-view/view.py" % SKELETON_DIR
tplsrc = "%s/create-view/template.jade" % SKELETON_DIR
viewdest_dir = os.path.join(app_dest, "views")
viewdest = os.path.join(viewdest_dir, "... | [
"def",
"add_view",
"(",
"name",
",",
"no_template",
")",
":",
"app_dest",
"=",
"APPLICATION_DIR",
"viewsrc",
"=",
"\"%s/create-view/view.py\"",
"%",
"SKELETON_DIR",
"tplsrc",
"=",
"\"%s/create-view/template.jade\"",
"%",
"SKELETON_DIR",
"viewdest_dir",
"=",
"os",
".",... | Create a new view and template page | [
"Create",
"a",
"new",
"view",
"and",
"template",
"page"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L184-L221 | train |
mardix/Mocha | mocha/cli.py | initdb | def initdb():
""" Sync database Create new tables etc... """
print("Syncing up database...")
cwd_to_sys_path()
if db and hasattr(db, "Model"):
db.create_all()
for m in db.Model.__subclasses__():
if hasattr(m, "initialize__"):
print("Sync up model: %s ..." % m... | python | def initdb():
""" Sync database Create new tables etc... """
print("Syncing up database...")
cwd_to_sys_path()
if db and hasattr(db, "Model"):
db.create_all()
for m in db.Model.__subclasses__():
if hasattr(m, "initialize__"):
print("Sync up model: %s ..." % m... | [
"def",
"initdb",
"(",
")",
":",
"print",
"(",
"\"Syncing up database...\"",
")",
"cwd_to_sys_path",
"(",
")",
"if",
"db",
"and",
"hasattr",
"(",
"db",
",",
"\"Model\"",
")",
":",
"db",
".",
"create_all",
"(",
")",
"for",
"m",
"in",
"db",
".",
"Model",
... | Sync database Create new tables etc... | [
"Sync",
"database",
"Create",
"new",
"tables",
"etc",
"..."
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L239-L251 | train |
mardix/Mocha | mocha/cli.py | _set_flask_alembic | def _set_flask_alembic():
from flask_alembic import Alembic
""" Add the SQLAlchemy object in the global extension """
application.app.extensions["sqlalchemy"] = type('', (), {"db": db})
alembic = Alembic()
alembic.init_app(application.app)
return alembic | python | def _set_flask_alembic():
from flask_alembic import Alembic
""" Add the SQLAlchemy object in the global extension """
application.app.extensions["sqlalchemy"] = type('', (), {"db": db})
alembic = Alembic()
alembic.init_app(application.app)
return alembic | [
"def",
"_set_flask_alembic",
"(",
")",
":",
"from",
"flask_alembic",
"import",
"Alembic",
"application",
".",
"app",
".",
"extensions",
"[",
"\"sqlalchemy\"",
"]",
"=",
"type",
"(",
"''",
",",
"(",
")",
",",
"{",
"\"db\"",
":",
"db",
"}",
")",
"alembic",... | Add the SQLAlchemy object in the global extension | [
"Add",
"the",
"SQLAlchemy",
"object",
"in",
"the",
"global",
"extension"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L254-L261 | train |
mardix/Mocha | mocha/cli.py | assets2s3 | def assets2s3():
""" Upload assets files to S3 """
import flask_s3
header("Assets2S3...")
print("")
print("Building assets files..." )
print("")
build_assets(application.app)
print("")
print("Uploading assets files to S3 ...")
flask_s3.create_all(application.app)
print("") | python | def assets2s3():
""" Upload assets files to S3 """
import flask_s3
header("Assets2S3...")
print("")
print("Building assets files..." )
print("")
build_assets(application.app)
print("")
print("Uploading assets files to S3 ...")
flask_s3.create_all(application.app)
print("") | [
"def",
"assets2s3",
"(",
")",
":",
"import",
"flask_s3",
"header",
"(",
"\"Assets2S3...\"",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"Building assets files...\"",
")",
"print",
"(",
"\"\"",
")",
"build_assets",
"(",
"application",
".",
"app",
")",
"pr... | Upload assets files to S3 | [
"Upload",
"assets",
"files",
"to",
"S3"
] | bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L285-L297 | train |
swharden/webinspect | webinspect/webinspect.py | launch | def launch(thing,title=False):
"""analyze a thing, create a nice HTML document, and launch it."""
html=htmlFromThing(thing,title=title)
if not html:
print("no HTML was generated.")
return
fname="%s/%s.html"%(tempfile.gettempdir(),str(time.time()))
with open(fname,'w') as f:
... | python | def launch(thing,title=False):
"""analyze a thing, create a nice HTML document, and launch it."""
html=htmlFromThing(thing,title=title)
if not html:
print("no HTML was generated.")
return
fname="%s/%s.html"%(tempfile.gettempdir(),str(time.time()))
with open(fname,'w') as f:
... | [
"def",
"launch",
"(",
"thing",
",",
"title",
"=",
"False",
")",
":",
"html",
"=",
"htmlFromThing",
"(",
"thing",
",",
"title",
"=",
"title",
")",
"if",
"not",
"html",
":",
"print",
"(",
"\"no HTML was generated.\"",
")",
"return",
"fname",
"=",
"\"%s/%s.... | analyze a thing, create a nice HTML document, and launch it. | [
"analyze",
"a",
"thing",
"create",
"a",
"nice",
"HTML",
"document",
"and",
"launch",
"it",
"."
] | 432674b61666d66e5be330b61f9fad0b46dac84e | https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L24-L33 | train |
swharden/webinspect | webinspect/webinspect.py | analyzeThing | def analyzeThing(originalThing2):
"""analyze an object and all its attirbutes. Returns a dictionary."""
originalThing = copy.copy(originalThing2)
things={}
for name in sorted(dir(originalThing)):
print("analyzing",name)
thing = copy.copy(originalThing)
if name in webinspec... | python | def analyzeThing(originalThing2):
"""analyze an object and all its attirbutes. Returns a dictionary."""
originalThing = copy.copy(originalThing2)
things={}
for name in sorted(dir(originalThing)):
print("analyzing",name)
thing = copy.copy(originalThing)
if name in webinspec... | [
"def",
"analyzeThing",
"(",
"originalThing2",
")",
":",
"originalThing",
"=",
"copy",
".",
"copy",
"(",
"originalThing2",
")",
"things",
"=",
"{",
"}",
"for",
"name",
"in",
"sorted",
"(",
"dir",
"(",
"originalThing",
")",
")",
":",
"print",
"(",
"\"analy... | analyze an object and all its attirbutes. Returns a dictionary. | [
"analyze",
"an",
"object",
"and",
"all",
"its",
"attirbutes",
".",
"Returns",
"a",
"dictionary",
"."
] | 432674b61666d66e5be330b61f9fad0b46dac84e | https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L66-L94 | train |
swharden/webinspect | webinspect/webinspect.py | websafe | def websafe(s):
"""return a string with HTML-safe text"""
s=s.replace("<","<").replace(">",">")
s=s.replace(r'\x',r' \x')
s=s.replace("\n","<br>")
return s | python | def websafe(s):
"""return a string with HTML-safe text"""
s=s.replace("<","<").replace(">",">")
s=s.replace(r'\x',r' \x')
s=s.replace("\n","<br>")
return s | [
"def",
"websafe",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"\"<\"",
",",
"\"<\"",
")",
".",
"replace",
"(",
"\">\"",
",",
"\">\"",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"r'\\x'",
",",
"r' \\x'",
")",
"s",
"=",
"s",
".",
... | return a string with HTML-safe text | [
"return",
"a",
"string",
"with",
"HTML",
"-",
"safe",
"text"
] | 432674b61666d66e5be330b61f9fad0b46dac84e | https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L96-L101 | train |
ronhanson/python-tbx | tbx/text.py | slugify | def slugify(text, delim='-'):
"""Generates an slightly worse ASCII-only slug."""
punctuation_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
result = []
for word in punctuation_re.split(text.lower()):
word = normalize_text(word)
if word:
result.append(word)
... | python | def slugify(text, delim='-'):
"""Generates an slightly worse ASCII-only slug."""
punctuation_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
result = []
for word in punctuation_re.split(text.lower()):
word = normalize_text(word)
if word:
result.append(word)
... | [
"def",
"slugify",
"(",
"text",
",",
"delim",
"=",
"'-'",
")",
":",
"punctuation_re",
"=",
"re",
".",
"compile",
"(",
"r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.:]+'",
")",
"result",
"=",
"[",
"]",
"for",
"word",
"in",
"punctuation_re",
".",
"split",
"(",
... | Generates an slightly worse ASCII-only slug. | [
"Generates",
"an",
"slightly",
"worse",
"ASCII",
"-",
"only",
"slug",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L48-L57 | train |
ronhanson/python-tbx | tbx/text.py | javascript_escape | def javascript_escape(s, quote_double_quotes=True):
"""
Escape characters for javascript strings.
"""
ustring_re = re.compile(u"([\u0080-\uffff])")
def fix(match):
return r"\u%04x" % ord(match.group(1))
if type(s) == str:
s = s.decode('utf-8')
elif type(s) != six.text_type:... | python | def javascript_escape(s, quote_double_quotes=True):
"""
Escape characters for javascript strings.
"""
ustring_re = re.compile(u"([\u0080-\uffff])")
def fix(match):
return r"\u%04x" % ord(match.group(1))
if type(s) == str:
s = s.decode('utf-8')
elif type(s) != six.text_type:... | [
"def",
"javascript_escape",
"(",
"s",
",",
"quote_double_quotes",
"=",
"True",
")",
":",
"ustring_re",
"=",
"re",
".",
"compile",
"(",
"u\"([\\u0080-\\uffff])\"",
")",
"def",
"fix",
"(",
"match",
")",
":",
"return",
"r\"\\u%04x\"",
"%",
"ord",
"(",
"match",
... | Escape characters for javascript strings. | [
"Escape",
"characters",
"for",
"javascript",
"strings",
"."
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L84-L104 | train |
ronhanson/python-tbx | tbx/text.py | seconds_to_hms_verbose | def seconds_to_hms_verbose(t):
"""
Converts seconds float to 'H hours 8 minutes, 30 seconds' format
"""
hours = int((t / 3600))
mins = int((t / 60) % 60)
secs = int(t % 60)
return ' '.join([
(hours + ' hour' + ('s' if hours > 1 else '')) if hours > 0 else '',
(mins + ' minute... | python | def seconds_to_hms_verbose(t):
"""
Converts seconds float to 'H hours 8 minutes, 30 seconds' format
"""
hours = int((t / 3600))
mins = int((t / 60) % 60)
secs = int(t % 60)
return ' '.join([
(hours + ' hour' + ('s' if hours > 1 else '')) if hours > 0 else '',
(mins + ' minute... | [
"def",
"seconds_to_hms_verbose",
"(",
"t",
")",
":",
"hours",
"=",
"int",
"(",
"(",
"t",
"/",
"3600",
")",
")",
"mins",
"=",
"int",
"(",
"(",
"t",
"/",
"60",
")",
"%",
"60",
")",
"secs",
"=",
"int",
"(",
"t",
"%",
"60",
")",
"return",
"' '",
... | Converts seconds float to 'H hours 8 minutes, 30 seconds' format | [
"Converts",
"seconds",
"float",
"to",
"H",
"hours",
"8",
"minutes",
"30",
"seconds",
"format"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L158-L169 | train |
ronhanson/python-tbx | tbx/text.py | pretty_render | def pretty_render(data, format='text', indent=0):
"""
Render a dict based on a format
"""
if format == 'json':
return render_json(data)
elif format == 'html':
return render_html(data)
elif format == 'xml':
return render_xml(data)
else:
return dict_to_plaintext... | python | def pretty_render(data, format='text', indent=0):
"""
Render a dict based on a format
"""
if format == 'json':
return render_json(data)
elif format == 'html':
return render_html(data)
elif format == 'xml':
return render_xml(data)
else:
return dict_to_plaintext... | [
"def",
"pretty_render",
"(",
"data",
",",
"format",
"=",
"'text'",
",",
"indent",
"=",
"0",
")",
":",
"if",
"format",
"==",
"'json'",
":",
"return",
"render_json",
"(",
"data",
")",
"elif",
"format",
"==",
"'html'",
":",
"return",
"render_html",
"(",
"... | Render a dict based on a format | [
"Render",
"a",
"dict",
"based",
"on",
"a",
"format"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L263-L274 | train |
ronhanson/python-tbx | tbx/text.py | dict_to_xml | def dict_to_xml(xml_dict):
"""
Converts a dictionary to an XML ElementTree Element
"""
import lxml.etree as etree
root_tag = list(xml_dict.keys())[0]
root = etree.Element(root_tag)
_dict_to_xml_recurse(root, xml_dict[root_tag])
return root | python | def dict_to_xml(xml_dict):
"""
Converts a dictionary to an XML ElementTree Element
"""
import lxml.etree as etree
root_tag = list(xml_dict.keys())[0]
root = etree.Element(root_tag)
_dict_to_xml_recurse(root, xml_dict[root_tag])
return root | [
"def",
"dict_to_xml",
"(",
"xml_dict",
")",
":",
"import",
"lxml",
".",
"etree",
"as",
"etree",
"root_tag",
"=",
"list",
"(",
"xml_dict",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"root",
"=",
"etree",
".",
"Element",
"(",
"root_tag",
")",
"_dict_to... | Converts a dictionary to an XML ElementTree Element | [
"Converts",
"a",
"dictionary",
"to",
"an",
"XML",
"ElementTree",
"Element"
] | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L310-L318 | train |
ronhanson/python-tbx | tbx/text.py | xml_get_tag | def xml_get_tag(xml, tag, parent_tag=None, multi_line=False):
"""
Returns the tag data for the first instance of the named tag, or for all instances if multi is true.
If a parent tag is specified, then that will be required before the tag.
"""
expr_str = '[<:]' + tag + '.*?>(?P<matched_text>.+?)<'
... | python | def xml_get_tag(xml, tag, parent_tag=None, multi_line=False):
"""
Returns the tag data for the first instance of the named tag, or for all instances if multi is true.
If a parent tag is specified, then that will be required before the tag.
"""
expr_str = '[<:]' + tag + '.*?>(?P<matched_text>.+?)<'
... | [
"def",
"xml_get_tag",
"(",
"xml",
",",
"tag",
",",
"parent_tag",
"=",
"None",
",",
"multi_line",
"=",
"False",
")",
":",
"expr_str",
"=",
"'[<:]'",
"+",
"tag",
"+",
"'.*?>(?P<matched_text>.+?)<'",
"if",
"parent_tag",
":",
"expr_str",
"=",
"'[<:]'",
"+",
"p... | Returns the tag data for the first instance of the named tag, or for all instances if multi is true.
If a parent tag is specified, then that will be required before the tag. | [
"Returns",
"the",
"tag",
"data",
"for",
"the",
"first",
"instance",
"of",
"the",
"named",
"tag",
"or",
"for",
"all",
"instances",
"if",
"multi",
"is",
"true",
".",
"If",
"a",
"parent",
"tag",
"is",
"specified",
"then",
"that",
"will",
"be",
"required",
... | 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L505-L520 | train |
clement-alexandre/TotemBionet | totembionet/src/resource_table/resource_table.py | ResourceTable._build_table | def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
""" Private method which build the table which map a State to the active multiplex. """
result: Dict[State, Tuple[Multiplex, ...]] = {}
for state in self.influence_graph.all_states():
result[state] = tuple(multiplex for mu... | python | def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
""" Private method which build the table which map a State to the active multiplex. """
result: Dict[State, Tuple[Multiplex, ...]] = {}
for state in self.influence_graph.all_states():
result[state] = tuple(multiplex for mu... | [
"def",
"_build_table",
"(",
"self",
")",
"->",
"Dict",
"[",
"State",
",",
"Tuple",
"[",
"Multiplex",
",",
"...",
"]",
"]",
":",
"result",
":",
"Dict",
"[",
"State",
",",
"Tuple",
"[",
"Multiplex",
",",
"...",
"]",
"]",
"=",
"{",
"}",
"for",
"stat... | Private method which build the table which map a State to the active multiplex. | [
"Private",
"method",
"which",
"build",
"the",
"table",
"which",
"map",
"a",
"State",
"to",
"the",
"active",
"multiplex",
"."
] | f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table.py#L19-L25 | train |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | _to_base36 | def _to_base36(number):
"""
Convert a positive integer to a base36 string.
Taken from Stack Overflow and modified.
"""
if number < 0:
raise ValueError("Cannot encode negative numbers")
chars = ""
while number != 0:
number, i = divmod(number, 36) # 36-character alphabet
... | python | def _to_base36(number):
"""
Convert a positive integer to a base36 string.
Taken from Stack Overflow and modified.
"""
if number < 0:
raise ValueError("Cannot encode negative numbers")
chars = ""
while number != 0:
number, i = divmod(number, 36) # 36-character alphabet
... | [
"def",
"_to_base36",
"(",
"number",
")",
":",
"if",
"number",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot encode negative numbers\"",
")",
"chars",
"=",
"\"\"",
"while",
"number",
"!=",
"0",
":",
"number",
",",
"i",
"=",
"divmod",
"(",
"number",
... | Convert a positive integer to a base36 string.
Taken from Stack Overflow and modified. | [
"Convert",
"a",
"positive",
"integer",
"to",
"a",
"base36",
"string",
"."
] | 704d3f887cc8963769ffbb116eb7e6909deeaecd | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L20-L34 | train |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | _pad | def _pad(string, size):
"""
'Pad' a string with leading zeroes to fit the given size, truncating
if necessary.
"""
strlen = len(string)
if strlen == size:
return string
if strlen < size:
return _padding[0:size-strlen] + string
return string[-size:] | python | def _pad(string, size):
"""
'Pad' a string with leading zeroes to fit the given size, truncating
if necessary.
"""
strlen = len(string)
if strlen == size:
return string
if strlen < size:
return _padding[0:size-strlen] + string
return string[-size:] | [
"def",
"_pad",
"(",
"string",
",",
"size",
")",
":",
"strlen",
"=",
"len",
"(",
"string",
")",
"if",
"strlen",
"==",
"size",
":",
"return",
"string",
"if",
"strlen",
"<",
"size",
":",
"return",
"_padding",
"[",
"0",
":",
"size",
"-",
"strlen",
"]",... | 'Pad' a string with leading zeroes to fit the given size, truncating
if necessary. | [
"Pad",
"a",
"string",
"with",
"leading",
"zeroes",
"to",
"fit",
"the",
"given",
"size",
"truncating",
"if",
"necessary",
"."
] | 704d3f887cc8963769ffbb116eb7e6909deeaecd | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L38-L48 | train |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | _random_block | def _random_block():
"""
Generate a random string of `BLOCK_SIZE` length.
"""
# TODO: Use a better RNG than random.randint
random_number = random.randint(0, DISCRETE_VALUES)
random_string = _to_base36(random_number)
return _pad(random_string, BLOCK_SIZE) | python | def _random_block():
"""
Generate a random string of `BLOCK_SIZE` length.
"""
# TODO: Use a better RNG than random.randint
random_number = random.randint(0, DISCRETE_VALUES)
random_string = _to_base36(random_number)
return _pad(random_string, BLOCK_SIZE) | [
"def",
"_random_block",
"(",
")",
":",
"random_number",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"DISCRETE_VALUES",
")",
"random_string",
"=",
"_to_base36",
"(",
"random_number",
")",
"return",
"_pad",
"(",
"random_string",
",",
"BLOCK_SIZE",
")"
] | Generate a random string of `BLOCK_SIZE` length. | [
"Generate",
"a",
"random",
"string",
"of",
"BLOCK_SIZE",
"length",
"."
] | 704d3f887cc8963769ffbb116eb7e6909deeaecd | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L51-L58 | train |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | get_process_fingerprint | def get_process_fingerprint():
"""
Extract a unique fingerprint for the current process, using a
combination of the process PID and the system's hostname.
"""
pid = os.getpid()
hostname = socket.gethostname()
padded_pid = _pad(_to_base36(pid), 2)
hostname_hash = sum([ord(x) for x in host... | python | def get_process_fingerprint():
"""
Extract a unique fingerprint for the current process, using a
combination of the process PID and the system's hostname.
"""
pid = os.getpid()
hostname = socket.gethostname()
padded_pid = _pad(_to_base36(pid), 2)
hostname_hash = sum([ord(x) for x in host... | [
"def",
"get_process_fingerprint",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"hostname",
"=",
"socket",
".",
"gethostname",
"(",
")",
"padded_pid",
"=",
"_pad",
"(",
"_to_base36",
"(",
"pid",
")",
",",
"2",
")",
"hostname_hash",
"=",
"su... | Extract a unique fingerprint for the current process, using a
combination of the process PID and the system's hostname. | [
"Extract",
"a",
"unique",
"fingerprint",
"for",
"the",
"current",
"process",
"using",
"a",
"combination",
"of",
"the",
"process",
"PID",
"and",
"the",
"system",
"s",
"hostname",
"."
] | 704d3f887cc8963769ffbb116eb7e6909deeaecd | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L64-L74 | train |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | CuidGenerator.counter | def counter(self):
"""
Rolling counter that ensures same-machine and same-time
cuids don't collide.
"""
self._counter += 1
if self._counter >= DISCRETE_VALUES:
self._counter = 0
return self._counter | python | def counter(self):
"""
Rolling counter that ensures same-machine and same-time
cuids don't collide.
"""
self._counter += 1
if self._counter >= DISCRETE_VALUES:
self._counter = 0
return self._counter | [
"def",
"counter",
"(",
"self",
")",
":",
"self",
".",
"_counter",
"+=",
"1",
"if",
"self",
".",
"_counter",
">=",
"DISCRETE_VALUES",
":",
"self",
".",
"_counter",
"=",
"0",
"return",
"self",
".",
"_counter"
] | Rolling counter that ensures same-machine and same-time
cuids don't collide. | [
"Rolling",
"counter",
"that",
"ensures",
"same",
"-",
"machine",
"and",
"same",
"-",
"time",
"cuids",
"don",
"t",
"collide",
"."
] | 704d3f887cc8963769ffbb116eb7e6909deeaecd | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L103-L111 | train |
abnerjacobsen/tinydb-jsonorm | src/tinydb_jsonorm/cuid.py | CuidGenerator.cuid | def cuid(self):
"""
Generate a full-length cuid as a string.
"""
# start with a hardcoded lowercase c
identifier = "c"
# add a timestamp in milliseconds since the epoch, in base 36
millis = int(time.time() * 1000)
identifier += _to_base36(millis)
#... | python | def cuid(self):
"""
Generate a full-length cuid as a string.
"""
# start with a hardcoded lowercase c
identifier = "c"
# add a timestamp in milliseconds since the epoch, in base 36
millis = int(time.time() * 1000)
identifier += _to_base36(millis)
#... | [
"def",
"cuid",
"(",
"self",
")",
":",
"identifier",
"=",
"\"c\"",
"millis",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1000",
")",
"identifier",
"+=",
"_to_base36",
"(",
"millis",
")",
"count",
"=",
"_pad",
"(",
"_to_base36",
"(",
"self",
... | Generate a full-length cuid as a string. | [
"Generate",
"a",
"full",
"-",
"length",
"cuid",
"as",
"a",
"string",
"."
] | 704d3f887cc8963769ffbb116eb7e6909deeaecd | https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L113-L132 | train |
PBR/MQ2 | MQ2/plugins/xls_plugin.py | read_excel_file | def read_excel_file(inputfile, sheet_name):
""" Return a matrix containing all the information present in the
excel sheet of the specified excel document.
:arg inputfile: excel document to read
:arg sheetname: the name of the excel sheet to return
"""
workbook = xlrd.open_workbook(inputfile)
... | python | def read_excel_file(inputfile, sheet_name):
""" Return a matrix containing all the information present in the
excel sheet of the specified excel document.
:arg inputfile: excel document to read
:arg sheetname: the name of the excel sheet to return
"""
workbook = xlrd.open_workbook(inputfile)
... | [
"def",
"read_excel_file",
"(",
"inputfile",
",",
"sheet_name",
")",
":",
"workbook",
"=",
"xlrd",
".",
"open_workbook",
"(",
"inputfile",
")",
"output",
"=",
"[",
"]",
"found",
"=",
"False",
"for",
"sheet",
"in",
"workbook",
".",
"sheets",
"(",
")",
":",... | Return a matrix containing all the information present in the
excel sheet of the specified excel document.
:arg inputfile: excel document to read
:arg sheetname: the name of the excel sheet to return | [
"Return",
"a",
"matrix",
"containing",
"all",
"the",
"information",
"present",
"in",
"the",
"excel",
"sheet",
"of",
"the",
"specified",
"excel",
"document",
"."
] | 6d84dea47e6751333004743f588f03158e35c28d | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L66-L87 | train |
PBR/MQ2 | MQ2/plugins/xls_plugin.py | XslPlugin.get_session_identifiers | def get_session_identifiers(cls, folder=None, inputfile=None):
""" Retrieve the list of session identifiers contained in the
data on the folder or the inputfile.
For this plugin, it returns the list of excel sheet available.
:kwarg folder: the path to the folder containing the files to
... | python | def get_session_identifiers(cls, folder=None, inputfile=None):
""" Retrieve the list of session identifiers contained in the
data on the folder or the inputfile.
For this plugin, it returns the list of excel sheet available.
:kwarg folder: the path to the folder containing the files to
... | [
"def",
"get_session_identifiers",
"(",
"cls",
",",
"folder",
"=",
"None",
",",
"inputfile",
"=",
"None",
")",
":",
"sessions",
"=",
"[",
"]",
"if",
"inputfile",
"and",
"folder",
":",
"raise",
"MQ2Exception",
"(",
"'You should specify either a folder or a file'",
... | Retrieve the list of session identifiers contained in the
data on the folder or the inputfile.
For this plugin, it returns the list of excel sheet available.
:kwarg folder: the path to the folder containing the files to
check. This folder may contain sub-folders.
:kwarg inpu... | [
"Retrieve",
"the",
"list",
"of",
"session",
"identifiers",
"contained",
"in",
"the",
"data",
"on",
"the",
"folder",
"or",
"the",
"inputfile",
".",
"For",
"this",
"plugin",
"it",
"returns",
"the",
"list",
"of",
"excel",
"sheet",
"available",
"."
] | 6d84dea47e6751333004743f588f03158e35c28d | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L205-L240 | train |
cozy/python_cozy_management | cozy_management/helpers.py | file_rights | def file_rights(filepath, mode=None, uid=None, gid=None):
'''
Change file rights
'''
file_handle = os.open(filepath, os.O_RDONLY)
if mode:
os.fchmod(file_handle, mode)
if uid:
if not gid:
gid = 0
os.fchown(file_handle, uid, gid)
os.close(file_handle) | python | def file_rights(filepath, mode=None, uid=None, gid=None):
'''
Change file rights
'''
file_handle = os.open(filepath, os.O_RDONLY)
if mode:
os.fchmod(file_handle, mode)
if uid:
if not gid:
gid = 0
os.fchown(file_handle, uid, gid)
os.close(file_handle) | [
"def",
"file_rights",
"(",
"filepath",
",",
"mode",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
")",
":",
"file_handle",
"=",
"os",
".",
"open",
"(",
"filepath",
",",
"os",
".",
"O_RDONLY",
")",
"if",
"mode",
":",
"os",
".",
"f... | Change file rights | [
"Change",
"file",
"rights"
] | 820cea58458ae3e067fa8cc2da38edbda4681dac | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/helpers.py#L16-L27 | train |
DavidDoukhan/py_sonicvisualiser | py_sonicvisualiser/SVEnv.py | SVEnv.init_from_wave_file | def init_from_wave_file(wavpath):
"""Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile
"""
try:
samplerate, data = SW.read(... | python | def init_from_wave_file(wavpath):
"""Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile
"""
try:
samplerate, data = SW.read(... | [
"def",
"init_from_wave_file",
"(",
"wavpath",
")",
":",
"try",
":",
"samplerate",
",",
"data",
"=",
"SW",
".",
"read",
"(",
"wavpath",
")",
"nframes",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"except",
":",
"try",
":",
"w",
"=",
"wave",
".",
"open... | Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile | [
"Init",
"a",
"sonic",
"visualiser",
"environment",
"structure",
"based",
"the",
"analysis",
"of",
"the",
"main",
"audio",
"file",
".",
"The",
"audio",
"file",
"have",
"to",
"be",
"encoded",
"in",
"wave"
] | ebe83bd7dffb0275393255dcbcc6671cf0ade4a5 | https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L79-L100 | train |
DavidDoukhan/py_sonicvisualiser | py_sonicvisualiser/SVEnv.py | SVEnv.add_continuous_annotations | def add_continuous_annotations(self, x, y, colourName='Purple', colour='#c832ff', name='', view=None, vscale=None, presentationName=None):
"""
add a continous annotation layer
Args:
x (float iterable): temporal indices of the dataset
y (float iterable): values of the dataset... | python | def add_continuous_annotations(self, x, y, colourName='Purple', colour='#c832ff', name='', view=None, vscale=None, presentationName=None):
"""
add a continous annotation layer
Args:
x (float iterable): temporal indices of the dataset
y (float iterable): values of the dataset... | [
"def",
"add_continuous_annotations",
"(",
"self",
",",
"x",
",",
"y",
",",
"colourName",
"=",
"'Purple'",
",",
"colour",
"=",
"'#c832ff'",
",",
"name",
"=",
"''",
",",
"view",
"=",
"None",
",",
"vscale",
"=",
"None",
",",
"presentationName",
"=",
"None",... | add a continous annotation layer
Args:
x (float iterable): temporal indices of the dataset
y (float iterable): values of the dataset
Kwargs:
view (<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created
Return... | [
"add",
"a",
"continous",
"annotation",
"layer"
] | ebe83bd7dffb0275393255dcbcc6671cf0ade4a5 | https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L145-L212 | train |
DavidDoukhan/py_sonicvisualiser | py_sonicvisualiser/SVEnv.py | SVEnv.add_interval_annotations | def add_interval_annotations(self, temp_idx, durations, labels, values=None, colourName='Purple', colour='#c832ff', name='', view=None, presentationName = None):
"""
add a labelled interval annotation layer
Args:
temp_idx (float iterable): The temporal indices of invervals
d... | python | def add_interval_annotations(self, temp_idx, durations, labels, values=None, colourName='Purple', colour='#c832ff', name='', view=None, presentationName = None):
"""
add a labelled interval annotation layer
Args:
temp_idx (float iterable): The temporal indices of invervals
d... | [
"def",
"add_interval_annotations",
"(",
"self",
",",
"temp_idx",
",",
"durations",
",",
"labels",
",",
"values",
"=",
"None",
",",
"colourName",
"=",
"'Purple'",
",",
"colour",
"=",
"'#c832ff'",
",",
"name",
"=",
"''",
",",
"view",
"=",
"None",
",",
"pre... | add a labelled interval annotation layer
Args:
temp_idx (float iterable): The temporal indices of invervals
durations (float iterable): intervals durations
labels (string iterable): interval labels
values (int iterable): interval numeric values, if set to None, values ar... | [
"add",
"a",
"labelled",
"interval",
"annotation",
"layer"
] | ebe83bd7dffb0275393255dcbcc6671cf0ade4a5 | https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L215-L277 | train |
DsixTools/python-smeftrunner | smeftrunner/classes.py | SMEFT.load_initial | def load_initial(self, streams):
"""Load the initial values for parameters and Wilson coefficients from
one or several files.
`streams` should be a tuple of file-like objects strings."""
d = {}
for stream in streams:
s = io.load(stream)
if 'BLOCK' not in ... | python | def load_initial(self, streams):
"""Load the initial values for parameters and Wilson coefficients from
one or several files.
`streams` should be a tuple of file-like objects strings."""
d = {}
for stream in streams:
s = io.load(stream)
if 'BLOCK' not in ... | [
"def",
"load_initial",
"(",
"self",
",",
"streams",
")",
":",
"d",
"=",
"{",
"}",
"for",
"stream",
"in",
"streams",
":",
"s",
"=",
"io",
".",
"load",
"(",
"stream",
")",
"if",
"'BLOCK'",
"not",
"in",
"s",
":",
"raise",
"ValueError",
"(",
"\"No BLOC... | Load the initial values for parameters and Wilson coefficients from
one or several files.
`streams` should be a tuple of file-like objects strings. | [
"Load",
"the",
"initial",
"values",
"for",
"parameters",
"and",
"Wilson",
"coefficients",
"from",
"one",
"or",
"several",
"files",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L31-L47 | train |
DsixTools/python-smeftrunner | smeftrunner/classes.py | SMEFT.load_wcxf | def load_wcxf(self, stream, get_smpar=True):
"""Load the initial values for Wilson coefficients from
a file-like object or a string in WCxf format.
Note that Standard Model parameters have to be provided separately
and are assumed to be in the weak basis used for the Warsaw basis as
... | python | def load_wcxf(self, stream, get_smpar=True):
"""Load the initial values for Wilson coefficients from
a file-like object or a string in WCxf format.
Note that Standard Model parameters have to be provided separately
and are assumed to be in the weak basis used for the Warsaw basis as
... | [
"def",
"load_wcxf",
"(",
"self",
",",
"stream",
",",
"get_smpar",
"=",
"True",
")",
":",
"import",
"wcxf",
"wc",
"=",
"wcxf",
".",
"WC",
".",
"load",
"(",
"stream",
")",
"self",
".",
"set_initial_wcxf",
"(",
"wc",
",",
"get_smpar",
"=",
"get_smpar",
... | Load the initial values for Wilson coefficients from
a file-like object or a string in WCxf format.
Note that Standard Model parameters have to be provided separately
and are assumed to be in the weak basis used for the Warsaw basis as
defined in WCxf, i.e. in the basis where the down-t... | [
"Load",
"the",
"initial",
"values",
"for",
"Wilson",
"coefficients",
"from",
"a",
"file",
"-",
"like",
"object",
"or",
"a",
"string",
"in",
"WCxf",
"format",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L105-L115 | train |
DsixTools/python-smeftrunner | smeftrunner/classes.py | SMEFT.dump_wcxf | def dump_wcxf(self, C_out, scale_out, fmt='yaml', stream=None, **kwargs):
"""Return a string representation of the Wilson coefficients `C_out`
in WCxf format. If `stream` is specified, export it to a file.
`fmt` defaults to `yaml`, but can also be `json`.
Note that the Wilson coefficien... | python | def dump_wcxf(self, C_out, scale_out, fmt='yaml', stream=None, **kwargs):
"""Return a string representation of the Wilson coefficients `C_out`
in WCxf format. If `stream` is specified, export it to a file.
`fmt` defaults to `yaml`, but can also be `json`.
Note that the Wilson coefficien... | [
"def",
"dump_wcxf",
"(",
"self",
",",
"C_out",
",",
"scale_out",
",",
"fmt",
"=",
"'yaml'",
",",
"stream",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"wc",
"=",
"self",
".",
"get_wcxf",
"(",
"C_out",
",",
"scale_out",
")",
"return",
"wc",
".",
"du... | Return a string representation of the Wilson coefficients `C_out`
in WCxf format. If `stream` is specified, export it to a file.
`fmt` defaults to `yaml`, but can also be `json`.
Note that the Wilson coefficients are rotated into the Warsaw basis
as defined in WCxf, i.e. to the basis wh... | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"Wilson",
"coefficients",
"C_out",
"in",
"WCxf",
"format",
".",
"If",
"stream",
"is",
"specified",
"export",
"it",
"to",
"a",
"file",
".",
"fmt",
"defaults",
"to",
"yaml",
"but",
"can",
"also",
"be",
... | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L158-L167 | train |
DsixTools/python-smeftrunner | smeftrunner/classes.py | SMEFT.rgevolve_leadinglog | def rgevolve_leadinglog(self, scale_out):
"""Compute the leading logarithmix approximation to the solution
of the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients.
Much faster but less precise that `rgevolve`.
"""
... | python | def rgevolve_leadinglog(self, scale_out):
"""Compute the leading logarithmix approximation to the solution
of the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients.
Much faster but less precise that `rgevolve`.
"""
... | [
"def",
"rgevolve_leadinglog",
"(",
"self",
",",
"scale_out",
")",
":",
"self",
".",
"_check_initial",
"(",
")",
"return",
"rge",
".",
"smeft_evolve_leadinglog",
"(",
"C_in",
"=",
"self",
".",
"C_in",
",",
"scale_high",
"=",
"self",
".",
"scale_high",
",",
... | Compute the leading logarithmix approximation to the solution
of the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients.
Much faster but less precise that `rgevolve`. | [
"Compute",
"the",
"leading",
"logarithmix",
"approximation",
"to",
"the",
"solution",
"of",
"the",
"SMEFT",
"RGEs",
"from",
"the",
"initial",
"scale",
"to",
"scale_out",
".",
"Returns",
"a",
"dictionary",
"with",
"parameters",
"and",
"Wilson",
"coefficients",
".... | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L181-L191 | train |
DsixTools/python-smeftrunner | smeftrunner/classes.py | SMEFT._check_initial | def _check_initial(self):
"""Check if initial values and scale as well as the new physics scale
have been set."""
if self.C_in is None:
raise Exception("You have to specify the initial conditions first.")
if self.scale_in is None:
raise Exception("You have to spec... | python | def _check_initial(self):
"""Check if initial values and scale as well as the new physics scale
have been set."""
if self.C_in is None:
raise Exception("You have to specify the initial conditions first.")
if self.scale_in is None:
raise Exception("You have to spec... | [
"def",
"_check_initial",
"(",
"self",
")",
":",
"if",
"self",
".",
"C_in",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"You have to specify the initial conditions first.\"",
")",
"if",
"self",
".",
"scale_in",
"is",
"None",
":",
"raise",
"Exception",
"(",
... | Check if initial values and scale as well as the new physics scale
have been set. | [
"Check",
"if",
"initial",
"values",
"and",
"scale",
"as",
"well",
"as",
"the",
"new",
"physics",
"scale",
"have",
"been",
"set",
"."
] | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L193-L201 | train |
DsixTools/python-smeftrunner | smeftrunner/classes.py | SMEFT.rotate_defaultbasis | def rotate_defaultbasis(self, C):
"""Rotate all parameters to the basis where the running down-type quark
and charged lepton mass matrices are diagonal and where the running
up-type quark mass matrix has the form V.S, with V unitary and S real
diagonal, and where the CKM and PMNS matrice... | python | def rotate_defaultbasis(self, C):
"""Rotate all parameters to the basis where the running down-type quark
and charged lepton mass matrices are diagonal and where the running
up-type quark mass matrix has the form V.S, with V unitary and S real
diagonal, and where the CKM and PMNS matrice... | [
"def",
"rotate_defaultbasis",
"(",
"self",
",",
"C",
")",
":",
"v",
"=",
"sqrt",
"(",
"2",
"*",
"C",
"[",
"'m2'",
"]",
".",
"real",
"/",
"C",
"[",
"'Lambda'",
"]",
".",
"real",
")",
"Mep",
"=",
"v",
"/",
"sqrt",
"(",
"2",
")",
"*",
"(",
"C"... | Rotate all parameters to the basis where the running down-type quark
and charged lepton mass matrices are diagonal and where the running
up-type quark mass matrix has the form V.S, with V unitary and S real
diagonal, and where the CKM and PMNS matrices have the standard
phase convention. | [
"Rotate",
"all",
"parameters",
"to",
"the",
"basis",
"where",
"the",
"running",
"down",
"-",
"type",
"quark",
"and",
"charged",
"lepton",
"mass",
"matrices",
"are",
"diagonal",
"and",
"where",
"the",
"running",
"up",
"-",
"type",
"quark",
"mass",
"matrix",
... | 4c9130e53ad4f7bbb526657a82150ca9d57c4b37 | https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L203-L220 | train |
TheGhouls/oct | oct/results/models.py | set_database | def set_database(db_url, proxy, config):
"""Initialize the peewee database with the given configuration
If the given db_url is a regular file, it will be used as sqlite database
:param str db_url: the connection string for database or path if sqlite file
:param peewee.Proxy proxy: the peewee proxy to ... | python | def set_database(db_url, proxy, config):
"""Initialize the peewee database with the given configuration
If the given db_url is a regular file, it will be used as sqlite database
:param str db_url: the connection string for database or path if sqlite file
:param peewee.Proxy proxy: the peewee proxy to ... | [
"def",
"set_database",
"(",
"db_url",
",",
"proxy",
",",
"config",
")",
":",
"db_config",
"=",
"config",
".",
"get",
"(",
"'results_database'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'params'",
",",
"{",
"}",
")",
"if",
"'testing'",
"in",
"config",
"a... | Initialize the peewee database with the given configuration
If the given db_url is a regular file, it will be used as sqlite database
:param str db_url: the connection string for database or path if sqlite file
:param peewee.Proxy proxy: the peewee proxy to initialise
:param dict config: the configura... | [
"Initialize",
"the",
"peewee",
"database",
"with",
"the",
"given",
"configuration"
] | 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/models.py#L65-L83 | train |
Kortemme-Lab/klab | klab/cluster/simple_qtop.py | sh | def sh(cmd):
"""
Run the given command in a shell.
The command should be a single string containing a shell command. If the
command contains the names of any local variables enclosed in braces, the
actual values of the named variables will be filled in. (Note that this
works on variables defi... | python | def sh(cmd):
"""
Run the given command in a shell.
The command should be a single string containing a shell command. If the
command contains the names of any local variables enclosed in braces, the
actual values of the named variables will be filled in. (Note that this
works on variables defi... | [
"def",
"sh",
"(",
"cmd",
")",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"try",
":",
"locals",
"=",
"frame",
".",
"f_back",
".",
"f_locals",
"finally",
":",
"del",
"frame",
"from",
"subprocess",
"import",
"Popen",
... | Run the given command in a shell.
The command should be a single string containing a shell command. If the
command contains the names of any local variables enclosed in braces, the
actual values of the named variables will be filled in. (Note that this
works on variables defined in the calling scope,... | [
"Run",
"the",
"given",
"command",
"in",
"a",
"shell",
"."
] | 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cluster/simple_qtop.py#L24-L54 | train |
uw-it-aca/uw-restclients-sws | uw_sws/curriculum.py | get_curricula_by_department | def get_curricula_by_department(
department, future_terms=0, view_unpublished=False):
"""
Returns a list of restclients.Curriculum models, for the passed
Department model.
"""
if not isinstance(future_terms, int):
raise ValueError(future_terms)
if future_terms < 0 or future_term... | python | def get_curricula_by_department(
department, future_terms=0, view_unpublished=False):
"""
Returns a list of restclients.Curriculum models, for the passed
Department model.
"""
if not isinstance(future_terms, int):
raise ValueError(future_terms)
if future_terms < 0 or future_term... | [
"def",
"get_curricula_by_department",
"(",
"department",
",",
"future_terms",
"=",
"0",
",",
"view_unpublished",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"future_terms",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"future_terms",
")",
"if"... | Returns a list of restclients.Curriculum models, for the passed
Department model. | [
"Returns",
"a",
"list",
"of",
"restclients",
".",
"Curriculum",
"models",
"for",
"the",
"passed",
"Department",
"model",
"."
] | 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/curriculum.py#L14-L33 | train |
uw-it-aca/uw-restclients-sws | uw_sws/curriculum.py | get_curricula_by_term | def get_curricula_by_term(term, view_unpublished=False):
"""
Returns a list of restclients.Curriculum models, for the passed
Term model.
"""
view_unpublished = "true" if view_unpublished else "false"
url = "{}?{}".format(
curriculum_search_url_prefix,
urlencode([
... | python | def get_curricula_by_term(term, view_unpublished=False):
"""
Returns a list of restclients.Curriculum models, for the passed
Term model.
"""
view_unpublished = "true" if view_unpublished else "false"
url = "{}?{}".format(
curriculum_search_url_prefix,
urlencode([
... | [
"def",
"get_curricula_by_term",
"(",
"term",
",",
"view_unpublished",
"=",
"False",
")",
":",
"view_unpublished",
"=",
"\"true\"",
"if",
"view_unpublished",
"else",
"\"false\"",
"url",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"curriculum_search_url_prefix",
",",
"urlen... | Returns a list of restclients.Curriculum models, for the passed
Term model. | [
"Returns",
"a",
"list",
"of",
"restclients",
".",
"Curriculum",
"models",
"for",
"the",
"passed",
"Term",
"model",
"."
] | 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/curriculum.py#L36-L48 | train |
AtmaHou/atma | bleu.py | BP | def BP(candidate, references):
"""
calculate brevity penalty
"""
c = len(candidate)
ref_lens = (len(reference) for reference in references)
r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len))
if c > r:
return 1
else:
return math.exp(1 - r / c) | python | def BP(candidate, references):
"""
calculate brevity penalty
"""
c = len(candidate)
ref_lens = (len(reference) for reference in references)
r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len))
if c > r:
return 1
else:
return math.exp(1 - r / c) | [
"def",
"BP",
"(",
"candidate",
",",
"references",
")",
":",
"c",
"=",
"len",
"(",
"candidate",
")",
"ref_lens",
"=",
"(",
"len",
"(",
"reference",
")",
"for",
"reference",
"in",
"references",
")",
"r",
"=",
"min",
"(",
"ref_lens",
",",
"key",
"=",
... | calculate brevity penalty | [
"calculate",
"brevity",
"penalty"
] | 41cd8ea9443a9c3b2dd71432f46f44a0f83093c7 | https://github.com/AtmaHou/atma/blob/41cd8ea9443a9c3b2dd71432f46f44a0f83093c7/bleu.py#L10-L21 | train |
AtmaHou/atma | bleu.py | MP | def MP(candidate, references, n):
"""
calculate modified precision
"""
counts = Counter(ngrams(candidate, n))
if not counts:
return 0
max_counts = {}
for reference in references:
reference_counts = Counter(ngrams(reference, n))
for ngram in counts:
max_co... | python | def MP(candidate, references, n):
"""
calculate modified precision
"""
counts = Counter(ngrams(candidate, n))
if not counts:
return 0
max_counts = {}
for reference in references:
reference_counts = Counter(ngrams(reference, n))
for ngram in counts:
max_co... | [
"def",
"MP",
"(",
"candidate",
",",
"references",
",",
"n",
")",
":",
"counts",
"=",
"Counter",
"(",
"ngrams",
"(",
"candidate",
",",
"n",
")",
")",
"if",
"not",
"counts",
":",
"return",
"0",
"max_counts",
"=",
"{",
"}",
"for",
"reference",
"in",
"... | calculate modified precision | [
"calculate",
"modified",
"precision"
] | 41cd8ea9443a9c3b2dd71432f46f44a0f83093c7 | https://github.com/AtmaHou/atma/blob/41cd8ea9443a9c3b2dd71432f46f44a0f83093c7/bleu.py#L24-L40 | train |
trendels/rhino | rhino/mapper.py | template2regex | def template2regex(template, ranges=None):
"""Convert a URL template to a regular expression.
Converts a template, such as /{name}/ to a regular expression, e.g.
/(?P<name>[^/]+)/ and a list of the named parameters found in the template
(e.g. ['name']). Ranges are given after a colon in a template name... | python | def template2regex(template, ranges=None):
"""Convert a URL template to a regular expression.
Converts a template, such as /{name}/ to a regular expression, e.g.
/(?P<name>[^/]+)/ and a list of the named parameters found in the template
(e.g. ['name']). Ranges are given after a colon in a template name... | [
"def",
"template2regex",
"(",
"template",
",",
"ranges",
"=",
"None",
")",
":",
"if",
"len",
"(",
"template",
")",
"and",
"-",
"1",
"<",
"template",
".",
"find",
"(",
"'|'",
")",
"<",
"len",
"(",
"template",
")",
"-",
"1",
":",
"raise",
"InvalidTem... | Convert a URL template to a regular expression.
Converts a template, such as /{name}/ to a regular expression, e.g.
/(?P<name>[^/]+)/ and a list of the named parameters found in the template
(e.g. ['name']). Ranges are given after a colon in a template name to
indicate a restriction on the characters t... | [
"Convert",
"a",
"URL",
"template",
"to",
"a",
"regular",
"expression",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L119-L199 | train |
trendels/rhino | rhino/mapper.py | Context.add_callback | def add_callback(self, phase, fn):
"""Adds a callback to the context.
The `phase` determines when and if the callback is executed, and which
positional arguments are passed in:
'enter'
: Called from `rhino.Resource`, after a handler for the current
request has bee... | python | def add_callback(self, phase, fn):
"""Adds a callback to the context.
The `phase` determines when and if the callback is executed, and which
positional arguments are passed in:
'enter'
: Called from `rhino.Resource`, after a handler for the current
request has bee... | [
"def",
"add_callback",
"(",
"self",
",",
"phase",
",",
"fn",
")",
":",
"try",
":",
"self",
".",
"__callbacks",
"[",
"phase",
"]",
".",
"append",
"(",
"fn",
")",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Invalid callback phase '%s'. Must be one ... | Adds a callback to the context.
The `phase` determines when and if the callback is executed, and which
positional arguments are passed in:
'enter'
: Called from `rhino.Resource`, after a handler for the current
request has been resolved, but before the handler is called.
... | [
"Adds",
"a",
"callback",
"to",
"the",
"context",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L336-L390 | train |
trendels/rhino | rhino/mapper.py | Context.add_property | def add_property(self, name, fn, cached=True):
"""Adds a property to the Context.
See `Mapper.add_ctx_property`, which uses this method to install
the properties added on the Mapper level.
"""
if name in self.__properties:
raise KeyError("Trying to add a property '%s... | python | def add_property(self, name, fn, cached=True):
"""Adds a property to the Context.
See `Mapper.add_ctx_property`, which uses this method to install
the properties added on the Mapper level.
"""
if name in self.__properties:
raise KeyError("Trying to add a property '%s... | [
"def",
"add_property",
"(",
"self",
",",
"name",
",",
"fn",
",",
"cached",
"=",
"True",
")",
":",
"if",
"name",
"in",
"self",
".",
"__properties",
":",
"raise",
"KeyError",
"(",
"\"Trying to add a property '%s' that already exists on this %s object.\"",
"%",
"(",
... | Adds a property to the Context.
See `Mapper.add_ctx_property`, which uses this method to install
the properties added on the Mapper level. | [
"Adds",
"a",
"property",
"to",
"the",
"Context",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L405-L413 | train |
trendels/rhino | rhino/mapper.py | Route.path | def path(self, args, kw):
"""Builds the URL path fragment for this route."""
params = self._pop_params(args, kw)
if args or kw:
raise InvalidArgumentError("Extra parameters (%s, %s) when building path for %s" % (args, kw, self.template))
return self.build_url(**params) | python | def path(self, args, kw):
"""Builds the URL path fragment for this route."""
params = self._pop_params(args, kw)
if args or kw:
raise InvalidArgumentError("Extra parameters (%s, %s) when building path for %s" % (args, kw, self.template))
return self.build_url(**params) | [
"def",
"path",
"(",
"self",
",",
"args",
",",
"kw",
")",
":",
"params",
"=",
"self",
".",
"_pop_params",
"(",
"args",
",",
"kw",
")",
"if",
"args",
"or",
"kw",
":",
"raise",
"InvalidArgumentError",
"(",
"\"Extra parameters (%s, %s) when building path for %s\""... | Builds the URL path fragment for this route. | [
"Builds",
"the",
"URL",
"path",
"fragment",
"for",
"this",
"route",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L477-L482 | train |
trendels/rhino | rhino/mapper.py | Mapper.add | def add(self, template, resource, name=None):
"""Add a route to a resource.
The optional `name` assigns a name to this route that can be used when
building URLs. The name must be unique within this Mapper object.
"""
# Special case for standalone handler functions
if has... | python | def add(self, template, resource, name=None):
"""Add a route to a resource.
The optional `name` assigns a name to this route that can be used when
building URLs. The name must be unique within this Mapper object.
"""
# Special case for standalone handler functions
if has... | [
"def",
"add",
"(",
"self",
",",
"template",
",",
"resource",
",",
"name",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"resource",
",",
"'_rhino_meta'",
")",
":",
"route",
"=",
"Route",
"(",
"template",
",",
"Resource",
"(",
"resource",
")",
",",
"na... | Add a route to a resource.
The optional `name` assigns a name to this route that can be used when
building URLs. The name must be unique within this Mapper object. | [
"Add",
"a",
"route",
"to",
"a",
"resource",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L553-L576 | train |
trendels/rhino | rhino/mapper.py | Mapper.add_ctx_property | def add_ctx_property(self, name, fn, cached=True):
"""Install a context property.
A context property is a factory function whos return value will be
available as a property named `name` on `Context` objects passing
through this mapper. The result will be cached unless `cached` is
... | python | def add_ctx_property(self, name, fn, cached=True):
"""Install a context property.
A context property is a factory function whos return value will be
available as a property named `name` on `Context` objects passing
through this mapper. The result will be cached unless `cached` is
... | [
"def",
"add_ctx_property",
"(",
"self",
",",
"name",
",",
"fn",
",",
"cached",
"=",
"True",
")",
":",
"if",
"name",
"in",
"[",
"item",
"[",
"0",
"]",
"for",
"item",
"in",
"self",
".",
"_ctx_properties",
"]",
":",
"raise",
"InvalidArgumentError",
"(",
... | Install a context property.
A context property is a factory function whos return value will be
available as a property named `name` on `Context` objects passing
through this mapper. The result will be cached unless `cached` is
False.
The factory function will be called without ... | [
"Install",
"a",
"context",
"property",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L614-L627 | train |
trendels/rhino | rhino/mapper.py | Mapper.path | def path(self, target, args, kw):
"""Build a URL path fragment for a resource or route.
Possible values for `target`:
A string that does not start with a '.' and does not contain ':'.
: Looks up the route of the same name on this mapper and returns it's
path.
A s... | python | def path(self, target, args, kw):
"""Build a URL path fragment for a resource or route.
Possible values for `target`:
A string that does not start with a '.' and does not contain ':'.
: Looks up the route of the same name on this mapper and returns it's
path.
A s... | [
"def",
"path",
"(",
"self",
",",
"target",
",",
"args",
",",
"kw",
")",
":",
"if",
"type",
"(",
"target",
")",
"in",
"string_types",
":",
"if",
"':'",
"in",
"target",
":",
"prefix",
",",
"rest",
"=",
"target",
".",
"split",
"(",
"':'",
",",
"1",
... | Build a URL path fragment for a resource or route.
Possible values for `target`:
A string that does not start with a '.' and does not contain ':'.
: Looks up the route of the same name on this mapper and returns it's
path.
A string of the form 'a:b', 'a:b:c', etc.
... | [
"Build",
"a",
"URL",
"path",
"fragment",
"for",
"a",
"resource",
"or",
"route",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L629-L673 | train |
trendels/rhino | rhino/mapper.py | Mapper.wsgi | def wsgi(self, environ, start_response):
"""Implements the mapper's WSGI interface."""
request = Request(environ)
ctx = Context(request)
try:
try:
response = self(request, ctx)
ctx._run_callbacks('finalize', (request, response))
... | python | def wsgi(self, environ, start_response):
"""Implements the mapper's WSGI interface."""
request = Request(environ)
ctx = Context(request)
try:
try:
response = self(request, ctx)
ctx._run_callbacks('finalize', (request, response))
... | [
"def",
"wsgi",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"request",
"=",
"Request",
"(",
"environ",
")",
"ctx",
"=",
"Context",
"(",
"request",
")",
"try",
":",
"try",
":",
"response",
"=",
"self",
"(",
"request",
",",
"ctx",
")",... | Implements the mapper's WSGI interface. | [
"Implements",
"the",
"mapper",
"s",
"WSGI",
"interface",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L675-L693 | train |
trendels/rhino | rhino/mapper.py | Mapper.start_server | def start_server(self, host='localhost', port=9000, app=None):
"""Start a `wsgiref.simple_server` based server to run this mapper."""
from wsgiref.simple_server import make_server
if app is None:
app = self.wsgi
server = make_server(host, port, app)
server_addr = "%s:... | python | def start_server(self, host='localhost', port=9000, app=None):
"""Start a `wsgiref.simple_server` based server to run this mapper."""
from wsgiref.simple_server import make_server
if app is None:
app = self.wsgi
server = make_server(host, port, app)
server_addr = "%s:... | [
"def",
"start_server",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"9000",
",",
"app",
"=",
"None",
")",
":",
"from",
"wsgiref",
".",
"simple_server",
"import",
"make_server",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"self",
".",... | Start a `wsgiref.simple_server` based server to run this mapper. | [
"Start",
"a",
"wsgiref",
".",
"simple_server",
"based",
"server",
"to",
"run",
"this",
"mapper",
"."
] | f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L726-L734 | train |
safarijv/sbo-sphinx | sbo_sphinx/apidoc.py | generate_docs | def generate_docs(app):
"""
Run sphinx-apidoc to generate Python API documentation for the project.
"""
config = app.config
config_dir = app.env.srcdir
source_root = os.path.join(config_dir, config.apidoc_source_root)
output_root = os.path.join(config_dir, config.apidoc_output_root)
exec... | python | def generate_docs(app):
"""
Run sphinx-apidoc to generate Python API documentation for the project.
"""
config = app.config
config_dir = app.env.srcdir
source_root = os.path.join(config_dir, config.apidoc_source_root)
output_root = os.path.join(config_dir, config.apidoc_output_root)
exec... | [
"def",
"generate_docs",
"(",
"app",
")",
":",
"config",
"=",
"app",
".",
"config",
"config_dir",
"=",
"app",
".",
"env",
".",
"srcdir",
"source_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
",",
"config",
".",
"apidoc_source_root",
")",
... | Run sphinx-apidoc to generate Python API documentation for the project. | [
"Run",
"sphinx",
"-",
"apidoc",
"to",
"generate",
"Python",
"API",
"documentation",
"for",
"the",
"project",
"."
] | 7a8efb7c49488131c90c19ef1a1563f595630a36 | https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/apidoc.py#L33-L51 | train |
safarijv/sbo-sphinx | sbo_sphinx/apidoc.py | cleanup | def cleanup(output_root):
"""Remove any reST files which were generated by this extension"""
if os.path.exists(output_root):
if os.path.isdir(output_root):
rmtree(output_root)
else:
os.remove(output_root) | python | def cleanup(output_root):
"""Remove any reST files which were generated by this extension"""
if os.path.exists(output_root):
if os.path.isdir(output_root):
rmtree(output_root)
else:
os.remove(output_root) | [
"def",
"cleanup",
"(",
"output_root",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"output_root",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"output_root",
")",
":",
"rmtree",
"(",
"output_root",
")",
"else",
":",
"os",
".",
"r... | Remove any reST files which were generated by this extension | [
"Remove",
"any",
"reST",
"files",
"which",
"were",
"generated",
"by",
"this",
"extension"
] | 7a8efb7c49488131c90c19ef1a1563f595630a36 | https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/apidoc.py#L54-L60 | train |
jreese/aioslack | aioslack/types.py | Auto.build | def build(cls: Type[T], data: Generic) -> T:
"""Build objects from dictionaries, recursively."""
fields = fields_dict(cls)
kwargs: Dict[str, Any] = {}
for key, value in data.items():
if key in fields:
if isinstance(value, Mapping):
t = fiel... | python | def build(cls: Type[T], data: Generic) -> T:
"""Build objects from dictionaries, recursively."""
fields = fields_dict(cls)
kwargs: Dict[str, Any] = {}
for key, value in data.items():
if key in fields:
if isinstance(value, Mapping):
t = fiel... | [
"def",
"build",
"(",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"data",
":",
"Generic",
")",
"->",
"T",
":",
"fields",
"=",
"fields_dict",
"(",
"cls",
")",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"for",
"key",
",",
"va... | Build objects from dictionaries, recursively. | [
"Build",
"objects",
"from",
"dictionaries",
"recursively",
"."
] | 5e705f557dde9e81903d84ffb2896ec0a074ad5c | https://github.com/jreese/aioslack/blob/5e705f557dde9e81903d84ffb2896ec0a074ad5c/aioslack/types.py#L36-L51 | train |
jreese/aioslack | aioslack/types.py | Auto.generate | def generate(
cls: Type[T], data: Generic, name: str = None, *, recursive: bool = True
) -> T:
"""Build dataclasses and objects from dictionaries, recursively."""
if name is None:
name = cls.__name__
kls = make_class(name, {k: ib(default=None) for k in data}, bases=(cls,)... | python | def generate(
cls: Type[T], data: Generic, name: str = None, *, recursive: bool = True
) -> T:
"""Build dataclasses and objects from dictionaries, recursively."""
if name is None:
name = cls.__name__
kls = make_class(name, {k: ib(default=None) for k in data}, bases=(cls,)... | [
"def",
"generate",
"(",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"data",
":",
"Generic",
",",
"name",
":",
"str",
"=",
"None",
",",
"*",
",",
"recursive",
":",
"bool",
"=",
"True",
")",
"->",
"T",
":",
"if",
"name",
"is",
"None",
":",
"name",
... | Build dataclasses and objects from dictionaries, recursively. | [
"Build",
"dataclasses",
"and",
"objects",
"from",
"dictionaries",
"recursively",
"."
] | 5e705f557dde9e81903d84ffb2896ec0a074ad5c | https://github.com/jreese/aioslack/blob/5e705f557dde9e81903d84ffb2896ec0a074ad5c/aioslack/types.py#L54-L69 | train |
adaptive-learning/proso-apps | proso_models/models.py | emit_answer_event | def emit_answer_event(sender, instance, **kwargs):
"""
Save answer event to log file.
"""
if not issubclass(sender, Answer) or not kwargs['created']:
return
logger = get_events_logger()
logger.emit('answer', {
"user_id": instance.user_id,
"is_correct": instance.item_asked... | python | def emit_answer_event(sender, instance, **kwargs):
"""
Save answer event to log file.
"""
if not issubclass(sender, Answer) or not kwargs['created']:
return
logger = get_events_logger()
logger.emit('answer', {
"user_id": instance.user_id,
"is_correct": instance.item_asked... | [
"def",
"emit_answer_event",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"issubclass",
"(",
"sender",
",",
"Answer",
")",
"or",
"not",
"kwargs",
"[",
"'created'",
"]",
":",
"return",
"logger",
"=",
"get_events_logger",
"(",
... | Save answer event to log file. | [
"Save",
"answer",
"event",
"to",
"log",
"file",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L1217-L1236 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_all_available_leaves | def get_all_available_leaves(self, language=None, forbidden_item_ids=None):
"""
Get all available leaves.
"""
return self.get_all_leaves(language=language, forbidden_item_ids=forbidden_item_ids) | python | def get_all_available_leaves(self, language=None, forbidden_item_ids=None):
"""
Get all available leaves.
"""
return self.get_all_leaves(language=language, forbidden_item_ids=forbidden_item_ids) | [
"def",
"get_all_available_leaves",
"(",
"self",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_all_leaves",
"(",
"language",
"=",
"language",
",",
"forbidden_item_ids",
"=",
"forbidden_item_ids",
")"
] | Get all available leaves. | [
"Get",
"all",
"available",
"leaves",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L330-L334 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_children_graph | def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
languag... | python | def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
languag... | [
"def",
"get_children_graph",
"(",
"self",
",",
"item_ids",
"=",
"None",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"if",
"forbidden_item_ids",
"is",
"None",
":",
"forbidden_item_ids",
"=",
"set",
"(",
")",
"def",
"_childr... | Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the given language
... | [
"Get",
"a",
"subgraph",
"of",
"items",
"reachable",
"from",
"the",
"given",
"set",
"of",
"items",
"through",
"the",
"child",
"relation",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L436-L471 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_parents_graph | def get_parents_graph(self, item_ids, language=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'parent' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter ... | python | def get_parents_graph(self, item_ids, language=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'parent' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter ... | [
"def",
"get_parents_graph",
"(",
"self",
",",
"item_ids",
",",
"language",
"=",
"None",
")",
":",
"def",
"_parents",
"(",
"item_ids",
")",
":",
"if",
"item_ids",
"is",
"None",
":",
"items",
"=",
"Item",
".",
"objects",
".",
"filter",
"(",
"active",
"="... | Get a subgraph of items reachable from the given set of items through
the 'parent' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the given language
... | [
"Get",
"a",
"subgraph",
"of",
"items",
"reachable",
"from",
"the",
"given",
"set",
"of",
"items",
"through",
"the",
"parent",
"relation",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L478-L505 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_graph | def get_graph(self, item_ids, language=None):
"""
Get a subgraph of items reachable from the given set of items through
any relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which a... | python | def get_graph(self, item_ids, language=None):
"""
Get a subgraph of items reachable from the given set of items through
any relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which a... | [
"def",
"get_graph",
"(",
"self",
",",
"item_ids",
",",
"language",
"=",
"None",
")",
":",
"def",
"_related",
"(",
"item_ids",
")",
":",
"if",
"item_ids",
"is",
"None",
":",
"items",
"=",
"Item",
".",
"objects",
".",
"filter",
"(",
"active",
"=",
"Tru... | Get a subgraph of items reachable from the given set of items through
any relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the given language
Re... | [
"Get",
"a",
"subgraph",
"of",
"items",
"reachable",
"from",
"the",
"given",
"set",
"of",
"items",
"through",
"any",
"relation",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L507-L532 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.translate_item_ids | def translate_item_ids(self, item_ids, language, is_nested=None):
"""
Translate a list of item ids to JSON objects which reference them.
Args:
item_ids (list[int]): item ids
language (str): language used for further filtering (some objects
for different l... | python | def translate_item_ids(self, item_ids, language, is_nested=None):
"""
Translate a list of item ids to JSON objects which reference them.
Args:
item_ids (list[int]): item ids
language (str): language used for further filtering (some objects
for different l... | [
"def",
"translate_item_ids",
"(",
"self",
",",
"item_ids",
",",
"language",
",",
"is_nested",
"=",
"None",
")",
":",
"if",
"is_nested",
"is",
"None",
":",
"def",
"is_nested_fun",
"(",
"x",
")",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"is_nested",... | Translate a list of item ids to JSON objects which reference them.
Args:
item_ids (list[int]): item ids
language (str): language used for further filtering (some objects
for different languages share the same item)
is_nested (function): mapping from item ids ... | [
"Translate",
"a",
"list",
"of",
"item",
"ids",
"to",
"JSON",
"objects",
"which",
"reference",
"them",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L606-L647 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_leaves | def get_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get mapping of items to their reachable leaves. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | python | def get_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get mapping of items to their reachable leaves. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | [
"def",
"get_leaves",
"(",
"self",
",",
"item_ids",
"=",
"None",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"forbidden_item_ids",
"=",
"set",
"(",
")",
"if",
"forbidden_item_ids",
"is",
"None",
"else",
"set",
"(",
"forbi... | Get mapping of items to their reachable leaves. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the g... | [
"Get",
"mapping",
"of",
"items",
"to",
"their",
"reachable",
"leaves",
".",
"Leaves",
"having",
"inactive",
"relations",
"to",
"other",
"items",
"are",
"omitted",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L651-L694 | train |
adaptive-learning/proso-apps | proso_models/models.py | ItemManager.get_all_leaves | def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | python | def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | [
"def",
"get_all_leaves",
"(",
"self",
",",
"item_ids",
"=",
"None",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"set",
"(",
"flatten",
"(",
"self",
".",
"get_leaves",
"(",
"item_ids",
",",
"lan... | Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in... | [
"Get",
"all",
"leaves",
"reachable",
"from",
"the",
"given",
"set",
"of",
"items",
".",
"Leaves",
"having",
"inactive",
"relations",
"to",
"other",
"items",
"are",
"omitted",
"."
] | 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L697-L710 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.