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 |
|---|---|---|---|---|---|---|---|---|
KelSolaar/Umbra | umbra/components/factory/script_editor/script_editor.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/script_editor.py#L1838-L1844 | def __Script_Editor_Output_plainTextEdit_set_default_view_state(self):
"""
Sets the **Script_Editor_Output_plainTextEdit** Widget default View state.
"""
self.Script_Editor_Output_plainTextEdit.moveCursor(QTextCursor.End)
self.Script_Editor_Output_plainTextEdit.ensureCursorVisib... | [
"def",
"__Script_Editor_Output_plainTextEdit_set_default_view_state",
"(",
"self",
")",
":",
"self",
".",
"Script_Editor_Output_plainTextEdit",
".",
"moveCursor",
"(",
"QTextCursor",
".",
"End",
")",
"self",
".",
"Script_Editor_Output_plainTextEdit",
".",
"ensureCursorVisible... | Sets the **Script_Editor_Output_plainTextEdit** Widget default View state. | [
"Sets",
"the",
"**",
"Script_Editor_Output_plainTextEdit",
"**",
"Widget",
"default",
"View",
"state",
"."
] | python | train |
fabric-bolt/fabric-bolt | fabric_bolt/projects/views.py | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/views.py#L162-L171 | def form_valid(self, form):
"""After the form is valid lets let people know"""
ret = super(ProjectCopy, self).form_valid(form)
self.copy_relations()
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Project %s copied' % self.object.name)
... | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"ret",
"=",
"super",
"(",
"ProjectCopy",
",",
"self",
")",
".",
"form_valid",
"(",
"form",
")",
"self",
".",
"copy_relations",
"(",
")",
"# Good to make note of that",
"messages",
".",
"add_message",
... | After the form is valid lets let people know | [
"After",
"the",
"form",
"is",
"valid",
"lets",
"let",
"people",
"know"
] | python | train |
eqcorrscan/EQcorrscan | eqcorrscan/core/match_filter.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/core/match_filter.py#L743-L810 | def read(self, filename=None, read_detection_catalog=True):
"""
Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_de... | [
"def",
"read",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"read_detection_catalog",
"=",
"True",
")",
":",
"tribe",
"=",
"Tribe",
"(",
")",
"families",
"=",
"[",
"]",
"if",
"filename",
"is",
"None",
":",
"# If there is no filename given, then read the exa... | Read a Party from a file.
:type filename: str
:param filename:
File to read from - can be a list of files, and can contain
wildcards.
:type read_detection_catalog: bool
:param read_detection_catalog:
Whether to read the detection catalog or not, if Fa... | [
"Read",
"a",
"Party",
"from",
"a",
"file",
"."
] | python | train |
LuqueDaniel/pybooru | pybooru/api_moebooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_moebooru.py#L309-L317 | def wiki_create(self, title, body):
"""Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page.
body (str): The body of the wiki page.
"""
params = {'wiki_page[title]': title, 'wiki_page[body]': body}... | [
"def",
"wiki_create",
"(",
"self",
",",
"title",
",",
"body",
")",
":",
"params",
"=",
"{",
"'wiki_page[title]'",
":",
"title",
",",
"'wiki_page[body]'",
":",
"body",
"}",
"return",
"self",
".",
"_get",
"(",
"'wiki/create'",
",",
"params",
",",
"method",
... | Action to lets you create a wiki page (Requires login) (UNTESTED).
Parameters:
title (str): The title of the wiki page.
body (str): The body of the wiki page. | [
"Action",
"to",
"lets",
"you",
"create",
"a",
"wiki",
"page",
"(",
"Requires",
"login",
")",
"(",
"UNTESTED",
")",
"."
] | python | train |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L170-L198 | def _GetAttributeScripts(self, attribute_data, dest_dir):
"""Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping meta... | [
"def",
"_GetAttributeScripts",
"(",
"self",
",",
"attribute_data",
",",
"dest_dir",
")",
":",
"script_dict",
"=",
"{",
"}",
"attribute_data",
"=",
"attribute_data",
"or",
"{",
"}",
"metadata_key",
"=",
"'%s-script'",
"%",
"self",
".",
"script_type",
"metadata_va... | Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping metadata keys to files storing scripts. | [
"Retrieve",
"the",
"scripts",
"from",
"attribute",
"metadata",
"."
] | python | train |
liampauling/betfair | betfairlightweight/endpoints/historic.py | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/historic.py#L22-L33 | def get_my_data(self, session=None):
"""
Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetMyData'
... | [
"def",
"get_my_data",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'GetMyData'",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
... | Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict | [
"Returns",
"a",
"list",
"of",
"data",
"descriptions",
"for",
"data",
"which",
"has",
"been",
"purchased",
"by",
"the",
"signed",
"in",
"user",
"."
] | python | train |
keenlabs/KeenClient-Python | keen/api.py | https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/api.py#L113-L127 | def post_events(self, events):
"""
Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload
"""
url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
sel... | [
"def",
"post_events",
"(",
"self",
",",
"events",
")",
":",
"url",
"=",
"\"{0}/{1}/projects/{2}/events\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"api_version",
",",
"self",
".",
"project_id",
")",
"headers",
"=",
"utilities",
".",
... | Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload | [
"Posts",
"a",
"single",
"event",
"to",
"the",
"Keen",
"IO",
"API",
".",
"The",
"write",
"key",
"must",
"be",
"set",
"first",
"."
] | python | train |
aiogram/aiogram | aiogram/types/chat.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/chat.py#L530-L539 | async def typing(cls, sleep=None):
"""
Do typing
:param sleep: sleep timeout
:return:
"""
if isinstance(sleep, str):
sleep = cls.calc_timeout(sleep)
await cls._do(cls.TYPING, sleep) | [
"async",
"def",
"typing",
"(",
"cls",
",",
"sleep",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"sleep",
",",
"str",
")",
":",
"sleep",
"=",
"cls",
".",
"calc_timeout",
"(",
"sleep",
")",
"await",
"cls",
".",
"_do",
"(",
"cls",
".",
"TYPING",
... | Do typing
:param sleep: sleep timeout
:return: | [
"Do",
"typing"
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/settings_v1alpha1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/settings_v1alpha1_api.py#L879-L903 | def read_namespaced_pod_preset(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_preset # noqa: E501
read the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True... | [
"def",
"read_namespaced_pod_preset",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return... | read_namespaced_pod_preset # noqa: E501
read the specified PodPreset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_preset(name, namespace, async_req=True)
... | [
"read_namespaced_pod_preset",
"#",
"noqa",
":",
"E501"
] | python | train |
saltstack/salt | salt/modules/schedule.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L598-L650 | def enable_job(name, **kwargs):
'''
Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1
'''
ret = {'comment': [],
'result': True}
if not name:
ret['comment'] = 'Job name is required.'
ret['result'] ... | [
"def",
"enable_job",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'comment'",
":",
"[",
"]",
",",
"'result'",
":",
"True",
"}",
"if",
"not",
"name",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Job name is required.'",
"ret",
"[",
... | Enable a job in the minion's schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.enable_job job1 | [
"Enable",
"a",
"job",
"in",
"the",
"minion",
"s",
"schedule"
] | python | train |
bbangert/lettuce_webdriver | lettuce_webdriver/screenshot.py | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/screenshot.py#L13-L22 | def set_save_directory(base, source):
"""Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. """
root = os.path.join(base, source)
if not os.path.isdir(root):
os.makedirs(root)
world.screensho... | [
"def",
"set_save_directory",
"(",
"base",
",",
"source",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"source",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
")",
":",
"os",
".",
"makedirs",
"(",
"roo... | Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. | [
"Sets",
"the",
"root",
"save",
"directory",
"for",
"saving",
"screenshots",
".",
"Screenshots",
"will",
"be",
"saved",
"in",
"subdirectories",
"under",
"this",
"directory",
"by",
"browser",
"window",
"size",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/ext/dataforms.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L270-L299 | def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the elemen... | [
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"doc",
")",
":",
"if",
"self",
".",
"type",
"is",
"not",
"None",
"and",
"self",
".",
"type",
"not",
"in",
"self",
".",
"allowed_types",
":",
"raise",
"ValueError",
"(",
"\"Invalid form field ... | Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libx... | [
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] | python | valid |
boriel/zxbasic | arch/zx48k/optimizer.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L1654-L1662 | def get_label_idx(self, label):
""" Returns the index of a label.
Returns None if not found.
"""
for i in range(len(self)):
if self.mem[i].is_label and self.mem[i].inst == label:
return i
return None | [
"def",
"get_label_idx",
"(",
"self",
",",
"label",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"if",
"self",
".",
"mem",
"[",
"i",
"]",
".",
"is_label",
"and",
"self",
".",
"mem",
"[",
"i",
"]",
".",
"inst",
"... | Returns the index of a label.
Returns None if not found. | [
"Returns",
"the",
"index",
"of",
"a",
"label",
".",
"Returns",
"None",
"if",
"not",
"found",
"."
] | python | train |
themartorana/python-postmark | postmark/core.py | https://github.com/themartorana/python-postmark/blob/3087f6894ec2790e295fd59eba9c57da9de78d1c/postmark/core.py#L615-L620 | def remove_message(self, message):
'''
Remove a message from the batch
'''
if message in self.__messages:
self.__messages.remove(message) | [
"def",
"remove_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
"in",
"self",
".",
"__messages",
":",
"self",
".",
"__messages",
".",
"remove",
"(",
"message",
")"
] | Remove a message from the batch | [
"Remove",
"a",
"message",
"from",
"the",
"batch"
] | python | train |
jtwhite79/pyemu | pyemu/pst/pst_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_utils.py#L289-L304 | def write_input_files(pst):
"""write parameter values to a model input files using a template files with
current parameter values (stored in Pst.parameter_data.parval1).
This is a simple implementation of what PEST does. It does not
handle all the special cases, just a basic function...user beware
... | [
"def",
"write_input_files",
"(",
"pst",
")",
":",
"par",
"=",
"pst",
".",
"parameter_data",
"par",
".",
"loc",
"[",
":",
",",
"\"parval1_trans\"",
"]",
"=",
"(",
"par",
".",
"parval1",
"*",
"par",
".",
"scale",
")",
"+",
"par",
".",
"offset",
"for",
... | write parameter values to a model input files using a template files with
current parameter values (stored in Pst.parameter_data.parval1).
This is a simple implementation of what PEST does. It does not
handle all the special cases, just a basic function...user beware
Parameters
----------
pst ... | [
"write",
"parameter",
"values",
"to",
"a",
"model",
"input",
"files",
"using",
"a",
"template",
"files",
"with",
"current",
"parameter",
"values",
"(",
"stored",
"in",
"Pst",
".",
"parameter_data",
".",
"parval1",
")",
".",
"This",
"is",
"a",
"simple",
"im... | python | train |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L454-L463 | def NewOrClause(self, pred_str):
"""
{.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning.
"""
if pred_str:
pred = self._GetPredicate(pred_str, test_attr=False)
else:
pred = None
self.current_section.NewOrClau... | [
"def",
"NewOrClause",
"(",
"self",
",",
"pred_str",
")",
":",
"if",
"pred_str",
":",
"pred",
"=",
"self",
".",
"_GetPredicate",
"(",
"pred_str",
",",
"test_attr",
"=",
"False",
")",
"else",
":",
"pred",
"=",
"None",
"self",
".",
"current_section",
".",
... | {.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning. | [
"{",
".",
"or",
"...",
"}",
"Can",
"appear",
"inside",
"predicate",
"blocks",
"or",
"section",
"blocks",
"with",
"slightly",
"different",
"meaning",
"."
] | python | train |
tanghaibao/goatools | goatools/obo_parser.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L245-L251 | def get_all_child_edges(self):
"""Return tuples for all child GO IDs, containing current GO ID and child GO ID."""
all_child_edges = set()
for parent in self.children:
all_child_edges.add((parent.item_id, self.item_id))
all_child_edges |= parent.get_all_child_edges()
... | [
"def",
"get_all_child_edges",
"(",
"self",
")",
":",
"all_child_edges",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"children",
":",
"all_child_edges",
".",
"add",
"(",
"(",
"parent",
".",
"item_id",
",",
"self",
".",
"item_id",
")",
")",
... | Return tuples for all child GO IDs, containing current GO ID and child GO ID. | [
"Return",
"tuples",
"for",
"all",
"child",
"GO",
"IDs",
"containing",
"current",
"GO",
"ID",
"and",
"child",
"GO",
"ID",
"."
] | python | train |
ktdreyer/txkoji | txkoji/connection.py | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L356-L370 | def listTagged(self, *args, **kwargs):
"""
List builds tagged with a tag.
Calls "listTagged" XML-RPC.
:returns: deferred that when fired returns a list of Build objects.
"""
data = yield self.call('listTagged', *args, **kwargs)
builds = []
for bdata in d... | [
"def",
"listTagged",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"yield",
"self",
".",
"call",
"(",
"'listTagged'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"builds",
"=",
"[",
"]",
"for",
"bdata",
"in",
... | List builds tagged with a tag.
Calls "listTagged" XML-RPC.
:returns: deferred that when fired returns a list of Build objects. | [
"List",
"builds",
"tagged",
"with",
"a",
"tag",
"."
] | python | train |
Dentosal/python-sc2 | sc2/client.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/client.py#L249-L270 | async def query_available_abilities(
self, units: Union[List[Unit], "Units"], ignore_resource_requirements: bool = False
) -> List[List[AbilityId]]:
""" Query abilities of multiple units """
if not isinstance(units, list):
""" Deprecated, accepting a single unit may be removed in... | [
"async",
"def",
"query_available_abilities",
"(",
"self",
",",
"units",
":",
"Union",
"[",
"List",
"[",
"Unit",
"]",
",",
"\"Units\"",
"]",
",",
"ignore_resource_requirements",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"List",
"[",
"AbilityId",
"]... | Query abilities of multiple units | [
"Query",
"abilities",
"of",
"multiple",
"units"
] | python | train |
jazzband/django-authority | authority/permissions.py | https://github.com/jazzband/django-authority/blob/58e08483cdd91a6a69e8019dd2a2edf68531ae97/authority/permissions.py#L119-L138 | def _user_perm_cache(self):
"""
cached_permissions will generate the cache in a lazy fashion.
"""
# Check to see if the cache has been primed.
if not self.user:
return {}
cache_filled = getattr(
self.user,
'_authority_perm_cache_filled'... | [
"def",
"_user_perm_cache",
"(",
"self",
")",
":",
"# Check to see if the cache has been primed.",
"if",
"not",
"self",
".",
"user",
":",
"return",
"{",
"}",
"cache_filled",
"=",
"getattr",
"(",
"self",
".",
"user",
",",
"'_authority_perm_cache_filled'",
",",
"Fals... | cached_permissions will generate the cache in a lazy fashion. | [
"cached_permissions",
"will",
"generate",
"the",
"cache",
"in",
"a",
"lazy",
"fashion",
"."
] | python | train |
nws-cip/zenconf | zenconf/merged_config.py | https://github.com/nws-cip/zenconf/blob/fc96706468c0741fb1b54b2eeb9f9225737e3e36/zenconf/merged_config.py#L47-L70 | def walk_recursive(f, data):
"""
Recursively apply a function to all dicts in a nested dictionary
:param f: Function to apply
:param data: Dictionary (possibly nested) to recursively apply
function to
:return:
"""
results = {}
if isinstance(data, list):
return [walk_recursiv... | [
"def",
"walk_recursive",
"(",
"f",
",",
"data",
")",
":",
"results",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"[",
"walk_recursive",
"(",
"f",
",",
"d",
")",
"for",
"d",
"in",
"data",
"]",
"elif",
"isinstance... | Recursively apply a function to all dicts in a nested dictionary
:param f: Function to apply
:param data: Dictionary (possibly nested) to recursively apply
function to
:return: | [
"Recursively",
"apply",
"a",
"function",
"to",
"all",
"dicts",
"in",
"a",
"nested",
"dictionary"
] | python | train |
defunkt/pystache | pystache/parser.py | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L242-L338 | def parse(self, template):
"""
Parse a template string starting at some index.
This method uses the current tag delimiter.
Arguments:
template: a unicode string that is the template to parse.
index: the index at which to start parsing.
Returns:
... | [
"def",
"parse",
"(",
"self",
",",
"template",
")",
":",
"self",
".",
"_compile_delimiters",
"(",
")",
"start_index",
"=",
"0",
"content_end_index",
",",
"parsed_section",
",",
"section_key",
"=",
"None",
",",
"None",
",",
"None",
"parsed_template",
"=",
"Par... | Parse a template string starting at some index.
This method uses the current tag delimiter.
Arguments:
template: a unicode string that is the template to parse.
index: the index at which to start parsing.
Returns:
a ParsedTemplate instance. | [
"Parse",
"a",
"template",
"string",
"starting",
"at",
"some",
"index",
"."
] | python | train |
Kautenja/nes-py | nes_py/_image_viewer.py | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_image_viewer.py#L50-L80 | def show(self, frame):
"""
Show an array of pixels on the window.
Args:
frame (numpy.ndarray): the frame to show on the window
Returns:
None
"""
# check that the frame has the correct dimensions
if len(frame.shape) != 3:
raise... | [
"def",
"show",
"(",
"self",
",",
"frame",
")",
":",
"# check that the frame has the correct dimensions",
"if",
"len",
"(",
"frame",
".",
"shape",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'frame should have shape with only 3 dimensions'",
")",
"# open the wind... | Show an array of pixels on the window.
Args:
frame (numpy.ndarray): the frame to show on the window
Returns:
None | [
"Show",
"an",
"array",
"of",
"pixels",
"on",
"the",
"window",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/util/convergence.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/util/convergence.py#L325-L357 | def multi_curve_fit(xs, ys, verbose):
"""
fit multiple functions to the x, y data, return the best fit
"""
#functions = {exponential: p0_exponential, reciprocal: p0_reciprocal, single_reciprocal: p0_single_reciprocal}
functions = {
exponential: p0_exponential,
reciprocal: p0_reciproc... | [
"def",
"multi_curve_fit",
"(",
"xs",
",",
"ys",
",",
"verbose",
")",
":",
"#functions = {exponential: p0_exponential, reciprocal: p0_reciprocal, single_reciprocal: p0_single_reciprocal}",
"functions",
"=",
"{",
"exponential",
":",
"p0_exponential",
",",
"reciprocal",
":",
"p0... | fit multiple functions to the x, y data, return the best fit | [
"fit",
"multiple",
"functions",
"to",
"the",
"x",
"y",
"data",
"return",
"the",
"best",
"fit"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vswitch.py#L402-L414 | def get_vnetwork_dvpgs_output_vnetwork_dvpgs_datacenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvpgs = ET.Element("get_vnetwork_dvpgs")
config = get_vnetwork_dvpgs
output = ET.SubElement(get_vnetwork_dvpgs, "output")
... | [
"def",
"get_vnetwork_dvpgs_output_vnetwork_dvpgs_datacenter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_dvpgs",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_dvpgs\"",
")",
"config"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
horazont/aioxmpp | aioxmpp/pep/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pep/service.py#L326-L338 | def close(self):
"""
Unclaim the PEP node and unregister the registered features.
It is not necessary to call close if this claim is managed by
:class:`~aioxmpp.pep.register_pep_node`.
"""
if self._closed:
return
self._closed = True
self._pep... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"_pep_service",
".",
"_unclaim",
"(",
"self",
".",
"node_namespace",
")",
"self",
".",
"_unregister",
"(",
")"
] | Unclaim the PEP node and unregister the registered features.
It is not necessary to call close if this claim is managed by
:class:`~aioxmpp.pep.register_pep_node`. | [
"Unclaim",
"the",
"PEP",
"node",
"and",
"unregister",
"the",
"registered",
"features",
"."
] | python | train |
openid/python-openid | openid/consumer/consumer.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L687-L699 | def _checkSetupNeeded(self, message):
"""Check an id_res message to see if it is a
checkid_immediate cancel response.
@raises SetupNeededError: if it is a checkid_immediate cancellation
"""
# In OpenID 1, we check to see if this is a cancel from
# immediate mode by the p... | [
"def",
"_checkSetupNeeded",
"(",
"self",
",",
"message",
")",
":",
"# In OpenID 1, we check to see if this is a cancel from",
"# immediate mode by the presence of the user_setup_url",
"# parameter.",
"if",
"message",
".",
"isOpenID1",
"(",
")",
":",
"user_setup_url",
"=",
"me... | Check an id_res message to see if it is a
checkid_immediate cancel response.
@raises SetupNeededError: if it is a checkid_immediate cancellation | [
"Check",
"an",
"id_res",
"message",
"to",
"see",
"if",
"it",
"is",
"a",
"checkid_immediate",
"cancel",
"response",
"."
] | python | train |
brianhie/scanorama | scanorama/scanorama.py | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L114-L169 | def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE,
verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX,
sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False,
geosketch_max=20000, n_iter=1, union=False, hvg=None):
"""Integrate a list of data sets.
Pa... | [
"def",
"integrate",
"(",
"datasets_full",
",",
"genes_list",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"verbose",
"=",
"VERBOSE",
",",
"ds_names",
"=",
"None",
",",
"dimred",
"=",
"DIMRED",
",",
"approx",
"=",
"APPROX",
",",
"sigma",
"=",
"SIGMA",
",",
... | Integrate a list of data sets.
Parameters
----------
datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray`
Data sets to integrate and correct.
genes_list: `list` of `list` of `string`
List of genes for each data set.
batch_size: `int`, optional (default: `5000`)
... | [
"Integrate",
"a",
"list",
"of",
"data",
"sets",
"."
] | python | train |
aio-libs/aioredis | aioredis/pubsub.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/pubsub.py#L313-L324 | def iter(self, *, encoding=None, decoder=None):
"""Returns async iterator.
Usage example:
>>> async for ch, msg in mpsc.iter():
... print(ch, msg)
"""
return _IterHelper(self,
is_active=lambda r: not r._queue.exhausted,
... | [
"def",
"iter",
"(",
"self",
",",
"*",
",",
"encoding",
"=",
"None",
",",
"decoder",
"=",
"None",
")",
":",
"return",
"_IterHelper",
"(",
"self",
",",
"is_active",
"=",
"lambda",
"r",
":",
"not",
"r",
".",
"_queue",
".",
"exhausted",
",",
"encoding",
... | Returns async iterator.
Usage example:
>>> async for ch, msg in mpsc.iter():
... print(ch, msg) | [
"Returns",
"async",
"iterator",
"."
] | python | train |
reingart/pyafipws | utils.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L903-L919 | def abrir_conf(config_file, debug=False):
"Abrir el archivo de configuración (usar primer parámetro como ruta)"
# en principio, usar el nombre de archivo predeterminado
# si se pasa el archivo de configuración por parámetro, confirmar que exista
# y descartar que sea una opción
if len(sys.argv)>1:
... | [
"def",
"abrir_conf",
"(",
"config_file",
",",
"debug",
"=",
"False",
")",
":",
"# en principio, usar el nombre de archivo predeterminado",
"# si se pasa el archivo de configuración por parámetro, confirmar que exista",
"# y descartar que sea una opción",
"if",
"len",
"(",
"sys",
".... | Abrir el archivo de configuración (usar primer parámetro como ruta) | [
"Abrir",
"el",
"archivo",
"de",
"configuración",
"(",
"usar",
"primer",
"parámetro",
"como",
"ruta",
")"
] | python | train |
numenta/nupic | src/nupic/algorithms/fdrutilities.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L65-L94 | def generateCoincMatrix(nCoinc=10, length=500, activity=50):
"""
Generate a coincidence matrix. This is used to generate random inputs to the
temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total of 'activity' bits on.... | [
"def",
"generateCoincMatrix",
"(",
"nCoinc",
"=",
"10",
",",
"length",
"=",
"500",
",",
"activity",
"=",
"50",
")",
":",
"coincMatrix0",
"=",
"SM32",
"(",
"int",
"(",
"nCoinc",
")",
",",
"int",
"(",
"length",
")",
")",
"theOnes",
"=",
"numpy",
".",
... | Generate a coincidence matrix. This is used to generate random inputs to the
temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total of 'activity' bits on.
Parameters:
-----------------------------------------------
n... | [
"Generate",
"a",
"coincidence",
"matrix",
".",
"This",
"is",
"used",
"to",
"generate",
"random",
"inputs",
"to",
"the",
"temporal",
"learner",
"and",
"to",
"compare",
"the",
"predicted",
"output",
"against",
"."
] | python | valid |
timothydmorton/isochrones | isochrones/starmodel.py | https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L559-L577 | def mnest_basename(self):
"""Full path to basename
"""
if not hasattr(self, '_mnest_basename'):
s = self.labelstring
if s=='0_0':
s = 'single'
elif s=='0_0-0_1':
s = 'binary'
elif s=='0_0-0_1-0_2':
s ... | [
"def",
"mnest_basename",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_mnest_basename'",
")",
":",
"s",
"=",
"self",
".",
"labelstring",
"if",
"s",
"==",
"'0_0'",
":",
"s",
"=",
"'single'",
"elif",
"s",
"==",
"'0_0-0_1'",
":",
"... | Full path to basename | [
"Full",
"path",
"to",
"basename"
] | python | train |
getfleety/coralillo | coralillo/fields.py | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/fields.py#L173-L177 | def delete(self, redis):
''' Deletes this field's value from the databse. Should be implemented
in special cases '''
value = getattr(self.obj, self.name)
redis.srem(self.key() + ':' + value, self.obj.id) | [
"def",
"delete",
"(",
"self",
",",
"redis",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
".",
"obj",
",",
"self",
".",
"name",
")",
"redis",
".",
"srem",
"(",
"self",
".",
"key",
"(",
")",
"+",
"':'",
"+",
"value",
",",
"self",
".",
"obj",
... | Deletes this field's value from the databse. Should be implemented
in special cases | [
"Deletes",
"this",
"field",
"s",
"value",
"from",
"the",
"databse",
".",
"Should",
"be",
"implemented",
"in",
"special",
"cases"
] | python | train |
ClericPy/torequests | torequests/utils.py | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L622-L633 | def search(self, string, default=None):
"""Use re.search to find the result
:rtype: list"""
default = default if default else []
result = [item[1] for item in self.container if item[0].search(string)]
if self.ensure_mapping:
assert len(result) < 2, "%s matches more t... | [
"def",
"search",
"(",
"self",
",",
"string",
",",
"default",
"=",
"None",
")",
":",
"default",
"=",
"default",
"if",
"default",
"else",
"[",
"]",
"result",
"=",
"[",
"item",
"[",
"1",
"]",
"for",
"item",
"in",
"self",
".",
"container",
"if",
"item"... | Use re.search to find the result
:rtype: list | [
"Use",
"re",
".",
"search",
"to",
"find",
"the",
"result"
] | python | train |
Neurosim-lab/netpyne | doc/source/code/HHCellFile.py | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/doc/source/code/HHCellFile.py#L66-L78 | def defineBiophysics(self):
"""Assign the membrane properties across the cell."""
# Insert active Hodgkin-Huxley current in the soma
self.soma.insert('hh')
self.soma.gnabar_hh = 0.12 # Sodium conductance in S/cm2
self.soma.gkbar_hh = 0.036 # Potassium conductance in S/cm2
... | [
"def",
"defineBiophysics",
"(",
"self",
")",
":",
"# Insert active Hodgkin-Huxley current in the soma",
"self",
".",
"soma",
".",
"insert",
"(",
"'hh'",
")",
"self",
".",
"soma",
".",
"gnabar_hh",
"=",
"0.12",
"# Sodium conductance in S/cm2",
"self",
".",
"soma",
... | Assign the membrane properties across the cell. | [
"Assign",
"the",
"membrane",
"properties",
"across",
"the",
"cell",
"."
] | python | train |
noahbenson/neuropythy | neuropythy/util/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/util/core.py#L819-L845 | def tangent(x, null=(-np.inf, np.inf), rtol=default_rtol, atol=default_atol):
'''
tangent(x) is equivalent to tan(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x == -pi/2 or... | [
"def",
"tangent",
"(",
"x",
",",
"null",
"=",
"(",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
")",
",",
"rtol",
"=",
"default_rtol",
",",
"atol",
"=",
"default_atol",
")",
":",
"if",
"sps",
".",
"issparse",
"(",
"x",
")",
":",
"x",
"=",
"x... | tangent(x) is equivalent to tan(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x == -pi/2 or -pi/2. If only one number is given, then it is
used for both values; otherwise the fi... | [
"tangent",
"(",
"x",
")",
"is",
"equivalent",
"to",
"tan",
"(",
"x",
")",
"except",
"that",
"it",
"also",
"works",
"on",
"sparse",
"arrays",
"."
] | python | train |
open-homeautomation/pknx | knxip/ip.py | https://github.com/open-homeautomation/pknx/blob/a8aed8271563923c447aa330ba7c1c2927286f7a/knxip/ip.py#L129-L170 | def from_body(cls, cemi):
"""Create a new CEMIMessage initialized from the given CEMI data."""
# TODO: check that length matches
message = cls()
message.code = cemi[0]
offset = cemi[1]
message.ctl1 = cemi[2 + offset]
message.ctl2 = cemi[3 + offset]
messa... | [
"def",
"from_body",
"(",
"cls",
",",
"cemi",
")",
":",
"# TODO: check that length matches",
"message",
"=",
"cls",
"(",
")",
"message",
".",
"code",
"=",
"cemi",
"[",
"0",
"]",
"offset",
"=",
"cemi",
"[",
"1",
"]",
"message",
".",
"ctl1",
"=",
"cemi",
... | Create a new CEMIMessage initialized from the given CEMI data. | [
"Create",
"a",
"new",
"CEMIMessage",
"initialized",
"from",
"the",
"given",
"CEMI",
"data",
"."
] | python | train |
simoninireland/epyc | epyc/clusterlab.py | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/clusterlab.py#L351-L365 | def cancelPendingResultsFor( self, params ):
"""Cancel any results pending for experiments at the given point
in the parameter space.
:param params: the experimental parameters"""
# grab the result job ids
jobs = self.pendingResultsFor(params)
if len(jo... | [
"def",
"cancelPendingResultsFor",
"(",
"self",
",",
"params",
")",
":",
"# grab the result job ids",
"jobs",
"=",
"self",
".",
"pendingResultsFor",
"(",
"params",
")",
"if",
"len",
"(",
"jobs",
")",
">",
"0",
":",
"# abort in the cluster",
"self",
".",
"_abort... | Cancel any results pending for experiments at the given point
in the parameter space.
:param params: the experimental parameters | [
"Cancel",
"any",
"results",
"pending",
"for",
"experiments",
"at",
"the",
"given",
"point",
"in",
"the",
"parameter",
"space",
"."
] | python | train |
QuantEcon/QuantEcon.py | quantecon/lss.py | https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/lss.py#L160-L200 | def simulate(self, ts_length=100, random_state=None):
r"""
Simulate a time series of length ts_length, first drawing
.. math::
x_0 \sim N(\mu_0, \Sigma_0)
Parameters
----------
ts_length : scalar(int), optional(default=100)
The length of the sim... | [
"def",
"simulate",
"(",
"self",
",",
"ts_length",
"=",
"100",
",",
"random_state",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"x0",
"=",
"multivariate_normal",
"(",
"self",
".",
"mu_0",
".",
"flatten",
"(",
... | r"""
Simulate a time series of length ts_length, first drawing
.. math::
x_0 \sim N(\mu_0, \Sigma_0)
Parameters
----------
ts_length : scalar(int), optional(default=100)
The length of the simulation
random_state : int or np.random.RandomState, o... | [
"r",
"Simulate",
"a",
"time",
"series",
"of",
"length",
"ts_length",
"first",
"drawing"
] | python | train |
phaethon/kamene | kamene/plist.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/plist.py#L479-L490 | def summary(self, prn=None, lfilter=None):
"""prints a summary of each SndRcv packet pair
prn: function to apply to each packet pair instead of lambda s, r: "%s ==> %s" % (s.summary(),r.summary())
lfilter: truth function to apply to each packet pair to decide whether it will be displayed"""
for s, r... | [
"def",
"summary",
"(",
"self",
",",
"prn",
"=",
"None",
",",
"lfilter",
"=",
"None",
")",
":",
"for",
"s",
",",
"r",
"in",
"self",
".",
"res",
":",
"if",
"lfilter",
"is",
"not",
"None",
":",
"if",
"not",
"lfilter",
"(",
"s",
",",
"r",
")",
":... | prints a summary of each SndRcv packet pair
prn: function to apply to each packet pair instead of lambda s, r: "%s ==> %s" % (s.summary(),r.summary())
lfilter: truth function to apply to each packet pair to decide whether it will be displayed | [
"prints",
"a",
"summary",
"of",
"each",
"SndRcv",
"packet",
"pair",
"prn",
":",
"function",
"to",
"apply",
"to",
"each",
"packet",
"pair",
"instead",
"of",
"lambda",
"s",
"r",
":",
"%s",
"==",
">",
"%s",
"%",
"(",
"s",
".",
"summary",
"()",
"r",
".... | python | train |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L492-L503 | def get_hkr_state(self):
"""Get the thermostate state."""
self.update()
try:
return {
126.5: 'off',
127.0: 'on',
self.eco_temperature: 'eco',
self.comfort_temperature: 'comfort'
}[self.target_temperature]
... | [
"def",
"get_hkr_state",
"(",
"self",
")",
":",
"self",
".",
"update",
"(",
")",
"try",
":",
"return",
"{",
"126.5",
":",
"'off'",
",",
"127.0",
":",
"'on'",
",",
"self",
".",
"eco_temperature",
":",
"'eco'",
",",
"self",
".",
"comfort_temperature",
":"... | Get the thermostate state. | [
"Get",
"the",
"thermostate",
"state",
"."
] | python | train |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/withdraw.py | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/withdraw.py#L97-L125 | def withdraw(self, uuid, organization, from_date=None, to_date=None):
"""Withdraw a unique identity from an organization.
This method removes all the enrollments between the unique identity,
identified by <uuid>, and <organization>. Both entities must exist
on the registry before being ... | [
"def",
"withdraw",
"(",
"self",
",",
"uuid",
",",
"organization",
",",
"from_date",
"=",
"None",
",",
"to_date",
"=",
"None",
")",
":",
"# Empty or None values for uuid and organizations are not allowed,",
"# so do nothing",
"if",
"not",
"uuid",
"or",
"not",
"organi... | Withdraw a unique identity from an organization.
This method removes all the enrollments between the unique identity,
identified by <uuid>, and <organization>. Both entities must exist
on the registry before being deleted.
When a period of time is given using either <from_date> and <to... | [
"Withdraw",
"a",
"unique",
"identity",
"from",
"an",
"organization",
"."
] | python | train |
knagra/farnsworth | workshift/views.py | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L62-L192 | def add_workshift_context(request):
""" Add workshift variables to all dictionaries passed to templates. """
if not request.user.is_authenticated():
return {}
if Semester.objects.count() < 1:
return {
"WORKSHIFT_ENABLED": False,
}
# Current semester is for navbar no... | [
"def",
"add_workshift_context",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"{",
"}",
"if",
"Semester",
".",
"objects",
".",
"count",
"(",
")",
"<",
"1",
":",
"return",
"{",
"\"WORKSH... | Add workshift variables to all dictionaries passed to templates. | [
"Add",
"workshift",
"variables",
"to",
"all",
"dictionaries",
"passed",
"to",
"templates",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L617-L629 | def getskyimg(self,chip):
"""
Notes
=====
Return an array representing the sky image for the detector. The value
of the sky is what would actually be subtracted from the exposure by
the skysub step.
:units: electrons
"""
sci_chip = self._image[s... | [
"def",
"getskyimg",
"(",
"self",
",",
"chip",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"return",
"np",
".",
"ones",
"(",
"sci_chip",
".",
"image_shape",
",",
"dtype",
"=",
"sci_chip",
".",
"i... | Notes
=====
Return an array representing the sky image for the detector. The value
of the sky is what would actually be subtracted from the exposure by
the skysub step.
:units: electrons | [
"Notes",
"=====",
"Return",
"an",
"array",
"representing",
"the",
"sky",
"image",
"for",
"the",
"detector",
".",
"The",
"value",
"of",
"the",
"sky",
"is",
"what",
"would",
"actually",
"be",
"subtracted",
"from",
"the",
"exposure",
"by",
"the",
"skysub",
"s... | python | train |
pydata/xarray | xarray/plot/plot.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/plot/plot.py#L823-L869 | def pcolormesh(x, y, z, ax, infer_intervals=None, **kwargs):
"""
Pseudocolor plot of 2d DataArray
Wraps :func:`matplotlib:matplotlib.pyplot.pcolormesh`
"""
# decide on a default for infer_intervals (GH781)
x = np.asarray(x)
if infer_intervals is None:
if hasattr(ax, 'projection'):
... | [
"def",
"pcolormesh",
"(",
"x",
",",
"y",
",",
"z",
",",
"ax",
",",
"infer_intervals",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# decide on a default for infer_intervals (GH781)",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"if",
"infer_intervals... | Pseudocolor plot of 2d DataArray
Wraps :func:`matplotlib:matplotlib.pyplot.pcolormesh` | [
"Pseudocolor",
"plot",
"of",
"2d",
"DataArray"
] | python | train |
jingw/pyhdfs | pyhdfs.py | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L447-L462 | def concat(self, target, sources, **kwargs):
"""Concat existing files together.
For preconditions, see
https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/filesystem/filesystem.html#void_concatPath_p_Path_sources
:param target: the path to the target destination.
... | [
"def",
"concat",
"(",
"self",
",",
"target",
",",
"sources",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"sources",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"\"sources should be a list\"",
")",
"if",
"any",
"(",
"','",
"in... | Concat existing files together.
For preconditions, see
https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/filesystem/filesystem.html#void_concatPath_p_Path_sources
:param target: the path to the target destination.
:param sources: the paths to the sources to use f... | [
"Concat",
"existing",
"files",
"together",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xorbrecordedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordedit.py#L222-L248 | def setRecord( self, record ):
"""
Sets the record instance for this widget to the inputed record.
:param record | <orb.Table>
"""
self._record = record
if ( not record ):
return
self.setModel(record.__class__... | [
"def",
"setRecord",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"_record",
"=",
"record",
"if",
"(",
"not",
"record",
")",
":",
"return",
"self",
".",
"setModel",
"(",
"record",
".",
"__class__",
")",
"schema",
"=",
"self",
".",
"model",
"(",
... | Sets the record instance for this widget to the inputed record.
:param record | <orb.Table> | [
"Sets",
"the",
"record",
"instance",
"for",
"this",
"widget",
"to",
"the",
"inputed",
"record",
".",
":",
"param",
"record",
"|",
"<orb",
".",
"Table",
">"
] | python | train |
bmwcarit/zubbi | zubbi/utils.py | https://github.com/bmwcarit/zubbi/blob/b99dfd6113c0351f13876f4172648c2eb63468ba/zubbi/utils.py#L44-L59 | def prettydate(date):
now = datetime.now(timezone.utc)
"""
Return the relative timeframe between the given date and now.
e.g. 'Just now', 'x days ago', 'x hours ago', ...
When the difference is greater than 7 days, the timestamp will be returned
instead.
"""
diff = now - date
# Sho... | [
"def",
"prettydate",
"(",
"date",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
"timezone",
".",
"utc",
")",
"diff",
"=",
"now",
"-",
"date",
"# Show the timestamp rather than the relative timeframe when the difference",
"# is greater than 7 days",
"if",
"diff",
... | Return the relative timeframe between the given date and now.
e.g. 'Just now', 'x days ago', 'x hours ago', ...
When the difference is greater than 7 days, the timestamp will be returned
instead. | [
"Return",
"the",
"relative",
"timeframe",
"between",
"the",
"given",
"date",
"and",
"now",
"."
] | python | train |
collectiveacuity/labPack | labpack/location/find.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/location/find.py#L296-L366 | def update_positions(self):
'''
a method to update the latest position of all users being tracked
:return: dictionary with user_id keys and location/time dictionary values
NOTE: self.players is updated with position details
{
'us... | [
"def",
"update_positions",
"(",
"self",
")",
":",
"# construct user list",
"user_list",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"positions",
".",
"keys",
"(",
")",
":",
"user_list",
".",
"append",
"(",
"key",
")",
"# return empty result",
"if",
"no... | a method to update the latest position of all users being tracked
:return: dictionary with user_id keys and location/time dictionary values
NOTE: self.players is updated with position details
{
'user_id': {
'time': 0.0,
... | [
"a",
"method",
"to",
"update",
"the",
"latest",
"position",
"of",
"all",
"users",
"being",
"tracked",
":",
"return",
":",
"dictionary",
"with",
"user_id",
"keys",
"and",
"location",
"/",
"time",
"dictionary",
"values",
"NOTE",
":",
"self",
".",
"players",
... | python | train |
signalfx/signalfx-python | signalfx/signalflow/ws.py | https://github.com/signalfx/signalfx-python/blob/650eb9a2b301bcc795e4e3a8c031574ade69849d/signalfx/signalflow/ws.py#L146-L155 | def opened(self):
"""Handler called when the WebSocket connection is opened. The first
thing to do then is to authenticate ourselves."""
request = {
'type': 'authenticate',
'token': self._token,
'userAgent': '{} ws4py/{}'.format(version.user_agent,
... | [
"def",
"opened",
"(",
"self",
")",
":",
"request",
"=",
"{",
"'type'",
":",
"'authenticate'",
",",
"'token'",
":",
"self",
".",
"_token",
",",
"'userAgent'",
":",
"'{} ws4py/{}'",
".",
"format",
"(",
"version",
".",
"user_agent",
",",
"ws4py",
".",
"__ve... | Handler called when the WebSocket connection is opened. The first
thing to do then is to authenticate ourselves. | [
"Handler",
"called",
"when",
"the",
"WebSocket",
"connection",
"is",
"opened",
".",
"The",
"first",
"thing",
"to",
"do",
"then",
"is",
"to",
"authenticate",
"ourselves",
"."
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/teal.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/teal.py#L343-L361 | def execEmbCode(SCOPE, NAME, VAL, TEAL, codeStr):
""" .cfgspc embedded code execution is done here, in a relatively confined
space. The variables available to the code to be executed are:
SCOPE, NAME, VAL, PARENT, TEAL
The code string itself is expected to set a var named OUT
"""
... | [
"def",
"execEmbCode",
"(",
"SCOPE",
",",
"NAME",
",",
"VAL",
",",
"TEAL",
",",
"codeStr",
")",
":",
"# This was all we needed in Python 2.x",
"# OUT = None",
"# exec codeStr",
"# return OUT",
"# In Python 3 (& 2.x) be more explicit: http://bugs.python.org/issue4831",
"PA... | .cfgspc embedded code execution is done here, in a relatively confined
space. The variables available to the code to be executed are:
SCOPE, NAME, VAL, PARENT, TEAL
The code string itself is expected to set a var named OUT | [
".",
"cfgspc",
"embedded",
"code",
"execution",
"is",
"done",
"here",
"in",
"a",
"relatively",
"confined",
"space",
".",
"The",
"variables",
"available",
"to",
"the",
"code",
"to",
"be",
"executed",
"are",
":",
"SCOPE",
"NAME",
"VAL",
"PARENT",
"TEAL",
"Th... | python | train |
isislovecruft/python-gnupg | pretty_bad_protocol/_parsers.py | https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L883-L896 | def _handle_status(self, key, value):
"""Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown.
"""
if key in ("USERID_HINT", "NEED_PASSPHRASE",
"GET_HIDDEN", "SIGEXPIRED", "KEYEXPIRED",
... | [
"def",
"_handle_status",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"(",
"\"USERID_HINT\"",
",",
"\"NEED_PASSPHRASE\"",
",",
"\"GET_HIDDEN\"",
",",
"\"SIGEXPIRED\"",
",",
"\"KEYEXPIRED\"",
",",
"\"GOOD_PASSPHRASE\"",
",",
"\"GOT_IT\"",
"... | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | [
"Parse",
"a",
"status",
"code",
"from",
"the",
"attached",
"GnuPG",
"process",
"."
] | python | train |
reingart/pyafipws | wslpg.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L1389-L1415 | def AjustarLiquidacionUnificado(self):
"Ajustar Liquidación Primaria de Granos"
# limpiar estructuras no utilizadas (si no hay deducciones / retenciones)
for k in ('ajusteDebito', 'ajusteCredito'):
if not any(self.ajuste[k].values()):
del self.ajuste[k]
... | [
"def",
"AjustarLiquidacionUnificado",
"(",
"self",
")",
":",
"# limpiar estructuras no utilizadas (si no hay deducciones / retenciones)",
"for",
"k",
"in",
"(",
"'ajusteDebito'",
",",
"'ajusteCredito'",
")",
":",
"if",
"not",
"any",
"(",
"self",
".",
"ajuste",
"[",
"k... | Ajustar Liquidación Primaria de Granos | [
"Ajustar",
"Liquidación",
"Primaria",
"de",
"Granos"
] | python | train |
fantasticfears/kgekit | kgekit/data.py | https://github.com/fantasticfears/kgekit/blob/5e464e1fc3ae9c7e216f6dd94f879a967d065247/kgekit/data.py#L69-L105 | def shrink_indexes_in_place(self, triples):
"""Uses a union find to find segment."""
_ent_roots = self.UnionFind(self._ent_id)
_rel_roots = self.UnionFind(self._rel_id)
for t in triples:
_ent_roots.add(t.head)
_ent_roots.add(t.tail)
_rel_roots.add(t.... | [
"def",
"shrink_indexes_in_place",
"(",
"self",
",",
"triples",
")",
":",
"_ent_roots",
"=",
"self",
".",
"UnionFind",
"(",
"self",
".",
"_ent_id",
")",
"_rel_roots",
"=",
"self",
".",
"UnionFind",
"(",
"self",
".",
"_rel_id",
")",
"for",
"t",
"in",
"trip... | Uses a union find to find segment. | [
"Uses",
"a",
"union",
"find",
"to",
"find",
"segment",
"."
] | python | valid |
alefnula/tea | tea/shell/__init__.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L276-L297 | def move(source, destination):
"""Move a file or directory (recursively) to another location.
If the destination is on our current file system, then simply use
rename. Otherwise, copy source to the destination and then remove
source.
Args:
source (str): Source file or directory (file or di... | [
"def",
"move",
"(",
"source",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"Move: %s -> %s\"",
"%",
"(",
"source",
",",
"destination",
")",
")",
"try",
":",
"__create_destdir",
"(",
"destination",
")",
"shutil",
".",
"move",
"(",
"source",
... | Move a file or directory (recursively) to another location.
If the destination is on our current file system, then simply use
rename. Otherwise, copy source to the destination and then remove
source.
Args:
source (str): Source file or directory (file or directory to move).
destination ... | [
"Move",
"a",
"file",
"or",
"directory",
"(",
"recursively",
")",
"to",
"another",
"location",
"."
] | python | train |
portantier/habu | habu/cli/cmd_cve_2018_9995.py | https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_cve_2018_9995.py#L14-L67 | def cmd_cve_2018_9995(ip, port, verbose):
"""Exploit the CVE-2018-9995 vulnerability, present on various DVR systems.
Note: Based on the original code from Ezequiel Fernandez (@capitan_alfa).
Reference: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-9995
Example:
\b
$ python habu.cv... | [
"def",
"cmd_cve_2018_9995",
"(",
"ip",
",",
"port",
",",
"verbose",
")",
":",
"url",
"=",
"'http://'",
"+",
"ip",
"+",
"':'",
"+",
"str",
"(",
"port",
")",
"fullhost",
"=",
"url",
"+",
"'/device.rsp?opt=user&cmd=list'",
"headers",
"=",
"{",
"'Host'",
":"... | Exploit the CVE-2018-9995 vulnerability, present on various DVR systems.
Note: Based on the original code from Ezequiel Fernandez (@capitan_alfa).
Reference: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-9995
Example:
\b
$ python habu.cve.2018-9995 82.202.102.42
[
{
... | [
"Exploit",
"the",
"CVE",
"-",
"2018",
"-",
"9995",
"vulnerability",
"present",
"on",
"various",
"DVR",
"systems",
"."
] | python | train |
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#L102-L107 | def restore(self):
"""Restore signal handlers to their original settings."""
signal.signal(signal.SIGINT, self.original_sigint)
signal.signal(signal.SIGTERM, self.original_sigterm)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, self.original_sigbreak) | [
"def",
"restore",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"original_sigint",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"self",
".",
"original_sigterm",
")",
"if",
"os",
"."... | Restore signal handlers to their original settings. | [
"Restore",
"signal",
"handlers",
"to",
"their",
"original",
"settings",
"."
] | python | train |
fitnr/convertdate | convertdate/mayan.py | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/mayan.py#L176-L194 | def next_haab(month, jd):
'''For a given haab month and a julian day count, find the next start of that month on or after the JDC'''
if jd < EPOCH:
raise IndexError("Input day is before Mayan epoch.")
hday, hmonth = to_haab(jd)
if hmonth == month:
days = 1 - hday
else:
cou... | [
"def",
"next_haab",
"(",
"month",
",",
"jd",
")",
":",
"if",
"jd",
"<",
"EPOCH",
":",
"raise",
"IndexError",
"(",
"\"Input day is before Mayan epoch.\"",
")",
"hday",
",",
"hmonth",
"=",
"to_haab",
"(",
"jd",
")",
"if",
"hmonth",
"==",
"month",
":",
"day... | For a given haab month and a julian day count, find the next start of that month on or after the JDC | [
"For",
"a",
"given",
"haab",
"month",
"and",
"a",
"julian",
"day",
"count",
"find",
"the",
"next",
"start",
"of",
"that",
"month",
"on",
"or",
"after",
"the",
"JDC"
] | python | train |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L235-L286 | def patch(self, *args, **kwargs):
"""Update an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema_kwargs = getattr(self, 'patch_schema_kwargs', dict())
schema_kwargs.update({'partial': True})
self.before_marshmallow(args, kwa... | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"schem... | Update an object | [
"Update",
"an",
"object"
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L31-L53 | def run_qsnp(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Run qSNP calling on paired tumor/normal.
"""
if utils.file_exists(out_file):
return out_file
paired = get_paired_bams(align_bams, items)
if paired.normal_bam:
region_files = []
... | [
"def",
"run_qsnp",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"if",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"return",
"out_file",
"paired",
"="... | Run qSNP calling on paired tumor/normal. | [
"Run",
"qSNP",
"calling",
"on",
"paired",
"tumor",
"/",
"normal",
"."
] | python | train |
pettarin/ipapy | ipapy/ipachar.py | https://github.com/pettarin/ipapy/blob/ede4b3c40636f6eb90068369d31a2e75c7115324/ipapy/ipachar.py#L816-L824 | def roundness(self, value):
"""
Set the roundness of the vowel.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_V_ROUNDNESS):
raise ValueError("Unrecognized value for roundness: '%s'" % value)
self.__roundness = value | [
"def",
"roundness",
"(",
"self",
",",
"value",
")",
":",
"if",
"(",
"value",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"value",
"in",
"DG_V_ROUNDNESS",
")",
":",
"raise",
"ValueError",
"(",
"\"Unrecognized value for roundness: '%s'\"",
"%",
"value",
")",
... | Set the roundness of the vowel.
:param str value: the value to be set | [
"Set",
"the",
"roundness",
"of",
"the",
"vowel",
"."
] | python | train |
ARMmbed/yotta | yotta/lib/access_common.py | https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/access_common.py#L324-L346 | def unpackTarballStream(stream, into_directory, hash={}, cache_key=None, origin_info=dict()):
''' Unpack a responses stream that contains a tarball into a directory. If
a hash is provided, then it will be used as a cache key (for future
requests you can try to retrieve the key value from the cache f... | [
"def",
"unpackTarballStream",
"(",
"stream",
",",
"into_directory",
",",
"hash",
"=",
"{",
"}",
",",
"cache_key",
"=",
"None",
",",
"origin_info",
"=",
"dict",
"(",
")",
")",
":",
"cache_key",
"=",
"_encodeCacheKey",
"(",
"cache_key",
")",
"# if the cache is... | Unpack a responses stream that contains a tarball into a directory. If
a hash is provided, then it will be used as a cache key (for future
requests you can try to retrieve the key value from the cache first,
before making the request) | [
"Unpack",
"a",
"responses",
"stream",
"that",
"contains",
"a",
"tarball",
"into",
"a",
"directory",
".",
"If",
"a",
"hash",
"is",
"provided",
"then",
"it",
"will",
"be",
"used",
"as",
"a",
"cache",
"key",
"(",
"for",
"future",
"requests",
"you",
"can",
... | python | valid |
Fantomas42/django-blog-zinnia | zinnia/admin/entry.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/admin/entry.py#L294-L300 | def close_trackbacks(self, request, queryset):
"""
Close the trackbacks for selected entries.
"""
queryset.update(trackback_enabled=False)
self.message_user(
request, _('Trackbacks are now closed for selected entries.')) | [
"def",
"close_trackbacks",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"queryset",
".",
"update",
"(",
"trackback_enabled",
"=",
"False",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'Trackbacks are now closed for selected entries.... | Close the trackbacks for selected entries. | [
"Close",
"the",
"trackbacks",
"for",
"selected",
"entries",
"."
] | python | train |
happyleavesaoc/python-limitlessled | limitlessled/group/commands/__init__.py | https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/group/commands/__init__.py#L5-L31 | def command_set_factory(bridge, group_number, led_type):
"""
Create command set for controlling a specific led group.
:param bridge: The bridge the leds are connected to.
:param group_number: The group number.
:param led_type: The type of the leds.
:return: The created command set.
"""
f... | [
"def",
"command_set_factory",
"(",
"bridge",
",",
"group_number",
",",
"led_type",
")",
":",
"from",
"limitlessled",
".",
"group",
".",
"commands",
".",
"legacy",
"import",
"(",
"CommandSetWhiteLegacy",
",",
"CommandSetRgbwLegacy",
")",
"from",
"limitlessled",
"."... | Create command set for controlling a specific led group.
:param bridge: The bridge the leds are connected to.
:param group_number: The group number.
:param led_type: The type of the leds.
:return: The created command set. | [
"Create",
"command",
"set",
"for",
"controlling",
"a",
"specific",
"led",
"group",
".",
":",
"param",
"bridge",
":",
"The",
"bridge",
"the",
"leds",
"are",
"connected",
"to",
".",
":",
"param",
"group_number",
":",
"The",
"group",
"number",
".",
":",
"pa... | python | train |
apache/airflow | airflow/hooks/mysql_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/mysql_hook.py#L107-L117 | def bulk_load(self, table, tmp_file):
"""
Loads a tab-delimited file into a database table
"""
conn = self.get_conn()
cur = conn.cursor()
cur.execute("""
LOAD DATA LOCAL INFILE '{tmp_file}'
INTO TABLE {table}
""".format(tmp_file=tmp_fil... | [
"def",
"bulk_load",
"(",
"self",
",",
"table",
",",
"tmp_file",
")",
":",
"conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"\"\"\n LOAD DATA LOCAL INFILE '{tmp_file}'\n ... | Loads a tab-delimited file into a database table | [
"Loads",
"a",
"tab",
"-",
"delimited",
"file",
"into",
"a",
"database",
"table"
] | python | test |
log2timeline/plaso | plaso/cli/helpers/database_config.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/helpers/database_config.py#L22-L45 | def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|arg... | [
"def",
"AddArguments",
"(",
"cls",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--user'",
",",
"dest",
"=",
"'username'",
",",
"type",
"=",
"str",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"cls",
".",
"_DEFAULT_U... | Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse grou... | [
"Adds",
"command",
"line",
"arguments",
"the",
"helper",
"supports",
"to",
"an",
"argument",
"group",
"."
] | python | train |
jtwhite79/pyemu | pyemu/prototypes/moouu.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/prototypes/moouu.py#L255-L289 | def crowd_distance(self,obs_df):
"""determine the crowding distance for each candidate solution
Parameters
----------
obs_df : pandas.DataFrame
dataframe with columns of observation names and rows of realizations
Returns
-------
crowd_distance : pand... | [
"def",
"crowd_distance",
"(",
"self",
",",
"obs_df",
")",
":",
"# initialize the distance container",
"crowd_distance",
"=",
"pd",
".",
"Series",
"(",
"data",
"=",
"0.0",
",",
"index",
"=",
"obs_df",
".",
"index",
")",
"for",
"name",
",",
"direction",
"in",
... | determine the crowding distance for each candidate solution
Parameters
----------
obs_df : pandas.DataFrame
dataframe with columns of observation names and rows of realizations
Returns
-------
crowd_distance : pandas.Series
series with index of o... | [
"determine",
"the",
"crowding",
"distance",
"for",
"each",
"candidate",
"solution"
] | python | train |
mapbox/mapbox-sdk-py | mapbox/encoding.py | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L20-L56 | def read_points(features):
""" Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface
"""
for feature in features:
if isinstance(feature, (tuple, list)) and len(feature) == 2:
yield feature
... | [
"def",
"read_points",
"(",
"features",
")",
":",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"feature",
")",
"==",
"2",
":",
"yield",
"feature",
"elif",
"ha... | Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface | [
"Iterable",
"of",
"features",
"to",
"a",
"sequence",
"of",
"point",
"tuples",
"Where",
"features",
"can",
"be",
"either",
"GeoJSON",
"mappings",
"or",
"objects",
"implementing",
"the",
"geo_interface"
] | python | train |
keans/lmnotify | lmnotify/lmnotify.py | https://github.com/keans/lmnotify/blob/b0a5282a582e5090852dc20fea8a135ca258d0d3/lmnotify/lmnotify.py#L599-L614 | def alarm_set(self, time, wake_with_radio=False):
"""
set the alarm clock
:param str time: time of the alarm (format: %H:%M:%S)
:param bool wake_with_radio: if True, radio will be used for the alarm
instead of beep sound
"""
# TODO: c... | [
"def",
"alarm_set",
"(",
"self",
",",
"time",
",",
"wake_with_radio",
"=",
"False",
")",
":",
"# TODO: check for correct time format",
"log",
".",
"debug",
"(",
"\"alarm => set...\"",
")",
"params",
"=",
"{",
"\"enabled\"",
":",
"True",
",",
"\"time\"",
":",
"... | set the alarm clock
:param str time: time of the alarm (format: %H:%M:%S)
:param bool wake_with_radio: if True, radio will be used for the alarm
instead of beep sound | [
"set",
"the",
"alarm",
"clock"
] | python | train |
carpedm20/ndrive | ndrive/models.py | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/ndrive/models.py#L302-L334 | def getDiskSpace(self, file_path, upload_path = '', overwrite = False):
"""getDiskSpace
Args:
file_path: Full path for a file you want to checkUpload
upload_path: Ndrive path where you want to upload file
ex) /Picture/
Returns:
True: Possible... | [
"def",
"getDiskSpace",
"(",
"self",
",",
"file_path",
",",
"upload_path",
"=",
"''",
",",
"overwrite",
"=",
"False",
")",
":",
"self",
".",
"checkAccount",
"(",
")",
"url",
"=",
"nurls",
"[",
"'checkUpload'",
"]",
"file_size",
"=",
"os",
".",
"stat",
"... | getDiskSpace
Args:
file_path: Full path for a file you want to checkUpload
upload_path: Ndrive path where you want to upload file
ex) /Picture/
Returns:
True: Possible to upload a file with a given file_size
False: Impossible to upload a ... | [
"getDiskSpace"
] | python | train |
rwl/pylon | pyreto/auction.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/auction.py#L106-L117 | def _clearQuantities(self):
""" Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution.
"""
generators = [g for g in self.case.generators if not g.is_load]
vLoads = [g for g in self.case.generators if g.is_load]
for g ... | [
"def",
"_clearQuantities",
"(",
"self",
")",
":",
"generators",
"=",
"[",
"g",
"for",
"g",
"in",
"self",
".",
"case",
".",
"generators",
"if",
"not",
"g",
".",
"is_load",
"]",
"vLoads",
"=",
"[",
"g",
"for",
"g",
"in",
"self",
".",
"case",
".",
"... | Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution. | [
"Computes",
"the",
"cleared",
"quantities",
"for",
"each",
"offer",
"/",
"bid",
"according",
"to",
"the",
"dispatched",
"output",
"from",
"the",
"OPF",
"solution",
"."
] | python | train |
saltstack/salt | salt/utils/minions.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1026-L1030 | def runner_check(self, auth_list, fun, args):
'''
Check special API permissions
'''
return self.spec_check(auth_list, fun, args, 'runner') | [
"def",
"runner_check",
"(",
"self",
",",
"auth_list",
",",
"fun",
",",
"args",
")",
":",
"return",
"self",
".",
"spec_check",
"(",
"auth_list",
",",
"fun",
",",
"args",
",",
"'runner'",
")"
] | Check special API permissions | [
"Check",
"special",
"API",
"permissions"
] | python | train |
seleniumbase/SeleniumBase | seleniumbase/fixtures/base_case.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/base_case.py#L1683-L1693 | def create_folder(self, folder):
""" Creates a folder of the given name if it doesn't already exist. """
if folder.endswith("/"):
folder = folder[:-1]
if len(folder) < 1:
raise Exception("Minimum folder name length = 1.")
if not os.path.exists(folder):
... | [
"def",
"create_folder",
"(",
"self",
",",
"folder",
")",
":",
"if",
"folder",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"folder",
"=",
"folder",
"[",
":",
"-",
"1",
"]",
"if",
"len",
"(",
"folder",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\... | Creates a folder of the given name if it doesn't already exist. | [
"Creates",
"a",
"folder",
"of",
"the",
"given",
"name",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | python | train |
zengbin93/zb | zb/crawlers/xinshipu.py | https://github.com/zengbin93/zb/blob/ccdb384a0b5801b459933220efcb71972c2b89a7/zb/crawlers/xinshipu.py#L20-L83 | def get_recipe_detail(recipe_url):
"""从url中获取菜谱详细信息
:param recipe_url: str
菜谱url,如:https://www.xinshipu.com/zuofa/598775;
https://www.xinshipu.com//zuofa/749342
:return:dict
"""
response = requests.get(recipe_url, headers=get_header())
html = BeautifulSoup(response.text, 'lxml')... | [
"def",
"get_recipe_detail",
"(",
"recipe_url",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"recipe_url",
",",
"headers",
"=",
"get_header",
"(",
")",
")",
"html",
"=",
"BeautifulSoup",
"(",
"response",
".",
"text",
",",
"'lxml'",
")",
"# 获取菜名",... | 从url中获取菜谱详细信息
:param recipe_url: str
菜谱url,如:https://www.xinshipu.com/zuofa/598775;
https://www.xinshipu.com//zuofa/749342
:return:dict | [
"从url中获取菜谱详细信息"
] | python | train |
Sanji-IO/sanji | sanji/model/__init__.py | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/model/__init__.py#L153-L174 | def set(self, id, newObj):
"""Set a object
Args:
id (int): Target Object ID
newObj (object): New object will be set
Returns:
Object: New object
None: If specified object id is not found
MultipleInvalid: If in... | [
"def",
"set",
"(",
"self",
",",
"id",
",",
"newObj",
")",
":",
"newObj",
"=",
"self",
".",
"validation",
"(",
"newObj",
")",
"for",
"index",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"model",
".",
"db",
")",
")",
":",
"if",
"self"... | Set a object
Args:
id (int): Target Object ID
newObj (object): New object will be set
Returns:
Object: New object
None: If specified object id is not found
MultipleInvalid: If input object is invaild | [
"Set",
"a",
"object",
"Args",
":",
"id",
"(",
"int",
")",
":",
"Target",
"Object",
"ID",
"newObj",
"(",
"object",
")",
":",
"New",
"object",
"will",
"be",
"set",
"Returns",
":",
"Object",
":",
"New",
"object",
"None",
":",
"If",
"specified",
"object"... | python | train |
juju/charm-helpers | charmhelpers/core/host.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L859-L868 | def get_nic_mtu(nic):
"""Return the Maximum Transmission Unit (MTU) for a network interface."""
cmd = ['ip', 'addr', 'show', nic]
ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n')
mtu = ""
for line in ip_output:
words = line.split()
if 'mtu' in words:
m... | [
"def",
"get_nic_mtu",
"(",
"nic",
")",
":",
"cmd",
"=",
"[",
"'ip'",
",",
"'addr'",
",",
"'show'",
",",
"nic",
"]",
"ip_output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"split",
"(",
"'\\n'",
... | Return the Maximum Transmission Unit (MTU) for a network interface. | [
"Return",
"the",
"Maximum",
"Transmission",
"Unit",
"(",
"MTU",
")",
"for",
"a",
"network",
"interface",
"."
] | python | train |
rcsb/mmtf-python | mmtf/utils/decoder_utils.py | https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/utils/decoder_utils.py#L150-L159 | def add_entity_info( data_api, struct_inflator):
"""Add the entity info to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
"""
for entity in data_api.entity_list:
struct_inflator.set_entity_info(enti... | [
"def",
"add_entity_info",
"(",
"data_api",
",",
"struct_inflator",
")",
":",
"for",
"entity",
"in",
"data_api",
".",
"entity_list",
":",
"struct_inflator",
".",
"set_entity_info",
"(",
"entity",
"[",
"\"chainIndexList\"",
"]",
",",
"entity",
"[",
"\"sequence\"",
... | Add the entity info to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object | [
"Add",
"the",
"entity",
"info",
"to",
"the",
"structure",
".",
":",
"param",
"data_api",
"the",
"interface",
"to",
"the",
"decoded",
"data",
":",
"param",
"struct_inflator",
"the",
"interface",
"to",
"put",
"the",
"data",
"into",
"the",
"client",
"object"
] | python | train |
manns/pyspread | pyspread/src/model/model.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/model/model.py#L1360-L1368 | def reload_modules(self):
"""Reloads modules that are available in cells"""
import src.lib.charts as charts
from src.gui.grid_panels import vlcpanel_factory
modules = [charts, bz2, base64, re, ast, sys, wx, numpy, datetime]
for module in modules:
reload(module) | [
"def",
"reload_modules",
"(",
"self",
")",
":",
"import",
"src",
".",
"lib",
".",
"charts",
"as",
"charts",
"from",
"src",
".",
"gui",
".",
"grid_panels",
"import",
"vlcpanel_factory",
"modules",
"=",
"[",
"charts",
",",
"bz2",
",",
"base64",
",",
"re",
... | Reloads modules that are available in cells | [
"Reloads",
"modules",
"that",
"are",
"available",
"in",
"cells"
] | python | train |
BD2KGenomics/toil-scripts | src/toil_scripts/rnaseq_unc/rnaseq_unc_pipeline.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/rnaseq_unc/rnaseq_unc_pipeline.py#L578-L604 | def bamsort_and_index(job, job_vars):
"""
Sorts bam file and produces index file
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
# Unpack variables
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
sudo = input_args['sudo']
# I/O
rg_alignmen... | [
"def",
"bamsort_and_index",
"(",
"job",
",",
"job_vars",
")",
":",
"# Unpack variables",
"input_args",
",",
"ids",
"=",
"job_vars",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"sudo",
"=",
"input_args",
"[",
"'sudo'",
"]",
"# ... | Sorts bam file and produces index file
job_vars: tuple Tuple of dictionaries: input_args and ids | [
"Sorts",
"bam",
"file",
"and",
"produces",
"index",
"file"
] | python | train |
juju/charm-helpers | charmhelpers/contrib/database/mysql.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L299-L370 | def set_mysql_password(self, username, password):
"""Update a mysql password for the provided username changing the
leader settings
To update root's password pass `None` in the username
"""
if username is None:
username = 'root'
# get root password via lead... | [
"def",
"set_mysql_password",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"if",
"username",
"is",
"None",
":",
"username",
"=",
"'root'",
"# get root password via leader-get, it may be that in the past (when",
"# changes to root-password were not supported) the user... | Update a mysql password for the provided username changing the
leader settings
To update root's password pass `None` in the username | [
"Update",
"a",
"mysql",
"password",
"for",
"the",
"provided",
"username",
"changing",
"the",
"leader",
"settings"
] | python | train |
guaix-ucm/pyemir | emirdrp/util/sextractor.py | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/util/sextractor.py#L419-L476 | def setup(self, path=None):
"""
Look for SExtractor program ('sextractor', or 'sex').
If a full path is provided, only this path is checked.
Raise a SExtractorException if it failed.
Return program and version if it succeed.
"""
# -- Finding sextractor program an... | [
"def",
"setup",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"# -- Finding sextractor program and its version",
"# first look for 'sextractor', then 'sex'",
"candidates",
"=",
"[",
"'sextractor'",
",",
"'sex'",
"]",
"if",
"(",
"path",
")",
":",
"candidates",
"="... | Look for SExtractor program ('sextractor', or 'sex').
If a full path is provided, only this path is checked.
Raise a SExtractorException if it failed.
Return program and version if it succeed. | [
"Look",
"for",
"SExtractor",
"program",
"(",
"sextractor",
"or",
"sex",
")",
".",
"If",
"a",
"full",
"path",
"is",
"provided",
"only",
"this",
"path",
"is",
"checked",
".",
"Raise",
"a",
"SExtractorException",
"if",
"it",
"failed",
".",
"Return",
"program"... | python | train |
theislab/scvelo | scvelo/preprocessing/utils.py | https://github.com/theislab/scvelo/blob/c7a96d70edfe705e86bf364434a9527d4fd8df11/scvelo/preprocessing/utils.py#L417-L423 | def recipe_velocity(adata, min_counts=3, min_counts_u=3, n_top_genes=None, n_pcs=30, n_neighbors=30, log=True, copy=False):
"""Runs pp.filter_and_normalize() and pp.moments()
"""
from .moments import moments
filter_and_normalize(adata, min_counts=min_counts, min_counts_u=min_counts_u, n_top_genes=n_top_... | [
"def",
"recipe_velocity",
"(",
"adata",
",",
"min_counts",
"=",
"3",
",",
"min_counts_u",
"=",
"3",
",",
"n_top_genes",
"=",
"None",
",",
"n_pcs",
"=",
"30",
",",
"n_neighbors",
"=",
"30",
",",
"log",
"=",
"True",
",",
"copy",
"=",
"False",
")",
":",... | Runs pp.filter_and_normalize() and pp.moments() | [
"Runs",
"pp",
".",
"filter_and_normalize",
"()",
"and",
"pp",
".",
"moments",
"()"
] | python | train |
zhanglab/psamm | psamm/balancecheck.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/balancecheck.py#L65-L88 | def reaction_formula(reaction, compound_formula):
"""Calculate formula compositions for both sides of the specified reaction.
If the compounds in the reaction all have formula, then calculate and
return the chemical compositions for both sides, otherwise return `None`.
Args:
reaction: :class:`... | [
"def",
"reaction_formula",
"(",
"reaction",
",",
"compound_formula",
")",
":",
"def",
"multiply_formula",
"(",
"compound_list",
")",
":",
"for",
"compound",
",",
"count",
"in",
"compound_list",
":",
"yield",
"count",
"*",
"compound_formula",
"[",
"compound",
"."... | Calculate formula compositions for both sides of the specified reaction.
If the compounds in the reaction all have formula, then calculate and
return the chemical compositions for both sides, otherwise return `None`.
Args:
reaction: :class:`psamm.reaction.Reaction`.
compound_formula: a map... | [
"Calculate",
"formula",
"compositions",
"for",
"both",
"sides",
"of",
"the",
"specified",
"reaction",
"."
] | python | train |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-TC.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-TC.py#L120-L248 | def prettyOut(self, value): # override asn1 type method
"""Implements DISPLAY-HINT evaluation"""
if self.displayHint and (self.__integer.isSuperTypeOf(self, matchConstraints=False) and not self.getNamedValues() or
self.__unsigned32.isSuperTypeOf(self, matchConstraints=F... | [
"def",
"prettyOut",
"(",
"self",
",",
"value",
")",
":",
"# override asn1 type method",
"if",
"self",
".",
"displayHint",
"and",
"(",
"self",
".",
"__integer",
".",
"isSuperTypeOf",
"(",
"self",
",",
"matchConstraints",
"=",
"False",
")",
"and",
"not",
"self... | Implements DISPLAY-HINT evaluation | [
"Implements",
"DISPLAY",
"-",
"HINT",
"evaluation"
] | python | train |
Qiskit/qiskit-terra | qiskit/transpiler/layout.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/layout.py#L118-L121 | def is_virtual(value):
"""Checks if value has the format of a virtual qubit """
return value is None or isinstance(value, tuple) and len(value) == 2 and isinstance(
value[0], Register) and isinstance(value[1], int) | [
"def",
"is_virtual",
"(",
"value",
")",
":",
"return",
"value",
"is",
"None",
"or",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"and",
"len",
"(",
"value",
")",
"==",
"2",
"and",
"isinstance",
"(",
"value",
"[",
"0",
"]",
",",
"Register",
")",
"... | Checks if value has the format of a virtual qubit | [
"Checks",
"if",
"value",
"has",
"the",
"format",
"of",
"a",
"virtual",
"qubit"
] | python | test |
sdispater/pendulum | pendulum/date.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/date.py#L59-L67 | def day_of_year(self):
"""
Returns the day of the year (1-366).
:rtype: int
"""
k = 1 if self.is_leap_year() else 2
return (275 * self.month) // 9 - k * ((self.month + 9) // 12) + self.day - 30 | [
"def",
"day_of_year",
"(",
"self",
")",
":",
"k",
"=",
"1",
"if",
"self",
".",
"is_leap_year",
"(",
")",
"else",
"2",
"return",
"(",
"275",
"*",
"self",
".",
"month",
")",
"//",
"9",
"-",
"k",
"*",
"(",
"(",
"self",
".",
"month",
"+",
"9",
")... | Returns the day of the year (1-366).
:rtype: int | [
"Returns",
"the",
"day",
"of",
"the",
"year",
"(",
"1",
"-",
"366",
")",
"."
] | python | train |
EnergieID/smappy | smappy/smappy.py | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L314-L333 | def actuator_on(self, service_location_id, actuator_id, duration=None):
"""
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
... | [
"def",
"actuator_on",
"(",
"self",
",",
"service_location_id",
",",
"actuator_id",
",",
"duration",
"=",
"None",
")",
":",
"return",
"self",
".",
"_actuator_on_off",
"(",
"on_off",
"=",
"'on'",
",",
"service_location_id",
"=",
"service_location_id",
",",
"actuat... | Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
un... | [
"Turn",
"actuator",
"on"
] | python | train |
core/uricore | uricore/wkz_urls.py | https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L383-L394 | def url_quote(s, charset='utf-8', safe='/:'):
"""URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.
"""
if isinstance(s, unicode):
s = s.encode(charset)
elif n... | [
"def",
"url_quote",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
",",
"safe",
"=",
"'/:'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"charset",
")",
"elif",
"not",
"isinstance",
"(",
"s",
",... | URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters. | [
"URL",
"encode",
"a",
"single",
"string",
"with",
"a",
"given",
"encoding",
"."
] | python | train |
collectiveacuity/labPack | labpack/records/time.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/time.py#L181-L206 | def fromEpoch(cls, epoch_time):
''' a method for constructing a labDT object from epoch timestamp
:param epoch_time: number with epoch timestamp info
:return: labDT object
'''
# validate input
title = 'Epoch time input for labDT.fromEpoch'
if not isinstan... | [
"def",
"fromEpoch",
"(",
"cls",
",",
"epoch_time",
")",
":",
"# validate input\r",
"title",
"=",
"'Epoch time input for labDT.fromEpoch'",
"if",
"not",
"isinstance",
"(",
"epoch_time",
",",
"float",
")",
"and",
"not",
"isinstance",
"(",
"epoch_time",
",",
"int",
... | a method for constructing a labDT object from epoch timestamp
:param epoch_time: number with epoch timestamp info
:return: labDT object | [
"a",
"method",
"for",
"constructing",
"a",
"labDT",
"object",
"from",
"epoch",
"timestamp",
":",
"param",
"epoch_time",
":",
"number",
"with",
"epoch",
"timestamp",
"info",
":",
"return",
":",
"labDT",
"object"
] | python | train |
shoebot/shoebot | shoebot/data/geometry.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L157-L174 | def point_in_polygon(points, x, y):
""" Ray casting algorithm.
Determines how many times a horizontal ray starting from the point
intersects with the sides of the polygon.
If it is an even number of times, the point is outside, if odd, inside.
The algorithm does not always repor... | [
"def",
"point_in_polygon",
"(",
"points",
",",
"x",
",",
"y",
")",
":",
"odd",
"=",
"False",
"n",
"=",
"len",
"(",
"points",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"j",
"=",
"i",
"<",
"n",
"-",
"1",
"and",
"i",
"+",
"1",
"or",
... | Ray casting algorithm.
Determines how many times a horizontal ray starting from the point
intersects with the sides of the polygon.
If it is an even number of times, the point is outside, if odd, inside.
The algorithm does not always report correctly when the point is very close to t... | [
"Ray",
"casting",
"algorithm",
".",
"Determines",
"how",
"many",
"times",
"a",
"horizontal",
"ray",
"starting",
"from",
"the",
"point",
"intersects",
"with",
"the",
"sides",
"of",
"the",
"polygon",
".",
"If",
"it",
"is",
"an",
"even",
"number",
"of",
"time... | python | valid |
eng-tools/sfsimodels | sfsimodels/models/time.py | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/time.py#L64-L86 | def time_indices(npts, dt, start, end, index):
"""
Determine the new start and end indices of the time series.
:param npts: Number of points in original time series
:param dt: Time step of original time series
:param start: int or float, optional, New start point
:param end: int or float, optio... | [
"def",
"time_indices",
"(",
"npts",
",",
"dt",
",",
"start",
",",
"end",
",",
"index",
")",
":",
"if",
"index",
"is",
"False",
":",
"# Convert time values into indices",
"if",
"end",
"!=",
"-",
"1",
":",
"e_index",
"=",
"int",
"(",
"end",
"/",
"dt",
... | Determine the new start and end indices of the time series.
:param npts: Number of points in original time series
:param dt: Time step of original time series
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if Fal... | [
"Determine",
"the",
"new",
"start",
"and",
"end",
"indices",
"of",
"the",
"time",
"series",
"."
] | python | train |
saltstack/salt | salt/modules/zabbix.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L1161-L1223 | def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visib... | [
"def",
"host_exists",
"(",
"host",
"=",
"None",
",",
"hostid",
"=",
"None",
",",
"name",
"=",
"None",
",",
"node",
"=",
"None",
",",
"nodeids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn_args",
"=",
"_login",
"(",
"*",
"*",
"kwargs",
"... | Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visible name of the host
:param node: name of the node the hosts must belong to (zabbix API < 2.4)
... | [
"Checks",
"if",
"at",
"least",
"one",
"host",
"that",
"matches",
"the",
"given",
"filter",
"criteria",
"exists",
"."
] | python | train |
konstantint/matplotlib-venn | matplotlib_venn/_arc.py | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_arc.py#L417-L428 | def reversed(self):
'''
Returns a copy of this arc, with the direction flipped.
>>> Arc((0, 0), 1, 0, 360, True).reversed()
Arc([0.000, 0.000], 1.000, 360.000, 0.000, False, degrees=360.000)
>>> Arc((0, 0), 1, 175, -175, True).reversed()
Arc([0.000, 0.000],... | [
"def",
"reversed",
"(",
"self",
")",
":",
"return",
"Arc",
"(",
"self",
".",
"center",
",",
"self",
".",
"radius",
",",
"self",
".",
"to_angle",
",",
"self",
".",
"from_angle",
",",
"not",
"self",
".",
"direction",
")"
] | Returns a copy of this arc, with the direction flipped.
>>> Arc((0, 0), 1, 0, 360, True).reversed()
Arc([0.000, 0.000], 1.000, 360.000, 0.000, False, degrees=360.000)
>>> Arc((0, 0), 1, 175, -175, True).reversed()
Arc([0.000, 0.000], 1.000, -175.000, 175.000, False, ... | [
"Returns",
"a",
"copy",
"of",
"this",
"arc",
"with",
"the",
"direction",
"flipped",
".",
">>>",
"Arc",
"((",
"0",
"0",
")",
"1",
"0",
"360",
"True",
")",
".",
"reversed",
"()",
"Arc",
"(",
"[",
"0",
".",
"000",
"0",
".",
"000",
"]",
"1",
".",
... | python | train |
ejeschke/ginga | ginga/ImageView.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2148-L2157 | def set_scale_base_xy(self, scale_x_base, scale_y_base):
"""Set stretch factors.
Parameters
----------
scale_x_base, scale_y_base : float
Stretch factors for X and Y, respectively.
"""
self.t_.set(scale_x_base=scale_x_base, scale_y_base=scale_y_base) | [
"def",
"set_scale_base_xy",
"(",
"self",
",",
"scale_x_base",
",",
"scale_y_base",
")",
":",
"self",
".",
"t_",
".",
"set",
"(",
"scale_x_base",
"=",
"scale_x_base",
",",
"scale_y_base",
"=",
"scale_y_base",
")"
] | Set stretch factors.
Parameters
----------
scale_x_base, scale_y_base : float
Stretch factors for X and Y, respectively. | [
"Set",
"stretch",
"factors",
"."
] | python | train |
gwastro/pycbc | pycbc/inference/io/base_hdf.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_hdf.py#L787-L809 | def write_kwargs_to_attrs(cls, attrs, **kwargs):
"""Writes the given keywords to the given ``attrs``.
If any keyword argument points to a dict, the keyword will point to a
list of the dict's keys. Each key is then written to the attrs with its
corresponding value.
Parameters
... | [
"def",
"write_kwargs_to_attrs",
"(",
"cls",
",",
"attrs",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arg",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"val",
"is",
"None",
":",
"val",
"=",
"str",
"(",
"None",
")",
"if",
"isinst... | Writes the given keywords to the given ``attrs``.
If any keyword argument points to a dict, the keyword will point to a
list of the dict's keys. Each key is then written to the attrs with its
corresponding value.
Parameters
----------
attrs : an HDF attrs
Th... | [
"Writes",
"the",
"given",
"keywords",
"to",
"the",
"given",
"attrs",
"."
] | python | train |
jeffh/sniffer | sniffer/runner.py | https://github.com/jeffh/sniffer/blob/8e4c3e77743aef08109ea0225b4a6536d4e60270/sniffer/runner.py#L68-L76 | def absorb_args(self, func):
"""
Calls a function without any arguments. The returned caller function
accepts any arguments (and throws them away).
"""
@wraps(func)
def wrapper(*args, **kwargs):
return func()
return wrapper | [
"def",
"absorb_args",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"func",
"(",
")",
"return",
"wrapper"
] | Calls a function without any arguments. The returned caller function
accepts any arguments (and throws them away). | [
"Calls",
"a",
"function",
"without",
"any",
"arguments",
".",
"The",
"returned",
"caller",
"function",
"accepts",
"any",
"arguments",
"(",
"and",
"throws",
"them",
"away",
")",
"."
] | python | train |
portantier/habu | habu/cli/cmd_whois_ip.py | https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_whois_ip.py#L12-L36 | def cmd_whois_ip(ip):
"""Simple whois client to check IP addresses (IPv4 and IPv6).
Example:
\b
$ habu.whois.ip 8.8.8.8
{
"nir": null,
"asn_registry": "arin",
"asn": "15169",
"asn_cidr": "8.8.8.0/24",
"asn_country_code": "US",
"asn_date": "1992-12-01... | [
"def",
"cmd_whois_ip",
"(",
"ip",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
")",
"obj",
"=",
"IPWhois",
"(",
"ip",
")",
"data",
"=",
"obj",
".",
"lookup_rdap",
"(",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"data",
",",
"ind... | Simple whois client to check IP addresses (IPv4 and IPv6).
Example:
\b
$ habu.whois.ip 8.8.8.8
{
"nir": null,
"asn_registry": "arin",
"asn": "15169",
"asn_cidr": "8.8.8.0/24",
"asn_country_code": "US",
"asn_date": "1992-12-01",
"asn_description":... | [
"Simple",
"whois",
"client",
"to",
"check",
"IP",
"addresses",
"(",
"IPv4",
"and",
"IPv6",
")",
"."
] | python | train |
osrg/ryu | ryu/lib/lacplib.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/lacplib.py#L73-L94 | def add(self, dpid, ports):
"""add a setting of a bonding i/f.
'add' method takes the corresponding args in this order.
========= =====================================================
Attribute Description
========= =====================================================
d... | [
"def",
"add",
"(",
"self",
",",
"dpid",
",",
"ports",
")",
":",
"assert",
"isinstance",
"(",
"ports",
",",
"list",
")",
"assert",
"len",
"(",
"ports",
")",
">=",
"2",
"ifs",
"=",
"{",
"}",
"for",
"port",
"in",
"ports",
":",
"ifs",
"[",
"port",
... | add a setting of a bonding i/f.
'add' method takes the corresponding args in this order.
========= =====================================================
Attribute Description
========= =====================================================
dpid datapath id.
ports ... | [
"add",
"a",
"setting",
"of",
"a",
"bonding",
"i",
"/",
"f",
".",
"add",
"method",
"takes",
"the",
"corresponding",
"args",
"in",
"this",
"order",
"."
] | python | train |
mushkevych/scheduler | process_starter.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/process_starter.py#L10-L47 | def get_class(kls):
"""
:param kls - string of fully identified starter function or starter method path
for instance:
- workers.abstract_worker.AbstractWorker.start
- workers.example_script_worker.main
:return tuple (type, object, starter)
for instance:
- (FunctionType, <function_ma... | [
"def",
"get_class",
"(",
"kls",
")",
":",
"parts",
"=",
"kls",
".",
"split",
"(",
"'.'",
")",
"try",
":",
"# First, try to import module hosting starter function",
"module",
"=",
"'.'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")",
"m",
"=",
... | :param kls - string of fully identified starter function or starter method path
for instance:
- workers.abstract_worker.AbstractWorker.start
- workers.example_script_worker.main
:return tuple (type, object, starter)
for instance:
- (FunctionType, <function_main>, None)
- (type, <Class_... | [
":",
"param",
"kls",
"-",
"string",
"of",
"fully",
"identified",
"starter",
"function",
"or",
"starter",
"method",
"path",
"for",
"instance",
":",
"-",
"workers",
".",
"abstract_worker",
".",
"AbstractWorker",
".",
"start",
"-",
"workers",
".",
"example_script... | python | train |
LionelAuroux/pyrser | pyrser/type_system/scope.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/scope.py#L180-L184 | def union(self, sig: Scope) -> Scope:
""" Create a new Set produce by the union of 2 Set """
new = Scope(sig=self._hsig.values(), state=self.state)
new |= sig
return new | [
"def",
"union",
"(",
"self",
",",
"sig",
":",
"Scope",
")",
"->",
"Scope",
":",
"new",
"=",
"Scope",
"(",
"sig",
"=",
"self",
".",
"_hsig",
".",
"values",
"(",
")",
",",
"state",
"=",
"self",
".",
"state",
")",
"new",
"|=",
"sig",
"return",
"ne... | Create a new Set produce by the union of 2 Set | [
"Create",
"a",
"new",
"Set",
"produce",
"by",
"the",
"union",
"of",
"2",
"Set"
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.