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 |
|---|---|---|---|---|---|---|---|---|
titusjan/argos | argos/qt/registrytable.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L184-L188 | def itemFromIndex(self, index):
""" Gets the item given the model index
"""
sourceIndex = self.mapToSource(index)
return self.sourceModel().itemFromIndex(sourceIndex) | [
"def",
"itemFromIndex",
"(",
"self",
",",
"index",
")",
":",
"sourceIndex",
"=",
"self",
".",
"mapToSource",
"(",
"index",
")",
"return",
"self",
".",
"sourceModel",
"(",
")",
".",
"itemFromIndex",
"(",
"sourceIndex",
")"
] | Gets the item given the model index | [
"Gets",
"the",
"item",
"given",
"the",
"model",
"index"
] | python | train |
Mollom/mollom_python | mollom/mollom.py | https://github.com/Mollom/mollom_python/blob/dfacb63fd79f82c0eabde76b511116df5b51d6f1/mollom/mollom.py#L211-L246 | def check_captcha(self,
captcha_id,
solution,
author_name=None,
author_url=None,
author_mail=None,
author_ip=None,
author_id=None,
author_o... | [
"def",
"check_captcha",
"(",
"self",
",",
"captcha_id",
",",
"solution",
",",
"author_name",
"=",
"None",
",",
"author_url",
"=",
"None",
",",
"author_mail",
"=",
"None",
",",
"author_ip",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"author_open_id",
... | Checks a CAPTCHA that was solved by the end-user.
Keyword arguments:
captcha_id -- Unique identifier of the CAPTCHA solved.
solution -- Solution provided by the end-user for the CAPTCHA.
author_name -- The name of the content author.
author_url -- The homepage/website URL of the... | [
"Checks",
"a",
"CAPTCHA",
"that",
"was",
"solved",
"by",
"the",
"end",
"-",
"user",
"."
] | python | train |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L194-L238 | def _connect(self):
"""Initialize an ldap client"""
ldap_client = ldap.initialize(self.uri)
ldap.set_option(ldap.OPT_REFERRALS, 0)
ldap.set_option(ldap.OPT_TIMEOUT, self.timeout)
if self.starttls == 'on':
ldap.set_option(ldap.OPT_X_TLS_DEMAND, True)
else:
... | [
"def",
"_connect",
"(",
"self",
")",
":",
"ldap_client",
"=",
"ldap",
".",
"initialize",
"(",
"self",
".",
"uri",
")",
"ldap",
".",
"set_option",
"(",
"ldap",
".",
"OPT_REFERRALS",
",",
"0",
")",
"ldap",
".",
"set_option",
"(",
"ldap",
".",
"OPT_TIMEOU... | Initialize an ldap client | [
"Initialize",
"an",
"ldap",
"client"
] | python | train |
pypa/pipenv | pipenv/vendor/jinja2/ext.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L119-L129 | def call_method(self, name, args=None, kwargs=None, dyn_args=None,
dyn_kwargs=None, lineno=None):
"""Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`.
"""
if args is None:
args = []
if kwargs is None... | [
"def",
"call_method",
"(",
"self",
",",
"name",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"dyn_args",
"=",
"None",
",",
"dyn_kwargs",
"=",
"None",
",",
"lineno",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
... | Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`. | [
"Call",
"a",
"method",
"of",
"the",
"extension",
".",
"This",
"is",
"a",
"shortcut",
"for",
":",
"meth",
":",
"attr",
"+",
":",
"class",
":",
"jinja2",
".",
"nodes",
".",
"Call",
"."
] | python | train |
fossasia/AYABInterface | AYABInterface/interaction.py | https://github.com/fossasia/AYABInterface/blob/e2065eed8daf17b2936f6ca5e488c9bfb850914e/AYABInterface/interaction.py#L47-L59 | def communicate_through(self, file):
"""Setup communication through a file.
:rtype: AYABInterface.communication.Communication
"""
if self._communication is not None:
raise ValueError("Already communicating.")
self._communication = communication = Communication(
... | [
"def",
"communicate_through",
"(",
"self",
",",
"file",
")",
":",
"if",
"self",
".",
"_communication",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Already communicating.\"",
")",
"self",
".",
"_communication",
"=",
"communication",
"=",
"Communicati... | Setup communication through a file.
:rtype: AYABInterface.communication.Communication | [
"Setup",
"communication",
"through",
"a",
"file",
"."
] | python | train |
hsolbrig/pyjsg | pyjsg/jsglib/jsg_object.py | https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/jsglib/jsg_object.py#L133-L140 | def _default(self, obj: object):
""" Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj
"""
return None if obj is JSGNull else obj.val if type(obj) is AnyType else \
JSGObject.... | [
"def",
"_default",
"(",
"self",
",",
"obj",
":",
"object",
")",
":",
"return",
"None",
"if",
"obj",
"is",
"JSGNull",
"else",
"obj",
".",
"val",
"if",
"type",
"(",
"obj",
")",
"is",
"AnyType",
"else",
"JSGObject",
".",
"_strip_nones",
"(",
"obj",
".",... | Return a serializable version of obj. Overrides JsonObj _default method
:param obj: Object to be serialized
:return: Serialized version of obj | [
"Return",
"a",
"serializable",
"version",
"of",
"obj",
".",
"Overrides",
"JsonObj",
"_default",
"method",
":",
"param",
"obj",
":",
"Object",
"to",
"be",
"serialized",
":",
"return",
":",
"Serialized",
"version",
"of",
"obj"
] | python | train |
rocky/python3-trepan | trepan/processor/command/base_submgr.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_submgr.py#L107-L162 | def help(self, args):
"""Give help for a command which has subcommands. This can be
called in several ways:
help cmd
help cmd subcmd
help cmd commands
Our shtick is to give help for the overall command only if
subcommand or 'commands' is not given. If... | [
"def",
"help",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<=",
"2",
":",
"# \"help cmd\". Give the general help for the command part.",
"doc",
"=",
"self",
".",
"__doc__",
"or",
"self",
".",
"run",
".",
"__doc__",
"if",
"doc",
":",... | Give help for a command which has subcommands. This can be
called in several ways:
help cmd
help cmd subcmd
help cmd commands
Our shtick is to give help for the overall command only if
subcommand or 'commands' is not given. If a subcommand is given and
... | [
"Give",
"help",
"for",
"a",
"command",
"which",
"has",
"subcommands",
".",
"This",
"can",
"be",
"called",
"in",
"several",
"ways",
":",
"help",
"cmd",
"help",
"cmd",
"subcmd",
"help",
"cmd",
"commands"
] | python | test |
inspirehep/harvesting-kit | harvestingkit/oup_package.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/oup_package.py#L79-L101 | def connect(self):
"""Logs into the specified ftp server and returns connector."""
for tried_connection_count in range(CFG_FTP_CONNECTION_ATTEMPTS):
try:
self.ftp = FtpHandler(self.config.OXFORD.URL,
self.config.OXFORD.LOGIN,
... | [
"def",
"connect",
"(",
"self",
")",
":",
"for",
"tried_connection_count",
"in",
"range",
"(",
"CFG_FTP_CONNECTION_ATTEMPTS",
")",
":",
"try",
":",
"self",
".",
"ftp",
"=",
"FtpHandler",
"(",
"self",
".",
"config",
".",
"OXFORD",
".",
"URL",
",",
"self",
... | Logs into the specified ftp server and returns connector. | [
"Logs",
"into",
"the",
"specified",
"ftp",
"server",
"and",
"returns",
"connector",
"."
] | python | valid |
twilio/twilio-python | twilio/rest/autopilot/v1/assistant/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/autopilot/v1/assistant/__init__.py#L388-L397 | def defaults(self):
"""
Access the defaults
:returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList
:rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList
"""
if self._defaults is None:
self._defaults = DefaultsList(self._version, assista... | [
"def",
"defaults",
"(",
"self",
")",
":",
"if",
"self",
".",
"_defaults",
"is",
"None",
":",
"self",
".",
"_defaults",
"=",
"DefaultsList",
"(",
"self",
".",
"_version",
",",
"assistant_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
... | Access the defaults
:returns: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList
:rtype: twilio.rest.autopilot.v1.assistant.defaults.DefaultsList | [
"Access",
"the",
"defaults"
] | python | train |
blockstack-packages/blockstack-gpg | blockstack_gpg/gpg.py | https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L703-L759 | def gpg_app_put_key( blockchain_id, appname, keyname, key_data, txid=None, immutable=False, proxy=None, wallet_keys=None, config_dir=None ):
"""
Put an application GPG key.
Stash the private key locally to an app-specific keyring.
Return {'status': True, 'key_url': ..., 'key_data': ...} on success
... | [
"def",
"gpg_app_put_key",
"(",
"blockchain_id",
",",
"appname",
",",
"keyname",
",",
"key_data",
",",
"txid",
"=",
"None",
",",
"immutable",
"=",
"False",
",",
"proxy",
"=",
"None",
",",
"wallet_keys",
"=",
"None",
",",
"config_dir",
"=",
"None",
")",
":... | Put an application GPG key.
Stash the private key locally to an app-specific keyring.
Return {'status': True, 'key_url': ..., 'key_data': ...} on success
Return {'error': ...} on error
If immutable is True, then store the data as an immutable entry (e.g. update the zonefile with the key hash)
... | [
"Put",
"an",
"application",
"GPG",
"key",
".",
"Stash",
"the",
"private",
"key",
"locally",
"to",
"an",
"app",
"-",
"specific",
"keyring",
"."
] | python | train |
jupyter-widgets/ipywidgets | ipywidgets/widgets/interaction.py | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L341-L354 | def widget_from_single_value(o):
"""Make widgets from single values, which can be used as parameter defaults."""
if isinstance(o, string_types):
return Text(value=unicode_type(o))
elif isinstance(o, bool):
return Checkbox(value=o)
elif isinstance(o, Integral):
... | [
"def",
"widget_from_single_value",
"(",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"string_types",
")",
":",
"return",
"Text",
"(",
"value",
"=",
"unicode_type",
"(",
"o",
")",
")",
"elif",
"isinstance",
"(",
"o",
",",
"bool",
")",
":",
"return"... | Make widgets from single values, which can be used as parameter defaults. | [
"Make",
"widgets",
"from",
"single",
"values",
"which",
"can",
"be",
"used",
"as",
"parameter",
"defaults",
"."
] | python | train |
WZBSocialScienceCenter/tmtoolkit | tmtoolkit/topicmod/model_stats.py | https://github.com/WZBSocialScienceCenter/tmtoolkit/blob/ca8b9d072e37ccc82b533f47d48bd9755722305b/tmtoolkit/topicmod/model_stats.py#L84-L91 | def get_most_salient_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
"""
Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from most to least salient. Optionally only
return the `n` most salient words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualiz... | [
"def",
"get_most_salient_words",
"(",
"vocab",
",",
"topic_word_distrib",
",",
"doc_topic_distrib",
",",
"doc_lengths",
",",
"n",
"=",
"None",
")",
":",
"return",
"_words_by_salience_score",
"(",
"vocab",
",",
"topic_word_distrib",
",",
"doc_topic_distrib",
",",
"do... | Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from most to least salient. Optionally only
return the `n` most salient words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models" | [
"Order",
"the",
"words",
"from",
"vocab",
"by",
"saliency",
"score",
"(",
"Chuang",
"et",
"al",
".",
"2012",
")",
"from",
"most",
"to",
"least",
"salient",
".",
"Optionally",
"only",
"return",
"the",
"n",
"most",
"salient",
"words",
"."
] | python | train |
RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L272-L302 | def create_sns_topic(self, region):
"""Creates an SNS topic if needed. Returns the ARN if the created SNS topic
Args:
region (str): Region name
Returns:
`str`
"""
sns = self.session.client('sns', region_name=region)
self.log.info('Creating SNS t... | [
"def",
"create_sns_topic",
"(",
"self",
",",
"region",
")",
":",
"sns",
"=",
"self",
".",
"session",
".",
"client",
"(",
"'sns'",
",",
"region_name",
"=",
"region",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Creating SNS topic for {}/{}'",
".",
"format",... | Creates an SNS topic if needed. Returns the ARN if the created SNS topic
Args:
region (str): Region name
Returns:
`str` | [
"Creates",
"an",
"SNS",
"topic",
"if",
"needed",
".",
"Returns",
"the",
"ARN",
"if",
"the",
"created",
"SNS",
"topic"
] | python | train |
SwissDataScienceCenter/renku-python | renku/cli/runner.py | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/runner.py#L77-L101 | def rerun(client, run, job):
"""Re-run existing workflow or tool using CWL runner."""
from renku.models.provenance import ProcessRun
activity = client.process_commmit()
if not isinstance(activity, ProcessRun):
click.secho('No tool was found.', fg='red', file=sys.stderr)
return
try:... | [
"def",
"rerun",
"(",
"client",
",",
"run",
",",
"job",
")",
":",
"from",
"renku",
".",
"models",
".",
"provenance",
"import",
"ProcessRun",
"activity",
"=",
"client",
".",
"process_commmit",
"(",
")",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Pro... | Re-run existing workflow or tool using CWL runner. | [
"Re",
"-",
"run",
"existing",
"workflow",
"or",
"tool",
"using",
"CWL",
"runner",
"."
] | python | train |
biocore/burrito-fillings | bfillings/cd_hit.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/cd_hit.py#L203-L208 | def _get_result_paths(self, data):
"""Return dict of {key: ResultPath}"""
result = {}
result['FASTA'] = ResultPath(Path=self._get_seqs_outfile())
result['CLSTR'] = ResultPath(Path=self._get_clstr_outfile())
return result | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"result",
"[",
"'FASTA'",
"]",
"=",
"ResultPath",
"(",
"Path",
"=",
"self",
".",
"_get_seqs_outfile",
"(",
")",
")",
"result",
"[",
"'CLSTR'",
"]",
"=",
"ResultPat... | Return dict of {key: ResultPath} | [
"Return",
"dict",
"of",
"{",
"key",
":",
"ResultPath",
"}"
] | python | train |
belbio/bel | bel/db/arangodb.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L62-L87 | def get_client(host=None, port=None, username=None, password=None, enable_logging=True):
"""Get arango client and edgestore db handle"""
host = utils.first_true(
[host, config["bel_api"]["servers"]["arangodb_host"], "localhost"]
)
port = utils.first_true([port, config["bel_api"]["servers"]["ara... | [
"def",
"get_client",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"enable_logging",
"=",
"True",
")",
":",
"host",
"=",
"utils",
".",
"first_true",
"(",
"[",
"host",
",",
"config... | Get arango client and edgestore db handle | [
"Get",
"arango",
"client",
"and",
"edgestore",
"db",
"handle"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L6509-L6530 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'exclude_tags_completely'
) and self.exclude_tags_completely is not None:
_dict['exclude_tags_completely'] = self.exclude_tags_completely
if hasattr(self,... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'exclude_tags_completely'",
")",
"and",
"self",
".",
"exclude_tags_completely",
"is",
"not",
"None",
":",
"_dict",
"[",
"'exclude_tags_completely'",
"]",
"=... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
AustralianSynchrotron/lightflow | lightflow/models/dag.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/dag.py#L77-L100 | def define(self, schema, *, validate=True):
""" Store the task graph definition (schema).
The schema has to adhere to the following rules:
A key in the schema dict represents a parent task and the value one or more
children:
{parent: [child]} or {parent: [child1, child2]}
... | [
"def",
"define",
"(",
"self",
",",
"schema",
",",
"*",
",",
"validate",
"=",
"True",
")",
":",
"self",
".",
"_schema",
"=",
"schema",
"if",
"validate",
":",
"self",
".",
"validate",
"(",
"self",
".",
"make_graph",
"(",
"self",
".",
"_schema",
")",
... | Store the task graph definition (schema).
The schema has to adhere to the following rules:
A key in the schema dict represents a parent task and the value one or more
children:
{parent: [child]} or {parent: [child1, child2]}
The data output of one task can be routed to a l... | [
"Store",
"the",
"task",
"graph",
"definition",
"(",
"schema",
")",
"."
] | python | train |
python/performance | performance/compare.py | https://github.com/python/performance/blob/2a9524c0a5714e85106671bc61d750e800fe17db/performance/compare.py#L89-L103 | def tscore(sample1, sample2):
"""Calculate a t-test score for the difference between two samples.
Args:
sample1: one sample.
sample2: the other sample.
Returns:
The t-test score, as a float.
"""
if len(sample1) != len(sample2):
raise ValueError("different number of ... | [
"def",
"tscore",
"(",
"sample1",
",",
"sample2",
")",
":",
"if",
"len",
"(",
"sample1",
")",
"!=",
"len",
"(",
"sample2",
")",
":",
"raise",
"ValueError",
"(",
"\"different number of values\"",
")",
"error",
"=",
"pooled_sample_variance",
"(",
"sample1",
","... | Calculate a t-test score for the difference between two samples.
Args:
sample1: one sample.
sample2: the other sample.
Returns:
The t-test score, as a float. | [
"Calculate",
"a",
"t",
"-",
"test",
"score",
"for",
"the",
"difference",
"between",
"two",
"samples",
"."
] | python | test |
oscarlazoarjona/fast | fast/angular_momentum.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L365-L416 | def spherical_tensor(Ji, Jj, K, Q):
ur"""Return a matrix representation of the spherical tensor with quantum
numbers $J_i, J_j, K, Q$.
>>> from sympy import pprint
>>> pprint(spherical_tensor(1, 1, 1, 0))
⎡-√2 ⎤
⎢──── 0 0 ⎥
⎢ 2 ⎥
⎢ ⎥
⎢ 0 0 0 ⎥
⎢ ... | [
"def",
"spherical_tensor",
"(",
"Ji",
",",
"Jj",
",",
"K",
",",
"Q",
")",
":",
"keti",
"=",
"{",
"(",
"Ji",
",",
"Mi",
")",
":",
"Matrix",
"(",
"[",
"KroneckerDelta",
"(",
"i",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"2",
"*",
"Ji",
... | ur"""Return a matrix representation of the spherical tensor with quantum
numbers $J_i, J_j, K, Q$.
>>> from sympy import pprint
>>> pprint(spherical_tensor(1, 1, 1, 0))
⎡-√2 ⎤
⎢──── 0 0 ⎥
⎢ 2 ⎥
⎢ ⎥
⎢ 0 0 0 ⎥
⎢ ⎥
⎢ √2⎥
⎢ 0 0... | [
"ur",
"Return",
"a",
"matrix",
"representation",
"of",
"the",
"spherical",
"tensor",
"with",
"quantum",
"numbers",
"$J_i",
"J_j",
"K",
"Q$",
"."
] | python | train |
CellProfiler/centrosome | centrosome/cpmorphology.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/cpmorphology.py#L2479-L2592 | def euler_number(labels, indexes=None):
"""Calculate the Euler number of each label
labels - a label matrix
indexes - the indexes of the labels to measure or None to
treat the labels matrix as a binary matrix
"""
if indexes is None:
labels = labels != 0
indexes = n... | [
"def",
"euler_number",
"(",
"labels",
",",
"indexes",
"=",
"None",
")",
":",
"if",
"indexes",
"is",
"None",
":",
"labels",
"=",
"labels",
"!=",
"0",
"indexes",
"=",
"np",
".",
"array",
"(",
"[",
"1",
"]",
",",
"dtype",
"=",
"np",
".",
"int32",
")... | Calculate the Euler number of each label
labels - a label matrix
indexes - the indexes of the labels to measure or None to
treat the labels matrix as a binary matrix | [
"Calculate",
"the",
"Euler",
"number",
"of",
"each",
"label",
"labels",
"-",
"a",
"label",
"matrix",
"indexes",
"-",
"the",
"indexes",
"of",
"the",
"labels",
"to",
"measure",
"or",
"None",
"to",
"treat",
"the",
"labels",
"matrix",
"as",
"a",
"binary",
"m... | python | train |
shoebot/shoebot | lib/web/BeautifulSoup.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L278-L282 | def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._findOne(self.findPreviousSiblings, name, attrs, text,
**kw... | [
"def",
"findPreviousSibling",
"(",
"self",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
",",
"text",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_findOne",
"(",
"self",
".",
"findPreviousSiblings",
",",
"name",
"... | Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document. | [
"Returns",
"the",
"closest",
"sibling",
"to",
"this",
"Tag",
"that",
"matches",
"the",
"given",
"criteria",
"and",
"appears",
"before",
"this",
"Tag",
"in",
"the",
"document",
"."
] | python | valid |
DataONEorg/d1_python | client_cli/src/d1_cli/impl/command_parser.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_cli/src/d1_cli/impl/command_parser.py#L419-L428 | def do_archive(self, line):
"""archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived."""
pids = self._split_args(line, 1, -1)
self._command_processor.science_object_archive(pids)
self._print_info_if_verbose(
"Added archive operati... | [
"def",
"do_archive",
"(",
"self",
",",
"line",
")",
":",
"pids",
"=",
"self",
".",
"_split_args",
"(",
"line",
",",
"1",
",",
"-",
"1",
")",
"self",
".",
"_command_processor",
".",
"science_object_archive",
"(",
"pids",
")",
"self",
".",
"_print_info_if_... | archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived. | [
"archive",
"<identifier",
">",
"[",
"identifier",
"...",
"]",
"Mark",
"one",
"or",
"more",
"existing",
"Science",
"Objects",
"as",
"archived",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/base_node.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L643-L689 | def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False):
"""
Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_... | [
"def",
"_add_ubridge_ethernet_connection",
"(",
"self",
",",
"bridge_name",
",",
"ethernet_interface",
",",
"block_host_traffic",
"=",
"False",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
"and",
"block_host_traffic",
"is",
"Fa... | Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_traffic: block network traffic originating from the host OS (Windows only) | [
"Creates",
"a",
"connection",
"with",
"an",
"Ethernet",
"interface",
"in",
"uBridge",
"."
] | python | train |
jssimporter/python-jss | jss/contrib/mount_shares_better.py | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/contrib/mount_shares_better.py#L67-L94 | def mount_share_at_path(share_path, mount_path):
"""Mounts a share at the specified path
Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.
Returns:
The mount point or raises an error
"""
sh_url = CFURLCreateWithStr... | [
"def",
"mount_share_at_path",
"(",
"share_path",
",",
"mount_path",
")",
":",
"sh_url",
"=",
"CFURLCreateWithString",
"(",
"None",
",",
"share_path",
",",
"None",
")",
"mo_url",
"=",
"CFURLCreateWithString",
"(",
"None",
",",
"mount_path",
",",
"None",
")",
"#... | Mounts a share at the specified path
Args:
share_path: String URL with all auth info to connect to file share.
mount_path: Path to mount share on.
Returns:
The mount point or raises an error | [
"Mounts",
"a",
"share",
"at",
"the",
"specified",
"path"
] | python | train |
linuxsoftware/ls.joyous | ls/joyous/models/events.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L972-L979 | def prev_date(self):
"""
Date when this event last occurred in the local time zone
(Does not include postponements, but does exclude cancellations)
"""
prevDt = self.__localBefore(timezone.localtime(), dt.time.min)
if prevDt is not None:
return prevDt.date() | [
"def",
"prev_date",
"(",
"self",
")",
":",
"prevDt",
"=",
"self",
".",
"__localBefore",
"(",
"timezone",
".",
"localtime",
"(",
")",
",",
"dt",
".",
"time",
".",
"min",
")",
"if",
"prevDt",
"is",
"not",
"None",
":",
"return",
"prevDt",
".",
"date",
... | Date when this event last occurred in the local time zone
(Does not include postponements, but does exclude cancellations) | [
"Date",
"when",
"this",
"event",
"last",
"occurred",
"in",
"the",
"local",
"time",
"zone",
"(",
"Does",
"not",
"include",
"postponements",
"but",
"does",
"exclude",
"cancellations",
")"
] | python | train |
e-dard/postcodes | postcodes.py | https://github.com/e-dard/postcodes/blob/d63c47b4ecd765bc2e4e6ba34bc0b8a796f44005/postcodes.py#L22-L34 | def get(postcode):
"""
Request data associated with `postcode`.
:param postcode: the postcode to search for. The postcode may
contain spaces (they will be removed).
:returns: a dict of the nearest postcode's data or None if no
postcode data is found.
"""
po... | [
"def",
"get",
"(",
"postcode",
")",
":",
"postcode",
"=",
"quote",
"(",
"postcode",
".",
"replace",
"(",
"' '",
",",
"''",
")",
")",
"url",
"=",
"'%s/postcode/%s.json'",
"%",
"(",
"END_POINT",
",",
"postcode",
")",
"return",
"_get_json_resp",
"(",
"url",... | Request data associated with `postcode`.
:param postcode: the postcode to search for. The postcode may
contain spaces (they will be removed).
:returns: a dict of the nearest postcode's data or None if no
postcode data is found. | [
"Request",
"data",
"associated",
"with",
"postcode",
"."
] | python | train |
note35/sinon | sinon/lib/stub.py | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/stub.py#L187-L204 | def withArgs(self, *args, **kwargs): #pylint: disable=invalid-name
"""
Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified argument(s) into the condition list.
For example, when the stub function is called w... | [
"def",
"withArgs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#pylint: disable=invalid-name",
"cond_args",
"=",
"args",
"if",
"len",
"(",
"args",
")",
">",
"0",
"else",
"None",
"cond_kwargs",
"=",
"kwargs",
"if",
"len",
"(",
"kw... | Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified argument(s) into the condition list.
For example, when the stub function is called with argument 1, it will return "#":
stub.withArgs(1).returns("#")
... | [
"Adds",
"a",
"condition",
"for",
"when",
"the",
"stub",
"is",
"called",
".",
"When",
"the",
"condition",
"is",
"met",
"a",
"special",
"return",
"value",
"can",
"be",
"returned",
".",
"Adds",
"the",
"specified",
"argument",
"(",
"s",
")",
"into",
"the",
... | python | train |
Unidata/MetPy | metpy/interpolate/grid.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/interpolate/grid.py#L258-L335 | def interpolate_to_grid(x, y, z, interp_type='linear', hres=50000,
minimum_neighbors=3, gamma=0.25, kappa_star=5.052,
search_radius=None, rbf_func='linear', rbf_smooth=0,
boundary_coords=None):
r"""Interpolate given (x,y), observation (z) pairs... | [
"def",
"interpolate_to_grid",
"(",
"x",
",",
"y",
",",
"z",
",",
"interp_type",
"=",
"'linear'",
",",
"hres",
"=",
"50000",
",",
"minimum_neighbors",
"=",
"3",
",",
"gamma",
"=",
"0.25",
",",
"kappa_star",
"=",
"5.052",
",",
"search_radius",
"=",
"None",... | r"""Interpolate given (x,y), observation (z) pairs to a grid based on given parameters.
Parameters
----------
x: array_like
x coordinate
y: array_like
y coordinate
z: array_like
observation value
interp_type: str
What type of interpolation to use. Available optio... | [
"r",
"Interpolate",
"given",
"(",
"x",
"y",
")",
"observation",
"(",
"z",
")",
"pairs",
"to",
"a",
"grid",
"based",
"on",
"given",
"parameters",
"."
] | python | train |
subdownloader/subdownloader | subdownloader/video2.py | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/video2.py#L131-L138 | def get_osdb_hash(self):
"""
Get the hash of this local videofile
:return: hash as string
"""
if self._osdb_hash is None:
self._osdb_hash = self._calculate_osdb_hash()
return self._osdb_hash | [
"def",
"get_osdb_hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"_osdb_hash",
"is",
"None",
":",
"self",
".",
"_osdb_hash",
"=",
"self",
".",
"_calculate_osdb_hash",
"(",
")",
"return",
"self",
".",
"_osdb_hash"
] | Get the hash of this local videofile
:return: hash as string | [
"Get",
"the",
"hash",
"of",
"this",
"local",
"videofile",
":",
"return",
":",
"hash",
"as",
"string"
] | python | train |
lltk/lltk | lltk/nl/scrapers/uitmuntend.py | https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/nl/scrapers/uitmuntend.py#L60-L79 | def articles(self):
''' Tries to scrape the correct articles for singular and plural from uitmuntend.nl. '''
result = [None, None]
element = self._first('NN')
if element:
element = element.split('\r\n')[0]
if ' | ' in element:
# This means there is a plural
singular, plural = element.split(' | ')... | [
"def",
"articles",
"(",
"self",
")",
":",
"result",
"=",
"[",
"None",
",",
"None",
"]",
"element",
"=",
"self",
".",
"_first",
"(",
"'NN'",
")",
"if",
"element",
":",
"element",
"=",
"element",
".",
"split",
"(",
"'\\r\\n'",
")",
"[",
"0",
"]",
"... | Tries to scrape the correct articles for singular and plural from uitmuntend.nl. | [
"Tries",
"to",
"scrape",
"the",
"correct",
"articles",
"for",
"singular",
"and",
"plural",
"from",
"uitmuntend",
".",
"nl",
"."
] | python | train |
dagster-io/dagster | python_modules/dagster/dagster/core/types/field_utils.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/types/field_utils.py#L284-L308 | def PermissiveDict(fields=None):
'''A permissive dict will permit the user to partially specify the permitted fields. Any fields
that are specified and passed in will be type checked. Other fields will be allowed, but
will be ignored by the type checker.
'''
if fields:
check_user_facing_fie... | [
"def",
"PermissiveDict",
"(",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
":",
"check_user_facing_fields_dict",
"(",
"fields",
",",
"'PermissiveDict'",
")",
"class",
"_PermissiveDict",
"(",
"_ConfigComposite",
")",
":",
"def",
"__init__",
"(",
"self",
")",
... | A permissive dict will permit the user to partially specify the permitted fields. Any fields
that are specified and passed in will be type checked. Other fields will be allowed, but
will be ignored by the type checker. | [
"A",
"permissive",
"dict",
"will",
"permit",
"the",
"user",
"to",
"partially",
"specify",
"the",
"permitted",
"fields",
".",
"Any",
"fields",
"that",
"are",
"specified",
"and",
"passed",
"in",
"will",
"be",
"type",
"checked",
".",
"Other",
"fields",
"will",
... | python | test |
4degrees/riffle | source/riffle/model.py | https://github.com/4degrees/riffle/blob/e5a0d908df8c93ff1ee7abdda8875fd1667df53d/source/riffle/model.py#L191-L216 | def _fetchChildren(self):
'''Fetch and return new child items.'''
children = []
# List paths under this directory.
paths = []
for name in os.listdir(self.path):
paths.append(os.path.normpath(os.path.join(self.path, name)))
# Handle collections.
colle... | [
"def",
"_fetchChildren",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"# List paths under this directory.",
"paths",
"=",
"[",
"]",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
")",
":",
"paths",
".",
"append",
"(",
"os",
"... | Fetch and return new child items. | [
"Fetch",
"and",
"return",
"new",
"child",
"items",
"."
] | python | test |
night-crawler/django-docker-helpers | django_docker_helpers/utils.py | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L97-L140 | def dot_path(obj: t.Union[t.Dict, object],
path: str,
default: t.Any = None,
separator: str = '.'):
"""
Provides an access to elements of a mixed dict/object type by a delimiter-separated path.
::
class O1:
my_dict = {'a': {'b': 1}}
class ... | [
"def",
"dot_path",
"(",
"obj",
":",
"t",
".",
"Union",
"[",
"t",
".",
"Dict",
",",
"object",
"]",
",",
"path",
":",
"str",
",",
"default",
":",
"t",
".",
"Any",
"=",
"None",
",",
"separator",
":",
"str",
"=",
"'.'",
")",
":",
"path_items",
"=",... | Provides an access to elements of a mixed dict/object type by a delimiter-separated path.
::
class O1:
my_dict = {'a': {'b': 1}}
class O2:
def __init__(self):
self.nested = O1()
class O3:
final = O2()
o = O3()
assert uti... | [
"Provides",
"an",
"access",
"to",
"elements",
"of",
"a",
"mixed",
"dict",
"/",
"object",
"type",
"by",
"a",
"delimiter",
"-",
"separated",
"path",
".",
"::"
] | python | train |
CameronLonsdale/lantern | lantern/modules/shift.py | https://github.com/CameronLonsdale/lantern/blob/235e163e96bf0719d49c54204ee576b2ca93abb6/lantern/modules/shift.py#L48-L80 | def crack(ciphertext, *fitness_functions, min_key=0, max_key=26, shift_function=shift_case_english):
"""Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``.
Example:
>>> decryptions = crack("KHOOR", fitness.english.quadgrams)
>>> print(''.join(decryptions[0].plaintext))... | [
"def",
"crack",
"(",
"ciphertext",
",",
"*",
"fitness_functions",
",",
"min_key",
"=",
"0",
",",
"max_key",
"=",
"26",
",",
"shift_function",
"=",
"shift_case_english",
")",
":",
"if",
"min_key",
">=",
"max_key",
":",
"raise",
"ValueError",
"(",
"\"min_key c... | Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``.
Example:
>>> decryptions = crack("KHOOR", fitness.english.quadgrams)
>>> print(''.join(decryptions[0].plaintext))
HELLO
Args:
ciphertext (iterable): The symbols to decrypt
*fitness_functions (... | [
"Break",
"ciphertext",
"by",
"enumerating",
"keys",
"between",
"min_key",
"and",
"max_key",
"."
] | python | train |
msoulier/tftpy | tftpy/TftpStates.py | https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L39-L53 | def handleOACK(self, pkt):
"""This method handles an OACK from the server, syncing any accepted
options."""
if len(pkt.options.keys()) > 0:
if pkt.match_options(self.context.options):
log.info("Successful negotiation of options")
# Set options to OACK ... | [
"def",
"handleOACK",
"(",
"self",
",",
"pkt",
")",
":",
"if",
"len",
"(",
"pkt",
".",
"options",
".",
"keys",
"(",
")",
")",
">",
"0",
":",
"if",
"pkt",
".",
"match_options",
"(",
"self",
".",
"context",
".",
"options",
")",
":",
"log",
".",
"i... | This method handles an OACK from the server, syncing any accepted
options. | [
"This",
"method",
"handles",
"an",
"OACK",
"from",
"the",
"server",
"syncing",
"any",
"accepted",
"options",
"."
] | python | train |
wbond/asn1crypto | asn1crypto/core.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L2857-L2905 | def set(self, value):
"""
Sets the value of the object
:param value:
A unicode string. May be a dotted integer string, or if _map is
provided, one of the mapped values.
:raises:
ValueError - when an invalid value is passed
"""
if not... | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str_cls",
")",
":",
"raise",
"TypeError",
"(",
"unwrap",
"(",
"'''\n %s value must be a unicode string, not %s\n '''",
",",
"type_name",
"... | Sets the value of the object
:param value:
A unicode string. May be a dotted integer string, or if _map is
provided, one of the mapped values.
:raises:
ValueError - when an invalid value is passed | [
"Sets",
"the",
"value",
"of",
"the",
"object"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py#L96-L109 | def show_raslog_output_show_all_raslog_raslog_entries_date_and_time_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_all_r... | [
"def",
"show_raslog_output_show_all_raslog_raslog_entries_date_and_time_info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_raslog",
"=",
"ET",
".",
"Element",
"(",
"\"show_raslog\"",
")",
"conf... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
ANTsX/ANTsPy | ants/core/ants_transform_io.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L16-L35 | def new_ants_transform(precision='float', dimension=3, transform_type='AffineTransform', parameters=None):
"""
Create a new ANTsTransform
ANTsR function: None
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
"""
libfn = utils.get_lib_fn('newAntsTransform%s%i' % (u... | [
"def",
"new_ants_transform",
"(",
"precision",
"=",
"'float'",
",",
"dimension",
"=",
"3",
",",
"transform_type",
"=",
"'AffineTransform'",
",",
"parameters",
"=",
"None",
")",
":",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'newAntsTransform%s%i'",
"%",
... | Create a new ANTsTransform
ANTsR function: None
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform() | [
"Create",
"a",
"new",
"ANTsTransform"
] | python | train |
sorgerlab/indra | indra/sources/bel/rdf_processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L526-L652 | def get_transcription(self):
"""Extract Increase/DecreaseAmount INDRA Statements from BEL.
Three distinct SPARQL patterns are used to extract amount
regulations from BEL.
- q_tscript1 searches for a subject which is a Transcription
ActivityType of a ProteinAbundance and an ob... | [
"def",
"get_transcription",
"(",
"self",
")",
":",
"q_tscript1",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT ?tfName ?targetName ?stmt ?tf ?target ?rel\n WHERE {\n ?stmt a belvoc:Statement .\n ?stmt belvoc:hasRelationship ?rel .\n ?st... | Extract Increase/DecreaseAmount INDRA Statements from BEL.
Three distinct SPARQL patterns are used to extract amount
regulations from BEL.
- q_tscript1 searches for a subject which is a Transcription
ActivityType of a ProteinAbundance and an object which is
an RNAAbundance ... | [
"Extract",
"Increase",
"/",
"DecreaseAmount",
"INDRA",
"Statements",
"from",
"BEL",
"."
] | python | train |
deep-compute/logagg | logagg/collector.py | https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/collector.py#L184-L221 | def assign_default_log_values(self, fpath, line, formatter):
'''
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
... | [
"def",
"assign_default_log_values",
"(",
"self",
",",
"fpath",
",",
"line",
",",
"formatter",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"None",
",",
"file",
"=",
"fpath",
",",
"host",
"=",
"self",
".",
"HOST",
",",
"formatter",
"=",
"formatter",
",",... | >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
>>> line = 'some log line here'
>>> default_log = lc.assign_defaul... | [
">>>",
"lc",
"=",
"LogCollector",
"(",
"file",
"=",
"/",
"path",
"/",
"to",
"/",
"log_file",
".",
"log",
":",
"formatter",
"=",
"logagg",
".",
"formatters",
".",
"basescript",
"30",
")",
">>>",
"from",
"pprint",
"import",
"pprint"
] | python | train |
Akay7/nosql2django | nosql2django/parser_mapper.py | https://github.com/Akay7/nosql2django/blob/f33af832d4d0d652bd730471d1ce6a717700d1e7/nosql2django/parser_mapper.py#L27-L53 | def save_to_db(model_text_id, parsed_values):
"""save to db and return saved object"""
Model = apps.get_model(model_text_id)
# normalise values and separate to m2m, simple
simple_fields = {}
many2many_fields = {}
for field, value in parsed_values.items():
if ... | [
"def",
"save_to_db",
"(",
"model_text_id",
",",
"parsed_values",
")",
":",
"Model",
"=",
"apps",
".",
"get_model",
"(",
"model_text_id",
")",
"# normalise values and separate to m2m, simple",
"simple_fields",
"=",
"{",
"}",
"many2many_fields",
"=",
"{",
"}",
"for",
... | save to db and return saved object | [
"save",
"to",
"db",
"and",
"return",
"saved",
"object"
] | python | train |
RaRe-Technologies/gensim-simserver | simserver/simserver.py | https://github.com/RaRe-Technologies/gensim-simserver/blob/e7e59e836ef6d9da019a8c6b218ef0bdd998b2da/simserver/simserver.py#L556-L583 | def train(self, corpus=None, method='auto', clear_buffer=True, params=None):
"""
Create an indexing model. Will overwrite the model if it already exists.
All indexes become invalid, because documents in them use a now-obsolete
representation.
The model is trained on documents pr... | [
"def",
"train",
"(",
"self",
",",
"corpus",
"=",
"None",
",",
"method",
"=",
"'auto'",
",",
"clear_buffer",
"=",
"True",
",",
"params",
"=",
"None",
")",
":",
"if",
"corpus",
"is",
"not",
"None",
":",
"# use the supplied corpus only (erase existing buffer, if ... | Create an indexing model. Will overwrite the model if it already exists.
All indexes become invalid, because documents in them use a now-obsolete
representation.
The model is trained on documents previously entered via `buffer`,
or directly on `corpus`, if specified. | [
"Create",
"an",
"indexing",
"model",
".",
"Will",
"overwrite",
"the",
"model",
"if",
"it",
"already",
"exists",
".",
"All",
"indexes",
"become",
"invalid",
"because",
"documents",
"in",
"them",
"use",
"a",
"now",
"-",
"obsolete",
"representation",
"."
] | python | train |
facetoe/zenpy | zenpy/lib/api.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api.py#L834-L838 | def skips(self, user):
"""
Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.
"""
return self._get(self._build_url(self.endpoint.skips(id=user))) | [
"def",
"skips",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"_get",
"(",
"self",
".",
"_build_url",
"(",
"self",
".",
"endpoint",
".",
"skips",
"(",
"id",
"=",
"user",
")",
")",
")"
] | Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__. | [
"Skips",
"for",
"user",
".",
"Zendesk",
"API",
"Reference",
"<https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"ticket_skips",
">",
"__",
"."
] | python | train |
raiden-network/raiden | raiden/network/proxies/payment_channel.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/payment_channel.py#L178-L195 | def close(
self,
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
signature: Signature,
block_identifier: BlockSpecification,
):
""" Closes the channel using the provided balance proof. """
self.token_ne... | [
"def",
"close",
"(",
"self",
",",
"nonce",
":",
"Nonce",
",",
"balance_hash",
":",
"BalanceHash",
",",
"additional_hash",
":",
"AdditionalHash",
",",
"signature",
":",
"Signature",
",",
"block_identifier",
":",
"BlockSpecification",
",",
")",
":",
"self",
".",... | Closes the channel using the provided balance proof. | [
"Closes",
"the",
"channel",
"using",
"the",
"provided",
"balance",
"proof",
"."
] | python | train |
marshallward/f90nml | f90nml/parser.py | https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/parser.py#L639-L647 | def _parse_indices(self):
"""Parse a sequence of Fortran vector indices as a list of tuples."""
v_name = self.prior_token
v_indices = []
while self.token in (',', '('):
v_indices.append(self._parse_index(v_name))
return v_indices | [
"def",
"_parse_indices",
"(",
"self",
")",
":",
"v_name",
"=",
"self",
".",
"prior_token",
"v_indices",
"=",
"[",
"]",
"while",
"self",
".",
"token",
"in",
"(",
"','",
",",
"'('",
")",
":",
"v_indices",
".",
"append",
"(",
"self",
".",
"_parse_index",
... | Parse a sequence of Fortran vector indices as a list of tuples. | [
"Parse",
"a",
"sequence",
"of",
"Fortran",
"vector",
"indices",
"as",
"a",
"list",
"of",
"tuples",
"."
] | python | train |
craigahobbs/chisel | src/chisel/app.py | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L224-L241 | def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
"""
Send a JSON response
"""
encoder = JSONEncoder(
check_circular=self.app.validate_output,
allow_nan=False,
sort_keys=True,
... | [
"def",
"response_json",
"(",
"self",
",",
"status",
",",
"response",
",",
"content_type",
"=",
"'application/json'",
",",
"encoding",
"=",
"'utf-8'",
",",
"headers",
"=",
"None",
",",
"jsonp",
"=",
"None",
")",
":",
"encoder",
"=",
"JSONEncoder",
"(",
"che... | Send a JSON response | [
"Send",
"a",
"JSON",
"response"
] | python | train |
crate/crash | src/crate/crash/tabulate.py | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L468-L478 | def _visible_width(s):
"""Visible width of a printed string. ANSI color codes are removed.
>>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world")
(5, 5)
"""
if isinstance(s, _text_type) or isinstance(s, _binary_type):
return _max_line_width(_strip_invisible(s))
else:
... | [
"def",
"_visible_width",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"_text_type",
")",
"or",
"isinstance",
"(",
"s",
",",
"_binary_type",
")",
":",
"return",
"_max_line_width",
"(",
"_strip_invisible",
"(",
"s",
")",
")",
"else",
":",
"return... | Visible width of a printed string. ANSI color codes are removed.
>>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world")
(5, 5) | [
"Visible",
"width",
"of",
"a",
"printed",
"string",
".",
"ANSI",
"color",
"codes",
"are",
"removed",
"."
] | python | train |
moonso/loqusdb | loqusdb/utils/vcf.py | https://github.com/moonso/loqusdb/blob/792dcd0d461aff5adc703c49eebf58964913a513/loqusdb/utils/vcf.py#L89-L180 | def check_vcf(vcf_path, expected_type='snv'):
"""Check if there are any problems with the vcf file
Args:
vcf_path(str)
expected_type(str): 'sv' or 'snv'
Returns:
vcf_info(dict): dict like
{
'nr_variants':<INT>,
'variant_type': <STR> in ['snv', 'sv'],... | [
"def",
"check_vcf",
"(",
"vcf_path",
",",
"expected_type",
"=",
"'snv'",
")",
":",
"LOG",
".",
"info",
"(",
"\"Check if vcf is on correct format...\"",
")",
"vcf",
"=",
"VCF",
"(",
"vcf_path",
")",
"individuals",
"=",
"vcf",
".",
"samples",
"variant_type",
"="... | Check if there are any problems with the vcf file
Args:
vcf_path(str)
expected_type(str): 'sv' or 'snv'
Returns:
vcf_info(dict): dict like
{
'nr_variants':<INT>,
'variant_type': <STR> in ['snv', 'sv'],
'individuals': <LIST> individual positio... | [
"Check",
"if",
"there",
"are",
"any",
"problems",
"with",
"the",
"vcf",
"file"
] | python | train |
log2timeline/plaso | plaso/engine/zeromq_queue.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/zeromq_queue.py#L181-L219 | def _CreateZMQSocket(self):
"""Creates a ZeroMQ socket."""
logger.debug('Creating socket for {0:s}'.format(self.name))
if not self._zmq_context:
self._zmq_context = zmq.Context()
# The terminate and close threading events need to be created when the
# socket is opened. Threading events are u... | [
"def",
"_CreateZMQSocket",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Creating socket for {0:s}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"not",
"self",
".",
"_zmq_context",
":",
"self",
".",
"_zmq_context",
"=",
"zmq",
".",
... | Creates a ZeroMQ socket. | [
"Creates",
"a",
"ZeroMQ",
"socket",
"."
] | python | train |
secdev/scapy | scapy/layers/tls/cert.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/tls/cert.py#L959-L984 | def verifyChainFromCAPath(self, capath, untrusted_file=None):
"""
Does the same job as .verifyChainFromCAFile() but using the list
of anchors in capath directory. The directory should (only) contain
certificates files in PEM format. As for .verifyChainFromCAFile(),
a list of untr... | [
"def",
"verifyChainFromCAPath",
"(",
"self",
",",
"capath",
",",
"untrusted_file",
"=",
"None",
")",
":",
"try",
":",
"anchors",
"=",
"[",
"]",
"for",
"cafile",
"in",
"os",
".",
"listdir",
"(",
"capath",
")",
":",
"anchors",
".",
"append",
"(",
"Cert",... | Does the same job as .verifyChainFromCAFile() but using the list
of anchors in capath directory. The directory should (only) contain
certificates files in PEM format. As for .verifyChainFromCAFile(),
a list of untrusted certificates can be passed as a file
(concatenation of the certifica... | [
"Does",
"the",
"same",
"job",
"as",
".",
"verifyChainFromCAFile",
"()",
"but",
"using",
"the",
"list",
"of",
"anchors",
"in",
"capath",
"directory",
".",
"The",
"directory",
"should",
"(",
"only",
")",
"contain",
"certificates",
"files",
"in",
"PEM",
"format... | python | train |
alexhayes/django-toolkit | django_toolkit/date_util.py | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/date_util.py#L50-L63 | def days(start, stop):
"""
Return days between start & stop (inclusive)
Note that start must be less than stop or else 0 is returned.
@param start: Start date
@param stop: Stop date
@return int
"""
dates=rrule.rruleset()
# Get dates between start/stop (which are inclusive)
... | [
"def",
"days",
"(",
"start",
",",
"stop",
")",
":",
"dates",
"=",
"rrule",
".",
"rruleset",
"(",
")",
"# Get dates between start/stop (which are inclusive)",
"dates",
".",
"rrule",
"(",
"rrule",
".",
"rrule",
"(",
"rrule",
".",
"DAILY",
",",
"dtstart",
"=",
... | Return days between start & stop (inclusive)
Note that start must be less than stop or else 0 is returned.
@param start: Start date
@param stop: Stop date
@return int | [
"Return",
"days",
"between",
"start",
"&",
"stop",
"(",
"inclusive",
")",
"Note",
"that",
"start",
"must",
"be",
"less",
"than",
"stop",
"or",
"else",
"0",
"is",
"returned",
"."
] | python | train |
datajoint/datajoint-python | datajoint/external.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/external.py#L121-L129 | def references(self):
"""
:return: generator of referencing table names and their referencing columns
"""
return self.connection.query("""
SELECT concat('`', table_schema, '`.`', table_name, '`') as referencing_table, column_name
FROM information_schema.key_column_usage
... | [
"def",
"references",
"(",
"self",
")",
":",
"return",
"self",
".",
"connection",
".",
"query",
"(",
"\"\"\"\n SELECT concat('`', table_schema, '`.`', table_name, '`') as referencing_table, column_name\n FROM information_schema.key_column_usage\n WHERE referenced_table_... | :return: generator of referencing table names and their referencing columns | [
":",
"return",
":",
"generator",
"of",
"referencing",
"table",
"names",
"and",
"their",
"referencing",
"columns"
] | python | train |
Parsl/parsl | parsl/dataflow/dflow.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/dflow.py#L1033-L1050 | def load(cls, config: Optional[Config] = None):
"""Load a DataFlowKernel.
Args:
- config (Config) : Configuration to load. This config will be passed to a
new DataFlowKernel instantiation which will be set as the active DataFlowKernel.
Returns:
- DataFlowKe... | [
"def",
"load",
"(",
"cls",
",",
"config",
":",
"Optional",
"[",
"Config",
"]",
"=",
"None",
")",
":",
"if",
"cls",
".",
"_dfk",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Config has already been loaded'",
")",
"if",
"config",
"is",
"None",... | Load a DataFlowKernel.
Args:
- config (Config) : Configuration to load. This config will be passed to a
new DataFlowKernel instantiation which will be set as the active DataFlowKernel.
Returns:
- DataFlowKernel : The loaded DataFlowKernel object. | [
"Load",
"a",
"DataFlowKernel",
"."
] | python | valid |
Groundworkstech/pybfd | pybfd/bfd.py | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L516-L521 | def file_flags(self, _file_flags):
"""Set the new file flags attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.set_file_flags(self._ptr, _file_flags) | [
"def",
"file_flags",
"(",
"self",
",",
"_file_flags",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"set_file_flags",
"(",
"self",
".",
"_ptr",
",",
"_file_flags",
")"
] | Set the new file flags attribute of the BFD file being processed. | [
"Set",
"the",
"new",
"file",
"flags",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/attribute_converter.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L104-L148 | def list_to_local(acs, attrlist, allow_unknown_attributes=False):
""" Replaces the attribute names in a attribute value assertion with the
equivalent name from a local name format.
:param acs: List of Attribute Converters
:param attrlist: List of Attributes
:param allow_unknown_attributes: If unkno... | [
"def",
"list_to_local",
"(",
"acs",
",",
"attrlist",
",",
"allow_unknown_attributes",
"=",
"False",
")",
":",
"if",
"not",
"acs",
":",
"acs",
"=",
"[",
"AttributeConverter",
"(",
")",
"]",
"acsd",
"=",
"{",
"\"\"",
":",
"acs",
"}",
"else",
":",
"acsd",... | Replaces the attribute names in a attribute value assertion with the
equivalent name from a local name format.
:param acs: List of Attribute Converters
:param attrlist: List of Attributes
:param allow_unknown_attributes: If unknown attributes are allowed
:return: A key,values dictionary | [
"Replaces",
"the",
"attribute",
"names",
"in",
"a",
"attribute",
"value",
"assertion",
"with",
"the",
"equivalent",
"name",
"from",
"a",
"local",
"name",
"format",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/xen.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/xen.py#L370-L411 | def vdi_list(call=None, kwargs=None):
'''
Return available Xen VDI images
If this function is called with the ``-f`` or ``--function`` then
it can return a list with minimal deatil using the ``terse=True`` keyword
argument.
.. code-block:: bash
salt-cloud -f vdi_list myxen terse=True
... | [
"def",
"vdi_list",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudException",
"(",
"'This function must be called with -f or --function.'",
")",
"log",
".",
"debug",
"(",
"'kwargs is %s'",
... | Return available Xen VDI images
If this function is called with the ``-f`` or ``--function`` then
it can return a list with minimal deatil using the ``terse=True`` keyword
argument.
.. code-block:: bash
salt-cloud -f vdi_list myxen terse=True | [
"Return",
"available",
"Xen",
"VDI",
"images"
] | python | train |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/config.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L16-L21 | def read(self, filename):
"""Read a filename as UTF-8 configuration data."""
kwargs = {}
if sys.version_info >= (3, 2):
kwargs['encoding'] = "utf-8"
return configparser.RawConfigParser.read(self, filename, **kwargs) | [
"def",
"read",
"(",
"self",
",",
"filename",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"2",
")",
":",
"kwargs",
"[",
"'encoding'",
"]",
"=",
"\"utf-8\"",
"return",
"configparser",
".",
"RawConfigParser",
... | Read a filename as UTF-8 configuration data. | [
"Read",
"a",
"filename",
"as",
"UTF",
"-",
"8",
"configuration",
"data",
"."
] | python | test |
mar10/wsgidav | wsgidav/util.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L91-L118 | def _parse_gmt_time(timestring):
"""Return a standard time tuple (see time and calendar), for a date/time string."""
# Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
try:
return time.strptime(timestring, "%a, %d %b %Y %H:%M:%S GMT")
except Exception:
pass
# Sunday, 06... | [
"def",
"_parse_gmt_time",
"(",
"timestring",
")",
":",
"# Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123",
"try",
":",
"return",
"time",
".",
"strptime",
"(",
"timestring",
",",
"\"%a, %d %b %Y %H:%M:%S GMT\"",
")",
"except",
"Exception",
":",
"pass",
"# Su... | Return a standard time tuple (see time and calendar), for a date/time string. | [
"Return",
"a",
"standard",
"time",
"tuple",
"(",
"see",
"time",
"and",
"calendar",
")",
"for",
"a",
"date",
"/",
"time",
"string",
"."
] | python | valid |
MisterY/pydatum | pydatum/datum.py | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L172-L175 | def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value | [
"def",
"subtract_months",
"(",
"self",
",",
"months",
":",
"int",
")",
"->",
"datetime",
":",
"self",
".",
"value",
"=",
"self",
".",
"value",
"-",
"relativedelta",
"(",
"months",
"=",
"months",
")",
"return",
"self",
".",
"value"
] | Subtracts a number of months from the current value | [
"Subtracts",
"a",
"number",
"of",
"months",
"from",
"the",
"current",
"value"
] | python | train |
CityOfZion/neo-python | neo/Implementations/Notifications/LevelDB/NotificationDB.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Notifications/LevelDB/NotificationDB.py#L233-L259 | def get_by_addr(self, address):
"""
Lookup a set of notifications by address
Args:
address (UInt160 or str): hash of address for notifications
Returns:
list: a list of notifications
"""
addr = address
if isinstance(address, str) and len(ad... | [
"def",
"get_by_addr",
"(",
"self",
",",
"address",
")",
":",
"addr",
"=",
"address",
"if",
"isinstance",
"(",
"address",
",",
"str",
")",
"and",
"len",
"(",
"address",
")",
"==",
"34",
":",
"addr",
"=",
"Helper",
".",
"AddrStrToScriptHash",
"(",
"addre... | Lookup a set of notifications by address
Args:
address (UInt160 or str): hash of address for notifications
Returns:
list: a list of notifications | [
"Lookup",
"a",
"set",
"of",
"notifications",
"by",
"address",
"Args",
":",
"address",
"(",
"UInt160",
"or",
"str",
")",
":",
"hash",
"of",
"address",
"for",
"notifications"
] | python | train |
rytilahti/python-songpal | songpal/discovery.py | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/discovery.py#L21-L68 | async def discover(timeout, debug=0, callback=None):
"""Discover supported devices."""
ST = "urn:schemas-sony-com:service:ScalarWebAPI:1"
_LOGGER.info("Discovering for %s seconds" % timeout)
from async_upnp_client import UpnpFactory
from async_upnp_client.aiohttp import AiohttpR... | [
"async",
"def",
"discover",
"(",
"timeout",
",",
"debug",
"=",
"0",
",",
"callback",
"=",
"None",
")",
":",
"ST",
"=",
"\"urn:schemas-sony-com:service:ScalarWebAPI:1\"",
"_LOGGER",
".",
"info",
"(",
"\"Discovering for %s seconds\"",
"%",
"timeout",
")",
"from",
... | Discover supported devices. | [
"Discover",
"supported",
"devices",
"."
] | python | train |
noxdafox/clipspy | clips/classes.py | https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/classes.py#L187-L202 | def save_instances(self, path, binary=False, mode=SaveMode.LOCAL_SAVE):
"""Save the instances in the system to the specified file.
If binary is True, the instances will be saved in binary format.
The Python equivalent of the CLIPS save-instances command.
"""
if binary:
... | [
"def",
"save_instances",
"(",
"self",
",",
"path",
",",
"binary",
"=",
"False",
",",
"mode",
"=",
"SaveMode",
".",
"LOCAL_SAVE",
")",
":",
"if",
"binary",
":",
"ret",
"=",
"lib",
".",
"EnvBinarySaveInstances",
"(",
"self",
".",
"_env",
",",
"path",
"."... | Save the instances in the system to the specified file.
If binary is True, the instances will be saved in binary format.
The Python equivalent of the CLIPS save-instances command. | [
"Save",
"the",
"instances",
"in",
"the",
"system",
"to",
"the",
"specified",
"file",
"."
] | python | train |
PythonCharmers/python-future | src/future/backports/http/client.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/client.py#L771-L782 | def set_tunnel(self, host, port=None, headers=None):
""" Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request.
"""
self._tunnel_host = host
self._tunnel_port = port
... | [
"def",
"set_tunnel",
"(",
"self",
",",
"host",
",",
"port",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"self",
".",
"_tunnel_host",
"=",
"host",
"self",
".",
"_tunnel_port",
"=",
"port",
"if",
"headers",
":",
"self",
".",
"_tunnel_headers",
"=... | Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request. | [
"Sets",
"up",
"the",
"host",
"and",
"the",
"port",
"for",
"the",
"HTTP",
"CONNECT",
"Tunnelling",
"."
] | python | train |
google/grr | grr/core/grr_response_core/lib/parsers/wmi_parser.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/wmi_parser.py#L99-L138 | def ParseMultiple(self, result_dicts):
"""Parse WMI Event Consumers."""
for result_dict in result_dicts:
wmi_dict = result_dict.ToDict()
try:
creator_sid_bytes = bytes(wmi_dict["CreatorSID"])
wmi_dict["CreatorSID"] = BinarySIDtoStringSID(creator_sid_bytes)
except ValueError:
... | [
"def",
"ParseMultiple",
"(",
"self",
",",
"result_dicts",
")",
":",
"for",
"result_dict",
"in",
"result_dicts",
":",
"wmi_dict",
"=",
"result_dict",
".",
"ToDict",
"(",
")",
"try",
":",
"creator_sid_bytes",
"=",
"bytes",
"(",
"wmi_dict",
"[",
"\"CreatorSID\"",... | Parse WMI Event Consumers. | [
"Parse",
"WMI",
"Event",
"Consumers",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/assessment/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L9138-L9155 | def has_child_banks(self, bank_id):
"""Tests if a bank has any children.
arg: bank_id (osid.id.Id): a ``bank_id``
return: (boolean) - ``true`` if the ``bank_id`` has children,
``false`` otherwise
raise: NotFound - ``bank_id`` is not found
raise: NullArgument... | [
"def",
"has_child_banks",
"(",
"self",
",",
"bank_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.has_child_bins",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"ha... | Tests if a bank has any children.
arg: bank_id (osid.id.Id): a ``bank_id``
return: (boolean) - ``true`` if the ``bank_id`` has children,
``false`` otherwise
raise: NotFound - ``bank_id`` is not found
raise: NullArgument - ``bank_id`` is ``null``
raise: Oper... | [
"Tests",
"if",
"a",
"bank",
"has",
"any",
"children",
"."
] | python | train |
guaix-ucm/numina | numina/array/wavecalib/crosscorrelation.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/crosscorrelation.py#L150-L370 | def periodic_corr1d(sp_reference, sp_offset,
fminmax=None,
naround_zero=None,
norm_spectra=False,
plottitle=None,
pdf=None,
debugplot=0):
"""Periodic correlation between two spectra, implemented u... | [
"def",
"periodic_corr1d",
"(",
"sp_reference",
",",
"sp_offset",
",",
"fminmax",
"=",
"None",
",",
"naround_zero",
"=",
"None",
",",
"norm_spectra",
"=",
"False",
",",
"plottitle",
"=",
"None",
",",
"pdf",
"=",
"None",
",",
"debugplot",
"=",
"0",
")",
":... | Periodic correlation between two spectra, implemented using FFT.
Parameters
----------
sp_reference : numpy array
Reference spectrum.
sp_offset : numpy array
Spectrum which offset is going to be measured relative to the
reference spectrum.
fminmax : tuple of floats or None
... | [
"Periodic",
"correlation",
"between",
"two",
"spectra",
"implemented",
"using",
"FFT",
"."
] | python | train |
shoebot/shoebot | lib/graph/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L381-L411 | def update(self, iterations=10):
""" Iterates the graph layout and updates node positions.
"""
# The graph fades in when initially constructed.
self.alpha += 0.05
self.alpha = min(self.alpha, 1.0)
# Iterates over the graph's layout.
# Each s... | [
"def",
"update",
"(",
"self",
",",
"iterations",
"=",
"10",
")",
":",
"# The graph fades in when initially constructed.",
"self",
".",
"alpha",
"+=",
"0.05",
"self",
".",
"alpha",
"=",
"min",
"(",
"self",
".",
"alpha",
",",
"1.0",
")",
"# Iterates over the gra... | Iterates the graph layout and updates node positions. | [
"Iterates",
"the",
"graph",
"layout",
"and",
"updates",
"node",
"positions",
"."
] | python | valid |
SiLab-Bonn/pyBAR | pybar/fei4/register_utils.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/fei4/register_utils.py#L913-L1252 | def scan_loop(self, command, repeat_command=100, use_delay=True, additional_delay=0, mask_steps=3, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=False, fast_dc_loop=True, bol_function=None, eol_function=None, digital_injection=False, enable_shift_masks=None, disable_shift_masks=None, restore_... | [
"def",
"scan_loop",
"(",
"self",
",",
"command",
",",
"repeat_command",
"=",
"100",
",",
"use_delay",
"=",
"True",
",",
"additional_delay",
"=",
"0",
",",
"mask_steps",
"=",
"3",
",",
"enable_mask_steps",
"=",
"None",
",",
"enable_double_columns",
"=",
"None... | Implementation of the scan loops (mask shifting, loop over double columns, repeatedly sending any arbitrary command).
Parameters
----------
command : BitVector
(FEI4) command that will be sent out serially.
repeat_command : int
The number of repetitions command will be sent out e... | [
"Implementation",
"of",
"the",
"scan",
"loops",
"(",
"mask",
"shifting",
"loop",
"over",
"double",
"columns",
"repeatedly",
"sending",
"any",
"arbitrary",
"command",
")",
".",
"Parameters",
"----------",
"command",
":",
"BitVector",
"(",
"FEI4",
")",
"command",
... | python | train |
LionelAuroux/pyrser | pyrser/parsing/base.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L543-L556 | def read_cstring(self) -> bool:
"""
read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"'
"""
self._stream.save_context()
idx = self._stream.index
if self.read_char("\"") and self.read_until("\"", "\\"):
txt = self._stream[i... | [
"def",
"read_cstring",
"(",
"self",
")",
"->",
"bool",
":",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"idx",
"=",
"self",
".",
"_stream",
".",
"index",
"if",
"self",
".",
"read_char",
"(",
"\"\\\"\"",
")",
"and",
"self",
".",
"read_until",... | read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"' | [
"read",
"a",
"double",
"quoted",
"string",
"Read",
"following",
"BNF",
"rule",
"else",
"return",
"False",
"::"
] | python | test |
kyuupichan/aiorpcX | aiorpcx/jsonrpc.py | https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/jsonrpc.py#L247-L280 | def message_to_item(cls, message):
'''Translate an unframed received message and return an
(item, request_id) pair.
The item can be a Request, Notification, Response or a list.
A JSON RPC error response is returned as an RPCError inside a
Response object.
If a Batch is... | [
"def",
"message_to_item",
"(",
"cls",
",",
"message",
")",
":",
"payload",
"=",
"cls",
".",
"_message_to_payload",
"(",
"message",
")",
"if",
"isinstance",
"(",
"payload",
",",
"dict",
")",
":",
"if",
"'method'",
"in",
"payload",
":",
"return",
"cls",
".... | Translate an unframed received message and return an
(item, request_id) pair.
The item can be a Request, Notification, Response or a list.
A JSON RPC error response is returned as an RPCError inside a
Response object.
If a Batch is returned, request_id is an iterable of reques... | [
"Translate",
"an",
"unframed",
"received",
"message",
"and",
"return",
"an",
"(",
"item",
"request_id",
")",
"pair",
"."
] | python | train |
gem/oq-engine | openquake/baselib/node.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L160-L172 | def floatformat(fmt_string):
"""
Context manager to change the default format string for the
function :func:`openquake.commonlib.writers.scientificformat`.
:param fmt_string: the format to use; for instance '%13.9E'
"""
fmt_defaults = scientificformat.__defaults__
scientificformat.__default... | [
"def",
"floatformat",
"(",
"fmt_string",
")",
":",
"fmt_defaults",
"=",
"scientificformat",
".",
"__defaults__",
"scientificformat",
".",
"__defaults__",
"=",
"(",
"fmt_string",
",",
")",
"+",
"fmt_defaults",
"[",
"1",
":",
"]",
"try",
":",
"yield",
"finally",... | Context manager to change the default format string for the
function :func:`openquake.commonlib.writers.scientificformat`.
:param fmt_string: the format to use; for instance '%13.9E' | [
"Context",
"manager",
"to",
"change",
"the",
"default",
"format",
"string",
"for",
"the",
"function",
":",
"func",
":",
"openquake",
".",
"commonlib",
".",
"writers",
".",
"scientificformat",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/bin/t2t_distill.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/bin/t2t_distill.py#L91-L114 | def create_teacher_experiment(run_config, hparams, argv):
"""Creates experiment function."""
tf.logging.info("training teacher")
tf.logging.set_verbosity(tf.logging.INFO)
trainer_lib.set_random_seed(FLAGS.random_seed)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
t2t_trainer.maybe_log_registry_and_exit()
if ... | [
"def",
"create_teacher_experiment",
"(",
"run_config",
",",
"hparams",
",",
"argv",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"training teacher\"",
")",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"INFO",
")",
"tra... | Creates experiment function. | [
"Creates",
"experiment",
"function",
"."
] | python | train |
numenta/nupic | src/nupic/algorithms/backtracking_tm.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1479-L1523 | def _computeOutput(self):
"""
Computes output for both learning and inference. In both cases, the
output is the boolean OR of ``activeState`` and ``predictedState`` at ``t``.
Stores ``currentOutput`` for ``checkPrediction``.
:returns: TODO: document
"""
# TODO: This operation can be spe... | [
"def",
"_computeOutput",
"(",
"self",
")",
":",
"# TODO: This operation can be sped up by:",
"# 1.) Pre-allocating space for the currentOutput",
"# 2.) Making predictedState and activeState of type 'float32' up front",
"# 3.) Using logical_or(self.predictedState['t'], self.activeState['t'],"... | Computes output for both learning and inference. In both cases, the
output is the boolean OR of ``activeState`` and ``predictedState`` at ``t``.
Stores ``currentOutput`` for ``checkPrediction``.
:returns: TODO: document | [
"Computes",
"output",
"for",
"both",
"learning",
"and",
"inference",
".",
"In",
"both",
"cases",
"the",
"output",
"is",
"the",
"boolean",
"OR",
"of",
"activeState",
"and",
"predictedState",
"at",
"t",
".",
"Stores",
"currentOutput",
"for",
"checkPrediction",
"... | python | valid |
limix/glimix-core | glimix_core/lmm/_lmm_scan.py | https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm_scan.py#L267-L315 | def scan(self, M):
"""
LML, fixed-effect sizes, and scale of the candidate set.
Parameters
----------
M : array_like
Fixed-effects set.
Returns
-------
lml : float
Log of the marginal likelihood.
effsizes0 : ndarray
... | [
"def",
"scan",
"(",
"self",
",",
"M",
")",
":",
"from",
"numpy_sugar",
".",
"linalg",
"import",
"ddot",
"from",
"numpy_sugar",
"import",
"is_all_finite",
"M",
"=",
"asarray",
"(",
"M",
",",
"float",
")",
"if",
"M",
".",
"shape",
"[",
"1",
"]",
"==",
... | LML, fixed-effect sizes, and scale of the candidate set.
Parameters
----------
M : array_like
Fixed-effects set.
Returns
-------
lml : float
Log of the marginal likelihood.
effsizes0 : ndarray
Covariates fixed-effect sizes.
... | [
"LML",
"fixed",
"-",
"effect",
"sizes",
"and",
"scale",
"of",
"the",
"candidate",
"set",
"."
] | python | valid |
GNS3/gns3-server | gns3server/compute/notification_manager.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/notification_manager.py#L60-L68 | def instance():
"""
Singleton to return only on instance of NotificationManager.
:returns: instance of NotificationManager
"""
if not hasattr(NotificationManager, '_instance') or NotificationManager._instance is None:
NotificationManager._instance = NotificationManag... | [
"def",
"instance",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"NotificationManager",
",",
"'_instance'",
")",
"or",
"NotificationManager",
".",
"_instance",
"is",
"None",
":",
"NotificationManager",
".",
"_instance",
"=",
"NotificationManager",
"(",
")",
"retur... | Singleton to return only on instance of NotificationManager.
:returns: instance of NotificationManager | [
"Singleton",
"to",
"return",
"only",
"on",
"instance",
"of",
"NotificationManager",
".",
":",
"returns",
":",
"instance",
"of",
"NotificationManager"
] | python | train |
RiotGames/cloud-inquisitor | plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-cloudtrail/cinq_auditor_cloudtrail/__init__.py#L338-L361 | def subscribe_sns_topic_to_sqs(self, region):
"""Subscribe SQS to the SNS topic. Returns the ARN of the SNS Topic subscribed
Args:
region (`str`): Name of the AWS region
Returns:
`str`
"""
sns = self.session.resource('sns', region_name=region)
to... | [
"def",
"subscribe_sns_topic_to_sqs",
"(",
"self",
",",
"region",
")",
":",
"sns",
"=",
"self",
".",
"session",
".",
"resource",
"(",
"'sns'",
",",
"region_name",
"=",
"region",
")",
"topic",
"=",
"sns",
".",
"Topic",
"(",
"'arn:aws:sns:{}:{}:{}'",
".",
"fo... | Subscribe SQS to the SNS topic. Returns the ARN of the SNS Topic subscribed
Args:
region (`str`): Name of the AWS region
Returns:
`str` | [
"Subscribe",
"SQS",
"to",
"the",
"SNS",
"topic",
".",
"Returns",
"the",
"ARN",
"of",
"the",
"SNS",
"Topic",
"subscribed"
] | python | train |
bachya/pyairvisual | pyairvisual/api.py | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L28-L38 | async def city(self, city: str, state: str, country: str) -> dict:
"""Return data for the specified city."""
data = await self._request(
'get',
'city',
params={
'city': city,
'state': state,
'country': country
... | [
"async",
"def",
"city",
"(",
"self",
",",
"city",
":",
"str",
",",
"state",
":",
"str",
",",
"country",
":",
"str",
")",
"->",
"dict",
":",
"data",
"=",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'city'",
",",
"params",
"=",
"{",
"'cit... | Return data for the specified city. | [
"Return",
"data",
"for",
"the",
"specified",
"city",
"."
] | python | train |
googleapis/google-cloud-python | logging/google/cloud/logging/_http.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_http.py#L163-L176 | def logger_delete(self, project, logger_name):
"""API call: delete all entries in a logger via a DELETE request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete
:type project: str
:param project: ID of project containing the log entries to de... | [
"def",
"logger_delete",
"(",
"self",
",",
"project",
",",
"logger_name",
")",
":",
"path",
"=",
"\"/projects/%s/logs/%s\"",
"%",
"(",
"project",
",",
"logger_name",
")",
"self",
".",
"api_request",
"(",
"method",
"=",
"\"DELETE\"",
",",
"path",
"=",
"path",
... | API call: delete all entries in a logger via a DELETE request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete
:type project: str
:param project: ID of project containing the log entries to delete
:type logger_name: str
:param logger... | [
"API",
"call",
":",
"delete",
"all",
"entries",
"in",
"a",
"logger",
"via",
"a",
"DELETE",
"request"
] | python | train |
Chilipp/sphinx-nbexamples | sphinx_nbexamples/__init__.py | https://github.com/Chilipp/sphinx-nbexamples/blob/08e0319ff3c70f8a931dfa8890caf48add4d0470/sphinx_nbexamples/__init__.py#L509-L548 | def get_description(self):
"""Get summary and description of this notebook"""
def split_header(s, get_header=True):
s = s.lstrip().rstrip()
parts = s.splitlines()
if parts[0].startswith('#'):
if get_header:
header = re.sub('#+\s*', ... | [
"def",
"get_description",
"(",
"self",
")",
":",
"def",
"split_header",
"(",
"s",
",",
"get_header",
"=",
"True",
")",
":",
"s",
"=",
"s",
".",
"lstrip",
"(",
")",
".",
"rstrip",
"(",
")",
"parts",
"=",
"s",
".",
"splitlines",
"(",
")",
"if",
"pa... | Get summary and description of this notebook | [
"Get",
"summary",
"and",
"description",
"of",
"this",
"notebook"
] | python | test |
christian-oudard/htmltreediff | htmltreediff/diff_core.py | https://github.com/christian-oudard/htmltreediff/blob/0e28f56492ae7e69bb0f74f9a79a8909a5ad588d/htmltreediff/diff_core.py#L268-L285 | def merge_blocks(a_blocks, b_blocks):
"""Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length.
"""
# Check sentinels for sequence length.
assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size... | [
"def",
"merge_blocks",
"(",
"a_blocks",
",",
"b_blocks",
")",
":",
"# Check sentinels for sequence length.",
"assert",
"a_blocks",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"==",
"b_blocks",
"[",
"-",
"1",
"]",
"[",
"2",
"]",
"==",
"0",
"# sentinel size is 0",
"a... | Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length. | [
"Given",
"two",
"lists",
"of",
"blocks",
"combine",
"them",
"in",
"the",
"proper",
"order",
"."
] | python | train |
cyrus-/cypy | cypy/np/__init__.py | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/np/__init__.py#L60-L78 | def packed(self):
"""
each row is placed side-by-side with the length of the row interlaced
the head of the packed matrix contains offsets to this length
e.g. [[11, 22, 33], [44, 55], []] => [3, 7, 10, 3, 11, 22, 33, 2, 44, 55, 0]
"""
# not the most efficient implementati... | [
"def",
"packed",
"(",
"self",
")",
":",
"# not the most efficient implementation atm but whatever",
"n_rows",
"=",
"len",
"(",
"self",
")",
"size",
"=",
"len",
"(",
"self",
")",
"*",
"2",
"+",
"self",
".",
"n_edges",
"packed",
"=",
"numpy",
".",
"empty",
"... | each row is placed side-by-side with the length of the row interlaced
the head of the packed matrix contains offsets to this length
e.g. [[11, 22, 33], [44, 55], []] => [3, 7, 10, 3, 11, 22, 33, 2, 44, 55, 0] | [
"each",
"row",
"is",
"placed",
"side",
"-",
"by",
"-",
"side",
"with",
"the",
"length",
"of",
"the",
"row",
"interlaced",
"the",
"head",
"of",
"the",
"packed",
"matrix",
"contains",
"offsets",
"to",
"this",
"length",
"e",
".",
"g",
".",
"[[",
"11",
"... | python | train |
log2timeline/dfvfs | dfvfs/lib/gzipfile.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L288-L333 | def ReadAtOffset(self, offset, size=None):
"""Reads a byte string from the gzip member at the specified offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
offset (int): offset within the uncompressed data in this member... | [
"def",
"ReadAtOffset",
"(",
"self",
",",
"offset",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
"is",
"not",
"None",
"and",
"size",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid size value {0!s}'",
".",
"format",
"(",
"size",
")",
")",
"if"... | Reads a byte string from the gzip member at the specified offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
offset (int): offset within the uncompressed data in this member to
read from.
size (Optional[int]):... | [
"Reads",
"a",
"byte",
"string",
"from",
"the",
"gzip",
"member",
"at",
"the",
"specified",
"offset",
"."
] | python | train |
saltstack/salt | salt/runners/vault.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vault.py#L262-L269 | def _get_token_create_url(config):
'''
Create Vault url for token creation
'''
role_name = config.get('role_name', None)
auth_path = '/v1/auth/token/create'
base_url = config['url']
return '/'.join(x.strip('/') for x in (base_url, auth_path, role_name) if x) | [
"def",
"_get_token_create_url",
"(",
"config",
")",
":",
"role_name",
"=",
"config",
".",
"get",
"(",
"'role_name'",
",",
"None",
")",
"auth_path",
"=",
"'/v1/auth/token/create'",
"base_url",
"=",
"config",
"[",
"'url'",
"]",
"return",
"'/'",
".",
"join",
"(... | Create Vault url for token creation | [
"Create",
"Vault",
"url",
"for",
"token",
"creation"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L11661-L11672 | def log_request_data_encode(self, target_system, target_component, id, ofs, count):
'''
Request a chunk of a log
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
id :... | [
"def",
"log_request_data_encode",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"id",
",",
"ofs",
",",
"count",
")",
":",
"return",
"MAVLink_log_request_data_message",
"(",
"target_system",
",",
"target_component",
",",
"id",
",",
"ofs",
",",
... | Request a chunk of a log
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
id : Log id (from LOG_ENTRY reply) (uint16_t)
ofs : Offset into the log (uint32_t)
... | [
"Request",
"a",
"chunk",
"of",
"a",
"log"
] | python | train |
RRZE-HPC/kerncraft | kerncraft/kernel.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/kernel.py#L1075-L1103 | def _build_const_declartions(self, with_init=True):
"""
Generate constants declarations
:return: list of declarations
"""
decls = []
# Use type as provided by user in loop indices
index_type = self.get_index_type()
i = 2 # subscript for cli input, 1 is... | [
"def",
"_build_const_declartions",
"(",
"self",
",",
"with_init",
"=",
"True",
")",
":",
"decls",
"=",
"[",
"]",
"# Use type as provided by user in loop indices",
"index_type",
"=",
"self",
".",
"get_index_type",
"(",
")",
"i",
"=",
"2",
"# subscript for cli input, ... | Generate constants declarations
:return: list of declarations | [
"Generate",
"constants",
"declarations"
] | python | test |
chrisspen/burlap | burlap/supervisor.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/supervisor.py#L237-L297 | def deploy_services(self, site=None):
"""
Collects the configurations for all registered services and writes
the appropriate supervisord.conf file.
"""
verbose = self.verbose
r = self.local_renderer
if not r.env.manage_configs:
return
#
# tar... | [
"def",
"deploy_services",
"(",
"self",
",",
"site",
"=",
"None",
")",
":",
"verbose",
"=",
"self",
".",
"verbose",
"r",
"=",
"self",
".",
"local_renderer",
"if",
"not",
"r",
".",
"env",
".",
"manage_configs",
":",
"return",
"#",
"# target_sites = s... | Collects the configurations for all registered services and writes
the appropriate supervisord.conf file. | [
"Collects",
"the",
"configurations",
"for",
"all",
"registered",
"services",
"and",
"writes",
"the",
"appropriate",
"supervisord",
".",
"conf",
"file",
"."
] | python | valid |
vektorlab/slacksocket | slacksocket/webclient.py | https://github.com/vektorlab/slacksocket/blob/8eb8b0f14fe80740217ea0aaf6feb7f736bdf57f/slacksocket/webclient.py#L155-L163 | def match(self, attr, val):
""" lookup object in directory with attribute matching value """
self._lock.acquire()
try:
for x in self:
if getattr(x, attr) == val:
return x
finally:
self._lock.release() | [
"def",
"match",
"(",
"self",
",",
"attr",
",",
"val",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"for",
"x",
"in",
"self",
":",
"if",
"getattr",
"(",
"x",
",",
"attr",
")",
"==",
"val",
":",
"return",
"x",
"finally",
... | lookup object in directory with attribute matching value | [
"lookup",
"object",
"in",
"directory",
"with",
"attribute",
"matching",
"value"
] | python | train |
pybel/pybel | src/pybel/struct/filters/node_predicates.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicates.py#L152-L174 | def _node_has_modifier(graph: BELGraph, node: BaseEntity, modifier: str) -> bool:
"""Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
... | [
"def",
"_node_has_modifier",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
",",
"modifier",
":",
"str",
")",
"->",
"bool",
":",
"modifier_in_subject",
"=",
"any",
"(",
"part_has_modifier",
"(",
"d",
",",
"SUBJECT",
",",
"modifier",
")",
"f... | Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
:param modifier: One of :data:`pybel.constants.ACTIVITY`, :data:`pybel.constants.DEGRAD... | [
"Return",
"true",
"if",
"over",
"any",
"of",
"a",
"nodes",
"edges",
"it",
"has",
"a",
"given",
"modifier",
"."
] | python | train |
jonbretman/jinja-to-js | jinja_to_js/__init__.py | https://github.com/jonbretman/jinja-to-js/blob/0a784b10a83d37a3171c5797547e9fc460c51289/jinja_to_js/__init__.py#L405-L422 | def _process_name(self, node, **kwargs):
"""
Processes a `Name` node. Some examples of `Name` nodes:
{{ foo }} -> 'foo' is a Name
{% if foo }} -> 'foo' is a Name
"""
with self._interpolation():
with self._python_bool_wrapper(**kwargs):
... | [
"def",
"_process_name",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_interpolation",
"(",
")",
":",
"with",
"self",
".",
"_python_bool_wrapper",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"node",
".",
"name",
"not... | Processes a `Name` node. Some examples of `Name` nodes:
{{ foo }} -> 'foo' is a Name
{% if foo }} -> 'foo' is a Name | [
"Processes",
"a",
"Name",
"node",
".",
"Some",
"examples",
"of",
"Name",
"nodes",
":",
"{{",
"foo",
"}}",
"-",
">",
"foo",
"is",
"a",
"Name",
"{",
"%",
"if",
"foo",
"}}",
"-",
">",
"foo",
"is",
"a",
"Name"
] | python | train |
7sDream/zhihu-py3 | zhihu/question.py | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/question.py#L176-L273 | def answers(self):
"""获取问题的所有答案.
:return: 问题的所有答案,返回生成器
:rtype: Answer.Iterable
"""
from .author import Author
from .answer import Answer
self._make_soup()
# TODO: 统一逻辑. 完全可以都用 _parse_answer_html 的逻辑替换
if self._url.endswith('sort=created'):
... | [
"def",
"answers",
"(",
"self",
")",
":",
"from",
".",
"author",
"import",
"Author",
"from",
".",
"answer",
"import",
"Answer",
"self",
".",
"_make_soup",
"(",
")",
"# TODO: 统一逻辑. 完全可以都用 _parse_answer_html 的逻辑替换",
"if",
"self",
".",
"_url",
".",
"endswith",
"("... | 获取问题的所有答案.
:return: 问题的所有答案,返回生成器
:rtype: Answer.Iterable | [
"获取问题的所有答案",
"."
] | python | train |
SystemRDL/systemrdl-compiler | systemrdl/rdltypes.py | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L188-L211 | def get_scope_path(cls, scope_separator="::"):
"""
Generate a string that represents this enum's declaration namespace
scope.
Parameters
----------
scope_separator: str
Override the separator between namespace scopes
"""
if cls.get_parent_scop... | [
"def",
"get_scope_path",
"(",
"cls",
",",
"scope_separator",
"=",
"\"::\"",
")",
":",
"if",
"cls",
".",
"get_parent_scope",
"(",
")",
"is",
"None",
":",
"return",
"\"\"",
"elif",
"isinstance",
"(",
"cls",
".",
"get_parent_scope",
"(",
")",
",",
"comp",
"... | Generate a string that represents this enum's declaration namespace
scope.
Parameters
----------
scope_separator: str
Override the separator between namespace scopes | [
"Generate",
"a",
"string",
"that",
"represents",
"this",
"enum",
"s",
"declaration",
"namespace",
"scope",
"."
] | python | train |
juju/charm-helpers | charmhelpers/contrib/peerstorage/__init__.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L143-L157 | def relation_get(attribute=None, unit=None, rid=None):
"""Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which case we as... | [
"def",
"relation_get",
"(",
"attribute",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"rid",
"=",
"None",
")",
":",
"try",
":",
"if",
"rid",
"in",
"relation_ids",
"(",
"'cluster'",
")",
":",
"return",
"leader_get",
"(",
"attribute",
",",
"rid",
")",
"... | Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which case we assume we are
within the peer relation context). | [
"Attempt",
"to",
"use",
"leader",
"-",
"get",
"if",
"supported",
"in",
"the",
"current",
"version",
"of",
"Juju",
"otherwise",
"falls",
"back",
"on",
"relation",
"-",
"get",
"."
] | python | train |
nnseva/django-access | access/admin.py | https://github.com/nnseva/django-access/blob/2e8b72830b1092652ca63125a8309189d70ad584/access/admin.py#L279-L286 | def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
queryset = self.model._default_manager.filter(pk=object_id)
response = self.delete_selected(request, queryset)
if response:
return response
url = reverse('admin:%s... | [
"def",
"delete_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
"=",
"None",
")",
":",
"queryset",
"=",
"self",
".",
"model",
".",
"_default_manager",
".",
"filter",
"(",
"pk",
"=",
"object_id",
")",
"response",
"=",
"self",
".... | The 'delete' admin view for this model. | [
"The",
"delete",
"admin",
"view",
"for",
"this",
"model",
"."
] | python | train |
uw-it-aca/uw-restclients | restclients/bookstore.py | https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/bookstore.py#L56-L74 | def get_books_for_schedule(self, schedule):
"""
Returns a dictionary of data. SLNs are the keys, an array of Book
objects are the values.
"""
slns = self._get_slns(schedule)
books = {}
for sln in slns:
try:
section_books = self.get_b... | [
"def",
"get_books_for_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"slns",
"=",
"self",
".",
"_get_slns",
"(",
"schedule",
")",
"books",
"=",
"{",
"}",
"for",
"sln",
"in",
"slns",
":",
"try",
":",
"section_books",
"=",
"self",
".",
"get_books_by_qu... | Returns a dictionary of data. SLNs are the keys, an array of Book
objects are the values. | [
"Returns",
"a",
"dictionary",
"of",
"data",
".",
"SLNs",
"are",
"the",
"keys",
"an",
"array",
"of",
"Book",
"objects",
"are",
"the",
"values",
"."
] | python | train |
jaywink/federation | federation/protocols/diaspora/protocol.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/protocol.py#L71-L83 | def store_magic_envelope_doc(self, payload):
"""Get the Magic Envelope, trying JSON first."""
try:
json_payload = json.loads(decode_if_bytes(payload))
except ValueError:
# XML payload
xml = unquote(decode_if_bytes(payload))
xml = xml.lstrip().encod... | [
"def",
"store_magic_envelope_doc",
"(",
"self",
",",
"payload",
")",
":",
"try",
":",
"json_payload",
"=",
"json",
".",
"loads",
"(",
"decode_if_bytes",
"(",
"payload",
")",
")",
"except",
"ValueError",
":",
"# XML payload",
"xml",
"=",
"unquote",
"(",
"deco... | Get the Magic Envelope, trying JSON first. | [
"Get",
"the",
"Magic",
"Envelope",
"trying",
"JSON",
"first",
"."
] | python | train |
django-auth-ldap/django-auth-ldap | django_auth_ldap/config.py | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/config.py#L105-L122 | def search_with_additional_terms(self, term_dict, escape=True):
"""
Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False.
"""
term_... | [
"def",
"search_with_additional_terms",
"(",
"self",
",",
"term_dict",
",",
"escape",
"=",
"True",
")",
":",
"term_strings",
"=",
"[",
"self",
".",
"filterstr",
"]",
"for",
"name",
",",
"value",
"in",
"term_dict",
".",
"items",
"(",
")",
":",
"if",
"escap... | Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False. | [
"Returns",
"a",
"new",
"search",
"object",
"with",
"additional",
"search",
"terms",
"and",
"-",
"ed",
"to",
"the",
"filter",
"string",
".",
"term_dict",
"maps",
"attribute",
"names",
"to",
"assertion",
"values",
".",
"If",
"you",
"don",
"t",
"want",
"the",... | python | train |
bcbio/bcbio-nextgen | bcbio/qc/qualimap.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/qualimap.py#L131-L139 | def _parse_qualimap_globals_inregion(table):
"""Retrieve metrics from the global targeted region table.
"""
out = {}
for row in table.find_all("tr"):
col, val = [x.text for x in row.find_all("td")]
if col == "Mapped reads":
out.update(_parse_num_pct("%s (in regions)" % col, v... | [
"def",
"_parse_qualimap_globals_inregion",
"(",
"table",
")",
":",
"out",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
".",
"find_all",
"(",
"\"tr\"",
")",
":",
"col",
",",
"val",
"=",
"[",
"x",
".",
"text",
"for",
"x",
"in",
"row",
".",
"find_all",
... | Retrieve metrics from the global targeted region table. | [
"Retrieve",
"metrics",
"from",
"the",
"global",
"targeted",
"region",
"table",
"."
] | python | train |
gdestuynder/simple_bugzilla | bugzilla.py | https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L77-L84 | def put_bug(self, bugid, bug_update):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug'''
assert type(bug_update) is DotDict
if (not 'ids' in bug_update):
bug_update.ids = [bugid]
return self._put('bug/{bugid}'.format(bugid=bugid),
... | [
"def",
"put_bug",
"(",
"self",
",",
"bugid",
",",
"bug_update",
")",
":",
"assert",
"type",
"(",
"bug_update",
")",
"is",
"DotDict",
"if",
"(",
"not",
"'ids'",
"in",
"bug_update",
")",
":",
"bug_update",
".",
"ids",
"=",
"[",
"bugid",
"]",
"return",
... | http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug | [
"http",
":",
"//",
"bugzilla",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
"latest",
"/",
"api",
"/",
"core",
"/",
"v1",
"/",
"bug",
".",
"html#update",
"-",
"bug"
] | python | train |
openpaperwork/paperwork-backend | paperwork_backend/shell.py | https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/shell.py#L327-L401 | def cmd_guess_labels(*args):
"""
Arguments: <document id> [-- [--apply]]
Guess the labels that should be set on the document.
Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
... | [
"def",
"cmd_guess_labels",
"(",
"*",
"args",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"apply_labels",
"=",
"False",
"if",
"\"--apply\"",
"in",
"args",
":",
"apply_labels",
"=",
"True",
"args",
".",
"remove",
"(",
"\"--apply\"",
")",
"docid",
"=",... | Arguments: <document id> [-- [--apply]]
Guess the labels that should be set on the document.
Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "args": "(xxxx, )"
... | [
"Arguments",
":",
"<document",
"id",
">",
"[",
"--",
"[",
"--",
"apply",
"]]"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.