repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
kgori/treeCl | treeCl/bootstrap.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/bootstrap.py#L316-L322 | def levenberg_marquardt(self, start_x=None, damping=1.0e-3, tolerance=1.0e-6):
"""
Optimise value of x using levenberg marquardt
"""
if start_x is None:
start_x = self._analytical_fitter.fit(self._c)
return optimise_levenberg_marquardt(start_x, self._a, self._c, toler... | [
"def",
"levenberg_marquardt",
"(",
"self",
",",
"start_x",
"=",
"None",
",",
"damping",
"=",
"1.0e-3",
",",
"tolerance",
"=",
"1.0e-6",
")",
":",
"if",
"start_x",
"is",
"None",
":",
"start_x",
"=",
"self",
".",
"_analytical_fitter",
".",
"fit",
"(",
"sel... | Optimise value of x using levenberg marquardt | [
"Optimise",
"value",
"of",
"x",
"using",
"levenberg",
"marquardt"
] | python | train | 45.571429 |
svinota/mdns | mdns/zeroconf.py | https://github.com/svinota/mdns/blob/295f6407132616a0ff7401124b9057d89555f91d/mdns/zeroconf.py#L968-L992 | def write_name(self, name):
"""Writes a domain name to the packet"""
try:
# Find existing instance of this name in packet
#
index = self.names[name]
except KeyError:
# No record of this name already, so write it
# out as normal, record... | [
"def",
"write_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"# Find existing instance of this name in packet",
"#",
"index",
"=",
"self",
".",
"names",
"[",
"name",
"]",
"except",
"KeyError",
":",
"# No record of this name already, so write it",
"# out as nor... | Writes a domain name to the packet | [
"Writes",
"a",
"domain",
"name",
"to",
"the",
"packet"
] | python | train | 31.32 |
elliterate/capybara.py | capybara/node/actions.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L197-L234 | def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None,
**kwargs):
"""
Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element ... | [
"def",
"_check_with_label",
"(",
"self",
",",
"selector",
",",
"checked",
",",
"locator",
"=",
"None",
",",
"allow_label_click",
"=",
"None",
",",
"visible",
"=",
"None",
",",
"wait",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"allow_label_cli... | Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_label_click (bool, optional): Attempt to click the label to toggle st... | [
"Args",
":",
"selector",
"(",
"str",
")",
":",
"The",
"selector",
"for",
"the",
"type",
"of",
"element",
"that",
"should",
"be",
"checked",
"/",
"unchecked",
".",
"checked",
"(",
"bool",
")",
":",
"Whether",
"the",
"element",
"should",
"be",
"checked",
... | python | test | 48.526316 |
ricequant/rqalpha | rqalpha/model/tick.py | https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/model/tick.py#L44-L58 | def datetime(self):
"""
[datetime.datetime] 当前快照数据的时间戳
"""
try:
dt = self._tick_dict['datetime']
except (KeyError, ValueError):
return datetime.datetime.min
else:
if not isinstance(dt, datetime.datetime):
if dt > 1000000... | [
"def",
"datetime",
"(",
"self",
")",
":",
"try",
":",
"dt",
"=",
"self",
".",
"_tick_dict",
"[",
"'datetime'",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"min",
"else",
":",
"if",
"not",
"... | [datetime.datetime] 当前快照数据的时间戳 | [
"[",
"datetime",
".",
"datetime",
"]",
"当前快照数据的时间戳"
] | python | train | 32 |
palantir/typedjsonrpc | typedjsonrpc/registry.py | https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/typedjsonrpc/registry.py#L95-L118 | def dispatch(self, request):
"""Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0
... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
")",
":",
"def",
"_wrapped",
"(",
")",
":",
"messages",
"=",
"self",
".",
"_get_request_messages",
"(",
"request",
")",
"results",
"=",
"[",
"self",
".",
"_dispatch_and_handle_errors",
"(",
"message",
")",
"f... | Takes a request and dispatches its data to a jsonrpc method.
:param request: a werkzeug request with json data
:type request: werkzeug.wrappers.Request
:return: json output of the corresponding method
:rtype: str
.. versionadded:: 0.1.0 | [
"Takes",
"a",
"request",
"and",
"dispatches",
"its",
"data",
"to",
"a",
"jsonrpc",
"method",
"."
] | python | train | 38.833333 |
SheffieldML/GPy | GPy/util/univariate_Gaussian.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/univariate_Gaussian.py#L14-L24 | def inv_std_norm_cdf(x):
"""
Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008)
"""
z = 2*x -1
ln1z2 = np.log(1-z**2)
a = 8*(np.pi -3)/(3*np.pi*(4-np.pi))
b = 2/(np.pi * a) + ln1z2/2
inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b )
return ... | [
"def",
"inv_std_norm_cdf",
"(",
"x",
")",
":",
"z",
"=",
"2",
"*",
"x",
"-",
"1",
"ln1z2",
"=",
"np",
".",
"log",
"(",
"1",
"-",
"z",
"**",
"2",
")",
"a",
"=",
"8",
"*",
"(",
"np",
".",
"pi",
"-",
"3",
")",
"/",
"(",
"3",
"*",
"np",
"... | Inverse cumulative standard Gaussian distribution
Based on Winitzki, S. (2008) | [
"Inverse",
"cumulative",
"standard",
"Gaussian",
"distribution",
"Based",
"on",
"Winitzki",
"S",
".",
"(",
"2008",
")"
] | python | train | 30 |
Alignak-monitoring/alignak | alignak/http/arbiter_interface.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1629-L1638 | def _wait_new_conf(self):
"""Ask the daemon to drop its configuration and wait for a new one
This overrides the default method from GenericInterface
:return: None
"""
with self.app.conf_lock:
logger.warning("My master Arbiter wants me to wait for a new configuration... | [
"def",
"_wait_new_conf",
"(",
"self",
")",
":",
"with",
"self",
".",
"app",
".",
"conf_lock",
":",
"logger",
".",
"warning",
"(",
"\"My master Arbiter wants me to wait for a new configuration.\"",
")",
"self",
".",
"app",
".",
"cur_conf",
"=",
"{",
"}"
] | Ask the daemon to drop its configuration and wait for a new one
This overrides the default method from GenericInterface
:return: None | [
"Ask",
"the",
"daemon",
"to",
"drop",
"its",
"configuration",
"and",
"wait",
"for",
"a",
"new",
"one"
] | python | train | 34.9 |
timothydmorton/VESPA | vespa/fpp.py | https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/fpp.py#L406-L433 | def plotsignal(self,fig=None,saveplot=True,folder=None,figformat='png',**kwargs):
"""
Plots TransitSignal
Calls :func:`TransitSignal.plot`, saves to provided folder.
:param fig: (optional)
Argument for :func:`plotutils.setfig`.
:param saveplot: (optional)
... | [
"def",
"plotsignal",
"(",
"self",
",",
"fig",
"=",
"None",
",",
"saveplot",
"=",
"True",
",",
"folder",
"=",
"None",
",",
"figformat",
"=",
"'png'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"folder",
"is",
"None",
":",
"folder",
"=",
"self",
".",
... | Plots TransitSignal
Calls :func:`TransitSignal.plot`, saves to provided folder.
:param fig: (optional)
Argument for :func:`plotutils.setfig`.
:param saveplot: (optional)
Whether to save figure.
:param folder: (optional)
Folder to which to save plot... | [
"Plots",
"TransitSignal"
] | python | train | 29.035714 |
rande/python-simple-ioc | ioc/extra/tornado/router.py | https://github.com/rande/python-simple-ioc/blob/36ddf667c1213a07a53cd4cdd708d02494e5190b/ioc/extra/tornado/router.py#L32-L42 | def generate_static(self, path):
"""
This method generates a valid path to the public folder of the running project
"""
if not path:
return ""
if path[0] == '/':
return "%s?v=%s" % (path, self.version)
return "%s/%s?v=%s" % (self.static, path, se... | [
"def",
"generate_static",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"\"\"",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"return",
"\"%s?v=%s\"",
"%",
"(",
"path",
",",
"self",
".",
"version",
")",
"return",
"\"%s/%s?v... | This method generates a valid path to the public folder of the running project | [
"This",
"method",
"generates",
"a",
"valid",
"path",
"to",
"the",
"public",
"folder",
"of",
"the",
"running",
"project"
] | python | train | 29.181818 |
bcbio/bcbio-nextgen | bcbio/structural/hydra.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/hydra.py#L148-L162 | def detect_sv(align_bam, genome_build, dirs, config):
"""Detect structural variation from discordant aligned pairs.
"""
work_dir = utils.safe_makedir(os.path.join(dirs["work"], "structural"))
pair_stats = shared.calc_paired_insert_stats(align_bam)
fix_bam = remove_nopairs(align_bam, work_dir, config... | [
"def",
"detect_sv",
"(",
"align_bam",
",",
"genome_build",
",",
"dirs",
",",
"config",
")",
":",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
"[",
"\"work\"",
"]",
",",
"\"structural\"",
")",
")",
"pa... | Detect structural variation from discordant aligned pairs. | [
"Detect",
"structural",
"variation",
"from",
"discordant",
"aligned",
"pairs",
"."
] | python | train | 53.866667 |
azogue/dataweb | dataweb/mergedataweb.py | https://github.com/azogue/dataweb/blob/085035855df7cef0fe7725bbe9a706832344d946/dataweb/mergedataweb.py#L39-L91 | def merge_data(lista_dfs_o_dict, keys_merge=None):
"""
Realiza y devuelve el merge de una lista de pandas DataFrame's (o bien de un diccionario de {key:pd.Dataframe}).
Coge la primera y en ella va añadiendo el resto, de una en una.
Seguramente no sea la mejor opción para realizar la fusión de los datos ... | [
"def",
"merge_data",
"(",
"lista_dfs_o_dict",
",",
"keys_merge",
"=",
"None",
")",
":",
"def",
"_merge_lista",
"(",
"lista_dfs",
")",
":",
"if",
"len",
"(",
"lista_dfs",
")",
"==",
"2",
"and",
"lista_dfs",
"[",
"0",
"]",
".",
"index",
"[",
"-",
"1",
... | Realiza y devuelve el merge de una lista de pandas DataFrame's (o bien de un diccionario de {key:pd.Dataframe}).
Coge la primera y en ella va añadiendo el resto, de una en una.
Seguramente no sea la mejor opción para realizar la fusión de los datos de distintos días, pero aguanta bien la
superposición de mu... | [
"Realiza",
"y",
"devuelve",
"el",
"merge",
"de",
"una",
"lista",
"de",
"pandas",
"DataFrame",
"s",
"(",
"o",
"bien",
"de",
"un",
"diccionario",
"de",
"{",
"key",
":",
"pd",
".",
"Dataframe",
"}",
")",
".",
"Coge",
"la",
"primera",
"y",
"en",
"ella",
... | python | train | 50.471698 |
StanfordVL/robosuite | robosuite/devices/keyboard.py | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L26-L45 | def _display_controls(self):
"""
Method to pretty print controls.
"""
def print_command(char, info):
char += " " * (10 - len(char))
print("{}\t{}".format(char, info))
print("")
print_command("Keys", "Command")
print_command("q", "reset si... | [
"def",
"_display_controls",
"(",
"self",
")",
":",
"def",
"print_command",
"(",
"char",
",",
"info",
")",
":",
"char",
"+=",
"\" \"",
"*",
"(",
"10",
"-",
"len",
"(",
"char",
")",
")",
"print",
"(",
"\"{}\\t{}\"",
".",
"format",
"(",
"char",
",",
"... | Method to pretty print controls. | [
"Method",
"to",
"pretty",
"print",
"controls",
"."
] | python | train | 36.1 |
saltstack/salt | salt/modules/mac_power.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_power.py#L379-L404 | def set_restart_power_failure(enabled):
'''
Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False r... | [
"def",
"set_restart_power_failure",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setrestartpowerfailure {0}'",
".",
"format",
"(",
"state",
")",
"salt",
"... | Set whether or not the computer will automatically restart after a power
failure.
:param bool enabled: True to enable, False to disable. "On" and "Off" are
also acceptable values. Additionally you can pass 1 and 0 to represent
True and False respectively
:return: True if successful, False ... | [
"Set",
"whether",
"or",
"not",
"the",
"computer",
"will",
"automatically",
"restart",
"after",
"a",
"power",
"failure",
"."
] | python | train | 29.269231 |
xtrementl/focus | focus/task.py | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/task.py#L285-L300 | def remove(self, task_name):
""" Removes an existing task directory.
`task_name`
Task name.
Returns ``True`` if removal successful.
"""
try:
task_dir = self._get_task_dir(task_name)
shutil.rmtree(task_dir)
return ... | [
"def",
"remove",
"(",
"self",
",",
"task_name",
")",
":",
"try",
":",
"task_dir",
"=",
"self",
".",
"_get_task_dir",
"(",
"task_name",
")",
"shutil",
".",
"rmtree",
"(",
"task_dir",
")",
"return",
"True",
"except",
"OSError",
":",
"return",
"False"
] | Removes an existing task directory.
`task_name`
Task name.
Returns ``True`` if removal successful. | [
"Removes",
"an",
"existing",
"task",
"directory",
"."
] | python | train | 22.4375 |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L160-L179 | def populate(self, deserialized_txs=None, filename=None, retry=None):
"""Populates the batch with unsaved model instances
from a generator of deserialized objects.
"""
if not deserialized_txs:
raise BatchError("Failed to populate batch. There are no objects to add.")
... | [
"def",
"populate",
"(",
"self",
",",
"deserialized_txs",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"retry",
"=",
"None",
")",
":",
"if",
"not",
"deserialized_txs",
":",
"raise",
"BatchError",
"(",
"\"Failed to populate batch. There are no objects to add.\"",
... | Populates the batch with unsaved model instances
from a generator of deserialized objects. | [
"Populates",
"the",
"batch",
"with",
"unsaved",
"model",
"instances",
"from",
"a",
"generator",
"of",
"deserialized",
"objects",
"."
] | python | train | 45.15 |
ethereum/pyethereum | ethereum/tools/_solidity.py | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L124-L130 | def compiler_version():
""" Return the version of the installed solc. """
version_info = subprocess.check_output(['solc', '--version'])
match = re.search(b'^Version: ([0-9a-z.-]+)/', version_info, re.MULTILINE)
if match:
return match.group(1) | [
"def",
"compiler_version",
"(",
")",
":",
"version_info",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'solc'",
",",
"'--version'",
"]",
")",
"match",
"=",
"re",
".",
"search",
"(",
"b'^Version: ([0-9a-z.-]+)/'",
",",
"version_info",
",",
"re",
".",
"M... | Return the version of the installed solc. | [
"Return",
"the",
"version",
"of",
"the",
"installed",
"solc",
"."
] | python | train | 37.285714 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L72-L134 | def add_output(self, key, value, variable_type):
"""Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the ... | [
"def",
"add_output",
"(",
"self",
",",
"key",
",",
"value",
",",
"variable_type",
")",
":",
"index",
"=",
"'{}-{}'",
".",
"format",
"(",
"key",
",",
"variable_type",
")",
"self",
".",
"output_data",
".",
"setdefault",
"(",
"index",
",",
"{",
"}",
")",
... | Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the data can be
stored inline, when it is generated and ... | [
"Dynamically",
"add",
"output",
"to",
"output_data",
"dictionary",
"to",
"be",
"written",
"to",
"DB",
"later",
"."
] | python | train | 37.793651 |
gwpy/gwpy | gwpy/utils/decorators.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/utils/decorators.py#L64-L90 | def deprecated_function(func, warning=DEPRECATED_FUNCTION_WARNING):
"""Adds a `DeprecationWarning` to a function
Parameters
----------
func : `callable`
the function to decorate with a `DeprecationWarning`
warning : `str`, optional
the warning to present
Notes
-----
Th... | [
"def",
"deprecated_function",
"(",
"func",
",",
"warning",
"=",
"DEPRECATED_FUNCTION_WARNING",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"DEPRECATED_F... | Adds a `DeprecationWarning` to a function
Parameters
----------
func : `callable`
the function to decorate with a `DeprecationWarning`
warning : `str`, optional
the warning to present
Notes
-----
The final warning message is formatted as ``warning.format(func)``
so you... | [
"Adds",
"a",
"DeprecationWarning",
"to",
"a",
"function"
] | python | train | 27.592593 |
Stewori/pytypes | pytypes/__init__.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/__init__.py#L425-L438 | def enable_global_annotations_decorator(flag = True, retrospective = True):
"""Enables or disables global annotation mode via decorators.
See flag global_annotations_decorator.
In contrast to setting the flag directly, this function provides
a retrospective option. If retrospective is true, this will al... | [
"def",
"enable_global_annotations_decorator",
"(",
"flag",
"=",
"True",
",",
"retrospective",
"=",
"True",
")",
":",
"global",
"global_annotations_decorator",
"global_annotations_decorator",
"=",
"flag",
"if",
"import_hook_enabled",
":",
"_install_import_hook",
"(",
")",
... | Enables or disables global annotation mode via decorators.
See flag global_annotations_decorator.
In contrast to setting the flag directly, this function provides
a retrospective option. If retrospective is true, this will also
affect already imported modules, not only future imports. | [
"Enables",
"or",
"disables",
"global",
"annotation",
"mode",
"via",
"decorators",
".",
"See",
"flag",
"global_annotations_decorator",
".",
"In",
"contrast",
"to",
"setting",
"the",
"flag",
"directly",
"this",
"function",
"provides",
"a",
"retrospective",
"option",
... | python | train | 47.285714 |
libChEBI/libChEBIpy | libchebipy/_chebi_entity.py | https://github.com/libChEBI/libChEBIpy/blob/89f223a91f518619d5e3910070d283adcac1626e/libchebipy/_chebi_entity.py#L215-L230 | def get_mol_filename(self):
'''Returns mol filename'''
mol_filename = parsers.get_mol_filename(self.__chebi_id)
if mol_filename is None:
mol_filename = parsers.get_mol_filename(self.get_parent_id())
if mol_filename is None:
for parent_or_child_id in self.__get_a... | [
"def",
"get_mol_filename",
"(",
"self",
")",
":",
"mol_filename",
"=",
"parsers",
".",
"get_mol_filename",
"(",
"self",
".",
"__chebi_id",
")",
"if",
"mol_filename",
"is",
"None",
":",
"mol_filename",
"=",
"parsers",
".",
"get_mol_filename",
"(",
"self",
".",
... | Returns mol filename | [
"Returns",
"mol",
"filename"
] | python | train | 32.0625 |
oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/metadata.py | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/metadata.py#L57-L64 | def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | [
"def",
"create_metadata_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"return",
"headers",
",",
... | Create metadata response | [
"Create",
"metadata",
"response"
] | python | train | 36 |
timeyyy/apptools | peasoup/uploadlogs.py | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/uploadlogs.py#L31-L43 | def logexception(self, logger=None):
'''
calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return:
'''
traceback.print_exc()
if logger:
logger... | [
"def",
"logexception",
"(",
"self",
",",
"logger",
"=",
"None",
")",
":",
"traceback",
".",
"print_exc",
"(",
")",
"if",
"logger",
":",
"logger",
".",
"exception",
"(",
"'Unexpected runtime Error...'",
")",
"else",
":",
"self",
".",
"logger",
".",
"excepti... | calls exception method on a loger and prints the log to stdout
logger is set in the cfg
#Todo more details here on the cfg etc
:param logger:
:return: | [
"calls",
"exception",
"method",
"on",
"a",
"loger",
"and",
"prints",
"the",
"log",
"to",
"stdout",
"logger",
"is",
"set",
"in",
"the",
"cfg",
"#Todo",
"more",
"details",
"here",
"on",
"the",
"cfg",
"etc",
":",
"param",
"logger",
":",
":",
"return",
":"... | python | train | 32.923077 |
threema-ch/ocspresponder | ocspresponder/__init__.py | https://github.com/threema-ch/ocspresponder/blob/b9486af68dd02b84e01bedabe4f6843a6ff0f698/ocspresponder/__init__.py#L120-L127 | def _handle_post(self):
"""
An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body.
"""
der = request.body.read()
ocsp_request = self._parse_ocsp_request(der)
return self._build_http_response(ocsp_request) | [
"def",
"_handle_post",
"(",
"self",
")",
":",
"der",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
"ocsp_request",
"=",
"self",
".",
"_parse_ocsp_request",
"(",
"der",
")",
"return",
"self",
".",
"_build_http_response",
"(",
"ocsp_request",
")"
] | An OCSP POST request contains the DER encoded OCSP request in the HTTP
request body. | [
"An",
"OCSP",
"POST",
"request",
"contains",
"the",
"DER",
"encoded",
"OCSP",
"request",
"in",
"the",
"HTTP",
"request",
"body",
"."
] | python | train | 35.375 |
wesleybeckner/salty | salty/core.py | https://github.com/wesleybeckner/salty/blob/ef17a97aea3e4f81fcd0359ce85b3438c0e6499b/salty/core.py#L210-L302 | def aggregate_data(data, T=[0, inf], P=[0, inf], data_ranges=None,
merge="overlap", feature_type=None, impute=False,
scale_center=True):
"""
Aggregates molecular data for model training
Parameters
----------
data: list
density, cpt, and/or viscosity
... | [
"def",
"aggregate_data",
"(",
"data",
",",
"T",
"=",
"[",
"0",
",",
"inf",
"]",
",",
"P",
"=",
"[",
"0",
",",
"inf",
"]",
",",
"data_ranges",
"=",
"None",
",",
"merge",
"=",
"\"overlap\"",
",",
"feature_type",
"=",
"None",
",",
"impute",
"=",
"Fa... | Aggregates molecular data for model training
Parameters
----------
data: list
density, cpt, and/or viscosity
T: array
desired min and max of temperature distribution
P: array
desired min and max of pressure distribution
data_ranges: array
desired min and max of p... | [
"Aggregates",
"molecular",
"data",
"for",
"model",
"training"
] | python | train | 43.462366 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py#L349-L360 | def get_vnetwork_dvpgs_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = get_vnetwork_dvpgs
input = ET.SubElement(get_vnetwork_dvpgs, "input")
vcenter = ET.SubElem... | [
"def",
"get_vnetwork_dvpgs_input_vcenter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_dvpgs",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_dvpgs\"",
")",
"config",
"=",
"get_vne... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 38.833333 |
greenelab/PathCORE-T | pathcore/network.py | https://github.com/greenelab/PathCORE-T/blob/9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c/pathcore/network.py#L512-L520 | def _augment_network(self, edge_dict):
"""Given a dictionary of edges (edge id -> feature list), add all of
these to the CoNetwork object
"""
for (vertex0, vertex1), feature_list in edge_dict.items():
edge_obj = Edge(vertex0, vertex1, feature_list)
self.edges[(ver... | [
"def",
"_augment_network",
"(",
"self",
",",
"edge_dict",
")",
":",
"for",
"(",
"vertex0",
",",
"vertex1",
")",
",",
"feature_list",
"in",
"edge_dict",
".",
"items",
"(",
")",
":",
"edge_obj",
"=",
"Edge",
"(",
"vertex0",
",",
"vertex1",
",",
"feature_li... | Given a dictionary of edges (edge id -> feature list), add all of
these to the CoNetwork object | [
"Given",
"a",
"dictionary",
"of",
"edges",
"(",
"edge",
"id",
"-",
">",
"feature",
"list",
")",
"add",
"all",
"of",
"these",
"to",
"the",
"CoNetwork",
"object"
] | python | train | 50 |
maweigert/gputools | gputools/convolve/convolve.py | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/convolve.py#L18-L54 | def convolve(data, h, res_g=None, sub_blocks=None):
"""
convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge.
"""
if not len(data.shape) in [1, 2, 3]:
... | [
"def",
"convolve",
"(",
"data",
",",
"h",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"None",
")",
":",
"if",
"not",
"len",
"(",
"data",
".",
"shape",
")",
"in",
"[",
"1",
",",
"2",
",",
"3",
"]",
":",
"raise",
"ValueError",
"(",
"\"dim ... | convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge. | [
"convolves",
"1d",
"-",
"3d",
"data",
"with",
"kernel",
"h"
] | python | train | 41.837838 |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L1214-L1220 | def append(self, data, size):
"""
Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method.
"""
return lib.zchunk_append(self._as_p... | [
"def",
"append",
"(",
"self",
",",
"data",
",",
"size",
")",
":",
"return",
"lib",
".",
"zchunk_append",
"(",
"self",
".",
"_as_parameter_",
",",
"data",
",",
"size",
")"
] | Append user-supplied data to chunk, return resulting chunk size. If the
data would exceeded the available space, it is truncated. If you want to
grow the chunk to accommodate new data, use the zchunk_extend method. | [
"Append",
"user",
"-",
"supplied",
"data",
"to",
"chunk",
"return",
"resulting",
"chunk",
"size",
".",
"If",
"the",
"data",
"would",
"exceeded",
"the",
"available",
"space",
"it",
"is",
"truncated",
".",
"If",
"you",
"want",
"to",
"grow",
"the",
"chunk",
... | python | train | 48 |
rcbops/flake8-filename | flake8_filename/__init__.py | https://github.com/rcbops/flake8-filename/blob/5718d4af394c318d376de7434193543e0da45651/flake8_filename/__init__.py#L68-L86 | def run(self):
"""Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation
"""
if len(self.filename_checks) == 0:
message = "N401 no configuration found ... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"filename_checks",
")",
"==",
"0",
":",
"message",
"=",
"\"N401 no configuration found for {}, \"",
"\"please provide filename configuration in a flake8 config\"",
".",
"format",
"(",
"self",
".",
"... | Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation | [
"Required",
"by",
"flake8",
"Will",
"be",
"called",
"after",
"add_options",
"and",
"parse_options",
"."
] | python | train | 38.684211 |
mattjj/pyslds | pyslds/states.py | https://github.com/mattjj/pyslds/blob/c505c2bd05a5549d450b518f02493b68ed12e590/pyslds/states.py#L730-L748 | def mf_aBl(self):
"""
These are the expected log likelihoods (node potentials)
as seen from the discrete states.
"""
mf_aBl = self._mf_aBl = np.zeros((self.T, self.num_states))
ids, dds, eds = self.init_dynamics_distns, self.dynamics_distns, \
self.emission_di... | [
"def",
"mf_aBl",
"(",
"self",
")",
":",
"mf_aBl",
"=",
"self",
".",
"_mf_aBl",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"T",
",",
"self",
".",
"num_states",
")",
")",
"ids",
",",
"dds",
",",
"eds",
"=",
"self",
".",
"init_dynamics_distns",
... | These are the expected log likelihoods (node potentials)
as seen from the discrete states. | [
"These",
"are",
"the",
"expected",
"log",
"likelihoods",
"(",
"node",
"potentials",
")",
"as",
"seen",
"from",
"the",
"discrete",
"states",
"."
] | python | train | 39.052632 |
Clinical-Genomics/scout | scout/adapter/mongo/panel.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/panel.py#L189-L200 | def delete_panel(self, panel_obj):
"""Delete a panel by '_id'.
Args:
panel_obj(dict)
Returns:
res(pymongo.DeleteResult)
"""
res = self.panel_collection.delete_one({'_id': panel_obj['_id']})
LOG.warning("Deleting panel %s, version %s" % (panel_obj... | [
"def",
"delete_panel",
"(",
"self",
",",
"panel_obj",
")",
":",
"res",
"=",
"self",
".",
"panel_collection",
".",
"delete_one",
"(",
"{",
"'_id'",
":",
"panel_obj",
"[",
"'_id'",
"]",
"}",
")",
"LOG",
".",
"warning",
"(",
"\"Deleting panel %s, version %s\"",... | Delete a panel by '_id'.
Args:
panel_obj(dict)
Returns:
res(pymongo.DeleteResult) | [
"Delete",
"a",
"panel",
"by",
"_id",
"."
] | python | test | 30.5 |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L287-L307 | 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",
"."
] | python | train | 50.380952 |
mikedh/trimesh | trimesh/base.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/base.py#L1387-L1402 | def is_winding_consistent(self):
"""
Does the mesh have consistent winding or not.
A mesh with consistent winding has each shared edge
going in an opposite direction from the other in the pair.
Returns
--------
consistent : bool
Is winding is consistent... | [
"def",
"is_winding_consistent",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_empty",
":",
"return",
"False",
"# consistent winding check is populated into the cache by is_watertight",
"populate",
"=",
"self",
".",
"is_watertight",
"return",
"self",
".",
"_cache",
"[",
... | Does the mesh have consistent winding or not.
A mesh with consistent winding has each shared edge
going in an opposite direction from the other in the pair.
Returns
--------
consistent : bool
Is winding is consistent or not | [
"Does",
"the",
"mesh",
"have",
"consistent",
"winding",
"or",
"not",
".",
"A",
"mesh",
"with",
"consistent",
"winding",
"has",
"each",
"shared",
"edge",
"going",
"in",
"an",
"opposite",
"direction",
"from",
"the",
"other",
"in",
"the",
"pair",
"."
] | python | train | 34.0625 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L13047-L13098 | def update(cls, request_response_id, monetary_account_id=None,
amount_responded=None, status=None, address_shipping=None,
address_billing=None, custom_headers=None):
"""
Update the status to accept or reject the RequestResponse.
:type user_id: int
:type mon... | [
"def",
"update",
"(",
"cls",
",",
"request_response_id",
",",
"monetary_account_id",
"=",
"None",
",",
"amount_responded",
"=",
"None",
",",
"status",
"=",
"None",
",",
"address_shipping",
"=",
"None",
",",
"address_billing",
"=",
"None",
",",
"custom_headers",
... | Update the status to accept or reject the RequestResponse.
:type user_id: int
:type monetary_account_id: int
:type request_response_id: int
:param amount_responded: The Amount the user decides to pay.
:type amount_responded: object_.Amount
:param status: The responding s... | [
"Update",
"the",
"status",
"to",
"accept",
"or",
"reject",
"the",
"RequestResponse",
"."
] | python | train | 45.75 |
INM-6/hybridLFPy | examples/Hagen_et_al_2016_cercor/plot_methods.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/Hagen_et_al_2016_cercor/plot_methods.py#L43-L382 | def network_sketch(ax, highlight=None, labels=True, yscaling=1.):
'''
highlight : None or string
if string, then only the label of this population is set and the box is highlighted
'''
name_to_id_mapping={'L6E':(0,0),
'L6I':(0,1),
'L5E':(1,0)... | [
"def",
"network_sketch",
"(",
"ax",
",",
"highlight",
"=",
"None",
",",
"labels",
"=",
"True",
",",
"yscaling",
"=",
"1.",
")",
":",
"name_to_id_mapping",
"=",
"{",
"'L6E'",
":",
"(",
"0",
",",
"0",
")",
",",
"'L6I'",
":",
"(",
"0",
",",
"1",
")"... | highlight : None or string
if string, then only the label of this population is set and the box is highlighted | [
"highlight",
":",
"None",
"or",
"string",
"if",
"string",
"then",
"only",
"the",
"label",
"of",
"this",
"population",
"is",
"set",
"and",
"the",
"box",
"is",
"highlighted"
] | python | train | 52.041176 |
mikedh/trimesh | trimesh/scene/transforms.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/scene/transforms.py#L76-L86 | def md5(self):
"""
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
"""
result = str(self._updated) + str(self.base_frame)
return result | [
"def",
"md5",
"(",
"self",
")",
":",
"result",
"=",
"str",
"(",
"self",
".",
"_updated",
")",
"+",
"str",
"(",
"self",
".",
"base_frame",
")",
"return",
"result"
] | "Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms | [
"Hash",
"of",
"transforms"
] | python | train | 21.272727 |
jxtech/wechatpy | wechatpy/pay/api/coupon.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/pay/api/coupon.py#L11-L41 | def send(self, user_id, stock_id, op_user_id=None, device_info=None,
out_trade_no=None):
"""
发放代金券
:param user_id: 用户在公众号下的 openid
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:param out_trade_no: 可... | [
"def",
"send",
"(",
"self",
",",
"user_id",
",",
"stock_id",
",",
"op_user_id",
"=",
"None",
",",
"device_info",
"=",
"None",
",",
"out_trade_no",
"=",
"None",
")",
":",
"if",
"not",
"out_trade_no",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
... | 发放代金券
:param user_id: 用户在公众号下的 openid
:param stock_id: 代金券批次 ID
:param op_user_id: 可选,操作员账号,默认为商户号
:param device_info: 可选,微信支付分配的终端设备号
:param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成
:return: 返回的结果信息 | [
"发放代金券"
] | python | train | 32.387097 |
adafruit/Adafruit_Python_GPIO | Adafruit_GPIO/FT232H.py | https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/FT232H.py#L861-L866 | def readS8(self, register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
if result > 127:
result -= 256
return result | [
"def",
"readS8",
"(",
"self",
",",
"register",
")",
":",
"result",
"=",
"self",
".",
"readU8",
"(",
"register",
")",
"if",
"result",
">",
"127",
":",
"result",
"-=",
"256",
"return",
"result"
] | Read a signed byte from the specified register. | [
"Read",
"a",
"signed",
"byte",
"from",
"the",
"specified",
"register",
"."
] | python | valid | 32.666667 |
IdentityPython/SATOSA | src/satosa/deprecated.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L122-L132 | def save_state(internal_request, state):
"""
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
"""
state_data = {"hash_type... | [
"def",
"save_state",
"(",
"internal_request",
",",
"state",
")",
":",
"state_data",
"=",
"{",
"\"hash_type\"",
":",
"internal_request",
".",
"user_id_hash_type",
"}",
"state",
"[",
"UserIdHasher",
".",
"STATE_KEY",
"]",
"=",
"state_data"
] | Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state | [
"Saves",
"all",
"necessary",
"information",
"needed",
"by",
"the",
"UserIdHasher"
] | python | train | 36.272727 |
inveniosoftware-attic/invenio-comments | invenio_comments/api.py | https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/api.py#L945-L951 | def get_reply_order_cache_data(comid):
"""
Prepare a representation of the comment ID given as parameter so
that it is suitable for byte ordering in MySQL.
"""
return "%s%s%s%s" % (chr((comid >> 24) % 256), chr((comid >> 16) % 256),
chr((comid >> 8) % 256), chr(comid % 256)) | [
"def",
"get_reply_order_cache_data",
"(",
"comid",
")",
":",
"return",
"\"%s%s%s%s\"",
"%",
"(",
"chr",
"(",
"(",
"comid",
">>",
"24",
")",
"%",
"256",
")",
",",
"chr",
"(",
"(",
"comid",
">>",
"16",
")",
"%",
"256",
")",
",",
"chr",
"(",
"(",
"c... | Prepare a representation of the comment ID given as parameter so
that it is suitable for byte ordering in MySQL. | [
"Prepare",
"a",
"representation",
"of",
"the",
"comment",
"ID",
"given",
"as",
"parameter",
"so",
"that",
"it",
"is",
"suitable",
"for",
"byte",
"ordering",
"in",
"MySQL",
"."
] | python | train | 44.857143 |
wummel/linkchecker | third_party/dnspython/dns/ipv6.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/ipv6.py#L96-L163 | def inet_aton(text):
"""Convert a text format IPv6 address into network format.
@param text: the textual address
@type text: string
@rtype: string
@raises dns.exception.SyntaxError: the text was not properly formatted
"""
#
# Our aim here is not something fast; we just want something t... | [
"def",
"inet_aton",
"(",
"text",
")",
":",
"#",
"# Our aim here is not something fast; we just want something that works.",
"#",
"if",
"text",
"==",
"'::'",
":",
"text",
"=",
"'0::'",
"#",
"# Get rid of the icky dot-quad syntax if we have it.",
"#",
"m",
"=",
"_v4_ending"... | Convert a text format IPv6 address into network format.
@param text: the textual address
@type text: string
@rtype: string
@raises dns.exception.SyntaxError: the text was not properly formatted | [
"Convert",
"a",
"text",
"format",
"IPv6",
"address",
"into",
"network",
"format",
"."
] | python | train | 27.352941 |
OLC-LOC-Bioinformatics/GenomeQAML | genomeqaml/extract_features.py | https://github.com/OLC-LOC-Bioinformatics/GenomeQAML/blob/2953e574c185afab23075641da4ce5392bc003e9/genomeqaml/extract_features.py#L54-L63 | def find_files(sequencepath):
"""
Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as
.fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported
:param sequencepath: path of folder containing FASTA genomes
:return: li... | [
"def",
"find_files",
"(",
"sequencepath",
")",
":",
"# Create a sorted list of all the FASTA files in the sequence path",
"files",
"=",
"sorted",
"(",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sequencepath",
",",
"'*.fa*'",
")",
")",
")",
"return",
"files... | Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as
.fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported
:param sequencepath: path of folder containing FASTA genomes
:return: list of FASTA files | [
"Use",
"glob",
"to",
"find",
"all",
"FASTA",
"files",
"in",
"the",
"provided",
"sequence",
"path",
".",
"NOTE",
":",
"FASTA",
"files",
"must",
"have",
"an",
"extension",
"such",
"as",
".",
"fasta",
".",
"fa",
"or",
".",
"fas",
".",
"Extensions",
"of",
... | python | train | 48.6 |
Dapid/tmscoring | tmscoring/tmscore.py | https://github.com/Dapid/tmscoring/blob/353c567e201ee9835c8209f6130b80b1cfb5b10f/tmscoring/tmscore.py#L45-L81 | def get_default_values(self):
"""
Make a crude estimation of the alignment using the center of mass
and general C->N orientation.
"""
out = dict(dx=0, dy=0, dz=0, theta=0, phi=0, psi=0)
dx, dy, dz, _ = np.mean(self.coord1 - self.coord2, axis=1)
out['dx'] = dx
... | [
"def",
"get_default_values",
"(",
"self",
")",
":",
"out",
"=",
"dict",
"(",
"dx",
"=",
"0",
",",
"dy",
"=",
"0",
",",
"dz",
"=",
"0",
",",
"theta",
"=",
"0",
",",
"phi",
"=",
"0",
",",
"psi",
"=",
"0",
")",
"dx",
",",
"dy",
",",
"dz",
",... | Make a crude estimation of the alignment using the center of mass
and general C->N orientation. | [
"Make",
"a",
"crude",
"estimation",
"of",
"the",
"alignment",
"using",
"the",
"center",
"of",
"mass",
"and",
"general",
"C",
"-",
">",
"N",
"orientation",
"."
] | python | train | 39.459459 |
dead-beef/markovchain | markovchain/text/scanner.py | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/text/scanner.py#L282-L293 | def save(self):
"""Convert the scanner to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super().save()
data['expr'] = self.expr.pattern
data['default_end'] = self.default_end
return data | [
"def",
"save",
"(",
"self",
")",
":",
"data",
"=",
"super",
"(",
")",
".",
"save",
"(",
")",
"data",
"[",
"'expr'",
"]",
"=",
"self",
".",
"expr",
".",
"pattern",
"data",
"[",
"'default_end'",
"]",
"=",
"self",
".",
"default_end",
"return",
"data"
... | Convert the scanner to JSON.
Returns
-------
`dict`
JSON data. | [
"Convert",
"the",
"scanner",
"to",
"JSON",
"."
] | python | train | 22.083333 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1915-L1948 | def _number_type_helper(national_number, metadata):
"""Return the type of the given number against the metadata"""
if not _is_number_matching_desc(national_number, metadata.general_desc):
return PhoneNumberType.UNKNOWN
if _is_number_matching_desc(national_number, metadata.premium_rate):
retu... | [
"def",
"_number_type_helper",
"(",
"national_number",
",",
"metadata",
")",
":",
"if",
"not",
"_is_number_matching_desc",
"(",
"national_number",
",",
"metadata",
".",
"general_desc",
")",
":",
"return",
"PhoneNumberType",
".",
"UNKNOWN",
"if",
"_is_number_matching_de... | Return the type of the given number against the metadata | [
"Return",
"the",
"type",
"of",
"the",
"given",
"number",
"against",
"the",
"metadata"
] | python | train | 52.470588 |
textbook/atmdb | atmdb/client.py | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L246-L261 | def _calculate_page_index(index, data):
"""Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the... | [
"def",
"_calculate_page_index",
"(",
"index",
",",
"data",
")",
":",
"if",
"index",
">",
"data",
"[",
"'total_results'",
"]",
":",
"raise",
"ValueError",
"(",
"'index not in paged data'",
")",
"page_length",
"=",
"len",
"(",
"data",
"[",
"'results'",
"]",
")... | Determine the location of a given index in paged data.
Arguments:
index (:py:class:`int`): The overall index.
data: (:py:class:`dict`) The first page of data.
Returns:
:py:class:`tuple`: The location of that index, in the format
``(page, index_in_page)``. | [
"Determine",
"the",
"location",
"of",
"a",
"given",
"index",
"in",
"paged",
"data",
"."
] | python | train | 35.875 |
kstaniek/condoor | condoor/hopinfo.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/hopinfo.py#L16-L63 | def make_hop_info_from_url(url, verify_reachability=None):
"""Build HopInfo object from url.
It allows only telnet and ssh as a valid protocols.
Args:
url (str): The url string describing the node. i.e.
telnet://username@1.1.1.1. The protocol, username and address
portion o... | [
"def",
"make_hop_info_from_url",
"(",
"url",
",",
"verify_reachability",
"=",
"None",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"username",
"=",
"None",
"if",
"parsed",
".",
"username",
"is",
"None",
"else",
"unquote",
"(",
"parsed",
".",
"user... | Build HopInfo object from url.
It allows only telnet and ssh as a valid protocols.
Args:
url (str): The url string describing the node. i.e.
telnet://username@1.1.1.1. The protocol, username and address
portion of url is mandatory. Port and password is optional.
If ... | [
"Build",
"HopInfo",
"object",
"from",
"url",
"."
] | python | train | 38.25 |
log2timeline/plaso | plaso/parsers/sqlite_plugins/hangouts_messages.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/sqlite_plugins/hangouts_messages.py#L265-L290 | def ParseMessagesRow(self, parser_mediator, query, row, **unused_kwargs):
"""Parses an Messages row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.R... | [
"def",
"ParseMessagesRow",
"(",
"self",
",",
"parser_mediator",
",",
"query",
",",
"row",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"query_hash",
"=",
"hash",
"(",
"query",
")",
"event_data",
"=",
"HangoutsMessageData",
"(",
")",
"event_data",
".",
"sender",... | Parses an Messages row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | [
"Parses",
"an",
"Messages",
"row",
"."
] | python | train | 41.884615 |
mikedh/trimesh | trimesh/parent.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/parent.py#L168-L185 | def bounding_primitive(self):
"""
The minimum volume primitive (box, sphere, or cylinder) that
bounds the mesh.
Returns
---------
bounding_primitive : trimesh.primitives.Sphere
trimesh.primitives.Box
trimesh.primi... | [
"def",
"bounding_primitive",
"(",
"self",
")",
":",
"options",
"=",
"[",
"self",
".",
"bounding_box_oriented",
",",
"self",
".",
"bounding_sphere",
",",
"self",
".",
"bounding_cylinder",
"]",
"volume_min",
"=",
"np",
".",
"argmin",
"(",
"[",
"i",
".",
"vol... | The minimum volume primitive (box, sphere, or cylinder) that
bounds the mesh.
Returns
---------
bounding_primitive : trimesh.primitives.Sphere
trimesh.primitives.Box
trimesh.primitives.Cylinder
Primitive which bounds th... | [
"The",
"minimum",
"volume",
"primitive",
"(",
"box",
"sphere",
"or",
"cylinder",
")",
"that",
"bounds",
"the",
"mesh",
"."
] | python | train | 37.222222 |
scott-griffiths/bitstring | bitstring.py | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1679-L1685 | def _setse(self, i):
"""Initialise bitstring with signed exponential-Golomb code for integer i."""
if i > 0:
u = (i * 2) - 1
else:
u = -2 * i
self._setue(u) | [
"def",
"_setse",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
">",
"0",
":",
"u",
"=",
"(",
"i",
"*",
"2",
")",
"-",
"1",
"else",
":",
"u",
"=",
"-",
"2",
"*",
"i",
"self",
".",
"_setue",
"(",
"u",
")"
] | Initialise bitstring with signed exponential-Golomb code for integer i. | [
"Initialise",
"bitstring",
"with",
"signed",
"exponential",
"-",
"Golomb",
"code",
"for",
"integer",
"i",
"."
] | python | train | 29.428571 |
wavycloud/pyboto3 | pyboto3/swf.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/swf.py#L1483-L1693 | def list_closed_workflow_executions(domain=None, startTimeFilter=None, closeTimeFilter=None, executionFilter=None, closeStatusFilter=None, typeFilter=None, tagFilter=None, nextPageToken=None, maximumPageSize=None, reverseOrder=None):
"""
Returns a list of closed workflow executions in the specified domain that ... | [
"def",
"list_closed_workflow_executions",
"(",
"domain",
"=",
"None",
",",
"startTimeFilter",
"=",
"None",
",",
"closeTimeFilter",
"=",
"None",
",",
"executionFilter",
"=",
"None",
",",
"closeStatusFilter",
"=",
"None",
",",
"typeFilter",
"=",
"None",
",",
"tagF... | Returns a list of closed workflow executions in the specified domain that meet the filtering criteria. The results may be split into multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken returned by the initial call.
Access Control
You can use IAM policies to control this act... | [
"Returns",
"a",
"list",
"of",
"closed",
"workflow",
"executions",
"in",
"the",
"specified",
"domain",
"that",
"meet",
"the",
"filtering",
"criteria",
".",
"The",
"results",
"may",
"be",
"split",
"into",
"multiple",
"pages",
".",
"To",
"retrieve",
"subsequent",... | python | train | 53.085308 |
LPgenerator/django-db-mailer | dbmail/providers/slack/push.py | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/slack/push.py#L23-L65 | def send(channel, message, **kwargs):
"""
Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging
"""
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),
}
username = from_unicode(kwargs.pop("us... | [
"def",
"send",
"(",
"channel",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencoded\"",
",",
"\"User-Agent\"",
":",
"\"DBMail/%s\"",
"%",
"get_version",
"(",
")",
",",
"}",
"usern... | Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging | [
"Site",
":",
"https",
":",
"//",
"slack",
".",
"com",
"API",
":",
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"Desc",
":",
"real",
"-",
"time",
"messaging"
] | python | train | 26.883721 |
Erotemic/utool | utool/util_path.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_path.py#L140-L142 | def tail(fpath, n=2, trailing=True):
""" Alias for path_ndir_split """
return path_ndir_split(fpath, n=n, trailing=trailing) | [
"def",
"tail",
"(",
"fpath",
",",
"n",
"=",
"2",
",",
"trailing",
"=",
"True",
")",
":",
"return",
"path_ndir_split",
"(",
"fpath",
",",
"n",
"=",
"n",
",",
"trailing",
"=",
"trailing",
")"
] | Alias for path_ndir_split | [
"Alias",
"for",
"path_ndir_split"
] | python | train | 43.333333 |
gpoulter/python-ngram | ngram.py | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L310-L339 | def search(self, query, threshold=None):
"""Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decre... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"threshold",
"=",
"None",
")",
":",
"threshold",
"=",
"threshold",
"if",
"threshold",
"is",
"not",
"None",
"else",
"self",
".",
"threshold",
"results",
"=",
"[",
"]",
"# Identify possible results",
"for",
"m... | Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decreasing similarity.
>>> from ngram import NGr... | [
"Search",
"the",
"index",
"for",
"items",
"whose",
"key",
"exceeds",
"threshold",
"similarity",
"to",
"the",
"query",
"string",
"."
] | python | train | 42.066667 |
rbit/pydtls | dtls/sslconnection.py | https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/sslconnection.py#L699-L715 | def connect(self, peer_address):
"""Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of s... | [
"def",
"connect",
"(",
"self",
",",
"peer_address",
")",
":",
"self",
".",
"_sock",
".",
"connect",
"(",
"peer_address",
")",
"peer_address",
"=",
"self",
".",
"_sock",
".",
"getpeername",
"(",
")",
"# substituted host addrinfo",
"BIO_dgram_set_connected",
"(",
... | Client-side UDP connection establishment
This method connects this object's underlying socket. It subsequently
performs a handshake if do_handshake_on_connect was set during
initialization.
Arguments:
peer_address - address tuple of server peer | [
"Client",
"-",
"side",
"UDP",
"connection",
"establishment"
] | python | train | 36.647059 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2800-L2843 | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False):
"""Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directo... | [
"def",
"makedirs",
"(",
"self",
",",
"dir_name",
",",
"mode",
"=",
"PERM_DEF",
",",
"exist_ok",
"=",
"False",
")",
":",
"ends_with_sep",
"=",
"self",
".",
"ends_with_path_separator",
"(",
"dir_name",
")",
"dir_name",
"=",
"self",
".",
"absnormpath",
"(",
"... | Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask i... | [
"Create",
"a",
"leaf",
"Fake",
"directory",
"and",
"create",
"any",
"non",
"-",
"existent",
"parent",
"dirs",
"."
] | python | train | 43.340909 |
psychok7/django-celery-inspect | celery_inspect/api/viewsets.py | https://github.com/psychok7/django-celery-inspect/blob/26302cd71a0bb6bed8caf922b8cf15ea95aef699/celery_inspect/api/viewsets.py#L29-L52 | def active_status(self, request):
"""
This will only work if you have django-celery installed (for now).
In case you only need to work with status codes to find out if the
workers are up or not.
This will only work if we assume our db only contains "active workers".
To us... | [
"def",
"active_status",
"(",
"self",
",",
"request",
")",
":",
"app_installed",
"=",
"\"djcelery\"",
"in",
"settings",
".",
"INSTALLED_APPS",
"if",
"not",
"app_installed",
":",
"return",
"Response",
"(",
"status",
"=",
"status",
".",
"HTTP_501_NOT_IMPLEMENTED",
... | This will only work if you have django-celery installed (for now).
In case you only need to work with status codes to find out if the
workers are up or not.
This will only work if we assume our db only contains "active workers".
To use this feature, you must ensure you use only named wor... | [
"This",
"will",
"only",
"work",
"if",
"you",
"have",
"django",
"-",
"celery",
"installed",
"(",
"for",
"now",
")",
".",
"In",
"case",
"you",
"only",
"need",
"to",
"work",
"with",
"status",
"codes",
"to",
"find",
"out",
"if",
"the",
"workers",
"are",
... | python | train | 41.5 |
pmorissette/bt | bt/core.py | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L184-L190 | def weight(self):
"""
Current weight of the Node (with respect to the parent).
"""
if self.root.stale:
self.root.update(self.root.now, None)
return self._weight | [
"def",
"weight",
"(",
"self",
")",
":",
"if",
"self",
".",
"root",
".",
"stale",
":",
"self",
".",
"root",
".",
"update",
"(",
"self",
".",
"root",
".",
"now",
",",
"None",
")",
"return",
"self",
".",
"_weight"
] | Current weight of the Node (with respect to the parent). | [
"Current",
"weight",
"of",
"the",
"Node",
"(",
"with",
"respect",
"to",
"the",
"parent",
")",
"."
] | python | train | 29.428571 |
geometalab/pyGeoTile | pygeotile/tile.py | https://github.com/geometalab/pyGeoTile/blob/b1f44271698f5fc4d18c2add935797ed43254aa6/pygeotile/tile.py#L43-L46 | def for_point(cls, point, zoom):
"""Creates a tile for given point"""
latitude, longitude = point.latitude_longitude
return cls.for_latitude_longitude(latitude=latitude, longitude=longitude, zoom=zoom) | [
"def",
"for_point",
"(",
"cls",
",",
"point",
",",
"zoom",
")",
":",
"latitude",
",",
"longitude",
"=",
"point",
".",
"latitude_longitude",
"return",
"cls",
".",
"for_latitude_longitude",
"(",
"latitude",
"=",
"latitude",
",",
"longitude",
"=",
"longitude",
... | Creates a tile for given point | [
"Creates",
"a",
"tile",
"for",
"given",
"point"
] | python | train | 55.5 |
atlassian-api/atlassian-python-api | atlassian/confluence.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/confluence.py#L696-L704 | def get_page_as_pdf(self, page_id):
"""
Export page as standard pdf exporter
:param page_id: Page ID
:return: PDF File
"""
headers = self.form_token_headers
url = 'spaces/flyingpdf/pdfpageexport.action?pageId={pageId}'.format(pageId=page_id)
return self.ge... | [
"def",
"get_page_as_pdf",
"(",
"self",
",",
"page_id",
")",
":",
"headers",
"=",
"self",
".",
"form_token_headers",
"url",
"=",
"'spaces/flyingpdf/pdfpageexport.action?pageId={pageId}'",
".",
"format",
"(",
"pageId",
"=",
"page_id",
")",
"return",
"self",
".",
"ge... | Export page as standard pdf exporter
:param page_id: Page ID
:return: PDF File | [
"Export",
"page",
"as",
"standard",
"pdf",
"exporter",
":",
"param",
"page_id",
":",
"Page",
"ID",
":",
"return",
":",
"PDF",
"File"
] | python | train | 39.888889 |
ludeeus/GHLocalApi | ghlocalapi/utils/convert.py | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/utils/convert.py#L9-L21 | def get_device_type(device_type=0):
"""Return the device type from a device_type list."""
device_types = {
0: "Unknown",
1: "Classic - BR/EDR devices",
2: "Low Energy - LE-only",
3: "Dual Mode - BR/EDR/LE"
}
if device_type in [0, 1, 2, 3]:
return_value = device_ty... | [
"def",
"get_device_type",
"(",
"device_type",
"=",
"0",
")",
":",
"device_types",
"=",
"{",
"0",
":",
"\"Unknown\"",
",",
"1",
":",
"\"Classic - BR/EDR devices\"",
",",
"2",
":",
"\"Low Energy - LE-only\"",
",",
"3",
":",
"\"Dual Mode - BR/EDR/LE\"",
"}",
"if",
... | Return the device type from a device_type list. | [
"Return",
"the",
"device",
"type",
"from",
"a",
"device_type",
"list",
"."
] | python | train | 30.538462 |
sparklingpandas/sparklingpandas | sparklingpandas/prdd.py | https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/prdd.py#L59-L66 | def groupby(self, *args, **kwargs):
"""Takes the same parameters as groupby on DataFrame.
Like with groupby on DataFrame disabling sorting will result in an
even larger performance improvement. This returns a Sparkling Pandas
L{GroupBy} object which supports many of the same operations a... | [
"def",
"groupby",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"sparklingpandas",
".",
"groupby",
"import",
"GroupBy",
"return",
"GroupBy",
"(",
"self",
".",
"_rdd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Takes the same parameters as groupby on DataFrame.
Like with groupby on DataFrame disabling sorting will result in an
even larger performance improvement. This returns a Sparkling Pandas
L{GroupBy} object which supports many of the same operations as regular
GroupBy but not all. | [
"Takes",
"the",
"same",
"parameters",
"as",
"groupby",
"on",
"DataFrame",
".",
"Like",
"with",
"groupby",
"on",
"DataFrame",
"disabling",
"sorting",
"will",
"result",
"in",
"an",
"even",
"larger",
"performance",
"improvement",
".",
"This",
"returns",
"a",
"Spa... | python | train | 57.125 |
williamjameshandley/fgivenx | fgivenx/plot.py | https://github.com/williamjameshandley/fgivenx/blob/a16790652a3cef3cfacd4b97da62786cb66fec13/fgivenx/plot.py#L7-L106 | def plot(x, y, z, ax=None, **kwargs):
r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to pl... | [
"def",
"plot",
"(",
"x",
",",
"y",
",",
"z",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"matplotlib",
".",
"pyplot",
".",
"gca",
"(",
")",
"# Get inputs",
"colors",
"=",
"kwargs",
".",
... | r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to plot the contours
onto. If unsupplie... | [
"r",
"Plot",
"iso",
"-",
"probability",
"mass",
"function",
"converted",
"to",
"sigmas",
"."
] | python | train | 32.62 |
Koed00/django-q | django_q/cluster.py | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/cluster.py#L560-L594 | def set_cpu_affinity(n, process_ids, actual=not Conf.TESTING):
"""
Sets the cpu affinity for the supplied processes.
Requires the optional psutil module.
:param int n: affinity
:param list process_ids: a list of pids
:param bool actual: Test workaround for Travis not supporting cpu affinity
... | [
"def",
"set_cpu_affinity",
"(",
"n",
",",
"process_ids",
",",
"actual",
"=",
"not",
"Conf",
".",
"TESTING",
")",
":",
"# check if we have the psutil module",
"if",
"not",
"psutil",
":",
"logger",
".",
"warning",
"(",
"'Skipping cpu affinity because psutil was not foun... | Sets the cpu affinity for the supplied processes.
Requires the optional psutil module.
:param int n: affinity
:param list process_ids: a list of pids
:param bool actual: Test workaround for Travis not supporting cpu affinity | [
"Sets",
"the",
"cpu",
"affinity",
"for",
"the",
"supplied",
"processes",
".",
"Requires",
"the",
"optional",
"psutil",
"module",
".",
":",
"param",
"int",
"n",
":",
"affinity",
":",
"param",
"list",
"process_ids",
":",
"a",
"list",
"of",
"pids",
":",
"pa... | python | train | 39.028571 |
mozilla/treeherder | treeherder/webapp/api/job_log_url.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/job_log_url.py#L23-L28 | def retrieve(self, request, project, pk=None):
"""
Returns a job_log_url object given its ID
"""
log = JobLog.objects.get(id=pk)
return Response(self._log_as_dict(log)) | [
"def",
"retrieve",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"log",
"=",
"JobLog",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"pk",
")",
"return",
"Response",
"(",
"self",
".",
"_log_as_dict",
"(",
"log",
")",
... | Returns a job_log_url object given its ID | [
"Returns",
"a",
"job_log_url",
"object",
"given",
"its",
"ID"
] | python | train | 33.833333 |
zetaops/zengine | zengine/models/workflow_manager.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/models/workflow_manager.py#L369-L383 | def get_object_query_dict(self):
"""returns objects keys according to self.object_query_code
which can be json encoded queryset filter dict or key=value set
in the following format: ```"key=val, key2 = val2 , key3= value with spaces"```
Returns:
(dict): Queryset filtering ... | [
"def",
"get_object_query_dict",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"object_query_code",
",",
"dict",
")",
":",
"# _DATE_ _DATETIME_",
"return",
"self",
".",
"object_query_code",
"else",
":",
"# comma separated, key=value pairs. wrapping spaces ... | returns objects keys according to self.object_query_code
which can be json encoded queryset filter dict or key=value set
in the following format: ```"key=val, key2 = val2 , key3= value with spaces"```
Returns:
(dict): Queryset filtering dicqt | [
"returns",
"objects",
"keys",
"according",
"to",
"self",
".",
"object_query_code",
"which",
"can",
"be",
"json",
"encoded",
"queryset",
"filter",
"dict",
"or",
"key",
"=",
"value",
"set",
"in",
"the",
"following",
"format",
":",
"key",
"=",
"val",
"key2",
... | python | train | 46.533333 |
pricingassistant/mrq | mrq/job.py | https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/job.py#L263-L275 | def requeue(self, queue=None, retry_count=0):
""" Requeues the current job. Doesn't interrupt it """
if not queue:
if not self.data or not self.data.get("queue"):
self.fetch(full_data={"_id": 0, "queue": 1, "path": 1})
queue = self.data["queue"]
self._sa... | [
"def",
"requeue",
"(",
"self",
",",
"queue",
"=",
"None",
",",
"retry_count",
"=",
"0",
")",
":",
"if",
"not",
"queue",
":",
"if",
"not",
"self",
".",
"data",
"or",
"not",
"self",
".",
"data",
".",
"get",
"(",
"\"queue\"",
")",
":",
"self",
".",
... | Requeues the current job. Doesn't interrupt it | [
"Requeues",
"the",
"current",
"job",
".",
"Doesn",
"t",
"interrupt",
"it"
] | python | train | 36.076923 |
jreinhardt/handkerchief | handkerchief/handkerchief.py | https://github.com/jreinhardt/handkerchief/blob/450291314ccbbf557b41a30ce9c523587758fe76/handkerchief/handkerchief.py#L289-L299 | def collect_github_config():
"""
Try load Github configuration such as usernames from the local or global git config
"""
github_config = {}
for field in ["user", "token"]:
try:
github_config[field] = subprocess.check_output(["git", "config", "github.{}".format(field)]).decode('utf-8').strip()
except (OSErro... | [
"def",
"collect_github_config",
"(",
")",
":",
"github_config",
"=",
"{",
"}",
"for",
"field",
"in",
"[",
"\"user\"",
",",
"\"token\"",
"]",
":",
"try",
":",
"github_config",
"[",
"field",
"]",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"git\"",
... | Try load Github configuration such as usernames from the local or global git config | [
"Try",
"load",
"Github",
"configuration",
"such",
"as",
"usernames",
"from",
"the",
"local",
"or",
"global",
"git",
"config"
] | python | train | 34 |
mjirik/sed3 | sed3/sed3.py | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L708-L735 | def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
... | [
"def",
"__get_slice",
"(",
"data",
",",
"slice_number",
",",
"axis",
"=",
"0",
",",
"flipH",
"=",
"False",
",",
"flipV",
"=",
"False",
")",
":",
"if",
"axis",
"==",
"0",
":",
"data2d",
"=",
"data",
"[",
"slice_number",
",",
":",
",",
":",
"]",
"e... | :param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return: | [
":",
"param",
"data",
":",
":",
"param",
"slice_number",
":",
":",
"param",
"axis",
":",
":",
"param",
"flipV",
":",
"vertical",
"flip",
":",
"param",
"flipH",
":",
"horizontal",
"flip",
":",
"return",
":"
] | python | train | 25.178571 |
tgsmith61591/pmdarima | pmdarima/arima/auto.py | https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/arima/auto.py#L565-L593 | def _return_wrapper(fits, return_all, start, trace):
"""If the user wants to get all of the models back, this will
return a list of the ARIMA models, otherwise it will just return
the model. If this is called from the end of the function, ``fits``
will already be a list.
We *know* that if a functio... | [
"def",
"_return_wrapper",
"(",
"fits",
",",
"return_all",
",",
"start",
",",
"trace",
")",
":",
"# make sure it's an iterable",
"if",
"not",
"is_iterable",
"(",
"fits",
")",
":",
"fits",
"=",
"[",
"fits",
"]",
"# whether to print the final runtime",
"if",
"trace... | If the user wants to get all of the models back, this will
return a list of the ARIMA models, otherwise it will just return
the model. If this is called from the end of the function, ``fits``
will already be a list.
We *know* that if a function call makes it here, ``fits`` is NOT None
or it would h... | [
"If",
"the",
"user",
"wants",
"to",
"get",
"all",
"of",
"the",
"models",
"back",
"this",
"will",
"return",
"a",
"list",
"of",
"the",
"ARIMA",
"models",
"otherwise",
"it",
"will",
"just",
"return",
"the",
"model",
".",
"If",
"this",
"is",
"called",
"fro... | python | train | 30.62069 |
BD2KGenomics/protect | attic/ProTECT.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/attic/ProTECT.py#L1761-L1785 | def get_pipeline_inputs(job, input_flag, input_file):
"""
Get the input file from s3 or disk, untargz if necessary and then write to file job store.
:param job: job
:param str input_flag: The name of the flag
:param str input_file: The value passed in the config file
:return: The jobstore ID for... | [
"def",
"get_pipeline_inputs",
"(",
"job",
",",
"input_flag",
",",
"input_file",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Obtaining file (%s) to the file job store'",
"... | Get the input file from s3 or disk, untargz if necessary and then write to file job store.
:param job: job
:param str input_flag: The name of the flag
:param str input_file: The value passed in the config file
:return: The jobstore ID for the file | [
"Get",
"the",
"input",
"file",
"from",
"s3",
"or",
"disk",
"untargz",
"if",
"necessary",
"and",
"then",
"write",
"to",
"file",
"job",
"store",
".",
":",
"param",
"job",
":",
"job",
":",
"param",
"str",
"input_flag",
":",
"The",
"name",
"of",
"the",
"... | python | train | 52.84 |
deepmind/sonnet | sonnet/python/modules/base.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/base.py#L60-L66 | def _get_or_create_stack(name):
"""Returns a thread local stack uniquified by the given name."""
stack = getattr(_LOCAL_STACKS, name, None)
if stack is None:
stack = []
setattr(_LOCAL_STACKS, name, stack)
return stack | [
"def",
"_get_or_create_stack",
"(",
"name",
")",
":",
"stack",
"=",
"getattr",
"(",
"_LOCAL_STACKS",
",",
"name",
",",
"None",
")",
"if",
"stack",
"is",
"None",
":",
"stack",
"=",
"[",
"]",
"setattr",
"(",
"_LOCAL_STACKS",
",",
"name",
",",
"stack",
")... | Returns a thread local stack uniquified by the given name. | [
"Returns",
"a",
"thread",
"local",
"stack",
"uniquified",
"by",
"the",
"given",
"name",
"."
] | python | train | 32.428571 |
mardix/Mocha | mocha/utils.py | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/utils.py#L103-L111 | def md5(value):
"""
Create MD5
:param value:
:return:
"""
m = hashlib.md5()
m.update(value)
return str(m.hexdigest()) | [
"def",
"md5",
"(",
"value",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"value",
")",
"return",
"str",
"(",
"m",
".",
"hexdigest",
"(",
")",
")"
] | Create MD5
:param value:
:return: | [
"Create",
"MD5",
":",
"param",
"value",
":",
":",
"return",
":"
] | python | train | 15.666667 |
PythonCharmers/python-future | src/future/backports/xmlrpc/server.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L177-L211 | def register_instance(self, instance, allow_dotted_names=False):
"""Registers an instance to respond to XML-RPC requests.
Only one instance can be installed at a time.
If the registered instance has a _dispatch method then that
method will be called with the name of the XML-RPC method ... | [
"def",
"register_instance",
"(",
"self",
",",
"instance",
",",
"allow_dotted_names",
"=",
"False",
")",
":",
"self",
".",
"instance",
"=",
"instance",
"self",
".",
"allow_dotted_names",
"=",
"allow_dotted_names"
] | Registers an instance to respond to XML-RPC requests.
Only one instance can be installed at a time.
If the registered instance has a _dispatch method then that
method will be called with the name of the XML-RPC method and
its parameters as a tuple
e.g. instance._dispatch('add',... | [
"Registers",
"an",
"instance",
"to",
"respond",
"to",
"XML",
"-",
"RPC",
"requests",
"."
] | python | train | 41.171429 |
yyuu/botornado | boto/manage/volume.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/manage/volume.py#L183-L198 | def get_snapshots(self):
"""
Returns a list of all completed snapshots for this volume ID.
"""
ec2 = self.get_ec2_connection()
rs = ec2.get_all_snapshots()
all_vols = [self.volume_id] + self.past_volume_ids
snaps = []
for snapshot in rs:
if sna... | [
"def",
"get_snapshots",
"(",
"self",
")",
":",
"ec2",
"=",
"self",
".",
"get_ec2_connection",
"(",
")",
"rs",
"=",
"ec2",
".",
"get_all_snapshots",
"(",
")",
"all_vols",
"=",
"[",
"self",
".",
"volume_id",
"]",
"+",
"self",
".",
"past_volume_ids",
"snaps... | Returns a list of all completed snapshots for this volume ID. | [
"Returns",
"a",
"list",
"of",
"all",
"completed",
"snapshots",
"for",
"this",
"volume",
"ID",
"."
] | python | train | 38.6875 |
quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L288-L305 | def stats(self):
"""The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
the stats may have changed.
... | [
"def",
"stats",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dirty_stats",
":",
"calculate_position_tracker_stats",
"(",
"self",
".",
"positions",
",",
"self",
".",
"_stats",
")",
"self",
".",
"_dirty_stats",
"=",
"False",
"return",
"self",
".",
"_stats"
] | The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
the stats may have changed. | [
"The",
"current",
"status",
"of",
"the",
"positions",
"."
] | python | train | 26.555556 |
Unidata/siphon | siphon/radarserver.py | https://github.com/Unidata/siphon/blob/53fb0d84fbce1c18c8e81c9e68bc81620ee0a6ac/siphon/radarserver.py#L217-L220 | def parse_station_table(root):
"""Parse station list XML file."""
stations = [parse_xml_station(elem) for elem in root.findall('station')]
return {st.id: st for st in stations} | [
"def",
"parse_station_table",
"(",
"root",
")",
":",
"stations",
"=",
"[",
"parse_xml_station",
"(",
"elem",
")",
"for",
"elem",
"in",
"root",
".",
"findall",
"(",
"'station'",
")",
"]",
"return",
"{",
"st",
".",
"id",
":",
"st",
"for",
"st",
"in",
"... | Parse station list XML file. | [
"Parse",
"station",
"list",
"XML",
"file",
"."
] | python | train | 46.25 |
edx/edx-enterprise | consent/migrations/0002_migrate_to_new_data_sharing_consent.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/migrations/0002_migrate_to_new_data_sharing_consent.py#L20-L45 | def populate_data_sharing_consent(apps, schema_editor):
"""
Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.
Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.
"""
DataSharingConsent = apps.get_model('co... | [
"def",
"populate_data_sharing_consent",
"(",
"apps",
",",
"schema_editor",
")",
":",
"DataSharingConsent",
"=",
"apps",
".",
"get_model",
"(",
"'consent'",
",",
"'DataSharingConsent'",
")",
"EnterpriseCourseEnrollment",
"=",
"apps",
".",
"get_model",
"(",
"'enterprise... | Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.
Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model. | [
"Populates",
"the",
"DataSharingConsent",
"model",
"with",
"the",
"enterprise",
"application",
"s",
"consent",
"data",
"."
] | python | valid | 52.461538 |
ecederstrand/exchangelib | exchangelib/items.py | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L116-L126 | def deregister(cls, attr_name):
"""
De-register an extended property that has been registered with register()
"""
try:
field = cls.get_field_by_fieldname(attr_name)
except InvalidField:
raise ValueError("'%s' is not registered" % attr_name)
if not ... | [
"def",
"deregister",
"(",
"cls",
",",
"attr_name",
")",
":",
"try",
":",
"field",
"=",
"cls",
".",
"get_field_by_fieldname",
"(",
"attr_name",
")",
"except",
"InvalidField",
":",
"raise",
"ValueError",
"(",
"\"'%s' is not registered\"",
"%",
"attr_name",
")",
... | De-register an extended property that has been registered with register() | [
"De",
"-",
"register",
"an",
"extended",
"property",
"that",
"has",
"been",
"registered",
"with",
"register",
"()"
] | python | train | 43 |
python-fedex-devs/python-fedex | fedex/services/track_service.py | https://github.com/python-fedex-devs/python-fedex/blob/7ea2ca80c362f5dbbc8d959ab47648c7a4ab24eb/fedex/services/track_service.py#L92-L108 | def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED.
"""
client = self.client
# Fire off the query.
return c... | [
"def",
"_assemble_and_send_request",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"client",
"# Fire off the query.",
"return",
"client",
".",
"service",
".",
"track",
"(",
"WebAuthenticationDetail",
"=",
"self",
".",
"WebAuthenticationDetail",
",",
"ClientDeta... | Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED. | [
"Fires",
"off",
"the",
"Fedex",
"request",
"."
] | python | train | 38.470588 |
peri-source/peri | peri/states.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/states.py#L257-L268 | def temp_update(self, params, values):
"""
Context manager to temporarily perform a parameter update (by using the
stack structure). To use:
with state.temp_update(params, values):
# measure the cost or something
state.error
"""
self.p... | [
"def",
"temp_update",
"(",
"self",
",",
"params",
",",
"values",
")",
":",
"self",
".",
"push_update",
"(",
"params",
",",
"values",
")",
"yield",
"self",
".",
"pop_update",
"(",
")"
] | Context manager to temporarily perform a parameter update (by using the
stack structure). To use:
with state.temp_update(params, values):
# measure the cost or something
state.error | [
"Context",
"manager",
"to",
"temporarily",
"perform",
"a",
"parameter",
"update",
"(",
"by",
"using",
"the",
"stack",
"structure",
")",
".",
"To",
"use",
":"
] | python | valid | 31.25 |
DomBennett/TaxonNamesResolver | taxon_names_resolver/manip_tools.py | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/manip_tools.py#L208-L241 | def taxTree(taxdict):
"""Return taxonomic Newick tree"""
# the taxonomic dictionary holds the lineage of each ident in
# the same order as the taxonomy
# use hierarchy to construct a taxonomic tree
for rank in taxdict.taxonomy:
current_level = float(taxdict.taxonomy.index(rank))
# g... | [
"def",
"taxTree",
"(",
"taxdict",
")",
":",
"# the taxonomic dictionary holds the lineage of each ident in",
"# the same order as the taxonomy",
"# use hierarchy to construct a taxonomic tree",
"for",
"rank",
"in",
"taxdict",
".",
"taxonomy",
":",
"current_level",
"=",
"float",
... | Return taxonomic Newick tree | [
"Return",
"taxonomic",
"Newick",
"tree"
] | python | train | 48.705882 |
FreekingDean/insteon-hub | insteon/insteon.py | https://github.com/FreekingDean/insteon-hub/blob/afd60d0a7fa74752f29d63c9bb6ccccd46d7aa3e/insteon/insteon.py#L102-L110 | def query_status(self):
'''Query the hub for the status of this command'''
try:
data = self.api_iface._api_get(self.link)
self._update_details(data)
except APIError as e:
print("API error: ")
for key,value in e.data.iteritems:
print... | [
"def",
"query_status",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"api_iface",
".",
"_api_get",
"(",
"self",
".",
"link",
")",
"self",
".",
"_update_details",
"(",
"data",
")",
"except",
"APIError",
"as",
"e",
":",
"print",
"(",
"\"... | Query the hub for the status of this command | [
"Query",
"the",
"hub",
"for",
"the",
"status",
"of",
"this",
"command"
] | python | train | 38 |
mitsei/dlkit | dlkit/json_/hierarchy/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/hierarchy/sessions.py#L978-L1001 | def can_create_hierarchy_with_record_types(self, hierarchy_record_types):
"""Tests if this user can create a single ``Hierarchy`` using the desired record types.
While ``HierarchyManager.getHierarchyRecordTypes()`` can be used
to examine which records are supported, this method tests which
... | [
"def",
"can_create_hierarchy_with_record_types",
"(",
"self",
",",
"hierarchy_record_types",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.can_create_bin_with_record_types",
"# NOTE: It is expected that real authentication hints will be",
"# handled in a service... | Tests if this user can create a single ``Hierarchy`` using the desired record types.
While ``HierarchyManager.getHierarchyRecordTypes()`` can be used
to examine which records are supported, this method tests which
record(s) are required for creating a specific ``Hierarchy``.
Providing a... | [
"Tests",
"if",
"this",
"user",
"can",
"create",
"a",
"single",
"Hierarchy",
"using",
"the",
"desired",
"record",
"types",
"."
] | python | train | 54.458333 |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttdepitem.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttdepitem.py#L42-L58 | def paint( self, painter, option, widget ):
"""
Overloads the paint method from QGraphicsPathItem to \
handle custom drawing of the path using this items \
pens and polygons.
:param painter <QPainter>
:param option <QGraphicsItemStyleOption>
... | [
"def",
"paint",
"(",
"self",
",",
"painter",
",",
"option",
",",
"widget",
")",
":",
"super",
"(",
"XGanttDepItem",
",",
"self",
")",
".",
"paint",
"(",
"painter",
",",
"option",
",",
"widget",
")",
"# redraw the poly to force-fill it",
"if",
"(",
"self",
... | Overloads the paint method from QGraphicsPathItem to \
handle custom drawing of the path using this items \
pens and polygons.
:param painter <QPainter>
:param option <QGraphicsItemStyleOption>
:param widget <QWidget> | [
"Overloads",
"the",
"paint",
"method",
"from",
"QGraphicsPathItem",
"to",
"\\",
"handle",
"custom",
"drawing",
"of",
"the",
"path",
"using",
"this",
"items",
"\\",
"pens",
"and",
"polygons",
".",
":",
"param",
"painter",
"<QPainter",
">",
":",
"param",
"opti... | python | train | 38.705882 |
briancappello/flask-unchained | flask_unchained/bundles/controller/templates.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/templates.py#L89-L148 | def explain_template_loading_attempts(app, template, attempts):
"""
This should help developers understand what failed. Mostly the same as
:func:`flask.debughelpers.explain_template_loading_attempts`, except here we've
extended it to support showing what :class:`UnchainedJinjaLoader` is doing.
"""
... | [
"def",
"explain_template_loading_attempts",
"(",
"app",
",",
"template",
",",
"attempts",
")",
":",
"from",
"flask",
"import",
"Flask",
",",
"Blueprint",
"from",
"flask",
".",
"debughelpers",
"import",
"_dump_loader_info",
"from",
"flask",
".",
"globals",
"import"... | This should help developers understand what failed. Mostly the same as
:func:`flask.debughelpers.explain_template_loading_attempts`, except here we've
extended it to support showing what :class:`UnchainedJinjaLoader` is doing. | [
"This",
"should",
"help",
"developers",
"understand",
"what",
"failed",
".",
"Mostly",
"the",
"same",
"as",
":",
"func",
":",
"flask",
".",
"debughelpers",
".",
"explain_template_loading_attempts",
"except",
"here",
"we",
"ve",
"extended",
"it",
"to",
"support",... | python | train | 37.783333 |
bhmm/bhmm | bhmm/hmm/generic_sampled_hmm.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L162-L167 | def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].eigenvectors_left
... | [
"def",
"eigenvectors_left_samples",
"(",
"self",
")",
":",
"res",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"nsamples",
",",
"self",
".",
"nstates",
",",
"self",
".",
"nstates",
")",
",",
"dtype",
"=",
"config",
".",
"dtype",
")",
"for",
"i",
... | r""" Samples of the left eigenvectors of the hidden transition matrix | [
"r",
"Samples",
"of",
"the",
"left",
"eigenvectors",
"of",
"the",
"hidden",
"transition",
"matrix"
] | python | train | 54.333333 |
mitodl/pylti | pylti/common.py | https://github.com/mitodl/pylti/blob/18a608282e0d5bc941beb2eaaeea3b7ad484b399/pylti/common.py#L473-L485 | def name(self): # pylint: disable=no-self-use
"""
Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user
"""
if 'lis_person_sourcedid' in self.session:
return self.session['lis_person_sourcedid']
elif 'lis_person_... | [
"def",
"name",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"if",
"'lis_person_sourcedid'",
"in",
"self",
".",
"session",
":",
"return",
"self",
".",
"session",
"[",
"'lis_person_sourcedid'",
"]",
"elif",
"'lis_person_contact_email_primary'",
"in",
"self",
... | Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user | [
"Name",
"returns",
"user",
"s",
"name",
"or",
"user",
"s",
"email",
"or",
"user_id",
":",
"return",
":",
"best",
"guess",
"of",
"name",
"to",
"use",
"to",
"greet",
"user"
] | python | train | 41.076923 |
johnnoone/facts | facts/grafts/system_grafts.py | https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L26-L33 | def os_info():
"""Returns os data.
"""
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
} | [
"def",
"os_info",
"(",
")",
":",
"return",
"{",
"'uname'",
":",
"dict",
"(",
"platform",
".",
"uname",
"(",
")",
".",
"_asdict",
"(",
")",
")",
",",
"'path'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"... | Returns os data. | [
"Returns",
"os",
"data",
"."
] | python | train | 27.125 |
xav-b/pyconsul | pyconsul/utils.py | https://github.com/xav-b/pyconsul/blob/06ce3b921d01010c19643424486bea4b22196076/pyconsul/utils.py#L25-L43 | def safe_request(fct):
''' Return json messages instead of raising errors '''
def inner(*args, **kwargs):
''' decorator '''
try:
_data = fct(*args, **kwargs)
except requests.exceptions.ConnectionError as error:
return {'error': str(error), 'status': 404}
... | [
"def",
"safe_request",
"(",
"fct",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"''' decorator '''",
"try",
":",
"_data",
"=",
"fct",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"requests",
".",
"exce... | Return json messages instead of raising errors | [
"Return",
"json",
"messages",
"instead",
"of",
"raising",
"errors"
] | python | train | 30.684211 |
shoyer/h5netcdf | h5netcdf/core.py | https://github.com/shoyer/h5netcdf/blob/3ae35cd58297281a1dc69c46fb0b315a0007ac2b/h5netcdf/core.py#L550-L575 | def resize_dimension(self, dimension, size):
"""
Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary.
"""
if self.dimensions[dimension] is not None:
raise ValueError("Dimension '%s' ... | [
"def",
"resize_dimension",
"(",
"self",
",",
"dimension",
",",
"size",
")",
":",
"if",
"self",
".",
"dimensions",
"[",
"dimension",
"]",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Dimension '%s' is not unlimited and thus \"",
"\"cannot be resized.\"",
... | Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary. | [
"Resize",
"a",
"dimension",
"to",
"a",
"certain",
"size",
"."
] | python | train | 37.346154 |
hobson/pug-dj | pug/dj/miner/views.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L126-L128 | def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"indent",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_json_response",
"(",
"self",
".",
"convert_context_to_json",
"(",
"context",
",",
"indent",
"=",
"indent",
")",
")"
] | Returns a JSON response containing 'context' as payload | [
"Returns",
"a",
"JSON",
"response",
"containing",
"context",
"as",
"payload"
] | python | train | 69 |
chrislit/abydos | abydos/stemmer/_snowball_dutch.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stemmer/_snowball_dutch.py#L52-L72 | def _undouble(self, word):
"""Undouble endings -kk, -dd, and -tt.
Parameters
----------
word : str
The word to stem
Returns
-------
str
The word with doubled endings undoubled
"""
if (
len(word) > 1
... | [
"def",
"_undouble",
"(",
"self",
",",
"word",
")",
":",
"if",
"(",
"len",
"(",
"word",
")",
">",
"1",
"and",
"word",
"[",
"-",
"1",
"]",
"==",
"word",
"[",
"-",
"2",
"]",
"and",
"word",
"[",
"-",
"1",
"]",
"in",
"{",
"'d'",
",",
"'k'",
",... | Undouble endings -kk, -dd, and -tt.
Parameters
----------
word : str
The word to stem
Returns
-------
str
The word with doubled endings undoubled | [
"Undouble",
"endings",
"-",
"kk",
"-",
"dd",
"and",
"-",
"tt",
"."
] | python | valid | 20.380952 |
SheffieldML/GPy | GPy/likelihoods/gaussian.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/likelihoods/gaussian.py#L316-L327 | def samples(self, gp, Y_metadata=None):
"""
Returns a set of samples of observations based on a given value of the latent variable.
:param gp: latent variable
"""
orig_shape = gp.shape
gp = gp.flatten()
#orig_shape = gp.shape
gp = gp.flatten()
Ysi... | [
"def",
"samples",
"(",
"self",
",",
"gp",
",",
"Y_metadata",
"=",
"None",
")",
":",
"orig_shape",
"=",
"gp",
".",
"shape",
"gp",
"=",
"gp",
".",
"flatten",
"(",
")",
"#orig_shape = gp.shape",
"gp",
"=",
"gp",
".",
"flatten",
"(",
")",
"Ysim",
"=",
... | Returns a set of samples of observations based on a given value of the latent variable.
:param gp: latent variable | [
"Returns",
"a",
"set",
"of",
"samples",
"of",
"observations",
"based",
"on",
"a",
"given",
"value",
"of",
"the",
"latent",
"variable",
"."
] | python | train | 38.25 |
ask/redish | redish/types.py | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/types.py#L322-L326 | def range_by_score(self, min, max, num=None, withscores=False):
"""Return all the elements with score >= min and score <= max
(a range query) from the sorted set."""
return self.client.zrangebyscore(self.name, min, max, num=num,
withscores=withscores) | [
"def",
"range_by_score",
"(",
"self",
",",
"min",
",",
"max",
",",
"num",
"=",
"None",
",",
"withscores",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"zrangebyscore",
"(",
"self",
".",
"name",
",",
"min",
",",
"max",
",",
"num",
"... | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. | [
"Return",
"all",
"the",
"elements",
"with",
"score",
">",
"=",
"min",
"and",
"score",
"<",
"=",
"max",
"(",
"a",
"range",
"query",
")",
"from",
"the",
"sorted",
"set",
"."
] | python | train | 62.4 |
push-things/wallabag_api | wallabag_api/wallabag.py | https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L118-L130 | def __get_attr(what, type_attr, value_attr, **kwargs):
"""
get the value of a parm
:param what: string parm
:param type_attr: type of parm
:param value_attr:
:param kwargs:
:return: value of the parm
"""
if what in kwargs:
value = int(k... | [
"def",
"__get_attr",
"(",
"what",
",",
"type_attr",
",",
"value_attr",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"what",
"in",
"kwargs",
":",
"value",
"=",
"int",
"(",
"kwargs",
"[",
"what",
"]",
")",
"if",
"type_attr",
"==",
"'int'",
"else",
"kwargs"... | get the value of a parm
:param what: string parm
:param type_attr: type of parm
:param value_attr:
:param kwargs:
:return: value of the parm | [
"get",
"the",
"value",
"of",
"a",
"parm",
":",
"param",
"what",
":",
"string",
"parm",
":",
"param",
"type_attr",
":",
"type",
"of",
"parm",
":",
"param",
"value_attr",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":",
"value",
"of",
"the",
"parm... | python | train | 32.692308 |
endeepak/pungi | pungi/matchers.py | https://github.com/endeepak/pungi/blob/4c90e0959f3498d0be85aa1e8e3ee4348be45593/pungi/matchers.py#L25-L29 | def message(self):
''' Override this to provide failure message'''
name = self.__class__.__name__
return "{0} {1}".format(humanize(name),
pp(*self.expectedArgs, **self.expectedKwArgs)) | [
"def",
"message",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"return",
"\"{0} {1}\"",
".",
"format",
"(",
"humanize",
"(",
"name",
")",
",",
"pp",
"(",
"*",
"self",
".",
"expectedArgs",
",",
"*",
"*",
"self",
".",
... | Override this to provide failure message | [
"Override",
"this",
"to",
"provide",
"failure",
"message"
] | python | train | 47.2 |
odlgroup/odl | odl/operator/pspace_ops.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L230-L283 | def _convert_to_spmatrix(operators):
"""Convert an array-like object of operators to a sparse matrix."""
# Lazy import to improve `import odl` time
import scipy.sparse
# Convert ops to sparse representation. This is not trivial because
# operators can be indexable themselves and... | [
"def",
"_convert_to_spmatrix",
"(",
"operators",
")",
":",
"# Lazy import to improve `import odl` time",
"import",
"scipy",
".",
"sparse",
"# Convert ops to sparse representation. This is not trivial because",
"# operators can be indexable themselves and give the wrong impression",
"# of a... | Convert an array-like object of operators to a sparse matrix. | [
"Convert",
"an",
"array",
"-",
"like",
"object",
"of",
"operators",
"to",
"a",
"sparse",
"matrix",
"."
] | python | train | 42.907407 |
Nic30/hwt | hwt/serializer/systemC/statements.py | https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/serializer/systemC/statements.py#L43-L58 | def HWProcess(cls, proc, ctx):
"""
Serialize HWProcess instance
:param scope: name scope to prevent name collisions
"""
body = proc.statements
childCtx = ctx.withIndent()
statemets = [cls.asHdl(s, childCtx) for s in body]
proc.name = ctx.scope.checkedName... | [
"def",
"HWProcess",
"(",
"cls",
",",
"proc",
",",
"ctx",
")",
":",
"body",
"=",
"proc",
".",
"statements",
"childCtx",
"=",
"ctx",
".",
"withIndent",
"(",
")",
"statemets",
"=",
"[",
"cls",
".",
"asHdl",
"(",
"s",
",",
"childCtx",
")",
"for",
"s",
... | Serialize HWProcess instance
:param scope: name scope to prevent name collisions | [
"Serialize",
"HWProcess",
"instance"
] | python | test | 29.625 |
knipknap/exscript | Exscript/account.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L508-L518 | def get_account_from_name(self, name):
"""
Returns the account with the given name.
:type name: string
:param name: The name of the account.
"""
for account in self.accounts:
if account.get_name() == name:
return account
return None | [
"def",
"get_account_from_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"account",
"in",
"self",
".",
"accounts",
":",
"if",
"account",
".",
"get_name",
"(",
")",
"==",
"name",
":",
"return",
"account",
"return",
"None"
] | Returns the account with the given name.
:type name: string
:param name: The name of the account. | [
"Returns",
"the",
"account",
"with",
"the",
"given",
"name",
"."
] | python | train | 28 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.