repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
zeth/inputs | inputs.py | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L1525-L1556 | def emulate_wheel(self, data, direction, timeval):
"""Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
... | [
"def",
"emulate_wheel",
"(",
"self",
",",
"data",
",",
"direction",
",",
"timeval",
")",
":",
"if",
"direction",
"==",
"'x'",
":",
"code",
"=",
"0x06",
"elif",
"direction",
"==",
"'z'",
":",
"# Not enitely sure if this exists",
"code",
"=",
"0x07",
"else",
... | Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
wheels found on the vast majority of mice. It also works on... | [
"Emulate",
"rel",
"values",
"for",
"the",
"mouse",
"wheel",
"."
] | python | train | 35.28125 |
SergeySatskiy/cdm-gc-plugin | cdmplugins/gc/__init__.py | https://github.com/SergeySatskiy/cdm-gc-plugin/blob/f6dd59d5dc80d3f8f5ca5bcf49bad86c88be38df/cdmplugins/gc/__init__.py#L140-L161 | def populateBufferContextMenu(self, parentMenu):
"""Populates the editing buffer context menu.
The buffer context menu shown for the current edited/viewed file
will have an item with a plugin name and subitems which are
populated here. If no items were populated then the plugin menu
... | [
"def",
"populateBufferContextMenu",
"(",
"self",
",",
"parentMenu",
")",
":",
"parentMenu",
".",
"addAction",
"(",
"\"Configure\"",
",",
"self",
".",
"configure",
")",
"parentMenu",
".",
"addAction",
"(",
"\"Collect garbage\"",
",",
"self",
".",
"__collectGarbage"... | Populates the editing buffer context menu.
The buffer context menu shown for the current edited/viewed file
will have an item with a plugin name and subitems which are
populated here. If no items were populated then the plugin menu
item will not be shown.
Note: when a buffer co... | [
"Populates",
"the",
"editing",
"buffer",
"context",
"menu",
"."
] | python | train | 51.454545 |
nion-software/nionswift | nion/swift/Thumbnails.py | https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/Thumbnails.py#L56-L60 | def mark_data_dirty(self):
""" Called from item to indicate its data or metadata has changed."""
self.__cache.set_cached_value_dirty(self.__display_item, self.__cache_property_name)
self.__initialize_cache()
self.__cached_value_dirty = True | [
"def",
"mark_data_dirty",
"(",
"self",
")",
":",
"self",
".",
"__cache",
".",
"set_cached_value_dirty",
"(",
"self",
".",
"__display_item",
",",
"self",
".",
"__cache_property_name",
")",
"self",
".",
"__initialize_cache",
"(",
")",
"self",
".",
"__cached_value_... | Called from item to indicate its data or metadata has changed. | [
"Called",
"from",
"item",
"to",
"indicate",
"its",
"data",
"or",
"metadata",
"has",
"changed",
"."
] | python | train | 53.6 |
PMBio/limix-backup | limix/deprecated/archive/FastVDMM.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/FastVDMM.py#L145-L199 | def fit(self,Params0=None,grad_threshold=1e-2):
"""
fit a variance component model with the predefined design and the initialization and returns all the results
"""
# GPVD initialization
lik = limix.CLikNormalNULL()
# Initial Params
if Params0==None:
... | [
"def",
"fit",
"(",
"self",
",",
"Params0",
"=",
"None",
",",
"grad_threshold",
"=",
"1e-2",
")",
":",
"# GPVD initialization",
"lik",
"=",
"limix",
".",
"CLikNormalNULL",
"(",
")",
"# Initial Params",
"if",
"Params0",
"==",
"None",
":",
"n_params",
"=",
"s... | fit a variance component model with the predefined design and the initialization and returns all the results | [
"fit",
"a",
"variance",
"component",
"model",
"with",
"the",
"predefined",
"design",
"and",
"the",
"initialization",
"and",
"returns",
"all",
"the",
"results"
] | python | train | 37.381818 |
census-instrumentation/opencensus-python | opencensus/common/monitored_resource/k8s_utils.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/monitored_resource/k8s_utils.py#L50-L64 | def get_k8s_metadata():
"""Get kubernetes container metadata, as on GCP GKE."""
k8s_metadata = {}
gcp_cluster = (gcp_metadata_config.GcpMetadataConfig
.get_attribute(gcp_metadata_config.CLUSTER_NAME_KEY))
if gcp_cluster is not None:
k8s_metadata[CLUSTER_NAME_KEY] = gcp_cluste... | [
"def",
"get_k8s_metadata",
"(",
")",
":",
"k8s_metadata",
"=",
"{",
"}",
"gcp_cluster",
"=",
"(",
"gcp_metadata_config",
".",
"GcpMetadataConfig",
".",
"get_attribute",
"(",
"gcp_metadata_config",
".",
"CLUSTER_NAME_KEY",
")",
")",
"if",
"gcp_cluster",
"is",
"not"... | Get kubernetes container metadata, as on GCP GKE. | [
"Get",
"kubernetes",
"container",
"metadata",
"as",
"on",
"GCP",
"GKE",
"."
] | python | train | 37.066667 |
cuihantao/andes | andes/models/pq.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pq.py#L62-L65 | def init0(self, dae):
"""Set initial p and q for power flow"""
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | [
"def",
"init0",
"(",
"self",
",",
"dae",
")",
":",
"self",
".",
"p0",
"=",
"matrix",
"(",
"self",
".",
"p",
",",
"(",
"self",
".",
"n",
",",
"1",
")",
",",
"'d'",
")",
"self",
".",
"q0",
"=",
"matrix",
"(",
"self",
".",
"q",
",",
"(",
"se... | Set initial p and q for power flow | [
"Set",
"initial",
"p",
"and",
"q",
"for",
"power",
"flow"
] | python | train | 42.25 |
Spinmob/spinmob | egg/_gui.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L949-L959 | def click(self):
"""
Pretends to user clicked it, sending the signal and everything.
"""
if self.is_checkable():
if self.is_checked(): self.set_checked(False)
else: self.set_checked(True)
self.signal_clicked.emit(self.is_checked... | [
"def",
"click",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_checkable",
"(",
")",
":",
"if",
"self",
".",
"is_checked",
"(",
")",
":",
"self",
".",
"set_checked",
"(",
"False",
")",
"else",
":",
"self",
".",
"set_checked",
"(",
"True",
")",
"self... | Pretends to user clicked it, sending the signal and everything. | [
"Pretends",
"to",
"user",
"clicked",
"it",
"sending",
"the",
"signal",
"and",
"everything",
"."
] | python | train | 35.454545 |
nerdvegas/rez | src/rez/vendor/pyparsing/pyparsing.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pyparsing/pyparsing.py#L570-L589 | def dump(self,indent='',depth=0):
"""Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data."""
out = []
out.append( indent+_ustr(self.asList()) )... | [
"def",
"dump",
"(",
"self",
",",
"indent",
"=",
"''",
",",
"depth",
"=",
"0",
")",
":",
"out",
"=",
"[",
"]",
"out",
".",
"append",
"(",
"indent",
"+",
"_ustr",
"(",
"self",
".",
"asList",
"(",
")",
")",
")",
"keys",
"=",
"self",
".",
"items"... | Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data. | [
"Diagnostic",
"method",
"for",
"listing",
"out",
"the",
"contents",
"of",
"a",
"C",
"{",
"ParseResults",
"}",
".",
"Accepts",
"an",
"optional",
"C",
"{",
"indent",
"}",
"argument",
"so",
"that",
"this",
"string",
"can",
"be",
"embedded",
"in",
"a",
"nest... | python | train | 39.1 |
centralniak/py-raildriver | raildriver/library.py | https://github.com/centralniak/py-raildriver/blob/c7f5f551e0436451b9507fc63a62e49a229282b9/raildriver/library.py#L50-L65 | def get_controller_list(self):
"""
Returns an iterable of tuples containing (index, controller_name) pairs.
Controller indexes start at 0.
You may easily transform this to a {name: index} mapping by using:
>>> controllers = {name: index for index, name in raildriver.get_contro... | [
"def",
"get_controller_list",
"(",
"self",
")",
":",
"ret_str",
"=",
"self",
".",
"dll",
".",
"GetControllerList",
"(",
")",
".",
"decode",
"(",
")",
"if",
"not",
"ret_str",
":",
"return",
"[",
"]",
"return",
"enumerate",
"(",
"ret_str",
".",
"split",
... | Returns an iterable of tuples containing (index, controller_name) pairs.
Controller indexes start at 0.
You may easily transform this to a {name: index} mapping by using:
>>> controllers = {name: index for index, name in raildriver.get_controller_list()}
:return enumerate | [
"Returns",
"an",
"iterable",
"of",
"tuples",
"containing",
"(",
"index",
"controller_name",
")",
"pairs",
"."
] | python | train | 31.5 |
mitsei/dlkit | dlkit/json_/learning/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L5796-L5835 | def update_objective_bank(self, objective_bank_form):
"""Updates an existing objective bank.
arg: objective_bank_form (osid.learning.ObjectiveBankForm):
the form containing the elements to be updated
raise: IllegalState - ``objective_bank_form`` already used in
... | [
"def",
"update_objective_bank",
"(",
"self",
",",
"objective_bank_form",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.update_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_ses... | Updates an existing objective bank.
arg: objective_bank_form (osid.learning.ObjectiveBankForm):
the form containing the elements to be updated
raise: IllegalState - ``objective_bank_form`` already used in
an update transaction
raise: InvalidArgument - the fo... | [
"Updates",
"an",
"existing",
"objective",
"bank",
"."
] | python | train | 58.575 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/cpnr_client.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/cpnr_client.py#L140-L143 | def get_scopes(self, vpnid='.*'):
"""Returns a list of all the scopes from CPNR server."""
request_url = self._build_url(['Scope'], vpn=vpnid)
return self._do_request('GET', request_url) | [
"def",
"get_scopes",
"(",
"self",
",",
"vpnid",
"=",
"'.*'",
")",
":",
"request_url",
"=",
"self",
".",
"_build_url",
"(",
"[",
"'Scope'",
"]",
",",
"vpn",
"=",
"vpnid",
")",
"return",
"self",
".",
"_do_request",
"(",
"'GET'",
",",
"request_url",
")"
] | Returns a list of all the scopes from CPNR server. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"scopes",
"from",
"CPNR",
"server",
"."
] | python | train | 51.75 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ClientFactory.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ClientFactory.py#L602-L608 | def create_usuario(self):
"""Get an instance of usuario services facade."""
return Usuario(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_usuario",
"(",
"self",
")",
":",
"return",
"Usuario",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | Get an instance of usuario services facade. | [
"Get",
"an",
"instance",
"of",
"usuario",
"services",
"facade",
"."
] | python | train | 30.285714 |
Galarzaa90/tibia.py | tibiapy/utils.py | https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/utils.py#L210-L239 | def try_date(obj) -> Optional[datetime.date]:
"""Attempts to convert an object into a date.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`datetime.datetime`, :class:`dat... | [
"def",
"try_date",
"(",
"obj",
")",
"->",
"Optional",
"[",
"datetime",
".",
"date",
"]",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
".",
"date",
... | Attempts to convert an object into a date.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`datetime.datetime`, :class:`datetime.date`
The object to convert.
Retur... | [
"Attempts",
"to",
"convert",
"an",
"object",
"into",
"a",
"date",
"."
] | python | train | 26.866667 |
watson-developer-cloud/python-sdk | ibm_watson/assistant_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v1.py#L2294-L2419 | def create_dialog_node(self,
workspace_id,
dialog_node,
description=None,
conditions=None,
parent=None,
previous_sibling=None,
outp... | [
"def",
"create_dialog_node",
"(",
"self",
",",
"workspace_id",
",",
"dialog_node",
",",
"description",
"=",
"None",
",",
"conditions",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"previous_sibling",
"=",
"None",
",",
"output",
"=",
"None",
",",
"context",
... | Create dialog node.
Create a new dialog node.
This operation is limited to 500 requests per 30 minutes. For more information,
see **Rate limiting**.
:param str workspace_id: Unique identifier of the workspace.
:param str dialog_node: The dialog node ID. This string must conform... | [
"Create",
"dialog",
"node",
"."
] | python | train | 45.238095 |
automl/HpBandSter | hpbandster/optimizers/config_generators/bohb.py | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/bohb.py#L99-L234 | def get_config(self, budget):
"""
Function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration
... | [
"def",
"get_config",
"(",
"self",
",",
"budget",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'start sampling a new configuration.'",
")",
"sample",
"=",
"None",
"info_dict",
"=",
"{",
"}",
"# If no model is available, sample from prior",
"# also mix in a frac... | Function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration | [
"Function",
"to",
"sample",
"a",
"new",
"configuration"
] | python | train | 33.551471 |
ajenhl/tacl | tacl/__main__.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L527-L539 | def prepare_xml(args, parser):
"""Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work.
"""
if args.source == constants.TEI_SOURCE_CBETA_GITHUB:
corpus_class = tacl.TEICorpusCBETAGitHub
else:
raise Exception('Unsupported TEI sou... | [
"def",
"prepare_xml",
"(",
"args",
",",
"parser",
")",
":",
"if",
"args",
".",
"source",
"==",
"constants",
".",
"TEI_SOURCE_CBETA_GITHUB",
":",
"corpus_class",
"=",
"tacl",
".",
"TEICorpusCBETAGitHub",
"else",
":",
"raise",
"Exception",
"(",
"'Unsupported TEI s... | Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work. | [
"Prepares",
"XML",
"files",
"for",
"stripping",
"."
] | python | train | 30.615385 |
scrapinghub/dateparser | dateparser/languages/locale.py | https://github.com/scrapinghub/dateparser/blob/11a761c99d3ee522a3c63756b70c106a579e8b5c/dateparser/languages/locale.py#L114-L149 | def translate(self, date_string, keep_formatting=False, settings=None):
"""
Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_for... | [
"def",
"translate",
"(",
"self",
",",
"date_string",
",",
"keep_formatting",
"=",
"False",
",",
"settings",
"=",
"None",
")",
":",
"date_string",
"=",
"self",
".",
"_translate_numerals",
"(",
"date_string",
")",
"if",
"settings",
".",
"NORMALIZE",
":",
"date... | Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_formatting:
If True, retain formatting of the date string after translation.
... | [
"Translate",
"the",
"date",
"string",
"to",
"its",
"English",
"equivalent",
"."
] | python | test | 43.25 |
bunq/sdk_python | bunq/sdk/security.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/security.py#L254-L271 | def _generate_response_head_bytes(status_code, headers):
"""
:type status_code: int
:type headers: dict[str, str]
:rtype: bytes
"""
head_string = str(status_code) + _DELIMITER_NEWLINE
header_tuples = sorted((k, headers[k]) for k in headers)
for name, value in header_tuples:
na... | [
"def",
"_generate_response_head_bytes",
"(",
"status_code",
",",
"headers",
")",
":",
"head_string",
"=",
"str",
"(",
"status_code",
")",
"+",
"_DELIMITER_NEWLINE",
"header_tuples",
"=",
"sorted",
"(",
"(",
"k",
",",
"headers",
"[",
"k",
"]",
")",
"for",
"k"... | :type status_code: int
:type headers: dict[str, str]
:rtype: bytes | [
":",
"type",
"status_code",
":",
"int",
":",
"type",
"headers",
":",
"dict",
"[",
"str",
"str",
"]"
] | python | train | 28.555556 |
lago-project/lago | lago/utils.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L850-L865 | def ver_cmp(ver1, ver2):
"""
Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2.
"""
return cmp(
pkg_resources.parse_version(ver1), pkg_resourc... | [
"def",
"ver_cmp",
"(",
"ver1",
",",
"ver2",
")",
":",
"return",
"cmp",
"(",
"pkg_resources",
".",
"parse_version",
"(",
"ver1",
")",
",",
"pkg_resources",
".",
"parse_version",
"(",
"ver2",
")",
")"
] | Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2. | [
"Compare",
"lago",
"versions"
] | python | train | 20.8125 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winresource.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winresource.py#L267-L278 | def UpdateResourcesFromResFile(dstpath, srcpath, types=None, names=None,
languages=None):
"""
Update or add resources from dll/exe file srcpath in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update... | [
"def",
"UpdateResourcesFromResFile",
"(",
"dstpath",
",",
"srcpath",
",",
"types",
"=",
"None",
",",
"names",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"res",
"=",
"GetResources",
"(",
"srcpath",
",",
"types",
",",
"names",
",",
"languages",
... | Update or add resources from dll/exe file srcpath in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
languages = a list of resource languages to update (None = all) | [
"Update",
"or",
"add",
"resources",
"from",
"dll",
"/",
"exe",
"file",
"srcpath",
"in",
"dll",
"/",
"exe",
"file",
"dstpath",
".",
"types",
"=",
"a",
"list",
"of",
"resource",
"types",
"to",
"update",
"(",
"None",
"=",
"all",
")",
"names",
"=",
"a",
... | python | train | 41.833333 |
MrYsLab/pymata-aio | pymata_aio/pymata_core.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_core.py#L610-L622 | async def disable_digital_reporting(self, pin):
"""
Disables digital reporting. By turning reporting off for this pin,
Reporting is disabled for all 8 bits in the "port"
:param pin: Pin and all pins for this port
:returns: No return value
"""
port = pin // 8
... | [
"async",
"def",
"disable_digital_reporting",
"(",
"self",
",",
"pin",
")",
":",
"port",
"=",
"pin",
"//",
"8",
"command",
"=",
"[",
"PrivateConstants",
".",
"REPORT_DIGITAL",
"+",
"port",
",",
"PrivateConstants",
".",
"REPORTING_DISABLE",
"]",
"await",
"self",... | Disables digital reporting. By turning reporting off for this pin,
Reporting is disabled for all 8 bits in the "port"
:param pin: Pin and all pins for this port
:returns: No return value | [
"Disables",
"digital",
"reporting",
".",
"By",
"turning",
"reporting",
"off",
"for",
"this",
"pin",
"Reporting",
"is",
"disabled",
"for",
"all",
"8",
"bits",
"in",
"the",
"port"
] | python | train | 35.384615 |
pandas-dev/pandas | pandas/core/groupby/categorical.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/categorical.py#L77-L100 | def recode_from_groupby(c, sort, ci):
"""
Reverse the codes_to_groupby to account for sort / observed.
Parameters
----------
c : Categorical
sort : boolean
The value of the sort parameter groupby was called with.
ci : CategoricalIndex
The codes / categories to recode
Re... | [
"def",
"recode_from_groupby",
"(",
"c",
",",
"sort",
",",
"ci",
")",
":",
"# we re-order to the original category orderings",
"if",
"sort",
":",
"return",
"ci",
".",
"set_categories",
"(",
"c",
".",
"categories",
")",
"# we are not sorting, so add unobserved to the end"... | Reverse the codes_to_groupby to account for sort / observed.
Parameters
----------
c : Categorical
sort : boolean
The value of the sort parameter groupby was called with.
ci : CategoricalIndex
The codes / categories to recode
Returns
-------
CategoricalIndex | [
"Reverse",
"the",
"codes_to_groupby",
"to",
"account",
"for",
"sort",
"/",
"observed",
"."
] | python | train | 25 |
MillionIntegrals/vel | vel/models/imagenet/resnet34.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/imagenet/resnet34.py#L102-L107 | def create(fc_layers=None, dropout=None, pretrained=True):
""" Vel factory function """
def instantiate(**_):
return Resnet34(fc_layers, dropout, pretrained)
return ModelFactory.generic(instantiate) | [
"def",
"create",
"(",
"fc_layers",
"=",
"None",
",",
"dropout",
"=",
"None",
",",
"pretrained",
"=",
"True",
")",
":",
"def",
"instantiate",
"(",
"*",
"*",
"_",
")",
":",
"return",
"Resnet34",
"(",
"fc_layers",
",",
"dropout",
",",
"pretrained",
")",
... | Vel factory function | [
"Vel",
"factory",
"function"
] | python | train | 35.666667 |
mmp2/megaman | megaman/utils/analyze_dimension_and_radius.py | https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/utils/analyze_dimension_and_radius.py#L90-L139 | def run_analyze_dimension_and_radius(data, rmin, rmax, nradii, adjacency_method='brute', adjacency_kwds = {},
fit_range=None, savefig=False, plot_name = 'dimension_plot.png'):
"""
This function is used to estimate the doubling dimension (approximately equal to the intrinsic
... | [
"def",
"run_analyze_dimension_and_radius",
"(",
"data",
",",
"rmin",
",",
"rmax",
",",
"nradii",
",",
"adjacency_method",
"=",
"'brute'",
",",
"adjacency_kwds",
"=",
"{",
"}",
",",
"fit_range",
"=",
"None",
",",
"savefig",
"=",
"False",
",",
"plot_name",
"="... | This function is used to estimate the doubling dimension (approximately equal to the intrinsic
dimension) by computing a graph of neighborhood radius versus average number of neighbors.
The "radius" refers to the truncation constant where all distances greater than
a specified radius are taken to be infini... | [
"This",
"function",
"is",
"used",
"to",
"estimate",
"the",
"doubling",
"dimension",
"(",
"approximately",
"equal",
"to",
"the",
"intrinsic",
"dimension",
")",
"by",
"computing",
"a",
"graph",
"of",
"neighborhood",
"radius",
"versus",
"average",
"number",
"of",
... | python | train | 42.48 |
dwavesystems/minorminer | examples/fourcolor.py | https://github.com/dwavesystems/minorminer/blob/05cac6db180adf8223a613dff808248e3048b07d/examples/fourcolor.py#L43-L70 | def graph_coloring_qubo(graph, k):
"""
the QUBO for k-coloring a graph A is as follows:
variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise
constraints:
1) each v in A gets exactly one color.
This constraint is enforced by including the term (\sum_c x_{v,c} - 1)... | [
"def",
"graph_coloring_qubo",
"(",
"graph",
",",
"k",
")",
":",
"K",
"=",
"nx",
".",
"complete_graph",
"(",
"k",
")",
"g1",
"=",
"nx",
".",
"cartesian_product",
"(",
"nx",
".",
"create_empty_copy",
"(",
"graph",
")",
",",
"K",
")",
"g2",
"=",
"nx",
... | the QUBO for k-coloring a graph A is as follows:
variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise
constraints:
1) each v in A gets exactly one color.
This constraint is enforced by including the term (\sum_c x_{v,c} - 1)^2 in the QUBO,
which is minimized when ... | [
"the",
"QUBO",
"for",
"k",
"-",
"coloring",
"a",
"graph",
"A",
"is",
"as",
"follows",
":"
] | python | test | 37.535714 |
genialis/resolwe | resolwe/flow/engine.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/engine.py#L29-L86 | def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'):
"""Load engines."""
loaded_engines = {}
for module_name_or_dict in engines:
if not isinstance(module_name_or_dict, dict):
module_name_or_dict = {
class_key: module_name... | [
"def",
"load_engines",
"(",
"manager",
",",
"class_name",
",",
"base_module",
",",
"engines",
",",
"class_key",
"=",
"'ENGINE'",
",",
"engine_type",
"=",
"'engine'",
")",
":",
"loaded_engines",
"=",
"{",
"}",
"for",
"module_name_or_dict",
"in",
"engines",
":",... | Load engines. | [
"Load",
"engines",
"."
] | python | train | 45.689655 |
NASA-AMMOS/AIT-Core | ait/core/bin/ait_create_dirs.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bin/ait_create_dirs.py#L129-L159 | def createDirStruct(paths, verbose=True):
'''Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of di... | [
"def",
"createDirStruct",
"(",
"paths",
",",
"verbose",
"=",
"True",
")",
":",
"for",
"k",
",",
"path",
"in",
"paths",
".",
"items",
"(",
")",
":",
"p",
"=",
"None",
"try",
":",
"pathlist",
"=",
"path",
"if",
"type",
"(",
"path",
")",
"is",
"list... | Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of directory paths you would like to create.
... | [
"Loops",
"ait",
".",
"config",
".",
"_datapaths",
"from",
"AIT_CONFIG",
"and",
"creates",
"a",
"directory",
"."
] | python | train | 31.612903 |
pybel/pybel | src/pybel/io/web.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/io/web.py#L52-L100 | def to_web(graph: BELGraph,
host: Optional[str] = None,
user: Optional[str] = None,
password: Optional[str] = None,
public: bool = False,
) -> requests.Response:
"""Send a graph to the receiver service and returns the :mod:`requests` response object.
:para... | [
"def",
"to_web",
"(",
"graph",
":",
"BELGraph",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"user",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"password",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"public",
... | Send a graph to the receiver service and returns the :mod:`requests` response object.
:param graph: A BEL graph
:param host: The location of the BEL Commons server. Alternatively, looks up in PyBEL config with
``PYBEL_REMOTE_HOST`` or the environment as ``PYBEL_REMOTE_HOST`` Defaults to
:data:`pybel.... | [
"Send",
"a",
"graph",
"to",
"the",
"receiver",
"service",
"and",
"returns",
"the",
":",
"mod",
":",
"requests",
"response",
"object",
"."
] | python | train | 34.693878 |
Scifabric/pybossa-client | pbclient/__init__.py | https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L260-L277 | def update_project(project):
"""Update a project instance.
:param project: PYBOSSA project
:type project: PYBOSSA Project
:returns: True -- the response status code
"""
try:
project_id = project.id
project = _forbidden_attributes(project)
res = _pybossa_req('put', 'proj... | [
"def",
"update_project",
"(",
"project",
")",
":",
"try",
":",
"project_id",
"=",
"project",
".",
"id",
"project",
"=",
"_forbidden_attributes",
"(",
"project",
")",
"res",
"=",
"_pybossa_req",
"(",
"'put'",
",",
"'project'",
",",
"project_id",
",",
"payload... | Update a project instance.
:param project: PYBOSSA project
:type project: PYBOSSA Project
:returns: True -- the response status code | [
"Update",
"a",
"project",
"instance",
"."
] | python | valid | 26.833333 |
noahbenson/pimms | pimms/immutable.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/immutable.py#L247-L255 | def _imm_dir(self):
'''
An immutable object's dir function should list not only its attributes, but also its un-cached
lazy values.
'''
dir0 = set(dir(self.__class__))
dir0.update(self.__dict__.keys())
dir0.update(six.iterkeys(_imm_value_data(self)))
return sorted(list(dir0)) | [
"def",
"_imm_dir",
"(",
"self",
")",
":",
"dir0",
"=",
"set",
"(",
"dir",
"(",
"self",
".",
"__class__",
")",
")",
"dir0",
".",
"update",
"(",
"self",
".",
"__dict__",
".",
"keys",
"(",
")",
")",
"dir0",
".",
"update",
"(",
"six",
".",
"iterkeys"... | An immutable object's dir function should list not only its attributes, but also its un-cached
lazy values. | [
"An",
"immutable",
"object",
"s",
"dir",
"function",
"should",
"list",
"not",
"only",
"its",
"attributes",
"but",
"also",
"its",
"un",
"-",
"cached",
"lazy",
"values",
"."
] | python | train | 33.333333 |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1785-L1796 | def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True):
"""Implements a step-through function, using pause_point.
"""
shutit_global.shutit_global_object.yield_to_draw()
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_chil... | [
"def",
"step_through",
"(",
"self",
",",
"msg",
"=",
"''",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"level",
"=",
"1",
",",
"print_input",
"=",
"True",
",",
"value",
"=",
"True",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_... | Implements a step-through function, using pause_point. | [
"Implements",
"a",
"step",
"-",
"through",
"function",
"using",
"pause_point",
"."
] | python | train | 61.166667 |
hollenstein/maspy | maspy/xml.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L491-L501 | def parseSpectra(self):
""" #TODO: docstring
:returns: #TODO: docstring
"""
#Note: the spectra need to be iterated completely to save the
#metadataNode
if self._parsed:
raise TypeError('Mzml file already parsed.')
self._parsed = True
return se... | [
"def",
"parseSpectra",
"(",
"self",
")",
":",
"#Note: the spectra need to be iterated completely to save the",
"#metadataNode",
"if",
"self",
".",
"_parsed",
":",
"raise",
"TypeError",
"(",
"'Mzml file already parsed.'",
")",
"self",
".",
"_parsed",
"=",
"True",
"return... | #TODO: docstring
:returns: #TODO: docstring | [
"#TODO",
":",
"docstring"
] | python | train | 29.545455 |
phaethon/kamene | kamene/layers/inet6.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/layers/inet6.py#L1899-L1926 | def names2dnsrepr(x):
"""
Take as input a list of DNS names or a single DNS name
and encode it in DNS format (with possible compression)
If a string that is already a DNS name in DNS format
is passed, it is returned unmodified. Result is a string.
!!! At the moment, compression is not implement... | [
"def",
"names2dnsrepr",
"(",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"is",
"str",
":",
"if",
"x",
"and",
"x",
"[",
"-",
"1",
"]",
"==",
"'\\x00'",
":",
"# stupid heuristic",
"return",
"x",
".",
"encode",
"(",
"'ascii'",
")",
"x",
"=",
"[",
... | Take as input a list of DNS names or a single DNS name
and encode it in DNS format (with possible compression)
If a string that is already a DNS name in DNS format
is passed, it is returned unmodified. Result is a string.
!!! At the moment, compression is not implemented !!! | [
"Take",
"as",
"input",
"a",
"list",
"of",
"DNS",
"names",
"or",
"a",
"single",
"DNS",
"name",
"and",
"encode",
"it",
"in",
"DNS",
"format",
"(",
"with",
"possible",
"compression",
")",
"If",
"a",
"string",
"that",
"is",
"already",
"a",
"DNS",
"name",
... | python | train | 32.25 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/completer.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L642-L665 | def python_matches(self,text):
"""Match attributes or global python names"""
#io.rprint('Completer->python_matches, txt=%r' % text) # dbg
if "." in text:
try:
matches = self.attr_matches(text)
if text.endswith('.') and self.omit__names:
... | [
"def",
"python_matches",
"(",
"self",
",",
"text",
")",
":",
"#io.rprint('Completer->python_matches, txt=%r' % text) # dbg",
"if",
"\".\"",
"in",
"text",
":",
"try",
":",
"matches",
"=",
"self",
".",
"attr_matches",
"(",
"text",
")",
"if",
"text",
".",
"endswith... | Match attributes or global python names | [
"Match",
"attributes",
"or",
"global",
"python",
"names"
] | python | test | 42 |
mar10/wsgidav | wsgidav/lock_storage.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/lock_storage.py#L356-L363 | def _flush(self):
"""Write persistent dictionary to disc."""
_logger.debug("_flush()")
self._lock.acquire_write() # TODO: read access is enough?
try:
self._dict.sync()
finally:
self._lock.release() | [
"def",
"_flush",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"\"_flush()\"",
")",
"self",
".",
"_lock",
".",
"acquire_write",
"(",
")",
"# TODO: read access is enough?",
"try",
":",
"self",
".",
"_dict",
".",
"sync",
"(",
")",
"finally",
":",
"s... | Write persistent dictionary to disc. | [
"Write",
"persistent",
"dictionary",
"to",
"disc",
"."
] | python | valid | 31.875 |
pmacosta/peng | peng/functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L571-L595 | def peng_mant(snum):
r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.f... | [
"def",
"peng_mant",
"(",
"snum",
")",
":",
"snum",
"=",
"snum",
".",
"rstrip",
"(",
")",
"return",
"float",
"(",
"snum",
"if",
"snum",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"else",
"snum",
"[",
":",
"-",
"1",
"]",
")"
] | r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_mant
:... | [
"r",
"Return",
"the",
"mantissa",
"of",
"a",
"number",
"represented",
"in",
"engineering",
"notation",
"."
] | python | test | 24.12 |
nuagenetworks/monolithe | monolithe/generators/lang/csharp/writers/apiversionwriter.py | https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/csharp/writers/apiversionwriter.py#L142-L173 | def _write_model(self, specification, specification_set):
""" Write autogenerate specification file
"""
filename = "vspk/%s%s.cs" % (self._class_prefix, specification.entity_name)
override_content = self._extract_override_content(specification.entity_name)
superclass_name = "Re... | [
"def",
"_write_model",
"(",
"self",
",",
"specification",
",",
"specification_set",
")",
":",
"filename",
"=",
"\"vspk/%s%s.cs\"",
"%",
"(",
"self",
".",
"_class_prefix",
",",
"specification",
".",
"entity_name",
")",
"override_content",
"=",
"self",
".",
"_extr... | Write autogenerate specification file | [
"Write",
"autogenerate",
"specification",
"file"
] | python | train | 42.90625 |
pydata/xarray | xarray/backends/common.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/backends/common.py#L307-L338 | def set_dimensions(self, variables, unlimited_dims=None):
"""
This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited... | [
"def",
"set_dimensions",
"(",
"self",
",",
"variables",
",",
"unlimited_dims",
"=",
"None",
")",
":",
"if",
"unlimited_dims",
"is",
"None",
":",
"unlimited_dims",
"=",
"set",
"(",
")",
"existing_dims",
"=",
"self",
".",
"get_dimensions",
"(",
")",
"dims",
... | This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited_dims : list-like
List of dimension names that should be treated a... | [
"This",
"provides",
"a",
"centralized",
"method",
"to",
"set",
"the",
"dimensions",
"on",
"the",
"data",
"store",
"."
] | python | train | 36.9375 |
pyQode/pyqode.core | pyqode/core/widgets/menu_recents.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/menu_recents.py#L74-L83 | def set_value(self, key, value):
"""
Set the recent files value in QSettings.
:param key: value key
:param value: new value
"""
if value is None:
value = []
value = [os.path.normpath(pth) for pth in value]
self._settings.setValue('recent_files/... | [
"def",
"set_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"[",
"]",
"value",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"pth",
")",
"for",
"pth",
"in",
"value",
"]",
"self",
"."... | Set the recent files value in QSettings.
:param key: value key
:param value: new value | [
"Set",
"the",
"recent",
"files",
"value",
"in",
"QSettings",
".",
":",
"param",
"key",
":",
"value",
"key",
":",
"param",
"value",
":",
"new",
"value"
] | python | train | 32.8 |
treethought/flask-assistant | flask_assistant/response.py | https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L161-L192 | def build_list(self, title=None, items=None):
"""Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify... | [
"def",
"build_list",
"(",
"self",
",",
"title",
"=",
"None",
",",
"items",
"=",
"None",
")",
":",
"list_card",
"=",
"_ListSelector",
"(",
"self",
".",
"_speech",
",",
"display_text",
"=",
"self",
".",
"_display_text",
",",
"title",
"=",
"title",
",",
"... | Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify the existing response object
Therefore, to add i... | [
"Presents",
"the",
"user",
"with",
"a",
"vertical",
"list",
"of",
"multiple",
"items",
"."
] | python | train | 32.21875 |
IDSIA/sacred | sacred/utils.py | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L372-L395 | def set_by_dotted_path(d, path, value):
"""
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.... | [
"def",
"set_by_dotted_path",
"(",
"d",
",",
"path",
",",
"value",
")",
":",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_option",
"=",
"d",
"for",
"p",
"in",
"split_path",
"[",
":",
"-",
"1",
"]",
":",
"if",
"p",
"not",
"in",
... | Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'ba... | [
"Set",
"an",
"entry",
"in",
"a",
"nested",
"dict",
"using",
"a",
"dotted",
"path",
"."
] | python | train | 25.541667 |
saltstack/salt | salt/runners/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L43-L52 | def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
a... | [
"def",
"soft_kill",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"minion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"minion",
".",
"functions",
"[",
"'state.soft_kill'",
"]",
"(",
"jid",
",",
"state_id",
")"
] | Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run. | [
"Set",
"up",
"a",
"state",
"run",
"to",
"die",
"before",
"executing",
"the",
"given",
"state",
"id",
"this",
"instructs",
"a",
"running",
"state",
"to",
"safely",
"exit",
"at",
"a",
"given",
"state",
"id",
".",
"This",
"needs",
"to",
"pass",
"in",
"the... | python | train | 46 |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L40-L63 | def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not params:
params = {}
if not command:
command = ''
else:
command = '/' + command
... | [
"def",
"_create_get_request",
"(",
"self",
",",
"resource",
",",
"billomat_id",
"=",
"''",
",",
"command",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"command",
":",
"command",
... | Creates a get request and return the response data | [
"Creates",
"a",
"get",
"request",
"and",
"return",
"the",
"response",
"data"
] | python | train | 31.291667 |
all-umass/graphs | graphs/base/base.py | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/base/base.py#L94-L110 | def reweight_by_distance(self, coords, metric='l2', copy=False):
'''Replaces existing edge weights by distances between connected vertices.
The new weight of edge (i,j) is given by: metric(coords[i], coords[j]).
coords : (num_vertices x d) array of coordinates, in vertex order
metric : str or callable, ... | [
"def",
"reweight_by_distance",
"(",
"self",
",",
"coords",
",",
"metric",
"=",
"'l2'",
",",
"copy",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"'Cannot supply weights for unweighted graph; '",
... | Replaces existing edge weights by distances between connected vertices.
The new weight of edge (i,j) is given by: metric(coords[i], coords[j]).
coords : (num_vertices x d) array of coordinates, in vertex order
metric : str or callable, see sklearn.metrics.pairwise.paired_distances | [
"Replaces",
"existing",
"edge",
"weights",
"by",
"distances",
"between",
"connected",
"vertices",
".",
"The",
"new",
"weight",
"of",
"edge",
"(",
"i",
"j",
")",
"is",
"given",
"by",
":",
"metric",
"(",
"coords",
"[",
"i",
"]",
"coords",
"[",
"j",
"]",
... | python | train | 50.588235 |
googleapis/google-cloud-python | dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/workflow_template_service_client.py#L202-L268 | def create_workflow_template(
self,
parent,
template,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates new workflow template.
Example:
>>> from google.clo... | [
"def",
"create_workflow_template",
"(",
"self",
",",
"parent",
",",
"template",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".... | Creates new workflow template.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.WorkflowTemplateServiceClient()
>>>
>>> parent = client.region_path('[PROJECT]', '[REGION]')
>>>
>>> # TODO... | [
"Creates",
"new",
"workflow",
"template",
"."
] | python | train | 45.164179 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1210-L1217 | def _set_id_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good ids for the different entities'''
if self.id_variable_by_entity_key is None:
self.id_variable_by_entity_key = dict(
(entity.key, entity.key + '_id') for entity in self.tax_benefit_system.... | [
"def",
"_set_id_variable_by_entity_key",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"if",
"self",
".",
"id_variable_by_entity_key",
"is",
"None",
":",
"self",
".",
"id_variable_by_entity_key",
"=",
"dict",
"(",
"(",
"entity",
".",
"key... | Identify and set the good ids for the different entities | [
"Identify",
"and",
"set",
"the",
"good",
"ids",
"for",
"the",
"different",
"entities"
] | python | train | 58.75 |
Jajcus/pyxmpp2 | pyxmpp2/ext/muc/muccore.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L635-L644 | def make_muc_userinfo(self):
"""
Create <x xmlns="...muc#user"/> element in the stanza.
:return: the element created.
:returntype: `MucUserX`
"""
self.clear_muc_child()
self.muc_child=MucUserX(parent=self.xmlnode)
return self.muc_child | [
"def",
"make_muc_userinfo",
"(",
"self",
")",
":",
"self",
".",
"clear_muc_child",
"(",
")",
"self",
".",
"muc_child",
"=",
"MucUserX",
"(",
"parent",
"=",
"self",
".",
"xmlnode",
")",
"return",
"self",
".",
"muc_child"
] | Create <x xmlns="...muc#user"/> element in the stanza.
:return: the element created.
:returntype: `MucUserX` | [
"Create",
"<x",
"xmlns",
"=",
"...",
"muc#user",
"/",
">",
"element",
"in",
"the",
"stanza",
"."
] | python | valid | 29.1 |
thusoy/python-crypt | pcrypt.py | https://github.com/thusoy/python-crypt/blob/0835f7568c14762890cea70b7605d04b3459e4a0/pcrypt.py#L81-L216 | def sha2_crypt(key, salt, hashfunc, rounds=_ROUNDS_DEFAULT):
"""
This algorithm is insane. History can be found at
https://en.wikipedia.org/wiki/Crypt_%28C%29
"""
key = key.encode('utf-8')
h = hashfunc()
alt_h = hashfunc()
digest_size = h.digest_size
key_len = len(key)
# First, ... | [
"def",
"sha2_crypt",
"(",
"key",
",",
"salt",
",",
"hashfunc",
",",
"rounds",
"=",
"_ROUNDS_DEFAULT",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"h",
"=",
"hashfunc",
"(",
")",
"alt_h",
"=",
"hashfunc",
"(",
")",
"digest_size",
... | This algorithm is insane. History can be found at
https://en.wikipedia.org/wiki/Crypt_%28C%29 | [
"This",
"algorithm",
"is",
"insane",
".",
"History",
"can",
"be",
"found",
"at",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Crypt_%28C%29"
] | python | train | 41.713235 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L940-L1019 | def transfer_to(self, cloudpath, bbox, block_size=None, compress=True):
"""
Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. Thi... | [
"def",
"transfer_to",
"(",
"self",
",",
"cloudpath",
",",
"bbox",
",",
"block_size",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"type",
"(",
"bbox",
")",
"is",
"Bbox",
":",
"requested_bbox",
"=",
"bbox",
"else",
":",
"(",
"requested_bbo... | Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is provided for convenience. It
may be optimized for better performance... | [
"Transfer",
"files",
"from",
"one",
"storage",
"location",
"to",
"another",
"bypassing",
"volume",
"painting",
".",
"This",
"enables",
"using",
"a",
"single",
"CloudVolume",
"instance",
"to",
"transfer",
"big",
"volumes",
".",
"In",
"some",
"cases",
"gsutil",
... | python | train | 38.5625 |
Garee/pytodoist | pytodoist/api.py | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L415-L427 | def _get(self, end_point, params=None, **kwargs):
"""Send a HTTP GET request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param kwargs: Any optional param... | [
"def",
"_get",
"(",
"self",
",",
"end_point",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_request",
"(",
"requests",
".",
"get",
",",
"end_point",
",",
"params",
",",
"*",
"*",
"kwargs",
")"
] | Send a HTTP GET request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param kwargs: Any optional parameters.
:type kwargs: dict
:return: The HTTP r... | [
"Send",
"a",
"HTTP",
"GET",
"request",
"to",
"a",
"Todoist",
"API",
"end",
"-",
"point",
"."
] | python | train | 39.923077 |
tanghaibao/jcvi | jcvi/variation/cnv.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/cnv.py#L849-L888 | def hmm(args):
"""
%prog hmm workdir sample_key
Run CNV segmentation caller. The workdir must contain a subfolder called
`sample_key-cn` that contains CN for each chromosome. A `beta` directory
that contains scaler for each bin must also be present in the current
directory.
"""
p = Opti... | [
"def",
"hmm",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"hmm",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mu\"",
",",
"default",
"=",
".003",
",",
"type",
"=",
"\"float\"",
",",
"help",
"=",
"\"Transition probability\"",
")",
"p... | %prog hmm workdir sample_key
Run CNV segmentation caller. The workdir must contain a subfolder called
`sample_key-cn` that contains CN for each chromosome. A `beta` directory
that contains scaler for each bin must also be present in the current
directory. | [
"%prog",
"hmm",
"workdir",
"sample_key"
] | python | train | 37.825 |
hydpy-dev/hydpy | hydpy/models/hland/hland_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hland/hland_model.py#L13-L57 | def calc_tc_v1(self):
"""Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
... | [
"def",
"calc_tc_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"inp",
"=",
"self",
".",
"sequences",
".",
"inputs",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fas... | Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
:math:`TC = T - TCAlt \... | [
"Adjust",
"the",
"measured",
"air",
"temperature",
"to",
"the",
"altitude",
"of",
"the",
"individual",
"zones",
"."
] | python | train | 25.777778 |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/client.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/client.py#L305-L312 | def stop_button_click_handler(self):
"""Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True)
# Interrupt computations or stop debugging
if not self.shellwidget._reading:
self.interrupt_kernel()
else:
self... | [
"def",
"stop_button_click_handler",
"(",
"self",
")",
":",
"self",
".",
"stop_button",
".",
"setDisabled",
"(",
"True",
")",
"# Interrupt computations or stop debugging\r",
"if",
"not",
"self",
".",
"shellwidget",
".",
"_reading",
":",
"self",
".",
"interrupt_kernel... | Method to handle what to do when the stop button is pressed | [
"Method",
"to",
"handle",
"what",
"to",
"do",
"when",
"the",
"stop",
"button",
"is",
"pressed"
] | python | train | 43.5 |
CalebBell/fluids | fluids/numerics/__init__.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L620-L640 | def polyder(c, m=1, scl=1, axis=0):
'''not quite a copy of numpy's version because this was faster to implement.
'''
c = list(c)
cnt = int(m)
if cnt == 0:
return c
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
for i in range(cnt):
n = n - 1
c... | [
"def",
"polyder",
"(",
"c",
",",
"m",
"=",
"1",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"list",
"(",
"c",
")",
"cnt",
"=",
"int",
"(",
"m",
")",
"if",
"cnt",
"==",
"0",
":",
"return",
"c",
"n",
"=",
"len",
"(",
... | not quite a copy of numpy's version because this was faster to implement. | [
"not",
"quite",
"a",
"copy",
"of",
"numpy",
"s",
"version",
"because",
"this",
"was",
"faster",
"to",
"implement",
"."
] | python | train | 21.714286 |
bububa/pyTOP | pyTOP/packages/requests/models.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/models.py#L569-L600 | def content(self):
"""Content of the response, in bytes or unicode
(if available).
"""
if self._content is not None:
return self._content
if self._content_consumed:
raise RuntimeError('The content for this response was '
'a... | [
"def",
"content",
"(",
"self",
")",
":",
"if",
"self",
".",
"_content",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_content",
"if",
"self",
".",
"_content_consumed",
":",
"raise",
"RuntimeError",
"(",
"'The content for this response was '",
"'already cons... | Content of the response, in bytes or unicode
(if available). | [
"Content",
"of",
"the",
"response",
"in",
"bytes",
"or",
"unicode",
"(",
"if",
"available",
")",
"."
] | python | train | 27.59375 |
kgori/treeCl | treeCl/utils/ambiguate.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/utils/ambiguate.py#L83-L90 | def remove_empty(rec):
""" Deletes sequences that were marked for deletion by convert_to_IUPAC """
for header, sequence in rec.mapping.items():
if all(char == 'X' for char in sequence):
rec.headers.remove(header)
rec.sequences.remove(sequence)
rec.update()
return rec | [
"def",
"remove_empty",
"(",
"rec",
")",
":",
"for",
"header",
",",
"sequence",
"in",
"rec",
".",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"all",
"(",
"char",
"==",
"'X'",
"for",
"char",
"in",
"sequence",
")",
":",
"rec",
".",
"headers",
".",
... | Deletes sequences that were marked for deletion by convert_to_IUPAC | [
"Deletes",
"sequences",
"that",
"were",
"marked",
"for",
"deletion",
"by",
"convert_to_IUPAC"
] | python | train | 38.5 |
keras-rl/keras-rl | rl/callbacks.py | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L267-L279 | def on_step_end(self, step, logs):
""" Update progression bar at the end of each step """
if self.info_names is None:
self.info_names = logs['info'].keys()
values = [('reward', logs['reward'])]
if KERAS_VERSION > '2.1.3':
self.progbar.update((self.step % self.inte... | [
"def",
"on_step_end",
"(",
"self",
",",
"step",
",",
"logs",
")",
":",
"if",
"self",
".",
"info_names",
"is",
"None",
":",
"self",
".",
"info_names",
"=",
"logs",
"[",
"'info'",
"]",
".",
"keys",
"(",
")",
"values",
"=",
"[",
"(",
"'reward'",
",",
... | Update progression bar at the end of each step | [
"Update",
"progression",
"bar",
"at",
"the",
"end",
"of",
"each",
"step"
] | python | train | 47.538462 |
instaloader/instaloader | instaloader/instaloader.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloader.py#L603-L636 | def download_highlights(self,
user: Union[int, Profile],
fast_update: bool = False,
filename_target: Optional[str] = None,
storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> None:
"""
... | [
"def",
"download_highlights",
"(",
"self",
",",
"user",
":",
"Union",
"[",
"int",
",",
"Profile",
"]",
",",
"fast_update",
":",
"bool",
"=",
"False",
",",
"filename_target",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"storyitem_filter",
":",
"Op... | Download available highlights from a user whose ID is given.
To use this, one needs to be logged in.
.. versionadded:: 4.1
:param user: ID or Profile of the user whose highlights should get downloaded.
:param fast_update: If true, abort when first already-downloaded picture is encounte... | [
"Download",
"available",
"highlights",
"from",
"a",
"user",
"whose",
"ID",
"is",
"given",
".",
"To",
"use",
"this",
"one",
"needs",
"to",
"be",
"logged",
"in",
"."
] | python | train | 60.205882 |
a1ezzz/wasp-general | wasp_general/task/registry.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/registry.py#L180-L192 | def remove(self, task_cls):
""" Remove task from the storage. If task class are stored multiple times
(if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is True) - removes all of them.
:param task_cls: task to remove
:return: None
"""
registry_tag = task_cls.__registry_tag__
if registry_tag in ... | [
"def",
"remove",
"(",
"self",
",",
"task_cls",
")",
":",
"registry_tag",
"=",
"task_cls",
".",
"__registry_tag__",
"if",
"registry_tag",
"in",
"self",
".",
"__registry",
".",
"keys",
"(",
")",
":",
"self",
".",
"__registry",
"[",
"registry_tag",
"]",
"=",
... | Remove task from the storage. If task class are stored multiple times
(if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is True) - removes all of them.
:param task_cls: task to remove
:return: None | [
"Remove",
"task",
"from",
"the",
"storage",
".",
"If",
"task",
"class",
"are",
"stored",
"multiple",
"times",
"(",
"if",
":",
"attr",
":",
".",
"WTaskRegistryStorage",
".",
"__multiple_tasks_per_tag__",
"is",
"True",
")",
"-",
"removes",
"all",
"of",
"them",... | python | train | 40.461538 |
saltstack/salt | salt/modules/keystone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L542-L558 | def service_delete(service_id=None, name=None, profile=None, **connection_args):
'''
Delete a service from Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.service_delete name=nova
'''
... | [
"def",
"service_delete",
"(",
"service_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"*",
"*",
"connection_args",
")",
"if",
"name",
":",... | Delete a service from Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.service_delete name=nova | [
"Delete",
"a",
"service",
"from",
"Keystone",
"service",
"catalog"
] | python | train | 34.764706 |
gem/oq-engine | openquake/hazardlib/mfd/youngs_coppersmith_1985.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L289-L308 | def _get_rate(self, mag):
"""
Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value.
... | [
"def",
"_get_rate",
"(",
"self",
",",
"mag",
")",
":",
"mag_lo",
"=",
"mag",
"-",
"self",
".",
"bin_width",
"/",
"2.0",
"mag_hi",
"=",
"mag",
"+",
"self",
".",
"bin_width",
"/",
"2.0",
"if",
"mag",
">=",
"self",
".",
"min_mag",
"and",
"mag",
"<",
... | Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value. | [
"Calculate",
"and",
"return",
"the",
"annual",
"occurrence",
"rate",
"for",
"a",
"specific",
"bin",
"."
] | python | train | 42.9 |
phac-nml/sistr_cmd | sistr/src/serovar_prediction/__init__.py | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/serovar_prediction/__init__.py#L434-L540 | def overall_serovar_call(serovar_prediction, antigen_predictor):
"""
Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or lis... | [
"def",
"overall_serovar_call",
"(",
"serovar_prediction",
",",
"antigen_predictor",
")",
":",
"assert",
"isinstance",
"(",
"serovar_prediction",
",",
"SerovarPrediction",
")",
"assert",
"isinstance",
"(",
"antigen_predictor",
",",
"SerovarPredictor",
")",
"h1",
"=",
"... | Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or list of serovars, however,
the cgMLST membership may be able to help narrow ... | [
"Predict",
"serovar",
"from",
"cgMLST",
"cluster",
"membership",
"analysis",
"and",
"antigen",
"BLAST",
"results",
".",
"SerovarPrediction",
"object",
"is",
"assigned",
"H1",
"H2",
"and",
"Serogroup",
"from",
"the",
"antigen",
"BLAST",
"results",
".",
"Antigen",
... | python | train | 43.654206 |
Qiskit/qiskit-terra | qiskit/quantum_info/operators/channel/superop.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/superop.py#L416-L425 | def _instruction_to_superop(cls, instruction):
"""Convert a QuantumCircuit or Instruction to a SuperOp."""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
instruction = instruction.to_instruction()
# Initialize an identity superoperator of the ... | [
"def",
"_instruction_to_superop",
"(",
"cls",
",",
"instruction",
")",
":",
"# Convert circuit to an instruction",
"if",
"isinstance",
"(",
"instruction",
",",
"QuantumCircuit",
")",
":",
"instruction",
"=",
"instruction",
".",
"to_instruction",
"(",
")",
"# Initializ... | Convert a QuantumCircuit or Instruction to a SuperOp. | [
"Convert",
"a",
"QuantumCircuit",
"or",
"Instruction",
"to",
"a",
"SuperOp",
"."
] | python | test | 46.8 |
openstack/horizon | openstack_dashboard/utils/settings.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L41-L61 | def import_dashboard_config(modules):
"""Imports configuration from all the modules and merges it."""
config = collections.defaultdict(dict)
for module in modules:
for submodule in import_submodules(module).values():
if hasattr(submodule, 'DASHBOARD'):
dashboard = submodu... | [
"def",
"import_dashboard_config",
"(",
"modules",
")",
":",
"config",
"=",
"collections",
".",
"defaultdict",
"(",
"dict",
")",
"for",
"module",
"in",
"modules",
":",
"for",
"submodule",
"in",
"import_submodules",
"(",
"module",
")",
".",
"values",
"(",
")",... | Imports configuration from all the modules and merges it. | [
"Imports",
"configuration",
"from",
"all",
"the",
"modules",
"and",
"merges",
"it",
"."
] | python | train | 53.095238 |
juztin/flask-tracy | flask_tracy/base.py | https://github.com/juztin/flask-tracy/blob/8a43094f0fced3c216f7b65ad6c5c7a22c14ea25/flask_tracy/base.py#L48-L57 | def init_app(self, app):
"""Setup before_request, after_request handlers for tracing.
"""
app.config.setdefault("TRACY_REQUIRE_CLIENT", False)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.before_request(self._... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"\"TRACY_REQUIRE_CLIENT\"",
",",
"False",
")",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}... | Setup before_request, after_request handlers for tracing. | [
"Setup",
"before_request",
"after_request",
"handlers",
"for",
"tracing",
"."
] | python | valid | 35.7 |
Crunch-io/crunch-cube | src/cr/cube/cube_slice.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/cube_slice.py#L588-L609 | def _array_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils... | [
"def",
"_array_type_std_res",
"(",
"self",
",",
"counts",
",",
"total",
",",
"colsum",
",",
"rowsum",
")",
":",
"if",
"self",
".",
"mr_dim_ind",
"==",
"0",
":",
"# --This is a special case where broadcasting cannot be",
"# --automatically done. We need to \"inflate\" the ... | Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually indep... | [
"Return",
"ndarray",
"containing",
"standard",
"residuals",
"for",
"array",
"values",
"."
] | python | train | 55.363636 |
bitly/asyncmongo | asyncmongo/pool.py | https://github.com/bitly/asyncmongo/blob/3da47c96d4592ec9e8b3ef5cf1b7d5b439ab3a5b/asyncmongo/pool.py#L41-L54 | def close_idle_connections(self, pool_id=None):
"""close idle connections to mongo"""
if not hasattr(self, '_pools'):
return
if pool_id:
if pool_id not in self._pools:
raise ProgrammingError("pool %r does not exist" % pool_id)
else:
... | [
"def",
"close_idle_connections",
"(",
"self",
",",
"pool_id",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_pools'",
")",
":",
"return",
"if",
"pool_id",
":",
"if",
"pool_id",
"not",
"in",
"self",
".",
"_pools",
":",
"raise",
"Pro... | close idle connections to mongo | [
"close",
"idle",
"connections",
"to",
"mongo"
] | python | train | 33.285714 |
gwastro/pycbc | pycbc/inference/sampler/base_mcmc.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/base_mcmc.py#L358-L369 | def pos(self):
"""A dictionary of the current walker positions.
If the sampler hasn't been run yet, returns p0.
"""
pos = self._pos
if pos is None:
return self.p0
# convert to dict
pos = {param: self._pos[..., k]
for (k, param) in enume... | [
"def",
"pos",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"_pos",
"if",
"pos",
"is",
"None",
":",
"return",
"self",
".",
"p0",
"# convert to dict",
"pos",
"=",
"{",
"param",
":",
"self",
".",
"_pos",
"[",
"...",
",",
"k",
"]",
"for",
"(",
"... | A dictionary of the current walker positions.
If the sampler hasn't been run yet, returns p0. | [
"A",
"dictionary",
"of",
"the",
"current",
"walker",
"positions",
"."
] | python | train | 29.583333 |
eirannejad/Revit-Journal-Maker | rjm/__init__.py | https://github.com/eirannejad/Revit-Journal-Maker/blob/09a4f27da6d183f63a2c93ed99dca8a8590d5241/rjm/__init__.py#L59-L73 | def _init_journal(self, permissive=True):
"""Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journ... | [
"def",
"_init_journal",
"(",
"self",
",",
"permissive",
"=",
"True",
")",
":",
"nowstamp",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%d-%b-%Y %H:%M:%S.%f\"",
")",
"[",
":",
"-",
"3",
"]",
"self",
".",
"_add_entry",
"(",
"templates",... | Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journal execution.
Some sti... | [
"Add",
"the",
"initialization",
"lines",
"to",
"the",
"journal",
"."
] | python | train | 41.6 |
pysathq/pysat | pysat/card.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/card.py#L463-L531 | def increase(self, ubound=1, top_id=None):
"""
Increases a potential upper bound that can be imposed on the
literals in the sum of an existing :class:`ITotalizer` object to a
new value.
:param ubound: a new upper bound.
:param top_id: a new top variab... | [
"def",
"increase",
"(",
"self",
",",
"ubound",
"=",
"1",
",",
"top_id",
"=",
"None",
")",
":",
"self",
".",
"top_id",
"=",
"max",
"(",
"self",
".",
"top_id",
",",
"top_id",
"if",
"top_id",
"!=",
"None",
"else",
"0",
")",
"# do nothing if the bound is s... | Increases a potential upper bound that can be imposed on the
literals in the sum of an existing :class:`ITotalizer` object to a
new value.
:param ubound: a new upper bound.
:param top_id: a new top variable identifier.
:type ubound: int
:type top... | [
"Increases",
"a",
"potential",
"upper",
"bound",
"that",
"can",
"be",
"imposed",
"on",
"the",
"literals",
"in",
"the",
"sum",
"of",
"an",
"existing",
":",
"class",
":",
"ITotalizer",
"object",
"to",
"a",
"new",
"value",
"."
] | python | train | 36.956522 |
esheldon/fitsio | fitsio/header.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/header.py#L372-L438 | def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello ... | [
"def",
"_record2card",
"(",
"self",
",",
"record",
")",
":",
"name",
"=",
"record",
"[",
"'name'",
"]",
"value",
"=",
"record",
"[",
"'value'",
"]",
"v_isstring",
"=",
"isstring",
"(",
"value",
")",
"if",
"name",
"==",
"'COMMENT'",
":",
"# card = 'COMMEN... | when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello '
KEYSC = 'hello ' / a c... | [
"when",
"we",
"add",
"new",
"records",
"they",
"don",
"t",
"have",
"a",
"card",
"this",
"sort",
"of",
"fakes",
"it",
"up",
"similar",
"to",
"what",
"cfitsio",
"does",
"just",
"for",
"display",
"purposes",
".",
"e",
".",
"g",
"."
] | python | train | 32.955224 |
ga4gh/ga4gh-server | ga4gh/server/datamodel/__init__.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/__init__.py#L250-L257 | def obfuscate(cls, idStr):
"""
Mildly obfuscates the specified ID string in an easily reversible
fashion. This is not intended for security purposes, but rather to
dissuade users from depending on our internal ID structures.
"""
return unicode(base64.urlsafe_b64encode(
... | [
"def",
"obfuscate",
"(",
"cls",
",",
"idStr",
")",
":",
"return",
"unicode",
"(",
"base64",
".",
"urlsafe_b64encode",
"(",
"idStr",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"replace",
"(",
"b'='",
",",
"b''",
")",
")"
] | Mildly obfuscates the specified ID string in an easily reversible
fashion. This is not intended for security purposes, but rather to
dissuade users from depending on our internal ID structures. | [
"Mildly",
"obfuscates",
"the",
"specified",
"ID",
"string",
"in",
"an",
"easily",
"reversible",
"fashion",
".",
"This",
"is",
"not",
"intended",
"for",
"security",
"purposes",
"but",
"rather",
"to",
"dissuade",
"users",
"from",
"depending",
"on",
"our",
"inter... | python | train | 45.625 |
saltstack/salt | salt/grains/core.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L2087-L2112 | def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaul... | [
"def",
"locale_info",
"(",
")",
":",
"grains",
"=",
"{",
"}",
"grains",
"[",
"'locale_info'",
"]",
"=",
"{",
"}",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_proxy",
"(",
")",
":",
"return",
"grains",
"try",
":",
"(",
"grains",
"[",
"'loc... | Provides
defaultlanguage
defaultencoding | [
"Provides",
"defaultlanguage",
"defaultencoding"
] | python | train | 30.846154 |
eqcorrscan/EQcorrscan | eqcorrscan/core/match_filter.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/core/match_filter.py#L366-L375 | def select(self, template_name):
"""
Select a specific family from the party.
:type template_name: str
:param template_name: Template name of Family to select from a party.
:returns: Family
"""
return [fam for fam in self.families
if fam.template.... | [
"def",
"select",
"(",
"self",
",",
"template_name",
")",
":",
"return",
"[",
"fam",
"for",
"fam",
"in",
"self",
".",
"families",
"if",
"fam",
".",
"template",
".",
"name",
"==",
"template_name",
"]",
"[",
"0",
"]"
] | Select a specific family from the party.
:type template_name: str
:param template_name: Template name of Family to select from a party.
:returns: Family | [
"Select",
"a",
"specific",
"family",
"from",
"the",
"party",
"."
] | python | train | 33.6 |
hydpy-dev/hydpy | hydpy/models/lland/lland_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_model.py#L47-L78 | def calc_tkor_v1(self):
"""Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland ... | [
"def",
"calc_tkor_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"inp",
"=",
"self",
".",
"sequences",
".",
"inputs",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"f... | Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland import *
>>> parameters... | [
"Adjust",
"the",
"given",
"air",
"temperature",
"values",
"."
] | python | train | 22.0625 |
gem/oq-engine | openquake/hazardlib/site.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L256-L262 | def make_complete(self):
"""
Turns the site collection into a complete one, if needed
"""
# reset the site indices from 0 to N-1 and set self.complete to self
self.array['sids'] = numpy.arange(len(self), dtype=numpy.uint32)
self.complete = self | [
"def",
"make_complete",
"(",
"self",
")",
":",
"# reset the site indices from 0 to N-1 and set self.complete to self",
"self",
".",
"array",
"[",
"'sids'",
"]",
"=",
"numpy",
".",
"arange",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"numpy",
".",
"uint32",... | Turns the site collection into a complete one, if needed | [
"Turns",
"the",
"site",
"collection",
"into",
"a",
"complete",
"one",
"if",
"needed"
] | python | train | 40.857143 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L152-L165 | def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.respo... | [
"def",
"_parse_response_types",
"(",
"argspec",
",",
"attrs",
")",
":",
"return_type",
"=",
"argspec",
".",
"annotations",
".",
"get",
"(",
"\"return\"",
")",
"or",
"None",
"type_description",
"=",
"attrs",
".",
"parameter_descriptions",
".",
"get",
"(",
"\"re... | from the given parameters, return back the response type dictionaries. | [
"from",
"the",
"given",
"parameters",
"return",
"back",
"the",
"response",
"type",
"dictionaries",
"."
] | python | train | 43.285714 |
saltstack/salt | salt/modules/cabal.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cabal.py#L106-L149 | def list_(
pkg=None,
user=None,
installed=False,
env=None):
'''
List packages matching a search string.
pkg
Search string for matching package names
user
The user to run cabal list with
installed
If True, only return installed packages.
en... | [
"def",
"list_",
"(",
"pkg",
"=",
"None",
",",
"user",
"=",
"None",
",",
"installed",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'cabal list --simple-output'",
"]",
"if",
"installed",
":",
"cmd",
".",
"append",
"(",
"'--installed... | List packages matching a search string.
pkg
Search string for matching package names
user
The user to run cabal list with
installed
If True, only return installed packages.
env
Environment variables to set when invoking cabal. Uses the
same ``env`` format as the ... | [
"List",
"packages",
"matching",
"a",
"search",
"string",
"."
] | python | train | 23.227273 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_package.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_package.py#L352-L368 | def zip_file(self, app_path, app_name, tmp_path):
"""Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip.
"""
# zip build directo... | [
"def",
"zip_file",
"(",
"self",
",",
"app_path",
",",
"app_name",
",",
"tmp_path",
")",
":",
"# zip build directory",
"zip_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_path",
",",
"self",
".",
"args",
".",
"outdir",
",",
"app_name",
")",
"zip_fi... | Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip. | [
"Zip",
"the",
"App",
"with",
"tcex",
"extension",
"."
] | python | train | 44.764706 |
pytorch/text | torchtext/data/field.py | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/data/field.py#L694-L723 | def numericalize(self, arrs, device=None):
"""Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokeni... | [
"def",
"numericalize",
"(",
"self",
",",
"arrs",
",",
"device",
"=",
"None",
")",
":",
"numericalized",
"=",
"[",
"]",
"self",
".",
"nesting_field",
".",
"include_lengths",
"=",
"False",
"if",
"self",
".",
"include_lengths",
":",
"arrs",
",",
"sentence_len... | Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokenized and padded examples.
device (str or to... | [
"Convert",
"a",
"padded",
"minibatch",
"into",
"a",
"variable",
"tensor",
"."
] | python | train | 44.966667 |
kubernetes-client/python | kubernetes/client/apis/authorization_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/authorization_v1_api.py#L369-L391 | def create_subject_access_review(self, body, **kwargs):
"""
create a SubjectAccessReview
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_subject_access_review(body, async_req=True)
... | [
"def",
"create_subject_access_review",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"create_subject_... | create a SubjectAccessReview
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_subject_access_review(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:par... | [
"create",
"a",
"SubjectAccessReview",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api",
".",
... | python | train | 64.304348 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/input_readers.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L682-L713 | def _validate_filters_ndb(cls, filters, model_class):
"""Validate ndb.Model filters."""
if not filters:
return
properties = model_class._properties
for idx, f in enumerate(filters):
prop, ineq, val = f
if prop not in properties:
raise errors.BadReaderParamsError(
... | [
"def",
"_validate_filters_ndb",
"(",
"cls",
",",
"filters",
",",
"model_class",
")",
":",
"if",
"not",
"filters",
":",
"return",
"properties",
"=",
"model_class",
".",
"_properties",
"for",
"idx",
",",
"f",
"in",
"enumerate",
"(",
"filters",
")",
":",
"pro... | Validate ndb.Model filters. | [
"Validate",
"ndb",
".",
"Model",
"filters",
"."
] | python | train | 31.28125 |
boto/s3transfer | s3transfer/processpool.py | https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/processpool.py#L321-L364 | def download_file(self, bucket, key, filename, extra_args=None,
expected_size=None):
"""Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to dow... | [
"def",
"download_file",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"filename",
",",
"extra_args",
"=",
"None",
",",
"expected_size",
"=",
"None",
")",
":",
"self",
".",
"_start_if_needed",
"(",
")",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
... | Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to download from
:type filename: str
:param filename: The name of a file to download to.
:type ext... | [
"Downloads",
"the",
"object",
"s",
"contents",
"to",
"a",
"file"
] | python | test | 41 |
brocade/pynos | pynos/versions/base/yang/brocade_sflow.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/brocade_sflow.py#L22-L34 | def sflow_collector_collector_ip_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")
collector = ET.SubElement(sflow, "collector")
collector_port_number_key = ... | [
"def",
"sflow_collector_collector_ip_address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"sflow",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"sflow\"",
",",
"xmlns",
"=",
"\"urn:br... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 52 |
Enteee/pdml2flow | pdml2flow/autovivification.py | https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L36-L55 | def compress(self, d=DEFAULT):
"""Returns a copy of d with compressed leaves."""
if d is DEFAULT:
d = self
if isinstance(d, list):
l = [v for v in (self.compress(v) for v in d)]
try:
return list(set(l))
except TypeError:
... | [
"def",
"compress",
"(",
"self",
",",
"d",
"=",
"DEFAULT",
")",
":",
"if",
"d",
"is",
"DEFAULT",
":",
"d",
"=",
"self",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"l",
"=",
"[",
"v",
"for",
"v",
"in",
"(",
"self",
".",
"compress",
"(... | Returns a copy of d with compressed leaves. | [
"Returns",
"a",
"copy",
"of",
"d",
"with",
"compressed",
"leaves",
"."
] | python | train | 38.05 |
taskcluster/taskcluster-client.py | taskcluster/authevents.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/authevents.py#L128-L150 | def roleUpdated(self, *args, **kwargs):
"""
Role Updated Messages
Message that a new role has been updated.
This exchange outputs: ``v1/role-message.json#``This exchange takes the following keys:
* reserved: Space reserved for future routing-key entries, you should always mat... | [
"def",
"roleUpdated",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ref",
"=",
"{",
"'exchange'",
":",
"'role-updated'",
",",
"'name'",
":",
"'roleUpdated'",
",",
"'routingKey'",
":",
"[",
"{",
"'multipleWords'",
":",
"True",
",",
... | Role Updated Messages
Message that a new role has been updated.
This exchange outputs: ``v1/role-message.json#``This exchange takes the following keys:
* reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling... | [
"Role",
"Updated",
"Messages"
] | python | train | 33.130435 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/breakpoint.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L2744-L2766 | def enable_one_shot_page_breakpoint(self, dwProcessId, address):
"""
Enables the page breakpoint at the given address for only one shot.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
... | [
"def",
"enable_one_shot_page_breakpoint",
"(",
"self",
",",
"dwProcessId",
",",
"address",
")",
":",
"p",
"=",
"self",
".",
"system",
".",
"get_process",
"(",
"dwProcessId",
")",
"bp",
"=",
"self",
".",
"get_page_breakpoint",
"(",
"dwProcessId",
",",
"address"... | Enables the page breakpoint at the given address for only one shot.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
L{disable_page_breakpoint}
L{erase_page_breakpoint},
@... | [
"Enables",
"the",
"page",
"breakpoint",
"at",
"the",
"given",
"address",
"for",
"only",
"one",
"shot",
"."
] | python | train | 33.434783 |
mezz64/pyEmby | pyemby/server.py | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/server.py#L232-L253 | async def api_request(self, url, params):
"""Make api fetch request."""
request = None
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
request = await self._api_session.get(
url, params=params)
if request.status... | [
"async",
"def",
"api_request",
"(",
"self",
",",
"url",
",",
"params",
")",
":",
"request",
"=",
"None",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"DEFAULT_TIMEOUT",
",",
"loop",
"=",
"self",
".",
"_event_loop",
")",
":",
"request",
"=",
... | Make api fetch request. | [
"Make",
"api",
"fetch",
"request",
"."
] | python | train | 43.5 |
nok/sklearn-porter | sklearn_porter/estimator/classifier/RandomForestClassifier/__init__.py | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/RandomForestClassifier/__init__.py#L153-L176 | def predict(self, temp_type):
"""
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict metho... | [
"def",
"predict",
"(",
"self",
",",
"temp_type",
")",
":",
"# Exported:",
"if",
"temp_type",
"==",
"'exported'",
":",
"temp",
"=",
"self",
".",
"temp",
"(",
"'exported.class'",
")",
"return",
"temp",
".",
"format",
"(",
"class_name",
"=",
"self",
".",
"c... | Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict method as string. | [
"Transpile",
"the",
"predict",
"method",
"."
] | python | train | 31.833333 |
timothydmorton/VESPA | vespa/populations.py | https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/populations.py#L409-L422 | def prior(self):
"""
Model prior for particular model.
Product of eclipse probability (``self.prob``),
the fraction of scenario that is allowed by the various
constraints (``self.selectfrac``), and all additional
factors in ``self.priorfactors``.
"""
pri... | [
"def",
"prior",
"(",
"self",
")",
":",
"prior",
"=",
"self",
".",
"prob",
"*",
"self",
".",
"selectfrac",
"for",
"f",
"in",
"self",
".",
"priorfactors",
":",
"prior",
"*=",
"self",
".",
"priorfactors",
"[",
"f",
"]",
"return",
"prior"
] | Model prior for particular model.
Product of eclipse probability (``self.prob``),
the fraction of scenario that is allowed by the various
constraints (``self.selectfrac``), and all additional
factors in ``self.priorfactors``. | [
"Model",
"prior",
"for",
"particular",
"model",
"."
] | python | train | 31.285714 |
google/python-adb | adb/fastboot.py | https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/fastboot.py#L328-L340 | def Flash(self, partition, timeout_ms=0, info_cb=DEFAULT_MESSAGE_CALLBACK):
"""Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_c... | [
"def",
"Flash",
"(",
"self",
",",
"partition",
",",
"timeout_ms",
"=",
"0",
",",
"info_cb",
"=",
"DEFAULT_MESSAGE_CALLBACK",
")",
":",
"return",
"self",
".",
"_SimpleCommand",
"(",
"b'flash'",
",",
"arg",
"=",
"partition",
",",
"info_cb",
"=",
"info_cb",
"... | Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. Usually no messages.
Returns:
Response to a downloa... | [
"Flashes",
"the",
"last",
"downloaded",
"file",
"to",
"the",
"given",
"partition",
"."
] | python | train | 43.846154 |
pybel/pybel | src/pybel/struct/filters/node_predicates.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicates.py#L152-L174 | def _node_has_modifier(graph: BELGraph, node: BaseEntity, modifier: str) -> bool:
"""Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
... | [
"def",
"_node_has_modifier",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
",",
"modifier",
":",
"str",
")",
"->",
"bool",
":",
"modifier_in_subject",
"=",
"any",
"(",
"part_has_modifier",
"(",
"d",
",",
"SUBJECT",
",",
"modifier",
")",
"f... | Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
:param modifier: One of :data:`pybel.constants.ACTIVITY`, :data:`pybel.constants.DEGRAD... | [
"Return",
"true",
"if",
"over",
"any",
"of",
"a",
"nodes",
"edges",
"it",
"has",
"a",
"given",
"modifier",
"."
] | python | train | 34.826087 |
JosuaKrause/quick_cache | quick_cache.py | https://github.com/JosuaKrause/quick_cache/blob/a6001f2d77247ae278e679a026174c83ff195d5a/quick_cache.py#L316-L319 | def has(self):
"""Whether the cache file exists in the file system."""
self._done = os.path.exists(self._cache_file)
return self._done or self._out is not None | [
"def",
"has",
"(",
"self",
")",
":",
"self",
".",
"_done",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_file",
")",
"return",
"self",
".",
"_done",
"or",
"self",
".",
"_out",
"is",
"not",
"None"
] | Whether the cache file exists in the file system. | [
"Whether",
"the",
"cache",
"file",
"exists",
"in",
"the",
"file",
"system",
"."
] | python | train | 45 |
Carbonara-Project/Guanciale | guanciale/idblib.py | https://github.com/Carbonara-Project/Guanciale/blob/c239ffac6fb481d09c4071d1de1a09f60dc584ab/guanciale/idblib.py#L924-L936 | def makekey(self, *args):
""" return a binary key for the nodeid, tag and optional value """
if len(args) > 1:
args = args[:1] + (args[1].encode('utf-8'),) + args[2:]
if len(args) == 3 and type(args[-1]) == str:
# node.tag.string type keys
return struct.... | [
"def",
"makekey",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"args",
"=",
"args",
"[",
":",
"1",
"]",
"+",
"(",
"args",
"[",
"1",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
",",
")",
"+",
"args",
... | return a binary key for the nodeid, tag and optional value | [
"return",
"a",
"binary",
"key",
"for",
"the",
"nodeid",
"tag",
"and",
"optional",
"value"
] | python | train | 57.230769 |
cltk/cltk | cltk/corpus/akkadian/cdli_corpus.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/akkadian/cdli_corpus.py#L108-L119 | def toc(self):
"""
Returns a rich list of texts in the catalog.
"""
output = []
for key in sorted(self.catalog.keys()):
edition = self.catalog[key]['edition']
length = len(self.catalog[key]['transliteration'])
output.append(
"Pn... | [
"def",
"toc",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"catalog",
".",
"keys",
"(",
")",
")",
":",
"edition",
"=",
"self",
".",
"catalog",
"[",
"key",
"]",
"[",
"'edition'",
"]",
"length",
... | Returns a rich list of texts in the catalog. | [
"Returns",
"a",
"rich",
"list",
"of",
"texts",
"in",
"the",
"catalog",
"."
] | python | train | 38.083333 |
mitsei/dlkit | dlkit/json_/assessment/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/managers.py#L2284-L2307 | def get_assessment_lookup_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment lookup service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.Assessm... | [
"def",
"get_assessment_lookup_session_for_bank",
"(",
"self",
",",
"bank_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment_lookup",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see if the ... | Gets the ``OsidSession`` associated with the assessment lookup service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentLookupSession) - ``an
_assessment_lookup_session``
... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"assessment",
"lookup",
"service",
"for",
"the",
"given",
"bank",
"."
] | python | train | 49.375 |
cloudmesh/cloudmesh-common | cloudmesh/common/util.py | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/util.py#L117-L132 | def convert_from_unicode(data):
"""
converts unicode data to a string
:param data: the data to convert
:return:
"""
# if isinstance(data, basestring):
if isinstance(data, str):
return str(data)
elif isinstance(data, collectionsAbc.Mapping):
return dict(map(convert_from_... | [
"def",
"convert_from_unicode",
"(",
"data",
")",
":",
"# if isinstance(data, basestring):",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"str",
"(",
"data",
")",
"elif",
"isinstance",
"(",
"data",
",",
"collectionsAbc",
".",
"Mapping",
")",... | converts unicode data to a string
:param data: the data to convert
:return: | [
"converts",
"unicode",
"data",
"to",
"a",
"string",
":",
"param",
"data",
":",
"the",
"data",
"to",
"convert",
":",
"return",
":"
] | python | train | 29.3125 |
python-openxml/python-docx | docx/image/image.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/image/image.py#L30-L36 | def from_blob(cls, blob):
"""
Return a new |Image| subclass instance parsed from the image binary
contained in *blob*.
"""
stream = BytesIO(blob)
return cls._from_stream(stream, blob) | [
"def",
"from_blob",
"(",
"cls",
",",
"blob",
")",
":",
"stream",
"=",
"BytesIO",
"(",
"blob",
")",
"return",
"cls",
".",
"_from_stream",
"(",
"stream",
",",
"blob",
")"
] | Return a new |Image| subclass instance parsed from the image binary
contained in *blob*. | [
"Return",
"a",
"new",
"|Image|",
"subclass",
"instance",
"parsed",
"from",
"the",
"image",
"binary",
"contained",
"in",
"*",
"blob",
"*",
"."
] | python | train | 32.142857 |
basho/riak-python-client | riak/bucket.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/bucket.py#L694-L710 | def get_buckets(self, timeout=None):
"""
Get the list of buckets under this bucket-type as
:class:`RiakBucket <riak.bucket.RiakBucket>` instances.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: Th... | [
"def",
"get_buckets",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"get_buckets",
"(",
"bucket_type",
"=",
"self",
",",
"timeout",
"=",
"timeout",
")"
] | Get the list of buckets under this bucket-type as
:class:`RiakBucket <riak.bucket.RiakBucket>` instances.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: This request is automatically retried :attr:`retries`
... | [
"Get",
"the",
"list",
"of",
"buckets",
"under",
"this",
"bucket",
"-",
"type",
"as",
":",
"class",
":",
"RiakBucket",
"<riak",
".",
"bucket",
".",
"RiakBucket",
">",
"instances",
"."
] | python | train | 39.529412 |
joeyespo/gitpress | gitpress/themes.py | https://github.com/joeyespo/gitpress/blob/a23edb80b6e4a113d167217475344a01c92b5c6d/gitpress/themes.py#L17-L21 | def list_themes(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
path = os.path.join(repo, themes_dir)
return os.listdir(path) if os.path.isdir(path) else None | [
"def",
"list_themes",
"(",
"directory",
"=",
"None",
")",
":",
"repo",
"=",
"require_repo",
"(",
"directory",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repo",
",",
"themes_dir",
")",
"return",
"os",
".",
"listdir",
"(",
"path",
")",
"if... | Gets a list of the installed themes. | [
"Gets",
"a",
"list",
"of",
"the",
"installed",
"themes",
"."
] | python | train | 42.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.