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').where(
docType='main',
submissionDate='20160701',
appUpdateChannel='nightly'
)
"""
meta_bucket = 'net-mozaws-prod-us-west-2-pipeline-metadata'
store = S3Store(meta_bucket)
try:
source = json.loads(store.get_key('sources.json').read().decode('utf-8'))[source_name]
except KeyError:
raise Exception('Unknown source {}'.format(source_name))
schema = store.get_key('{}/schema.json'.format(source['metadata_prefix'])).read().decode('utf-8')
dimensions = [f['field_name'] for f in json.loads(schema)['dimensions']]
return Dataset(source['bucket'], dimensions, prefix=source['prefix']) | [
"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',
submissionDate='20160701',
appUpdateChannel='nightly'
) | [
"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'] = self.url
if hasattr(self, 'collection') and self.collection is not None:
_dict['collection'] = [x._to_dict() for x in self.collection]
return _dict | [
"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
into self.config_values
"""
# Username and password are required.
for item in [self.CONFIG_NAME_USER, self.CONFIG_NAME_KEY]:
if item not in config_data:
raise ValueError('Error: Missing %s in configuration.' % item)
configuration = Configuration()
# Add to the final configuration (required)
configuration.username = config_data[self.CONFIG_NAME_USER]
configuration.password = config_data[self.CONFIG_NAME_KEY]
# Proxy
if self.CONFIG_NAME_PROXY in config_data:
configuration.proxy = config_data[self.CONFIG_NAME_PROXY]
# Cert File
if self.CONFIG_NAME_SSL_CA_CERT in config_data:
configuration.ssl_ca_cert = config_data[self.
CONFIG_NAME_SSL_CA_CERT]
# Keep config values with class instance, and load api client!
self.config_values = config_data
try:
self.api_client = ApiClient(configuration)
except Exception as error:
if 'Proxy' in type(error).__name__:
raise ValueError(
'The specified proxy ' +
config_data[self.CONFIG_NAME_PROXY] +
' is not valid, please check your proxy settings')
else:
raise ValueError(
'Unauthorized: you must download an API key or export '
'credentials to the environment. Please see\n ' +
'https://github.com/Kaggle/kaggle-api#api-credentials ' +
'for instructions.') | [
"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
constructor = self.color_map.get(color, None)
if isinstance(constructor, basestring):
# If this is an X11 color name, we just hope there is a close SVG
# color name. We could use QColor's static method
# 'setAllowX11ColorNames()', but this is global and only available
# on X11. It seems cleaner to aim for uniformity of behavior.
return QtGui.QColor(constructor)
elif isinstance(constructor, (tuple, list)):
return QtGui.QColor(*constructor)
return None | [
"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:
ValueError: if the node already contains a scan object for
the path segment.
"""
if path_segment in self._path_segments:
raise ValueError('Path segment already set.')
if isinstance(scan_object, PathFilterScanTreeNode):
scan_object.parent = self
self._path_segments[path_segment] = scan_object | [
"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
the path segment. | [
"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 installed.
if len(dom) > 1:
list(dom.children)[1].replaceWith('') # Removing default content
soup = Element.soup(self)
dom.append(soup)
for plugin in self.plugins(deduplicate=True):
dom = plugin(dom)
return dom | [
"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 at_end: At the end of the editable line, so allow spaced for cursor.
:return: The offset within `text` to start at to reduce it to the required length.
"""
# Is the solution trivial? Worth optimizing for text heavy UIs...
if 2 * len(text) < max_width:
return 0
# OK - do it the hard way...
result = 0
string_len = wcswidth if unicode_aware else len
char_len = wcwidth if unicode_aware else lambda x: 1
display_end = string_len(text)
while display_end > max_width:
result += 1
display_end -= char_len(text[0])
text = text[1:]
if at_end and display_end == max_width:
result += 1
return result | [
"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: The offset within `text` to start at to reduce it to the required length. | [
"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 temporary reference
file as AECCAR0 + AECCAR2
3. Runs Bader analysis twice: once for charge, and a second time
for the charge difference (magnetization density).
:param path: path to folder to search in
:param suffix: specific suffix to look for (e.g. '.relax1' for 'CHGCAR.relax1.gz'
:return: summary dict
"""
def _get_filepath(filename, warning, path=path, suffix=suffix):
paths = glob.glob(os.path.join(path, filename + suffix + '*'))
if not paths:
warnings.warn(warning)
return None
if len(paths) > 1:
# using reverse=True because, if multiple files are present,
# they likely have suffixes 'static', 'relax', 'relax2', etc.
# and this would give 'static' over 'relax2' over 'relax'
# however, better to use 'suffix' kwarg to avoid this!
paths.sort(reverse=True)
warnings.warn('Multiple files detected, using {}'.format(os.path.basename(path)))
path = paths[0]
return path
chgcar_path = _get_filepath('CHGCAR', 'Could not find CHGCAR!')
chgcar = Chgcar.from_file(chgcar_path)
aeccar0_path = _get_filepath('AECCAR0', 'Could not find AECCAR0, interpret Bader results with caution.')
aeccar0 = Chgcar.from_file(aeccar0_path) if aeccar0_path else None
aeccar2_path = _get_filepath('AECCAR2', 'Could not find AECCAR2, interpret Bader results with caution.')
aeccar2 = Chgcar.from_file(aeccar2_path) if aeccar2_path else None
potcar_path = _get_filepath('POTCAR', 'Could not find POTCAR, cannot calculate charge transfer.')
potcar = Potcar.from_file(potcar_path) if potcar_path else None
return bader_analysis_from_objects(chgcar, potcar, aeccar0, aeccar2) | [
"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 Bader analysis twice: once for charge, and a second time
for the charge difference (magnetization density).
:param path: path to folder to search in
:param suffix: specific suffix to look for (e.g. '.relax1' for 'CHGCAR.relax1.gz'
:return: summary dict | [
"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|/]+)>', element, re.U)[0].split('/')
if re.search(', -(\w+)>', element, re.U):
# Suffix is provided
suffix = re.findall(', -(\w+)>', element, re.U)[0]
return [self.word + suffix]
if element.endswith('->'):
# Plural is the same as singular
return [self.word]
return [None] | [
"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,
top_percent: Optional[float] = None,
topology_weight: Optional[float] = None,
) -> Optional[Mapping[str, float]]:
"""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 relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.
Defaults to 1.0.
:param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).
:param topology_weight: The relative weight of the topolgical analysis core from
:py:func:`neurommsig_topology`. Defaults to 1.0.
:return: A dictionary from {annotation value: NeuroMMSig composite score}
Pre-processing steps:
1. Infer the central dogma with :func:``
2. Collapse all proteins, RNAs and miRNAs to genes with :func:``
3. Collapse variants to genes with :func:``
"""
return {
name: get_neurommsig_score(
graph=subgraph,
genes=genes,
ora_weight=ora_weight,
hub_weight=hub_weight,
top_percent=top_percent,
topology_weight=topology_weight,
)
for name, subgraph in subgraphs.items()
} | [
"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 relative weight of the hub analysis score from :py:func:`neurommsig_hubs`.
Defaults to 1.0.
:param top_percent: The percentage of top genes to use as hubs. Defaults to 5% (0.05).
:param topology_weight: The relative weight of the topolgical analysis core from
:py:func:`neurommsig_topology`. Defaults to 1.0.
:return: A dictionary from {annotation value: NeuroMMSig composite score}
Pre-processing steps:
1. Infer the central dogma with :func:``
2. Collapse all proteins, RNAs and miRNAs to genes with :func:``
3. Collapse variants to genes with :func:`` | [
"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_tuple[1]))\
.map(lambda t: Sample.from_ndarray(t[0], t[1]))
test_data = get_mnist(sc, "test", options.dataPath)\
.map(lambda rec_tuple: (normalizer(rec_tuple[0], mnist.TEST_MEAN, mnist.TEST_STD),
rec_tuple[1]))\
.map(lambda t: Sample.from_ndarray(t[0], t[1]))
return train_data, test_data | [
"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__(self.mol, newvalues, newdescs) | [
"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 (EPSG:4326)
y (float): map center y-coordinate in Mercator projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
Returns:
GridBB: Bounding box of the map in TileCoordinates.
>>> str(get_print_bbox(4164462.1505763642, 985738.7965919945, 14, 297, 150, 120))
'<tile min: <zoom: 14, x: 9891, y: 7786>, max: <zoom: 14, x: 9897, y: 7790>>'
"""
tiles_h = width * dpi_to_dpmm(dpi) / TILE_SIZE
tiles_v = height * dpi_to_dpmm(dpi) / TILE_SIZE
mercator_coords = MercatorCoordinate(x, y)
tile_coords = mercator_coords.to_tile(zoom)
tile_bb = GridBB(zoom,
min_x=tile_coords.x - math.ceil(tiles_h / 2),
max_x=tile_coords.x + math.ceil(tiles_h / 2),
min_y=tile_coords.y - math.ceil(tiles_v / 2),
max_y=tile_coords.y + math.ceil(tiles_v / 2))
return tile_bb | [
"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 projection (EPSG:4326)
zoom (int): tile zoom level to use for printing
width (float): page width in mm
height (float): page height in mm
dpi (int): resolution in dots per inch
Returns:
GridBB: Bounding box of the map in TileCoordinates.
>>> str(get_print_bbox(4164462.1505763642, 985738.7965919945, 14, 297, 150, 120))
'<tile min: <zoom: 14, x: 9891, y: 7786>, max: <zoom: 14, x: 9897, y: 7790>>' | [
"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 kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; show install all impact'
if ki is not None:
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
else:
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu and ki is None:
cmd = cmd + ' non-disruptive'
log.info("Check upgrade impact using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress',
'Pre-upgrade check failed']
kwargs.update({'error_pattern': error_pattern_list})
# Execute Upgrade Impact Check
try:
impact_check = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
impact_check = ast.literal_eval(e.message)
return _parse_upgrade_data(impact_check) | [
"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)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False | [
"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.
## Usage example in Tornado application
Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:
.. code-block:: python
from opentracing_instrumentation import request_context
@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)
request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)
with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)
:param span:
:return:
Return StackContext that wraps the request context.
"""
if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
raise RuntimeError('scope_manager is not TornadoScopeManager')
# Enter the newly created stack context so we have
# storage available for Span activation.
context = tracer_stack_context()
entered_context = _TracerEnteredStackContext(context)
if span is None:
return entered_context
opentracing.tracer.scope_manager.activate(span, False)
assert opentracing.tracer.active_span is not None
assert opentracing.tracer.active_span is span
return entered_context | [
"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
Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:
.. code-block:: python
from opentracing_instrumentation import request_context
@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)
request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)
with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)
:param span:
:return:
Return StackContext that wraps the request context. | [
"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_processors``)
params : array_like
Parameter values
vaired_data : array_like
Numerical values of the varied parameter.
varied_idx : int or str
Index of the varied parameter (indexing starts at 0).
If ``self.par_by_name`` this should be the name (str) of the varied
parameter.
internal_x0 : array_like (default: None)
Guess (*not* subject to ``self.post_processors``).
Overrides ``x0`` when given.
solver : str or callback
See :meth:`solve`.
propagate : bool (default: True)
Use last successful solution as ``x0`` in consecutive solves.
\\*\\*kwargs :
Keyword arguments pass along to :meth:`solve`.
Returns
-------
xout : array
Of shape ``(varied_data.size, x0.size)``.
info_dicts : list of dictionaries
Dictionaries each containing keys such as containing 'success', 'nfev', 'njev' etc.
"""
if self.x_by_name and isinstance(x0, dict):
x0 = [x0[k] for k in self.names]
if self.par_by_name:
if isinstance(params, dict):
params = [params[k] for k in self.param_names]
if isinstance(varied_idx, str):
varied_idx = self.param_names.index(varied_idx)
new_params = np.atleast_1d(np.array(params, dtype=np.float64))
xout = np.empty((len(varied_data), len(x0)))
self.internal_xout = np.empty_like(xout)
self.internal_params_out = np.empty((len(varied_data),
len(new_params)))
info_dicts = []
new_x0 = np.array(x0, dtype=np.float64) # copy
conds = kwargs.get('initial_conditions', None) # see ConditionalNeqSys
for idx, value in enumerate(varied_data):
try:
new_params[varied_idx] = value
except TypeError:
new_params = value # e.g. type(new_params) == int
if conds is not None:
kwargs['initial_conditions'] = conds
x, info_dict = self.solve(new_x0, new_params, internal_x0, solver,
**kwargs)
if propagate:
if info_dict['success']:
try:
# See ChainedNeqSys.solve
new_x0 = info_dict['x_vecs'][0]
internal_x0 = info_dict['internal_x_vecs'][0]
conds = info_dict['intermediate_info'][0].get(
'conditions', None)
except:
new_x0 = x
internal_x0 = None
conds = info_dict.get('conditions', None)
xout[idx, :] = x
self.internal_xout[idx, :] = self.internal_x
self.internal_params_out[idx, :] = self.internal_params
info_dicts.append(info_dict)
return xout, info_dicts | [
"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 parameter.
varied_idx : int or str
Index of the varied parameter (indexing starts at 0).
If ``self.par_by_name`` this should be the name (str) of the varied
parameter.
internal_x0 : array_like (default: None)
Guess (*not* subject to ``self.post_processors``).
Overrides ``x0`` when given.
solver : str or callback
See :meth:`solve`.
propagate : bool (default: True)
Use last successful solution as ``x0`` in consecutive solves.
\\*\\*kwargs :
Keyword arguments pass along to :meth:`solve`.
Returns
-------
xout : array
Of shape ``(varied_data.size, x0.size)``.
info_dicts : list of dictionaries
Dictionaries each containing keys such as containing 'success', 'nfev', 'njev' etc. | [
"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.
InvalidArgument: if message is not a common_pb2.Message.
"""
if not isinstance(message, common_pb2.Message):
raise InvalidArgument("Attempt to send unexpected message type: %s" %
message.__class__.__name__)
if not message.HasField("source"):
message.source.service_name = self._service_name
# Sometimes GRPC reports failure, even though the call succeeded. To prevent
# retry logic from creating duplicate messages we fix the message_id.
if not message.message_id:
message.message_id = os.urandom(32)
return self._RetryLoop(
lambda t: self._stub.InsertMessage(message, timeout=t)) | [
"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']['password']
credentials = (username, password)
# Get patient map file:
patient_id_map = self.open_and_parse_yaml(self.map_files['patient_ids'])
udp_internal_ids = patient_id_map.keys()
phenotype_fields = ['Patient', 'HPID', 'Present']
# Get phenotype ids for each patient
phenotype_params = {
'method': 'search_subjects',
'subject_type': 'Phenotype',
'search_mode': 'DEEP',
'fields': 'Patient',
'conditions': 'equals',
'values': ','.join(udp_internal_ids),
'user_fields': ','.join(phenotype_fields)
}
prioritized_variants = [
'Patient', 'Gene', 'Chromosome Position', 'Variant Allele', 'Transcript']
prioritized_params = {
'method': 'search_subjects',
'subject_type': 'Variant Prioritization',
'search_mode': 'DEEP',
'fields': 'Patient',
'conditions': 'equals',
'values': ','.join(udp_internal_ids),
'user_fields': ','.join(prioritized_variants),
'format': 'json'}
variant_fields = [
'Patient', 'Family', 'Chr', 'Build', 'Chromosome Position',
'Reference Allele', 'Variant Allele', 'Parent of origin',
'Allele Type', 'Mutation Type', 'Gene', 'Transcript', 'Original Amino Acid',
'Variant Amino Acid', 'Amino Acid Change', 'Segregates with',
'Position', 'Exon', 'Inheritance model', 'Zygosity', 'dbSNP ID',
'1K Frequency', 'Number of Alleles']
variant_params = {
'method': 'search_subjects',
'subject_type': 'Exome Analysis Results',
'search_mode': 'DEEP',
'fields': 'Patient',
'conditions': 'equals',
'user_fields': ','.join(variant_fields),
'format': 'json'}
pheno_file = open(
'/'.join((self.rawdir, self.files['patient_phenotypes']['file'])), 'w')
variant_file = open(
'/'.join((self.rawdir, self.files['patient_variants']['file'])), 'w')
pheno_file.write('{0}\n'.format('\t'.join(phenotype_fields)))
variant_file.write('{0}\n'.format('\t'.join(variant_fields)))
variant_gene = self._fetch_data_from_udp(
udp_internal_ids, prioritized_params, prioritized_variants, credentials)
variant_gene_map = dict()
for line in variant_gene:
variant_gene_map.setdefault(line[0], []).append(
# Try to make a unique value based on gene-pos-variantAlele-transcript
# TODO make this a dict for readability purposes
"{0}-{1}-{2}-{3}".format(line[1], line[2], line[3], line[4]))
variant_info = self._fetch_data_from_udp(
udp_internal_ids, variant_params, variant_fields, credentials)
for line in variant_info:
variant = "{0}-{1}-{2}-{3}".format(line[10], line[4], line[6], line[11])
if variant in variant_gene_map[line[0]]:
line[0] = patient_id_map[line[0]]
line[4] = re.sub(r'\.0$', '', line[4])
variant_file.write('{0}\n'.format('\t'.join(line)))
phenotype_info = self._fetch_data_from_udp(
udp_internal_ids, phenotype_params, phenotype_fields, credentials)
for line in phenotype_info:
line[0] = patient_id_map[line[0]]
pheno_file.write('{0}\n'.format('\t'.join(line)))
variant_file.close()
pheno_file.close()
return | [
"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: Connection result code (0: success, others: error)
"""
if result_code:
# result_code != 0: something wrong happened
_logger.error(
"Error connecting the MQTT server: %s (%d)",
paho.connack_string(result_code),
result_code,
)
else:
# Connection is OK: stop the reconnection timer
self.__stop_timer()
# Notify the caller, if any
if self.on_connect is not None:
try:
self.on_connect(self, result_code)
except Exception as ex:
_logger.exception("Error notifying MQTT listener: %s", ex) | [
"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:
change.clear() | [
"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 = self._sock.recv(recv_buffer).decode('latin-1')
data += chunk
if chunk.startswith('E,'): # error condition
if chunk.startswith('E,!NO_DATA!'):
log.warn('No data available for the given symbol or dates')
return
else:
raise Exception(chunk)
elif end_msg in chunk:
break
# Clean up the data.
data = data[:-1 * (len(end_msg) + 3)]
data = "".join(data.split("\r"))
data = data.replace(",\n", ",")[:-1]
data = data.split(",")
return data | [
"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 default value if conversion is not supported.
"""
value = self.get(key)
return DateTimeConverter.to_datetime_with_default(value, default_value) | [
"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 the collective count
per bin for all files.
TODO: is it faster to merge all in one command?
"""
# windows is a list of chromosome dfs per file
windows = iter(windows) # can iterate over because it is odict_values
merged = next(windows)
# if there is only one file, the merging is skipped since the windows is used up
for chromosome_dfs in windows:
# merge_same_files merges the chromosome files in parallel
merged = merge_same_files(merged, chromosome_dfs, nb_cpu)
return merged | [
"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)
if df is None:
return None
return df.plot() | [
"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
raise: NullArgument - ``objective_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.ontology.SubjectHierarchySession.get_child_subjects_template
if self._hierarchy_session.has_children(objective_id):
child_ids = self._hierarchy_session.get_children(objective_id)
collection = JSONClientValidated('learning',
collection='Objective',
runtime=self._runtime)
result = collection.find(
dict({'_id': {'$in': [ObjectId(child_id.get_identifier()) for child_id in child_ids]}},
**self._view_filter()))
return objects.ObjectiveList(
result,
runtime=self._runtime,
proxy=self._proxy)
raise errors.IllegalState('no children') | [
"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``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | [
"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_conditions=None,
access_conditions=None,
size=None,
format_name=None,
format_version=None,
inherit_dates=False,
inherit_notes=False,
):
"""
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.
:param string uri: The URI to an instantiation of the digital object.
:param string location_of_originals: If provided, will create an `originalsloc` (location of originals) note in the digital object using this text.
:param string object_type: The type of the digital object.
Defaults to "text".
:param string xlink_show: Controls how the file will be displayed.
For supported values, see: http://www.w3.org/TR/xlink/#link-behaviors
:param string xlink_actuate:
:param string use_statement:
:param string use_conditions: A paragraph of human-readable text to specify conditions of use for the digital object.
If provided, creates a "conditions governing use" note in the digital object.
:param string access_conditions: A paragraph of human-readable text to specify conditions of use for the digital object.
If provided, creates a "conditions governing access" note in the digital object.
:param int size: Size in bytes of the digital object
:param str format_name: Name of the digital object's format
:param str format_version: Name of the digital object's format version
:param bool inherit_dates: Inherit dates
:param bool inherit_notes: Inherit parent notes
"""
parent_record = self.get_record(parent_archival_object)
repository = parent_record["repository"]["ref"]
language = parent_record.get("language", "")
if not title:
filename = os.path.basename(uri) if uri is not None else "Untitled"
title = parent_record.get("display_string", filename)
new_object = {
"title": title,
"digital_object_id": identifier,
"digital_object_type": object_type,
"language": language,
"notes": [],
"restrictions": restricted,
"subjects": parent_record["subjects"],
"linked_agents": parent_record["linked_agents"],
}
if inherit_dates:
new_object["dates"] = parent_record["dates"]
if location_of_originals is not None:
new_object["notes"].append(
{
"jsonmodel_type": "note_digital_object",
"type": "originalsloc",
"content": [location_of_originals],
"publish": False,
}
)
if uri is not None:
new_object["file_versions"] = [
{
"file_uri": uri,
"use_statement": use_statement,
"xlink_show_attribute": xlink_show,
"xlink_actuate_attribute": xlink_actuate,
}
]
note_digital_object_type = [
"summary",
"bioghist",
"accessrestrict",
"userestrict",
"custodhist",
"dimensions",
"edition",
"extent",
"altformavail",
"originalsloc",
"note",
"acqinfo",
"inscription",
"langmaterial",
"legalstatus",
"physdesc",
"prefercite",
"processinfo",
"relatedmaterial",
]
if inherit_notes:
for pnote in parent_record["notes"]:
if pnote["type"] in note_digital_object_type:
dnote = pnote["type"]
else:
dnote = "note"
if "subnotes" in pnote:
content = []
for subnote in pnote["subnotes"]:
if "content" in subnote:
content.append(subnote["content"])
else:
LOGGER.info(
"No content field in %s, skipping adding to child digital object.",
subnote,
)
else:
content = pnote.get("content", "")
new_object["notes"].append(
{
"jsonmodel_type": "note_digital_object",
"type": dnote,
"label": pnote.get("label", ""),
"content": content,
"publish": pnote["publish"],
}
)
if use_conditions:
new_object["notes"].append(
{
"jsonmodel_type": "note_digital_object",
"type": "userestrict",
"content": [use_conditions],
"publish": True,
}
)
if access_conditions:
new_object["notes"].append(
{
"jsonmodel_type": "note_digital_object",
"type": "accessrestrict",
"content": [access_conditions],
"publish": True,
}
)
if restricted:
new_object["file_versions"][0]["publish"] = False
new_object["publish"] = False
if size:
new_object["file_versions"][0]["file_size_bytes"] = size
if format_name:
new_object["file_versions"][0]["file_format_name"] = format_name
if format_version:
new_object["file_versions"][0]["file_format_version"] = format_version
new_object_uri = self._post(
repository + "/digital_objects", data=json.dumps(new_object)
).json()["uri"]
# Now we need to update the parent object with a link to this instance
parent_record["instances"].append(
{
"instance_type": "digital_object",
"digital_object": {"ref": new_object_uri},
}
)
self._post(parent_archival_object, data=json.dumps(parent_record))
new_object["id"] = new_object_uri
return new_object | [
"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.
:param string uri: The URI to an instantiation of the digital object.
:param string location_of_originals: If provided, will create an `originalsloc` (location of originals) note in the digital object using this text.
:param string object_type: The type of the digital object.
Defaults to "text".
:param string xlink_show: Controls how the file will be displayed.
For supported values, see: http://www.w3.org/TR/xlink/#link-behaviors
:param string xlink_actuate:
:param string use_statement:
:param string use_conditions: A paragraph of human-readable text to specify conditions of use for the digital object.
If provided, creates a "conditions governing use" note in the digital object.
:param string access_conditions: A paragraph of human-readable text to specify conditions of use for the digital object.
If provided, creates a "conditions governing access" note in the digital object.
:param int size: Size in bytes of the digital object
:param str format_name: Name of the digital object's format
:param str format_version: Name of the digital object's format version
:param bool inherit_dates: Inherit dates
:param bool inherit_notes: Inherit parent notes | [
"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', 'course_level_at_or_below': '200'})
"""
if self.val_info is None:
self.val_info = self.search_params()
if validate:
errors = self.validate(self.val_info, params)
if not validate or len(errors) == 0:
return self._iter_response(ENDPOINTS['SEARCH'], params)
else:
return {'Errors': errors} | [
"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
--------
>>> model.set_components({'birth_rate': 10})
>>> model.set_components({'Birth Rate': 10})
>>> br = pandas.Series(index=range(30), values=np.sin(range(30))
>>> model.set_components({'birth_rate': br})
"""
# 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, this may conflict
# with a pandas series being passed in as a dictionary element.
for key, value in params.items():
if isinstance(value, pd.Series):
new_function = self._timeseries_component(value)
elif callable(value):
new_function = value
else:
new_function = self._constant_component(value)
func_name = utils.get_value_by_insensitive_key_or_value(key, self.components._namespace)
if func_name is None:
raise NameError('%s is not recognized as a model component' % key)
if '_integ_' + func_name in dir(self.components): # this won't handle other statefuls...
warnings.warn("Replacing the equation of stock {} with params".format(key),
stacklevel=2)
setattr(self.components, func_name, new_function) | [
"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})
>>> model.set_components({'Birth Rate': 10})
>>> br = pandas.Series(index=range(30), values=np.sin(range(30))
>>> model.set_components({'birth_rate': br}) | [
"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:
yield item | [
"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 DJANGO_STATIC_MEDIA_ROOTS look for apps' files if we're
# in DEBUG mode
if settings.DEBUG:
try:
from django.contrib.staticfiles import finders
absolute_path = finders.find(filename)
if absolute_path:
root, filepath = os.path.split(absolute_path)
return absolute_path, root
except ImportError:
pass
return None, None | [
"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 parseado
central_catalog (str o dict): ruta a catálogo central, o un dict
con el catálogo ya parseado
"""
result = {
'datasets_federados_cant': None,
'datasets_federados_pct': None,
'datasets_no_federados_cant': None,
'datasets_federados_eliminados_cant': None,
'distribuciones_federadas_cant': None,
'datasets_federados_eliminados': [],
'datasets_no_federados': [],
'datasets_federados': [],
}
try:
central_catalog = readers.read_catalog(central_catalog)
except Exception as e:
msg = u'Error leyendo el catálogo central: {}'.format(str(e))
logger.error(msg)
return result
generator = FederationIndicatorsGenerator(central_catalog, catalog,
id_based=identifier_search)
result.update({
'datasets_federados_cant':
generator.datasets_federados_cant(),
'datasets_no_federados_cant':
generator.datasets_no_federados_cant(),
'datasets_federados_eliminados_cant':
generator.datasets_federados_eliminados_cant(),
'datasets_federados_eliminados':
generator.datasets_federados_eliminados(),
'datasets_no_federados':
generator.datasets_no_federados(),
'datasets_federados':
generator.datasets_federados(),
'datasets_federados_pct':
generator.datasets_federados_pct(),
'distribuciones_federadas_cant':
generator.distribuciones_federadas_cant()
})
return result | [
"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 parseado | [
"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(inertia) | [
"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 MMS as MMS numbers downgrade to SMS if the other
party isn't MMS-capable. If it is important that the number is valid, then
its validity must first be checked using is_valid_short_number or
is_valid_short_number_for_region. Returns False if the number doesn't
match the region provided.
Arguments:
numobj -- the valid short number to check
region_dialing_from -- the region from which the number is dialed
Returns whether the short number is an SMS service in the provided region,
assuming the input was a valid short number.
"""
if not _region_dialing_from_matches_number(numobj, region_dialing_from):
return False
metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)
return (metadata is not None and
_matches_possible_number_and_national_number(national_significant_number(numobj), metadata.sms_services)) | [
"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-capable. If it is important that the number is valid, then
its validity must first be checked using is_valid_short_number or
is_valid_short_number_for_region. Returns False if the number doesn't
match the region provided.
Arguments:
numobj -- the valid short number to check
region_dialing_from -- the region from which the number is dialed
Returns whether the short number is an SMS service in the provided region,
assuming the input was a valid short number. | [
"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=self.disable_notification, reply_to_message_id=reply_id
game_short_name=self.game_short_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup
) | [
"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('ansible.modules{0}'.format(
'.'.join([elm.split('.')[0] for elm in m_ref.split(os.path.sep)])))
return mod | [
"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:
ref: reference ticker or exchange for timezone
keep_tz: if keep tz if reference ticker / exchange is given
start_time: start time
end_time: end time
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Returns:
pd.DataFrame
"""
from xbbg.core import intervals
cur_data = bdib(ticker=ticker, dt=dt, typ=kwargs.get('typ', 'TRADE'))
if cur_data.empty: return pd.DataFrame()
fmt = '%H:%M:%S'
ss = intervals.SessNA
ref = kwargs.get('ref', None)
exch = pd.Series() if ref is None else const.exch_info(ticker=ref)
if session: ss = intervals.get_interval(
ticker=kwargs.get('ref', ticker), session=session
)
start_time = kwargs.get('start_time', None)
end_time = kwargs.get('end_time', None)
if ss != intervals.SessNA:
start_time = pd.Timestamp(ss.start_time).strftime(fmt)
end_time = pd.Timestamp(ss.end_time).strftime(fmt)
if start_time and end_time:
kw = dict(start_time=start_time, end_time=end_time)
if not exch.empty:
cur_tz = cur_data.index.tz
res = cur_data.tz_convert(exch.tz).between_time(**kw)
if kwargs.get('keep_tz', False):
res = res.tz_convert(cur_tz)
return pd.DataFrame(res)
return pd.DataFrame(cur_data.between_time(**kw))
return cur_data | [
"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 keep tz if reference ticker / exchange is given
start_time: start time
end_time: end time
typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK]
Returns:
pd.DataFrame | [
"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:
rm_s3(c) | [
"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
additional information.
"""
self.elements -= self.search_elementnames(*substrings).elements
return self | [
"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:
pass
raise ValueError('No valid api key found') | [
"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. This is meant to help simplify
engine implementations. This allows a developer to just focus on
iterating and executing the cell contents.
"""
nb_man = NotebookExecutionManager(
nb, output_path=output_path, progress_bar=progress_bar, log_output=log_output
)
nb_man.notebook_start()
try:
nb = cls.execute_managed_notebook(nb_man, kernel_name, log_output=log_output, **kwargs)
# Update the notebook object in case the executor didn't do it for us
if nb:
nb_man.nb = nb
finally:
nb_man.cleanup_pbar()
nb_man.notebook_complete()
return nb_man.nb | [
"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 contents. | [
"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)
return memory_file(data, self.profile()), 'image/png' | [
"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_chars: TokenChars
:type delimiter: str
:type token_length: int
:type token_hex: bool
:type token_chars: str
:return: heroku-like random string
:rtype: str
"""
if token_hex:
token_chars = '0123456789abcdef'
adjective = self._random_element(self._adjectives)
noun = self._random_element(self._nouns)
token = ''.join(self._random_element(token_chars) for _ in range(token_length))
sections = [adjective, noun, token]
return delimiter.join(filter(None, sections)) | [
"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
:type token_chars: str
:return: heroku-like random string
:rtype: str | [
"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
information.
"""
return {element.name: element.model.sequences.conditions
for element in self} | [
"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_set in sorted(self.get_condition_sets(), key=lambda x: x.get_group_label()):
group = unicode(condition_set.get_group_label())
for field in condition_set.fields.itervalues():
yield condition_set.get_id(), group, field | [
"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: The encoding of the file.
"""
byte_order_marks = (
('utf-8-sig', (codecs.BOM_UTF8, )),
('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),
('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)),
)
try:
with open(path, 'rb') as infile:
raw = infile.read(4)
except IOError:
return default
for encoding, boms in byte_order_marks:
if any(raw.startswith(bom) for bom in boms):
return encoding
return default | [
"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.
This can be useful for mocking and other nefarious activities.
"""
wrapped_by = None
if isinstance(func, property):
fget, fset, fdel = func.fget, func.fset, func.fdel
if fget: fget = fix_func(fget, **kwargs)
if fset: fset = fix_func(fset, **kwargs)
if fdel: fdel = fix_func(fdel, **kwargs)
wrapped_by = type(func)
return wrapped_by(fget, fset, fdel)
elif isinstance(func, (staticmethod, classmethod)):
func = func.__func__
wrapped_by = type(func)
newfunc = _inject_closure_values(func, **kwargs)
if wrapped_by:
newfunc = wrapped_by(newfunc)
return newfunc | [
"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 activities. | [
"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)
addresses = relationship("Address", backref="user")
@memoize
def address_count(self):
return len(self.addresses)
sqlalchemy.event.listen(User, 'expire', User.address_count.reset_memoize)
"""
memoize_key = '_memoize_cache_{0}'.format(id(method_to_wrap))
@wrapt.decorator
def inner_memoize(wrapped, instance, args, kwargs):
if instance is None and inspect.isclass(wrapped):
# Wrapped function is a class and we are creating an
# instance of the class. Don't support this case, just
# return straight away.
return wrapped(*args, **kwargs)
# Retrieve the cache, attaching an empty one if none exists.
cache = instance.__dict__.setdefault(memoize_key, {})
# Now see if entry is in the cache and if it isn't then call
# the wrapped function to generate it.
try:
key = (args, frozenset(kwargs.items()))
return cache[key]
except KeyError:
result = cache[key] = wrapped(*args, **kwargs)
return result
def reset_memoize(target, *args):
target.__dict__[memoize_key] = {}
decorated = inner_memoize(method_to_wrap)
decorated.reset_memoize = reset_memoize
return decorated | [
"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="user")
@memoize
def address_count(self):
return len(self.addresses)
sqlalchemy.event.listen(User, 'expire', User.address_count.reset_memoize) | [
"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 in [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]:
warnings.warn(
'Database %r uses unsupported %r engine.' % (
alias, engine,
),
UserWarning,
)
self.api = autodiscover()
self.api.ready() | [
"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, basestring):
return '"' + value + '"'
else:
return value
# our compacted format
doc = literal_eval(txt)
g = digraph()
for attrs, values in doc.get("nodes", []):
attrs = [(k, conv(v)) for k, v in attrs]
for value in values:
if isinstance(value, basestring):
node_name = value
attrs_ = attrs
else:
node_name, label = value
attrs_ = attrs + [("label", conv(label))]
g.add_node(node_name, attrs=attrs_)
for attrs, values in doc.get("edges", []):
attrs_ = [(k, conv(v)) for k, v in attrs]
for value in values:
if len(value) == 3:
edge = value[:2]
label = value[-1]
else:
edge = value
label = ''
g.add_edge(edge, label=label, attrs=attrs_)
return g | [
"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 with
# "#eigvals"
data = None
with open(i_filename, "r") as i_file:
data = re.split(
r"\s+",
re.sub(r"(^\s+)|(\s+$)", "", i_file.readline()),
)
if not data[0].startswith("#eigvals"):
m = "{}: not a evec file".format(i_filename)
raise ProgramError(m)
data = np.array(data[1:], dtype=float)
return data | [
"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 ``False`` depending on the fact if all
items withstand the validation or not. Per default the validation / evaluation is
short-circuit and will return as soon an item evaluates to ``False``.
When ``raise_ex`` is set to ``True`` the function will raise a meaningful error message
after the first item evaluates to ``False`` (short-circuit).
When ``summary`` is set to ``False`` a dictionary is returned containing the individual
evaluation result of each item (non short-circuit).
Examples:
>>> class MyStream():
... def read(self):
... pass
>>> Validator.is_stream(stream=MyStream())
True
>>> Validator.is_stream(nonstream='abc')
False
>>> Validator.is_stream(stream=MyStream(), nonstream='abc', summary=True)
False
>>> (Validator.is_stream(stream=MyStream(), nonstream='abc', summary=False)
... == {'stream': True, 'nonstream': False})
True
>>> Validator.is_stream(nonstream='abc', raise_ex=True)
Traceback (most recent call last):
...
ValueError: 'nonstream' is not a stream
Args:
raise_ex (bool, optional): If set to ``True`` an exception is raised if at least one
item is validated to ``False`` (works short-circuit and will abort the validation when
the first item is evaluated to ``False``).
summary (bool, optional): If set to ``False`` instead of returning just a single
``bool`` the validation will return a dictionary containing the individual evaluation
result of each item.
Returns:
(boolean or dictionary): ``True`` when the value was successfully validated; ``False``
otherwise.
If ``summary`` is set to ``False`` a dictionary containing the individual evaluation
result of each item will be returned.
If ``raise_ex`` is set to True, instead of returning False a meaningful error will be
raised.
"""
return Validator.__test_all(
condition=lambda _, val: getattr(val, 'read', None) is not None,
formatter=lambda name, _: "'{varname}' is not a stream".format(varname=name),
raise_ex=raise_ex,
summary=summary,
**items
) | [
"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
short-circuit and will return as soon an item evaluates to ``False``.
When ``raise_ex`` is set to ``True`` the function will raise a meaningful error message
after the first item evaluates to ``False`` (short-circuit).
When ``summary`` is set to ``False`` a dictionary is returned containing the individual
evaluation result of each item (non short-circuit).
Examples:
>>> class MyStream():
... def read(self):
... pass
>>> Validator.is_stream(stream=MyStream())
True
>>> Validator.is_stream(nonstream='abc')
False
>>> Validator.is_stream(stream=MyStream(), nonstream='abc', summary=True)
False
>>> (Validator.is_stream(stream=MyStream(), nonstream='abc', summary=False)
... == {'stream': True, 'nonstream': False})
True
>>> Validator.is_stream(nonstream='abc', raise_ex=True)
Traceback (most recent call last):
...
ValueError: 'nonstream' is not a stream
Args:
raise_ex (bool, optional): If set to ``True`` an exception is raised if at least one
item is validated to ``False`` (works short-circuit and will abort the validation when
the first item is evaluated to ``False``).
summary (bool, optional): If set to ``False`` instead of returning just a single
``bool`` the validation will return a dictionary containing the individual evaluation
result of each item.
Returns:
(boolean or dictionary): ``True`` when the value was successfully validated; ``False``
otherwise.
If ``summary`` is set to ``False`` a dictionary containing the individual evaluation
result of each item will be returned.
If ``raise_ex`` is set to True, instead of returning False a meaningful error will be
raised. | [
"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.EnableNetworkInterfaces(
[interface.name for interface in network_interfaces[1:]])
for interface in network_interfaces:
if self.ip_forwarding_enabled:
self.ip_forwarding.HandleForwardedIps(
interface.name, interface.forwarded_ips, interface.ip) | [
"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 should be installed."""
import os
import errno
install_dir = os.path.expanduser(INSTALL_DIR)
try:
os.makedirs(install_dir)
except OSError as ose:
if ose.errno != errno.EEXIST:
raise ose
jar_filename = os.path.join(install_dir, jar_base_filename)
return jar_filename | [
"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)
output = "{0}".format(output)
# if not running under pyinstaller, run in another process.
# This is done because multiprocesing has a design flaw that
# causes non main programs to run multiple times on Windows.
else:
from subprocess import Popen, PIPE
command = [sys.executable, __file__, '--json']
p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
output = p1.communicate()[0]
if p1.returncode != 0:
return "{}"
if not IS_PY2:
output = output.decode(encoding='UTF-8')
return output | [
"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_{}'.format(event.uid), 'score': 0}
elif event.type == E_DISCONNECT:
#print(datetime.now(), '### player with uid {} disconnected'.format(event.uid))
self.players.pop(event.uid)
elif event.type == E_KEYDOWN:
#print(datetime.now(), '###', self.players[event.uid]['name'], 'pressed', event.button)
self.colors.append(self.colors.pop(0))
elif event.type == E_KEYUP:
#print(datetime.now(), '###', self.players[event.uid]['name'], 'released', event.button)
self.colors.append(self.colors.pop(0))
elif event.type == E_PING:
#print(datetime.now(), '### ping from', self.players[event.uid]['name'])
pass | [
"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 or plt.gca()
assert letter_heights.shape[1] == len(VOCABS[vocab])
x_range = [1, letter_heights.shape[0]]
pos_heights = np.copy(letter_heights)
pos_heights[letter_heights < 0] = 0
neg_heights = np.copy(letter_heights)
neg_heights[letter_heights > 0] = 0
for x_pos, heights in enumerate(letter_heights):
letters_and_heights = sorted(zip(heights, list(VOCABS[vocab].keys())))
y_pos_pos = 0.0
y_neg_pos = 0.0
for height, letter in letters_and_heights:
color = VOCABS[vocab][letter]
polygons = letter_polygons[letter]
if height > 0:
add_letter_to_axis(ax, polygons, color, 0.5 + x_pos, y_pos_pos, height)
y_pos_pos += height
else:
add_letter_to_axis(ax, polygons, color, 0.5 + x_pos, y_neg_pos, height)
y_neg_pos += height
# if add_hline:
# ax.axhline(color="black", linewidth=1)
ax.set_xlim(x_range[0] - 1, x_range[1] + 1)
ax.grid(False)
ax.set_xticks(list(range(*x_range)) + [x_range[-1]])
ax.set_aspect(aspect='auto', adjustable='box')
ax.autoscale_view() | [
"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 in all_vars])
# print("All variable values")
# print(sess.run(all_vars))
var_res = self._get_var_res_sess(sess, var)
return var_res | [
"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] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1].replace('\\\\', '\\').replace('\\"', '"')
return value | [
"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.run'](cmd)
grains = {}
for line in hardware.splitlines():
field_name, _, field_val = line.partition(': ')
if field_name.strip() == "Model Name":
key = 'model_name'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Boot ROM Version":
key = 'boot_rom_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "SMC Version (system)":
key = 'smc_version'
grains[key] = _clean_value(key, field_val)
if field_name.strip() == "Serial Number (system)":
key = 'system_serialnumber'
grains[key] = _clean_value(key, field_val)
return grains | [
"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 the list:
{<analysis_uid>: '<slot_number>:<position_within_slot>',}
:returns: a dictionary with the full position within the worksheet of
all analyses defined in the current layout.
"""
uids_positions = dict()
layout = self.context.getLayout()
layout = layout and layout or []
# Map the analysis uids with their positions.
occupied = []
next_positions = {}
for item in layout:
uid = item.get("analysis_uid", "")
slot = int(item["position"])
occupied.append(slot)
position = next_positions.get(slot, 1)
str_position = "{:010}:{:010}".format(slot, position)
next_positions[slot] = position + 1
uids_positions[uid] = str_position
# Fill empties
last_slot = max(occupied) if occupied else 1
empties = [num for num in range(1, last_slot) if num not in occupied]
for empty_slot in empties:
str_position = "{:010}:{:010}".format(empty_slot, 1)
uid = "empty-{}".format(empty_slot)
uids_positions[uid] = str_position
return uids_positions | [
"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>: '<slot_number>:<position_within_slot>',}
:returns: a dictionary with the full position within the worksheet of
all analyses defined in the current layout. | [
"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(x,Lambda) - abs(seeb)) ** 2, 1.,full_output=True)
return out[0][0] | [
"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 entityMeta in response:
entityMetaList.append(Schemas.EntityMeta(entityMeta=entityMeta))
return entityMetaList | [
"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 : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel
"""
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('"graph" input must be a SGraph object.')
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.degree_count.create(
{'graph': graph.__proxy__})
return DegreeCountingModel(params['model']) | [
"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
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel | [
"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.permalink
def get_absolute_url(self):
return ('myapp.urls', 'model_detail', (), {'slug': self.slug})
"""
def inner(*args, **kwargs):
return app_reverse(*func(*args, **kwargs))
return wraps(func)(inner) | [
"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_absolute_url(self):
return ('myapp.urls', 'model_detail', (), {'slug': self.slug}) | [
"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 (container['Names'] or [])
if matches(n, '/' + identifier)])
# Determine if identifier is a container
containers = [c['Id'] for c in self.client.containers(all=True)
if (__cname_matches(c, identifier) or
matches(c['Id'], identifier + '*'))]
if len(containers) > 1:
raise SelectionMatchError(identifier, containers)
elif len(containers) == 1:
c = containers[0]
return self._clone(c)
# Determine if identifier is an image UUID
images = [i for i in set(self.client.images(all=True, quiet=True))
if i.startswith(identifier)]
if len(images) > 1:
raise SelectionMatchError(identifier, images)
elif len(images) == 1:
return self._create_temp_container(images[0])
# Match image tag.
images = util.image_by_name(identifier)
if len(images) > 1:
tags = [t for i in images for t in i['RepoTags']]
raise SelectionMatchError(identifier, tags)
elif len(images) == 1:
return self._create_temp_container(images[0]['Id'].replace("sha256:", ""))
raise MountError('{} did not match any image or container.'
''.format(identifier)) | [
"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 adapter_catalog.keys()]
models = [model.lower().rstrip('s') for model in (models or [])]
for model in models:
if model not in doc_types_names:
log.error('Unknown model %s', model)
sys.exit(-1)
log.info('Initiliazing index "{0}"'.format(index_name))
if es.indices.exists(index_name):
if IS_TTY and not force:
msg = 'Index {0} will be deleted, are you sure?'
click.confirm(msg.format(index_name), abort=True)
es.indices.delete(index_name)
es.initialize(index_name)
with handle_error(index_name, keep):
disable_refresh(index_name)
for adapter in iter_adapters():
if not models or adapter.doc_type().lower() in models:
index_model(index_name, adapter)
else:
log.info('Copying {0} objects to the new index'.format(
adapter.model.__name__))
# Need upgrade to Elasticsearch-py 5.0.0 to write:
# es.reindex({
# 'source': {'index': es.index_name, 'type': adapter.doc_type()},
# 'dest': {'index': index_name}
# })
#
# http://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.reindex
# This method (introduced in Elasticsearch 2.3 but only in Elasticsearch-py 5.0.0)
# triggers a server-side documents copy.
# Instead we use this helper for meant for backward compatibility
# but with poor performance as copy is client-side (scan+bulk)
es_reindex(es.client, es.index_name, index_name, scan_kwargs={
'doc_type': adapter.doc_type()
})
enable_refresh(index_name)
# At this step, we don't want error handler to delete the index
# in case of error
set_alias(index_name, delete=not keep) | [
"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 in G.
"""
if self.H is None:
self.H, self.G, self.Hvv, self.Hsvals, self.Gsvals = riemann_metric(self.Y, self.L, self.mdimG, invert_h = invert_h, mode_inv = mode_inv)
if invert_h:
return self.H, self.G
else:
return self.H | [
"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 text | [
"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 str and int
:raises SerializationError: if unable to unpack
"""
end = offset + length
try:
return (codecs.decode(source[offset:end], aws_encryption_sdk.internal.defaults.ENCODING), end)
except Exception:
raise SerializationError("Bad format of serialized context.") | [
"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 unable to unpack | [
"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:
mutex = my_task.workflow._get_mutex(lock)
if not mutex.testandset():
return
# Assign variables, if so requested.
for assignment in self.pre_assign:
assignment.assign(my_task, my_task)
# Run task-specific code.
self._on_ready_before_hook(my_task)
self.reached_event.emit(my_task.workflow, my_task)
self._on_ready_hook(my_task)
# Run user code, if any.
if self.ready_event.emit(my_task.workflow, my_task):
# Assign variables, if so requested.
for assignment in self.post_assign:
assignment.assign(my_task, my_task)
# Release locks, if any.
for lock in self.locks:
mutex = my_task.workflow._get_mutex(lock)
mutex.unlock()
self.finished_event.emit(my_task.workflow, my_task) | [
"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 defines this symbol
module: module (any object) this symbol is defined in
Returns:
bool(if symbol was *not* already present)
"""
# TODO(nnorwitz): verify symbol_name doesn't contain :: ?
if namespace_stack:
# Handle non-global symbols (ie, in some namespace).
last_namespace = self.namespaces
for namespace in namespace_stack:
last_namespace = last_namespace.setdefault(namespace, {})
else:
last_namespace = self.namespaces[None]
return self._add(symbol_name, last_namespace, node, module) | [
"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 defined in
Returns:
bool(if symbol was *not* already present) | [
"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 = [('matrix', array_str(self.matrix, nprint=10), '')]
optargs.append(('exponent', self.exponent, 2.0))
return signature_string([], optargs, mod=[[], ['!s', ':.4']]) | [
"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 the
tag, plus the ID of the last commit. Further, the patch will be
extended with "-dirty" if there are uncommitted changes in the
current codeset.
eg 1.0.1-gd5aa65e-dirty
Assumes that the tags fit the regex [0-9]*.[0-9]*
"""
try:
cwd = os.getcwd ()
except: # pylint: disable=W0702
cwd = None
try:
try:
mod = __import__ (pkg)
path = os.path.dirname (mod.__file__)
os.chdir (path)
except: # pylint: disable=W0702
pass
o = subprocess.check_output (
DEFAULT_GITCMD.split (),
stderr = subprocess.PIPE,
shell = False).decode ().strip ()
s = o.replace ("-", ".", 1).replace ("-", "+", 1).replace ("-", ".", 1)
except: # pylint: disable=W0702
s = pkg_resources.get_distribution (pkg.split (".")[0]).version
if cwd is not None:
os.chdir (cwd)
if public:
vals = s.split (".")
patch = ((vals[2][:vals[2].find ("+")])
if vals[2].find ("+") != -1 else vals[2])
info = ((vals[0], vals[1], patch, "dev1")
if len (vals) == 4 else (vals[0], vals[1], patch))
return ".".join (info), info
else:
return s, s.split (".") | [
"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 patch will be
extended with "-dirty" if there are uncommitted changes in the
current codeset.
eg 1.0.1-gd5aa65e-dirty
Assumes that the tags fit the regex [0-9]*.[0-9]* | [
"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:
_map[ch] = chr(ch)
else:
_map[ch] = '\\%02x' % ch
if six.PY2:
_map[chr(ch)] = _map[ch]
buf = [_map[ch] for ch in text]
return ''.join(buf) | [
"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 function will inherit the function's docstring
Examples
--------
In some module you have defined a function
>>> @shortcut('is_tmatrix') # doctest: +SKIP
>>> def is_transition_matrix(args): # doctest: +SKIP
... pass # doctest: +SKIP
Now you are able to call the function under its short name
>>> is_tmatrix(args) # doctest: +SKIP
"""
def wrap(f):
globals_ = f.__globals__
for name in names:
globals_[name] = f
if '__all__' in globals_ and name not in globals_['__all__']:
globals_['__all__'].append(name)
return f
return wrap | [
"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's docstring
Examples
--------
In some module you have defined a function
>>> @shortcut('is_tmatrix') # doctest: +SKIP
>>> def is_transition_matrix(args): # doctest: +SKIP
... pass # doctest: +SKIP
Now you are able to call the function under its short name
>>> is_tmatrix(args) # doctest: +SKIP | [
"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 the mean and cov.
"""
try:
from pylab import fill, plot, clf, axis
x = concatenate((mesh, mesh[::-1]))
mean, var = point_eval(M, C, mesh)
sig = sqrt(var)
mean = M(mesh)
y = concatenate((mean - sig, (mean + sig)[::-1]))
# clf()
fill(x, y, facecolor='.8', edgecolor='1.')
plot(mesh, mean, 'k-.')
except ImportError:
print_("Matplotlib is not installed; plotting is disabled.") | [
"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 = []
info = conn.list_saml_providers()
for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']:
providers.append(arn['arn'].rsplit('/', 1)[1])
return providers
except boto.exception.BotoServerError as e:
log.debug(__utils__['boto.get_error'](e))
log.error('Failed to get list of SAML providers.')
return False | [
"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 LookupError:
raise ImproperlyConfigured(
"PERM_MODEL refers to model '{}' that has not been installed".format(settings.PERM_MODEL)
) | [
"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 start of each line
"""
ind = ''
if kwargs.get("indent"):
ind = ''.ljust(kwargs['indent'], ' ')
prepend = ind + kwargs.get("prepend", "")
if not max_width:
return "{}{}".format(prepend, text)
len_pre = len(kwargs.get("prepend", "")) + kwargs.get("indent", 0)
test_words = text.split(" ")
word_limit = max_width - len_pre
if word_limit < 3:
word_limit = 3
max_width = len_pre + word_limit
words = []
for word in test_words:
if len(word) + len_pre > max_width:
n = max_width - len_pre
words += [word[i:i + word_limit]
for i in range(0, len(word), word_limit)]
else:
words.append(word)
idx = 0
lines = []
idx_limit = len(words) - 1
sub_idx_limit = idx_limit
while idx < idx_limit:
current_len = len_pre
line = prepend
for i, word in enumerate(words[idx:]):
if (current_len + len(word)) == max_width and line == prepend:
idx += i or 1
line += word
lines.append(line)
if idx == idx_limit:
idx -= 1
sub_idx_limit -= 1
del words[0]
break
if (current_len + len(word) + 1) > max_width:
idx += i
if idx == idx_limit:
idx -= 1
sub_idx_limit -= 1
del words[0]
if idx == 0:
del words[0]
lines.append(line)
break
if (i + idx) == sub_idx_limit:
idx += i or 1
if line != prepend:
line = " ".join([line, word])
elif word:
line += word
lines.append(line)
else:
if line != prepend:
line = " ".join([line, word])
elif word:
line += word
current_len = len(line)
return "\n".join(lines) | [
"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 _get_used_items_np(u):
volume_config_name, __, volume_instance = u.name.partition('.')
attaching_config_name = attaching.get(volume_config_name)
if attaching_config_name:
used_c_name = attaching_config_name
used_instances = instances.get(attaching_config_name)
else:
used_c_name = volume_config_name
if volume_instance:
used_instances = (volume_instance, )
else:
used_instances = instances.get(volume_config_name)
return [MapConfigId(ItemType.CONTAINER, self._name, used_c_name, ai)
for ai in used_instances or (None, )]
def _get_used_items_ap(u):
volume_config_name, __, volume_instance = u.name.partition('.')
attaching_config = ext_map.get_existing(volume_config_name)
attaching_instances = instances.get(volume_config_name)
config_volumes = {a.name for a in attaching_config.attaches}
if not volume_instance or volume_instance in config_volumes:
used_instances = attaching_instances
else:
used_instances = (volume_instance, )
return [MapConfigId(ItemType.CONTAINER, self._name, volume_config_name, ai)
for ai in used_instances or (None, )]
def _get_linked_items(lc):
linked_config_name, __, linked_instance = lc.partition('.')
if linked_instance:
linked_instances = (linked_instance, )
else:
linked_instances = instances.get(linked_config_name)
return [MapConfigId(ItemType.CONTAINER, self._name, linked_config_name, li)
for li in linked_instances or (None, )]
def _get_network_mode_items(n):
net_config_name, net_instance = n
network_ref_config = ext_map.get_existing(net_config_name)
if network_ref_config:
if net_instance and net_instance in network_ref_config.instances:
network_instances = (net_instance, )
else:
network_instances = network_ref_config.instances or (None, )
return [MapConfigId(ItemType.CONTAINER, self._name, net_config_name, ni)
for ni in network_instances]
return []
def _get_network_items(n):
if n.network_name in DEFAULT_PRESET_NETWORKS:
return []
net_items = [MapConfigId(ItemType.NETWORK, self._name, n.network_name)]
if n.links:
net_items.extend(itertools.chain.from_iterable(_get_linked_items(l.container) for l in n.links))
return net_items
if self._extended:
ext_map = self
else:
ext_map = self.get_extended_map()
instances = {c_name: c_config.instances
for c_name, c_config in ext_map}
if not self.use_attached_parent_name:
attaching = {attaches.name: c_name
for c_name, c_config in ext_map
for attaches in c_config.attaches}
used_func = _get_used_items_np
else:
used_func = _get_used_items_ap
def _get_dep_list(name, config):
image, tag = self.get_image(config.image or name)
d = []
nw = config.network_mode
if isinstance(nw, tuple):
merge_list(d, _get_network_mode_items(nw))
merge_list(d, itertools.chain.from_iterable(map(_get_network_items, config.networks)))
merge_list(d, itertools.chain.from_iterable(map(used_func, config.uses)))
merge_list(d, itertools.chain.from_iterable(_get_linked_items(l.container) for l in config.links))
d.extend(MapConfigId(ItemType.VOLUME, self._name, name, a.name)
for a in config.attaches)
d.append(MapConfigId(ItemType.IMAGE, self._name, image, tag))
return d
for c_name, c_config in ext_map:
dep_list = _get_dep_list(c_name, c_config)
for c_instance in c_config.instances or (None, ):
yield MapConfigId(ItemType.CONTAINER, self._name, c_name, c_instance), dep_list | [
"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}'.format(e))
return None
else:
return response.json() or response.text | [
"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:
if num > 0:
val = chunk*(val // chunk + 1)
elif num < 0:
val = chunk*(val // chunk)
val = max(self._min(), min(self._max(), val))
self.set(val) | [
"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.