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 |
|---|---|---|---|---|---|---|---|---|
openpermissions/chub | chub/handlers.py | https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/handlers.py#L91-L101 | def parse_response(response):
"""
parse response and return a dictionary if the content type.
is json/application.
:param response: HTTPRequest
:return dictionary for json content type otherwise response body
"""
if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE):
... | [
"def",
"parse_response",
"(",
"response",
")",
":",
"if",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"JSON_TYPE",
")",
".",
"startswith",
"(",
"JSON_TYPE",
")",
":",
"return",
"ResponseObject",
"(",
"json",
".",
"loads",
"(",
"resp... | parse response and return a dictionary if the content type.
is json/application.
:param response: HTTPRequest
:return dictionary for json content type otherwise response body | [
"parse",
"response",
"and",
"return",
"a",
"dictionary",
"if",
"the",
"content",
"type",
".",
"is",
"json",
"/",
"application",
".",
":",
"param",
"response",
":",
"HTTPRequest",
":",
"return",
"dictionary",
"for",
"json",
"content",
"type",
"otherwise",
"re... | python | train |
adamcharnock/django-hordak | hordak/models/core.py | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L574-L600 | def create_transaction(self, to_account):
"""Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transacti... | [
"def",
"create_transaction",
"(",
"self",
",",
"to_account",
")",
":",
"from_account",
"=",
"self",
".",
"statement_import",
".",
"bank_account",
"transaction",
"=",
"Transaction",
".",
"objects",
".",
"create",
"(",
")",
"Leg",
".",
"objects",
".",
"create",
... | Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transaction is into / out of.
Returns:
Tr... | [
"Create",
"a",
"transaction",
"for",
"this",
"statement",
"amount",
"and",
"account",
"into",
"to_account"
] | python | train |
aaugustin/websockets | src/websockets/extensions/permessage_deflate.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L313-L323 | def get_request_params(self) -> List[ExtensionParameter]:
"""
Build request parameters.
"""
return _build_parameters(
self.server_no_context_takeover,
self.client_no_context_takeover,
self.server_max_window_bits,
self.client_max_window_bit... | [
"def",
"get_request_params",
"(",
"self",
")",
"->",
"List",
"[",
"ExtensionParameter",
"]",
":",
"return",
"_build_parameters",
"(",
"self",
".",
"server_no_context_takeover",
",",
"self",
".",
"client_no_context_takeover",
",",
"self",
".",
"server_max_window_bits",... | Build request parameters. | [
"Build",
"request",
"parameters",
"."
] | python | train |
user-cont/colin | colin/core/colin.py | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L135-L164 | def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
"""
Set personal logger for this library.
... | [
"def",
"_set_logging",
"(",
"logger_name",
"=",
"\"colin\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"handler_class",
"=",
"logging",
".",
"StreamHandler",
",",
"handler_kwargs",
"=",
"None",
",",
"format",
"=",
"'%(asctime)s.%(msecs).03d %(filename)-17s %(l... | Set personal logger for this library.
:param logger_name: str, name of the logger
:param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler
:param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)
:param handler_kwargs: dict, keyword arguments to h... | [
"Set",
"personal",
"logger",
"for",
"this",
"library",
"."
] | python | train |
reingart/pyafipws | wslum.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslum.py#L239-L251 | def AgregarUbicacionTambo(self, latitud, longitud, domicilio,
cod_localidad, cod_provincia, codigo_postal,
nombre_partido_depto, **kwargs):
"Agrego los datos del productor a la liq."
ubic_tambo = {'latitud': latitud,
'lon... | [
"def",
"AgregarUbicacionTambo",
"(",
"self",
",",
"latitud",
",",
"longitud",
",",
"domicilio",
",",
"cod_localidad",
",",
"cod_provincia",
",",
"codigo_postal",
",",
"nombre_partido_depto",
",",
"*",
"*",
"kwargs",
")",
":",
"ubic_tambo",
"=",
"{",
"'latitud'",... | Agrego los datos del productor a la liq. | [
"Agrego",
"los",
"datos",
"del",
"productor",
"a",
"la",
"liq",
"."
] | python | train |
openspending/babbage | babbage/validation.py | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L24-L39 | def check_valid_hierarchies(instance):
""" Additional check for the hierarchies model, to ensure that levels
given are pointing to actual dimensions """
hierarchies = instance.get('hierarchies', {}).values()
dimensions = set(instance.get('dimensions', {}).keys())
all_levels = set()
for hierarcy ... | [
"def",
"check_valid_hierarchies",
"(",
"instance",
")",
":",
"hierarchies",
"=",
"instance",
".",
"get",
"(",
"'hierarchies'",
",",
"{",
"}",
")",
".",
"values",
"(",
")",
"dimensions",
"=",
"set",
"(",
"instance",
".",
"get",
"(",
"'dimensions'",
",",
"... | Additional check for the hierarchies model, to ensure that levels
given are pointing to actual dimensions | [
"Additional",
"check",
"for",
"the",
"hierarchies",
"model",
"to",
"ensure",
"that",
"levels",
"given",
"are",
"pointing",
"to",
"actual",
"dimensions"
] | python | train |
openvax/varcode | varcode/variant_collection.py | https://github.com/openvax/varcode/blob/981633db45ca2b31f76c06894a7360ea5d70a9b8/varcode/variant_collection.py#L108-L122 | def effects(self, raise_on_error=True):
"""
Parameters
----------
raise_on_error : bool, optional
If exception is raised while determining effect of variant on a
transcript, should it be raised? This default is True, meaning
errors result in raised exc... | [
"def",
"effects",
"(",
"self",
",",
"raise_on_error",
"=",
"True",
")",
":",
"return",
"EffectCollection",
"(",
"[",
"effect",
"for",
"variant",
"in",
"self",
"for",
"effect",
"in",
"variant",
".",
"effects",
"(",
"raise_on_error",
"=",
"raise_on_error",
")"... | Parameters
----------
raise_on_error : bool, optional
If exception is raised while determining effect of variant on a
transcript, should it be raised? This default is True, meaning
errors result in raised exceptions, otherwise they are only logged. | [
"Parameters",
"----------",
"raise_on_error",
":",
"bool",
"optional",
"If",
"exception",
"is",
"raised",
"while",
"determining",
"effect",
"of",
"variant",
"on",
"a",
"transcript",
"should",
"it",
"be",
"raised?",
"This",
"default",
"is",
"True",
"meaning",
"er... | python | train |
juju/juju-bundlelib | jujubundlelib/pyutils.py | https://github.com/juju/juju-bundlelib/blob/c2efa614f53675ed9526027776448bfbb0454ca6/jujubundlelib/pyutils.py#L11-L23 | def string_class(cls):
"""Define __unicode__ and __str__ methods on the given class in Python 2.
The given class must define a __str__ method returning a unicode string,
otherwise a TypeError is raised.
Under Python 3, the class is returned as is.
"""
if not PY3:
if '__str__' not in cls... | [
"def",
"string_class",
"(",
"cls",
")",
":",
"if",
"not",
"PY3",
":",
"if",
"'__str__'",
"not",
"in",
"cls",
".",
"__dict__",
":",
"raise",
"TypeError",
"(",
"'the given class has no __str__ method'",
")",
"cls",
".",
"__unicode__",
",",
"cls",
".",
"__strin... | Define __unicode__ and __str__ methods on the given class in Python 2.
The given class must define a __str__ method returning a unicode string,
otherwise a TypeError is raised.
Under Python 3, the class is returned as is. | [
"Define",
"__unicode__",
"and",
"__str__",
"methods",
"on",
"the",
"given",
"class",
"in",
"Python",
"2",
"."
] | python | train |
SheffieldML/GPy | GPy/util/datasets.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/datasets.py#L96-L112 | def data_available(dataset_name=None):
"""Check if the data set is available on the local machine already."""
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
dr = data_resources[dataset_name]
zip_urls = (dr['files'], )
... | [
"def",
"data_available",
"(",
"dataset_name",
"=",
"None",
")",
":",
"try",
":",
"from",
"itertools",
"import",
"zip_longest",
"except",
"ImportError",
":",
"from",
"itertools",
"import",
"izip_longest",
"as",
"zip_longest",
"dr",
"=",
"data_resources",
"[",
"da... | Check if the data set is available on the local machine already. | [
"Check",
"if",
"the",
"data",
"set",
"is",
"available",
"on",
"the",
"local",
"machine",
"already",
"."
] | python | train |
OpenTreeOfLife/peyotl | peyotl/api/taxomachine.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/api/taxomachine.py#L205-L228 | def autocomplete(self, name, context_name=None, include_dubious=False):
"""Takes a name and optional context_name returns a list of matches.
Each match is a dict with:
'higher' boolean DEF???
'exact' boolean for exact match
'ottId' int
'name' name (or uniqnam... | [
"def",
"autocomplete",
"(",
"self",
",",
"name",
",",
"context_name",
"=",
"None",
",",
"include_dubious",
"=",
"False",
")",
":",
"if",
"context_name",
"and",
"context_name",
"not",
"in",
"self",
".",
"valid_contexts",
":",
"raise",
"ValueError",
"(",
"'\"{... | Takes a name and optional context_name returns a list of matches.
Each match is a dict with:
'higher' boolean DEF???
'exact' boolean for exact match
'ottId' int
'name' name (or uniqname???) for the taxon in OTT
'nodeId' int ID of not in the taxomachine db.... | [
"Takes",
"a",
"name",
"and",
"optional",
"context_name",
"returns",
"a",
"list",
"of",
"matches",
".",
"Each",
"match",
"is",
"a",
"dict",
"with",
":",
"higher",
"boolean",
"DEF???",
"exact",
"boolean",
"for",
"exact",
"match",
"ottId",
"int",
"name",
"nam... | python | train |
daler/metaseq | metaseq/results_table.py | https://github.com/daler/metaseq/blob/fa875d1f72317aa7ef95cb128b739956b16eef9f/metaseq/results_table.py#L131-L147 | def reindex_to(self, x, attribute="Name"):
"""
Returns a copy that only has rows corresponding to feature names in x.
Parameters
----------
x : str or pybedtools.BedTool
BED, GFF, GTF, or VCF where the "Name" field (that is, the value
returned by feature[... | [
"def",
"reindex_to",
"(",
"self",
",",
"x",
",",
"attribute",
"=",
"\"Name\"",
")",
":",
"names",
"=",
"[",
"i",
"[",
"attribute",
"]",
"for",
"i",
"in",
"x",
"]",
"new",
"=",
"self",
".",
"copy",
"(",
")",
"new",
".",
"data",
"=",
"new",
".",
... | Returns a copy that only has rows corresponding to feature names in x.
Parameters
----------
x : str or pybedtools.BedTool
BED, GFF, GTF, or VCF where the "Name" field (that is, the value
returned by feature['Name']) or any arbitrary attribute
attribute : str
... | [
"Returns",
"a",
"copy",
"that",
"only",
"has",
"rows",
"corresponding",
"to",
"feature",
"names",
"in",
"x",
"."
] | python | train |
RedFantom/ttkwidgets | ttkwidgets/frames/balloon.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/frames/balloon.py#L66-L70 | def _grid_widgets(self):
"""Place the widgets in the Toplevel."""
self._canvas.grid(sticky="nswe")
self.header_label.grid(row=1, column=1, sticky="nswe", pady=5, padx=5)
self.text_label.grid(row=3, column=1, sticky="nswe", pady=6, padx=5) | [
"def",
"_grid_widgets",
"(",
"self",
")",
":",
"self",
".",
"_canvas",
".",
"grid",
"(",
"sticky",
"=",
"\"nswe\"",
")",
"self",
".",
"header_label",
".",
"grid",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"\"nswe\"",
",",
"... | Place the widgets in the Toplevel. | [
"Place",
"the",
"widgets",
"in",
"the",
"Toplevel",
"."
] | python | train |
CSchoel/nolds | nolds/measures.py | https://github.com/CSchoel/nolds/blob/8a5ecc472d67ac08b571bd68967287668ca9058e/nolds/measures.py#L839-L874 | def logmid_n(max_n, ratio=1/4.0, nsteps=15):
"""
Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
This function has... | [
"def",
"logmid_n",
"(",
"max_n",
",",
"ratio",
"=",
"1",
"/",
"4.0",
",",
"nsteps",
"=",
"15",
")",
":",
"l",
"=",
"np",
".",
"log",
"(",
"max_n",
")",
"span",
"=",
"l",
"*",
"ratio",
"start",
"=",
"l",
"*",
"(",
"1",
"-",
"ratio",
")",
"*"... | Creates an array of integers that lie evenly spaced in the "middle" of the
logarithmic scale from 0 to log(max_n).
If max_n is very small and/or nsteps is very large, this may lead to
duplicate values which will be removed from the output.
This function has benefits in hurst_rs, because it cuts away both very... | [
"Creates",
"an",
"array",
"of",
"integers",
"that",
"lie",
"evenly",
"spaced",
"in",
"the",
"middle",
"of",
"the",
"logarithmic",
"scale",
"from",
"0",
"to",
"log",
"(",
"max_n",
")",
"."
] | python | train |
flowroute/txjason | txjason/service.py | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L397-L410 | def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
... | [
"def",
"_get_params",
"(",
"self",
",",
"rdata",
")",
":",
"if",
"'params'",
"in",
"rdata",
":",
"if",
"isinstance",
"(",
"rdata",
"[",
"'params'",
"]",
",",
"dict",
")",
"or",
"isinstance",
"(",
"rdata",
"[",
"'params'",
"]",
",",
"list",
")",
"or",... | Returns a list of jsonrpc request's method parameters. | [
"Returns",
"a",
"list",
"of",
"jsonrpc",
"request",
"s",
"method",
"parameters",
"."
] | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L2224-L2229 | def AvgPool3D(a, k, strides, padding):
"""
Average 3D pooling op.
"""
patches = _pool_patches(a, k, strides, padding.decode("ascii"))
return np.average(patches, axis=tuple(range(-len(k), 0))), | [
"def",
"AvgPool3D",
"(",
"a",
",",
"k",
",",
"strides",
",",
"padding",
")",
":",
"patches",
"=",
"_pool_patches",
"(",
"a",
",",
"k",
",",
"strides",
",",
"padding",
".",
"decode",
"(",
"\"ascii\"",
")",
")",
"return",
"np",
".",
"average",
"(",
"... | Average 3D pooling op. | [
"Average",
"3D",
"pooling",
"op",
"."
] | python | train |
inspirehep/harvesting-kit | harvestingkit/inspire_cds_package/from_cds.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L317-L327 | def update_keywords(self):
"""653 Free Keywords."""
for field in record_get_field_instances(self.record, '653', ind1='1'):
subs = field_get_subfields(field)
new_subs = []
if 'a' in subs:
for val in subs['a']:
new_subs.extend([('9', ... | [
"def",
"update_keywords",
"(",
"self",
")",
":",
"for",
"field",
"in",
"record_get_field_instances",
"(",
"self",
".",
"record",
",",
"'653'",
",",
"ind1",
"=",
"'1'",
")",
":",
"subs",
"=",
"field_get_subfields",
"(",
"field",
")",
"new_subs",
"=",
"[",
... | 653 Free Keywords. | [
"653",
"Free",
"Keywords",
"."
] | python | valid |
pazz/alot | alot/ui.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/ui.py#L514-L579 | def choice(self, message, choices=None, select=None, cancel=None,
msg_position='above', choices_to_return=None):
"""
prompt user to make a choice.
:param message: string to display before list of choices
:type message: unicode
:param choices: dict of possible choi... | [
"def",
"choice",
"(",
"self",
",",
"message",
",",
"choices",
"=",
"None",
",",
"select",
"=",
"None",
",",
"cancel",
"=",
"None",
",",
"msg_position",
"=",
"'above'",
",",
"choices_to_return",
"=",
"None",
")",
":",
"choices",
"=",
"choices",
"or",
"{... | prompt user to make a choice.
:param message: string to display before list of choices
:type message: unicode
:param choices: dict of possible choices
:type choices: dict: keymap->choice (both str)
:param choices_to_return: dict of possible choices to return for the
... | [
"prompt",
"user",
"to",
"make",
"a",
"choice",
"."
] | python | train |
open511/open511 | open511/utils/schedule.py | https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L58-L64 | def next_interval(self, after=None):
"""Returns the next Period this event is in effect, or None if the event
has no remaining periods."""
if after is None:
after = timezone.now()
after = self.to_timezone(after)
return next(self.intervals(range_start=after), None) | [
"def",
"next_interval",
"(",
"self",
",",
"after",
"=",
"None",
")",
":",
"if",
"after",
"is",
"None",
":",
"after",
"=",
"timezone",
".",
"now",
"(",
")",
"after",
"=",
"self",
".",
"to_timezone",
"(",
"after",
")",
"return",
"next",
"(",
"self",
... | Returns the next Period this event is in effect, or None if the event
has no remaining periods. | [
"Returns",
"the",
"next",
"Period",
"this",
"event",
"is",
"in",
"effect",
"or",
"None",
"if",
"the",
"event",
"has",
"no",
"remaining",
"periods",
"."
] | python | valid |
fitnr/twitter_bot_utils | twitter_bot_utils/args.py | https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/args.py#L21-L53 | def add_default_args(parser, version=None, include=None):
'''
Add default arguments to a parser. These are:
- config: argument for specifying a configuration file.
- user: argument for specifying a user.
- dry-run: option for running without side effects.
- verbose: option for ru... | [
"def",
"add_default_args",
"(",
"parser",
",",
"version",
"=",
"None",
",",
"include",
"=",
"None",
")",
":",
"include",
"=",
"include",
"or",
"(",
"'config'",
",",
"'user'",
",",
"'dry-run'",
",",
"'verbose'",
",",
"'quiet'",
")",
"if",
"'config'",
"in"... | Add default arguments to a parser. These are:
- config: argument for specifying a configuration file.
- user: argument for specifying a user.
- dry-run: option for running without side effects.
- verbose: option for running verbosely.
- quiet: option for running quietly.
... | [
"Add",
"default",
"arguments",
"to",
"a",
"parser",
".",
"These",
"are",
":",
"-",
"config",
":",
"argument",
"for",
"specifying",
"a",
"configuration",
"file",
".",
"-",
"user",
":",
"argument",
"for",
"specifying",
"a",
"user",
".",
"-",
"dry",
"-",
... | python | train |
peerplays-network/python-peerplays | peerplays/peerplays.py | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/peerplays.py#L874-L899 | def sport_delete(self, sport_id="0.0.0", account=None, **kwargs):
""" Remove a sport. This needs to be **proposed**.
:param str sport_id: Sport ID to identify the Sport to be deleted
:param str account: (optional) Account used to verify the operation
"""
if not accoun... | [
"def",
"sport_delete",
"(",
"self",
",",
"sport_id",
"=",
"\"0.0.0\"",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"config",
":",
"account",
"=",
"config",
"[",
"\"defaul... | Remove a sport. This needs to be **proposed**.
:param str sport_id: Sport ID to identify the Sport to be deleted
:param str account: (optional) Account used to verify the operation | [
"Remove",
"a",
"sport",
".",
"This",
"needs",
"to",
"be",
"**",
"proposed",
"**",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py#L250-L263 | def get_mac_address_table_input_request_type_get_request_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
input = ET.SubElement(get_mac_address_... | [
"def",
"get_mac_address_table_input_request_type_get_request_mac_address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_mac_address_table",
"=",
"ET",
".",
"Element",
"(",
"\"get_mac_address_table\""... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
rehandalal/buchner | buchner/project-template/manage.py | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/manage.py#L30-L36 | def db_create():
"""Create the database"""
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' | [
"def",
"db_create",
"(",
")",
":",
"try",
":",
"migrate_api",
".",
"version_control",
"(",
"url",
"=",
"db_url",
",",
"repository",
"=",
"db_repo",
")",
"db_upgrade",
"(",
")",
"except",
"DatabaseAlreadyControlledError",
":",
"print",
"'ERROR: Database is already ... | Create the database | [
"Create",
"the",
"database"
] | python | train |
qubell/contrib-python-qubell-client | qubell/api/private/instance.py | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/instance.py#L113-L121 | def __collect_interfaces_return(interfaces):
"""Collect new style (44.1+) return values to old-style kv-list"""
acc = []
for (interfaceName, interfaceData) in interfaces.items():
signalValues = interfaceData.get("signals", {})
for (signalName, signalValue) in signalValues... | [
"def",
"__collect_interfaces_return",
"(",
"interfaces",
")",
":",
"acc",
"=",
"[",
"]",
"for",
"(",
"interfaceName",
",",
"interfaceData",
")",
"in",
"interfaces",
".",
"items",
"(",
")",
":",
"signalValues",
"=",
"interfaceData",
".",
"get",
"(",
"\"signal... | Collect new style (44.1+) return values to old-style kv-list | [
"Collect",
"new",
"style",
"(",
"44",
".",
"1",
"+",
")",
"return",
"values",
"to",
"old",
"-",
"style",
"kv",
"-",
"list"
] | python | train |
mikedh/trimesh | trimesh/path/polygons.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/polygons.py#L376-L398 | def random_polygon(segments=8, radius=1.0):
"""
Generate a random polygon with a maximum number of sides and approximate radius.
Parameters
---------
segments: int, the maximum number of sides the random polygon will have
radius: float, the approximate radius of the polygon desired
Retur... | [
"def",
"random_polygon",
"(",
"segments",
"=",
"8",
",",
"radius",
"=",
"1.0",
")",
":",
"angles",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"cumsum",
"(",
"np",
".",
"random",
".",
"random",
"(",
"segments",
")",
"*",
"np",
".",
"pi",
"*",
"2",
... | Generate a random polygon with a maximum number of sides and approximate radius.
Parameters
---------
segments: int, the maximum number of sides the random polygon will have
radius: float, the approximate radius of the polygon desired
Returns
---------
polygon: shapely.geometry.Polygon o... | [
"Generate",
"a",
"random",
"polygon",
"with",
"a",
"maximum",
"number",
"of",
"sides",
"and",
"approximate",
"radius",
"."
] | python | train |
opendatateam/udata | udata/assets.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L27-L36 | def register_manifest(app, filename='manifest.json'):
'''Register an assets json manifest'''
if current_app.config.get('TESTING'):
return # Do not spend time here when testing
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.format(**locals())
raise ValueEr... | [
"def",
"register_manifest",
"(",
"app",
",",
"filename",
"=",
"'manifest.json'",
")",
":",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not spend time here when testing",
"if",
"not",
"has_manifest",
"(",
"app",
","... | Register an assets json manifest | [
"Register",
"an",
"assets",
"json",
"manifest"
] | python | train |
tcalmant/ipopo | pelix/remote/beans.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L605-L616 | def matches(self, ldap_filter):
# type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool
"""
Tests the properties of this EndpointDescription against the given
filter
:param ldap_filter: A filter
:return: True if properties matches the filter
"""
return pe... | [
"def",
"matches",
"(",
"self",
",",
"ldap_filter",
")",
":",
"# type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool",
"return",
"pelix",
".",
"ldapfilter",
".",
"get_ldap_filter",
"(",
"ldap_filter",
")",
".",
"matches",
"(",
"self",
".",
"__properties",
")"
] | Tests the properties of this EndpointDescription against the given
filter
:param ldap_filter: A filter
:return: True if properties matches the filter | [
"Tests",
"the",
"properties",
"of",
"this",
"EndpointDescription",
"against",
"the",
"given",
"filter"
] | python | train |
depop/python-flexisettings | flexisettings/__init__.py | https://github.com/depop/python-flexisettings/blob/36d08280ab7c45568fdf206fcdb4cf771d240c6b/flexisettings/__init__.py#L90-L114 | def _load_config(initial_namespace=None, defaults=None):
# type: (Optional[str], Optional[str]) -> ConfigLoader
"""
Kwargs:
initial_namespace:
defaults:
"""
# load defaults
if defaults:
config = ConfigLoader()
config.update_from_object(defaults)
namespace = g... | [
"def",
"_load_config",
"(",
"initial_namespace",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"# type: (Optional[str], Optional[str]) -> ConfigLoader",
"# load defaults",
"if",
"defaults",
":",
"config",
"=",
"ConfigLoader",
"(",
")",
"config",
".",
"update_fr... | Kwargs:
initial_namespace:
defaults: | [
"Kwargs",
":",
"initial_namespace",
":",
"defaults",
":"
] | python | train |
BlendedSiteGenerator/Blended | blended/__main__.py | https://github.com/BlendedSiteGenerator/Blended/blob/e5865a8633e461a22c86ef6ee98cdd7051c412ac/blended/__main__.py#L348-L713 | def build_files(outdir):
"""Build the files!"""
# Make sure there is actually a configuration file
config_file_dir = os.path.join(cwd, "config.py")
if not os.path.exists(config_file_dir):
sys.exit(
"There dosen't seem to be a configuration file. Have you run the init command?")
e... | [
"def",
"build_files",
"(",
"outdir",
")",
":",
"# Make sure there is actually a configuration file",
"config_file_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"config.py\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_file_d... | Build the files! | [
"Build",
"the",
"files!"
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/rbridge_id/vrf/address_family/ip/unicast/ip/route/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/vrf/address_family/ip/unicast/ip/route/__init__.py#L199-L220 | def _set_static_route_oif(self, v, load=False):
"""
Setter method for static_route_oif, mapped from YANG variable /rbridge_id/vrf/address_family/ip/unicast/ip/route/static_route_oif (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_static_route_oif is considered as ... | [
"def",
"_set_static_route_oif",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for static_route_oif, mapped from YANG variable /rbridge_id/vrf/address_family/ip/unicast/ip/route/static_route_oif (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_static_route_oif is considered as a private
method. Backends looking to populate this vari... | [
"Setter",
"method",
"for",
"static_route_oif",
"mapped",
"from",
"YANG",
"variable",
"/",
"rbridge_id",
"/",
"vrf",
"/",
"address_family",
"/",
"ip",
"/",
"unicast",
"/",
"ip",
"/",
"route",
"/",
"static_route_oif",
"(",
"list",
")",
"If",
"this",
"variable"... | python | train |
pyblish/pyblish-qml | pyblish_qml/models.py | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L821-L828 | def _add_rule(self, group, role, value):
"""Implementation detail"""
if role not in group:
group[role] = list()
group[role].append(value)
self.invalidate() | [
"def",
"_add_rule",
"(",
"self",
",",
"group",
",",
"role",
",",
"value",
")",
":",
"if",
"role",
"not",
"in",
"group",
":",
"group",
"[",
"role",
"]",
"=",
"list",
"(",
")",
"group",
"[",
"role",
"]",
".",
"append",
"(",
"value",
")",
"self",
... | Implementation detail | [
"Implementation",
"detail"
] | python | train |
Parsl/parsl | parsl/dataflow/usage_tracking/usage.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L156-L176 | def construct_start_message(self):
"""Collect preliminary run info at the start of the DFK.
Returns :
- Message dict dumped as json string, ready for UDP
"""
uname = getpass.getuser().encode('latin1')
hashed_username = hashlib.sha256(uname).hexdigest()[0:10]
... | [
"def",
"construct_start_message",
"(",
"self",
")",
":",
"uname",
"=",
"getpass",
".",
"getuser",
"(",
")",
".",
"encode",
"(",
"'latin1'",
")",
"hashed_username",
"=",
"hashlib",
".",
"sha256",
"(",
"uname",
")",
".",
"hexdigest",
"(",
")",
"[",
"0",
... | Collect preliminary run info at the start of the DFK.
Returns :
- Message dict dumped as json string, ready for UDP | [
"Collect",
"preliminary",
"run",
"info",
"at",
"the",
"start",
"of",
"the",
"DFK",
"."
] | python | valid |
baruwa-enterprise/BaruwaAPI | BaruwaAPI/resource.py | https://github.com/baruwa-enterprise/BaruwaAPI/blob/53335b377ccfd388e42f4f240f181eed72f51180/BaruwaAPI/resource.py#L151-L156 | def update_domain(self, domainid, data):
"""Update a domain"""
return self.api_call(
ENDPOINTS['domains']['update'],
dict(domainid=domainid),
body=data) | [
"def",
"update_domain",
"(",
"self",
",",
"domainid",
",",
"data",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"ENDPOINTS",
"[",
"'domains'",
"]",
"[",
"'update'",
"]",
",",
"dict",
"(",
"domainid",
"=",
"domainid",
")",
",",
"body",
"=",
"data",... | Update a domain | [
"Update",
"a",
"domain"
] | python | train |
cloudera/cm_api | python/src/cm_api/endpoints/clusters.py | https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/clusters.py#L59-L66 | def get_all_clusters(resource_root, view=None):
"""
Get all clusters
@param resource_root: The root Resource object.
@return: A list of ApiCluster objects.
"""
return call(resource_root.get, CLUSTERS_PATH, ApiCluster, True,
params=view and dict(view=view) or None) | [
"def",
"get_all_clusters",
"(",
"resource_root",
",",
"view",
"=",
"None",
")",
":",
"return",
"call",
"(",
"resource_root",
".",
"get",
",",
"CLUSTERS_PATH",
",",
"ApiCluster",
",",
"True",
",",
"params",
"=",
"view",
"and",
"dict",
"(",
"view",
"=",
"v... | Get all clusters
@param resource_root: The root Resource object.
@return: A list of ApiCluster objects. | [
"Get",
"all",
"clusters"
] | python | train |
shmir/PyIxExplorer | ixexplorer/ixe_app.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L187-L195 | def stop_transmit(self, *ports):
""" Stop traffic on ports.
:param ports: list of ports to stop traffic on, if empty start on all ports.
"""
port_list = self.set_ports_list(*ports)
self.api.call_rc('ixStopTransmit {}'.format(port_list))
time.sleep(0.2) | [
"def",
"stop_transmit",
"(",
"self",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStopTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
... | Stop traffic on ports.
:param ports: list of ports to stop traffic on, if empty start on all ports. | [
"Stop",
"traffic",
"on",
"ports",
"."
] | python | train |
saltstack/salt | salt/runners/venafiapi.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L629-L640 | def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains') | [
"def",
"list_domain_cache",
"(",
")",
":",
"cache",
"=",
"salt",
".",
"cache",
".",
"Cache",
"(",
"__opts__",
",",
"syspaths",
".",
"CACHE_DIR",
")",
"return",
"cache",
".",
"list",
"(",
"'venafi/domains'",
")"
] | List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache | [
"List",
"domains",
"that",
"have",
"been",
"cached"
] | python | train |
twisted/vertex | vertex/conncache.py | https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/conncache.py#L103-L115 | def shutdown(self):
"""
Disconnect all cached connections.
@returns: a deferred that fires once all connection are disconnected.
@rtype: L{Deferred}
"""
self._shuttingDown = {key: Deferred()
for key in self.cachedConnections.keys()}
... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"_shuttingDown",
"=",
"{",
"key",
":",
"Deferred",
"(",
")",
"for",
"key",
"in",
"self",
".",
"cachedConnections",
".",
"keys",
"(",
")",
"}",
"return",
"DeferredList",
"(",
"[",
"maybeDeferred",
"... | Disconnect all cached connections.
@returns: a deferred that fires once all connection are disconnected.
@rtype: L{Deferred} | [
"Disconnect",
"all",
"cached",
"connections",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/clc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L285-L304 | def get_build_status(req_id, nodename):
'''
get the build status from CLC to make sure we dont return to early
'''
counter = 0
req_id = six.text_type(req_id)
while counter < 10:
queue = clc.v1.Blueprint.GetStatus(request_id=(req_id))
if queue["PercentComplete"] == 100:
... | [
"def",
"get_build_status",
"(",
"req_id",
",",
"nodename",
")",
":",
"counter",
"=",
"0",
"req_id",
"=",
"six",
".",
"text_type",
"(",
"req_id",
")",
"while",
"counter",
"<",
"10",
":",
"queue",
"=",
"clc",
".",
"v1",
".",
"Blueprint",
".",
"GetStatus"... | get the build status from CLC to make sure we dont return to early | [
"get",
"the",
"build",
"status",
"from",
"CLC",
"to",
"make",
"sure",
"we",
"dont",
"return",
"to",
"early"
] | python | train |
numenta/nupic | src/nupic/data/generators/pattern_machine.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/generators/pattern_machine.py#L115-L135 | def numberMapForBits(self, bits):
"""
Return a map from number to matching on bits,
for all numbers that match a set of bits.
@param bits (set) Indices of bits
@return (dict) Mapping from number => on bits.
"""
numberMap = dict()
for bit in bits:
numbers = self.numbersForBit(bit... | [
"def",
"numberMapForBits",
"(",
"self",
",",
"bits",
")",
":",
"numberMap",
"=",
"dict",
"(",
")",
"for",
"bit",
"in",
"bits",
":",
"numbers",
"=",
"self",
".",
"numbersForBit",
"(",
"bit",
")",
"for",
"number",
"in",
"numbers",
":",
"if",
"not",
"nu... | Return a map from number to matching on bits,
for all numbers that match a set of bits.
@param bits (set) Indices of bits
@return (dict) Mapping from number => on bits. | [
"Return",
"a",
"map",
"from",
"number",
"to",
"matching",
"on",
"bits",
"for",
"all",
"numbers",
"that",
"match",
"a",
"set",
"of",
"bits",
"."
] | python | valid |
mosdef-hub/mbuild | mbuild/coordinate_transform.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/coordinate_transform.py#L577-L597 | def _spin(coordinates, theta, around):
"""Rotate a set of coordinates in place around an arbitrary vector.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being spun.
theta : float
The angle by which to spin the coordinates, in radians.
a... | [
"def",
"_spin",
"(",
"coordinates",
",",
"theta",
",",
"around",
")",
":",
"around",
"=",
"np",
".",
"asarray",
"(",
"around",
")",
".",
"reshape",
"(",
"3",
")",
"if",
"np",
".",
"array_equal",
"(",
"around",
",",
"np",
".",
"zeros",
"(",
"3",
"... | Rotate a set of coordinates in place around an arbitrary vector.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being spun.
theta : float
The angle by which to spin the coordinates, in radians.
around : np.ndarray, shape=(3,), dtype=float
... | [
"Rotate",
"a",
"set",
"of",
"coordinates",
"in",
"place",
"around",
"an",
"arbitrary",
"vector",
"."
] | python | train |
spotify/luigi | luigi/contrib/redshift.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L386-L408 | def copy(self, cursor, f):
"""
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used.
"""
logger.info("Inserting file: %s", f)
colnames = ''
if self.columns and len(self.columns) > 0:
... | [
"def",
"copy",
"(",
"self",
",",
"cursor",
",",
"f",
")",
":",
"logger",
".",
"info",
"(",
"\"Inserting file: %s\"",
",",
"f",
")",
"colnames",
"=",
"''",
"if",
"self",
".",
"columns",
"and",
"len",
"(",
"self",
".",
"columns",
")",
">",
"0",
":",
... | Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used. | [
"Defines",
"copying",
"from",
"s3",
"into",
"redshift",
"."
] | python | train |
incuna/django-wkhtmltopdf | wkhtmltopdf/views.py | https://github.com/incuna/django-wkhtmltopdf/blob/4e73f604c48f7f449c916c4257a72af59517322c/wkhtmltopdf/views.py#L64-L82 | def rendered_content(self):
"""Returns the freshly rendered content for the template and context
described by the PDFResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using t... | [
"def",
"rendered_content",
"(",
"self",
")",
":",
"cmd_options",
"=",
"self",
".",
"cmd_options",
".",
"copy",
"(",
")",
"return",
"render_pdf_from_template",
"(",
"self",
".",
"resolve_template",
"(",
"self",
".",
"template_name",
")",
",",
"self",
".",
"re... | Returns the freshly rendered content for the template and context
described by the PDFResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using the value of this property. | [
"Returns",
"the",
"freshly",
"rendered",
"content",
"for",
"the",
"template",
"and",
"context",
"described",
"by",
"the",
"PDFResponse",
"."
] | python | test |
kwikteam/phy | phy/io/array.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/array.py#L163-L180 | def _get_padded(data, start, end):
"""Return `data[start:end]` filling in with zeros outside array bounds
Assumes that either `start<0` or `end>len(data)` but not both.
"""
if start < 0 and end > data.shape[0]:
raise RuntimeError()
if start < 0:
start_zeros = np.zeros((-start, data... | [
"def",
"_get_padded",
"(",
"data",
",",
"start",
",",
"end",
")",
":",
"if",
"start",
"<",
"0",
"and",
"end",
">",
"data",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"RuntimeError",
"(",
")",
"if",
"start",
"<",
"0",
":",
"start_zeros",
"=",
"np"... | Return `data[start:end]` filling in with zeros outside array bounds
Assumes that either `start<0` or `end>len(data)` but not both. | [
"Return",
"data",
"[",
"start",
":",
"end",
"]",
"filling",
"in",
"with",
"zeros",
"outside",
"array",
"bounds"
] | python | train |
facebook/pyre-check | sapp/sapp/base_parser.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/base_parser.py#L224-L231 | def compute_diff_handle(filename, old_line, code):
"""Uses the absolute line and ignores the callable/character offsets.
Used only in determining whether new issues are old issues.
"""
key = "{filename}:{old_line}:{code}".format(
filename=filename, old_line=old_line, code=cod... | [
"def",
"compute_diff_handle",
"(",
"filename",
",",
"old_line",
",",
"code",
")",
":",
"key",
"=",
"\"{filename}:{old_line}:{code}\"",
".",
"format",
"(",
"filename",
"=",
"filename",
",",
"old_line",
"=",
"old_line",
",",
"code",
"=",
"code",
")",
"return",
... | Uses the absolute line and ignores the callable/character offsets.
Used only in determining whether new issues are old issues. | [
"Uses",
"the",
"absolute",
"line",
"and",
"ignores",
"the",
"callable",
"/",
"character",
"offsets",
".",
"Used",
"only",
"in",
"determining",
"whether",
"new",
"issues",
"are",
"old",
"issues",
"."
] | python | train |
Lagg/steamodd | steam/api.py | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/api.py#L248-L259 | def call(self):
""" Make the API call again and fetch fresh data. """
data = self._downloader.download()
# Only try to pass errors arg if supported
if sys.version >= "2.7":
data = data.decode("utf-8", errors="ignore")
else:
data = data.decode("utf-8")
... | [
"def",
"call",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_downloader",
".",
"download",
"(",
")",
"# Only try to pass errors arg if supported",
"if",
"sys",
".",
"version",
">=",
"\"2.7\"",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"\"utf-8\"",
... | Make the API call again and fetch fresh data. | [
"Make",
"the",
"API",
"call",
"again",
"and",
"fetch",
"fresh",
"data",
"."
] | python | train |
atlassian-api/atlassian-python-api | atlassian/service_desk.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/service_desk.py#L90-L100 | def get_customer_request_status(self, issue_id_or_key):
"""
Get customer request status name
:param issue_id_or_key: str
:return: Status name
"""
request = self.get('rest/servicedeskapi/request/{}/status'.format(issue_id_or_key)).get('values')
status = request[0]... | [
"def",
"get_customer_request_status",
"(",
"self",
",",
"issue_id_or_key",
")",
":",
"request",
"=",
"self",
".",
"get",
"(",
"'rest/servicedeskapi/request/{}/status'",
".",
"format",
"(",
"issue_id_or_key",
")",
")",
".",
"get",
"(",
"'values'",
")",
"status",
... | Get customer request status name
:param issue_id_or_key: str
:return: Status name | [
"Get",
"customer",
"request",
"status",
"name"
] | python | train |
influxdata/influxdb-python | influxdb/influxdb08/client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L815-L825 | def delete_database_user(self, username):
"""Delete database user."""
url = "db/{0}/users/{1}".format(self._database, username)
self.request(
url=url,
method='DELETE',
expected_response_code=200
)
return True | [
"def",
"delete_database_user",
"(",
"self",
",",
"username",
")",
":",
"url",
"=",
"\"db/{0}/users/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"username",
")",
"self",
".",
"request",
"(",
"url",
"=",
"url",
",",
"method",
"=",
"'DELETE'",
... | Delete database user. | [
"Delete",
"database",
"user",
"."
] | python | train |
Julian/jsonschema | jsonschema/validators.py | https://github.com/Julian/jsonschema/blob/a72332004cdc3ba456de7918bc32059822b2f69a/jsonschema/validators.py#L154-L364 | def create(
meta_schema,
validators=(),
version=None,
default_types=None,
type_checker=None,
id_of=_id_of,
):
"""
Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collec... | [
"def",
"create",
"(",
"meta_schema",
",",
"validators",
"=",
"(",
")",
",",
"version",
"=",
"None",
",",
"default_types",
"=",
"None",
",",
"type_checker",
"=",
"None",
",",
"id_of",
"=",
"_id_of",
",",
")",
":",
"if",
"default_types",
"is",
"not",
"No... | Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collections.Mapping):
a mapping from names to callables, where each callable will
validate the schema property with the given n... | [
"Create",
"a",
"new",
"validator",
"class",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/op/setnym.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/op/setnym.py#L185-L211 | def main(args: Sequence[str] = None) -> int:
"""
Main line for script: check arguments and dispatch operation to set nym.
:param args: command-line arguments
:return: 0 for OK, 1 for failure
"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)-15s | %(levelname)-8s |... | [
"def",
"main",
"(",
"args",
":",
"Sequence",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"int",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"'%(asctime)-15s | %(levelname)-8s | %(message)s'",
",",
"datefmt"... | Main line for script: check arguments and dispatch operation to set nym.
:param args: command-line arguments
:return: 0 for OK, 1 for failure | [
"Main",
"line",
"for",
"script",
":",
"check",
"arguments",
"and",
"dispatch",
"operation",
"to",
"set",
"nym",
"."
] | python | train |
ray-project/ray | python/ray/log_monitor.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/log_monitor.py#L210-L223 | def run(self):
"""Run the log monitor.
This will query Redis once every second to check if there are new log
files to monitor. It will also store those log files in Redis.
"""
while True:
self.update_log_filenames()
self.open_closed_files()
an... | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"update_log_filenames",
"(",
")",
"self",
".",
"open_closed_files",
"(",
")",
"anything_published",
"=",
"self",
".",
"check_log_files_and_publish_updates",
"(",
")",
"# If nothing was publish... | Run the log monitor.
This will query Redis once every second to check if there are new log
files to monitor. It will also store those log files in Redis. | [
"Run",
"the",
"log",
"monitor",
"."
] | python | train |
JamesPHoughton/pysd | pysd/py_backend/functions.py | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L935-L943 | def lookup_discrete(x, xs, ys):
"""
Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.
Out-of-range values are the same as the closest endpoint (i.e, no extrapo... | [
"def",
"lookup_discrete",
"(",
"x",
",",
"xs",
",",
"ys",
")",
":",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"xs",
")",
")",
":",
"if",
"x",
"<",
"xs",
"[",
"index",
"]",
":",
"return",
"ys",
"[",
"index",
"-",
"1",
"]",
"i... | Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.
Out-of-range values are the same as the closest endpoint (i.e, no extrapolation is performed). | [
"Intermediate",
"values",
"take",
"on",
"the",
"value",
"associated",
"with",
"the",
"next",
"lower",
"x",
"-",
"coordinate",
"(",
"also",
"called",
"a",
"step",
"-",
"wise",
"function",
")",
".",
"The",
"last",
"two",
"points",
"of",
"a",
"discrete",
"g... | python | train |
lucasmaystre/choix | choix/ep.py | https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/ep.py#L157-L176 | def _log_phi(z):
"""Stable computation of the log of the Normal CDF and its derivative."""
# Adapted from the GPML function `logphi.m`.
if z * z < 0.0492:
# First case: z close to zero.
coef = -z / SQRT2PI
val = functools.reduce(lambda acc, c: coef * (c + acc), CS, 0)
res = -... | [
"def",
"_log_phi",
"(",
"z",
")",
":",
"# Adapted from the GPML function `logphi.m`.",
"if",
"z",
"*",
"z",
"<",
"0.0492",
":",
"# First case: z close to zero.",
"coef",
"=",
"-",
"z",
"/",
"SQRT2PI",
"val",
"=",
"functools",
".",
"reduce",
"(",
"lambda",
"acc... | Stable computation of the log of the Normal CDF and its derivative. | [
"Stable",
"computation",
"of",
"the",
"log",
"of",
"the",
"Normal",
"CDF",
"and",
"its",
"derivative",
"."
] | python | train |
jcrist/skein | skein/objects.py | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L243-L245 | def to_json(self, skip_nulls=True):
"""Convert object to a json string"""
return json.dumps(self.to_dict(skip_nulls=skip_nulls)) | [
"def",
"to_json",
"(",
"self",
",",
"skip_nulls",
"=",
"True",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
"skip_nulls",
"=",
"skip_nulls",
")",
")"
] | Convert object to a json string | [
"Convert",
"object",
"to",
"a",
"json",
"string"
] | python | train |
diging/tethne | tethne/classes/graphcollection.py | https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/classes/graphcollection.py#L190-L211 | def nodes(self, data=False, native=True):
"""
Returns a list of all nodes in the :class:`.GraphCollection`\.
Parameters
----------
data : bool
(default: False) If True, returns a list of 2-tuples containing
node labels and attributes.
Returns
... | [
"def",
"nodes",
"(",
"self",
",",
"data",
"=",
"False",
",",
"native",
"=",
"True",
")",
":",
"nodes",
"=",
"self",
".",
"master_graph",
".",
"nodes",
"(",
"data",
"=",
"data",
")",
"if",
"native",
":",
"if",
"data",
":",
"nodes",
"=",
"[",
"(",
... | Returns a list of all nodes in the :class:`.GraphCollection`\.
Parameters
----------
data : bool
(default: False) If True, returns a list of 2-tuples containing
node labels and attributes.
Returns
-------
nodes : list | [
"Returns",
"a",
"list",
"of",
"all",
"nodes",
"in",
"the",
":",
"class",
":",
".",
"GraphCollection",
"\\",
"."
] | python | train |
O365/python-o365 | O365/excel.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L1186-L1208 | def get_columns(self, *, top=None, skip=None):
"""
Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip
"""
url = self.build_url(self._endpoints.get('get_columns'))
params = {}
if top is... | [
"def",
"get_columns",
"(",
"self",
",",
"*",
",",
"top",
"=",
"None",
",",
"skip",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_columns'",
")",
")",
"params",
"=",
"{",
"}",
"... | Return the columns of this table
:param int top: specify n columns to retrieve
:param int skip: specify n columns to skip | [
"Return",
"the",
"columns",
"of",
"this",
"table",
":",
"param",
"int",
"top",
":",
"specify",
"n",
"columns",
"to",
"retrieve",
":",
"param",
"int",
"skip",
":",
"specify",
"n",
"columns",
"to",
"skip"
] | python | train |
LeastAuthority/txkube | src/txkube/_swagger.py | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_swagger.py#L158-L197 | def pclass_for_definition(self, name):
"""
Get a ``pyrsistent.PClass`` subclass representing the Swagger definition
in this specification which corresponds to the given name.
:param unicode name: The name of the definition to use.
:return: A Python class which can be used to re... | [
"def",
"pclass_for_definition",
"(",
"self",
",",
"name",
")",
":",
"while",
"True",
":",
"try",
":",
"cls",
"=",
"self",
".",
"_pclasses",
"[",
"name",
"]",
"except",
"KeyError",
":",
"try",
":",
"original_definition",
"=",
"self",
".",
"definitions",
"... | Get a ``pyrsistent.PClass`` subclass representing the Swagger definition
in this specification which corresponds to the given name.
:param unicode name: The name of the definition to use.
:return: A Python class which can be used to represent the Swagger
definition of the given nam... | [
"Get",
"a",
"pyrsistent",
".",
"PClass",
"subclass",
"representing",
"the",
"Swagger",
"definition",
"in",
"this",
"specification",
"which",
"corresponds",
"to",
"the",
"given",
"name",
"."
] | python | train |
google/grr | grr/server/grr_response_server/flows/cron/system.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/cron/system.py#L167-L193 | def Run(self):
"""Retrieve all the clients for the AbstractClientStatsCollectors."""
try:
self.stats = {}
self.BeginProcessing()
processed_count = 0
for client_info_batch in _IterateAllClients(
recency_window=self.recency_window):
for client_info in client_info_batc... | [
"def",
"Run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"stats",
"=",
"{",
"}",
"self",
".",
"BeginProcessing",
"(",
")",
"processed_count",
"=",
"0",
"for",
"client_info_batch",
"in",
"_IterateAllClients",
"(",
"recency_window",
"=",
"self",
".",
... | Retrieve all the clients for the AbstractClientStatsCollectors. | [
"Retrieve",
"all",
"the",
"clients",
"for",
"the",
"AbstractClientStatsCollectors",
"."
] | python | train |
cloud-custodian/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_logexporter/c7n_logexporter/exporter.py#L372-L388 | def filter_creation_date(groups, start, end):
"""Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start.
"""
results = []
for g in groups:
created = datetime.fromtimestamp(g['creationTime'] / 1000.0)
if created... | [
"def",
"filter_creation_date",
"(",
"groups",
",",
"start",
",",
"end",
")",
":",
"results",
"=",
"[",
"]",
"for",
"g",
"in",
"groups",
":",
"created",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"g",
"[",
"'creationTime'",
"]",
"/",
"1000.0",
")",
"if... | Filter log groups by their creation date.
Also sets group specific value for start to the minimum
of creation date or start. | [
"Filter",
"log",
"groups",
"by",
"their",
"creation",
"date",
"."
] | python | train |
logston/py3s3 | py3s3/storage.py | https://github.com/logston/py3s3/blob/1910ca60c53a53d839d6f7b09c05b555f3bfccf4/py3s3/storage.py#L276-L298 | def _put_file(self, file):
"""Send PUT request to S3 with file contents"""
post_params = {
'file_size': file.size,
'file_hash': file.md5hash(),
'content_type': self._get_content_type(file),
}
headers = self._request_headers('PUT', file.prefixed_name... | [
"def",
"_put_file",
"(",
"self",
",",
"file",
")",
":",
"post_params",
"=",
"{",
"'file_size'",
":",
"file",
".",
"size",
",",
"'file_hash'",
":",
"file",
".",
"md5hash",
"(",
")",
",",
"'content_type'",
":",
"self",
".",
"_get_content_type",
"(",
"file"... | Send PUT request to S3 with file contents | [
"Send",
"PUT",
"request",
"to",
"S3",
"with",
"file",
"contents"
] | python | train |
Miserlou/SoundScrape | soundscrape/soundscrape.py | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L731-L774 | def scrape_mixcloud_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Returns:
list: filenames to open
"""
try:
data = get_mixcloud_data(mc_url)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + mc_url)
print(e)
ret... | [
"def",
"scrape_mixcloud_url",
"(",
"mc_url",
",",
"num_tracks",
"=",
"sys",
".",
"maxsize",
",",
"folders",
"=",
"False",
",",
"custom_path",
"=",
"''",
")",
":",
"try",
":",
"data",
"=",
"get_mixcloud_data",
"(",
"mc_url",
")",
"except",
"Exception",
"as"... | Returns:
list: filenames to open | [
"Returns",
":",
"list",
":",
"filenames",
"to",
"open"
] | python | train |
ScriptSmith/socialreaper | socialreaper/tools.py | https://github.com/ScriptSmith/socialreaper/blob/87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da/socialreaper/tools.py#L132-L194 | def to_csv(data, field_names=None, filename='data.csv',
overwrite=True,
write_headers=True, append=False, flat=True,
primary_fields=None, sort_fields=True):
"""
DEPRECATED Write a list of dicts to a csv file
:param data: List of dicts
:param field_names: The ... | [
"def",
"to_csv",
"(",
"data",
",",
"field_names",
"=",
"None",
",",
"filename",
"=",
"'data.csv'",
",",
"overwrite",
"=",
"True",
",",
"write_headers",
"=",
"True",
",",
"append",
"=",
"False",
",",
"flat",
"=",
"True",
",",
"primary_fields",
"=",
"None"... | DEPRECATED Write a list of dicts to a csv file
:param data: List of dicts
:param field_names: The list column names
:param filename: The name of the file
:param overwrite: Overwrite the file if exists
:param write_headers: Write the headers to the csv file
:param append: Write new row... | [
"DEPRECATED",
"Write",
"a",
"list",
"of",
"dicts",
"to",
"a",
"csv",
"file",
":",
"param",
"data",
":",
"List",
"of",
"dicts",
":",
"param",
"field_names",
":",
"The",
"list",
"column",
"names",
":",
"param",
"filename",
":",
"The",
"name",
"of",
"the"... | python | valid |
lucaslamounier/USGSDownload | usgsdownload/usgs.py | https://github.com/lucaslamounier/USGSDownload/blob/0969483ea9f9648aa17b099f36d2e1010488b2a4/usgsdownload/usgs.py#L86-L92 | def validate_sceneInfo(self):
"""Check scene name and whether remote file exists. Raises
WrongSceneNameError if the scene name is wrong.
"""
if self.sceneInfo.prefix not in self.__satellitesMap:
raise WrongSceneNameError('USGS Downloader: Prefix of %s (%s) is invalid'
... | [
"def",
"validate_sceneInfo",
"(",
"self",
")",
":",
"if",
"self",
".",
"sceneInfo",
".",
"prefix",
"not",
"in",
"self",
".",
"__satellitesMap",
":",
"raise",
"WrongSceneNameError",
"(",
"'USGS Downloader: Prefix of %s (%s) is invalid'",
"%",
"(",
"self",
".",
"sce... | Check scene name and whether remote file exists. Raises
WrongSceneNameError if the scene name is wrong. | [
"Check",
"scene",
"name",
"and",
"whether",
"remote",
"file",
"exists",
".",
"Raises",
"WrongSceneNameError",
"if",
"the",
"scene",
"name",
"is",
"wrong",
"."
] | python | test |
pyrogram/pyrogram | pyrogram/client/client.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/client.py#L467-L484 | def remove_handler(self, handler: Handler, group: int = 0):
"""Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly... | [
"def",
"remove_handler",
"(",
"self",
",",
"handler",
":",
"Handler",
",",
"group",
":",
"int",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"handler",
",",
"DisconnectHandler",
")",
":",
"self",
".",
"disconnect_handler",
"=",
"None",
"else",
":",
"self... | Removes a previously-added update handler.
Make sure to provide the right group that the handler was added in. You can use
the return value of the :meth:`add_handler` method, a tuple of (handler, group), and
pass it directly.
Args:
handler (``Handler``):
The... | [
"Removes",
"a",
"previously",
"-",
"added",
"update",
"handler",
"."
] | python | train |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1876-L1882 | def conf_budget(self, budget):
"""
Set limit on the number of conflicts.
"""
if self.maplesat:
pysolvers.maplechrono_cbudget(self.maplesat, budget) | [
"def",
"conf_budget",
"(",
"self",
",",
"budget",
")",
":",
"if",
"self",
".",
"maplesat",
":",
"pysolvers",
".",
"maplechrono_cbudget",
"(",
"self",
".",
"maplesat",
",",
"budget",
")"
] | Set limit on the number of conflicts. | [
"Set",
"limit",
"on",
"the",
"number",
"of",
"conflicts",
"."
] | python | train |
devoperate/chronos | chronos/cli.py | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L91-L111 | def bump(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch').
"""
try:
last_tag = last_git_release_tag(git_tags())
except N... | [
"def",
"bump",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"try",
":",
"last_tag",
"=",
"last_git_release_tag",
"(",
"git_tags",
"(",
")",
")",
"except",
"NoGitTagsException",
":",
"print",
"(",
"SemVer",
"(",
"0",
",",
"1",
... | :args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch'). | [
":",
"args",
":",
"An",
"argparse",
".",
"Namespace",
"object",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/workflow/template.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L421-L461 | def _add_metadata(item, metadata, remotes, only_metadata=False):
"""Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel ite... | [
"def",
"_add_metadata",
"(",
"item",
",",
"metadata",
",",
"remotes",
",",
"only_metadata",
"=",
"False",
")",
":",
"for",
"check_key",
"in",
"[",
"item",
"[",
"\"description\"",
"]",
"]",
"+",
"_get_file_keys",
"(",
"item",
")",
"+",
"_get_vrn_keys",
"(",... | Add metadata information from CSV file to current item.
Retrieves metadata based on 'description' parsed from input CSV file.
Adds to object and handles special keys:
- `description`: A new description for the item. Used to relabel items
based on the pre-determined description from fastq name or BAM... | [
"Add",
"metadata",
"information",
"from",
"CSV",
"file",
"to",
"current",
"item",
"."
] | python | train |
benzrf/parthial | parthial/context.py | https://github.com/benzrf/parthial/blob/ab1e316aec87ed34dda0ec0e145fe0c8cc8e907f/parthial/context.py#L51-L59 | def new_scope(self, new_scope={}):
"""Add a new innermost scope for the duration of the with block.
Args:
new_scope (dict-like): The scope to add.
"""
old_scopes, self.scopes = self.scopes, self.scopes.new_child(new_scope)
yield
self.scopes = old_scopes | [
"def",
"new_scope",
"(",
"self",
",",
"new_scope",
"=",
"{",
"}",
")",
":",
"old_scopes",
",",
"self",
".",
"scopes",
"=",
"self",
".",
"scopes",
",",
"self",
".",
"scopes",
".",
"new_child",
"(",
"new_scope",
")",
"yield",
"self",
".",
"scopes",
"="... | Add a new innermost scope for the duration of the with block.
Args:
new_scope (dict-like): The scope to add. | [
"Add",
"a",
"new",
"innermost",
"scope",
"for",
"the",
"duration",
"of",
"the",
"with",
"block",
"."
] | python | train |
genepattern/genepattern-python | gp/modules.py | https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/modules.py#L665-L691 | def register(self, task_spec):
"""
Registers a module specification with the LSID authority.
Validates that it possesses an LSID assigned by the authority.
Raises an exception if registration wasn't successful.
:param task_spec:
:return: boolean - True if registration was... | [
"def",
"register",
"(",
"self",
",",
"task_spec",
")",
":",
"if",
"self",
".",
"validate",
"(",
"task_spec",
".",
"lsid",
")",
":",
"# Add the module name to the map",
"self",
".",
"registered_modules",
"[",
"task_spec",
".",
"lsid",
"]",
"=",
"task_spec",
"... | Registers a module specification with the LSID authority.
Validates that it possesses an LSID assigned by the authority.
Raises an exception if registration wasn't successful.
:param task_spec:
:return: boolean - True if registration was successful | [
"Registers",
"a",
"module",
"specification",
"with",
"the",
"LSID",
"authority",
".",
"Validates",
"that",
"it",
"possesses",
"an",
"LSID",
"assigned",
"by",
"the",
"authority",
".",
"Raises",
"an",
"exception",
"if",
"registration",
"wasn",
"t",
"successful",
... | python | train |
numenta/htmresearch | htmresearch/algorithms/column_pooler.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L643-L655 | def _sampleRange(rng, start, end, step, k):
"""
Equivalent to:
random.sample(xrange(start, end, step), k)
except it uses our random number generator.
This wouldn't need to create the arange if it were implemented in C.
"""
array = numpy.empty(k, dtype="uint32")
rng.sample(numpy.arange(start, end, ste... | [
"def",
"_sampleRange",
"(",
"rng",
",",
"start",
",",
"end",
",",
"step",
",",
"k",
")",
":",
"array",
"=",
"numpy",
".",
"empty",
"(",
"k",
",",
"dtype",
"=",
"\"uint32\"",
")",
"rng",
".",
"sample",
"(",
"numpy",
".",
"arange",
"(",
"start",
",... | Equivalent to:
random.sample(xrange(start, end, step), k)
except it uses our random number generator.
This wouldn't need to create the arange if it were implemented in C. | [
"Equivalent",
"to",
":"
] | python | train |
gmr/rejected | rejected/consumer.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L532-L550 | def require_setting(self, name, feature='this feature'):
"""Raises an exception if the given app setting is not defined.
As a generalization, this method should called from a Consumer's
:py:meth:`~rejected.consumer.Consumer.initialize` method. If a required
setting is not found, this me... | [
"def",
"require_setting",
"(",
"self",
",",
"name",
",",
"feature",
"=",
"'this feature'",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"settings",
":",
"raise",
"ConfigurationException",
"(",
"\"You must define the '{}' setting in your \"",
"\"application to use... | Raises an exception if the given app setting is not defined.
As a generalization, this method should called from a Consumer's
:py:meth:`~rejected.consumer.Consumer.initialize` method. If a required
setting is not found, this method will cause the
consumer to shutdown prior to receiving ... | [
"Raises",
"an",
"exception",
"if",
"the",
"given",
"app",
"setting",
"is",
"not",
"defined",
"."
] | python | train |
googleapis/oauth2client | oauth2client/contrib/keyring_storage.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/keyring_storage.py#L62-L78 | def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
credentials = None
content = keyring.get_password(self._service_name, self._user_name)
if content is not None:
try:
credentials =... | [
"def",
"locked_get",
"(",
"self",
")",
":",
"credentials",
"=",
"None",
"content",
"=",
"keyring",
".",
"get_password",
"(",
"self",
".",
"_service_name",
",",
"self",
".",
"_user_name",
")",
"if",
"content",
"is",
"not",
"None",
":",
"try",
":",
"creden... | Retrieve Credential from file.
Returns:
oauth2client.client.Credentials | [
"Retrieve",
"Credential",
"from",
"file",
"."
] | python | valid |
theislab/scanpy | scanpy/neighbors/__init__.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/neighbors/__init__.py#L579-L661 | def compute_neighbors(
self,
n_neighbors: int = 30,
knn: bool = True,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
method: str = 'umap',
random_state: Optional[Union[RandomState, int]] = 0,
write_knn_indices: bool = False,
metric: st... | [
"def",
"compute_neighbors",
"(",
"self",
",",
"n_neighbors",
":",
"int",
"=",
"30",
",",
"knn",
":",
"bool",
"=",
"True",
",",
"n_pcs",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"use_rep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",... | \
Compute distances and connectivities of neighbors.
Parameters
----------
n_neighbors
Use this number of nearest neighbors.
knn
Restrict result to `n_neighbors` nearest neighbors.
{n_pcs}
{use_rep}
Returns
-------
... | [
"\\",
"Compute",
"distances",
"and",
"connectivities",
"of",
"neighbors",
"."
] | python | train |
nathancahill/mimicdb | mimicdb/s3/bucket.py | https://github.com/nathancahill/mimicdb/blob/9d0e8ebcba31d937f73752f9b88e5a4fec860765/mimicdb/s3/bucket.py#L102-L127 | def list(self, *args, **kwargs):
"""Return an iterable of keys from MimicDB.
:param boolean force: If true, API call is forced to S3
"""
if kwargs.pop('force', None):
headers = kwargs.get('headers', args[4] if len(args) > 4 else None) or dict()
headers['force'] =... | [
"def",
"list",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"'force'",
",",
"None",
")",
":",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"args",
"[",
"4",
"]",
"if",
"len",... | Return an iterable of keys from MimicDB.
:param boolean force: If true, API call is forced to S3 | [
"Return",
"an",
"iterable",
"of",
"keys",
"from",
"MimicDB",
"."
] | python | valid |
pantsbuild/pants | src/python/pants/cache/cache_setup.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/cache/cache_setup.py#L175-L185 | def get_write_cache(self):
"""Returns the write cache for this setup, creating it if necessary.
Returns None if no write cache is configured.
"""
if self._options.write_to and not self._write_cache:
cache_spec = self._resolve(self._sanitize_cache_spec(self._options.write_to))
if cache_spec:... | [
"def",
"get_write_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"_options",
".",
"write_to",
"and",
"not",
"self",
".",
"_write_cache",
":",
"cache_spec",
"=",
"self",
".",
"_resolve",
"(",
"self",
".",
"_sanitize_cache_spec",
"(",
"self",
".",
"_optio... | Returns the write cache for this setup, creating it if necessary.
Returns None if no write cache is configured. | [
"Returns",
"the",
"write",
"cache",
"for",
"this",
"setup",
"creating",
"it",
"if",
"necessary",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/agent/topo_disc/topo_disc.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/agent/topo_disc/topo_disc.py#L135-L140 | def remote_sys_desc_uneq_store(self, remote_system_desc):
"""This function saves the system desc, if different from stored. """
if remote_system_desc != self.remote_system_desc:
self.remote_system_desc = remote_system_desc
return True
return False | [
"def",
"remote_sys_desc_uneq_store",
"(",
"self",
",",
"remote_system_desc",
")",
":",
"if",
"remote_system_desc",
"!=",
"self",
".",
"remote_system_desc",
":",
"self",
".",
"remote_system_desc",
"=",
"remote_system_desc",
"return",
"True",
"return",
"False"
] | This function saves the system desc, if different from stored. | [
"This",
"function",
"saves",
"the",
"system",
"desc",
"if",
"different",
"from",
"stored",
"."
] | python | train |
mixcloud/django-experiments | experiments/admin_utils.py | https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/admin_utils.py#L61-L82 | def points_with_surrounding_gaps(points):
"""
This function makes sure that any gaps in the sequence provided have stopper points at their beginning
and end so a graph will be drawn with correct 0 ranges. This is more efficient than filling in all points
up to the maximum value. For example:
input:... | [
"def",
"points_with_surrounding_gaps",
"(",
"points",
")",
":",
"points_with_gaps",
"=",
"[",
"]",
"last_point",
"=",
"-",
"1",
"for",
"point",
"in",
"points",
":",
"if",
"last_point",
"+",
"1",
"==",
"point",
":",
"pass",
"elif",
"last_point",
"+",
"2",
... | This function makes sure that any gaps in the sequence provided have stopper points at their beginning
and end so a graph will be drawn with correct 0 ranges. This is more efficient than filling in all points
up to the maximum value. For example:
input: [1,2,3,10,11,13]
output [1,2,3,4,9,10,11,12,13] | [
"This",
"function",
"makes",
"sure",
"that",
"any",
"gaps",
"in",
"the",
"sequence",
"provided",
"have",
"stopper",
"points",
"at",
"their",
"beginning",
"and",
"end",
"so",
"a",
"graph",
"will",
"be",
"drawn",
"with",
"correct",
"0",
"ranges",
".",
"This"... | python | train |
tonybaloney/wily | wily/cache.py | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L236-L252 | def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: The index data
:... | [
"def",
"get_archiver_index",
"(",
"config",
",",
"archiver",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
"with",
"(",
"root",
"/",
"\"index.json\"",
")",
".",
"open",
"(",
"\"r\"",
")",
"as",
"... | Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: The index data
:rtype: ``dict`` | [
"Get",
"the",
"contents",
"of",
"the",
"archiver",
"index",
"file",
"."
] | python | train |
twilio/twilio-python | twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py#L194-L207 | def get_instance(self, payload):
"""
Build an instance of DependentHostedNumberOrderInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance
:... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"DependentHostedNumberOrderInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"signing_document_sid",
"=",
"self",
".",
"_solution",
"[",
"'signing_document_sid'",
"]",
",",
")"
] | Build an instance of DependentHostedNumberOrderInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance
:rtype: twilio.rest.preview.hosted_numbers.authorizati... | [
"Build",
"an",
"instance",
"of",
"DependentHostedNumberOrderInstance"
] | python | train |
emlazzarin/acrylic | acrylic/datatable.py | https://github.com/emlazzarin/acrylic/blob/08c6702d73b9660ead1024653f4fa016f6340e46/acrylic/datatable.py#L486-L507 | def apply(self, func, *fields):
"""
Applies the function, `func`, to every row in the DataTable.
If no fields are supplied, the entire row is passed to `func`.
If fields are supplied, the values at all of those fields
are passed into func in that order.
---
data[... | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"fields",
")",
":",
"results",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
":",
"if",
"not",
"fields",
":",
"results",
".",
"append",
"(",
"func",
"(",
"row",
")",
")",
"else",
":",
"if",
"any"... | Applies the function, `func`, to every row in the DataTable.
If no fields are supplied, the entire row is passed to `func`.
If fields are supplied, the values at all of those fields
are passed into func in that order.
---
data['diff'] = data.apply(short_diff, 'old_count', 'new_c... | [
"Applies",
"the",
"function",
"func",
"to",
"every",
"row",
"in",
"the",
"DataTable",
"."
] | python | train |
anomaly/prestans | prestans/parser/parameter_set.py | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/parser/parameter_set.py#L56-L90 | def blueprint(self):
"""
blueprint support, returns a partial dictionary
"""
blueprint = dict()
blueprint['type'] = "%s.%s" % (self.__module__, self.__class__.__name__)
# Fields
fields = dict()
# inspects the attributes of a parameter set and tries to v... | [
"def",
"blueprint",
"(",
"self",
")",
":",
"blueprint",
"=",
"dict",
"(",
")",
"blueprint",
"[",
"'type'",
"]",
"=",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"# Fields",
"fields",
"=",
"dict... | blueprint support, returns a partial dictionary | [
"blueprint",
"support",
"returns",
"a",
"partial",
"dictionary"
] | python | train |
ulf1/oxyba | oxyba/clean_german_date.py | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_german_date.py#L2-L61 | def clean_german_date(x):
"""Convert a string with a German date 'DD.MM.YYYY' to Datetime objects
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a German formated date,
or an array of these strings, e.g. list, ndarray, df.
Returns
----... | [
"def",
"clean_german_date",
"(",
"x",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"from",
"datetime",
"import",
"datetime",
"def",
"proc_elem",
"(",
"e",
")",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"e",
... | Convert a string with a German date 'DD.MM.YYYY' to Datetime objects
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a German formated date,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, num... | [
"Convert",
"a",
"string",
"with",
"a",
"German",
"date",
"DD",
".",
"MM",
".",
"YYYY",
"to",
"Datetime",
"objects"
] | python | train |
twisted/mantissa | xmantissa/signup.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/signup.py#L213-L220 | def attemptByKey(self, key):
"""
Locate the L{_PasswordResetAttempt} that corresponds to C{key}
"""
return self.store.findUnique(_PasswordResetAttempt,
_PasswordResetAttempt.key == key,
default=None) | [
"def",
"attemptByKey",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"store",
".",
"findUnique",
"(",
"_PasswordResetAttempt",
",",
"_PasswordResetAttempt",
".",
"key",
"==",
"key",
",",
"default",
"=",
"None",
")"
] | Locate the L{_PasswordResetAttempt} that corresponds to C{key} | [
"Locate",
"the",
"L",
"{",
"_PasswordResetAttempt",
"}",
"that",
"corresponds",
"to",
"C",
"{",
"key",
"}"
] | python | train |
bcbio/bcbio-nextgen | bcbio/ngsalign/alignprep.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L281-L292 | def total_reads_from_grabix(in_file):
"""Retrieve total reads in a fastq file from grabix index.
"""
gbi_file = _get_grabix_index(in_file)
if gbi_file:
with open(gbi_file) as in_handle:
next(in_handle) # throw away
num_lines = int(next(in_handle).strip())
assert ... | [
"def",
"total_reads_from_grabix",
"(",
"in_file",
")",
":",
"gbi_file",
"=",
"_get_grabix_index",
"(",
"in_file",
")",
"if",
"gbi_file",
":",
"with",
"open",
"(",
"gbi_file",
")",
"as",
"in_handle",
":",
"next",
"(",
"in_handle",
")",
"# throw away",
"num_line... | Retrieve total reads in a fastq file from grabix index. | [
"Retrieve",
"total",
"reads",
"in",
"a",
"fastq",
"file",
"from",
"grabix",
"index",
"."
] | python | train |
peterbrittain/asciimatics | asciimatics/scene.py | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/scene.py#L39-L60 | def reset(self, old_scene=None, screen=None):
"""
Reset the scene ready for playing.
:param old_scene: The previous version of this Scene that was running before the
application reset - e.g. due to a screen resize.
:param screen: New screen to use if old_scene is not None.
... | [
"def",
"reset",
"(",
"self",
",",
"old_scene",
"=",
"None",
",",
"screen",
"=",
"None",
")",
":",
"# Always reset all the effects.",
"for",
"effect",
"in",
"self",
".",
"_effects",
":",
"effect",
".",
"reset",
"(",
")",
"# If we have an old Scene to recreate, ge... | Reset the scene ready for playing.
:param old_scene: The previous version of this Scene that was running before the
application reset - e.g. due to a screen resize.
:param screen: New screen to use if old_scene is not None. | [
"Reset",
"the",
"scene",
"ready",
"for",
"playing",
"."
] | python | train |
shoebot/shoebot | lib/sbaudio/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/sbaudio/__init__.py#L14-L34 | def fft_bandpassfilter(data, fs, lowcut, highcut):
"""
http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801
"""
fft = np.fft.fft(data)
# n = len(data)
# timestep = 1.0 / fs
# freq = np.fft.fftfreq(n, d=timestep)
bp = fft.copy()
# Zero out fft coefficie... | [
"def",
"fft_bandpassfilter",
"(",
"data",
",",
"fs",
",",
"lowcut",
",",
"highcut",
")",
":",
"fft",
"=",
"np",
".",
"fft",
".",
"fft",
"(",
"data",
")",
"# n = len(data)",
"# timestep = 1.0 / fs",
"# freq = np.fft.fftfreq(n, d=timestep)",
"bp",
"=",
"fft",
".... | http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801 | [
"http",
":",
"//",
"www",
".",
"swharden",
".",
"com",
"/",
"blog",
"/",
"2009",
"-",
"01",
"-",
"21",
"-",
"signal",
"-",
"filtering",
"-",
"with",
"-",
"python",
"/",
"#comment",
"-",
"16801"
] | python | valid |
materialsproject/pymatgen | pymatgen/io/abinit/qadapters.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/qadapters.py#L750-L774 | def validate(self):
"""Validate the parameters of the run. Raises self.Error if invalid parameters."""
errors = []
app = errors.append
if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores:
app("self.hint_cores >= mpi_procs * omp_threads >= self.min_c... | [
"def",
"validate",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"]",
"app",
"=",
"errors",
".",
"append",
"if",
"not",
"self",
".",
"hint_cores",
">=",
"self",
".",
"mpi_procs",
"*",
"self",
".",
"omp_threads",
">=",
"self",
".",
"min_cores",
":",
"app... | Validate the parameters of the run. Raises self.Error if invalid parameters. | [
"Validate",
"the",
"parameters",
"of",
"the",
"run",
".",
"Raises",
"self",
".",
"Error",
"if",
"invalid",
"parameters",
"."
] | python | train |
jldantas/libmft | libmft/attribute.py | https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/attribute.py#L1025-L1031 | def _from_binary_volname(cls, binary_stream):
"""See base class."""
name = binary_stream.tobytes().decode("utf_16_le")
_MOD_LOGGER.debug("Attempted to unpack VOLUME_NAME Entry from \"%s\"\nResult: %s", binary_stream.tobytes(), name)
return cls(name) | [
"def",
"_from_binary_volname",
"(",
"cls",
",",
"binary_stream",
")",
":",
"name",
"=",
"binary_stream",
".",
"tobytes",
"(",
")",
".",
"decode",
"(",
"\"utf_16_le\"",
")",
"_MOD_LOGGER",
".",
"debug",
"(",
"\"Attempted to unpack VOLUME_NAME Entry from \\\"%s\\\"\\nRe... | See base class. | [
"See",
"base",
"class",
"."
] | python | train |
theislab/scanpy | scanpy/tools/_sim.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/tools/_sim.py#L798-L803 | def process_rule(self,rule,pa,tuple):
''' Process a string that denotes a boolean rule.
'''
for i,v in enumerate(tuple):
rule = rule.replace(pa[i],str(v))
return eval(rule) | [
"def",
"process_rule",
"(",
"self",
",",
"rule",
",",
"pa",
",",
"tuple",
")",
":",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"tuple",
")",
":",
"rule",
"=",
"rule",
".",
"replace",
"(",
"pa",
"[",
"i",
"]",
",",
"str",
"(",
"v",
")",
")"... | Process a string that denotes a boolean rule. | [
"Process",
"a",
"string",
"that",
"denotes",
"a",
"boolean",
"rule",
"."
] | python | train |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L233-L266 | def get_post_by_id(self, post_id):
"""
Fetch the blog post given by ``post_id``
:param post_id: The post identifier for the blog post
:type post_id: str
:return: If the ``post_id`` is valid, the post data is retrieved, else
returns ``None``.
"""
r = None... | [
"def",
"get_post_by_id",
"(",
"self",
",",
"post_id",
")",
":",
"r",
"=",
"None",
"post_id",
"=",
"_as_int",
"(",
"post_id",
")",
"with",
"self",
".",
"_engine",
".",
"begin",
"(",
")",
"as",
"conn",
":",
"try",
":",
"post_statement",
"=",
"sqla",
".... | Fetch the blog post given by ``post_id``
:param post_id: The post identifier for the blog post
:type post_id: str
:return: If the ``post_id`` is valid, the post data is retrieved, else
returns ``None``. | [
"Fetch",
"the",
"blog",
"post",
"given",
"by",
"post_id"
] | python | train |
python-openxml/python-docx | docx/image/tiff.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/image/tiff.py#L318-L326 | def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
"""
Return the long int value contained in the *value_offset* field of
this entry. Only supports single values at present.
"""
if value_count == 1:
return stream_rdr.read_long(offset, 8)
els... | [
"def",
"_parse_value",
"(",
"cls",
",",
"stream_rdr",
",",
"offset",
",",
"value_count",
",",
"value_offset",
")",
":",
"if",
"value_count",
"==",
"1",
":",
"return",
"stream_rdr",
".",
"read_long",
"(",
"offset",
",",
"8",
")",
"else",
":",
"# pragma: no ... | Return the long int value contained in the *value_offset* field of
this entry. Only supports single values at present. | [
"Return",
"the",
"long",
"int",
"value",
"contained",
"in",
"the",
"*",
"value_offset",
"*",
"field",
"of",
"this",
"entry",
".",
"Only",
"supports",
"single",
"values",
"at",
"present",
"."
] | python | train |
apache/incubator-superset | superset/connectors/base/models.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L148-L159 | def short_data(self):
"""Data representation of the datasource sent to the frontend"""
return {
'edit_url': self.url,
'id': self.id,
'uid': self.uid,
'schema': self.schema,
'name': self.name,
'type': self.type,
'connecti... | [
"def",
"short_data",
"(",
"self",
")",
":",
"return",
"{",
"'edit_url'",
":",
"self",
".",
"url",
",",
"'id'",
":",
"self",
".",
"id",
",",
"'uid'",
":",
"self",
".",
"uid",
",",
"'schema'",
":",
"self",
".",
"schema",
",",
"'name'",
":",
"self",
... | Data representation of the datasource sent to the frontend | [
"Data",
"representation",
"of",
"the",
"datasource",
"sent",
"to",
"the",
"frontend"
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/rml/processor.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/processor.py#L1010-L1128 | def execute(self, triple_map, output, **kwargs):
"""Execute """
subjects = []
if NS_MGR.ql.JSON.rdflib in \
triple_map.logicalSource.reference_formulations:
output_format = "json"
else:
output_format = "xml"
if 'limit' not in kwargs:
... | [
"def",
"execute",
"(",
"self",
",",
"triple_map",
",",
"output",
",",
"*",
"*",
"kwargs",
")",
":",
"subjects",
"=",
"[",
"]",
"if",
"NS_MGR",
".",
"ql",
".",
"JSON",
".",
"rdflib",
"in",
"triple_map",
".",
"logicalSource",
".",
"reference_formulations",... | Execute | [
"Execute"
] | python | train |
google/grr | grr/server/grr_response_server/aff4_objects/filestore.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/filestore.py#L636-L660 | def Run(self):
"""Create FileStore and HashFileStore namespaces."""
if not data_store.AFF4Enabled():
return
try:
filestore = aff4.FACTORY.Create(
FileStore.PATH, FileStore, mode="rw", token=aff4.FACTORY.root_token)
filestore.Close()
hash_filestore = aff4.FACTORY.Create(
... | [
"def",
"Run",
"(",
"self",
")",
":",
"if",
"not",
"data_store",
".",
"AFF4Enabled",
"(",
")",
":",
"return",
"try",
":",
"filestore",
"=",
"aff4",
".",
"FACTORY",
".",
"Create",
"(",
"FileStore",
".",
"PATH",
",",
"FileStore",
",",
"mode",
"=",
"\"rw... | Create FileStore and HashFileStore namespaces. | [
"Create",
"FileStore",
"and",
"HashFileStore",
"namespaces",
"."
] | python | train |
rbw/pysnow | pysnow/query_builder.py | https://github.com/rbw/pysnow/blob/87c8ce0d3a089c2f59247f30efbd545fcdb8e985/pysnow/query_builder.py#L87-L100 | def equals(self, data):
"""Adds new `IN` or `=` condition depending on if a list or string was provided
:param data: string or list of values
:raise:
- QueryTypeError: if `data` is of an unexpected type
"""
if isinstance(data, six.string_types):
return s... | [
"def",
"equals",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"return",
"self",
".",
"_add_condition",
"(",
"'='",
",",
"data",
",",
"types",
"=",
"[",
"int",
",",
"str",
"]",
")",
... | Adds new `IN` or `=` condition depending on if a list or string was provided
:param data: string or list of values
:raise:
- QueryTypeError: if `data` is of an unexpected type | [
"Adds",
"new",
"IN",
"or",
"=",
"condition",
"depending",
"on",
"if",
"a",
"list",
"or",
"string",
"was",
"provided"
] | python | train |
althonos/InstaLooter | instalooter/batch.py | https://github.com/althonos/InstaLooter/blob/e894d8da368dd57423dd0fda4ac479ea2ea0c3c1/instalooter/batch.py#L120-L128 | def run_all(self):
# type: () -> None
"""Run all the jobs specified in the configuration file.
"""
logger.debug("Creating batch session")
session = Session()
for section_id in self.parser.sections():
self.run_job(section_id, session=session) | [
"def",
"run_all",
"(",
"self",
")",
":",
"# type: () -> None",
"logger",
".",
"debug",
"(",
"\"Creating batch session\"",
")",
"session",
"=",
"Session",
"(",
")",
"for",
"section_id",
"in",
"self",
".",
"parser",
".",
"sections",
"(",
")",
":",
"self",
".... | Run all the jobs specified in the configuration file. | [
"Run",
"all",
"the",
"jobs",
"specified",
"in",
"the",
"configuration",
"file",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/stanzaprocessor.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L277-L300 | def process_message(self, stanza):
"""Process message stanza.
Pass it to a handler of the stanza's type and payload namespace.
If no handler for the actual stanza type succeeds then hadlers
for type "normal" are used.
:Parameters:
- `stanza`: message stanza to be ha... | [
"def",
"process_message",
"(",
"self",
",",
"stanza",
")",
":",
"stanza_type",
"=",
"stanza",
".",
"stanza_type",
"if",
"stanza_type",
"is",
"None",
":",
"stanza_type",
"=",
"\"normal\"",
"if",
"self",
".",
"__try_handlers",
"(",
"self",
".",
"_message_handler... | Process message stanza.
Pass it to a handler of the stanza's type and payload namespace.
If no handler for the actual stanza type succeeds then hadlers
for type "normal" are used.
:Parameters:
- `stanza`: message stanza to be handled | [
"Process",
"message",
"stanza",
"."
] | python | valid |
smarie/python-parsyfiles | parsyfiles/parsing_registries.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L922-L930 | def get_all_conversion_chains_to_type(self, to_type: Type[Any])\
-> Tuple[List[Converter], List[Converter], List[Converter]]:
"""
Utility method to find all converters to a given type
:param to_type:
:return:
"""
return self.get_all_conversion_chains(to_type=... | [
"def",
"get_all_conversion_chains_to_type",
"(",
"self",
",",
"to_type",
":",
"Type",
"[",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Converter",
"]",
",",
"List",
"[",
"Converter",
"]",
",",
"List",
"[",
"Converter",
"]",
"]",
":",
"return",
"... | Utility method to find all converters to a given type
:param to_type:
:return: | [
"Utility",
"method",
"to",
"find",
"all",
"converters",
"to",
"a",
"given",
"type"
] | python | train |
spacetelescope/drizzlepac | drizzlepac/alignimages.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L868-L897 | def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for ca... | [
"def",
"generate_astrometric_catalog",
"(",
"imglist",
",",
"*",
"*",
"pars",
")",
":",
"# generate catalog",
"temp_pars",
"=",
"pars",
".",
"copy",
"(",
")",
"if",
"pars",
"[",
"'output'",
"]",
"==",
"True",
":",
"pars",
"[",
"'output'",
"]",
"=",
"'ref... | Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table :... | [
"Generates",
"a",
"catalog",
"of",
"all",
"sources",
"from",
"an",
"existing",
"astrometric",
"catalog",
"are",
"in",
"or",
"near",
"the",
"FOVs",
"of",
"the",
"images",
"in",
"the",
"input",
"list",
"."
] | python | train |
flo-compbio/genometools | genometools/gdc/tcga.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/tcga.py#L174-L221 | def get_masked_cnv_manifest(tcga_id):
"""Get manifest for masked TCGA copy-number variation data.
Params
------
tcga_id : str
The TCGA project ID.
download_file : str
The path of the download file.
Returns
-------
`pandas.DataFrame`
The manifest.
... | [
"def",
"get_masked_cnv_manifest",
"(",
"tcga_id",
")",
":",
"payload",
"=",
"{",
"\"filters\"",
":",
"json",
".",
"dumps",
"(",
"{",
"\"op\"",
":",
"\"and\"",
",",
"\"content\"",
":",
"[",
"{",
"\"op\"",
":",
"\"in\"",
",",
"\"content\"",
":",
"{",
"\"fi... | Get manifest for masked TCGA copy-number variation data.
Params
------
tcga_id : str
The TCGA project ID.
download_file : str
The path of the download file.
Returns
-------
`pandas.DataFrame`
The manifest. | [
"Get",
"manifest",
"for",
"masked",
"TCGA",
"copy",
"-",
"number",
"variation",
"data",
".",
"Params",
"------",
"tcga_id",
":",
"str",
"The",
"TCGA",
"project",
"ID",
".",
"download_file",
":",
"str",
"The",
"path",
"of",
"the",
"download",
"file",
".",
... | python | train |
mmp2/megaman | megaman/geometry/rmetric.py | https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/geometry/rmetric.py#L270-L281 | def get_rmetric( self, mode_inv = 'svd', return_svd = False ):
"""
Compute the Reimannian Metric
"""
if self.H is None:
self.H, self.G, self.Hvv, self.Hsval = riemann_metric(self.Y, self.L, self.mdimG, invert_h = True, mode_inv = mode_inv)
if self.G is None:
... | [
"def",
"get_rmetric",
"(",
"self",
",",
"mode_inv",
"=",
"'svd'",
",",
"return_svd",
"=",
"False",
")",
":",
"if",
"self",
".",
"H",
"is",
"None",
":",
"self",
".",
"H",
",",
"self",
".",
"G",
",",
"self",
".",
"Hvv",
",",
"self",
".",
"Hsval",
... | Compute the Reimannian Metric | [
"Compute",
"the",
"Reimannian",
"Metric"
] | python | train |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1359-L1378 | def cmpabs(op1, op2):
"""
Compare the absolute values of op1 and op2.
Return a positive value if op1 > op2, zero if op1 = op2, and a negative
value if op1 < op2. Both op1 and op2 are considered to their full own
precision, which may differ. If one of the operands is NaN, raise
ValueError.
... | [
"def",
"cmpabs",
"(",
"op1",
",",
"op2",
")",
":",
"op1",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"op1",
")",
"op2",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"op2",
")",
"if",
"is_nan",
"(",
"op1",
")",
"or",
"is_nan",
"(",
"op2",
")",... | Compare the absolute values of op1 and op2.
Return a positive value if op1 > op2, zero if op1 = op2, and a negative
value if op1 < op2. Both op1 and op2 are considered to their full own
precision, which may differ. If one of the operands is NaN, raise
ValueError.
Note: This function may be useful ... | [
"Compare",
"the",
"absolute",
"values",
"of",
"op1",
"and",
"op2",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.