text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def setSpeciesFromJson(self, speciesJson):
"""
Sets the species, an OntologyTerm, to the specified value, given as
a JSON string.
See the documentation for details of this field.
"""
try:
parsed = protocol.fromJson(speciesJson, protocol.OntologyTerm)
... | [
"def",
"setSpeciesFromJson",
"(",
"self",
",",
"speciesJson",
")",
":",
"try",
":",
"parsed",
"=",
"protocol",
".",
"fromJson",
"(",
"speciesJson",
",",
"protocol",
".",
"OntologyTerm",
")",
"except",
":",
"raise",
"exceptions",
".",
"InvalidJsonException",
"(... | 35.916667 | 19.25 |
def _init_context(self, gene_seq):
"""Initializes attributes defining mutation contexts and their position.
The self.context2pos and self.pos2context dictionaries map from
sequence context to sequence position and sequence position to
sequence context, respectively. These attributes all... | [
"def",
"_init_context",
"(",
"self",
",",
"gene_seq",
")",
":",
"self",
".",
"context2pos",
",",
"self",
".",
"pos2context",
"=",
"{",
"}",
",",
"{",
"}",
"gene_len",
"=",
"len",
"(",
"gene_seq",
".",
"exon_seq",
")",
"# get length of CDS",
"five_ss_len",
... | 52.426471 | 20.169118 |
def shutdown_executors(wait=True):
"""
Clean-up the resources of all initialized executors.
:param wait:
If True then shutdown will not return until all running futures have
finished executing and the resources used by the executors have been
reclaimed.
:type wait: bool
:re... | [
"def",
"shutdown_executors",
"(",
"wait",
"=",
"True",
")",
":",
"return",
"{",
"k",
":",
"shutdown_executor",
"(",
"k",
",",
"wait",
")",
"for",
"k",
"in",
"list",
"(",
"_EXECUTORS",
".",
"keys",
"(",
")",
")",
"}"
] | 30.266667 | 21.733333 |
def blend_line(messages, blend_combos=None):
"""
Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line.
"""
blend_co... | [
"def",
"blend_line",
"(",
"messages",
",",
"blend_combos",
"=",
"None",
")",
":",
"blend_combos",
"=",
"blend_combos",
"or",
"BLEND_COMBOS",
"blend_lists",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"blend_combos",
")",
")",
"]",
"bl... | 47.745763 | 25.101695 |
def is_displayed(self):
"""
:return: True id at least one element is displayed, otherwise False.
Ignore implicit and element timeouts and execute immediately.
"""
t = self.wait_timeout
self.wait_timeout = 0
try:
self.reload()
return... | [
"def",
"is_displayed",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"wait_timeout",
"self",
".",
"wait_timeout",
"=",
"0",
"try",
":",
"self",
".",
"reload",
"(",
")",
"return",
"any",
"(",
"e",
".",
"is_displayed",
"(",
")",
"for",
"e",
"in",
"se... | 33 | 16.666667 |
def array_values(expr):
"""Given an expression expr denoting a list of values, array_values(expr)
returns a list of values for that expression."""
if isinstance(expr, Array):
return expr.get_elems(all_subs(expr._bounds))
elif isinstance(expr, list):
vals = [array_values(x) for x in e... | [
"def",
"array_values",
"(",
"expr",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"Array",
")",
":",
"return",
"expr",
".",
"get_elems",
"(",
"all_subs",
"(",
"expr",
".",
"_bounds",
")",
")",
"elif",
"isinstance",
"(",
"expr",
",",
"list",
")",
":... | 37.6 | 11.5 |
def _values(metadata, rel):
"""Searches a set <metadata> to find all relations <rel>
Returns a list of the values of those relations
(A list, because a rel can occur more than once)"""
result = []
for r in metadata:
if(r[REL] == rel):
result.append(r[VAL])
return result | [
"def",
"_values",
"(",
"metadata",
",",
"rel",
")",
":",
"result",
"=",
"[",
"]",
"for",
"r",
"in",
"metadata",
":",
"if",
"(",
"r",
"[",
"REL",
"]",
"==",
"rel",
")",
":",
"result",
".",
"append",
"(",
"r",
"[",
"VAL",
"]",
")",
"return",
"r... | 30.6 | 15.1 |
async def query_available_abilities(
self, units: Union[List[Unit], "Units"], ignore_resource_requirements: bool = False
) -> List[List[AbilityId]]:
""" Query abilities of multiple units """
if not isinstance(units, list):
""" Deprecated, accepting a single unit may be removed in... | [
"async",
"def",
"query_available_abilities",
"(",
"self",
",",
"units",
":",
"Union",
"[",
"List",
"[",
"Unit",
"]",
",",
"\"Units\"",
"]",
",",
"ignore_resource_requirements",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"List",
"[",
"AbilityId",
"]... | 49.954545 | 19.136364 |
def _parse_tcpreplay_result(stdout, stderr, argv):
"""
Parse the output of tcpreplay and modify the results_dict to populate output information. # noqa: E501
Tested with tcpreplay v3.4.4
Tested with tcpreplay v4.1.2
:param stdout: stdout of tcpreplay subprocess call
:param stderr: stderr of tcp... | [
"def",
"_parse_tcpreplay_result",
"(",
"stdout",
",",
"stderr",
",",
"argv",
")",
":",
"try",
":",
"results",
"=",
"{",
"}",
"stdout",
"=",
"plain_str",
"(",
"stdout",
")",
".",
"lower",
"(",
")",
"stderr",
"=",
"plain_str",
"(",
"stderr",
")",
".",
... | 40.150943 | 13.169811 |
def refresh_report_version(self):
"""
This method will query firmata for the report version.
Retrieve the report version via a call to get_firmata_version()
"""
command = [self._command_handler.REPORT_VERSION]
self._command_handler.send_command(command) | [
"def",
"refresh_report_version",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"_command_handler",
".",
"REPORT_VERSION",
"]",
"self",
".",
"_command_handler",
".",
"send_command",
"(",
"command",
")"
] | 42.142857 | 12.428571 |
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Respons... | [
"def",
"job_counters",
"(",
"self",
",",
"job_id",
")",
":",
"path",
"=",
"'/ws/v1/history/mapreduce/jobs/{jobid}/counters'",
".",
"format",
"(",
"jobid",
"=",
"job_id",
")",
"return",
"self",
".",
"request",
"(",
"path",
")"
] | 35 | 17 |
def get_group_id(self, uuid=None):
"""Get group id based on uuid.
Args:
uuid (str): optional uuid. defaults to self.cuuid
Raises:
PyLmodUnexpectedData: No group data was returned.
requests.RequestException: Exception connection error
Returns:
... | [
"def",
"get_group_id",
"(",
"self",
",",
"uuid",
"=",
"None",
")",
":",
"group_data",
"=",
"self",
".",
"get_group",
"(",
"uuid",
")",
"try",
":",
"return",
"group_data",
"[",
"'response'",
"]",
"[",
"'docs'",
"]",
"[",
"0",
"]",
"[",
"'id'",
"]",
... | 32.772727 | 19.545455 |
def _check_nominal_power(self, storage_parameters, timeseries):
"""
Tries to assign a nominal power to the storage.
Checks if nominal power is provided through `storage_parameters`,
otherwise tries to return the absolute maximum of `timeseries`. Raises
an error if it cannot assi... | [
"def",
"_check_nominal_power",
"(",
"self",
",",
"storage_parameters",
",",
"timeseries",
")",
":",
"if",
"storage_parameters",
".",
"get",
"(",
"'nominal_power'",
",",
"None",
")",
"is",
"None",
":",
"try",
":",
"storage_parameters",
"[",
"'nominal_power'",
"]"... | 40.375 | 24.5625 |
def run(self):
""" Main process loop.
"""
self._prepare()
while self.running:
if self._run() is False:
break
time.sleep(self._sleep_period)
self.shutdown() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_prepare",
"(",
")",
"while",
"self",
".",
"running",
":",
"if",
"self",
".",
"_run",
"(",
")",
"is",
"False",
":",
"break",
"time",
".",
"sleep",
"(",
"self",
".",
"_sleep_period",
")",
"self",
... | 19.25 | 18.166667 |
def delete_proficiency(self, proficiency_id):
"""Deletes a ``Proficiency``.
arg: proficiency_id (osid.id.Id): the ``Id`` of the
``Proficiency`` to remove
raise: NotFound - ``proficiency_id`` not found
raise: NullArgument - ``proficiency_id`` is ``null``
rais... | [
"def",
"delete_proficiency",
"(",
"self",
",",
"proficiency_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'learning'",
",",
"collection",
"=",
"'Proficiency'",
"... | 50.36 | 21.32 |
def load_tasks(self, command='all'):
""" Returns a dictionary of tasks for a list of command."""
results = dict(
(db, self._get_task_objects('status:%s' % db, 'export'))
for db in Command.files(command)
)
# 'waiting' tasks are returned separately from 'pending' ... | [
"def",
"load_tasks",
"(",
"self",
",",
"command",
"=",
"'all'",
")",
":",
"results",
"=",
"dict",
"(",
"(",
"db",
",",
"self",
".",
"_get_task_objects",
"(",
"'status:%s'",
"%",
"db",
",",
"'export'",
")",
")",
"for",
"db",
"in",
"Command",
".",
"fil... | 36.266667 | 21.133333 |
def _try_coerce_args(self, values, other):
"""
localize and return i8 for the values
Parameters
----------
values : ndarray-like
other : ndarray-like or scalar
Returns
-------
base-type values, base-type other
"""
# asi8 is a view... | [
"def",
"_try_coerce_args",
"(",
"self",
",",
"values",
",",
"other",
")",
":",
"# asi8 is a view, needs copy",
"values",
"=",
"_block_shape",
"(",
"values",
".",
"view",
"(",
"\"i8\"",
")",
",",
"ndim",
"=",
"self",
".",
"ndim",
")",
"if",
"isinstance",
"(... | 31.953488 | 15.813953 |
def delete_leads_list(self, leads_list_id):
"""
Delete a leads list.
:param leads_list_id: The id of the list to delete.
:return: 204 Response.
"""
params = self.base_params
endpoint = self.base_endpoint.format(
'leads_lists/' +
str(lead... | [
"def",
"delete_leads_list",
"(",
"self",
",",
"leads_list_id",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"endpoint",
"=",
"self",
".",
"base_endpoint",
".",
"format",
"(",
"'leads_lists/'",
"+",
"str",
"(",
"leads_list_id",
")",
")",
"return",
"se... | 24.25 | 18.125 |
def fit_transform(self, y, exogenous=None, **transform_kwargs):
"""Fit and transform the arrays
Parameters
----------
y : array-like or None, shape=(n_samples,)
The endogenous (time-series) array.
exogenous : array-like or None, shape=(n_samples, n_features), option... | [
"def",
"fit_transform",
"(",
"self",
",",
"y",
",",
"exogenous",
"=",
"None",
",",
"*",
"*",
"transform_kwargs",
")",
":",
"self",
".",
"fit",
"(",
"y",
",",
"exogenous",
")",
"return",
"self",
".",
"transform",
"(",
"y",
",",
"exogenous",
",",
"*",
... | 36.3125 | 19.9375 |
def options(self, parser, env=os.environ):
"""Register commandline options."""
super(TimerPlugin, self).options(parser, env)
# timer top n
parser.add_option(
"--timer-top-n",
action="store",
default="-1",
dest="timer_top_n",
he... | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
"=",
"os",
".",
"environ",
")",
":",
"super",
"(",
"TimerPlugin",
",",
"self",
")",
".",
"options",
"(",
"parser",
",",
"env",
")",
"# timer top n",
"parser",
".",
"add_option",
"(",
"\"--timer-... | 30.554217 | 20.951807 |
def add_graph(self, other):
"""
Add other graph to this graph.
@attention: Attributes and labels are not preserved.
@type other: graph
@param other: Graph
"""
self.add_nodes( n for n in other.nodes() if not n in self.nodes() )
f... | [
"def",
"add_graph",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"add_nodes",
"(",
"n",
"for",
"n",
"in",
"other",
".",
"nodes",
"(",
")",
"if",
"not",
"n",
"in",
"self",
".",
"nodes",
"(",
")",
")",
"for",
"each_node",
"in",
"other",
".",
... | 34.333333 | 16.6 |
def check_unique(self):
"""Check the repository's name is unique"""
result = yield views.repository_name.values(key=self.name)
repo_id = getattr(self, 'id', None)
repos = {x for x in result if x != repo_id and x}
if repos:
raise exceptions.ValidationError(
... | [
"def",
"check_unique",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"views",
".",
"repository_name",
".",
"values",
"(",
"key",
"=",
"self",
".",
"name",
")",
"repo_id",
"=",
"getattr",
"(",
"self",
",",
"'id'",
",",
"None",
")",
"repos",
"=",
"{",... | 42.111111 | 18.666667 |
def _debug(message, color=None, attrs=None):
"""
Print a message if the class attribute 'verbose' is enabled
Args:
message (str): Message to print
"""
if attrs is None:
attrs = []
if color is not None:
print colored(message, color, attrs=attrs)
else:
if len(attrs) > 0:
print colored(messa... | [
"def",
"_debug",
"(",
"message",
",",
"color",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"[",
"]",
"if",
"color",
"is",
"not",
"None",
":",
"print",
"colored",
"(",
"message",
",",
"color",
... | 22.3125 | 18.0625 |
def get_filter(self):
""" Returns the filter applie to this column """
q = self.q().select('name').expand('filter')
response = self.session.get(self.build_url(''), params=q.as_params())
if not response:
return None
data = response.json()
return data.get('crite... | [
"def",
"get_filter",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"q",
"(",
")",
".",
"select",
"(",
"'name'",
")",
".",
"expand",
"(",
"'filter'",
")",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"build_url",
"(",
"''... | 40.5 | 14 |
def dump(self, content, filepath, indent=4):
"""
Dump settings content to filepath.
Args:
content (str): Settings content.
filepath (str): Settings file location.
"""
with open(filepath, 'w') as fp:
json.dump(content, fp, indent=indent) | [
"def",
"dump",
"(",
"self",
",",
"content",
",",
"filepath",
",",
"indent",
"=",
"4",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'w'",
")",
"as",
"fp",
":",
"json",
".",
"dump",
"(",
"content",
",",
"fp",
",",
"indent",
"=",
"indent",
")"
] | 30.4 | 9.8 |
def initWithEventUriList(uriList):
"""
Set a custom list of event uris. The results will be then computed on this list - no query will be done (all conditions will be ignored).
"""
q = QueryEvents()
assert isinstance(uriList, list), "uriList has to be a list of strings that repre... | [
"def",
"initWithEventUriList",
"(",
"uriList",
")",
":",
"q",
"=",
"QueryEvents",
"(",
")",
"assert",
"isinstance",
"(",
"uriList",
",",
"list",
")",
",",
"\"uriList has to be a list of strings that represent event uris\"",
"q",
".",
"queryParams",
"=",
"{",
"\"acti... | 53.875 | 32.375 |
def psd(data, dt, ndivide=1, window=hanning, overlap_half=False):
"""Calculate power spectrum density of data.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
ax (m... | [
"def",
"psd",
"(",
"data",
",",
"dt",
",",
"ndivide",
"=",
"1",
",",
"window",
"=",
"hanning",
",",
"overlap_half",
"=",
"False",
")",
":",
"logger",
"=",
"getLogger",
"(",
"'decode.utils.ndarray.psd'",
")",
"if",
"overlap_half",
":",
"step",
"=",
"int",... | 33.795918 | 20.265306 |
def copy(self, keys = None):
"""
Return a copy of the segmentlistdict object. The return
value is a new object with a new offsets attribute, with
references to the original keys, and shallow copies of the
segment lists. Modifications made to the offset dictionary
or segmentlists in the object returned by ... | [
"def",
"copy",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"self",
"new",
"=",
"self",
".",
"__class__",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"new",
"[",
"key",
"]",
"=",
"_shallowcopy",
... | 36.953488 | 19.372093 |
def terminal(self, module_color='default', background='reverse',
quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes tha... | [
"def",
"terminal",
"(",
"self",
",",
"module_color",
"=",
"'default'",
",",
"background",
"=",
"'reverse'",
",",
"quiet_zone",
"=",
"4",
")",
":",
"return",
"builder",
".",
"_terminal",
"(",
"self",
".",
"code",
",",
"module_color",
",",
"background",
",",... | 51.212766 | 24.255319 |
def CallClient(self,
action_cls,
request=None,
next_state=None,
request_data=None,
**kwargs):
"""Calls the client asynchronously.
This sends a message to the client to invoke an Action. The run action may
send back many re... | [
"def",
"CallClient",
"(",
"self",
",",
"action_cls",
",",
"request",
"=",
"None",
",",
"next_state",
"=",
"None",
",",
"request_data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"action_identifier",
"=",
"action_registry",
".",
"ID_BY_ACTI... | 38.141304 | 21.163043 |
def extends_(cls, kls):
"""
A view decorator to extend another view class or function to itself
It will inherit all its methods and propeties and use them on itself
-- EXAMPLES --
class Index(Pylot):
pass
index = Index()
::-> As decorator on classe... | [
"def",
"extends_",
"(",
"cls",
",",
"kls",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"kls",
")",
":",
"for",
"_name",
",",
"_val",
"in",
"kls",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"_name",
".",
"startswith",
"(",
"\"_... | 24.611111 | 19.388889 |
def getReffs(self, textId, level=1, subreference=None):
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param level: Depth for retrieval
:type level: int
:param subreference: CapitainsCtsPassage Reference
:... | [
"def",
"getReffs",
"(",
"self",
",",
"textId",
",",
"level",
"=",
"1",
",",
"subreference",
"=",
"None",
")",
":",
"depth",
"=",
"level",
"if",
"subreference",
":",
"textId",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"textId",
",",
"subreference",
")",
"if... | 35.26087 | 13.782609 |
def parse_config_input_output(args=sys.argv):
"""Parse the args using the config_file, input_dir, output_dir pattern
Args:
args: sys.argv
Returns:
The populated namespace object from parser.parse_args().
Raises:
TBD
"""
parser = argparse.ArgumentParser(
descrip... | [
"def",
"parse_config_input_output",
"(",
"args",
"=",
"sys",
".",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Process the input files using the given config'",
")",
"parser",
".",
"add_argument",
"(",
"'config_file'",... | 29.851852 | 17.37037 |
def get_extension(self, publisher_name, extension_name, version=None, flags=None, account_token=None, account_token_header=None):
"""GetExtension.
[Preview API]
:param str publisher_name:
:param str extension_name:
:param str version:
:param str flags:
:param str ... | [
"def",
"get_extension",
"(",
"self",
",",
"publisher_name",
",",
"extension_name",
",",
"version",
"=",
"None",
",",
"flags",
"=",
"None",
",",
"account_token",
"=",
"None",
",",
"account_token_header",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
... | 55.034483 | 24.793103 |
def snapshot(self, target, defer=True, file_number=None):
'''
Ask the drawqueue to output to target.
target can be anything supported by the combination
of canvas implementation and drawqueue implmentation.
If target is not supported then an exception is thrown.
'''
... | [
"def",
"snapshot",
"(",
"self",
",",
"target",
",",
"defer",
"=",
"True",
",",
"file_number",
"=",
"None",
")",
":",
"output_func",
"=",
"self",
".",
"output_closure",
"(",
"target",
",",
"file_number",
")",
"if",
"defer",
":",
"self",
".",
"_drawqueue",... | 36 | 22.857143 |
def transform_annotation(self, ann, duration):
'''Apply the vector transformation.
Parameters
----------
ann : jams.Annotation
The input annotation
duration : number > 0
The duration of the track
Returns
-------
data : dict
... | [
"def",
"transform_annotation",
"(",
"self",
",",
"ann",
",",
"duration",
")",
":",
"_",
",",
"values",
"=",
"ann",
".",
"to_interval_values",
"(",
")",
"vector",
"=",
"np",
".",
"asarray",
"(",
"values",
"[",
"0",
"]",
",",
"dtype",
"=",
"self",
".",... | 27.931034 | 19.586207 |
def ifftn(a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT). In other ... | [
"def",
"ifftn",
"(",
"a",
",",
"s",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"norm",
"=",
"None",
")",
":",
"unitary",
"=",
"_unitary",
"(",
"norm",
")",
"output",
"=",
"mkl_fft",
".",
"ifftn",
"(",
"a",
",",
"s",
",",
"axes",
")",
"if",
"... | 39.845361 | 24.030928 |
def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The str... | [
"def",
"get_valid_class_name",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"s",
"=",
"str",
"(",
"s",
")",
".",
"strip",
"(",
")",
"s",
"=",
"''",
".",
"join",
"(",
"[",
"w",
".",
"title",
"(",
")",
"for",
"w",
"in",
"re",
".",
"split",
"(... | 37.307692 | 16.307692 |
def _conn_string_adodbapi(self, db_key, instance=None, conn_key=None, db_name=None):
''' Return a connection string to use with adodbapi
'''
if instance:
_, host, username, password, database, _ = self._get_access_info(instance, db_key, db_name)
elif conn_key:
_, ... | [
"def",
"_conn_string_adodbapi",
"(",
"self",
",",
"db_key",
",",
"instance",
"=",
"None",
",",
"conn_key",
"=",
"None",
",",
"db_name",
"=",
"None",
")",
":",
"if",
"instance",
":",
"_",
",",
"host",
",",
"username",
",",
"password",
",",
"database",
"... | 42.944444 | 25.611111 |
def _start_http_session(self):
"""
Start a new requests HTTP session, clearing cookies and session data.
:return: None
"""
api_logger.debug("Starting new HTTP session...")
self.session = requests.Session()
self.session.headers.update({"User-Agent": self.user_agent... | [
"def",
"_start_http_session",
"(",
"self",
")",
":",
"api_logger",
".",
"debug",
"(",
"\"Starting new HTTP session...\"",
")",
"self",
".",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"session",
".",
"headers",
".",
"update",
"(",
"{",... | 45.181818 | 15.727273 |
def _EccZmaxRperiRap(self,*args,**kwargs):
"""
NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the Staeckel approximation
INPUT:
Either:
a) R,vR,vT,z,vz[,phi... | [
"def",
"_EccZmaxRperiRap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"delta",
"=",
"kwargs",
".",
"get",
"(",
"'delta'",
",",
"self",
".",
"_delta",
")",
"umin",
",",
"umax",
",",
"vmin",
"=",
"self",
".",
"_uminumaxvmin",
"... | 57.814815 | 33 |
def _apply_common_rules(self, part, maxlength):
"""This method contains the rules that must be applied to both the
domain and the local part of the e-mail address.
"""
part = part.strip()
if self.fix:
part = part.strip('.')
if not part:
... | [
"def",
"_apply_common_rules",
"(",
"self",
",",
"part",
",",
"maxlength",
")",
":",
"part",
"=",
"part",
".",
"strip",
"(",
")",
"if",
"self",
".",
"fix",
":",
"part",
"=",
"part",
".",
"strip",
"(",
"'.'",
")",
"if",
"not",
"part",
":",
"return",
... | 30.6 | 18.4 |
def transaction_type(self, value):
"""Set the TransactionType (with Input Validation)"""
if value is not None:
if value not in self.ALLOWED_TRANSACTION_TYPES:
raise AttributeError('%s transaction_type element must be one of %s not %s' % (
self.__class__.__... | [
"def",
"transaction_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
"not",
"in",
"self",
".",
"ALLOWED_TRANSACTION_TYPES",
":",
"raise",
"AttributeError",
"(",
"'%s transaction_type element must be one of %s not %s... | 58.714286 | 21.142857 |
def FingerprintFile(self, pathspec, max_filesize=None, request_data=None):
"""Launch a fingerprint client action."""
request = rdf_client_action.FingerprintRequest(pathspec=pathspec)
if max_filesize is not None:
request.max_filesize = max_filesize
# Generic hash.
request.AddRequest(
f... | [
"def",
"FingerprintFile",
"(",
"self",
",",
"pathspec",
",",
"max_filesize",
"=",
"None",
",",
"request_data",
"=",
"None",
")",
":",
"request",
"=",
"rdf_client_action",
".",
"FingerprintRequest",
"(",
"pathspec",
"=",
"pathspec",
")",
"if",
"max_filesize",
"... | 36.758621 | 21.068966 |
def _get_event_kwargs(view_obj):
""" Helper function to get event kwargs.
:param view_obj: Instance of View that processes the request.
:returns dict: Containing event kwargs or None if events shouldn't
be fired.
"""
request = view_obj.request
view_method = getattr(view_obj, request.ac... | [
"def",
"_get_event_kwargs",
"(",
"view_obj",
")",
":",
"request",
"=",
"view_obj",
".",
"request",
"view_method",
"=",
"getattr",
"(",
"view_obj",
",",
"request",
".",
"action",
")",
"do_trigger",
"=",
"not",
"(",
"getattr",
"(",
"view_method",
",",
"'_silen... | 31.653846 | 15.615385 |
def setCurrentIndex(self, index):
"""
Sets the current index for the history stack.
:param index | <int>
:return <bool> | success
"""
if 0 <= index and index < len(self._stack):
self._blockStack = True
self._index = inde... | [
"def",
"setCurrentIndex",
"(",
"self",
",",
"index",
")",
":",
"if",
"0",
"<=",
"index",
"and",
"index",
"<",
"len",
"(",
"self",
".",
"_stack",
")",
":",
"self",
".",
"_blockStack",
"=",
"True",
"self",
".",
"_index",
"=",
"index",
"self",
".",
"e... | 28.533333 | 10.933333 |
async def get_reply_message(self):
"""
The `Message` that this message is replying to, or ``None``.
The result will be cached after its first use.
"""
if self._reply_message is None:
if not self.reply_to_msg_id:
return None
# Bots cannot ... | [
"async",
"def",
"get_reply_message",
"(",
"self",
")",
":",
"if",
"self",
".",
"_reply_message",
"is",
"None",
":",
"if",
"not",
"self",
".",
"reply_to_msg_id",
":",
"return",
"None",
"# Bots cannot access other bots' messages by their ID.",
"# However they can access t... | 39.703704 | 18.37037 |
def session_preparation(self):
"""Prepare the session after the connection has been established."""
self.set_base_prompt()
cmd = self.RETURN + "rows 0" + self.RETURN
self.disable_paging(command=cmd) | [
"def",
"session_preparation",
"(",
"self",
")",
":",
"self",
".",
"set_base_prompt",
"(",
")",
"cmd",
"=",
"self",
".",
"RETURN",
"+",
"\"rows 0\"",
"+",
"self",
".",
"RETURN",
"self",
".",
"disable_paging",
"(",
"command",
"=",
"cmd",
")"
] | 45.2 | 6 |
def handle(self,
t_input: inference.TranslatorInput,
t_output: inference.TranslatorOutput,
t_walltime: float = 0.):
"""
:param t_input: Translator input.
:param t_output: Translator output.
:param t_walltime: Total wall-clock time for translat... | [
"def",
"handle",
"(",
"self",
",",
"t_input",
":",
"inference",
".",
"TranslatorInput",
",",
"t_output",
":",
"inference",
".",
"TranslatorOutput",
",",
"t_walltime",
":",
"float",
"=",
"0.",
")",
":",
"print_attention_text",
"(",
"t_output",
".",
"attention_m... | 39.692308 | 8 |
async def starttls(
self,
tls_context: ssl.SSLContext,
server_hostname: str = None,
timeout: NumType = None,
) -> StartTLSResponse:
"""
Puts the connection to the SMTP server into TLS mode.
"""
if self._stream_reader is None or self._stream_writer is N... | [
"async",
"def",
"starttls",
"(",
"self",
",",
"tls_context",
":",
"ssl",
".",
"SSLContext",
",",
"server_hostname",
":",
"str",
"=",
"None",
",",
"timeout",
":",
"NumType",
"=",
"None",
",",
")",
"->",
"StartTLSResponse",
":",
"if",
"self",
".",
"_stream... | 32.967742 | 21.935484 |
def cronbach_alpha(data=None, items=None, scores=None, subject=None,
remove_na=False, ci=.95):
"""Cronbach's alpha reliability measure.
Parameters
----------
data : pandas dataframe
Wide or long-format dataframe.
items : str
Column in ``data`` with the items names... | [
"def",
"cronbach_alpha",
"(",
"data",
"=",
"None",
",",
"items",
"=",
"None",
",",
"scores",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"remove_na",
"=",
"False",
",",
"ci",
"=",
".95",
")",
":",
"# Safety check",
"assert",
"isinstance",
"(",
"data... | 35.541096 | 24.917808 |
def fetch(self):
"""
Fetch a TaskActionsInstance
:returns: Fetched TaskActionsInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self.... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"TaskA... | 25.952381 | 18.809524 |
def kappa(self, x, y, kwargs, diff=diff):
"""
computes the convergence
:return: kappa
"""
f_xx, f_xy, f_yx, f_yy = self.hessian(x, y, kwargs, diff=diff)
kappa = 1./2 * (f_xx + f_yy)
return kappa | [
"def",
"kappa",
"(",
"self",
",",
"x",
",",
"y",
",",
"kwargs",
",",
"diff",
"=",
"diff",
")",
":",
"f_xx",
",",
"f_xy",
",",
"f_yx",
",",
"f_yy",
"=",
"self",
".",
"hessian",
"(",
"x",
",",
"y",
",",
"kwargs",
",",
"diff",
"=",
"diff",
")",
... | 30.375 | 10.125 |
def get_state(self, state):
"""Returns True if the specified state is enabled."""
# Check to see if we have a change request pending; if we do
# return the value we expect it to change to.
for data in list(self._send_queue.queue):
desired_states = data['desired_states']
... | [
"def",
"get_state",
"(",
"self",
",",
"state",
")",
":",
"# Check to see if we have a change request pending; if we do",
"# return the value we expect it to change to.",
"for",
"data",
"in",
"list",
"(",
"self",
".",
"_send_queue",
".",
"queue",
")",
":",
"desired_states"... | 51.666667 | 12.083333 |
def rename(
df,
values: Dict[str, Dict[str, str]] = None,
columns: Dict[str, Dict[str, str]] = None,
locale: str = None
):
"""
Replaces data values and column names according to the locale
---
### Parameters
- `values` (optional: dict):
- key: term to be re... | [
"def",
"rename",
"(",
"df",
",",
"values",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
",",
"columns",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
",",
"locale"... | 23.61194 | 20.119403 |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
self.needs_no_rtr(rtr)
self.set_attributes(priority, address, rtr) | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
")",
"self",
".",
"set_attributes",
"(",
"priority",
",",
"address",
",",
"rtr",
")"
] | 28.833333 | 8.166667 |
def set_network(ip, netmask, gateway, host=None,
admin_username=None, admin_password=None):
'''
Configure Network on the CMC or individual iDRAC.
Use ``set_niccfg`` for blade and switch addresses.
CLI Example:
.. code-block:: bash
salt dell dracr.set_network [DRAC IP] [NET... | [
"def",
"set_network",
"(",
"ip",
",",
"netmask",
",",
"gateway",
",",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
")",
":",
"return",
"__execute_cmd",
"(",
"'setniccfg -s {0} {1} {2}'",
".",
"format",
"(",
"ip... | 36 | 25.222222 |
def paintEvent( self, event ):
"""
Overloads the paint event to handle drawing the splitter lines.
:param event | <QPaintEvent>
"""
lines = []
count = 20
# calculate the lines
if ( self.orientation() == Qt.Vertical ):
x =... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"lines",
"=",
"[",
"]",
"count",
"=",
"20",
"# calculate the lines",
"if",
"(",
"self",
".",
"orientation",
"(",
")",
"==",
"Qt",
".",
"Vertical",
")",
":",
"x",
"=",
"self",
".",
"_resizeGrip... | 32.09375 | 14.40625 |
def cert(name,
aliases=None,
email=None,
webroot=None,
test_cert=False,
renew=None,
keysize=None,
server=None,
owner='root',
group='root',
mode='0640',
certname=None,
preferred_challenges=None,
tls_sni_0... | [
"def",
"cert",
"(",
"name",
",",
"aliases",
"=",
"None",
",",
"email",
"=",
"None",
",",
"webroot",
"=",
"None",
",",
"test_cert",
"=",
"False",
",",
"renew",
"=",
"None",
",",
"keysize",
"=",
"None",
",",
"server",
"=",
"None",
",",
"owner",
"=",
... | 42.881579 | 26.473684 |
def _config_profile_get(self, thisprofile):
"""Get information of a config profile from DCNM.
:param thisprofile: network config profile in request
"""
url = self._cfg_profile_get_url % (thisprofile)
payload = {}
res = self._send_request('GET', url, payload, 'config-pro... | [
"def",
"_config_profile_get",
"(",
"self",
",",
"thisprofile",
")",
":",
"url",
"=",
"self",
".",
"_cfg_profile_get_url",
"%",
"(",
"thisprofile",
")",
"payload",
"=",
"{",
"}",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"url",
",",
"pa... | 36.272727 | 17.545455 |
def set_id(self, dxid):
'''
:param dxid: New ID to be associated with the handler
:type dxid: string
Discards the currently stored ID and associates the handler with *dxid*
'''
if dxid is not None:
verify_string_dxid(dxid, self._class)
self._dxid = d... | [
"def",
"set_id",
"(",
"self",
",",
"dxid",
")",
":",
"if",
"dxid",
"is",
"not",
"None",
":",
"verify_string_dxid",
"(",
"dxid",
",",
"self",
".",
"_class",
")",
"self",
".",
"_dxid",
"=",
"dxid"
] | 28.454545 | 24.090909 |
def _start_remaining_containers(self, containers_remaining, tool_d):
"""
Select remaining containers that didn't have priorities to start
"""
s_containers = []
f_containers = []
for container in containers_remaining:
s_containers, f_containers = self._start_co... | [
"def",
"_start_remaining_containers",
"(",
"self",
",",
"containers_remaining",
",",
"tool_d",
")",
":",
"s_containers",
"=",
"[",
"]",
"f_containers",
"=",
"[",
"]",
"for",
"container",
"in",
"containers_remaining",
":",
"s_containers",
",",
"f_containers",
"=",
... | 49.666667 | 19.5 |
def send_message(self, subject=None, text=None, markdown=None, message_dict=None):
"""
Helper function to send a message to a group
"""
message = FiestaMessage(self.api, self, subject, text, markdown, message_dict)
return message.send() | [
"def",
"send_message",
"(",
"self",
",",
"subject",
"=",
"None",
",",
"text",
"=",
"None",
",",
"markdown",
"=",
"None",
",",
"message_dict",
"=",
"None",
")",
":",
"message",
"=",
"FiestaMessage",
"(",
"self",
".",
"api",
",",
"self",
",",
"subject",
... | 45.166667 | 18.5 |
def url(self):
"""
Return the appropriate URL.
URL is constructed based on these field conditions:
* If empty (not `self.name`) and a placeholder is defined, the
URL to the placeholder is returned.
* Otherwise, defaults to vanilla ImageFieldFile behavior.
... | [
"def",
"url",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"name",
"and",
"self",
".",
"field",
".",
"placeholder_image_name",
":",
"return",
"self",
".",
"storage",
".",
"url",
"(",
"self",
".",
"field",
".",
"placeholder_image_name",
")",
"return",... | 38.923077 | 20.461538 |
def connect_to_jira(self, JIRAUsername=None,
JIRAPassword=None, options=None):
"""
Connect to a JIRA server.
Arguments:
| JIRAUsername (string) | (Optional) A JIRA Username you wish to authenticate with, will authorise with anonymous account... | [
"def",
"connect_to_jira",
"(",
"self",
",",
"JIRAUsername",
"=",
"None",
",",
"JIRAPassword",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"JIRAUsername",
"is",
"not",
"None",
"and",
"(",
"JIRAPassword",
"is",
"\"\"",
"or",
"JIRAPassword",
"is... | 60.234043 | 44.87234 |
def content_children(self):
"""
A sequence containing the text-container child elements of this
``<a:p>`` element, i.e. (a:r|a:br|a:fld).
"""
text_types = {CT_RegularTextRun, CT_TextLineBreak, CT_TextField}
return tuple(elm for elm in self if type(elm) in text_types) | [
"def",
"content_children",
"(",
"self",
")",
":",
"text_types",
"=",
"{",
"CT_RegularTextRun",
",",
"CT_TextLineBreak",
",",
"CT_TextField",
"}",
"return",
"tuple",
"(",
"elm",
"for",
"elm",
"in",
"self",
"if",
"type",
"(",
"elm",
")",
"in",
"text_types",
... | 44.142857 | 16.142857 |
def servers_update_addresses(request, servers, all_tenants=False):
"""Retrieve servers networking information from Neutron if enabled.
Should be used when up to date networking information is required,
and Nova's networking info caching mechanism is not fast enough.
"""
# NOTE(amotoki): This... | [
"def",
"servers_update_addresses",
"(",
"request",
",",
"servers",
",",
"all_tenants",
"=",
"False",
")",
":",
"# NOTE(amotoki): This check is still needed because 'instances' panel",
"# calls this method. We dropped security group and floating IP support",
"# through Nova API (due to no... | 54.333333 | 25.222222 |
def expand_cmd_labels(self):
"""Expand make-style variables in cmd parameters.
Currently:
$(location <foo>) Location of one dependency or output file.
$(locations <foo>) Space-delimited list of foo's output files.
$(SRCS) Space-delimited list of this rule's ... | [
"def",
"expand_cmd_labels",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"cmd",
"def",
"_expand_onesrc",
"(",
")",
":",
"\"\"\"Expand $@ or $(@) to one output file.\"\"\"",
"outs",
"=",
"self",
".",
"rule",
".",
"params",
"[",
"'outs'",
"]",
"or",
"[",
"]... | 45 | 20.558559 |
def _get_stats_table(html_page, div, footer=False):
"""
Returns a generator of all rows in a requested table.
When given a PyQuery HTML object and a requested div, this function creates
a generator where every item is a PyQuery object pertaining to every row in
the table. Generally, each row will c... | [
"def",
"_get_stats_table",
"(",
"html_page",
",",
"div",
",",
"footer",
"=",
"False",
")",
":",
"stats_html",
"=",
"html_page",
"(",
"div",
")",
"try",
":",
"stats_table",
"=",
"pq",
"(",
"_remove_html_comment_tags",
"(",
"stats_html",
")",
")",
"except",
... | 35.514286 | 23.628571 |
def unionstore(self, destination, *others):
""" The same as :meth:union, but stores the result in @destination
@destination: #str keyname or :class:RedisSet
@others: one or several #str keynames or :class:RedisSet objects
-> #int number of items in the resulting set
... | [
"def",
"unionstore",
"(",
"self",
",",
"destination",
",",
"*",
"others",
")",
":",
"others",
"=",
"self",
".",
"_typesafe_others",
"(",
"others",
")",
"destination",
"=",
"self",
".",
"_typesafe",
"(",
"destination",
")",
"return",
"self",
".",
"_client",... | 44.545455 | 18.636364 |
def do_continue(self, args):
"""Continue the interpreter
"""
self._do_print_from_last_cmd = True
self._interp.cont()
return True | [
"def",
"do_continue",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"_do_print_from_last_cmd",
"=",
"True",
"self",
".",
"_interp",
".",
"cont",
"(",
")",
"return",
"True"
] | 27.166667 | 8.166667 |
def parse_uri(uri, default_port=DEFAULT_PORT, validate=True, warn=False):
"""Parse and validate a MongoDB URI.
Returns a dict of the form::
{
'nodelist': <list of (host, port) tuples>,
'username': <username> or None,
'password': <password> or None,
'data... | [
"def",
"parse_uri",
"(",
"uri",
",",
"default_port",
"=",
"DEFAULT_PORT",
",",
"validate",
"=",
"True",
",",
"warn",
"=",
"False",
")",
":",
"if",
"uri",
".",
"startswith",
"(",
"SCHEME",
")",
":",
"is_srv",
"=",
"False",
"scheme_free",
"=",
"uri",
"["... | 33.124138 | 20.524138 |
def check_params(**kwargs):
"""check_params: check whether some parameters are missing
"""
missing_params = []
check = True
for param in kwargs:
if kwargs[param] is None:
missing_params.append(param)
if len(missing_params) > 0:
print("POT - Warning: following neces... | [
"def",
"check_params",
"(",
"*",
"*",
"kwargs",
")",
":",
"missing_params",
"=",
"[",
"]",
"check",
"=",
"True",
"for",
"param",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"param",
"]",
"is",
"None",
":",
"missing_params",
".",
"append",
"(",
"param",
... | 22.736842 | 20.263158 |
def projects(self):
"""*All child projects of this taskpaper object*
**Usage:**
Given a taskpaper document object (`doc`), to get a list of the project objects found within the document use:
.. code-block:: python
docProjects = doc.projects
The sa... | [
"def",
"projects",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_object",
"(",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'((?<=\\n)|(?<=^))(?P<title>(?!\\[Searches\\]|- )\\S.*?:(?!\\S)) *(?P<tagString>( *?@[^(\\s]+(\\([^)]*\\))?)+)?(?P<content>(\\n(( |\\t)+\\S.*)|\\n( |\\t)*... | 33.708333 | 28.25 |
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
"""
root_node = ET.Element("no2index")
reference_time_node = ET.SubElement(root_node, "reference_time")
reference_t... | [
"def",
"_to_DOM",
"(",
"self",
")",
":",
"root_node",
"=",
"ET",
".",
"Element",
"(",
"\"no2index\"",
")",
"reference_time_node",
"=",
"ET",
".",
"SubElement",
"(",
"root_node",
",",
"\"reference_time\"",
")",
"reference_time_node",
".",
"text",
"=",
"str",
... | 43.692308 | 18.461538 |
def __clear_variable_watch(self, tid, address):
"""
Used by L{dont_watch_variable} and L{dont_stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to stop watching.
"""
if self.has_... | [
"def",
"__clear_variable_watch",
"(",
"self",
",",
"tid",
",",
"address",
")",
":",
"if",
"self",
".",
"has_hardware_breakpoint",
"(",
"tid",
",",
"address",
")",
":",
"self",
".",
"erase_hardware_breakpoint",
"(",
"tid",
",",
"address",
")"
] | 33.333333 | 17 |
def write_node(node, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descen... | [
"def",
"write_node",
"(",
"node",
",",
"writer",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"indent",
"=",
"0",
",",
"newline",
"=",
"''",
",",
"omit_declaration",
"=",
"False",
",",
"node_depth",
"=",
"0",
",",
"quote_char",
"=",
"'\"'",
")",
... | 41.847953 | 15.912281 |
def set_exe(self, pipes_code):
"""
Dump launcher code to the distributed file system.
"""
if not self.output:
raise RuntimeError("no output directory, can't create launcher")
parent = hdfs.path.dirname(hdfs.path.abspath(self.output.rstrip("/")))
self.exe = hdf... | [
"def",
"set_exe",
"(",
"self",
",",
"pipes_code",
")",
":",
"if",
"not",
"self",
".",
"output",
":",
"raise",
"RuntimeError",
"(",
"\"no output directory, can't create launcher\"",
")",
"parent",
"=",
"hdfs",
".",
"path",
".",
"dirname",
"(",
"hdfs",
".",
"p... | 44 | 15.777778 |
def get_last_ticker(self, symbol, _async=False):
"""
获取tradedetail
:param symbol
:return:
"""
params = {'symbol': symbol}
url = u.MARKET_URL + '/market/trade'
return http_get_request(url, params, _async=_async) | [
"def",
"get_last_ticker",
"(",
"self",
",",
"symbol",
",",
"_async",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'symbol'",
":",
"symbol",
"}",
"url",
"=",
"u",
".",
"MARKET_URL",
"+",
"'/market/trade'",
"return",
"http_get_request",
"(",
"url",
",",
"p... | 26.6 | 13.8 |
def has_space_element(source):
"""
判断对象中的元素,如果存在 None 或空字符串,则返回 True, 否则返回 False, 支持字典、列表和元组
:param:
* source: (list, set, dict) 需要检查的对象
:return:
* result: (bool) 存在 None 或空字符串或空格字符串返回 True, 否则返回 False
举例如下::
print('--- has_space_element demo---')
print(has_space_... | [
"def",
"has_space_element",
"(",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"dict",
")",
":",
"check_list",
"=",
"list",
"(",
"source",
".",
"values",
"(",
")",
")",
"elif",
"isinstance",
"(",
"source",
",",
"list",
")",
"or",
"isinsta... | 25.444444 | 21.177778 |
def validate_ldap(self):
logging.debug('Validating LDAPLoginForm against LDAP')
'Validate the username/password data against ldap directory'
ldap_mgr = current_app.ldap3_login_manager
username = self.username.data
password = self.password.data
result = ldap_mgr.authentic... | [
"def",
"validate_ldap",
"(",
"self",
")",
":",
"logging",
".",
"debug",
"(",
"'Validating LDAPLoginForm against LDAP'",
")",
"ldap_mgr",
"=",
"current_app",
".",
"ldap3_login_manager",
"username",
"=",
"self",
".",
"username",
".",
"data",
"password",
"=",
"self",... | 35.347826 | 19 |
def frombed(args):
"""
%prog frombed bedfile
Generate AGP file based on bed file. The bed file must have at least 6
columns. With the 4-th column indicating the new object.
"""
p = OptionParser(frombed.__doc__)
p.add_option("--gapsize", default=100, type="int",
help="Insert... | [
"def",
"frombed",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"frombed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--gapsize\"",
",",
"default",
"=",
"100",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Insert gaps of size [default... | 30.513514 | 18.081081 |
def generalized_lsp_value_withtau(times, mags, errs, omega):
'''Generalized LSP value for a single omega.
This uses tau to provide an arbitrary time-reference point.
The relations used are::
P(w) = (1/YY) * (YC*YC/CC + YS*YS/SS)
where: YC, YS, CC, and SS are all calculated at T
... | [
"def",
"generalized_lsp_value_withtau",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"omega",
")",
":",
"one_over_errs2",
"=",
"1.0",
"/",
"(",
"errs",
"*",
"errs",
")",
"W",
"=",
"npsum",
"(",
"one_over_errs2",
")",
"wi",
"=",
"one_over_errs2",
"/",
"W"... | 25.8 | 20.219048 |
def _pad_sequence_fix(attr, kernelDim=None):
"""Changing onnx's pads sequence to match with mxnet's pad_width
mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)"""
new_attr = ()
if len(attr) % 2 == 0:
for index in range(int(len(attr) / 2)):
... | [
"def",
"_pad_sequence_fix",
"(",
"attr",
",",
"kernelDim",
"=",
"None",
")",
":",
"new_attr",
"=",
"(",
")",
"if",
"len",
"(",
"attr",
")",
"%",
"2",
"==",
"0",
":",
"for",
"index",
"in",
"range",
"(",
"int",
"(",
"len",
"(",
"attr",
")",
"/",
... | 41.428571 | 13.357143 |
def postponed_to(self):
"""
Date that the event was postponed to (in the local time zone).
"""
toDate = getLocalDate(self.date, self.time_from, self.tz)
return dateFormat(toDate) | [
"def",
"postponed_to",
"(",
"self",
")",
":",
"toDate",
"=",
"getLocalDate",
"(",
"self",
".",
"date",
",",
"self",
".",
"time_from",
",",
"self",
".",
"tz",
")",
"return",
"dateFormat",
"(",
"toDate",
")"
] | 35.5 | 13.166667 |
def walk(
self,
path="/", # type: Text
namespaces=None, # type: Optional[Collection[Text]]
**kwargs # type: Any
):
# type: (...) -> Iterator[Step]
"""Walk the directory structure of a filesystem.
Arguments:
path (str):
namespaces (l... | [
"def",
"walk",
"(",
"self",
",",
"path",
"=",
"\"/\"",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
"*",
"*",
"kwargs",
"# type: Any",
")",
":",
"# type: (...) -> Iterator[Step]",
"walker",
"=",
"self",
".",
"_make_wal... | 47.983333 | 24.9 |
def set_itunes_explicit(self):
"""Parses explicit from itunes tags and sets value"""
try:
self.itunes_explicit = self.soup.find('itunes:explicit').string
self.itunes_explicit = self.itunes_explicit.lower()
except AttributeError:
self.itunes_explicit = None | [
"def",
"set_itunes_explicit",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_explicit",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:explicit'",
")",
".",
"string",
"self",
".",
"itunes_explicit",
"=",
"self",
".",
"itunes_explicit",
".",
... | 44.285714 | 15.285714 |
def safe_repr(source, max_length=0):
"""Wrapper for repr() that catches exceptions."""
try:
return ellipsis(repr(source), max_length)
except Exception as e:
return ellipsis("<n/a: repr(...) raised %s>" % e, max_length) | [
"def",
"safe_repr",
"(",
"source",
",",
"max_length",
"=",
"0",
")",
":",
"try",
":",
"return",
"ellipsis",
"(",
"repr",
"(",
"source",
")",
",",
"max_length",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"ellipsis",
"(",
"\"<n/a: repr(...) raised... | 40.166667 | 14.666667 |
def frigg(branch: str):
"""
Performs necessary checks to ensure that the frigg build is one
that should create releases.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('FRIGG_BUILD_BRANCH') == branch
assert not os.environ.get('FRIGG_PULL_REQUE... | [
"def",
"frigg",
"(",
"branch",
":",
"str",
")",
":",
"assert",
"os",
".",
"environ",
".",
"get",
"(",
"'FRIGG_BUILD_BRANCH'",
")",
"==",
"branch",
"assert",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'FRIGG_PULL_REQUEST'",
")"
] | 35.111111 | 16.888889 |
def handleOACK(self, pkt):
"""This method handles an OACK from the server, syncing any accepted
options."""
if len(pkt.options.keys()) > 0:
if pkt.match_options(self.context.options):
log.info("Successful negotiation of options")
# Set options to OACK ... | [
"def",
"handleOACK",
"(",
"self",
",",
"pkt",
")",
":",
"if",
"len",
"(",
"pkt",
".",
"options",
".",
"keys",
"(",
")",
")",
">",
"0",
":",
"if",
"pkt",
".",
"match_options",
"(",
"self",
".",
"context",
".",
"options",
")",
":",
"log",
".",
"i... | 47.2 | 14.866667 |
def _sendDDEcommand(self, cmd, timeout=None):
"""Send command to DDE client"""
reply = self.conversation.Request(cmd, timeout)
if self.pyver > 2:
reply = reply.decode('ascii').rstrip()
return reply | [
"def",
"_sendDDEcommand",
"(",
"self",
",",
"cmd",
",",
"timeout",
"=",
"None",
")",
":",
"reply",
"=",
"self",
".",
"conversation",
".",
"Request",
"(",
"cmd",
",",
"timeout",
")",
"if",
"self",
".",
"pyver",
">",
"2",
":",
"reply",
"=",
"reply",
... | 39.333333 | 10.666667 |
def getResultsRange(self):
"""Returns the valid result ranges for the analyses this Analysis
Request contains.
By default uses the result ranges defined in the Analysis Specification
set in "Specification" field if any. Values manually set through
`ResultsRange` field for any gi... | [
"def",
"getResultsRange",
"(",
"self",
")",
":",
"specs_range",
"=",
"[",
"]",
"specification",
"=",
"self",
".",
"getSpecification",
"(",
")",
"if",
"specification",
":",
"specs_range",
"=",
"specification",
".",
"getResultsRange",
"(",
")",
"specs_range",
"=... | 47.108108 | 22.081081 |
def weld_unique(array, weld_type):
"""Return the unique elements of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Representation of this ... | [
"def",
"weld_unique",
"(",
"array",
",",
"weld_type",
")",
":",
"obj_id",
",",
"weld_obj",
"=",
"create_weld_object",
"(",
"array",
")",
"weld_template",
"=",
"\"\"\"map(\n tovec(\n result(\n for(\n map(\n {array},\n ... | 22.121951 | 20.829268 |
def main():
"""Entry point for the application script"""
if len(sys.argv) >= 2:
cmd = sys.argv[1]
if cmd == "help":
print_usage()
else:
if cmd == "mensa":
print_menu("Mensa")
elif cmd == "bistro":
print_menu("Bistro")
... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">=",
"2",
":",
"cmd",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"if",
"cmd",
"==",
"\"help\"",
":",
"print_usage",
"(",
")",
"else",
":",
"if",
"cmd",
"==",
"\"mensa\"",
... | 31.481481 | 10.666667 |
def send_ready_for_review(build_id, release_name, release_number):
"""Sends an email indicating that the release is ready for review."""
build = models.Build.query.get(build_id)
if not build.send_email:
logging.debug(
'Not sending ready for review email because build does not have '
... | [
"def",
"send_ready_for_review",
"(",
"build_id",
",",
"release_name",
",",
"release_number",
")",
":",
"build",
"=",
"models",
".",
"Build",
".",
"query",
".",
"get",
"(",
"build_id",
")",
"if",
"not",
"build",
".",
"send_email",
":",
"logging",
".",
"debu... | 33.75 | 21.576923 |
def solve_let(expr, vars):
"""Solves a let-form by calling RHS with nested scope."""
lhs_value = solve(expr.lhs, vars).value
if not isinstance(lhs_value, structured.IStructured):
raise errors.EfilterTypeError(
root=expr.lhs, query=expr.original,
message="The LHS of 'let' must... | [
"def",
"solve_let",
"(",
"expr",
",",
"vars",
")",
":",
"lhs_value",
"=",
"solve",
"(",
"expr",
".",
"lhs",
",",
"vars",
")",
".",
"value",
"if",
"not",
"isinstance",
"(",
"lhs_value",
",",
"structured",
".",
"IStructured",
")",
":",
"raise",
"errors",... | 44.5 | 16.2 |
def getUserInfoError(sAccessToken):
"""
May be return {u'msg': u'Access_token repealed', u'errno': u'-102', u'data': []}
"""
import urllib.request, urllib.parse, urllib.error
payload = urllib.parse.urlencode({'access_token': sAccessToken})
c = http.client.HTTPSConnection('796.com')
c.req... | [
"def",
"getUserInfoError",
"(",
"sAccessToken",
")",
":",
"import",
"urllib",
".",
"request",
",",
"urllib",
".",
"parse",
",",
"urllib",
".",
"error",
"payload",
"=",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"{",
"'access_token'",
":",
"sAccessToken",... | 38.583333 | 14.75 |
def _lexists(self, path):
'''IMPORTANT: expects `path` to already be deref()'erenced.'''
try:
return bool(self._lstat(path))
except os.error:
return False | [
"def",
"_lexists",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"return",
"bool",
"(",
"self",
".",
"_lstat",
"(",
"path",
")",
")",
"except",
"os",
".",
"error",
":",
"return",
"False"
] | 28.833333 | 19.833333 |
def leave(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[1]
if method is not None:
method(node) | [
"def",
"leave",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"self",
".",
"get_callbacks",
"(",
"node",
")",
"[",
"1",
"]",
"if",
"method",
"is",
"not",
"None",
":",
"method",
"(",
"node",
")"
] | 38.8 | 9.6 |
def printable(sequence):
'''
Return a printable string from the input ``sequence``
:param sequence: byte or string sequence
>>> print(printable('\\x1b[1;34mtest\\x1b[0m'))
.[1;34mtest.[0m
>>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........'
True
>>> print(printable(... | [
"def",
"printable",
"(",
"sequence",
")",
":",
"return",
"''",
".",
"join",
"(",
"list",
"(",
"map",
"(",
"lambda",
"c",
":",
"c",
"if",
"c",
"in",
"PRINTABLE",
"else",
"'.'",
",",
"sequence",
")",
")",
")"
] | 24.05 | 24.75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.