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 |
|---|---|---|---|---|---|---|---|---|
Linaro/squad | squad/core/management/commands/users.py | https://github.com/Linaro/squad/blob/27da5375e119312a86f231df95f99c979b9f48f0/squad/core/management/commands/users.py#L194-L206 | def handle_details(self, username):
""" Print user details """
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise CommandError("Unable to find user '%s'" % username)
self.stdout.write("username : %s" % username)
self.stdout... | [
"def",
"handle_details",
"(",
"self",
",",
"username",
")",
":",
"try",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"raise",
"CommandError",
"(",
"\"Unable to find... | Print user details | [
"Print",
"user",
"details"
] | python | train |
pantsbuild/pants | src/python/pants/pantsd/service/fs_event_service.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/service/fs_event_service.py#L86-L99 | def register_handler(self, name, metadata, callback):
"""Register subscriptions and their event handlers.
:param str name: the subscription name as used by watchman
:param dict metadata: a dictionary of metadata to be serialized and passed to the watchman
subscribe command. t... | [
"def",
"register_handler",
"(",
"self",
",",
"name",
",",
"metadata",
",",
"callback",
")",
":",
"assert",
"name",
"not",
"in",
"self",
".",
"_handlers",
",",
"'duplicate handler name: {}'",
".",
"format",
"(",
"name",
")",
"assert",
"(",
"isinstance",
"(",
... | Register subscriptions and their event handlers.
:param str name: the subscription name as used by watchman
:param dict metadata: a dictionary of metadata to be serialized and passed to the watchman
subscribe command. this should include the match expression as well
... | [
"Register",
"subscriptions",
"and",
"their",
"event",
"handlers",
"."
] | python | train |
numenta/htmresearch | projects/l2_pooling/topology_experiments.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/topology_experiments.py#L40-L116 | def runExperimentPool(numObjects,
numLocations,
numFeatures,
numColumns,
networkType=["MultipleL4L2Columns"],
longDistanceConnectionsRange = [0.0],
numWorkers=7,
nTri... | [
"def",
"runExperimentPool",
"(",
"numObjects",
",",
"numLocations",
",",
"numFeatures",
",",
"numColumns",
",",
"networkType",
"=",
"[",
"\"MultipleL4L2Columns\"",
"]",
",",
"longDistanceConnectionsRange",
"=",
"[",
"0.0",
"]",
",",
"numWorkers",
"=",
"7",
",",
... | Allows you to run a number of experiments using multiple processes.
For each parameter except numWorkers, pass in a list containing valid values
for that parameter. The cross product of everything is run, and each
combination is run nTrials times.
Returns a list of dict containing detailed results from each ex... | [
"Allows",
"you",
"to",
"run",
"a",
"number",
"of",
"experiments",
"using",
"multiple",
"processes",
".",
"For",
"each",
"parameter",
"except",
"numWorkers",
"pass",
"in",
"a",
"list",
"containing",
"valid",
"values",
"for",
"that",
"parameter",
".",
"The",
"... | python | train |
kiwiz/gkeepapi | gkeepapi/__init__.py | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L431-L444 | def history(self, storage_version):
"""Get reminder changes.
"""
params = {
"storageVersion": storage_version,
"includeSnoozePresetUpdates": True,
}
params.update(self.static_params)
return self.send(
url=self._base_url + 'history',
... | [
"def",
"history",
"(",
"self",
",",
"storage_version",
")",
":",
"params",
"=",
"{",
"\"storageVersion\"",
":",
"storage_version",
",",
"\"includeSnoozePresetUpdates\"",
":",
"True",
",",
"}",
"params",
".",
"update",
"(",
"self",
".",
"static_params",
")",
"r... | Get reminder changes. | [
"Get",
"reminder",
"changes",
"."
] | python | train |
projectshift/shift-schema | shiftschema/schema.py | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/schema.py#L199-L222 | def filter_properties(self, model, context=None):
"""
Filter simple properties
Runs filters on simple properties changing them in place.
:param model: object or dict
:param context: object, dict or None
:return: None
"""
if model is None:
retu... | [
"def",
"filter_properties",
"(",
"self",
",",
"model",
",",
"context",
"=",
"None",
")",
":",
"if",
"model",
"is",
"None",
":",
"return",
"for",
"property_name",
"in",
"self",
".",
"properties",
":",
"prop",
"=",
"self",
".",
"properties",
"[",
"property... | Filter simple properties
Runs filters on simple properties changing them in place.
:param model: object or dict
:param context: object, dict or None
:return: None | [
"Filter",
"simple",
"properties",
"Runs",
"filters",
"on",
"simple",
"properties",
"changing",
"them",
"in",
"place",
".",
":",
"param",
"model",
":",
"object",
"or",
"dict",
":",
"param",
"context",
":",
"object",
"dict",
"or",
"None",
":",
"return",
":",... | python | train |
MycroftAI/mycroft-precise | precise/util.py | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/util.py#L98-L101 | def find_wavs(folder: str) -> Tuple[List[str], List[str]]:
"""Finds wake-word and not-wake-word wavs in folder"""
return (glob_all(join(folder, 'wake-word'), '*.wav'),
glob_all(join(folder, 'not-wake-word'), '*.wav')) | [
"def",
"find_wavs",
"(",
"folder",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"return",
"(",
"glob_all",
"(",
"join",
"(",
"folder",
",",
"'wake-word'",
")",
",",
"'*.wav'",
")",
",",
"gl... | Finds wake-word and not-wake-word wavs in folder | [
"Finds",
"wake",
"-",
"word",
"and",
"not",
"-",
"wake",
"-",
"word",
"wavs",
"in",
"folder"
] | python | train |
GiulioRossetti/dynetx | dynetx/readwrite/edgelist.py | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/readwrite/edgelist.py#L71-L91 | def read_interactions(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False):
"""Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filenam... | [
"def",
"read_interactions",
"(",
"path",
",",
"comments",
"=",
"\"#\"",
",",
"directed",
"=",
"False",
",",
"delimiter",
"=",
"None",
",",
"nodetype",
"=",
"None",
",",
"timestamptype",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"keys",
"=",
"Fal... | Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filename
delimiter : character
Column delimiter | [
"Read",
"a",
"DyNetx",
"graph",
"from",
"interaction",
"list",
"format",
"."
] | python | train |
chop-dbhi/varify | varify/context_processors.py | https://github.com/chop-dbhi/varify/blob/5dc721e49ed9bd3582f4b117785fdd1a8b6ba777/varify/context_processors.py#L8-L16 | def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
... | [
"def",
"static",
"(",
"request",
")",
":",
"static_url",
"=",
"settings",
".",
"STATIC_URL",
"prefix",
"=",
"'src'",
"if",
"settings",
".",
"DEBUG",
"else",
"'min'",
"return",
"{",
"'CSS_URL'",
":",
"os",
".",
"path",
".",
"join",
"(",
"static_url",
",",... | Shorthand static URLs. In debug mode, the JavaScript is not minified. | [
"Shorthand",
"static",
"URLs",
".",
"In",
"debug",
"mode",
"the",
"JavaScript",
"is",
"not",
"minified",
"."
] | python | train |
learningequality/ricecooker | ricecooker/utils/metadata_provider.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/metadata_provider.py#L144-L149 | def get_metadata_file_path(channeldir, filename):
"""
Return the path to the metadata file named `filename` that is a sibling of `channeldir`.
"""
channelparentdir, channeldirname = os.path.split(channeldir)
return os.path.join(channelparentdir, filename) | [
"def",
"get_metadata_file_path",
"(",
"channeldir",
",",
"filename",
")",
":",
"channelparentdir",
",",
"channeldirname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"channeldir",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"channelparentdir",
",",
"f... | Return the path to the metadata file named `filename` that is a sibling of `channeldir`. | [
"Return",
"the",
"path",
"to",
"the",
"metadata",
"file",
"named",
"filename",
"that",
"is",
"a",
"sibling",
"of",
"channeldir",
"."
] | python | train |
nickpandolfi/Cyther | cyther/launcher.py | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/launcher.py#L54-L62 | def getOutput(self):
"""
Returns the combined output of stdout and stderr
"""
output = self.stdout
if self.stdout:
output += '\r\n'
output += self.stderr
return output | [
"def",
"getOutput",
"(",
"self",
")",
":",
"output",
"=",
"self",
".",
"stdout",
"if",
"self",
".",
"stdout",
":",
"output",
"+=",
"'\\r\\n'",
"output",
"+=",
"self",
".",
"stderr",
"return",
"output"
] | Returns the combined output of stdout and stderr | [
"Returns",
"the",
"combined",
"output",
"of",
"stdout",
"and",
"stderr"
] | python | train |
Clinical-Genomics/scout | scout/commands/update/institute.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/commands/update/institute.py#L30-L49 | def institute(context, institute_id, sanger_recipient, coverage_cutoff, frequency_cutoff,
display_name, remove_sanger):
"""
Update an institute
"""
adapter = context.obj['adapter']
LOG.info("Running scout update institute")
try:
adapter.update_institute(
i... | [
"def",
"institute",
"(",
"context",
",",
"institute_id",
",",
"sanger_recipient",
",",
"coverage_cutoff",
",",
"frequency_cutoff",
",",
"display_name",
",",
"remove_sanger",
")",
":",
"adapter",
"=",
"context",
".",
"obj",
"[",
"'adapter'",
"]",
"LOG",
".",
"i... | Update an institute | [
"Update",
"an",
"institute"
] | python | test |
docker/docker-py | docker/api/image.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/image.py#L421-L480 | def push(self, repository, tag=None, stream=False, auth_config=None,
decode=False):
"""
Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional ta... | [
"def",
"push",
"(",
"self",
",",
"repository",
",",
"tag",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"auth_config",
"=",
"None",
",",
"decode",
"=",
"False",
")",
":",
"if",
"not",
"tag",
":",
"repository",
",",
"tag",
"=",
"utils",
".",
"pars... | Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional tag to push
stream (bool): Stream the output as a blocking generator
auth_config (dict): Overri... | [
"Push",
"an",
"image",
"or",
"a",
"repository",
"to",
"the",
"registry",
".",
"Similar",
"to",
"the",
"docker",
"push",
"command",
"."
] | python | train |
numenta/nupic | examples/opf/tools/sp_plotter.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/examples/opf/tools/sp_plotter.py#L194-L206 | def getRandomWithMods(inputSpace, maxChanges):
""" Returns a random selection from the inputSpace with randomly modified
up to maxChanges number of bits.
"""
size = len(inputSpace)
ind = np.random.random_integers(0, size-1, 1)[0]
value = copy.deepcopy(inputSpace[ind])
if maxChanges == 0:
return valu... | [
"def",
"getRandomWithMods",
"(",
"inputSpace",
",",
"maxChanges",
")",
":",
"size",
"=",
"len",
"(",
"inputSpace",
")",
"ind",
"=",
"np",
".",
"random",
".",
"random_integers",
"(",
"0",
",",
"size",
"-",
"1",
",",
"1",
")",
"[",
"0",
"]",
"value",
... | Returns a random selection from the inputSpace with randomly modified
up to maxChanges number of bits. | [
"Returns",
"a",
"random",
"selection",
"from",
"the",
"inputSpace",
"with",
"randomly",
"modified",
"up",
"to",
"maxChanges",
"number",
"of",
"bits",
"."
] | python | valid |
summa-tx/riemann | riemann/encoding/cashaddr.py | https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/encoding/cashaddr.py#L29-L45 | def encode(data):
'''
bytes -> str
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
data = convertbits(data, 8, 5)
checksum = calculate_checksum(riemann.net... | [
"def",
"encode",
"(",
"data",
")",
":",
"if",
"riemann",
".",
"network",
".",
"CASHADDR_PREFIX",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Network {} does not support cashaddresses.'",
".",
"format",
"(",
"riemann",
".",
"get_current_network_name",
"(",
")"... | bytes -> str | [
"bytes",
"-",
">",
"str"
] | python | train |
Gandi/gandi.cli | gandi/cli/modules/network.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/network.py#L46-L53 | def update(cls, resource, params, background=False):
""" Update this IP """
cls.echo('Updating your IP')
result = cls.call('hosting.ip.update', cls.usable_id(resource),
params)
if not background:
cls.display_progress(result)
return result | [
"def",
"update",
"(",
"cls",
",",
"resource",
",",
"params",
",",
"background",
"=",
"False",
")",
":",
"cls",
".",
"echo",
"(",
"'Updating your IP'",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.ip.update'",
",",
"cls",
".",
"usable_id",
"(",
... | Update this IP | [
"Update",
"this",
"IP"
] | python | train |
smartfile/client-python | smartfile/sync.py | https://github.com/smartfile/client-python/blob/f9ccc40a2870df447c65b53dc0747e37cab62d63/smartfile/sync.py#L67-L72 | def signature(self, block_size=None):
"Requests a signature for remote file via API."
kwargs = {}
if block_size:
kwargs['block_size'] = block_size
return self.api.get('path/sync/signature', self.path, **kwargs) | [
"def",
"signature",
"(",
"self",
",",
"block_size",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"block_size",
":",
"kwargs",
"[",
"'block_size'",
"]",
"=",
"block_size",
"return",
"self",
".",
"api",
".",
"get",
"(",
"'path/sync/signature'",
",... | Requests a signature for remote file via API. | [
"Requests",
"a",
"signature",
"for",
"remote",
"file",
"via",
"API",
"."
] | python | train |
maxalbert/tohu | tohu/v6/base.py | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/base.py#L121-L129 | def reset(self, seed):
"""
Reset this generator's seed generator and any clones.
"""
logger.debug(f'Resetting {self} (seed={seed})')
self.seed_generator.reset(seed)
for c in self.clones:
c.reset(seed) | [
"def",
"reset",
"(",
"self",
",",
"seed",
")",
":",
"logger",
".",
"debug",
"(",
"f'Resetting {self} (seed={seed})'",
")",
"self",
".",
"seed_generator",
".",
"reset",
"(",
"seed",
")",
"for",
"c",
"in",
"self",
".",
"clones",
":",
"c",
".",
"reset",
"... | Reset this generator's seed generator and any clones. | [
"Reset",
"this",
"generator",
"s",
"seed",
"generator",
"and",
"any",
"clones",
"."
] | python | train |
dswah/pyGAM | pygam/terms.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1275-L1298 | def build_columns(self, X, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse arr... | [
"def",
"build_columns",
"(",
"self",
",",
"X",
",",
"verbose",
"=",
"False",
")",
":",
"splines",
"=",
"self",
".",
"_terms",
"[",
"0",
"]",
".",
"build_columns",
"(",
"X",
",",
"verbose",
"=",
"verbose",
")",
"for",
"term",
"in",
"self",
".",
"_te... | construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse array with n rows | [
"construct",
"the",
"model",
"matrix",
"columns",
"for",
"the",
"term"
] | python | train |
robotools/fontParts | Lib/fontParts/ui.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/ui.py#L87-L99 | def Message(message, title='FontParts', informativeText=""):
"""
An message dialog.
Optionally a `message`, `title` and `informativeText` can be provided.
::
from fontParts.ui import Message
print(Message("This is a message"))
"""
return dispatcher["Message"](message=message, ... | [
"def",
"Message",
"(",
"message",
",",
"title",
"=",
"'FontParts'",
",",
"informativeText",
"=",
"\"\"",
")",
":",
"return",
"dispatcher",
"[",
"\"Message\"",
"]",
"(",
"message",
"=",
"message",
",",
"title",
"=",
"title",
",",
"informativeText",
"=",
"in... | An message dialog.
Optionally a `message`, `title` and `informativeText` can be provided.
::
from fontParts.ui import Message
print(Message("This is a message")) | [
"An",
"message",
"dialog",
".",
"Optionally",
"a",
"message",
"title",
"and",
"informativeText",
"can",
"be",
"provided",
"."
] | python | train |
adamziel/python_translate | python_translate/loaders.py | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L63-L77 | def assert_valid_path(self, path):
"""
Ensures that the path represents an existing file
@type path: str
@param path: path to check
"""
if not isinstance(path, str):
raise NotFoundResourceException(
"Resource passed to load() method must be a... | [
"def",
"assert_valid_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"raise",
"NotFoundResourceException",
"(",
"\"Resource passed to load() method must be a file path\"",
")",
"if",
"not",
"os",
".",
"path"... | Ensures that the path represents an existing file
@type path: str
@param path: path to check | [
"Ensures",
"that",
"the",
"path",
"represents",
"an",
"existing",
"file"
] | python | train |
wmayner/pyphi | pyphi/validate.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L238-L258 | def blackbox_and_coarse_grain(blackbox, coarse_grain):
"""Validate that a coarse-graining properly combines the outputs of a
blackboxing.
"""
if blackbox is None:
return
for box in blackbox.partition:
# Outputs of the box
outputs = set(box) & set(blackbox.output_indices)
... | [
"def",
"blackbox_and_coarse_grain",
"(",
"blackbox",
",",
"coarse_grain",
")",
":",
"if",
"blackbox",
"is",
"None",
":",
"return",
"for",
"box",
"in",
"blackbox",
".",
"partition",
":",
"# Outputs of the box",
"outputs",
"=",
"set",
"(",
"box",
")",
"&",
"se... | Validate that a coarse-graining properly combines the outputs of a
blackboxing. | [
"Validate",
"that",
"a",
"coarse",
"-",
"graining",
"properly",
"combines",
"the",
"outputs",
"of",
"a",
"blackboxing",
"."
] | python | train |
divio/aldryn-apphooks-config | aldryn_apphooks_config/admin.py | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/admin.py#L140-L164 | def get_form(self, request, obj=None, **kwargs):
"""
Provides a flexible way to get the right form according to the context
For the add view it checks whether the app_config is set; if not, a special form
to select the namespace is shown, which is reloaded after namespace selection.
... | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"super",
"(",
"ModelAppHookConfig",
",",
"self",
")",
".",
"get_form",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")"... | Provides a flexible way to get the right form according to the context
For the add view it checks whether the app_config is set; if not, a special form
to select the namespace is shown, which is reloaded after namespace selection.
If only one namespace exists, the current is selected and the no... | [
"Provides",
"a",
"flexible",
"way",
"to",
"get",
"the",
"right",
"form",
"according",
"to",
"the",
"context"
] | python | train |
opencast/pyCA | pyca/ui/jsonapi.py | https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/ui/jsonapi.py#L69-L78 | def event(uid):
'''Return a specific events JSON
'''
db = get_session()
event = db.query(RecordedEvent).filter(RecordedEvent.uid == uid).first() \
or db.query(UpcomingEvent).filter(UpcomingEvent.uid == uid).first()
if event:
return make_data_response(event.serialize())
return ma... | [
"def",
"event",
"(",
"uid",
")",
":",
"db",
"=",
"get_session",
"(",
")",
"event",
"=",
"db",
".",
"query",
"(",
"RecordedEvent",
")",
".",
"filter",
"(",
"RecordedEvent",
".",
"uid",
"==",
"uid",
")",
".",
"first",
"(",
")",
"or",
"db",
".",
"qu... | Return a specific events JSON | [
"Return",
"a",
"specific",
"events",
"JSON"
] | python | test |
tariqdaouda/pyGeno | pyGeno/SNP.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/SNP.py#L18-L25 | def getSNPSetsList() :
"""Return the names of all imported snp sets"""
import rabaDB.filters as rfilt
f = rfilt.RabaQuery(SNPMaster)
names = []
for g in f.iterRun() :
names.append(g.setName)
return names | [
"def",
"getSNPSetsList",
"(",
")",
":",
"import",
"rabaDB",
".",
"filters",
"as",
"rfilt",
"f",
"=",
"rfilt",
".",
"RabaQuery",
"(",
"SNPMaster",
")",
"names",
"=",
"[",
"]",
"for",
"g",
"in",
"f",
".",
"iterRun",
"(",
")",
":",
"names",
".",
"appe... | Return the names of all imported snp sets | [
"Return",
"the",
"names",
"of",
"all",
"imported",
"snp",
"sets"
] | python | train |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L6083-L6093 | def getSkeletalBoneDataCompressed(self, action, eMotionRange, pvCompressedData, unCompressedSize):
"""
Reads the state of the skeletal bone data in a compressed form that is suitable for
sending over the network. The required buffer size will never exceed ( sizeof(VR_BoneTransform_t)*boneCount +... | [
"def",
"getSkeletalBoneDataCompressed",
"(",
"self",
",",
"action",
",",
"eMotionRange",
",",
"pvCompressedData",
",",
"unCompressedSize",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getSkeletalBoneDataCompressed",
"punRequiredCompressedSize",
"=",
"c_uint... | Reads the state of the skeletal bone data in a compressed form that is suitable for
sending over the network. The required buffer size will never exceed ( sizeof(VR_BoneTransform_t)*boneCount + 2).
Usually the size will be much smaller. | [
"Reads",
"the",
"state",
"of",
"the",
"skeletal",
"bone",
"data",
"in",
"a",
"compressed",
"form",
"that",
"is",
"suitable",
"for",
"sending",
"over",
"the",
"network",
".",
"The",
"required",
"buffer",
"size",
"will",
"never",
"exceed",
"(",
"sizeof",
"("... | python | train |
Alignak-monitoring/alignak | alignak/dependencynode.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L602-L655 | def eval_simple_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
"""Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts li... | [
"def",
"eval_simple_cor_pattern",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
",",
"hostgroups",
",",
"servicegroups",
",",
"running",
"=",
"False",
")",
":",
"node",
"=",
"DependencyNode",
"(",
")",
"pattern",
"=",
"self",
".",
"eval_xof_pat... | Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific se... | [
"Parse",
"and",
"build",
"recursively",
"a",
"tree",
"of",
"DependencyNode",
"from",
"a",
"simple",
"pattern"
] | python | train |
sirfoga/pyhal | hal/strings/models.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/strings/models.py#L43-L53 | def convert_accents(self):
"""Removes accents from text
:return: input with converted accents chars
"""
nkfd_form = unicodedata.normalize('NFKD', self.string)
return "".join([
char
for char in nkfd_form
if not unicodedata.combining(char)
... | [
"def",
"convert_accents",
"(",
"self",
")",
":",
"nkfd_form",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"self",
".",
"string",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"char",
"for",
"char",
"in",
"nkfd_form",
"if",
"not",
"unicodeda... | Removes accents from text
:return: input with converted accents chars | [
"Removes",
"accents",
"from",
"text"
] | python | train |
linkedin/luminol | src/luminol/utils.py | https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/utils.py#L66-L82 | def to_epoch(t_str):
"""
Covert a timestamp string to an epoch number.
:param str t_str: a timestamp string.
:return int: epoch number of the timestamp.
"""
try:
t = float(t_str)
return t
except ValueError:
for format in constants.TIMESTAMP_STR_FORMATS:
tr... | [
"def",
"to_epoch",
"(",
"t_str",
")",
":",
"try",
":",
"t",
"=",
"float",
"(",
"t_str",
")",
"return",
"t",
"except",
"ValueError",
":",
"for",
"format",
"in",
"constants",
".",
"TIMESTAMP_STR_FORMATS",
":",
"try",
":",
"t",
"=",
"datetime",
".",
"date... | Covert a timestamp string to an epoch number.
:param str t_str: a timestamp string.
:return int: epoch number of the timestamp. | [
"Covert",
"a",
"timestamp",
"string",
"to",
"an",
"epoch",
"number",
".",
":",
"param",
"str",
"t_str",
":",
"a",
"timestamp",
"string",
".",
":",
"return",
"int",
":",
"epoch",
"number",
"of",
"the",
"timestamp",
"."
] | python | train |
mcs07/MolVS | molvs/standardize.py | https://github.com/mcs07/MolVS/blob/d815fe52d160abcecbcbf117e6437bf727dbd8ad/molvs/standardize.py#L281-L286 | def canonicalize_tautomer(self):
"""
:returns: A callable :class:`~molvs.tautomer.TautomerCanonicalizer` instance.
"""
return TautomerCanonicalizer(transforms=self.tautomer_transforms, scores=self.tautomer_scores,
max_tautomers=self.max_tautomers) | [
"def",
"canonicalize_tautomer",
"(",
"self",
")",
":",
"return",
"TautomerCanonicalizer",
"(",
"transforms",
"=",
"self",
".",
"tautomer_transforms",
",",
"scores",
"=",
"self",
".",
"tautomer_scores",
",",
"max_tautomers",
"=",
"self",
".",
"max_tautomers",
")"
] | :returns: A callable :class:`~molvs.tautomer.TautomerCanonicalizer` instance. | [
":",
"returns",
":",
"A",
"callable",
":",
"class",
":",
"~molvs",
".",
"tautomer",
".",
"TautomerCanonicalizer",
"instance",
"."
] | python | test |
zhanglab/psamm | psamm/command.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/command.py#L248-L268 | def _create_executor(self, handler, args, cpus_per_worker=1):
"""Return a new :class:`.Executor` instance."""
if self._args.parallel > 0:
workers = self._args.parallel
else:
try:
workers = mp.cpu_count() // cpus_per_worker
except NotImplemented... | [
"def",
"_create_executor",
"(",
"self",
",",
"handler",
",",
"args",
",",
"cpus_per_worker",
"=",
"1",
")",
":",
"if",
"self",
".",
"_args",
".",
"parallel",
">",
"0",
":",
"workers",
"=",
"self",
".",
"_args",
".",
"parallel",
"else",
":",
"try",
":... | Return a new :class:`.Executor` instance. | [
"Return",
"a",
"new",
":",
"class",
":",
".",
"Executor",
"instance",
"."
] | python | train |
dhermes/bezier | docs/make_images.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1002-L1033 | def classify_intersection7(s, curve1a, curve1b, curve2):
"""Image for :func:`._surface_helpers.classify_intersection` docstring."""
if NO_IMAGES:
return
surface1 = bezier.Surface.from_nodes(
np.asfortranarray(
[
[0.0, 4.5, 9.0, 0.0, 4.5, 0.0],
[0.... | [
"def",
"classify_intersection7",
"(",
"s",
",",
"curve1a",
",",
"curve1b",
",",
"curve2",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"surface1",
"=",
"bezier",
".",
"Surface",
".",
"from_nodes",
"(",
"np",
".",
"asfortranarray",
"(",
"[",
"[",
"0.0",
",... | Image for :func:`._surface_helpers.classify_intersection` docstring. | [
"Image",
"for",
":",
"func",
":",
".",
"_surface_helpers",
".",
"classify_intersection",
"docstring",
"."
] | python | train |
woolfson-group/isambard | isambard/add_ons/knobs_into_holes.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/add_ons/knobs_into_holes.py#L655-L677 | def tag_residues_with_heptad_register(helices):
""" tags Residues in input helices with heptad register. (Helices not required to be the same length).
Parameters
----------
helices : [Polypeptide]
Returns
-------
None
"""
base_reg = 'abcdefg'
start, end = start_and_end_of_refer... | [
"def",
"tag_residues_with_heptad_register",
"(",
"helices",
")",
":",
"base_reg",
"=",
"'abcdefg'",
"start",
",",
"end",
"=",
"start_and_end_of_reference_axis",
"(",
"helices",
")",
"for",
"h",
"in",
"helices",
":",
"ref_axis",
"=",
"gen_reference_primitive",
"(",
... | tags Residues in input helices with heptad register. (Helices not required to be the same length).
Parameters
----------
helices : [Polypeptide]
Returns
-------
None | [
"tags",
"Residues",
"in",
"input",
"helices",
"with",
"heptad",
"register",
".",
"(",
"Helices",
"not",
"required",
"to",
"be",
"the",
"same",
"length",
")",
"."
] | python | train |
benfred/implicit | implicit/datasets/movielens.py | https://github.com/benfred/implicit/blob/6b16c50d1d514a814f2e5b8cf2a829ff23dbba63/implicit/datasets/movielens.py#L67-L74 | def _read_dataframes_20M(path):
""" reads in the movielens 20M"""
import pandas
ratings = pandas.read_csv(os.path.join(path, "ratings.csv"))
movies = pandas.read_csv(os.path.join(path, "movies.csv"))
return ratings, movies | [
"def",
"_read_dataframes_20M",
"(",
"path",
")",
":",
"import",
"pandas",
"ratings",
"=",
"pandas",
".",
"read_csv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"ratings.csv\"",
")",
")",
"movies",
"=",
"pandas",
".",
"read_csv",
"(",
"os",
... | reads in the movielens 20M | [
"reads",
"in",
"the",
"movielens",
"20M"
] | python | train |
ioos/pyoos | pyoos/parsers/hads.py | https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/hads.py#L160-L246 | def _parse_metadata(self, metadata):
"""
Transforms raw HADS metadata into a dictionary (station code -> props)
"""
retval = {}
# these are the first keys, afterwards follows a var-len list of variables/props
# first key always blank so skip it
field_keys = [
... | [
"def",
"_parse_metadata",
"(",
"self",
",",
"metadata",
")",
":",
"retval",
"=",
"{",
"}",
"# these are the first keys, afterwards follows a var-len list of variables/props",
"# first key always blank so skip it",
"field_keys",
"=",
"[",
"\"nesdis_id\"",
",",
"\"nwsli\"",
","... | Transforms raw HADS metadata into a dictionary (station code -> props) | [
"Transforms",
"raw",
"HADS",
"metadata",
"into",
"a",
"dictionary",
"(",
"station",
"code",
"-",
">",
"props",
")"
] | python | train |
svinota/mdns | mdns/zeroconf.py | https://github.com/svinota/mdns/blob/295f6407132616a0ff7401124b9057d89555f91d/mdns/zeroconf.py#L838-L844 | def read_utf(self, offset, len):
"""Reads a UTF-8 string of a given length from the packet"""
try:
result = self.data[offset:offset + len].decode('utf-8')
except UnicodeDecodeError:
result = str('')
return result | [
"def",
"read_utf",
"(",
"self",
",",
"offset",
",",
"len",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"data",
"[",
"offset",
":",
"offset",
"+",
"len",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"result",
"="... | Reads a UTF-8 string of a given length from the packet | [
"Reads",
"a",
"UTF",
"-",
"8",
"string",
"of",
"a",
"given",
"length",
"from",
"the",
"packet"
] | python | train |
yunojuno-archive/django-inbound-email | inbound_email/backends/mandrill.py | https://github.com/yunojuno-archive/django-inbound-email/blob/c0c1186fc2ced56b43d6b223e73cd5e8700dfc48/inbound_email/backends/mandrill.py#L90-L99 | def _get_recipients(self, array):
"""Returns an iterator of objects
in the form ["Name <address@example.com", ...]
from the array [["address@example.com", "Name"]]
"""
for address, name in array:
if not name:
yield address
else:
... | [
"def",
"_get_recipients",
"(",
"self",
",",
"array",
")",
":",
"for",
"address",
",",
"name",
"in",
"array",
":",
"if",
"not",
"name",
":",
"yield",
"address",
"else",
":",
"yield",
"\"\\\"%s\\\" <%s>\"",
"%",
"(",
"name",
",",
"address",
")"
] | Returns an iterator of objects
in the form ["Name <address@example.com", ...]
from the array [["address@example.com", "Name"]] | [
"Returns",
"an",
"iterator",
"of",
"objects",
"in",
"the",
"form",
"[",
"Name",
"<address"
] | python | train |
huge-success/sanic | sanic/router.py | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L398-L415 | def get(self, request):
"""Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments
"""
# No virtual hosts specified; default behavior
if not self.hosts:
re... | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"# No virtual hosts specified; default behavior",
"if",
"not",
"self",
".",
"hosts",
":",
"return",
"self",
".",
"_get",
"(",
"request",
".",
"path",
",",
"request",
".",
"method",
",",
"\"\"",
")",
"# v... | Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments | [
"Get",
"a",
"request",
"handler",
"based",
"on",
"the",
"URL",
"of",
"the",
"request",
"or",
"raises",
"an",
"error"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/serving/query.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/query.py#L63-L76 | def make_request_fn():
"""Returns a request function."""
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_... | [
"def",
"make_request_fn",
"(",
")",
":",
"if",
"FLAGS",
".",
"cloud_mlengine_model_name",
":",
"request_fn",
"=",
"serving_utils",
".",
"make_cloud_mlengine_request_fn",
"(",
"credentials",
"=",
"GoogleCredentials",
".",
"get_application_default",
"(",
")",
",",
"mode... | Returns a request function. | [
"Returns",
"a",
"request",
"function",
"."
] | python | train |
wright-group/WrightTools | WrightTools/data/_channel.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_channel.py#L87-L89 | def minor_extent(self) -> complex:
"""Minimum deviation from null."""
return min((self.max() - self.null, self.null - self.min())) | [
"def",
"minor_extent",
"(",
"self",
")",
"->",
"complex",
":",
"return",
"min",
"(",
"(",
"self",
".",
"max",
"(",
")",
"-",
"self",
".",
"null",
",",
"self",
".",
"null",
"-",
"self",
".",
"min",
"(",
")",
")",
")"
] | Minimum deviation from null. | [
"Minimum",
"deviation",
"from",
"null",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/image_transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L386-L400 | def imagetransformer_base_8l_8h_big_cond_dr03_dan():
"""big 1d model for conditional image generation.2.99 on cifar10."""
hparams = imagetransformer_sep_channels_8l()
hparams.block_width = 256
hparams.block_length = 256
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.b... | [
"def",
"imagetransformer_base_8l_8h_big_cond_dr03_dan",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_sep_channels_8l",
"(",
")",
"hparams",
".",
"block_width",
"=",
"256",
"hparams",
".",
"block_length",
"=",
"256",
"hparams",
".",
"hidden_size",
"=",
"512",
"hp... | big 1d model for conditional image generation.2.99 on cifar10. | [
"big",
"1d",
"model",
"for",
"conditional",
"image",
"generation",
".",
"2",
".",
"99",
"on",
"cifar10",
"."
] | python | train |
hyperledger/sawtooth-core | validator/sawtooth_validator/database/database.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/database/database.py#L53-L64 | def get(self, key, index=None):
"""Retrieves a value associated with a key from the database
Args:
key (str): The key to retrieve
"""
records = self.get_multi([key], index=index)
try:
return records[0][1] # return the value from the key/value tuple
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"index",
"=",
"None",
")",
":",
"records",
"=",
"self",
".",
"get_multi",
"(",
"[",
"key",
"]",
",",
"index",
"=",
"index",
")",
"try",
":",
"return",
"records",
"[",
"0",
"]",
"[",
"1",
"]",
"# retur... | Retrieves a value associated with a key from the database
Args:
key (str): The key to retrieve | [
"Retrieves",
"a",
"value",
"associated",
"with",
"a",
"key",
"from",
"the",
"database"
] | python | train |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py#L103-L123 | def get_response(self, url, username=None, password=None):
"""
does the dirty work of actually getting the rsponse object using urllib2
and its HTTP auth builtins.
"""
scheme, netloc, path, query, frag = urlparse.urlsplit(url)
req = self.get_request(url)
stored_u... | [
"def",
"get_response",
"(",
"self",
",",
"url",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"frag",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"req",
"=",
"s... | does the dirty work of actually getting the rsponse object using urllib2
and its HTTP auth builtins. | [
"does",
"the",
"dirty",
"work",
"of",
"actually",
"getting",
"the",
"rsponse",
"object",
"using",
"urllib2",
"and",
"its",
"HTTP",
"auth",
"builtins",
"."
] | python | train |
projectatomic/osbs-client | osbs/build/build_request.py | https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/build_request.py#L814-L841 | def render_koji(self):
"""
if there is yum repo specified, don't pick stuff from koji
"""
phase = 'prebuild_plugins'
plugin = 'koji'
if not self.dj.dock_json_has_plugin_conf(phase, plugin):
return
if self.spec.yum_repourls.value:
logger.in... | [
"def",
"render_koji",
"(",
"self",
")",
":",
"phase",
"=",
"'prebuild_plugins'",
"plugin",
"=",
"'koji'",
"if",
"not",
"self",
".",
"dj",
".",
"dock_json_has_plugin_conf",
"(",
"phase",
",",
"plugin",
")",
":",
"return",
"if",
"self",
".",
"spec",
".",
"... | if there is yum repo specified, don't pick stuff from koji | [
"if",
"there",
"is",
"yum",
"repo",
"specified",
"don",
"t",
"pick",
"stuff",
"from",
"koji"
] | python | train |
waqasbhatti/astrobase | astrobase/lcproc/lcpfeatures.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/lcpfeatures.py#L573-L776 | def serial_periodicfeatures(pfpkl_list,
lcbasedir,
outdir,
starfeaturesdir=None,
fourierorder=5,
# these are depth, duration, ingress duration
transitpa... | [
"def",
"serial_periodicfeatures",
"(",
"pfpkl_list",
",",
"lcbasedir",
",",
"outdir",
",",
"starfeaturesdir",
"=",
"None",
",",
"fourierorder",
"=",
"5",
",",
"# these are depth, duration, ingress duration",
"transitparams",
"=",
"(",
"-",
"0.01",
",",
"0.1",
",",
... | This drives the periodicfeatures collection for a list of periodfinding
pickles.
Parameters
----------
pfpkl_list : list of str
The list of period-finding pickles to use.
lcbasedir : str
The base directory where the associated light curves are located.
outdir : str
Th... | [
"This",
"drives",
"the",
"periodicfeatures",
"collection",
"for",
"a",
"list",
"of",
"periodfinding",
"pickles",
"."
] | python | valid |
pkkid/python-plexapi | plexapi/video.py | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L69-L73 | def markWatched(self):
""" Mark video as watched. """
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | [
"def",
"markWatched",
"(",
"self",
")",
":",
"key",
"=",
"'/:/scrobble?key=%s&identifier=com.plexapp.plugins.library'",
"%",
"self",
".",
"ratingKey",
"self",
".",
"_server",
".",
"query",
"(",
"key",
")",
"self",
".",
"reload",
"(",
")"
] | Mark video as watched. | [
"Mark",
"video",
"as",
"watched",
"."
] | python | train |
Yelp/swagger_zipkin | swagger_zipkin/decorate_client.py | https://github.com/Yelp/swagger_zipkin/blob/8159b5d04f2c1089ae0a60851a5f097d7e09a40e/swagger_zipkin/decorate_client.py#L33-L71 | def decorate_client(api_client, func, name):
"""A helper for decorating :class:`bravado.client.SwaggerClient`.
:class:`bravado.client.SwaggerClient` can be extended by creating a class
which wraps all calls to it. This helper is used in a :func:`__getattr__`
to check if the attr exists on the api_client... | [
"def",
"decorate_client",
"(",
"api_client",
",",
"func",
",",
"name",
")",
":",
"client_attr",
"=",
"getattr",
"(",
"api_client",
",",
"name",
")",
"if",
"not",
"callable",
"(",
"client_attr",
")",
":",
"return",
"client_attr",
"return",
"OperationDecorator",... | A helper for decorating :class:`bravado.client.SwaggerClient`.
:class:`bravado.client.SwaggerClient` can be extended by creating a class
which wraps all calls to it. This helper is used in a :func:`__getattr__`
to check if the attr exists on the api_client. If the attr does not exist
raise :class:`Attri... | [
"A",
"helper",
"for",
"decorating",
":",
"class",
":",
"bravado",
".",
"client",
".",
"SwaggerClient",
".",
":",
"class",
":",
"bravado",
".",
"client",
".",
"SwaggerClient",
"can",
"be",
"extended",
"by",
"creating",
"a",
"class",
"which",
"wraps",
"all",... | python | train |
Scoppio/RagnarokEngine3 | RagnarokEngine3/RE3.py | https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/RagnarokEngine3/RE3.py#L746-L752 | def angle(vec1, vec2):
"""Returns the angle between two vectors"""
dot_vec = dot(vec1, vec2)
mag1 = vec1.length()
mag2 = vec2.length()
result = dot_vec / (mag1 * mag2)
return math.acos(result) | [
"def",
"angle",
"(",
"vec1",
",",
"vec2",
")",
":",
"dot_vec",
"=",
"dot",
"(",
"vec1",
",",
"vec2",
")",
"mag1",
"=",
"vec1",
".",
"length",
"(",
")",
"mag2",
"=",
"vec2",
".",
"length",
"(",
")",
"result",
"=",
"dot_vec",
"/",
"(",
"mag1",
"*... | Returns the angle between two vectors | [
"Returns",
"the",
"angle",
"between",
"two",
"vectors"
] | python | train |
schettino72/import-deps | import_deps/__init__.py | https://github.com/schettino72/import-deps/blob/311f2badd2c93f743d09664397f21e7eaa16e1f1/import_deps/__init__.py#L65-L75 | def _get_fqn(cls, path):
"""get full qualified name as list of strings
:return: (list - str) of path segments from top package to given path
"""
name_list = [path.stem]
current_path = path
# move to parent path until parent path is a python package
while cls.is_pk... | [
"def",
"_get_fqn",
"(",
"cls",
",",
"path",
")",
":",
"name_list",
"=",
"[",
"path",
".",
"stem",
"]",
"current_path",
"=",
"path",
"# move to parent path until parent path is a python package",
"while",
"cls",
".",
"is_pkg",
"(",
"current_path",
".",
"parent",
... | get full qualified name as list of strings
:return: (list - str) of path segments from top package to given path | [
"get",
"full",
"qualified",
"name",
"as",
"list",
"of",
"strings",
":",
"return",
":",
"(",
"list",
"-",
"str",
")",
"of",
"path",
"segments",
"from",
"top",
"package",
"to",
"given",
"path"
] | python | train |
paulgb/penkit | penkit/preview.py | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/preview.py#L28-L39 | def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""Preview a plot in a jupyter notebook.
Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview
Returns:
An object that render... | [
"def",
"show_plot",
"(",
"plot",
",",
"width",
"=",
"PREVIEW_WIDTH",
",",
"height",
"=",
"PREVIEW_HEIGHT",
")",
":",
"return",
"SVG",
"(",
"data",
"=",
"plot_to_svg",
"(",
"plot",
",",
"width",
",",
"height",
")",
")"
] | Preview a plot in a jupyter notebook.
Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview
Returns:
An object that renders in Jupyter as the provided plot | [
"Preview",
"a",
"plot",
"in",
"a",
"jupyter",
"notebook",
"."
] | python | train |
ANTsX/ANTsPy | ants/utils/multi_label_morphology.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/multi_label_morphology.py#L9-L98 | def multi_label_morphology(image, operation, radius, dilation_mask=None, label_list=None, force=False):
"""
Morphology on multi label images.
Wraps calls to iMath binary morphology. Additionally, dilation and closing operations preserve
pre-existing labels. The choices of operation are:
Di... | [
"def",
"multi_label_morphology",
"(",
"image",
",",
"operation",
",",
"radius",
",",
"dilation_mask",
"=",
"None",
",",
"label_list",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"(",
"label_list",
"is",
"None",
")",
"or",
"(",
"len",
"(",
... | Morphology on multi label images.
Wraps calls to iMath binary morphology. Additionally, dilation and closing operations preserve
pre-existing labels. The choices of operation are:
Dilation: dilates all labels sequentially, but does not overwrite original labels.
This reduces dependence on the ... | [
"Morphology",
"on",
"multi",
"label",
"images",
".",
"Wraps",
"calls",
"to",
"iMath",
"binary",
"morphology",
".",
"Additionally",
"dilation",
"and",
"closing",
"operations",
"preserve",
"pre",
"-",
"existing",
"labels",
".",
"The",
"choices",
"of",
"operation",... | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/system.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/system.py#L1218-L1237 | def start_service(name, argv = None):
"""
Start the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{stop_service}, L{pause_service}, L{resume_service}
@type name: str
@param name: Service unique name. You can get th... | [
"def",
"start_service",
"(",
"name",
",",
"argv",
"=",
"None",
")",
":",
"with",
"win32",
".",
"OpenSCManager",
"(",
"dwDesiredAccess",
"=",
"win32",
".",
"SC_MANAGER_CONNECT",
")",
"as",
"hSCManager",
":",
"with",
"win32",
".",
"OpenService",
"(",
"hSCManag... | Start the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{stop_service}, L{pause_service}, L{resume_service}
@type name: str
@param name: Service unique name. You can get this value from the
C{ServiceName} member of the... | [
"Start",
"the",
"service",
"given",
"by",
"name",
"."
] | python | train |
ethereum/py-evm | eth/db/chain.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L302-L313 | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
"""
Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for update... | [
"def",
"add_transaction",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"transaction",
":",
"'BaseTransaction'",
")",
"->",
"Hash32",
":",
"transaction_db",
"=",
"HexaryTrie",
"(",
"self",
".",
"db",
",",
"root_hash",... | Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header. | [
"Adds",
"the",
"given",
"transaction",
"to",
"the",
"provided",
"block",
"header",
"."
] | python | train |
nerdvegas/rez | src/rez/utils/formatting.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/formatting.py#L376-L403 | def get_epoch_time_from_str(s):
"""Convert a string into epoch time. Examples of valid strings:
1418350671 # already epoch time
-12s # 12 seconds ago
-5.4m # 5.4 minutes ago
"""
try:
return int(s)
except:
pass
try:
if s.startswith('-'):... | [
"def",
"get_epoch_time_from_str",
"(",
"s",
")",
":",
"try",
":",
"return",
"int",
"(",
"s",
")",
"except",
":",
"pass",
"try",
":",
"if",
"s",
".",
"startswith",
"(",
"'-'",
")",
":",
"chars",
"=",
"{",
"'d'",
":",
"24",
"*",
"60",
"*",
"60",
... | Convert a string into epoch time. Examples of valid strings:
1418350671 # already epoch time
-12s # 12 seconds ago
-5.4m # 5.4 minutes ago | [
"Convert",
"a",
"string",
"into",
"epoch",
"time",
".",
"Examples",
"of",
"valid",
"strings",
":"
] | python | train |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_prediction_explainer.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L301-L332 | def _image_gradients(self, input_csvlines, label, image_column_name):
"""Compute gradients from prob of label to image. Used by integrated gradients (probe)."""
with tf.Graph().as_default() as g, tf.Session() as sess:
logging_level = tf.logging.get_verbosity()
try:
... | [
"def",
"_image_gradients",
"(",
"self",
",",
"input_csvlines",
",",
"label",
",",
"image_column_name",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"g",
",",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"lo... | Compute gradients from prob of label to image. Used by integrated gradients (probe). | [
"Compute",
"gradients",
"from",
"prob",
"of",
"label",
"to",
"image",
".",
"Used",
"by",
"integrated",
"gradients",
"(",
"probe",
")",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/mem_cronjobs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_cronjobs.py#L84-L94 | def DeleteCronJob(self, cronjob_id):
"""Deletes a cronjob along with all its runs."""
if cronjob_id not in self.cronjobs:
raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)
del self.cronjobs[cronjob_id]
try:
del self.cronjob_leases[cronjob_id]
except KeyError:
pass... | [
"def",
"DeleteCronJob",
"(",
"self",
",",
"cronjob_id",
")",
":",
"if",
"cronjob_id",
"not",
"in",
"self",
".",
"cronjobs",
":",
"raise",
"db",
".",
"UnknownCronJobError",
"(",
"\"Cron job %s not known.\"",
"%",
"cronjob_id",
")",
"del",
"self",
".",
"cronjobs... | Deletes a cronjob along with all its runs. | [
"Deletes",
"a",
"cronjob",
"along",
"with",
"all",
"its",
"runs",
"."
] | python | train |
apache/airflow | airflow/contrib/hooks/datastore_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/datastore_hook.py#L102-L121 | def commit(self, body):
"""
Commit a transaction, optionally creating, deleting or modifying some entities.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/commit
:param body: the body of the commit request.
:type body: dict
:... | [
"def",
"commit",
"(",
"self",
",",
"body",
")",
":",
"conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"resp",
"=",
"(",
"conn",
".",
"projects",
"(",
")",
".",
"commit",
"(",
"projectId",
"=",
"self",
".",
"project_id",
",",
"body",
"=",
"body",
"... | Commit a transaction, optionally creating, deleting or modifying some entities.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/commit
:param body: the body of the commit request.
:type body: dict
:return: the response body of the commit requ... | [
"Commit",
"a",
"transaction",
"optionally",
"creating",
"deleting",
"or",
"modifying",
"some",
"entities",
"."
] | python | test |
pantsbuild/pants | src/python/pants/util/contextutil.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L50-L74 | def environment_as(**kwargs):
"""Update the environment to the supplied values, for example:
with environment_as(PYTHONPATH='foo:bar:baz',
PYTHON='/usr/bin/python2.7'):
subprocess.Popen(foo).wait()
"""
new_environment = kwargs
old_environment = {}
def setenv(key, val):
if val... | [
"def",
"environment_as",
"(",
"*",
"*",
"kwargs",
")",
":",
"new_environment",
"=",
"kwargs",
"old_environment",
"=",
"{",
"}",
"def",
"setenv",
"(",
"key",
",",
"val",
")",
":",
"if",
"val",
"is",
"not",
"None",
":",
"os",
".",
"environ",
"[",
"key"... | Update the environment to the supplied values, for example:
with environment_as(PYTHONPATH='foo:bar:baz',
PYTHON='/usr/bin/python2.7'):
subprocess.Popen(foo).wait() | [
"Update",
"the",
"environment",
"to",
"the",
"supplied",
"values",
"for",
"example",
":"
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/utils/types.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/utils/types.py#L30-L43 | def is_estimator(model):
"""
Determines if a model is an estimator using issubclass and isinstance.
Parameters
----------
estimator : class or instance
The object to test if it is a Scikit-Learn clusterer, especially a
Scikit-Learn estimator or Yellowbrick visualizer
"""
if ... | [
"def",
"is_estimator",
"(",
"model",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"model",
")",
":",
"return",
"issubclass",
"(",
"model",
",",
"BaseEstimator",
")",
"return",
"isinstance",
"(",
"model",
",",
"BaseEstimator",
")"
] | Determines if a model is an estimator using issubclass and isinstance.
Parameters
----------
estimator : class or instance
The object to test if it is a Scikit-Learn clusterer, especially a
Scikit-Learn estimator or Yellowbrick visualizer | [
"Determines",
"if",
"a",
"model",
"is",
"an",
"estimator",
"using",
"issubclass",
"and",
"isinstance",
"."
] | python | train |
SCIP-Interfaces/PySCIPOpt | examples/tutorial/logical.py | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/tutorial/logical.py#L69-L78 | def xorc_constraint(v=0, sense="maximize"):
""" XOR (r as variable) custom constraint"""
assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__()
model, x, y, z = _init()
r = model.addVar("r", "B")
n = model.addVar("n", "I") # auxiliary
model.addCons(r+quicksum([x,y,z]) == 2*n)
mod... | [
"def",
"xorc_constraint",
"(",
"v",
"=",
"0",
",",
"sense",
"=",
"\"maximize\"",
")",
":",
"assert",
"v",
"in",
"[",
"0",
",",
"1",
"]",
",",
"\"v must be 0 or 1 instead of %s\"",
"%",
"v",
".",
"__repr__",
"(",
")",
"model",
",",
"x",
",",
"y",
",",... | XOR (r as variable) custom constraint | [
"XOR",
"(",
"r",
"as",
"variable",
")",
"custom",
"constraint"
] | python | train |
mikedh/trimesh | trimesh/path/entities.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/entities.py#L395-L412 | def discrete(self, vertices, scale=1.0):
"""
Discretize into a world- space path.
Parameters
------------
vertices: (n, dimension) float
Points in space
scale : float
Size of overall scene for numerical comparisons
Returns
-----------... | [
"def",
"discrete",
"(",
"self",
",",
"vertices",
",",
"scale",
"=",
"1.0",
")",
":",
"discrete",
"=",
"self",
".",
"_orient",
"(",
"vertices",
"[",
"self",
".",
"points",
"]",
")",
"return",
"discrete"
] | Discretize into a world- space path.
Parameters
------------
vertices: (n, dimension) float
Points in space
scale : float
Size of overall scene for numerical comparisons
Returns
-------------
discrete: (m, dimension) float
Path in s... | [
"Discretize",
"into",
"a",
"world",
"-",
"space",
"path",
"."
] | python | train |
pettarin/ipapy | ipapy/__main__.py | https://github.com/pettarin/ipapy/blob/ede4b3c40636f6eb90068369d31a2e75c7115324/ipapy/__main__.py#L183-L199 | def command_u2a(string, vargs):
"""
Print the ARPABEY ASCII string corresponding to the given Unicode IPA string.
:param str string: the string to act upon
:param dict vargs: the command line arguments
"""
try:
l = ARPABETMapper().map_unicode_string(
unicode_string=string,
... | [
"def",
"command_u2a",
"(",
"string",
",",
"vargs",
")",
":",
"try",
":",
"l",
"=",
"ARPABETMapper",
"(",
")",
".",
"map_unicode_string",
"(",
"unicode_string",
"=",
"string",
",",
"ignore",
"=",
"vargs",
"[",
"\"ignore\"",
"]",
",",
"single_char_parsing",
... | Print the ARPABEY ASCII string corresponding to the given Unicode IPA string.
:param str string: the string to act upon
:param dict vargs: the command line arguments | [
"Print",
"the",
"ARPABEY",
"ASCII",
"string",
"corresponding",
"to",
"the",
"given",
"Unicode",
"IPA",
"string",
"."
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L708-L710 | def start(self):
''' Starts the server. '''
self._app.run(host=self._host, port=self._port) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_app",
".",
"run",
"(",
"host",
"=",
"self",
".",
"_host",
",",
"port",
"=",
"self",
".",
"_port",
")"
] | Starts the server. | [
"Starts",
"the",
"server",
"."
] | python | train |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/bases.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/bases.py#L399-L420 | def from_files(cls, ID, datafiles, parser, readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs):
"""
Create a Collection of measurements from a set of data files.
Parameters
----------
{_bases_ID}
{_bases_data_files}
{_bases_filename_parser}
{_bases_ID_kw... | [
"def",
"from_files",
"(",
"cls",
",",
"ID",
",",
"datafiles",
",",
"parser",
",",
"readdata_kwargs",
"=",
"{",
"}",
",",
"readmeta_kwargs",
"=",
"{",
"}",
",",
"*",
"*",
"ID_kwargs",
")",
":",
"d",
"=",
"_assign_IDS_to_datafiles",
"(",
"datafiles",
",",
... | Create a Collection of measurements from a set of data files.
Parameters
----------
{_bases_ID}
{_bases_data_files}
{_bases_filename_parser}
{_bases_ID_kwargs} | [
"Create",
"a",
"Collection",
"of",
"measurements",
"from",
"a",
"set",
"of",
"data",
"files",
"."
] | python | train |
googleapis/google-cloud-python | error_reporting/google/cloud/error_reporting/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/client.py#L335-L361 | def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
... | [
"def",
"report_exception",
"(",
"self",
",",
"http_context",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"self",
".",
"_send_error_report",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"http_context",
"=",
"http_context",
",",
"user",
"=",
"use... | Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
error was triggered.
:type user:... | [
"Reports",
"the",
"details",
"of",
"the",
"latest",
"exceptions",
"to",
"Stackdriver",
"Error",
"Reporting",
"."
] | python | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L529-L542 | def getvalue(self):
"""
Get value of file. Work around for second strategy.
Always returns bytes
"""
if self.strategy == 0:
return self._delegate.getvalue()
self._delegate.flush()
self._delegate.seek(0)
value = self._delegate.read()
if... | [
"def",
"getvalue",
"(",
"self",
")",
":",
"if",
"self",
".",
"strategy",
"==",
"0",
":",
"return",
"self",
".",
"_delegate",
".",
"getvalue",
"(",
")",
"self",
".",
"_delegate",
".",
"flush",
"(",
")",
"self",
".",
"_delegate",
".",
"seek",
"(",
"0... | Get value of file. Work around for second strategy.
Always returns bytes | [
"Get",
"value",
"of",
"file",
".",
"Work",
"around",
"for",
"second",
"strategy",
".",
"Always",
"returns",
"bytes"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py#L34-L54 | def mac_address_table_static_forward(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
static = ET.SubElement(mac_address_table, "static"... | [
"def",
"mac_address_table_static_forward",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"mac_address_table",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"mac-address-table\"",
",",
"xmlns"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
OpenKMIP/PyKMIP | kmip/core/primitives.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/primitives.py#L772-L784 | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the encoding of the Boolean object to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of a
Boolean object. Usually a BytearrayStream object. Required.
... | [
"def",
"write",
"(",
"self",
",",
"ostream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"Boolean",
",",
"self",
")",
".",
"write",
"(",
"ostream",
",",
"kmip_version",
"=",
"kmip_version",
")",
"self",... | Write the encoding of the Boolean object to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of a
Boolean object. Usually a BytearrayStream object. Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
vers... | [
"Write",
"the",
"encoding",
"of",
"the",
"Boolean",
"object",
"to",
"the",
"output",
"stream",
"."
] | python | test |
sighingnow/parsec.py | src/parsec/__init__.py | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L605-L613 | def letter():
'''Parse a letter in alphabet.'''
@Parser
def letter_parser(text, index=0):
if index < len(text) and text[index].isalpha():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a letter')
return letter_parser | [
"def",
"letter",
"(",
")",
":",
"@",
"Parser",
"def",
"letter_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
"<",
"len",
"(",
"text",
")",
"and",
"text",
"[",
"index",
"]",
".",
"isalpha",
"(",
")",
":",
"return",
"Value",... | Parse a letter in alphabet. | [
"Parse",
"a",
"letter",
"in",
"alphabet",
"."
] | python | train |
PyThaiNLP/pythainlp | pythainlp/ulmfit/__init__.py | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L169-L200 | def merge_wgts(em_sz, wgts, itos_pre, itos_new):
"""
:meth: `merge_wgts` insert pretrained weights and vocab into a new set of weights and vocab;
use average if vocab not in pretrained vocab
:param int em_sz: embedding size
:param wgts: torch model weights
:param list itos_pre: pretrained list o... | [
"def",
"merge_wgts",
"(",
"em_sz",
",",
"wgts",
",",
"itos_pre",
",",
"itos_new",
")",
":",
"vocab_size",
"=",
"len",
"(",
"itos_new",
")",
"enc_wgts",
"=",
"wgts",
"[",
"\"0.encoder.weight\"",
"]",
".",
"numpy",
"(",
")",
"# Average weight of encoding",
"ro... | :meth: `merge_wgts` insert pretrained weights and vocab into a new set of weights and vocab;
use average if vocab not in pretrained vocab
:param int em_sz: embedding size
:param wgts: torch model weights
:param list itos_pre: pretrained list of vocab
:param list itos_new: list of new vocab
:retu... | [
":",
"meth",
":",
"merge_wgts",
"insert",
"pretrained",
"weights",
"and",
"vocab",
"into",
"a",
"new",
"set",
"of",
"weights",
"and",
"vocab",
";",
"use",
"average",
"if",
"vocab",
"not",
"in",
"pretrained",
"vocab",
":",
"param",
"int",
"em_sz",
":",
"e... | python | train |
Xion/callee | callee/operators.py | https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/operators.py#L104-L109 | def _get_placeholder_repr(self):
"""Return the placeholder part of matcher's ``__repr__``."""
placeholder = '...'
if self.TRANSFORM is not None:
placeholder = '%s(%s)' % (self.TRANSFORM.__name__, placeholder)
return placeholder | [
"def",
"_get_placeholder_repr",
"(",
"self",
")",
":",
"placeholder",
"=",
"'...'",
"if",
"self",
".",
"TRANSFORM",
"is",
"not",
"None",
":",
"placeholder",
"=",
"'%s(%s)'",
"%",
"(",
"self",
".",
"TRANSFORM",
".",
"__name__",
",",
"placeholder",
")",
"ret... | Return the placeholder part of matcher's ``__repr__``. | [
"Return",
"the",
"placeholder",
"part",
"of",
"matcher",
"s",
"__repr__",
"."
] | python | train |
markovmodel/PyEMMA | pyemma/thermo/api.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/api.py#L283-L458 | def estimate_multi_temperature(
energy_trajs, temp_trajs, dtrajs,
energy_unit='kcal/mol', temp_unit='K', reference_temperature=None,
maxiter=10000, maxerr=1.0E-15, save_convergence_info=0,
estimator='wham', lag=1, dt_traj='1 step', init=None, init_maxiter=10000, init_maxerr=1e-8,
**kwargs):
r"""... | [
"def",
"estimate_multi_temperature",
"(",
"energy_trajs",
",",
"temp_trajs",
",",
"dtrajs",
",",
"energy_unit",
"=",
"'kcal/mol'",
",",
"temp_unit",
"=",
"'K'",
",",
"reference_temperature",
"=",
"None",
",",
"maxiter",
"=",
"10000",
",",
"maxerr",
"=",
"1.0E-15... | r"""
This function acts as a wrapper for ``tram()``, ``dtram()``, ``mbar``, and ``wham()`` and
handles the calculation of bias energies (``bias``) and thermodynamic state trajectories
(``ttrajs``) when the data comes from multi-temperature simulations.
Parameters
----------
energy_trajs : list ... | [
"r",
"This",
"function",
"acts",
"as",
"a",
"wrapper",
"for",
"tram",
"()",
"dtram",
"()",
"mbar",
"and",
"wham",
"()",
"and",
"handles",
"the",
"calculation",
"of",
"bias",
"energies",
"(",
"bias",
")",
"and",
"thermodynamic",
"state",
"trajectories",
"("... | python | train |
jic-dtool/dtoolcore | dtoolcore/storagebroker.py | https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L252-L256 | def put_readme(self, content):
"""Store the readme descriptive metadata."""
logger.debug("Putting readme")
key = self.get_readme_key()
self.put_text(key, content) | [
"def",
"put_readme",
"(",
"self",
",",
"content",
")",
":",
"logger",
".",
"debug",
"(",
"\"Putting readme\"",
")",
"key",
"=",
"self",
".",
"get_readme_key",
"(",
")",
"self",
".",
"put_text",
"(",
"key",
",",
"content",
")"
] | Store the readme descriptive metadata. | [
"Store",
"the",
"readme",
"descriptive",
"metadata",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/mpls_config/router/mpls/mpls_cmds_holder/policy/traffic_engineering/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_config/router/mpls/mpls_cmds_holder/policy/traffic_engineering/__init__.py#L126-L147 | def _set_traffic_eng_ospf(self, v, load=False):
"""
Setter method for traffic_eng_ospf, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/traffic_engineering/traffic_eng_ospf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_traffic_eng... | [
"def",
"_set_traffic_eng_ospf",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for traffic_eng_ospf, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/traffic_engineering/traffic_eng_ospf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_traffic_eng_ospf is considered as a private
method. Backends lookin... | [
"Setter",
"method",
"for",
"traffic_eng_ospf",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_config",
"/",
"router",
"/",
"mpls",
"/",
"mpls_cmds_holder",
"/",
"policy",
"/",
"traffic_engineering",
"/",
"traffic_eng_ospf",
"(",
"container",
")",
"If",
"this",
... | python | train |
horazont/aioxmpp | aioxmpp/security_layer.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1142-L1204 | def negotiate_sasl(transport, xmlstream,
sasl_providers,
negotiation_timeout,
jid, features):
"""
Perform SASL authentication on the given :class:`.protocol.XMLStream`
`stream`. `transport` must be the :class:`asyncio.Transport` over which the
`st... | [
"def",
"negotiate_sasl",
"(",
"transport",
",",
"xmlstream",
",",
"sasl_providers",
",",
"negotiation_timeout",
",",
"jid",
",",
"features",
")",
":",
"if",
"not",
"transport",
".",
"get_extra_info",
"(",
"\"sslcontext\"",
")",
":",
"transport",
"=",
"None",
"... | Perform SASL authentication on the given :class:`.protocol.XMLStream`
`stream`. `transport` must be the :class:`asyncio.Transport` over which the
`stream` runs. It is used to detect whether TLS is used and may be required
by some SASL mechanisms.
`sasl_providers` must be an iterable of :class:`SASLProv... | [
"Perform",
"SASL",
"authentication",
"on",
"the",
"given",
":",
"class",
":",
".",
"protocol",
".",
"XMLStream",
"stream",
".",
"transport",
"must",
"be",
"the",
":",
"class",
":",
"asyncio",
".",
"Transport",
"over",
"which",
"the",
"stream",
"runs",
".",... | python | train |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1709-L1734 | def UpsertAttachment(self, document_link, attachment, options=None):
"""Upserts an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to upsert.
:param dict options:
The re... | [
"def",
"UpsertAttachment",
"(",
"self",
",",
"document_link",
",",
"attachment",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"document_id",
",",
"path",
"=",
"self",
".",
"_GetItemIdWithPathForAttachme... | Upserts an attachment in a document.
:param str document_link:
The link to the document.
:param dict attachment:
The Azure Cosmos attachment to upsert.
:param dict options:
The request options for the request.
:return:
The upserted Attach... | [
"Upserts",
"an",
"attachment",
"in",
"a",
"document",
"."
] | python | train |
emc-openstack/storops | storops/unity/client.py | https://github.com/emc-openstack/storops/blob/24b4b13bf065c0ef0538dd0b5ebb8f25d24176bd/storops/unity/client.py#L63-L84 | def get_all(self, type_name, base_fields=None, the_filter=None,
nested_fields=None):
"""Get the resource by resource id.
:param nested_fields: nested resource fields
:param base_fields: fields of this resource
:param the_filter: dictionary of filter like `{'name': 'abc'}... | [
"def",
"get_all",
"(",
"self",
",",
"type_name",
",",
"base_fields",
"=",
"None",
",",
"the_filter",
"=",
"None",
",",
"nested_fields",
"=",
"None",
")",
":",
"fields",
"=",
"self",
".",
"get_fields",
"(",
"type_name",
",",
"base_fields",
",",
"nested_fiel... | Get the resource by resource id.
:param nested_fields: nested resource fields
:param base_fields: fields of this resource
:param the_filter: dictionary of filter like `{'name': 'abc'}`
:param type_name: Resource type. For example, pool, lun, nasServer.
:return: List of resource ... | [
"Get",
"the",
"resource",
"by",
"resource",
"id",
"."
] | python | train |
coleifer/walrus | walrus/containers.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1432-L1443 | def set_id(self, id='$'):
"""
Set the last-read message id for each stream in the consumer group. By
default, this will be the special "$" identifier, meaning all messages
are marked as having been read.
:param id: id of last-read message (or "$").
"""
accum = {}... | [
"def",
"set_id",
"(",
"self",
",",
"id",
"=",
"'$'",
")",
":",
"accum",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"keys",
":",
"accum",
"[",
"key",
"]",
"=",
"self",
".",
"database",
".",
"xgroup_setid",
"(",
"key",
",",
"self",
".",
"nam... | Set the last-read message id for each stream in the consumer group. By
default, this will be the special "$" identifier, meaning all messages
are marked as having been read.
:param id: id of last-read message (or "$"). | [
"Set",
"the",
"last",
"-",
"read",
"message",
"id",
"for",
"each",
"stream",
"in",
"the",
"consumer",
"group",
".",
"By",
"default",
"this",
"will",
"be",
"the",
"special",
"$",
"identifier",
"meaning",
"all",
"messages",
"are",
"marked",
"as",
"having",
... | python | train |
Jammy2211/PyAutoLens | autolens/data/array/grids.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L460-L469 | def array_2d_from_array_1d(self, array_1d):
""" Map a 1D array the same dimension as the grid to its original masked 2D array.
Parameters
-----------
array_1d : ndarray
The 1D array which is mapped to its masked 2D array.
"""
return mapping_util.map_masked_1d... | [
"def",
"array_2d_from_array_1d",
"(",
"self",
",",
"array_1d",
")",
":",
"return",
"mapping_util",
".",
"map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two",
"(",
"array_1d",
"=",
"array_1d",
",",
"shape",
"=",
"self",
".",
"mask",
".",
"shape",
",",
... | Map a 1D array the same dimension as the grid to its original masked 2D array.
Parameters
-----------
array_1d : ndarray
The 1D array which is mapped to its masked 2D array. | [
"Map",
"a",
"1D",
"array",
"the",
"same",
"dimension",
"as",
"the",
"grid",
"to",
"its",
"original",
"masked",
"2D",
"array",
"."
] | python | valid |
MillionIntegrals/vel | vel/rl/buffers/backend/circular_vec_buffer_backend.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/backend/circular_vec_buffer_backend.py#L7-L13 | def take_along_axis(large_array, indexes):
""" Take along axis """
# Reshape indexes into the right shape
if len(large_array.shape) > len(indexes.shape):
indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.shape) - len(indexes.shape))))
return np.take_along_axis(large_array, ... | [
"def",
"take_along_axis",
"(",
"large_array",
",",
"indexes",
")",
":",
"# Reshape indexes into the right shape",
"if",
"len",
"(",
"large_array",
".",
"shape",
")",
">",
"len",
"(",
"indexes",
".",
"shape",
")",
":",
"indexes",
"=",
"indexes",
".",
"reshape",... | Take along axis | [
"Take",
"along",
"axis"
] | python | train |
yoavaviram/python-amazon-simple-product-api | amazon/api.py | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L358-L372 | def cart_clear(self, CartId=None, HMAC=None, **kwargs):
"""CartClear. Removes all items from cart
:param CartId: Id of cart
:param HMAC: HMAC of cart. Do not use url encoded
:return: An :class:`~.AmazonCart`.
"""
if not CartId or not HMAC:
raise CartException(... | [
"def",
"cart_clear",
"(",
"self",
",",
"CartId",
"=",
"None",
",",
"HMAC",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"CartId",
"or",
"not",
"HMAC",
":",
"raise",
"CartException",
"(",
"'CartId required for CartClear call'",
")",
"respons... | CartClear. Removes all items from cart
:param CartId: Id of cart
:param HMAC: HMAC of cart. Do not use url encoded
:return: An :class:`~.AmazonCart`. | [
"CartClear",
".",
"Removes",
"all",
"items",
"from",
"cart",
":",
"param",
"CartId",
":",
"Id",
"of",
"cart",
":",
"param",
"HMAC",
":",
"HMAC",
"of",
"cart",
".",
"Do",
"not",
"use",
"url",
"encoded",
":",
"return",
":",
"An",
":",
"class",
":",
"... | python | train |
cloudtools/stacker | stacker/blueprints/raw.py | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/raw.py#L194-L215 | def rendered(self):
"""Return (generating first if needed) rendered template."""
if not self._rendered:
template_path = get_template_path(self.raw_template_path)
if template_path:
with open(template_path, 'r') as template:
if len(os.path.splite... | [
"def",
"rendered",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_rendered",
":",
"template_path",
"=",
"get_template_path",
"(",
"self",
".",
"raw_template_path",
")",
"if",
"template_path",
":",
"with",
"open",
"(",
"template_path",
",",
"'r'",
")",
... | Return (generating first if needed) rendered template. | [
"Return",
"(",
"generating",
"first",
"if",
"needed",
")",
"rendered",
"template",
"."
] | python | train |
cstockton/py-gensend | gensend/providers/common.py | https://github.com/cstockton/py-gensend/blob/8c8e911f8e8c386bea42967350beb4636fc19240/gensend/providers/common.py#L102-L114 | def istrue(self, *args):
"""Strict test for 'true' value test. If multiple args are provided it will
test them all.
ISTRUE:true
%{ISTRUE:true} -> 'True'
"""
def is_true(val):
if val is True:
return True
val = str(val).lower().s... | [
"def",
"istrue",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"is_true",
"(",
"val",
")",
":",
"if",
"val",
"is",
"True",
":",
"return",
"True",
"val",
"=",
"str",
"(",
"val",
")",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"return",
... | Strict test for 'true' value test. If multiple args are provided it will
test them all.
ISTRUE:true
%{ISTRUE:true} -> 'True' | [
"Strict",
"test",
"for",
"true",
"value",
"test",
".",
"If",
"multiple",
"args",
"are",
"provided",
"it",
"will",
"test",
"them",
"all",
".",
"ISTRUE",
":",
"true"
] | python | train |
tBuLi/symfit | symfit/contrib/interactive_guess/interactive_guess.py | https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L211-L219 | def _eval_model(self):
"""
Convenience method for evaluating the model with the current parameters
:return: named tuple with results
"""
arguments = self._x_grid.copy()
arguments.update({param: param.value for param in self.model.params})
return self.model(**key2... | [
"def",
"_eval_model",
"(",
"self",
")",
":",
"arguments",
"=",
"self",
".",
"_x_grid",
".",
"copy",
"(",
")",
"arguments",
".",
"update",
"(",
"{",
"param",
":",
"param",
".",
"value",
"for",
"param",
"in",
"self",
".",
"model",
".",
"params",
"}",
... | Convenience method for evaluating the model with the current parameters
:return: named tuple with results | [
"Convenience",
"method",
"for",
"evaluating",
"the",
"model",
"with",
"the",
"current",
"parameters"
] | python | train |
Zitrax/nose-dep | nosedep.py | https://github.com/Zitrax/nose-dep/blob/fd29c95e0e5eb2dbd821f6566b72dfcf42631226/nosedep.py#L268-L279 | def prepare_suite(self, suite):
"""Prepare suite and determine test ordering"""
all_tests = {}
for s in suite:
m = re.match(r'(\w+)\s+\(.+\)', str(s))
if m:
name = m.group(1)
else:
name = str(s).split('.')[-1]
all_te... | [
"def",
"prepare_suite",
"(",
"self",
",",
"suite",
")",
":",
"all_tests",
"=",
"{",
"}",
"for",
"s",
"in",
"suite",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'(\\w+)\\s+\\(.+\\)'",
",",
"str",
"(",
"s",
")",
")",
"if",
"m",
":",
"name",
"=",
"m",... | Prepare suite and determine test ordering | [
"Prepare",
"suite",
"and",
"determine",
"test",
"ordering"
] | python | train |
quintusdias/glymur | glymur/jp2box.py | https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/jp2box.py#L116-L123 | def _str_superbox(self):
"""__str__ method for all superboxes."""
msg = Jp2kBox.__str__(self)
for box in self.box:
boxstr = str(box)
# Indent the child boxes to make the association clear.
msg += '\n' + self._indent(boxstr)
return msg | [
"def",
"_str_superbox",
"(",
"self",
")",
":",
"msg",
"=",
"Jp2kBox",
".",
"__str__",
"(",
"self",
")",
"for",
"box",
"in",
"self",
".",
"box",
":",
"boxstr",
"=",
"str",
"(",
"box",
")",
"# Indent the child boxes to make the association clear.",
"msg",
"+="... | __str__ method for all superboxes. | [
"__str__",
"method",
"for",
"all",
"superboxes",
"."
] | python | train |
jmgilman/Neolib | neolib/pyamf/alias.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/alias.py#L353-L418 | def getEncodableAttributes(self, obj, codec=None):
"""
Must return a C{dict} of attributes to be encoded, even if its empty.
@param codec: An optional argument that will contain the encoder
instance calling this function.
@since: 0.5
"""
if not self._compiled... | [
"def",
"getEncodableAttributes",
"(",
"self",
",",
"obj",
",",
"codec",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_compiled",
":",
"self",
".",
"compile",
"(",
")",
"if",
"self",
".",
"is_dict",
":",
"return",
"dict",
"(",
"obj",
")",
"if",
... | Must return a C{dict} of attributes to be encoded, even if its empty.
@param codec: An optional argument that will contain the encoder
instance calling this function.
@since: 0.5 | [
"Must",
"return",
"a",
"C",
"{",
"dict",
"}",
"of",
"attributes",
"to",
"be",
"encoded",
"even",
"if",
"its",
"empty",
"."
] | python | train |
moonso/vcftoolbox | vcftoolbox/add_variant_information.py | https://github.com/moonso/vcftoolbox/blob/438fb1d85a83812c389774b94802eb5921c89e3a/vcftoolbox/add_variant_information.py#L140-L185 | def add_vcf_info(keyword, variant_line=None, variant_dict=None, annotation=None):
"""
Add information to the info field of a vcf variant line.
Arguments:
variant_line (str): A vcf formatted variant line
keyword (str): The info field key
annotation (str): If the annotation is a k... | [
"def",
"add_vcf_info",
"(",
"keyword",
",",
"variant_line",
"=",
"None",
",",
"variant_dict",
"=",
"None",
",",
"annotation",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"annotation",
":",
"new_info",
"=",... | Add information to the info field of a vcf variant line.
Arguments:
variant_line (str): A vcf formatted variant line
keyword (str): The info field key
annotation (str): If the annotation is a key, value pair
this is the string that represents the value
... | [
"Add",
"information",
"to",
"the",
"info",
"field",
"of",
"a",
"vcf",
"variant",
"line",
".",
"Arguments",
":",
"variant_line",
"(",
"str",
")",
":",
"A",
"vcf",
"formatted",
"variant",
"line",
"keyword",
"(",
"str",
")",
":",
"The",
"info",
"field",
"... | python | train |
kennethreitz/maya | maya/core.py | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L710-L739 | def when(string, timezone='UTC', prefer_dates_from='current_period'):
""""Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
stri... | [
"def",
"when",
"(",
"string",
",",
"timezone",
"=",
"'UTC'",
",",
"prefer_dates_from",
"=",
"'current_period'",
")",
":",
"settings",
"=",
"{",
"'TIMEZONE'",
":",
"timezone",
",",
"'RETURN_AS_TIMEZONE_AWARE'",
":",
"True",
",",
"'TO_TIMEZONE'",
":",
"'UTC'",
"... | Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
string -- string to be parsed
timezone -- timezone referenced from (defaul... | [
"Returns",
"a",
"MayaDT",
"instance",
"for",
"the",
"human",
"moment",
"specified",
"."
] | python | train |
olitheolix/qtmacs | qtmacs/extensions/qtmacsscintilla_macros.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1463-L1500 | def highlightNextMatch(self):
"""
Select and highlight the next match in the set of matches.
"""
# If this method was called on an empty input field (ie.
# if the user hit <ctrl>+s again) then pick the default
# selection.
if self.qteText.toPlainText() == '':
... | [
"def",
"highlightNextMatch",
"(",
"self",
")",
":",
"# If this method was called on an empty input field (ie.",
"# if the user hit <ctrl>+s again) then pick the default",
"# selection.",
"if",
"self",
".",
"qteText",
".",
"toPlainText",
"(",
")",
"==",
"''",
":",
"self",
".... | Select and highlight the next match in the set of matches. | [
"Select",
"and",
"highlight",
"the",
"next",
"match",
"in",
"the",
"set",
"of",
"matches",
"."
] | python | train |
Kronuz/pyScss | scss/util.py | https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/util.py#L108-L122 | def make_filename_hash(key):
"""Convert the given key (a simple Python object) to a unique-ish hash
suitable for a filename.
"""
key_repr = repr(key).replace(BASE_DIR, '').encode('utf8')
# This is really stupid but necessary for making the repr()s be the same on
# Python 2 and 3 and thus allowin... | [
"def",
"make_filename_hash",
"(",
"key",
")",
":",
"key_repr",
"=",
"repr",
"(",
"key",
")",
".",
"replace",
"(",
"BASE_DIR",
",",
"''",
")",
".",
"encode",
"(",
"'utf8'",
")",
"# This is really stupid but necessary for making the repr()s be the same on",
"# Python ... | Convert the given key (a simple Python object) to a unique-ish hash
suitable for a filename. | [
"Convert",
"the",
"given",
"key",
"(",
"a",
"simple",
"Python",
"object",
")",
"to",
"a",
"unique",
"-",
"ish",
"hash",
"suitable",
"for",
"a",
"filename",
"."
] | python | train |
gccxml/pygccxml | pygccxml/declarations/namespace.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L94-L104 | def remove_declaration(self, decl):
"""
Removes declaration from members list.
:param decl: declaration to be removed
:type decl: :class:`declaration_t`
"""
del self.declarations[self.declarations.index(decl)]
decl.cache.reset() | [
"def",
"remove_declaration",
"(",
"self",
",",
"decl",
")",
":",
"del",
"self",
".",
"declarations",
"[",
"self",
".",
"declarations",
".",
"index",
"(",
"decl",
")",
"]",
"decl",
".",
"cache",
".",
"reset",
"(",
")"
] | Removes declaration from members list.
:param decl: declaration to be removed
:type decl: :class:`declaration_t` | [
"Removes",
"declaration",
"from",
"members",
"list",
"."
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/util.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/util.py#L56-L67 | def demunge(s: str) -> str:
"""Replace munged string components with their original
representation."""
def demunge_replacer(match: Match) -> str:
full_match = match.group(0)
replacement = _DEMUNGE_REPLACEMENTS.get(full_match, None)
if replacement:
return replacement
... | [
"def",
"demunge",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"def",
"demunge_replacer",
"(",
"match",
":",
"Match",
")",
"->",
"str",
":",
"full_match",
"=",
"match",
".",
"group",
"(",
"0",
")",
"replacement",
"=",
"_DEMUNGE_REPLACEMENTS",
".",
"get... | Replace munged string components with their original
representation. | [
"Replace",
"munged",
"string",
"components",
"with",
"their",
"original",
"representation",
"."
] | python | test |
wavefrontHQ/python-client | wavefront_api_client/api/saved_search_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/saved_search_api.py#L226-L248 | def get_all_entity_type_saved_searches(self, entitytype, **kwargs): # noqa: E501
"""Get all saved searches for a specific entity type for a user # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async... | [
"def",
"get_all_entity_type_saved_searches",
"(",
"self",
",",
"entitytype",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"se... | Get all saved searches for a specific entity type for a user # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_entity_type_saved_searches(entitytype, async_req=T... | [
"Get",
"all",
"saved",
"searches",
"for",
"a",
"specific",
"entity",
"type",
"for",
"a",
"user",
"#",
"noqa",
":",
"E501"
] | python | train |
secdev/scapy | scapy/arch/windows/__init__.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/arch/windows/__init__.py#L283-L287 | def get_ip_from_name(ifname, v6=False):
"""Backward compatibility: indirectly calls get_ips
Deprecated."""
iface = IFACES.dev_from_name(ifname)
return get_ips(v6=v6).get(iface, [""])[0] | [
"def",
"get_ip_from_name",
"(",
"ifname",
",",
"v6",
"=",
"False",
")",
":",
"iface",
"=",
"IFACES",
".",
"dev_from_name",
"(",
"ifname",
")",
"return",
"get_ips",
"(",
"v6",
"=",
"v6",
")",
".",
"get",
"(",
"iface",
",",
"[",
"\"\"",
"]",
")",
"["... | Backward compatibility: indirectly calls get_ips
Deprecated. | [
"Backward",
"compatibility",
":",
"indirectly",
"calls",
"get_ips",
"Deprecated",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/lib/tzlocal/unix.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/lib/tzlocal/unix.py#L39-L146 | def _get_localzone(_root='/'):
"""Tries to find the local timezone configuration.
This method prefers finding the timezone name and passing that to pytz,
over passing in the localtime file, as in the later case the zoneinfo
name is unknown.
The parameter _root makes the function look for files lik... | [
"def",
"_get_localzone",
"(",
"_root",
"=",
"'/'",
")",
":",
"tzenv",
"=",
"_try_tz_from_env",
"(",
")",
"if",
"tzenv",
":",
"return",
"tzenv",
"# Now look for distribution specific configuration files",
"# that contain the timezone name.",
"for",
"configfile",
"in",
"(... | Tries to find the local timezone configuration.
This method prefers finding the timezone name and passing that to pytz,
over passing in the localtime file, as in the later case the zoneinfo
name is unknown.
The parameter _root makes the function look for files like /etc/localtime
beneath the _root... | [
"Tries",
"to",
"find",
"the",
"local",
"timezone",
"configuration",
"."
] | python | train |
tchx84/grestful | grestful/helpers.py | https://github.com/tchx84/grestful/blob/5f7ee7eb358cf260c97d41f8680e8f168ef5d843/grestful/helpers.py#L19-L26 | def param_upload(field, path):
""" Pack upload metadata. """
if not path:
return None
param = {}
param['field'] = field
param['path'] = path
return param | [
"def",
"param_upload",
"(",
"field",
",",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"None",
"param",
"=",
"{",
"}",
"param",
"[",
"'field'",
"]",
"=",
"field",
"param",
"[",
"'path'",
"]",
"=",
"path",
"return",
"param"
] | Pack upload metadata. | [
"Pack",
"upload",
"metadata",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L431-L437 | def config_profile_list(self):
"""Return config profile list from DCNM."""
these_profiles = self._config_profile_list() or []
profile_list = [q for p in these_profiles for q in
[p.get('profileName')]]
return profile_list | [
"def",
"config_profile_list",
"(",
"self",
")",
":",
"these_profiles",
"=",
"self",
".",
"_config_profile_list",
"(",
")",
"or",
"[",
"]",
"profile_list",
"=",
"[",
"q",
"for",
"p",
"in",
"these_profiles",
"for",
"q",
"in",
"[",
"p",
".",
"get",
"(",
"... | Return config profile list from DCNM. | [
"Return",
"config",
"profile",
"list",
"from",
"DCNM",
"."
] | python | train |
ace0/pyrelic | pyrelic/common.py | https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/common.py#L14-L21 | def assertSameType(a, b):
"""
Raises an exception if @b is not an instance of type(@a)
"""
if not isinstance(b, type(a)):
raise NotImplementedError("This operation is only supported for " \
"elements of the same type. Instead found {} and {}".
format(type(a), type(b))... | [
"def",
"assertSameType",
"(",
"a",
",",
"b",
")",
":",
"if",
"not",
"isinstance",
"(",
"b",
",",
"type",
"(",
"a",
")",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"This operation is only supported for \"",
"\"elements of the same type. Instead found {} and {}\""... | Raises an exception if @b is not an instance of type(@a) | [
"Raises",
"an",
"exception",
"if"
] | python | train |
tanghaibao/jcvi | jcvi/formats/bed.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/bed.py#L580-L602 | def density(args):
"""
%prog density bedfile ref.fasta
Calculates density of features per seqid.
"""
p = OptionParser(density.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
bedfile, fastafile = args
bed = Bed(bedfile)
sizes = S... | [
"def",
"density",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"density",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | %prog density bedfile ref.fasta
Calculates density of features per seqid. | [
"%prog",
"density",
"bedfile",
"ref",
".",
"fasta"
] | python | train |
ChrisCummins/labm8 | fs.py | https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/fs.py#L422-L428 | def mkopen(p, *args, **kwargs):
"""
A wrapper for the open() builtin which makes parent directories if needed.
"""
dir = os.path.dirname(p)
mkdir(dir)
return open(p, *args, **kwargs) | [
"def",
"mkopen",
"(",
"p",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"p",
")",
"mkdir",
"(",
"dir",
")",
"return",
"open",
"(",
"p",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | A wrapper for the open() builtin which makes parent directories if needed. | [
"A",
"wrapper",
"for",
"the",
"open",
"()",
"builtin",
"which",
"makes",
"parent",
"directories",
"if",
"needed",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.