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 |
|---|---|---|---|---|---|---|---|---|
diefans/docker-events | src/docker_events/__init__.py | https://github.com/diefans/docker-events/blob/cc07591d908fefcc265285ba7fc0047632e06dea/src/docker_events/__init__.py#L50-L56 | def filter_events(cls, client, event_data):
"""Filter registered events and yield them."""
for event in cls.events:
# try event filters
if event.matches(client, event_data):
yield event | [
"def",
"filter_events",
"(",
"cls",
",",
"client",
",",
"event_data",
")",
":",
"for",
"event",
"in",
"cls",
".",
"events",
":",
"# try event filters",
"if",
"event",
".",
"matches",
"(",
"client",
",",
"event_data",
")",
":",
"yield",
"event"
] | Filter registered events and yield them. | [
"Filter",
"registered",
"events",
"and",
"yield",
"them",
"."
] | python | train |
mozilla/python_moztelemetry | moztelemetry/dataset.py | https://github.com/mozilla/python_moztelemetry/blob/09ddf1ec7d953a4308dfdcb0ed968f27bd5921bb/moztelemetry/dataset.py#L388-L412 | def from_source(source_name):
"""Create a Dataset configured for the given source_name
This is particularly convenient when the user doesn't know
the list of dimensions or the bucket name, but only the source name.
Usage example::
records = Dataset.from_source('telemetry')... | [
"def",
"from_source",
"(",
"source_name",
")",
":",
"meta_bucket",
"=",
"'net-mozaws-prod-us-west-2-pipeline-metadata'",
"store",
"=",
"S3Store",
"(",
"meta_bucket",
")",
"try",
":",
"source",
"=",
"json",
".",
"loads",
"(",
"store",
".",
"get_key",
"(",
"'sourc... | Create a Dataset configured for the given source_name
This is particularly convenient when the user doesn't know
the list of dimensions or the bucket name, but only the source name.
Usage example::
records = Dataset.from_source('telemetry').where(
docType='main',
... | [
"Create",
"a",
"Dataset",
"configured",
"for",
"the",
"given",
"source_name"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/natural_language_classifier_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/natural_language_classifier_v1.py#L428-L437 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'classifier_id') and self.classifier_id is not None:
_dict['classifier_id'] = self.classifier_id
if hasattr(self, 'url') and self.url is not None:
_dict['url'] ... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'classifier_id'",
")",
"and",
"self",
".",
"classifier_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'classifier_id'",
"]",
"=",
"self",
".",
"classif... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L146-L199 | def _load_config(self, config_data):
"""the final step of the authenticate steps, where we load the values
from config_data into the Configuration object.
Parameters
==========
config_data: a dictionary with configuration values (keys) to read
... | [
"def",
"_load_config",
"(",
"self",
",",
"config_data",
")",
":",
"# Username and password are required.",
"for",
"item",
"in",
"[",
"self",
".",
"CONFIG_NAME_USER",
",",
"self",
".",
"CONFIG_NAME_KEY",
"]",
":",
"if",
"item",
"not",
"in",
"config_data",
":",
... | the final step of the authenticate steps, where we load the values
from config_data into the Configuration object.
Parameters
==========
config_data: a dictionary with configuration values (keys) to read
into self.config_values | [
"the",
"final",
"step",
"of",
"the",
"authenticate",
"steps",
"where",
"we",
"load",
"the",
"values",
"from",
"config_data",
"into",
"the",
"Configuration",
"object",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L309-L331 | def get_color(self, color, intensity=0):
""" Returns a QColor for a given color code, or None if one cannot be
constructed.
"""
if color is None:
return None
# Adjust for intensity, if possible.
if color < 8 and intensity > 0:
color += 8
... | [
"def",
"get_color",
"(",
"self",
",",
"color",
",",
"intensity",
"=",
"0",
")",
":",
"if",
"color",
"is",
"None",
":",
"return",
"None",
"# Adjust for intensity, if possible.",
"if",
"color",
"<",
"8",
"and",
"intensity",
">",
"0",
":",
"color",
"+=",
"8... | Returns a QColor for a given color code, or None if one cannot be
constructed. | [
"Returns",
"a",
"QColor",
"for",
"a",
"given",
"color",
"code",
"or",
"None",
"if",
"one",
"cannot",
"be",
"constructed",
"."
] | python | test |
log2timeline/plaso | plaso/filters/path_filter.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/filters/path_filter.py#L576-L594 | def AddPathSegment(self, path_segment, scan_object):
"""Adds a path segment.
Args:
path_segment: a string containing the path segment.
scan_object: a scan object, either a scan tree sub node (instance of
PathFilterScanTreeNode) or a string containing a path.
Raises:
Va... | [
"def",
"AddPathSegment",
"(",
"self",
",",
"path_segment",
",",
"scan_object",
")",
":",
"if",
"path_segment",
"in",
"self",
".",
"_path_segments",
":",
"raise",
"ValueError",
"(",
"'Path segment already set.'",
")",
"if",
"isinstance",
"(",
"scan_object",
",",
... | Adds a path segment.
Args:
path_segment: a string containing the path segment.
scan_object: a scan object, either a scan tree sub node (instance of
PathFilterScanTreeNode) or a string containing a path.
Raises:
ValueError: if the node already contains a scan object for
... | [
"Adds",
"a",
"path",
"segment",
"."
] | python | train |
abingham/spor | src/spor/repository/repository.py | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L141-L145 | def _anchor_path(self, anchor_id):
"Absolute path to the data file for `anchor_id`."
file_name = '{}.yml'.format(anchor_id)
file_path = self._spor_dir / file_name
return file_path | [
"def",
"_anchor_path",
"(",
"self",
",",
"anchor_id",
")",
":",
"file_name",
"=",
"'{}.yml'",
".",
"format",
"(",
"anchor_id",
")",
"file_path",
"=",
"self",
".",
"_spor_dir",
"/",
"file_name",
"return",
"file_path"
] | Absolute path to the data file for `anchor_id`. | [
"Absolute",
"path",
"to",
"the",
"data",
"file",
"for",
"anchor_id",
"."
] | python | train |
oksome/Tumulus | tumulus/element.py | https://github.com/oksome/Tumulus/blob/20fca0e251d6f1825c33e61a8d497b62a8cbc0da/tumulus/element.py#L86-L104 | def soup(self):
'''
Running plugins and adding an HTML doctype to the
generated Tag HTML.
'''
dom = BeautifulSoup('<!DOCTYPE html>')
# BeautifulSoup behaves differently if lxml is installed or not,
# and will create a basic HTML structure if lxml is insta... | [
"def",
"soup",
"(",
"self",
")",
":",
"dom",
"=",
"BeautifulSoup",
"(",
"'<!DOCTYPE html>'",
")",
"# BeautifulSoup behaves differently if lxml is installed or not,",
"# and will create a basic HTML structure if lxml is installed.",
"if",
"len",
"(",
"dom",
")",
">",
"1",
":... | Running plugins and adding an HTML doctype to the
generated Tag HTML. | [
"Running",
"plugins",
"and",
"adding",
"an",
"HTML",
"doctype",
"to",
"the",
"generated",
"Tag",
"HTML",
"."
] | python | train |
peterbrittain/asciimatics | asciimatics/widgets.py | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/widgets.py#L161-L187 | def _find_min_start(text, max_width, unicode_aware=True, at_end=False):
"""
Find the starting point in the string that will reduce it to be less than or equal to the
specified width when displayed on screen.
:param text: The text to analyze.
:param max_width: The required maximum width
:param a... | [
"def",
"_find_min_start",
"(",
"text",
",",
"max_width",
",",
"unicode_aware",
"=",
"True",
",",
"at_end",
"=",
"False",
")",
":",
"# Is the solution trivial? Worth optimizing for text heavy UIs...",
"if",
"2",
"*",
"len",
"(",
"text",
")",
"<",
"max_width",
":",... | Find the starting point in the string that will reduce it to be less than or equal to the
specified width when displayed on screen.
:param text: The text to analyze.
:param max_width: The required maximum width
:param at_end: At the end of the editable line, so allow spaced for cursor.
:return: Th... | [
"Find",
"the",
"starting",
"point",
"in",
"the",
"string",
"that",
"will",
"reduce",
"it",
"to",
"be",
"less",
"than",
"or",
"equal",
"to",
"the",
"specified",
"width",
"when",
"displayed",
"on",
"screen",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/command_line/bader_caller.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/command_line/bader_caller.py#L369-L415 | def bader_analysis_from_path(path, suffix=''):
"""
Convenience method to run Bader analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present, constructs a temp... | [
"def",
"bader_analysis_from_path",
"(",
"path",
",",
"suffix",
"=",
"''",
")",
":",
"def",
"_get_filepath",
"(",
"filename",
",",
"warning",
",",
"path",
"=",
"path",
",",
"suffix",
"=",
"suffix",
")",
":",
"paths",
"=",
"glob",
".",
"glob",
"(",
"os",... | Convenience method to run Bader analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present, constructs a temporary reference
file as AECCAR0 + AECCAR2
3. Runs B... | [
"Convenience",
"method",
"to",
"run",
"Bader",
"analysis",
"on",
"a",
"folder",
"containing",
"typical",
"VASP",
"output",
"files",
"."
] | python | train |
lltk/lltk | lltk/de/scrapers/pons.py | https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/de/scrapers/pons.py#L80-L98 | def plural(self):
''' Tries to scrape the plural version from pons.eu. '''
element = self._first('NN')
if element:
if 'kein Plur' in element:
# There is no plural
return ['']
if re.search(', ([\w|\s|/]+)>', element, re.U):
# Plural form is provided
return re.findall(', ([\w|\s|/]+)>', eleme... | [
"def",
"plural",
"(",
"self",
")",
":",
"element",
"=",
"self",
".",
"_first",
"(",
"'NN'",
")",
"if",
"element",
":",
"if",
"'kein Plur'",
"in",
"element",
":",
"# There is no plural",
"return",
"[",
"''",
"]",
"if",
"re",
".",
"search",
"(",
"', ([\\... | Tries to scrape the plural version from pons.eu. | [
"Tries",
"to",
"scrape",
"the",
"plural",
"version",
"from",
"pons",
".",
"eu",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/df/tools/lib/bloomfilter.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/tools/lib/bloomfilter.py#L140-L143 | def add(self, item):
"Add an item (string) to the filter. Cannot be removed later!"
for pos in self._hashes(item):
self.hash |= (2 ** pos) | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"for",
"pos",
"in",
"self",
".",
"_hashes",
"(",
"item",
")",
":",
"self",
".",
"hash",
"|=",
"(",
"2",
"**",
"pos",
")"
] | Add an item (string) to the filter. Cannot be removed later! | [
"Add",
"an",
"item",
"(",
"string",
")",
"to",
"the",
"filter",
".",
"Cannot",
"be",
"removed",
"later!"
] | python | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAIndicator/hurst.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/hurst.py#L15-L24 | def run(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
try:
return self.calculateHurst(series, exponent)
except Exception as e:
print(" Error: %s" % e) | [
"def",
"run",
"(",
"self",
",",
"series",
",",
"exponent",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"calculateHurst",
"(",
"series",
",",
"exponent",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\" Error: %s\"",
"%",
"e... | :type series: List
:type exponent: int
:rtype: float | [
":",
"type",
"series",
":",
"List",
":",
"type",
"exponent",
":",
"int",
":",
"rtype",
":",
"float"
] | python | train |
pybel/pybel-tools | src/pybel_tools/analysis/neurommsig/algorithm.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L88-L124 | def get_neurommsig_scores_prestratified(subgraphs: Mapping[str, BELGraph],
genes: List[Gene],
ora_weight: Optional[float] = None,
hub_weight: Optional[float] = None,
... | [
"def",
"get_neurommsig_scores_prestratified",
"(",
"subgraphs",
":",
"Mapping",
"[",
"str",
",",
"BELGraph",
"]",
",",
"genes",
":",
"List",
"[",
"Gene",
"]",
",",
"ora_weight",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"hub_weight",
":",
"Opti... | Takes a graph stratification and runs neurommsig on each
:param subgraphs: A pre-stratified set of graphs
:param genes: A list of gene nodes
:param ora_weight: The relative weight of the over-enrichment analysis score from
:py:func:`neurommsig_gene_ora`. Defaults to 1.0.
:param hub_weight: The rel... | [
"Takes",
"a",
"graph",
"stratification",
"and",
"runs",
"neurommsig",
"on",
"each"
] | python | valid |
rm-hull/luma.emulator | luma/emulator/render.py | https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/render.py#L45-L49 | def identity(self, surface):
"""
Fast scale operation that does not sample the results
"""
return self._pygame.transform.scale(surface, self._output_size) | [
"def",
"identity",
"(",
"self",
",",
"surface",
")",
":",
"return",
"self",
".",
"_pygame",
".",
"transform",
".",
"scale",
"(",
"surface",
",",
"self",
".",
"_output_size",
")"
] | Fast scale operation that does not sample the results | [
"Fast",
"scale",
"operation",
"that",
"does",
"not",
"sample",
"the",
"results"
] | python | train |
intel-analytics/BigDL | pyspark/bigdl/models/lenet/utils.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/models/lenet/utils.py#L39-L52 | def preprocess_mnist(sc, options):
"""
Preprocess mnist dataset.
Normalize and transform into Sample of RDDs.
"""
train_data = get_mnist(sc, "train", options.dataPath)\
.map(lambda rec_tuple: (normalizer(rec_tuple[0], mnist.TRAIN_MEAN, mnist.TRAIN_STD),
rec_tu... | [
"def",
"preprocess_mnist",
"(",
"sc",
",",
"options",
")",
":",
"train_data",
"=",
"get_mnist",
"(",
"sc",
",",
"\"train\"",
",",
"options",
".",
"dataPath",
")",
".",
"map",
"(",
"lambda",
"rec_tuple",
":",
"(",
"normalizer",
"(",
"rec_tuple",
"[",
"0",... | Preprocess mnist dataset.
Normalize and transform into Sample of RDDs. | [
"Preprocess",
"mnist",
"dataset",
".",
"Normalize",
"and",
"transform",
"into",
"Sample",
"of",
"RDDs",
"."
] | python | test |
mordred-descriptor/mordred | mordred/_base/result.py | https://github.com/mordred-descriptor/mordred/blob/2848b088fd7b6735590242b5e22573babc724f10/mordred/_base/result.py#L49-L63 | def drop_missing(self):
r"""Delete missing value.
Returns:
Result
"""
newvalues = []
newdescs = []
for d, v in self.items():
if not is_missing(v):
newvalues.append(v)
newdescs.append(d)
return self.__class... | [
"def",
"drop_missing",
"(",
"self",
")",
":",
"newvalues",
"=",
"[",
"]",
"newdescs",
"=",
"[",
"]",
"for",
"d",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"not",
"is_missing",
"(",
"v",
")",
":",
"newvalues",
".",
"append",
"(",
... | r"""Delete missing value.
Returns:
Result | [
"r",
"Delete",
"missing",
"value",
"."
] | python | test |
grst/geos | geos/print.py | https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/print.py#L73-L103 | def get_print_bbox(x, y, zoom, width, height, dpi):
"""
Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPS... | [
"def",
"get_print_bbox",
"(",
"x",
",",
"y",
",",
"zoom",
",",
"width",
",",
"height",
",",
"dpi",
")",
":",
"tiles_h",
"=",
"width",
"*",
"dpi_to_dpmm",
"(",
"dpi",
")",
"/",
"TILE_SIZE",
"tiles_v",
"=",
"height",
"*",
"dpi_to_dpmm",
"(",
"dpi",
")"... | Calculate the tile bounding box based on position, map size and resolution.
The function returns the next larger tile-box, that covers the specified
page size in mm.
Args:
x (float): map center x-coordinate in Mercator projection (EPSG:4326)
y (float): map center y-coordinate in Mercator p... | [
"Calculate",
"the",
"tile",
"bounding",
"box",
"based",
"on",
"position",
"map",
"size",
"and",
"resolution",
"."
] | python | train |
saltstack/salt | salt/modules/nxos_upgrade.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos_upgrade.py#L77-L139 | def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickst... | [
"def",
"check_upgrade_impact",
"(",
"system_image",
",",
"kickstart_image",
"=",
"None",
",",
"issu",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Input Validation",
"if",
"not",
"isinstance",
"(",
"issu",
",",
"bool",
")",
":",
"return",
"'Input Error... | Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
... | [
"Display",
"upgrade",
"impact",
"information",
"without",
"actually",
"upgrading",
"the",
"device",
"."
] | python | train |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/request_context.py | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/request_context.py#L181-L226 | def span_in_stack_context(span):
"""
Create Tornado's StackContext that stores the given span in the
thread-local request context. This function is intended for use
in Tornado applications based on IOLoop, although will work fine
in single-threaded apps like Flask, albeit with more overhead.
##... | [
"def",
"span_in_stack_context",
"(",
"span",
")",
":",
"if",
"not",
"isinstance",
"(",
"opentracing",
".",
"tracer",
".",
"scope_manager",
",",
"TornadoScopeManager",
")",
":",
"raise",
"RuntimeError",
"(",
"'scope_manager is not TornadoScopeManager'",
")",
"# Enter t... | Create Tornado's StackContext that stores the given span in the
thread-local request context. This function is intended for use
in Tornado applications based on IOLoop, although will work fine
in single-threaded apps like Flask, albeit with more overhead.
## Usage example in Tornado application
Su... | [
"Create",
"Tornado",
"s",
"StackContext",
"that",
"stores",
"the",
"given",
"span",
"in",
"the",
"thread",
"-",
"local",
"request",
"context",
".",
"This",
"function",
"is",
"intended",
"for",
"use",
"in",
"Tornado",
"applications",
"based",
"on",
"IOLoop",
... | python | train |
bjodah/pyneqsys | pyneqsys/core.py | https://github.com/bjodah/pyneqsys/blob/1c8f2fe1ab2b6cc6cb55b7a1328aca2e3a3c5c77/pyneqsys/core.py#L91-L166 | def solve_series(self, x0, params, varied_data, varied_idx,
internal_x0=None, solver=None, propagate=True, **kwargs):
""" Solve system for a set of parameters in which one is varied
Parameters
----------
x0 : array_like
Guess (subject to ``self.post_proc... | [
"def",
"solve_series",
"(",
"self",
",",
"x0",
",",
"params",
",",
"varied_data",
",",
"varied_idx",
",",
"internal_x0",
"=",
"None",
",",
"solver",
"=",
"None",
",",
"propagate",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"x_... | Solve system for a set of parameters in which one is varied
Parameters
----------
x0 : array_like
Guess (subject to ``self.post_processors``)
params : array_like
Parameter values
vaired_data : array_like
Numerical values of the varied paramete... | [
"Solve",
"system",
"for",
"a",
"set",
"of",
"parameters",
"in",
"which",
"one",
"is",
"varied"
] | python | train |
google/fleetspeak | fleetspeak/src/server/grpcservice/client/client.py | https://github.com/google/fleetspeak/blob/bc95dd6941494461d2e5dff0a7f4c78a07ff724d/fleetspeak/src/server/grpcservice/client/client.py#L174-L202 | def InsertMessage(self, message, timeout=None):
"""Inserts a message into the Fleetspeak server.
Sets message.source, if unset.
Args:
message: common_pb2.Message
The message to send.
timeout: How many seconds to try for.
Raises:
grpc.RpcError: if the RPC fails.
Invali... | [
"def",
"InsertMessage",
"(",
"self",
",",
"message",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"common_pb2",
".",
"Message",
")",
":",
"raise",
"InvalidArgument",
"(",
"\"Attempt to send unexpected message type: %s\"",
... | Inserts a message into the Fleetspeak server.
Sets message.source, if unset.
Args:
message: common_pb2.Message
The message to send.
timeout: How many seconds to try for.
Raises:
grpc.RpcError: if the RPC fails.
InvalidArgument: if message is not a common_pb2.Message. | [
"Inserts",
"a",
"message",
"into",
"the",
"Fleetspeak",
"server",
"."
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L611-L615 | def channels_voice_availability_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/voice-api/availabilities#show-availability"
api_path = "/api/v2/channels/voice/availabilities/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"channels_voice_availability_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/channels/voice/availabilities/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
... | https://developer.zendesk.com/rest_api/docs/voice-api/availabilities#show-availability | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"voice",
"-",
"api",
"/",
"availabilities#show",
"-",
"availability"
] | python | train |
lazygunner/xunleipy | xunleipy/rsa_lib.py | https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L33-L40 | def extendedEuclid(a, b):
"""return a tuple of three values: x, y and z, such that x is
the GCD of a and b, and x = y * a + z * b"""
if a == 0:
return b, 0, 1
else:
g, y, x = extendedEuclid(b % a, a)
return g, x - (b // a) * y, y | [
"def",
"extendedEuclid",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"==",
"0",
":",
"return",
"b",
",",
"0",
",",
"1",
"else",
":",
"g",
",",
"y",
",",
"x",
"=",
"extendedEuclid",
"(",
"b",
"%",
"a",
",",
"a",
")",
"return",
"g",
",",
"x",
... | return a tuple of three values: x, y and z, such that x is
the GCD of a and b, and x = y * a + z * b | [
"return",
"a",
"tuple",
"of",
"three",
"values",
":",
"x",
"y",
"and",
"z",
"such",
"that",
"x",
"is",
"the",
"GCD",
"of",
"a",
"and",
"b",
"and",
"x",
"=",
"y",
"*",
"a",
"+",
"z",
"*",
"b"
] | python | train |
monarch-initiative/dipper | dipper/sources/UDP.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/UDP.py#L93-L190 | def fetch(self, is_dl_forced=True):
"""
Fetches data from udp collaboration server,
see top level comments for class for more information
:return:
"""
username = config.get_config()['dbauth']['udp']['user']
password = config.get_config()['dbauth']['udp']['passwor... | [
"def",
"fetch",
"(",
"self",
",",
"is_dl_forced",
"=",
"True",
")",
":",
"username",
"=",
"config",
".",
"get_config",
"(",
")",
"[",
"'dbauth'",
"]",
"[",
"'udp'",
"]",
"[",
"'user'",
"]",
"password",
"=",
"config",
".",
"get_config",
"(",
")",
"[",... | Fetches data from udp collaboration server,
see top level comments for class for more information
:return: | [
"Fetches",
"data",
"from",
"udp",
"collaboration",
"server",
"see",
"top",
"level",
"comments",
"for",
"class",
"for",
"more",
"information",
":",
"return",
":"
] | python | train |
tcalmant/ipopo | pelix/misc/mqtt_client.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L343-L369 | def __on_connect(self, client, userdata, flags, result_code):
# pylint: disable=W0613
"""
Client connected to the server
:param client: Connected Paho client
:param userdata: User data (unused)
:param flags: Response flags sent by the broker
:param result_code: C... | [
"def",
"__on_connect",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"flags",
",",
"result_code",
")",
":",
"# pylint: disable=W0613",
"if",
"result_code",
":",
"# result_code != 0: something wrong happened",
"_logger",
".",
"error",
"(",
"\"Error connecting the MQT... | Client connected to the server
:param client: Connected Paho client
:param userdata: User data (unused)
:param flags: Response flags sent by the broker
:param result_code: Connection result code (0: success, others: error) | [
"Client",
"connected",
"to",
"the",
"server"
] | python | train |
obriencj/python-javatools | javatools/change.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L522-L532 | def squash_children(self, options):
"""
reduces the memory footprint of this super-change by converting
all child changes into squashed changes
"""
oldsubs = self.collect()
self.changes = tuple(squash(c, options=options) for c in oldsubs)
for change in oldsubs:
... | [
"def",
"squash_children",
"(",
"self",
",",
"options",
")",
":",
"oldsubs",
"=",
"self",
".",
"collect",
"(",
")",
"self",
".",
"changes",
"=",
"tuple",
"(",
"squash",
"(",
"c",
",",
"options",
"=",
"options",
")",
"for",
"c",
"in",
"oldsubs",
")",
... | reduces the memory footprint of this super-change by converting
all child changes into squashed changes | [
"reduces",
"the",
"memory",
"footprint",
"of",
"this",
"super",
"-",
"change",
"by",
"converting",
"all",
"child",
"changes",
"into",
"squashed",
"changes"
] | python | train |
backtrader/backtrader | contrib/utils/iqfeed-to-influxdb.py | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L63-L90 | def iq_query(self, message: str):
"""Send data query to IQFeed API."""
end_msg = '!ENDMSG!'
recv_buffer = 4096
# Send the historical data request message and buffer the data
self._send_cmd(message)
chunk = ""
data = ""
while True:
chunk = sel... | [
"def",
"iq_query",
"(",
"self",
",",
"message",
":",
"str",
")",
":",
"end_msg",
"=",
"'!ENDMSG!'",
"recv_buffer",
"=",
"4096",
"# Send the historical data request message and buffer the data",
"self",
".",
"_send_cmd",
"(",
"message",
")",
"chunk",
"=",
"\"\"",
"... | Send data query to IQFeed API. | [
"Send",
"data",
"query",
"to",
"IQFeed",
"API",
"."
] | python | train |
elifesciences/proofreader-python | proofreader/license_checker/__init__.py | https://github.com/elifesciences/proofreader-python/blob/387b3c65ee7777e26b3a7340179dc4ed68f24f58/proofreader/license_checker/__init__.py#L12-L19 | def _get_packages():
# type: () -> List[Package]
"""Convert `pkg_resources.working_set` into a list of `Package` objects.
:return: list
"""
return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set,
key=lambda x: str(x).lower())] | [
"def",
"_get_packages",
"(",
")",
":",
"# type: () -> List[Package]",
"return",
"[",
"Package",
"(",
"pkg_obj",
"=",
"pkg",
")",
"for",
"pkg",
"in",
"sorted",
"(",
"pkg_resources",
".",
"working_set",
",",
"key",
"=",
"lambda",
"x",
":",
"str",
"(",
"x",
... | Convert `pkg_resources.working_set` into a list of `Package` objects.
:return: list | [
"Convert",
"pkg_resources",
".",
"working_set",
"into",
"a",
"list",
"of",
"Package",
"objects",
"."
] | python | train |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/data/AnyValueMap.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L338-L349 | def get_as_datetime_with_default(self, key, default_value):
"""
Converts map element into a Date or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: Date value ot the element or defaul... | [
"def",
"get_as_datetime_with_default",
"(",
"self",
",",
"key",
",",
"default_value",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
")",
"return",
"DateTimeConverter",
".",
"to_datetime_with_default",
"(",
"value",
",",
"default_value",
")"
] | Converts map element into a Date or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: Date value ot the element or default value if conversion is not supported. | [
"Converts",
"map",
"element",
"into",
"a",
"Date",
"or",
"returns",
"default",
"value",
"if",
"conversion",
"is",
"not",
"possible",
"."
] | python | train |
biocore-ntnu/epic | epic/run/run_epic.py | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/run/run_epic.py#L147-L169 | def _merge_files(windows, nb_cpu):
# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame
"""Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with ... | [
"def",
"_merge_files",
"(",
"windows",
",",
"nb_cpu",
")",
":",
"# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame",
"# windows is a list of chromosome dfs per file",
"windows",
"=",
"iter",
"(",
"windows",
")",
"# can iterate over because it is odict_values",
"merged",
"=",
... | Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with the collective count
per bin for all files.
TODO: is it faster to merge all in one command? | [
"Merge",
"lists",
"of",
"chromosome",
"bin",
"df",
"chromosome",
"-",
"wise",
"."
] | python | train |
adamhajari/spyre | spyre/server.py | https://github.com/adamhajari/spyre/blob/5dd9f6de072e99af636ab7e7393d249761c56e69/spyre/server.py#L387-L402 | def getPlot(self, params):
"""Override this function
arguments:
params (dict)
returns:
matplotlib.pyplot figure
"""
try:
return eval("self." + str(params['output_id']) + "(params)")
except AttributeError:
df = self.getData(params)... | [
"def",
"getPlot",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"return",
"eval",
"(",
"\"self.\"",
"+",
"str",
"(",
"params",
"[",
"'output_id'",
"]",
")",
"+",
"\"(params)\"",
")",
"except",
"AttributeError",
":",
"df",
"=",
"self",
".",
"getData... | Override this function
arguments:
params (dict)
returns:
matplotlib.pyplot figure | [
"Override",
"this",
"function"
] | python | train |
tensorflow/cleverhans | cleverhans/utils.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L341-L349 | def deep_copy(numpy_dict):
"""
Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them.
"""
out = {}
for key in numpy_dict:
out[key] = numpy_dict[key].copy()
return out | [
"def",
"deep_copy",
"(",
"numpy_dict",
")",
":",
"out",
"=",
"{",
"}",
"for",
"key",
"in",
"numpy_dict",
":",
"out",
"[",
"key",
"]",
"=",
"numpy_dict",
"[",
"key",
"]",
".",
"copy",
"(",
")",
"return",
"out"
] | Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them. | [
"Returns",
"a",
"copy",
"of",
"a",
"dictionary",
"whose",
"values",
"are",
"numpy",
"arrays",
".",
"Copies",
"their",
"values",
"rather",
"than",
"copying",
"references",
"to",
"them",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/learning/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L1195-L1222 | def get_child_objectives(self, objective_id):
"""Gets the children of the given objective.
arg: objective_id (osid.id.Id): the ``Id`` to query
return: (osid.learning.ObjectiveList) - the children of the
objective
raise: NotFound - ``objective_id`` is not found
... | [
"def",
"get_child_objectives",
"(",
"self",
",",
"objective_id",
")",
":",
"# Implemented from template for",
"# osid.ontology.SubjectHierarchySession.get_child_subjects_template",
"if",
"self",
".",
"_hierarchy_session",
".",
"has_children",
"(",
"objective_id",
")",
":",
"c... | Gets the children of the given objective.
arg: objective_id (osid.id.Id): the ``Id`` to query
return: (osid.learning.ObjectiveList) - the children of the
objective
raise: NotFound - ``objective_id`` is not found
raise: NullArgument - ``objective_id`` is ``null``
... | [
"Gets",
"the",
"children",
"of",
"the",
"given",
"objective",
"."
] | python | train |
artefactual-labs/agentarchives | agentarchives/archivesspace/client.py | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivesspace/client.py#L785-L965 | def add_digital_object(
self,
parent_archival_object,
identifier,
title=None,
uri=None,
location_of_originals=None,
object_type="text",
xlink_show="embed",
xlink_actuate="onLoad",
restricted=False,
use_statement="",
use_cond... | [
"def",
"add_digital_object",
"(",
"self",
",",
"parent_archival_object",
",",
"identifier",
",",
"title",
"=",
"None",
",",
"uri",
"=",
"None",
",",
"location_of_originals",
"=",
"None",
",",
"object_type",
"=",
"\"text\"",
",",
"xlink_show",
"=",
"\"embed\"",
... | Creates a new digital object.
:param string parent_archival_object: The archival object to which the newly-created digital object will be parented.
:param string identifier: A unique identifier for the digital object, in any format.
:param string title: The title of the digital object.
... | [
"Creates",
"a",
"new",
"digital",
"object",
"."
] | python | train |
pennlabs/penn-sdk-python | penn/registrar.py | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L47-L63 | def search(self, params, validate=False):
"""Return a generator of section objects for the given search params.
:param params: Dictionary of course search parameters.
:param validate: Optional. Set to true to enable request validation.
>>> cis100s = r.search({'course_id': 'cis', 'cours... | [
"def",
"search",
"(",
"self",
",",
"params",
",",
"validate",
"=",
"False",
")",
":",
"if",
"self",
".",
"val_info",
"is",
"None",
":",
"self",
".",
"val_info",
"=",
"self",
".",
"search_params",
"(",
")",
"if",
"validate",
":",
"errors",
"=",
"self"... | Return a generator of section objects for the given search params.
:param params: Dictionary of course search parameters.
:param validate: Optional. Set to true to enable request validation.
>>> cis100s = r.search({'course_id': 'cis', 'course_level_at_or_below': '200'}) | [
"Return",
"a",
"generator",
"of",
"section",
"objects",
"for",
"the",
"given",
"search",
"params",
"."
] | python | train |
JamesPHoughton/pysd | pysd/py_backend/functions.py | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L376-L415 | def set_components(self, params):
""" Set the value of exogenous model elements.
Element values can be passed as keyword=value pairs in the function call.
Values can be numeric type or pandas Series.
Series will be interpolated by integrator.
Examples
--------
>... | [
"def",
"set_components",
"(",
"self",
",",
"params",
")",
":",
"# It might make sense to allow the params argument to take a pandas series, where",
"# the indices of the series are variable names. This would make it easier to",
"# do a Pandas apply on a DataFrame of parameter values. However, th... | Set the value of exogenous model elements.
Element values can be passed as keyword=value pairs in the function call.
Values can be numeric type or pandas Series.
Series will be interpolated by integrator.
Examples
--------
>>> model.set_components({'birth_rate': 10})
... | [
"Set",
"the",
"value",
"of",
"exogenous",
"model",
"elements",
".",
"Element",
"values",
"can",
"be",
"passed",
"as",
"keyword",
"=",
"value",
"pairs",
"in",
"the",
"function",
"call",
".",
"Values",
"can",
"be",
"numeric",
"type",
"or",
"pandas",
"Series"... | python | train |
vxgmichel/aiostream | aiostream/stream/select.py | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L49-L58 | async def skip(source, n):
"""Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
... | [
"async",
"def",
"skip",
"(",
"source",
",",
"n",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"item",
"i... | Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped. | [
"Forward",
"an",
"asynchronous",
"sequence",
"skipping",
"the",
"first",
"n",
"elements",
"."
] | python | train |
googleapis/google-cloud-python | spanner/google/cloud/spanner_v1/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L161-L167 | def database_admin_api(self):
"""Helper for session-related API calls."""
if self._database_admin_api is None:
self._database_admin_api = DatabaseAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._database_admin_api | [
"def",
"database_admin_api",
"(",
"self",
")",
":",
"if",
"self",
".",
"_database_admin_api",
"is",
"None",
":",
"self",
".",
"_database_admin_api",
"=",
"DatabaseAdminClient",
"(",
"credentials",
"=",
"self",
".",
"credentials",
",",
"client_info",
"=",
"_CLIEN... | Helper for session-related API calls. | [
"Helper",
"for",
"session",
"-",
"related",
"API",
"calls",
"."
] | python | train |
peterbe/django-static | django_static/templatetags/django_static.py | https://github.com/peterbe/django-static/blob/05c0d2f302274b9d3f7df6ad92bd861889316ebd/django_static/templatetags/django_static.py#L660-L677 | def _find_filepath_in_roots(filename):
"""Look for filename in all MEDIA_ROOTS, and return the first one found."""
for root in settings.DJANGO_STATIC_MEDIA_ROOTS:
filepath = _filename2filepath(filename, root)
if os.path.isfile(filepath):
return filepath, root
# havent found it in... | [
"def",
"_find_filepath_in_roots",
"(",
"filename",
")",
":",
"for",
"root",
"in",
"settings",
".",
"DJANGO_STATIC_MEDIA_ROOTS",
":",
"filepath",
"=",
"_filename2filepath",
"(",
"filename",
",",
"root",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepat... | Look for filename in all MEDIA_ROOTS, and return the first one found. | [
"Look",
"for",
"filename",
"in",
"all",
"MEDIA_ROOTS",
"and",
"return",
"the",
"first",
"one",
"found",
"."
] | python | train |
datosgobar/pydatajson | pydatajson/indicators.py | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/indicators.py#L160-L209 | def _federation_indicators(catalog, central_catalog,
identifier_search=False):
"""Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya par... | [
"def",
"_federation_indicators",
"(",
"catalog",
",",
"central_catalog",
",",
"identifier_search",
"=",
"False",
")",
":",
"result",
"=",
"{",
"'datasets_federados_cant'",
":",
"None",
",",
"'datasets_federados_pct'",
":",
"None",
",",
"'datasets_no_federados_cant'",
... | Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya parseado
central_catalog (str o dict): ruta a catálogo central, o un dict
con el catálogo ya par... | [
"Cuenta",
"la",
"cantidad",
"de",
"datasets",
"incluídos",
"tanto",
"en",
"la",
"lista",
"catalogs",
"como",
"en",
"el",
"catálogo",
"central",
"y",
"genera",
"indicadores",
"a",
"partir",
"de",
"esa",
"información",
"."
] | python | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L25-L33 | def _inertia_from_labels(X, centers, labels):
"""Compute inertia with cosine distance using known labels.
"""
n_examples, n_features = X.shape
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
inertia[ee] = 1 - X[ee, :].dot(centers[int(labels[ee]), :].T)
return np.sum(inert... | [
"def",
"_inertia_from_labels",
"(",
"X",
",",
"centers",
",",
"labels",
")",
":",
"n_examples",
",",
"n_features",
"=",
"X",
".",
"shape",
"inertia",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_examples",
",",
")",
")",
"for",
"ee",
"in",
"range",
"(",
"n_... | Compute inertia with cosine distance using known labels. | [
"Compute",
"inertia",
"with",
"cosine",
"distance",
"using",
"known",
"labels",
"."
] | python | train |
daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L431-L452 | def is_sms_service_for_region(numobj, region_dialing_from):
"""Given a valid short number, determines whether it is an SMS service
(however, nothing is implied about its validity). An SMS service is where
the primary or only intended usage is to receive and/or send text messages
(SMSs). This includes MM... | [
"def",
"is_sms_service_for_region",
"(",
"numobj",
",",
"region_dialing_from",
")",
":",
"if",
"not",
"_region_dialing_from_matches_number",
"(",
"numobj",
",",
"region_dialing_from",
")",
":",
"return",
"False",
"metadata",
"=",
"PhoneMetadata",
".",
"short_metadata_fo... | Given a valid short number, determines whether it is an SMS service
(however, nothing is implied about its validity). An SMS service is where
the primary or only intended usage is to receive and/or send text messages
(SMSs). This includes MMS as MMS numbers downgrade to SMS if the other
party isn't MMS-... | [
"Given",
"a",
"valid",
"short",
"number",
"determines",
"whether",
"it",
"is",
"an",
"SMS",
"service",
"(",
"however",
"nothing",
"is",
"implied",
"about",
"its",
"validity",
")",
".",
"An",
"SMS",
"service",
"is",
"where",
"the",
"primary",
"or",
"only",
... | python | train |
luckydonald/pytgbot | code_generation/output/teleflask_messages.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L4203-L4215 | def send(self, sender: PytgbotApiBot):
"""
Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage
"""
return sender.send_game(
# receiver, self.media, disable_notification=... | [
"def",
"send",
"(",
"self",
",",
"sender",
":",
"PytgbotApiBot",
")",
":",
"return",
"sender",
".",
"send_game",
"(",
"# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id",
"game_short_name",
"=",
"self",
".",
"game_short_name"... | Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage | [
"Send",
"the",
"message",
"via",
"pytgbot",
"."
] | python | train |
saltstack/salt | salt/modules/ansiblegate.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L94-L107 | def load_module(self, module):
'''
Introspect Ansible module.
:param module:
:return:
'''
m_ref = self._modules_map.get(module)
if m_ref is None:
raise LoaderError('Module "{0}" was not found'.format(module))
mod = importlib.import_module('ans... | [
"def",
"load_module",
"(",
"self",
",",
"module",
")",
":",
"m_ref",
"=",
"self",
".",
"_modules_map",
".",
"get",
"(",
"module",
")",
"if",
"m_ref",
"is",
"None",
":",
"raise",
"LoaderError",
"(",
"'Module \"{0}\" was not found'",
".",
"format",
"(",
"mod... | Introspect Ansible module.
:param module:
:return: | [
"Introspect",
"Ansible",
"module",
"."
] | python | train |
alpha-xone/xbbg | xbbg/blp.py | https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L350-L398 | def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame:
"""
Bloomberg intraday bar data within market session
Args:
ticker: ticker
dt: date
session: examples include
day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000
**kwargs:
... | [
"def",
"intraday",
"(",
"ticker",
",",
"dt",
",",
"session",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"pd",
".",
"DataFrame",
":",
"from",
"xbbg",
".",
"core",
"import",
"intervals",
"cur_data",
"=",
"bdib",
"(",
"ticker",
"=",
"ticker",
",",
... | Bloomberg intraday bar data within market session
Args:
ticker: ticker
dt: date
session: examples include
day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000
**kwargs:
ref: reference ticker or exchange for timezone
keep_tz: if ... | [
"Bloomberg",
"intraday",
"bar",
"data",
"within",
"market",
"session"
] | python | valid |
tanghaibao/jcvi | jcvi/utils/aws.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/aws.py#L326-L341 | def rm(args):
"""
%prog rm "s3://hli-mv-data-science/htang/str/*.csv"
Remove a bunch of files.
"""
p = OptionParser(rm.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
store, = args
contents = glob_s3(store)
for c in contents:
... | [
"def",
"rm",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"rm",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
"... | %prog rm "s3://hli-mv-data-science/htang/str/*.csv"
Remove a bunch of files. | [
"%prog",
"rm",
"s3",
":",
"//",
"hli",
"-",
"mv",
"-",
"data",
"-",
"science",
"/",
"htang",
"/",
"str",
"/",
"*",
".",
"csv"
] | python | train |
hydpy-dev/hydpy | hydpy/core/selectiontools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/selectiontools.py#L819-L828 | def deselect_elementnames(self, *substrings: str) -> 'Selection':
"""Restrict the current selection to all elements with a name
not containing at least one of the given substrings. (does
not affect any nodes).
See the documentation on method |Selection.search_elementnames| for
... | [
"def",
"deselect_elementnames",
"(",
"self",
",",
"*",
"substrings",
":",
"str",
")",
"->",
"'Selection'",
":",
"self",
".",
"elements",
"-=",
"self",
".",
"search_elementnames",
"(",
"*",
"substrings",
")",
".",
"elements",
"return",
"self"
] | Restrict the current selection to all elements with a name
not containing at least one of the given substrings. (does
not affect any nodes).
See the documentation on method |Selection.search_elementnames| for
additional information. | [
"Restrict",
"the",
"current",
"selection",
"to",
"all",
"elements",
"with",
"a",
"name",
"not",
"containing",
"at",
"least",
"one",
"of",
"the",
"given",
"substrings",
".",
"(",
"does",
"not",
"affect",
"any",
"nodes",
")",
"."
] | python | train |
mbarkhau/tinypng | tinypng/api.py | https://github.com/mbarkhau/tinypng/blob/58e33cd5b46b26aab530a184b70856f7e936d79a/tinypng/api.py#L84-L99 | def get_shrink_data_info(in_data, api_key=None):
"""Shrink binary data of a png
returns api_info
"""
if api_key:
return _shrink_info(in_data, api_key)
api_keys = find_keys()
for key in api_keys:
try:
return _shrink_info(in_data, key)
except ValueError:
... | [
"def",
"get_shrink_data_info",
"(",
"in_data",
",",
"api_key",
"=",
"None",
")",
":",
"if",
"api_key",
":",
"return",
"_shrink_info",
"(",
"in_data",
",",
"api_key",
")",
"api_keys",
"=",
"find_keys",
"(",
")",
"for",
"key",
"in",
"api_keys",
":",
"try",
... | Shrink binary data of a png
returns api_info | [
"Shrink",
"binary",
"data",
"of",
"a",
"png"
] | python | train |
nteract/papermill | papermill/engines.py | https://github.com/nteract/papermill/blob/7423a303f3fa22ec6d03edf5fd9700d659b5a6fa/papermill/engines.py#L292-L317 | def execute_notebook(
cls, nb, kernel_name, output_path=None, progress_bar=True, log_output=False, **kwargs
):
"""
A wrapper to handle notebook execution tasks.
Wraps the notebook object in a `NotebookExecutionManager` in order to track
execution state in a uniform manner. T... | [
"def",
"execute_notebook",
"(",
"cls",
",",
"nb",
",",
"kernel_name",
",",
"output_path",
"=",
"None",
",",
"progress_bar",
"=",
"True",
",",
"log_output",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"nb_man",
"=",
"NotebookExecutionManager",
"(",
"nb... | A wrapper to handle notebook execution tasks.
Wraps the notebook object in a `NotebookExecutionManager` in order to track
execution state in a uniform manner. This is meant to help simplify
engine implementations. This allows a developer to just focus on
iterating and executing the cell... | [
"A",
"wrapper",
"to",
"handle",
"notebook",
"execution",
"tasks",
"."
] | python | train |
ungarj/mapchete | mapchete/formats/default/png.py | https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/png.py#L181-L195 | def for_web(self, data):
"""
Convert data to web output.
Parameters
----------
data : array
Returns
-------
web data : array
"""
rgba = self._prepare_array_for_png(data)
data = ma.masked_where(rgba == self.nodata, rgba)
re... | [
"def",
"for_web",
"(",
"self",
",",
"data",
")",
":",
"rgba",
"=",
"self",
".",
"_prepare_array_for_png",
"(",
"data",
")",
"data",
"=",
"ma",
".",
"masked_where",
"(",
"rgba",
"==",
"self",
".",
"nodata",
",",
"rgba",
")",
"return",
"memory_file",
"("... | Convert data to web output.
Parameters
----------
data : array
Returns
-------
web data : array | [
"Convert",
"data",
"to",
"web",
"output",
"."
] | python | valid |
6809/MC6809 | MC6809/components/mc6809_base.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_base.py#L631-L639 | def instruction_DEC_register(self, opcode, register):
""" Decrement accumulator """
a = register.value
r = self.DEC(a)
# log.debug("$%x DEC %s value $%x -1 = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) | [
"def",
"instruction_DEC_register",
"(",
"self",
",",
"opcode",
",",
"register",
")",
":",
"a",
"=",
"register",
".",
"value",
"r",
"=",
"self",
".",
"DEC",
"(",
"a",
")",
"# log.debug(\"$%x DEC %s value $%x -1 = $%x\" % (",
"# self.program_counter,",... | Decrement accumulator | [
"Decrement",
"accumulator"
] | python | train |
Atrox/haikunatorpy | haikunator/haikunator.py | https://github.com/Atrox/haikunatorpy/blob/47551e8564dc903341706c35852f7b66e7e49a24/haikunator/haikunator.py#L53-L76 | def haikunate(self, delimiter='-', token_length=4, token_hex=False, token_chars='0123456789'):
"""
Generate heroku-like random names to use in your python applications
:param delimiter: Delimiter
:param token_length: TokenLength
:param token_hex: TokenHex
:param token_ch... | [
"def",
"haikunate",
"(",
"self",
",",
"delimiter",
"=",
"'-'",
",",
"token_length",
"=",
"4",
",",
"token_hex",
"=",
"False",
",",
"token_chars",
"=",
"'0123456789'",
")",
":",
"if",
"token_hex",
":",
"token_chars",
"=",
"'0123456789abcdef'",
"adjective",
"=... | Generate heroku-like random names to use in your python applications
:param delimiter: Delimiter
:param token_length: TokenLength
:param token_hex: TokenHex
:param token_chars: TokenChars
:type delimiter: str
:type token_length: int
:type token_hex: bool
... | [
"Generate",
"heroku",
"-",
"like",
"random",
"names",
"to",
"use",
"in",
"your",
"python",
"applications"
] | python | train |
hydpy-dev/hydpy | hydpy/core/devicetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/devicetools.py#L1017-L1026 | def conditions(self) -> \
Dict[str, Dict[str, Dict[str, Union[float, numpy.ndarray]]]]:
"""A nested dictionary containing the values of all
|ConditionSequence| objects of all currently handled models.
See the documentation on property |HydPy.conditions| for further
informati... | [
"def",
"conditions",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Union",
"[",
"float",
",",
"numpy",
".",
"ndarray",
"]",
"]",
"]",
"]",
":",
"return",
"{",
"element",
".",
"name",
":",
"e... | A nested dictionary containing the values of all
|ConditionSequence| objects of all currently handled models.
See the documentation on property |HydPy.conditions| for further
information. | [
"A",
"nested",
"dictionary",
"containing",
"the",
"values",
"of",
"all",
"|ConditionSequence|",
"objects",
"of",
"all",
"currently",
"handled",
"models",
"."
] | python | train |
disqus/gargoyle | gargoyle/manager.py | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/manager.py#L131-L141 | def get_all_conditions(self):
"""
Returns a generator which yields groups of lists of conditions.
>>> for set_id, label, field in gargoyle.get_all_conditions(): #doctest: +SKIP
>>> print "%(label)s: %(field)s" % (label, field.label) #doctest: +SKIP
"""
for condition_... | [
"def",
"get_all_conditions",
"(",
"self",
")",
":",
"for",
"condition_set",
"in",
"sorted",
"(",
"self",
".",
"get_condition_sets",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"get_group_label",
"(",
")",
")",
":",
"group",
"=",
"unicode",
... | Returns a generator which yields groups of lists of conditions.
>>> for set_id, label, field in gargoyle.get_all_conditions(): #doctest: +SKIP
>>> print "%(label)s: %(field)s" % (label, field.label) #doctest: +SKIP | [
"Returns",
"a",
"generator",
"which",
"yields",
"groups",
"of",
"lists",
"of",
"conditions",
"."
] | python | train |
chimera0/accel-brain-code | Reinforcement-Learning/pyqlearning/annealingmodel/distancecomputable/euclidean.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/annealingmodel/distancecomputable/euclidean.py#L11-L20 | def compute(self, x, y):
'''
Args:
x: Data point.
y: Data point.
Returns:
Distance.
'''
return np.sqrt(np.sum((x-y)**2)) | [
"def",
"compute",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"(",
"x",
"-",
"y",
")",
"**",
"2",
")",
")"
] | Args:
x: Data point.
y: Data point.
Returns:
Distance. | [
"Args",
":",
"x",
":",
"Data",
"point",
".",
"y",
":",
"Data",
"point",
".",
"Returns",
":",
"Distance",
"."
] | python | train |
c-w/gutenberg | gutenberg/_util/os.py | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/os.py#L39-L67 | def determine_encoding(path, default=None):
"""Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str... | [
"def",
"determine_encoding",
"(",
"path",
",",
"default",
"=",
"None",
")",
":",
"byte_order_marks",
"=",
"(",
"(",
"'utf-8-sig'",
",",
"(",
"codecs",
".",
"BOM_UTF8",
",",
")",
")",
",",
"(",
"'utf-16'",
",",
"(",
"codecs",
".",
"BOM_UTF16_LE",
",",
"... | Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str: The encoding of the file. | [
"Determines",
"the",
"encoding",
"of",
"a",
"file",
"based",
"on",
"byte",
"order",
"marks",
"."
] | python | train |
rootpy/rootpy | rootpy/utils/inject_closure.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/utils/inject_closure.py#L137-L165 | def inject_closure_values(func, **kwargs):
"""
Returns a new function identical to the previous one except that it acts as
though global variables named in `kwargs` have been closed over with the
values specified in the `kwargs` dictionary.
Works on properties, class/static methods and functions.
... | [
"def",
"inject_closure_values",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"wrapped_by",
"=",
"None",
"if",
"isinstance",
"(",
"func",
",",
"property",
")",
":",
"fget",
",",
"fset",
",",
"fdel",
"=",
"func",
".",
"fget",
",",
"func",
".",
"fset... | Returns a new function identical to the previous one except that it acts as
though global variables named in `kwargs` have been closed over with the
values specified in the `kwargs` dictionary.
Works on properties, class/static methods and functions.
This can be useful for mocking and other nefarious ... | [
"Returns",
"a",
"new",
"function",
"identical",
"to",
"the",
"previous",
"one",
"except",
"that",
"it",
"acts",
"as",
"though",
"global",
"variables",
"named",
"in",
"kwargs",
"have",
"been",
"closed",
"over",
"with",
"the",
"values",
"specified",
"in",
"the... | python | train |
blazelibs/blazeutils | blazeutils/decorators.py | https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/decorators.py#L346-L396 | def memoize(method_to_wrap):
"""
Currently only works on instance methods. Designed for use with SQLAlchemy entities. Could
be updated in the future to be more flexible.
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
a... | [
"def",
"memoize",
"(",
"method_to_wrap",
")",
":",
"memoize_key",
"=",
"'_memoize_cache_{0}'",
".",
"format",
"(",
"id",
"(",
"method_to_wrap",
")",
")",
"@",
"wrapt",
".",
"decorator",
"def",
"inner_memoize",
"(",
"wrapped",
",",
"instance",
",",
"args",
",... | Currently only works on instance methods. Designed for use with SQLAlchemy entities. Could
be updated in the future to be more flexible.
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
addresses = relationship("Address", backref="u... | [
"Currently",
"only",
"works",
"on",
"instance",
"methods",
".",
"Designed",
"for",
"use",
"with",
"SQLAlchemy",
"entities",
".",
"Could",
"be",
"updated",
"in",
"the",
"future",
"to",
"be",
"more",
"flexible",
"."
] | python | train |
rgs1/zk_shell | zk_shell/xclient.py | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/xclient.py#L159-L161 | def get_bytes(self, *args, **kwargs):
""" no string decoding performed """
return super(XClient, self).get(*args, **kwargs) | [
"def",
"get_bytes",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"XClient",
",",
"self",
")",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | no string decoding performed | [
"no",
"string",
"decoding",
"performed"
] | python | train |
jazzband/django-ddp | dddp/apps.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/apps.py#L18-L35 | def ready(self):
"""Initialisation for django-ddp (setup lookups and signal handlers)."""
if not settings.DATABASES:
raise ImproperlyConfigured('No databases configured.')
for (alias, conf) in settings.DATABASES.items():
engine = conf['ENGINE']
if engine not i... | [
"def",
"ready",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"DATABASES",
":",
"raise",
"ImproperlyConfigured",
"(",
"'No databases configured.'",
")",
"for",
"(",
"alias",
",",
"conf",
")",
"in",
"settings",
".",
"DATABASES",
".",
"items",
"(",
")... | Initialisation for django-ddp (setup lookups and signal handlers). | [
"Initialisation",
"for",
"django",
"-",
"ddp",
"(",
"setup",
"lookups",
"and",
"signal",
"handlers",
")",
"."
] | python | test |
nerdvegas/rez | src/rez/utils/graph_utils.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L20-L66 | def read_graph_from_string(txt):
"""Read a graph from a string, either in dot format, or our own
compressed format.
Returns:
`pygraph.digraph`: Graph object.
"""
if not txt.startswith('{'):
return read_dot(txt) # standard dot format
def conv(value):
if isinstance(value... | [
"def",
"read_graph_from_string",
"(",
"txt",
")",
":",
"if",
"not",
"txt",
".",
"startswith",
"(",
"'{'",
")",
":",
"return",
"read_dot",
"(",
"txt",
")",
"# standard dot format",
"def",
"conv",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
"... | Read a graph from a string, either in dot format, or our own
compressed format.
Returns:
`pygraph.digraph`: Graph object. | [
"Read",
"a",
"graph",
"from",
"a",
"string",
"either",
"in",
"dot",
"format",
"or",
"our",
"own",
"compressed",
"format",
"."
] | python | train |
lemieuxl/pyGenClean | pyGenClean/Ethnicity/plot_eigenvalues.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/Ethnicity/plot_eigenvalues.py#L131-L154 | def read_eigenvalues(i_filename):
"""Reads the eigenvalues from EIGENSOFT results.
:param i_filename: the name of the input file.
:type i_filename: str
:returns: a :py:class:`numpy.ndarray` array containing the eigenvalues.
"""
# The data is the first line of the result file (should begin wi... | [
"def",
"read_eigenvalues",
"(",
"i_filename",
")",
":",
"# The data is the first line of the result file (should begin with",
"# \"#eigvals\"",
"data",
"=",
"None",
"with",
"open",
"(",
"i_filename",
",",
"\"r\"",
")",
"as",
"i_file",
":",
"data",
"=",
"re",
".",
"s... | Reads the eigenvalues from EIGENSOFT results.
:param i_filename: the name of the input file.
:type i_filename: str
:returns: a :py:class:`numpy.ndarray` array containing the eigenvalues. | [
"Reads",
"the",
"eigenvalues",
"from",
"EIGENSOFT",
"results",
"."
] | python | train |
HazardDede/dictmentor | dictmentor/validator.py | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/validator.py#L150-L209 | def is_stream(raise_ex: bool = False, summary: bool = True,
**items: Any) -> ValidationReturn:
"""
Tests if the given key-value pairs (items) are all streams. Basically checks if the item
provides a read(...) method.
Per default this function yields whether ``True`` or ... | [
"def",
"is_stream",
"(",
"raise_ex",
":",
"bool",
"=",
"False",
",",
"summary",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"items",
":",
"Any",
")",
"->",
"ValidationReturn",
":",
"return",
"Validator",
".",
"__test_all",
"(",
"condition",
"=",
"lambda",
... | Tests if the given key-value pairs (items) are all streams. Basically checks if the item
provides a read(...) method.
Per default this function yields whether ``True`` or ``False`` depending on the fact if all
items withstand the validation or not. Per default the validation / evaluation is
... | [
"Tests",
"if",
"the",
"given",
"key",
"-",
"value",
"pairs",
"(",
"items",
")",
"are",
"all",
"streams",
".",
"Basically",
"checks",
"if",
"the",
"item",
"provides",
"a",
"read",
"(",
"...",
")",
"method",
".",
"Per",
"default",
"this",
"function",
"yi... | python | train |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/networking/network_daemon.py#L84-L99 | def HandleNetworkInterfaces(self, result):
"""Called when network interface metadata changes.
Args:
result: dict, the metadata response with the network interfaces.
"""
network_interfaces = self._ExtractInterfaceMetadata(result)
if self.network_setup_enabled:
self.network_setup.EnableN... | [
"def",
"HandleNetworkInterfaces",
"(",
"self",
",",
"result",
")",
":",
"network_interfaces",
"=",
"self",
".",
"_ExtractInterfaceMetadata",
"(",
"result",
")",
"if",
"self",
".",
"network_setup_enabled",
":",
"self",
".",
"network_setup",
".",
"EnableNetworkInterfa... | Called when network interface metadata changes.
Args:
result: dict, the metadata response with the network interfaces. | [
"Called",
"when",
"network",
"interface",
"metadata",
"changes",
"."
] | python | train |
dmcc/PyStanfordDependencies | StanfordDependencies/StanfordDependencies.py | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/StanfordDependencies.py#L126-L140 | def setup_and_get_default_path(self, jar_base_filename):
"""Determine the user-specific install path for the Stanford
Dependencies jar if the jar_url is not specified and ensure that
it is writable (that is, make sure the directory exists). Returns
the full path for where the jar file sh... | [
"def",
"setup_and_get_default_path",
"(",
"self",
",",
"jar_base_filename",
")",
":",
"import",
"os",
"import",
"errno",
"install_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"INSTALL_DIR",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"install_dir",
... | Determine the user-specific install path for the Stanford
Dependencies jar if the jar_url is not specified and ensure that
it is writable (that is, make sure the directory exists). Returns
the full path for where the jar file should be installed. | [
"Determine",
"the",
"user",
"-",
"specific",
"install",
"path",
"for",
"the",
"Stanford",
"Dependencies",
"jar",
"if",
"the",
"jar_url",
"is",
"not",
"specified",
"and",
"ensure",
"that",
"it",
"is",
"writable",
"(",
"that",
"is",
"make",
"sure",
"the",
"d... | python | train |
workhorsy/py-cpuinfo | cpuinfo/cpuinfo.py | https://github.com/workhorsy/py-cpuinfo/blob/c15afb770c1139bf76215852e17eb4f677ca3d2f/cpuinfo/cpuinfo.py#L2275-L2306 | def get_cpu_info_json():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string
'''
import json
output = None
# If running under pyinstaller, run normally
if getattr(sys, 'frozen', False):
info = _get_cpu_info_internal()
output = json.dumps(info... | [
"def",
"get_cpu_info_json",
"(",
")",
":",
"import",
"json",
"output",
"=",
"None",
"# If running under pyinstaller, run normally",
"if",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
":",
"info",
"=",
"_get_cpu_info_internal",
"(",
")",
"output",
"... | Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string | [
"Returns",
"the",
"CPU",
"info",
"by",
"using",
"the",
"best",
"sources",
"of",
"information",
"for",
"your",
"OS",
".",
"Returns",
"the",
"result",
"in",
"a",
"json",
"string"
] | python | train |
PyMLGame/pymlgame | game_example.py | https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L113-L132 | def handle_events(self):
"""
Loop through all events.
"""
for event in pymlgame.get_events():
if event.type == E_NEWCTLR:
#print(datetime.now(), '### new player connected with uid', event.uid)
self.players[event.uid] = {'name': 'alien_{}'.forma... | [
"def",
"handle_events",
"(",
"self",
")",
":",
"for",
"event",
"in",
"pymlgame",
".",
"get_events",
"(",
")",
":",
"if",
"event",
".",
"type",
"==",
"E_NEWCTLR",
":",
"#print(datetime.now(), '### new player connected with uid', event.uid)",
"self",
".",
"players",
... | Loop through all events. | [
"Loop",
"through",
"all",
"events",
"."
] | python | train |
gagneurlab/concise | concise/utils/plot.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/plot.py#L196-L234 | def seqlogo(letter_heights, vocab="DNA", ax=None):
"""Make a logo plot
# Arguments
letter_heights: "motif length" x "vocabulary size" numpy array
Can also contain negative values.
vocab: str, Vocabulary name. Can be: DNA, RNA, AA, RNAStruct.
ax: matplotlib axis
"""
ax = ax o... | [
"def",
"seqlogo",
"(",
"letter_heights",
",",
"vocab",
"=",
"\"DNA\"",
",",
"ax",
"=",
"None",
")",
":",
"ax",
"=",
"ax",
"or",
"plt",
".",
"gca",
"(",
")",
"assert",
"letter_heights",
".",
"shape",
"[",
"1",
"]",
"==",
"len",
"(",
"VOCABS",
"[",
... | Make a logo plot
# Arguments
letter_heights: "motif length" x "vocabulary size" numpy array
Can also contain negative values.
vocab: str, Vocabulary name. Can be: DNA, RNA, AA, RNAStruct.
ax: matplotlib axis | [
"Make",
"a",
"logo",
"plot"
] | python | train |
gagneurlab/concise | concise/legacy/concise.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L519-L532 | def _get_var_res(self, graph, var, other_var):
"""
Get the weights from our graph
"""
with tf.Session(graph=graph) as sess:
sess.run(other_var["init"])
# all_vars = tf.all_variables()
# print("All variable names")
# print([var.name for var... | [
"def",
"_get_var_res",
"(",
"self",
",",
"graph",
",",
"var",
",",
"other_var",
")",
":",
"with",
"tf",
".",
"Session",
"(",
"graph",
"=",
"graph",
")",
"as",
"sess",
":",
"sess",
".",
"run",
"(",
"other_var",
"[",
"\"init\"",
"]",
")",
"# all_vars =... | Get the weights from our graph | [
"Get",
"the",
"weights",
"from",
"our",
"graph"
] | python | train |
ericflo/hurricane | hurricane/handlers/comet/utils.py | https://github.com/ericflo/hurricane/blob/c192b711b2b1c06a386d1a1a47f538b13a659cde/hurricane/handlers/comet/utils.py#L10-L23 | def unquote_header_value(value):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
"""
if value and value[0] == value[-1] == '"':
# thi... | [
"def",
"unquote_header_value",
"(",
"value",
")",
":",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"# this is not the real unquoting, but fixing this so that the",
"# RFC is met will result in bugs with internet ex... | r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote. | [
"r",
"Unquotes",
"a",
"header",
"value",
".",
"(",
"Reversal",
"of",
":",
"func",
":",
"quote_header_value",
")",
".",
"This",
"does",
"not",
"use",
"the",
"real",
"unquoting",
"but",
"what",
"browsers",
"are",
"actually",
"using",
"for",
"quoting",
"."
] | python | train |
saltstack/salt | salt/grains/core.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/core.py#L1322-L1350 | def _osx_platform_data():
'''
Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber
'''
cmd = 'system_profiler SPHardwareDataType'
hardware = __salt__['cmd.r... | [
"def",
"_osx_platform_data",
"(",
")",
":",
"cmd",
"=",
"'system_profiler SPHardwareDataType'",
"hardware",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"grains",
"=",
"{",
"}",
"for",
"line",
"in",
"hardware",
".",
"splitlines",
"(",
")",
":",
... | Additional data for macOS systems
Returns: A dictionary containing values for the following:
- model_name
- boot_rom_version
- smc_version
- system_serialnumber | [
"Additional",
"data",
"for",
"macOS",
"systems",
"Returns",
":",
"A",
"dictionary",
"containing",
"values",
"for",
"the",
"following",
":",
"-",
"model_name",
"-",
"boot_rom_version",
"-",
"smc_version",
"-",
"system_serialnumber"
] | python | train |
senaite/senaite.core | bika/lims/browser/worksheet/views/analyses.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/worksheet/views/analyses.py#L236-L270 | def get_uids_strpositions(self):
"""Returns a dict with the positions of each analysis within the
current worksheet in accordance with the current layout. The key of the
dict is the uid of the analysis and the value is an string
representation of the full position of the analysis within ... | [
"def",
"get_uids_strpositions",
"(",
"self",
")",
":",
"uids_positions",
"=",
"dict",
"(",
")",
"layout",
"=",
"self",
".",
"context",
".",
"getLayout",
"(",
")",
"layout",
"=",
"layout",
"and",
"layout",
"or",
"[",
"]",
"# Map the analysis uids with their pos... | Returns a dict with the positions of each analysis within the
current worksheet in accordance with the current layout. The key of the
dict is the uid of the analysis and the value is an string
representation of the full position of the analysis within the list:
{<analysis_uid>: '<sl... | [
"Returns",
"a",
"dict",
"with",
"the",
"positions",
"of",
"each",
"analysis",
"within",
"the",
"current",
"worksheet",
"in",
"accordance",
"with",
"the",
"current",
"layout",
".",
"The",
"key",
"of",
"the",
"dict",
"is",
"the",
"uid",
"of",
"the",
"analysi... | python | train |
materialsproject/pymatgen | pymatgen/electronic_structure/boltztrap.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/boltztrap.py#L2321-L2329 | def eta_from_seebeck(seeb,Lambda):
"""
It takes a value of seebeck and adjusts the analytic seebeck until it's equal
Returns: eta where the two seebeck coefficients are equal
(reduced chemical potential)
"""
from scipy.optimize import fsolve
out = fsolve(lambda x: (seebeck_spb(... | [
"def",
"eta_from_seebeck",
"(",
"seeb",
",",
"Lambda",
")",
":",
"from",
"scipy",
".",
"optimize",
"import",
"fsolve",
"out",
"=",
"fsolve",
"(",
"lambda",
"x",
":",
"(",
"seebeck_spb",
"(",
"x",
",",
"Lambda",
")",
"-",
"abs",
"(",
"seeb",
")",
")",... | It takes a value of seebeck and adjusts the analytic seebeck until it's equal
Returns: eta where the two seebeck coefficients are equal
(reduced chemical potential) | [
"It",
"takes",
"a",
"value",
"of",
"seebeck",
"and",
"adjusts",
"the",
"analytic",
"seebeck",
"until",
"it",
"s",
"equal",
"Returns",
":",
"eta",
"where",
"the",
"two",
"seebeck",
"coefficients",
"are",
"equal",
"(",
"reduced",
"chemical",
"potential",
")"
] | python | train |
Falkonry/falkonry-python-client | falkonryclient/service/falkonry.py | https://github.com/Falkonry/falkonry-python-client/blob/0aeb2b00293ee94944f1634e9667401b03da29c1/falkonryclient/service/falkonry.py#L350-L361 | def get_entity_meta(self, datastream):
"""
To add entity meta data to a datastream
:param datastream: string
:param options: dict
"""
url = '/datastream/' + str(datastream) + '/entityMeta'
response = self.http.get(url)
entityMetaList = []
for entit... | [
"def",
"get_entity_meta",
"(",
"self",
",",
"datastream",
")",
":",
"url",
"=",
"'/datastream/'",
"+",
"str",
"(",
"datastream",
")",
"+",
"'/entityMeta'",
"response",
"=",
"self",
".",
"http",
".",
"get",
"(",
"url",
")",
"entityMetaList",
"=",
"[",
"]"... | To add entity meta data to a datastream
:param datastream: string
:param options: dict | [
"To",
"add",
"entity",
"meta",
"data",
"to",
"a",
"datastream",
":",
"param",
"datastream",
":",
"string",
":",
"param",
"options",
":",
"dict"
] | python | train |
fastai/fastai | fastai/text/transform.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L50-L56 | def replace_wrep(t:str) -> str:
"Replace word repetitions in `t`."
def _replace_wrep(m:Collection[str]) -> str:
c,cc = m.groups()
return f' {TK_WREP} {len(cc.split())+1} {c} '
re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})')
return re_wrep.sub(_replace_wrep, t) | [
"def",
"replace_wrep",
"(",
"t",
":",
"str",
")",
"->",
"str",
":",
"def",
"_replace_wrep",
"(",
"m",
":",
"Collection",
"[",
"str",
"]",
")",
"->",
"str",
":",
"c",
",",
"cc",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"f' {TK_WREP} {len(cc.split(... | Replace word repetitions in `t`. | [
"Replace",
"word",
"repetitions",
"in",
"t",
"."
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/graph_analytics/degree_counting.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/graph_analytics/degree_counting.py#L57-L119 | def create(graph, verbose=True):
"""
Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out :... | [
"def",
"create",
"(",
"graph",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"turicreate",
".",
"_cython",
".",
"cy_server",
"import",
"QuietProgress",
"if",
"not",
"isinstance",
"(",
"graph",
",",
"_SGraph",
")",
":",
"raise",
"TypeError",
"(",
"'\"graph... | Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
------... | [
"Compute",
"the",
"in",
"degree",
"out",
"degree",
"and",
"total",
"degree",
"of",
"each",
"vertex",
"."
] | python | train |
django-leonardo/django-leonardo | leonardo/module/web/widget/application/reverse.py | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widget/application/reverse.py#L112-L125 | def permalink(func):
"""
Decorator that calls app_reverse()
Use this instead of standard django.db.models.permalink if you want to
integrate the model through ApplicationContent. The wrapped function
must return 4 instead of 3 arguments::
class MyModel(models.Model):
@appmodels.p... | [
"def",
"permalink",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"app_reverse",
"(",
"*",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"wraps",
"(",
"func",
")",
... | Decorator that calls app_reverse()
Use this instead of standard django.db.models.permalink if you want to
integrate the model through ApplicationContent. The wrapped function
must return 4 instead of 3 arguments::
class MyModel(models.Model):
@appmodels.permalink
def get_abso... | [
"Decorator",
"that",
"calls",
"app_reverse",
"()",
"Use",
"this",
"instead",
"of",
"standard",
"django",
".",
"db",
".",
"models",
".",
"permalink",
"if",
"you",
"want",
"to",
"integrate",
"the",
"model",
"through",
"ApplicationContent",
".",
"The",
"wrapped",... | python | train |
RedHatInsights/insights-core | insights/client/mount.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/mount.py#L216-L256 | def _identifier_as_cid(self, identifier):
"""
Returns a container uuid for identifier.
If identifier is an image UUID or image tag, create a temporary
container and return its uuid.
"""
def __cname_matches(container, identifier):
return any([n for n in (conta... | [
"def",
"_identifier_as_cid",
"(",
"self",
",",
"identifier",
")",
":",
"def",
"__cname_matches",
"(",
"container",
",",
"identifier",
")",
":",
"return",
"any",
"(",
"[",
"n",
"for",
"n",
"in",
"(",
"container",
"[",
"'Names'",
"]",
"or",
"[",
"]",
")"... | Returns a container uuid for identifier.
If identifier is an image UUID or image tag, create a temporary
container and return its uuid. | [
"Returns",
"a",
"container",
"uuid",
"for",
"identifier",
"."
] | python | train |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L1161-L1164 | def p_concat(self, p):
'concat : LBRACE concatlist RBRACE'
p[0] = Concat(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_concat",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Concat",
"(",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1... | concat : LBRACE concatlist RBRACE | [
"concat",
":",
"LBRACE",
"concatlist",
"RBRACE"
] | python | train |
welbornprod/colr | colr/controls.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/controls.py#L139-L144 | def move_column(column=1, file=sys.stdout):
""" Move the cursor to the specified column, default 1.
Esc[<column>G
"""
move.column(column).write(file=file) | [
"def",
"move_column",
"(",
"column",
"=",
"1",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"move",
".",
"column",
"(",
"column",
")",
".",
"write",
"(",
"file",
"=",
"file",
")"
] | Move the cursor to the specified column, default 1.
Esc[<column>G | [
"Move",
"the",
"cursor",
"to",
"the",
"specified",
"column",
"default",
"1",
"."
] | python | train |
dranjan/python-plyfile | plyfile.py | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L841-L850 | def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration | [
"def",
"_read_bin",
"(",
"self",
",",
"stream",
",",
"byte_order",
")",
":",
"try",
":",
"return",
"_read_array",
"(",
"stream",
",",
"self",
".",
"dtype",
"(",
"byte_order",
")",
",",
"1",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"S... | Read data from a binary stream. Raise StopIteration if the
property could not be read. | [
"Read",
"data",
"from",
"a",
"binary",
"stream",
".",
"Raise",
"StopIteration",
"if",
"the",
"property",
"could",
"not",
"be",
"read",
"."
] | python | train |
opendatateam/udata | udata/search/commands.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/commands.py#L162-L214 | def index(models=None, name=None, force=False, keep=False):
'''
Initialize or rebuild the search index
Models to reindex can optionally be specified as arguments.
If not, all models are reindexed.
'''
index_name = name or default_index_name()
doc_types_names = [m.__name__.lower() for m in ... | [
"def",
"index",
"(",
"models",
"=",
"None",
",",
"name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"keep",
"=",
"False",
")",
":",
"index_name",
"=",
"name",
"or",
"default_index_name",
"(",
")",
"doc_types_names",
"=",
"[",
"m",
".",
"__name__",
... | Initialize or rebuild the search index
Models to reindex can optionally be specified as arguments.
If not, all models are reindexed. | [
"Initialize",
"or",
"rebuild",
"the",
"search",
"index"
] | python | train |
mmp2/megaman | megaman/geometry/rmetric.py | https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/geometry/rmetric.py#L256-L268 | def get_dual_rmetric( self, invert_h = False, mode_inv = 'svd' ):
"""
Compute the dual Riemannian Metric
This is not satisfactory, because if mdimG<mdimY the shape of H
will not be the same as the shape of G. TODO(maybe): return a (copied)
smaller H with only the rows and columns... | [
"def",
"get_dual_rmetric",
"(",
"self",
",",
"invert_h",
"=",
"False",
",",
"mode_inv",
"=",
"'svd'",
")",
":",
"if",
"self",
".",
"H",
"is",
"None",
":",
"self",
".",
"H",
",",
"self",
".",
"G",
",",
"self",
".",
"Hvv",
",",
"self",
".",
"Hsvals... | Compute the dual Riemannian Metric
This is not satisfactory, because if mdimG<mdimY the shape of H
will not be the same as the shape of G. TODO(maybe): return a (copied)
smaller H with only the rows and columns in G. | [
"Compute",
"the",
"dual",
"Riemannian",
"Metric",
"This",
"is",
"not",
"satisfactory",
"because",
"if",
"mdimG<mdimY",
"the",
"shape",
"of",
"H",
"will",
"not",
"be",
"the",
"same",
"as",
"the",
"shape",
"of",
"G",
".",
"TODO",
"(",
"maybe",
")",
":",
... | python | train |
iamjarret/pystockfish | pystockfish.py | https://github.com/iamjarret/pystockfish/blob/ae34a4b4d29c577c888b72691fcf0cb5a89b1792/pystockfish.py#L289-L297 | def isready(self):
"""
Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.'
"""
self.put('isready')
while True:
text = self.stdout.readline().strip()
if text == 'readyok':
return t... | [
"def",
"isready",
"(",
"self",
")",
":",
"self",
".",
"put",
"(",
"'isready'",
")",
"while",
"True",
":",
"text",
"=",
"self",
".",
"stdout",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"if",
"text",
"==",
"'readyok'",
":",
"return",
"text"
... | Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.' | [
"Used",
"to",
"synchronize",
"the",
"python",
"engine",
"object",
"with",
"the",
"back",
"-",
"end",
"engine",
".",
"Sends",
"isready",
"and",
"waits",
"for",
"readyok",
"."
] | python | train |
aws/aws-encryption-sdk-python | src/aws_encryption_sdk/internal/formatting/encryption_context.py | https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/encryption_context.py#L115-L129 | def read_string(source, offset, length):
"""Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of ... | [
"def",
"read_string",
"(",
"source",
",",
"offset",
",",
"length",
")",
":",
"end",
"=",
"offset",
"+",
"length",
"try",
":",
"return",
"(",
"codecs",
".",
"decode",
"(",
"source",
"[",
"offset",
":",
"end",
"]",
",",
"aws_encryption_sdk",
".",
"intern... | Reads a string from a byte string.
:param bytes source: Source byte string
:param int offset: Point in byte string to start reading
:param int length: Length of string to read
:returns: Read string and offset at point after read data
:rtype: tuple of str and int
:raises SerializationError: if u... | [
"Reads",
"a",
"string",
"from",
"a",
"byte",
"string",
"."
] | python | train |
knipknap/SpiffWorkflow | SpiffWorkflow/specs/base.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/specs/base.py#L303-L339 | def _on_ready(self, my_task):
"""
Return True on success, False otherwise.
:type my_task: Task
:param my_task: The associated task in the task tree.
"""
assert my_task is not None
self.test()
# Acquire locks, if any.
for lock in self.locks:
... | [
"def",
"_on_ready",
"(",
"self",
",",
"my_task",
")",
":",
"assert",
"my_task",
"is",
"not",
"None",
"self",
".",
"test",
"(",
")",
"# Acquire locks, if any.",
"for",
"lock",
"in",
"self",
".",
"locks",
":",
"mutex",
"=",
"my_task",
".",
"workflow",
".",... | Return True on success, False otherwise.
:type my_task: Task
:param my_task: The associated task in the task tree. | [
"Return",
"True",
"on",
"success",
"False",
"otherwise",
"."
] | python | valid |
myint/cppclean | cpp/symbols.py | https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L152-L172 | def add_symbol(self, symbol_name, namespace_stack, node, module):
"""Adds symbol_name defined in namespace_stack to the symbol table.
Args:
symbol_name: 'name of the symbol to lookup'
namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in']
node: ast.Node that de... | [
"def",
"add_symbol",
"(",
"self",
",",
"symbol_name",
",",
"namespace_stack",
",",
"node",
",",
"module",
")",
":",
"# TODO(nnorwitz): verify symbol_name doesn't contain :: ?",
"if",
"namespace_stack",
":",
"# Handle non-global symbols (ie, in some namespace).",
"last_namespace... | Adds symbol_name defined in namespace_stack to the symbol table.
Args:
symbol_name: 'name of the symbol to lookup'
namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in']
node: ast.Node that defines this symbol
module: module (any object) this symbol is define... | [
"Adds",
"symbol_name",
"defined",
"in",
"namespace_stack",
"to",
"the",
"symbol",
"table",
"."
] | python | train |
odlgroup/odl | odl/space/weighting.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/weighting.py#L426-L437 | def repr_part(self):
"""Return a string usable in a space's ``__repr__`` method."""
# Lazy import to improve `import odl` time
import scipy.sparse
if scipy.sparse.isspmatrix(self.matrix):
optargs = [('matrix', str(self.matrix), '')]
else:
optargs = [('mat... | [
"def",
"repr_part",
"(",
"self",
")",
":",
"# Lazy import to improve `import odl` time",
"import",
"scipy",
".",
"sparse",
"if",
"scipy",
".",
"sparse",
".",
"isspmatrix",
"(",
"self",
".",
"matrix",
")",
":",
"optargs",
"=",
"[",
"(",
"'matrix'",
",",
"str"... | Return a string usable in a space's ``__repr__`` method. | [
"Return",
"a",
"string",
"usable",
"in",
"a",
"space",
"s",
"__repr__",
"method",
"."
] | python | train |
clearclaw/pyver | pyver/__init__.py | https://github.com/clearclaw/pyver/blob/2717600b8595903feddba4588fa11d5d9f27d494/pyver/__init__.py#L10-L52 | def get_version (pkg = __name__, public = False):
"""
Uses `git describe` to dynamically generate a version for the
current code. The version is effecvtively a traditional tri-tuple
ala (major, minor, patch), with the addenda that in this case the
patch string is a combination of the number of commits since ... | [
"def",
"get_version",
"(",
"pkg",
"=",
"__name__",
",",
"public",
"=",
"False",
")",
":",
"try",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"except",
":",
"# pylint: disable=W0702",
"cwd",
"=",
"None",
"try",
":",
"try",
":",
"mod",
"=",
"__impo... | Uses `git describe` to dynamically generate a version for the
current code. The version is effecvtively a traditional tri-tuple
ala (major, minor, patch), with the addenda that in this case the
patch string is a combination of the number of commits since the
tag, plus the ID of the last commit. Further, the p... | [
"Uses",
"git",
"describe",
"to",
"dynamically",
"generate",
"a",
"version",
"for",
"the",
"current",
"code",
".",
"The",
"version",
"is",
"effecvtively",
"a",
"traditional",
"tri",
"-",
"tuple",
"ala",
"(",
"major",
"minor",
"patch",
")",
"with",
"the",
"a... | python | train |
numba/llvmlite | llvmlite/ir/values.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L20-L38 | def _escape_string(text, _map={}):
"""
Escape the given bytestring for safe use as a LLVM array constant.
"""
if isinstance(text, str):
text = text.encode('ascii')
assert isinstance(text, (bytes, bytearray))
if not _map:
for ch in range(256):
if ch in _VALID_CHARS:
... | [
"def",
"_escape_string",
"(",
"text",
",",
"_map",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"text",
"=",
"text",
".",
"encode",
"(",
"'ascii'",
")",
"assert",
"isinstance",
"(",
"text",
",",
"(",
"bytes",
",",... | Escape the given bytestring for safe use as a LLVM array constant. | [
"Escape",
"the",
"given",
"bytestring",
"for",
"safe",
"use",
"as",
"a",
"LLVM",
"array",
"constant",
"."
] | python | train |
markovmodel/PyEMMA | pyemma/util/annotators.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/annotators.py#L136-L161 | def shortcut(*names):
"""Add an shortcut (alias) to a decorated function, but not to class methods!
Use aliased/alias decorators for class members!
Calling the shortcut (alias) will call the decorated function. The shortcut name will be appended
to the module's __all__ variable and the shortcut functi... | [
"def",
"shortcut",
"(",
"*",
"names",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"globals_",
"=",
"f",
".",
"__globals__",
"for",
"name",
"in",
"names",
":",
"globals_",
"[",
"name",
"]",
"=",
"f",
"if",
"'__all__'",
"in",
"globals_",
"and",
"nam... | Add an shortcut (alias) to a decorated function, but not to class methods!
Use aliased/alias decorators for class members!
Calling the shortcut (alias) will call the decorated function. The shortcut name will be appended
to the module's __all__ variable and the shortcut function will inherit the function'... | [
"Add",
"an",
"shortcut",
"(",
"alias",
")",
"to",
"a",
"decorated",
"function",
"but",
"not",
"to",
"class",
"methods!"
] | python | train |
pymc-devs/pymc | pymc/gp/GPutils.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/GPutils.py#L232-L261 | def plot_envelope(M, C, mesh):
"""
plot_envelope(M,C,mesh)
plots the pointwise mean +/- sd envelope defined by M and C
along their base mesh.
:Arguments:
- `M`: A Gaussian process mean.
- `C`: A Gaussian process covariance
- `mesh`: The mesh on which to evaluate ... | [
"def",
"plot_envelope",
"(",
"M",
",",
"C",
",",
"mesh",
")",
":",
"try",
":",
"from",
"pylab",
"import",
"fill",
",",
"plot",
",",
"clf",
",",
"axis",
"x",
"=",
"concatenate",
"(",
"(",
"mesh",
",",
"mesh",
"[",
":",
":",
"-",
"1",
"]",
")",
... | plot_envelope(M,C,mesh)
plots the pointwise mean +/- sd envelope defined by M and C
along their base mesh.
:Arguments:
- `M`: A Gaussian process mean.
- `C`: A Gaussian process covariance
- `mesh`: The mesh on which to evaluate the mean and cov. | [
"plot_envelope",
"(",
"M",
"C",
"mesh",
")"
] | python | train |
saltstack/salt | salt/modules/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L2333-L2353 | def list_saml_providers(region=None, key=None, keyid=None, profile=None):
'''
List SAML providers.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.list_saml_providers
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
providers = []
... | [
"def",
"list_saml_providers",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
... | List SAML providers.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.list_saml_providers | [
"List",
"SAML",
"providers",
"."
] | python | train |
Formulka/django-fperms | fperms/__init__.py | https://github.com/Formulka/django-fperms/blob/88b8fa3dd87075a56d8bfeb2b9993c578c22694e/fperms/__init__.py#L9-L20 | def get_perm_model():
"""
Returns the Perm model that is active in this project.
"""
try:
return django_apps.get_model(settings.PERM_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'")
except LookupErr... | [
"def",
"get_perm_model",
"(",
")",
":",
"try",
":",
"return",
"django_apps",
".",
"get_model",
"(",
"settings",
".",
"PERM_MODEL",
",",
"require_ready",
"=",
"False",
")",
"except",
"ValueError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"PERM_MODEL must be of ... | Returns the Perm model that is active in this project. | [
"Returns",
"the",
"Perm",
"model",
"that",
"is",
"active",
"in",
"this",
"project",
"."
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/utilities/formattingfunctions.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/formattingfunctions.py#L224-L298 | def format_max_width(text, max_width=None, **kwargs):
"""
Takes a string and formats it to a max width seperated by carriage
returns
args:
max_width: the max with for a line
kwargs:
indent: the number of spaces to add to the start of each line
prepend: text to add to the st... | [
"def",
"format_max_width",
"(",
"text",
",",
"max_width",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ind",
"=",
"''",
"if",
"kwargs",
".",
"get",
"(",
"\"indent\"",
")",
":",
"ind",
"=",
"''",
".",
"ljust",
"(",
"kwargs",
"[",
"'indent'",
"]"... | Takes a string and formats it to a max width seperated by carriage
returns
args:
max_width: the max with for a line
kwargs:
indent: the number of spaces to add to the start of each line
prepend: text to add to the start of each line | [
"Takes",
"a",
"string",
"and",
"formats",
"it",
"to",
"a",
"max",
"width",
"seperated",
"by",
"carriage",
"returns"
] | python | train |
merll/docker-map | dockermap/map/config/main.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/config/main.py#L332-L428 | def dependency_items(self):
"""
Generates all containers' dependencies, i.e. an iterator on tuples in the format
``(container_name, used_containers)``, whereas the used containers are a set, and can be empty.
:return: Container dependencies.
:rtype: collections.Iterable
... | [
"def",
"dependency_items",
"(",
"self",
")",
":",
"def",
"_get_used_items_np",
"(",
"u",
")",
":",
"volume_config_name",
",",
"__",
",",
"volume_instance",
"=",
"u",
".",
"name",
".",
"partition",
"(",
"'.'",
")",
"attaching_config_name",
"=",
"attaching",
"... | Generates all containers' dependencies, i.e. an iterator on tuples in the format
``(container_name, used_containers)``, whereas the used containers are a set, and can be empty.
:return: Container dependencies.
:rtype: collections.Iterable | [
"Generates",
"all",
"containers",
"dependencies",
"i",
".",
"e",
".",
"an",
"iterator",
"on",
"tuples",
"in",
"the",
"format",
"(",
"container_name",
"used_containers",
")",
"whereas",
"the",
"used",
"containers",
"are",
"a",
"set",
"and",
"can",
"be",
"empt... | python | train |
mishbahr/django-connected | connected_accounts/providers/base.py | https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L73-L82 | def get_profile_data(self, raw_token):
"""Fetch user profile information."""
try:
response = self.request('get', self.profile_url, token=raw_token)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch user profile: {0}'.forma... | [
"def",
"get_profile_data",
"(",
"self",
",",
"raw_token",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"self",
".",
"profile_url",
",",
"token",
"=",
"raw_token",
")",
"response",
".",
"raise_for_status",
"(",
")",
"e... | Fetch user profile information. | [
"Fetch",
"user",
"profile",
"information",
"."
] | python | train |
HiPERCAM/hcam_widgets | hcam_widgets/widgets.py | https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L607-L625 | def add(self, num):
"""
Adds num to the current value, jumping up the next
multiple of mfac if the result is not a multiple already
"""
try:
val = self.value() + num
except:
val = num
chunk = self.mfac.value()
if val % chunk > 0:
... | [
"def",
"add",
"(",
"self",
",",
"num",
")",
":",
"try",
":",
"val",
"=",
"self",
".",
"value",
"(",
")",
"+",
"num",
"except",
":",
"val",
"=",
"num",
"chunk",
"=",
"self",
".",
"mfac",
".",
"value",
"(",
")",
"if",
"val",
"%",
"chunk",
">",
... | Adds num to the current value, jumping up the next
multiple of mfac if the result is not a multiple already | [
"Adds",
"num",
"to",
"the",
"current",
"value",
"jumping",
"up",
"the",
"next",
"multiple",
"of",
"mfac",
"if",
"the",
"result",
"is",
"not",
"a",
"multiple",
"already"
] | python | train |
edx/edx-lint | edx_lint/cmd/main.py | https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/cmd/main.py#L31-L39 | def show_help():
"""Print the help string for the edx_lint command."""
print("""\
Manage local config files from masters in edx_lint.
Commands:
""")
for cmd in [write_main, check_main, list_main]:
print(cmd.__doc__.lstrip("\n")) | [
"def",
"show_help",
"(",
")",
":",
"print",
"(",
"\"\"\"\\\nManage local config files from masters in edx_lint.\n\nCommands:\n\"\"\"",
")",
"for",
"cmd",
"in",
"[",
"write_main",
",",
"check_main",
",",
"list_main",
"]",
":",
"print",
"(",
"cmd",
".",
"__doc__",
"."... | Print the help string for the edx_lint command. | [
"Print",
"the",
"help",
"string",
"for",
"the",
"edx_lint",
"command",
"."
] | python | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.