repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
Yubico/python-pyhsm | pyhsm/base.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/base.py#L505-L522 | def aes_ecb_encrypt(self, key_handle, plaintext):
"""
AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@t... | [
"def",
"aes_ecb_encrypt",
"(",
"self",
",",
"key_handle",
",",
"plaintext",
")",
":",
"return",
"pyhsm",
".",
"aes_ecb_cmd",
".",
"YHSM_Cmd_AES_ECB_Encrypt",
"(",
"self",
".",
"stick",
",",
"key_handle",
",",
"plaintext",
")",
".",
"execute",
"(",
")"
] | AES ECB encrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB encryption
@param plaintext: Data to encrypt
@type key_handle: integer or string
@type plaintext: string
... | [
"AES",
"ECB",
"encrypt",
"using",
"a",
"key",
"handle",
"."
] | python | train |
bwohlberg/sporco | sporco/admm/ccmod.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmod.py#L806-L819 | def xistep(self, i):
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`
component :math:`\mathbf{x}_i`.
"""
self.YU[:] = self.Y - self.U[..., i]
b = np.take(self.ZSf, [i], axis=self.cri.axisK) + \
self.rho*sl.rfftn(self.YU, None, self.cri.axisN)
... | [
"def",
"xistep",
"(",
"self",
",",
"i",
")",
":",
"self",
".",
"YU",
"[",
":",
"]",
"=",
"self",
".",
"Y",
"-",
"self",
".",
"U",
"[",
"...",
",",
"i",
"]",
"b",
"=",
"np",
".",
"take",
"(",
"self",
".",
"ZSf",
",",
"[",
"i",
"]",
",",
... | r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`
component :math:`\mathbf{x}_i`. | [
"r",
"Minimise",
"Augmented",
"Lagrangian",
"with",
"respect",
"to",
":",
"math",
":",
"\\",
"mathbf",
"{",
"x",
"}",
"component",
":",
"math",
":",
"\\",
"mathbf",
"{",
"x",
"}",
"_i",
"."
] | python | train |
celliern/triflow | triflow/core/fields.py | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/fields.py#L80-L105 | def factory1D(dependent_variables,
helper_functions):
"""Fields factory generating specialized container build around a
triflow Model and xarray.
Wrapper for 1D data.
Parameters
----------
dependent_variables : iterable for str
n... | [
"def",
"factory1D",
"(",
"dependent_variables",
",",
"helper_functions",
")",
":",
"return",
"BaseFields",
".",
"factory",
"(",
"(",
"\"x\"",
",",
")",
",",
"[",
"(",
"name",
",",
"(",
"\"x\"",
",",
")",
")",
"for",
"name",
"in",
"dependent_variables",
"... | Fields factory generating specialized container build around a
triflow Model and xarray.
Wrapper for 1D data.
Parameters
----------
dependent_variables : iterable for str
name of the dependent variables
helper_functions : iterable of str
... | [
"Fields",
"factory",
"generating",
"specialized",
"container",
"build",
"around",
"a",
"triflow",
"Model",
"and",
"xarray",
".",
"Wrapper",
"for",
"1D",
"data",
"."
] | python | train |
sernst/cauldron | cauldron/cli/threads.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/threads.py#L51-L83 | def run(self):
"""
Executes the Cauldron command in a thread to prevent long-running
computations from locking the main Cauldron thread, which is needed
to serve and print status information.
"""
async def run_command():
try:
self.result = sel... | [
"def",
"run",
"(",
"self",
")",
":",
"async",
"def",
"run_command",
"(",
")",
":",
"try",
":",
"self",
".",
"result",
"=",
"self",
".",
"command",
"(",
"context",
"=",
"self",
".",
"context",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"except",
"... | Executes the Cauldron command in a thread to prevent long-running
computations from locking the main Cauldron thread, which is needed
to serve and print status information. | [
"Executes",
"the",
"Cauldron",
"command",
"in",
"a",
"thread",
"to",
"prevent",
"long",
"-",
"running",
"computations",
"from",
"locking",
"the",
"main",
"Cauldron",
"thread",
"which",
"is",
"needed",
"to",
"serve",
"and",
"print",
"status",
"information",
"."... | python | train |
nilp0inter/cpe | cpe/cpe2_3_uri.py | https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_uri.py#L254-L343 | def _parse(self):
"""
Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name
"""
# CPE Name must not have whitespaces
if (self._str.find(" ") != -1):
msg = "Bad-formed CPE Name: it must not have whitespaces"
... | [
"def",
"_parse",
"(",
"self",
")",
":",
"# CPE Name must not have whitespaces",
"if",
"(",
"self",
".",
"_str",
".",
"find",
"(",
"\" \"",
")",
"!=",
"-",
"1",
")",
":",
"msg",
"=",
"\"Bad-formed CPE Name: it must not have whitespaces\"",
"raise",
"ValueError",
... | Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name | [
"Checks",
"if",
"the",
"CPE",
"Name",
"is",
"valid",
"."
] | python | train |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1084-L1114 | def _is_axis_allowed(self, axis):
"""Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases.
"""
if axis is None:
# If table direction was requested, we must ensure that each slice
... | [
"def",
"_is_axis_allowed",
"(",
"self",
",",
"axis",
")",
":",
"if",
"axis",
"is",
"None",
":",
"# If table direction was requested, we must ensure that each slice",
"# doesn't have the CA items dimension (thus the [-2:] part). It's",
"# OK for the 0th dimension to be items, since no c... | Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases. | [
"Check",
"if",
"axis",
"are",
"allowed",
"."
] | python | train |
albertz/py_better_exchook | better_exchook.py | https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L1405-L1431 | def _StackSummary_extract(frame_gen, limit=None, lookup_lines=True, capture_locals=False):
"""
Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is... | [
"def",
"_StackSummary_extract",
"(",
"frame_gen",
",",
"limit",
"=",
"None",
",",
"lookup_lines",
"=",
"True",
",",
"capture_locals",
"=",
"False",
")",
":",
"result",
"=",
"StackSummary",
"(",
")",
"for",
"f",
",",
"lineno",
"in",
"frame_gen",
":",
"co",
... | Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is why we overwrite it.
Additionally, we also capture the frame.
This is a bit hacky and also not... | [
"Replacement",
"for",
":",
"func",
":",
"StackSummary",
".",
"extract",
"."
] | python | train |
contentful/contentful-management.py | contentful_management/content_type_field_validation.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type_field_validation.py#L28-L36 | def to_json(self):
"""
Returns the JSON Representation of the content type field validation.
"""
result = {}
for k, v in self._data.items():
result[camel_case(k)] = v
return result | [
"def",
"to_json",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_data",
".",
"items",
"(",
")",
":",
"result",
"[",
"camel_case",
"(",
"k",
")",
"]",
"=",
"v",
"return",
"result"
] | Returns the JSON Representation of the content type field validation. | [
"Returns",
"the",
"JSON",
"Representation",
"of",
"the",
"content",
"type",
"field",
"validation",
"."
] | python | train |
helixyte/everest | everest/traversal.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/traversal.py#L125-L139 | def get_matching(self, source_id):
"""
Returns a matching target object for the given source ID.
"""
value = self._accessor.get_by_id(source_id)
if not value is None:
reg = get_current_registry()
prx_fac = reg.getUtility(IDataTraversalProxyFactory)
... | [
"def",
"get_matching",
"(",
"self",
",",
"source_id",
")",
":",
"value",
"=",
"self",
".",
"_accessor",
".",
"get_by_id",
"(",
"source_id",
")",
"if",
"not",
"value",
"is",
"None",
":",
"reg",
"=",
"get_current_registry",
"(",
")",
"prx_fac",
"=",
"reg",... | Returns a matching target object for the given source ID. | [
"Returns",
"a",
"matching",
"target",
"object",
"for",
"the",
"given",
"source",
"ID",
"."
] | python | train |
jkwill87/mapi | mapi/endpoints.py | https://github.com/jkwill87/mapi/blob/730bf57c12aecaf49e18c15bf2b35af7f554b3cc/mapi/endpoints.py#L69-L78 | def _clean_dict(target_dict, whitelist=None):
""" Convenience function that removes a dicts keys that have falsy values
"""
assert isinstance(target_dict, dict)
return {
ustr(k).strip(): ustr(v).strip()
for k, v in target_dict.items()
if v not in (None, Ellipsis, [], (), "")
... | [
"def",
"_clean_dict",
"(",
"target_dict",
",",
"whitelist",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"target_dict",
",",
"dict",
")",
"return",
"{",
"ustr",
"(",
"k",
")",
".",
"strip",
"(",
")",
":",
"ustr",
"(",
"v",
")",
".",
"strip",
... | Convenience function that removes a dicts keys that have falsy values | [
"Convenience",
"function",
"that",
"removes",
"a",
"dicts",
"keys",
"that",
"have",
"falsy",
"values"
] | python | train |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/injector.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/injector.py#L706-L732 | def remove(self):
"""
remove this component from Ariane server cache, stop the on demand refresh and actor linked to this component
:return:
"""
LOGGER.debug("InjectorCachedComponent.remove")
ret = True
args = {'properties': {'OPERATION': 'DEL_COMPONENT_FROM_CACHE... | [
"def",
"remove",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"InjectorCachedComponent.remove\"",
")",
"ret",
"=",
"True",
"args",
"=",
"{",
"'properties'",
":",
"{",
"'OPERATION'",
":",
"'DEL_COMPONENT_FROM_CACHE'",
",",
"'REMOTE_COMPONENT'",
":",
"str... | remove this component from Ariane server cache, stop the on demand refresh and actor linked to this component
:return: | [
"remove",
"this",
"component",
"from",
"Ariane",
"server",
"cache",
"stop",
"the",
"on",
"demand",
"refresh",
"and",
"actor",
"linked",
"to",
"this",
"component",
":",
"return",
":"
] | python | train |
noirbizarre/django-eztables | eztables/views.py | https://github.com/noirbizarre/django-eztables/blob/347e74dcc08121d20f4cf942181d873dbe33b995/eztables/views.py#L126-L144 | def global_search(self, queryset):
'''Filter a queryset with global search'''
search = self.dt_data['sSearch']
if search:
if self.dt_data['bRegex']:
criterions = [
Q(**{'%s__iregex' % field: search})
for field in self.get_db_fie... | [
"def",
"global_search",
"(",
"self",
",",
"queryset",
")",
":",
"search",
"=",
"self",
".",
"dt_data",
"[",
"'sSearch'",
"]",
"if",
"search",
":",
"if",
"self",
".",
"dt_data",
"[",
"'bRegex'",
"]",
":",
"criterions",
"=",
"[",
"Q",
"(",
"*",
"*",
... | Filter a queryset with global search | [
"Filter",
"a",
"queryset",
"with",
"global",
"search"
] | python | train |
ejeschke/ginga | ginga/rv/plugins/SaveImage.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L329-L370 | def _write_history(self, pfx, hdu, linechar=60, indentchar=2):
"""Write change history to given HDU header.
Limit each HISTORY line to given number of characters.
Subsequent lines of the same history will be indented.
"""
channel = self.fv.get_channel(self.chname)
if chan... | [
"def",
"_write_history",
"(",
"self",
",",
"pfx",
",",
"hdu",
",",
"linechar",
"=",
"60",
",",
"indentchar",
"=",
"2",
")",
":",
"channel",
"=",
"self",
".",
"fv",
".",
"get_channel",
"(",
"self",
".",
"chname",
")",
"if",
"channel",
"is",
"None",
... | Write change history to given HDU header.
Limit each HISTORY line to given number of characters.
Subsequent lines of the same history will be indented. | [
"Write",
"change",
"history",
"to",
"given",
"HDU",
"header",
".",
"Limit",
"each",
"HISTORY",
"line",
"to",
"given",
"number",
"of",
"characters",
".",
"Subsequent",
"lines",
"of",
"the",
"same",
"history",
"will",
"be",
"indented",
"."
] | python | train |
matthewdeanmartin/find_known_secrets | build.py | https://github.com/matthewdeanmartin/find_known_secrets/blob/f25735c1ab4512bad85ade33af7021f6fac1d13b/build.py#L332-L351 | def dead_code():
"""
This also finds code you are working on today!
"""
with safe_cd(SRC):
if IS_TRAVIS:
command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split()
else:
command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split()
... | [
"def",
"dead_code",
"(",
")",
":",
"with",
"safe_cd",
"(",
"SRC",
")",
":",
"if",
"IS_TRAVIS",
":",
"command",
"=",
"\"{0} vulture {1}\"",
".",
"format",
"(",
"PYTHON",
",",
"PROJECT_NAME",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"else",
... | This also finds code you are working on today! | [
"This",
"also",
"finds",
"code",
"you",
"are",
"working",
"on",
"today!"
] | python | test |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1295-L1299 | def group_memberships_assignable(self, group_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/group_memberships#list-assignable-memberships"
api_path = "/api/v2/groups/{group_id}/memberships/assignable.json"
api_path = api_path.format(group_id=group_id)
return self.call(a... | [
"def",
"group_memberships_assignable",
"(",
"self",
",",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/groups/{group_id}/memberships/assignable.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"group_id",
"=",
"group_id",
")",
"... | https://developer.zendesk.com/rest_api/docs/core/group_memberships#list-assignable-memberships | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"group_memberships#list",
"-",
"assignable",
"-",
"memberships"
] | python | train |
jwodder/doapi | doapi/doapi.py | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/doapi.py#L493-L522 | def wait_actions(self, actions, wait_interval=None, wait_time=None):
r"""
Poll the server periodically until all actions in ``actions`` have
either completed or errored out, yielding each `Action`'s final value
as it ends.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (cont... | [
"def",
"wait_actions",
"(",
"self",
",",
"actions",
",",
"wait_interval",
"=",
"None",
",",
"wait_time",
"=",
"None",
")",
":",
"return",
"self",
".",
"_wait",
"(",
"map",
"(",
"self",
".",
"_action",
",",
"actions",
")",
",",
"\"done\"",
",",
"True",
... | r"""
Poll the server periodically until all actions in ``actions`` have
either completed or errored out, yielding each `Action`'s final value
as it ends.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any
remaining in-progress actions) is raised.
If a `K... | [
"r",
"Poll",
"the",
"server",
"periodically",
"until",
"all",
"actions",
"in",
"actions",
"have",
"either",
"completed",
"or",
"errored",
"out",
"yielding",
"each",
"Action",
"s",
"final",
"value",
"as",
"it",
"ends",
"."
] | python | train |
metagriffin/globre | globre/__init__.py | https://github.com/metagriffin/globre/blob/d4b0ffb352b0b7d5e221d2357d4094e390d4fbeb/globre/__init__.py#L120-L216 | def compile(pattern, flags=0, sep=None, split_prefix=False):
'''
Converts a glob-matching pattern (using Apache Cocoon style rules)
to a regular expression, which basically means that the following
characters have special meanings:
* ``?``: matches any single character excluding the separator character
... | [
"def",
"compile",
"(",
"pattern",
",",
"flags",
"=",
"0",
",",
"sep",
"=",
"None",
",",
"split_prefix",
"=",
"False",
")",
":",
"prefix",
"=",
"None",
"expr",
"=",
"''",
"if",
"sep",
"is",
"None",
":",
"sep",
"=",
"'/'",
"if",
"not",
"sep",
":",
... | Converts a glob-matching pattern (using Apache Cocoon style rules)
to a regular expression, which basically means that the following
characters have special meanings:
* ``?``: matches any single character excluding the separator character
* ``*``: matches zero or more characters excluding the separator... | [
"Converts",
"a",
"glob",
"-",
"matching",
"pattern",
"(",
"using",
"Apache",
"Cocoon",
"style",
"rules",
")",
"to",
"a",
"regular",
"expression",
"which",
"basically",
"means",
"that",
"the",
"following",
"characters",
"have",
"special",
"meanings",
":"
] | python | train |
divio/aldryn-apphooks-config | aldryn_apphooks_config/utils.py | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/utils.py#L88-L96 | def get_apphook_configs(obj):
"""
Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj
"""
keys = get_apphook_field_names(obj)
return [getattr(obj, key) for key in keys] if keys else [] | [
"def",
"get_apphook_configs",
"(",
"obj",
")",
":",
"keys",
"=",
"get_apphook_field_names",
"(",
"obj",
")",
"return",
"[",
"getattr",
"(",
"obj",
",",
"key",
")",
"for",
"key",
"in",
"keys",
"]",
"if",
"keys",
"else",
"[",
"]"
] | Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj | [
"Get",
"apphook",
"configs",
"for",
"an",
"object",
"obj"
] | python | train |
square/connect-python-sdk | squareconnect/models/catalog_query_range.py | https://github.com/square/connect-python-sdk/blob/adc1d09e817986cdc607391580f71d6b48ed4066/squareconnect/models/catalog_query_range.py#L67-L81 | def attribute_name(self, attribute_name):
"""
Sets the attribute_name of this CatalogQueryRange.
The name of the attribute to be searched.
:param attribute_name: The attribute_name of this CatalogQueryRange.
:type: str
"""
if attribute_name is None:
... | [
"def",
"attribute_name",
"(",
"self",
",",
"attribute_name",
")",
":",
"if",
"attribute_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `attribute_name`, must not be `None`\"",
")",
"if",
"len",
"(",
"attribute_name",
")",
"<",
"1",
":",
... | Sets the attribute_name of this CatalogQueryRange.
The name of the attribute to be searched.
:param attribute_name: The attribute_name of this CatalogQueryRange.
:type: str | [
"Sets",
"the",
"attribute_name",
"of",
"this",
"CatalogQueryRange",
".",
"The",
"name",
"of",
"the",
"attribute",
"to",
"be",
"searched",
"."
] | python | train |
Opentrons/opentrons | api/src/opentrons/server/endpoints/control.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/control.py#L385-L416 | def _move_mount(robot, mount, point):
"""
The carriage moves the mount in the Z axis, and the gantry moves in X and Y
Mount movements do not have the same protections calculated in to an
existing `move` command like Pipette does, so the safest thing is to home
the Z axis, then move in X and Y, then... | [
"def",
"_move_mount",
"(",
"robot",
",",
"mount",
",",
"point",
")",
":",
"carriage",
"=",
"robot",
".",
"_actuators",
"[",
"mount",
"]",
"[",
"'carriage'",
"]",
"# Home both carriages, to prevent collisions and to ensure that the other",
"# mount doesn't block the one be... | The carriage moves the mount in the Z axis, and the gantry moves in X and Y
Mount movements do not have the same protections calculated in to an
existing `move` command like Pipette does, so the safest thing is to home
the Z axis, then move in X and Y, then move down to the specified Z height | [
"The",
"carriage",
"moves",
"the",
"mount",
"in",
"the",
"Z",
"axis",
"and",
"the",
"gantry",
"moves",
"in",
"X",
"and",
"Y"
] | python | train |
gitpython-developers/GitPython | git/remote.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/remote.py#L813-L843 | def push(self, refspec=None, progress=None, **kwargs):
"""Push changes from source branch in refspec to target branch in refspec.
:param refspec: see 'fetch' method
:param progress:
Can take one of many value types:
* None to discard progress information
* A... | [
"def",
"push",
"(",
"self",
",",
"refspec",
"=",
"None",
",",
"progress",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"add_progress",
"(",
"kwargs",
",",
"self",
".",
"repo",
".",
"git",
",",
"progress",
")",
"proc",
"=",
"self",... | Push changes from source branch in refspec to target branch in refspec.
:param refspec: see 'fetch' method
:param progress:
Can take one of many value types:
* None to discard progress information
* A function (callable) that is called with the progress information.... | [
"Push",
"changes",
"from",
"source",
"branch",
"in",
"refspec",
"to",
"target",
"branch",
"in",
"refspec",
"."
] | python | train |
xapple/plumbing | plumbing/common.py | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L472-L492 | def prepend_to_file(path, data, bufsize=1<<15):
"""TODO:
* Add a random string to the backup file.
* Restore permissions after copy.
"""
# Backup the file #
backupname = path + os.extsep + 'bak'
# Remove previous backup if it exists #
try: os.unlink(backupname)
except OSError: pass
... | [
"def",
"prepend_to_file",
"(",
"path",
",",
"data",
",",
"bufsize",
"=",
"1",
"<<",
"15",
")",
":",
"# Backup the file #",
"backupname",
"=",
"path",
"+",
"os",
".",
"extsep",
"+",
"'bak'",
"# Remove previous backup if it exists #",
"try",
":",
"os",
".",
"u... | TODO:
* Add a random string to the backup file.
* Restore permissions after copy. | [
"TODO",
":",
"*",
"Add",
"a",
"random",
"string",
"to",
"the",
"backup",
"file",
".",
"*",
"Restore",
"permissions",
"after",
"copy",
"."
] | python | train |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd1xx.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd1xx.py#L196-L274 | def authors2marc(self, key, value):
"""Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects.
"""
value = force_list(value)
def _get_ids(value):
ids = {
'i': [],
'j': [],
}
if value.get('ids'):
... | [
"def",
"authors2marc",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"value",
"=",
"force_list",
"(",
"value",
")",
"def",
"_get_ids",
"(",
"value",
")",
":",
"ids",
"=",
"{",
"'i'",
":",
"[",
"]",
",",
"'j'",
":",
"[",
"]",
",",
"}",
"if",
... | Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects. | [
"Populate",
"the",
"100",
"MARC",
"field",
"."
] | python | train |
mikicz/arca | arca/_arca.py | https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/_arca.py#L334-L344 | def get_repo(self, repo: str, branch: str, *,
depth: Optional[int]=1,
reference: Optional[Path]=None
) -> Repo:
""" Returns a :class:`Repo <git.repo.base.Repo>` instance for the branch.
See :meth:`run` for arguments descriptions.
"""
gi... | [
"def",
"get_repo",
"(",
"self",
",",
"repo",
":",
"str",
",",
"branch",
":",
"str",
",",
"*",
",",
"depth",
":",
"Optional",
"[",
"int",
"]",
"=",
"1",
",",
"reference",
":",
"Optional",
"[",
"Path",
"]",
"=",
"None",
")",
"->",
"Repo",
":",
"g... | Returns a :class:`Repo <git.repo.base.Repo>` instance for the branch.
See :meth:`run` for arguments descriptions. | [
"Returns",
"a",
":",
"class",
":",
"Repo",
"<git",
".",
"repo",
".",
"base",
".",
"Repo",
">",
"instance",
"for",
"the",
"branch",
"."
] | python | train |
martinkosir/neverbounce-python | neverbounce/client.py | https://github.com/martinkosir/neverbounce-python/blob/8d8b3f381dbff2a753a8770fac0d2bfab80d5bec/neverbounce/client.py#L125-L148 | def _handle_response(response):
"""
Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails.
"""
if not response.ok:
ra... | [
"def",
"_handle_response",
"(",
"response",
")",
":",
"if",
"not",
"response",
".",
"ok",
":",
"raise",
"NeverBounceAPIError",
"(",
"response",
")",
"if",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
"==",
"'application/octet-stream'",
"... | Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails. | [
"Handle",
"the",
"response",
"and",
"possible",
"failures",
".",
":",
"param",
"Response",
"response",
":",
"Response",
"data",
".",
":",
"return",
":",
"A",
"dictionary",
"or",
"a",
"string",
"with",
"response",
"data",
".",
":",
"raises",
":",
"NeverBoun... | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/feature_management/feature_management_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/feature_management/feature_management_client.py#L43-L56 | def get_features(self, target_contribution_id=None):
"""GetFeatures.
[Preview API] Get a list of all defined features
:param str target_contribution_id: Optional target contribution. If null/empty, return all features. If specified include the features that target the specified contribution.
... | [
"def",
"get_features",
"(",
"self",
",",
"target_contribution_id",
"=",
"None",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"target_contribution_id",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'targetContributionId'",
"]",
"=",
"self",
".",
"_ser... | GetFeatures.
[Preview API] Get a list of all defined features
:param str target_contribution_id: Optional target contribution. If null/empty, return all features. If specified include the features that target the specified contribution.
:rtype: [ContributedFeature] | [
"GetFeatures",
".",
"[",
"Preview",
"API",
"]",
"Get",
"a",
"list",
"of",
"all",
"defined",
"features",
":",
"param",
"str",
"target_contribution_id",
":",
"Optional",
"target",
"contribution",
".",
"If",
"null",
"/",
"empty",
"return",
"all",
"features",
".... | python | train |
dj-stripe/dj-stripe | djstripe/checks.py | https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/checks.py#L126-L144 | def check_webhook_secret(app_configs=None, **kwargs):
"""
Check that DJSTRIPE_WEBHOOK_SECRET looks correct
"""
from . import settings as djstripe_settings
messages = []
secret = djstripe_settings.WEBHOOK_SECRET
if secret and not secret.startswith("whsec_"):
messages.append(
checks.Warning(
"DJSTRIPE_W... | [
"def",
"check_webhook_secret",
"(",
"app_configs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"settings",
"as",
"djstripe_settings",
"messages",
"=",
"[",
"]",
"secret",
"=",
"djstripe_settings",
".",
"WEBHOOK_SECRET",
"if",
"secret... | Check that DJSTRIPE_WEBHOOK_SECRET looks correct | [
"Check",
"that",
"DJSTRIPE_WEBHOOK_SECRET",
"looks",
"correct"
] | python | train |
theolind/pymysensors | mysensors/sensor.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/sensor.py#L157-L165 | def get_schema(self, protocol_version):
"""Return the child schema for the correct const version."""
const = get_const(protocol_version)
custom_schema = vol.Schema({
typ.value: const.VALID_SETREQ[typ]
for typ in const.VALID_TYPES[const.Presentation.S_CUSTOM]})
ret... | [
"def",
"get_schema",
"(",
"self",
",",
"protocol_version",
")",
":",
"const",
"=",
"get_const",
"(",
"protocol_version",
")",
"custom_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"typ",
".",
"value",
":",
"const",
".",
"VALID_SETREQ",
"[",
"typ",
"]",
"... | Return the child schema for the correct const version. | [
"Return",
"the",
"child",
"schema",
"for",
"the",
"correct",
"const",
"version",
"."
] | python | train |
xiaocong/uiautomator | uiautomator/__init__.py | https://github.com/xiaocong/uiautomator/blob/9a0c892ffd056713f91aa2153d1533c5b0553a1c/uiautomator/__init__.py#L912-L929 | def click(self):
'''
click on the ui object.
Usage:
d(text="Clock").click() # click on the center of the ui object
d(text="OK").click.wait(timeout=3000) # click and wait for the new window update
d(text="John").click.topleft() # click on the topleft of the ui object
... | [
"def",
"click",
"(",
"self",
")",
":",
"@",
"param_to_property",
"(",
"action",
"=",
"[",
"\"tl\"",
",",
"\"topleft\"",
",",
"\"br\"",
",",
"\"bottomright\"",
",",
"\"wait\"",
"]",
")",
"def",
"_click",
"(",
"action",
"=",
"None",
",",
"timeout",
"=",
... | click on the ui object.
Usage:
d(text="Clock").click() # click on the center of the ui object
d(text="OK").click.wait(timeout=3000) # click and wait for the new window update
d(text="John").click.topleft() # click on the topleft of the ui object
d(text="John").click.bottomright(... | [
"click",
"on",
"the",
"ui",
"object",
".",
"Usage",
":",
"d",
"(",
"text",
"=",
"Clock",
")",
".",
"click",
"()",
"#",
"click",
"on",
"the",
"center",
"of",
"the",
"ui",
"object",
"d",
"(",
"text",
"=",
"OK",
")",
".",
"click",
".",
"wait",
"("... | python | train |
dpkp/kafka-python | kafka/coordinator/base.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/coordinator/base.py#L650-L671 | def _send_group_coordinator_request(self):
"""Discover the current coordinator for the group.
Returns:
Future: resolves to the node id of the coordinator
"""
node_id = self._client.least_loaded_node()
if node_id is None:
return Future().failure(Errors.NoB... | [
"def",
"_send_group_coordinator_request",
"(",
"self",
")",
":",
"node_id",
"=",
"self",
".",
"_client",
".",
"least_loaded_node",
"(",
")",
"if",
"node_id",
"is",
"None",
":",
"return",
"Future",
"(",
")",
".",
"failure",
"(",
"Errors",
".",
"NoBrokersAvail... | Discover the current coordinator for the group.
Returns:
Future: resolves to the node id of the coordinator | [
"Discover",
"the",
"current",
"coordinator",
"for",
"the",
"group",
"."
] | python | train |
glomex/gcdt | gcdt/iam.py | https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/iam.py#L138-L188 | def build_role(self, name, policies=False):
"""
Generate role for IAM cloudformation template
:param name: Name of role
:param policies: List of policies to attach to this role (False = none)
:return: Ref to new role
"""
# Build role template
if policies:
... | [
"def",
"build_role",
"(",
"self",
",",
"name",
",",
"policies",
"=",
"False",
")",
":",
"# Build role template",
"if",
"policies",
":",
"role",
"=",
"self",
".",
"__template",
".",
"add_resource",
"(",
"Role",
"(",
"self",
".",
"name_strip",
"(",
"name",
... | Generate role for IAM cloudformation template
:param name: Name of role
:param policies: List of policies to attach to this role (False = none)
:return: Ref to new role | [
"Generate",
"role",
"for",
"IAM",
"cloudformation",
"template",
":",
"param",
"name",
":",
"Name",
"of",
"role",
":",
"param",
"policies",
":",
"List",
"of",
"policies",
"to",
"attach",
"to",
"this",
"role",
"(",
"False",
"=",
"none",
")",
":",
"return",... | python | train |
PokeAPI/pokebase | pokebase/common.py | https://github.com/PokeAPI/pokebase/blob/e7d695662037811f3956ed4ea817ffee70b12e33/pokebase/common.py#L72-L80 | def sprite_filepath_build(sprite_type, sprite_id, **kwargs):
"""returns the filepath of the sprite *relative to SPRITE_CACHE*"""
options = parse_sprite_options(sprite_type, **kwargs)
filename = '.'.join([str(sprite_id), SPRITE_EXT])
filepath = os.path.join(sprite_type, *options, filename)
return ... | [
"def",
"sprite_filepath_build",
"(",
"sprite_type",
",",
"sprite_id",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"parse_sprite_options",
"(",
"sprite_type",
",",
"*",
"*",
"kwargs",
")",
"filename",
"=",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
... | returns the filepath of the sprite *relative to SPRITE_CACHE* | [
"returns",
"the",
"filepath",
"of",
"the",
"sprite",
"*",
"relative",
"to",
"SPRITE_CACHE",
"*"
] | python | train |
mazulo/pynews_cli | pynews/utils.py | https://github.com/mazulo/pynews_cli/blob/88a6d70e18b9d8ea87ab7321a3d7ee78c4fa5ffb/pynews/utils.py#L40-L53 | def get_story(new):
"""Return a story of the given ID."""
url = URLS['item'].format(new)
try:
data = req.get(url)
except req.ConnectionError:
raise
except req.Timeout:
raise req.Timeout('A timeout problem occurred.')
except req.TooManyRedirects:
raise req.TooManyR... | [
"def",
"get_story",
"(",
"new",
")",
":",
"url",
"=",
"URLS",
"[",
"'item'",
"]",
".",
"format",
"(",
"new",
")",
"try",
":",
"data",
"=",
"req",
".",
"get",
"(",
"url",
")",
"except",
"req",
".",
"ConnectionError",
":",
"raise",
"except",
"req",
... | Return a story of the given ID. | [
"Return",
"a",
"story",
"of",
"the",
"given",
"ID",
"."
] | python | train |
aouyar/PyMunin | pymunin/__init__.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/__init__.py#L171-L184 | def _getGraph(self, graph_name, fail_noexist=False):
"""Private method for returning graph object with name graph_name.
@param graph_name: Graph Name
@param fail_noexist: If true throw exception if there is no graph with
name graph_name.
@return: ... | [
"def",
"_getGraph",
"(",
"self",
",",
"graph_name",
",",
"fail_noexist",
"=",
"False",
")",
":",
"graph",
"=",
"self",
".",
"_graphDict",
".",
"get",
"(",
"graph_name",
")",
"if",
"fail_noexist",
"and",
"graph",
"is",
"None",
":",
"raise",
"AttributeError"... | Private method for returning graph object with name graph_name.
@param graph_name: Graph Name
@param fail_noexist: If true throw exception if there is no graph with
name graph_name.
@return: Graph Object or None | [
"Private",
"method",
"for",
"returning",
"graph",
"object",
"with",
"name",
"graph_name",
"."
] | python | train |
AtteqCom/zsl | src/zsl/task/task_decorator.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L342-L356 | def xml_output(f):
"""
Set content-type for response to WEB-REQUEST to 'text/xml'
"""
@wraps(f)
def xml_output_inner_fn(*args, **kwargs):
ret_val = f(*args, **kwargs)
if isinstance(JobContext.get_current_context(), WebJobContext):
JobContext.get_current_context().add_re... | [
"def",
"xml_output",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"xml_output_inner_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret_val",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",... | Set content-type for response to WEB-REQUEST to 'text/xml' | [
"Set",
"content",
"-",
"type",
"for",
"response",
"to",
"WEB",
"-",
"REQUEST",
"to",
"text",
"/",
"xml"
] | python | train |
kisom/pypcapfile | pcapfile/protocols/linklayer/wifi.py | https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/protocols/linklayer/wifi.py#L1569-L1581 | def strip_ccmp(self, idx):
"""strip(8 byte) wlan.ccmp.extiv
CCMP Extended Initialization Vector
:return: int
number of processed bytes
:return: ctypes.raw
ccmp vector
"""
ccmp_extiv = None
if len(self._packet[idx:]) >= 8:
raw_by... | [
"def",
"strip_ccmp",
"(",
"self",
",",
"idx",
")",
":",
"ccmp_extiv",
"=",
"None",
"if",
"len",
"(",
"self",
".",
"_packet",
"[",
"idx",
":",
"]",
")",
">=",
"8",
":",
"raw_bytes",
"=",
"self",
".",
"_packet",
"[",
"idx",
":",
"idx",
"+",
"8",
... | strip(8 byte) wlan.ccmp.extiv
CCMP Extended Initialization Vector
:return: int
number of processed bytes
:return: ctypes.raw
ccmp vector | [
"strip",
"(",
"8",
"byte",
")",
"wlan",
".",
"ccmp",
".",
"extiv",
"CCMP",
"Extended",
"Initialization",
"Vector",
":",
"return",
":",
"int",
"number",
"of",
"processed",
"bytes",
":",
"return",
":",
"ctypes",
".",
"raw",
"ccmp",
"vector"
] | python | valid |
spyder-ide/spyder | spyder/plugins/editor/lsp/transport/main.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/lsp/transport/main.py#L62-L76 | def logger_init(level):
"""
Initialize the logger for this thread.
Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3),
depending on the argument `level`.
"""
levellist = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
handler = logging.StreamHandler()
fmt... | [
"def",
"logger_init",
"(",
"level",
")",
":",
"levellist",
"=",
"[",
"logging",
".",
"ERROR",
",",
"logging",
".",
"WARNING",
",",
"logging",
".",
"INFO",
",",
"logging",
".",
"DEBUG",
"]",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"fm... | Initialize the logger for this thread.
Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3),
depending on the argument `level`. | [
"Initialize",
"the",
"logger",
"for",
"this",
"thread",
"."
] | python | train |
bapakode/OmMongo | ommongo/session.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/session.py#L259-L306 | def execute_query(self, query, session):
''' Get the results of ``query``. This method does flush in a
transaction, so any objects retrieved which are not in the cache
which would be updated when the transaction finishes will be
stale '''
self.auto_ensure_indexes(query.type)
kwargs = dict()
if query.... | [
"def",
"execute_query",
"(",
"self",
",",
"query",
",",
"session",
")",
":",
"self",
".",
"auto_ensure_indexes",
"(",
"query",
".",
"type",
")",
"kwargs",
"=",
"dict",
"(",
")",
"if",
"query",
".",
"_get_fields",
"(",
")",
":",
"if",
"PYMONGO_3",
":",
... | Get the results of ``query``. This method does flush in a
transaction, so any objects retrieved which are not in the cache
which would be updated when the transaction finishes will be
stale | [
"Get",
"the",
"results",
"of",
"query",
".",
"This",
"method",
"does",
"flush",
"in",
"a",
"transaction",
"so",
"any",
"objects",
"retrieved",
"which",
"are",
"not",
"in",
"the",
"cache",
"which",
"would",
"be",
"updated",
"when",
"the",
"transaction",
"fi... | python | train |
luckydonald/pytgbot | code_generation/output/teleflask_messages.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L14-L32 | def _apply_update_receiver(self, receiver, reply_id):
"""
Updates `self.receiver` and/or `self.reply_id` if they still contain the default value.
:param receiver: The receiver `chat_id` to use.
Either `self.receiver`, if set, e.g. when instancing `TextMessage(receiver=10... | [
"def",
"_apply_update_receiver",
"(",
"self",
",",
"receiver",
",",
"reply_id",
")",
":",
"if",
"self",
".",
"receiver",
"is",
"None",
":",
"self",
".",
"receiver",
"=",
"receiver",
"# end if",
"if",
"self",
".",
"reply_id",
"is",
"DEFAULT_MESSAGE_ID",
":",
... | Updates `self.receiver` and/or `self.reply_id` if they still contain the default value.
:param receiver: The receiver `chat_id` to use.
Either `self.receiver`, if set, e.g. when instancing `TextMessage(receiver=10001231231, ...)`,
or the `chat.id` of the update ... | [
"Updates",
"self",
".",
"receiver",
"and",
"/",
"or",
"self",
".",
"reply_id",
"if",
"they",
"still",
"contain",
"the",
"default",
"value",
".",
":",
"param",
"receiver",
":",
"The",
"receiver",
"chat_id",
"to",
"use",
".",
"Either",
"self",
".",
"receiv... | python | train |
note35/sinon | sinon/lib/matcher.py | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/matcher.py#L46-L61 | def __value_compare(self, target):
"""
Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean
"""
if self.expectation == "__ANY__":
return True
elif self.expectation == "__DEFINED__":
return True if targ... | [
"def",
"__value_compare",
"(",
"self",
",",
"target",
")",
":",
"if",
"self",
".",
"expectation",
"==",
"\"__ANY__\"",
":",
"return",
"True",
"elif",
"self",
".",
"expectation",
"==",
"\"__DEFINED__\"",
":",
"return",
"True",
"if",
"target",
"is",
"not",
"... | Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean | [
"Comparing",
"result",
"based",
"on",
"expectation",
"if",
"arg_type",
"is",
"VALUE",
"Args",
":",
"Anything",
"Return",
":",
"Boolean"
] | python | train |
zhmcclient/python-zhmcclient | zhmcclient/_console.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L231-L239 | def user_patterns(self):
"""
:class:`~zhmcclient.UserPatternManager`: Access to the
:term:`User Patterns <User Pattern>` in this Console.
"""
# We do here some lazy loading.
if not self._user_patterns:
self._user_patterns = UserPatternManager(self)
ret... | [
"def",
"user_patterns",
"(",
"self",
")",
":",
"# We do here some lazy loading.",
"if",
"not",
"self",
".",
"_user_patterns",
":",
"self",
".",
"_user_patterns",
"=",
"UserPatternManager",
"(",
"self",
")",
"return",
"self",
".",
"_user_patterns"
] | :class:`~zhmcclient.UserPatternManager`: Access to the
:term:`User Patterns <User Pattern>` in this Console. | [
":",
"class",
":",
"~zhmcclient",
".",
"UserPatternManager",
":",
"Access",
"to",
"the",
":",
"term",
":",
"User",
"Patterns",
"<User",
"Pattern",
">",
"in",
"this",
"Console",
"."
] | python | train |
knipknap/SpiffWorkflow | SpiffWorkflow/serializer/xml.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/xml.py#L140-L161 | def serialize_value_map(self, map_elem, thedict):
"""
Serializes a dictionary of key/value pairs, where the values are
either strings, or Attrib, or PathAttrib objects.
Example::
<variable>
<name>foo</name>
<value>text</value>
</v... | [
"def",
"serialize_value_map",
"(",
"self",
",",
"map_elem",
",",
"thedict",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"thedict",
".",
"items",
"(",
... | Serializes a dictionary of key/value pairs, where the values are
either strings, or Attrib, or PathAttrib objects.
Example::
<variable>
<name>foo</name>
<value>text</value>
</variable>
<variable>
<name>foo2</name>
... | [
"Serializes",
"a",
"dictionary",
"of",
"key",
"/",
"value",
"pairs",
"where",
"the",
"values",
"are",
"either",
"strings",
"or",
"Attrib",
"or",
"PathAttrib",
"objects",
"."
] | python | valid |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py#L143-L161 | def port_profile_vlan_profile_switchport_access_mac_group_vlan_classification_access_vlan_access_mac_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
... | [
"def",
"port_profile_vlan_profile_switchport_access_mac_group_vlan_classification_access_vlan_access_mac_group",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"port_profile",
"=",
"ET",
".",
"SubElement",
"(... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
gatkin/declxml | declxml.py | https://github.com/gatkin/declxml/blob/3a2324b43aee943e82a04587fbb68932c6f392ba/declxml.py#L579-L608 | def string(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default='', # type: Optional[Text]
omit_empty=False, # type: bool
strip_whitespace=True, # type: bool
hooks=... | [
"def",
"string",
"(",
"element_name",
",",
"# type: Text",
"attribute",
"=",
"None",
",",
"# type: Optional[Text]",
"required",
"=",
"True",
",",
"# type: bool",
"alias",
"=",
"None",
",",
"# type: Optional[Text]",
"default",
"=",
"''",
",",
"# type: Optional[Text]"... | Create a processor for string values.
:param strip_whitespace: Indicates whether leading and trailing whitespace should be stripped
from parsed string values.
See also :func:`declxml.boolean` | [
"Create",
"a",
"processor",
"for",
"string",
"values",
"."
] | python | train |
JarryShaw/PyPCAPKit | src/protocols/link/link.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/link.py#L79-L121 | def _import_next_layer(self, proto, length):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Returns:
* bool -- flag if extraction of next layer succeeded
... | [
"def",
"_import_next_layer",
"(",
"self",
",",
"proto",
",",
"length",
")",
":",
"if",
"length",
"==",
"0",
":",
"from",
"pcapkit",
".",
"protocols",
".",
"null",
"import",
"NoPayload",
"as",
"Protocol",
"elif",
"self",
".",
"_sigterm",
":",
"from",
"pca... | Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Returns:
* bool -- flag if extraction of next layer succeeded
* Info -- info of next layer
* ProtoChain --... | [
"Import",
"next",
"layer",
"extractor",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L62-L81 | def db_create_table(self, table_name, columns):
"""Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB.
"""
formatted_columns = ''
for col in set(columns):
formatted... | [
"def",
"db_create_table",
"(",
"self",
",",
"table_name",
",",
"columns",
")",
":",
"formatted_columns",
"=",
"''",
"for",
"col",
"in",
"set",
"(",
"columns",
")",
":",
"formatted_columns",
"+=",
"'\"{}\" text, '",
".",
"format",
"(",
"col",
".",
"strip",
... | Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB. | [
"Create",
"a",
"temporary",
"DB",
"table",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/assessment_authoring/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/objects.py#L814-L819 | def _init_metadata(self, **kwargs):
"""Initialize form metadata"""
osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
self._cumulative_default = self._mdata['cumulative']['default_boolean_values'][0]
self._minimum_score_default = self._mdata['minimum_score']['default_cardinal_val... | [
"def",
"_init_metadata",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"osid_objects",
".",
"OsidObjectForm",
".",
"_init_metadata",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_cumulative_default",
"=",
"self",
".",
"_mdata",
"[",
"'cumulat... | Initialize form metadata | [
"Initialize",
"form",
"metadata"
] | python | train |
bokeh/bokeh | bokeh/server/views/ws.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L243-L257 | def send_message(self, message):
''' Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send
'''
try:
if _message_test_port is not None:
_message_test_port.sent.append(message)
yield m... | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"if",
"_message_test_port",
"is",
"not",
"None",
":",
"_message_test_port",
".",
"sent",
".",
"append",
"(",
"message",
")",
"yield",
"message",
".",
"send",
"(",
"self",
")",
"exc... | Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send | [
"Send",
"a",
"Bokeh",
"Server",
"protocol",
"message",
"to",
"the",
"connected",
"client",
"."
] | python | train |
theonion/django-bulbs | bulbs/utils/methods.py | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/utils/methods.py#L125-L133 | def import_class(name):
"""Load class from fully-qualified python module name.
ex: import_class('bulbs.content.models.Content')
"""
module, _, klass = name.rpartition('.')
mod = import_module(module)
return getattr(mod, klass) | [
"def",
"import_class",
"(",
"name",
")",
":",
"module",
",",
"_",
",",
"klass",
"=",
"name",
".",
"rpartition",
"(",
"'.'",
")",
"mod",
"=",
"import_module",
"(",
"module",
")",
"return",
"getattr",
"(",
"mod",
",",
"klass",
")"
] | Load class from fully-qualified python module name.
ex: import_class('bulbs.content.models.Content') | [
"Load",
"class",
"from",
"fully",
"-",
"qualified",
"python",
"module",
"name",
"."
] | python | train |
gmr/tinman | tinman/handlers/mixins.py | https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/handlers/mixins.py#L43-L55 | def _statsd_address(self):
"""Return a tuple of host and port for the statsd server to send
stats to.
:return: tuple(host, port)
"""
return (self.application.settings.get('statsd',
{}).get('host',
... | [
"def",
"_statsd_address",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"application",
".",
"settings",
".",
"get",
"(",
"'statsd'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'host'",
",",
"self",
".",
"STATSD_HOST",
")",
",",
"self",
".",
"applicat... | Return a tuple of host and port for the statsd server to send
stats to.
:return: tuple(host, port) | [
"Return",
"a",
"tuple",
"of",
"host",
"and",
"port",
"for",
"the",
"statsd",
"server",
"to",
"send",
"stats",
"to",
"."
] | python | train |
geertj/gruvi | lib/gruvi/ssl.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/ssl.py#L135-L192 | def feed_ssldata(self, data):
"""Feed SSL record level data into the pipe.
The data must be a bytes instance. It is OK to send an empty bytes
instance. This can be used to get ssldata for a handshake initiated by
this endpoint.
Return a (ssldata, appdata) tuple. The ssldata ele... | [
"def",
"feed_ssldata",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_state",
"==",
"self",
".",
"S_UNWRAPPED",
":",
"# If unwrapped, pass plaintext data straight through.",
"return",
"(",
"[",
"]",
",",
"[",
"data",
"]",
"if",
"data",
"else",
"[",... | Feed SSL record level data into the pipe.
The data must be a bytes instance. It is OK to send an empty bytes
instance. This can be used to get ssldata for a handshake initiated by
this endpoint.
Return a (ssldata, appdata) tuple. The ssldata element is a list of
buffers contain... | [
"Feed",
"SSL",
"record",
"level",
"data",
"into",
"the",
"pipe",
"."
] | python | train |
matthiask/django-cte-forest | cte_forest/models.py | https://github.com/matthiask/django-cte-forest/blob/7bff29d69eddfcf214e9cf61647c91d28655619c/cte_forest/models.py#L604-L645 | def as_tree(self, visitor=None, children=None):
""" Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary ... | [
"def",
"as_tree",
"(",
"self",
",",
"visitor",
"=",
"None",
",",
"children",
"=",
"None",
")",
":",
"return",
"[",
"root",
".",
"as_tree",
"(",
"visitor",
"=",
"visitor",
",",
"children",
"=",
"children",
")",
"for",
"root",
"in",
"self",
".",
"roots... | Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary representation, where the entry
``children`` (by... | [
"Recursively",
"traverses",
"each",
"tree",
"(",
"starting",
"from",
"each",
"root",
")",
"in",
"order",
"to",
"generate",
"a",
"dictionary",
"-",
"based",
"tree",
"structure",
"of",
"the",
"entire",
"forest",
".",
"Each",
"level",
"of",
"the",
"forest",
"... | python | train |
idlesign/uwsgiconf | uwsgiconf/options/networking.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/networking.py#L121-L158 | def register_socket(self, socket):
"""Registers the given socket(s) for further use.
:param Socket|list[Socket] socket: Socket type object. See ``.sockets``.
"""
sockets = self._sockets
for socket in listify(socket):
uses_shared = isinstance(socket.address, Socket... | [
"def",
"register_socket",
"(",
"self",
",",
"socket",
")",
":",
"sockets",
"=",
"self",
".",
"_sockets",
"for",
"socket",
"in",
"listify",
"(",
"socket",
")",
":",
"uses_shared",
"=",
"isinstance",
"(",
"socket",
".",
"address",
",",
"SocketShared",
")",
... | Registers the given socket(s) for further use.
:param Socket|list[Socket] socket: Socket type object. See ``.sockets``. | [
"Registers",
"the",
"given",
"socket",
"(",
"s",
")",
"for",
"further",
"use",
"."
] | python | train |
innogames/polysh | polysh/remote_dispatcher.py | https://github.com/innogames/polysh/blob/fbea36f3bc9f47a62d72040c48dad1776124dae3/polysh/remote_dispatcher.py#L51-L56 | def main_loop_iteration(timeout=None):
"""Return the number of RemoteDispatcher.handle_read() calls made by this
iteration"""
prev_nr_read = nr_handle_read
asyncore.loop(count=1, timeout=timeout, use_poll=True)
return nr_handle_read - prev_nr_read | [
"def",
"main_loop_iteration",
"(",
"timeout",
"=",
"None",
")",
":",
"prev_nr_read",
"=",
"nr_handle_read",
"asyncore",
".",
"loop",
"(",
"count",
"=",
"1",
",",
"timeout",
"=",
"timeout",
",",
"use_poll",
"=",
"True",
")",
"return",
"nr_handle_read",
"-",
... | Return the number of RemoteDispatcher.handle_read() calls made by this
iteration | [
"Return",
"the",
"number",
"of",
"RemoteDispatcher",
".",
"handle_read",
"()",
"calls",
"made",
"by",
"this",
"iteration"
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_button.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_button.py#L131-L136 | def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = FloatingActionButton(self.get_context(), None, d.style) | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"FloatingActionButton",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
")"
] | Create the underlying widget. | [
"Create",
"the",
"underlying",
"widget",
"."
] | python | train |
esheldon/fitsio | fitsio/header.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/header.py#L359-L369 | def next(self):
"""
for iteration over the header entries
"""
if self._current < len(self._record_list):
rec = self._record_list[self._current]
key = rec['name']
self._current += 1
return key
else:
raise StopIteration | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current",
"<",
"len",
"(",
"self",
".",
"_record_list",
")",
":",
"rec",
"=",
"self",
".",
"_record_list",
"[",
"self",
".",
"_current",
"]",
"key",
"=",
"rec",
"[",
"'name'",
"]",
"self",
... | for iteration over the header entries | [
"for",
"iteration",
"over",
"the",
"header",
"entries"
] | python | train |
senaite/senaite.core | bika/lims/browser/partition_magic.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/partition_magic.py#L297-L315 | def get_number_of_partitions_for(self, ar):
"""Return the number of selected partitions
"""
# fetch the number of partitions from the request
uid = api.get_uid(ar)
num = self.request.get("primary", {}).get(uid)
if num is None:
# get the number of partitions f... | [
"def",
"get_number_of_partitions_for",
"(",
"self",
",",
"ar",
")",
":",
"# fetch the number of partitions from the request",
"uid",
"=",
"api",
".",
"get_uid",
"(",
"ar",
")",
"num",
"=",
"self",
".",
"request",
".",
"get",
"(",
"\"primary\"",
",",
"{",
"}",
... | Return the number of selected partitions | [
"Return",
"the",
"number",
"of",
"selected",
"partitions"
] | python | train |
timster/peewee-validates | peewee_validates.py | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L314-L334 | def coerce_single_instance(lookup_field, value):
"""
Convert from whatever value is given to a scalar value for lookup_field.
If value is a dict, then lookup_field.name is used to get the value from the dict. Example:
lookup_field.name = 'id'
value = {'id': 123, 'name': 'tim'}
return... | [
"def",
"coerce_single_instance",
"(",
"lookup_field",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"value",
".",
"get",
"(",
"lookup_field",
".",
"name",
")",
"if",
"isinstance",
"(",
"value",
",",
"peewee",
... | Convert from whatever value is given to a scalar value for lookup_field.
If value is a dict, then lookup_field.name is used to get the value from the dict. Example:
lookup_field.name = 'id'
value = {'id': 123, 'name': 'tim'}
returns = 123
If value is a model, then lookup_field.name is ex... | [
"Convert",
"from",
"whatever",
"value",
"is",
"given",
"to",
"a",
"scalar",
"value",
"for",
"lookup_field",
".",
"If",
"value",
"is",
"a",
"dict",
"then",
"lookup_field",
".",
"name",
"is",
"used",
"to",
"get",
"the",
"value",
"from",
"the",
"dict",
".",... | python | train |
googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L264-L276 | def send(self, request):
"""Queue a request to be sent to the RPC."""
if self._UNARY_REQUESTS:
try:
self._send_unary_request(request)
except exceptions.GoogleAPICallError:
_LOGGER.debug(
"Exception while sending unary RPC. This ... | [
"def",
"send",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"_UNARY_REQUESTS",
":",
"try",
":",
"self",
".",
"_send_unary_request",
"(",
"request",
")",
"except",
"exceptions",
".",
"GoogleAPICallError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"E... | Queue a request to be sent to the RPC. | [
"Queue",
"a",
"request",
"to",
"be",
"sent",
"to",
"the",
"RPC",
"."
] | python | train |
brandonxiang/geojson-python-utils | geojson_utils/geojson_utils.py | https://github.com/brandonxiang/geojson-python-utils/blob/33d0dcd5f16e0567b48c0d49fd292a4f1db16b41/geojson_utils/geojson_utils.py#L170-L194 | def draw_circle(radius_in_meters, center_point, steps=15):
"""
get a circle shape polygon based on centerPoint and radius
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
if(point inside multipoly) return true else false
"""
steps = steps if st... | [
"def",
"draw_circle",
"(",
"radius_in_meters",
",",
"center_point",
",",
"steps",
"=",
"15",
")",
":",
"steps",
"=",
"steps",
"if",
"steps",
">",
"15",
"else",
"15",
"center",
"=",
"[",
"center_point",
"[",
"'coordinates'",
"]",
"[",
"1",
"]",
",",
"ce... | get a circle shape polygon based on centerPoint and radius
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
if(point inside multipoly) return true else false | [
"get",
"a",
"circle",
"shape",
"polygon",
"based",
"on",
"centerPoint",
"and",
"radius"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2161-L2182 | def insert_multiple_records(self,
table: str,
fields: Sequence[str],
records: Sequence[Sequence[Any]]) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the list of re... | [
"def",
"insert_multiple_records",
"(",
"self",
",",
"table",
":",
"str",
",",
"fields",
":",
"Sequence",
"[",
"str",
"]",
",",
"records",
":",
"Sequence",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
")",
"->",
"int",
":",
"self",
".",
"ensure_db_open",
"(",... | Inserts a record into database, table "table", using the list of
fieldnames and the list of records (each a list of values).
Returns number of rows affected. | [
"Inserts",
"a",
"record",
"into",
"database",
"table",
"table",
"using",
"the",
"list",
"of",
"fieldnames",
"and",
"the",
"list",
"of",
"records",
"(",
"each",
"a",
"list",
"of",
"values",
")",
".",
"Returns",
"number",
"of",
"rows",
"affected",
"."
] | python | train |
robmcmullen/atrcopy | atrcopy/segments.py | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/segments.py#L1003-L1016 | def get_comments_in_range(self, start, end):
"""Get a list of comments at specified indexes"""
comments = {}
# Naive way, but maybe it's fast enough: loop over all comments
# gathering those within the bounds
for rawindex, comment in self.rawdata.extra.comments.items():
... | [
"def",
"get_comments_in_range",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"comments",
"=",
"{",
"}",
"# Naive way, but maybe it's fast enough: loop over all comments",
"# gathering those within the bounds",
"for",
"rawindex",
",",
"comment",
"in",
"self",
".",
"r... | Get a list of comments at specified indexes | [
"Get",
"a",
"list",
"of",
"comments",
"at",
"specified",
"indexes"
] | python | train |
assemblerflow/flowcraft | flowcraft/generator/engine.py | https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/generator/engine.py#L1478-L1587 | def fetch_docker_tags(self):
"""
Export all dockerhub tags associated with each component given by
the -t flag.
"""
# dict to store the already parsed components (useful when forks are
# given to the pipeline string via -t flag
dict_of_parsed = {}
# fetc... | [
"def",
"fetch_docker_tags",
"(",
"self",
")",
":",
"# dict to store the already parsed components (useful when forks are",
"# given to the pipeline string via -t flag",
"dict_of_parsed",
"=",
"{",
"}",
"# fetches terminal width and subtracts 3 because we always add a",
"# new line characte... | Export all dockerhub tags associated with each component given by
the -t flag. | [
"Export",
"all",
"dockerhub",
"tags",
"associated",
"with",
"each",
"component",
"given",
"by",
"the",
"-",
"t",
"flag",
"."
] | python | test |
googleads/googleads-python-lib | examples/adwords/v201809/migration/migrate_to_extension_settings.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/v201809/migration/migrate_to_extension_settings.py#L178-L228 | def GetCampaignFeeds(client, feed, placeholder_type):
"""Get a list of Feed Item Ids used by a campaign via a given Campaign Feed.
Args:
client: an AdWordsClient instance.
feed: a Campaign Feed.
placeholder_type: the Placeholder Type.
Returns:
A list of Feed Item Ids.
"""
campaign_feed_servi... | [
"def",
"GetCampaignFeeds",
"(",
"client",
",",
"feed",
",",
"placeholder_type",
")",
":",
"campaign_feed_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignFeedService'",
",",
"'v201809'",
")",
"campaign_feeds",
"=",
"[",
"]",
"more_pages",
"=",
"True",
... | Get a list of Feed Item Ids used by a campaign via a given Campaign Feed.
Args:
client: an AdWordsClient instance.
feed: a Campaign Feed.
placeholder_type: the Placeholder Type.
Returns:
A list of Feed Item Ids. | [
"Get",
"a",
"list",
"of",
"Feed",
"Item",
"Ids",
"used",
"by",
"a",
"campaign",
"via",
"a",
"given",
"Campaign",
"Feed",
"."
] | python | train |
saltstack/salt | salt/modules/rvm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rvm.py#L410-L440 | def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
... | [
"def",
"gemset_list_all",
"(",
"runas",
"=",
"None",
")",
":",
"gemsets",
"=",
"{",
"}",
"current_ruby",
"=",
"None",
"output",
"=",
"_rvm_do",
"(",
"'default'",
",",
"[",
"'rvm'",
",",
"'gemset'",
",",
"'list_all'",
"]",
",",
"runas",
"=",
"runas",
")... | List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.g... | [
"List",
"all",
"gemsets",
"for",
"all",
"installed",
"rubies",
"."
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/core/packages.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/packages.py#L133-L148 | def check_constraint(self, pkge=None, constr=None):
"""
Checks the constraints.
:param pkge: the package to check
:type pkge: Package
:param constr: the package constraint to check
:type constr: PackageConstraint
"""
if not pkge is None:
retur... | [
"def",
"check_constraint",
"(",
"self",
",",
"pkge",
"=",
"None",
",",
"constr",
"=",
"None",
")",
":",
"if",
"not",
"pkge",
"is",
"None",
":",
"return",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"checkConstraint\"",
",",
"\"(Lweka/c... | Checks the constraints.
:param pkge: the package to check
:type pkge: Package
:param constr: the package constraint to check
:type constr: PackageConstraint | [
"Checks",
"the",
"constraints",
"."
] | python | train |
python-cmd2/cmd2 | examples/async_printing.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/async_printing.py#L118-L141 | def _generate_alert_str(self) -> str:
"""
Combines alerts into one string that can be printed to the terminal
:return: the alert string
"""
global ALERTS
alert_str = ''
alerts = self._get_alerts()
longest_alert = max(ALERTS, key=len)
num_asterisk... | [
"def",
"_generate_alert_str",
"(",
"self",
")",
"->",
"str",
":",
"global",
"ALERTS",
"alert_str",
"=",
"''",
"alerts",
"=",
"self",
".",
"_get_alerts",
"(",
")",
"longest_alert",
"=",
"max",
"(",
"ALERTS",
",",
"key",
"=",
"len",
")",
"num_asterisks",
"... | Combines alerts into one string that can be printed to the terminal
:return: the alert string | [
"Combines",
"alerts",
"into",
"one",
"string",
"that",
"can",
"be",
"printed",
"to",
"the",
"terminal",
":",
"return",
":",
"the",
"alert",
"string"
] | python | train |
intel-analytics/BigDL | pyspark/bigdl/util/tf_utils.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/tf_utils.py#L167-L202 | def merge_checkpoint(input_graph,
checkpoint,
output_node_names,
output_graph,
sess):
"""
Get the variable values from the checkpoint file, and merge them to the GraphDef file
Args:
input_graph: the GraphDef file, do... | [
"def",
"merge_checkpoint",
"(",
"input_graph",
",",
"checkpoint",
",",
"output_node_names",
",",
"output_graph",
",",
"sess",
")",
":",
"restore_op_name",
"=",
"\"save/restore_all\"",
"filename_tensor_name",
"=",
"\"save/Const:0\"",
"input_graph_def",
"=",
"graph_pb2",
... | Get the variable values from the checkpoint file, and merge them to the GraphDef file
Args:
input_graph: the GraphDef file, doesn't contain variable values
checkpoint: the checkpoint file
output_node_names: A list of string, the output names
output_graph: String of the location and t... | [
"Get",
"the",
"variable",
"values",
"from",
"the",
"checkpoint",
"file",
"and",
"merge",
"them",
"to",
"the",
"GraphDef",
"file",
"Args",
":",
"input_graph",
":",
"the",
"GraphDef",
"file",
"doesn",
"t",
"contain",
"variable",
"values",
"checkpoint",
":",
"t... | python | test |
Esri/ArcREST | src/arcrest/manageags/_services.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_services.py#L524-L552 | def exists(self, folderName, serviceName=None, serviceType=None):
"""
This operation allows you to check whether a folder or a service
exists. To test if a folder exists, supply only a folderName. To
test if a service exists in a root folder, supply both serviceName
and serviceTy... | [
"def",
"exists",
"(",
"self",
",",
"folderName",
",",
"serviceName",
"=",
"None",
",",
"serviceType",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/exists\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"folderName\"",
":",
... | This operation allows you to check whether a folder or a service
exists. To test if a folder exists, supply only a folderName. To
test if a service exists in a root folder, supply both serviceName
and serviceType with folderName=None. To test if a service exists
in a folder, supply all t... | [
"This",
"operation",
"allows",
"you",
"to",
"check",
"whether",
"a",
"folder",
"or",
"a",
"service",
"exists",
".",
"To",
"test",
"if",
"a",
"folder",
"exists",
"supply",
"only",
"a",
"folderName",
".",
"To",
"test",
"if",
"a",
"service",
"exists",
"in",... | python | train |
architv/soccer-cli | soccer/writers.py | https://github.com/architv/soccer-cli/blob/472e9f492f7633a8e9739e228a6c31de454da88b/soccer/writers.py#L230-L242 | def team_scores(self, team_scores, time):
"""Store output of team scores to a CSV file"""
headers = ['Date', 'Home Team Name', 'Home Team Goals',
'Away Team Goals', 'Away Team Name']
result = [headers]
result.extend([score["utcDate"].split('T')[0],
... | [
"def",
"team_scores",
"(",
"self",
",",
"team_scores",
",",
"time",
")",
":",
"headers",
"=",
"[",
"'Date'",
",",
"'Home Team Name'",
",",
"'Home Team Goals'",
",",
"'Away Team Goals'",
",",
"'Away Team Name'",
"]",
"result",
"=",
"[",
"headers",
"]",
"result"... | Store output of team scores to a CSV file | [
"Store",
"output",
"of",
"team",
"scores",
"to",
"a",
"CSV",
"file"
] | python | train |
mozilla-iot/webthing-python | webthing/server.py | https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/server.py#L165-L171 | def prepare(self):
"""Validate Host header."""
host = self.request.headers.get('Host', None)
if host is not None and host in self.hosts:
return
raise tornado.web.HTTPError(403) | [
"def",
"prepare",
"(",
"self",
")",
":",
"host",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Host'",
",",
"None",
")",
"if",
"host",
"is",
"not",
"None",
"and",
"host",
"in",
"self",
".",
"hosts",
":",
"return",
"raise",
"tornad... | Validate Host header. | [
"Validate",
"Host",
"header",
"."
] | python | test |
cloudbase/python-hnvclient | hnv/client.py | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L139-L145 | def _get_client():
"""Create a new client for the HNV REST API."""
return utils.get_client(url=CONFIG.HNV.url,
username=CONFIG.HNV.username,
password=CONFIG.HNV.password,
allow_insecure=CONFIG.HNV.https_allow... | [
"def",
"_get_client",
"(",
")",
":",
"return",
"utils",
".",
"get_client",
"(",
"url",
"=",
"CONFIG",
".",
"HNV",
".",
"url",
",",
"username",
"=",
"CONFIG",
".",
"HNV",
".",
"username",
",",
"password",
"=",
"CONFIG",
".",
"HNV",
".",
"password",
",... | Create a new client for the HNV REST API. | [
"Create",
"a",
"new",
"client",
"for",
"the",
"HNV",
"REST",
"API",
"."
] | python | train |
frictionlessdata/tableschema-sql-py | tableschema_sql/mapper.py | https://github.com/frictionlessdata/tableschema-sql-py/blob/81ca4b564f6dac5fe3adc6553b353826190df6f8/tableschema_sql/mapper.py#L159-L164 | def restore_bucket(self, table_name):
"""Restore bucket from SQL
"""
if table_name.startswith(self.__prefix):
return table_name.replace(self.__prefix, '', 1)
return None | [
"def",
"restore_bucket",
"(",
"self",
",",
"table_name",
")",
":",
"if",
"table_name",
".",
"startswith",
"(",
"self",
".",
"__prefix",
")",
":",
"return",
"table_name",
".",
"replace",
"(",
"self",
".",
"__prefix",
",",
"''",
",",
"1",
")",
"return",
... | Restore bucket from SQL | [
"Restore",
"bucket",
"from",
"SQL"
] | python | train |
Julian/jsonschema | jsonschema/validators.py | https://github.com/Julian/jsonschema/blob/a72332004cdc3ba456de7918bc32059822b2f69a/jsonschema/validators.py#L367-L437 | def extend(validator, validators=(), version=None, type_checker=None):
"""
Create a new validator class by extending an existing one.
Arguments:
validator (jsonschema.IValidator):
an existing validator class
validators (collections.Mapping):
a mapping of new vali... | [
"def",
"extend",
"(",
"validator",
",",
"validators",
"=",
"(",
")",
",",
"version",
"=",
"None",
",",
"type_checker",
"=",
"None",
")",
":",
"all_validators",
"=",
"dict",
"(",
"validator",
".",
"VALIDATORS",
")",
"all_validators",
".",
"update",
"(",
"... | Create a new validator class by extending an existing one.
Arguments:
validator (jsonschema.IValidator):
an existing validator class
validators (collections.Mapping):
a mapping of new validator callables to extend with, whose
structure is as in `create`.
... | [
"Create",
"a",
"new",
"validator",
"class",
"by",
"extending",
"an",
"existing",
"one",
"."
] | python | train |
apache/spark | python/pyspark/mllib/clustering.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/clustering.py#L625-L632 | def load(cls, sc, path):
"""
Load a model from the given path.
"""
model = cls._load_java(sc, path)
wrapper =\
sc._jvm.org.apache.spark.mllib.api.python.PowerIterationClusteringModelWrapper(model)
return PowerIterationClusteringModel(wrapper) | [
"def",
"load",
"(",
"cls",
",",
"sc",
",",
"path",
")",
":",
"model",
"=",
"cls",
".",
"_load_java",
"(",
"sc",
",",
"path",
")",
"wrapper",
"=",
"sc",
".",
"_jvm",
".",
"org",
".",
"apache",
".",
"spark",
".",
"mllib",
".",
"api",
".",
"python... | Load a model from the given path. | [
"Load",
"a",
"model",
"from",
"the",
"given",
"path",
"."
] | python | train |
quaddra/provision | provision/config.py | https://github.com/quaddra/provision/blob/d84dca80abb34ed93381aae4d5b8005bd08a5681/provision/config.py#L110-L114 | def is_node_destroyable(name, prefixes=DESTROYABLE_PREFIXES):
"""Return True if name starts with a destroyable prefix"""
return any([name.startswith(p) for p in prefixes]) | [
"def",
"is_node_destroyable",
"(",
"name",
",",
"prefixes",
"=",
"DESTROYABLE_PREFIXES",
")",
":",
"return",
"any",
"(",
"[",
"name",
".",
"startswith",
"(",
"p",
")",
"for",
"p",
"in",
"prefixes",
"]",
")"
] | Return True if name starts with a destroyable prefix | [
"Return",
"True",
"if",
"name",
"starts",
"with",
"a",
"destroyable",
"prefix"
] | python | train |
annoviko/pyclustering | pyclustering/cluster/clarans.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/clarans.py#L163-L233 | def __optimize_configuration(self):
"""!
@brief Finds quasi-optimal medoids and updates in line with them clusters in line with algorithm's rules.
"""
index_neighbor = 0
while (index_neighbor < self.__maxneighbor):
# get random current medoid that is ... | [
"def",
"__optimize_configuration",
"(",
"self",
")",
":",
"index_neighbor",
"=",
"0",
"while",
"(",
"index_neighbor",
"<",
"self",
".",
"__maxneighbor",
")",
":",
"# get random current medoid that is to be replaced\r",
"current_medoid_index",
"=",
"self",
".",
"__curren... | !
@brief Finds quasi-optimal medoids and updates in line with them clusters in line with algorithm's rules. | [
"!"
] | python | valid |
cjhutto/vaderSentiment | additional_resources/build_emoji_lexicon.py | https://github.com/cjhutto/vaderSentiment/blob/cfc2bce747afb2c49799c1de1dcf517358948d71/additional_resources/build_emoji_lexicon.py#L7-L11 | def get_list_from_file(file_name):
"""read the lines from a file into a list"""
with open(file_name, mode='r', encoding='utf-8') as f1:
lst = f1.readlines()
return lst | [
"def",
"get_list_from_file",
"(",
"file_name",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f1",
":",
"lst",
"=",
"f1",
".",
"readlines",
"(",
")",
"return",
"lst"
] | read the lines from a file into a list | [
"read",
"the",
"lines",
"from",
"a",
"file",
"into",
"a",
"list"
] | python | train |
fermiPy/fermipy | fermipy/scripts/cluster_sources.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/scripts/cluster_sources.py#L34-L51 | def make_cos_vects(lon_vect, lat_vect):
""" Convert from longitude (RA or GLON) and latitude (DEC or GLAT) values to directional cosines
Parameters
----------
lon_vect,lat_vect : np.ndarray(nsrc)
Input values
returns (np.ndarray(3,nsrc)) with the directional cosine (i.e., x,y,z component)... | [
"def",
"make_cos_vects",
"(",
"lon_vect",
",",
"lat_vect",
")",
":",
"lon_rad",
"=",
"np",
".",
"radians",
"(",
"lon_vect",
")",
"lat_rad",
"=",
"np",
".",
"radians",
"(",
"lat_vect",
")",
"cvals",
"=",
"np",
".",
"cos",
"(",
"lat_rad",
")",
"xvals",
... | Convert from longitude (RA or GLON) and latitude (DEC or GLAT) values to directional cosines
Parameters
----------
lon_vect,lat_vect : np.ndarray(nsrc)
Input values
returns (np.ndarray(3,nsrc)) with the directional cosine (i.e., x,y,z component) values | [
"Convert",
"from",
"longitude",
"(",
"RA",
"or",
"GLON",
")",
"and",
"latitude",
"(",
"DEC",
"or",
"GLAT",
")",
"values",
"to",
"directional",
"cosines"
] | python | train |
prthkms/alex | alex/handler.py | https://github.com/prthkms/alex/blob/79d3167c877e94cc07db0aab55a35857fac67ef7/alex/handler.py#L18-L26 | def words(query):
"""lines(query) -- print the number of words in a given file
"""
filename = support.get_file_name(query)
if(os.path.isfile(filename)):
with open(filename) as openfile:
print len(openfile.read().split())
else:
print 'File not found : ' + filename | [
"def",
"words",
"(",
"query",
")",
":",
"filename",
"=",
"support",
".",
"get_file_name",
"(",
"query",
")",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"openfile",
":",
"... | lines(query) -- print the number of words in a given file | [
"lines",
"(",
"query",
")",
"--",
"print",
"the",
"number",
"of",
"words",
"in",
"a",
"given",
"file"
] | python | train |
estnltk/estnltk | estnltk/text.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L696-L700 | def root_tokens(self):
"""Root tokens of word roots."""
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
return self.get_analysis_element(ROOT_TOKENS) | [
"def",
"root_tokens",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"ANALYSIS",
")",
":",
"self",
".",
"tag_analysis",
"(",
")",
"return",
"self",
".",
"get_analysis_element",
"(",
"ROOT_TOKENS",
")"
] | Root tokens of word roots. | [
"Root",
"tokens",
"of",
"word",
"roots",
"."
] | python | train |
ib-lundgren/flask-oauthprovider | examples/mongo_demoprovider/login.py | https://github.com/ib-lundgren/flask-oauthprovider/blob/6c91e8c11fc3cee410cb755d52d9d2c5331ee324/examples/mongo_demoprovider/login.py#L86-L109 | def edit_profile():
"""Updates a profile"""
if g.user is None:
abort(401)
form = dict(name=g.user.name, email=g.user.email)
if request.method == 'POST':
if 'delete' in request.form:
User.get_collection().remove(g.user)
session['openid'] = None
flash(u'... | [
"def",
"edit_profile",
"(",
")",
":",
"if",
"g",
".",
"user",
"is",
"None",
":",
"abort",
"(",
"401",
")",
"form",
"=",
"dict",
"(",
"name",
"=",
"g",
".",
"user",
".",
"name",
",",
"email",
"=",
"g",
".",
"user",
".",
"email",
")",
"if",
"re... | Updates a profile | [
"Updates",
"a",
"profile"
] | python | train |
PmagPy/PmagPy | programs/incfish.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/incfish.py#L8-L63 | def main():
"""
NAME
incfish.py
DESCRIPTION
calculates fisher parameters from inc only data
INPUT FORMAT
takes inc data
SYNTAX
incfish.py [options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive filename entry
-f... | [
"def",
"main",
"(",
")",
":",
"inc",
"=",
"[",
"]",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"# check if help is needed",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"# graceful quit",
"if",
"'-i'",
"in",
"sys",
".",
... | NAME
incfish.py
DESCRIPTION
calculates fisher parameters from inc only data
INPUT FORMAT
takes inc data
SYNTAX
incfish.py [options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive filename entry
-f FILE, specify input fil... | [
"NAME",
"incfish",
".",
"py"
] | python | train |
google/openhtf | openhtf/plugs/usb/fastboot_protocol.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_protocol.py#L276-L288 | def flash(self, partition, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):
"""Flashes the last downloaded file to the given partition.
Args:
partition: Partition to flash.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. Usually no messages.
... | [
"def",
"flash",
"(",
"self",
",",
"partition",
",",
"timeout_ms",
"=",
"None",
",",
"info_cb",
"=",
"DEFAULT_MESSAGE_CALLBACK",
")",
":",
"return",
"self",
".",
"_simple_command",
"(",
"'flash'",
",",
"arg",
"=",
"partition",
",",
"info_cb",
"=",
"info_cb",
... | Flashes the last downloaded file to the given partition.
Args:
partition: Partition to flash.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. Usually no messages.
Returns:
Response to a download request, normally nothing. | [
"Flashes",
"the",
"last",
"downloaded",
"file",
"to",
"the",
"given",
"partition",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L302-L307 | def get_all_sources(self):
"""Returns all sources for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.sources)
return result | [
"def",
"get_all_sources",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"batch",
"in",
"self",
".",
"batches",
":",
"result",
".",
"extend",
"(",
"batch",
".",
"sources",
")",
"return",
"result"
] | Returns all sources for all batches of this Executor. | [
"Returns",
"all",
"sources",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"."
] | python | train |
saltstack/salt | salt/modules/github.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1870-L1959 | def _query(profile,
action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None,
url='https://api.github.com/',
per_page=None):
'''
Make a web call to the GitHub API and deal with paginated results.
'... | [
"def",
"_query",
"(",
"profile",
",",
"action",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
",",
"url",
"=",
"'https://api.github.com/'",
",... | Make a web call to the GitHub API and deal with paginated results. | [
"Make",
"a",
"web",
"call",
"to",
"the",
"GitHub",
"API",
"and",
"deal",
"with",
"paginated",
"results",
"."
] | python | train |
pennersr/django-allauth | allauth/account/adapter.py | https://github.com/pennersr/django-allauth/blob/f70cb3d622f992f15fe9b57098e0b328445b664e/allauth/account/adapter.py#L246-L278 | def clean_username(self, username, shallow=False):
"""
Validates the username. You can hook into this if you want to
(dynamically) restrict what usernames can be chosen.
"""
for validator in app_settings.USERNAME_VALIDATORS:
validator(username)
# TODO: Add re... | [
"def",
"clean_username",
"(",
"self",
",",
"username",
",",
"shallow",
"=",
"False",
")",
":",
"for",
"validator",
"in",
"app_settings",
".",
"USERNAME_VALIDATORS",
":",
"validator",
"(",
"username",
")",
"# TODO: Add regexp support to USERNAME_BLACKLIST",
"username_b... | Validates the username. You can hook into this if you want to
(dynamically) restrict what usernames can be chosen. | [
"Validates",
"the",
"username",
".",
"You",
"can",
"hook",
"into",
"this",
"if",
"you",
"want",
"to",
"(",
"dynamically",
")",
"restrict",
"what",
"usernames",
"can",
"be",
"chosen",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/stisData.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/stisData.py#L415-L433 | def expand_image(image, shape):
""" Expand image from original shape to requested shape. Output shape
must be an integer multiple of input image shape for each axis. """
if (shape[0] % image.shape[0]) or (shape[1] % image.shape[1]):
raise ValueError("Output shape must be an integer multiple of input... | [
"def",
"expand_image",
"(",
"image",
",",
"shape",
")",
":",
"if",
"(",
"shape",
"[",
"0",
"]",
"%",
"image",
".",
"shape",
"[",
"0",
"]",
")",
"or",
"(",
"shape",
"[",
"1",
"]",
"%",
"image",
".",
"shape",
"[",
"1",
"]",
")",
":",
"raise",
... | Expand image from original shape to requested shape. Output shape
must be an integer multiple of input image shape for each axis. | [
"Expand",
"image",
"from",
"original",
"shape",
"to",
"requested",
"shape",
".",
"Output",
"shape",
"must",
"be",
"an",
"integer",
"multiple",
"of",
"input",
"image",
"shape",
"for",
"each",
"axis",
"."
] | python | train |
openstack/horizon | horizon/middleware/base.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/base.py#L123-L159 | def process_exception(self, request, exception):
"""Catches internal Horizon exception classes.
Exception classes such as NotAuthorized, NotFound and Http302
are caught and handles them gracefully.
"""
if isinstance(exception, (exceptions.NotAuthorized,
... | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"(",
"exceptions",
".",
"NotAuthorized",
",",
"exceptions",
".",
"NotAuthenticated",
")",
")",
":",
"auth_url",
"=",
"settings",
"... | Catches internal Horizon exception classes.
Exception classes such as NotAuthorized, NotFound and Http302
are caught and handles them gracefully. | [
"Catches",
"internal",
"Horizon",
"exception",
"classes",
"."
] | python | train |
edx/edx-enterprise | enterprise/migrations/0065_add_enterprise_feature_roles.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/migrations/0065_add_enterprise_feature_roles.py#L13-L18 | def create_roles(apps, schema_editor):
"""Create the enterprise roles if they do not already exist."""
EnterpriseFeatureRole = apps.get_model('enterprise', 'EnterpriseFeatureRole')
EnterpriseFeatureRole.objects.update_or_create(name=ENTERPRISE_CATALOG_ADMIN_ROLE)
EnterpriseFeatureRole.objects.update_or_... | [
"def",
"create_roles",
"(",
"apps",
",",
"schema_editor",
")",
":",
"EnterpriseFeatureRole",
"=",
"apps",
".",
"get_model",
"(",
"'enterprise'",
",",
"'EnterpriseFeatureRole'",
")",
"EnterpriseFeatureRole",
".",
"objects",
".",
"update_or_create",
"(",
"name",
"=",
... | Create the enterprise roles if they do not already exist. | [
"Create",
"the",
"enterprise",
"roles",
"if",
"they",
"do",
"not",
"already",
"exist",
"."
] | python | valid |
cjdrake/pyeda | pyeda/boolalg/bfarray.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L1001-L1007 | def _uint2farray(ftype, num, length=None):
"""Convert an unsigned integer to an farray."""
if num < 0:
raise ValueError("expected num >= 0")
else:
objs = _uint2objs(ftype, num, length)
return farray(objs) | [
"def",
"_uint2farray",
"(",
"ftype",
",",
"num",
",",
"length",
"=",
"None",
")",
":",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"expected num >= 0\"",
")",
"else",
":",
"objs",
"=",
"_uint2objs",
"(",
"ftype",
",",
"num",
",",
"length"... | Convert an unsigned integer to an farray. | [
"Convert",
"an",
"unsigned",
"integer",
"to",
"an",
"farray",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L2737-L2758 | def drdlat(r, lon, lat):
"""
Compute the Jacobian of the transformation from latitudinal to
rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdlat_c.html
:param r: Distance of a point from the origin.
:type r: float
:param lon: Angle of the point from the X... | [
"def",
"drdlat",
"(",
"r",
",",
"lon",
",",
"lat",
")",
":",
"r",
"=",
"ctypes",
".",
"c_double",
"(",
"r",
")",
"lon",
"=",
"ctypes",
".",
"c_double",
"(",
"lon",
")",
"lat",
"=",
"ctypes",
".",
"c_double",
"(",
"lat",
")",
"jacobi",
"=",
"sty... | Compute the Jacobian of the transformation from latitudinal to
rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdlat_c.html
:param r: Distance of a point from the origin.
:type r: float
:param lon: Angle of the point from the XZ plane in radians.
:type lon: fl... | [
"Compute",
"the",
"Jacobian",
"of",
"the",
"transformation",
"from",
"latitudinal",
"to",
"rectangular",
"coordinates",
"."
] | python | train |
maas/python-libmaas | maas/client/viscera/partitions.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/partitions.py#L97-L103 | async def mount(self, mount_point, *, mount_options=None):
"""Mount this partition."""
self._data = await self._handler.mount(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id,
mount_point=mount_point,
mount_options=mo... | [
"async",
"def",
"mount",
"(",
"self",
",",
"mount_point",
",",
"*",
",",
"mount_options",
"=",
"None",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"mount",
"(",
"system_id",
"=",
"self",
".",
"block_device",
".",
"node",... | Mount this partition. | [
"Mount",
"this",
"partition",
"."
] | python | train |
angr/angr | angr/knowledge_plugins/variables/variable_manager.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/knowledge_plugins/variables/variable_manager.py#L405-L423 | def get_variable_accesses(self, variable, same_name=False):
"""
Get a list of all references to the given variable.
:param SimVariable variable: The variable.
:param bool same_name: Whether to include all variables with the same variable name, or just
... | [
"def",
"get_variable_accesses",
"(",
"self",
",",
"variable",
",",
"same_name",
"=",
"False",
")",
":",
"if",
"variable",
".",
"region",
"==",
"'global'",
":",
"return",
"self",
".",
"global_manager",
".",
"get_variable_accesses",
"(",
"variable",
",",
"same_n... | Get a list of all references to the given variable.
:param SimVariable variable: The variable.
:param bool same_name: Whether to include all variables with the same variable name, or just
based on the variable identifier.
:retur... | [
"Get",
"a",
"list",
"of",
"all",
"references",
"to",
"the",
"given",
"variable",
"."
] | python | train |
eeue56/PyChat.js | pychatjs/server/connections.py | https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/connections.py#L21-L24 | def write_message(self, message):
""" Writes a message to this chat connection's handler """
logging.debug("Sending message {mes} to {usr}".format(mes=message, usr=self.id))
self.handler.write_message(message) | [
"def",
"write_message",
"(",
"self",
",",
"message",
")",
":",
"logging",
".",
"debug",
"(",
"\"Sending message {mes} to {usr}\"",
".",
"format",
"(",
"mes",
"=",
"message",
",",
"usr",
"=",
"self",
".",
"id",
")",
")",
"self",
".",
"handler",
".",
"writ... | Writes a message to this chat connection's handler | [
"Writes",
"a",
"message",
"to",
"this",
"chat",
"connection",
"s",
"handler"
] | python | train |
PmagPy/PmagPy | pmagpy/ipmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/ipmag.py#L6790-L6968 | def curie(path_to_file='.', file_name='', magic=False,
window_length=3, save=False, save_folder='.', fmt='svg', t_begin="", t_end=""):
"""
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with widt... | [
"def",
"curie",
"(",
"path_to_file",
"=",
"'.'",
",",
"file_name",
"=",
"''",
",",
"magic",
"=",
"False",
",",
"window_length",
"=",
"3",
",",
"save",
"=",
"False",
",",
"save_folder",
"=",
"'.'",
",",
"fmt",
"=",
"'svg'",
",",
"t_begin",
"=",
"\"\""... | Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with width= <-w> degrees)
***
The 2nd derivative is calculated from smoothed 1st derivative curve
(using the same sliding window width)
***
The es... | [
"Plots",
"and",
"interprets",
"curie",
"temperature",
"data",
".",
"***",
"The",
"1st",
"derivative",
"is",
"calculated",
"from",
"smoothed",
"M",
"-",
"T",
"curve",
"(",
"convolution",
"with",
"trianfular",
"window",
"with",
"width",
"=",
"<",
"-",
"w",
"... | python | train |
snowplow/snowplow-python-analytics-sdk | snowplow_analytics_sdk/run_manifests.py | https://github.com/snowplow/snowplow-python-analytics-sdk/blob/0ddca91e3f6d8bed88627fa557790aa4868bdace/snowplow_analytics_sdk/run_manifests.py#L112-L137 | def split_full_path(path):
"""Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
('mybucket', None)
>>> ... | [
"def",
"split_full_path",
"(",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'s3://'",
")",
":",
"path",
"=",
"path",
"[",
"5",
":",
"]",
"elif",
"path",
".",
"startswith",
"(",
"'s3n://'",
")",
":",
"path",
"=",
"path",
"[",
"6",
":",
... | Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
('mybucket', None)
>>> split_full_path('s3n://snowplow-bu... | [
"Return",
"pair",
"of",
"bucket",
"without",
"protocol",
"and",
"path"
] | python | test |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L746-L752 | def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font) | [
"def",
"change_font_size",
"(",
"self",
",",
"delta",
")",
":",
"font",
"=",
"self",
".",
"font",
"size",
"=",
"max",
"(",
"font",
".",
"pointSize",
"(",
")",
"+",
"delta",
",",
"1",
")",
"# minimum 1 point",
"font",
".",
"setPointSize",
"(",
"size",
... | Change the font size by the specified amount (in points). | [
"Change",
"the",
"font",
"size",
"by",
"the",
"specified",
"amount",
"(",
"in",
"points",
")",
"."
] | python | test |
danielhrisca/asammdf | asammdf/mdf.py | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/mdf.py#L2193-L2425 | def stack(files, version="4.10", sync=True, **kwargs):
""" stack several files and return the stacked *MDF* object
Parameters
----------
files : list | tuple
list of *MDF* file names or *MDF* instances
version : str
merged file version
sync : bool... | [
"def",
"stack",
"(",
"files",
",",
"version",
"=",
"\"4.10\"",
",",
"sync",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"files",
":",
"raise",
"MdfException",
"(",
"\"No files given for stack\"",
")",
"version",
"=",
"validate_version_argume... | stack several files and return the stacked *MDF* object
Parameters
----------
files : list | tuple
list of *MDF* file names or *MDF* instances
version : str
merged file version
sync : bool
sync the files based on the start of measurement, defa... | [
"stack",
"several",
"files",
"and",
"return",
"the",
"stacked",
"*",
"MDF",
"*",
"object"
] | python | train |
jhermann/rudiments | src/rudiments/reamed/click.py | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L72-L75 | def get_command(self, ctx, cmd_name):
"""Map some aliases to their 'real' names."""
cmd_name = self.MAP.get(cmd_name, cmd_name)
return super(AliasedGroup, self).get_command(ctx, cmd_name) | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"cmd_name",
"=",
"self",
".",
"MAP",
".",
"get",
"(",
"cmd_name",
",",
"cmd_name",
")",
"return",
"super",
"(",
"AliasedGroup",
",",
"self",
")",
".",
"get_command",
"(",
"ctx",
... | Map some aliases to their 'real' names. | [
"Map",
"some",
"aliases",
"to",
"their",
"real",
"names",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.