text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def remove_job_resolver(self, job_resolver):
"""Remove job_resolver from the list of job resolvers.
Keyword arguments:
job_resolver -- Function reference of the job resolver to be removed.
"""
for i, r in enumerate(self.job_resolvers()):
if job_resolver == r:
... | [
"def",
"remove_job_resolver",
"(",
"self",
",",
"job_resolver",
")",
":",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"self",
".",
"job_resolvers",
"(",
")",
")",
":",
"if",
"job_resolver",
"==",
"r",
":",
"del",
"self",
".",
"_job_resolvers",
"[",
"... | 38.555556 | 12.888889 |
def sum(self, array, role = None):
"""
Return the sum of ``array`` for the members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
... | [
"def",
"sum",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"self",
".",
"entity",
".",
"check_role_validity",
"(",
"role",
")",
"self",
".",
"members",
".",
"check_array_compatible_with_entity",
"(",
"array",
")",
"if",
"role",
"is",
"n... | 39.125 | 22.125 |
def assign_properties(thing):
"""Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table.
"""
for p in rang... | [
"def",
"assign_properties",
"(",
"thing",
")",
":",
"for",
"p",
"in",
"range",
"(",
"5",
")",
":",
"property_name",
"=",
"\"property\"",
"+",
"str",
"(",
"p",
"+",
"1",
")",
"property",
"=",
"request_parameter",
"(",
"parameter",
"=",
"property_name",
",... | 38 | 21.785714 |
def get_object(self):
"""
Get the object we are working with. Makes sure
get_queryset is called even when in add mode.
"""
if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None):
return super(FormView, self).get_object()
else:
self.q... | [
"def",
"get_object",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"force_add",
"and",
"self",
".",
"kwargs",
".",
"get",
"(",
"self",
".",
"slug_url_kwarg",
",",
"None",
")",
":",
"return",
"super",
"(",
"FormView",
",",
"self",
")",
".",
"get_ob... | 29.916667 | 19.25 |
def _load_recursive(self, shape, gen):
"""Recursively create a multidimensional array (as lists of lists)
from a bit generator.
"""
if len(shape) > 0:
ans = []
for i in range(shape[0]):
ans.append(self._load_recursive(shape[1:], gen))
else:... | [
"def",
"_load_recursive",
"(",
"self",
",",
"shape",
",",
"gen",
")",
":",
"if",
"len",
"(",
"shape",
")",
">",
"0",
":",
"ans",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"shape",
"[",
"0",
"]",
")",
":",
"ans",
".",
"append",
"(",
"self... | 38.205128 | 12.282051 |
def _blocks_to_samples(sig_data, n_samp, fmt):
"""
Convert uint8 blocks into signal samples for unaligned dat formats.
Parameters
----------
sig_data : numpy array
The uint8 data blocks.
n_samp : int
The number of samples contained in the bytes
Returns
-------
signa... | [
"def",
"_blocks_to_samples",
"(",
"sig_data",
",",
"n_samp",
",",
"fmt",
")",
":",
"if",
"fmt",
"==",
"'212'",
":",
"# Easier to process when dealing with whole blocks",
"if",
"n_samp",
"%",
"2",
":",
"n_samp",
"+=",
"1",
"added_samps",
"=",
"1",
"sig_data",
"... | 38.480769 | 24.75 |
def activities(self, limit=1, event=None):
"""Return device activity information."""
activities = self._activities or []
# Filter our activity array if requested
if event:
activities = list(
filter(
lambda activity:
act... | [
"def",
"activities",
"(",
"self",
",",
"limit",
"=",
"1",
",",
"event",
"=",
"None",
")",
":",
"activities",
"=",
"self",
".",
"_activities",
"or",
"[",
"]",
"# Filter our activity array if requested",
"if",
"event",
":",
"activities",
"=",
"list",
"(",
"f... | 32.461538 | 13.923077 |
def set_tab(self, widget, switch=False, title=None):
"""Add or modify a tab.
If widget is not a tab, it will be added. If switch is True, switch to
this tab. If title is given, set the tab's title.
"""
if widget not in self._widgets:
self._widgets.append(widget)
... | [
"def",
"set_tab",
"(",
"self",
",",
"widget",
",",
"switch",
"=",
"False",
",",
"title",
"=",
"None",
")",
":",
"if",
"widget",
"not",
"in",
"self",
".",
"_widgets",
":",
"self",
".",
"_widgets",
".",
"append",
"(",
"widget",
")",
"self",
".",
"_wi... | 36.857143 | 13.714286 |
def handle_message(self, client_conn, msg):
"""Handle messages of all types from clients.
Parameters
----------
client_conn : ClientConnection object
The client connection the message was from.
msg : Message object
The message to process.
"""
... | [
"def",
"handle_message",
"(",
"self",
",",
"client_conn",
",",
"msg",
")",
":",
"# log messages received so that no one else has to",
"self",
".",
"_logger",
".",
"debug",
"(",
"'received: {0!s}'",
".",
"format",
"(",
"msg",
")",
")",
"if",
"msg",
".",
"mtype",
... | 37.125 | 16.958333 |
def filter(self, *filt, **kwargs):
"""Filter this `TimeSeries` with an IIR or FIR filter
Parameters
----------
*filt : filter arguments
1, 2, 3, or 4 arguments defining the filter to be applied,
- an ``Nx1`` `~numpy.ndarray` of FIR coefficients
... | [
"def",
"filter",
"(",
"self",
",",
"*",
"filt",
",",
"*",
"*",
"kwargs",
")",
":",
"# parse keyword arguments",
"filtfilt",
"=",
"kwargs",
".",
"pop",
"(",
"'filtfilt'",
",",
"False",
")",
"# parse filter",
"form",
",",
"filt",
"=",
"filter_design",
".",
... | 34.031008 | 22.170543 |
def _lazy_load_units_by_code():
"""Populate dict of units by code iff UNITS_BY_CODE is empty."""
if UNITS_BY_CODE:
# already populated
return
for unit in units.UNITS_BY_NAME.values():
UNITS_BY_CODE[unit.code] = unit | [
"def",
"_lazy_load_units_by_code",
"(",
")",
":",
"if",
"UNITS_BY_CODE",
":",
"# already populated",
"return",
"for",
"unit",
"in",
"units",
".",
"UNITS_BY_NAME",
".",
"values",
"(",
")",
":",
"UNITS_BY_CODE",
"[",
"unit",
".",
"code",
"]",
"=",
"unit"
] | 28.375 | 15.625 |
def assert_valid_path(path):
"""Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid.
:param str path: The app id.
:rtype: str
"""
if path is None:
return
# As seen in:
# https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef790... | [
"def",
"assert_valid_path",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"# As seen in:",
"# https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71",
"for",
"id",
"in",
"fil... | 38.5625 | 26.25 |
def compile(self):
"""
Compile SQL and return 3-tuple ``(sql, params, keys)``.
Example usage::
(sql, params, keys) = sc.compile()
for row in cursor.execute(sql, params):
record = dict(zip(keys, row))
"""
params = self.column_params + sel... | [
"def",
"compile",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"column_params",
"+",
"self",
".",
"join_params",
"+",
"self",
".",
"params",
"if",
"self",
".",
"limit",
"and",
"self",
".",
"limit",
">=",
"0",
":",
"self",
".",
"sql_limit",
"=",... | 30.875 | 15.375 |
def delete_user(self, user, group):
""" Deletes user from group """
if not self.__contains__(group):
raise GroupNotExists
if not self.is_user_in(user, group):
raise UserNotInAGroup
self.new_groups.popvalue(group, user) | [
"def",
"delete_user",
"(",
"self",
",",
"user",
",",
"group",
")",
":",
"if",
"not",
"self",
".",
"__contains__",
"(",
"group",
")",
":",
"raise",
"GroupNotExists",
"if",
"not",
"self",
".",
"is_user_in",
"(",
"user",
",",
"group",
")",
":",
"raise",
... | 38.285714 | 4.142857 |
def readVersion(self):
""" Read the document version.
::
<designspace format="3">
"""
ds = self.root.findall("[@format]")[0]
raw_format = ds.attrib['format']
try:
self.documentFormatVersion = int(raw_format)
except ValueError:
#... | [
"def",
"readVersion",
"(",
"self",
")",
":",
"ds",
"=",
"self",
".",
"root",
".",
"findall",
"(",
"\"[@format]\"",
")",
"[",
"0",
"]",
"raw_format",
"=",
"ds",
".",
"attrib",
"[",
"'format'",
"]",
"try",
":",
"self",
".",
"documentFormatVersion",
"=",
... | 35.916667 | 14.166667 |
def _stringifyKeys(d):
"""
Return a copy of C{d} with C{str} keys.
@type d: C{dict} with C{unicode} keys.
@rtype: C{dict} with C{str} keys.
"""
return dict((k.encode('ascii'), v) for (k, v) in d.iteritems()) | [
"def",
"_stringifyKeys",
"(",
"d",
")",
":",
"return",
"dict",
"(",
"(",
"k",
".",
"encode",
"(",
"'ascii'",
")",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"iteritems",
"(",
")",
")"
] | 28.25 | 11.75 |
def struct_from_value( cls, name, volume,
channel_list=None, mute=False, device=None ):
'Same arguments as with class instance init.'
chan_map = c.PA_CHANNEL_MAP()
if not channel_list: c.pa.channel_map_init_mono(chan_map)
else:
if not is_str(channel_list):
channel_list = b','.join(map(c.force_bytes, c... | [
"def",
"struct_from_value",
"(",
"cls",
",",
"name",
",",
"volume",
",",
"channel_list",
"=",
"None",
",",
"mute",
"=",
"False",
",",
"device",
"=",
"None",
")",
":",
"chan_map",
"=",
"c",
".",
"PA_CHANNEL_MAP",
"(",
")",
"if",
"not",
"channel_list",
"... | 41.4375 | 12.4375 |
def delete(self, name):
"""
Handle deletion race condition present in Django prior to 1.4
https://code.djangoproject.com/ticket/16108
"""
try:
super(StaticCompilerFileStorage, self).delete(name)
except OSError, e:
if e.errno != errno.ENOENT:
... | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"super",
"(",
"StaticCompilerFileStorage",
",",
"self",
")",
".",
"delete",
"(",
"name",
")",
"except",
"OSError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
... | 32.6 | 14.2 |
def _process_organism_dbxref(self, limit):
"""
This is the mapping between the flybase organisms and
external identifier "FBsp". We will want to use the NCBITaxon as
the primary, if possible, but will default to a blank node/internal id
if that is all that is available
Bu... | [
"def",
"_process_organism_dbxref",
"(",
"self",
",",
"limit",
")",
":",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"else",
":",
"graph",
"=",
"self",
".",
"graph",
"model",
"=",
"Model",
"(",
"graph",
")",
"line_counter"... | 37.732143 | 18.446429 |
def _longest_contig(self, contig_set, contig_lengths):
'''Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length.'''
longest_name = None
max_length = -1
for name in contig_set:
... | [
"def",
"_longest_contig",
"(",
"self",
",",
"contig_set",
",",
"contig_lengths",
")",
":",
"longest_name",
"=",
"None",
"max_length",
"=",
"-",
"1",
"for",
"name",
"in",
"contig_set",
":",
"if",
"contig_lengths",
"[",
"name",
"]",
">",
"max_length",
":",
"... | 44.5 | 15.666667 |
def get_tree_root(self):
""" Returns the absolute root node of current tree structure."""
root = self
while root.up is not None:
root = root.up
return root | [
"def",
"get_tree_root",
"(",
"self",
")",
":",
"root",
"=",
"self",
"while",
"root",
".",
"up",
"is",
"not",
"None",
":",
"root",
"=",
"root",
".",
"up",
"return",
"root"
] | 32.333333 | 13 |
def tic(self):
"""Start collecting stats for current batch.
Call before calling forward."""
if self.step % self.interval == 0:
for exe in self.exes:
for array in exe.arg_arrays:
array.wait_to_read()
for array in exe.aux_arrays:
... | [
"def",
"tic",
"(",
"self",
")",
":",
"if",
"self",
".",
"step",
"%",
"self",
".",
"interval",
"==",
"0",
":",
"for",
"exe",
"in",
"self",
".",
"exes",
":",
"for",
"array",
"in",
"exe",
".",
"arg_arrays",
":",
"array",
".",
"wait_to_read",
"(",
")... | 35.833333 | 6.75 |
def implicitly_declare_ro(instructions: List[AbstractInstruction]):
"""
Implicitly declare a register named ``ro`` for backwards compatibility with Quil 1.
There used to be one un-named hunk of classical memory. Now there are variables with
declarations. Instead of::
MEASURE 0 [0]
You mus... | [
"def",
"implicitly_declare_ro",
"(",
"instructions",
":",
"List",
"[",
"AbstractInstruction",
"]",
")",
":",
"ro_addrs",
":",
"List",
"[",
"int",
"]",
"=",
"[",
"]",
"for",
"instr",
"in",
"instructions",
":",
"if",
"isinstance",
"(",
"instr",
",",
"Declare... | 38.925926 | 27.962963 |
def depth_december_average_ground_temperature(self, value=None):
"""Corresponds to IDD Field `depth_december_average_ground_temperature`
Args:
value (float): value for IDD Field `depth_december_average_ground_temperature`
Unit: C
if `value` is None it will no... | [
"def",
"depth_december_average_ground_temperature",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'... | 38.090909 | 23.545455 |
def get_waveform_filter_precondition(approximant, length, delta_f):
"""Return the data preconditioning factor for this approximant.
"""
if approximant in _filter_preconditions:
return _filter_preconditions[approximant](length, delta_f)
else:
return None | [
"def",
"get_waveform_filter_precondition",
"(",
"approximant",
",",
"length",
",",
"delta_f",
")",
":",
"if",
"approximant",
"in",
"_filter_preconditions",
":",
"return",
"_filter_preconditions",
"[",
"approximant",
"]",
"(",
"length",
",",
"delta_f",
")",
"else",
... | 39.857143 | 15.571429 |
def send(sender_instance):
"""Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/
"""
m = Mailin(
"https://api.sendinblue.com/v2.0",
sender_instance._kwargs.get("api_key")
)
data = {
"to": email_list_... | [
"def",
"send",
"(",
"sender_instance",
")",
":",
"m",
"=",
"Mailin",
"(",
"\"https://api.sendinblue.com/v2.0\"",
",",
"sender_instance",
".",
"_kwargs",
".",
"get",
"(",
"\"api_key\"",
")",
")",
"data",
"=",
"{",
"\"to\"",
":",
"email_list_to_email_dict",
"(",
... | 38.032258 | 16.935484 |
def setup_catalogs(
portal, catalogs_definition={},
force_reindex=False, catalogs_extension={}, force_no_reindex=False):
"""
Setup the given catalogs. Redefines the map between content types and
catalogs and then checks the indexes and metacolumns, if one index/column
doesn't exist in th... | [
"def",
"setup_catalogs",
"(",
"portal",
",",
"catalogs_definition",
"=",
"{",
"}",
",",
"force_reindex",
"=",
"False",
",",
"catalogs_extension",
"=",
"{",
"}",
",",
"force_no_reindex",
"=",
"False",
")",
":",
"# If not given catalogs_definition, use the LIMS one",
... | 40.466667 | 19.866667 |
def _bisect(value_and_gradients_function, initial_args, f_lim):
"""Actual implementation of bisect given initial_args in a _BracketResult."""
def _loop_cond(curr):
# TODO(b/112524024): Also take into account max_iterations.
return ~tf.reduce_all(input_tensor=curr.stopped)
def _loop_body(curr):
"""Nar... | [
"def",
"_bisect",
"(",
"value_and_gradients_function",
",",
"initial_args",
",",
"f_lim",
")",
":",
"def",
"_loop_cond",
"(",
"curr",
")",
":",
"# TODO(b/112524024): Also take into account max_iterations.",
"return",
"~",
"tf",
".",
"reduce_all",
"(",
"input_tensor",
... | 49.155556 | 25.177778 |
def incident_path(cls, project, incident):
"""Return a fully-qualified incident string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}",
project=project,
incident=incident,
) | [
"def",
"incident_path",
"(",
"cls",
",",
"project",
",",
"incident",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}\"",
",",
"project",
"=",
"project",
",",
"incident",
"=",
"in... | 38.571429 | 11.571429 |
def id_pools_vmac_ranges(self):
"""
Gets the IdPoolsRanges API Client for VMAC Ranges.
Returns:
IdPoolsRanges:
"""
if not self.__id_pools_vmac_ranges:
self.__id_pools_vmac_ranges = IdPoolsRanges('vmac', self.__connection)
return self.__id_pools_vm... | [
"def",
"id_pools_vmac_ranges",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__id_pools_vmac_ranges",
":",
"self",
".",
"__id_pools_vmac_ranges",
"=",
"IdPoolsRanges",
"(",
"'vmac'",
",",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__id_pools_v... | 32 | 15.2 |
def ArcTan2(x: vertex_constructor_param_types, y: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Calculates the signed angle, in radians, between the positive x-axis and a ray to the point (x, y) from the origin
:param x: x coordinate
:param y: y coordinate
"""
re... | [
"def",
"ArcTan2",
"(",
"x",
":",
"vertex_constructor_param_types",
",",
"y",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"jvm_view",
"(... | 52.125 | 36.375 |
def certify_list(
value, certifier=None, min_len=None, max_len=None, required=True, schema=None,
include_collections=False,
):
"""
Certifier for a list.
:param list value:
The array to be certified.
:param func certifier:
A function to be called on each value in the iterable to ... | [
"def",
"certify_list",
"(",
"value",
",",
"certifier",
"=",
"None",
",",
"min_len",
"=",
"None",
",",
"max_len",
"=",
"None",
",",
"required",
"=",
"True",
",",
"schema",
"=",
"None",
",",
"include_collections",
"=",
"False",
",",
")",
":",
"certify_bool... | 34.833333 | 21.357143 |
def with_params(self, **kwargs):
"""Modify various execution parameters of a Pipeline before it runs.
This method has no effect in test mode.
Args:
kwargs: Attributes to modify on this Pipeline instance before it has
been executed.
Returns:
This Pipeline instance, for easy chainin... | [
"def",
"with_params",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_TEST_MODE",
":",
"logging",
".",
"info",
"(",
"'Setting runtime parameters for %s#%s: %r'",
",",
"self",
",",
"self",
".",
"pipeline_id",
",",
"kwargs",
")",
"return",
"self",
"if"... | 31.551724 | 19.37931 |
def get_reversed_unification_program(angles, control_indices,
target, controls, mode):
"""
Gets the Program representing the reversed circuit
for the decomposition of the uniformly controlled
rotations in a unification step.
If :math:`n` is the number of control... | [
"def",
"get_reversed_unification_program",
"(",
"angles",
",",
"control_indices",
",",
"target",
",",
"controls",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"'phase'",
":",
"gate",
"=",
"RZ",
"elif",
"mode",
"==",
"'magnitude'",
":",
"gate",
"=",
"RY",
"el... | 43.295455 | 22.068182 |
def _new_stream(self, idx):
'''Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# Don't activate the stream if the weight is 0 or None
if self.stream_weights_[idx]:
... | [
"def",
"_new_stream",
"(",
"self",
",",
"idx",
")",
":",
"# Don't activate the stream if the weight is 0 or None",
"if",
"self",
".",
"stream_weights_",
"[",
"idx",
"]",
":",
"self",
".",
"streams_",
"[",
"idx",
"]",
"=",
"self",
".",
"streamers",
"[",
"idx",
... | 30.4375 | 16.4375 |
def get_unique_backends():
"""Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available.
"""
backends = IBMQ.backends()
unique_hardware_backends = []
unique_names = []
for back in backends:
... | [
"def",
"get_unique_backends",
"(",
")",
":",
"backends",
"=",
"IBMQ",
".",
"backends",
"(",
")",
"unique_hardware_backends",
"=",
"[",
"]",
"unique_names",
"=",
"[",
"]",
"for",
"back",
"in",
"backends",
":",
"if",
"back",
".",
"name",
"(",
")",
"not",
... | 31.368421 | 14.736842 |
def do_exit(*args):
'''
We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work.
'''
try:
import java.lang.System
java.lang.System.exit(1)
except ImportError:
if len(args) =... | [
"def",
"do_exit",
"(",
"*",
"args",
")",
":",
"try",
":",
"import",
"java",
".",
"lang",
".",
"System",
"java",
".",
"lang",
".",
"System",
".",
"exit",
"(",
"1",
")",
"except",
"ImportError",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
... | 25.2 | 25.466667 |
def set_features(self):
""""Merge all psms and peptides"""
allpsms_str = readers.generate_psms_multiple_fractions_strings(
self.mergefiles, self.ns)
allpeps = preparation.merge_peptides(self.mergefiles, self.ns)
self.features = {'psm': allpsms_str, 'peptide': allpeps} | [
"def",
"set_features",
"(",
"self",
")",
":",
"allpsms_str",
"=",
"readers",
".",
"generate_psms_multiple_fractions_strings",
"(",
"self",
".",
"mergefiles",
",",
"self",
".",
"ns",
")",
"allpeps",
"=",
"preparation",
".",
"merge_peptides",
"(",
"self",
".",
"... | 51.166667 | 17.5 |
def VEXTRACTF128(cpu, dest, src, offset):
"""Extract Packed Floating-Point Values
Extracts 128-bits of packed floating-point values from the source
operand (second operand) at an 128-bit offset from imm8[0] into the
destination operand (first operand). The destination may be either an
... | [
"def",
"VEXTRACTF128",
"(",
"cpu",
",",
"dest",
",",
"src",
",",
"offset",
")",
":",
"offset",
"=",
"offset",
".",
"read",
"(",
")",
"dest",
".",
"write",
"(",
"Operators",
".",
"EXTRACT",
"(",
"src",
".",
"read",
"(",
")",
",",
"offset",
"*",
"1... | 48.8 | 21 |
def get_job_id_from_name(self, job_name):
"""Retrieve the first job ID matching the given name"""
jobs = self._client.list_jobs(jobQueue=self._queue, jobStatus='RUNNING')['jobSummaryList']
matching_jobs = [job for job in jobs if job['jobName'] == job_name]
if matching_jobs:
r... | [
"def",
"get_job_id_from_name",
"(",
"self",
",",
"job_name",
")",
":",
"jobs",
"=",
"self",
".",
"_client",
".",
"list_jobs",
"(",
"jobQueue",
"=",
"self",
".",
"_queue",
",",
"jobStatus",
"=",
"'RUNNING'",
")",
"[",
"'jobSummaryList'",
"]",
"matching_jobs",... | 57.666667 | 18.833333 |
def insert_contribution_entries(database, entries):
"""Insert a set of records of a contribution report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param database: The MongoDB database to operate on. The contributions
... | [
"def",
"insert_contribution_entries",
"(",
"database",
",",
"entries",
")",
":",
"entries",
"=",
"map",
"(",
"clean_entry",
",",
"entries",
")",
"database",
".",
"contributions",
".",
"insert",
"(",
"entries",
",",
"continue_on_error",
"=",
"True",
")"
] | 42.428571 | 17.714286 |
def create_event_study_tear_sheet(factor_data,
prices=None,
avgretplot=(5, 15),
rate_of_ret=True,
n_bars=50):
"""
Creates an event study tear sheet for analysis of a specific e... | [
"def",
"create_event_study_tear_sheet",
"(",
"factor_data",
",",
"prices",
"=",
"None",
",",
"avgretplot",
"=",
"(",
"5",
",",
"15",
")",
",",
"rate_of_ret",
"=",
"True",
",",
"n_bars",
"=",
"50",
")",
":",
"long_short",
"=",
"False",
"plotting",
".",
"p... | 38.766355 | 20.82243 |
def update_display(cb, pool, params, plane, qwertz):
"""
Draws everything.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plan... | [
"def",
"update_display",
"(",
"cb",
",",
"pool",
",",
"params",
",",
"plane",
",",
"qwertz",
")",
":",
"cb",
".",
"clear",
"(",
")",
"draw_panel",
"(",
"cb",
",",
"pool",
",",
"params",
",",
"plane",
")",
"update_position",
"(",
"params",
")",
"# Upd... | 30.882353 | 16.176471 |
def one(nodes, or_none=False):
"""
Assert that there is exactly one node in the give list, and return it.
"""
if not nodes and or_none:
return None
assert len(
nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes))
return nodes[0] | [
"def",
"one",
"(",
"nodes",
",",
"or_none",
"=",
"False",
")",
":",
"if",
"not",
"nodes",
"and",
"or_none",
":",
"return",
"None",
"assert",
"len",
"(",
"nodes",
")",
"==",
"1",
",",
"'Expected 1 result. Received %d results.'",
"%",
"(",
"len",
"(",
"nod... | 30.777778 | 17.666667 |
def invalidate(self, comparison: Comparison[Entity, Entity]) -> None:
"""
Invalidate paths in a zone. See https://api.cloudflare.com
/#zone-purge-individual-files-by-url-and-cache-tags
:param comparison: The comparison whose changes to invalidate.
:raises requests.exceptions.Req... | [
"def",
"invalidate",
"(",
"self",
",",
"comparison",
":",
"Comparison",
"[",
"Entity",
",",
"Entity",
"]",
")",
"->",
"None",
":",
"@",
"backoff",
".",
"on_exception",
"(",
"backoff",
".",
"expo",
",",
"requests",
".",
"exceptions",
".",
"RequestException"... | 47.440678 | 19.881356 |
def as_numpy(dataset, graph=None):
"""Converts a `tf.data.Dataset` to an iterable of NumPy arrays.
`as_numpy` converts a possibly nested structure of `tf.data.Dataset`s
and `tf.Tensor`s to iterables of NumPy arrays and NumPy arrays, respectively.
Args:
dataset: a possibly nested structure of `tf.data.Data... | [
"def",
"as_numpy",
"(",
"dataset",
",",
"graph",
"=",
"None",
")",
":",
"nested_ds",
"=",
"dataset",
"del",
"dataset",
"# Flatten",
"flat_ds",
"=",
"tf",
".",
"nest",
".",
"flatten",
"(",
"nested_ds",
")",
"flat_np",
"=",
"[",
"]",
"# Type check for Tensor... | 33.701493 | 22.925373 |
def get_single_child_from_xml(elem, tag):
"""
Get a single child tag from an XML element.
Similar to "elem.find(tag)", but warns if there are multiple child tags with the given name.
"""
children = elem.findall(tag)
if not children:
return None
if len(children) > 1:
logging.w... | [
"def",
"get_single_child_from_xml",
"(",
"elem",
",",
"tag",
")",
":",
"children",
"=",
"elem",
".",
"findall",
"(",
"tag",
")",
"if",
"not",
"children",
":",
"return",
"None",
"if",
"len",
"(",
"children",
")",
">",
"1",
":",
"logging",
".",
"warning"... | 38.615385 | 16.615385 |
def _make_summary_statistic(attr):
"""Factory for implementing summary statistics, eg, mean, stddev, mode."""
def _fn(self, **kwargs):
"""Implements summary statistic, eg, mean, stddev, mode."""
x = getattr(self.distribution, attr)(**kwargs)
shape = prefer_static.concat([
self.distribution.batch... | [
"def",
"_make_summary_statistic",
"(",
"attr",
")",
":",
"def",
"_fn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Implements summary statistic, eg, mean, stddev, mode.\"\"\"",
"x",
"=",
"getattr",
"(",
"self",
".",
"distribution",
",",
"attr",
")",
"... | 40.789474 | 12 |
def package_name(self, PACKAGES_TXT):
"""Returns list with all the names of packages repository
"""
packages = []
for line in PACKAGES_TXT.splitlines():
if line.startswith("PACKAGE NAME:"):
packages.append(split_package(line[14:].strip())[0])
return pa... | [
"def",
"package_name",
"(",
"self",
",",
"PACKAGES_TXT",
")",
":",
"packages",
"=",
"[",
"]",
"for",
"line",
"in",
"PACKAGES_TXT",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"PACKAGE NAME:\"",
")",
":",
"packages",
".",
"ap... | 39.875 | 10.125 |
def get(self):
"""Get run list"""
LOG.info('Returning all ansible runs')
response = []
for run in self.backend_store.list_runs():
response.append(run_model.format_response(run))
return response | [
"def",
"get",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"'Returning all ansible runs'",
")",
"response",
"=",
"[",
"]",
"for",
"run",
"in",
"self",
".",
"backend_store",
".",
"list_runs",
"(",
")",
":",
"response",
".",
"append",
"(",
"run_model",
... | 34.142857 | 13.857143 |
def execute(self, string, max_tacts=None):
"""Execute algorithm (if max_times = None, there can be forever loop)."""
self.init_tape(string)
counter = 0
while True:
self.execute_once()
if self.state == self.TERM_STATE:
break
counter += ... | [
"def",
"execute",
"(",
"self",
",",
"string",
",",
"max_tacts",
"=",
"None",
")",
":",
"self",
".",
"init_tape",
"(",
"string",
")",
"counter",
"=",
"0",
"while",
"True",
":",
"self",
".",
"execute_once",
"(",
")",
"if",
"self",
".",
"state",
"==",
... | 33.642857 | 17.285714 |
def __find_node_by_rule(self, point, search_rule, cur_node):
"""!
@brief Search node that satisfy to parameters in search rule.
@details If node with specified parameters does not exist then None will be returned,
otherwise required node will be returned.
... | [
"def",
"__find_node_by_rule",
"(",
"self",
",",
"point",
",",
"search_rule",
",",
"cur_node",
")",
":",
"req_node",
"=",
"None",
"if",
"cur_node",
"is",
"None",
":",
"cur_node",
"=",
"self",
".",
"__root",
"while",
"cur_node",
":",
"if",
"cur_node",
".",
... | 38.5 | 23.21875 |
def _filter_attribute(mcs, attribute_name, attribute_value):
"""
decides whether the given attribute should be excluded from tracing or not
"""
if attribute_name == '__module__':
return True
elif hasattr(attribute_value, '_trace_disable'):
return True
... | [
"def",
"_filter_attribute",
"(",
"mcs",
",",
"attribute_name",
",",
"attribute_value",
")",
":",
"if",
"attribute_name",
"==",
"'__module__'",
":",
"return",
"True",
"elif",
"hasattr",
"(",
"attribute_value",
",",
"'_trace_disable'",
")",
":",
"return",
"True",
... | 36.444444 | 14.888889 |
def send(self, data):
"""
Sending data back to client
:return:
"""
data = data.decode().replace("\n", "\r\n")
self.writer.write(data.encode()) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\\r\\n\"",
")",
"self",
".",
"writer",
".",
"write",
"(",
"data",
".",
"encode",
"(",
")",
")"
] | 26.285714 | 8.285714 |
def calc_A(Ys):
'''Return the matrix A from a list of Y vectors.'''
return sum(np.dot(np.reshape(Y, (3,1)), np.reshape(Y, (1, 3)))
for Y in Ys) | [
"def",
"calc_A",
"(",
"Ys",
")",
":",
"return",
"sum",
"(",
"np",
".",
"dot",
"(",
"np",
".",
"reshape",
"(",
"Y",
",",
"(",
"3",
",",
"1",
")",
")",
",",
"np",
".",
"reshape",
"(",
"Y",
",",
"(",
"1",
",",
"3",
")",
")",
")",
"for",
"Y... | 40 | 20.5 |
def poke(self, context):
"""
Pokes for a mail attachment on the mail server.
:param context: The context that is being provided when poking.
:type context: dict
:return: True if attachment with the given name is present and False if not.
:rtype: bool
"""
... | [
"def",
"poke",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Poking for %s'",
",",
"self",
".",
"attachment_name",
")",
"with",
"ImapHook",
"(",
"imap_conn_id",
"=",
"self",
".",
"conn_id",
")",
"as",
"imap_hook",
":",
... | 36.352941 | 18.117647 |
def weighted_choice(self, probabilities, key):
"""Makes a weighted choice between several options.
Probabilities is a list of 2-tuples, (probability, option). The
probabilties don't need to add up to anything, they are automatically
scaled."""
total = sum(x[0] for x in probabil... | [
"def",
"weighted_choice",
"(",
"self",
",",
"probabilities",
",",
"key",
")",
":",
"total",
"=",
"sum",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"probabilities",
")",
"choice",
"=",
"total",
"*",
"self",
".",
"_random",
"(",
"key",
")",
"for",
"p... | 35.642857 | 17.428571 |
def setDefaultIREncoding(encoding):
'''
setDefaultIREncoding - Sets the default encoding used by IndexedRedis.
This will be the default encoding used for field data. You can override this on a
per-field basis by using an IRField (such as IRUnicodeField or IRRawField)
@param encoding - An encoding (like ut... | [
"def",
"setDefaultIREncoding",
"(",
"encoding",
")",
":",
"try",
":",
"b''",
".",
"decode",
"(",
"encoding",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'setDefaultIREncoding was provided an invalid codec. Got (encoding=\"%s\")'",
"%",
"(",
"str",
"(",
"encoding"... | 34.866667 | 30.6 |
def generate_session_token(refresh_token, verbose):
"""
Generates new session token from the given refresh token.
:param refresh_token: refresh token to generate from
:param verbose: whether expiration time should be added to output
"""
platform = _get_platform(authenticated=False)
session_... | [
"def",
"generate_session_token",
"(",
"refresh_token",
",",
"verbose",
")",
":",
"platform",
"=",
"_get_platform",
"(",
"authenticated",
"=",
"False",
")",
"session_token",
",",
"expires_in",
"=",
"platform",
".",
"generate_session_token",
"(",
"refresh_token",
")",... | 38.5 | 23.642857 |
def is_fresh(self): # type: () -> bool
"""
Checks whether the lock file is still up to date with the current hash.
"""
lock = self._lock.read()
metadata = lock.get("metadata", {})
if "content-hash" in metadata:
return self._content_hash == lock["metadata"]["... | [
"def",
"is_fresh",
"(",
"self",
")",
":",
"# type: () -> bool",
"lock",
"=",
"self",
".",
"_lock",
".",
"read",
"(",
")",
"metadata",
"=",
"lock",
".",
"get",
"(",
"\"metadata\"",
",",
"{",
"}",
")",
"if",
"\"content-hash\"",
"in",
"metadata",
":",
"re... | 31.454545 | 16.909091 |
def julian_day(t: date) -> int:
"""Convert a Python datetime to a Julian day"""
# Compute the number of days from January 1, 2000 to date t
dt = t - julian_base_date
# Add the julian base number to the number of days from the julian base date to date t
return julian_base_number + dt.days | [
"def",
"julian_day",
"(",
"t",
":",
"date",
")",
"->",
"int",
":",
"# Compute the number of days from January 1, 2000 to date t",
"dt",
"=",
"t",
"-",
"julian_base_date",
"# Add the julian base number to the number of days from the julian base date to date t",
"return",
"julian_b... | 50.5 | 15.666667 |
def deltas(self):
"""
Dictionary of relative offsets. The keys in the result are
pairs of keys from the offset vector, (a, b), and the
values are the relative offsets, (offset[b] - offset[a]).
Raises ValueError if the offsetvector is empty (WARNING:
this behaviour might change in the future).
Example:
... | [
"def",
"deltas",
"(",
"self",
")",
":",
"# FIXME: instead of raising ValueError when the",
"# offsetvector is empty this should return an empty",
"# dictionary. the inverse, .fromdeltas() accepts",
"# empty dictionaries",
"# NOTE: the arithmetic used to construct the offsets",
"# *must* mat... | 35.948718 | 18.615385 |
def validate_state(self, model, context=None):
"""
Validate model state
Run state validators and return and result object.
:param model: object or dict
:param context: object, dict or None
:return: shiftschema.result.Result
"""
result = Result()
f... | [
"def",
"validate_state",
"(",
"self",
",",
"model",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"Result",
"(",
")",
"for",
"state_validator",
"in",
"self",
".",
"state",
":",
"error",
"=",
"state_validator",
".",
"run",
"(",
"value",
"=",
"mo... | 30.105263 | 10.842105 |
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size]) | [
"def",
"_unpack_header",
"(",
"self",
",",
"data",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"self",
".",
"_struct_header",
",",
"data",
"[",
":",
"self",
".",
"_struct_header_size",
"]",
")"
] | 35.166667 | 7.833333 |
def map_entity(self, entity: dal.AssetClass):
""" maps data from entity -> object """
obj = model.AssetClass()
obj.id = entity.id
obj.parent_id = entity.parentid
obj.name = entity.name
obj.allocation = entity.allocation
obj.sort_order = entity.sortorder
#... | [
"def",
"map_entity",
"(",
"self",
",",
"entity",
":",
"dal",
".",
"AssetClass",
")",
":",
"obj",
"=",
"model",
".",
"AssetClass",
"(",
")",
"obj",
".",
"id",
"=",
"entity",
".",
"id",
"obj",
".",
"parent_id",
"=",
"entity",
".",
"parentid",
"obj",
... | 29.2 | 12.333333 |
def get_gatk_version(self):
"""Retrieve GATK version, handling locally and config cached versions.
Calling version can be expensive due to all the startup and shutdown
of JVMs, so we prefer cached version information.
"""
if self._gatk_version is None:
self._set_defau... | [
"def",
"get_gatk_version",
"(",
"self",
")",
":",
"if",
"self",
".",
"_gatk_version",
"is",
"None",
":",
"self",
".",
"_set_default_versions",
"(",
"self",
".",
"_config",
")",
"if",
"\"gatk4\"",
"not",
"in",
"dd",
".",
"get_tools_off",
"(",
"{",
"\"config... | 47.304348 | 17.521739 |
def is_same_dict(d1, d2):
"""Test two dictionary is equal on values. (ignore order)
"""
for k, v in d1.items():
if isinstance(v, dict):
is_same_dict(v, d2[k])
else:
assert d1[k] == d2[k]
for k, v in d2.items():
if isinstance(v, dict):
is_same_... | [
"def",
"is_same_dict",
"(",
"d1",
",",
"d2",
")",
":",
"for",
"k",
",",
"v",
"in",
"d1",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"is_same_dict",
"(",
"v",
",",
"d2",
"[",
"k",
"]",
")",
"else",
":",
... | 26.357143 | 12.785714 |
def _list_of_dicts_to_column_headers(list_of_dicts):
"""
Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to ... | [
"def",
"_list_of_dicts_to_column_headers",
"(",
"list_of_dicts",
")",
":",
"if",
"len",
"(",
"list_of_dicts",
")",
"<",
"2",
"or",
"not",
"all",
"(",
"isinstance",
"(",
"item",
",",
"dict",
")",
"for",
"item",
"in",
"list_of_dicts",
")",
":",
"return",
"No... | 35.958333 | 26.041667 |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extracts relevant user timestamp entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extract... | [
"def",
"GetEntries",
"(",
"self",
",",
"parser_mediator",
",",
"match",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"if",
"'name'",
"not",
"in",
"match",
"or",
"'uid'",
"not",
"in",
"match",
":",
"return",
"account",
"=",
"match",
"[",
"'nam... | 42.823077 | 21.661538 |
def to_type(self, dtype: type, *cols, **kwargs):
"""
Convert colums values to a given type in the
main dataframe
:param dtype: a type to convert to: ex: ``str``
:type dtype: type
:param \*cols: names of the colums
:type \*cols: str, at least one
:param \... | [
"def",
"to_type",
"(",
"self",
",",
"dtype",
":",
"type",
",",
"*",
"cols",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"allcols",
"=",
"self",
".",
"df",
".",
"columns",
".",
"values",
"for",
"col",
"in",
"cols",
":",
"if",
"col",
"not",
"i... | 34.913043 | 13.608696 |
def key_file_private(self):
'''str: path to the private key used by Ansible to connect to virtual
machines (by default looks for a file with name
:attr:`key_name <tmdeploy.config.CloudSection.key_name>` in ``~/.ssh``
directory)
'''
if not hasattr(self, '_key_file_private'... | [
"def",
"key_file_private",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_key_file_private'",
")",
":",
"self",
".",
"key_file_private",
"=",
"'~/.ssh/{key}'",
".",
"format",
"(",
"key",
"=",
"self",
".",
"key_name",
")",
"return",
"se... | 47.666667 | 22.555556 |
def read_memory_block8(self, addr, size):
"""
read a block of unaligned bytes in memory. Returns
an array of byte values
"""
data = self.ap.read_memory_block8(addr, size)
return self.bp_manager.filter_memory_unaligned_8(addr, size, data) | [
"def",
"read_memory_block8",
"(",
"self",
",",
"addr",
",",
"size",
")",
":",
"data",
"=",
"self",
".",
"ap",
".",
"read_memory_block8",
"(",
"addr",
",",
"size",
")",
"return",
"self",
".",
"bp_manager",
".",
"filter_memory_unaligned_8",
"(",
"addr",
",",... | 39.857143 | 10.714286 |
def encrypt(self, key):
"""This method encrypts and signs the state to make it unreadable by
the server, since it contains information that would allow faking
proof of storage.
:param key: the key to encrypt and sign with
"""
if (self.encrypted):
return
... | [
"def",
"encrypt",
"(",
"self",
",",
"key",
")",
":",
"if",
"(",
"self",
".",
"encrypted",
")",
":",
"return",
"# encrypt",
"self",
".",
"iv",
"=",
"Random",
".",
"new",
"(",
")",
".",
"read",
"(",
"AES",
".",
"block_size",
")",
"aes",
"=",
"AES",... | 35.294118 | 14.647059 |
def get_aspect(self, xspan, yspan):
"""
Computes the aspect ratio of the plot
"""
if isinstance(self.aspect, (int, float)):
return self.aspect
elif self.aspect == 'square':
return 1
elif self.aspect == 'equal':
return xspan/yspan
... | [
"def",
"get_aspect",
"(",
"self",
",",
"xspan",
",",
"yspan",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"aspect",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"self",
".",
"aspect",
"elif",
"self",
".",
"aspect",
"==",
"'square'",
... | 29.090909 | 8.181818 |
def mail_setup(path):
"""
Set the variables to be able to send emails.
:param path: path to the config file
"""
global dest_mails
global smtp_server
global smtp_port
global src_server
config = configparser.RawConfigParser()
config.readfp(path)
dest_mails = config.get('mail',... | [
"def",
"mail_setup",
"(",
"path",
")",
":",
"global",
"dest_mails",
"global",
"smtp_server",
"global",
"smtp_port",
"global",
"src_server",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"config",
".",
"readfp",
"(",
"path",
")",
"dest_mails",
... | 29.9375 | 13.0625 |
def histogram(self, stat, value, tags=None):
"""Report a histogram."""
self._log('histogram', stat, value, tags) | [
"def",
"histogram",
"(",
"self",
",",
"stat",
",",
"value",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"_log",
"(",
"'histogram'",
",",
"stat",
",",
"value",
",",
"tags",
")"
] | 42 | 4.333333 |
def empty_wav(wav_path: Union[Path, str]) -> bool:
"""Check if a wav contains data"""
with wave.open(str(wav_path), 'rb') as wav_f:
return wav_f.getnframes() == 0 | [
"def",
"empty_wav",
"(",
"wav_path",
":",
"Union",
"[",
"Path",
",",
"str",
"]",
")",
"->",
"bool",
":",
"with",
"wave",
".",
"open",
"(",
"str",
"(",
"wav_path",
")",
",",
"'rb'",
")",
"as",
"wav_f",
":",
"return",
"wav_f",
".",
"getnframes",
"(",... | 43.75 | 5.25 |
def jsonify(py_data, default=None, indent=4, sort_keys=True):
"""
Converts the inputted Python data to JSON format.
:param py_data | <variant>
"""
return json.dumps(py_data, default=py2json, indent=indent, sort_keys=sort_keys) | [
"def",
"jsonify",
"(",
"py_data",
",",
"default",
"=",
"None",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"py_data",
",",
"default",
"=",
"py2json",
",",
"indent",
"=",
"indent",
",",
"sort_... | 35.714286 | 16.857143 |
def or_(cls, obj, **kwargs):
"""Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if at leat one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
"""
return cls.__e... | [
"def",
"or_",
"(",
"cls",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"__eval_seqexp",
"(",
"obj",
",",
"operator",
".",
"or_",
",",
"*",
"*",
"kwargs",
")"
] | 24.714286 | 19.928571 |
def call(cmd, input=None, assert_zero_exit_status=True, warn_on_non_zero_exist_status=False, **kwargs):
"""
:rtype: SubprocessResult
Raises OSError if command was not found
Returns non-zero result in result.ret if subprocess terminated with non-zero exist status.
"""
if (not kwargs.get('shell'... | [
"def",
"call",
"(",
"cmd",
",",
"input",
"=",
"None",
",",
"assert_zero_exit_status",
"=",
"True",
",",
"warn_on_non_zero_exist_status",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"not",
"kwargs",
".",
"get",
"(",
"'shell'",
")",
")",
... | 39 | 24.666667 |
def _check_function(self):
''' make some basic checks on the function to make sure it is valid'''
# note, callable is valid for Python 2 and Python 3.2 onwards but
# not inbetween
if not callable(self._function):
raise RuntimeError(
"provided function '{0}' is... | [
"def",
"_check_function",
"(",
"self",
")",
":",
"# note, callable is valid for Python 2 and Python 3.2 onwards but",
"# not inbetween",
"if",
"not",
"callable",
"(",
"self",
".",
"_function",
")",
":",
"raise",
"RuntimeError",
"(",
"\"provided function '{0}' is not callable\... | 44.866667 | 13.533333 |
def start(self, *args):
"""
Start a nested log.
"""
if self._is_verbose:
# verbose log has no start method
return self
self.writeln('start', *args)
self._indent += 1
return self | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"_is_verbose",
":",
"# verbose log has no start method",
"return",
"self",
"self",
".",
"writeln",
"(",
"'start'",
",",
"*",
"args",
")",
"self",
".",
"_indent",
"+=",
"1",
"retu... | 20.666667 | 15.333333 |
def pairwise(iterable: Iterable[X]) -> Iterable[Tuple[X, X]]:
"""Iterate over pairs in list s -> (s0,s1), (s1,s2), (s2, s3), ..."""
a, b = itt.tee(iterable)
next(b, None)
return zip(a, b) | [
"def",
"pairwise",
"(",
"iterable",
":",
"Iterable",
"[",
"X",
"]",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"X",
",",
"X",
"]",
"]",
":",
"a",
",",
"b",
"=",
"itt",
".",
"tee",
"(",
"iterable",
")",
"next",
"(",
"b",
",",
"None",
")",
"retu... | 39.8 | 15.2 |
def signed_session(self, session=None):
# type: (Optional[requests.Session]) -> requests.Session
"""Create requests session with ApiKey.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configu... | [
"def",
"signed_session",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"# type: (Optional[requests.Session]) -> requests.Session",
"session",
"=",
"super",
"(",
"ApiKeyCredentials",
",",
"self",
")",
".",
"signed_session",
"(",
"session",
")",
"session",
".",
... | 45.263158 | 20.736842 |
def _MakeConnection(self, database=""):
"""Repeat connection attempts to server until we get a valid connection."""
first_attempt_time = time.time()
wait_time = config.CONFIG["Mysql.max_connect_wait"]
while wait_time == 0 or time.time() - first_attempt_time < wait_time:
try:
connection_arg... | [
"def",
"_MakeConnection",
"(",
"self",
",",
"database",
"=",
"\"\"",
")",
":",
"first_attempt_time",
"=",
"time",
".",
"time",
"(",
")",
"wait_time",
"=",
"config",
".",
"CONFIG",
"[",
"\"Mysql.max_connect_wait\"",
"]",
"while",
"wait_time",
"==",
"0",
"or",... | 36.325581 | 18.302326 |
def WriteFlowResponses(self, responses):
"""Writes FlowMessages and updates corresponding requests."""
if not responses:
return
for batch in collection.Batch(responses, self._WRITE_ROWS_BATCH_SIZE):
self._WriteFlowResponsesAndExpectedUpdates(batch)
completed_requests = self._UpdateRequ... | [
"def",
"WriteFlowResponses",
"(",
"self",
",",
"responses",
")",
":",
"if",
"not",
"responses",
":",
"return",
"for",
"batch",
"in",
"collection",
".",
"Batch",
"(",
"responses",
",",
"self",
".",
"_WRITE_ROWS_BATCH_SIZE",
")",
":",
"self",
".",
"_WriteFlowR... | 30.214286 | 25.428571 |
def copy(self):
"""Create a copy.
Examples:
This example copies constraint :math:`a \\ne b` and tests a solution
on the copied constraint.
>>> import dwavebinarycsp
>>> import operator
>>> const = dwavebinarycsp.Constraint.from_func(operator.... | [
"def",
"copy",
"(",
"self",
")",
":",
"# each object is itself immutable (except the function)",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"func",
",",
"self",
".",
"configurations",
",",
"self",
".",
"variables",
",",
"self",
".",
"vartype",
",",
... | 34.6 | 20.9 |
def __start_connection(self, context, node, ccallbacks=None):
"""Start a new connection, and manage it from a new greenlet."""
_logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]",
context, node)
c = nsq.connection.Connection(
context,
... | [
"def",
"__start_connection",
"(",
"self",
",",
"context",
",",
"node",
",",
"ccallbacks",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Creating connection object: CONTEXT=[%s] NODE=[%s]\"",
",",
"context",
",",
"node",
")",
"c",
"=",
"nsq",
".",
"co... | 33.484848 | 21.545455 |
def create_aeff(event_class, event_type, egy, cth):
"""Create an array of effective areas versus energy and incidence
angle. Binning in energy and incidence angle is controlled with
the egy and cth input parameters.
Parameters
----------
event_class : str
Event class string (e.g. P8R2_... | [
"def",
"create_aeff",
"(",
"event_class",
",",
"event_type",
",",
"egy",
",",
"cth",
")",
":",
"irf",
"=",
"create_irf",
"(",
"event_class",
",",
"event_type",
")",
"irf",
".",
"aeff",
"(",
")",
".",
"setPhiDependence",
"(",
"False",
")",
"theta",
"=",
... | 26.46875 | 18.96875 |
def get_filters(self, dataset):
"""Get available filters from dataset you've selected"""
filters = self.filters(dataset)
filt_ = [ (k, v[0]) for k, v in filters.items()]
return pd.DataFrame(filt_, columns=["Filter", "Description"]) | [
"def",
"get_filters",
"(",
"self",
",",
"dataset",
")",
":",
"filters",
"=",
"self",
".",
"filters",
"(",
"dataset",
")",
"filt_",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
")",
"for",
"k",
",",
"v",
"in",
"filters",
".",
"items",
"(",
")",
... | 51.8 | 11 |
def emit(self, record):
"""Save a logging.LogRecord to our test record.
Logs carry useful metadata such as the logger name and level information.
We capture this in a structured format in the test record to enable
filtering by client applications.
Args:
record: A logging.LogRecord to record.... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"message",
"=",
"self",
".",
"format",
"(",
"record",
")",
"log_record",
"=",
"LogRecord",
"(",
"record",
".",
"levelno",
",",
"record",
".",
"name",
",",
"os",
".",
"path",
".",
"bas... | 34.6 | 19.2 |
def prepend(self, _, child, name=None):
"""Adds childs to this tag, starting from the first position."""
self._insert(child, prepend=True, name=name)
return self | [
"def",
"prepend",
"(",
"self",
",",
"_",
",",
"child",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"child",
",",
"prepend",
"=",
"True",
",",
"name",
"=",
"name",
")",
"return",
"self"
] | 45.5 | 8.5 |
def _decorate(flush=True, attempts=1, only_authenticate=False):
"""
Wraps the given function such that conn.login() or conn.authenticate() is
executed.
Doing the real work for autologin and autoauthenticate to minimize code
duplication.
:type flush: bool
:param flush: Whether to flush the ... | [
"def",
"_decorate",
"(",
"flush",
"=",
"True",
",",
"attempts",
"=",
"1",
",",
"only_authenticate",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"def",
"decorated",
"(",
"job",
",",
"host",
",",
"conn",
",",
"*",
"args",
","... | 35.771429 | 16.285714 |
def periodogram_auto(self, oversampling=5, nyquist_factor=3,
return_periods=True):
"""Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data win... | [
"def",
"periodogram_auto",
"(",
"self",
",",
"oversampling",
"=",
"5",
",",
"nyquist_factor",
"=",
"3",
",",
"return_periods",
"=",
"True",
")",
":",
"N",
"=",
"len",
"(",
"self",
".",
"t",
")",
"T",
"=",
"np",
".",
"max",
"(",
"self",
".",
"t",
... | 36.852941 | 19.117647 |
def _iq_request_coro_done_send_reply(self, request, task):
"""
Called when an IQ request handler coroutine returns. `request` holds
the IQ request which triggered the excecution of the coroutine and
`task` is the :class:`asyncio.Task` which tracks the running coroutine.
Compose ... | [
"def",
"_iq_request_coro_done_send_reply",
"(",
"self",
",",
"request",
",",
"task",
")",
":",
"try",
":",
"payload",
"=",
"task",
".",
"result",
"(",
")",
"except",
"errors",
".",
"XMPPError",
"as",
"err",
":",
"self",
".",
"_send_iq_reply",
"(",
"request... | 41.222222 | 17.888889 |
def update(self, storagemodel:object, modeldefinition = None, hide = 0) -> StorageQueueModel:
""" update the message in queue """
if (storagemodel.id != '') and (storagemodel.pop_receipt != '') and (not storagemodel.id is None) and (not storagemodel.pop_receipt is None):
try:
... | [
"def",
"update",
"(",
"self",
",",
"storagemodel",
":",
"object",
",",
"modeldefinition",
"=",
"None",
",",
"hide",
"=",
"0",
")",
"->",
"StorageQueueModel",
":",
"if",
"(",
"storagemodel",
".",
"id",
"!=",
"''",
")",
"and",
"(",
"storagemodel",
".",
"... | 60.75 | 41 |
def _validate_depedencies(batches):
"""Validates the transaction dependencies for the transactions contained
within the sequence of batches. Given that all the batches are expected to
to be executed for the genesis blocks, it is assumed that any dependent
transaction will proceed the depending transacti... | [
"def",
"_validate_depedencies",
"(",
"batches",
")",
":",
"transaction_ids",
"=",
"set",
"(",
")",
"for",
"batch",
"in",
"batches",
":",
"for",
"txn",
"in",
"batch",
".",
"transactions",
":",
"txn_header",
"=",
"TransactionHeader",
"(",
")",
"txn_header",
".... | 41.73913 | 14.478261 |
def _pkg(jail=None, chroot=None, root=None):
'''
Returns the prefix for a pkg command, using -j if a jail is specified, or
-c if chroot is specified.
'''
ret = ['pkg']
if jail:
ret.extend(['-j', jail])
elif chroot:
ret.extend(['-c', chroot])
elif root:
ret.extend(... | [
"def",
"_pkg",
"(",
"jail",
"=",
"None",
",",
"chroot",
"=",
"None",
",",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"'pkg'",
"]",
"if",
"jail",
":",
"ret",
".",
"extend",
"(",
"[",
"'-j'",
",",
"jail",
"]",
")",
"elif",
"chroot",
":",
"... | 25.846154 | 20.461538 |
def is_number_type_geographical(num_type, country_code):
"""Tests whether a phone number has a geographical association,
as represented by its type and the country it belongs to.
This version of isNumberGeographical exists since calculating the phone
number type is expensive; if we have already done th... | [
"def",
"is_number_type_geographical",
"(",
"num_type",
",",
"country_code",
")",
":",
"return",
"(",
"num_type",
"==",
"PhoneNumberType",
".",
"FIXED_LINE",
"or",
"num_type",
"==",
"PhoneNumberType",
".",
"FIXED_LINE_OR_MOBILE",
"or",
"(",
"(",
"country_code",
"in",... | 48.25 | 19.416667 |
def sheetDeleteEmpty(bookName=None):
"""Delete all sheets which contain no data"""
if bookName is None:
bookName = activeBook()
if not bookName.lower() in [x.lower() for x in bookNames()]:
print("can't clean up a book that doesn't exist:",bookName)
return
poBook=PyOrigin.Workshee... | [
"def",
"sheetDeleteEmpty",
"(",
"bookName",
"=",
"None",
")",
":",
"if",
"bookName",
"is",
"None",
":",
"bookName",
"=",
"activeBook",
"(",
")",
"if",
"not",
"bookName",
".",
"lower",
"(",
")",
"in",
"[",
"x",
".",
"lower",
"(",
")",
"for",
"x",
"i... | 43.375 | 13.8125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.