text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_version():
"""
Return formatted version string.
Returns:
str: string with project version or empty string.
"""
if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]):
return FORMAT_STRING.format(**{"version": VERSION, "updated": UPD... | [
"def",
"get_version",
"(",
")",
":",
"if",
"all",
"(",
"[",
"VERSION",
",",
"UPDATED",
",",
"any",
"(",
"[",
"isinstance",
"(",
"UPDATED",
",",
"date",
")",
",",
"isinstance",
"(",
"UPDATED",
",",
"datetime",
")",
",",
"]",
")",
",",
"]",
")",
":... | 25.45 | 29.95 |
def _inject_conversion(self, value, conversion):
"""
value: '{x}', conversion: 's' -> '{x!s}'
"""
t = type(value)
return value[:-1] + t(u'!') + conversion + t(u'}') | [
"def",
"_inject_conversion",
"(",
"self",
",",
"value",
",",
"conversion",
")",
":",
"t",
"=",
"type",
"(",
"value",
")",
"return",
"value",
"[",
":",
"-",
"1",
"]",
"+",
"t",
"(",
"u'!'",
")",
"+",
"conversion",
"+",
"t",
"(",
"u'}'",
")"
] | 33.166667 | 8.5 |
def transmit(self, payload, **kwargs):
"""
Send a completion status call to the integrated channel using the client.
Args:
payload: The learner completion data payload to send to the integrated channel.
kwargs: Contains integrated channel-specific information for customi... | [
"def",
"transmit",
"(",
"self",
",",
"payload",
",",
"*",
"*",
"kwargs",
")",
":",
"IntegratedChannelLearnerDataTransmissionAudit",
"=",
"apps",
".",
"get_model",
"(",
"# pylint: disable=invalid-name",
"app_label",
"=",
"kwargs",
".",
"get",
"(",
"'app_label'",
",... | 57.728814 | 34.067797 |
def run(self, order=None):
"""
self.runner must be present
"""
for event in self.runner.run(order=order):
self.receive(event) | [
"def",
"run",
"(",
"self",
",",
"order",
"=",
"None",
")",
":",
"for",
"event",
"in",
"self",
".",
"runner",
".",
"run",
"(",
"order",
"=",
"order",
")",
":",
"self",
".",
"receive",
"(",
"event",
")"
] | 23.666667 | 7.333333 |
def rnd_date(start=date(1970, 1, 1), end=None, **kwargs):
"""
Generate a random date between ``start`` to ``end``.
:param start: Left bound
:type start: string or datetime.date, (default date(1970, 1, 1))
:param end: Right bound
:type end: string or datetime.date, (default date.today())
:re... | [
"def",
"rnd_date",
"(",
"start",
"=",
"date",
"(",
"1970",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"date",
".",
"today",
"(",
")",
"start",
"=",
"parser"... | 29.2 | 15.9 |
def get_success_url(self):
"""Reverses the ``redis_metric_aggregate_detail`` URL using
``self.metric_slugs`` as an argument."""
slugs = '+'.join(self.metric_slugs)
url = reverse('redis_metric_aggregate_detail', args=[slugs])
# Django 1.6 quotes reversed URLs, which changes + into... | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"slugs",
"=",
"'+'",
".",
"join",
"(",
"self",
".",
"metric_slugs",
")",
"url",
"=",
"reverse",
"(",
"'redis_metric_aggregate_detail'",
",",
"args",
"=",
"[",
"slugs",
"]",
")",
"# Django 1.6 quotes reversed URL... | 57.444444 | 17.111111 |
def _get_parts_list(to_go, so_far=[[]], ticker=None):
""" Iterates over to_go, building the list of parts. To provide
items for the beginning, use so_far.
"""
try:
part = to_go.pop(0)
except IndexError:
return so_far, ticker
# Lists of input groups
if isinstance(part, list) ... | [
"def",
"_get_parts_list",
"(",
"to_go",
",",
"so_far",
"=",
"[",
"[",
"]",
"]",
",",
"ticker",
"=",
"None",
")",
":",
"try",
":",
"part",
"=",
"to_go",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"return",
"so_far",
",",
"ticker",
"# Li... | 33.96875 | 17.65625 |
def bmgs(ctx, event):
""" [bookie] List betting market groups for an event
:param str event: Event id
"""
eg = Event(event, peerplays_instance=ctx.peerplays)
click.echo(pretty_print(eg.bettingmarketgroups, ctx=ctx)) | [
"def",
"bmgs",
"(",
"ctx",
",",
"event",
")",
":",
"eg",
"=",
"Event",
"(",
"event",
",",
"peerplays_instance",
"=",
"ctx",
".",
"peerplays",
")",
"click",
".",
"echo",
"(",
"pretty_print",
"(",
"eg",
".",
"bettingmarketgroups",
",",
"ctx",
"=",
"ctx",... | 33.428571 | 14.428571 |
def qxq(q1, q2):
"""
Multiply two quaternions.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/qxq_c.html
:param q1: First SPICE quaternion.
:type q1: 4-Element Array of floats
:param q2: Second SPICE quaternion.
:type q2: 4-Element Array of floats
:return: Product of q1 and q2... | [
"def",
"qxq",
"(",
"q1",
",",
"q2",
")",
":",
"q1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"q1",
")",
"q2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"q2",
")",
"vout",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"4",
")",
"libspice",
".",
"... | 29.555556 | 10.111111 |
def on_status_update(self, channel, callback):
"""
Callback to execute on status of update of channel
"""
if channel not in self._callbacks:
self._callbacks[channel] = []
self._callbacks[channel].append(callback) | [
"def",
"on_status_update",
"(",
"self",
",",
"channel",
",",
"callback",
")",
":",
"if",
"channel",
"not",
"in",
"self",
".",
"_callbacks",
":",
"self",
".",
"_callbacks",
"[",
"channel",
"]",
"=",
"[",
"]",
"self",
".",
"_callbacks",
"[",
"channel",
"... | 36.857143 | 5.142857 |
def pop(self):
"""Leave the current scope
:returns: TODO
"""
res = self._scope_stack.pop()
self._dlog("popping scope, scope level = {}".format(self.level()))
self._curr_scope = self._scope_stack[-1]
return res | [
"def",
"pop",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"_scope_stack",
".",
"pop",
"(",
")",
"self",
".",
"_dlog",
"(",
"\"popping scope, scope level = {}\"",
".",
"format",
"(",
"self",
".",
"level",
"(",
")",
")",
")",
"self",
".",
"_curr_scop... | 28.666667 | 16.777778 |
def from_sequence(chain, list_of_residues, sequence_type = None):
'''Takes in a chain identifier and protein sequence and returns a Sequence object of Residues, indexed from 1.'''
s = Sequence(sequence_type)
count = 1
for ResidueAA in list_of_residues:
s.add(Residue(chain, co... | [
"def",
"from_sequence",
"(",
"chain",
",",
"list_of_residues",
",",
"sequence_type",
"=",
"None",
")",
":",
"s",
"=",
"Sequence",
"(",
"sequence_type",
")",
"count",
"=",
"1",
"for",
"ResidueAA",
"in",
"list_of_residues",
":",
"s",
".",
"add",
"(",
"Residu... | 48 | 25.5 |
def _convert_agg_to_wx_bitmap(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return w... | [
"def",
"_convert_agg_to_wx_bitmap",
"(",
"agg",
",",
"bbox",
")",
":",
"if",
"bbox",
"is",
"None",
":",
"# agg => rgba buffer -> bitmap",
"return",
"wx",
".",
"BitmapFromBufferRGBA",
"(",
"int",
"(",
"agg",
".",
"width",
")",
",",
"int",
"(",
"agg",
".",
"... | 36.714286 | 16.142857 |
def _recurse_on_row(self, col_dict, nested_value):
"""Apply the schema specified by the given dict to the nested value by
recursing on it.
Parameters
----------
col_dict : dict
The schema to apply to the nested value.
nested_value : A value nested in a BigQue... | [
"def",
"_recurse_on_row",
"(",
"self",
",",
"col_dict",
",",
"nested_value",
")",
":",
"row_value",
"=",
"None",
"# Multiple nested records",
"if",
"col_dict",
"[",
"'mode'",
"]",
"==",
"'REPEATED'",
"and",
"isinstance",
"(",
"nested_value",
",",
"list",
")",
... | 30.964286 | 23.214286 |
def load_value(self, key, binary=False):
"""
Load an arbitrary value identified by `key`.
:param str key: The key that identifies the value
:return: The loaded value
"""
with self.load_stream(key, binary=binary) as s:
return s.read() | [
"def",
"load_value",
"(",
"self",
",",
"key",
",",
"binary",
"=",
"False",
")",
":",
"with",
"self",
".",
"load_stream",
"(",
"key",
",",
"binary",
"=",
"binary",
")",
"as",
"s",
":",
"return",
"s",
".",
"read",
"(",
")"
] | 31.777778 | 11.555556 |
def convert(cls, obj, flatten=True):
"""
This function converts object into a Dict optionally Flattening it
:param obj: Object to be converted
:param flatten: boolean to specify if the dict has to be flattened
:return dict: the dict of the object (Flattened or Un-... | [
"def",
"convert",
"(",
"cls",
",",
"obj",
",",
"flatten",
"=",
"True",
")",
":",
"dict_result",
"=",
"cls",
".",
"object_to_dict",
"(",
"obj",
")",
"if",
"flatten",
":",
"dict_result",
"=",
"FlatDict",
"(",
"dict_result",
")",
"return",
"dict_result"
] | 43 | 15.363636 |
def path_get(p: tcod.path.AStar, idx: int) -> Tuple[int, int]:
"""Get a point on a path.
Args:
p (AStar): An AStar instance.
idx (int): Should be in range: 0 <= inx < :any:`path_size`
"""
x = ffi.new("int *")
y = ffi.new("int *")
lib.TCOD_path_get(p._path_c, idx, x, y)
retur... | [
"def",
"path_get",
"(",
"p",
":",
"tcod",
".",
"path",
".",
"AStar",
",",
"idx",
":",
"int",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"x",
"=",
"ffi",
".",
"new",
"(",
"\"int *\"",
")",
"y",
"=",
"ffi",
".",
"new",
"(",
"\"int *\... | 29.272727 | 16 |
def get_context_data(self, **kwargs):
"""Add context data to view"""
context = super().get_context_data(**kwargs)
context.update({
'title': self.title,
'submit_value': self.submit_value,
'cancel_url': self.get_cancel_url(),
'model_verbose_name': se... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"{",
"'title'",
":",
"self",
".",
"title",
",",
"'subm... | 34.909091 | 16 |
def unlock_kinetis_read_until_ack(jlink, address):
"""Polls the device until the request is acknowledged.
Sends a read request to the connected device to read the register at the
given 'address'. Polls indefinitely until either the request is ACK'd or
the request ends in a fault.
Args:
jlin... | [
"def",
"unlock_kinetis_read_until_ack",
"(",
"jlink",
",",
"address",
")",
":",
"request",
"=",
"swd",
".",
"ReadRequest",
"(",
"address",
",",
"ap",
"=",
"True",
")",
"response",
"=",
"None",
"while",
"True",
":",
"response",
"=",
"request",
".",
"send",
... | 31.15625 | 23.125 |
def is_unclaimed(work):
"""Returns True if work piece is unclaimed."""
if work['is_completed']:
return False
cutoff_time = time.time() - MAX_PROCESSING_TIME
if (work['claimed_worker_id'] and
work['claimed_worker_start_time'] is not None
and work['claimed_worker_start_time'] >= cutoff_time):
... | [
"def",
"is_unclaimed",
"(",
"work",
")",
":",
"if",
"work",
"[",
"'is_completed'",
"]",
":",
"return",
"False",
"cutoff_time",
"=",
"time",
".",
"time",
"(",
")",
"-",
"MAX_PROCESSING_TIME",
"if",
"(",
"work",
"[",
"'claimed_worker_id'",
"]",
"and",
"work"... | 33.7 | 15.1 |
def set_LObj(self,LObj=None):
""" Set the LObj attribute, storing objects the instance depends on
For example:
A Detect object depends on a vessel and some apertures
That link between should be stored somewhere (for saving/loading).
LObj does this: it stores the ID (as dict) of ... | [
"def",
"set_LObj",
"(",
"self",
",",
"LObj",
"=",
"None",
")",
":",
"self",
".",
"_LObj",
"=",
"{",
"}",
"if",
"LObj",
"is",
"not",
"None",
":",
"if",
"type",
"(",
"LObj",
")",
"is",
"not",
"list",
":",
"LObj",
"=",
"[",
"LObj",
"]",
"for",
"... | 40 | 19.333333 |
def do_alarm_definition_create(mc, args):
'''Create an alarm definition.'''
fields = {}
fields['name'] = args.name
if args.description:
fields['description'] = args.description
fields['expression'] = args.expression
if args.alarm_actions:
fields['alarm_actions'] = args.alarm_acti... | [
"def",
"do_alarm_definition_create",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"args",
".",
"description",
":",
"fields",
"[",
"'description'",
"]",
"=",
"args",
".",
"descr... | 37.4 | 14.6 |
def change_vartype(self, vartype, inplace=True):
"""Create a binary quadratic model with the specified vartype.
Args:
vartype (:class:`.Vartype`/str/set, optional):
Variable type for the changed model. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN... | [
"def",
"change_vartype",
"(",
"self",
",",
"vartype",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"not",
"inplace",
":",
"# create a new model of the appropriate type, then add self's biases to it",
"new_model",
"=",
"BinaryQuadraticModel",
"(",
"{",
"}",
",",
"{",
... | 39.815385 | 26.538462 |
def export(g, csv_fname):
""" export a graph to CSV for simpler viewing """
with open(csv_fname, "w") as f:
num_tuples = 0
f.write('"num","subject","predicate","object"\n')
for subj, pred, obj in g:
num_tuples += 1
f.write('"' + str(num_tuples) + '",')
... | [
"def",
"export",
"(",
"g",
",",
"csv_fname",
")",
":",
"with",
"open",
"(",
"csv_fname",
",",
"\"w\"",
")",
"as",
"f",
":",
"num_tuples",
"=",
"0",
"f",
".",
"write",
"(",
"'\"num\",\"subject\",\"predicate\",\"object\"\\n'",
")",
"for",
"subj",
",",
"pred"... | 44.5 | 13.083333 |
def register_function_hooks(self, func):
"""Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items():
for field_name, hook in hooks:
if field_name and field_name != self.state_field:
conti... | [
"def",
"register_function_hooks",
"(",
"self",
",",
"func",
")",
":",
"for",
"hook_kind",
",",
"hooks",
"in",
"func",
".",
"xworkflows_hook",
".",
"items",
"(",
")",
":",
"for",
"field_name",
",",
"hook",
"in",
"hooks",
":",
"if",
"field_name",
"and",
"f... | 54.4 | 12.6 |
def iter_segments(obj, neurite_filter=None, neurite_order=NeuriteIter.FileOrder):
'''Return an iterator to the segments in a collection of neurites
Parameters:
obj: neuron, population, neurite, section, or iterable containing neurite objects
neurite_filter: optional top level filter on properti... | [
"def",
"iter_segments",
"(",
"obj",
",",
"neurite_filter",
"=",
"None",
",",
"neurite_order",
"=",
"NeuriteIter",
".",
"FileOrder",
")",
":",
"sections",
"=",
"iter",
"(",
"(",
"obj",
",",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Section",
")",
"else",... | 52.454545 | 31.636364 |
def prepare(self, context, stream_id):
"""Invoke prepare() of this custom grouping"""
self.grouping.prepare(context, self.source_comp_name, stream_id, self.task_ids) | [
"def",
"prepare",
"(",
"self",
",",
"context",
",",
"stream_id",
")",
":",
"self",
".",
"grouping",
".",
"prepare",
"(",
"context",
",",
"self",
".",
"source_comp_name",
",",
"stream_id",
",",
"self",
".",
"task_ids",
")"
] | 57 | 15 |
def value_from_datadict(self, data, files, name):
"""
Given a dictionary of data and this widget's name, returns the value
of this widget. Returns None if it's not provided.
"""
value = super(FileSizeWidget, self).value_from_datadict(data, files, name)
if value not in EMP... | [
"def",
"value_from_datadict",
"(",
"self",
",",
"data",
",",
"files",
",",
"name",
")",
":",
"value",
"=",
"super",
"(",
"FileSizeWidget",
",",
"self",
")",
".",
"value_from_datadict",
"(",
"data",
",",
"files",
",",
"name",
")",
"if",
"value",
"not",
... | 37.5 | 15.166667 |
def wait_travel(self, character, thing, dest, cb=None):
"""Schedule a thing to travel someplace, then wait for it to finish, and call ``cb`` if provided
:param character: name of the character
:param thing: name of the thing
:param dest: name of the destination (a place)
:param ... | [
"def",
"wait_travel",
"(",
"self",
",",
"character",
",",
"thing",
",",
"dest",
",",
"cb",
"=",
"None",
")",
":",
"self",
".",
"wait_turns",
"(",
"self",
".",
"engine",
".",
"character",
"[",
"character",
"]",
".",
"thing",
"[",
"thing",
"]",
".",
... | 44.545455 | 17.363636 |
def run(self):
"""Run the App using the current profile.
The current profile has the install_json and args pre-loaded.
"""
install_json = self.profile.get('install_json')
program_language = self.profile.get('install_json').get('programLanguage', 'python').lower()
print(... | [
"def",
"run",
"(",
"self",
")",
":",
"install_json",
"=",
"self",
".",
"profile",
".",
"get",
"(",
"'install_json'",
")",
"program_language",
"=",
"self",
".",
"profile",
".",
"get",
"(",
"'install_json'",
")",
".",
"get",
"(",
"'programLanguage'",
",",
... | 38 | 25.888889 |
def close(self):
"""Close a port on dummy_serial."""
if VERBOSE:
_print_out('\nDummy_serial: Closing port\n')
if not self._isOpen:
raise IOError('Dummy_serial: The port is already closed')
self._isOpen = False
self.port = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'\\nDummy_serial: Closing port\\n'",
")",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"IOError",
"(",
"'Dummy_serial: The port is already closed'",
")",
"self",
".",
"_isOpen",... | 29.5 | 19.8 |
def _get_recurrence_model(input_model):
"""
Returns the annual and cumulative recurrence rates predicted by the
recurrence model
"""
if not isinstance(input_model, (TruncatedGRMFD,
EvenlyDiscretizedMFD,
YoungsCoppersmith1985MFD)... | [
"def",
"_get_recurrence_model",
"(",
"input_model",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_model",
",",
"(",
"TruncatedGRMFD",
",",
"EvenlyDiscretizedMFD",
",",
"YoungsCoppersmith1985MFD",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Recurrence model not rec... | 46.9375 | 15.5625 |
def find_notignored_git_files(self, context, silent_build):
"""
Return a list of files that are not ignored by git
"""
def git(args, error_message, cwd=context.parent_dir, **error_kwargs):
output, status = command_output("git {0}".format(args), cwd=cwd)
if status ... | [
"def",
"find_notignored_git_files",
"(",
"self",
",",
"context",
",",
"silent_build",
")",
":",
"def",
"git",
"(",
"args",
",",
"error_message",
",",
"cwd",
"=",
"context",
".",
"parent_dir",
",",
"*",
"*",
"error_kwargs",
")",
":",
"output",
",",
"status"... | 52.571429 | 31.673469 |
def update_version(self, service_id, version_number, **kwargs):
"""Update a particular version for a particular service."""
body = self._formdata(kwargs, FastlyVersion.FIELDS)
content = self._fetch("/service/%s/version/%d/" % (service_id, version_number), method="PUT", body=body)
return FastlyVersion(self, cont... | [
"def",
"update_version",
"(",
"self",
",",
"service_id",
",",
"version_number",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"self",
".",
"_formdata",
"(",
"kwargs",
",",
"FastlyVersion",
".",
"FIELDS",
")",
"content",
"=",
"self",
".",
"_fetch",
"(",... | 64 | 21 |
def do_translate(parser, token):
"""
This will mark a string for translation and will
translate the string for the current language.
Usage::
{% trans "this is a test" %}
This will mark the string for translation so it will
be pulled out by mark-messages.py into the .po files
and will... | [
"def",
"do_translate",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one argument\"",
"%",
"bits",
"[",
... | 40.320513 | 18.961538 |
def wait(timeout=None, flush=True):
"""Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`... | [
"def",
"wait",
"(",
"timeout",
"=",
"None",
",",
"flush",
"=",
"True",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"timeout",
"+",
"_time",
".",
"clock",
"(",
")",
"# timeout at this time",
"while",
"True",
":",
"if",
"_eventQu... | 36.074074 | 19.407407 |
def split_add_ops(text):
"""Specialized function splitting text at add/sub operators.
Operands are *not* translated. Example result ['op1', '+', 'op2', '-', 'op3']"""
n = 0
text = text.replace('++', '##').replace(
'--', '@@') #text does not normally contain any of these
spotted = False # s... | [
"def",
"split_add_ops",
"(",
"text",
")",
":",
"n",
"=",
"0",
"text",
"=",
"text",
".",
"replace",
"(",
"'++'",
",",
"'##'",
")",
".",
"replace",
"(",
"'--'",
",",
"'@@'",
")",
"#text does not normally contain any of these",
"spotted",
"=",
"False",
"# set... | 38 | 17.272727 |
def candidate_pair_priority(local, remote, ice_controlling):
"""
See RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
"""
G = ice_controlling and local.priority or remote.priority
D = ice_controlling and remote.priority or local.priority
return (1 << 32) * min(G, D) + 2 * max(G, D) +... | [
"def",
"candidate_pair_priority",
"(",
"local",
",",
"remote",
",",
"ice_controlling",
")",
":",
"G",
"=",
"ice_controlling",
"and",
"local",
".",
"priority",
"or",
"remote",
".",
"priority",
"D",
"=",
"ice_controlling",
"and",
"remote",
".",
"priority",
"or",... | 47.571429 | 17 |
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
... | [
"def",
"reciprocal_rank",
"(",
"truth",
",",
"recommend",
")",
":",
"for",
"n",
"in",
"range",
"(",
"recommend",
".",
"size",
")",
":",
"if",
"recommend",
"[",
"n",
"]",
"in",
"truth",
":",
"return",
"1.",
"/",
"(",
"n",
"+",
"1",
")",
"return",
... | 23.2 | 19.666667 |
def serialize(cls, installation):
"""
:type installation: core.Installation
:rtype: list
"""
return [
{cls._FIELD_ID: converter.serialize(installation.id_)},
{cls._FIELD_TOKEN: converter.serialize(installation.token)},
{
cls._... | [
"def",
"serialize",
"(",
"cls",
",",
"installation",
")",
":",
"return",
"[",
"{",
"cls",
".",
"_FIELD_ID",
":",
"converter",
".",
"serialize",
"(",
"installation",
".",
"id_",
")",
"}",
",",
"{",
"cls",
".",
"_FIELD_TOKEN",
":",
"converter",
".",
"ser... | 27.8125 | 21.0625 |
def crypto_hash_sha512(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = ffi.new("unsigned char[]", crypto_hash_sha512_BYTES)
rc = lib.crypto_hash_sha512(digest, message, len(message))
ensure(rc == 0,
'Unexpected librar... | [
"def",
"crypto_hash_sha512",
"(",
"message",
")",
":",
"digest",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_hash_sha512_BYTES",
")",
"rc",
"=",
"lib",
".",
"crypto_hash_sha512",
"(",
"digest",
",",
"message",
",",
"len",
"(",
"message",
... | 31.769231 | 14.230769 |
def use_active_composition_view(self):
"""Pass through to provider CompositionLookupSession.use_active_composition_view"""
self._operable_views['composition'] = ACTIVE
# self._get_provider_session('composition_lookup_session') # To make sure the session is tracked
for session in self._g... | [
"def",
"use_active_composition_view",
"(",
"self",
")",
":",
"self",
".",
"_operable_views",
"[",
"'composition'",
"]",
"=",
"ACTIVE",
"# self._get_provider_session('composition_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_g... | 51.333333 | 17.222222 |
def disable(self):
"""Disable a NApp if it is enabled."""
core_napps_manager = CoreNAppsManager(base_path=self._enabled)
core_napps_manager.disable(self.user, self.napp) | [
"def",
"disable",
"(",
"self",
")",
":",
"core_napps_manager",
"=",
"CoreNAppsManager",
"(",
"base_path",
"=",
"self",
".",
"_enabled",
")",
"core_napps_manager",
".",
"disable",
"(",
"self",
".",
"user",
",",
"self",
".",
"napp",
")"
] | 47.5 | 17 |
def domain_name(self, domain_name):
"""
Sets the domain_name of this RegisterDomainRequest.
A domain name as described in RFC-1034 that will be registered with ApplePay
:param domain_name: The domain_name of this RegisterDomainRequest.
:type: str
"""
if domain_n... | [
"def",
"domain_name",
"(",
"self",
",",
"domain_name",
")",
":",
"if",
"domain_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `domain_name`, must not be `None`\"",
")",
"if",
"len",
"(",
"domain_name",
")",
">",
"255",
":",
"raise",
"... | 42 | 25.529412 |
def index_of(self, data):
"""
Finds the position of a node in the list. The index of the first
occurrence of the data is returned (indexes start at 0)
:param data: data of the seeked node
:type: object
:returns: the int index or -1 if the node is not in the list
... | [
"def",
"index_of",
"(",
"self",
",",
"data",
")",
":",
"current_node",
"=",
"self",
".",
"_first_node",
"pos",
"=",
"0",
"while",
"current_node",
":",
"if",
"current_node",
".",
"data",
"(",
")",
"==",
"data",
":",
"return",
"pos",
"else",
":",
"curren... | 30.157895 | 17.315789 |
def past_trades(self, timestamp=0, symbol='btcusd'):
"""
Fetch past trades
:param timestamp:
:param symbol:
:return:
"""
payload = {
"request": "/v1/mytrades",
"nonce": self._nonce,
"symbol": symbol,
"timestamp": tim... | [
"def",
"past_trades",
"(",
"self",
",",
"timestamp",
"=",
"0",
",",
"symbol",
"=",
"'btcusd'",
")",
":",
"payload",
"=",
"{",
"\"request\"",
":",
"\"/v1/mytrades\"",
",",
"\"nonce\"",
":",
"self",
".",
"_nonce",
",",
"\"symbol\"",
":",
"symbol",
",",
"\"... | 27.052632 | 17.263158 |
def indent(self):
"""
Indents text at cursor position.
"""
cursor = self.editor.textCursor()
assert isinstance(cursor, QtGui.QTextCursor)
if cursor.hasSelection():
self.indent_selection(cursor)
else:
# simply insert indentation at the curso... | [
"def",
"indent",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
"assert",
"isinstance",
"(",
"cursor",
",",
"QtGui",
".",
"QTextCursor",
")",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"self",
".",
... | 37.611111 | 11.166667 |
def _concatenate_spike_clusters(*pairs):
"""Concatenate a list of pairs (spike_ids, spike_clusters)."""
pairs = [(_as_array(x), _as_array(y)) for (x, y) in pairs]
concat = np.vstack(np.hstack((x[:, None], y[:, None]))
for x, y in pairs)
reorder = np.argsort(concat[:, 0])
conca... | [
"def",
"_concatenate_spike_clusters",
"(",
"*",
"pairs",
")",
":",
"pairs",
"=",
"[",
"(",
"_as_array",
"(",
"x",
")",
",",
"_as_array",
"(",
"y",
")",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"pairs",
"]",
"concat",
"=",
"np",
".",
"vstack",
"... | 50.875 | 10.375 |
def app_template_global(self, name: Optional[str]=None) -> Callable:
"""Add an application wide template global.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.template_global`. An example usage,
.. code-block:: python
bluepri... | [
"def",
"app_template_global",
"(",
"self",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"add_app_template_global",
"(",
... | 34.941176 | 18.823529 |
def access_array(self, id_, lineno, scope=None, default_type=None):
"""
Called whenever an accessed variable is expected to be an array.
ZX BASIC requires arrays to be declared before usage, so they're
checked.
Also checks for class array.
"""
if not self.check_i... | [
"def",
"access_array",
"(",
"self",
",",
"id_",
",",
"lineno",
",",
"scope",
"=",
"None",
",",
"default_type",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"check_is_declared",
"(",
"id_",
",",
"lineno",
",",
"'array'",
",",
"scope",
")",
":",
"r... | 36.333333 | 24.466667 |
def mk_req(self, url, **kwargs):
"""
Helper function to create a tornado HTTPRequest object, kwargs get passed in to
create the HTTPRequest object. See:
http://tornado.readthedocs.org/en/latest/httpclient.html#request-objects
"""
req_url = self.base_url + url
req_... | [
"def",
"mk_req",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"req_url",
"=",
"self",
".",
"base_url",
"+",
"url",
"req_kwargs",
"=",
"kwargs",
"req_kwargs",
"[",
"'ca_certs'",
"]",
"=",
"req_kwargs",
".",
"get",
"(",
"'ca_certs'",
",",
... | 42.4375 | 16.1875 |
def get_field_definition(node):
""""node is a class attribute that is a mongoengine. Returns
the definition statement for the attribute
"""
name = node.attrname
cls = get_node_parent_class(node)
definition = cls.lookup(name)[1][0].statement()
return definition | [
"def",
"get_field_definition",
"(",
"node",
")",
":",
"name",
"=",
"node",
".",
"attrname",
"cls",
"=",
"get_node_parent_class",
"(",
"node",
")",
"definition",
"=",
"cls",
".",
"lookup",
"(",
"name",
")",
"[",
"1",
"]",
"[",
"0",
"]",
".",
"statement"... | 31.333333 | 11.666667 |
def restore_instances(self, instances):
"""Restore a set of instances into the CLIPS data base.
The Python equivalent of the CLIPS restore-instances command.
Instances can be passed as a set of strings or as a file.
"""
instances = instances.encode()
if os.path.exists... | [
"def",
"restore_instances",
"(",
"self",
",",
"instances",
")",
":",
"instances",
"=",
"instances",
".",
"encode",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"instances",
")",
":",
"ret",
"=",
"lib",
".",
"EnvRestoreInstances",
"(",
"self",
... | 31.45 | 20.25 |
def paint( self, painter, option, widget ):
"""
Draws this item with the inputed painter.
:param painter | <QPainter>
rect | <QRect>
"""
if self._dirty:
self.rebuild()
scene = self.scene()
if n... | [
"def",
"paint",
"(",
"self",
",",
"painter",
",",
"option",
",",
"widget",
")",
":",
"if",
"self",
".",
"_dirty",
":",
"self",
".",
"rebuild",
"(",
")",
"scene",
"=",
"self",
".",
"scene",
"(",
")",
"if",
"not",
"scene",
":",
"return",
"grid",
"=... | 35.067797 | 13.915254 |
def from_name(cls, name):
"""Retrieve datacenter id associated to a name."""
result = cls.list()
dc_names = {}
for dc in result:
dc_names[dc['name']] = dc['id']
return dc_names.get(name) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
")",
"dc_names",
"=",
"{",
"}",
"for",
"dc",
"in",
"result",
":",
"dc_names",
"[",
"dc",
"[",
"'name'",
"]",
"]",
"=",
"dc",
"[",
"'id'",
"]",
"retur... | 29 | 14 |
def BuildServiceStub(self, cls):
"""Constructs the stub class.
Args:
cls: The class that will be constructed.
"""
def _ServiceStubInit(stub, rpc_channel):
stub.rpc_channel = rpc_channel
self.cls = cls
cls.__init__ = _ServiceStubInit
for method in self.descriptor.methods:
... | [
"def",
"BuildServiceStub",
"(",
"self",
",",
"cls",
")",
":",
"def",
"_ServiceStubInit",
"(",
"stub",
",",
"rpc_channel",
")",
":",
"stub",
".",
"rpc_channel",
"=",
"rpc_channel",
"self",
".",
"cls",
"=",
"cls",
"cls",
".",
"__init__",
"=",
"_ServiceStubIn... | 28.230769 | 14.384615 |
def get_optional_attribute(self, element, attribute):
"""Attempt to retrieve an optional attribute from the xml and return None on failure."""
try:
return self.get_attribute(element, attribute)
except self.XmlError:
return None | [
"def",
"get_optional_attribute",
"(",
"self",
",",
"element",
",",
"attribute",
")",
":",
"try",
":",
"return",
"self",
".",
"get_attribute",
"(",
"element",
",",
"attribute",
")",
"except",
"self",
".",
"XmlError",
":",
"return",
"None"
] | 41 | 15.666667 |
def get(self, namespacePrefix):
"""Get a specific configuration namespace"""
ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix)
if not ns:
return self.make_response('No such namespace: {}'.format(namespacePrefix), HTTP.NOT_FOUND)
return sel... | [
"def",
"get",
"(",
"self",
",",
"namespacePrefix",
")",
":",
"ns",
"=",
"db",
".",
"ConfigNamespace",
".",
"find_one",
"(",
"ConfigNamespace",
".",
"namespace_prefix",
"==",
"namespacePrefix",
")",
"if",
"not",
"ns",
":",
"return",
"self",
".",
"make_respons... | 39.6 | 24.6 |
def network_xml(identifier, xml, address=None):
"""Fills the XML file with the required fields.
* name
* uuid
* bridge
* ip
** dhcp
"""
netname = identifier[:8]
network = etree.fromstring(xml)
subelement(network, './/name', 'name', identifier)
subelement(network, './/... | [
"def",
"network_xml",
"(",
"identifier",
",",
"xml",
",",
"address",
"=",
"None",
")",
":",
"netname",
"=",
"identifier",
"[",
":",
"8",
"]",
"network",
"=",
"etree",
".",
"fromstring",
"(",
"xml",
")",
"subelement",
"(",
"network",
",",
"'.//name'",
"... | 25 | 21.952381 |
def buckets(bucket=None, account=None, matched=False, kdenied=False,
errors=False, dbpath=None, size=None, denied=False,
format=None, incomplete=False, oversize=False, region=(),
not_region=(), inventory=None, output=None, config=None, sort=None,
tagprefix=None, not_bucke... | [
"def",
"buckets",
"(",
"bucket",
"=",
"None",
",",
"account",
"=",
"None",
",",
"matched",
"=",
"False",
",",
"kdenied",
"=",
"False",
",",
"errors",
"=",
"False",
",",
"dbpath",
"=",
"None",
",",
"size",
"=",
"None",
",",
"denied",
"=",
"False",
"... | 34.966102 | 16.542373 |
def backtrace_on_usr1 ():
"""Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python ... | [
"def",
"backtrace_on_usr1",
"(",
")",
":",
"import",
"signal",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR1",
",",
"_print_backtrace_signal_handler",
")",
"except",
"Exception",
"as",
"e",
":",
"warn",
"(",
"'failed to set up Python backtraces... | 47.277778 | 26.111111 |
def work(self, actions_queue, returns_queue, control_queue=None): # pragma: no cover
"""Wrapper function for do_work in order to catch the exception
to see the real work, look at do_work
:param actions_queue: Global Queue Master->Slave
:type actions_queue: Queue.Queue
:param re... | [
"def",
"work",
"(",
"self",
",",
"actions_queue",
",",
"returns_queue",
",",
"control_queue",
"=",
"None",
")",
":",
"# pragma: no cover",
"try",
":",
"logger",
".",
"info",
"(",
"\"[%s] (pid=%d) starting my job...\"",
",",
"self",
".",
"_id",
",",
"os",
".",
... | 49.086957 | 22.304348 |
def data(self, where, start, end, archiver="", timeout=DEFAULT_TIMEOUT):
"""
With the given WHERE clause, retrieves all RAW data between the 2 given timestamps
Arguments:
[where]: the where clause (e.g. 'path like "keti"', 'SourceName = "TED Main"')
[start, end]: time references... | [
"def",
"data",
"(",
"self",
",",
"where",
",",
"start",
",",
"end",
",",
"archiver",
"=",
"\"\"",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"return",
"self",
".",
"query",
"(",
"\"select data in ({0}, {1}) where {2}\"",
".",
"format",
"(",
"start",
... | 57.916667 | 33.416667 |
def local(tool, slug, config_loader, offline=False):
"""
Create/update local copy of github.com/org/repo/branch.
Returns path to local copy
"""
# Parse slug
slug = Slug(slug, offline=offline)
local_path = Path(LOCAL_PATH).expanduser() / slug.org / slug.repo
git = Git(f"-C {shlex.quote(... | [
"def",
"local",
"(",
"tool",
",",
"slug",
",",
"config_loader",
",",
"offline",
"=",
"False",
")",
":",
"# Parse slug",
"slug",
"=",
"Slug",
"(",
"slug",
",",
"offline",
"=",
"offline",
")",
"local_path",
"=",
"Path",
"(",
"LOCAL_PATH",
")",
".",
"expa... | 35.275 | 22.475 |
def save(self, *args):
""" Save cache to file using pickle.
Parameters
----------
*args:
All but the last argument are inputs to the cached function. The
last is the actual value of the function.
"""
with open(self.file_root + '.pkl', "wb") as f:
... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
")",
":",
"with",
"open",
"(",
"self",
".",
"file_root",
"+",
"'.pkl'",
",",
"\"wb\"",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"args",
",",
"f",
",",
"protocol",
"=",
"pickle",
".",
"HIGHEST_... | 34.181818 | 19.727273 |
def _detach(self, item):
"""Hide items from treeview that do not match the search string."""
to_detach = []
children_det = []
children_match = False
match_found = False
value = self.filtervar.get()
txt = self.treeview.item(item, 'text').lower()
if value i... | [
"def",
"_detach",
"(",
"self",
",",
"item",
")",
":",
"to_detach",
"=",
"[",
"]",
"children_det",
"=",
"[",
"]",
"children_match",
"=",
"False",
"match_found",
"=",
"False",
"value",
"=",
"self",
".",
"filtervar",
".",
"get",
"(",
")",
"txt",
"=",
"s... | 33.405405 | 14.189189 |
def ssn(self, min_age=18, max_age=90):
"""
Returns a 10 digit Swedish SSN, "Personnummer".
It consists of 10 digits in the form YYMMDD-SSGQ, where
YYMMDD is the date of birth, SSS is a serial number
and Q is a control character (Luhn checksum).
http://en.wikipedia.org/w... | [
"def",
"ssn",
"(",
"self",
",",
"min_age",
"=",
"18",
",",
"max_age",
"=",
"90",
")",
":",
"def",
"_luhn_checksum",
"(",
"number",
")",
":",
"def",
"digits_of",
"(",
"n",
")",
":",
"return",
"[",
"int",
"(",
"d",
")",
"for",
"d",
"in",
"str",
"... | 39.142857 | 16.914286 |
def get_field_type(f):
"""Obtain the type name of a GRPC Message field."""
types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and
getattr(f, t) == f.type)
return next(types) | [
"def",
"get_field_type",
"(",
"f",
")",
":",
"types",
"=",
"(",
"t",
"[",
"5",
":",
"]",
"for",
"t",
"in",
"dir",
"(",
"f",
")",
"if",
"t",
"[",
":",
"4",
"]",
"==",
"'TYPE'",
"and",
"getattr",
"(",
"f",
",",
"t",
")",
"==",
"f",
".",
"ty... | 38.6 | 11.2 |
def module_ids(self, rev=False):
"""Gets a list of module ids guaranteed to be sorted by run_order, ignoring conn modules
(run order < 0).
"""
shutit_global.shutit_global_object.yield_to_draw()
ids = sorted(list(self.shutit_map.keys()),key=lambda module_id: self.shutit_map[module_id].run_order)
if rev:
r... | [
"def",
"module_ids",
"(",
"self",
",",
"rev",
"=",
"False",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"ids",
"=",
"sorted",
"(",
"list",
"(",
"self",
".",
"shutit_map",
".",
"keys",
"(",
")",
")",
",",
"key... | 38.888889 | 19.444444 |
def generate(self, text):
"""Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l].
:param text: The text used to generate image.
"""
sizes = current_app.config['AVATARS_SIZE_TUPLE']
path = current_app.config['AVATARS_SAVE_PATH']
suf... | [
"def",
"generate",
"(",
"self",
",",
"text",
")",
":",
"sizes",
"=",
"current_app",
".",
"config",
"[",
"'AVATARS_SIZE_TUPLE'",
"]",
"path",
"=",
"current_app",
".",
"config",
"[",
"'AVATARS_SAVE_PATH'",
"]",
"suffix",
"=",
"{",
"sizes",
"[",
"0",
"]",
"... | 43.823529 | 17.705882 |
def paga_adjacency(
adata,
adjacency='connectivities',
adjacency_tree='connectivities_tree',
as_heatmap=True,
color_map=None,
show=None,
save=None):
"""Connectivity of paga groups.
"""
connectivity = adata.uns[adjacency].toarray()
connectivity_sele... | [
"def",
"paga_adjacency",
"(",
"adata",
",",
"adjacency",
"=",
"'connectivities'",
",",
"adjacency_tree",
"=",
"'connectivities_tree'",
",",
"as_heatmap",
"=",
"True",
",",
"color_map",
"=",
"None",
",",
"show",
"=",
"None",
",",
"save",
"=",
"None",
")",
":"... | 38.821429 | 16.035714 |
def create_db_entry(self, comment=''):
"""Create a db entry for this task file info
and link it with a optional comment
:param comment: a comment for the task file entry
:type comment: str
:returns: The created TaskFile django instance and the comment. If the comment was empty, ... | [
"def",
"create_db_entry",
"(",
"self",
",",
"comment",
"=",
"''",
")",
":",
"jbfile",
"=",
"JB_File",
"(",
"self",
")",
"p",
"=",
"jbfile",
".",
"get_fullpath",
"(",
")",
"user",
"=",
"dj",
".",
"get_current_user",
"(",
")",
"tf",
"=",
"dj",
".",
"... | 43.785714 | 22.821429 |
def normalize_topic(topic):
"""
Get a canonical representation of a Wikipedia topic, which may include
a disambiguation string in parentheses.
Returns (name, disambig), where "name" is the normalized topic name,
and "disambig" is a string corresponding to the disambiguation text or
None.
""... | [
"def",
"normalize_topic",
"(",
"topic",
")",
":",
"# find titles of the form Foo (bar)",
"topic",
"=",
"topic",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
"match",
"=",
"re",
".",
"match",
"(",
"r'([^(]+) \\(([^)]+)\\)'",
",",
"topic",
")",
"if",
"not",
"m... | 36 | 18.5 |
def get_list_continuous_queries(self):
"""Get the list of continuous queries in InfluxDB.
:return: all CQs in InfluxDB
:rtype: list of dictionaries
:Example:
::
>> cqs = client.get_list_cqs()
>> cqs
[
{
u... | [
"def",
"get_list_continuous_queries",
"(",
"self",
")",
":",
"query_string",
"=",
"\"SHOW CONTINUOUS QUERIES\"",
"return",
"[",
"{",
"sk",
"[",
"0",
"]",
":",
"list",
"(",
"p",
")",
"}",
"for",
"sk",
",",
"p",
"in",
"self",
".",
"query",
"(",
"query_stri... | 31.322581 | 21.354839 |
def statuscategories(self):
"""Get a list of status category Resources from the server.
:rtype: List[StatusCategory]
"""
r_json = self._get_json('statuscategory')
statuscategories = [StatusCategory(self._options, self._session, raw_stat_json)
for raw_... | [
"def",
"statuscategories",
"(",
"self",
")",
":",
"r_json",
"=",
"self",
".",
"_get_json",
"(",
"'statuscategory'",
")",
"statuscategories",
"=",
"[",
"StatusCategory",
"(",
"self",
".",
"_options",
",",
"self",
".",
"_session",
",",
"raw_stat_json",
")",
"f... | 40.444444 | 15.333333 |
def Pareto2(q, b, tag=None):
"""
A Pareto random variate (second kind). This form always starts at the
origin.
Parameters
----------
q : scalar
The scale parameter
b : scalar
The shape parameter
"""
assert q > 0 and b > 0, 'Pareto2 "q" and "b" must be positive sc... | [
"def",
"Pareto2",
"(",
"q",
",",
"b",
",",
"tag",
"=",
"None",
")",
":",
"assert",
"q",
">",
"0",
"and",
"b",
">",
"0",
",",
"'Pareto2 \"q\" and \"b\" must be positive scalars'",
"return",
"Pareto",
"(",
"q",
",",
"b",
",",
"tag",
")",
"-",
"b"
] | 24.714286 | 20.142857 |
def get_checkcode(cls, id_number_str):
"""
计算身份证号码的校验位;
:param:
* id_number_str: (string) 身份证号的前17位,比如 3201241987010100
:returns:
* 返回类型 (tuple)
* flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False
* checkcode: 计算身份证前17位的校验码
举例如下::
... | [
"def",
"get_checkcode",
"(",
"cls",
",",
"id_number_str",
")",
":",
"# 判断长度,如果不是 17 位,直接返回失败",
"if",
"len",
"(",
"id_number_str",
")",
"!=",
"17",
":",
"return",
"False",
",",
"-",
"1",
"id_regex",
"=",
"'[1-9][0-9]{14}([0-9]{2}[0-9X])?'",
"if",
"not",
"re",
"... | 24.322034 | 22.694915 |
def exists_alias(self, index=None, name=None, params=None):
"""
Return a boolean indicating whether given alias exists.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names to filter aliases
:a... | [
"def",
"exists_alias",
"(",
"self",
",",
"index",
"=",
"None",
",",
"name",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"HEAD\"",
",",
"_make_path",
"(",
"index",
",",
"\"_alias\""... | 55.619048 | 25.142857 |
def from_csv(self, csv_source, delimiter=","):
"""
Set tabular attributes to the writer from a character-separated values (CSV) data source.
Following attributes are set to the writer by the method:
- :py:attr:`~.headers`.
- :py:attr:`~.value_matrix`.
:py:attr:`~.table_... | [
"def",
"from_csv",
"(",
"self",
",",
"csv_source",
",",
"delimiter",
"=",
"\",\"",
")",
":",
"import",
"pytablereader",
"as",
"ptr",
"loader",
"=",
"ptr",
".",
"CsvTableTextLoader",
"(",
"csv_source",
",",
"quoting_flags",
"=",
"self",
".",
"_quoting_flags",
... | 34.864865 | 23.081081 |
def mod(value, arg):
"""Return the modulo value."""
try:
return valid_numeric(value) % valid_numeric(arg)
except (ValueError, TypeError):
try:
return value % arg
except Exception:
return '' | [
"def",
"mod",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"return",
"valid_numeric",
"(",
"value",
")",
"%",
"valid_numeric",
"(",
"arg",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"try",
":",
"return",
"value",
"%",
"arg",
"ex... | 26.777778 | 16.111111 |
def normalize_reference_name(name):
"""
Search the dictionary of species-specific references to find a reference
name that matches aside from capitalization.
If no matching reference is found, raise an exception.
"""
lower_name = name.strip().lower()
for reference in Species._reference_name... | [
"def",
"normalize_reference_name",
"(",
"name",
")",
":",
"lower_name",
"=",
"name",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"reference",
"in",
"Species",
".",
"_reference_names_to_species",
".",
"keys",
"(",
")",
":",
"if",
"reference",
"."... | 38.75 | 14.25 |
def gen_secret(length=64):
""" Generates a secret of given length
"""
charset = string.ascii_letters + string.digits
return ''.join(random.SystemRandom().choice(charset)
for _ in range(length)) | [
"def",
"gen_secret",
"(",
"length",
"=",
"64",
")",
":",
"charset",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"charset",
")",
"for",... | 37.166667 | 7 |
def click_button(self, index_or_name):
""" Click button """
_platform_class_dict = {'ios': 'UIAButton',
'android': 'android.widget.Button'}
if self._is_support_platform(_platform_class_dict):
class_name = self._get_class(_platform_class_dict)
... | [
"def",
"click_button",
"(",
"self",
",",
"index_or_name",
")",
":",
"_platform_class_dict",
"=",
"{",
"'ios'",
":",
"'UIAButton'",
",",
"'android'",
":",
"'android.widget.Button'",
"}",
"if",
"self",
".",
"_is_support_platform",
"(",
"_platform_class_dict",
")",
"... | 54.714286 | 16.571429 |
def get_fba_flux(self, objective):
"""Return a dictionary of all the fluxes solved by FBA.
Dictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma`
to minimize changes in the flux distributions following model
perturbation.
Args:
objective: The objective ... | [
"def",
"get_fba_flux",
"(",
"self",
",",
"objective",
")",
":",
"flux_result",
"=",
"self",
".",
"solve_fba",
"(",
"objective",
")",
"fba_fluxes",
"=",
"{",
"}",
"# Place all the flux values in a dictionary",
"for",
"key",
"in",
"self",
".",
"_model",
".",
"re... | 34.25 | 21.35 |
def register_suite():
"""
Call this method in a module containing a test suite. The stack trace from
which call descriptor hashes are derived will be truncated at this module.
"""
global test_suite
frm = inspect.stack()[1]
test_suite = ".".join(os.path.basename(frm[1]).split('.')[0:-1]) | [
"def",
"register_suite",
"(",
")",
":",
"global",
"test_suite",
"frm",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"test_suite",
"=",
"\".\"",
".",
"join",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"frm",
"[",
"1",
"]",
")",
".",
"... | 34.222222 | 21.555556 |
def get_config(repo_root):
"""Gets the configuration file either from the repository or the default."""
config = os.path.join(os.path.dirname(__file__), 'configs', 'config.yaml')
if repo_root:
repo_config = os.path.join(repo_root, '.gitlint.yaml')
if os.path.exists(repo_config):
... | [
"def",
"get_config",
"(",
"repo_root",
")",
":",
"config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'configs'",
",",
"'config.yaml'",
")",
"if",
"repo_root",
":",
"repo_config",
"=",
"os",... | 35.6 | 20.7 |
def initialize_fields(self, content):
""" Initializes the :class:`Field` elements in the `Array` with the
*values* in the *content* list.
If the *content* list is shorter than the `Array` then the *content*
list is used as a rotating fill pattern for the :class:`Field` elements
... | [
"def",
"initialize_fields",
"(",
"self",
",",
"content",
")",
":",
"if",
"isinstance",
"(",
"content",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"capacity",
"=",
"len",
"(",
"content",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",... | 41.657895 | 14.868421 |
def build(template_directories):
"""
Build a template from the source template directories.
:param template_directories: source template directories
:return: template workflow
"""
template = load_template(template_directories[0])
for directory in template_directories[1:]:
template.u... | [
"def",
"build",
"(",
"template_directories",
")",
":",
"template",
"=",
"load_template",
"(",
"template_directories",
"[",
"0",
"]",
")",
"for",
"directory",
"in",
"template_directories",
"[",
"1",
":",
"]",
":",
"template",
".",
"update",
"(",
"load_template"... | 32.818182 | 13.181818 |
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
output = E... | [
"def",
"logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_index",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"logical_chassis_fwdl_status",
"=",
"ET",
".",
"Element",
"(",
"\"logical_... | 49.642857 | 19.857143 |
def create(cls, name, engines, include_core_files=False,
include_slapcat_output=False, comment=None):
"""
Create an sginfo task.
:param str name: name of task
:param engines: list of engines to apply the sginfo task
:type engines: list(Engine)
:pa... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"engines",
",",
"include_core_files",
"=",
"False",
",",
"include_slapcat_output",
"=",
"False",
",",
"comment",
"=",
"None",
")",
":",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'comment'",
":",
"commen... | 39.68 | 14.64 |
def camera_list(self, **kwargs):
"""Return a list of cameras."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'List',
'version': api['version'],
}, **kwargs)
response = self._get_j... | [
"def",
"camera_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"_api_info",
"[",
"'camera'",
"]",
"payload",
"=",
"dict",
"(",
"{",
"'_sid'",
":",
"self",
".",
"_sid",
",",
"'api'",
":",
"api",
"[",
"'name'",
"]",
... | 29.411765 | 17.235294 |
def patch_cmdline_parser():
"""
Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`.
"""
# store original functions
_init = luigi.cmdline_parser.CmdlineParser.__init__
# patch init
def ... | [
"def",
"patch_cmdline_parser",
"(",
")",
":",
"# store original functions",
"_init",
"=",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"__init__",
"# patch init",
"def",
"__init__",
"(",
"self",
",",
"cmdline_args",
")",
":",
"_init",
"(",
"self",
... | 33.642857 | 17.928571 |
def ndvi(self):
""" Normalized difference vegetation index.
:return: NDVI
"""
red, nir = self.reflectance(3), self.reflectance(4)
ndvi = self._divide_zero((nir - red), (nir + red), nan)
return ndvi | [
"def",
"ndvi",
"(",
"self",
")",
":",
"red",
",",
"nir",
"=",
"self",
".",
"reflectance",
"(",
"3",
")",
",",
"self",
".",
"reflectance",
"(",
"4",
")",
"ndvi",
"=",
"self",
".",
"_divide_zero",
"(",
"(",
"nir",
"-",
"red",
")",
",",
"(",
"nir"... | 29.875 | 18.375 |
def disbatch(self):
'''
Disbatch all lowstates to the appropriate clients
'''
ret = []
# check clients before going, we want to throw 400 if one is bad
for low in self.lowstate:
if not self._verify_client(low):
return
# Make sure ... | [
"def",
"disbatch",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"# check clients before going, we want to throw 400 if one is bad",
"for",
"low",
"in",
"self",
".",
"lowstate",
":",
"if",
"not",
"self",
".",
"_verify_client",
"(",
"low",
")",
":",
"return",
"#... | 39.828571 | 24.228571 |
def show_image(self, name):
"""Show image (item is a PIL image)"""
command = "%s.show()" % name
sw = self.shellwidget
if sw._reading:
sw.kernel_client.input(command)
else:
sw.execute(command) | [
"def",
"show_image",
"(",
"self",
",",
"name",
")",
":",
"command",
"=",
"\"%s.show()\"",
"%",
"name",
"sw",
"=",
"self",
".",
"shellwidget",
"if",
"sw",
".",
"_reading",
":",
"sw",
".",
"kernel_client",
".",
"input",
"(",
"command",
")",
"else",
":",
... | 31.875 | 10 |
def decrypt(self, data, decode=False):
""" Decrypt the given data with cipher that is got from AES.cipher call.
:param data: data to decrypt
:param decode: whether to decode bytes to str or not
:return: bytes or str (depends on decode flag)
"""
#result = self.cipher().decrypt(data)
result = self.cipher(... | [
"def",
"decrypt",
"(",
"self",
",",
"data",
",",
"decode",
"=",
"False",
")",
":",
"#result = self.cipher().decrypt(data)",
"result",
"=",
"self",
".",
"cipher",
"(",
")",
".",
"decrypt_block",
"(",
"data",
")",
"padding",
"=",
"self",
".",
"mode",
"(",
... | 31.8125 | 16.25 |
def disconnect(self):
"""Disconnect from the server."""
# here we just request the disconnection
# later in _handle_eio_disconnect we invoke the disconnect handler
for n in self.namespaces:
self._send_packet(packet.Packet(packet.DISCONNECT, namespace=n))
self._send_pa... | [
"def",
"disconnect",
"(",
"self",
")",
":",
"# here we just request the disconnection",
"# later in _handle_eio_disconnect we invoke the disconnect handler",
"for",
"n",
"in",
"self",
".",
"namespaces",
":",
"self",
".",
"_send_packet",
"(",
"packet",
".",
"Packet",
"(",
... | 46.444444 | 12.333333 |
def read_json(file_or_path):
"""Parse json contents of string or file object or file path and return python nested dict/lists"""
try:
with (open(file_or_path, 'r') if isinstance(file_or_path, (str, bytes)) else file_or_path) as f:
obj = json.load(f)
except IOError:
obj = json.loa... | [
"def",
"read_json",
"(",
"file_or_path",
")",
":",
"try",
":",
"with",
"(",
"open",
"(",
"file_or_path",
",",
"'r'",
")",
"if",
"isinstance",
"(",
"file_or_path",
",",
"(",
"str",
",",
"bytes",
")",
")",
"else",
"file_or_path",
")",
"as",
"f",
":",
"... | 43 | 20.875 |
def _xray_clean_up_entries_for_driver(self, driver_id):
"""Remove this driver's object/task entries from redis.
Removes control-state entries of all tasks and task return
objects belonging to the driver.
Args:
driver_id: The driver id.
"""
xray_task_table_p... | [
"def",
"_xray_clean_up_entries_for_driver",
"(",
"self",
",",
"driver_id",
")",
":",
"xray_task_table_prefix",
"=",
"(",
"ray",
".",
"gcs_utils",
".",
"TablePrefix_RAYLET_TASK_string",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"xray_object_table_prefix",
"=",
"(",
... | 44.063492 | 17.68254 |
def read_causal_pairs(filename, scale=True, **kwargs):
"""Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray.
:param filename: path of the file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param scale: Scale the data
:type scale: bool
... | [
"def",
"read_causal_pairs",
"(",
"filename",
",",
"scale",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"convert_row",
"(",
"row",
",",
"scale",
")",
":",
"\"\"\"Convert a CCEPC row into numpy.ndarrays.\n\n :param row:\n :type row: pandas.Series\n ... | 31.458333 | 16.583333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.