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 |
|---|---|---|---|---|---|---|---|---|
Clinical-Genomics/scout | scripts/transfer-archive.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scripts/transfer-archive.py#L62-L116 | def migrate_case(adapter: MongoAdapter, scout_case: dict, archive_data: dict):
"""Migrate case information from archive."""
# update collaborators
collaborators = list(set(scout_case['collaborators'] + archive_data['collaborators']))
if collaborators != scout_case['collaborators']:
LOG.info(f"se... | [
"def",
"migrate_case",
"(",
"adapter",
":",
"MongoAdapter",
",",
"scout_case",
":",
"dict",
",",
"archive_data",
":",
"dict",
")",
":",
"# update collaborators",
"collaborators",
"=",
"list",
"(",
"set",
"(",
"scout_case",
"[",
"'collaborators'",
"]",
"+",
"ar... | Migrate case information from archive. | [
"Migrate",
"case",
"information",
"from",
"archive",
"."
] | python | test |
robinandeer/puzzle | puzzle/models/variant.py | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/models/variant.py#L134-L144 | def add_transcript(self, transcript):
"""Add the information transcript
This adds a transcript dict to variant['transcripts']
Args:
transcript (dict): A transcript dictionary
"""
logger.debug("Adding transcript {0} to variant {1}".format(
tra... | [
"def",
"add_transcript",
"(",
"self",
",",
"transcript",
")",
":",
"logger",
".",
"debug",
"(",
"\"Adding transcript {0} to variant {1}\"",
".",
"format",
"(",
"transcript",
",",
"self",
"[",
"'variant_id'",
"]",
")",
")",
"self",
"[",
"'transcripts'",
"]",
".... | Add the information transcript
This adds a transcript dict to variant['transcripts']
Args:
transcript (dict): A transcript dictionary | [
"Add",
"the",
"information",
"transcript"
] | python | train |
markovmodel/msmtools | msmtools/analysis/sparse/mean_first_passage_time.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/sparse/mean_first_passage_time.py#L101-L142 | def mfpt_between_sets(T, target, origin, mu=None):
"""Compute mean-first-passage time between subsets of state space.
Parameters
----------
T : scipy.sparse matrix
Transition matrix.
target : int or list of int
Set of target states.
origin : int or list of int
Set of sta... | [
"def",
"mfpt_between_sets",
"(",
"T",
",",
"target",
",",
"origin",
",",
"mu",
"=",
"None",
")",
":",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"stationary_distribution",
"(",
"T",
")",
"\"\"\"Stationary distribution restriced on starting set X\"\"\"",
"nuX",
"=... | Compute mean-first-passage time between subsets of state space.
Parameters
----------
T : scipy.sparse matrix
Transition matrix.
target : int or list of int
Set of target states.
origin : int or list of int
Set of starting states.
mu : (M,) ndarray (optional)
The... | [
"Compute",
"mean",
"-",
"first",
"-",
"passage",
"time",
"between",
"subsets",
"of",
"state",
"space",
"."
] | python | train |
sentinel-hub/sentinelhub-py | sentinelhub/aws.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L630-L640 | def get_gml_url(self, qi_type, band='B00'):
"""
:param qi_type: type of quality indicator
:type qi_type: str
:param band: band name
:type band: str
:return: location of gml file on AWS
:rtype: str
"""
band = band.split('/')[-1]
return self.... | [
"def",
"get_gml_url",
"(",
"self",
",",
"qi_type",
",",
"band",
"=",
"'B00'",
")",
":",
"band",
"=",
"band",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"return",
"self",
".",
"get_qi_url",
"(",
"'MSK_{}_{}.gml'",
".",
"format",
"(",
"qi_type"... | :param qi_type: type of quality indicator
:type qi_type: str
:param band: band name
:type band: str
:return: location of gml file on AWS
:rtype: str | [
":",
"param",
"qi_type",
":",
"type",
"of",
"quality",
"indicator",
":",
"type",
"qi_type",
":",
"str",
":",
"param",
"band",
":",
"band",
"name",
":",
"type",
"band",
":",
"str",
":",
"return",
":",
"location",
"of",
"gml",
"file",
"on",
"AWS",
":",... | python | train |
INM-6/hybridLFPy | hybridLFPy/population.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/hybridLFPy/population.py#L1334-L1376 | def insert_all_synapses(self, cellindex, cell):
"""
Insert all synaptic events from all presynaptic layers on
cell object with index `cellindex`.
Parameters
----------
cellindex : int
cell index in the population.
cell : `LFPy.Cell` instance
... | [
"def",
"insert_all_synapses",
"(",
"self",
",",
"cellindex",
",",
"cell",
")",
":",
"for",
"i",
",",
"X",
"in",
"enumerate",
"(",
"self",
".",
"X",
")",
":",
"#range(self.k_yXL.shape[1]):",
"synParams",
"=",
"self",
".",
"synParams",
"synParams",
".",
"upd... | Insert all synaptic events from all presynaptic layers on
cell object with index `cellindex`.
Parameters
----------
cellindex : int
cell index in the population.
cell : `LFPy.Cell` instance
Postsynaptic target cell.
Returns
-------
... | [
"Insert",
"all",
"synaptic",
"events",
"from",
"all",
"presynaptic",
"layers",
"on",
"cell",
"object",
"with",
"index",
"cellindex",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L657-L698 | def errors(self, batch_id, halt_on_error=True):
"""Retrieve Batch errors to ThreatConnect API.
.. code-block:: javascript
[{
"errorReason": "Incident incident-001 has an invalid status.",
"errorSource": "incident-001 is not valid."
}, {
... | [
"def",
"errors",
"(",
"self",
",",
"batch_id",
",",
"halt_on_error",
"=",
"True",
")",
":",
"errors",
"=",
"[",
"]",
"try",
":",
"r",
"=",
"self",
".",
"tcex",
".",
"session",
".",
"get",
"(",
"'/v2/batch/{}/errors'",
".",
"format",
"(",
"batch_id",
... | Retrieve Batch errors to ThreatConnect API.
.. code-block:: javascript
[{
"errorReason": "Incident incident-001 has an invalid status.",
"errorSource": "incident-001 is not valid."
}, {
"errorReason": "Incident incident-002 has an invalid... | [
"Retrieve",
"Batch",
"errors",
"to",
"ThreatConnect",
"API",
"."
] | python | train |
Chilipp/psy-simple | psy_simple/widgets/texts.py | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/widgets/texts.py#L420-L437 | def refresh(self):
"""Refresh the widgets from the current font"""
font = self.current_font
# refresh btn_bold
self.btn_bold.blockSignals(True)
self.btn_bold.setChecked(font.weight() > 50)
self.btn_bold.blockSignals(False)
# refresh btn_italic
self.btn_i... | [
"def",
"refresh",
"(",
"self",
")",
":",
"font",
"=",
"self",
".",
"current_font",
"# refresh btn_bold",
"self",
".",
"btn_bold",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"btn_bold",
".",
"setChecked",
"(",
"font",
".",
"weight",
"(",
")",
">"... | Refresh the widgets from the current font | [
"Refresh",
"the",
"widgets",
"from",
"the",
"current",
"font"
] | python | train |
roclark/sportsreference | sportsreference/nfl/roster.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/roster.py#L357-L373 | def _parse_player_information(self, player_info):
"""
Parse general player information.
Parse general player information such as height, weight, and name. The
attribute for the requested field will be set with the value prior to
returning.
Parameters
----------
... | [
"def",
"_parse_player_information",
"(",
"self",
",",
"player_info",
")",
":",
"for",
"field",
"in",
"[",
"'_height'",
",",
"'_weight'",
",",
"'_name'",
"]",
":",
"short_field",
"=",
"str",
"(",
"field",
")",
"[",
"1",
":",
"]",
"value",
"=",
"utils",
... | Parse general player information.
Parse general player information such as height, weight, and name. The
attribute for the requested field will be set with the value prior to
returning.
Parameters
----------
player_info : PyQuery object
A PyQuery object cont... | [
"Parse",
"general",
"player",
"information",
"."
] | python | train |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L68-L84 | def make_python_name(self, name):
"""Transforms an USR into a valid python name."""
# FIXME see cindex.SpellingCache
for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''),
("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"),
('-', '_'... | [
"def",
"make_python_name",
"(",
"self",
",",
"name",
")",
":",
"# FIXME see cindex.SpellingCache",
"for",
"k",
",",
"v",
"in",
"[",
"(",
"'<'",
",",
"'_'",
")",
",",
"(",
"'>'",
",",
"'_'",
")",
",",
"(",
"'::'",
",",
"'__'",
")",
",",
"(",
"','",
... | Transforms an USR into a valid python name. | [
"Transforms",
"an",
"USR",
"into",
"a",
"valid",
"python",
"name",
"."
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/task_agent/task_agent_client.py#L640-L690 | def get_deployment_targets(self, project, deployment_group_id, tags=None, name=None, partial_name_match=None, expand=None, agent_status=None, agent_job_result=None, continuation_token=None, top=None, enabled=None, property_filters=None):
"""GetDeploymentTargets.
[Preview API] Get a list of deployment ta... | [
"def",
"get_deployment_targets",
"(",
"self",
",",
"project",
",",
"deployment_group_id",
",",
"tags",
"=",
"None",
",",
"name",
"=",
"None",
",",
"partial_name_match",
"=",
"None",
",",
"expand",
"=",
"None",
",",
"agent_status",
"=",
"None",
",",
"agent_jo... | GetDeploymentTargets.
[Preview API] Get a list of deployment targets in a deployment group.
:param str project: Project ID or project name
:param int deployment_group_id: ID of the deployment group.
:param [str] tags: Get only the deployment targets that contain all these comma separted ... | [
"GetDeploymentTargets",
".",
"[",
"Preview",
"API",
"]",
"Get",
"a",
"list",
"of",
"deployment",
"targets",
"in",
"a",
"deployment",
"group",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"int",
"deployme... | python | train |
cidrblock/modelsettings | modelsettings/__init__.py | https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L146-L180 | def load_ini(self, ini_file):
""" Load the contents from the ini file
Args:
ini_file (str): The file from which the settings should be loaded
"""
if ini_file and not os.path.exists(ini_file):
self.log.critical(f"Settings file specified but not found. {in... | [
"def",
"load_ini",
"(",
"self",
",",
"ini_file",
")",
":",
"if",
"ini_file",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"ini_file",
")",
":",
"self",
".",
"log",
".",
"critical",
"(",
"f\"Settings file specified but not found. {ini_file}\"",
")",
"... | Load the contents from the ini file
Args:
ini_file (str): The file from which the settings should be loaded | [
"Load",
"the",
"contents",
"from",
"the",
"ini",
"file"
] | python | train |
hydpy-dev/hydpy | hydpy/models/lstream/lstream_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lstream/lstream_model.py#L878-L939 | def calc_qa_v1(self):
"""Calculate outflow.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required flux sequence:
|RK|
Required state sequence:
|QZ|
Updated sta... | [
"def",
"calc_qa_v1",
"(",
"self",
")",
":",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"old",
"=",
"self",
".",
"sequences",
".",
"states",
".",
"fastaccess_old",
"new",
"=",
"self",
".",
"sequences",
".",
"states",
".",
"f... | Calculate outflow.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required flux sequence:
|RK|
Required state sequence:
|QZ|
Updated state sequence:
|QA|
... | [
"Calculate",
"outflow",
"."
] | python | train |
Kortemme-Lab/klab | klab/bio/pdb.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L748-L770 | def _get_replacement_pdb_id(self):
'''Checks to see if the PDB file has been deprecated and, if so, what the new ID is.'''
deprecation_lines = self.parsed_lines['OBSLTE']
date_regex = re.compile('(\d+)-(\w{3})-(\d+)')
if deprecation_lines:
assert(len(deprecation_lines) == 1)
... | [
"def",
"_get_replacement_pdb_id",
"(",
"self",
")",
":",
"deprecation_lines",
"=",
"self",
".",
"parsed_lines",
"[",
"'OBSLTE'",
"]",
"date_regex",
"=",
"re",
".",
"compile",
"(",
"'(\\d+)-(\\w{3})-(\\d+)'",
")",
"if",
"deprecation_lines",
":",
"assert",
"(",
"l... | Checks to see if the PDB file has been deprecated and, if so, what the new ID is. | [
"Checks",
"to",
"see",
"if",
"the",
"PDB",
"file",
"has",
"been",
"deprecated",
"and",
"if",
"so",
"what",
"the",
"new",
"ID",
"is",
"."
] | python | train |
Kensuke-Mitsuzawa/JapaneseTokenizers | JapaneseTokenizer/common/text_preprocess.py | https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/common/text_preprocess.py#L77-L83 | def normalize_text_normal_ipadic(input_text, kana=True, ascii=True, digit=True):
# type: (text_type,bool,bool,bool)->text_type
"""
* All hankaku Katanaka is converted into Zenkaku Katakana
* All hankaku English alphabet and numberc string are converted into Zenkaku one
"""
return jaconv.h2z(inpu... | [
"def",
"normalize_text_normal_ipadic",
"(",
"input_text",
",",
"kana",
"=",
"True",
",",
"ascii",
"=",
"True",
",",
"digit",
"=",
"True",
")",
":",
"# type: (text_type,bool,bool,bool)->text_type",
"return",
"jaconv",
".",
"h2z",
"(",
"input_text",
",",
"kana",
"... | * All hankaku Katanaka is converted into Zenkaku Katakana
* All hankaku English alphabet and numberc string are converted into Zenkaku one | [
"*",
"All",
"hankaku",
"Katanaka",
"is",
"converted",
"into",
"Zenkaku",
"Katakana",
"*",
"All",
"hankaku",
"English",
"alphabet",
"and",
"numberc",
"string",
"are",
"converted",
"into",
"Zenkaku",
"one"
] | python | train |
manns/pyspread | pyspread/src/lib/selection.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/selection.py#L245-L252 | def parameters(self):
"""Returns tuple of selection parameters of self
(self.block_tl, self.block_br, self.rows, self.cols, self.cells)
"""
return self.block_tl, self.block_br, self.rows, self.cols, self.cells | [
"def",
"parameters",
"(",
"self",
")",
":",
"return",
"self",
".",
"block_tl",
",",
"self",
".",
"block_br",
",",
"self",
".",
"rows",
",",
"self",
".",
"cols",
",",
"self",
".",
"cells"
] | Returns tuple of selection parameters of self
(self.block_tl, self.block_br, self.rows, self.cols, self.cells) | [
"Returns",
"tuple",
"of",
"selection",
"parameters",
"of",
"self"
] | python | train |
jonathanj/txspinneret | txspinneret/query.py | https://github.com/jonathanj/txspinneret/blob/717008a2c313698984a23e3f3fc62ea3675ed02d/txspinneret/query.py#L148-L177 | def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),
encoding=None):
"""
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for... | [
"def",
"Boolean",
"(",
"value",
",",
"true",
"=",
"(",
"u'yes'",
",",
"u'1'",
",",
"u'true'",
")",
",",
"false",
"=",
"(",
"u'no'",
",",
"u'0'",
",",
"u'false'",
")",
",",
"encoding",
"=",
"None",
")",
":",
"value",
"=",
"Text",
"(",
"value",
","... | Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for ``True`` values.
:type false: `tuple` of `unicode`
:param false: Values to compare, ignoring case, for ``Fals... | [
"Parse",
"a",
"value",
"as",
"a",
"boolean",
"."
] | python | valid |
ubyssey/dispatch | dispatch/api/views.py | https://github.com/ubyssey/dispatch/blob/8da6084fe61726f20e9cf675190480cfc45ee764/dispatch/api/views.py#L138-L153 | def get_queryset(self):
"""Only display unpublished content to authenticated users, filter by
query parameter if present."""
# Get base queryset from DispatchPublishableMixin
queryset = self.get_publishable_queryset()
queryset = queryset.order_by('-updated_at')
# Optio... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"# Get base queryset from DispatchPublishableMixin",
"queryset",
"=",
"self",
".",
"get_publishable_queryset",
"(",
")",
"queryset",
"=",
"queryset",
".",
"order_by",
"(",
"'-updated_at'",
")",
"# Optionally filter by a query ... | Only display unpublished content to authenticated users, filter by
query parameter if present. | [
"Only",
"display",
"unpublished",
"content",
"to",
"authenticated",
"users",
"filter",
"by",
"query",
"parameter",
"if",
"present",
"."
] | python | test |
chaoss/grimoirelab-elk | grimoire_elk/utils.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/utils.py#L262-L284 | def get_kibiter_version(url):
"""
Return kibiter major number version
The url must point to the Elasticsearch used by Kibiter
"""
config_url = '.kibana/config/_search'
# Avoid having // in the URL because ES will fail
if url[-1] != '/':
url += "/"
url += config_url
... | [
"def",
"get_kibiter_version",
"(",
"url",
")",
":",
"config_url",
"=",
"'.kibana/config/_search'",
"# Avoid having // in the URL because ES will fail",
"if",
"url",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"url",
"+=",
"\"/\"",
"url",
"+=",
"config_url",
"r",
"=",
... | Return kibiter major number version
The url must point to the Elasticsearch used by Kibiter | [
"Return",
"kibiter",
"major",
"number",
"version"
] | python | train |
clchiou/startup | startup.py | https://github.com/clchiou/startup/blob/13cbf3ce1deffbc10d33a5f64c396a73129a5929/startup.py#L271-L294 | def _parse_ret(func, variables, annotations=None):
"""Parse func's return annotation and return either None, a variable,
or a tuple of variables.
NOTE:
* _parse_ret() also notifies variables about will-writes.
* A variable can be written multiple times per return annotation.
"""
anno = ... | [
"def",
"_parse_ret",
"(",
"func",
",",
"variables",
",",
"annotations",
"=",
"None",
")",
":",
"anno",
"=",
"(",
"annotations",
"or",
"func",
".",
"__annotations__",
")",
".",
"get",
"(",
"'return'",
")",
"if",
"anno",
"is",
"None",
":",
"return",
"Non... | Parse func's return annotation and return either None, a variable,
or a tuple of variables.
NOTE:
* _parse_ret() also notifies variables about will-writes.
* A variable can be written multiple times per return annotation. | [
"Parse",
"func",
"s",
"return",
"annotation",
"and",
"return",
"either",
"None",
"a",
"variable",
"or",
"a",
"tuple",
"of",
"variables",
"."
] | python | train |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L9128-L9150 | def svs_description_metadata(description):
"""Return metatata from Aperio image description as dict.
The Aperio image description format is unspecified. Expect failures.
>>> svs_description_metadata('Aperio Image Library v1.0')
{'Aperio Image Library': 'v1.0'}
"""
if not description.startswit... | [
"def",
"svs_description_metadata",
"(",
"description",
")",
":",
"if",
"not",
"description",
".",
"startswith",
"(",
"'Aperio Image Library '",
")",
":",
"raise",
"ValueError",
"(",
"'invalid Aperio image description'",
")",
"result",
"=",
"{",
"}",
"lines",
"=",
... | Return metatata from Aperio image description as dict.
The Aperio image description format is unspecified. Expect failures.
>>> svs_description_metadata('Aperio Image Library v1.0')
{'Aperio Image Library': 'v1.0'} | [
"Return",
"metatata",
"from",
"Aperio",
"image",
"description",
"as",
"dict",
"."
] | python | train |
LLNL/scraper | scripts/get_traffic.py | https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scripts/get_traffic.py#L134-L140 | def get_releases(self, url='', headers={}, repo_name=''):
"""
Retrieves the releases for the given repo in JSON.
"""
url_releases = (url + '/releases')
r = requests.get(url_releases, headers=headers)
self.releases_json[repo_name] = r.json() | [
"def",
"get_releases",
"(",
"self",
",",
"url",
"=",
"''",
",",
"headers",
"=",
"{",
"}",
",",
"repo_name",
"=",
"''",
")",
":",
"url_releases",
"=",
"(",
"url",
"+",
"'/releases'",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url_releases",
",",
"... | Retrieves the releases for the given repo in JSON. | [
"Retrieves",
"the",
"releases",
"for",
"the",
"given",
"repo",
"in",
"JSON",
"."
] | python | test |
xzased/lvm2py | lvm2py/lv.py | https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/lv.py#L65-L78 | def open(self):
"""
Obtains the lvm, vg_t and lv_t handle. Usually you would never need to use this
method unless you are doing operations using the ctypes function wrappers in
conversion.py
*Raises:*
* HandleError
"""
self.vg.open()
self._... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"vg",
".",
"open",
"(",
")",
"self",
".",
"__lvh",
"=",
"lvm_lv_from_uuid",
"(",
"self",
".",
"vg",
".",
"handle",
",",
"self",
".",
"uuid",
")",
"if",
"not",
"bool",
"(",
"self",
".",
"__lvh",
... | Obtains the lvm, vg_t and lv_t handle. Usually you would never need to use this
method unless you are doing operations using the ctypes function wrappers in
conversion.py
*Raises:*
* HandleError | [
"Obtains",
"the",
"lvm",
"vg_t",
"and",
"lv_t",
"handle",
".",
"Usually",
"you",
"would",
"never",
"need",
"to",
"use",
"this",
"method",
"unless",
"you",
"are",
"doing",
"operations",
"using",
"the",
"ctypes",
"function",
"wrappers",
"in",
"conversion",
"."... | python | train |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/containers.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/containers.py#L71-L77 | def get_meta_fields(self, fields, kwargs={}):
'''
Return a dictionary of metadata fields
'''
fields = to_list(fields)
meta = self.get_meta()
return {field: meta.get(field) for field in fields} | [
"def",
"get_meta_fields",
"(",
"self",
",",
"fields",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"fields",
"=",
"to_list",
"(",
"fields",
")",
"meta",
"=",
"self",
".",
"get_meta",
"(",
")",
"return",
"{",
"field",
":",
"meta",
".",
"get",
"(",
"field... | Return a dictionary of metadata fields | [
"Return",
"a",
"dictionary",
"of",
"metadata",
"fields"
] | python | train |
dhermes/bezier | src/bezier/_algebraic_intersection.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1225-L1253 | def _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t):
"""Resolve a computed intersection and add to lists.
We perform one Newton step to deal with any residual issues of
high-degree polynomial solves (one of which depends on the already
approximate ``x_val, y_val``).
Args:
... | [
"def",
"_resolve_and_add",
"(",
"nodes1",
",",
"s_val",
",",
"final_s",
",",
"nodes2",
",",
"t_val",
",",
"final_t",
")",
":",
"s_val",
",",
"t_val",
"=",
"_intersection_helpers",
".",
"newton_refine",
"(",
"s_val",
",",
"nodes1",
",",
"t_val",
",",
"nodes... | Resolve a computed intersection and add to lists.
We perform one Newton step to deal with any residual issues of
high-degree polynomial solves (one of which depends on the already
approximate ``x_val, y_val``).
Args:
nodes1 (numpy.ndarray): The nodes in the first curve.
s_val (float): ... | [
"Resolve",
"a",
"computed",
"intersection",
"and",
"add",
"to",
"lists",
"."
] | python | train |
dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L535-L623 | def from_raw_file(self, raw_file, store=current_store, size=None,
mimetype=None, original=True, extra_args=None,
extra_kwargs=None):
"""Similar to :meth:`from_file()` except it's lower than that.
It assumes that ``raw_file`` is readable and seekable while
... | [
"def",
"from_raw_file",
"(",
"self",
",",
"raw_file",
",",
"store",
"=",
"current_store",
",",
"size",
"=",
"None",
",",
"mimetype",
"=",
"None",
",",
"original",
"=",
"True",
",",
"extra_args",
"=",
"None",
",",
"extra_kwargs",
"=",
"None",
")",
":",
... | Similar to :meth:`from_file()` except it's lower than that.
It assumes that ``raw_file`` is readable and seekable while
:meth:`from_file()` only assumes the file is readable.
Also it doesn't make any in-memory buffer while
:meth:`from_file()` always makes an in-memory buffer and copy
... | [
"Similar",
"to",
":",
"meth",
":",
"from_file",
"()",
"except",
"it",
"s",
"lower",
"than",
"that",
".",
"It",
"assumes",
"that",
"raw_file",
"is",
"readable",
"and",
"seekable",
"while",
":",
"meth",
":",
"from_file",
"()",
"only",
"assumes",
"the",
"fi... | python | train |
Kozea/pygal | pygal/graph/line.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/line.py#L86-L187 | def line(self, serie, rescale=False):
"""Draw the line serie"""
serie_node = self.svg.serie(serie)
if rescale and self.secondary_series:
points = self._rescale(serie.points)
else:
points = serie.points
view_values = list(map(self.view, points))
if ... | [
"def",
"line",
"(",
"self",
",",
"serie",
",",
"rescale",
"=",
"False",
")",
":",
"serie_node",
"=",
"self",
".",
"svg",
".",
"serie",
"(",
"serie",
")",
"if",
"rescale",
"and",
"self",
".",
"secondary_series",
":",
"points",
"=",
"self",
".",
"_resc... | Draw the line serie | [
"Draw",
"the",
"line",
"serie"
] | python | train |
Rockhopper-Technologies/pluginlib | pluginlib/_objects.py | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_objects.py#L202-L230 | def _process_blacklist(self, blacklist):
"""
Process blacklist into set of excluded versions
"""
# Assume blacklist is correct format since it is checked by PluginLoader
blacklist_cache = {}
blacklist_cache_old = self._cache.get('blacklist', {})
for entry in bl... | [
"def",
"_process_blacklist",
"(",
"self",
",",
"blacklist",
")",
":",
"# Assume blacklist is correct format since it is checked by PluginLoader",
"blacklist_cache",
"=",
"{",
"}",
"blacklist_cache_old",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"'blacklist'",
",",
"{... | Process blacklist into set of excluded versions | [
"Process",
"blacklist",
"into",
"set",
"of",
"excluded",
"versions"
] | python | train |
cloudera/impyla | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L4758-L4766 | def delete_table_column_statistics(self, db_name, tbl_name, col_name):
"""
Parameters:
- db_name
- tbl_name
- col_name
"""
self.send_delete_table_column_statistics(db_name, tbl_name, col_name)
return self.recv_delete_table_column_statistics() | [
"def",
"delete_table_column_statistics",
"(",
"self",
",",
"db_name",
",",
"tbl_name",
",",
"col_name",
")",
":",
"self",
".",
"send_delete_table_column_statistics",
"(",
"db_name",
",",
"tbl_name",
",",
"col_name",
")",
"return",
"self",
".",
"recv_delete_table_col... | Parameters:
- db_name
- tbl_name
- col_name | [
"Parameters",
":",
"-",
"db_name",
"-",
"tbl_name",
"-",
"col_name"
] | python | train |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L936-L944 | def process_request_body(fn):
'''
A decorator to skip a processor function if process_request_body is False
'''
@functools.wraps(fn)
def wrapped(*args, **kwargs): # pylint: disable=C0111
if cherrypy.request.process_request_body is not False:
fn(*args, **kwargs)
return wrappe... | [
"def",
"process_request_body",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0111",
"if",
"cherrypy",
".",
"request",
".",
"process_request_bo... | A decorator to skip a processor function if process_request_body is False | [
"A",
"decorator",
"to",
"skip",
"a",
"processor",
"function",
"if",
"process_request_body",
"is",
"False"
] | python | train |
moralrecordings/mrcrowbar | mrcrowbar/statistics.py | https://github.com/moralrecordings/mrcrowbar/blob/b1ed882c4555552e7656b2d84aca543184577fa3/mrcrowbar/statistics.py#L34-L59 | def ansi_format( self, width=64, height=12 ):
"""Return a human readable ANSI-terminal printout of the stats.
width
Custom width for the graph (in characters).
height
Custom height for the graph (in characters).
"""
from mrcrowbar.ansi import format_bar_... | [
"def",
"ansi_format",
"(",
"self",
",",
"width",
"=",
"64",
",",
"height",
"=",
"12",
")",
":",
"from",
"mrcrowbar",
".",
"ansi",
"import",
"format_bar_graph_iter",
"if",
"(",
"256",
"%",
"width",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'Widt... | Return a human readable ANSI-terminal printout of the stats.
width
Custom width for the graph (in characters).
height
Custom height for the graph (in characters). | [
"Return",
"a",
"human",
"readable",
"ANSI",
"-",
"terminal",
"printout",
"of",
"the",
"stats",
"."
] | python | train |
saltstack/salt | salt/utils/files.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/files.py#L435-L476 | def fpopen(*args, **kwargs):
'''
Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, i... | [
"def",
"fpopen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove uid, gid and mode from kwargs if present",
"uid",
"=",
"kwargs",
".",
"pop",
"(",
"'uid'",
",",
"-",
"1",
")",
"# -1 means no change to current uid",
"gid",
"=",
"kwargs",
".",
"po... | Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, if not set, or it is None or -1 no changes... | [
"Shortcut",
"for",
"fopen",
"with",
"extra",
"uid",
"gid",
"and",
"mode",
"options",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L550-L585 | def _networking(self):
"""
Configures the IOL bridge in uBridge.
"""
bridge_name = "IOL-BRIDGE-{}".format(self.application_id + 512)
try:
# delete any previous bridge if it exists
yield from self._ubridge_send("iol_bridge delete {name}".format(name=bridge... | [
"def",
"_networking",
"(",
"self",
")",
":",
"bridge_name",
"=",
"\"IOL-BRIDGE-{}\"",
".",
"format",
"(",
"self",
".",
"application_id",
"+",
"512",
")",
"try",
":",
"# delete any previous bridge if it exists",
"yield",
"from",
"self",
".",
"_ubridge_send",
"(",
... | Configures the IOL bridge in uBridge. | [
"Configures",
"the",
"IOL",
"bridge",
"in",
"uBridge",
"."
] | python | train |
google/brotli | research/brotlidump.py | https://github.com/google/brotli/blob/4b2b2d4f83ffeaac7708e44409fe34896a01a278/research/brotlidump.py#L1376-L1383 | def makeHexData(self, pos):
"""Produce hex dump of all data containing the bits
from pos to stream.pos
"""
firstAddress = pos+7>>3
lastAddress = self.stream.pos+7>>3
return ''.join(map('{:02x} '.format,
self.stream.data[firstAddress:lastAddress])) | [
"def",
"makeHexData",
"(",
"self",
",",
"pos",
")",
":",
"firstAddress",
"=",
"pos",
"+",
"7",
">>",
"3",
"lastAddress",
"=",
"self",
".",
"stream",
".",
"pos",
"+",
"7",
">>",
"3",
"return",
"''",
".",
"join",
"(",
"map",
"(",
"'{:02x} '",
".",
... | Produce hex dump of all data containing the bits
from pos to stream.pos | [
"Produce",
"hex",
"dump",
"of",
"all",
"data",
"containing",
"the",
"bits",
"from",
"pos",
"to",
"stream",
".",
"pos"
] | python | test |
saltstack/salt | salt/modules/cloud.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L140-L153 | def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True | [
"def",
"has_instance",
"(",
"name",
",",
"provider",
"=",
"None",
")",
":",
"data",
"=",
"get_instance",
"(",
"name",
",",
"provider",
")",
"if",
"data",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance | [
"Return",
"true",
"if",
"the",
"instance",
"is",
"found",
"on",
"a",
"provider"
] | python | train |
matplotlib/cmocean | cmocean/plots.py | https://github.com/matplotlib/cmocean/blob/37edd4a209a733d87dea7fed9eb22adc1d5a57c8/cmocean/plots.py#L164-L183 | def quick_plot(cmap, fname=None, fig=None, ax=None, N=10):
'''Show quick test of a colormap.
'''
x = np.linspace(0, 10, N)
X, _ = np.meshgrid(x, x)
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
mappable = ax.pcolor(X, cmap=cmap)
ax.set_title(cmap.name, fontsi... | [
"def",
"quick_plot",
"(",
"cmap",
",",
"fname",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"N",
"=",
"10",
")",
":",
"x",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"10",
",",
"N",
")",
"X",
",",
"_",
"=",
"np",
".... | Show quick test of a colormap. | [
"Show",
"quick",
"test",
"of",
"a",
"colormap",
"."
] | python | train |
aiortc/aiortc | aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcicetransport.py#L270-L294 | async def start(self, remoteParameters):
"""
Initiate connectivity checks.
:param: remoteParameters: The :class:`RTCIceParameters` associated with
the remote :class:`RTCIceTransport`.
"""
if self.state == 'closed':
raise InvalidState... | [
"async",
"def",
"start",
"(",
"self",
",",
"remoteParameters",
")",
":",
"if",
"self",
".",
"state",
"==",
"'closed'",
":",
"raise",
"InvalidStateError",
"(",
"'RTCIceTransport is closed'",
")",
"# handle the case where start is already in progress",
"if",
"self",
"."... | Initiate connectivity checks.
:param: remoteParameters: The :class:`RTCIceParameters` associated with
the remote :class:`RTCIceTransport`. | [
"Initiate",
"connectivity",
"checks",
"."
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/aio/index.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/index.py#L127-L139 | async def findTask(self, *args, **kwargs):
"""
Find Indexed Task
Find a task by index path, returning the highest-rank task with that path. If no
task exists for the given path, this API end-point will respond with a 404 status.
This method gives output: ``v1/indexed-task-respo... | [
"async",
"def",
"findTask",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"findTask\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Find Indexed Task
Find a task by index path, returning the highest-rank task with that path. If no
task exists for the given path, this API end-point will respond with a 404 status.
This method gives output: ``v1/indexed-task-response.json#``
This method is ``stable`` | [
"Find",
"Indexed",
"Task"
] | python | train |
asyncdef/interfaces | asyncdef/interfaces/engine/itime.py | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/itime.py#L24-L50 | def defer(
self,
func: typing.Callable[[], typing.Any],
until: typing.Union[int, float]=-1,
) -> typing.Any:
"""Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
... | [
"def",
"defer",
"(",
"self",
",",
"func",
":",
"typing",
".",
"Callable",
"[",
"[",
"]",
",",
"typing",
".",
"Any",
"]",
",",
"until",
":",
"typing",
".",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"-",
"1",
",",
")",
"->",
"typing",
".",
"... | Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
arguments. All return values are ignored.
until (typing.Union[int, float]): A numeric value that represents
the clock time w... | [
"Defer",
"the",
"execution",
"of",
"a",
"function",
"until",
"some",
"clock",
"value",
"."
] | python | train |
CalebBell/ht | ht/hx.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/hx.py#L2964-L2977 | def _NTU_from_P_solver(P1, R1, NTU_min, NTU_max, function, **kwargs):
'''Private function to solve the P-NTU method backwards, given the
function to use, the upper and lower NTU bounds for consideration,
and the desired P1 and R1 values.
'''
P1_max = _NTU_from_P_objective(NTU_max, R1, 0, function, *... | [
"def",
"_NTU_from_P_solver",
"(",
"P1",
",",
"R1",
",",
"NTU_min",
",",
"NTU_max",
",",
"function",
",",
"*",
"*",
"kwargs",
")",
":",
"P1_max",
"=",
"_NTU_from_P_objective",
"(",
"NTU_max",
",",
"R1",
",",
"0",
",",
"function",
",",
"*",
"*",
"kwargs"... | Private function to solve the P-NTU method backwards, given the
function to use, the upper and lower NTU bounds for consideration,
and the desired P1 and R1 values. | [
"Private",
"function",
"to",
"solve",
"the",
"P",
"-",
"NTU",
"method",
"backwards",
"given",
"the",
"function",
"to",
"use",
"the",
"upper",
"and",
"lower",
"NTU",
"bounds",
"for",
"consideration",
"and",
"the",
"desired",
"P1",
"and",
"R1",
"values",
"."... | python | train |
oanda/v20-python | src/v20/account.py | https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/account.py#L1323-L1391 | def list(
self,
**kwargs
):
"""
Get a list of all Accounts authorized for the provided token.
Args:
Returns:
v20.response.Response containing the results from submitting the
request
"""
request = Request(
'GET',
... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"Request",
"(",
"'GET'",
",",
"'/v3/accounts'",
")",
"response",
"=",
"self",
".",
"ctx",
".",
"request",
"(",
"request",
")",
"if",
"response",
".",
"content_type",
"is",
... | Get a list of all Accounts authorized for the provided token.
Args:
Returns:
v20.response.Response containing the results from submitting the
request | [
"Get",
"a",
"list",
"of",
"all",
"Accounts",
"authorized",
"for",
"the",
"provided",
"token",
"."
] | python | train |
nickmckay/LiPD-utilities | Matlab/bagit.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L366-L374 | def is_valid(self, fast=False):
"""Returns validation success or failure as boolean.
Optional fast parameter passed directly to validate().
"""
try:
self.validate(fast=fast)
except BagError:
return False
return True | [
"def",
"is_valid",
"(",
"self",
",",
"fast",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"validate",
"(",
"fast",
"=",
"fast",
")",
"except",
"BagError",
":",
"return",
"False",
"return",
"True"
] | Returns validation success or failure as boolean.
Optional fast parameter passed directly to validate(). | [
"Returns",
"validation",
"success",
"or",
"failure",
"as",
"boolean",
".",
"Optional",
"fast",
"parameter",
"passed",
"directly",
"to",
"validate",
"()",
"."
] | python | train |
justinabrahms/imhotep | imhotep/reporters/github.py | https://github.com/justinabrahms/imhotep/blob/c6dc365ef34505d7b6837187900e59b00e5fab08/imhotep/reporters/github.py#L97-L108 | def post_comment(self, message):
"""
Comments on an issue, not on a particular line.
"""
report_url = (
'https://api.github.com/repos/%s/issues/%s/comments'
% (self.repo_name, self.pr_number)
)
result = self.requester.post(report_url, {'body': mess... | [
"def",
"post_comment",
"(",
"self",
",",
"message",
")",
":",
"report_url",
"=",
"(",
"'https://api.github.com/repos/%s/issues/%s/comments'",
"%",
"(",
"self",
".",
"repo_name",
",",
"self",
".",
"pr_number",
")",
")",
"result",
"=",
"self",
".",
"requester",
... | Comments on an issue, not on a particular line. | [
"Comments",
"on",
"an",
"issue",
"not",
"on",
"a",
"particular",
"line",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xview.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xview.py#L44-L83 | def xviewSlot(*typs, **opts):
"""
Defines a method as being a slot for the XView system. This will validate
the method against the signal properties if it is triggered from the
dispatcher, taking into account currency and grouping for the widget.
You can specify the optional policy keyword to def... | [
"def",
"xviewSlot",
"(",
"*",
"typs",
",",
"*",
"*",
"opts",
")",
":",
"default",
"=",
"opts",
".",
"get",
"(",
"'default'",
")",
"policy",
"=",
"opts",
".",
"get",
"(",
"'policy'",
")",
"if",
"typs",
":",
"typ_count",
"=",
"len",
"(",
"typs",
")... | Defines a method as being a slot for the XView system. This will validate
the method against the signal properties if it is triggered from the
dispatcher, taking into account currency and grouping for the widget.
You can specify the optional policy keyword to define the specific signal
policy for thi... | [
"Defines",
"a",
"method",
"as",
"being",
"a",
"slot",
"for",
"the",
"XView",
"system",
".",
"This",
"will",
"validate",
"the",
"method",
"against",
"the",
"signal",
"properties",
"if",
"it",
"is",
"triggered",
"from",
"the",
"dispatcher",
"taking",
"into",
... | python | train |
Jaymon/endpoints | endpoints/http.py | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L434-L447 | def parse_query(cls, query):
"""return name=val&name2=val2 strings into {name: val} dict"""
if not query: return {}
d = {}
# https://docs.python.org/2/library/urlparse.html
for k, kv in urlparse.parse_qs(query, True, strict_parsing=True).items():
#k = k.rstrip("[]") ... | [
"def",
"parse_query",
"(",
"cls",
",",
"query",
")",
":",
"if",
"not",
"query",
":",
"return",
"{",
"}",
"d",
"=",
"{",
"}",
"# https://docs.python.org/2/library/urlparse.html",
"for",
"k",
",",
"kv",
"in",
"urlparse",
".",
"parse_qs",
"(",
"query",
",",
... | return name=val&name2=val2 strings into {name: val} dict | [
"return",
"name",
"=",
"val&name2",
"=",
"val2",
"strings",
"into",
"{",
"name",
":",
"val",
"}",
"dict"
] | python | train |
spencerahill/aospy | aospy/calc.py | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L349-L363 | def _compute_full_ts(self, data):
"""Perform calculation and create yearly timeseries at each point."""
# Get results at each desired timestep and spatial point.
full_ts, dt = self._compute(data)
# Vertically integrate.
vert_types = ('vert_int', 'vert_av')
if self.dtype_o... | [
"def",
"_compute_full_ts",
"(",
"self",
",",
"data",
")",
":",
"# Get results at each desired timestep and spatial point.",
"full_ts",
",",
"dt",
"=",
"self",
".",
"_compute",
"(",
"data",
")",
"# Vertically integrate.",
"vert_types",
"=",
"(",
"'vert_int'",
",",
"'... | Perform calculation and create yearly timeseries at each point. | [
"Perform",
"calculation",
"and",
"create",
"yearly",
"timeseries",
"at",
"each",
"point",
"."
] | python | train |
SheffieldML/GPy | GPy/inference/latent_function_inference/vardtc_md.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/inference/latent_function_inference/vardtc_md.py#L32-L171 | def inference(self, kern, X, Z, likelihood, Y, indexD, output_dim, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None):
"""
The first phase of inference:
Compute: log-likelihood, dL_dKmm
Cached intermediate results: Kmm, KmmInv,
"""
input_dim = Z.shape[0]
u... | [
"def",
"inference",
"(",
"self",
",",
"kern",
",",
"X",
",",
"Z",
",",
"likelihood",
",",
"Y",
",",
"indexD",
",",
"output_dim",
",",
"Y_metadata",
"=",
"None",
",",
"Lm",
"=",
"None",
",",
"dL_dKmm",
"=",
"None",
",",
"Kuu_sigma",
"=",
"None",
")"... | The first phase of inference:
Compute: log-likelihood, dL_dKmm
Cached intermediate results: Kmm, KmmInv, | [
"The",
"first",
"phase",
"of",
"inference",
":",
"Compute",
":",
"log",
"-",
"likelihood",
"dL_dKmm"
] | python | train |
uber/doubles | doubles/target.py | https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/target.py#L96-L112 | def hijack_attr(self, attr_name):
"""Hijack an attribute on the target object.
Updates the underlying class and delegating the call to the instance.
This allows specially-handled attributes like __call__, __enter__,
and __exit__ to be mocked on a per-instance basis.
:param str ... | [
"def",
"hijack_attr",
"(",
"self",
",",
"attr_name",
")",
":",
"if",
"not",
"self",
".",
"_original_attr",
"(",
"attr_name",
")",
":",
"setattr",
"(",
"self",
".",
"obj",
".",
"__class__",
",",
"attr_name",
",",
"_proxy_class_method_to_instance",
"(",
"getat... | Hijack an attribute on the target object.
Updates the underlying class and delegating the call to the instance.
This allows specially-handled attributes like __call__, __enter__,
and __exit__ to be mocked on a per-instance basis.
:param str attr_name: the name of the attribute to hijac... | [
"Hijack",
"an",
"attribute",
"on",
"the",
"target",
"object",
"."
] | python | train |
UCL-INGI/INGInious | inginious/common/tasks.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tasks.py#L132-L160 | def check_answer(self, task_input, language):
"""
Verify the answers in task_input. Returns six values
1st: True the input is **currently** valid. (may become invalid after running the code), False else
2nd: True if the input needs to be run in the VM, False else
... | [
"def",
"check_answer",
"(",
"self",
",",
"task_input",
",",
"language",
")",
":",
"valid",
"=",
"True",
"need_launch",
"=",
"False",
"main_message",
"=",
"[",
"]",
"problem_messages",
"=",
"{",
"}",
"error_count",
"=",
"0",
"multiple_choice_error_count",
"=",
... | Verify the answers in task_input. Returns six values
1st: True the input is **currently** valid. (may become invalid after running the code), False else
2nd: True if the input needs to be run in the VM, False else
3rd: Main message, as a list (that can be join with \n or <br/> for ex... | [
"Verify",
"the",
"answers",
"in",
"task_input",
".",
"Returns",
"six",
"values",
"1st",
":",
"True",
"the",
"input",
"is",
"**",
"currently",
"**",
"valid",
".",
"(",
"may",
"become",
"invalid",
"after",
"running",
"the",
"code",
")",
"False",
"else",
"2... | python | train |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L284-L295 | def ReadVarString(self, max=sys.maxsize):
"""
Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator.
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes:
"""
length = self.Re... | [
"def",
"ReadVarString",
"(",
"self",
",",
"max",
"=",
"sys",
".",
"maxsize",
")",
":",
"length",
"=",
"self",
".",
"ReadVarInt",
"(",
"max",
")",
"return",
"self",
".",
"unpack",
"(",
"str",
"(",
"length",
")",
"+",
"'s'",
",",
"length",
")"
] | Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator.
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes: | [
"Similar",
"to",
"ReadString",
"but",
"expects",
"a",
"variable",
"length",
"indicator",
"instead",
"of",
"the",
"fixed",
"1",
"byte",
"indicator",
"."
] | python | train |
pantsbuild/pants | src/python/pants/java/nailgun_client.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_client.py#L110-L166 | def _process_session(self):
"""Process the outputs of the nailgun session.
:raises: :class:`NailgunProtocol.ProcessStreamTimeout` if a timeout set from a signal handler
with .set_exit_timeout() completes.
:raises: :class:`Exception` if the session ... | [
"def",
"_process_session",
"(",
"self",
")",
":",
"try",
":",
"for",
"chunk_type",
",",
"payload",
"in",
"self",
".",
"iter_chunks",
"(",
"self",
".",
"_sock",
",",
"return_bytes",
"=",
"True",
",",
"timeout_object",
"=",
"self",
")",
":",
"# TODO(#6579): ... | Process the outputs of the nailgun session.
:raises: :class:`NailgunProtocol.ProcessStreamTimeout` if a timeout set from a signal handler
with .set_exit_timeout() completes.
:raises: :class:`Exception` if the session completes before the timeout, the `... | [
"Process",
"the",
"outputs",
"of",
"the",
"nailgun",
"session",
"."
] | python | train |
gem/oq-engine | openquake/commonlib/logictree.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L661-L688 | def parse_branchset(self, branchset_node, depth, number, validate):
"""
Create :class:`BranchSet` object using data in ``branchset_node``.
:param branchset_node:
``etree.Element`` object with tag "logicTreeBranchSet".
:param depth:
The sequential number of branch... | [
"def",
"parse_branchset",
"(",
"self",
",",
"branchset_node",
",",
"depth",
",",
"number",
",",
"validate",
")",
":",
"uncertainty_type",
"=",
"branchset_node",
".",
"attrib",
".",
"get",
"(",
"'uncertaintyType'",
")",
"filters",
"=",
"dict",
"(",
"(",
"filt... | Create :class:`BranchSet` object using data in ``branchset_node``.
:param branchset_node:
``etree.Element`` object with tag "logicTreeBranchSet".
:param depth:
The sequential number of branchset's branching level, based on 0.
:param number:
Index number of th... | [
"Create",
":",
"class",
":",
"BranchSet",
"object",
"using",
"data",
"in",
"branchset_node",
"."
] | python | train |
RLBot/RLBot | src/main/python/rlbot/utils/class_importer.py | https://github.com/RLBot/RLBot/blob/3f9b6bec8b9baf4dcfff0f6cf3103c8744ac6234/src/main/python/rlbot/utils/class_importer.py#L65-L95 | def load_external_module(python_file):
"""
Returns the loaded module.
All of its newly added dependencies are removed from sys.path after load.
"""
# There's a special case where python_file may be pointing at the base agent definition here in the framework.
# This is sometimes done as a defaul... | [
"def",
"load_external_module",
"(",
"python_file",
")",
":",
"# There's a special case where python_file may be pointing at the base agent definition here in the framework.",
"# This is sometimes done as a default and we want to allow it. Short-circuit the logic because",
"# loading it as if it's an... | Returns the loaded module.
All of its newly added dependencies are removed from sys.path after load. | [
"Returns",
"the",
"loaded",
"module",
".",
"All",
"of",
"its",
"newly",
"added",
"dependencies",
"are",
"removed",
"from",
"sys",
".",
"path",
"after",
"load",
"."
] | python | train |
saltstack/salt | salt/modules/bsd_shadow.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bsd_shadow.py#L49-L103 | def info(name):
'''
Return information for the specified user
CLI Example:
.. code-block:: bash
salt '*' shadow.info someuser
'''
try:
data = pwd.getpwnam(name)
ret = {
'name': data.pw_name,
'passwd': data.pw_passwd}
except KeyError:
... | [
"def",
"info",
"(",
"name",
")",
":",
"try",
":",
"data",
"=",
"pwd",
".",
"getpwnam",
"(",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"data",
".",
"pw_name",
",",
"'passwd'",
":",
"data",
".",
"pw_passwd",
"}",
"except",
"KeyError",
":",
"return... | Return information for the specified user
CLI Example:
.. code-block:: bash
salt '*' shadow.info someuser | [
"Return",
"information",
"for",
"the",
"specified",
"user"
] | python | train |
tjvr/kurt | kurt/__init__.py | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2241-L2252 | def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
... | [
"def",
"_convert",
"(",
"self",
",",
"format",
")",
":",
"if",
"self",
".",
"format",
"==",
"format",
":",
"return",
"self",
"else",
":",
"image",
"=",
"Image",
"(",
"self",
".",
"pil_image",
")",
"image",
".",
"_format",
"=",
"format",
"return",
"im... | Return a new Image instance with the given format.
Returns self if the format is already the same. | [
"Return",
"a",
"new",
"Image",
"instance",
"with",
"the",
"given",
"format",
"."
] | python | train |
abseil/abseil-py | absl/logging/__init__.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L367-L380 | def log_every_n(level, msg, n, *args):
"""Logs 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n: int, the number of times this shou... | [
"def",
"log_every_n",
"(",
"level",
",",
"msg",
",",
"n",
",",
"*",
"args",
")",
":",
"count",
"=",
"_get_next_log_count_per_token",
"(",
"get_absl_logger",
"(",
")",
".",
"findCaller",
"(",
")",
")",
"log_if",
"(",
"level",
",",
"msg",
",",
"not",
"("... | Logs 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n: int, the number of times this should be called before it is logged.
*args:... | [
"Logs",
"msg",
"%",
"args",
"at",
"level",
"level",
"once",
"per",
"n",
"times",
"."
] | python | train |
pantsbuild/pex | pex/third_party/__init__.py | https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/third_party/__init__.py#L244-L267 | def install(cls, uninstallable, prefix, path_items, root=None, warning=None):
"""Install an importer for modules found under ``path_items`` at the given import ``prefix``.
:param bool uninstallable: ``True`` if the installed importer should be uninstalled and any
imports it perfo... | [
"def",
"install",
"(",
"cls",
",",
"uninstallable",
",",
"prefix",
",",
"path_items",
",",
"root",
"=",
"None",
",",
"warning",
"=",
"None",
")",
":",
"root",
"=",
"cls",
".",
"_abs_root",
"(",
"root",
")",
"importables",
"=",
"tuple",
"(",
"cls",
".... | Install an importer for modules found under ``path_items`` at the given import ``prefix``.
:param bool uninstallable: ``True`` if the installed importer should be uninstalled and any
imports it performed be un-imported when ``uninstall`` is called.
:param str prefix: The import p... | [
"Install",
"an",
"importer",
"for",
"modules",
"found",
"under",
"path_items",
"at",
"the",
"given",
"import",
"prefix",
"."
] | python | train |
FPGAwars/apio | apio/commands/upgrade.py | https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/upgrade.py#L16-L32 | def cli(ctx):
"""Check the latest Apio version."""
current_version = get_distribution('apio').version
latest_version = get_pypi_latest_version()
if latest_version is None:
ctx.exit(1)
if latest_version == current_version:
click.secho('You\'re up-to-date!\nApio {} is currently the ... | [
"def",
"cli",
"(",
"ctx",
")",
":",
"current_version",
"=",
"get_distribution",
"(",
"'apio'",
")",
".",
"version",
"latest_version",
"=",
"get_pypi_latest_version",
"(",
")",
"if",
"latest_version",
"is",
"None",
":",
"ctx",
".",
"exit",
"(",
"1",
")",
"i... | Check the latest Apio version. | [
"Check",
"the",
"latest",
"Apio",
"version",
"."
] | python | train |
pazz/alot | alot/db/manager.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L424-L445 | def add_message(self, path, tags=None, afterwards=None):
"""
Adds a file to the notmuch index.
:param path: path to the file
:type path: str
:param tags: tagstrings to add
:type tags: list of str
:param afterwards: callback to trigger after adding
:type a... | [
"def",
"add_message",
"(",
"self",
",",
"path",
",",
"tags",
"=",
"None",
",",
"afterwards",
"=",
"None",
")",
":",
"tags",
"=",
"tags",
"or",
"[",
"]",
"if",
"self",
".",
"ro",
":",
"raise",
"DatabaseROError",
"(",
")",
"if",
"not",
"is_subdir_of",
... | Adds a file to the notmuch index.
:param path: path to the file
:type path: str
:param tags: tagstrings to add
:type tags: list of str
:param afterwards: callback to trigger after adding
:type afterwards: callable or None | [
"Adds",
"a",
"file",
"to",
"the",
"notmuch",
"index",
"."
] | python | train |
The-Politico/politico-civic-entity | entity/models/person.py | https://github.com/The-Politico/politico-civic-entity/blob/318cd14c407e8e650374f784e692923798eacd81/entity/models/person.py#L62-L86 | def save(self, *args, **kwargs):
"""
**uid**: :code:`person:{slug}`
"""
if not self.full_name:
self.full_name = '{0}{1}{2}'.format(
self.first_name,
'{}'.format(
' ' + self.middle_name + ' ' if self.middle_name else ' ',
... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"full_name",
":",
"self",
".",
"full_name",
"=",
"'{0}{1}{2}'",
".",
"format",
"(",
"self",
".",
"first_name",
",",
"'{}'",
".",
"format",
"(... | **uid**: :code:`person:{slug}` | [
"**",
"uid",
"**",
":",
":",
"code",
":",
"person",
":",
"{",
"slug",
"}"
] | python | train |
lablup/backend.ai-client-py | src/ai/backend/client/cli/config.py | https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/config.py#L9-L23 | def config():
'''
Shows the current configuration.
'''
config = get_config()
print('Client version: {0}'.format(click.style(__version__, bold=True)))
print('API endpoint: {0}'.format(click.style(str(config.endpoint), bold=True)))
print('API version: {0}'.format(click.style(config.version, bo... | [
"def",
"config",
"(",
")",
":",
"config",
"=",
"get_config",
"(",
")",
"print",
"(",
"'Client version: {0}'",
".",
"format",
"(",
"click",
".",
"style",
"(",
"__version__",
",",
"bold",
"=",
"True",
")",
")",
")",
"print",
"(",
"'API endpoint: {0}'",
"."... | Shows the current configuration. | [
"Shows",
"the",
"current",
"configuration",
"."
] | python | train |
karel-brinda/rnftools | rnftools/rnfformat/FqCreator.py | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/rnfformat/FqCreator.py#L49-L87 | def flush_read_tuple(self):
"""Flush the internal buffer of reads.
"""
if not self.is_empty():
suffix_comment_buffer = []
if self._info_simulator is not None:
suffix_comment_buffer.append(self._info_simulator)
if self._info_reads_in_tuple:
... | [
"def",
"flush_read_tuple",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_empty",
"(",
")",
":",
"suffix_comment_buffer",
"=",
"[",
"]",
"if",
"self",
".",
"_info_simulator",
"is",
"not",
"None",
":",
"suffix_comment_buffer",
".",
"append",
"(",
"sel... | Flush the internal buffer of reads. | [
"Flush",
"the",
"internal",
"buffer",
"of",
"reads",
"."
] | python | train |
Kane610/deconz | pydeconz/websocket.py | https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/websocket.py#L88-L92 | def retry(self):
"""Retry to connect to deCONZ."""
self.state = STATE_STARTING
self.loop.call_later(RETRY_TIMER, self.start)
_LOGGER.debug('Reconnecting to deCONZ in %i.', RETRY_TIMER) | [
"def",
"retry",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"STATE_STARTING",
"self",
".",
"loop",
".",
"call_later",
"(",
"RETRY_TIMER",
",",
"self",
".",
"start",
")",
"_LOGGER",
".",
"debug",
"(",
"'Reconnecting to deCONZ in %i.'",
",",
"RETRY_TIMER... | Retry to connect to deCONZ. | [
"Retry",
"to",
"connect",
"to",
"deCONZ",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/sdist.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/sdist.py#L62-L83 | def externals_finder(dirname, filename):
"""Find any 'svn:externals' directories"""
found = False
f = open(filename,'rt')
for line in iter(f.readline, ''): # can't use direct iter!
parts = line.split()
if len(parts)==2:
kind,length = parts
data = f.read(int(len... | [
"def",
"externals_finder",
"(",
"dirname",
",",
"filename",
")",
":",
"found",
"=",
"False",
"f",
"=",
"open",
"(",
"filename",
",",
"'rt'",
")",
"for",
"line",
"in",
"iter",
"(",
"f",
".",
"readline",
",",
"''",
")",
":",
"# can't use direct iter!",
"... | Find any 'svn:externals' directories | [
"Find",
"any",
"svn",
":",
"externals",
"directories"
] | python | test |
pyamg/pyamg | pyamg/multilevel.py | https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/multilevel.py#L275-L316 | def aspreconditioner(self, cycle='V'):
"""Create a preconditioner using this multigrid cycle.
Parameters
----------
cycle : {'V','W','F','AMLI'}
Type of multigrid cycle to perform in each iteration.
Returns
-------
precond : LinearOperator
... | [
"def",
"aspreconditioner",
"(",
"self",
",",
"cycle",
"=",
"'V'",
")",
":",
"from",
"scipy",
".",
"sparse",
".",
"linalg",
"import",
"LinearOperator",
"shape",
"=",
"self",
".",
"levels",
"[",
"0",
"]",
".",
"A",
".",
"shape",
"dtype",
"=",
"self",
"... | Create a preconditioner using this multigrid cycle.
Parameters
----------
cycle : {'V','W','F','AMLI'}
Type of multigrid cycle to perform in each iteration.
Returns
-------
precond : LinearOperator
Preconditioner suitable for the iterative solver... | [
"Create",
"a",
"preconditioner",
"using",
"this",
"multigrid",
"cycle",
"."
] | python | train |
saltstack/salt | salt/runners/f5.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L330-L345 | def check_member_pool(lb, member, pool_name):
'''
Check a pool member exists in a specific pool
CLI Examples:
.. code-block:: bash
salt-run f5.check_member_pool load_balancer 10.0.0.1 my_pool
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__... | [
"def",
"check_member_pool",
"(",
"lb",
",",
"member",
",",
"pool_name",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"list",
"(",
"__opts__",
"[",
... | Check a pool member exists in a specific pool
CLI Examples:
.. code-block:: bash
salt-run f5.check_member_pool load_balancer 10.0.0.1 my_pool | [
"Check",
"a",
"pool",
"member",
"exists",
"in",
"a",
"specific",
"pool"
] | python | train |
tsnaomi/finnsyll | finnsyll/prev/v06.py | https://github.com/tsnaomi/finnsyll/blob/6a42740311688c946a636a3e2304866c7aa041b3/finnsyll/prev/v06.py#L148-L173 | def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
word = split(word) # detect any non-delimited compounds
compound = True if re.search(r'-| |\.', word) else False
syllabify = _syllabify_compound if compound else _syllabify
syll, rules = syllabify(word)
yield syll... | [
"def",
"syllabify",
"(",
"word",
")",
":",
"word",
"=",
"split",
"(",
"word",
")",
"# detect any non-delimited compounds",
"compound",
"=",
"True",
"if",
"re",
".",
"search",
"(",
"r'-| |\\.'",
",",
"word",
")",
"else",
"False",
"syllabify",
"=",
"_syllabify... | Syllabify the given word, whether simplex or complex. | [
"Syllabify",
"the",
"given",
"word",
"whether",
"simplex",
"or",
"complex",
"."
] | python | train |
intel-analytics/BigDL | pyspark/bigdl/optim/optimizer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/optim/optimizer.py#L914-L923 | def set_traindata(self, training_rdd, batch_size):
"""
Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return:
"""
callBigDlFunc(self.bigdl_type, "setTrainData", self.value,
... | [
"def",
"set_traindata",
"(",
"self",
",",
"training_rdd",
",",
"batch_size",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"setTrainData\"",
",",
"self",
".",
"value",
",",
"training_rdd",
",",
"batch_size",
")"
] | Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return: | [
"Set",
"new",
"training",
"dataset",
"for",
"optimizer",
"reuse"
] | python | test |
hayalasalah/adhan.py | adhan/calculations.py | https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/calculations.py#L81-L102 | def sun_declination(day):
"""Compute the declination angle of the sun for the given date.
Uses the Spencer Formula
(found at http://www.illustratingshadows.com/www-formulae-collection.pdf)
:param day: The datetime.date to compute the declination angle for
:returns: The angle, in degrees, of the an... | [
"def",
"sun_declination",
"(",
"day",
")",
":",
"day_of_year",
"=",
"day",
".",
"toordinal",
"(",
")",
"-",
"date",
"(",
"day",
".",
"year",
",",
"1",
",",
"1",
")",
".",
"toordinal",
"(",
")",
"day_angle",
"=",
"2",
"*",
"pi",
"*",
"day_of_year",
... | Compute the declination angle of the sun for the given date.
Uses the Spencer Formula
(found at http://www.illustratingshadows.com/www-formulae-collection.pdf)
:param day: The datetime.date to compute the declination angle for
:returns: The angle, in degrees, of the angle of declination | [
"Compute",
"the",
"declination",
"angle",
"of",
"the",
"sun",
"for",
"the",
"given",
"date",
"."
] | python | train |
mohamedattahri/PyXMLi | pyxmli/__init__.py | https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/__init__.py#L256-L264 | def to_string(self, indent="", newl="", addindent=""):
'''
Returns a string representation of the XMLi element.
@return: str
'''
buf = StringIO()
self.to_xml().writexml(buf, indent=indent, addindent=addindent,
newl=newl)
return buf.g... | [
"def",
"to_string",
"(",
"self",
",",
"indent",
"=",
"\"\"",
",",
"newl",
"=",
"\"\"",
",",
"addindent",
"=",
"\"\"",
")",
":",
"buf",
"=",
"StringIO",
"(",
")",
"self",
".",
"to_xml",
"(",
")",
".",
"writexml",
"(",
"buf",
",",
"indent",
"=",
"i... | Returns a string representation of the XMLi element.
@return: str | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"XMLi",
"element",
"."
] | python | train |
sammchardy/python-kucoin | kucoin/client.py | https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L1484-L1521 | def get_fiat_prices(self, base=None, symbol=None):
"""Get fiat price for currency
https://docs.kucoin.com/#get-fiat-price
:param base: (optional) Fiat,eg.USD,EUR, default is USD.
:type base: string
:param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please... | [
"def",
"get_fiat_prices",
"(",
"self",
",",
"base",
"=",
"None",
",",
"symbol",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"base",
"is",
"not",
"None",
":",
"data",
"[",
"'base'",
"]",
"=",
"base",
"if",
"symbol",
"is",
"not",
"None",
":... | Get fiat price for currency
https://docs.kucoin.com/#get-fiat-price
:param base: (optional) Fiat,eg.USD,EUR, default is USD.
:type base: string
:param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with
comma one by one. d... | [
"Get",
"fiat",
"price",
"for",
"currency"
] | python | train |
boriel/zxbasic | arch/zx48k/backend/__pload.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__pload.py#L22-L49 | def _paddr(ins):
""" Returns code sequence which points to
local variable or parameter (HL)
"""
output = []
oper = ins.quad[1]
indirect = (oper[0] == '*')
if indirect:
oper = oper[1:]
I = int(oper)
if I >= 0:
I += 4 # Return Address + "push IX"
output.append('... | [
"def",
"_paddr",
"(",
"ins",
")",
":",
"output",
"=",
"[",
"]",
"oper",
"=",
"ins",
".",
"quad",
"[",
"1",
"]",
"indirect",
"=",
"(",
"oper",
"[",
"0",
"]",
"==",
"'*'",
")",
"if",
"indirect",
":",
"oper",
"=",
"oper",
"[",
"1",
":",
"]",
"... | Returns code sequence which points to
local variable or parameter (HL) | [
"Returns",
"code",
"sequence",
"which",
"points",
"to",
"local",
"variable",
"or",
"parameter",
"(",
"HL",
")"
] | python | train |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1592-L1622 | def pretty_print(self, objlist):
'''Pretty print the result of s3walk. Here we calculate the maximum width
of each column and align them.
'''
def normalize_time(timestamp):
'''Normalize the timestamp format for pretty print.'''
if timestamp is None:
return ' ' * 16
return ... | [
"def",
"pretty_print",
"(",
"self",
",",
"objlist",
")",
":",
"def",
"normalize_time",
"(",
"timestamp",
")",
":",
"'''Normalize the timestamp format for pretty print.'''",
"if",
"timestamp",
"is",
"None",
":",
"return",
"' '",
"*",
"16",
"return",
"TIMESTAMP_FORMAT... | Pretty print the result of s3walk. Here we calculate the maximum width
of each column and align them. | [
"Pretty",
"print",
"the",
"result",
"of",
"s3walk",
".",
"Here",
"we",
"calculate",
"the",
"maximum",
"width",
"of",
"each",
"column",
"and",
"align",
"them",
"."
] | python | test |
inasafe/inasafe | safe/gui/tools/wizard/step_kw33_multi_classifications.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw33_multi_classifications.py#L391-L469 | def show_current_state(self):
"""Setup the UI for QTextEdit to show the current state."""
right_panel_heading = QLabel(tr('Status'))
right_panel_heading.setFont(big_font)
right_panel_heading.setSizePolicy(
QSizePolicy.Maximum, QSizePolicy.Maximum)
self.right_layout.ad... | [
"def",
"show_current_state",
"(",
"self",
")",
":",
"right_panel_heading",
"=",
"QLabel",
"(",
"tr",
"(",
"'Status'",
")",
")",
"right_panel_heading",
".",
"setFont",
"(",
"big_font",
")",
"right_panel_heading",
".",
"setSizePolicy",
"(",
"QSizePolicy",
".",
"Ma... | Setup the UI for QTextEdit to show the current state. | [
"Setup",
"the",
"UI",
"for",
"QTextEdit",
"to",
"show",
"the",
"current",
"state",
"."
] | python | train |
CivicSpleen/ambry | ambry/orm/file.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/file.py#L90-L107 | def unpacked_contents(self):
"""
:return:
"""
from nbformat import read
import msgpack
if self.mime_type == 'text/plain':
return self.contents.decode('utf-8')
elif self.mime_type == 'application/msgpack':
# FIXME: Note: I'm not sure that... | [
"def",
"unpacked_contents",
"(",
"self",
")",
":",
"from",
"nbformat",
"import",
"read",
"import",
"msgpack",
"if",
"self",
".",
"mime_type",
"==",
"'text/plain'",
":",
"return",
"self",
".",
"contents",
".",
"decode",
"(",
"'utf-8'",
")",
"elif",
"self",
... | :return: | [
":",
"return",
":"
] | python | train |
goldhand/django-nupages | nupages/views.py | https://github.com/goldhand/django-nupages/blob/4e54fae7e057f9530c22dc30c03812fd660cb7f4/nupages/views.py#L87-L96 | def get_template_names(self):
'''
Looks for a custom_template value and prepends it to template_names
if it exists otherwise 'nupages/page_detail.html' is used
'''
template_names = super(PageDetail, self).get_template_names()
if self.get_object().custom_template:
... | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"template_names",
"=",
"super",
"(",
"PageDetail",
",",
"self",
")",
".",
"get_template_names",
"(",
")",
"if",
"self",
".",
"get_object",
"(",
")",
".",
"custom_template",
":",
"# there is a custom template, i... | Looks for a custom_template value and prepends it to template_names
if it exists otherwise 'nupages/page_detail.html' is used | [
"Looks",
"for",
"a",
"custom_template",
"value",
"and",
"prepends",
"it",
"to",
"template_names",
"if",
"it",
"exists",
"otherwise",
"nupages",
"/",
"page_detail",
".",
"html",
"is",
"used"
] | python | train |
rbaier/python-urltools | urltools/urltools.py | https://github.com/rbaier/python-urltools/blob/76bf599aeb4cb463df8e38367aa40a7d8ec7d9a1/urltools/urltools.py#L134-L147 | def encode(url):
"""Encode URL."""
parts = extract(url)
return construct(URL(parts.scheme,
parts.username,
parts.password,
_idna_encode(parts.subdomain),
_idna_encode(parts.domain),
_... | [
"def",
"encode",
"(",
"url",
")",
":",
"parts",
"=",
"extract",
"(",
"url",
")",
"return",
"construct",
"(",
"URL",
"(",
"parts",
".",
"scheme",
",",
"parts",
".",
"username",
",",
"parts",
".",
"password",
",",
"_idna_encode",
"(",
"parts",
".",
"su... | Encode URL. | [
"Encode",
"URL",
"."
] | python | train |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L75-L96 | def read_file(self, filepath=None, filename=None):
"""
Tries to read JSON content from filename and convert it to a dict.
:param filepath: Path where the file is
:param filename: File name
:return: Dictionary read from the file
:raises EnvironmentError, ValueError
... | [
"def",
"read_file",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"name",
"=",
"filename",
"if",
"filename",
"else",
"self",
".",
"filename",
"path",
"=",
"filepath",
"if",
"filepath",
"else",
"self",
".",
"filepath",... | Tries to read JSON content from filename and convert it to a dict.
:param filepath: Path where the file is
:param filename: File name
:return: Dictionary read from the file
:raises EnvironmentError, ValueError | [
"Tries",
"to",
"read",
"JSON",
"content",
"from",
"filename",
"and",
"convert",
"it",
"to",
"a",
"dict",
"."
] | python | train |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L202-L261 | def formula_to_dictionary(formula='', thickness=np.NaN, density=np.NaN, database='ENDF_VII'):
"""create dictionary based on formula given
Parameters:
===========
formula: string
ex: 'AgCo2'
ex: 'Ag'
thickness: float (in mm) default is np.NaN
density: float (in g/cm3) default i... | [
"def",
"formula_to_dictionary",
"(",
"formula",
"=",
"''",
",",
"thickness",
"=",
"np",
".",
"NaN",
",",
"density",
"=",
"np",
".",
"NaN",
",",
"database",
"=",
"'ENDF_VII'",
")",
":",
"if",
"'.'",
"in",
"formula",
":",
"raise",
"ValueError",
"(",
"\"f... | create dictionary based on formula given
Parameters:
===========
formula: string
ex: 'AgCo2'
ex: 'Ag'
thickness: float (in mm) default is np.NaN
density: float (in g/cm3) default is np.NaN
database: string (default is ENDV_VIII). Database where to look for elements
Ra... | [
"create",
"dictionary",
"based",
"on",
"formula",
"given",
"Parameters",
":",
"===========",
"formula",
":",
"string",
"ex",
":",
"AgCo2",
"ex",
":",
"Ag",
"thickness",
":",
"float",
"(",
"in",
"mm",
")",
"default",
"is",
"np",
".",
"NaN",
"density",
":"... | python | train |
objectrocket/python-client | objectrocket/acls.py | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L78-L90 | def get(self, instance, acl):
"""Get an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance from which to fetch the ACL.
:param str acl: The ID of the ACL to fetch.
:returns: An :py:class:`Acl` object, or None if ACL does not exist.
... | [
"def",
"get",
"(",
"self",
",",
"instance",
",",
"acl",
")",
":",
"base_url",
"=",
"self",
".",
"_url",
".",
"format",
"(",
"instance",
"=",
"instance",
")",
"url",
"=",
"'{base}{aclid}/'",
".",
"format",
"(",
"base",
"=",
"base_url",
",",
"aclid",
"... | Get an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance from which to fetch the ACL.
:param str acl: The ID of the ACL to fetch.
:returns: An :py:class:`Acl` object, or None if ACL does not exist.
:rtype: :py:class:`Acl` | [
"Get",
"an",
"ACL",
"by",
"ID",
"belonging",
"to",
"the",
"instance",
"specified",
"by",
"name",
"."
] | python | train |
koalalorenzo/python-digitalocean | digitalocean/baseapi.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/baseapi.py#L151-L165 | def get_timeout(self):
"""
Checks if any timeout for the requests to DigitalOcean is required.
To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment
variable.
"""
timeout_str = os.environ.get(REQUEST_TIMEOUT_ENV_VAR)
if timeout_str:
... | [
"def",
"get_timeout",
"(",
"self",
")",
":",
"timeout_str",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"REQUEST_TIMEOUT_ENV_VAR",
")",
"if",
"timeout_str",
":",
"try",
":",
"return",
"float",
"(",
"timeout_str",
")",
"except",
":",
"self",
".",
"_log",
... | Checks if any timeout for the requests to DigitalOcean is required.
To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment
variable. | [
"Checks",
"if",
"any",
"timeout",
"for",
"the",
"requests",
"to",
"DigitalOcean",
"is",
"required",
".",
"To",
"set",
"a",
"timeout",
"use",
"the",
"REQUEST_TIMEOUT_ENV_VAR",
"environment",
"variable",
"."
] | python | valid |
lipoja/URLExtract | urlextract/urlextract_core.py | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L557-L568 | def find_urls(self, text, only_unique=False):
"""
Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list
"""
urls = self.gen_urls(text... | [
"def",
"find_urls",
"(",
"self",
",",
"text",
",",
"only_unique",
"=",
"False",
")",
":",
"urls",
"=",
"self",
".",
"gen_urls",
"(",
"text",
")",
"urls",
"=",
"OrderedDict",
".",
"fromkeys",
"(",
"urls",
")",
"if",
"only_unique",
"else",
"urls",
"retur... | Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list | [
"Find",
"all",
"URLs",
"in",
"given",
"text",
"."
] | python | train |
Robpol86/libnl | example_scan_access_points.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/example_scan_access_points.py#L289-L319 | def print_table(data):
"""Print the table of detected SSIDs and their data to screen.
Positional arguments:
data -- list of dictionaries.
"""
table = AsciiTable([COLUMNS])
table.justify_columns[2] = 'right'
table.justify_columns[3] = 'right'
table.justify_columns[4] = 'right'
table_... | [
"def",
"print_table",
"(",
"data",
")",
":",
"table",
"=",
"AsciiTable",
"(",
"[",
"COLUMNS",
"]",
")",
"table",
".",
"justify_columns",
"[",
"2",
"]",
"=",
"'right'",
"table",
".",
"justify_columns",
"[",
"3",
"]",
"=",
"'right'",
"table",
".",
"justi... | Print the table of detected SSIDs and their data to screen.
Positional arguments:
data -- list of dictionaries. | [
"Print",
"the",
"table",
"of",
"detected",
"SSIDs",
"and",
"their",
"data",
"to",
"screen",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/list_types.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L277-L281 | def process_result_value(self, value: Optional[str],
dialect: Dialect) -> List[int]:
"""Convert things on the way from the database to Python."""
retval = self._dbstr_to_intlist(value)
return retval | [
"def",
"process_result_value",
"(",
"self",
",",
"value",
":",
"Optional",
"[",
"str",
"]",
",",
"dialect",
":",
"Dialect",
")",
"->",
"List",
"[",
"int",
"]",
":",
"retval",
"=",
"self",
".",
"_dbstr_to_intlist",
"(",
"value",
")",
"return",
"retval"
] | Convert things on the way from the database to Python. | [
"Convert",
"things",
"on",
"the",
"way",
"from",
"the",
"database",
"to",
"Python",
"."
] | python | train |
shaypal5/utilp | utilp/classes/classes.py | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/classes/classes.py#L273-L278 | def tqdm(self, iterable, **kwargs):
"""Wraps the given iterable with a tqdm progress bar if this logger is
set to verbose. Otherwise, returns the iterable unchanged."""
if 'disable' in kwargs:
kwargs.pop('disable')
return tqdm(iterable, disable=not self.verbose, **kwargs) | [
"def",
"tqdm",
"(",
"self",
",",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'disable'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'disable'",
")",
"return",
"tqdm",
"(",
"iterable",
",",
"disable",
"=",
"not",
"self",
".",
"verbose"... | Wraps the given iterable with a tqdm progress bar if this logger is
set to verbose. Otherwise, returns the iterable unchanged. | [
"Wraps",
"the",
"given",
"iterable",
"with",
"a",
"tqdm",
"progress",
"bar",
"if",
"this",
"logger",
"is",
"set",
"to",
"verbose",
".",
"Otherwise",
"returns",
"the",
"iterable",
"unchanged",
"."
] | python | train |
robotpy/pyfrc | lib/pyfrc/sim/field/elements.py | https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/sim/field/elements.py#L36-L53 | def move(self, v):
"""v is a tuple of x/y coordinates to move object"""
# rotate movement vector according to the angle of the object
vx, vy = v
vx, vy = (
vx * math.cos(self.angle) - vy * math.sin(self.angle),
vx * math.sin(self.angle) + vy * math.cos(self.angle... | [
"def",
"move",
"(",
"self",
",",
"v",
")",
":",
"# rotate movement vector according to the angle of the object",
"vx",
",",
"vy",
"=",
"v",
"vx",
",",
"vy",
"=",
"(",
"vx",
"*",
"math",
".",
"cos",
"(",
"self",
".",
"angle",
")",
"-",
"vy",
"*",
"math"... | v is a tuple of x/y coordinates to move object | [
"v",
"is",
"a",
"tuple",
"of",
"x",
"/",
"y",
"coordinates",
"to",
"move",
"object"
] | python | train |
OCR-D/core | ocrd/ocrd/cli/workspace.py | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L267-L272 | def workspace_backup_add(ctx):
"""
Create a new backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.add() | [
"def",
"workspace_backup_add",
"(",
"ctx",
")",
":",
"backup_manager",
"=",
"WorkspaceBackupManager",
"(",
"Workspace",
"(",
"ctx",
".",
"resolver",
",",
"directory",
"=",
"ctx",
".",
"directory",
",",
"mets_basename",
"=",
"ctx",
".",
"mets_basename",
",",
"a... | Create a new backup | [
"Create",
"a",
"new",
"backup"
] | python | train |
mitsei/dlkit | dlkit/records/assessment/edx/item_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/edx/item_records.py#L313-L324 | def get_solution(self, parameters=None):
"""stub"""
if not self.has_solution():
raise IllegalState()
try:
if not self.get_text('python_script'):
return self.get_text('solution').text
if not parameters:
parameters = self.get_para... | [
"def",
"get_solution",
"(",
"self",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"has_solution",
"(",
")",
":",
"raise",
"IllegalState",
"(",
")",
"try",
":",
"if",
"not",
"self",
".",
"get_text",
"(",
"'python_script'",
")",
":"... | stub | [
"stub"
] | python | train |
inasafe/inasafe | safe/messaging/item/horizontal_rule.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/horizontal_rule.py#L42-L55 | def to_html(self, **kwargs):
"""Render as html
:returns: the html representation (<hr>)
:rtype: str
We pass the kwargs on to the base class so an exception is raised
if invalid keywords were passed. See:
http://stackoverflow.com/questions/13124961/
how-to-pass-... | [
"def",
"to_html",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"HorizontalRule",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"*",
"kwargs",
")",
"return",
"'<hr%s/>\\n'",
"%",
"self",
".",
"html_attributes",
"(",
")"
] | Render as html
:returns: the html representation (<hr>)
:rtype: str
We pass the kwargs on to the base class so an exception is raised
if invalid keywords were passed. See:
http://stackoverflow.com/questions/13124961/
how-to-pass-arguments-efficiently-kwargs-in-python | [
"Render",
"as",
"html"
] | python | train |
keras-rl/keras-rl | rl/policy.py | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L314-L346 | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
# We can't use BGE during testing, since we don't have access to the
#... | [
"def",
"select_action",
"(",
"self",
",",
"q_values",
")",
":",
"# We can't use BGE during testing, since we don't have access to the",
"# action_counts at the end of training.",
"assert",
"self",
".",
"agent",
".",
"training",
",",
"\"BoltzmannGumbelQPolicy should only be used for... | Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action | [
"Return",
"the",
"selected",
"action"
] | python | train |
awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L45-L63 | def get_command(self, ctx, cmd_name):
"""
gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSu... | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"if",
"cmd_name",
"not",
"in",
"self",
".",
"all_cmds",
":",
"return",
"None",
"return",
"EventTypeSubCommand",
"(",
"self",
".",
"events_lib",
",",
"cmd_name",
",",
"self",
".",
"... | gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, No... | [
"gets",
"the",
"subcommands",
"under",
"the",
"service",
"name"
] | python | train |
kubernetes-client/python | kubernetes/client/apis/node_v1beta1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/node_v1beta1_api.py#L823-L846 | def replace_runtime_class(self, name, body, **kwargs):
"""
replace the specified RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_runtime_class(name, body, async_req=Tru... | [
"def",
"replace_runtime_class",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"repla... | replace the specified RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_runtime_class(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool
... | [
"replace",
"the",
"specified",
"RuntimeClass",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api... | python | train |
Yelp/kafka-utils | kafka_utils/kafka_corruption_check/main.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_corruption_check/main.py#L321-L347 | def check_files_on_host(java_home, host, files, batch_size):
"""Check the files on the host. Files are grouped together in groups
of batch_size files. The dump class will be executed on each batch,
sequentially.
:param java_home: the JAVA_HOME of the broker
:type java_home: str
:param host: the... | [
"def",
"check_files_on_host",
"(",
"java_home",
",",
"host",
",",
"files",
",",
"batch_size",
")",
":",
"with",
"closing",
"(",
"ssh_client",
"(",
"host",
")",
")",
"as",
"ssh",
":",
"for",
"i",
",",
"batch",
"in",
"enumerate",
"(",
"chunks",
"(",
"fil... | Check the files on the host. Files are grouped together in groups
of batch_size files. The dump class will be executed on each batch,
sequentially.
:param java_home: the JAVA_HOME of the broker
:type java_home: str
:param host: the host where the tool will be executed
:type host: str
:param... | [
"Check",
"the",
"files",
"on",
"the",
"host",
".",
"Files",
"are",
"grouped",
"together",
"in",
"groups",
"of",
"batch_size",
"files",
".",
"The",
"dump",
"class",
"will",
"be",
"executed",
"on",
"each",
"batch",
"sequentially",
"."
] | python | train |
Robin8Put/pmes | ams/views.py | https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/ams/views.py#L592-L718 | async def post(self):
"""
Funds from account to given address.
1. Verify signature
2. Freeze senders amount.
3. Request to withdraw server.
4. Call balances sub_frozen method.
Accepts:
- message [dict]:
- coinid [string]
- amount [integer]
- address [string]
- timestamp [float]
- r... | [
"async",
"def",
"post",
"(",
"self",
")",
":",
"# Sign-verifying functional",
"if",
"settings",
".",
"SIGNATURE_VERIFICATION",
":",
"super",
"(",
")",
".",
"verify",
"(",
")",
"logging",
".",
"debug",
"(",
"\"\\n\\n[+] -- Withdraw debugging\"",
")",
"# Get data fr... | Funds from account to given address.
1. Verify signature
2. Freeze senders amount.
3. Request to withdraw server.
4. Call balances sub_frozen method.
Accepts:
- message [dict]:
- coinid [string]
- amount [integer]
- address [string]
- timestamp [float]
- recvWindow [float]
- public_... | [
"Funds",
"from",
"account",
"to",
"given",
"address",
".",
"1",
".",
"Verify",
"signature",
"2",
".",
"Freeze",
"senders",
"amount",
".",
"3",
".",
"Request",
"to",
"withdraw",
"server",
".",
"4",
".",
"Call",
"balances",
"sub_frozen",
"method",
"."
] | python | train |
jazzband/django-ddp | dddp/alea.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/alea.py#L110-L134 | def seed(self, values):
"""Seed internal state from supplied values."""
if not values:
# Meteor uses epoch seconds as the seed if no args supplied, we use
# a much more secure seed by default to avoid hash collisions.
seed_ids = [int, str, random, self, values, self._... | [
"def",
"seed",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"values",
":",
"# Meteor uses epoch seconds as the seed if no args supplied, we use",
"# a much more secure seed by default to avoid hash collisions.",
"seed_ids",
"=",
"[",
"int",
",",
"str",
",",
"random",
... | Seed internal state from supplied values. | [
"Seed",
"internal",
"state",
"from",
"supplied",
"values",
"."
] | python | test |
saltstack/salt | salt/modules/portage_config.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L176-L200 | def _unify_keywords():
'''
Merge /etc/portage/package.keywords and
/etc/portage/package.accept_keywords.
'''
old_path = BASE_PATH.format('keywords')
if os.path.exists(old_path):
if os.path.isdir(old_path):
for triplet in salt.utils.path.os_walk(old_path):
for ... | [
"def",
"_unify_keywords",
"(",
")",
":",
"old_path",
"=",
"BASE_PATH",
".",
"format",
"(",
"'keywords'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"old_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"old_path",
")",
":",
"for",
... | Merge /etc/portage/package.keywords and
/etc/portage/package.accept_keywords. | [
"Merge",
"/",
"etc",
"/",
"portage",
"/",
"package",
".",
"keywords",
"and",
"/",
"etc",
"/",
"portage",
"/",
"package",
".",
"accept_keywords",
"."
] | python | train |
saltstack/salt | salt/modules/syslog_ng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L975-L1009 | def stop(name=None):
'''
Kills syslog-ng. This function is intended to be used from the state module.
Users shouldn't use this function, if the service module is available on
their system. If :mod:`syslog_ng.set_config_file
<salt.modules.syslog_ng.set_binary_path>` is called before, this function
... | [
"def",
"stop",
"(",
"name",
"=",
"None",
")",
":",
"pids",
"=",
"__salt__",
"[",
"'ps.pgrep'",
"]",
"(",
"pattern",
"=",
"'syslog-ng'",
")",
"if",
"not",
"pids",
":",
"return",
"_format_state_result",
"(",
"name",
",",
"result",
"=",
"False",
",",
"com... | Kills syslog-ng. This function is intended to be used from the state module.
Users shouldn't use this function, if the service module is available on
their system. If :mod:`syslog_ng.set_config_file
<salt.modules.syslog_ng.set_binary_path>` is called before, this function
will use the set binary path.... | [
"Kills",
"syslog",
"-",
"ng",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"the",
"state",
"module",
"."
] | python | train |
kvh/ramp | ramp/estimators/base.py | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/estimators/base.py#L44-L48 | def predict_maxprob(self, x, **kwargs):
"""
Most likely value. Generally equivalent to predict.
"""
return self.base_estimator_.predict(x.values, **kwargs) | [
"def",
"predict_maxprob",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"base_estimator_",
".",
"predict",
"(",
"x",
".",
"values",
",",
"*",
"*",
"kwargs",
")"
] | Most likely value. Generally equivalent to predict. | [
"Most",
"likely",
"value",
".",
"Generally",
"equivalent",
"to",
"predict",
"."
] | python | train |
cgoldberg/sauceclient | sauceclient.py | https://github.com/cgoldberg/sauceclient/blob/aa27b7da8eb2e483adc2754c694fe5082e1fa8f7/sauceclient.py#L135-L140 | def get_subaccount_info(self):
"""Get information about a sub account."""
method = 'GET'
endpoint = '/rest/v1/users/{}/subaccounts'.format(
self.client.sauce_username)
return self.client.request(method, endpoint) | [
"def",
"get_subaccount_info",
"(",
"self",
")",
":",
"method",
"=",
"'GET'",
"endpoint",
"=",
"'/rest/v1/users/{}/subaccounts'",
".",
"format",
"(",
"self",
".",
"client",
".",
"sauce_username",
")",
"return",
"self",
".",
"client",
".",
"request",
"(",
"metho... | Get information about a sub account. | [
"Get",
"information",
"about",
"a",
"sub",
"account",
"."
] | python | train |
mcs07/PubChemPy | pubchempy.py | https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1241-L1250 | def compounds_to_frame(compounds, properties=None):
"""Construct a pandas :class:`~pandas.DataFrame` from a list of :class:`~pubchempy.Compound` objects.
Optionally specify a list of the desired :class:`~pubchempy.Compound` properties.
"""
import pandas as pd
if isinstance(compounds, Compound):
... | [
"def",
"compounds_to_frame",
"(",
"compounds",
",",
"properties",
"=",
"None",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"isinstance",
"(",
"compounds",
",",
"Compound",
")",
":",
"compounds",
"=",
"[",
"compounds",
"]",
"properties",
"=",
"set",
"("... | Construct a pandas :class:`~pandas.DataFrame` from a list of :class:`~pubchempy.Compound` objects.
Optionally specify a list of the desired :class:`~pubchempy.Compound` properties. | [
"Construct",
"a",
"pandas",
":",
"class",
":",
"~pandas",
".",
"DataFrame",
"from",
"a",
"list",
"of",
":",
"class",
":",
"~pubchempy",
".",
"Compound",
"objects",
"."
] | python | train |
pavelsof/ipalint | ipalint/report.py | https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/report.py#L69-L81 | def _get_report(self, with_line_nums=True):
"""
Returns a report which includes each distinct error only once, together
with a list of the input lines where the error occurs. The latter will
be omitted if flag is set to False.
Helper for the get_report method.
"""
templ = '{} ← {}' if with_line_nums else... | [
"def",
"_get_report",
"(",
"self",
",",
"with_line_nums",
"=",
"True",
")",
":",
"templ",
"=",
"'{} ← {}' i",
" w",
"th_line_nums e",
"se '",
"}'",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"templ",
".",
"format",
"(",
"error",
".",
"string",
",",
"','",... | Returns a report which includes each distinct error only once, together
with a list of the input lines where the error occurs. The latter will
be omitted if flag is set to False.
Helper for the get_report method. | [
"Returns",
"a",
"report",
"which",
"includes",
"each",
"distinct",
"error",
"only",
"once",
"together",
"with",
"a",
"list",
"of",
"the",
"input",
"lines",
"where",
"the",
"error",
"occurs",
".",
"The",
"latter",
"will",
"be",
"omitted",
"if",
"flag",
"is"... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.