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 |
|---|---|---|---|---|---|---|---|---|---|
RedHatInsights/insights-core | insights/client/__init__.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/__init__.py#L356-L375 | def upload(self, payload=None, content_type=None):
"""
Upload the archive at `path` with content type `content_type`
returns (int): upload status code
"""
# platform - prefer the value passed in to func over config
payload = payload or self.config.payload
... | [
"def",
"upload",
"(",
"self",
",",
"payload",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"# platform - prefer the value passed in to func over config",
"payload",
"=",
"payload",
"or",
"self",
".",
"config",
".",
"payload",
"content_type",
"=",
"cont... | Upload the archive at `path` with content type `content_type`
returns (int): upload status code | [
"Upload",
"the",
"archive",
"at",
"path",
"with",
"content",
"type",
"content_type",
"returns",
"(",
"int",
")",
":",
"upload",
"status",
"code"
] | python | train | 36.45 |
robotools/fontParts | Lib/fontParts/base/normalizers.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/normalizers.py#L708-L718 | def normalizeInternalObjectType(value, cls, name):
"""
Normalizes an internal object type.
* **value** must be a instance of **cls**.
* Returned value is the same type as the input value.
"""
if not isinstance(value, cls):
raise TypeError("%s must be a %s instance, not %s."
... | [
"def",
"normalizeInternalObjectType",
"(",
"value",
",",
"cls",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"cls",
")",
":",
"raise",
"TypeError",
"(",
"\"%s must be a %s instance, not %s.\"",
"%",
"(",
"name",
",",
"name",
",",
"typ... | Normalizes an internal object type.
* **value** must be a instance of **cls**.
* Returned value is the same type as the input value. | [
"Normalizes",
"an",
"internal",
"object",
"type",
"."
] | python | train | 34.181818 |
holtjma/msbwt | MUS/MSBWTGen.py | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MSBWTGen.py#L789-L979 | def mergeNewMSBWT(mergedDir, inputBwtDirs, numProcs, logger):
'''
This function will take a list of input BWTs (compressed or not) and merge them into a single BWT
@param mergedFN - the destination for the final merged MSBWT
@param inputBWTFN1 - the fn of the first BWT to merge
@param inputBWTFN2 - ... | [
"def",
"mergeNewMSBWT",
"(",
"mergedDir",
",",
"inputBwtDirs",
",",
"numProcs",
",",
"logger",
")",
":",
"st",
"=",
"time",
".",
"time",
"(",
")",
"iterst",
"=",
"time",
".",
"time",
"(",
")",
"vcLen",
"=",
"6",
"#TODO: take advantage of these to skip an ite... | This function will take a list of input BWTs (compressed or not) and merge them into a single BWT
@param mergedFN - the destination for the final merged MSBWT
@param inputBWTFN1 - the fn of the first BWT to merge
@param inputBWTFN2 - the fn of the second BWT to merge
@param numProcs - number of processe... | [
"This",
"function",
"will",
"take",
"a",
"list",
"of",
"input",
"BWTs",
"(",
"compressed",
"or",
"not",
")",
"and",
"merge",
"them",
"into",
"a",
"single",
"BWT"
] | python | train | 42.387435 |
matthewdeanmartin/jiggle_version | sample_projects/ver_in_weird_file/setup_helpers.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/sample_projects/ver_in_weird_file/setup_helpers.py#L125-L134 | def long_description(*filenames):
"""Provide a long description."""
res = ['']
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append(' ' + line)
res.append('')
res.append('\n')
return EMPTYSTRING.join(res) | [
"def",
"long_description",
"(",
"*",
"filenames",
")",
":",
"res",
"=",
"[",
"''",
"]",
"for",
"filename",
"in",
"filenames",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"res",
".",
"append",
"(",
"' ... | Provide a long description. | [
"Provide",
"a",
"long",
"description",
"."
] | python | train | 29.7 |
log2timeline/plaso | plaso/multi_processing/psort.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/multi_processing/psort.py#L635-L648 | def _StatusUpdateThreadMain(self):
"""Main function of the status update thread."""
while self._status_update_active:
# Make a local copy of the PIDs in case the dict is changed by
# the main thread.
for pid in list(self._process_information_per_pid.keys()):
self._CheckStatusAnalysisPr... | [
"def",
"_StatusUpdateThreadMain",
"(",
"self",
")",
":",
"while",
"self",
".",
"_status_update_active",
":",
"# Make a local copy of the PIDs in case the dict is changed by",
"# the main thread.",
"for",
"pid",
"in",
"list",
"(",
"self",
".",
"_process_information_per_pid",
... | Main function of the status update thread. | [
"Main",
"function",
"of",
"the",
"status",
"update",
"thread",
"."
] | python | train | 36.357143 |
deepmind/sonnet | sonnet/python/modules/nets/mlp.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/mlp.py#L237-L265 | def transpose(self, name=None, activate_final=None):
"""Returns transposed `MLP`.
Args:
name: Optional string specifying the name of the transposed module. The
default name is constructed by appending "_transpose"
to `self.module_name`.
activate_final: Optional boolean determining i... | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
",",
"activate_final",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_transpose\"",
"if",
"activate_final",
"is",
"None",
":",
"activate... | Returns transposed `MLP`.
Args:
name: Optional string specifying the name of the transposed module. The
default name is constructed by appending "_transpose"
to `self.module_name`.
activate_final: Optional boolean determining if the activation and batch
normalization, if turned ... | [
"Returns",
"transposed",
"MLP",
"."
] | python | train | 35.551724 |
yougov/mongo-connector | mongo_connector/connector.py | https://github.com/yougov/mongo-connector/blob/557cafd4b54c848cd54ef28a258391a154650cb4/mongo_connector/connector.py#L475-L480 | def oplog_thread_join(self):
"""Stops all the OplogThreads
"""
LOG.info("MongoConnector: Stopping all OplogThreads")
for thread in self.shard_set.values():
thread.join() | [
"def",
"oplog_thread_join",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"\"MongoConnector: Stopping all OplogThreads\"",
")",
"for",
"thread",
"in",
"self",
".",
"shard_set",
".",
"values",
"(",
")",
":",
"thread",
".",
"join",
"(",
")"
] | Stops all the OplogThreads | [
"Stops",
"all",
"the",
"OplogThreads"
] | python | train | 34.666667 |
tensorflow/tensorboard | tensorboard/plugins/debugger/tensor_store.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/tensor_store.py#L200-L257 | def query(self,
watch_key,
time_indices=None,
slicing=None,
mapping=None):
"""Query tensor store for a given watch_key.
Args:
watch_key: The watch key to query.
time_indices: A numpy-style slicing string for time indices. E.g.,
`-1`, `:-2`, `[... | [
"def",
"query",
"(",
"self",
",",
"watch_key",
",",
"time_indices",
"=",
"None",
",",
"slicing",
"=",
"None",
",",
"mapping",
"=",
"None",
")",
":",
"if",
"watch_key",
"not",
"in",
"self",
".",
"_tensor_data",
":",
"raise",
"KeyError",
"(",
"\"watch_key ... | Query tensor store for a given watch_key.
Args:
watch_key: The watch key to query.
time_indices: A numpy-style slicing string for time indices. E.g.,
`-1`, `:-2`, `[::2]`. If not provided (`None`), will use -1.
slicing: A numpy-style slicing string for individual time steps.
mapping... | [
"Query",
"tensor",
"store",
"for",
"a",
"given",
"watch_key",
"."
] | python | train | 36.034483 |
basho/riak-python-client | riak/client/operations.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/client/operations.py#L807-L845 | def stream_mapred(self, inputs, query, timeout):
"""
Streams a MapReduce query as (phase, data) pairs. This is a
generator method which should be iterated over.
The caller should explicitly close the returned iterator,
either using :func:`contextlib.closing` or calling ``close()... | [
"def",
"stream_mapred",
"(",
"self",
",",
"inputs",
",",
"query",
",",
"timeout",
")",
":",
"_validate_timeout",
"(",
"timeout",
")",
"def",
"make_op",
"(",
"transport",
")",
":",
"return",
"transport",
".",
"stream_mapred",
"(",
"inputs",
",",
"query",
",... | Streams a MapReduce query as (phase, data) pairs. This is a
generator method which should be iterated over.
The caller should explicitly close the returned iterator,
either using :func:`contextlib.closing` or calling ``close()``
explicitly. Consuming the entire iterator will also close ... | [
"Streams",
"a",
"MapReduce",
"query",
"as",
"(",
"phase",
"data",
")",
"pairs",
".",
"This",
"is",
"a",
"generator",
"method",
"which",
"should",
"be",
"iterated",
"over",
"."
] | python | train | 35.410256 |
pandas-profiling/pandas-profiling | pandas_profiling/base.py | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/base.py#L63-L123 | def get_vartype(data):
"""Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
... | [
"def",
"get_vartype",
"(",
"data",
")",
":",
"if",
"data",
".",
"name",
"is",
"not",
"None",
"and",
"data",
".",
"name",
"in",
"_MEMO",
":",
"return",
"_MEMO",
"[",
"data",
".",
"name",
"]",
"vartype",
"=",
"None",
"try",
":",
"distinct_count",
"=",
... | Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
* Boolean (`TYPE_BOOL`... | [
"Infer",
"the",
"type",
"of",
"a",
"variable",
"(",
"technically",
"a",
"Series",
")",
"."
] | python | train | 32.885246 |
kstaniek/condoor | condoor/protocols/telnet.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/telnet.py#L100-L108 | def disconnect(self, device):
"""Disconnect using protocol specific method."""
# self.device.ctrl.sendcontrol(']')
# self.device.ctrl.sendline('quit')
self.log("TELNET disconnect")
try:
self.device.ctrl.send(chr(4))
except OSError:
self.log("Protoc... | [
"def",
"disconnect",
"(",
"self",
",",
"device",
")",
":",
"# self.device.ctrl.sendcontrol(']')",
"# self.device.ctrl.sendline('quit')",
"self",
".",
"log",
"(",
"\"TELNET disconnect\"",
")",
"try",
":",
"self",
".",
"device",
".",
"ctrl",
".",
"send",
"(",
"chr",... | Disconnect using protocol specific method. | [
"Disconnect",
"using",
"protocol",
"specific",
"method",
"."
] | python | train | 37.444444 |
thieman/dagobah | dagobah/core/core.py | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L926-L936 | def kill(self):
""" Send SIGKILL to the task's process. """
logger.info('Sending SIGKILL to task {0}'.format(self.name))
if hasattr(self, 'remote_client') and self.remote_client is not None:
self.kill_sent = True
self.remote_client.close()
return
if no... | [
"def",
"kill",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Sending SIGKILL to task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'remote_client'",
")",
"and",
"self",
".",
"remote_client",
"is",
"n... | Send SIGKILL to the task's process. | [
"Send",
"SIGKILL",
"to",
"the",
"task",
"s",
"process",
"."
] | python | train | 41.272727 |
nvbn/thefuck | thefuck/output_readers/rerun.py | https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/output_readers/rerun.py#L23-L42 | def _wait_output(popen, is_slow):
"""Returns `True` if we can get output of the command in the
`settings.wait_command` time.
Command will be killed if it wasn't finished in the time.
:type popen: Popen
:rtype: bool
"""
proc = Process(popen.pid)
try:
proc.wait(settings.wait_slo... | [
"def",
"_wait_output",
"(",
"popen",
",",
"is_slow",
")",
":",
"proc",
"=",
"Process",
"(",
"popen",
".",
"pid",
")",
"try",
":",
"proc",
".",
"wait",
"(",
"settings",
".",
"wait_slow_command",
"if",
"is_slow",
"else",
"settings",
".",
"wait_command",
")... | Returns `True` if we can get output of the command in the
`settings.wait_command` time.
Command will be killed if it wasn't finished in the time.
:type popen: Popen
:rtype: bool | [
"Returns",
"True",
"if",
"we",
"can",
"get",
"output",
"of",
"the",
"command",
"in",
"the",
"settings",
".",
"wait_command",
"time",
"."
] | python | train | 27.4 |
lexruee/pi-switch-python | send.py | https://github.com/lexruee/pi-switch-python/blob/5c367a6d51aa15811e997160746d1512a37e2dc6/send.py#L32-L71 | def create_switch(type, settings, pin):
"""Create a switch.
Args:
type: (str): type of the switch [A,B,C,D]
settings (str): a comma separted list
pin (int): wiringPi pin
Returns:
switch
"""
switch = None
if type == "A":
group, device = settings.split(",")
switch = p... | [
"def",
"create_switch",
"(",
"type",
",",
"settings",
",",
"pin",
")",
":",
"switch",
"=",
"None",
"if",
"type",
"==",
"\"A\"",
":",
"group",
",",
"device",
"=",
"settings",
".",
"split",
"(",
"\",\"",
")",
"switch",
"=",
"pi_switch",
".",
"RCSwitchA",... | Create a switch.
Args:
type: (str): type of the switch [A,B,C,D]
settings (str): a comma separted list
pin (int): wiringPi pin
Returns:
switch | [
"Create",
"a",
"switch",
"."
] | python | train | 21.525 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/extensions_v1beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/extensions_v1beta1_api.py#L1375-L1404 | def delete_collection_namespaced_replica_set(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_replica_set # noqa: E501
delete collection of ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, p... | [
"def",
"delete_collection_namespaced_replica_set",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | delete_collection_namespaced_replica_set # noqa: E501
delete collection of ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_replica_set(namesp... | [
"delete_collection_namespaced_replica_set",
"#",
"noqa",
":",
"E501"
] | python | train | 164.4 |
pkgw/pwkit | pwkit/kwargv.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/kwargv.py#L464-L475 | def parse_or_die(self, args=None):
"""Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a
:exc:`KwargvError` is raised, printing the exception text. Returns
*self* for convenience.
"""
from .cli import die
try:
return self.parse(args)
... | [
"def",
"parse_or_die",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"from",
".",
"cli",
"import",
"die",
"try",
":",
"return",
"self",
".",
"parse",
"(",
"args",
")",
"except",
"KwargvError",
"as",
"e",
":",
"die",
"(",
"e",
")"
] | Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a
:exc:`KwargvError` is raised, printing the exception text. Returns
*self* for convenience. | [
"Like",
":",
"meth",
":",
"ParseKeywords",
".",
"parse",
"but",
"calls",
":",
"func",
":",
"pkwit",
".",
"cli",
".",
"die",
"if",
"a",
":",
"exc",
":",
"KwargvError",
"is",
"raised",
"printing",
"the",
"exception",
"text",
".",
"Returns",
"*",
"self",
... | python | train | 29.666667 |
yero13/na3x | na3x/transformation/transformer.py | https://github.com/yero13/na3x/blob/b31ef801ea574081125020a7d0f9c4242f8f8b02/na3x/transformation/transformer.py#L305-L329 | def copy(input, **params):
"""
Copies input or input's selected fields
:param input:
:param params:
:return: input
"""
PARAM_FIELDS = 'fields'
def filter_fields(obj, fields):
return {k:v for k,v in obj.items() if k in fields}
if PARAM_FIELDS in params:
fields = para... | [
"def",
"copy",
"(",
"input",
",",
"*",
"*",
"params",
")",
":",
"PARAM_FIELDS",
"=",
"'fields'",
"def",
"filter_fields",
"(",
"obj",
",",
"fields",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",... | Copies input or input's selected fields
:param input:
:param params:
:return: input | [
"Copies",
"input",
"or",
"input",
"s",
"selected",
"fields",
":",
"param",
"input",
":",
":",
"param",
"params",
":",
":",
"return",
":",
"input"
] | python | train | 27.72 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L19817-L19847 | def fs_obj_query_info(self, path, follow_symlinks):
"""Queries information about a file system object (file, directory, etc)
in the guest.
in path of type str
Path to the file system object to gather information about.
Guest path style.
in follow_symlinks of typ... | [
"def",
"fs_obj_query_info",
"(",
"self",
",",
"path",
",",
"follow_symlinks",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"path can only be an instance of type basestring\"",
")",
"if",
"not",
"isinst... | Queries information about a file system object (file, directory, etc)
in the guest.
in path of type str
Path to the file system object to gather information about.
Guest path style.
in follow_symlinks of type bool
Information about symbolic links is returned... | [
"Queries",
"information",
"about",
"a",
"file",
"system",
"object",
"(",
"file",
"directory",
"etc",
")",
"in",
"the",
"guest",
"."
] | python | train | 40.935484 |
metglobal/django-exchange | exchange/conversion.py | https://github.com/metglobal/django-exchange/blob/2133593885e02f42a4ed2ed4be2763c4777a1245/exchange/conversion.py#L36-L52 | def convert_values(args_list):
"""convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values
"""
rate_map = get_rates(map(itemgetter(1, 2), args_list))
value_map = {}
for value, source, target in args_list:
args = (value, ... | [
"def",
"convert_values",
"(",
"args_list",
")",
":",
"rate_map",
"=",
"get_rates",
"(",
"map",
"(",
"itemgetter",
"(",
"1",
",",
"2",
")",
",",
"args_list",
")",
")",
"value_map",
"=",
"{",
"}",
"for",
"value",
",",
"source",
",",
"target",
"in",
"ar... | convert_value in bulk.
:param args_list: list of value, source, target currency pairs
:return: map of converted values | [
"convert_value",
"in",
"bulk",
"."
] | python | train | 28.529412 |
TeamHG-Memex/eli5 | eli5/formatters/as_dataframe.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/as_dataframe.py#L26-L35 | def explain_weights_dfs(estimator, **kwargs):
# type: (...) -> Dict[str, pd.DataFrame]
""" Explain weights and export them to a dict with ``pandas.DataFrame``
values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does).
All keyword arguments are passed to :func:`eli5.explain_weights`.
... | [
"def",
"explain_weights_dfs",
"(",
"estimator",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> Dict[str, pd.DataFrame]",
"kwargs",
"=",
"_set_defaults",
"(",
"kwargs",
")",
"return",
"format_as_dataframes",
"(",
"eli5",
".",
"explain_weights",
"(",
"estimator",
... | Explain weights and export them to a dict with ``pandas.DataFrame``
values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does).
All keyword arguments are passed to :func:`eli5.explain_weights`.
Weights of all features are exported by default. | [
"Explain",
"weights",
"and",
"export",
"them",
"to",
"a",
"dict",
"with",
"pandas",
".",
"DataFrame",
"values",
"(",
"as",
":",
"func",
":",
"eli5",
".",
"formatters",
".",
"as_dataframe",
".",
"format_as_dataframes",
"does",
")",
".",
"All",
"keyword",
"a... | python | train | 48.7 |
PmagPy/PmagPy | pmagpy/ipmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/ipmag.py#L10216-L10540 | def zeq_magic(meas_file='measurements.txt', spec_file='',crd='s',input_dir_path='.', angle=0,
n_plots=5, save_plots=True, fmt="svg", interactive=False, specimen="",
samp_file='samples.txt', contribution=None,fignum=1):
"""
zeq_magic makes zijderveld and equal area plots for magic for... | [
"def",
"zeq_magic",
"(",
"meas_file",
"=",
"'measurements.txt'",
",",
"spec_file",
"=",
"''",
",",
"crd",
"=",
"'s'",
",",
"input_dir_path",
"=",
"'.'",
",",
"angle",
"=",
"0",
",",
"n_plots",
"=",
"5",
",",
"save_plots",
"=",
"True",
",",
"fmt",
"=",
... | zeq_magic makes zijderveld and equal area plots for magic formatted measurements files.
Parameters
----------
meas_file : str
input measurement file
spec_file : str
input specimen interpretation file
samp_file : str
input sample orientations file
crd : str
coordin... | [
"zeq_magic",
"makes",
"zijderveld",
"and",
"equal",
"area",
"plots",
"for",
"magic",
"formatted",
"measurements",
"files",
".",
"Parameters",
"----------",
"meas_file",
":",
"str",
"input",
"measurement",
"file",
"spec_file",
":",
"str",
"input",
"specimen",
"inte... | python | train | 49.015385 |
chrisspen/dtree | dtree.py | https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L270-L277 | def update(self, dist):
"""
Adds the given distribution's counts to the current distribution.
"""
assert isinstance(dist, DDist)
for k, c in iteritems(dist.counts):
self.counts[k] += c
self.total += dist.total | [
"def",
"update",
"(",
"self",
",",
"dist",
")",
":",
"assert",
"isinstance",
"(",
"dist",
",",
"DDist",
")",
"for",
"k",
",",
"c",
"in",
"iteritems",
"(",
"dist",
".",
"counts",
")",
":",
"self",
".",
"counts",
"[",
"k",
"]",
"+=",
"c",
"self",
... | Adds the given distribution's counts to the current distribution. | [
"Adds",
"the",
"given",
"distribution",
"s",
"counts",
"to",
"the",
"current",
"distribution",
"."
] | python | train | 32.75 |
peeringdb/peeringdb-py | peeringdb/backend.py | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/backend.py#L8-L27 | def reftag_to_cls(fn):
"""
decorator that checks function arguments for `concrete` and `resource`
and will properly set them to class references if a string (reftag) is
passed as the value
"""
names, _, _, values = inspect.getargspec(fn)
@wraps(fn)
def wrapped(*args, **kwargs):
i... | [
"def",
"reftag_to_cls",
"(",
"fn",
")",
":",
"names",
",",
"_",
",",
"_",
",",
"values",
"=",
"inspect",
".",
"getargspec",
"(",
"fn",
")",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"i"... | decorator that checks function arguments for `concrete` and `resource`
and will properly set them to class references if a string (reftag) is
passed as the value | [
"decorator",
"that",
"checks",
"function",
"arguments",
"for",
"concrete",
"and",
"resource",
"and",
"will",
"properly",
"set",
"them",
"to",
"class",
"references",
"if",
"a",
"string",
"(",
"reftag",
")",
"is",
"passed",
"as",
"the",
"value"
] | python | train | 36.45 |
albahnsen/CostSensitiveClassification | costcla/probcal/probcal.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/probcal/probcal.py#L137-L161 | def predict_proba(self, p):
""" Calculate the calibrated probabilities
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be calibrated using calibration map
Returns
-------
y_prob_cal : array-like of shape... | [
"def",
"predict_proba",
"(",
"self",
",",
"p",
")",
":",
"# TODO: Check input",
"if",
"p",
".",
"size",
"!=",
"p",
".",
"shape",
"[",
"0",
"]",
":",
"p",
"=",
"p",
"[",
":",
",",
"1",
"]",
"calibrated_proba",
"=",
"np",
".",
"zeros",
"(",
"p",
... | Calculate the calibrated probabilities
Parameters
----------
y_prob : array-like of shape = [n_samples, 2]
Predicted probabilities to be calibrated using calibration map
Returns
-------
y_prob_cal : array-like of shape = [n_samples, 1]
Predicted ... | [
"Calculate",
"the",
"calibrated",
"probabilities"
] | python | train | 31.64 |
spyder-ide/spyder | spyder/plugins/plots/widgets/figurebrowser.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/widgets/figurebrowser.py#L517-L539 | def setup_scrollarea(self):
"""Setup the scrollarea that will contain the FigureThumbnails."""
self.view = QWidget()
self.scene = QGridLayout(self.view)
self.scene.setColumnStretch(0, 100)
self.scene.setColumnStretch(2, 100)
self.scrollarea = QScrollArea()
self.... | [
"def",
"setup_scrollarea",
"(",
"self",
")",
":",
"self",
".",
"view",
"=",
"QWidget",
"(",
")",
"self",
".",
"scene",
"=",
"QGridLayout",
"(",
"self",
".",
"view",
")",
"self",
".",
"scene",
".",
"setColumnStretch",
"(",
"0",
",",
"100",
")",
"self"... | Setup the scrollarea that will contain the FigureThumbnails. | [
"Setup",
"the",
"scrollarea",
"that",
"will",
"contain",
"the",
"FigureThumbnails",
"."
] | python | train | 43.956522 |
datadesk/django-bakery | bakery/management/commands/build.py | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L90-L115 | def handle(self, *args, **options):
"""
Making it happen.
"""
logger.info("Build started")
# Set options
self.set_options(*args, **options)
# Get the build directory ready
if not options.get("keep_build_dir"):
self.init_build_dir()
#... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"logger",
".",
"info",
"(",
"\"Build started\"",
")",
"# Set options",
"self",
".",
"set_options",
"(",
"*",
"args",
",",
"*",
"*",
"options",
")",
"# Get the build direc... | Making it happen. | [
"Making",
"it",
"happen",
"."
] | python | train | 23.5 |
eqcorrscan/EQcorrscan | eqcorrscan/utils/archive_read.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/archive_read.py#L31-L140 | def read_data(archive, arc_type, day, stachans, length=86400):
"""
Function to read the appropriate data from an archive for a day.
:type archive: str
:param archive:
The archive source - if arc_type is seishub, this should be a url,
if the arc_type is FDSN then this can be either a url... | [
"def",
"read_data",
"(",
"archive",
",",
"arc_type",
",",
"day",
",",
"stachans",
",",
"length",
"=",
"86400",
")",
":",
"st",
"=",
"[",
"]",
"available_stations",
"=",
"_check_available_data",
"(",
"archive",
",",
"arc_type",
",",
"day",
")",
"for",
"st... | Function to read the appropriate data from an archive for a day.
:type archive: str
:param archive:
The archive source - if arc_type is seishub, this should be a url,
if the arc_type is FDSN then this can be either a url or a known obspy
client. If arc_type is day_vols, then this is th... | [
"Function",
"to",
"read",
"the",
"appropriate",
"data",
"from",
"an",
"archive",
"for",
"a",
"day",
"."
] | python | train | 42.045455 |
billyoverton/tweetqueue | tweetqueue/TweetList.py | https://github.com/billyoverton/tweetqueue/blob/e54972a0137ea2a21b2357b81408d9d4c92fdd61/tweetqueue/TweetList.py#L57-L78 | def append(self, tweet):
"""Add a tweet to the end of the list."""
c = self.connection.cursor()
last_tweet = c.execute("SELECT tweet from tweetlist where label='last_tweet'").next()[0]
c.execute("INSERT INTO tweets(message, previous_tweet, next_tweet) VALUES (?,?,NULL)", (tweet, last_... | [
"def",
"append",
"(",
"self",
",",
"tweet",
")",
":",
"c",
"=",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"last_tweet",
"=",
"c",
".",
"execute",
"(",
"\"SELECT tweet from tweetlist where label='last_tweet'\"",
")",
".",
"next",
"(",
")",
"[",
"0... | Add a tweet to the end of the list. | [
"Add",
"a",
"tweet",
"to",
"the",
"end",
"of",
"the",
"list",
"."
] | python | train | 41.954545 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L711-L740 | def verify(self, message, pubkey, rnum, snum):
"""
Verify the signature
for message m, pubkey Y, signature (r,s)
r = xcoord(R)
verify that : G*m+Y*r=R*s
this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k }
G*m+G*x*r = G*k*(m+x*r)/k ->
G*(m+x*r) = G*(... | [
"def",
"verify",
"(",
"self",
",",
"message",
",",
"pubkey",
",",
"rnum",
",",
"snum",
")",
":",
"m",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"message",
")",
"r",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"rnum",
")",
"s",
"=",
"self",
... | Verify the signature
for message m, pubkey Y, signature (r,s)
r = xcoord(R)
verify that : G*m+Y*r=R*s
this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k }
G*m+G*x*r = G*k*(m+x*r)/k ->
G*(m+x*r) = G*(m+x*r)
several ways to do the verification:
r =... | [
"Verify",
"the",
"signature",
"for",
"message",
"m",
"pubkey",
"Y",
"signature",
"(",
"r",
"s",
")",
"r",
"=",
"xcoord",
"(",
"R",
")",
"verify",
"that",
":",
"G",
"*",
"m",
"+",
"Y",
"*",
"r",
"=",
"R",
"*",
"s",
"this",
"is",
"true",
"because... | python | train | 31.033333 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L106-L114 | def bound_bboxes(bboxes):
"""
Finds the minimal bbox that contains all given bboxes
"""
group_x0 = min(map(lambda l: l[x0], bboxes))
group_y0 = min(map(lambda l: l[y0], bboxes))
group_x1 = max(map(lambda l: l[x1], bboxes))
group_y1 = max(map(lambda l: l[y1], bboxes))
return (group_x0, gr... | [
"def",
"bound_bboxes",
"(",
"bboxes",
")",
":",
"group_x0",
"=",
"min",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
"[",
"x0",
"]",
",",
"bboxes",
")",
")",
"group_y0",
"=",
"min",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
"[",
"y0",
"]",
",",
... | Finds the minimal bbox that contains all given bboxes | [
"Finds",
"the",
"minimal",
"bbox",
"that",
"contains",
"all",
"given",
"bboxes"
] | python | train | 37.666667 |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L1908-L1913 | def SegmentMax(a, ids):
"""
Segmented max op.
"""
func = lambda idxs: np.amax(a[idxs], axis=0)
return seg_map(func, a, ids), | [
"def",
"SegmentMax",
"(",
"a",
",",
"ids",
")",
":",
"func",
"=",
"lambda",
"idxs",
":",
"np",
".",
"amax",
"(",
"a",
"[",
"idxs",
"]",
",",
"axis",
"=",
"0",
")",
"return",
"seg_map",
"(",
"func",
",",
"a",
",",
"ids",
")",
","
] | Segmented max op. | [
"Segmented",
"max",
"op",
"."
] | python | train | 23.166667 |
djgagne/hagelslag | hagelslag/processing/EnsembleProducts.py | https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/processing/EnsembleProducts.py#L631-L721 | def load_data(self, grid_method="gamma", num_samples=1000, condition_threshold=0.5, zero_inflate=False,
percentile=None):
"""
Reads the track forecasts and converts them to grid point values based on random sampling.
Args:
grid_method: "gamma" by default
... | [
"def",
"load_data",
"(",
"self",
",",
"grid_method",
"=",
"\"gamma\"",
",",
"num_samples",
"=",
"1000",
",",
"condition_threshold",
"=",
"0.5",
",",
"zero_inflate",
"=",
"False",
",",
"percentile",
"=",
"None",
")",
":",
"self",
".",
"percentile",
"=",
"pe... | Reads the track forecasts and converts them to grid point values based on random sampling.
Args:
grid_method: "gamma" by default
num_samples: Number of samples drawn from predicted pdf
condition_threshold: Objects are not written to the grid if condition model probability is... | [
"Reads",
"the",
"track",
"forecasts",
"and",
"converts",
"them",
"to",
"grid",
"point",
"values",
"based",
"on",
"random",
"sampling",
"."
] | python | train | 63.153846 |
ultrabug/py3status | py3status/util.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/util.py#L18-L26 | def hex_2_rgb(self, color):
"""
convert a hex color to rgb
"""
if not self.RE_HEX.match(color):
color = "#FFF"
if len(color) == 7:
return (int(color[i : i + 2], 16) / 255 for i in [1, 3, 5])
return (int(c, 16) / 15 for c in color) | [
"def",
"hex_2_rgb",
"(",
"self",
",",
"color",
")",
":",
"if",
"not",
"self",
".",
"RE_HEX",
".",
"match",
"(",
"color",
")",
":",
"color",
"=",
"\"#FFF\"",
"if",
"len",
"(",
"color",
")",
"==",
"7",
":",
"return",
"(",
"int",
"(",
"color",
"[",
... | convert a hex color to rgb | [
"convert",
"a",
"hex",
"color",
"to",
"rgb"
] | python | train | 32.666667 |
google/prettytensor | prettytensor/layers.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/layers.py#L31-L72 | def apply_activation(
books,
x,
activation,
activation_args=(),
activation_kwargs=None):
"""Returns activation(x, *activation_args, **activation_kwargs).
This applies the given activation and adds useful summaries specific to the
activation.
Args:
books: The bookkeeper.
x: The tens... | [
"def",
"apply_activation",
"(",
"books",
",",
"x",
",",
"activation",
",",
"activation_args",
"=",
"(",
")",
",",
"activation_kwargs",
"=",
"None",
")",
":",
"if",
"activation",
"is",
"None",
":",
"return",
"x",
"if",
"activation_kwargs",
"is",
"None",
":"... | Returns activation(x, *activation_args, **activation_kwargs).
This applies the given activation and adds useful summaries specific to the
activation.
Args:
books: The bookkeeper.
x: The tensor to apply activation to.
activation: An activation function.
activation_args: Optional additional argume... | [
"Returns",
"activation",
"(",
"x",
"*",
"activation_args",
"**",
"activation_kwargs",
")",
"."
] | python | train | 34.142857 |
contentful-labs/contentful.py | contentful/cda/serialization.py | https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L226-L242 | def create_array(self, json):
"""Create :class:`.resources.Array` from JSON.
:param json: JSON dict.
:return: Array instance.
"""
result = Array(json['sys'])
result.total = json['total']
result.skip = json['skip']
result.limit = json['limit']
resu... | [
"def",
"create_array",
"(",
"self",
",",
"json",
")",
":",
"result",
"=",
"Array",
"(",
"json",
"[",
"'sys'",
"]",
")",
"result",
".",
"total",
"=",
"json",
"[",
"'total'",
"]",
"result",
".",
"skip",
"=",
"json",
"[",
"'skip'",
"]",
"result",
".",... | Create :class:`.resources.Array` from JSON.
:param json: JSON dict.
:return: Array instance. | [
"Create",
":",
"class",
":",
".",
"resources",
".",
"Array",
"from",
"JSON",
"."
] | python | train | 29.117647 |
openstack/proliantutils | proliantutils/hpssa/objects.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/objects.py#L428-L449 | def _get_erase_command(self, drive, pattern):
"""Return the command arguments based on the pattern.
Erase command examples:
1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase
erasepattern=overwrite unrestricted=off forced"
2) Zeros: "ssacli ctrl slot=0 pd 1I:1... | [
"def",
"_get_erase_command",
"(",
"self",
",",
"drive",
",",
"pattern",
")",
":",
"cmd_args",
"=",
"[",
"]",
"cmd_args",
".",
"append",
"(",
"\"pd %s\"",
"%",
"drive",
")",
"cmd_args",
".",
"extend",
"(",
"[",
"'modify'",
",",
"'erase'",
",",
"pattern",
... | Return the command arguments based on the pattern.
Erase command examples:
1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase
erasepattern=overwrite unrestricted=off forced"
2) Zeros: "ssacli ctrl slot=0 pd 1I:1:1 modify erase
erasepattern=zero forc... | [
"Return",
"the",
"command",
"arguments",
"based",
"on",
"the",
"pattern",
"."
] | python | train | 37.636364 |
log2timeline/plaso | plaso/parsers/docker.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/docker.py#L94-L108 | def _GetIdentifierFromPath(self, parser_mediator):
"""Extracts a container or a graph ID from a JSON file's path.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
Returns:
str: container or graph identifier... | [
"def",
"_GetIdentifierFromPath",
"(",
"self",
",",
"parser_mediator",
")",
":",
"file_entry",
"=",
"parser_mediator",
".",
"GetFileEntry",
"(",
")",
"path",
"=",
"file_entry",
".",
"path_spec",
".",
"location",
"file_system",
"=",
"file_entry",
".",
"GetFileSystem... | Extracts a container or a graph ID from a JSON file's path.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
Returns:
str: container or graph identifier. | [
"Extracts",
"a",
"container",
"or",
"a",
"graph",
"ID",
"from",
"a",
"JSON",
"file",
"s",
"path",
"."
] | python | train | 35.066667 |
RudolfCardinal/pythonlib | cardinal_pythonlib/fileops.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L438-L468 | def exists_locked(filepath: str) -> Tuple[bool, bool]:
"""
Checks if a file is locked by opening it in append mode.
(If no exception is thrown in that situation, then the file is not locked.)
Args:
filepath: file to check
Returns:
tuple: ``(exists, locked)``
See https://www.ca... | [
"def",
"exists_locked",
"(",
"filepath",
":",
"str",
")",
"->",
"Tuple",
"[",
"bool",
",",
"bool",
"]",
":",
"exists",
"=",
"False",
"locked",
"=",
"None",
"file_object",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",... | Checks if a file is locked by opening it in append mode.
(If no exception is thrown in that situation, then the file is not locked.)
Args:
filepath: file to check
Returns:
tuple: ``(exists, locked)``
See https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/. | [
"Checks",
"if",
"a",
"file",
"is",
"locked",
"by",
"opening",
"it",
"in",
"append",
"mode",
".",
"(",
"If",
"no",
"exception",
"is",
"thrown",
"in",
"that",
"situation",
"then",
"the",
"file",
"is",
"not",
"locked",
".",
")"
] | python | train | 28.903226 |
annoviko/pyclustering | pyclustering/cluster/kmeans.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/kmeans.py#L544-L557 | def __calculate_dataset_difference(self, amount_clusters):
"""!
@brief Calculate distance from each point to each cluster center.
"""
dataset_differences = numpy.zeros((amount_clusters, len(self.__pointer_data)))
for index_center in range(amount_clusters):
if ... | [
"def",
"__calculate_dataset_difference",
"(",
"self",
",",
"amount_clusters",
")",
":",
"dataset_differences",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"amount_clusters",
",",
"len",
"(",
"self",
".",
"__pointer_data",
")",
")",
")",
"for",
"index_center",
"in",
... | !
@brief Calculate distance from each point to each cluster center. | [
"!"
] | python | valid | 52.214286 |
inasafe/inasafe | safe/report/extractors/analysis_provenance_details.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L228-L339 | def analysis_provenance_details_simplified_extractor(
impact_report, component_metadata):
"""Extracting simplified version of provenance details of layers.
This extractor will produce provenance details which will be displayed in
the main report.
:param impact_report: the impact report that ac... | [
"def",
"analysis_provenance_details_simplified_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"context",
"=",
"{",
"}",
"extra_args",
"=",
"component_metadata",
".",
"extra_args",
"default_source",
"=",
"resolve_from_dictionary",
"(",
"extra_args",
... | Extracting simplified version of provenance details of layers.
This extractor will produce provenance details which will be displayed in
the main report.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.im... | [
"Extracting",
"simplified",
"version",
"of",
"provenance",
"details",
"of",
"layers",
"."
] | python | train | 37.25 |
williamfzc/ConnectionTracer | ConnectionTracer/utils.py | https://github.com/williamfzc/ConnectionTracer/blob/190003e374d6903cb82d2d21a1378979dc419ed3/ConnectionTracer/utils.py#L36-L48 | def decode_response(content: bytes) -> set:
""" adb response text -> device set """
content = content[4:].decode(config.ENCODING)
if '\t' not in content and '\n' not in content:
return set()
connected_devices = set()
device_list = [i for i in content.split('\n') if i]
for each_device in... | [
"def",
"decode_response",
"(",
"content",
":",
"bytes",
")",
"->",
"set",
":",
"content",
"=",
"content",
"[",
"4",
":",
"]",
".",
"decode",
"(",
"config",
".",
"ENCODING",
")",
"if",
"'\\t'",
"not",
"in",
"content",
"and",
"'\\n'",
"not",
"in",
"con... | adb response text -> device set | [
"adb",
"response",
"text",
"-",
">",
"device",
"set"
] | python | train | 37.846154 |
flo-compbio/genometools | genometools/gcloud/storage.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/storage.py#L64-L70 | def get_files(client, bucket, prefix=''):
"""Lists files/objects on a bucket.
TODO: docstring"""
bucket = client.get_bucket(bucket)
files = list(bucket.list_blobs(prefix=prefix))
return files | [
"def",
"get_files",
"(",
"client",
",",
"bucket",
",",
"prefix",
"=",
"''",
")",
":",
"bucket",
"=",
"client",
".",
"get_bucket",
"(",
"bucket",
")",
"files",
"=",
"list",
"(",
"bucket",
".",
"list_blobs",
"(",
"prefix",
"=",
"prefix",
")",
")",
"ret... | Lists files/objects on a bucket.
TODO: docstring | [
"Lists",
"files",
"/",
"objects",
"on",
"a",
"bucket",
".",
"TODO",
":",
"docstring"
] | python | train | 30.571429 |
arubertoson/maya-launcher | mayalauncher.py | https://github.com/arubertoson/maya-launcher/blob/9bd82cce7edf4afb803dd8044107a324e93f197f/mayalauncher.py#L167-L179 | def build_config(config_file=get_system_config_directory()):
"""
Construct the config object from necessary elements.
"""
config = Config(config_file, allow_no_value=True)
application_versions = find_applications_on_system()
# Add found versions to config if they don't exist. Versions fo... | [
"def",
"build_config",
"(",
"config_file",
"=",
"get_system_config_directory",
"(",
")",
")",
":",
"config",
"=",
"Config",
"(",
"config_file",
",",
"allow_no_value",
"=",
"True",
")",
"application_versions",
"=",
"find_applications_on_system",
"(",
")",
"# Add foun... | Construct the config object from necessary elements. | [
"Construct",
"the",
"config",
"object",
"from",
"necessary",
"elements",
"."
] | python | train | 44.538462 |
sdss/sdss_access | python/sdss_access/sync/rsync.py | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L160-L167 | def commit(self, offset=None, limit=None, dryrun=False):
""" Start the rsync download """
self.stream.command = "rsync -avRK --files-from={path} {source} {destination}"
self.stream.append_tasks_to_streamlets(offset=offset, limit=limit)
self.stream.commit_streamlets()
self.stream... | [
"def",
"commit",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"dryrun",
"=",
"False",
")",
":",
"self",
".",
"stream",
".",
"command",
"=",
"\"rsync -avRK --files-from={path} {source} {destination}\"",
"self",
".",
"stream",
".",
... | Start the rsync download | [
"Start",
"the",
"rsync",
"download"
] | python | train | 46 |
inspirehep/harvesting-kit | harvestingkit/bibrecord.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/bibrecord.py#L1722-L1725 | def _record_sort_by_indicators(record):
"""Sort the fields inside the record by indicators."""
for tag, fields in record.items():
record[tag] = _fields_sort_by_indicators(fields) | [
"def",
"_record_sort_by_indicators",
"(",
"record",
")",
":",
"for",
"tag",
",",
"fields",
"in",
"record",
".",
"items",
"(",
")",
":",
"record",
"[",
"tag",
"]",
"=",
"_fields_sort_by_indicators",
"(",
"fields",
")"
] | Sort the fields inside the record by indicators. | [
"Sort",
"the",
"fields",
"inside",
"the",
"record",
"by",
"indicators",
"."
] | python | valid | 47.75 |
mirukan/whratio | whratio/__main__.py | https://github.com/mirukan/whratio/blob/e19cf7346351649d196d2eb3369870841f7bfea5/whratio/__main__.py#L33-L68 | def main():
"Process CLI arguments and call appropriate functions."
try:
args = docopt.docopt(__doc__, version=__about__.__version__)
except docopt.DocoptExit:
if len(sys.argv) > 1:
print(f"{Fore.RED}Invalid command syntax, "
f"check help:{Fore.RESET}\n")
... | [
"def",
"main",
"(",
")",
":",
"try",
":",
"args",
"=",
"docopt",
".",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__about__",
".",
"__version__",
")",
"except",
"docopt",
".",
"DocoptExit",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"... | Process CLI arguments and call appropriate functions. | [
"Process",
"CLI",
"arguments",
"and",
"call",
"appropriate",
"functions",
"."
] | python | train | 28.555556 |
econ-ark/HARK | HARK/interpolation.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/interpolation.py#L3113-L3195 | def findSector(self,x,y):
'''
Finds the quadrilateral "sector" for each (x,y) point in the input.
Only called as a subroutine of _evaluate().
Parameters
----------
x : np.array
Values whose sector should be found.
y : np.array
Values whose... | [
"def",
"findSector",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# Initialize the sector guess",
"m",
"=",
"x",
".",
"size",
"x_pos_guess",
"=",
"(",
"np",
".",
"ones",
"(",
"m",
")",
"*",
"self",
".",
"x_n",
"/",
"2",
")",
".",
"astype",
"(",
"i... | Finds the quadrilateral "sector" for each (x,y) point in the input.
Only called as a subroutine of _evaluate().
Parameters
----------
x : np.array
Values whose sector should be found.
y : np.array
Values whose sector should be found. Should be same size ... | [
"Finds",
"the",
"quadrilateral",
"sector",
"for",
"each",
"(",
"x",
"y",
")",
"point",
"in",
"the",
"input",
".",
"Only",
"called",
"as",
"a",
"subroutine",
"of",
"_evaluate",
"()",
"."
] | python | train | 47.39759 |
robhowley/nhlscrapi | nhlscrapi/games/faceoffcomp.py | https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/faceoffcomp.py#L129-L144 | def fo_pct_by_zone(self):
"""
Get the by team face-off win % by zone. Format is
:returns: dict ``{ 'home/away': { 'off/def/neut': % } }``
"""
bz = self.by_zone
return {
t: {
z: bz[t][z]['won']/(1.0*bz[t][z]['total']) if bz[t][z]['t... | [
"def",
"fo_pct_by_zone",
"(",
"self",
")",
":",
"bz",
"=",
"self",
".",
"by_zone",
"return",
"{",
"t",
":",
"{",
"z",
":",
"bz",
"[",
"t",
"]",
"[",
"z",
"]",
"[",
"'won'",
"]",
"/",
"(",
"1.0",
"*",
"bz",
"[",
"t",
"]",
"[",
"z",
"]",
"[... | Get the by team face-off win % by zone. Format is
:returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` | [
"Get",
"the",
"by",
"team",
"face",
"-",
"off",
"win",
"%",
"by",
"zone",
".",
"Format",
"is",
":",
"returns",
":",
"dict",
"{",
"home",
"/",
"away",
":",
"{",
"off",
"/",
"def",
"/",
"neut",
":",
"%",
"}",
"}"
] | python | train | 29.0625 |
onespacemedia/cms-redirects | redirects/models.py | https://github.com/onespacemedia/cms-redirects/blob/9a412dbd4fdac016fbe0ac7bf6773868169cb148/redirects/models.py#L52-L57 | def sub_path(self, path):
""" If this redirect is a regular expression, it will return a
rewritten version of `path`; otherwise returns the `new_path`. """
if not self.regular_expression:
return self.new_path
return re.sub(self.old_path, self.new_path, path) | [
"def",
"sub_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"self",
".",
"regular_expression",
":",
"return",
"self",
".",
"new_path",
"return",
"re",
".",
"sub",
"(",
"self",
".",
"old_path",
",",
"self",
".",
"new_path",
",",
"path",
")"
] | If this redirect is a regular expression, it will return a
rewritten version of `path`; otherwise returns the `new_path`. | [
"If",
"this",
"redirect",
"is",
"a",
"regular",
"expression",
"it",
"will",
"return",
"a",
"rewritten",
"version",
"of",
"path",
";",
"otherwise",
"returns",
"the",
"new_path",
"."
] | python | train | 49.5 |
peri-source/peri | peri/opt/optimize.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1186-L1201 | def check_terminate(self):
"""
Returns a Bool of whether to terminate.
Checks whether a satisfactory minimum has been found or whether
too many iterations have occurred.
"""
if not self._has_run:
return False
else:
#1-3. errtol, paramtol, ... | [
"def",
"check_terminate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_has_run",
":",
"return",
"False",
"else",
":",
"#1-3. errtol, paramtol, model cosine low enough?",
"terminate",
"=",
"self",
".",
"check_completion",
"(",
")",
"#4. too many iterations??",
... | Returns a Bool of whether to terminate.
Checks whether a satisfactory minimum has been found or whether
too many iterations have occurred. | [
"Returns",
"a",
"Bool",
"of",
"whether",
"to",
"terminate",
"."
] | python | valid | 31.5 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py#L812-L819 | def add(self,dist):
"""Add `dist` if we ``can_add()`` it and it isn't already added"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key,[])
if dist not in dists:
dists.append(dist)
if dist.key in self._cache:
... | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"self",
".",
"can_add",
"(",
"dist",
")",
"and",
"dist",
".",
"has_version",
"(",
")",
":",
"dists",
"=",
"self",
".",
"_distmap",
".",
"setdefault",
"(",
"dist",
".",
"key",
",",
"[",
"]",
... | Add `dist` if we ``can_add()`` it and it isn't already added | [
"Add",
"dist",
"if",
"we",
"can_add",
"()",
"it",
"and",
"it",
"isn",
"t",
"already",
"added"
] | python | test | 45.875 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/setuptools/sandbox.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/sandbox.py#L70-L84 | def override_temp(replacement):
"""
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
"""
if not os.path.isdir(replacement):
os.makedirs(replacement)
saved = tempfile.tempdir
tempfile.tempdir = replacement
try:
yield
finally:
tempfile.tempdir =... | [
"def",
"override_temp",
"(",
"replacement",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"replacement",
")",
":",
"os",
".",
"makedirs",
"(",
"replacement",
")",
"saved",
"=",
"tempfile",
".",
"tempdir",
"tempfile",
".",
"tempdir",
"=",
... | Monkey-patch tempfile.tempdir with replacement, ensuring it exists | [
"Monkey",
"-",
"patch",
"tempfile",
".",
"tempdir",
"with",
"replacement",
"ensuring",
"it",
"exists"
] | python | test | 20.8 |
echonest/pyechonest | pyechonest/song.py | https://github.com/echonest/pyechonest/blob/d8c7af6c1da699b50b2f4b1bd3c0febe72e7f1ee/pyechonest/song.py#L323-L356 | def get_tracks(self, catalog, cache=True):
"""Get the tracks for a song given a catalog.
Args:
catalog (str): a string representing the catalog whose track you want to retrieve.
Returns:
A list of Track dicts.
Example:
>>> s ... | [
"def",
"get_tracks",
"(",
"self",
",",
"catalog",
",",
"cache",
"=",
"True",
")",
":",
"if",
"not",
"(",
"cache",
"and",
"(",
"'tracks'",
"in",
"self",
".",
"cache",
")",
"and",
"(",
"catalog",
"in",
"[",
"td",
"[",
"'catalog'",
"]",
"for",
"td",
... | Get the tracks for a song given a catalog.
Args:
catalog (str): a string representing the catalog whose track you want to retrieve.
Returns:
A list of Track dicts.
Example:
>>> s = song.Song('SOWDASQ12A6310F24F')
>>> s.ge... | [
"Get",
"the",
"tracks",
"for",
"a",
"song",
"given",
"a",
"catalog",
".",
"Args",
":",
"catalog",
"(",
"str",
")",
":",
"a",
"string",
"representing",
"the",
"catalog",
"whose",
"track",
"you",
"want",
"to",
"retrieve",
".",
"Returns",
":",
"A",
"list"... | python | train | 46.176471 |
apache/incubator-mxnet | python/mxnet/contrib/quantization.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L137-L149 | def collect(self, name, arr):
"""Callback function for collecting layer output NDArrays."""
name = py_str(name)
if self.include_layer is not None and not self.include_layer(name):
return
handle = ctypes.cast(arr, NDArrayHandle)
arr = NDArray(handle, writable=False).co... | [
"def",
"collect",
"(",
"self",
",",
"name",
",",
"arr",
")",
":",
"name",
"=",
"py_str",
"(",
"name",
")",
"if",
"self",
".",
"include_layer",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"include_layer",
"(",
"name",
")",
":",
"return",
"handle",... | Callback function for collecting layer output NDArrays. | [
"Callback",
"function",
"for",
"collecting",
"layer",
"output",
"NDArrays",
"."
] | python | train | 44.230769 |
tanghaibao/jcvi | jcvi/variation/cnv.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/cnv.py#L922-L975 | def mergecn(args):
"""
%prog mergecn FACE.csv
Compile matrix of GC-corrected copy numbers. Place a bunch of folders in
csv file. Each folder will be scanned, one chromosomes after another.
"""
p = OptionParser(mergecn.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
... | [
"def",
"mergecn",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mergecn",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
... | %prog mergecn FACE.csv
Compile matrix of GC-corrected copy numbers. Place a bunch of folders in
csv file. Each folder will be scanned, one chromosomes after another. | [
"%prog",
"mergecn",
"FACE",
".",
"csv"
] | python | train | 38.703704 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/commands/CommandSet.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/commands/CommandSet.py#L152-L159 | def add_event(self, event):
"""
Adds an IEvent event to this command set.
:param event: an event instance to be added
"""
self._events.append(event)
self._events_by_name[event.get_name] = event | [
"def",
"add_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_events",
".",
"append",
"(",
"event",
")",
"self",
".",
"_events_by_name",
"[",
"event",
".",
"get_name",
"]",
"=",
"event"
] | Adds an IEvent event to this command set.
:param event: an event instance to be added | [
"Adds",
"an",
"IEvent",
"event",
"to",
"this",
"command",
"set",
".",
":",
"param",
"event",
":",
"an",
"event",
"instance",
"to",
"be",
"added"
] | python | train | 30.375 |
boriel/zxbasic | api/symboltable.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/api/symboltable.py#L762-L804 | def declare_func(self, id_, lineno, type_=None):
""" Declares a function in the current scope.
Checks whether the id exist or not (error if exists).
And creates the entry at the symbol table.
"""
if not self.check_class(id_, 'function', lineno):
entry = self.get_entry... | [
"def",
"declare_func",
"(",
"self",
",",
"id_",
",",
"lineno",
",",
"type_",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"check_class",
"(",
"id_",
",",
"'function'",
",",
"lineno",
")",
":",
"entry",
"=",
"self",
".",
"get_entry",
"(",
"id_",
... | Declares a function in the current scope.
Checks whether the id exist or not (error if exists).
And creates the entry at the symbol table. | [
"Declares",
"a",
"function",
"in",
"the",
"current",
"scope",
".",
"Checks",
"whether",
"the",
"id",
"exist",
"or",
"not",
"(",
"error",
"if",
"exists",
")",
".",
"And",
"creates",
"the",
"entry",
"at",
"the",
"symbol",
"table",
"."
] | python | train | 49.139535 |
Miserlou/django-easy-timezones | easy_timezones/views.py | https://github.com/Miserlou/django-easy-timezones/blob/a25c6312a7ecb3ebfac7b2c458b1c5be5d45a239/easy_timezones/views.py#L8-L18 | def with_tz(request):
"""
Get the time with TZ enabled
"""
dt = datetime.now()
t = Template('{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}')
c = RequestContext(request)
response = t.render(c)
return HttpResponse(response) | [
"def",
"with_tz",
"(",
"request",
")",
":",
"dt",
"=",
"datetime",
".",
"now",
"(",
")",
"t",
"=",
"Template",
"(",
"'{% load tz %}{% localtime on %}{% get_current_timezone as TIME_ZONE %}{{ TIME_ZONE }}{% endlocaltime %}'",
")",
"c",
"=",
"RequestContext",
"(",
"reques... | Get the time with TZ enabled | [
"Get",
"the",
"time",
"with",
"TZ",
"enabled"
] | python | valid | 28.090909 |
striglia/stockfighter | stockfighter/stockfighter.py | https://github.com/striglia/stockfighter/blob/df908f5919d6f861601cd00c906a049d04253d47/stockfighter/stockfighter.py#L60-L80 | def place_new_order(self, stock, price, qty, direction, order_type):
"""Place an order for a stock.
https://starfighter.readme.io/docs/place-new-order
"""
url_fragment = 'venues/{venue}/stocks/{stock}/orders'.format(
venue=self.venue,
stock=stock,
)
... | [
"def",
"place_new_order",
"(",
"self",
",",
"stock",
",",
"price",
",",
"qty",
",",
"direction",
",",
"order_type",
")",
":",
"url_fragment",
"=",
"'venues/{venue}/stocks/{stock}/orders'",
".",
"format",
"(",
"venue",
"=",
"self",
".",
"venue",
",",
"stock",
... | Place an order for a stock.
https://starfighter.readme.io/docs/place-new-order | [
"Place",
"an",
"order",
"for",
"a",
"stock",
"."
] | python | train | 31.285714 |
NearHuscarl/py-currency | currency/currency.py | https://github.com/NearHuscarl/py-currency/blob/4e30426399872fd6bfaa4c752a91d67c2d7bf52c/currency/currency.py#L110-L131 | def pretty(price, currency, *, abbrev=True, trim=True):
""" return format price with symbol. Example format(100, 'USD') return '$100'
pretty(price, currency, abbrev=True, trim=False)
abbrev:
True: print value + symbol. Symbol can either be placed before or after value
False: print value + currency code. currency... | [
"def",
"pretty",
"(",
"price",
",",
"currency",
",",
"*",
",",
"abbrev",
"=",
"True",
",",
"trim",
"=",
"True",
")",
":",
"currency",
"=",
"validate_currency",
"(",
"currency",
")",
"price",
"=",
"validate_price",
"(",
"price",
")",
"space",
"=",
"''",... | return format price with symbol. Example format(100, 'USD') return '$100'
pretty(price, currency, abbrev=True, trim=False)
abbrev:
True: print value + symbol. Symbol can either be placed before or after value
False: print value + currency code. currency code is placed behind value
trim:
True: trim float value ... | [
"return",
"format",
"price",
"with",
"symbol",
".",
"Example",
"format",
"(",
"100",
"USD",
")",
"return",
"$100",
"pretty",
"(",
"price",
"currency",
"abbrev",
"=",
"True",
"trim",
"=",
"False",
")",
"abbrev",
":",
"True",
":",
"print",
"value",
"+",
... | python | train | 42.863636 |
agoragames/haigha | haigha/connections/rabbit_connection.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/connections/rabbit_connection.py#L206-L217 | def _recv_ack(self, method_frame):
'''Receive an ack from the broker.'''
if self._ack_listener:
delivery_tag = method_frame.args.read_longlong()
multiple = method_frame.args.read_bit()
if multiple:
while self._last_ack_id < delivery_tag:
... | [
"def",
"_recv_ack",
"(",
"self",
",",
"method_frame",
")",
":",
"if",
"self",
".",
"_ack_listener",
":",
"delivery_tag",
"=",
"method_frame",
".",
"args",
".",
"read_longlong",
"(",
")",
"multiple",
"=",
"method_frame",
".",
"args",
".",
"read_bit",
"(",
"... | Receive an ack from the broker. | [
"Receive",
"an",
"ack",
"from",
"the",
"broker",
"."
] | python | train | 43 |
psd-tools/psd-tools | src/psd_tools/api/mask.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/mask.py#L32-L34 | def bbox(self):
"""BBox"""
return self.left, self.top, self.right, self.bottom | [
"def",
"bbox",
"(",
"self",
")",
":",
"return",
"self",
".",
"left",
",",
"self",
".",
"top",
",",
"self",
".",
"right",
",",
"self",
".",
"bottom"
] | BBox | [
"BBox"
] | python | train | 30.666667 |
klahnakoski/pyLibrary | mo_dots/__init__.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_dots/__init__.py#L30-L38 | def inverse(d):
"""
reverse the k:v pairs
"""
output = {}
for k, v in unwrap(d).items():
output[v] = output.get(v, [])
output[v].append(k)
return output | [
"def",
"inverse",
"(",
"d",
")",
":",
"output",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"unwrap",
"(",
"d",
")",
".",
"items",
"(",
")",
":",
"output",
"[",
"v",
"]",
"=",
"output",
".",
"get",
"(",
"v",
",",
"[",
"]",
")",
"output",
"... | reverse the k:v pairs | [
"reverse",
"the",
"k",
":",
"v",
"pairs"
] | python | train | 20.444444 |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L249-L252 | def del_object_from_parent(self):
""" Delete object from parent object. """
if self.parent:
self.parent.objects.pop(self.ref) | [
"def",
"del_object_from_parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"self",
".",
"parent",
".",
"objects",
".",
"pop",
"(",
"self",
".",
"ref",
")"
] | Delete object from parent object. | [
"Delete",
"object",
"from",
"parent",
"object",
"."
] | python | train | 37.5 |
littlemo/moear-spider-zhihudaily | moear_spider_zhihudaily/spiders/zhihu_daily.py | https://github.com/littlemo/moear-spider-zhihudaily/blob/1e4e60b547afe3e2fbb3bbcb7d07a75dca608149/moear_spider_zhihudaily/spiders/zhihu_daily.py#L126-L166 | def parse_post(self, response):
'''
根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容,
并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中
:param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
'''
content = json.loads(response.body.decode(), encoding='UTF-8')
post = response.... | [
"def",
"parse_post",
"(",
"self",
",",
"response",
")",
":",
"content",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"body",
".",
"decode",
"(",
")",
",",
"encoding",
"=",
"'UTF-8'",
")",
"post",
"=",
"response",
".",
"meta",
"[",
"'post'",
"]",
... | 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容,
并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中
:param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 | [
"根据",
":",
"meth",
":",
".",
"ZhihuDailySpider",
".",
"parse",
"中生成的具体文章地址,获取到文章内容,",
"并对其进行格式化处理,结果填充到对象属性",
"item_list",
"中"
] | python | train | 36.780488 |
marshmallow-code/marshmallow | src/marshmallow/schema.py | https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/schema.py#L416-L433 | def _call_and_store(getter_func, data, field_name, error_store, index=None):
"""Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`.
:param callable getter_func: Function for getting the serialized/deserialized
value from ``data``.
:param data: The d... | [
"def",
"_call_and_store",
"(",
"getter_func",
",",
"data",
",",
"field_name",
",",
"error_store",
",",
"index",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"getter_func",
"(",
"data",
")",
"except",
"ValidationError",
"as",
"err",
":",
"error_store",
... | Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`.
:param callable getter_func: Function for getting the serialized/deserialized
value from ``data``.
:param data: The data passed to ``getter_func``.
:param str field_name: Field name.
:param... | [
"Call",
"getter_func",
"with",
"data",
"as",
"its",
"argument",
"and",
"store",
"any",
"ValidationErrors",
"."
] | python | train | 48.888889 |
ibis-project/ibis | ibis/bigquery/client.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/bigquery/client.py#L95-L98 | def fetchall(self):
"""Fetch all rows."""
result = self.query.result()
return [row.values() for row in result] | [
"def",
"fetchall",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"query",
".",
"result",
"(",
")",
"return",
"[",
"row",
".",
"values",
"(",
")",
"for",
"row",
"in",
"result",
"]"
] | Fetch all rows. | [
"Fetch",
"all",
"rows",
"."
] | python | train | 32.75 |
Opentrons/opentrons | api/src/opentrons/deck_calibration/endpoints.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/endpoints.py#L541-L578 | async def start(request):
"""
Begins the session manager for factory calibration, if a session is not
already in progress, or if the "force" key is specified in the request. To
force, use the following body:
{
"force": true
}
:return: The current session ID token or an error message
... | [
"async",
"def",
"start",
"(",
"request",
")",
":",
"global",
"session",
"try",
":",
"body",
"=",
"await",
"request",
".",
"json",
"(",
")",
"except",
"json",
".",
"decoder",
".",
"JSONDecodeError",
":",
"# Body will be null for requests without parameters (normal ... | Begins the session manager for factory calibration, if a session is not
already in progress, or if the "force" key is specified in the request. To
force, use the following body:
{
"force": true
}
:return: The current session ID token or an error message | [
"Begins",
"the",
"session",
"manager",
"for",
"factory",
"calibration",
"if",
"a",
"session",
"is",
"not",
"already",
"in",
"progress",
"or",
"if",
"the",
"force",
"key",
"is",
"specified",
"in",
"the",
"request",
".",
"To",
"force",
"use",
"the",
"followi... | python | train | 31.973684 |
googleapis/protoc-java-resource-names-plugin | plugin/utils/path_template.py | https://github.com/googleapis/protoc-java-resource-names-plugin/blob/3fb2ec9b778f62646c05a7b960c893464c7791c0/plugin/utils/path_template.py#L190-L211 | def parse(self, data):
"""Returns a list of path template segments parsed from data.
Args:
data: A path template string.
Returns:
A list of _Segment.
"""
self.binding_var_count = 0
self.segment_count = 0
segments = self.parser.parse(data)... | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"binding_var_count",
"=",
"0",
"self",
".",
"segment_count",
"=",
"0",
"segments",
"=",
"self",
".",
"parser",
".",
"parse",
"(",
"data",
")",
"# Validation step: checks that there are no nested ... | Returns a list of path template segments parsed from data.
Args:
data: A path template string.
Returns:
A list of _Segment. | [
"Returns",
"a",
"list",
"of",
"path",
"template",
"segments",
"parsed",
"from",
"data",
"."
] | python | train | 35.090909 |
inveniosoftware/invenio-oauth2server | invenio_oauth2server/provider.py | https://github.com/inveniosoftware/invenio-oauth2server/blob/7033d3495c1a2b830e101e43918e92a37bbb49f2/invenio_oauth2server/provider.py#L75-L88 | def get_client(client_id):
"""Load the client.
Needed for grant_type client_credentials.
Add support for OAuth client_credentials access type, with user
inactivation support.
:param client_id: The client ID.
:returns: The client instance or ``None``.
"""
client = Client.query.get(clie... | [
"def",
"get_client",
"(",
"client_id",
")",
":",
"client",
"=",
"Client",
".",
"query",
".",
"get",
"(",
"client_id",
")",
"if",
"client",
"and",
"client",
".",
"user",
".",
"active",
":",
"return",
"client"
] | Load the client.
Needed for grant_type client_credentials.
Add support for OAuth client_credentials access type, with user
inactivation support.
:param client_id: The client ID.
:returns: The client instance or ``None``. | [
"Load",
"the",
"client",
"."
] | python | train | 26.642857 |
geertj/gruvi | lib/gruvi/dbus.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L168-L174 | def getMechanismName(self):
"""Return the authentication mechanism name."""
if self._server_side:
mech = self._authenticator.current_mech
return mech.getMechanismName() if mech else None
else:
return getattr(self._authenticator, 'authMech', None) | [
"def",
"getMechanismName",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server_side",
":",
"mech",
"=",
"self",
".",
"_authenticator",
".",
"current_mech",
"return",
"mech",
".",
"getMechanismName",
"(",
")",
"if",
"mech",
"else",
"None",
"else",
":",
"retu... | Return the authentication mechanism name. | [
"Return",
"the",
"authentication",
"mechanism",
"name",
"."
] | python | train | 42.857143 |
frejanordsiek/hdf5storage | hdf5storage/utilities.py | https://github.com/frejanordsiek/hdf5storage/blob/539275141dd3a4efbbbfd9bdb978f3ed59e3f05d/hdf5storage/utilities.py#L548-L654 | def write_object_array(f, data, options):
""" Writes an array of objects recursively.
Writes the elements of the given object array recursively in the
HDF5 Group ``options.group_for_references`` and returns an
``h5py.Reference`` array to all the elements.
Parameters
----------
f : h5py.Fil... | [
"def",
"write_object_array",
"(",
"f",
",",
"data",
",",
"options",
")",
":",
"# We need to grab the special reference dtype and make an empty",
"# array to store all the references in.",
"ref_dtype",
"=",
"h5py",
".",
"special_dtype",
"(",
"ref",
"=",
"h5py",
".",
"Refer... | Writes an array of objects recursively.
Writes the elements of the given object array recursively in the
HDF5 Group ``options.group_for_references`` and returns an
``h5py.Reference`` array to all the elements.
Parameters
----------
f : h5py.File
The HDF5 file handle that is open.
d... | [
"Writes",
"an",
"array",
"of",
"objects",
"recursively",
"."
] | python | train | 38.878505 |
googledatalab/pydatalab | solutionbox/image_classification/mltoolbox/image/classification/_api.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_api.py#L89-L97 | def train(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None):
"""Blocking version of train_async(). The only difference is that it blocks the caller
until the job finishes, and it does not have a return value.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
... | [
"def",
"train",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
"=",
"None",
",",
"cloud",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
... | Blocking version of train_async(). The only difference is that it blocks the caller
until the job finishes, and it does not have a return value. | [
"Blocking",
"version",
"of",
"train_async",
"()",
".",
"The",
"only",
"difference",
"is",
"that",
"it",
"blocks",
"the",
"caller",
"until",
"the",
"job",
"finishes",
"and",
"it",
"does",
"not",
"have",
"a",
"return",
"value",
"."
] | python | train | 47.888889 |
belbio/bel | bel/lang/semantics.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/semantics.py#L239-L370 | def validate_arg_values(ast, bo):
"""Recursively validate arg (NSArg and StrArg) values
Check that NSArgs are found in BELbio API and match appropriate entity_type.
Check that StrArgs match their value - either default namespace or regex string
Generate a WARNING if not.
Args:
bo: bel obj... | [
"def",
"validate_arg_values",
"(",
"ast",
",",
"bo",
")",
":",
"if",
"not",
"bo",
".",
"api_url",
":",
"log",
".",
"info",
"(",
"\"No API endpoint defined\"",
")",
"return",
"bo",
"log",
".",
"debug",
"(",
"f\"AST: {ast}\"",
")",
"# Test NSArg terms",
"if",
... | Recursively validate arg (NSArg and StrArg) values
Check that NSArgs are found in BELbio API and match appropriate entity_type.
Check that StrArgs match their value - either default namespace or regex string
Generate a WARNING if not.
Args:
bo: bel object
Returns:
bel object | [
"Recursively",
"validate",
"arg",
"(",
"NSArg",
"and",
"StrArg",
")",
"values"
] | python | train | 38.924242 |
tanghaibao/goatools | goatools/parsers/david_chart.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/parsers/david_chart.py#L91-L100 | def get_num_sig(self, alpha=0.05):
"""Print the number of significant results using various metrics."""
# Get the number of significant GO terms
ctr = cx.Counter()
flds = set(['FDR', 'Bonferroni', 'Benjamini', 'PValue'])
for ntd in self.nts:
for fld in flds:
... | [
"def",
"get_num_sig",
"(",
"self",
",",
"alpha",
"=",
"0.05",
")",
":",
"# Get the number of significant GO terms",
"ctr",
"=",
"cx",
".",
"Counter",
"(",
")",
"flds",
"=",
"set",
"(",
"[",
"'FDR'",
",",
"'Bonferroni'",
",",
"'Benjamini'",
",",
"'PValue'",
... | Print the number of significant results using various metrics. | [
"Print",
"the",
"number",
"of",
"significant",
"results",
"using",
"various",
"metrics",
"."
] | python | train | 40 |
joshua-stone/DerPyBooru | derpibooru/search.py | https://github.com/joshua-stone/DerPyBooru/blob/75aec19488042ba89115ff002b4d696ad87fb03f/derpibooru/search.py#L135-L142 | def limit(self, limit):
"""
Set absolute limit on number of images to return, or set to None to return
as many results as needed; default 50 posts.
"""
params = join_params(self.parameters, {"limit": limit})
return self.__class__(**params) | [
"def",
"limit",
"(",
"self",
",",
"limit",
")",
":",
"params",
"=",
"join_params",
"(",
"self",
".",
"parameters",
",",
"{",
"\"limit\"",
":",
"limit",
"}",
")",
"return",
"self",
".",
"__class__",
"(",
"*",
"*",
"params",
")"
] | Set absolute limit on number of images to return, or set to None to return
as many results as needed; default 50 posts. | [
"Set",
"absolute",
"limit",
"on",
"number",
"of",
"images",
"to",
"return",
"or",
"set",
"to",
"None",
"to",
"return",
"as",
"many",
"results",
"as",
"needed",
";",
"default",
"50",
"posts",
"."
] | python | train | 32.125 |
hubo1016/namedstruct | namedstruct/namedstruct.py | https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/namedstruct/namedstruct.py#L226-L240 | def _gettype(self):
'''
Return current type of this struct
:returns: a typedef object (e.g. nstruct)
'''
current = self
lastname = getattr(current._parser, 'typedef', None)
while hasattr(current, '_sub'):
current = current._sub
... | [
"def",
"_gettype",
"(",
"self",
")",
":",
"current",
"=",
"self",
"lastname",
"=",
"getattr",
"(",
"current",
".",
"_parser",
",",
"'typedef'",
",",
"None",
")",
"while",
"hasattr",
"(",
"current",
",",
"'_sub'",
")",
":",
"current",
"=",
"current",
".... | Return current type of this struct
:returns: a typedef object (e.g. nstruct) | [
"Return",
"current",
"type",
"of",
"this",
"struct",
":",
"returns",
":",
"a",
"typedef",
"object",
"(",
"e",
".",
"g",
".",
"nstruct",
")"
] | python | train | 29.533333 |
wecatch/app-turbo | turbo/app.py | https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/app.py#L307-L314 | def wo_resp(self, resp):
"""
can override for other style
"""
if self._data is not None:
resp['res'] = self.to_str(self._data)
return self.wo_json(resp) | [
"def",
"wo_resp",
"(",
"self",
",",
"resp",
")",
":",
"if",
"self",
".",
"_data",
"is",
"not",
"None",
":",
"resp",
"[",
"'res'",
"]",
"=",
"self",
".",
"to_str",
"(",
"self",
".",
"_data",
")",
"return",
"self",
".",
"wo_json",
"(",
"resp",
")"
... | can override for other style | [
"can",
"override",
"for",
"other",
"style"
] | python | train | 24.75 |
kakwa/ldapcherry | ldapcherry/backend/backendLdap.py | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/backend/backendLdap.py#L469-L515 | def set_attrs(self, username, attrs):
""" set user attributes"""
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = self._byte_p2(tmp[0])
old_attrs = tmp[1... | [
"def",
"set_attrs",
"(",
"self",
",",
"username",
",",
"attrs",
")",
":",
"ldap_client",
"=",
"self",
".",
"_bind",
"(",
")",
"tmp",
"=",
"self",
".",
"_get_user",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",
",",
"ALL_ATTRS",
")",
"if",
"tmp"... | set user attributes | [
"set",
"user",
"attributes"
] | python | train | 40.361702 |
all-umass/graphs | graphs/base/base.py | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/base/base.py#L150-L163 | def to_graph_tool(self):
'''Converts this Graph object to a graph_tool-compatible object.
Requires the graph_tool library.
Note that the internal ordering of graph_tool seems to be column-major.'''
# Import here to avoid ImportErrors when graph_tool isn't available.
import graph_tool
gt = graph_... | [
"def",
"to_graph_tool",
"(",
"self",
")",
":",
"# Import here to avoid ImportErrors when graph_tool isn't available.",
"import",
"graph_tool",
"gt",
"=",
"graph_tool",
".",
"Graph",
"(",
"directed",
"=",
"self",
".",
"is_directed",
"(",
")",
")",
"gt",
".",
"add_edg... | Converts this Graph object to a graph_tool-compatible object.
Requires the graph_tool library.
Note that the internal ordering of graph_tool seems to be column-major. | [
"Converts",
"this",
"Graph",
"object",
"to",
"a",
"graph_tool",
"-",
"compatible",
"object",
".",
"Requires",
"the",
"graph_tool",
"library",
".",
"Note",
"that",
"the",
"internal",
"ordering",
"of",
"graph_tool",
"seems",
"to",
"be",
"column",
"-",
"major",
... | python | train | 42.285714 |
kgori/treeCl | treeCl/tasks.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/tasks.py#L64-L71 | def rfdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0):
"""
Distributed version of tree_distance.rfdist
Parameters: two valid newick strings and a boolean
"""
tree_a = Tree(newick_string_a)
tree_b = Tree(newick_string_b)
return treedist.rfdist(tree_... | [
"def",
"rfdist_task",
"(",
"newick_string_a",
",",
"newick_string_b",
",",
"normalise",
",",
"min_overlap",
"=",
"4",
",",
"overlap_fail_value",
"=",
"0",
")",
":",
"tree_a",
"=",
"Tree",
"(",
"newick_string_a",
")",
"tree_b",
"=",
"Tree",
"(",
"newick_string_... | Distributed version of tree_distance.rfdist
Parameters: two valid newick strings and a boolean | [
"Distributed",
"version",
"of",
"tree_distance",
".",
"rfdist",
"Parameters",
":",
"two",
"valid",
"newick",
"strings",
"and",
"a",
"boolean"
] | python | train | 45.875 |
daler/trackhub | trackhub/helpers.py | https://github.com/daler/trackhub/blob/e4655f79177822529f80b923df117e38e28df702/trackhub/helpers.py#L69-L97 | def sanitize(s, strict=True):
"""
Sanitize a string.
Spaces are converted to underscore; if strict=True they are then removed.
Parameters
----------
s : str
String to sanitize
strict : bool
If True, only alphanumeric characters are allowed. If False, a limited
set ... | [
"def",
"sanitize",
"(",
"s",
",",
"strict",
"=",
"True",
")",
":",
"allowed",
"=",
"''",
".",
"join",
"(",
"[",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'",
",",
"'abcdefghijklmnopqrstuvwxyz'",
",",
"'0123456789'",
",",
"]",
")",
"if",
"not",
"strict",
":",
"allowed",
... | Sanitize a string.
Spaces are converted to underscore; if strict=True they are then removed.
Parameters
----------
s : str
String to sanitize
strict : bool
If True, only alphanumeric characters are allowed. If False, a limited
set of additional characters (-._) will be all... | [
"Sanitize",
"a",
"string",
"."
] | python | train | 21.965517 |
mattja/nsim | nsim/analyses1/pyeeg.py | https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/pyeeg.py#L736-L834 | def permutation_entropy(x, n, tau):
"""Compute Permutation Entropy of a given time series x, specified by
permutation order n and embedding lag tau.
Parameters
----------
x
list
a time series
n
integer
Permutation order
tau
integer
Embed... | [
"def",
"permutation_entropy",
"(",
"x",
",",
"n",
",",
"tau",
")",
":",
"PeSeq",
"=",
"[",
"]",
"Em",
"=",
"embed_seq",
"(",
"x",
",",
"tau",
",",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"Em",
")",
")",
":",
"r",
"="... | Compute Permutation Entropy of a given time series x, specified by
permutation order n and embedding lag tau.
Parameters
----------
x
list
a time series
n
integer
Permutation order
tau
integer
Embedding lag
Returns
----------
P... | [
"Compute",
"Permutation",
"Entropy",
"of",
"a",
"given",
"time",
"series",
"x",
"specified",
"by",
"permutation",
"order",
"n",
"and",
"embedding",
"lag",
"tau",
"."
] | python | train | 25.191919 |
sbarham/dsrt | dsrt/data/SampleSet.py | https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/dsrt/data/SampleSet.py#L42-L46 | def load_sampleset(self, f, name):
'''Read the sampleset from using the HDF5 format. Name is usually in {train, test}.'''
self.encoder_x = np.array(f[name + '_encoder_x'])
self.decoder_x = np.array(f[name + '_decoder_x'])
self.decoder_y = np.array(f[name + '_decoder_y']) | [
"def",
"load_sampleset",
"(",
"self",
",",
"f",
",",
"name",
")",
":",
"self",
".",
"encoder_x",
"=",
"np",
".",
"array",
"(",
"f",
"[",
"name",
"+",
"'_encoder_x'",
"]",
")",
"self",
".",
"decoder_x",
"=",
"np",
".",
"array",
"(",
"f",
"[",
"nam... | Read the sampleset from using the HDF5 format. Name is usually in {train, test}. | [
"Read",
"the",
"sampleset",
"from",
"using",
"the",
"HDF5",
"format",
".",
"Name",
"is",
"usually",
"in",
"{",
"train",
"test",
"}",
"."
] | python | train | 59.8 |
senaite/senaite.core | bika/lims/content/analysisrequest.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisrequest.py#L2289-L2296 | def setParentAnalysisRequest(self, value):
"""Sets a parent analysis request, making the current a partition
"""
self.Schema().getField("ParentAnalysisRequest").set(self, value)
if not value:
noLongerProvides(self, IAnalysisRequestPartition)
else:
alsoProv... | [
"def",
"setParentAnalysisRequest",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"Schema",
"(",
")",
".",
"getField",
"(",
"\"ParentAnalysisRequest\"",
")",
".",
"set",
"(",
"self",
",",
"value",
")",
"if",
"not",
"value",
":",
"noLongerProvides",
"(",... | Sets a parent analysis request, making the current a partition | [
"Sets",
"a",
"parent",
"analysis",
"request",
"making",
"the",
"current",
"a",
"partition"
] | python | train | 43.75 |
appknox/google-chartwrapper | GChartWrapper/GChart.py | https://github.com/appknox/google-chartwrapper/blob/3769aecbef6c83b6cd93ee72ece478ffe433ac57/GChartWrapper/GChart.py#L343-L360 | def fill(self, *args):
"""
Apply a solid fill to your chart
args are of the form <fill type>,<fill style>,...
fill type must be one of c,bg,a
fill style must be one of s,lg,ls
the rest of the args refer to the particular style
APIPARAM: chf
"""
a,b... | [
"def",
"fill",
"(",
"self",
",",
"*",
"args",
")",
":",
"a",
",",
"b",
"=",
"args",
"[",
":",
"2",
"]",
"assert",
"a",
"in",
"(",
"'c'",
",",
"'bg'",
",",
"'a'",
")",
",",
"'Fill type must be bg/c/a not %s'",
"%",
"a",
"assert",
"b",
"in",
"(",
... | Apply a solid fill to your chart
args are of the form <fill type>,<fill style>,...
fill type must be one of c,bg,a
fill style must be one of s,lg,ls
the rest of the args refer to the particular style
APIPARAM: chf | [
"Apply",
"a",
"solid",
"fill",
"to",
"your",
"chart",
"args",
"are",
"of",
"the",
"form",
"<fill",
"type",
">",
"<fill",
"style",
">",
"...",
"fill",
"type",
"must",
"be",
"one",
"of",
"c",
"bg",
"a",
"fill",
"style",
"must",
"be",
"one",
"of",
"s"... | python | test | 36.277778 |
PlaidWeb/Publ | publ/image/image.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/image.py#L36-L55 | def get_img_attrs(self, style=None, **kwargs):
""" Get an attribute list (src, srcset, style, et al) for the image.
style -- an optional list of CSS style fragments
Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x']
"""
add = {}
if '... | [
"def",
"get_img_attrs",
"(",
"self",
",",
"style",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"add",
"=",
"{",
"}",
"if",
"'prefix'",
"in",
"kwargs",
":",
"attr_prefixes",
"=",
"kwargs",
".",
"get",
"(",
"'prefix'",
")",
"if",
"isinstance",
"(",... | Get an attribute list (src, srcset, style, et al) for the image.
style -- an optional list of CSS style fragments
Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x'] | [
"Get",
"an",
"attribute",
"list",
"(",
"src",
"srcset",
"style",
"et",
"al",
")",
"for",
"the",
"image",
"."
] | python | train | 35.6 |
flo-compbio/genometools | genometools/basic/gene_set_collection.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/basic/gene_set_collection.py#L159-L180 | def get_by_index(self, i):
"""Look up a gene set by its index.
Parameters
----------
i: int
The index of the gene set.
Returns
-------
GeneSet
The gene set.
Raises
------
ValueError
If the given index ... | [
"def",
"get_by_index",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
">=",
"self",
".",
"n",
":",
"raise",
"ValueError",
"(",
"'Index %d out of bounds '",
"%",
"i",
"+",
"'for database with %d gene sets.'",
"%",
"self",
".",
"n",
")",
"return",
"self",
".",
... | Look up a gene set by its index.
Parameters
----------
i: int
The index of the gene set.
Returns
-------
GeneSet
The gene set.
Raises
------
ValueError
If the given index is out of bounds. | [
"Look",
"up",
"a",
"gene",
"set",
"by",
"its",
"index",
"."
] | python | train | 24.545455 |
etingof/pysnmp | pysnmp/smi/rfc1902.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L158-L193 | def getLabel(self):
"""Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
... | [
"def",
"getLabel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_label",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__na... | Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
towards this MIB variable.
... | [
"Returns",
"symbolic",
"path",
"to",
"this",
"MIB",
"variable",
"."
] | python | train | 30.333333 |
PyCQA/pylint | pylint/checkers/base.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L997-L1001 | def open(self):
"""initialize visit variables and statistics
"""
self._tryfinallys = []
self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0) | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"_tryfinallys",
"=",
"[",
"]",
"self",
".",
"stats",
"=",
"self",
".",
"linter",
".",
"add_stats",
"(",
"module",
"=",
"0",
",",
"function",
"=",
"0",
",",
"method",
"=",
"0",
",",
"class_",
"=",... | initialize visit variables and statistics | [
"initialize",
"visit",
"variables",
"and",
"statistics"
] | python | test | 38.4 |
google/openhtf | openhtf/plugs/usb/filesync_service.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L205-L227 | def _check_for_fail_message(self, transport, exc_info, timeout): # pylint: disable=no-self-use
"""Check for a 'FAIL' message from transport.
This method always raises, if 'FAIL' was read, it will raise an
AdbRemoteError with the message, otherwise it will raise based on
exc_info, which should be a tup... | [
"def",
"_check_for_fail_message",
"(",
"self",
",",
"transport",
",",
"exc_info",
",",
"timeout",
")",
":",
"# pylint: disable=no-self-use",
"try",
":",
"transport",
".",
"read_message",
"(",
"timeout",
")",
"except",
"usb_exceptions",
".",
"CommonUsbError",
":",
... | Check for a 'FAIL' message from transport.
This method always raises, if 'FAIL' was read, it will raise an
AdbRemoteError with the message, otherwise it will raise based on
exc_info, which should be a tuple as per sys.exc_info().
Args:
transport: Transport from which to read for a 'FAIL' message... | [
"Check",
"for",
"a",
"FAIL",
"message",
"from",
"transport",
"."
] | python | train | 41.347826 |
broadinstitute/fiss | firecloud/fccore.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fccore.py#L122-L183 | def config_parse(files=None, config=None, config_profile=".fissconfig", **kwargs):
'''
Read initial configuration state, from named config files; store
this state within a config dictionary (which may be nested) whose keys may
also be referenced as attributes (safely, defaulting to None if unset). A
... | [
"def",
"config_parse",
"(",
"files",
"=",
"None",
",",
"config",
"=",
"None",
",",
"config_profile",
"=",
"\".fissconfig\"",
",",
"*",
"*",
"kwargs",
")",
":",
"local_config",
"=",
"config",
"config",
"=",
"__fcconfig",
"cfgparser",
"=",
"configparser",
".",... | Read initial configuration state, from named config files; store
this state within a config dictionary (which may be nested) whose keys may
also be referenced as attributes (safely, defaulting to None if unset). A
config object may be passed in, as a way of accumulating or overwriting
configuration sta... | [
"Read",
"initial",
"configuration",
"state",
"from",
"named",
"config",
"files",
";",
"store",
"this",
"state",
"within",
"a",
"config",
"dictionary",
"(",
"which",
"may",
"be",
"nested",
")",
"whose",
"keys",
"may",
"also",
"be",
"referenced",
"as",
"attrib... | python | train | 39.064516 |
cloudant/python-cloudant | src/cloudant/database.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L242-L260 | def get_design_document(self, ddoc_id):
"""
Retrieves a design document. If a design document exists remotely
then that content is wrapped in a DesignDocument object and returned
to the caller. Otherwise a "shell" DesignDocument object is returned.
:param str ddoc_id: Design d... | [
"def",
"get_design_document",
"(",
"self",
",",
"ddoc_id",
")",
":",
"ddoc",
"=",
"DesignDocument",
"(",
"self",
",",
"ddoc_id",
")",
"try",
":",
"ddoc",
".",
"fetch",
"(",
")",
"except",
"HTTPError",
"as",
"error",
":",
"if",
"error",
".",
"response",
... | Retrieves a design document. If a design document exists remotely
then that content is wrapped in a DesignDocument object and returned
to the caller. Otherwise a "shell" DesignDocument object is returned.
:param str ddoc_id: Design document id
:returns: A DesignDocument instance, if ... | [
"Retrieves",
"a",
"design",
"document",
".",
"If",
"a",
"design",
"document",
"exists",
"remotely",
"then",
"that",
"content",
"is",
"wrapped",
"in",
"a",
"DesignDocument",
"object",
"and",
"returned",
"to",
"the",
"caller",
".",
"Otherwise",
"a",
"shell",
"... | python | train | 34.210526 |
what-studio/profiling | profiling/remote/__init__.py | https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L163-L197 | def profiling(self):
"""A generator which profiles then broadcasts the result. Implement
sleeping loop using this::
def profile_periodically(self):
for __ in self.profiling():
time.sleep(self.interval)
"""
self._log_profiler_started()
... | [
"def",
"profiling",
"(",
"self",
")",
":",
"self",
".",
"_log_profiler_started",
"(",
")",
"while",
"self",
".",
"clients",
":",
"try",
":",
"self",
".",
"profiler",
".",
"start",
"(",
")",
"except",
"RuntimeError",
":",
"pass",
"# should sleep.",
"yield",... | A generator which profiles then broadcasts the result. Implement
sleeping loop using this::
def profile_periodically(self):
for __ in self.profiling():
time.sleep(self.interval) | [
"A",
"generator",
"which",
"profiles",
"then",
"broadcasts",
"the",
"result",
".",
"Implement",
"sleeping",
"loop",
"using",
"this",
"::"
] | python | train | 33.628571 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L115-L128 | def get_plan(self, nodes=None):
"""
Retrieve a plan, e.g. a list of fixtures to be loaded sorted on
dependency.
:param list nodes: list of nodes to be loaded.
:return:
"""
if nodes:
plan = self.graph.resolve_nodes(nodes)
else:
plan... | [
"def",
"get_plan",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"nodes",
":",
"plan",
"=",
"self",
".",
"graph",
".",
"resolve_nodes",
"(",
"nodes",
")",
"else",
":",
"plan",
"=",
"self",
".",
"graph",
".",
"resolve_node",
"(",
")",
"ret... | Retrieve a plan, e.g. a list of fixtures to be loaded sorted on
dependency.
:param list nodes: list of nodes to be loaded.
:return: | [
"Retrieve",
"a",
"plan",
"e",
".",
"g",
".",
"a",
"list",
"of",
"fixtures",
"to",
"be",
"loaded",
"sorted",
"on",
"dependency",
"."
] | python | train | 25.428571 |
googlefonts/glyphsLib | Lib/glyphsLib/builder/paths.py | https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/builder/paths.py#L21-L49 | def to_ufo_paths(self, ufo_glyph, layer):
"""Draw .glyphs paths onto a pen."""
pen = ufo_glyph.getPointPen()
for path in layer.paths:
# the list is changed below, otherwise you can't draw more than once
# per session.
nodes = list(path.nodes)
for node in nodes:
s... | [
"def",
"to_ufo_paths",
"(",
"self",
",",
"ufo_glyph",
",",
"layer",
")",
":",
"pen",
"=",
"ufo_glyph",
".",
"getPointPen",
"(",
")",
"for",
"path",
"in",
"layer",
".",
"paths",
":",
"# the list is changed below, otherwise you can't draw more than once",
"# per sessi... | Draw .glyphs paths onto a pen. | [
"Draw",
".",
"glyphs",
"paths",
"onto",
"a",
"pen",
"."
] | python | train | 35.896552 |
Nydareld/ConfigEnv | ConfigEnv/Config.py | https://github.com/Nydareld/ConfigEnv/blob/38c13e5dd9d6c5f3dcd4c1194507a43384c31e29/ConfigEnv/Config.py#L43-L58 | def get(self,path):
"""
permet de récupérer une config
Args:
path (String): Nom d'une config
Returns:
type: String
la valeur de la config ou None
"""
path = path.upper()
if path in self._configCache:
re... | [
"def",
"get",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"upper",
"(",
")",
"if",
"path",
"in",
"self",
".",
"_configCache",
":",
"return",
"self",
".",
"_configCache",
"[",
"path",
"]",
"else",
":",
"return",
"self",
".",
"_find... | permet de récupérer une config
Args:
path (String): Nom d'une config
Returns:
type: String
la valeur de la config ou None | [
"permet",
"de",
"récupérer",
"une",
"config"
] | python | train | 24.375 |
dourvaris/nano-python | src/nano/rpc.py | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L2901-L2924 | def work_cancel(self, hash):
"""
Stop generating **work** for block
.. enable_control required
:param hash: Hash to stop generating work for
:type hash: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.work_cancel(
... hash="718CC2121C3E641059B... | [
"def",
"work_cancel",
"(",
"self",
",",
"hash",
")",
":",
"hash",
"=",
"self",
".",
"_process_value",
"(",
"hash",
",",
"'block'",
")",
"payload",
"=",
"{",
"\"hash\"",
":",
"hash",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'work_cancel'",
",",
"p... | Stop generating **work** for block
.. enable_control required
:param hash: Hash to stop generating work for
:type hash: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.work_cancel(
... hash="718CC2121C3E641059BC1C2CFC45666C99E8AE922F7A807B7D07B62C995D79E2"
... | [
"Stop",
"generating",
"**",
"work",
"**",
"for",
"block"
] | python | train | 22.666667 |
LonamiWebs/Telethon | telethon/tl/custom/adminlogevent.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/adminlogevent.py#L95-L125 | def new(self):
"""
The new value present in the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionCha... | [
"def",
"new",
"(",
"self",
")",
":",
"ori",
"=",
"self",
".",
"original",
".",
"action",
"if",
"isinstance",
"(",
"ori",
",",
"(",
"types",
".",
"ChannelAdminLogEventActionChangeAbout",
",",
"types",
".",
"ChannelAdminLogEventActionChangeTitle",
",",
"types",
... | The new value present in the event. | [
"The",
"new",
"value",
"present",
"in",
"the",
"event",
"."
] | python | train | 46.741935 |
CybOXProject/mixbox | mixbox/namespaces.py | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L344-L405 | def add_namespace_uri(self, ns_uri, prefix=None, schema_location=None):
"""Adds a new namespace to this set, optionally with a prefix and
schema location URI.
If the namespace already exists, the given prefix and schema location
are merged with the existing entry:
* If non-N... | [
"def",
"add_namespace_uri",
"(",
"self",
",",
"ns_uri",
",",
"prefix",
"=",
"None",
",",
"schema_location",
"=",
"None",
")",
":",
"assert",
"ns_uri",
"if",
"ns_uri",
"in",
"self",
".",
"__ns_uri_map",
":",
"# We have a _NamespaceInfo object for this URI already. S... | Adds a new namespace to this set, optionally with a prefix and
schema location URI.
If the namespace already exists, the given prefix and schema location
are merged with the existing entry:
* If non-None, ``prefix`` is added to the set. The preferred
prefix is not m... | [
"Adds",
"a",
"new",
"namespace",
"to",
"this",
"set",
"optionally",
"with",
"a",
"prefix",
"and",
"schema",
"location",
"URI",
"."
] | python | train | 42.725806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.