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 |
|---|---|---|---|---|---|---|---|---|---|
carljm/django-adminfiles | adminfiles/flickr.py | https://github.com/carljm/django-adminfiles/blob/b01dc7be266305d575c11d5ff9a37ccac04a78c2/adminfiles/flickr.py#L266-L277 | def getLocation(self):
"""
Return the latitude+longitutde of the picture.
Returns None if no location given for this pic.
"""
method = 'flickr.photos.geo.getLocation'
try:
data = _doget(method, photo_id=self.id)
except FlickrError: # Some other error m... | [
"def",
"getLocation",
"(",
"self",
")",
":",
"method",
"=",
"'flickr.photos.geo.getLocation'",
"try",
":",
"data",
"=",
"_doget",
"(",
"method",
",",
"photo_id",
"=",
"self",
".",
"id",
")",
"except",
"FlickrError",
":",
"# Some other error might have occured too!... | Return the latitude+longitutde of the picture.
Returns None if no location given for this pic. | [
"Return",
"the",
"latitude",
"+",
"longitutde",
"of",
"the",
"picture",
".",
"Returns",
"None",
"if",
"no",
"location",
"given",
"for",
"this",
"pic",
"."
] | python | train | 36.583333 |
dwavesystems/dimod | dimod/binary_quadratic_model.py | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/binary_quadratic_model.py#L2356-L2408 | def from_numpy_vectors(cls, linear, quadratic, offset, vartype, variable_order=None):
"""Create a binary quadratic model from vectors.
Args:
linear (array_like):
A 1D array-like iterable of linear biases.
quadratic (tuple[array_like, array_like, array_like]):
... | [
"def",
"from_numpy_vectors",
"(",
"cls",
",",
"linear",
",",
"quadratic",
",",
"offset",
",",
"vartype",
",",
"variable_order",
"=",
"None",
")",
":",
"try",
":",
"heads",
",",
"tails",
",",
"values",
"=",
"quadratic",
"except",
"ValueError",
":",
"raise",... | Create a binary quadratic model from vectors.
Args:
linear (array_like):
A 1D array-like iterable of linear biases.
quadratic (tuple[array_like, array_like, array_like]):
A 3-tuple of 1D array_like vectors of the form (row, col, bias).
offse... | [
"Create",
"a",
"binary",
"quadratic",
"model",
"from",
"vectors",
"."
] | python | train | 37.622642 |
psd-tools/psd-tools | src/psd_tools/api/layers.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L259-L267 | def mask(self):
"""
Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None`
"""
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | [
"def",
"mask",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_mask\"",
")",
":",
"self",
".",
"_mask",
"=",
"Mask",
"(",
"self",
")",
"if",
"self",
".",
"has_mask",
"(",
")",
"else",
"None",
"return",
"self",
".",
"_mask"
] | Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None` | [
"Returns",
"mask",
"associated",
"with",
"this",
"layer",
"."
] | python | train | 30.555556 |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L69-L76 | def create_node(self, network, participant):
"""Make a new node for participants."""
if network.role == "practice" or network.role == "catch":
return RogersAgentFounder(network=network, participant=participant)
elif network.size(type=Agent) < network.generation_size:
retu... | [
"def",
"create_node",
"(",
"self",
",",
"network",
",",
"participant",
")",
":",
"if",
"network",
".",
"role",
"==",
"\"practice\"",
"or",
"network",
".",
"role",
"==",
"\"catch\"",
":",
"return",
"RogersAgentFounder",
"(",
"network",
"=",
"network",
",",
... | Make a new node for participants. | [
"Make",
"a",
"new",
"node",
"for",
"participants",
"."
] | python | train | 57.875 |
mishbahr/django-usersettings2 | usersettings/admin.py | https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/admin.py#L84-L126 | def select_site_view(self, request, form_url=''):
"""
Display a choice form to select which site to add settings.
"""
if not self.has_add_permission(request):
raise PermissionDenied
extra_qs = ''
if request.META['QUERY_STRING']:
extra_qs = '&' + r... | [
"def",
"select_site_view",
"(",
"self",
",",
"request",
",",
"form_url",
"=",
"''",
")",
":",
"if",
"not",
"self",
".",
"has_add_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"extra_qs",
"=",
"''",
"if",
"request",
".",
"META",
"[",
... | Display a choice form to select which site to add settings. | [
"Display",
"a",
"choice",
"form",
"to",
"select",
"which",
"site",
"to",
"add",
"settings",
"."
] | python | train | 34.209302 |
OpenKMIP/PyKMIP | kmip/services/server/monitor.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/services/server/monitor.py#L25-L30 | def get_json_files(p):
"""
Scan the provided policy directory for all JSON policy files.
"""
f = [os.path.join(p, x) for x in os.listdir(p) if x.endswith(".json")]
return sorted(f) | [
"def",
"get_json_files",
"(",
"p",
")",
":",
"f",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"p",
")",
"if",
"x",
".",
"endswith",
"(",
"\".json\"",
")",
"]",
"return",
"sor... | Scan the provided policy directory for all JSON policy files. | [
"Scan",
"the",
"provided",
"policy",
"directory",
"for",
"all",
"JSON",
"policy",
"files",
"."
] | python | test | 32.5 |
softlayer/softlayer-python | SoftLayer/managers/block.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/block.py#L528-L538 | def failover_to_replicant(self, volume_id, replicant_id, immediate=False):
"""Failover to a volume replicant.
:param integer volume_id: The id of the volume
:param integer replicant_id: ID of replicant to failover to
:param boolean immediate: Flag indicating if failover is immediate
... | [
"def",
"failover_to_replicant",
"(",
"self",
",",
"volume_id",
",",
"replicant_id",
",",
"immediate",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Network_Storage'",
",",
"'failoverToReplicant'",
",",
"replicant_id",
",",
"immedia... | Failover to a volume replicant.
:param integer volume_id: The id of the volume
:param integer replicant_id: ID of replicant to failover to
:param boolean immediate: Flag indicating if failover is immediate
:return: Returns whether failover was successful or not | [
"Failover",
"to",
"a",
"volume",
"replicant",
"."
] | python | train | 48 |
apache/incubator-heron | heron/tools/tracker/src/python/handlers/basehandler.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/handlers/basehandler.py#L129-L138 | def get_argument_role(self):
"""
Helper function to get request argument.
Raises exception if argument is missing.
Returns the role argument.
"""
try:
return self.get_argument(constants.PARAM_ROLE, default=None)
except tornado.web.MissingArgumentError as e:
raise Exception(e.log_... | [
"def",
"get_argument_role",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"get_argument",
"(",
"constants",
".",
"PARAM_ROLE",
",",
"default",
"=",
"None",
")",
"except",
"tornado",
".",
"web",
".",
"MissingArgumentError",
"as",
"e",
":",
"rais... | Helper function to get request argument.
Raises exception if argument is missing.
Returns the role argument. | [
"Helper",
"function",
"to",
"get",
"request",
"argument",
".",
"Raises",
"exception",
"if",
"argument",
"is",
"missing",
".",
"Returns",
"the",
"role",
"argument",
"."
] | python | valid | 31.9 |
dereneaton/ipyrad | ipyrad/analysis/structure.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/structure.py#L359-L399 | def get_clumpp_table(self, kvalues, max_var_multiple=0, quiet=False):
"""
Returns a dictionary of results tables for making structure barplots.
This calls the same functions used in get_evanno_table() to call
CLUMPP to permute replicates.
Parameters:
-----------
... | [
"def",
"get_clumpp_table",
"(",
"self",
",",
"kvalues",
",",
"max_var_multiple",
"=",
"0",
",",
"quiet",
"=",
"False",
")",
":",
"## do not allow bad vals",
"if",
"max_var_multiple",
":",
"if",
"max_var_multiple",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'m... | Returns a dictionary of results tables for making structure barplots.
This calls the same functions used in get_evanno_table() to call
CLUMPP to permute replicates.
Parameters:
-----------
kvalues : list or int
A kvalue or list of kvalues to run CLUMPP on and return... | [
"Returns",
"a",
"dictionary",
"of",
"results",
"tables",
"for",
"making",
"structure",
"barplots",
".",
"This",
"calls",
"the",
"same",
"functions",
"used",
"in",
"get_evanno_table",
"()",
"to",
"call",
"CLUMPP",
"to",
"permute",
"replicates",
"."
] | python | valid | 42.390244 |
gwpy/gwpy | gwpy/astro/range.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/astro/range.py#L104-L188 | def inspiral_range(psd, snr=8, mass1=1.4, mass2=1.4, fmin=None, fmax=None,
horizon=False):
"""Calculate the inspiral sensitive distance from a GW strain PSD
The method returns the distance (in megaparsecs) to which an compact
binary inspiral with the given component masses would be detec... | [
"def",
"inspiral_range",
"(",
"psd",
",",
"snr",
"=",
"8",
",",
"mass1",
"=",
"1.4",
",",
"mass2",
"=",
"1.4",
",",
"fmin",
"=",
"None",
",",
"fmax",
"=",
"None",
",",
"horizon",
"=",
"False",
")",
":",
"mass1",
"=",
"units",
".",
"Quantity",
"("... | Calculate the inspiral sensitive distance from a GW strain PSD
The method returns the distance (in megaparsecs) to which an compact
binary inspiral with the given component masses would be detectable
given the instrumental PSD. The calculation is as defined in:
https://dcc.ligo.org/LIGO-T030276/public... | [
"Calculate",
"the",
"inspiral",
"sensitive",
"distance",
"from",
"a",
"GW",
"strain",
"PSD"
] | python | train | 34.388235 |
kubernetes-client/python | kubernetes/client/apis/batch_v2alpha1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/batch_v2alpha1_api.py#L38-L61 | def create_namespaced_cron_job(self, namespace, body, **kwargs):
"""
create a CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_cron_job(namespace, body, async_req=T... | [
"def",
"create_namespaced_cron_job",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
"."... | create a CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_cron_job(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ... | [
"create",
"a",
"CronJob",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api",
".",
"create_nam... | python | train | 66.25 |
numenta/nupic | src/nupic/encoders/delta.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/delta.py#L102-L116 | def topDownCompute(self, encoded):
"""[ScalarEncoder class method override]"""
#Decode to delta scalar
if self._prevAbsolute==None or self._prevDelta==None:
return [EncoderResult(value=0, scalar=0,
encoding=numpy.zeros(self.n))]
ret = self._adaptiveScalarEnc.topDownCo... | [
"def",
"topDownCompute",
"(",
"self",
",",
"encoded",
")",
":",
"#Decode to delta scalar",
"if",
"self",
".",
"_prevAbsolute",
"==",
"None",
"or",
"self",
".",
"_prevDelta",
"==",
"None",
":",
"return",
"[",
"EncoderResult",
"(",
"value",
"=",
"0",
",",
"s... | [ScalarEncoder class method override] | [
"[",
"ScalarEncoder",
"class",
"method",
"override",
"]"
] | python | valid | 42.466667 |
lago-project/lago | lago/log_utils.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L614-L640 | def log_task(
task, logger=logging, level='info', propagate_fail=True, uuid=None
):
"""
Parameterized decorator to wrap a function in a log task
Example:
>>> @log_task('mytask')
... def do_something():
... pass
"""
def decorator(func):
@wraps(func)
d... | [
"def",
"log_task",
"(",
"task",
",",
"logger",
"=",
"logging",
",",
"level",
"=",
"'info'",
",",
"propagate_fail",
"=",
"True",
",",
"uuid",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"w... | Parameterized decorator to wrap a function in a log task
Example:
>>> @log_task('mytask')
... def do_something():
... pass | [
"Parameterized",
"decorator",
"to",
"wrap",
"a",
"function",
"in",
"a",
"log",
"task"
] | python | train | 22.555556 |
glitchassassin/lackey | lackey/RegionMatching.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1303-L1306 | def rightAt(self, offset=0):
""" Returns point in the center of the region's right side (offset to the right
by ``offset``) """
return Location(self.getX() + self.getW() + offset, self.getY() + (self.getH() / 2)) | [
"def",
"rightAt",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"return",
"Location",
"(",
"self",
".",
"getX",
"(",
")",
"+",
"self",
".",
"getW",
"(",
")",
"+",
"offset",
",",
"self",
".",
"getY",
"(",
")",
"+",
"(",
"self",
".",
"getH",
... | Returns point in the center of the region's right side (offset to the right
by ``offset``) | [
"Returns",
"point",
"in",
"the",
"center",
"of",
"the",
"region",
"s",
"right",
"side",
"(",
"offset",
"to",
"the",
"right",
"by",
"offset",
")"
] | python | train | 58.25 |
riptano/ccm | ccmlib/remote.py | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L47-L104 | def execute_ccm_remotely(remote_options, ccm_args):
"""
Execute CCM operation(s) remotely
:return A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script... | [
"def",
"execute_ccm_remotely",
"(",
"remote_options",
",",
"ccm_args",
")",
":",
"if",
"not",
"PARAMIKO_IS_AVAILABLE",
":",
"logging",
".",
"warn",
"(",
"\"Paramiko is not Availble: Skipping remote execution of CCM command\"",
")",
"return",
"None",
",",
"None",
"# Create... | Execute CCM operation(s) remotely
:return A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script
:raises Exception if invalid options are passed for `--dse-... | [
"Execute",
"CCM",
"operation",
"(",
"s",
")",
"remotely"
] | python | train | 46.448276 |
solocompt/plugs-core | plugs_core/mixins.py | https://github.com/solocompt/plugs-core/blob/19fd23101fcfdabe657485f0a22e6b63e2b44f9d/plugs_core/mixins.py#L12-L17 | def save(self, *args, **kwargs):
"""
Overrides the save method
"""
self.slug = self.create_slug()
super(Slugable, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"slug",
"=",
"self",
".",
"create_slug",
"(",
")",
"super",
"(",
"Slugable",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",... | Overrides the save method | [
"Overrides",
"the",
"save",
"method"
] | python | train | 29.333333 |
saltstack/salt | salt/returners/local_cache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L469-L482 | def update_endtime(jid, time):
'''
Update (or store) the end time for a given job
Endtime is stored as a plain text string
'''
jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type'])
try:
if not os.path.exists(jid_dir):
os.makedirs(jid_dir)
with salt... | [
"def",
"update_endtime",
"(",
"jid",
",",
"time",
")",
":",
"jid_dir",
"=",
"salt",
".",
"utils",
".",
"jid",
".",
"jid_dir",
"(",
"jid",
",",
"_job_dir",
"(",
")",
",",
"__opts__",
"[",
"'hash_type'",
"]",
")",
"try",
":",
"if",
"not",
"os",
".",
... | Update (or store) the end time for a given job
Endtime is stored as a plain text string | [
"Update",
"(",
"or",
"store",
")",
"the",
"end",
"time",
"for",
"a",
"given",
"job"
] | python | train | 38.285714 |
Azure/blobxfer | blobxfer/operations/upload.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/upload.py#L176-L186 | def create_destination_id(client, container, name):
# type: (azure.storage.StorageClient, str, str) -> str
"""Create a unique destination id
:param azure.storage.StorageClient client: storage client
:param str container: container name
:param str name: entity name
:rtype:... | [
"def",
"create_destination_id",
"(",
"client",
",",
"container",
",",
"name",
")",
":",
"# type: (azure.storage.StorageClient, str, str) -> str",
"path",
"=",
"str",
"(",
"pathlib",
".",
"PurePath",
"(",
"name",
")",
")",
"return",
"';'",
".",
"join",
"(",
"(",
... | Create a unique destination id
:param azure.storage.StorageClient client: storage client
:param str container: container name
:param str name: entity name
:rtype: str
:return: unique id for the destination | [
"Create",
"a",
"unique",
"destination",
"id",
":",
"param",
"azure",
".",
"storage",
".",
"StorageClient",
"client",
":",
"storage",
"client",
":",
"param",
"str",
"container",
":",
"container",
"name",
":",
"param",
"str",
"name",
":",
"entity",
"name",
"... | python | train | 44 |
Nachtfeuer/pipeline | spline/tools/loc/application.py | https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/loc/application.py#L121-L167 | def run(self):
"""Processing the pipeline."""
self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
self.logger.info("Running on platform %s", platform.platform())
self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())
configuration = self.l... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Running with Python %s\"",
",",
"sys",
".",
"version",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Running on platform... | Processing the pipeline. | [
"Processing",
"the",
"pipeline",
"."
] | python | train | 52.851064 |
mitsei/dlkit | dlkit/services/assessment.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/assessment.py#L2625-L2632 | def save_item(self, item_form, *args, **kwargs):
"""Pass through to provider ItemAdminSession.update_item"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if item_form.is_for_update():
return self.update_item(item_form, *args, ... | [
"def",
"save_item",
"(",
"self",
",",
"item_form",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.ResourceAdminSession.update_resource",
"if",
"item_form",
".",
"is_for_update",
"(",
")",
":",
"return... | Pass through to provider ItemAdminSession.update_item | [
"Pass",
"through",
"to",
"provider",
"ItemAdminSession",
".",
"update_item"
] | python | train | 50 |
watson-developer-cloud/python-sdk | ibm_watson/websocket/recognize_listener.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/websocket/recognize_listener.py#L89-L97 | def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT):
"""
Send message to server.
data: message to send. If you set opcode to OPCODE_TEXT,
data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT.
"""
self.ws_client.se... | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"opcode",
"=",
"websocket",
".",
"ABNF",
".",
"OPCODE_TEXT",
")",
":",
"self",
".",
"ws_client",
".",
"send",
"(",
"data",
",",
"opcode",
")"
] | Send message to server.
data: message to send. If you set opcode to OPCODE_TEXT,
data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT. | [
"Send",
"message",
"to",
"server",
"."
] | python | train | 36.444444 |
jbloomlab/phydms | phydmslib/models.py | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L1407-L1421 | def _update_dPrxy(self):
"""Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`."""
super(ExpCM_empirical_phi_divpressure, self)._update_dPrxy()
if 'omega2' in self.freeparams:
with scipy.errstate(divide='raise', under='raise', over='raise',
in... | [
"def",
"_update_dPrxy",
"(",
"self",
")",
":",
"super",
"(",
"ExpCM_empirical_phi_divpressure",
",",
"self",
")",
".",
"_update_dPrxy",
"(",
")",
"if",
"'omega2'",
"in",
"self",
".",
"freeparams",
":",
"with",
"scipy",
".",
"errstate",
"(",
"divide",
"=",
... | Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`. | [
"Update",
"dPrxy",
"accounting",
"for",
"dependence",
"of",
"Prxy",
"on",
"omega2",
"."
] | python | train | 59.533333 |
pjuren/pyokit | src/pyokit/datastruct/intervalTree.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/intervalTree.py#L133-L162 | def intersectingPoint(self, p):
"""
given a point, get intervals in the tree that are intersected.
:param p: intersection point
:return: the list of intersected intervals
"""
# perfect match
if p == self.data.mid:
return self.data.ends
if p > self.data.mid:
# we know all in... | [
"def",
"intersectingPoint",
"(",
"self",
",",
"p",
")",
":",
"# perfect match",
"if",
"p",
"==",
"self",
".",
"data",
".",
"mid",
":",
"return",
"self",
".",
"data",
".",
"ends",
"if",
"p",
">",
"self",
".",
"data",
".",
"mid",
":",
"# we know all in... | given a point, get intervals in the tree that are intersected.
:param p: intersection point
:return: the list of intersected intervals | [
"given",
"a",
"point",
"get",
"intervals",
"in",
"the",
"tree",
"that",
"are",
"intersected",
"."
] | python | train | 36.8 |
nesaro/pydsl | pydsl/check.py | https://github.com/nesaro/pydsl/blob/00b4fffd72036b80335e1a44a888fac57917ab41/pydsl/check.py#L93-L101 | def check(self, data):
"""returns True if any match any regexp"""
if isinstance(data, Iterable):
data = "".join(str(x) for x in data)
try:
data = str(data)
except UnicodeDecodeError:
return False
return bool(data and self.__regexp.match(data)) | [
"def",
"check",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"Iterable",
")",
":",
"data",
"=",
"\"\"",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"data",
")",
"try",
":",
"data",
"=",
"str",
"(",
"... | returns True if any match any regexp | [
"returns",
"True",
"if",
"any",
"match",
"any",
"regexp"
] | python | train | 34.555556 |
sdcooke/django_bundles | django_bundles/core.py | https://github.com/sdcooke/django_bundles/blob/2810fc455ec7391283792c1f108f4e8340f5d12f/django_bundles/core.py#L109-L115 | def get_url(self, version=None):
"""
Return the filename of the bundled bundle
"""
if self.fixed_bundle_url:
return self.fixed_bundle_url
return '%s.%s.%s' % (os.path.join(self.bundle_url_root, self.bundle_filename), version or self.get_version(), self.bundle_type) | [
"def",
"get_url",
"(",
"self",
",",
"version",
"=",
"None",
")",
":",
"if",
"self",
".",
"fixed_bundle_url",
":",
"return",
"self",
".",
"fixed_bundle_url",
"return",
"'%s.%s.%s'",
"%",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"bundle_url_r... | Return the filename of the bundled bundle | [
"Return",
"the",
"filename",
"of",
"the",
"bundled",
"bundle"
] | python | train | 44.428571 |
mikedh/trimesh | trimesh/viewer/trackball.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/viewer/trackball.py#L186-L218 | def scroll(self, clicks):
"""Zoom using a mouse scroll wheel motion.
Parameters
----------
clicks : int
The number of clicks. Positive numbers indicate forward wheel
movement.
"""
target = self._target
ratio = 0.90
mult = 1.0
... | [
"def",
"scroll",
"(",
"self",
",",
"clicks",
")",
":",
"target",
"=",
"self",
".",
"_target",
"ratio",
"=",
"0.90",
"mult",
"=",
"1.0",
"if",
"clicks",
">",
"0",
":",
"mult",
"=",
"ratio",
"**",
"clicks",
"elif",
"clicks",
"<",
"0",
":",
"mult",
... | Zoom using a mouse scroll wheel motion.
Parameters
----------
clicks : int
The number of clicks. Positive numbers indicate forward wheel
movement. | [
"Zoom",
"using",
"a",
"mouse",
"scroll",
"wheel",
"motion",
"."
] | python | train | 30.30303 |
SeattleTestbed/seash | modules/clearinghouse/command_callbacks.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/modules/clearinghouse/command_callbacks.py#L196-L256 | def _update_targets(vesseldicts, environment_dict):
"""
<Purpose>
Connects to the nodes in the vesseldicts and adds them to the list
of valid targets.
<Arguments>
vesseldicts:
A list of vesseldicts obtained through
SeattleClearinghouseClient calls.
<Side Effects>
All valid targ... | [
"def",
"_update_targets",
"(",
"vesseldicts",
",",
"environment_dict",
")",
":",
"# Compile a list of the nodes that we need to check",
"nodelist",
"=",
"[",
"]",
"for",
"vesseldict",
"in",
"vesseldicts",
":",
"nodeip_port",
"=",
"vesseldict",
"[",
"'node_ip'",
"]",
"... | <Purpose>
Connects to the nodes in the vesseldicts and adds them to the list
of valid targets.
<Arguments>
vesseldicts:
A list of vesseldicts obtained through
SeattleClearinghouseClient calls.
<Side Effects>
All valid targets that the user can access on the specified nodes
are ... | [
"<Purpose",
">",
"Connects",
"to",
"the",
"nodes",
"in",
"the",
"vesseldicts",
"and",
"adds",
"them",
"to",
"the",
"list",
"of",
"valid",
"targets",
"."
] | python | train | 28.278689 |
laurencium/Causalinference | causalinference/causal.py | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L118-L145 | def trim(self):
"""
Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has bee... | [
"def",
"trim",
"(",
"self",
")",
":",
"if",
"0",
"<",
"self",
".",
"cutoff",
"<=",
"0.5",
":",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"keep",
"=",
"(",
"pscore",
">=",
"self",
".",
"cutoff",
")",
"&",
"(",
"pscore",
"<=",
... | Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated. | [
"Trims",
"data",
"based",
"on",
"propensity",
"score",
"to",
"create",
"a",
"subsample",
"with",
"better",
"covariate",
"balance",
".",
"The",
"default",
"cutoff",
"value",
"is",
"set",
"to",
"0",
".",
"1",
".",
"To",
"set",
"a",
"custom",
"cutoff",
"val... | python | train | 30.214286 |
cggh/scikit-allel | allel/model/ndarray.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L714-L724 | def count_hom_ref(self, axis=None):
"""Count homozygous reference genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count.
"""
b = self.is_hom_ref()
return np.sum(b, axis=axis) | [
"def",
"count_hom_ref",
"(",
"self",
",",
"axis",
"=",
"None",
")",
":",
"b",
"=",
"self",
".",
"is_hom_ref",
"(",
")",
"return",
"np",
".",
"sum",
"(",
"b",
",",
"axis",
"=",
"axis",
")"
] | Count homozygous reference genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count. | [
"Count",
"homozygous",
"reference",
"genotypes",
"."
] | python | train | 26.636364 |
fananimi/pyzk | zk/base.py | https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L486-L501 | def get_device_name(self):
"""
return the device name
:return: str
"""
command = const.CMD_OPTIONS_RRQ
command_string = b'~DeviceName\x00'
response_size = 1024
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_resp... | [
"def",
"get_device_name",
"(",
"self",
")",
":",
"command",
"=",
"const",
".",
"CMD_OPTIONS_RRQ",
"command_string",
"=",
"b'~DeviceName\\x00'",
"response_size",
"=",
"1024",
"cmd_response",
"=",
"self",
".",
"__send_command",
"(",
"command",
",",
"command_string",
... | return the device name
:return: str | [
"return",
"the",
"device",
"name"
] | python | train | 29.0625 |
benjamin-hodgson/asynqp | src/asynqp/connection.py | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/connection.py#L50-L64 | def open_channel(self):
"""
Open a new channel on this connection.
This method is a :ref:`coroutine <coroutine>`.
:return: The new :class:`Channel` object.
"""
if self._closing:
raise ConnectionClosed("Closed by application")
if self.closed.done():
... | [
"def",
"open_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closing",
":",
"raise",
"ConnectionClosed",
"(",
"\"Closed by application\"",
")",
"if",
"self",
".",
"closed",
".",
"done",
"(",
")",
":",
"raise",
"self",
".",
"closed",
".",
"exception",... | Open a new channel on this connection.
This method is a :ref:`coroutine <coroutine>`.
:return: The new :class:`Channel` object. | [
"Open",
"a",
"new",
"channel",
"on",
"this",
"connection",
"."
] | python | train | 28.466667 |
chrismattmann/tika-python | tika/tika.py | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L552-L585 | def checkTikaServer(scheme="http", serverHost=ServerHost, port=Port, tikaServerJar=TikaServerJar, classpath=None, config_path=None):
'''
Check that tika-server is running. If not, download JAR file and start it up.
:param scheme: e.g. http or https
:param serverHost:
:param port:
:param tikaSer... | [
"def",
"checkTikaServer",
"(",
"scheme",
"=",
"\"http\"",
",",
"serverHost",
"=",
"ServerHost",
",",
"port",
"=",
"Port",
",",
"tikaServerJar",
"=",
"TikaServerJar",
",",
"classpath",
"=",
"None",
",",
"config_path",
"=",
"None",
")",
":",
"if",
"classpath",... | Check that tika-server is running. If not, download JAR file and start it up.
:param scheme: e.g. http or https
:param serverHost:
:param port:
:param tikaServerJar:
:param classpath:
:return: | [
"Check",
"that",
"tika",
"-",
"server",
"is",
"running",
".",
"If",
"not",
"download",
"JAR",
"file",
"and",
"start",
"it",
"up",
".",
":",
"param",
"scheme",
":",
"e",
".",
"g",
".",
"http",
"or",
"https",
":",
"param",
"serverHost",
":",
":",
"pa... | python | train | 40.5 |
agile-geoscience/welly | welly/curve.py | https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/curve.py#L597-L624 | def quality(self, tests, alias=None):
"""
Run a series of tests and return the corresponding results.
Args:
tests (list): a list of functions.
alias (dict): a dictionary mapping mnemonics to lists of mnemonics.
Returns:
list. The results. Stick to bo... | [
"def",
"quality",
"(",
"self",
",",
"tests",
",",
"alias",
"=",
"None",
")",
":",
"# Gather the test s.",
"# First, anything called 'all', 'All', or 'ALL'.",
"# Second, anything with the name of the curve we're in now.",
"# Third, anything that the alias list has for this curve.",
"#... | Run a series of tests and return the corresponding results.
Args:
tests (list): a list of functions.
alias (dict): a dictionary mapping mnemonics to lists of mnemonics.
Returns:
list. The results. Stick to booleans (True = pass) or ints. | [
"Run",
"a",
"series",
"of",
"tests",
"and",
"return",
"the",
"corresponding",
"results",
"."
] | python | train | 41.392857 |
tcalmant/ipopo | samples/run_remote.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L134-L151 | def discovery_redis(self):
"""
Installs the Redis discovery bundles and instantiates components
"""
# Install the bundle
self.context.install_bundle("pelix.remote.discovery.redis").start()
with use_waiting_list(self.context) as ipopo:
# Instantiate the discov... | [
"def",
"discovery_redis",
"(",
"self",
")",
":",
"# Install the bundle",
"self",
".",
"context",
".",
"install_bundle",
"(",
"\"pelix.remote.discovery.redis\"",
")",
".",
"start",
"(",
")",
"with",
"use_waiting_list",
"(",
"self",
".",
"context",
")",
"as",
"ipo... | Installs the Redis discovery bundles and instantiates components | [
"Installs",
"the",
"Redis",
"discovery",
"bundles",
"and",
"instantiates",
"components"
] | python | train | 35.444444 |
yyuu/botornado | boto/vpc/__init__.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/vpc/__init__.py#L127-L146 | def associate_route_table(self, route_table_id, subnet_id):
"""
Associates a route table with a specific subnet.
:type route_table_id: str
:param route_table_id: The ID of the route table to associate.
:type subnet_id: str
:param subnet_id: The ID of the subnet to assoc... | [
"def",
"associate_route_table",
"(",
"self",
",",
"route_table_id",
",",
"subnet_id",
")",
":",
"params",
"=",
"{",
"'RouteTableId'",
":",
"route_table_id",
",",
"'SubnetId'",
":",
"subnet_id",
"}",
"result",
"=",
"self",
".",
"get_object",
"(",
"'AssociateRoute... | Associates a route table with a specific subnet.
:type route_table_id: str
:param route_table_id: The ID of the route table to associate.
:type subnet_id: str
:param subnet_id: The ID of the subnet to associate with.
:rtype: str
:return: The ID of the association creat... | [
"Associates",
"a",
"route",
"table",
"with",
"a",
"specific",
"subnet",
"."
] | python | train | 30.7 |
OCA/odoorpc | odoorpc/models.py | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L345-L380 | def _init_values(self, context=None):
"""Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made.
"""
if context is None:
context = self.env.context
# Get basic fields (no relational ones)
... | [
"def",
"_init_values",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
".",
"env",
".",
"context",
"# Get basic fields (no relational ones)",
"basic_fields",
"=",
"[",
"]",
"for",
"field_name",
... | Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made. | [
"Retrieve",
"field",
"values",
"from",
"the",
"server",
".",
"May",
"be",
"used",
"to",
"restore",
"the",
"original",
"values",
"in",
"the",
"purpose",
"to",
"cancel",
"all",
"changes",
"made",
"."
] | python | train | 43.111111 |
spyder-ide/spyder | spyder/utils/sourcecode.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/sourcecode.py#L173-L195 | def disambiguate_fname(files_path_list, filename):
"""Get tab title without ambiguation."""
fname = os.path.basename(filename)
same_name_files = get_same_name_files(files_path_list, fname)
if len(same_name_files) > 1:
compare_path = shortest_path(same_name_files)
if compare_path ==... | [
"def",
"disambiguate_fname",
"(",
"files_path_list",
",",
"filename",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"same_name_files",
"=",
"get_same_name_files",
"(",
"files_path_list",
",",
"fname",
")",
"if",
"len",
"(",
... | Get tab title without ambiguation. | [
"Get",
"tab",
"title",
"without",
"ambiguation",
"."
] | python | train | 52.173913 |
robinagist/ezo | ezo/core/lib.py | https://github.com/robinagist/ezo/blob/fae896daa1c896c7c50f2c9cfe3f7f9cdb3fc986/ezo/core/lib.py#L41-L70 | def dial(self, target):
'''
connects to a node
:param url: string (optional) - resource in which to connect.
if not provided, will use default for the stage
:returns: provider, error
'''
if not target:
return None, "target network must be specified w... | [
"def",
"dial",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"target",
":",
"return",
"None",
",",
"\"target network must be specified with -t or --target\"",
"url",
"=",
"get_url",
"(",
"self",
".",
"config",
",",
"target",
")",
"try",
":",
"if",
"url"... | connects to a node
:param url: string (optional) - resource in which to connect.
if not provided, will use default for the stage
:returns: provider, error | [
"connects",
"to",
"a",
"node"
] | python | train | 29.4 |
tensorflow/tensorboard | tensorboard/program.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/program.py#L305-L310 | def _make_server(self):
"""Constructs the TensorBoard WSGI app and instantiates the server."""
app = application.standard_tensorboard_wsgi(self.flags,
self.plugin_loaders,
self.assets_zip_provider)
return self.se... | [
"def",
"_make_server",
"(",
"self",
")",
":",
"app",
"=",
"application",
".",
"standard_tensorboard_wsgi",
"(",
"self",
".",
"flags",
",",
"self",
".",
"plugin_loaders",
",",
"self",
".",
"assets_zip_provider",
")",
"return",
"self",
".",
"server_class",
"(",
... | Constructs the TensorBoard WSGI app and instantiates the server. | [
"Constructs",
"the",
"TensorBoard",
"WSGI",
"app",
"and",
"instantiates",
"the",
"server",
"."
] | python | train | 57 |
datascopeanalytics/traces | traces/timeseries.py | https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L840-L851 | def threshold(self, value, inclusive=False):
"""Return True if > than treshold value (or >= threshold value if
inclusive=True).
"""
if inclusive:
def function(x, y):
return True if x >= y else False
else:
def function(x, y):
... | [
"def",
"threshold",
"(",
"self",
",",
"value",
",",
"inclusive",
"=",
"False",
")",
":",
"if",
"inclusive",
":",
"def",
"function",
"(",
"x",
",",
"y",
")",
":",
"return",
"True",
"if",
"x",
">=",
"y",
"else",
"False",
"else",
":",
"def",
"function... | Return True if > than treshold value (or >= threshold value if
inclusive=True). | [
"Return",
"True",
"if",
">",
"than",
"treshold",
"value",
"(",
"or",
">",
"=",
"threshold",
"value",
"if",
"inclusive",
"=",
"True",
")",
"."
] | python | train | 32.416667 |
pvlib/pvlib-python | pvlib/pvsystem.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L2034-L2092 | def sapm_aoi_loss(aoi, module, upper=None):
"""
Calculates the SAPM angle of incidence loss coefficient, F2.
Parameters
----------
aoi : numeric
Angle of incidence in degrees. Negative input angles will return
zeros.
module : dict-like
A dict, Series, or DataFrame defin... | [
"def",
"sapm_aoi_loss",
"(",
"aoi",
",",
"module",
",",
"upper",
"=",
"None",
")",
":",
"aoi_coeff",
"=",
"[",
"module",
"[",
"'B5'",
"]",
",",
"module",
"[",
"'B4'",
"]",
",",
"module",
"[",
"'B3'",
"]",
",",
"module",
"[",
"'B2'",
"]",
",",
"mo... | Calculates the SAPM angle of incidence loss coefficient, F2.
Parameters
----------
aoi : numeric
Angle of incidence in degrees. Negative input angles will return
zeros.
module : dict-like
A dict, Series, or DataFrame defining the SAPM performance
parameters. See the :py... | [
"Calculates",
"the",
"SAPM",
"angle",
"of",
"incidence",
"loss",
"coefficient",
"F2",
"."
] | python | train | 31.20339 |
facelessuser/backrefs | backrefs/_bre_parse.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/_bre_parse.py#L1206-L1237 | def span_case(self, i, case):
"""Uppercase or lowercase the next range of characters until end marker is found."""
# A new \L, \C or \E should pop the last in the stack.
if self.span_stack:
self.span_stack.pop()
if self.single_stack:
self.single_stack.pop()
... | [
"def",
"span_case",
"(",
"self",
",",
"i",
",",
"case",
")",
":",
"# A new \\L, \\C or \\E should pop the last in the stack.",
"if",
"self",
".",
"span_stack",
":",
"self",
".",
"span_stack",
".",
"pop",
"(",
")",
"if",
"self",
".",
"single_stack",
":",
"self"... | Uppercase or lowercase the next range of characters until end marker is found. | [
"Uppercase",
"or",
"lowercase",
"the",
"next",
"range",
"of",
"characters",
"until",
"end",
"marker",
"is",
"found",
"."
] | python | train | 36.78125 |
apache/incubator-heron | heron/tools/common/src/python/access/heron_api.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/common/src/python/access/heron_api.py#L772-L799 | def fetch_max(self, cluster, metric, topology, component, instance, timerange, environ=None):
'''
:param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param environ:
:return:
'''
components = [component] if component != "*" els... | [
"def",
"fetch_max",
"(",
"self",
",",
"cluster",
",",
"metric",
",",
"topology",
",",
"component",
",",
"instance",
",",
"timerange",
",",
"environ",
"=",
"None",
")",
":",
"components",
"=",
"[",
"component",
"]",
"if",
"component",
"!=",
"\"*\"",
"else... | :param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param environ:
:return: | [
":",
"param",
"cluster",
":",
":",
"param",
"metric",
":",
":",
"param",
"topology",
":",
":",
"param",
"component",
":",
":",
"param",
"instance",
":",
":",
"param",
"timerange",
":",
":",
"param",
"environ",
":",
":",
"return",
":"
] | python | valid | 27.285714 |
FulcrumTechnologies/pyconfluence | pyconfluence/actions.py | https://github.com/FulcrumTechnologies/pyconfluence/blob/a999726dbc1cbdd3d9062234698eeae799ce84ce/pyconfluence/actions.py#L142-L148 | def get_page_name(id):
"""Return name of a page based on passed page id.
Parameters:
- id: id of a Confluence page.
"""
data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
return data["title"] | [
"def",
"get_page_name",
"(",
"id",
")",
":",
"data",
"=",
"_json",
".",
"loads",
"(",
"_api",
".",
"rest",
"(",
"\"/\"",
"+",
"str",
"(",
"id",
")",
"+",
"\"?expand=body.storage\"",
")",
")",
"return",
"data",
"[",
"\"title\"",
"]"
] | Return name of a page based on passed page id.
Parameters:
- id: id of a Confluence page. | [
"Return",
"name",
"of",
"a",
"page",
"based",
"on",
"passed",
"page",
"id",
".",
"Parameters",
":",
"-",
"id",
":",
"id",
"of",
"a",
"Confluence",
"page",
"."
] | python | train | 32.571429 |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_transformer2.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer2.py#L521-L531 | def mtf_bitransformer_tiny():
"""Small encoder-decoder model for testing."""
hparams = mtf_bitransformer_base()
hparams.batch_size = 2
hparams.mesh_shape = ""
hparams.d_model = 128
hparams.encoder_layers = ["self_att", "drd"] * 2
hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2
hparams.num_he... | [
"def",
"mtf_bitransformer_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_bitransformer_base",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"mesh_shape",
"=",
"\"\"",
"hparams",
".",
"d_model",
"=",
"128",
"hparams",
".",
"encoder_layers",
"=",... | Small encoder-decoder model for testing. | [
"Small",
"encoder",
"-",
"decoder",
"model",
"for",
"testing",
"."
] | python | train | 32.272727 |
Shizmob/pydle | pydle/features/rfc1459/client.py | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/rfc1459/client.py#L218-L227 | async def _registration_completed(self, message):
""" We're connected and registered. Receive proper nickname and emit fake NICK message. """
if not self.registered:
# Re-enable throttling.
self.registered = True
self.connection.throttle = True
target = m... | [
"async",
"def",
"_registration_completed",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"registered",
":",
"# Re-enable throttling.",
"self",
".",
"registered",
"=",
"True",
"self",
".",
"connection",
".",
"throttle",
"=",
"True",
"target",... | We're connected and registered. Receive proper nickname and emit fake NICK message. | [
"We",
"re",
"connected",
"and",
"registered",
".",
"Receive",
"proper",
"nickname",
"and",
"emit",
"fake",
"NICK",
"message",
"."
] | python | train | 45.2 |
ioos/compliance-checker | compliance_checker/cfutil.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cfutil.py#L681-L694 | def get_flag_variables(ds):
'''
Returns a list of variables that are defined as flag variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
flag_variables = []
for name, ncvar in ds.variables.items():
standard_name = getattr(ncvar, 'standard_name', None)
if isinstance(... | [
"def",
"get_flag_variables",
"(",
"ds",
")",
":",
"flag_variables",
"=",
"[",
"]",
"for",
"name",
",",
"ncvar",
"in",
"ds",
".",
"variables",
".",
"items",
"(",
")",
":",
"standard_name",
"=",
"getattr",
"(",
"ncvar",
",",
"'standard_name'",
",",
"None",... | Returns a list of variables that are defined as flag variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset | [
"Returns",
"a",
"list",
"of",
"variables",
"that",
"are",
"defined",
"as",
"flag",
"variables"
] | python | train | 37.214286 |
dhermes/bezier | scripts/clean_cython.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/clean_cython.py#L17-L40 | def clean_file(c_source, virtualenv_dirname):
"""Strip trailing whitespace and clean up "local" names in C source.
These source files are autogenerated from the ``cython`` CLI.
Args:
c_source (str): Path to a ``.c`` source file.
virtualenv_dirname (str): The name of the ``virtualenv``
... | [
"def",
"clean_file",
"(",
"c_source",
",",
"virtualenv_dirname",
")",
":",
"with",
"open",
"(",
"c_source",
",",
"\"r\"",
")",
"as",
"file_obj",
":",
"contents",
"=",
"file_obj",
".",
"read",
"(",
")",
".",
"rstrip",
"(",
")",
"# Replace the path to the Cyth... | Strip trailing whitespace and clean up "local" names in C source.
These source files are autogenerated from the ``cython`` CLI.
Args:
c_source (str): Path to a ``.c`` source file.
virtualenv_dirname (str): The name of the ``virtualenv``
directory where Cython is installed (this is ... | [
"Strip",
"trailing",
"whitespace",
"and",
"clean",
"up",
"local",
"names",
"in",
"C",
"source",
"."
] | python | train | 41.166667 |
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#L4326-L4425 | def __set_buffer_watch(self, pid, address, size, action, bOneShot):
"""
Used by L{watch_buffer} and L{stalk_buffer}.
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@... | [
"def",
"__set_buffer_watch",
"(",
"self",
",",
"pid",
",",
"address",
",",
"size",
",",
"action",
",",
"bOneShot",
")",
":",
"# Check the size isn't zero or negative.",
"if",
"size",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Bad size for buffer watch: %r\"",
"... | Used by L{watch_buffer} and L{stalk_buffer}.
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@param size: Size in bytes of buffer to watch.
@type action: function
@... | [
"Used",
"by",
"L",
"{",
"watch_buffer",
"}",
"and",
"L",
"{",
"stalk_buffer",
"}",
"."
] | python | train | 35.84 |
pyfca/pyfca | pyfca/implications.py | https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L532-L539 | def LL(n):
"""constructs the LL context"""
if (n<=0):return Context('0')
else:
LL1=LL(n-1)
r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1
r2 = LL1 - LL1 - LL1
return r1 + r2 | [
"def",
"LL",
"(",
"n",
")",
":",
"if",
"(",
"n",
"<=",
"0",
")",
":",
"return",
"Context",
"(",
"'0'",
")",
"else",
":",
"LL1",
"=",
"LL",
"(",
"n",
"-",
"1",
")",
"r1",
"=",
"C1",
"(",
"3",
"**",
"(",
"n",
"-",
"1",
")",
",",
"2",
"*... | constructs the LL context | [
"constructs",
"the",
"LL",
"context"
] | python | train | 25.25 |
PyThaiNLP/pythainlp | pythainlp/ulmfit/__init__.py | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L169-L200 | def merge_wgts(em_sz, wgts, itos_pre, itos_new):
"""
:meth: `merge_wgts` insert pretrained weights and vocab into a new set of weights and vocab;
use average if vocab not in pretrained vocab
:param int em_sz: embedding size
:param wgts: torch model weights
:param list itos_pre: pretrained list o... | [
"def",
"merge_wgts",
"(",
"em_sz",
",",
"wgts",
",",
"itos_pre",
",",
"itos_new",
")",
":",
"vocab_size",
"=",
"len",
"(",
"itos_new",
")",
"enc_wgts",
"=",
"wgts",
"[",
"\"0.encoder.weight\"",
"]",
".",
"numpy",
"(",
")",
"# Average weight of encoding",
"ro... | :meth: `merge_wgts` insert pretrained weights and vocab into a new set of weights and vocab;
use average if vocab not in pretrained vocab
:param int em_sz: embedding size
:param wgts: torch model weights
:param list itos_pre: pretrained list of vocab
:param list itos_new: list of new vocab
:retu... | [
":",
"meth",
":",
"merge_wgts",
"insert",
"pretrained",
"weights",
"and",
"vocab",
"into",
"a",
"new",
"set",
"of",
"weights",
"and",
"vocab",
";",
"use",
"average",
"if",
"vocab",
"not",
"in",
"pretrained",
"vocab",
":",
"param",
"int",
"em_sz",
":",
"e... | python | train | 35.1875 |
draperjames/qtpandas | qtpandas/views/CSVDialogs.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/views/CSVDialogs.py#L464-L474 | def _resetWidgets(self):
"""Resets all widgets of this dialog to its inital state.
"""
self._filenameLineEdit.setText('')
self._encodingComboBox.setCurrentIndex(0)
self._delimiterBox.reset()
self._headerCheckBox.setChecked(False)
self._statusBar.showMessage('')
... | [
"def",
"_resetWidgets",
"(",
"self",
")",
":",
"self",
".",
"_filenameLineEdit",
".",
"setText",
"(",
"''",
")",
"self",
".",
"_encodingComboBox",
".",
"setCurrentIndex",
"(",
"0",
")",
"self",
".",
"_delimiterBox",
".",
"reset",
"(",
")",
"self",
".",
"... | Resets all widgets of this dialog to its inital state. | [
"Resets",
"all",
"widgets",
"of",
"this",
"dialog",
"to",
"its",
"inital",
"state",
"."
] | python | train | 36.454545 |
squaresLab/BugZoo | bugzoo/client/bug.py | https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/bug.py#L100-L114 | def register(self, bug: Bug) -> None:
"""
Dynamically registers a given bug with the server. Note that the
registration will not persist beyond the lifetime of the server.
(I.e., when the server is closed, the bug will be deregistered.)
Raises:
BugAlreadyExists: if t... | [
"def",
"register",
"(",
"self",
",",
"bug",
":",
"Bug",
")",
"->",
"None",
":",
"path",
"=",
"\"bugs/{}\"",
".",
"format",
"(",
"bug",
".",
"name",
")",
"payload",
"=",
"bug",
".",
"to_dict",
"(",
")",
"r",
"=",
"self",
".",
"__api",
".",
"put",
... | Dynamically registers a given bug with the server. Note that the
registration will not persist beyond the lifetime of the server.
(I.e., when the server is closed, the bug will be deregistered.)
Raises:
BugAlreadyExists: if there is already a bug registered on the
se... | [
"Dynamically",
"registers",
"a",
"given",
"bug",
"with",
"the",
"server",
".",
"Note",
"that",
"the",
"registration",
"will",
"not",
"persist",
"beyond",
"the",
"lifetime",
"of",
"the",
"server",
".",
"(",
"I",
".",
"e",
".",
"when",
"the",
"server",
"is... | python | train | 41.266667 |
flavio/scsgate | scsgate/messages.py | https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/messages.py#L252-L260 | def compose_telegram(body):
""" Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance)
"""
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) | [
"def",
"compose_telegram",
"(",
"body",
")",
":",
"msg",
"=",
"[",
"b\"A8\"",
"]",
"+",
"body",
"+",
"[",
"checksum_bytes",
"(",
"body",
")",
"]",
"+",
"[",
"b\"A3\"",
"]",
"return",
"str",
".",
"encode",
"(",
"\"\"",
".",
"join",
"(",
"[",
"x",
... | Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance) | [
"Compose",
"a",
"SCS",
"message"
] | python | train | 32.222222 |
HttpRunner/HttpRunner | httprunner/utils.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/utils.py#L527-L570 | def dump_json_file(json_data, pwd_dir_path, dump_file_name):
""" dump json data to file
"""
class PythonObjectEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(self, obj)
except TypeError:
return str(obj)
logs_... | [
"def",
"dump_json_file",
"(",
"json_data",
",",
"pwd_dir_path",
",",
"dump_file_name",
")",
":",
"class",
"PythonObjectEncoder",
"(",
"json",
".",
"JSONEncoder",
")",
":",
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"return",
"super",
... | dump json data to file | [
"dump",
"json",
"data",
"to",
"file"
] | python | train | 32.159091 |
ga4gh/ga4gh-client | ga4gh/client/client.py | https://github.com/ga4gh/ga4gh-client/blob/d23b00b89112ef0930d45ee75aa3c6de3db615c5/ga4gh/client/client.py#L507-L517 | def search_datasets(self):
"""
Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server.
"""
request = protocol.SearchDatasetsRequest()
request.page_size = pb.int(self._page_size)... | [
"def",
"search_datasets",
"(",
"self",
")",
":",
"request",
"=",
"protocol",
".",
"SearchDatasetsRequest",
"(",
")",
"request",
".",
"page_size",
"=",
"pb",
".",
"int",
"(",
"self",
".",
"_page_size",
")",
"return",
"self",
".",
"_run_search_request",
"(",
... | Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server. | [
"Returns",
"an",
"iterator",
"over",
"the",
"Datasets",
"on",
"the",
"server",
"."
] | python | train | 37.909091 |
zvoase/django-relax | relax/couchdb/__init__.py | https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/couchdb/__init__.py#L138-L163 | def ensure_specifier_exists(db_spec):
"""Make sure a DB specifier exists, creating it if necessary."""
local_match = LOCAL_RE.match(db_spec)
remote_match = REMOTE_RE.match(db_spec)
plain_match = PLAIN_RE.match(db_spec)
if local_match:
db_name = local_match.groupdict().get('database')
... | [
"def",
"ensure_specifier_exists",
"(",
"db_spec",
")",
":",
"local_match",
"=",
"LOCAL_RE",
".",
"match",
"(",
"db_spec",
")",
"remote_match",
"=",
"REMOTE_RE",
".",
"match",
"(",
"db_spec",
")",
"plain_match",
"=",
"PLAIN_RE",
".",
"match",
"(",
"db_spec",
... | Make sure a DB specifier exists, creating it if necessary. | [
"Make",
"sure",
"a",
"DB",
"specifier",
"exists",
"creating",
"it",
"if",
"necessary",
"."
] | python | valid | 37.653846 |
google/grr | grr/server/grr_response_server/aff4.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4.py#L1212-L1250 | def RecursiveMultiListChildren(self, urns, limit=None, age=NEWEST_TIME):
"""Recursively lists bunch of directories.
Args:
urns: List of urns to list children.
limit: Max number of children to list (NOTE: this is per urn).
age: The age of the items to retrieve. Should be one of ALL_TIMES,
... | [
"def",
"RecursiveMultiListChildren",
"(",
"self",
",",
"urns",
",",
"limit",
"=",
"None",
",",
"age",
"=",
"NEWEST_TIME",
")",
":",
"checked_urns",
"=",
"set",
"(",
")",
"urns_to_check",
"=",
"urns",
"while",
"True",
":",
"found_children",
"=",
"[",
"]",
... | Recursively lists bunch of directories.
Args:
urns: List of urns to list children.
limit: Max number of children to list (NOTE: this is per urn).
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Yields:
(subject<->children urns) tuples... | [
"Recursively",
"lists",
"bunch",
"of",
"directories",
"."
] | python | train | 28.538462 |
regebro/hovercraft | hovercraft/position.py | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L10-L67 | def gather_positions(tree):
"""Makes a list of positions and position commands from the tree"""
pos = {'data-x': 'r0',
'data-y': 'r0',
'data-z': 'r0',
'data-rotate-x': 'r0',
'data-rotate-y': 'r0',
'data-rotate-z': 'r0',
'data-scale': 'r0',
... | [
"def",
"gather_positions",
"(",
"tree",
")",
":",
"pos",
"=",
"{",
"'data-x'",
":",
"'r0'",
",",
"'data-y'",
":",
"'r0'",
",",
"'data-z'",
":",
"'r0'",
",",
"'data-rotate-x'",
":",
"'r0'",
",",
"'data-rotate-y'",
":",
"'r0'",
",",
"'data-rotate-z'",
":",
... | Makes a list of positions and position commands from the tree | [
"Makes",
"a",
"list",
"of",
"positions",
"and",
"position",
"commands",
"from",
"the",
"tree"
] | python | train | 35.448276 |
fhs/pyhdf | pyhdf/V.py | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/V.py#L800-L820 | def findclass(self, name):
"""Find a vgroup given its class name, returning its reference
number if found.
Args::
name class name of the vgroup to find
Returns::
vgroup reference number
An exception is raised if the vgroup is not found.
C lib... | [
"def",
"findclass",
"(",
"self",
",",
"name",
")",
":",
"refnum",
"=",
"_C",
".",
"Vfindclass",
"(",
"self",
".",
"_hdf_inst",
".",
"_id",
",",
"name",
")",
"if",
"not",
"refnum",
":",
"raise",
"HDF4Error",
"(",
"\"vgroup not found\"",
")",
"return",
"... | Find a vgroup given its class name, returning its reference
number if found.
Args::
name class name of the vgroup to find
Returns::
vgroup reference number
An exception is raised if the vgroup is not found.
C library equivalent: Vfind | [
"Find",
"a",
"vgroup",
"given",
"its",
"class",
"name",
"returning",
"its",
"reference",
"number",
"if",
"found",
"."
] | python | train | 25.095238 |
SeleniumHQ/selenium | py/selenium/webdriver/support/select.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L89-L103 | def select_by_index(self, index):
"""Select the option at the given index. This is done by examing the "index" attribute of an
element, and not merely by counting.
:Args:
- index - The option at this index will be selected
throws NoSuchElementException If there is ... | [
"def",
"select_by_index",
"(",
"self",
",",
"index",
")",
":",
"match",
"=",
"str",
"(",
"index",
")",
"for",
"opt",
"in",
"self",
".",
"options",
":",
"if",
"opt",
".",
"get_attribute",
"(",
"\"index\"",
")",
"==",
"match",
":",
"self",
".",
"_setSe... | Select the option at the given index. This is done by examing the "index" attribute of an
element, and not merely by counting.
:Args:
- index - The option at this index will be selected
throws NoSuchElementException If there is no option with specified index in SELECT | [
"Select",
"the",
"option",
"at",
"the",
"given",
"index",
".",
"This",
"is",
"done",
"by",
"examing",
"the",
"index",
"attribute",
"of",
"an",
"element",
"and",
"not",
"merely",
"by",
"counting",
"."
] | python | train | 41.466667 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L2102-L2110 | def path_is_empty(p: tcod.path.AStar) -> bool:
"""Return True if a path is empty.
Args:
p (AStar): An AStar instance.
Returns:
bool: True if a path is empty. Otherwise False.
"""
return bool(lib.TCOD_path_is_empty(p._path_c)) | [
"def",
"path_is_empty",
"(",
"p",
":",
"tcod",
".",
"path",
".",
"AStar",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"lib",
".",
"TCOD_path_is_empty",
"(",
"p",
".",
"_path_c",
")",
")"
] | Return True if a path is empty.
Args:
p (AStar): An AStar instance.
Returns:
bool: True if a path is empty. Otherwise False. | [
"Return",
"True",
"if",
"a",
"path",
"is",
"empty",
"."
] | python | train | 28.333333 |
vaexio/vaex | packages/vaex-core/vaex/functions.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/functions.py#L392-L418 | def dt_weekofyear(x):
"""Returns the week ordinal of the year.
:returns: an expression containing the week ordinal of the year, extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:3... | [
"def",
"dt_weekofyear",
"(",
"x",
")",
":",
"import",
"pandas",
"as",
"pd",
"return",
"pd",
".",
"Series",
"(",
"x",
")",
".",
"dt",
".",
"weekofyear",
".",
"values"
] | Returns the week ordinal of the year.
:returns: an expression containing the week ordinal of the year, extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
... | [
"Returns",
"the",
"week",
"ordinal",
"of",
"the",
"year",
"."
] | python | test | 27.037037 |
dade-ai/snipy | snipy/basic.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/basic.py#L66-L78 | def tuple_arg(fn):
"""
fun(1,2) -> fun((1,), (2,))로
f(1,2,3) => f((1,), (2,), (3,))
:param fn:
:return:
"""
@wraps(fn)
def wrapped(*args, **kwargs):
args = map(tuplefy, args)
return fn(*args, **kwargs)
return wrapped | [
"def",
"tuple_arg",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"map",
"(",
"tuplefy",
",",
"args",
")",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*... | fun(1,2) -> fun((1,), (2,))로
f(1,2,3) => f((1,), (2,), (3,))
:param fn:
:return: | [
"fun",
"(",
"1",
"2",
")",
"-",
">",
"fun",
"((",
"1",
")",
"(",
"2",
"))",
"로",
"f",
"(",
"1",
"2",
"3",
")",
"=",
">",
"f",
"((",
"1",
")",
"(",
"2",
")",
"(",
"3",
"))",
":",
"param",
"fn",
":",
":",
"return",
":"
] | python | valid | 19.846154 |
ethereum/eth-abi | eth_abi/codec.py | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/codec.py#L155-L179 | def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
"""
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of stri... | [
"def",
"decode_abi",
"(",
"self",
",",
"types",
":",
"Iterable",
"[",
"TypeStr",
"]",
",",
"data",
":",
"Decodable",
")",
"->",
"Tuple",
"[",
"Any",
",",
"...",
"]",
":",
"if",
"not",
"is_bytes",
"(",
"data",
")",
":",
"raise",
"TypeError",
"(",
"\... | Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string representations of the ABI types that
will be used for decoding e.g. ``('uint256', 'bytes... | [
"Decodes",
"the",
"binary",
"value",
"data",
"as",
"a",
"sequence",
"of",
"values",
"of",
"the",
"ABI",
"types",
"in",
"types",
"via",
"the",
"head",
"-",
"tail",
"mechanism",
"into",
"a",
"tuple",
"of",
"equivalent",
"python",
"values",
"."
] | python | train | 38.68 |
macbre/sql-metadata | sql_metadata.py | https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L51-L66 | def get_query_tokens(query):
"""
:type query str
:rtype: list[sqlparse.sql.Token]
"""
query = preprocess_query(query)
parsed = sqlparse.parse(query)
# handle empty queries (#12)
if not parsed:
return []
tokens = TokenList(parsed[0].tokens).flatten()
# print([(token.valu... | [
"def",
"get_query_tokens",
"(",
"query",
")",
":",
"query",
"=",
"preprocess_query",
"(",
"query",
")",
"parsed",
"=",
"sqlparse",
".",
"parse",
"(",
"query",
")",
"# handle empty queries (#12)",
"if",
"not",
"parsed",
":",
"return",
"[",
"]",
"tokens",
"=",... | :type query str
:rtype: list[sqlparse.sql.Token] | [
":",
"type",
"query",
"str",
":",
"rtype",
":",
"list",
"[",
"sqlparse",
".",
"sql",
".",
"Token",
"]"
] | python | train | 25.9375 |
adamheins/r12 | r12/shell.py | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L95-L147 | def cmdloop(self, intro=None):
''' Override the command loop to handle Ctrl-C. '''
self.preloop()
# Set up completion with readline.
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
... | [
"def",
"cmdloop",
"(",
"self",
",",
"intro",
"=",
"None",
")",
":",
"self",
".",
"preloop",
"(",
")",
"# Set up completion with readline.",
"if",
"self",
".",
"use_rawinput",
"and",
"self",
".",
"completekey",
":",
"try",
":",
"import",
"readline",
"self",
... | Override the command loop to handle Ctrl-C. | [
"Override",
"the",
"command",
"loop",
"to",
"handle",
"Ctrl",
"-",
"C",
"."
] | python | train | 37.415094 |
ThreatConnect-Inc/tcex | tcex/tcex.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L186-L194 | def _logger_api(self):
"""Add API logging handler."""
from .tcex_logger import TcExLogHandler, TcExLogFormatter
api = TcExLogHandler(self.session)
api.set_name('api')
api.setLevel(logging.DEBUG)
api.setFormatter(TcExLogFormatter())
self.log.addHandler(api) | [
"def",
"_logger_api",
"(",
"self",
")",
":",
"from",
".",
"tcex_logger",
"import",
"TcExLogHandler",
",",
"TcExLogFormatter",
"api",
"=",
"TcExLogHandler",
"(",
"self",
".",
"session",
")",
"api",
".",
"set_name",
"(",
"'api'",
")",
"api",
".",
"setLevel",
... | Add API logging handler. | [
"Add",
"API",
"logging",
"handler",
"."
] | python | train | 33.888889 |
majuss/lupupy | lupupy/devices/__init__.py | https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/__init__.py#L124-L127 | def desc(self):
"""Get a short description of the device."""
return '{0} (ID: {1}) - {2} - {3}'.format(
self.name, self.device_id, self.type, self.status) | [
"def",
"desc",
"(",
"self",
")",
":",
"return",
"'{0} (ID: {1}) - {2} - {3}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"device_id",
",",
"self",
".",
"type",
",",
"self",
".",
"status",
")"
] | Get a short description of the device. | [
"Get",
"a",
"short",
"description",
"of",
"the",
"device",
"."
] | python | train | 44.75 |
raiden-network/raiden | raiden/connection_manager.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/connection_manager.py#L288-L297 | def retry_connect(self):
"""Will be called when new channels in the token network are detected.
If the minimum number of channels was not yet established, it will try
to open new channels.
If the connection manager has no funds, this is a noop.
"""
with self.lock:
... | [
"def",
"retry_connect",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"_funds_remaining",
">",
"0",
"and",
"not",
"self",
".",
"_leaving_state",
":",
"self",
".",
"_open_channels",
"(",
")"
] | Will be called when new channels in the token network are detected.
If the minimum number of channels was not yet established, it will try
to open new channels.
If the connection manager has no funds, this is a noop. | [
"Will",
"be",
"called",
"when",
"new",
"channels",
"in",
"the",
"token",
"network",
"are",
"detected",
".",
"If",
"the",
"minimum",
"number",
"of",
"channels",
"was",
"not",
"yet",
"established",
"it",
"will",
"try",
"to",
"open",
"new",
"channels",
"."
] | python | train | 41.2 |
vinta/pangu.py | pangu.py | https://github.com/vinta/pangu.py/blob/89407cf08dedf9d895c13053dd518d11a20f6c95/pangu.py#L156-L162 | def spacing_file(path):
"""
Perform paranoid text spacing from file.
"""
# TODO: read line by line
with open(os.path.abspath(path)) as f:
return spacing_text(f.read()) | [
"def",
"spacing_file",
"(",
"path",
")",
":",
"# TODO: read line by line",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"as",
"f",
":",
"return",
"spacing_text",
"(",
"f",
".",
"read",
"(",
")",
")"
] | Perform paranoid text spacing from file. | [
"Perform",
"paranoid",
"text",
"spacing",
"from",
"file",
"."
] | python | train | 27 |
pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L2333-L2346 | def load(self, require=True, *args, **kwargs):
"""
Require packages for this EntryPoint, then resolve it.
"""
if not require or args or kwargs:
warnings.warn(
"Parameters to load are deprecated. Call .resolve and "
".require separately.",
... | [
"def",
"load",
"(",
"self",
",",
"require",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"require",
"or",
"args",
"or",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"Parameters to load are deprecated. Call .resolve and \"... | Require packages for this EntryPoint, then resolve it. | [
"Require",
"packages",
"for",
"this",
"EntryPoint",
"then",
"resolve",
"it",
"."
] | python | train | 34.714286 |
SKA-ScienceDataProcessor/integration-prototype | sip/science_pipeline_workflows/receive_pss/csp_pss_sender/app/__main__.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/science_pipeline_workflows/receive_pss/csp_pss_sender/app/__main__.py#L46-L63 | def main():
"""Main script function"""
# Create simulation object, and start streaming SPEAD heaps
sender = PulsarSender()
# Parse command line arguments
args = parse_command_line()
# Initialise logging.
_log = _init_log(level=logging.DEBUG if args.verbose else logging.INFO)
# Load co... | [
"def",
"main",
"(",
")",
":",
"# Create simulation object, and start streaming SPEAD heaps",
"sender",
"=",
"PulsarSender",
"(",
")",
"# Parse command line arguments",
"args",
"=",
"parse_command_line",
"(",
")",
"# Initialise logging.",
"_log",
"=",
"_init_log",
"(",
"le... | Main script function | [
"Main",
"script",
"function"
] | python | train | 34.055556 |
Autodesk/aomi | aomi/validation.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L14-L23 | def find_file(name, directory):
"""Searches up from a directory looking for a file"""
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exi... | [
"def",
"find_file",
"(",
"name",
",",
"directory",
")",
":",
"path_bits",
"=",
"directory",
".",
"split",
"(",
"os",
".",
"sep",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"path_bits",
")",
"-",
"1",
")",
":",
"check_path",
"=",
"... | Searches up from a directory looking for a file | [
"Searches",
"up",
"from",
"a",
"directory",
"looking",
"for",
"a",
"file"
] | python | train | 38.3 |
datamachine/twx | twx/twx.py | https://github.com/datamachine/twx/blob/d9633f12f3647b1e54ba87b70b39df3b7e02b4eb/twx/twx.py#L638-L656 | def send_document(self, peer: Peer, document: str, reply: int=None, on_success: callable=None,
reply_markup: botapi.ReplyMarkup=None):
"""
Send document to peer.
:param peer: Peer to send message to.
:param document: File path to document to send.
:param rep... | [
"def",
"send_document",
"(",
"self",
",",
"peer",
":",
"Peer",
",",
"document",
":",
"str",
",",
"reply",
":",
"int",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"botapi",
".",
"ReplyMarkup",
"=",
"None",
")"... | Send document to peer.
:param peer: Peer to send message to.
:param document: File path to document to send.
:param reply: Message object or message_id to reply to.
:param on_success: Callback to call when call is complete.
:type reply: int or Message | [
"Send",
"document",
"to",
"peer",
".",
":",
"param",
"peer",
":",
"Peer",
"to",
"send",
"message",
"to",
".",
":",
"param",
"document",
":",
"File",
"path",
"to",
"document",
"to",
"send",
".",
":",
"param",
"reply",
":",
"Message",
"object",
"or",
"... | python | train | 48.736842 |
nchopin/particles | particles/smoothing.py | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smoothing.py#L319-L335 | def _twofilter_smoothing_ON2(self, t, ti, info, phi, lwinfo):
"""O(N^2) version of two-filter smoothing.
This method should not be called directly, see twofilter_smoothing.
"""
sp, sw = 0., 0.
upb = lwinfo.max() + self.wgt[t].lw.max()
if hasattr(self.model, 'upper_bound... | [
"def",
"_twofilter_smoothing_ON2",
"(",
"self",
",",
"t",
",",
"ti",
",",
"info",
",",
"phi",
",",
"lwinfo",
")",
":",
"sp",
",",
"sw",
"=",
"0.",
",",
"0.",
"upb",
"=",
"lwinfo",
".",
"max",
"(",
")",
"+",
"self",
".",
"wgt",
"[",
"t",
"]",
... | O(N^2) version of two-filter smoothing.
This method should not be called directly, see twofilter_smoothing. | [
"O",
"(",
"N^2",
")",
"version",
"of",
"two",
"-",
"filter",
"smoothing",
"."
] | python | train | 46 |
rigetti/quantumflow | quantumflow/measures.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L188-L194 | def gates_close(gate0: Gate, gate1: Gate,
tolerance: float = TOLERANCE) -> bool:
"""Returns: True if gates are almost identical.
Closeness is measured with the gate angle.
"""
return vectors_close(gate0.vec, gate1.vec, tolerance) | [
"def",
"gates_close",
"(",
"gate0",
":",
"Gate",
",",
"gate1",
":",
"Gate",
",",
"tolerance",
":",
"float",
"=",
"TOLERANCE",
")",
"->",
"bool",
":",
"return",
"vectors_close",
"(",
"gate0",
".",
"vec",
",",
"gate1",
".",
"vec",
",",
"tolerance",
")"
] | Returns: True if gates are almost identical.
Closeness is measured with the gate angle. | [
"Returns",
":",
"True",
"if",
"gates",
"are",
"almost",
"identical",
"."
] | python | train | 36.571429 |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L344-L367 | def channelRelease(BaRange_presence=0, GroupChannelDescription_presence=0,
GroupCipherKeyNumber_presence=0, GprsResumption_presence=0,
BaListPref_presence=0):
"""CHANNEL RELEASE Section 9.1.7"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0xD) # 00001101
c = RrCause(... | [
"def",
"channelRelease",
"(",
"BaRange_presence",
"=",
"0",
",",
"GroupChannelDescription_presence",
"=",
"0",
",",
"GroupCipherKeyNumber_presence",
"=",
"0",
",",
"GprsResumption_presence",
"=",
"0",
",",
"BaListPref_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd... | CHANNEL RELEASE Section 9.1.7 | [
"CHANNEL",
"RELEASE",
"Section",
"9",
".",
"1",
".",
"7"
] | python | train | 39.458333 |
scanny/python-pptx | pptx/oxml/slide.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/oxml/slide.py#L184-L193 | def _add_childTnLst(self):
"""Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Any existing `p:timing` child element is ruthlessly removed and
replaced.
"""
self.remove(self.get_or_add_timing())
timing = parse_xml(self._childTnLst_timing_xml())
self.... | [
"def",
"_add_childTnLst",
"(",
"self",
")",
":",
"self",
".",
"remove",
"(",
"self",
".",
"get_or_add_timing",
"(",
")",
")",
"timing",
"=",
"parse_xml",
"(",
"self",
".",
"_childTnLst_timing_xml",
"(",
")",
")",
"self",
".",
"_insert_timing",
"(",
"timing... | Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Any existing `p:timing` child element is ruthlessly removed and
replaced. | [
"Add",
".",
"/",
"p",
":",
"timing",
"/",
"p",
":",
"tnLst",
"/",
"p",
":",
"par",
"/",
"p",
":",
"cTn",
"/",
"p",
":",
"childTnLst",
"descendant",
"."
] | python | train | 40.2 |
Rapptz/discord.py | discord/ext/commands/core.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L488-L504 | def clean_params(self):
"""Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
result.popitem(last=False)
... | [
"def",
"clean_params",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"params",
".",
"copy",
"(",
")",
"if",
"self",
".",
"cog",
"is",
"not",
"None",
":",
"# first parameter is self",
"result",
".",
"popitem",
"(",
"last",
"=",
"False",
")",
"try",... | Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature. | [
"Retrieves",
"the",
"parameter",
"OrderedDict",
"without",
"the",
"context",
"or",
"self",
"parameters",
"."
] | python | train | 30.117647 |
bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L130-L138 | def _get_full_paths(fastq_dir, config, config_file):
"""Retrieve full paths for directories in the case of relative locations.
"""
if fastq_dir:
fastq_dir = utils.add_full_path(fastq_dir)
config_dir = utils.add_full_path(os.path.dirname(config_file))
galaxy_config_file = utils.add_full_path(... | [
"def",
"_get_full_paths",
"(",
"fastq_dir",
",",
"config",
",",
"config_file",
")",
":",
"if",
"fastq_dir",
":",
"fastq_dir",
"=",
"utils",
".",
"add_full_path",
"(",
"fastq_dir",
")",
"config_dir",
"=",
"utils",
".",
"add_full_path",
"(",
"os",
".",
"path",... | Retrieve full paths for directories in the case of relative locations. | [
"Retrieve",
"full",
"paths",
"for",
"directories",
"in",
"the",
"case",
"of",
"relative",
"locations",
"."
] | python | train | 54.222222 |
django-extensions/django-extensions | django_extensions/db/fields/encrypted.py | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/db/fields/encrypted.py#L46-L69 | def get_crypt_class(self):
"""
Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to ... | [
"def",
"get_crypt_class",
"(",
"self",
")",
":",
"crypt_type",
"=",
"getattr",
"(",
"settings",
",",
"'ENCRYPTED_FIELD_MODE'",
",",
"'DECRYPT_AND_ENCRYPT'",
")",
"if",
"crypt_type",
"==",
"'ENCRYPT'",
":",
"crypt_class_name",
"=",
"'Encrypter'",
"elif",
"crypt_type"... | Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to Keyczar.
Returns:
keyczar.... | [
"Get",
"the",
"Keyczar",
"class",
"to",
"use",
"."
] | python | train | 43.458333 |
NuGrid/NuGridPy | nugridpy/data_plot.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L4324-L4531 | def movie(self, cycles, plotstyle='',movname='',fps=12,**kwargs):
from matplotlib import animation
'''
Make an interactive movie in the matplotlib window for a number of
different plot types:
Plot types
----------
'iso_abund' : abundance distr... | [
"def",
"movie",
"(",
"self",
",",
"cycles",
",",
"plotstyle",
"=",
"''",
",",
"movname",
"=",
"''",
",",
"fps",
"=",
"12",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
"import",
"animation",
"modelself",
"=",
"self",
"supported_styles",
"="... | Make an interactive movie in the matplotlib window for a number of
different plot types:
Plot types
----------
'iso_abund' : abundance distribution a la se.iso_abund()
'abu_chart' : abundance chart a la se.abu_chart()
'plot' : plot any number... | [
"Make",
"an",
"interactive",
"movie",
"in",
"the",
"matplotlib",
"window",
"for",
"a",
"number",
"of",
"different",
"plot",
"types",
":"
] | python | train | 45.985577 |
erget/StereoVision | stereovision/blockmatchers.py | https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L326-L333 | def P1(self, value):
"""Set private ``_P1`` and reset ``_block_matcher``."""
if value < self.P2:
self._P1 = value
else:
raise InvalidFirstDisparityChangePenaltyError("P1 must be less "
"than P2.")
self._rep... | [
"def",
"P1",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"<",
"self",
".",
"P2",
":",
"self",
".",
"_P1",
"=",
"value",
"else",
":",
"raise",
"InvalidFirstDisparityChangePenaltyError",
"(",
"\"P1 must be less \"",
"\"than P2.\"",
")",
"self",
".",
... | Set private ``_P1`` and reset ``_block_matcher``. | [
"Set",
"private",
"_P1",
"and",
"reset",
"_block_matcher",
"."
] | python | train | 40.25 |
slightlynybbled/tk_tools | tk_tools/groups.py | https://github.com/slightlynybbled/tk_tools/blob/7c1792cad42890251a34f0617ce9b4b3e7abcf50/tk_tools/groups.py#L401-L411 | def reset(self):
"""
Clears all entries.
:return: None
"""
for i in range(len(self.values)):
self.values[i].delete(0, tk.END)
if self.defaults[i] is not None:
self.values[i].insert(0, self.defaults[i]) | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"values",
")",
")",
":",
"self",
".",
"values",
"[",
"i",
"]",
".",
"delete",
"(",
"0",
",",
"tk",
".",
"END",
")",
"if",
"self",
".",
"defaults",... | Clears all entries.
:return: None | [
"Clears",
"all",
"entries",
"."
] | python | train | 24.818182 |
softlayer/softlayer-python | SoftLayer/CLI/vpn/ipsec/detail.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/detail.py#L87-L102 | def _get_subnets_table(subnets):
"""Yields a formatted table to print subnet details.
:param List[dict] subnets: List of subnets.
:return Table: Formatted for subnet output.
"""
table = formatting.Table(['id',
'network identifier',
'cidr',... | [
"def",
"_get_subnets_table",
"(",
"subnets",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'network identifier'",
",",
"'cidr'",
",",
"'note'",
"]",
")",
"for",
"subnet",
"in",
"subnets",
":",
"table",
".",
"add_row",
"(",
"... | Yields a formatted table to print subnet details.
:param List[dict] subnets: List of subnets.
:return Table: Formatted for subnet output. | [
"Yields",
"a",
"formatted",
"table",
"to",
"print",
"subnet",
"details",
"."
] | python | train | 36.75 |
oasis-open/cti-stix-validator | stix2validator/output.py | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L191-L207 | def print_results(results):
"""Print `results` (the results of validation) to stdout.
Args:
results: A list of FileValidationResults or ObjectValidationResults
instances.
"""
if not isinstance(results, list):
results = [results]
for r in results:
try:
... | [
"def",
"print_results",
"(",
"results",
")",
":",
"if",
"not",
"isinstance",
"(",
"results",
",",
"list",
")",
":",
"results",
"=",
"[",
"results",
"]",
"for",
"r",
"in",
"results",
":",
"try",
":",
"r",
".",
"log",
"(",
")",
"except",
"AttributeErro... | Print `results` (the results of validation) to stdout.
Args:
results: A list of FileValidationResults or ObjectValidationResults
instances. | [
"Print",
"results",
"(",
"the",
"results",
"of",
"validation",
")",
"to",
"stdout",
"."
] | python | train | 30 |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/drivers/dokan/solrclient.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/dokan/solrclient.py#L283-L314 | def coerceType(self, ftype, value):
"""Returns unicode(value) after trying to coerce it into the SOLR field type.
@param ftype(string) The SOLR field type for the value
@param value(any) The value that is to be represented as Unicode text.
"""
if value is None:
retu... | [
"def",
"coerceType",
"(",
"self",
",",
"ftype",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"ftype",
"==",
"'string'",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"ftype",
"==",
"'text'",
":",
"return",
"str... | Returns unicode(value) after trying to coerce it into the SOLR field type.
@param ftype(string) The SOLR field type for the value
@param value(any) The value that is to be represented as Unicode text. | [
"Returns",
"unicode",
"(",
"value",
")",
"after",
"trying",
"to",
"coerce",
"it",
"into",
"the",
"SOLR",
"field",
"type",
"."
] | python | train | 31 |
carljm/django-icanhaz | icanhaz/templatetags/icanhaz.py | https://github.com/carljm/django-icanhaz/blob/57939325850058959c1ee8dce13e2b8c28156532/icanhaz/templatetags/icanhaz.py#L40-L50 | def icanhaz(parser, token):
"""
Finds the ICanHaz template for the given name and renders it surrounded by
the requisite ICanHaz <script> tags.
"""
bits = token.contents.split()
if len(bits) not in [2, 3]:
raise template.TemplateSyntaxError(
"'icanhaz' tag takes one argument... | [
"def",
"icanhaz",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"not",
"in",
"[",
"2",
",",
"3",
"]",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
... | Finds the ICanHaz template for the given name and renders it surrounded by
the requisite ICanHaz <script> tags. | [
"Finds",
"the",
"ICanHaz",
"template",
"for",
"the",
"given",
"name",
"and",
"renders",
"it",
"surrounded",
"by",
"the",
"requisite",
"ICanHaz",
"<script",
">",
"tags",
"."
] | python | train | 33.909091 |
CybOXProject/mixbox | mixbox/xml.py | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/xml.py#L114-L133 | def strip_cdata(text):
"""Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped str... | [
"def",
"strip_cdata",
"(",
"text",
")",
":",
"if",
"not",
"is_cdata",
"(",
"text",
")",
":",
"return",
"text",
"xml",
"=",
"\"<e>{0}</e>\"",
".",
"format",
"(",
"text",
")",
"node",
"=",
"etree",
".",
"fromstring",
"(",
"xml",
")",
"return",
"node",
... | Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped string with CDATA block qualifier... | [
"Removes",
"all",
"CDATA",
"blocks",
"from",
"text",
"if",
"it",
"contains",
"them",
"."
] | python | train | 24.4 |
ph4r05/monero-serialize | monero_serialize/xmrrpc.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrrpc.py#L961-L972 | async def uint(self, elem, elem_type, params=None):
"""
Integer types
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
return IntegerModel(elem, elem_type.WIDTH) if self.modelize else elem
else:
re... | [
"async",
"def",
"uint",
"(",
"self",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"return",
"IntegerModel",
"(",
"elem",
",",
"elem_type",
".",
"WIDTH",
")",
"if",
"self",
".",
"modelize",
"e... | Integer types
:param elem:
:param elem_type:
:param params:
:return: | [
"Integer",
"types",
":",
"param",
"elem",
":",
":",
"param",
"elem_type",
":",
":",
"param",
"params",
":",
":",
"return",
":"
] | python | train | 30 |
iotile/coretools | iotilecore/iotile/core/dev/semver.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L358-L368 | def filter(self, versions, key=lambda x: x):
"""Filter all of the versions in an iterable that match this version range
Args:
versions (iterable): An iterable of SemanticVersion objects
Returns:
list: A list of the SemanticVersion objects that matched this range
... | [
"def",
"filter",
"(",
"self",
",",
"versions",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"versions",
"if",
"self",
".",
"check",
"(",
"key",
"(",
"x",
")",
")",
"]"
] | Filter all of the versions in an iterable that match this version range
Args:
versions (iterable): An iterable of SemanticVersion objects
Returns:
list: A list of the SemanticVersion objects that matched this range | [
"Filter",
"all",
"of",
"the",
"versions",
"in",
"an",
"iterable",
"that",
"match",
"this",
"version",
"range"
] | python | train | 34 |
seequent/properties | properties/extras/singleton.py | https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/singleton.py#L64-L97 | def deserialize(cls, value, trusted=False, strict=False,
assert_valid=False, **kwargs):
"""Create a Singleton instance from a serialized dictionary.
This behaves identically to HasProperties.deserialize, except if
the singleton is already found in the singleton registry the ... | [
"def",
"deserialize",
"(",
"cls",
",",
"value",
",",
"trusted",
"=",
"False",
",",
"strict",
"=",
"False",
",",
"assert_valid",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
... | Create a Singleton instance from a serialized dictionary.
This behaves identically to HasProperties.deserialize, except if
the singleton is already found in the singleton registry the existing
value is used.
.. note::
If property values differ from the existing singleton a... | [
"Create",
"a",
"Singleton",
"instance",
"from",
"a",
"serialized",
"dictionary",
"."
] | python | train | 37.941176 |
materialsproject/custodian | custodian/vasp/jobs.py | https://github.com/materialsproject/custodian/blob/b33b01574fc899f959acb3c495398fd3d0fc41d0/custodian/vasp/jobs.py#L771-L791 | def postprocess(self):
"""
Postprocessing includes renaming and gzipping where necessary.
"""
# Add suffix to all sub_dir/{items}
for path in self.neb_dirs:
for f in VASP_NEB_OUTPUT_SUB_FILES:
f = os.path.join(path, f)
if os.path.exists... | [
"def",
"postprocess",
"(",
"self",
")",
":",
"# Add suffix to all sub_dir/{items}",
"for",
"path",
"in",
"self",
".",
"neb_dirs",
":",
"for",
"f",
"in",
"VASP_NEB_OUTPUT_SUB_FILES",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",... | Postprocessing includes renaming and gzipping where necessary. | [
"Postprocessing",
"includes",
"renaming",
"and",
"gzipping",
"where",
"necessary",
"."
] | python | train | 43.190476 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/dhcp_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/dhcp_driver.py#L160-L183 | def recover_devices(cls):
"""Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system.
"""
if "_devices" in globals():
return
global _devices
confs_dir = os.pa... | [
"def",
"recover_devices",
"(",
"cls",
")",
":",
"if",
"\"_devices\"",
"in",
"globals",
"(",
")",
":",
"return",
"global",
"_devices",
"confs_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"cfg",
".",
"CONF",... | Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system. | [
"Track",
"devices",
"."
] | python | train | 36.916667 |
fboender/ansible-cmdb | src/ansiblecmdb/parser.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansiblecmdb/parser.py#L50-L100 | def _parse_hosts_contents(self, hosts_contents):
"""
Parse the inventory contents. This returns a list of sections found in
the inventory, which can then be used to figure out which hosts belong
to which groups and such. Each section has a name, a type ('hosts',
'children', 'vars... | [
"def",
"_parse_hosts_contents",
"(",
"self",
",",
"hosts_contents",
")",
":",
"sections",
"=",
"[",
"]",
"cur_section",
"=",
"{",
"'type'",
":",
"'hosts'",
",",
"'name'",
":",
"None",
",",
"'entries'",
":",
"[",
"]",
"}",
"for",
"line",
"in",
"hosts_cont... | Parse the inventory contents. This returns a list of sections found in
the inventory, which can then be used to figure out which hosts belong
to which groups and such. Each section has a name, a type ('hosts',
'children', 'vars') and a list of entries for that section. Entries
consist of... | [
"Parse",
"the",
"inventory",
"contents",
".",
"This",
"returns",
"a",
"list",
"of",
"sections",
"found",
"in",
"the",
"inventory",
"which",
"can",
"then",
"be",
"used",
"to",
"figure",
"out",
"which",
"hosts",
"belong",
"to",
"which",
"groups",
"and",
"suc... | python | train | 34.980392 |
saltstack/salt | salt/modules/out.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/out.py#L37-L61 | def out_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configu... | [
"def",
"out_format",
"(",
"data",
",",
"out",
"=",
"'nested'",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"return",
"salt",
".",
"output",
".",
"out_format",
"(",
"data",
",",
"ou... | Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments ... | [
"Return",
"the",
"formatted",
"outputter",
"string",
"for",
"the",
"Python",
"object",
"."
] | python | train | 24.32 |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/statements/subtract_statement.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/statements/subtract_statement.py#L42-L75 | def execute(self, sensor_graph, scope_stack):
"""Execute this statement on the sensor_graph given the current scope tree.
This adds a single node to the sensor graph with subtract as the function
so that the current scope's trigger stream has the subtract_stream's value
subtracted from ... | [
"def",
"execute",
"(",
"self",
",",
"sensor_graph",
",",
"scope_stack",
")",
":",
"if",
"self",
".",
"subtract_stream",
".",
"stream_type",
"!=",
"DataStream",
".",
"ConstantType",
":",
"raise",
"SensorGraphSemanticError",
"(",
"\"You can only subtract a constant valu... | Execute this statement on the sensor_graph given the current scope tree.
This adds a single node to the sensor graph with subtract as the function
so that the current scope's trigger stream has the subtract_stream's value
subtracted from it.
Args:
sensor_graph (SensorGraph)... | [
"Execute",
"this",
"statement",
"on",
"the",
"sensor_graph",
"given",
"the",
"current",
"scope",
"tree",
"."
] | python | train | 46.294118 |
codenerix/django-codenerix | codenerix/authbackend.py | https://github.com/codenerix/django-codenerix/blob/1f5527b352141caaee902b37b2648791a06bd57d/codenerix/authbackend.py#L493-L527 | def authenticate(self, *args, **kwargs):
'''
Authenticate the user agains LDAP
'''
# Get config
username = kwargs.get("username", None)
password = kwargs.get("password", None)
# Check user in Active Directory (authorization == None if can not connect to Active D... | [
"def",
"authenticate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get config",
"username",
"=",
"kwargs",
".",
"get",
"(",
"\"username\"",
",",
"None",
")",
"password",
"=",
"kwargs",
".",
"get",
"(",
"\"password\"",
",",
"Non... | Authenticate the user agains LDAP | [
"Authenticate",
"the",
"user",
"agains",
"LDAP"
] | python | train | 36.285714 |
constverum/ProxyBroker | proxybroker/api.py | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L202-L288 | def serve(self, host='127.0.0.1', port=8888, limit=100, **kwargs):
"""Start a local proxy server.
The server distributes incoming requests to a pool of found proxies.
When the server receives an incoming request, it chooses the optimal
proxy (based on the percentage of errors and avera... | [
"def",
"serve",
"(",
"self",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8888",
",",
"limit",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"limit",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'In serve mode value of the limit cannot be les... | Start a local proxy server.
The server distributes incoming requests to a pool of found proxies.
When the server receives an incoming request, it chooses the optimal
proxy (based on the percentage of errors and average response time)
and passes to it the incoming request.
In a... | [
"Start",
"a",
"local",
"proxy",
"server",
"."
] | python | train | 47.712644 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.