repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
BernardFW/bernard | src/bernard/platforms/facebook/platform.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L472-L482 | async def _deferred_init(self):
"""
Run those things in a sepearate tasks as they are not required for the
bot to work and they take a lot of time to run.
"""
await self._check_subscriptions()
await self._set_whitelist()
await self._set_get_started()
awai... | [
"async",
"def",
"_deferred_init",
"(",
"self",
")",
":",
"await",
"self",
".",
"_check_subscriptions",
"(",
")",
"await",
"self",
".",
"_set_whitelist",
"(",
")",
"await",
"self",
".",
"_set_get_started",
"(",
")",
"await",
"self",
".",
"_set_greeting_text",
... | Run those things in a sepearate tasks as they are not required for the
bot to work and they take a lot of time to run. | [
"Run",
"those",
"things",
"in",
"a",
"sepearate",
"tasks",
"as",
"they",
"are",
"not",
"required",
"for",
"the",
"bot",
"to",
"work",
"and",
"they",
"take",
"a",
"lot",
"of",
"time",
"to",
"run",
"."
] | python | train |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2326-L2374 | def do_ls(self, line):
"""ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents.
"""
args = self.line_to_args(line)
if len(args.filenames) == 0:
args.filenames = ['.']
for idx, fn i... | [
"def",
"do_ls",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"line_to_args",
"(",
"line",
")",
"if",
"len",
"(",
"args",
".",
"filenames",
")",
"==",
"0",
":",
"args",
".",
"filenames",
"=",
"[",
"'.'",
"]",
"for",
"idx",
",",
... | ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents. | [
"ls",
"[",
"-",
"a",
"]",
"[",
"-",
"l",
"]",
"[",
"FILE|DIRECTORY|PATTERN",
"]",
"...",
"PATTERN",
"supports",
"*",
"?",
"[",
"seq",
"]",
"[",
"!seq",
"]",
"Unix",
"filename",
"matching"
] | python | train |
caseyjlaw/rtpipe | rtpipe/RT.py | https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/RT.py#L1039-L1048 | def correct_dm(d, dm, blrange):
""" Dedisperses data into data_resamp
Drops edges, since it assumes that data is read with overlapping chunks in time.
"""
data = numpyview(data_mem, 'complex64', datashape(d))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
bl0,bl1 = blrange
... | [
"def",
"correct_dm",
"(",
"d",
",",
"dm",
",",
"blrange",
")",
":",
"data",
"=",
"numpyview",
"(",
"data_mem",
",",
"'complex64'",
",",
"datashape",
"(",
"d",
")",
")",
"data_resamp",
"=",
"numpyview",
"(",
"data_resamp_mem",
",",
"'complex64'",
",",
"da... | Dedisperses data into data_resamp
Drops edges, since it assumes that data is read with overlapping chunks in time. | [
"Dedisperses",
"data",
"into",
"data_resamp",
"Drops",
"edges",
"since",
"it",
"assumes",
"that",
"data",
"is",
"read",
"with",
"overlapping",
"chunks",
"in",
"time",
"."
] | python | train |
smdabdoub/phylotoast | phylotoast/biom_calc.py | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/phylotoast/biom_calc.py#L95-L135 | def raw_abundance(biomf, sampleIDs=None, sample_abd=True):
"""
Calculate the total number of sequences in each OTU or SampleID.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: List
:param sampleIDs: A list of column id's from BIOM format OTU table. By default, the
... | [
"def",
"raw_abundance",
"(",
"biomf",
",",
"sampleIDs",
"=",
"None",
",",
"sample_abd",
"=",
"True",
")",
":",
"results",
"=",
"defaultdict",
"(",
"int",
")",
"if",
"sampleIDs",
"is",
"None",
":",
"sampleIDs",
"=",
"biomf",
".",
"ids",
"(",
")",
"else"... | Calculate the total number of sequences in each OTU or SampleID.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: List
:param sampleIDs: A list of column id's from BIOM format OTU table. By default, the
list has been set to None.
:type sample_abd: B... | [
"Calculate",
"the",
"total",
"number",
"of",
"sequences",
"in",
"each",
"OTU",
"or",
"SampleID",
"."
] | python | train |
brainiak/brainiak | brainiak/funcalign/rsrm.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/funcalign/rsrm.py#L304-L343 | def _init_transforms(self, subjs, voxels, features, random_state):
"""Initialize the mappings (Wi) with random orthogonal matrices.
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subjec... | [
"def",
"_init_transforms",
"(",
"self",
",",
"subjs",
",",
"voxels",
",",
"features",
",",
"random_state",
")",
":",
"# Init the Random seed generator",
"np",
".",
"random",
".",
"seed",
"(",
"self",
".",
"rand_seed",
")",
"# Draw a random W for each subject",
"W"... | Initialize the mappings (Wi) with random orthogonal matrices.
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subject.
features : int
The number of features in the model.
... | [
"Initialize",
"the",
"mappings",
"(",
"Wi",
")",
"with",
"random",
"orthogonal",
"matrices",
".",
"Parameters",
"----------"
] | python | train |
vivangkumar/uberpy | uberpy/api.py | https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/api.py#L58-L91 | def check_status(content, response):
"""
Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `response.statu... | [
"def",
"check_status",
"(",
"content",
",",
"response",
")",
":",
"if",
"response",
".",
"status",
"==",
"400",
":",
"raise",
"MalformedRequestException",
"(",
"content",
",",
"response",
")",
"if",
"response",
".",
"status",
"==",
"401",
":",
"raise",
"Un... | Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `response.status` is 401
NotFoundException if `response.status`... | [
"Check",
"the",
"response",
"that",
"is",
"returned",
"for",
"known",
"exceptions",
"and",
"errors",
".",
":",
"param",
"response",
":",
"Response",
"that",
"is",
"returned",
"from",
"the",
"call",
".",
":",
"raise",
":",
"MalformedRequestException",
"if",
"... | python | valid |
urtdevs/yaurtww | yaurtww/manifest.py | https://github.com/urtdevs/yaurtww/blob/842fbd1fb5d32c2be89df471591b70c767aebd14/yaurtww/manifest.py#L14-L23 | def _parse_version(self, line):
"""
There's a magic suffix to the release version, currently it's -03, but
it increments seemingly randomly.
"""
version_string = line.split(' ')[1]
version_list = version_string.split('.')
major_version = ''.join([version_list[0], ... | [
"def",
"_parse_version",
"(",
"self",
",",
"line",
")",
":",
"version_string",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"version_list",
"=",
"version_string",
".",
"split",
"(",
"'.'",
")",
"major_version",
"=",
"''",
".",
"join",
"("... | There's a magic suffix to the release version, currently it's -03, but
it increments seemingly randomly. | [
"There",
"s",
"a",
"magic",
"suffix",
"to",
"the",
"release",
"version",
"currently",
"it",
"s",
"-",
"03",
"but",
"it",
"increments",
"seemingly",
"randomly",
"."
] | python | train |
inveniosoftware/invenio-search | examples/app.py | https://github.com/inveniosoftware/invenio-search/blob/19c073d608d4c811f1c5aecb6622402d39715228/examples/app.py#L106-L119 | def index():
"""Query Elasticsearch using Invenio query syntax."""
page = request.values.get('page', 1, type=int)
size = request.values.get('size', 2, type=int)
search = ExampleSearch()[(page - 1) * size:page * size]
if 'q' in request.values:
search = search.query(QueryString(query=request.v... | [
"def",
"index",
"(",
")",
":",
"page",
"=",
"request",
".",
"values",
".",
"get",
"(",
"'page'",
",",
"1",
",",
"type",
"=",
"int",
")",
"size",
"=",
"request",
".",
"values",
".",
"get",
"(",
"'size'",
",",
"2",
",",
"type",
"=",
"int",
")",
... | Query Elasticsearch using Invenio query syntax. | [
"Query",
"Elasticsearch",
"using",
"Invenio",
"query",
"syntax",
"."
] | python | train |
sdispater/orator | orator/orm/scopes/soft_deleting.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/scopes/soft_deleting.py#L10-L22 | def apply(self, builder, model):
"""
Apply the scope to a given query builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:param model: The model
:type model: orator.orm.Model
"""
builder.where_null(model.get_qualified_de... | [
"def",
"apply",
"(",
"self",
",",
"builder",
",",
"model",
")",
":",
"builder",
".",
"where_null",
"(",
"model",
".",
"get_qualified_deleted_at_column",
"(",
")",
")",
"self",
".",
"extend",
"(",
"builder",
")"
] | Apply the scope to a given query builder.
:param builder: The query builder
:type builder: orator.orm.builder.Builder
:param model: The model
:type model: orator.orm.Model | [
"Apply",
"the",
"scope",
"to",
"a",
"given",
"query",
"builder",
"."
] | python | train |
adafruit/Adafruit_Python_MPR121 | Adafruit_MPR121/MPR121.py | https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L160-L165 | def filtered_data(self, pin):
"""Return filtered data register value for the provided pin (0-11).
Useful for debugging.
"""
assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)'
return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2) | [
"def",
"filtered_data",
"(",
"self",
",",
"pin",
")",
":",
"assert",
"pin",
">=",
"0",
"and",
"pin",
"<",
"12",
",",
"'pin must be between 0-11 (inclusive)'",
"return",
"self",
".",
"_i2c_retry",
"(",
"self",
".",
"_device",
".",
"readU16LE",
",",
"MPR121_FI... | Return filtered data register value for the provided pin (0-11).
Useful for debugging. | [
"Return",
"filtered",
"data",
"register",
"value",
"for",
"the",
"provided",
"pin",
"(",
"0",
"-",
"11",
")",
".",
"Useful",
"for",
"debugging",
"."
] | python | train |
blockadeio/analyst_toolbench | blockade/cli/aws_serverless.py | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L552-L589 | def remove_s3_bucket():
"""Remove the Blockade bucket."""
logger.debug("[#] Removing S3 bucket")
client = boto3.client("s3", region_name=PRIMARY_REGION)
buckets = client.list_buckets()
matches = [x for x in buckets.get('Buckets', list())
if x['Name'].startswith(S3_BUCKET_NAME)]
if... | [
"def",
"remove_s3_bucket",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"[#] Removing S3 bucket\"",
")",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
",",
"region_name",
"=",
"PRIMARY_REGION",
")",
"buckets",
"=",
"client",
".",
"list_buckets",
"(",
... | Remove the Blockade bucket. | [
"Remove",
"the",
"Blockade",
"bucket",
"."
] | python | train |
michaelpb/omnic | omnic/cli/commandparser.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/cli/commandparser.py#L16-L27 | def gen_subcommand_help(self):
'''
Generates s
'''
commands = sorted(self.subcommands.items(), key=lambda i: i[0])
return '\n'.join(
'%s %s' % (
subcommand.ljust(15),
textwrap.shorten(description, width=61),
)
fo... | [
"def",
"gen_subcommand_help",
"(",
"self",
")",
":",
"commands",
"=",
"sorted",
"(",
"self",
".",
"subcommands",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"0",
"]",
")",
"return",
"'\\n'",
".",
"join",
"(",
"'%s %s'",
"... | Generates s | [
"Generates",
"s"
] | python | train |
pypa/pipenv | pipenv/patched/notpip/_vendor/html5lib/_inputstream.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/_inputstream.py#L569-L581 | def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
i... | [
"def",
"detectEncodingMeta",
"(",
"self",
")",
":",
"buffer",
"=",
"self",
".",
"rawStream",
".",
"read",
"(",
"self",
".",
"numBytesMeta",
")",
"assert",
"isinstance",
"(",
"buffer",
",",
"bytes",
")",
"parser",
"=",
"EncodingParser",
"(",
"buffer",
")",
... | Report the encoding declared by the meta element | [
"Report",
"the",
"encoding",
"declared",
"by",
"the",
"meta",
"element"
] | python | train |
OCA/openupgradelib | openupgradelib/openupgrade.py | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L653-L670 | def rename_xmlids(cr, xmlids_spec):
"""
Rename XML IDs. Typically called in the pre script.
One usage example is when an ID changes module. In OpenERP 6 for example,
a number of res_groups IDs moved to module base from other modules (
although they were still being defined in their respective module... | [
"def",
"rename_xmlids",
"(",
"cr",
",",
"xmlids_spec",
")",
":",
"for",
"(",
"old",
",",
"new",
")",
"in",
"xmlids_spec",
":",
"if",
"'.'",
"not",
"in",
"old",
"or",
"'.'",
"not",
"in",
"new",
":",
"logger",
".",
"error",
"(",
"'Cannot rename XMLID %s ... | Rename XML IDs. Typically called in the pre script.
One usage example is when an ID changes module. In OpenERP 6 for example,
a number of res_groups IDs moved to module base from other modules (
although they were still being defined in their respective module).
:param xmlids_spec: a list of tuples (ol... | [
"Rename",
"XML",
"IDs",
".",
"Typically",
"called",
"in",
"the",
"pre",
"script",
".",
"One",
"usage",
"example",
"is",
"when",
"an",
"ID",
"changes",
"module",
".",
"In",
"OpenERP",
"6",
"for",
"example",
"a",
"number",
"of",
"res_groups",
"IDs",
"moved... | python | train |
ozak/georasters | georasters/georasters.py | https://github.com/ozak/georasters/blob/0612bd91bb2a2cb2f1d59ba89c1ff131dae27d70/georasters/georasters.py#L1110-L1190 | def distance(self, sources, destinations, x='x', y='y', isolation=True,
export_raster=False, export_shape=False, routes=False, path='./'):
"""
Compute cost distance measured from each start point to all end points.
The function returns the distances between the start point and t... | [
"def",
"distance",
"(",
"self",
",",
"sources",
",",
"destinations",
",",
"x",
"=",
"'x'",
",",
"y",
"=",
"'y'",
",",
"isolation",
"=",
"True",
",",
"export_raster",
"=",
"False",
",",
"export_shape",
"=",
"False",
",",
"routes",
"=",
"False",
",",
"... | Compute cost distance measured from each start point to all end points.
The function returns the distances between the start point and the end
points as a Pandas dataframe. Additionally, for each start point it computes
the level of isolation, i.e. its average travel distance to all other locati... | [
"Compute",
"cost",
"distance",
"measured",
"from",
"each",
"start",
"point",
"to",
"all",
"end",
"points",
".",
"The",
"function",
"returns",
"the",
"distances",
"between",
"the",
"start",
"point",
"and",
"the",
"end",
"points",
"as",
"a",
"Pandas",
"datafra... | python | train |
mitsei/dlkit | dlkit/records/assessment/basic/drag_and_drop_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/drag_and_drop_records.py#L303-L310 | def _init_map(self):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'] = \
self._zone_conditions_metadata['default_object_values'][0]
self.my_osid_object_form._my_map['coordinateConditions'] = \
self._coordinate_conditions_metadata['default_object_values'][0]
... | [
"def",
"_init_map",
"(",
"self",
")",
":",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"[",
"'zoneConditions'",
"]",
"=",
"self",
".",
"_zone_conditions_metadata",
"[",
"'default_object_values'",
"]",
"[",
"0",
"]",
"self",
".",
"my_osid_object_form",
".... | stub | [
"stub"
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/flow/base.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/base.py#L294-L305 | def storagehandler(self):
"""
Returns the storage handler available to thise actor.
:return: the storage handler, None if not available
"""
if isinstance(self, StorageHandler):
return self
elif self.parent is not None:
return self.parent.storageha... | [
"def",
"storagehandler",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"StorageHandler",
")",
":",
"return",
"self",
"elif",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"return",
"self",
".",
"parent",
".",
"storagehandler",
"else",
"... | Returns the storage handler available to thise actor.
:return: the storage handler, None if not available | [
"Returns",
"the",
"storage",
"handler",
"available",
"to",
"thise",
"actor",
"."
] | python | train |
PmagPy/PmagPy | dialogs/grid_frame2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/grid_frame2.py#L364-L399 | def remove_col_label(self, event):#, include_pmag=True):
"""
check to see if column is required
if it is not, delete it from grid
"""
er_possible_headers = self.grid_headers[self.grid_type]['er'][2]
pmag_possible_headers = self.grid_headers[self.grid_type]['pmag'][2]
... | [
"def",
"remove_col_label",
"(",
"self",
",",
"event",
")",
":",
"#, include_pmag=True):",
"er_possible_headers",
"=",
"self",
".",
"grid_headers",
"[",
"self",
".",
"grid_type",
"]",
"[",
"'er'",
"]",
"[",
"2",
"]",
"pmag_possible_headers",
"=",
"self",
".",
... | check to see if column is required
if it is not, delete it from grid | [
"check",
"to",
"see",
"if",
"column",
"is",
"required",
"if",
"it",
"is",
"not",
"delete",
"it",
"from",
"grid"
] | python | train |
nerdvegas/rez | src/rez/utils/filesystem.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L76-L112 | def make_path_writable(path):
"""Temporarily make `path` writable, if possible.
Does nothing if:
- config setting 'make_package_temporarily_writable' is False;
- this can't be done (eg we don't own `path`).
Args:
path (str): Path to make temporarily writable
"""
from rez.co... | [
"def",
"make_path_writable",
"(",
"path",
")",
":",
"from",
"rez",
".",
"config",
"import",
"config",
"try",
":",
"orig_mode",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
"new_mode",
"=",
"orig_mode",
"if",
"config",
".",
"make_package_tempor... | Temporarily make `path` writable, if possible.
Does nothing if:
- config setting 'make_package_temporarily_writable' is False;
- this can't be done (eg we don't own `path`).
Args:
path (str): Path to make temporarily writable | [
"Temporarily",
"make",
"path",
"writable",
"if",
"possible",
"."
] | python | train |
ethereum/py-evm | eth/db/journal.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L379-L408 | def commit(self, changeset_id: uuid.UUID) -> None:
"""
Commits a given changeset. This merges the given changeset and all
subsequent changesets into the previous changeset giving precidence
to later changesets in case of any conflicting keys.
If this is the base changeset then a... | [
"def",
"commit",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"None",
":",
"self",
".",
"_validate_changeset",
"(",
"changeset_id",
")",
"journal_data",
"=",
"self",
".",
"journal",
".",
"commit_changeset",
"(",
"changeset_id",
")",... | Commits a given changeset. This merges the given changeset and all
subsequent changesets into the previous changeset giving precidence
to later changesets in case of any conflicting keys.
If this is the base changeset then all changes will be written to
the underlying database and the J... | [
"Commits",
"a",
"given",
"changeset",
".",
"This",
"merges",
"the",
"given",
"changeset",
"and",
"all",
"subsequent",
"changesets",
"into",
"the",
"previous",
"changeset",
"giving",
"precidence",
"to",
"later",
"changesets",
"in",
"case",
"of",
"any",
"conflicti... | python | train |
google/grumpy | third_party/pypy/_sre.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L1068-L1077 | def check_charset(self, ctx, char):
"""Checks whether a character matches set of arbitrary length. Assumes
the code pointer is at the first member of the set."""
self.set_dispatcher.reset(char)
save_position = ctx.code_position
result = None
while result is None:
... | [
"def",
"check_charset",
"(",
"self",
",",
"ctx",
",",
"char",
")",
":",
"self",
".",
"set_dispatcher",
".",
"reset",
"(",
"char",
")",
"save_position",
"=",
"ctx",
".",
"code_position",
"result",
"=",
"None",
"while",
"result",
"is",
"None",
":",
"result... | Checks whether a character matches set of arbitrary length. Assumes
the code pointer is at the first member of the set. | [
"Checks",
"whether",
"a",
"character",
"matches",
"set",
"of",
"arbitrary",
"length",
".",
"Assumes",
"the",
"code",
"pointer",
"is",
"at",
"the",
"first",
"member",
"of",
"the",
"set",
"."
] | python | valid |
stbraun/fuzzing | features/steps/ft_fuzzer.py | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L110-L116 | def step_impl09(context):
"""Create application list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.app_list = [row['application'] for row in context.table.rows] | [
"def",
"step_impl09",
"(",
"context",
")",
":",
"assert",
"context",
".",
"table",
",",
"\"ENSURE: table is provided.\"",
"context",
".",
"app_list",
"=",
"[",
"row",
"[",
"'application'",
"]",
"for",
"row",
"in",
"context",
".",
"table",
".",
"rows",
"]"
] | Create application list.
:param context: test context. | [
"Create",
"application",
"list",
"."
] | python | train |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L394-L446 | def idngram2lm(idngram_file, vocab_file, output_file, context_file=None, vocab_type=1, oov_fraction=0.5, four_byte_counts=False, min_unicount=0, zeroton_fraction=False, n=3, verbosity=2, arpa_output=True, ascii_input=False):
"""
Takes an idngram-file (in either binary (by default) or ASCII (if specified) fo... | [
"def",
"idngram2lm",
"(",
"idngram_file",
",",
"vocab_file",
",",
"output_file",
",",
"context_file",
"=",
"None",
",",
"vocab_type",
"=",
"1",
",",
"oov_fraction",
"=",
"0.5",
",",
"four_byte_counts",
"=",
"False",
",",
"min_unicount",
"=",
"0",
",",
"zerot... | Takes an idngram-file (in either binary (by default) or ASCII (if specified) format), a vocabulary file, and (optionally) a context cues file. Additional command line parameters will specify the cutoffs, the discounting strategy and parameters, etc. It outputs a language model, in either binary format (to be read by ev... | [
"Takes",
"an",
"idngram",
"-",
"file",
"(",
"in",
"either",
"binary",
"(",
"by",
"default",
")",
"or",
"ASCII",
"(",
"if",
"specified",
")",
"format",
")",
"a",
"vocabulary",
"file",
"and",
"(",
"optionally",
")",
"a",
"context",
"cues",
"file",
".",
... | python | train |
mozilla-releng/scriptworker | scriptworker/ed25519.py | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L86-L100 | def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(
encoding=serializ... | [
"def",
"ed25519_private_key_to_string",
"(",
"key",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"Raw",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
... | Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str | [
"Convert",
"an",
"ed25519",
"private",
"key",
"to",
"a",
"base64",
"-",
"encoded",
"string",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/overlay_gateway/site/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/overlay_gateway/site/__init__.py#L144-L169 | def _set_tunnel_dst(self, v, load=False):
"""
Setter method for tunnel_dst, mapped from YANG variable /overlay_gateway/site/tunnel_dst (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel_dst is considered as a private
method. Backends looking to populate th... | [
"def",
"_set_tunnel_dst",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for tunnel_dst, mapped from YANG variable /overlay_gateway/site/tunnel_dst (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel_dst is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_... | [
"Setter",
"method",
"for",
"tunnel_dst",
"mapped",
"from",
"YANG",
"variable",
"/",
"overlay_gateway",
"/",
"site",
"/",
"tunnel_dst",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"... | python | train |
junzis/pyModeS | pyModeS/decoder/adsb.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L88-L114 | def position_with_ref(msg, lat_ref, lon_ref):
"""Decode position with only one message,
knowing reference nearby location, such as previously
calculated location, ground station, or airport location, etc.
Works with both airborne and surface position messages.
The reference position shall be with in... | [
"def",
"position_with_ref",
"(",
"msg",
",",
"lat_ref",
",",
"lon_ref",
")",
":",
"tc",
"=",
"typecode",
"(",
"msg",
")",
"if",
"5",
"<=",
"tc",
"<=",
"8",
":",
"return",
"surface_position_with_ref",
"(",
"msg",
",",
"lat_ref",
",",
"lon_ref",
")",
"el... | Decode position with only one message,
knowing reference nearby location, such as previously
calculated location, ground station, or airport location, etc.
Works with both airborne and surface position messages.
The reference position shall be with in 180NM (airborne) or 45NM (surface)
of the true p... | [
"Decode",
"position",
"with",
"only",
"one",
"message",
"knowing",
"reference",
"nearby",
"location",
"such",
"as",
"previously",
"calculated",
"location",
"ground",
"station",
"or",
"airport",
"location",
"etc",
".",
"Works",
"with",
"both",
"airborne",
"and",
... | python | train |
numenta/htmresearch | htmresearch/frameworks/layers/physical_objects.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/physical_objects.py#L447-L455 | def _sampleFromFaces(self):
"""
We start by sampling a dimension to "max out", then sample the sign and
the other dimensions' values.
"""
coordinates = [random.uniform(-1, 1) * dim / 2. for dim in self.dimensions]
dim = random.choice(range(self.dimension))
coordinates[dim] = self.dimensions[... | [
"def",
"_sampleFromFaces",
"(",
"self",
")",
":",
"coordinates",
"=",
"[",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
")",
"*",
"dim",
"/",
"2.",
"for",
"dim",
"in",
"self",
".",
"dimensions",
"]",
"dim",
"=",
"random",
".",
"choice",
"(",
... | We start by sampling a dimension to "max out", then sample the sign and
the other dimensions' values. | [
"We",
"start",
"by",
"sampling",
"a",
"dimension",
"to",
"max",
"out",
"then",
"sample",
"the",
"sign",
"and",
"the",
"other",
"dimensions",
"values",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L4553-L4620 | def shutdown_host(kwargs=None, call=None):
'''
Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
... | [
"def",
"shutdown_host",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The shutdown_host function must be called with '",
"'-f or --function.'",
")",
"host_name",
"=",
"kw... | Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
set ``force=True``. Default is ``force=False``.
C... | [
"Shut",
"down",
"the",
"specified",
"host",
"system",
"in",
"this",
"VMware",
"environment"
] | python | train |
pyviz/holoviews | holoviews/plotting/bokeh/renderer.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/renderer.py#L123-L137 | def get_plot(self_or_cls, obj, doc=None, renderer=None, **kwargs):
"""
Given a HoloViews Viewable return a corresponding plot instance.
Allows supplying a document attach the plot to, useful when
combining the bokeh model with another plot.
"""
if doc is None:
... | [
"def",
"get_plot",
"(",
"self_or_cls",
",",
"obj",
",",
"doc",
"=",
"None",
",",
"renderer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"Document",
"(",
")",
"if",
"self_or_cls",
".",
"notebook_context... | Given a HoloViews Viewable return a corresponding plot instance.
Allows supplying a document attach the plot to, useful when
combining the bokeh model with another plot. | [
"Given",
"a",
"HoloViews",
"Viewable",
"return",
"a",
"corresponding",
"plot",
"instance",
".",
"Allows",
"supplying",
"a",
"document",
"attach",
"the",
"plot",
"to",
"useful",
"when",
"combining",
"the",
"bokeh",
"model",
"with",
"another",
"plot",
"."
] | python | train |
springload/wagtaildraftail | wagtaildraftail/widgets.py | https://github.com/springload/wagtaildraftail/blob/87f1ae3ade493c00daff021394051aa656136c10/wagtaildraftail/widgets.py#L75-L85 | def intercept_image_formats(self, options):
"""
Load all image formats if needed.
"""
if 'entityTypes' in options:
for entity in options['entityTypes']:
if entity['type'] == ENTITY_TYPES.IMAGE and 'imageFormats' in entity:
if entity['imageF... | [
"def",
"intercept_image_formats",
"(",
"self",
",",
"options",
")",
":",
"if",
"'entityTypes'",
"in",
"options",
":",
"for",
"entity",
"in",
"options",
"[",
"'entityTypes'",
"]",
":",
"if",
"entity",
"[",
"'type'",
"]",
"==",
"ENTITY_TYPES",
".",
"IMAGE",
... | Load all image formats if needed. | [
"Load",
"all",
"image",
"formats",
"if",
"needed",
"."
] | python | train |
devoperate/chronos | chronos/helpers.py | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L65-L79 | def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:... | [
"def",
"git_tag_to_semver",
"(",
"git_tag",
":",
"str",
")",
"->",
"SemVer",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[0-9]+\\.[0-9]+\\.[0-9]+$'",
")",
"match",
"=",
"pattern",
".",
"search",
"(",
"git_tag",
")",
"if",
"match",
":",
"version",
"=... | :git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object. | [
":",
"git_tag",
":",
"A",
"string",
"representation",
"of",
"a",
"Git",
"tag",
"."
] | python | train |
PonteIneptique/collatinus-python | pycollatinus/lemmatiseur.py | https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L211-L225 | def _lemmatise_contractions(self, f, *args, **kwargs):
""" Lemmatise un mot f avec sa contraction
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise()
"""
fd = f
for contraction, decontraction in self._contractions.items():
if fd.endswith(co... | [
"def",
"_lemmatise_contractions",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fd",
"=",
"f",
"for",
"contraction",
",",
"decontraction",
"in",
"self",
".",
"_contractions",
".",
"items",
"(",
")",
":",
"if",
"fd",
"."... | Lemmatise un mot f avec sa contraction
:param f: Mot à lemmatiser
:yield: Match formated like in _lemmatise() | [
"Lemmatise",
"un",
"mot",
"f",
"avec",
"sa",
"contraction"
] | python | train |
arve0/leicascanningtemplate | leicascanningtemplate/template.py | https://github.com/arve0/leicascanningtemplate/blob/053e075d3bed11e335b61ce048c47067b8e9e921/leicascanningtemplate/template.py#L370-L415 | def write(self, filename=None):
"""Save template to xml. Before saving template will update
date, start position, well positions, and counts.
Parameters
----------
filename : str
If not set, XML will be written to self.filename.
"""
if not filename:
... | [
"def",
"write",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"self",
".",
"filename",
"# update time",
"self",
".",
"properties",
".",
"CurrentDate",
"=",
"_current_time",
"(",
")",
"# set rubber band to... | Save template to xml. Before saving template will update
date, start position, well positions, and counts.
Parameters
----------
filename : str
If not set, XML will be written to self.filename. | [
"Save",
"template",
"to",
"xml",
".",
"Before",
"saving",
"template",
"will",
"update",
"date",
"start",
"position",
"well",
"positions",
"and",
"counts",
"."
] | python | train |
MillionIntegrals/vel | vel/util/intepolate.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L53-L55 | def interpolate_single(start, end, coefficient, how='linear'):
""" Interpolate single value between start and end in given number of steps """
return INTERP_SINGLE_DICT[how](start, end, coefficient) | [
"def",
"interpolate_single",
"(",
"start",
",",
"end",
",",
"coefficient",
",",
"how",
"=",
"'linear'",
")",
":",
"return",
"INTERP_SINGLE_DICT",
"[",
"how",
"]",
"(",
"start",
",",
"end",
",",
"coefficient",
")"
] | Interpolate single value between start and end in given number of steps | [
"Interpolate",
"single",
"value",
"between",
"start",
"and",
"end",
"in",
"given",
"number",
"of",
"steps"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/trax/inputs.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/inputs.py#L262-L316 | def batch_fun(dataset, training, shapes, target_names, num_devices,
batch_size_per_device=32, batch_size=None, eval_batch_size=32,
bucket_length=32, buckets=None,
batch_shuffle_size=128, max_eval_length=None):
"""Batching function."""
del target_names
# Batch size is batc... | [
"def",
"batch_fun",
"(",
"dataset",
",",
"training",
",",
"shapes",
",",
"target_names",
",",
"num_devices",
",",
"batch_size_per_device",
"=",
"32",
",",
"batch_size",
"=",
"None",
",",
"eval_batch_size",
"=",
"32",
",",
"bucket_length",
"=",
"32",
",",
"bu... | Batching function. | [
"Batching",
"function",
"."
] | python | train |
cbclab/MOT | mot/mcmc_diagnostics.py | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/mcmc_diagnostics.py#L153-L194 | def get_auto_correlation_time(chain, max_lag=None):
r"""Compute the auto correlation time up to the given lag for the given chain (1d vector).
This will halt when the maximum lag :math:`m` is reached or when the sum of two consecutive lags for any
odd lag is lower or equal to zero.
The auto correlatio... | [
"def",
"get_auto_correlation_time",
"(",
"chain",
",",
"max_lag",
"=",
"None",
")",
":",
"max_lag",
"=",
"max_lag",
"or",
"min",
"(",
"len",
"(",
"chain",
")",
"//",
"3",
",",
"1000",
")",
"normalized_chain",
"=",
"chain",
"-",
"np",
".",
"mean",
"(",
... | r"""Compute the auto correlation time up to the given lag for the given chain (1d vector).
This will halt when the maximum lag :math:`m` is reached or when the sum of two consecutive lags for any
odd lag is lower or equal to zero.
The auto correlation sum is estimated as:
.. math::
\tau = 1 ... | [
"r",
"Compute",
"the",
"auto",
"correlation",
"time",
"up",
"to",
"the",
"given",
"lag",
"for",
"the",
"given",
"chain",
"(",
"1d",
"vector",
")",
"."
] | python | train |
Valuehorizon/valuehorizon-companies | companies/models.py | https://github.com/Valuehorizon/valuehorizon-companies/blob/5366e230da69ee30fcdc1bf4beddc99310f6b767/companies/models.py#L386-L398 | def save(self, *args, **kwargs):
"""
Generate a name, and ensure amount is less than or equal to 100
"""
self.name = str(self.parent.name) + " - " + str(self.child.name) + " - " + str(self.ownership_type)
if self.amount > 100:
raise ValueError("Ownership amoun... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"name",
"=",
"str",
"(",
"self",
".",
"parent",
".",
"name",
")",
"+",
"\" - \"",
"+",
"str",
"(",
"self",
".",
"child",
".",
"name",
")",
"+",
... | Generate a name, and ensure amount is less than or equal to 100 | [
"Generate",
"a",
"name",
"and",
"ensure",
"amount",
"is",
"less",
"than",
"or",
"equal",
"to",
"100"
] | python | train |
emory-libraries/eulxml | eulxml/forms/xmlobject.py | https://github.com/emory-libraries/eulxml/blob/17d71c7d98c0cebda9932b7f13e72093805e1fe2/eulxml/forms/xmlobject.py#L595-L609 | def _update_subinstance(self, name, subform):
"""Save bound data for a single subform into the XmlObject model
instance."""
old_subinstance = getattr(self.instance, name)
new_subinstance = subform.update_instance()
# if our instance previously had no node for the subform AND the... | [
"def",
"_update_subinstance",
"(",
"self",
",",
"name",
",",
"subform",
")",
":",
"old_subinstance",
"=",
"getattr",
"(",
"self",
".",
"instance",
",",
"name",
")",
"new_subinstance",
"=",
"subform",
".",
"update_instance",
"(",
")",
"# if our instance previousl... | Save bound data for a single subform into the XmlObject model
instance. | [
"Save",
"bound",
"data",
"for",
"a",
"single",
"subform",
"into",
"the",
"XmlObject",
"model",
"instance",
"."
] | python | train |
cogniteev/docido-python-sdk | docido_sdk/toolbox/decorators.py | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/decorators.py#L66-L83 | def reraise(clazz):
""" Decorator catching every exception that might be raised by wrapped
function and raise another exception instead.
Exception initially raised is passed in first argument of the raised
exception.
:param: Exception class: clazz:
Python exception class to raise
"""
... | [
"def",
"reraise",
"(",
"clazz",
")",
":",
"def",
"_decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
... | Decorator catching every exception that might be raised by wrapped
function and raise another exception instead.
Exception initially raised is passed in first argument of the raised
exception.
:param: Exception class: clazz:
Python exception class to raise | [
"Decorator",
"catching",
"every",
"exception",
"that",
"might",
"be",
"raised",
"by",
"wrapped",
"function",
"and",
"raise",
"another",
"exception",
"instead",
".",
"Exception",
"initially",
"raised",
"is",
"passed",
"in",
"first",
"argument",
"of",
"the",
"rais... | python | train |
project-rig/rig | rig/machine_control/machine_controller.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L1127-L1170 | def sdram_alloc_as_filelike(self, size, tag=0, x=Required, y=Required,
app_id=Required, clear=False):
"""Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
... | [
"def",
"sdram_alloc_as_filelike",
"(",
"self",
",",
"size",
",",
"tag",
"=",
"0",
",",
"x",
"=",
"Required",
",",
"y",
"=",
"Required",
",",
"app_id",
"=",
"Required",
",",
"clear",
"=",
"False",
")",
":",
"# Perform the malloc",
"start_address",
"=",
"s... | Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
Returns
-------
:py:class:`.MemoryIO`
File-like object which allows accessing the newly allocated region
... | [
"Like",
":",
"py",
":",
"meth",
":",
".",
"sdram_alloc",
"but",
"returns",
"a",
":",
"py",
":",
"class",
":",
"file",
"-",
"like",
"object",
"<",
".",
"MemoryIO",
">",
"which",
"allows",
"safe",
"reading",
"and",
"writing",
"to",
"the",
"block",
"tha... | python | train |
belbio/bel | bel/lang/belobj.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L339-L372 | def compute_edges(
self, rules: List[str] = None, ast_result=False, fmt="medium"
) -> List[Mapping[str, Any]]:
"""Computed edges from primary BEL statement
Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures.
Will run only the list of co... | [
"def",
"compute_edges",
"(",
"self",
",",
"rules",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"ast_result",
"=",
"False",
",",
"fmt",
"=",
"\"medium\"",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"if",
"not",
"... | Computed edges from primary BEL statement
Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures.
Will run only the list of computed edge rules if given.
Args:
rules (list): a list of rules to filter; only the rules in this list will be ap... | [
"Computed",
"edges",
"from",
"primary",
"BEL",
"statement"
] | python | train |
johnhw/pyspacenavigator | spacenavigator.py | https://github.com/johnhw/pyspacenavigator/blob/518bd89f94b83156f12dae261f95c517fb78ebe4/spacenavigator.py#L257-L270 | def list_devices():
"""Return a list of the supported devices connected
Returns:
A list of string names of the devices supported which were found. Empty if no supported devices found
"""
devices = []
all_hids = hid.find_all_hid_devices()
if all_hids:
for index, device in e... | [
"def",
"list_devices",
"(",
")",
":",
"devices",
"=",
"[",
"]",
"all_hids",
"=",
"hid",
".",
"find_all_hid_devices",
"(",
")",
"if",
"all_hids",
":",
"for",
"index",
",",
"device",
"in",
"enumerate",
"(",
"all_hids",
")",
":",
"for",
"device_name",
",",
... | Return a list of the supported devices connected
Returns:
A list of string names of the devices supported which were found. Empty if no supported devices found | [
"Return",
"a",
"list",
"of",
"the",
"supported",
"devices",
"connected",
"Returns",
":",
"A",
"list",
"of",
"string",
"names",
"of",
"the",
"devices",
"supported",
"which",
"were",
"found",
".",
"Empty",
"if",
"no",
"supported",
"devices",
"found"
] | python | train |
markovmodel/PyEMMA | pyemma/util/discrete_trajectories.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/discrete_trajectories.py#L144-L177 | def count_states(dtrajs, ignore_negative=False):
r"""returns a histogram count
Parameters
----------
dtrajs : array_like or list of array_like
Discretized trajectory or list of discretized trajectories
ignore_negative, bool, default=False
Ignore negative elements. By default, a nega... | [
"def",
"count_states",
"(",
"dtrajs",
",",
"ignore_negative",
"=",
"False",
")",
":",
"# format input",
"dtrajs",
"=",
"_ensure_dtraj_list",
"(",
"dtrajs",
")",
"# make bincounts for each input trajectory",
"nmax",
"=",
"0",
"bcs",
"=",
"[",
"]",
"for",
"dtraj",
... | r"""returns a histogram count
Parameters
----------
dtrajs : array_like or list of array_like
Discretized trajectory or list of discretized trajectories
ignore_negative, bool, default=False
Ignore negative elements. By default, a negative element will cause an
exception
Ret... | [
"r",
"returns",
"a",
"histogram",
"count"
] | python | train |
valentinalexeev/pwaqi | pwaqi/__init__.py | https://github.com/valentinalexeev/pwaqi/blob/81a1fa1ad87be7ba015c1cb07c52c7760ca99d8c/pwaqi/__init__.py#L31-L41 | def get_location_observation(lat, lng, token):
"""Lookup observations by geo coordinates."""
req = requests.get(
API_ENDPOINT_GEO % (lat, lng),
params={
'token': token
})
if req.status_code == 200 and req.json()["status"] == "ok":
return parse_observation_respons... | [
"def",
"get_location_observation",
"(",
"lat",
",",
"lng",
",",
"token",
")",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"API_ENDPOINT_GEO",
"%",
"(",
"lat",
",",
"lng",
")",
",",
"params",
"=",
"{",
"'token'",
":",
"token",
"}",
")",
"if",
"req",... | Lookup observations by geo coordinates. | [
"Lookup",
"observations",
"by",
"geo",
"coordinates",
"."
] | python | test |
ladybug-tools/ladybug | ladybug/sunpath.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/sunpath.py#L127-L131 | def is_daylight_saving_hour(self, datetime):
"""Check if a datetime is a daylight saving time."""
if not self.daylight_saving_period:
return False
return self.daylight_saving_period.isTimeIncluded(datetime.hoy) | [
"def",
"is_daylight_saving_hour",
"(",
"self",
",",
"datetime",
")",
":",
"if",
"not",
"self",
".",
"daylight_saving_period",
":",
"return",
"False",
"return",
"self",
".",
"daylight_saving_period",
".",
"isTimeIncluded",
"(",
"datetime",
".",
"hoy",
")"
] | Check if a datetime is a daylight saving time. | [
"Check",
"if",
"a",
"datetime",
"is",
"a",
"daylight",
"saving",
"time",
"."
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/compiler/parser.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/parser.py#L1788-L1876 | def __resolve_namespaced_symbol( # pylint: disable=too-many-branches
ctx: ParserContext, form: sym.Symbol
) -> Union[MaybeClass, MaybeHostForm, VarRef]:
"""Resolve a namespaced symbol into a Python name or Basilisp Var."""
assert form.ns is not None
if form.ns == ctx.current_ns.name:
v = ctx.c... | [
"def",
"__resolve_namespaced_symbol",
"(",
"# pylint: disable=too-many-branches",
"ctx",
":",
"ParserContext",
",",
"form",
":",
"sym",
".",
"Symbol",
")",
"->",
"Union",
"[",
"MaybeClass",
",",
"MaybeHostForm",
",",
"VarRef",
"]",
":",
"assert",
"form",
".",
"n... | Resolve a namespaced symbol into a Python name or Basilisp Var. | [
"Resolve",
"a",
"namespaced",
"symbol",
"into",
"a",
"Python",
"name",
"or",
"Basilisp",
"Var",
"."
] | python | test |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py#L1837-L1855 | def delete_dns_server(self, service_name, deployment_name, dns_server_name):
'''
Deletes a DNS server from a deployment.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
dns_server_name:
Name of the DNS serve... | [
"def",
"delete_dns_server",
"(",
"self",
",",
"service_name",
",",
"deployment_name",
",",
"dns_server_name",
")",
":",
"_validate_not_none",
"(",
"'service_name'",
",",
"service_name",
")",
"_validate_not_none",
"(",
"'deployment_name'",
",",
"deployment_name",
")",
... | Deletes a DNS server from a deployment.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
dns_server_name:
Name of the DNS server that you want to delete. | [
"Deletes",
"a",
"DNS",
"server",
"from",
"a",
"deployment",
"."
] | python | test |
woolfson-group/isambard | isambard/external_programs/dssp.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/external_programs/dssp.py#L180-L220 | def extract_helices_dssp(in_pdb):
"""Uses DSSP to find alpha-helices and extracts helices from a pdb file.
Returns a length 3 list with a helix id, the chain id and a dict
containing the coordinates of each residues CA.
Parameters
----------
in_pdb : string
Path to a PDB file.
"""
... | [
"def",
"extract_helices_dssp",
"(",
"in_pdb",
")",
":",
"from",
"ampal",
".",
"pdb_parser",
"import",
"split_pdb_lines",
"dssp_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"global_settings",
"[",
"'dssp'",
"]",
"[",
"'path'",
"]",
",",
"in_pdb",
"]"... | Uses DSSP to find alpha-helices and extracts helices from a pdb file.
Returns a length 3 list with a helix id, the chain id and a dict
containing the coordinates of each residues CA.
Parameters
----------
in_pdb : string
Path to a PDB file. | [
"Uses",
"DSSP",
"to",
"find",
"alpha",
"-",
"helices",
"and",
"extracts",
"helices",
"from",
"a",
"pdb",
"file",
"."
] | python | train |
aouyar/PyMunin | pysysinfo/system.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/system.py#L98-L118 | def getProcessStats(self):
"""Return stats for running and blocked processes, forks,
context switches and interrupts.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(cpustatFile, 'r')
data = fp.read()
... | [
"def",
"getProcessStats",
"(",
"self",
")",
":",
"info_dict",
"=",
"{",
"}",
"try",
":",
"fp",
"=",
"open",
"(",
"cpustatFile",
",",
"'r'",
")",
"data",
"=",
"fp",
".",
"read",
"(",
")",
"fp",
".",
"close",
"(",
")",
"except",
":",
"raise",
"IOEr... | Return stats for running and blocked processes, forks,
context switches and interrupts.
@return: Dictionary of stats. | [
"Return",
"stats",
"for",
"running",
"and",
"blocked",
"processes",
"forks",
"context",
"switches",
"and",
"interrupts",
"."
] | python | train |
siznax/wptools | wptools/utils.py | https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/utils.py#L110-L115 | def stderr(msg, silent=False):
"""
write msg to stderr if not silent
"""
if not silent:
print(msg, file=sys.stderr) | [
"def",
"stderr",
"(",
"msg",
",",
"silent",
"=",
"False",
")",
":",
"if",
"not",
"silent",
":",
"print",
"(",
"msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | write msg to stderr if not silent | [
"write",
"msg",
"to",
"stderr",
"if",
"not",
"silent"
] | python | train |
freakboy3742/pyxero | xero/auth.py | https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L165-L177 | def _init_oauth(self, oauth_token, oauth_token_secret):
"Store and initialize a verified set of OAuth credentials"
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
self._oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_sec... | [
"def",
"_init_oauth",
"(",
"self",
",",
"oauth_token",
",",
"oauth_token_secret",
")",
":",
"self",
".",
"oauth_token",
"=",
"oauth_token",
"self",
".",
"oauth_token_secret",
"=",
"oauth_token_secret",
"self",
".",
"_oauth",
"=",
"OAuth1",
"(",
"self",
".",
"c... | Store and initialize a verified set of OAuth credentials | [
"Store",
"and",
"initialize",
"a",
"verified",
"set",
"of",
"OAuth",
"credentials"
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/regex.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/regex.py#L11-L27 | def transform (list, pattern, indices = [1]):
""" Matches all elements of 'list' agains the 'pattern'
and returns a list of the elements indicated by indices of
all successfull matches. If 'indices' is omitted returns
a list of first paranthethised groups of all successfull
matches.
... | [
"def",
"transform",
"(",
"list",
",",
"pattern",
",",
"indices",
"=",
"[",
"1",
"]",
")",
":",
"result",
"=",
"[",
"]",
"for",
"e",
"in",
"list",
":",
"m",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"e",
")",
"if",
"m",
":",
"for",
"i",
... | Matches all elements of 'list' agains the 'pattern'
and returns a list of the elements indicated by indices of
all successfull matches. If 'indices' is omitted returns
a list of first paranthethised groups of all successfull
matches. | [
"Matches",
"all",
"elements",
"of",
"list",
"agains",
"the",
"pattern",
"and",
"returns",
"a",
"list",
"of",
"the",
"elements",
"indicated",
"by",
"indices",
"of",
"all",
"successfull",
"matches",
".",
"If",
"indices",
"is",
"omitted",
"returns",
"a",
"list"... | python | train |
pytroll/satpy | satpy/readers/grib.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/grib.py#L207-L217 | def get_area_def(self, dsid):
"""Get area definition for message.
If latlong grid then convert to valid eqc grid.
"""
msg = self._get_message(self._msg_datasets[dsid])
try:
return self._area_def_from_msg(msg)
except (RuntimeError, KeyError):
rais... | [
"def",
"get_area_def",
"(",
"self",
",",
"dsid",
")",
":",
"msg",
"=",
"self",
".",
"_get_message",
"(",
"self",
".",
"_msg_datasets",
"[",
"dsid",
"]",
")",
"try",
":",
"return",
"self",
".",
"_area_def_from_msg",
"(",
"msg",
")",
"except",
"(",
"Runt... | Get area definition for message.
If latlong grid then convert to valid eqc grid. | [
"Get",
"area",
"definition",
"for",
"message",
"."
] | python | train |
moonso/interval_tree | interval_tree/interval_tree.py | https://github.com/moonso/interval_tree/blob/c588177f5bd90bd9e2f1447216c78b024353f7a1/interval_tree/interval_tree.py#L64-L97 | def recursive_build_tree(self, intervals):
"""
recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
... | [
"def",
"recursive_build_tree",
"(",
"self",
",",
"intervals",
")",
":",
"center",
"=",
"int",
"(",
"round",
"(",
"len",
"(",
"intervals",
")",
"/",
"2",
")",
")",
"left",
"=",
"intervals",
"[",
":",
"center",
"]",
"right",
"=",
"intervals",
"[",
"cen... | recursively builds a BST based on the elementary intervals.
each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]].
nodes with no descendents have a -1 value in left/right descendent positions.
for example, a node with two empty descendents:
[5... | [
"recursively",
"builds",
"a",
"BST",
"based",
"on",
"the",
"elementary",
"intervals",
".",
"each",
"node",
"is",
"an",
"array",
":",
"[",
"interval",
"value",
"left",
"descendent",
"nodes",
"right",
"descendent",
"nodes",
"[",
"ids",
"]]",
".",
"nodes",
"w... | python | train |
postlund/pyatv | pyatv/conf.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/conf.py#L25-L35 | def add_service(self, service):
"""Add a new service.
If the service already exists, it will be replaced.
"""
if service.protocol in self._services:
existing = self._services[service.protocol]
if not existing.superseeded_by(service):
return
... | [
"def",
"add_service",
"(",
"self",
",",
"service",
")",
":",
"if",
"service",
".",
"protocol",
"in",
"self",
".",
"_services",
":",
"existing",
"=",
"self",
".",
"_services",
"[",
"service",
".",
"protocol",
"]",
"if",
"not",
"existing",
".",
"superseede... | Add a new service.
If the service already exists, it will be replaced. | [
"Add",
"a",
"new",
"service",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/oneoffs/validate_misc.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/oneoffs/validate_misc.py#L22-L43 | def validate_examples(example_file):
"""Validate that examples are well formed.
Pi should sum to 1.0
value should be {-1,1}
Usage:
validate_examples("../data/300.tfrecord.zz")
"""
def test_example(raw):
example = tf.train.Example()
example.ParseFromString(raw)
... | [
"def",
"validate_examples",
"(",
"example_file",
")",
":",
"def",
"test_example",
"(",
"raw",
")",
":",
"example",
"=",
"tf",
".",
"train",
".",
"Example",
"(",
")",
"example",
".",
"ParseFromString",
"(",
"raw",
")",
"pi",
"=",
"np",
".",
"frombuffer",
... | Validate that examples are well formed.
Pi should sum to 1.0
value should be {-1,1}
Usage:
validate_examples("../data/300.tfrecord.zz") | [
"Validate",
"that",
"examples",
"are",
"well",
"formed",
"."
] | python | train |
jab/bidict | bidict/_base.py | https://github.com/jab/bidict/blob/1a1ba9758651aed9c4f58384eff006d2e2ad6835/bidict/_base.py#L241-L293 | def _dedup_item(self, key, val, on_dup):
"""
Check *key* and *val* for any duplication in self.
Handle any duplication as per the duplication policies given in *on_dup*.
(key, val) already present is construed as a no-op, not a duplication.
If duplication is found and the corr... | [
"def",
"_dedup_item",
"(",
"self",
",",
"key",
",",
"val",
",",
"on_dup",
")",
":",
"fwdm",
"=",
"self",
".",
"_fwdm",
"invm",
"=",
"self",
".",
"_invm",
"oldval",
"=",
"fwdm",
".",
"get",
"(",
"key",
",",
"_MISS",
")",
"oldkey",
"=",
"invm",
"."... | Check *key* and *val* for any duplication in self.
Handle any duplication as per the duplication policies given in *on_dup*.
(key, val) already present is construed as a no-op, not a duplication.
If duplication is found and the corresponding duplication policy is
:attr:`~bidict.RAISE`... | [
"Check",
"*",
"key",
"*",
"and",
"*",
"val",
"*",
"for",
"any",
"duplication",
"in",
"self",
"."
] | python | test |
ralphje/imagemounter | imagemounter/parser.py | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/parser.py#L109-L119 | def mount_disks(self):
"""Mounts all disks in the parser, i.e. calling :func:`Disk.mount` on all underlying disks. You probably want to
use :func:`init` instead.
:return: whether all mounts have succeeded
:rtype: bool"""
result = True
for disk in self.disks:
... | [
"def",
"mount_disks",
"(",
"self",
")",
":",
"result",
"=",
"True",
"for",
"disk",
"in",
"self",
".",
"disks",
":",
"result",
"=",
"disk",
".",
"mount",
"(",
")",
"and",
"result",
"return",
"result"
] | Mounts all disks in the parser, i.e. calling :func:`Disk.mount` on all underlying disks. You probably want to
use :func:`init` instead.
:return: whether all mounts have succeeded
:rtype: bool | [
"Mounts",
"all",
"disks",
"in",
"the",
"parser",
"i",
".",
"e",
".",
"calling",
":",
"func",
":",
"Disk",
".",
"mount",
"on",
"all",
"underlying",
"disks",
".",
"You",
"probably",
"want",
"to",
"use",
":",
"func",
":",
"init",
"instead",
"."
] | python | train |
LogicalDash/LiSE | allegedb/allegedb/cache.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L765-L780 | def retrieve(self, *args):
"""Get a value previously .store(...)'d.
Needs at least five arguments. The -1th is the tick
within the turn you want,
the -2th is that turn, the -3th is the branch,
and the -4th is the key. All other arguments identify
the entity that the key ... | [
"def",
"retrieve",
"(",
"self",
",",
"*",
"args",
")",
":",
"ret",
"=",
"self",
".",
"_base_retrieve",
"(",
"args",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"HistoryError",
"(",
"\"Set, then deleted\"",
",",
"deleted",
"=",
"True",
")",
"elif",
"r... | Get a value previously .store(...)'d.
Needs at least five arguments. The -1th is the tick
within the turn you want,
the -2th is that turn, the -3th is the branch,
and the -4th is the key. All other arguments identify
the entity that the key is in. | [
"Get",
"a",
"value",
"previously",
".",
"store",
"(",
"...",
")",
"d",
"."
] | python | train |
boakley/robotframework-hub | rfhub/kwdb.py | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/kwdb.py#L86-L111 | def on_change(self, path, event_type):
"""Respond to changes in the file system
This method will be given the path to a file that
has changed on disk. We need to reload the keywords
from that file
"""
# I can do all this work in a sql statement, but
# for debuggi... | [
"def",
"on_change",
"(",
"self",
",",
"path",
",",
"event_type",
")",
":",
"# I can do all this work in a sql statement, but",
"# for debugging it's easier to do it in stages.",
"sql",
"=",
"\"\"\"SELECT collection_id\n FROM collection_table\n WHERE path =... | Respond to changes in the file system
This method will be given the path to a file that
has changed on disk. We need to reload the keywords
from that file | [
"Respond",
"to",
"changes",
"in",
"the",
"file",
"system"
] | python | train |
xingjiepan/cylinder_fitting | cylinder_fitting/geometry.py | https://github.com/xingjiepan/cylinder_fitting/blob/f96d79732bc49cbc0cb4b39f008af7ce42aeb213/cylinder_fitting/geometry.py#L23-L29 | def point_line_distance(p, l_p, l_v):
'''Calculate the distance between a point and a line defined
by a point and a direction vector.
'''
l_v = normalize(l_v)
u = p - l_p
return np.linalg.norm(u - np.dot(u, l_v) * l_v) | [
"def",
"point_line_distance",
"(",
"p",
",",
"l_p",
",",
"l_v",
")",
":",
"l_v",
"=",
"normalize",
"(",
"l_v",
")",
"u",
"=",
"p",
"-",
"l_p",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"u",
"-",
"np",
".",
"dot",
"(",
"u",
",",
"l_v",
... | Calculate the distance between a point and a line defined
by a point and a direction vector. | [
"Calculate",
"the",
"distance",
"between",
"a",
"point",
"and",
"a",
"line",
"defined",
"by",
"a",
"point",
"and",
"a",
"direction",
"vector",
"."
] | python | train |
cggh/scikit-allel | allel/stats/sf.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/sf.py#L638-L675 | def plot_sfs_folded_scaled(*args, **kwargs):
"""Plot a folded scaled site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes/2,)
Site frequency spectrum.
yscale : string, optional
Y axis scale.
bins : int or array_like, int, optional
Alle... | [
"def",
"plot_sfs_folded_scaled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'yscale'",
",",
"'linear'",
")",
"ax",
"=",
"plot_sfs_folded",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"set_ylab... | Plot a folded scaled site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes/2,)
Site frequency spectrum.
yscale : string, optional
Y axis scale.
bins : int or array_like, int, optional
Allele count bins.
n : int, optional
Number ... | [
"Plot",
"a",
"folded",
"scaled",
"site",
"frequency",
"spectrum",
"."
] | python | train |
fpoirotte/sphinxcontrib-varlinks | sphinxcontrib/varlinks.py | https://github.com/fpoirotte/sphinxcontrib-varlinks/blob/836899486e841fee4bac32a9d57da2786b2045c6/sphinxcontrib/varlinks.py#L92-L123 | def apply(self):
"""Replace substitutions in hyperlinks with their contents"""
# In this phase, we replace the substitutions in hyperlinks
# with the contents of the sub-nodes introduced during phase 1.
# We also remove those temporary nodes from the tree.
subst_re = re.compile(s... | [
"def",
"apply",
"(",
"self",
")",
":",
"# In this phase, we replace the substitutions in hyperlinks",
"# with the contents of the sub-nodes introduced during phase 1.",
"# We also remove those temporary nodes from the tree.",
"subst_re",
"=",
"re",
".",
"compile",
"(",
"self",
".",
... | Replace substitutions in hyperlinks with their contents | [
"Replace",
"substitutions",
"in",
"hyperlinks",
"with",
"their",
"contents"
] | python | train |
kratsg/ironman | ironman/utilities.py | https://github.com/kratsg/ironman/blob/7d67b79970870e7e5520181d2afa3f423e46eb3a/ironman/utilities.py#L7-L10 | def byteswap(data, word_size=4):
""" Swap the byte-ordering in a packet with N=4 bytes per word
"""
return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '') | [
"def",
"byteswap",
"(",
"data",
",",
"word_size",
"=",
"4",
")",
":",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"''",
".",
"join",
"(",
"reversed",
"(",
"y",
")",
")",
",",
"chunks",
"(",
"data",
",",
"word_size",
")",
",... | Swap the byte-ordering in a packet with N=4 bytes per word | [
"Swap",
"the",
"byte",
"-",
"ordering",
"in",
"a",
"packet",
"with",
"N",
"=",
"4",
"bytes",
"per",
"word"
] | python | train |
theduke/django-baseline | django_baseline/template.py | https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/template.py#L5-L24 | def render_template(tpl, context):
'''
A shortcut function to render a partial template with context and return
the output.
'''
templates = [tpl] if type(tpl) != list else tpl
tpl_instance = None
for tpl in templates:
try:
tpl_instance = template.loader.get_t... | [
"def",
"render_template",
"(",
"tpl",
",",
"context",
")",
":",
"templates",
"=",
"[",
"tpl",
"]",
"if",
"type",
"(",
"tpl",
")",
"!=",
"list",
"else",
"tpl",
"tpl_instance",
"=",
"None",
"for",
"tpl",
"in",
"templates",
":",
"try",
":",
"tpl_instance"... | A shortcut function to render a partial template with context and return
the output. | [
"A",
"shortcut",
"function",
"to",
"render",
"a",
"partial",
"template",
"with",
"context",
"and",
"return",
"the",
"output",
"."
] | python | test |
secdev/scapy | scapy/contrib/http2.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/http2.py#L1111-L1137 | def huffman_conv2str(cls, bit_str, bit_len):
# type: (int, int) -> str
""" huffman_conv2str converts a bitstring of bit_len bitlength into a
binary string. It DOES NOT compress/decompress the bitstring!
@param int bit_str: the bitstring to convert.
@param int bit_len: the bitlen... | [
"def",
"huffman_conv2str",
"(",
"cls",
",",
"bit_str",
",",
"bit_len",
")",
":",
"# type: (int, int) -> str",
"assert",
"(",
"bit_str",
">=",
"0",
")",
"assert",
"(",
"bit_len",
">=",
"0",
")",
"byte_len",
"=",
"bit_len",
"//",
"8",
"rem_bit",
"=",
"bit_le... | huffman_conv2str converts a bitstring of bit_len bitlength into a
binary string. It DOES NOT compress/decompress the bitstring!
@param int bit_str: the bitstring to convert.
@param int bit_len: the bitlength of bit_str.
@return str: the converted bitstring as a bytestring.
@rais... | [
"huffman_conv2str",
"converts",
"a",
"bitstring",
"of",
"bit_len",
"bitlength",
"into",
"a",
"binary",
"string",
".",
"It",
"DOES",
"NOT",
"compress",
"/",
"decompress",
"the",
"bitstring!"
] | python | train |
inspirehep/inspire-utils | inspire_utils/urls.py | https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/urls.py#L31-L51 | def ensure_scheme(url, default_scheme='http'):
"""Adds a scheme to a url if not present.
Args:
url (string): a url, assumed to start with netloc
default_scheme (string): a scheme to be added
Returns:
string: URL with a scheme
"""
parsed = urlsplit(url, scheme=default_scheme... | [
"def",
"ensure_scheme",
"(",
"url",
",",
"default_scheme",
"=",
"'http'",
")",
":",
"parsed",
"=",
"urlsplit",
"(",
"url",
",",
"scheme",
"=",
"default_scheme",
")",
"if",
"not",
"parsed",
".",
"netloc",
":",
"parsed",
"=",
"SplitResult",
"(",
"scheme",
... | Adds a scheme to a url if not present.
Args:
url (string): a url, assumed to start with netloc
default_scheme (string): a scheme to be added
Returns:
string: URL with a scheme | [
"Adds",
"a",
"scheme",
"to",
"a",
"url",
"if",
"not",
"present",
"."
] | python | train |
klmitch/turnstile | turnstile/config.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/config.py#L228-L254 | def to_bool(value, do_raise=True):
"""Convert a string to a boolean value.
If the string consists of digits, the integer value of the string
is coerced to a boolean value. Otherwise, any of the strings "t",
"true", "on", "y", and "yes" are considered True and any of the
strings... | [
"def",
"to_bool",
"(",
"value",
",",
"do_raise",
"=",
"True",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"# Try it as an integer",
"if",
"value",
".",
"isdigit",
"(",
")",
":",
"return",
"bool",
"(",
"int",
"(",
"value",
")",
")",
"# OK... | Convert a string to a boolean value.
If the string consists of digits, the integer value of the string
is coerced to a boolean value. Otherwise, any of the strings "t",
"true", "on", "y", and "yes" are considered True and any of the
strings "f", "false", "off", "n", and "no" are consid... | [
"Convert",
"a",
"string",
"to",
"a",
"boolean",
"value",
"."
] | python | train |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L164-L174 | def references(self):
"""Return EIDs of references of an article.
Note: Requires the FULL view of the article.
"""
refs = self.items.find('bibrecord/tail/bibliography', ns)
if refs is not None:
eids = [r.find("ref-info/refd-itemidlist/itemid", ns).text for r
... | [
"def",
"references",
"(",
"self",
")",
":",
"refs",
"=",
"self",
".",
"items",
".",
"find",
"(",
"'bibrecord/tail/bibliography'",
",",
"ns",
")",
"if",
"refs",
"is",
"not",
"None",
":",
"eids",
"=",
"[",
"r",
".",
"find",
"(",
"\"ref-info/refd-itemidlist... | Return EIDs of references of an article.
Note: Requires the FULL view of the article. | [
"Return",
"EIDs",
"of",
"references",
"of",
"an",
"article",
".",
"Note",
":",
"Requires",
"the",
"FULL",
"view",
"of",
"the",
"article",
"."
] | python | train |
openeemeter/eemeter | eemeter/caltrack/usage_per_day.py | https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/caltrack/usage_per_day.py#L1303-L1344 | def get_hdd_only_candidate_models(
data, minimum_non_zero_hdd, minimum_total_hdd, beta_hdd_maximum_p_value, weights_col
):
"""
Parameters
----------
data : :any:`pandas.DataFrame`
A DataFrame containing at least the column ``meter_value`` and 1 to n
columns with names of the form ``h... | [
"def",
"get_hdd_only_candidate_models",
"(",
"data",
",",
"minimum_non_zero_hdd",
",",
"minimum_total_hdd",
",",
"beta_hdd_maximum_p_value",
",",
"weights_col",
")",
":",
"balance_points",
"=",
"[",
"int",
"(",
"col",
"[",
"4",
":",
"]",
")",
"for",
"col",
"in",... | Parameters
----------
data : :any:`pandas.DataFrame`
A DataFrame containing at least the column ``meter_value`` and 1 to n
columns with names of the form ``hdd_<balance_point>``. All columns
with names of this form will be used to fit a candidate model.
DataFrames of this form ca... | [
"Parameters",
"----------",
"data",
":",
":",
"any",
":",
"pandas",
".",
"DataFrame",
"A",
"DataFrame",
"containing",
"at",
"least",
"the",
"column",
"meter_value",
"and",
"1",
"to",
"n",
"columns",
"with",
"names",
"of",
"the",
"form",
"hdd_<balance_point",
... | python | train |
pescadores/pescador | examples/mux/mux_files_example.py | https://github.com/pescadores/pescador/blob/786e2b5f882d13ea563769fbc7ad0a0a10c3553d/examples/mux/mux_files_example.py#L60-L71 | def npz_generator(npz_path):
"""Generate data from an npz file."""
npz_data = np.load(npz_path)
X = npz_data['X']
# Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,)
y = npz_data['Y']
n = X.shape[0]
while True:
i = np.random.randint(0, n)
yield {'X': X[i]... | [
"def",
"npz_generator",
"(",
"npz_path",
")",
":",
"npz_data",
"=",
"np",
".",
"load",
"(",
"npz_path",
")",
"X",
"=",
"npz_data",
"[",
"'X'",
"]",
"# Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,)",
"y",
"=",
"npz_data",
"[",
"'Y'",
"]",
"... | Generate data from an npz file. | [
"Generate",
"data",
"from",
"an",
"npz",
"file",
"."
] | python | train |
tjcsl/ion | intranet/apps/users/templatetags/users.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/templatetags/users.py#L21-L26 | def argument_request_user(obj, func_name):
"""Pass request.user as an argument to the given function call."""
func = getattr(obj, func_name)
request = threadlocals.request()
if request:
return func(request.user) | [
"def",
"argument_request_user",
"(",
"obj",
",",
"func_name",
")",
":",
"func",
"=",
"getattr",
"(",
"obj",
",",
"func_name",
")",
"request",
"=",
"threadlocals",
".",
"request",
"(",
")",
"if",
"request",
":",
"return",
"func",
"(",
"request",
".",
"use... | Pass request.user as an argument to the given function call. | [
"Pass",
"request",
".",
"user",
"as",
"an",
"argument",
"to",
"the",
"given",
"function",
"call",
"."
] | python | train |
PierreRust/apigpio | apigpio/apigpio.py | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L1033-L1054 | def set_servo_pulsewidth(self, user_gpio, pulsewidth):
"""
Starts (500-2500) or stops (0) servo pulses on the GPIO.
user_gpio:= 0-31.
pulsewidth:= 0 (off),
500 (most anti-clockwise) - 2500 (most clockwise).
The selected pulsewidth will continue to be transmi... | [
"def",
"set_servo_pulsewidth",
"(",
"self",
",",
"user_gpio",
",",
"pulsewidth",
")",
":",
"res",
"=",
"yield",
"from",
"self",
".",
"_pigpio_aio_command",
"(",
"_PI_CMD_SERVO",
",",
"user_gpio",
",",
"int",
"(",
"pulsewidth",
")",
")",
"return",
"_u2i",
"("... | Starts (500-2500) or stops (0) servo pulses on the GPIO.
user_gpio:= 0-31.
pulsewidth:= 0 (off),
500 (most anti-clockwise) - 2500 (most clockwise).
The selected pulsewidth will continue to be transmitted until
changed by a subsequent call to set_servo_pulsewidth.
... | [
"Starts",
"(",
"500",
"-",
"2500",
")",
"or",
"stops",
"(",
"0",
")",
"servo",
"pulses",
"on",
"the",
"GPIO",
".",
"user_gpio",
":",
"=",
"0",
"-",
"31",
".",
"pulsewidth",
":",
"=",
"0",
"(",
"off",
")",
"500",
"(",
"most",
"anti",
"-",
"clock... | python | train |
Brightmd/TxPx | txpx/process.py | https://github.com/Brightmd/TxPx/blob/403c18b3006fc68842ec05b259e8611fe80763aa/txpx/process.py#L86-L96 | def processEnded(self, reason):
"""
Connected process shut down
"""
log_debug("{name} process exited", name=self.name)
if self.deferred:
if reason.type == ProcessDone:
self.deferred.callback(reason.value.exitCode)
elif reason.type == Proces... | [
"def",
"processEnded",
"(",
"self",
",",
"reason",
")",
":",
"log_debug",
"(",
"\"{name} process exited\"",
",",
"name",
"=",
"self",
".",
"name",
")",
"if",
"self",
".",
"deferred",
":",
"if",
"reason",
".",
"type",
"==",
"ProcessDone",
":",
"self",
"."... | Connected process shut down | [
"Connected",
"process",
"shut",
"down"
] | python | train |
theislab/scanpy | scanpy/preprocessing/_simple.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/preprocessing/_simple.py#L826-L878 | def scale(data, zero_center=True, max_value=None, copy=False) -> Optional[AnnData]:
"""Scale data to unit variance and zero mean.
.. note::
Variables (genes) that do not display any variation (are constant across
all observations) are retained and set to 0 during this operation. In
the ... | [
"def",
"scale",
"(",
"data",
",",
"zero_center",
"=",
"True",
",",
"max_value",
"=",
"None",
",",
"copy",
"=",
"False",
")",
"->",
"Optional",
"[",
"AnnData",
"]",
":",
"if",
"isinstance",
"(",
"data",
",",
"AnnData",
")",
":",
"adata",
"=",
"data",
... | Scale data to unit variance and zero mean.
.. note::
Variables (genes) that do not display any variation (are constant across
all observations) are retained and set to 0 during this operation. In
the future, they might be set to NaNs.
Parameters
----------
data : :class:`~annda... | [
"Scale",
"data",
"to",
"unit",
"variance",
"and",
"zero",
"mean",
"."
] | python | train |
androguard/androguard | androguard/core/bytecodes/apk.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L1011-L1036 | def is_tag_matched(self, tag, **attribute_filter):
r"""
Return true if the attributes matches in attribute filter.
An attribute filter is a dictionary containing: {attribute_name: value}.
This function will return True if and only if all attributes have the same value.
This func... | [
"def",
"is_tag_matched",
"(",
"self",
",",
"tag",
",",
"*",
"*",
"attribute_filter",
")",
":",
"if",
"len",
"(",
"attribute_filter",
")",
"<=",
"0",
":",
"return",
"True",
"for",
"attr",
",",
"value",
"in",
"attribute_filter",
".",
"items",
"(",
")",
"... | r"""
Return true if the attributes matches in attribute filter.
An attribute filter is a dictionary containing: {attribute_name: value}.
This function will return True if and only if all attributes have the same value.
This function allows to set the dictionary via kwargs, thus you can ... | [
"r",
"Return",
"true",
"if",
"the",
"attributes",
"matches",
"in",
"attribute",
"filter",
"."
] | python | train |
awslabs/sockeye | sockeye/utils.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/utils.py#L503-L533 | def get_gpu_memory_usage(ctx: List[mx.context.Context]) -> Dict[int, Tuple[int, int]]:
"""
Returns used and total memory for GPUs identified by the given context list.
:param ctx: List of MXNet context devices.
:return: Dictionary of device id mapping to a tuple of (memory used, memory total).
"""
... | [
"def",
"get_gpu_memory_usage",
"(",
"ctx",
":",
"List",
"[",
"mx",
".",
"context",
".",
"Context",
"]",
")",
"->",
"Dict",
"[",
"int",
",",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"if",
"isinstance",
"(",
"ctx",
",",
"mx",
".",
"context",
... | Returns used and total memory for GPUs identified by the given context list.
:param ctx: List of MXNet context devices.
:return: Dictionary of device id mapping to a tuple of (memory used, memory total). | [
"Returns",
"used",
"and",
"total",
"memory",
"for",
"GPUs",
"identified",
"by",
"the",
"given",
"context",
"list",
"."
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/aio/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/queue.py#L767-L785 | async def declareWorkerType(self, *args, **kwargs):
"""
Update a worker-type
Declare a workerType, supplying some details about it.
`declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are
possessed. For example, a request t... | [
"async",
"def",
"declareWorkerType",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"declareWorkerType\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kw... | Update a worker-type
Declare a workerType, supplying some details about it.
`declareWorkerType` allows updating one or more properties of a worker-type as long as the required scopes are
possessed. For example, a request to update the `gecko-b-1-w2008` worker-type within the `aws-provisioner-v... | [
"Update",
"a",
"worker",
"-",
"type"
] | python | train |
woolfson-group/isambard | isambard/ampal/pdb_parser.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/pdb_parser.py#L337-L374 | def proc_monomer(self, monomer_info, parent, mon_cls=False):
"""Processes a records into a `Monomer`.
Parameters
----------
monomer_info : (set, OrderedDict)
Labels and data for a monomer.
parent : ampal.Polymer
`Polymer` used to assign `ampal_parent` on ... | [
"def",
"proc_monomer",
"(",
"self",
",",
"monomer_info",
",",
"parent",
",",
"mon_cls",
"=",
"False",
")",
":",
"monomer_labels",
",",
"monomer_data",
"=",
"monomer_info",
"if",
"len",
"(",
"monomer_labels",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
... | Processes a records into a `Monomer`.
Parameters
----------
monomer_info : (set, OrderedDict)
Labels and data for a monomer.
parent : ampal.Polymer
`Polymer` used to assign `ampal_parent` on created
`Monomer`.
mon_cls : `Monomer class or subcl... | [
"Processes",
"a",
"records",
"into",
"a",
"Monomer",
"."
] | python | train |
COLORFULBOARD/revision | revision/client.py | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L235-L243 | def save(self, revision):
"""
:param revision:
:type revision: :class:`revision.data.Revision`
"""
if not isinstance(revision, Revision):
raise InvalidArgType()
self.state.update(revision) | [
"def",
"save",
"(",
"self",
",",
"revision",
")",
":",
"if",
"not",
"isinstance",
"(",
"revision",
",",
"Revision",
")",
":",
"raise",
"InvalidArgType",
"(",
")",
"self",
".",
"state",
".",
"update",
"(",
"revision",
")"
] | :param revision:
:type revision: :class:`revision.data.Revision` | [
":",
"param",
"revision",
":",
":",
"type",
"revision",
":",
":",
"class",
":",
"revision",
".",
"data",
".",
"Revision"
] | python | train |
ewels/MultiQC | multiqc/utils/report.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/report.py#L48-L187 | def get_filelist(run_module_names):
"""
Go through all supplied search directories and assembly a master
list of files to search. Then fire search functions for each file.
"""
# Prep search patterns
spatterns = [{},{},{},{},{},{},{}]
epatterns = [{}, {}]
ignored_patterns = []
for key... | [
"def",
"get_filelist",
"(",
"run_module_names",
")",
":",
"# Prep search patterns",
"spatterns",
"=",
"[",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"]",
"epatterns",
"=",
"[",
"{",
"}",
... | Go through all supplied search directories and assembly a master
list of files to search. Then fire search functions for each file. | [
"Go",
"through",
"all",
"supplied",
"search",
"directories",
"and",
"assembly",
"a",
"master",
"list",
"of",
"files",
"to",
"search",
".",
"Then",
"fire",
"search",
"functions",
"for",
"each",
"file",
"."
] | python | train |
rh-marketingops/dwm | dwm/wrappers.py | https://github.com/rh-marketingops/dwm/blob/66c7d18db857afbe5d574478ceaaad6159ae7469/dwm/wrappers.py#L6-L37 | def lookupAll(data, configFields, lookupType, db, histObj={}):
"""
Return a record after having cleaning rules of specified type applied to all fields in the config
:param dict data: single record (dictionary) to which cleaning rules should be applied
:param dict configFields: "fields" object from DWM ... | [
"def",
"lookupAll",
"(",
"data",
",",
"configFields",
",",
"lookupType",
",",
"db",
",",
"histObj",
"=",
"{",
"}",
")",
":",
"for",
"field",
"in",
"data",
".",
"keys",
"(",
")",
":",
"if",
"field",
"in",
"configFields",
".",
"keys",
"(",
")",
"and"... | Return a record after having cleaning rules of specified type applied to all fields in the config
:param dict data: single record (dictionary) to which cleaning rules should be applied
:param dict configFields: "fields" object from DWM config (see DataDictionary)
:param string lookupType: Type of lookup to... | [
"Return",
"a",
"record",
"after",
"having",
"cleaning",
"rules",
"of",
"specified",
"type",
"applied",
"to",
"all",
"fields",
"in",
"the",
"config"
] | python | train |
walkr/oi | setup.py | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/setup.py#L17-L31 | def read_long_description(readme_file):
""" Read package long description from README file """
try:
import pypandoc
except (ImportError, OSError) as e:
print('No pypandoc or pandoc: %s' % (e,))
if is_py3:
fh = open(readme_file, encoding='utf-8')
else:
... | [
"def",
"read_long_description",
"(",
"readme_file",
")",
":",
"try",
":",
"import",
"pypandoc",
"except",
"(",
"ImportError",
",",
"OSError",
")",
"as",
"e",
":",
"print",
"(",
"'No pypandoc or pandoc: %s'",
"%",
"(",
"e",
",",
")",
")",
"if",
"is_py3",
":... | Read package long description from README file | [
"Read",
"package",
"long",
"description",
"from",
"README",
"file"
] | python | train |
raymondEhlers/pachyderm | pachyderm/histogram.py | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/histogram.py#L602-L620 | def get_bin_edges_from_axis(axis) -> np.ndarray:
""" Get bin edges from a ROOT hist axis.
Note:
Doesn't include over- or underflow bins!
Args:
axis (ROOT.TAxis): Axis from which the bin edges should be extracted.
Returns:
Array containing the bin edges.
"""
# Don't incl... | [
"def",
"get_bin_edges_from_axis",
"(",
"axis",
")",
"->",
"np",
".",
"ndarray",
":",
"# Don't include over- or underflow bins",
"bins",
"=",
"range",
"(",
"1",
",",
"axis",
".",
"GetNbins",
"(",
")",
"+",
"1",
")",
"# Bin edges",
"bin_edges",
"=",
"np",
".",... | Get bin edges from a ROOT hist axis.
Note:
Doesn't include over- or underflow bins!
Args:
axis (ROOT.TAxis): Axis from which the bin edges should be extracted.
Returns:
Array containing the bin edges. | [
"Get",
"bin",
"edges",
"from",
"a",
"ROOT",
"hist",
"axis",
"."
] | python | train |
DataBiosphere/dsub | dsub/lib/param_util.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/param_util.py#L836-L877 | def age_to_create_time(age, from_time=None):
"""Compute the create time (UTC) for the list filter.
If the age is an integer value it is treated as a UTC date.
Otherwise the value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
a... | [
"def",
"age_to_create_time",
"(",
"age",
",",
"from_time",
"=",
"None",
")",
":",
"if",
"not",
"age",
":",
"return",
"None",
"if",
"not",
"from_time",
":",
"from_time",
"=",
"dsub_util",
".",
"replace_timezone",
"(",
"datetime",
".",
"datetime",
".",
"now"... | Compute the create time (UTC) for the list filter.
If the age is an integer value it is treated as a UTC date.
Otherwise the value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
age: A "<integer><unit>" string or integer value.
... | [
"Compute",
"the",
"create",
"time",
"(",
"UTC",
")",
"for",
"the",
"list",
"filter",
"."
] | python | valid |
aptivate/django-sortable-listview | sortable_listview/views.py | https://github.com/aptivate/django-sortable-listview/blob/9d5fa5847f0c3e80893780c6540e5098635ace9f/sortable_listview/views.py#L94-L106 | def get_querystring(self):
"""
Clean existing query string (GET parameters) by removing
arguments that we don't want to preserve (sort parameter, 'page')
"""
to_remove = self.get_querystring_parameter_to_remove()
query_string = urlparse(self.request.get_full_path()).query... | [
"def",
"get_querystring",
"(",
"self",
")",
":",
"to_remove",
"=",
"self",
".",
"get_querystring_parameter_to_remove",
"(",
")",
"query_string",
"=",
"urlparse",
"(",
"self",
".",
"request",
".",
"get_full_path",
"(",
")",
")",
".",
"query",
"query_dict",
"=",... | Clean existing query string (GET parameters) by removing
arguments that we don't want to preserve (sort parameter, 'page') | [
"Clean",
"existing",
"query",
"string",
"(",
"GET",
"parameters",
")",
"by",
"removing",
"arguments",
"that",
"we",
"don",
"t",
"want",
"to",
"preserve",
"(",
"sort",
"parameter",
"page",
")"
] | python | train |
ethereum/py-evm | eth/vm/stack.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L99-L107 | def dup(self, position: int) -> None:
"""
Perform a DUP operation on the stack.
"""
idx = -1 * position
try:
self.push(self.values[idx])
except IndexError:
raise InsufficientStack("Insufficient stack items for DUP{0}".format(position)) | [
"def",
"dup",
"(",
"self",
",",
"position",
":",
"int",
")",
"->",
"None",
":",
"idx",
"=",
"-",
"1",
"*",
"position",
"try",
":",
"self",
".",
"push",
"(",
"self",
".",
"values",
"[",
"idx",
"]",
")",
"except",
"IndexError",
":",
"raise",
"Insuf... | Perform a DUP operation on the stack. | [
"Perform",
"a",
"DUP",
"operation",
"on",
"the",
"stack",
"."
] | python | train |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/collection.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L325-L343 | def start_after(self, document_fields):
"""Start query after a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
docu... | [
"def",
"start_after",
"(",
"self",
",",
"document_fields",
")",
":",
"query",
"=",
"query_mod",
".",
"Query",
"(",
"self",
")",
"return",
"query",
".",
"start_after",
"(",
"document_fields",
")"
] | Start query after a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a docum... | [
"Start",
"query",
"after",
"a",
"cursor",
"with",
"this",
"collection",
"as",
"parent",
"."
] | python | train |
DataBiosphere/toil | src/toil/worker.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/worker.py#L46-L100 | def nextChainableJobGraph(jobGraph, jobStore):
"""Returns the next chainable jobGraph after this jobGraph if one
exists, or None if the chain must terminate.
"""
#If no more jobs to run or services not finished, quit
if len(jobGraph.stack) == 0 or len(jobGraph.services) > 0 or jobGraph.checkpoint !=... | [
"def",
"nextChainableJobGraph",
"(",
"jobGraph",
",",
"jobStore",
")",
":",
"#If no more jobs to run or services not finished, quit",
"if",
"len",
"(",
"jobGraph",
".",
"stack",
")",
"==",
"0",
"or",
"len",
"(",
"jobGraph",
".",
"services",
")",
">",
"0",
"or",
... | Returns the next chainable jobGraph after this jobGraph if one
exists, or None if the chain must terminate. | [
"Returns",
"the",
"next",
"chainable",
"jobGraph",
"after",
"this",
"jobGraph",
"if",
"one",
"exists",
"or",
"None",
"if",
"the",
"chain",
"must",
"terminate",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/nose/plugins/logcapture.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/logcapture.py#L225-L233 | def formatError(self, test, err):
"""Add captured log messages to error output.
"""
# logic flow copied from Capture.formatError
test.capturedLogging = records = self.formatLogRecords()
if not records:
return err
ec, ev, tb = err
return (ec, self.addCa... | [
"def",
"formatError",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"# logic flow copied from Capture.formatError",
"test",
".",
"capturedLogging",
"=",
"records",
"=",
"self",
".",
"formatLogRecords",
"(",
")",
"if",
"not",
"records",
":",
"return",
"err",
... | Add captured log messages to error output. | [
"Add",
"captured",
"log",
"messages",
"to",
"error",
"output",
"."
] | python | test |
materialsproject/pymatgen | pymatgen/__init__.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/__init__.py#L82-L104 | def loadfn(fname):
"""
Convenience method to perform quick loading of data from a filename. The
type of object returned depends the file type.
Args:
fname (string): A filename.
Returns:
Note that fname is matched using unix-style, i.e., fnmatch.
(Structure) if *POSCAR*/*CON... | [
"def",
"loadfn",
"(",
"fname",
")",
":",
"if",
"(",
"fnmatch",
"(",
"fname",
",",
"\"*POSCAR*\"",
")",
"or",
"fnmatch",
"(",
"fname",
",",
"\"*CONTCAR*\"",
")",
"or",
"\".cif\"",
"in",
"fname",
".",
"lower",
"(",
")",
")",
"or",
"fnmatch",
"(",
"fnam... | Convenience method to perform quick loading of data from a filename. The
type of object returned depends the file type.
Args:
fname (string): A filename.
Returns:
Note that fname is matched using unix-style, i.e., fnmatch.
(Structure) if *POSCAR*/*CONTCAR*/*.cif
(Vasprun) *... | [
"Convenience",
"method",
"to",
"perform",
"quick",
"loading",
"of",
"data",
"from",
"a",
"filename",
".",
"The",
"type",
"of",
"object",
"returned",
"depends",
"the",
"file",
"type",
"."
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L3382-L3386 | def ticket_comment_attachment_redact(self, ticket_id, comment_id, attachment_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/attachments#redact-comment-attachment"
api_path = "/api/v2/tickets/{ticket_id}/comments/{comment_id}/attachments/{attachment_id}/redact.json"
api_pa... | [
"def",
"ticket_comment_attachment_redact",
"(",
"self",
",",
"ticket_id",
",",
"comment_id",
",",
"attachment_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/tickets/{ticket_id}/comments/{comment_id}/attachments/{attachment_id}/redact.json\"",... | https://developer.zendesk.com/rest_api/docs/core/attachments#redact-comment-attachment | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"attachments#redact",
"-",
"comment",
"-",
"attachment"
] | python | train |
etcher-be/elib_miz | elib_miz/mission.py | https://github.com/etcher-be/elib_miz/blob/f28db58fadb2cd9341e0ae4d65101c0cc7d8f3d7/elib_miz/mission.py#L1773-L1777 | def radio_presets(self) -> typing.Iterator['FlyingUnit.RadioPresets']:
"""
Returns: generator over unit radio presets
"""
raise TypeError('unit #{}: {}'.format(self.unit_id, self.unit_name)) | [
"def",
"radio_presets",
"(",
"self",
")",
"->",
"typing",
".",
"Iterator",
"[",
"'FlyingUnit.RadioPresets'",
"]",
":",
"raise",
"TypeError",
"(",
"'unit #{}: {}'",
".",
"format",
"(",
"self",
".",
"unit_id",
",",
"self",
".",
"unit_name",
")",
")"
] | Returns: generator over unit radio presets | [
"Returns",
":",
"generator",
"over",
"unit",
"radio",
"presets"
] | python | train |
wummel/dosage | dosagelib/output.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/output.py#L69-L88 | def write(self, s, level=0, color=None):
"""Write message with indentation, context and optional timestamp."""
if level > self.level:
return
if self.timestamps:
timestamp = time.strftime(u'%H:%M:%S ')
else:
timestamp = u''
with lock:
... | [
"def",
"write",
"(",
"self",
",",
"s",
",",
"level",
"=",
"0",
",",
"color",
"=",
"None",
")",
":",
"if",
"level",
">",
"self",
".",
"level",
":",
"return",
"if",
"self",
".",
"timestamps",
":",
"timestamp",
"=",
"time",
".",
"strftime",
"(",
"u'... | Write message with indentation, context and optional timestamp. | [
"Write",
"message",
"with",
"indentation",
"context",
"and",
"optional",
"timestamp",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/assistant_v2.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v2.py#L1009-L1014 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'system') and self.system is not None:
_dict['system'] = self.system._to_dict()
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'system'",
")",
"and",
"self",
".",
"system",
"is",
"not",
"None",
":",
"_dict",
"[",
"'system'",
"]",
"=",
"self",
".",
"system",
".",
"_to_dict"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
trivago/Protector | protector/parser/query_parser.py | https://github.com/trivago/Protector/blob/7ebe7bde965e27737b961a0cb5740724d174fdc7/protector/parser/query_parser.py#L139-L160 | def create_select_query(self, tokens):
"""
Parse tokens of select query
:param tokens: A list of InfluxDB query tokens
"""
if not tokens[Keyword.SELECT]:
return None
if not tokens[Keyword.FROM]:
return None
return SelectQuery(
... | [
"def",
"create_select_query",
"(",
"self",
",",
"tokens",
")",
":",
"if",
"not",
"tokens",
"[",
"Keyword",
".",
"SELECT",
"]",
":",
"return",
"None",
"if",
"not",
"tokens",
"[",
"Keyword",
".",
"FROM",
"]",
":",
"return",
"None",
"return",
"SelectQuery",... | Parse tokens of select query
:param tokens: A list of InfluxDB query tokens | [
"Parse",
"tokens",
"of",
"select",
"query",
":",
"param",
"tokens",
":",
"A",
"list",
"of",
"InfluxDB",
"query",
"tokens"
] | python | valid |
xhtml2pdf/xhtml2pdf | xhtml2pdf/reportlab_paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1461-L1655 | def drawPara(self, debug=0):
"""Draws a paragraph according to the given style.
Returns the final y position at the bottom. Not safe for
paragraphs without spaces e.g. Japanese; wrapping
algorithm will go infinite."""
if self.debug:
print (id(self), "drawPara", self.... | [
"def",
"drawPara",
"(",
"self",
",",
"debug",
"=",
"0",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"id",
"(",
"self",
")",
",",
"\"drawPara\"",
",",
"self",
".",
"blPara",
".",
"kind",
")",
"#stash the key facts locally for speed",
"canvas"... | Draws a paragraph according to the given style.
Returns the final y position at the bottom. Not safe for
paragraphs without spaces e.g. Japanese; wrapping
algorithm will go infinite. | [
"Draws",
"a",
"paragraph",
"according",
"to",
"the",
"given",
"style",
".",
"Returns",
"the",
"final",
"y",
"position",
"at",
"the",
"bottom",
".",
"Not",
"safe",
"for",
"paragraphs",
"without",
"spaces",
"e",
".",
"g",
".",
"Japanese",
";",
"wrapping",
... | python | train |
apple/turicreate | src/external/xgboost/python-package/xgboost/libpath.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/libpath.py#L13-L45 | def find_lib_path():
"""Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost
"""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
# make pythonpack hack: copy this directory one... | [
"def",
"find_lib_path",
"(",
")",
":",
"curr_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"__file__",
")",
")",
")",
"# make pythonpack hack: copy this directory one le... | Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost | [
"Load",
"find",
"the",
"path",
"to",
"xgboost",
"dynamic",
"library",
"files",
"."
] | python | train |
theno/fabsetup | fabsetup/fabfile/setup/service/__init__.py | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabfile/setup/service/__init__.py#L191-L233 | def vnc_raspi_osmc():
'''Install and configure dispmanx_vnc server on osmc (raspberry pi).
More Infos:
* https://github.com/patrikolausson/dispmanx_vnc
* https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517
* tightvnc:
* http://raspberry.tips/raspberrypi-einstei... | [
"def",
"vnc_raspi_osmc",
"(",
")",
":",
"print",
"(",
"blue",
"(",
"'Install dependencies'",
")",
")",
"install_packages",
"(",
"[",
"'git'",
",",
"'build-essential'",
",",
"'rbp-userland-dev-osmc'",
",",
"'libvncserver-dev'",
",",
"'libconfig++-dev'",
",",
"]",
"... | Install and configure dispmanx_vnc server on osmc (raspberry pi).
More Infos:
* https://github.com/patrikolausson/dispmanx_vnc
* https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517
* tightvnc:
* http://raspberry.tips/raspberrypi-einsteiger/raspberry-pi-einsteiger-g... | [
"Install",
"and",
"configure",
"dispmanx_vnc",
"server",
"on",
"osmc",
"(",
"raspberry",
"pi",
")",
"."
] | python | train |
roamanalytics/mittens | mittens/np_mittens.py | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/np_mittens.py#L176-L200 | def get_step(self, grad):
"""Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optim... | [
"def",
"get_step",
"(",
"self",
",",
"grad",
")",
":",
"if",
"self",
".",
"_momentum",
"is",
"None",
":",
"self",
".",
"_momentum",
"=",
"self",
".",
"initial_accumulator_value",
"*",
"np",
".",
"ones_like",
"(",
"grad",
")",
"self",
".",
"_momentum",
... | Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optimizer = AdaGradOptimizer(0.01)
... | [
"Computes",
"the",
"step",
"to",
"take",
"for",
"the",
"next",
"gradient",
"descent",
"update",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.