repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
gmr/rejected | rejected/mcp.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L628-L646 | def start_process(self, name):
"""Start a new consumer process for the given consumer name
:param str name: The consumer name
"""
process_name, proc = self.new_process(name)
LOGGER.info('Spawning %s process for %s', process_name, name)
# Append the process to the consu... | [
"def",
"start_process",
"(",
"self",
",",
"name",
")",
":",
"process_name",
",",
"proc",
"=",
"self",
".",
"new_process",
"(",
"name",
")",
"LOGGER",
".",
"info",
"(",
"'Spawning %s process for %s'",
",",
"process_name",
",",
"name",
")",
"# Append the process... | Start a new consumer process for the given consumer name
:param str name: The consumer name | [
"Start",
"a",
"new",
"consumer",
"process",
"for",
"the",
"given",
"consumer",
"name"
] | python | train | 34.368421 |
PGower/PyCanvas | pycanvas/apis/gradebook_history.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/gradebook_history.py#L88-L126 | def list_uncollated_submission_versions(self, course_id, ascending=None, assignment_id=None, user_id=None):
"""
List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects... | [
"def",
"list_uncollated_submission_versions",
"(",
"self",
",",
"course_id",
",",
"ascending",
"=",
"None",
",",
"assignment_id",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
... | List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects will not include
the +new_grade+ or +previous_grade+ keys, only the +grade+; same for
+graded_at+ and +grader+. | [
"List",
"uncollated",
"submission",
"versions",
".",
"Gives",
"a",
"paginated",
"uncollated",
"list",
"of",
"submission",
"versions",
"for",
"all",
"matching",
"submissions",
"in",
"the",
"context",
".",
"This",
"SubmissionVersion",
"objects",
"will",
"not",
"incl... | python | train | 46.974359 |
EpistasisLab/tpot | tpot/driver.py | https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/driver.py#L516-L574 | def tpot_driver(args):
"""Perform a TPOT run."""
if args.VERBOSITY >= 2:
_print_args(args)
input_data = _read_data_file(args)
features = input_data.drop(args.TARGET_NAME, axis=1)
training_features, testing_features, training_target, testing_target = \
train_test_split(features, inp... | [
"def",
"tpot_driver",
"(",
"args",
")",
":",
"if",
"args",
".",
"VERBOSITY",
">=",
"2",
":",
"_print_args",
"(",
"args",
")",
"input_data",
"=",
"_read_data_file",
"(",
"args",
")",
"features",
"=",
"input_data",
".",
"drop",
"(",
"args",
".",
"TARGET_NA... | Perform a TPOT run. | [
"Perform",
"a",
"TPOT",
"run",
"."
] | python | train | 39.135593 |
fake-name/ChromeController | ChromeController/Generator/Generated.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6341-L6359 | def Log_startViolationsReport(self, config):
"""
Function path: Log.startViolationsReport
Domain: Log
Method name: startViolationsReport
Parameters:
Required arguments:
'config' (type: array) -> Configuration for violations.
No return value.
Description: start violation reporting.
""... | [
"def",
"Log_startViolationsReport",
"(",
"self",
",",
"config",
")",
":",
"assert",
"isinstance",
"(",
"config",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"\"Argument 'config' must be of type '['list', 'tuple']'. Received type: '%s'\"",
"%",
"type",
"(",
"config"... | Function path: Log.startViolationsReport
Domain: Log
Method name: startViolationsReport
Parameters:
Required arguments:
'config' (type: array) -> Configuration for violations.
No return value.
Description: start violation reporting. | [
"Function",
"path",
":",
"Log",
".",
"startViolationsReport",
"Domain",
":",
"Log",
"Method",
"name",
":",
"startViolationsReport",
"Parameters",
":",
"Required",
"arguments",
":",
"config",
"(",
"type",
":",
"array",
")",
"-",
">",
"Configuration",
"for",
"vi... | python | train | 29.842105 |
Alignak-monitoring/alignak | alignak/acknowledge.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/acknowledge.py#L94-L104 | def serialize(self):
"""This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Acknowledge
:rtype: dict
"""
return {'u... | [
"def",
"serialize",
"(",
"self",
")",
":",
"return",
"{",
"'uuid'",
":",
"self",
".",
"uuid",
",",
"'ref'",
":",
"self",
".",
"ref",
",",
"'sticky'",
":",
"self",
".",
"sticky",
",",
"'notify'",
":",
"self",
".",
"notify",
",",
"'end_time'",
":",
"... | This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Acknowledge
:rtype: dict | [
"This",
"function",
"serialize",
"into",
"a",
"simple",
"dict",
"object",
".",
"It",
"is",
"used",
"when",
"transferring",
"data",
"to",
"other",
"daemons",
"over",
"the",
"network",
"(",
"http",
")"
] | python | train | 43.636364 |
maxalbert/tohu | tohu/v6/item_list.py | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L182-L280 | def to_csv(self, output_file=None, *, fields=None, fields_to_explode=None, append=False, header=True, header_prefix='', sep=',', newline='\n'):
"""
Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing... | [
"def",
"to_csv",
"(",
"self",
",",
"output_file",
"=",
"None",
",",
"*",
",",
"fields",
"=",
"None",
",",
"fields_to_explode",
"=",
"None",
",",
"append",
"=",
"False",
",",
"header",
"=",
"True",
",",
"header_prefix",
"=",
"''",
",",
"sep",
"=",
"',... | Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing content is
overwritten. Use `append=True` to open the file in append mode instead.
If `output_file` is None, the generated CSV output is re... | [
"Parameters",
"----------",
"output_file",
":",
"str",
"or",
"file",
"object",
"or",
"None",
"The",
"file",
"to",
"which",
"output",
"will",
"be",
"written",
".",
"By",
"default",
"any",
"existing",
"content",
"is",
"overwritten",
".",
"Use",
"append",
"=",
... | python | train | 48.363636 |
lcharleux/argiope | argiope/utils.py | https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/utils.py#L52-L66 | def list_to_string(l = range(200), width = 40, indent = " "):
"""
Converts a list-like to string with given line width.
"""
l = [str(v) + "," for v in l]
counter = 0
out = "" + indent
for w in l:
s = len(w)
if counter + s > width:
out += "\n" + indent
... | [
"def",
"list_to_string",
"(",
"l",
"=",
"range",
"(",
"200",
")",
",",
"width",
"=",
"40",
",",
"indent",
"=",
"\" \"",
")",
":",
"l",
"=",
"[",
"str",
"(",
"v",
")",
"+",
"\",\"",
"for",
"v",
"in",
"l",
"]",
"counter",
"=",
"0",
"out",
"=",... | Converts a list-like to string with given line width. | [
"Converts",
"a",
"list",
"-",
"like",
"to",
"string",
"with",
"given",
"line",
"width",
"."
] | python | test | 25.533333 |
frasertweedale/ledgertools | ltlib/ui.py | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L102-L148 | def filter_pastdate(string, default=None):
"""Coerce to a date not beyond the current date
If only a day is given, assumes the current month if that day has
passed or is the current day, otherwise assumes the previous month.
If a day and month are given, but no year, assumes the current year
if the... | [
"def",
"filter_pastdate",
"(",
"string",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"string",
"and",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"# split the string",
"... | Coerce to a date not beyond the current date
If only a day is given, assumes the current month if that day has
passed or is the current day, otherwise assumes the previous month.
If a day and month are given, but no year, assumes the current year
if the given date has passed (or is today), otherwise th... | [
"Coerce",
"to",
"a",
"date",
"not",
"beyond",
"the",
"current",
"date"
] | python | train | 32.638298 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py#L697-L700 | def fw_rule_update(self, data, fw_name=None):
"""Top level rule update routine. """
LOG.debug("FW Update Debug")
self._fw_rule_update(fw_name, data) | [
"def",
"fw_rule_update",
"(",
"self",
",",
"data",
",",
"fw_name",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"\"FW Update Debug\"",
")",
"self",
".",
"_fw_rule_update",
"(",
"fw_name",
",",
"data",
")"
] | Top level rule update routine. | [
"Top",
"level",
"rule",
"update",
"routine",
"."
] | python | train | 42.25 |
amperser/proselint | proselint/checks/misc/metadiscourse.py | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/misc/metadiscourse.py#L20-L33 | def check(text):
"""Suggest the preferred forms."""
err = "pinker.metadiscourse"
msg = "Excessive metadiscourse."
metadiscourse = [
"The preceeding discussion",
"The rest of this article",
"This chapter discusses",
"The preceding paragraph demonstrated",
"The pre... | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"pinker.metadiscourse\"",
"msg",
"=",
"\"Excessive metadiscourse.\"",
"metadiscourse",
"=",
"[",
"\"The preceeding discussion\"",
",",
"\"The rest of this article\"",
",",
"\"This chapter discusses\"",
",",
"\"The precedi... | Suggest the preferred forms. | [
"Suggest",
"the",
"preferred",
"forms",
"."
] | python | train | 28.285714 |
Trebek/pydealer | pydealer/tools.py | https://github.com/Trebek/pydealer/blob/2ac583dd8c55715658c740b614387775f4dda333/pydealer/tools.py#L248-L281 | def get_card(cards, term, limit=0, sort=False, ranks=None):
"""
Get the specified card from the stack.
:arg cards:
The cards to get from. Can be a ``Stack``, ``Deck`` or ``list``.
:arg str term:
The card's full name, value, suit, abbreviation, or stack indice.
:arg int limit:
... | [
"def",
"get_card",
"(",
"cards",
",",
"term",
",",
"limit",
"=",
"0",
",",
"sort",
"=",
"False",
",",
"ranks",
"=",
"None",
")",
":",
"got_cards",
"=",
"[",
"]",
"try",
":",
"indices",
"=",
"find_card",
"(",
"cards",
",",
"term",
",",
"limit",
"=... | Get the specified card from the stack.
:arg cards:
The cards to get from. Can be a ``Stack``, ``Deck`` or ``list``.
:arg str term:
The card's full name, value, suit, abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve for each term.
:arg bool sort:
... | [
"Get",
"the",
"specified",
"card",
"from",
"the",
"stack",
"."
] | python | train | 30.588235 |
oceanprotocol/squid-py | squid_py/keeper/conditions/sign.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/sign.py#L11-L29 | def fulfill(self, agreement_id, message, account_address, signature, from_account):
"""
Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreeme... | [
"def",
"fulfill",
"(",
"self",
",",
"agreement_id",
",",
"message",
",",
"account_address",
",",
"signature",
",",
"from_account",
")",
":",
"return",
"self",
".",
"_fulfill",
"(",
"agreement_id",
",",
"message",
",",
"account_address",
",",
"signature",
",",
... | Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreement hash, hex str
:param from_account: Account doing the transaction
:return: | [
"Fulfill",
"the",
"sign",
"conditon",
"."
] | python | train | 34.526316 |
boundary/pulse-api-cli | boundary/measurement_plot.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/measurement_plot.py#L115-L121 | def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
# ApiCli.get_arguments(self)
if self.args.file_name is not None:
self.file_name = self.args.file_name | [
"def",
"get_arguments",
"(",
"self",
")",
":",
"# ApiCli.get_arguments(self)",
"if",
"self",
".",
"args",
".",
"file_name",
"is",
"not",
"None",
":",
"self",
".",
"file_name",
"=",
"self",
".",
"args",
".",
"file_name"
] | Extracts the specific arguments of this CLI | [
"Extracts",
"the",
"specific",
"arguments",
"of",
"this",
"CLI"
] | python | test | 32 |
saltstack/salt | salt/modules/win_file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L594-L622 | def get_mode(path):
'''
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /... | [
"def",
"get_mode",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Path not found: {0}'",
".",
"format",
"(",
"path",
")",
")",
"func_name",
"=",
"'{0}.get_mode'",
".",
... | Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd | [
"Return",
"the",
"mode",
"of",
"a",
"file"
] | python | train | 25 |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_declared.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_declared.py#L15-L32 | def infer_declared(ms, namespace=None):
'''Retrieves any declared information from the given macaroons and returns
it as a key-value map.
Information is declared with a first party caveat as created by
declared_caveat.
If there are two caveats that declare the same key with different values,
th... | [
"def",
"infer_declared",
"(",
"ms",
",",
"namespace",
"=",
"None",
")",
":",
"conditions",
"=",
"[",
"]",
"for",
"m",
"in",
"ms",
":",
"for",
"cav",
"in",
"m",
".",
"caveats",
":",
"if",
"cav",
".",
"location",
"is",
"None",
"or",
"cav",
".",
"lo... | Retrieves any declared information from the given macaroons and returns
it as a key-value map.
Information is declared with a first party caveat as created by
declared_caveat.
If there are two caveats that declare the same key with different values,
the information is omitted from the map. When the... | [
"Retrieves",
"any",
"declared",
"information",
"from",
"the",
"given",
"macaroons",
"and",
"returns",
"it",
"as",
"a",
"key",
"-",
"value",
"map",
".",
"Information",
"is",
"declared",
"with",
"a",
"first",
"party",
"caveat",
"as",
"created",
"by",
"declared... | python | train | 45.333333 |
RobotStudio/bors | bors/app/api_factory.py | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/api_factory.py#L35-L40 | def shutdown(self):
"""Executed on shutdown of application"""
for wsock in self.wsocks:
wsock.shutdown()
for api in self.apis:
api.shutdown() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"for",
"wsock",
"in",
"self",
".",
"wsocks",
":",
"wsock",
".",
"shutdown",
"(",
")",
"for",
"api",
"in",
"self",
".",
"apis",
":",
"api",
".",
"shutdown",
"(",
")"
] | Executed on shutdown of application | [
"Executed",
"on",
"shutdown",
"of",
"application"
] | python | train | 30.666667 |
django-import-export/django-import-export | import_export/resources.py | https://github.com/django-import-export/django-import-export/blob/127f00d03fd0ad282615b064b7f444a639e6ff0c/import_export/resources.py#L324-L334 | def delete_instance(self, instance, using_transactions=True, dry_run=False):
"""
Calls :meth:`instance.delete` as long as ``dry_run`` is not set.
"""
self.before_delete_instance(instance, dry_run)
if not using_transactions and dry_run:
# we don't have transactions and... | [
"def",
"delete_instance",
"(",
"self",
",",
"instance",
",",
"using_transactions",
"=",
"True",
",",
"dry_run",
"=",
"False",
")",
":",
"self",
".",
"before_delete_instance",
"(",
"instance",
",",
"dry_run",
")",
"if",
"not",
"using_transactions",
"and",
"dry_... | Calls :meth:`instance.delete` as long as ``dry_run`` is not set. | [
"Calls",
":",
"meth",
":",
"instance",
".",
"delete",
"as",
"long",
"as",
"dry_run",
"is",
"not",
"set",
"."
] | python | train | 40.818182 |
jeradM/pyxeoma | pyxeoma/xeoma.py | https://github.com/jeradM/pyxeoma/blob/5bfa19c4968283af0f450acf80b4651cd718f389/pyxeoma/xeoma.py#L121-L130 | def get_session_cookie(self):
"""
Create a session cookie object for use by aiohttp
"""
if self._login is not None and self._password is not None:
session_key = self.encode_user(self._login, self._password)
return {'sessionkey': session_key}
else:
... | [
"def",
"get_session_cookie",
"(",
"self",
")",
":",
"if",
"self",
".",
"_login",
"is",
"not",
"None",
"and",
"self",
".",
"_password",
"is",
"not",
"None",
":",
"session_key",
"=",
"self",
".",
"encode_user",
"(",
"self",
".",
"_login",
",",
"self",
".... | Create a session cookie object for use by aiohttp | [
"Create",
"a",
"session",
"cookie",
"object",
"for",
"use",
"by",
"aiohttp"
] | python | train | 33.1 |
SKA-ScienceDataProcessor/integration-prototype | sip/execution_control/processing_block_controller/sip_pbc/tasks.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/processing_block_controller/sip_pbc/tasks.py#L190-L217 | def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict,
docker: DockerSwarmClient):
"""Abort the workflow.
TODO(BMo): This function currently does nothing as the abort flag
is hardcoded to False!
This function is used by `execute_processing_block`.
Args:
... | [
"def",
"_abort_workflow",
"(",
"pb",
":",
"ProcessingBlock",
",",
"workflow_stage_dict",
":",
"dict",
",",
"docker",
":",
"DockerSwarmClient",
")",
":",
"# TODO(BMo) Ask the database if the abort flag on the PB is set.",
"_abort_flag",
"=",
"False",
"if",
"_abort_flag",
"... | Abort the workflow.
TODO(BMo): This function currently does nothing as the abort flag
is hardcoded to False!
This function is used by `execute_processing_block`.
Args:
pb (ProcessingBlock): Configuration database Processing block object.
workflow_stage_dict (dict): Workflow stage ... | [
"Abort",
"the",
"workflow",
"."
] | python | train | 35.928571 |
kyuupichan/aiorpcX | aiorpcx/util.py | https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/util.py#L63-L77 | def classify_host(host):
'''Host is an IPv4Address, IPv6Address or a string.
If an IPv4Address or IPv6Address return it. Otherwise convert the string to an
IPv4Address or IPv6Address object if possible and return it. Otherwise return the
original string if it is a valid hostname.
Raise ValueErro... | [
"def",
"classify_host",
"(",
"host",
")",
":",
"if",
"isinstance",
"(",
"host",
",",
"(",
"IPv4Address",
",",
"IPv6Address",
")",
")",
":",
"return",
"host",
"if",
"is_valid_hostname",
"(",
"host",
")",
":",
"return",
"host",
"return",
"ip_address",
"(",
... | Host is an IPv4Address, IPv6Address or a string.
If an IPv4Address or IPv6Address return it. Otherwise convert the string to an
IPv4Address or IPv6Address object if possible and return it. Otherwise return the
original string if it is a valid hostname.
Raise ValueError if a string cannot be interpre... | [
"Host",
"is",
"an",
"IPv4Address",
"IPv6Address",
"or",
"a",
"string",
"."
] | python | train | 37 |
quantmind/dynts | dynts/api/timeseries.py | https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/api/timeseries.py#L220-L235 | def named_series(self, ordering=None):
'''Generator of tuples with name and serie data.'''
series = self.series()
if ordering:
series = list(series)
todo = dict(((n, idx) for idx, n in enumerate(self.names())))
for name in ordering:
if n... | [
"def",
"named_series",
"(",
"self",
",",
"ordering",
"=",
"None",
")",
":",
"series",
"=",
"self",
".",
"series",
"(",
")",
"if",
"ordering",
":",
"series",
"=",
"list",
"(",
"series",
")",
"todo",
"=",
"dict",
"(",
"(",
"(",
"n",
",",
"idx",
")"... | Generator of tuples with name and serie data. | [
"Generator",
"of",
"tuples",
"with",
"name",
"and",
"serie",
"data",
"."
] | python | train | 38.5625 |
dj-stripe/dj-stripe | djstripe/managers.py | https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/managers.py#L34-L41 | def started_plan_summary_for(self, year, month):
"""Return started_during Subscriptions with plan counts annotated."""
return (
self.started_during(year, month)
.values("plan")
.order_by()
.annotate(count=models.Count("plan"))
) | [
"def",
"started_plan_summary_for",
"(",
"self",
",",
"year",
",",
"month",
")",
":",
"return",
"(",
"self",
".",
"started_during",
"(",
"year",
",",
"month",
")",
".",
"values",
"(",
"\"plan\"",
")",
".",
"order_by",
"(",
")",
".",
"annotate",
"(",
"co... | Return started_during Subscriptions with plan counts annotated. | [
"Return",
"started_during",
"Subscriptions",
"with",
"plan",
"counts",
"annotated",
"."
] | python | train | 29.875 |
SpriteLink/NIPAP | nipap/nipap/xmlrpc.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/xmlrpc.py#L187-L212 | def add_vrf(self, args):
""" Add a new VRF.
Valid keys in the `args`-struct:
* `auth` [struct]
Authentication options passed to the :class:`AuthFactory`.
* `attr` [struct]
VRF attributes.
Returns the internal database ID for the ... | [
"def",
"add_vrf",
"(",
"self",
",",
"args",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"nip",
".",
"add_vrf",
"(",
"args",
".",
"get",
"(",
"'auth'",
")",
",",
"args",
".",
"get",
"(",
"'attr'",
")",
")",
"# fugly cast from large numbers to string ... | Add a new VRF.
Valid keys in the `args`-struct:
* `auth` [struct]
Authentication options passed to the :class:`AuthFactory`.
* `attr` [struct]
VRF attributes.
Returns the internal database ID for the VRF. | [
"Add",
"a",
"new",
"VRF",
"."
] | python | train | 35.576923 |
ReFirmLabs/binwalk | src/binwalk/modules/entropy.py | https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/modules/entropy.py#L221-L239 | def shannon(self, data):
'''
Performs a Shannon entropy analysis on a given block of data.
'''
entropy = 0
if data:
length = len(data)
seen = dict(((chr(x), 0) for x in range(0, 256)))
for byte in data:
seen[byte] += 1
... | [
"def",
"shannon",
"(",
"self",
",",
"data",
")",
":",
"entropy",
"=",
"0",
"if",
"data",
":",
"length",
"=",
"len",
"(",
"data",
")",
"seen",
"=",
"dict",
"(",
"(",
"(",
"chr",
"(",
"x",
")",
",",
"0",
")",
"for",
"x",
"in",
"range",
"(",
"... | Performs a Shannon entropy analysis on a given block of data. | [
"Performs",
"a",
"Shannon",
"entropy",
"analysis",
"on",
"a",
"given",
"block",
"of",
"data",
"."
] | python | train | 26 |
google-research/batch-ppo | agents/parts/normalize.py | https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/parts/normalize.py#L137-L153 | def _std(self):
"""Computes the current estimate of the standard deviation.
Note that the standard deviation is not defined until at least two samples
were seen.
Returns:
Tensor of current variance.
"""
variance = tf.cond(
self._count > 1,
lambda: self._var_sum / tf.cast(... | [
"def",
"_std",
"(",
"self",
")",
":",
"variance",
"=",
"tf",
".",
"cond",
"(",
"self",
".",
"_count",
">",
"1",
",",
"lambda",
":",
"self",
".",
"_var_sum",
"/",
"tf",
".",
"cast",
"(",
"self",
".",
"_count",
"-",
"1",
",",
"tf",
".",
"float32"... | Computes the current estimate of the standard deviation.
Note that the standard deviation is not defined until at least two samples
were seen.
Returns:
Tensor of current variance. | [
"Computes",
"the",
"current",
"estimate",
"of",
"the",
"standard",
"deviation",
"."
] | python | train | 34.823529 |
mkoura/dump2polarion | dump2polarion/exporters/transform.py | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/exporters/transform.py#L63-L86 | def include_class_in_title(result):
"""Makes sure that test class is included in "title".
e.g. "TestServiceRESTAPI.test_power_parent_service"
>>> result = {"title": "test_foo", "classname": "foo.bar.baz.TestFoo",
... "file": "foo/bar/baz.py"}
>>> include_class_in_title(result)
>>> str(resul... | [
"def",
"include_class_in_title",
"(",
"result",
")",
":",
"classname",
"=",
"result",
".",
"get",
"(",
"\"classname\"",
",",
"\"\"",
")",
"if",
"classname",
":",
"filepath",
"=",
"result",
".",
"get",
"(",
"\"file\"",
",",
"\"\"",
")",
"title",
"=",
"res... | Makes sure that test class is included in "title".
e.g. "TestServiceRESTAPI.test_power_parent_service"
>>> result = {"title": "test_foo", "classname": "foo.bar.baz.TestFoo",
... "file": "foo/bar/baz.py"}
>>> include_class_in_title(result)
>>> str(result.get("title"))
'TestFoo.test_foo'
... | [
"Makes",
"sure",
"that",
"test",
"class",
"is",
"included",
"in",
"title",
"."
] | python | train | 40.208333 |
pyca/pynacl | src/nacl/bindings/crypto_kx.py | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_kx.py#L38-L52 | def crypto_kx_keypair():
"""
Generate a keypair.
This is a duplicate crypto_box_keypair, but
is included for api consistency.
:return: (public_key, secret_key)
:rtype: (bytes, bytes)
"""
public_key = ffi.new("unsigned char[]", crypto_kx_PUBLIC_KEY_BYTES)
secret_key = ffi.new("unsigne... | [
"def",
"crypto_kx_keypair",
"(",
")",
":",
"public_key",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_kx_PUBLIC_KEY_BYTES",
")",
"secret_key",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_kx_SECRET_KEY_BYTES",
")",
"res",
"=... | Generate a keypair.
This is a duplicate crypto_box_keypair, but
is included for api consistency.
:return: (public_key, secret_key)
:rtype: (bytes, bytes) | [
"Generate",
"a",
"keypair",
".",
"This",
"is",
"a",
"duplicate",
"crypto_box_keypair",
"but",
"is",
"included",
"for",
"api",
"consistency",
".",
":",
"return",
":",
"(",
"public_key",
"secret_key",
")",
":",
"rtype",
":",
"(",
"bytes",
"bytes",
")"
] | python | train | 40.466667 |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2086-L2102 | def whoarewe(self,
shutit_pexpect_child=None,
note=None,
loglevel=logging.DEBUG):
"""Returns the current group.
@param shutit_pexpect_child: See send()
@param note: See send()
@return: the first group found
@rtype: string
"""
shutit_global.shutit_global_o... | [
"def",
"whoarewe",
"(",
"self",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"note",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"shutit_pexpect_child",
"... | Returns the current group.
@param shutit_pexpect_child: See send()
@param note: See send()
@return: the first group found
@rtype: string | [
"Returns",
"the",
"current",
"group",
"."
] | python | train | 37.294118 |
awslabs/aws-sam-cli | samcli/commands/local/lib/swagger/integration_uri.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/swagger/integration_uri.py#L173-L250 | def _resolve_fn_sub(uri_data):
"""
Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve
and produce a string output.
Example:
{
"Fn::Sub":
"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/funct... | [
"def",
"_resolve_fn_sub",
"(",
"uri_data",
")",
":",
"# Try the short form of Fn::Sub syntax where the value is the ARN",
"arn",
"=",
"uri_data",
"[",
"LambdaUri",
".",
"_FN_SUB",
"]",
"if",
"isinstance",
"(",
"arn",
",",
"list",
")",
":",
"# This is the long form of Fn... | Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve
and produce a string output.
Example:
{
"Fn::Sub":
"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations"
}
... | [
"Tries",
"to",
"resolve",
"an",
"Integration",
"URI",
"which",
"contains",
"Fn",
"::",
"Sub",
"intrinsic",
"function",
".",
"This",
"method",
"tries",
"to",
"resolve",
"and",
"produce",
"a",
"string",
"output",
"."
] | python | train | 41.320513 |
apple/turicreate | src/external/xgboost/python-package/xgboost/core.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/core.py#L855-L873 | def load_model(self, fname):
"""
Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw)
"""
if isinstance(fname, STRING_TYPES): # assume file name
if os.path... | [
"def",
"load_model",
"(",
"self",
",",
"fname",
")",
":",
"if",
"isinstance",
"(",
"fname",
",",
"STRING_TYPES",
")",
":",
"# assume file name",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"_LIB",
".",
"XGBoosterLoadModel",
"(",
"self... | Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw) | [
"Load",
"the",
"model",
"from",
"a",
"file",
"."
] | python | train | 36.894737 |
belbio/bel | bel/nanopub/nanopubs.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L85-L106 | def validate_context(
self, context: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]]:
""" Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool... | [
"def",
"validate_context",
"(",
"self",
",",
"context",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"bool",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"]",
":",
"url",
"=",
"f'{self.endpoint}/terms/{context[\... | Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is (... | [
"Validate",
"context"
] | python | train | 35.090909 |
serge-sans-paille/pythran | pythran/spec.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/spec.py#L290-L296 | def p_types(self, p):
'''types : type
| type COMMA types'''
if len(p) == 2:
p[0] = tuple((t,) for t in p[1])
else:
p[0] = tuple((t,) + ts for t in p[1] for ts in p[3]) | [
"def",
"p_types",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"tuple",
"(",
"(",
"t",
",",
")",
"for",
"t",
"in",
"p",
"[",
"1",
"]",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",... | types : type
| type COMMA types | [
"types",
":",
"type",
"|",
"type",
"COMMA",
"types"
] | python | train | 32.285714 |
odlgroup/odl | odl/operator/tensor_ops.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/tensor_ops.py#L1341-L1359 | def _call(self, x):
"""Sum all values if indices are given multiple times."""
y = np.bincount(self._indices_flat, weights=x,
minlength=self.range.size)
out = y.reshape(self.range.shape)
if self.variant == 'dirac':
weights = getattr(self.range, 'cell_... | [
"def",
"_call",
"(",
"self",
",",
"x",
")",
":",
"y",
"=",
"np",
".",
"bincount",
"(",
"self",
".",
"_indices_flat",
",",
"weights",
"=",
"x",
",",
"minlength",
"=",
"self",
".",
"range",
".",
"size",
")",
"out",
"=",
"y",
".",
"reshape",
"(",
... | Sum all values if indices are given multiple times. | [
"Sum",
"all",
"values",
"if",
"indices",
"are",
"given",
"multiple",
"times",
"."
] | python | train | 31.578947 |
dps/simplescheduler | simplescheduler/cli.py | https://github.com/dps/simplescheduler/blob/d633549a8b78d5c1ff37419f4970835f1c6a5947/simplescheduler/cli.py#L24-L42 | def main():
""" SimpleScheduler
redis parameters will be read from environment variables:
REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password)
"""
args = parser.parse_args()
scheduler = Scheduler()
print 'Start %s' % scheduler.scheduler_id
scheduler.interval = args.interval
if ar... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"scheduler",
"=",
"Scheduler",
"(",
")",
"print",
"'Start %s'",
"%",
"scheduler",
".",
"scheduler_id",
"scheduler",
".",
"interval",
"=",
"args",
".",
"interval",
"if",
"ar... | SimpleScheduler
redis parameters will be read from environment variables:
REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password) | [
"SimpleScheduler",
"redis",
"parameters",
"will",
"be",
"read",
"from",
"environment",
"variables",
":",
"REDIS_HOST",
"REDIS_PORT",
"REDIS_DB",
"REDIS_KEY",
"(",
"password",
")"
] | python | train | 33.684211 |
toumorokoshi/transmute-core | transmute_core/decorators.py | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/decorators.py#L5-L47 | def describe(**kwargs):
""" describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a... | [
"def",
"describe",
"(",
"*",
"*",
"kwargs",
")",
":",
"# if we have a single method, make it a list.",
"if",
"isinstance",
"(",
"kwargs",
".",
"get",
"(",
"\"paths\"",
")",
",",
"string_type",
")",
":",
"kwargs",
"[",
"\"paths\"",
"]",
"=",
"[",
"kwargs",
"[... | describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path)
:param list(str) met... | [
"describe",
"is",
"a",
"decorator",
"to",
"customize",
"the",
"rest",
"API",
"that",
"transmute",
"generates",
"such",
"as",
"choosing",
"certain",
"arguments",
"to",
"be",
"query",
"parameters",
"or",
"body",
"parameters",
"or",
"a",
"different",
"method",
".... | python | train | 43.325581 |
gwastro/pycbc | pycbc/types/timeseries.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/timeseries.py#L424-L433 | def save_to_wav(self, file_name):
""" Save this time series to a wav format audio file.
Parameters
----------
file_name : string
The output file name
"""
scaled = _numpy.int16(self.numpy()/max(abs(self)) * 32767)
write_wav(file_name, self.sample_rate... | [
"def",
"save_to_wav",
"(",
"self",
",",
"file_name",
")",
":",
"scaled",
"=",
"_numpy",
".",
"int16",
"(",
"self",
".",
"numpy",
"(",
")",
"/",
"max",
"(",
"abs",
"(",
"self",
")",
")",
"*",
"32767",
")",
"write_wav",
"(",
"file_name",
",",
"self",... | Save this time series to a wav format audio file.
Parameters
----------
file_name : string
The output file name | [
"Save",
"this",
"time",
"series",
"to",
"a",
"wav",
"format",
"audio",
"file",
"."
] | python | train | 32 |
molmod/molmod | molmod/graphs.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/graphs.py#L1402-L1407 | def compare(self, vertex0, vertex1, subject_graph):
"""Returns true when the two vertices are of the same kind"""
return (
self.pattern_graph.vertex_fingerprints[vertex0] ==
subject_graph.vertex_fingerprints[vertex1]
).all() | [
"def",
"compare",
"(",
"self",
",",
"vertex0",
",",
"vertex1",
",",
"subject_graph",
")",
":",
"return",
"(",
"self",
".",
"pattern_graph",
".",
"vertex_fingerprints",
"[",
"vertex0",
"]",
"==",
"subject_graph",
".",
"vertex_fingerprints",
"[",
"vertex1",
"]",... | Returns true when the two vertices are of the same kind | [
"Returns",
"true",
"when",
"the",
"two",
"vertices",
"are",
"of",
"the",
"same",
"kind"
] | python | train | 44.5 |
log2timeline/plaso | plaso/preprocessors/macos.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/macos.py#L159-L169 | def _ParsePlistKeyValue(self, knowledge_base, name, value):
"""Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key.
"""
if not knowledge_base.GetValue('operating_... | [
"def",
"_ParsePlistKeyValue",
"(",
"self",
",",
"knowledge_base",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"knowledge_base",
".",
"GetValue",
"(",
"'operating_system_version'",
")",
":",
"if",
"name",
"in",
"self",
".",
"_PLIST_KEYS",
":",
"knowledge_... | Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key. | [
"Parses",
"a",
"plist",
"key",
"value",
"."
] | python | train | 39 |
saltstack/salt | salt/modules/dockermod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockermod.py#L1899-L1914 | def list_tags():
'''
Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion docker.list_tags
'''
ret = set()
for item in six.itervalues(images()):
if not item.get('RepoTags'):
continue
ret.update(set(item['RepoTags']))
retur... | [
"def",
"list_tags",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"six",
".",
"itervalues",
"(",
"images",
"(",
")",
")",
":",
"if",
"not",
"item",
".",
"get",
"(",
"'RepoTags'",
")",
":",
"continue",
"ret",
".",
"update",
"(",... | Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion docker.list_tags | [
"Returns",
"a",
"list",
"of",
"tagged",
"images"
] | python | train | 19.875 |
reiinakano/scikit-plot | scikitplot/metrics.py | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/metrics.py#L1045-L1130 | def plot_cumulative_gain(y_true, y_probas, title='Cumulative Gains Curve',
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates the Cumulative Gains Plot from labels and scores/probabilities
The cumulative gains chart is used to ... | [
"def",
"plot_cumulative_gain",
"(",
"y_true",
",",
"y_probas",
",",
"title",
"=",
"'Cumulative Gains Curve'",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"title_fontsize",
"=",
"\"large\"",
",",
"text_fontsize",
"=",
"\"medium\"",
")",
":",
"y_tr... | Generates the Cumulative Gains Plot from labels and scores/probabilities
The cumulative gains chart is used to determine the effectiveness of a
binary classifier. A detailed explanation can be found at
http://mlwiki.org/index.php/Cumulative_Gain_Chart. The implementation
here works only for binary clas... | [
"Generates",
"the",
"Cumulative",
"Gains",
"Plot",
"from",
"labels",
"and",
"scores",
"/",
"probabilities"
] | python | train | 37.988372 |
pydata/xarray | xarray/backends/api.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/backends/api.py#L854-L950 | def save_mfdataset(datasets, paths, mode='w', format=None, groups=None,
engine=None, compute=True):
"""Write multiple datasets to disk as netCDF files simultaneously.
This function is intended for use with datasets consisting of dask.array
objects, in which case it can write the multiple... | [
"def",
"save_mfdataset",
"(",
"datasets",
",",
"paths",
",",
"mode",
"=",
"'w'",
",",
"format",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"compute",
"=",
"True",
")",
":",
"if",
"mode",
"==",
"'w'",
"and",
"len",
"("... | Write multiple datasets to disk as netCDF files simultaneously.
This function is intended for use with datasets consisting of dask.array
objects, in which case it can write the multiple datasets to disk
simultaneously using a shared thread pool.
When not using dask, it is no different than calling ``t... | [
"Write",
"multiple",
"datasets",
"to",
"disk",
"as",
"netCDF",
"files",
"simultaneously",
"."
] | python | train | 41.103093 |
apache/airflow | airflow/utils/dag_processing.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L645-L679 | def end(self):
"""
Terminate (and then kill) the manager process launched.
:return:
"""
if not self._process:
self.log.warn('Ending without manager process.')
return
this_process = psutil.Process(os.getpid())
try:
manager_proces... | [
"def",
"end",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_process",
":",
"self",
".",
"log",
".",
"warn",
"(",
"'Ending without manager process.'",
")",
"return",
"this_process",
"=",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
... | Terminate (and then kill) the manager process launched.
:return: | [
"Terminate",
"(",
"and",
"then",
"kill",
")",
"the",
"manager",
"process",
"launched",
".",
":",
"return",
":"
] | python | test | 40.171429 |
adafruit/Adafruit_CircuitPython_BME280 | adafruit_bme280.py | https://github.com/adafruit/Adafruit_CircuitPython_BME280/blob/febcd51983dc2bc3cd006bacaada505251c39af1/adafruit_bme280.py#L300-L309 | def measurement_time_typical(self):
"""Typical time in milliseconds required to complete a measurement in normal mode"""
meas_time_ms = 1.0
if self.overscan_temperature != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_temperature))
if self.oversca... | [
"def",
"measurement_time_typical",
"(",
"self",
")",
":",
"meas_time_ms",
"=",
"1.0",
"if",
"self",
".",
"overscan_temperature",
"!=",
"OVERSCAN_DISABLE",
":",
"meas_time_ms",
"+=",
"(",
"2",
"*",
"_BME280_OVERSCANS",
".",
"get",
"(",
"self",
".",
"overscan_temp... | Typical time in milliseconds required to complete a measurement in normal mode | [
"Typical",
"time",
"in",
"milliseconds",
"required",
"to",
"complete",
"a",
"measurement",
"in",
"normal",
"mode"
] | python | train | 59.7 |
PythonCharmers/python-future | src/future/backports/email/utils.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L80-L110 | def formataddr(pair, charset='utf-8'):
"""The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified.
O... | [
"def",
"formataddr",
"(",
"pair",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"name",
",",
"address",
"=",
"pair",
"# The address MUST (per RFC) be ascii, so raise an UnicodeError if it isn't.",
"address",
".",
"encode",
"(",
"'ascii'",
")",
"if",
"name",
":",
"try",
... | The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified.
Optional charset if given is the character set ... | [
"The",
"inverse",
"of",
"parseaddr",
"()",
"this",
"takes",
"a",
"2",
"-",
"tuple",
"of",
"the",
"form",
"(",
"realname",
"email_address",
")",
"and",
"returns",
"the",
"string",
"value",
"suitable",
"for",
"an",
"RFC",
"2822",
"From",
"To",
"or",
"Cc",
... | python | train | 38.580645 |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L3640-L3660 | def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"in",
"(",
"'add_subscriptions'",
",",
"'remove_subscriptions'",
")",
":",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"super",
"(",
"HostSubscription",
",",
"self",
")",
".",
... | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super`` is called otherwise. | [
"Extend",
"nailgun",
".",
"entity_mixins",
".",
"Entity",
".",
"path",
"."
] | python | train | 30.095238 |
coops/r53 | src/r53/r53.py | https://github.com/coops/r53/blob/3c4e7242ad65b0e1ad4ba6b4ac893c7d501ceb0a/src/r53/r53.py#L114-L161 | def generate_changeset(old, new, comment=None):
"""Diff two XML configs and return an object with changes to be written.
Args: old, new: lxml.etree.Element (<ResourceRecordSets>).
Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None"""
rrsets_tag = '{%s}ResourceRecordSets' % R53_XMLNS
if rrs... | [
"def",
"generate_changeset",
"(",
"old",
",",
"new",
",",
"comment",
"=",
"None",
")",
":",
"rrsets_tag",
"=",
"'{%s}ResourceRecordSets'",
"%",
"R53_XMLNS",
"if",
"rrsets_tag",
"not",
"in",
"(",
"old",
".",
"tag",
",",
"new",
".",
"tag",
")",
":",
"log",... | Diff two XML configs and return an object with changes to be written.
Args: old, new: lxml.etree.Element (<ResourceRecordSets>).
Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None | [
"Diff",
"two",
"XML",
"configs",
"and",
"return",
"an",
"object",
"with",
"changes",
"to",
"be",
"written",
"."
] | python | test | 40.979167 |
roboogle/gtkmvc3 | gtkmvco/examples/undo/undo_manager.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/undo/undo_manager.py#L165-L175 | def undo(self):
"""
Raises IndexError if more than one group is open, otherwise closes it
and invokes undo_nested_group.
"""
if self.grouping_level() == 1:
self.end_grouping()
if self._open:
raise IndexError
self.undo_nested_group()
... | [
"def",
"undo",
"(",
"self",
")",
":",
"if",
"self",
".",
"grouping_level",
"(",
")",
"==",
"1",
":",
"self",
".",
"end_grouping",
"(",
")",
"if",
"self",
".",
"_open",
":",
"raise",
"IndexError",
"self",
".",
"undo_nested_group",
"(",
")",
"self",
".... | Raises IndexError if more than one group is open, otherwise closes it
and invokes undo_nested_group. | [
"Raises",
"IndexError",
"if",
"more",
"than",
"one",
"group",
"is",
"open",
"otherwise",
"closes",
"it",
"and",
"invokes",
"undo_nested_group",
"."
] | python | train | 29.454545 |
fermiPy/fermipy | fermipy/jobs/gtlink.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/gtlink.py#L243-L256 | def command_template(self):
"""Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)`
"""
com_out = self.appname
for key, val i... | [
"def",
"command_template",
"(",
"self",
")",
":",
"com_out",
"=",
"self",
".",
"appname",
"for",
"key",
",",
"val",
"in",
"self",
".",
"args",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"_options",
":",
"com_out",
"+=",
"' %s={%s}'"... | Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)` | [
"Build",
"and",
"return",
"a",
"string",
"that",
"can",
"be",
"used",
"as",
"a",
"template",
"invoking",
"this",
"chain",
"from",
"the",
"command",
"line",
"."
] | python | train | 36.071429 |
Yelp/service_configuration_lib | service_configuration_lib/__init__.py | https://github.com/Yelp/service_configuration_lib/blob/83ac2872f95dd204e9f83ec95b4296a9501bf82d/service_configuration_lib/__init__.py#L270-L290 | def all_nodes_that_run_in_env(service, env, service_configuration=None):
""" Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to no... | [
"def",
"all_nodes_that_run_in_env",
"(",
"service",
",",
"env",
",",
"service_configuration",
"=",
"None",
")",
":",
"if",
"service_configuration",
"is",
"None",
":",
"service_configuration",
"=",
"read_services_configuration",
"(",
")",
"env_runs_on",
"=",
"service_c... | Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to nodes).
:param service: A string specifying which service to look up nodes for... | [
"Returns",
"all",
"nodes",
"that",
"run",
"in",
"an",
"environment",
".",
"This",
"needs",
"to",
"be",
"specified",
"in",
"field",
"named",
"env_runs_on",
"one",
"level",
"under",
"services",
"in",
"the",
"configuration",
"and",
"needs",
"to",
"contain",
"an... | python | train | 44.904762 |
KenLauLab/NVR | nvr/NVR.py | https://github.com/KenLauLab/NVR/blob/ca9b292d78a3ca6ad93ae327a203feed8ed47948/nvr/NVR.py#L28-L40 | def parseNoise(rawArray):
'''
Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices
'''
nnGenes=[]
for i in range(0,(rawArray.shape[1])): #Checks all genes
count... | [
"def",
"parseNoise",
"(",
"rawArray",
")",
":",
"nnGenes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"(",
"rawArray",
".",
"shape",
"[",
"1",
"]",
")",
")",
":",
"#Checks all genes",
"count0",
"=",
"np",
".",
"asarray",
"(",
"np",
... | Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices | [
"Function",
"returns",
"indices",
"that",
"contain",
"non",
"-",
"noisy",
"genes",
"as",
"an",
"integer",
"array",
":",
"param",
"rawArray",
":",
"numpy",
"ndarray",
"of",
"data",
"set",
":",
"return",
"nnGenes",
":",
"numpy",
"ndarray",
"of",
"non",
"-",
... | python | train | 41.538462 |
pydanny-archive/django-wysiwyg | django_wysiwyg/utils.py | https://github.com/pydanny-archive/django-wysiwyg/blob/f05866356d417309624ec4863acdebd2084b1bc2/django_wysiwyg/utils.py#L11-L30 | def clean_html5lib(input):
"""
Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed.
>>> clean_html5lib("<p>Foo<b>bar</b></p>")
u'<p>Foo<b>bar</b></p>'
>>> clean_html5lib("<p>Foo<b>bar</b><i>Ooops!</p>")
u'<p>Foo<b>bar</b><i>Ooops!</i></p>'
>>> clean... | [
"def",
"clean_html5lib",
"(",
"input",
")",
":",
"from",
"html5lib",
"import",
"treebuilders",
",",
"treewalkers",
",",
"serializer",
",",
"sanitizer",
"p",
"=",
"html5lib",
".",
"HTMLParser",
"(",
"tree",
"=",
"treebuilders",
".",
"getTreeBuilder",
"(",
"\"do... | Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed.
>>> clean_html5lib("<p>Foo<b>bar</b></p>")
u'<p>Foo<b>bar</b></p>'
>>> clean_html5lib("<p>Foo<b>bar</b><i>Ooops!</p>")
u'<p>Foo<b>bar</b><i>Ooops!</i></p>'
>>> clean_html5lib('<p>Foo<b>bar</b>& oops<a hre... | [
"Takes",
"an",
"HTML",
"fragment",
"and",
"processes",
"it",
"using",
"html5lib",
"to",
"ensure",
"that",
"the",
"HTML",
"is",
"well",
"-",
"formed",
"."
] | python | train | 42.3 |
WebarchivCZ/WA-KAT | src/wa_kat/analyzers/place_detector.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/analyzers/place_detector.py#L108-L128 | def get_place_tags(index_page, domain): #: TODO geoip to docstring
"""
Return list of `place` tags parsed from `meta` and `whois`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
domain (str): Domain of the web, without ``http://`` or other parts.
Returns:
... | [
"def",
"get_place_tags",
"(",
"index_page",
",",
"domain",
")",
":",
"#: TODO geoip to docstring",
"ip_address",
"=",
"get_ip_address",
"(",
"domain",
")",
"dom",
"=",
"dhtmlparser",
".",
"parseString",
"(",
"index_page",
")",
"place_tags",
"=",
"[",
"get_html_geo... | Return list of `place` tags parsed from `meta` and `whois`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
domain (str): Domain of the web, without ``http://`` or other parts.
Returns:
list: List of :class:`.SourceString` objects. | [
"Return",
"list",
"of",
"place",
"tags",
"parsed",
"from",
"meta",
"and",
"whois",
"."
] | python | train | 30.619048 |
jelmer/python-fastimport | fastimport/processors/filter_processor.py | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processors/filter_processor.py#L164-L193 | def _filter_filecommands(self, filecmd_iter):
"""Return the filecommands filtered by includes & excludes.
:return: a list of FileCommand objects
"""
if self.includes is None and self.excludes is None:
return list(filecmd_iter())
# Do the filtering, adjusting for the... | [
"def",
"_filter_filecommands",
"(",
"self",
",",
"filecmd_iter",
")",
":",
"if",
"self",
".",
"includes",
"is",
"None",
"and",
"self",
".",
"excludes",
"is",
"None",
":",
"return",
"list",
"(",
"filecmd_iter",
"(",
")",
")",
"# Do the filtering, adjusting for ... | Return the filecommands filtered by includes & excludes.
:return: a list of FileCommand objects | [
"Return",
"the",
"filecommands",
"filtered",
"by",
"includes",
"&",
"excludes",
"."
] | python | train | 39.633333 |
matrix-org/matrix-python-sdk | matrix_client/api.py | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/api.py#L1041-L1053 | def claim_keys(self, key_request, timeout=None):
"""Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) t... | [
"def",
"claim_keys",
"(",
"self",
",",
"key_request",
",",
"timeout",
"=",
"None",
")",
":",
"content",
"=",
"{",
"\"one_time_keys\"",
":",
"key_request",
"}",
"if",
"timeout",
":",
"content",
"[",
"\"timeout\"",
"]",
"=",
"timeout",
"return",
"self",
".",... | Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote ser... | [
"Claims",
"one",
"-",
"time",
"keys",
"for",
"use",
"in",
"pre",
"-",
"key",
"messages",
"."
] | python | train | 43.153846 |
XuShaohua/bcloud | bcloud/auth.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/auth.py#L104-L130 | def check_login(cookie, tokens, username):
'''进行登录验证, 主要是在服务器上验证这个帐户的状态.
如果帐户不存在, 或者帐户异常, 就不需要再进行最后一步的登录操作了.
这一步有可能需要输入验证码.
返回的信息如下:
{"errInfo":{ "no": "0" }, "data": { "codeString" : "", "vcodetype" : "" }}
'''
url = ''.join([
const.PASSPORT_URL,
'?logincheck',
'&to... | [
"def",
"check_login",
"(",
"cookie",
",",
"tokens",
",",
"username",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PASSPORT_URL",
",",
"'?logincheck'",
",",
"'&token='",
",",
"tokens",
"[",
"'token'",
"]",
",",
"'&tpl=mm&apiver=v3'",
... | 进行登录验证, 主要是在服务器上验证这个帐户的状态.
如果帐户不存在, 或者帐户异常, 就不需要再进行最后一步的登录操作了.
这一步有可能需要输入验证码.
返回的信息如下:
{"errInfo":{ "no": "0" }, "data": { "codeString" : "", "vcodetype" : "" }} | [
"进行登录验证",
"主要是在服务器上验证这个帐户的状态",
"."
] | python | train | 27.962963 |
poldracklab/niworkflows | niworkflows/interfaces/confounds.py | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/confounds.py#L247-L288 | def temporal_derivatives(order, variables, data):
"""
Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second de... | [
"def",
"temporal_derivatives",
"(",
"order",
",",
"variables",
",",
"data",
")",
":",
"variables_deriv",
"=",
"OrderedDict",
"(",
")",
"data_deriv",
"=",
"OrderedDict",
"(",
")",
"if",
"0",
"in",
"order",
":",
"data_deriv",
"[",
"0",
"]",
"=",
"data",
"[... | Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second derivative terms should be added.
To retain the original... | [
"Compute",
"temporal",
"derivative",
"terms",
"by",
"the",
"method",
"of",
"backwards",
"differences",
"."
] | python | train | 40.309524 |
misakar/mana | mana/mana.py | https://github.com/misakar/mana/blob/95ccdbf230ed7abc33ea2c878c66d2c8fc72ea69/mana/mana.py#L90-L107 | def create_templates_static_files(app_path):
"""
create templates and static
"""
templates_path = os.path.join(app_path, 'templates')
static_path = os.path.join(app_path, 'static')
_mkdir_p(templates_path)
_mkdir_p(static_path)
# create {img, css, js}
os.chdir(static_path)
img_pa... | [
"def",
"create_templates_static_files",
"(",
"app_path",
")",
":",
"templates_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_path",
",",
"'templates'",
")",
"static_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_path",
",",
"'static'",
")",
"... | create templates and static | [
"create",
"templates",
"and",
"static"
] | python | train | 29.944444 |
google/grr | grr/core/grr_response_core/lib/parsers/config_file.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/config_file.py#L677-L706 | def ParseAction(self, action):
"""Extract log configuration data from rsyslog actions.
Actions have the format:
<facility>/<severity> <type_def><destination>;<template>
e.g. *.* @@loghost.example.com.:514;RSYSLOG_ForwardFormat
Actions are selected by a type definition. These include:
"@@... | [
"def",
"ParseAction",
"(",
"self",
",",
"action",
")",
":",
"rslt",
"=",
"rdf_config_file",
".",
"LogTarget",
"(",
")",
"for",
"dst_str",
",",
"dst_re",
"in",
"iteritems",
"(",
"self",
".",
"destinations",
")",
":",
"dst",
"=",
"dst_re",
".",
"match",
... | Extract log configuration data from rsyslog actions.
Actions have the format:
<facility>/<severity> <type_def><destination>;<template>
e.g. *.* @@loghost.example.com.:514;RSYSLOG_ForwardFormat
Actions are selected by a type definition. These include:
"@@": TCP syslog
"@": UDP syslog
... | [
"Extract",
"log",
"configuration",
"data",
"from",
"rsyslog",
"actions",
"."
] | python | train | 27.433333 |
ryanpetrello/sdb | sdb.py | https://github.com/ryanpetrello/sdb/blob/4a198757a17e753ac88081d192ecc952b4228a36/sdb.py#L268-L273 | def debugger():
"""Return the current debugger instance, or create if none."""
sdb = _current[0]
if sdb is None or not sdb.active:
sdb = _current[0] = Sdb()
return sdb | [
"def",
"debugger",
"(",
")",
":",
"sdb",
"=",
"_current",
"[",
"0",
"]",
"if",
"sdb",
"is",
"None",
"or",
"not",
"sdb",
".",
"active",
":",
"sdb",
"=",
"_current",
"[",
"0",
"]",
"=",
"Sdb",
"(",
")",
"return",
"sdb"
] | Return the current debugger instance, or create if none. | [
"Return",
"the",
"current",
"debugger",
"instance",
"or",
"create",
"if",
"none",
"."
] | python | train | 31 |
yvesalexandre/bandicoot | bandicoot/individual.py | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/individual.py#L376-L405 | def balance_of_contacts(records, weighted=True):
"""
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\fra... | [
"def",
"balance_of_contacts",
"(",
"records",
",",
"weighted",
"=",
"True",
")",
":",
"counter_out",
"=",
"defaultdict",
"(",
"int",
")",
"counter",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"r",
"in",
"records",
":",
"if",
"r",
".",
"direction",
"==",... | The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\frac{\\bigl|\\text{outgoing}\,(c)\\bigr|}{\\bigl|\\text{outgoing... | [
"The",
"balance",
"of",
"interactions",
"per",
"contact",
".",
"For",
"every",
"contact",
"the",
"balance",
"is",
"the",
"number",
"of",
"outgoing",
"interactions",
"divided",
"by",
"the",
"total",
"number",
"of",
"interactions",
"(",
"in",
"+",
"out",
")",
... | python | train | 34.066667 |
postlund/pyatv | pyatv/mrp/srp.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L193-L215 | def step4(self, encrypted_data):
"""Last pairing step."""
chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
decrypted_tlv_bytes = chacha.decrypt(
encrypted_data, nounce='PS-Msg06'.encode())
if not decrypted_tlv_bytes:
raise Exception('data dec... | [
"def",
"step4",
"(",
"self",
",",
"encrypted_data",
")",
":",
"chacha",
"=",
"chacha20",
".",
"Chacha20Cipher",
"(",
"self",
".",
"_session_key",
",",
"self",
".",
"_session_key",
")",
"decrypted_tlv_bytes",
"=",
"chacha",
".",
"decrypt",
"(",
"encrypted_data"... | Last pairing step. | [
"Last",
"pairing",
"step",
"."
] | python | train | 42.478261 |
daxlab/Flask-Cache-Buster | flask_cache_buster/__init__.py | https://github.com/daxlab/Flask-Cache-Buster/blob/4c10bed9ab46020904df565a9c0014a7f2e4f6b3/flask_cache_buster/__init__.py#L20-L27 | def __is_file_to_be_busted(self, filepath):
"""
:param filepath:
:return: True or False
"""
if not self.extensions:
return True
return Path(filepath).suffix in self.extensions if filepath else False | [
"def",
"__is_file_to_be_busted",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"not",
"self",
".",
"extensions",
":",
"return",
"True",
"return",
"Path",
"(",
"filepath",
")",
".",
"suffix",
"in",
"self",
".",
"extensions",
"if",
"filepath",
"else",
"False... | :param filepath:
:return: True or False | [
":",
"param",
"filepath",
":",
":",
"return",
":",
"True",
"or",
"False"
] | python | train | 31.375 |
saltstack/salt | salt/modules/win_lgpo.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_lgpo.py#L4447-L4459 | def _binary_enable_zero_disable_one_reverse_conversion(cls, val, **kwargs):
'''
converts Enabled/Disabled to unicode char to write to a REG_BINARY value
'''
if val is not None:
if val.upper() == 'DISABLED':
return chr(0)
elif val.upper() == 'ENABLE... | [
"def",
"_binary_enable_zero_disable_one_reverse_conversion",
"(",
"cls",
",",
"val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"val",
"is",
"not",
"None",
":",
"if",
"val",
".",
"upper",
"(",
")",
"==",
"'DISABLED'",
":",
"return",
"chr",
"(",
"0",
")",
... | converts Enabled/Disabled to unicode char to write to a REG_BINARY value | [
"converts",
"Enabled",
"/",
"Disabled",
"to",
"unicode",
"char",
"to",
"write",
"to",
"a",
"REG_BINARY",
"value"
] | python | train | 32.692308 |
jupyter-widgets/ipywidgets | ipywidgets/widgets/widget_selection.py | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/widget_selection.py#L108-L131 | def _make_options(x):
"""Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated
"""
# Check if x is a mapping of... | [
"def",
"_make_options",
"(",
"x",
")",
":",
"# Check if x is a mapping of labels to values",
"if",
"isinstance",
"(",
"x",
",",
"Mapping",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"Support for mapping types has been deprecated and will be dropped in a... | Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated | [
"Standardize",
"the",
"options",
"tuple",
"format",
"."
] | python | train | 38.833333 |
jssimporter/python-jss | jss/jss_prefs.py | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jss_prefs.py#L199-L239 | def _handle_repos(self, root):
"""Handle repo configuration."""
ElementTree.SubElement(root, "key").text = "repos"
repos_array = ElementTree.SubElement(root, "array")
# Make a temporary jss object to try to pull repo information.
jss_server = JSS(url=self.url, user=self.user, pa... | [
"def",
"_handle_repos",
"(",
"self",
",",
"root",
")",
":",
"ElementTree",
".",
"SubElement",
"(",
"root",
",",
"\"key\"",
")",
".",
"text",
"=",
"\"repos\"",
"repos_array",
"=",
"ElementTree",
".",
"SubElement",
"(",
"root",
",",
"\"array\"",
")",
"# Make... | Handle repo configuration. | [
"Handle",
"repo",
"configuration",
"."
] | python | train | 48.97561 |
hyperledger/indy-sdk | wrappers/python/indy/wallet.py | https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/wallet.py#L214-L250 | async def export_wallet(handle: int,
export_config_json: str) -> None:
"""
Exports opened wallet to the file.
:param handle: wallet handle returned by indy_open_wallet.
:param export_config_json: JSON containing settings for input operation.
{
"path": path of th... | [
"async",
"def",
"export_wallet",
"(",
"handle",
":",
"int",
",",
"export_config_json",
":",
"str",
")",
"->",
"None",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"export_wallet: >>> handle: %r, export_con... | Exports opened wallet to the file.
:param handle: wallet handle returned by indy_open_wallet.
:param export_config_json: JSON containing settings for input operation.
{
"path": path of the file that contains exported wallet content
"key": string, Key or passphrase used for wallet exp... | [
"Exports",
"opened",
"wallet",
"to",
"the",
"file",
"."
] | python | train | 44.378378 |
roboogle/gtkmvc3 | gtkmvco/gtkmvc3/adapters/basic.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L472-L476 | def _set_property(self, val, *args):
"""Private method that sets the value currently of the property"""
if self._prop_write:
val = self._prop_write(val)
return self._setter(Adapter._get_property(self), val, *args) | [
"def",
"_set_property",
"(",
"self",
",",
"val",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"_prop_write",
":",
"val",
"=",
"self",
".",
"_prop_write",
"(",
"val",
")",
"return",
"self",
".",
"_setter",
"(",
"Adapter",
".",
"_get_property",
"(",
... | Private method that sets the value currently of the property | [
"Private",
"method",
"that",
"sets",
"the",
"value",
"currently",
"of",
"the",
"property"
] | python | train | 49 |
henzk/ape | ape/_tasks.py | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/_tasks.py#L25-L90 | def explain_feature(featurename):
'''print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files
'''
import os
import featuremonkey
import importlib
import subprocess
def guess_version(... | [
"def",
"explain_feature",
"(",
"featurename",
")",
":",
"import",
"os",
"import",
"featuremonkey",
"import",
"importlib",
"import",
"subprocess",
"def",
"guess_version",
"(",
"feature_module",
")",
":",
"if",
"hasattr",
"(",
"feature_module",
",",
"'__version__'",
... | print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files | [
"print",
"the",
"location",
"of",
"single",
"feature",
"and",
"its",
"version"
] | python | train | 33.621212 |
modin-project/modin | modin/backends/pandas/query_compiler.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pandas/query_compiler.py#L1168-L1185 | def first_valid_index(self):
"""Returns index of first non-NaN/NULL value.
Return:
Scalar of index name.
"""
# It may be possible to incrementally check each partition, but this
# computation is fairly cheap.
def first_valid_index_builder(df):
df.... | [
"def",
"first_valid_index",
"(",
"self",
")",
":",
"# It may be possible to incrementally check each partition, but this",
"# computation is fairly cheap.",
"def",
"first_valid_index_builder",
"(",
"df",
")",
":",
"df",
".",
"index",
"=",
"pandas",
".",
"RangeIndex",
"(",
... | Returns index of first non-NaN/NULL value.
Return:
Scalar of index name. | [
"Returns",
"index",
"of",
"first",
"non",
"-",
"NaN",
"/",
"NULL",
"value",
"."
] | python | train | 45.388889 |
tango-controls/pytango | tango/utils.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/utils.py#L1209-L1215 | def append(self, item):
"""Adds an item to the list and checks it's a string."""
if not isinstance(item, str):
raise TypeError(
'Members of this object must be strings. '
'You supplied \"%s\"' % type(item))
list.append(self, item) | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Members of this object must be strings. '",
"'You supplied \\\"%s\\\"'",
"%",
"type",
"(",
"item",
")",
")",
"list",... | Adds an item to the list and checks it's a string. | [
"Adds",
"an",
"item",
"to",
"the",
"list",
"and",
"checks",
"it",
"s",
"a",
"string",
"."
] | python | train | 41.714286 |
UCSBarchlab/PyRTL | pyrtl/rtllib/adders.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/adders.py#L6-L37 | def kogge_stone(a, b, cin=0):
"""
Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone ad... | [
"def",
"kogge_stone",
"(",
"a",
",",
"b",
",",
"cin",
"=",
"0",
")",
":",
"a",
",",
"b",
"=",
"libutils",
".",
"match_bitwidth",
"(",
"a",
",",
"b",
")",
"prop_orig",
"=",
"a",
"^",
"b",
"prop_bits",
"=",
"[",
"i",
"for",
"i",
"in",
"prop_orig"... | Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone adder is a fast tree-based adder with O(log(... | [
"Creates",
"a",
"Kogge",
"-",
"Stone",
"adder",
"given",
"two",
"inputs"
] | python | train | 38.78125 |
saltstack/salt | salt/modules/osquery.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L36-L48 | def _table_attrs(table):
'''
Helper function to find valid table attributes
'''
cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)]
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
attrs = []
text = salt.utils.json.loads(res['stdout'])
for... | [
"def",
"_table_attrs",
"(",
"table",
")",
":",
"cmd",
"=",
"[",
"'osqueryi'",
"]",
"+",
"[",
"'--json'",
"]",
"+",
"[",
"'pragma table_info({0})'",
".",
"format",
"(",
"table",
")",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")... | Helper function to find valid table attributes | [
"Helper",
"function",
"to",
"find",
"valid",
"table",
"attributes"
] | python | train | 30.692308 |
RedHatInsights/insights-core | insights/parsers/grub_conf.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/grub_conf.py#L447-L460 | def _parse_title(line_iter, cur_line, conf):
"""
Parse "title" in grub v1 config
"""
title = []
conf['title'].append(title)
title.append(('title_name', cur_line.split('title', 1)[1].strip()))
while (True):
line = next(line_iter)
if line.startswith("title "):
retur... | [
"def",
"_parse_title",
"(",
"line_iter",
",",
"cur_line",
",",
"conf",
")",
":",
"title",
"=",
"[",
"]",
"conf",
"[",
"'title'",
"]",
".",
"append",
"(",
"title",
")",
"title",
".",
"append",
"(",
"(",
"'title_name'",
",",
"cur_line",
".",
"split",
"... | Parse "title" in grub v1 config | [
"Parse",
"title",
"in",
"grub",
"v1",
"config"
] | python | train | 27.357143 |
spacetelescope/drizzlepac | drizzlepac/astrodrizzle.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/astrodrizzle.py#L124-L248 | def run(configobj, wcsmap=None):
"""
Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Passing a task name:
... | [
"def",
"run",
"(",
"configobj",
",",
"wcsmap",
"=",
"None",
")",
":",
"# turn on logging, redirecting stdout/stderr messages to a log file",
"# while also printing them out to stdout as well",
"# also, initialize timing of processing steps",
"#",
"# We need to define a default logfile na... | Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Passing a task name:
teal.teal('astrodrizzle')
The exa... | [
"Initial",
"example",
"by",
"Nadia",
"ran",
"MD",
"with",
"configobj",
"EPAR",
"using",
":",
"It",
"can",
"be",
"run",
"in",
"one",
"of",
"two",
"ways",
":"
] | python | train | 33.52 |
wakatime/wakatime | wakatime/packages/pygments/formatters/__init__.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L82-L114 | def load_formatter_from_file(filename, formattername="CustomFormatter",
**options):
"""Load a formatter from a file.
This method expects a file located relative to the current working
directory, which contains a class named CustomFormatter. By default,
it expects the Format... | [
"def",
"load_formatter_from_file",
"(",
"filename",
",",
"formattername",
"=",
"\"CustomFormatter\"",
",",
"*",
"*",
"options",
")",
":",
"try",
":",
"# This empty dict will contain the namespace for the exec'd file",
"custom_namespace",
"=",
"{",
"}",
"exec",
"(",
"ope... | Load a formatter from a file.
This method expects a file located relative to the current working
directory, which contains a class named CustomFormatter. By default,
it expects the Formatter to be named CustomFormatter; you can specify
your own class name as the second argument to this function.
U... | [
"Load",
"a",
"formatter",
"from",
"a",
"file",
"."
] | python | train | 43.606061 |
saltstack/salt | salt/utils/docker/translate/container.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/container.py#L694-L704 | def volumes(val, **kwargs): # pylint: disable=unused-argument
'''
Should be a list of absolute paths
'''
val = helpers.translate_stringlist(val)
for item in val:
if not os.path.isabs(item):
raise SaltInvocationError(
'\'{0}\' is not an absolute path'.format(item)... | [
"def",
"volumes",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"val",
"=",
"helpers",
".",
"translate_stringlist",
"(",
"val",
")",
"for",
"item",
"in",
"val",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",... | Should be a list of absolute paths | [
"Should",
"be",
"a",
"list",
"of",
"absolute",
"paths"
] | python | train | 30.818182 |
klmitch/bark | bark/conversions.py | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/conversions.py#L621-L641 | def convert(self, request, response, data):
"""
Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The... | [
"def",
"convert",
"(",
"self",
",",
"request",
",",
"response",
",",
"data",
")",
":",
"if",
"self",
".",
"modifier",
".",
"param",
"in",
"(",
"None",
",",
"'canonical'",
",",
"'local'",
")",
":",
"return",
"str",
"(",
"request",
".",
"environ",
"[",... | Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary returned by the prepare()
... | [
"Performs",
"the",
"desired",
"Conversion",
"."
] | python | train | 34.714286 |
Guake/guake | guake/prefs.py | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L631-L636 | def on_transparency_value_changed(self, hscale):
"""Changes the value of background_transparency in dconf
"""
value = hscale.get_value()
self.prefDlg.set_colors_from_settings()
self.settings.styleBackground.set_int('transparency', MAX_TRANSPARENCY - int(value)) | [
"def",
"on_transparency_value_changed",
"(",
"self",
",",
"hscale",
")",
":",
"value",
"=",
"hscale",
".",
"get_value",
"(",
")",
"self",
".",
"prefDlg",
".",
"set_colors_from_settings",
"(",
")",
"self",
".",
"settings",
".",
"styleBackground",
".",
"set_int"... | Changes the value of background_transparency in dconf | [
"Changes",
"the",
"value",
"of",
"background_transparency",
"in",
"dconf"
] | python | train | 49.333333 |
xflr6/gsheets | gsheets/models.py | https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L122-L134 | def findall(self, title=None):
"""Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty)
"""
if title is None:
... | [
"def",
"findall",
"(",
"self",
",",
"title",
"=",
"None",
")",
":",
"if",
"title",
"is",
"None",
":",
"return",
"list",
"(",
"self",
".",
"_sheets",
")",
"if",
"title",
"not",
"in",
"self",
".",
"_titles",
":",
"return",
"[",
"]",
"return",
"list",... | Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty) | [
"Return",
"a",
"list",
"of",
"worksheets",
"with",
"the",
"given",
"title",
"."
] | python | train | 34.230769 |
pythongssapi/python-gssapi | gssapi/creds.py | https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L205-L236 | def impersonate(self, name=None, lifetime=None, mechs=None,
usage='initiate'):
"""Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
... | [
"def",
"impersonate",
"(",
"self",
",",
"name",
"=",
"None",
",",
"lifetime",
"=",
"None",
",",
"mechs",
"=",
"None",
",",
"usage",
"=",
"'initiate'",
")",
":",
"if",
"rcred_s4u",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Your GSSAPI imple... | Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
name (Name): the name to impersonate
lifetime (int): the desired lifetime of the new credent... | [
"Impersonate",
"a",
"name",
"using",
"the",
"current",
"credentials"
] | python | train | 39.3125 |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L307-L355 | def filter_incomplete_spectra(self, flimit=1000, percAccept=85):
"""Remove all data points that belong to spectra that did not retain at
least **percAccept** percent of the number of data points.
..warning::
This function does not honor additional dimensions (e.g.,
time... | [
"def",
"filter_incomplete_spectra",
"(",
"self",
",",
"flimit",
"=",
"1000",
",",
"percAccept",
"=",
"85",
")",
":",
"assert",
"percAccept",
">",
"0",
"and",
"percAccept",
"<",
"100",
"def",
"_retain_only_complete_spectra",
"(",
"item",
",",
"fmax",
",",
"ac... | Remove all data points that belong to spectra that did not retain at
least **percAccept** percent of the number of data points.
..warning::
This function does not honor additional dimensions (e.g.,
timesteps) yet! | [
"Remove",
"all",
"data",
"points",
"that",
"belong",
"to",
"spectra",
"that",
"did",
"not",
"retain",
"at",
"least",
"**",
"percAccept",
"**",
"percent",
"of",
"the",
"number",
"of",
"data",
"points",
"."
] | python | train | 37.755102 |
synw/dataswim | dataswim/data/transform/calculations.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/transform/calculations.py#L174-L194 | def gsum_(self, col: str, index_col: bool=True) -> "Ds":
"""
Group by and sum column
:param col: column to group
:type col: str
:param index_col:
:type index_col: bool
:return: a dataswim instance
:rtype: Ds
:example: ``ds2 = ds.gsum("Col 1")``
... | [
"def",
"gsum_",
"(",
"self",
",",
"col",
":",
"str",
",",
"index_col",
":",
"bool",
"=",
"True",
")",
"->",
"\"Ds\"",
":",
"try",
":",
"df",
"=",
"self",
".",
"df",
".",
"copy",
"(",
")",
"df",
"=",
"df",
".",
"groupby",
"(",
"[",
"col",
"]",... | Group by and sum column
:param col: column to group
:type col: str
:param index_col:
:type index_col: bool
:return: a dataswim instance
:rtype: Ds
:example: ``ds2 = ds.gsum("Col 1")`` | [
"Group",
"by",
"and",
"sum",
"column"
] | python | train | 28.904762 |
kytos/python-openflow | pyof/foundation/basic_types.py | https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L724-L743 | def append(self, item):
"""Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
"""
if isinstance(item, list):
... | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"self",
".",
"extend",
"(",
"item",
")",
"elif",
"not",
"self",
":",
"list",
".",
"append",
"(",
"self",
",",
"item",
")",
"elif",
"item"... | Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored. | [
"Append",
"one",
"item",
"to",
"the",
"list",
"."
] | python | train | 31.6 |
wummel/linkchecker | linkcheck/bookmarks/chromium.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/bookmarks/chromium.py#L66-L72 | def parse_bookmark_data (data):
"""Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmarks are not sorted.
"""
for url, name in parse_bookmark_json(json.loads(data)):
yield url, name | [
"def",
"parse_bookmark_data",
"(",
"data",
")",
":",
"for",
"url",
",",
"name",
"in",
"parse_bookmark_json",
"(",
"json",
".",
"loads",
"(",
"data",
")",
")",
":",
"yield",
"url",
",",
"name"
] | Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmarks are not sorted. | [
"Parse",
"data",
"string",
".",
"Return",
"iterator",
"for",
"bookmarks",
"of",
"the",
"form",
"(",
"url",
"name",
")",
".",
"Bookmarks",
"are",
"not",
"sorted",
"."
] | python | train | 33.142857 |
mschwager/fierce | fierce/fierce.py | https://github.com/mschwager/fierce/blob/926c5555c3fab9950147a94a848ef9ab34d82587/fierce/fierce.py#L264-L280 | def update_resolver_nameservers(resolver, nameservers, nameserver_filename):
"""
Update a resolver's nameservers. The following priority is taken:
1. Nameservers list provided as an argument
2. A filename containing a list of nameservers
3. The original nameservers associated with the re... | [
"def",
"update_resolver_nameservers",
"(",
"resolver",
",",
"nameservers",
",",
"nameserver_filename",
")",
":",
"if",
"nameservers",
":",
"resolver",
".",
"nameservers",
"=",
"nameservers",
"elif",
"nameserver_filename",
":",
"nameservers",
"=",
"get_stripped_file_line... | Update a resolver's nameservers. The following priority is taken:
1. Nameservers list provided as an argument
2. A filename containing a list of nameservers
3. The original nameservers associated with the resolver | [
"Update",
"a",
"resolver",
"s",
"nameservers",
".",
"The",
"following",
"priority",
"is",
"taken",
":",
"1",
".",
"Nameservers",
"list",
"provided",
"as",
"an",
"argument",
"2",
".",
"A",
"filename",
"containing",
"a",
"list",
"of",
"nameservers",
"3",
"."... | python | train | 35.294118 |
cablehead/vanilla | vanilla/message.py | https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/message.py#L438-L508 | def Queue(hub, size):
"""
::
+----------+
send --> | Queue |
| (buffer) | --> recv
+----------+
A Queue may also only have exactly one sender and recver. A Queue however
has a fifo buffer of a custom size. Sends to the Queue won't block unt... | [
"def",
"Queue",
"(",
"hub",
",",
"size",
")",
":",
"assert",
"size",
">",
"0",
"def",
"main",
"(",
"upstream",
",",
"downstream",
",",
"size",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
")",
"while",
"True",
":",
"if",
"downstream",
... | ::
+----------+
send --> | Queue |
| (buffer) | --> recv
+----------+
A Queue may also only have exactly one sender and recver. A Queue however
has a fifo buffer of a custom size. Sends to the Queue won't block until
the buffer becomes full::
... | [
"::"
] | python | train | 27.901408 |
elastic/elasticsearch-py | elasticsearch/client/xpack/ml.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ml.py#L674-L688 | def put_calendar_job(self, calendar_id, job_id, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to modify
:arg job_id: The ID of the job to add to the calendar
"""
for param in (calendar_id, job_id):
if param in SKIP_IN_PATH:
... | [
"def",
"put_calendar_job",
"(",
"self",
",",
"calendar_id",
",",
"job_id",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"calendar_id",
",",
"job_id",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"E... | `<>`_
:arg calendar_id: The ID of the calendar to modify
:arg job_id: The ID of the job to add to the calendar | [
"<",
">",
"_"
] | python | train | 36.333333 |
tompollard/tableone | modality.py | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L127-L713 | def dip_pval_tabinterpol(dip, N):
'''
dip - dip value computed from dip_from_cdf
N - number of observations
'''
# if qDiptab_df is None:
# raise DataError("Tabulated p-values not available. See installation instructions.")
if np.isnan(N) or N < 10:
return ... | [
"def",
"dip_pval_tabinterpol",
"(",
"dip",
",",
"N",
")",
":",
"# if qDiptab_df is None:",
"# raise DataError(\"Tabulated p-values not available. See installation instructions.\")",
"if",
"np",
".",
"isnan",
"(",
"N",
")",
"or",
"N",
"<",
"10",
":",
"return",
"np",
... | dip - dip value computed from dip_from_cdf
N - number of observations | [
"dip",
"-",
"dip",
"value",
"computed",
"from",
"dip_from_cdf",
"N",
"-",
"number",
"of",
"observations"
] | python | train | 29.940375 |
tmontaigu/pylas | pylas/point/format.py | https://github.com/tmontaigu/pylas/blob/8335a1a7d7677f0e4bc391bb6fa3c75b42ed5b06/pylas/point/format.py#L55-L65 | def unpacked_dtype(self):
""" Returns the numpy.dtype used to store the point records in a numpy array
.. note::
The dtype corresponds to the dtype with sub_fields *unpacked*
"""
dtype = self._access_dict(dims.UNPACKED_POINT_FORMATS_DTYPES, self.id)
dtype = self._d... | [
"def",
"unpacked_dtype",
"(",
"self",
")",
":",
"dtype",
"=",
"self",
".",
"_access_dict",
"(",
"dims",
".",
"UNPACKED_POINT_FORMATS_DTYPES",
",",
"self",
".",
"id",
")",
"dtype",
"=",
"self",
".",
"_dtype_add_extra_dims",
"(",
"dtype",
")",
"return",
"dtype... | Returns the numpy.dtype used to store the point records in a numpy array
.. note::
The dtype corresponds to the dtype with sub_fields *unpacked* | [
"Returns",
"the",
"numpy",
".",
"dtype",
"used",
"to",
"store",
"the",
"point",
"records",
"in",
"a",
"numpy",
"array"
] | python | test | 32.454545 |
PyCQA/astroid | astroid/rebuilder.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/rebuilder.py#L690-L694 | def visit_keyword(self, node, parent):
"""visit a Keyword node by returning a fresh instance of it"""
newnode = nodes.Keyword(node.arg, parent=parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode | [
"def",
"visit_keyword",
"(",
"self",
",",
"node",
",",
"parent",
")",
":",
"newnode",
"=",
"nodes",
".",
"Keyword",
"(",
"node",
".",
"arg",
",",
"parent",
"=",
"parent",
")",
"newnode",
".",
"postinit",
"(",
"self",
".",
"visit",
"(",
"node",
".",
... | visit a Keyword node by returning a fresh instance of it | [
"visit",
"a",
"Keyword",
"node",
"by",
"returning",
"a",
"fresh",
"instance",
"of",
"it"
] | python | train | 48.6 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L255-L260 | def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec | [
"def",
"Platform",
"(",
"name",
"=",
"platform_default",
"(",
")",
")",
":",
"module",
"=",
"platform_module",
"(",
"name",
")",
"spec",
"=",
"PlatformSpec",
"(",
"name",
",",
"module",
".",
"generate",
")",
"return",
"spec"
] | Select a canned Platform specification. | [
"Select",
"a",
"canned",
"Platform",
"specification",
"."
] | python | train | 31.333333 |
behave/behave-django | behave_django/management/commands/behave.py | https://github.com/behave/behave-django/blob/7b56c8f38dede3601e31c72b5921785c148434d4/behave_django/management/commands/behave.py#L159-L177 | def get_behave_args(self, argv=sys.argv):
"""
Get a list of those command line arguments specified with the
management command that are meant as arguments for running behave.
"""
parser = BehaveArgsHelper().create_parser('manage.py', 'behave')
args, unknown = parser.parse... | [
"def",
"get_behave_args",
"(",
"self",
",",
"argv",
"=",
"sys",
".",
"argv",
")",
":",
"parser",
"=",
"BehaveArgsHelper",
"(",
")",
".",
"create_parser",
"(",
"'manage.py'",
",",
"'behave'",
")",
"args",
",",
"unknown",
"=",
"parser",
".",
"parse_known_arg... | Get a list of those command line arguments specified with the
management command that are meant as arguments for running behave. | [
"Get",
"a",
"list",
"of",
"those",
"command",
"line",
"arguments",
"specified",
"with",
"the",
"management",
"command",
"that",
"are",
"meant",
"as",
"arguments",
"for",
"running",
"behave",
"."
] | python | train | 36.315789 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1597-L1608 | def console_get_char_foreground(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
return Color._new_fro... | [
"def",
"console_get_char_foreground",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
"(",
"lib",
".",
"TCOD_console_get_char_foreground"... | Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`. | [
"Return",
"the",
"foreground",
"color",
"at",
"the",
"x",
"y",
"of",
"this",
"console",
"."
] | python | train | 32.416667 |
ihabunek/toot | toot/ui/utils.py | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/utils.py#L49-L62 | def size_as_drawn(lines, screen_width):
"""Get the bottom-right corner of some text as would be drawn by draw_lines"""
y = 0
x = 0
for line in lines:
wrapped = list(wc_wrap(line, screen_width))
if len(wrapped) > 0:
for wrapped_line in wrapped:
x = len(wrapped_... | [
"def",
"size_as_drawn",
"(",
"lines",
",",
"screen_width",
")",
":",
"y",
"=",
"0",
"x",
"=",
"0",
"for",
"line",
"in",
"lines",
":",
"wrapped",
"=",
"list",
"(",
"wc_wrap",
"(",
"line",
",",
"screen_width",
")",
")",
"if",
"len",
"(",
"wrapped",
"... | Get the bottom-right corner of some text as would be drawn by draw_lines | [
"Get",
"the",
"bottom",
"-",
"right",
"corner",
"of",
"some",
"text",
"as",
"would",
"be",
"drawn",
"by",
"draw_lines"
] | python | train | 30.5 |
saltstack/salt | salt/modules/elasticsearch.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L1113-L1135 | def snapshot_get(repository, snapshot, ignore_unavailable=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
... | [
"def",
"snapshot_get",
"(",
"repository",
",",
"snapshot",
",",
"ignore_unavailable",
"=",
"False",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"return",
"es... | .. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
ignore_unavailable
Ignore unavailable snapshots
CLI example::
salt myminion ela... | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | python | train | 37.086957 |
adaptive-learning/proso-apps | proso_models/models.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L697-L710 | def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | [
"def",
"get_all_leaves",
"(",
"self",
",",
"item_ids",
"=",
"None",
",",
"language",
"=",
"None",
",",
"forbidden_item_ids",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"set",
"(",
"flatten",
"(",
"self",
".",
"get_leaves",
"(",
"item_ids",
",",
"lan... | Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in... | [
"Get",
"all",
"leaves",
"reachable",
"from",
"the",
"given",
"set",
"of",
"items",
".",
"Leaves",
"having",
"inactive",
"relations",
"to",
"other",
"items",
"are",
"omitted",
"."
] | python | train | 47.357143 |
boriel/zxbasic | arch/zx48k/translator.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L106-L116 | def TYPE(type_):
""" Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done.
"""
if isinstance(type_, symbols.TYPE):
return type_
assert TYPE.is_valid... | [
"def",
"TYPE",
"(",
"type_",
")",
":",
"if",
"isinstance",
"(",
"type_",
",",
"symbols",
".",
"TYPE",
")",
":",
"return",
"type_",
"assert",
"TYPE",
".",
"is_valid",
"(",
"type_",
")",
"return",
"gl",
".",
"SYMBOL_TABLE",
".",
"basic_types",
"[",
"type... | Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done. | [
"Converts",
"a",
"backend",
"type",
"(",
"from",
"api",
".",
"constants",
")",
"to",
"a",
"SymbolTYPE",
"object",
"(",
"taken",
"from",
"the",
"SYMBOL_TABLE",
")",
".",
"If",
"type_",
"is",
"already",
"a",
"SymbolTYPE",
"object",
"nothing",
"is",
"done",
... | python | train | 33.363636 |
mongodb/mongo-python-driver | pymongo/bulk.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/bulk.py#L499-L521 | def execute(self, write_concern, session):
"""Execute operations.
"""
if not self.ops:
raise InvalidOperation('No operations to execute')
if self.executed:
raise InvalidOperation('Bulk operations can '
'only be executed once.')
... | [
"def",
"execute",
"(",
"self",
",",
"write_concern",
",",
"session",
")",
":",
"if",
"not",
"self",
".",
"ops",
":",
"raise",
"InvalidOperation",
"(",
"'No operations to execute'",
")",
"if",
"self",
".",
"executed",
":",
"raise",
"InvalidOperation",
"(",
"'... | Execute operations. | [
"Execute",
"operations",
"."
] | python | train | 39.478261 |
spyder-ide/spyder | spyder/plugins/plots/widgets/figurebrowser.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L706-L712 | def go_previous_thumbnail(self):
"""Select the thumbnail previous to the currently selected one."""
if self.current_thumbnail is not None:
index = self._thumbnails.index(self.current_thumbnail) - 1
index = index if index >= 0 else len(self._thumbnails) - 1
self.set_cu... | [
"def",
"go_previous_thumbnail",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_thumbnail",
"is",
"not",
"None",
":",
"index",
"=",
"self",
".",
"_thumbnails",
".",
"index",
"(",
"self",
".",
"current_thumbnail",
")",
"-",
"1",
"index",
"=",
"index",
... | Select the thumbnail previous to the currently selected one. | [
"Select",
"the",
"thumbnail",
"previous",
"to",
"the",
"currently",
"selected",
"one",
"."
] | python | train | 53 |
eisber/sarplus | python/pysarplus/SARPlus.py | https://github.com/eisber/sarplus/blob/945a1182e00a8bf70414fc3600086316701777f9/python/pysarplus/SARPlus.py#L209-L236 | def get_user_affinity(self, test):
"""Prepare test set for C++ SAR prediction code.
Find all items the test users have seen in the past.
Arguments:
test (pySpark.DataFrame): input dataframe which contains test users.
"""
test.createOrReplaceTempView(self.f("{prefix}d... | [
"def",
"get_user_affinity",
"(",
"self",
",",
"test",
")",
":",
"test",
".",
"createOrReplaceTempView",
"(",
"self",
".",
"f",
"(",
"\"{prefix}df_test\"",
")",
")",
"query",
"=",
"self",
".",
"f",
"(",
"\"SELECT DISTINCT {col_user} FROM {prefix}df_test CLUSTER BY {c... | Prepare test set for C++ SAR prediction code.
Find all items the test users have seen in the past.
Arguments:
test (pySpark.DataFrame): input dataframe which contains test users. | [
"Prepare",
"test",
"set",
"for",
"C",
"++",
"SAR",
"prediction",
"code",
".",
"Find",
"all",
"items",
"the",
"test",
"users",
"have",
"seen",
"in",
"the",
"past",
"."
] | python | test | 34.071429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.