text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def is_value_from_deprecated_setting(self, setting_name, deprecated_setting_name):
"""
Helps developers to determine where the settings helper got it's value
from when dealing with settings that replace deprecated settings.
Returns ``True`` when the new setting (with the name ``setting_... | [
"def",
"is_value_from_deprecated_setting",
"(",
"self",
",",
"setting_name",
",",
"deprecated_setting_name",
")",
":",
"if",
"not",
"self",
".",
"in_defaults",
"(",
"setting_name",
")",
":",
"self",
".",
"_raise_invalid_setting_name_error",
"(",
"setting_name",
")",
... | 48.060606 | 22.727273 |
def get_field_info(self, field):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
serializer = field.parent
if isinstance(field, serializers.ManyRelatedField):
field_info['type'] = s... | [
"def",
"get_field_info",
"(",
"self",
",",
"field",
")",
":",
"field_info",
"=",
"OrderedDict",
"(",
")",
"serializer",
"=",
"field",
".",
"parent",
"if",
"isinstance",
"(",
"field",
",",
"serializers",
".",
"ManyRelatedField",
")",
":",
"field_info",
"[",
... | 35.366667 | 22.866667 |
def isin(self, values, level=None):
"""
Return a boolean array where the index values are in `values`.
Compute boolean array of whether each index value is found in the
passed set of values. The length of the returned boolean array matches
the length of the index.
Param... | [
"def",
"isin",
"(",
"self",
",",
"values",
",",
"level",
"=",
"None",
")",
":",
"if",
"level",
"is",
"not",
"None",
":",
"self",
".",
"_validate_index_level",
"(",
"level",
")",
"return",
"algos",
".",
"isin",
"(",
"self",
",",
"values",
")"
] | 31.793103 | 22.114943 |
def video_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
"""Compute loss numerator and denominator for one shard of output."""
del vocab_size # unused arg
logits = top_out
logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:])
targets = tf.reshape(targets, [-1] + common_laye... | [
"def",
"video_loss",
"(",
"top_out",
",",
"targets",
",",
"model_hparams",
",",
"vocab_size",
",",
"weights_fn",
")",
":",
"del",
"vocab_size",
"# unused arg",
"logits",
"=",
"top_out",
"logits",
"=",
"tf",
".",
"reshape",
"(",
"logits",
",",
"[",
"-",
"1"... | 43.538462 | 19.769231 |
def get_all_used_vars(section):
'''Get variables which are variables used by input statement and statements before it'''
all_used_vars = set()
for statement in section.statements:
if statement[0] == '=':
all_used_vars |= accessed_vars('='.join(statement[1:3]))
elif statement[0] =... | [
"def",
"get_all_used_vars",
"(",
"section",
")",
":",
"all_used_vars",
"=",
"set",
"(",
")",
"for",
"statement",
"in",
"section",
".",
"statements",
":",
"if",
"statement",
"[",
"0",
"]",
"==",
"'='",
":",
"all_used_vars",
"|=",
"accessed_vars",
"(",
"'='"... | 43.057692 | 14.019231 |
def process_inlines(parser, token):
"""
Searches through the provided content and applies inlines where ever they
are found.
Syntax::
{% process_inlines entry.body [in template_dir] [as varname] }
Examples::
{% process_inlines entry.body %}
{% process_inlines entry.body ... | [
"def",
"process_inlines",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"not",
"len",
"(",
"args",
")",
"in",
"(",
"2",
",",
"4",
",",
"6",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError... | 28.439024 | 24.97561 |
def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs):
'''Decorate matplotlib drawing routines with blitting support.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) ... | [
"def",
"blittable_figure_tensor",
"(",
"func",
",",
"init_func",
",",
"*",
"*",
"tf_pyfunc_kwargs",
")",
":",
"name",
"=",
"tf_pyfunc_kwargs",
".",
"pop",
"(",
"'name'",
",",
"func",
".",
"__name__",
")",
"assert",
"callable",
"(",
"init_func",
")",
",",
"... | 41.191781 | 24.589041 |
def bundles_list(self, io_handler, name=None):
"""
Lists the bundles in the framework and their state. Possibility to
filter on the bundle name.
"""
# Head of the table
headers = ("ID", "Name", "State", "Version")
# Get the bundles
bundles = self._context... | [
"def",
"bundles_list",
"(",
"self",
",",
"io_handler",
",",
"name",
"=",
"None",
")",
":",
"# Head of the table",
"headers",
"=",
"(",
"\"ID\"",
",",
"\"Name\"",
",",
"\"State\"",
",",
"\"Version\"",
")",
"# Get the bundles",
"bundles",
"=",
"self",
".",
"_c... | 30.116279 | 19.325581 |
def get_cloud_masks(self, X):
"""
Runs the cloud detection on the input images (dimension n_images x n x m x 10
or n_images x n x m x 13) and returns the raster cloud mask (dimension n_images x n x m).
Pixel values equal to 0 indicate pixels classified as clear-sky, while values
... | [
"def",
"get_cloud_masks",
"(",
"self",
",",
"X",
")",
":",
"cloud_probs",
"=",
"self",
".",
"get_cloud_probability_maps",
"(",
"X",
")",
"return",
"self",
".",
"get_mask_from_prob",
"(",
"cloud_probs",
")"
] | 46.705882 | 26.235294 |
def process(self, request_adu):
""" Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request.
"""
validate_crc(request_adu)
return super(RTUServer, self).process(r... | [
"def",
"process",
"(",
"self",
",",
"request_adu",
")",
":",
"validate_crc",
"(",
"request_adu",
")",
"return",
"super",
"(",
"RTUServer",
",",
"self",
")",
".",
"process",
"(",
"request_adu",
")"
] | 40.5 | 16.625 |
def message(self, do_html=True, custom_email_template=None):
"""
Returns a tuple with (text_message,html_message)
"""
context = {
'build': self.build,
'important_metadata': self.important_metadata,
'metadata': self.metadata,
'notification':... | [
"def",
"message",
"(",
"self",
",",
"do_html",
"=",
"True",
",",
"custom_email_template",
"=",
"None",
")",
":",
"context",
"=",
"{",
"'build'",
":",
"self",
".",
"build",
",",
"'important_metadata'",
":",
"self",
".",
"important_metadata",
",",
"'metadata'"... | 39.307692 | 16.435897 |
def get_forces(self, a):
"""Calculate atomic forces."""
f = np.zeros( [ len(a), 3 ], dtype=float )
for c in self.calcs:
f += c.get_forces(a)
return f | [
"def",
"get_forces",
"(",
"self",
",",
"a",
")",
":",
"f",
"=",
"np",
".",
"zeros",
"(",
"[",
"len",
"(",
"a",
")",
",",
"3",
"]",
",",
"dtype",
"=",
"float",
")",
"for",
"c",
"in",
"self",
".",
"calcs",
":",
"f",
"+=",
"c",
".",
"get_force... | 31.333333 | 11.666667 |
def get_applied_migrations(databases=None):
"""
Returns a dictionary containing lists of all applied migrations
where the key is the database alias.
"""
if not databases:
databases = get_capable_databases()
else:
# We only loop through databases that are listed as "capable"
... | [
"def",
"get_applied_migrations",
"(",
"databases",
"=",
"None",
")",
":",
"if",
"not",
"databases",
":",
"databases",
"=",
"get_capable_databases",
"(",
")",
"else",
":",
"# We only loop through databases that are listed as \"capable\"",
"all_databases",
"=",
"list",
"(... | 33.3 | 18.1 |
def __contribution_from_parameters(self, parameter_names):
"""private method get the prior and posterior uncertainty reduction as a result of
some parameter becoming perfectly known
Parameters
----------
parameter_names : list
parameter that are perfectly known
... | [
"def",
"__contribution_from_parameters",
"(",
"self",
",",
"parameter_names",
")",
":",
"#get the prior and posterior for the base case",
"bprior",
",",
"bpost",
"=",
"self",
".",
"prior_prediction",
",",
"self",
".",
"posterior_prediction",
"#get the prior and posterior for ... | 34.241379 | 23.931034 |
def process_sequence(sequence,
rules=None,
skip_non_vietnamese=True):
"""\
Convert a key sequence into a Vietnamese string with diacritical marks.
Args:
rules (optional): see docstring for process_key().
skip_non_vietnamese (optional): see docstring... | [
"def",
"process_sequence",
"(",
"sequence",
",",
"rules",
"=",
"None",
",",
"skip_non_vietnamese",
"=",
"True",
")",
":",
"result",
"=",
"\"\"",
"raw",
"=",
"result",
"result_parts",
"=",
"[",
"]",
"if",
"rules",
"is",
"None",
":",
"rules",
"=",
"get_tel... | 29.378378 | 17.351351 |
def app_factory(global_settings, **local_settings): # pylint: disable=W0613
"""
Default factory for creating a WSGI application using the everest
configurator and root factory.
:param dict global_settings: Global settings extracted from an ini file.
Not used in this default app factory.
:pa... | [
"def",
"app_factory",
"(",
"global_settings",
",",
"*",
"*",
"local_settings",
")",
":",
"# pylint: disable=W0613",
"config",
"=",
"Configurator",
"(",
")",
"config",
".",
"setup_registry",
"(",
"settings",
"=",
"local_settings",
",",
"root_factory",
"=",
"RootFac... | 44.869565 | 17.565217 |
def close(self):
"""Close socket connection"""
if self._writer:
self._writer.transport.close()
self._writer = None
self._reader = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writer",
":",
"self",
".",
"_writer",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"_writer",
"=",
"None",
"self",
".",
"_reader",
"=",
"None"
] | 28.833333 | 11.333333 |
def _construct_unique_id(self, id_prefix, lines):
"""Constructs a unique ID for a particular prompt in this case,
based on the id_prefix and the lines in the prompt.
"""
text = []
for line in lines:
if isinstance(line, str):
text.append(line)
... | [
"def",
"_construct_unique_id",
"(",
"self",
",",
"id_prefix",
",",
"lines",
")",
":",
"text",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"text",
".",
"append",
"(",
"line",
")",
"elif",
... | 39.818182 | 8.181818 |
def mse(x, xhat):
""" Calcualte mse between vector or matrix x and xhat """
buf_ = x - xhat
np.square(buf_, out=buf_) # square in-place
sum_ = np.sum(buf_)
sum_ /= x.size # divide in-place
return sum_ | [
"def",
"mse",
"(",
"x",
",",
"xhat",
")",
":",
"buf_",
"=",
"x",
"-",
"xhat",
"np",
".",
"square",
"(",
"buf_",
",",
"out",
"=",
"buf_",
")",
"# square in-place",
"sum_",
"=",
"np",
".",
"sum",
"(",
"buf_",
")",
"sum_",
"/=",
"x",
".",
"size",
... | 31.428571 | 13.857143 |
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_m... | [
"def",
"back_make",
"(",
"dev",
",",
"cache_mode",
"=",
"'writeback'",
",",
"force",
"=",
"False",
",",
"attach",
"=",
"True",
",",
"bucket_size",
"=",
"None",
")",
":",
"# pylint: disable=too-many-return-statements",
"cache",
"=",
"uuid",
"(",
")",
"if",
"n... | 34.981481 | 26.240741 |
def _format_content(self, content):
"""Returns `content` with consecutive spaces converted to non-break
spaces, and linebreak converted into HTML br elements.
:param content: text to format
:type content: `str`
:rtype: `str`
"""
content = re.sub(r'\n', '<br/>\n'... | [
"def",
"_format_content",
"(",
"self",
",",
"content",
")",
":",
"content",
"=",
"re",
".",
"sub",
"(",
"r'\\n'",
",",
"'<br/>\\n'",
",",
"content",
")",
"content",
"=",
"re",
".",
"sub",
"(",
"r' '",
",",
"'  '",
",",
"content",
")",
"conte... | 35.384615 | 15.846154 |
def get_timeout(self, callback=None):
"""
Get the visibility timeout for the queue.
:rtype: int
:return: The number of seconds as an integer.
"""
def got_timeout(a):
if callable(callback):
callback(int(a['VisibilityTimeout']))
... | [
"def",
"get_timeout",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"def",
"got_timeout",
"(",
"a",
")",
":",
"if",
"callable",
"(",
"callback",
")",
":",
"callback",
"(",
"int",
"(",
"a",
"[",
"'VisibilityTimeout'",
"]",
")",
")",
"self",
"."... | 33.818182 | 12.727273 |
async def on_step(self, iteration):
self.combinedActions = []
"""
- depots when low on remaining supply
- townhalls contains commandcenter and orbitalcommand
- self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount... | [
"async",
"def",
"on_step",
"(",
"self",
",",
"iteration",
")",
":",
"self",
".",
"combinedActions",
"=",
"[",
"]",
"if",
"self",
".",
"supply_left",
"<",
"5",
"and",
"self",
".",
"townhalls",
".",
"exists",
"and",
"self",
".",
"supply_used",
">=",
"14"... | 67.078788 | 39.769697 |
def check_index(i):
"""
Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...]
"""
i = asarray(i)
if (i.ndim > 1) or (size(i) < 1):
raise Exception("Index must be one-dimensional and non-singleton")
return i | [
"def",
"check_index",
"(",
"i",
")",
":",
"i",
"=",
"asarray",
"(",
"i",
")",
"if",
"(",
"i",
".",
"ndim",
">",
"1",
")",
"or",
"(",
"size",
"(",
"i",
")",
"<",
"1",
")",
":",
"raise",
"Exception",
"(",
"\"Index must be one-dimensional and non-single... | 25.6 | 23 |
def get_json(self):
"""Create JSON data for AdapterConfig.
:returns: JSON data as follows:
{
"VIOMManage":{
},
"InitBoot":{
},
"UseVirtualAddresses":{
},
"BootMenuEnable":{
... | [
"def",
"get_json",
"(",
"self",
")",
":",
"viom_table",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"if",
"self",
".",
"slots",
":",
"viom_table",
"[",
"'Slots'",
"]",
"=",
"{",
"'Slot'",
":",
"[",
"s",
".",
"get_json",
"(",
")",
"for",
"s",
"in"... | 25.821429 | 16.928571 |
def verifies( self, hash, signature ):
"""Verify that signature is a valid signature of hash.
Return True if the signature is valid.
"""
# From X9.62 J.3.1.
G = self.generator
n = G.order()
r = signature.r
s = signature.s
if r < 1 or r > n-1: return False
if s < 1 or s > n-1: r... | [
"def",
"verifies",
"(",
"self",
",",
"hash",
",",
"signature",
")",
":",
"# From X9.62 J.3.1.",
"G",
"=",
"self",
".",
"generator",
"n",
"=",
"G",
".",
"order",
"(",
")",
"r",
"=",
"signature",
".",
"r",
"s",
"=",
"signature",
".",
"s",
"if",
"r",
... | 24.947368 | 14.473684 |
def main():
"""Main function creates the cvloop.functions example notebook."""
notebook = {
'cells': [
{
'cell_type': 'markdown',
'metadata': {},
'source': [
'# cvloop functions\n\n',
'This notebook shows... | [
"def",
"main",
"(",
")",
":",
"notebook",
"=",
"{",
"'cells'",
":",
"[",
"{",
"'cell_type'",
":",
"'markdown'",
",",
"'metadata'",
":",
"{",
"}",
",",
"'source'",
":",
"[",
"'# cvloop functions\\n\\n'",
",",
"'This notebook shows an overview over all cvloop '",
... | 35.403846 | 17.673077 |
def list_repos(owner=None, **kwargs):
"""List repositories in a namespace."""
client = get_repos_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
# pylint: disable=fixme
# FIXME: Compatibility code until we work out how to conflate
# the overlapping repos_list metho... | [
"def",
"list_repos",
"(",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"get_repos_api",
"(",
")",
"api_kwargs",
"=",
"{",
"}",
"api_kwargs",
".",
"update",
"(",
"utils",
".",
"get_page_kwargs",
"(",
"*",
"*",
"kwargs",
")",
... | 35.142857 | 16.821429 |
def status():
'''Display the database migrations status'''
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration:
status = green(migration['date'].strftime(DATE_FORMAT))
else:
status = yellow('Not applied... | [
"def",
"status",
"(",
")",
":",
"for",
"plugin",
",",
"package",
",",
"filename",
"in",
"available_migrations",
"(",
")",
":",
"migration",
"=",
"get_migration",
"(",
"plugin",
",",
"filename",
")",
"if",
"migration",
":",
"status",
"=",
"green",
"(",
"m... | 39.888889 | 16.111111 |
def _build_credentials_tuple(mech, source, user, passwd, extra):
"""Build and return a mechanism specific credentials tuple.
"""
user = _unicode(user) if user is not None else None
password = passwd if passwd is None else _unicode(passwd)
if mech == 'GSSAPI':
properties = extra.get('authmech... | [
"def",
"_build_credentials_tuple",
"(",
"mech",
",",
"source",
",",
"user",
",",
"passwd",
",",
"extra",
")",
":",
"user",
"=",
"_unicode",
"(",
"user",
")",
"if",
"user",
"is",
"not",
"None",
"else",
"None",
"password",
"=",
"passwd",
"if",
"passwd",
... | 50.545455 | 18.727273 |
def favorite_remove(self, post_id):
"""Remove a post from favorites (Requires login).
Parameters:
post_id (int): Where post_id is the post id.
"""
return self._get('favorites/{0}.json'.format(post_id), method='DELETE',
auth=True) | [
"def",
"favorite_remove",
"(",
"self",
",",
"post_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'favorites/{0}.json'",
".",
"format",
"(",
"post_id",
")",
",",
"method",
"=",
"'DELETE'",
",",
"auth",
"=",
"True",
")"
] | 36.5 | 15.75 |
def get_variant_label(v_conf):
"""
Generates name for variant images based settings (by variants sizes).
"""
if v_conf['MAX_SIZE'][0] is None:
return 'h{}'.format(v_conf['MAX_SIZE'][1])
if v_conf['MAX_SIZE'][1] is None:
return 'w{}'.format(v_conf['MAX_SIZE'][0])
return '{}x{}'.fo... | [
"def",
"get_variant_label",
"(",
"v_conf",
")",
":",
"if",
"v_conf",
"[",
"'MAX_SIZE'",
"]",
"[",
"0",
"]",
"is",
"None",
":",
"return",
"'h{}'",
".",
"format",
"(",
"v_conf",
"[",
"'MAX_SIZE'",
"]",
"[",
"1",
"]",
")",
"if",
"v_conf",
"[",
"'MAX_SIZ... | 37.444444 | 8.333333 |
def _on_mouse_moved(self, event):
""" mouse moved callback """
if event.modifiers() & QtCore.Qt.ControlModifier:
cursor = TextHelper(self.editor).word_under_mouse_cursor()
if (not self._cursor or
cursor.position() != self._cursor.position()):
s... | [
"def",
"_on_mouse_moved",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"modifiers",
"(",
")",
"&",
"QtCore",
".",
"Qt",
".",
"ControlModifier",
":",
"cursor",
"=",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"word_under_mouse_cursor",
... | 41.454545 | 12.727273 |
def set_bn_eval(m:nn.Module)->None:
"Set bn layers in eval mode for all recursive children of `m`."
for l in m.children():
if isinstance(l, bn_types) and not next(l.parameters()).requires_grad:
l.eval()
set_bn_eval(l) | [
"def",
"set_bn_eval",
"(",
"m",
":",
"nn",
".",
"Module",
")",
"->",
"None",
":",
"for",
"l",
"in",
"m",
".",
"children",
"(",
")",
":",
"if",
"isinstance",
"(",
"l",
",",
"bn_types",
")",
"and",
"not",
"next",
"(",
"l",
".",
"parameters",
"(",
... | 41.333333 | 20.333333 |
def makefile(self, sock, mode='r', bufsize=-1):
"""Return socket file object."""
cls = (
SSLFileobjectStreamReader
if 'r' in mode else
SSLFileobjectStreamWriter
)
if SSL and isinstance(sock, ssl_conn_type):
wrapped_socket = cls(sock, mode, ... | [
"def",
"makefile",
"(",
"self",
",",
"sock",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"-",
"1",
")",
":",
"cls",
"=",
"(",
"SSLFileobjectStreamReader",
"if",
"'r'",
"in",
"mode",
"else",
"SSLFileobjectStreamWriter",
")",
"if",
"SSL",
"and",
"isinsta... | 37.733333 | 13.333333 |
def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth,
rrup, mean, idx):
"""
Compute mean for subduction interface events, as explained in table 2,
page 67.
"""
mean[idx] = (A1 + A2 * mag + C['C1'] + C['C2'] * (A3 - mag) ** 3 +
... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"A1",
",",
"A2",
",",
"A3",
",",
"A4",
",",
"A5",
",",
"A6",
",",
"mag",
",",
"hypo_depth",
",",
"rrup",
",",
"mean",
",",
"idx",
")",
":",
"mean",
"[",
"idx",
"]",
"=",
"(",
"A1",
"+",
"A... | 45.222222 | 17.888889 |
def in_project_directory() -> bool:
"""
Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file.
"""
current_directory = os.path.realpath(os.curdir)
project_path = os.path.join(current_directory, 'cauldron.json')
return os.pat... | [
"def",
"in_project_directory",
"(",
")",
"->",
"bool",
":",
"current_directory",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"curdir",
")",
"project_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_directory",
",",
"'cauldron.json'",
... | 46 | 15.5 |
def num_in_memory(self):
"""Get number of values in memory."""
n = len(self._data) - 1
while n >= 0:
if isinstance(self._data[n], _TensorValueDiscarded):
break
n -= 1
return len(self._data) - 1 - n | [
"def",
"num_in_memory",
"(",
"self",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"_data",
")",
"-",
"1",
"while",
"n",
">=",
"0",
":",
"if",
"isinstance",
"(",
"self",
".",
"_data",
"[",
"n",
"]",
",",
"_TensorValueDiscarded",
")",
":",
"break",
... | 28.25 | 16.375 |
def _ParseHeader(self, parser_mediator, structure):
"""Parses a log header.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line ... | [
"def",
"_ParseHeader",
"(",
"self",
",",
"parser_mediator",
",",
"structure",
")",
":",
"_",
",",
"month",
",",
"day",
",",
"hours",
",",
"minutes",
",",
"seconds",
",",
"year",
"=",
"structure",
".",
"date_time",
"month",
"=",
"timelib",
".",
"MONTH_DIC... | 32.111111 | 20.6 |
def is_a_string(var, allow_none=False):
""" Returns True if var is a string (ascii or unicode)
Result py-2 py-3
----------------- ----- -----
b'bytes literal' True False
'string literal' True True
u'unicode literal' True True
Also returns True i... | [
"def",
"is_a_string",
"(",
"var",
",",
"allow_none",
"=",
"False",
")",
":",
"return",
"isinstance",
"(",
"var",
",",
"six",
".",
"string_types",
")",
"or",
"(",
"var",
"is",
"None",
"and",
"allow_none",
")"
] | 37.833333 | 14.75 |
def timetree_likelihood(self):
'''
Return the likelihood of the data given the current branch length in the tree
'''
LH = 0
for node in self.tree.find_clades(order='preorder'): # sum the likelihood contributions of all branches
if node.up is None: # root node
... | [
"def",
"timetree_likelihood",
"(",
"self",
")",
":",
"LH",
"=",
"0",
"for",
"node",
"in",
"self",
".",
"tree",
".",
"find_clades",
"(",
"order",
"=",
"'preorder'",
")",
":",
"# sum the likelihood contributions of all branches",
"if",
"node",
".",
"up",
"is",
... | 41.642857 | 29.214286 |
def _make_parameters(self):
"""Converts a list of Parameters into DEAP format."""
self.value_means = []
self.value_ranges = []
self.arrangement = []
self.variable_parameters = []
current_var = 0
for parameter in self.parameters:
if parameter.type == Pa... | [
"def",
"_make_parameters",
"(",
"self",
")",
":",
"self",
".",
"value_means",
"=",
"[",
"]",
"self",
".",
"value_ranges",
"=",
"[",
"]",
"self",
".",
"arrangement",
"=",
"[",
"]",
"self",
".",
"variable_parameters",
"=",
"[",
"]",
"current_var",
"=",
"... | 46.076923 | 14.884615 |
def list_envs():
"""List all environments"""
for env in lib.get_environments():
margin_left = lib.get_margin(len(env['name']))
print("{0}{1}{2}".format(
env['name'], margin_left,
env.get('description', '(no description)'))) | [
"def",
"list_envs",
"(",
")",
":",
"for",
"env",
"in",
"lib",
".",
"get_environments",
"(",
")",
":",
"margin_left",
"=",
"lib",
".",
"get_margin",
"(",
"len",
"(",
"env",
"[",
"'name'",
"]",
")",
")",
"print",
"(",
"\"{0}{1}{2}\"",
".",
"format",
"(... | 37.857143 | 9.428571 |
def get_occupation_updates(self, offset=0, count=1000):
""" Returns <count> occupation updates from <offset>.
An occupation update is a quadrupel
(pc, source, timestamp, occupation) """
ret = []
c = self.conn.cursor()
for pc_id, source_id, datetime, ... | [
"def",
"get_occupation_updates",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"count",
"=",
"1000",
")",
":",
"ret",
"=",
"[",
"]",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"for",
"pc_id",
",",
"source_id",
",",
"datetime",
",",
"occup... | 41 | 12.352941 |
def print_help(self, prog_name, subcommand):
"""
Prints parser's help.
:param prog_name: vcs main script name
:param subcommand: command name
"""
parser = self.get_parser(prog_name, subcommand)
parser.print_help() | [
"def",
"print_help",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
")",
":",
"parser",
"=",
"self",
".",
"get_parser",
"(",
"prog_name",
",",
"subcommand",
")",
"parser",
".",
"print_help",
"(",
")"
] | 29.111111 | 10 |
def _flip_feature(self, feature, parent_len):
'''Adjust a feature's location when flipping DNA.
:param feature: The feature to flip.
:type feature: coral.Feature
:param parent_len: The length of the sequence to which the feature belongs.
:type parent_len: int
'''
copy = feature.copy()
... | [
"def",
"_flip_feature",
"(",
"self",
",",
"feature",
",",
"parent_len",
")",
":",
"copy",
"=",
"feature",
".",
"copy",
"(",
")",
"# Put on the other strand",
"if",
"copy",
".",
"strand",
"==",
"0",
":",
"copy",
".",
"strand",
"=",
"1",
"else",
":",
"co... | 31.25 | 18.25 |
def set_objective(self, expression):
"""Set linear objective of problem"""
if isinstance(expression, numbers.Number):
# Allow expressions with no variables as objective,
# represented as a number
expression = Expression()
self._p.set_linear_objective(
... | [
"def",
"set_objective",
"(",
"self",
",",
"expression",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"numbers",
".",
"Number",
")",
":",
"# Allow expressions with no variables as objective,",
"# represented as a number",
"expression",
"=",
"Expression",
"(",
... | 37.090909 | 13.545455 |
def mine_urls(urls, params=None, callback=None, **kwargs):
"""Concurrently retrieve URLs.
:param urls: A set of URLs to concurrently retrieve.
:type urls: iterable
:param params: (optional) The URL parameters to send with each
request.
:type params: dict
:param callback: (o... | [
"def",
"mine_urls",
"(",
"urls",
",",
"params",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"miner",
"=",
"Miner",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"miner",
".",
"loop",
".",
"add_signal_handler",
"(",
"si... | 33.904762 | 23.952381 |
def _reverse_dependencies(self, cache_keys):
"""
Returns a lookup table of reverse dependencies for all the given cache keys.
Example input:
[('pep8', '1.5.7'),
('flake8', '2.4.0'),
('mccabe', '0.3'),
('pyflakes', '0.8.1')]
Example ou... | [
"def",
"_reverse_dependencies",
"(",
"self",
",",
"cache_keys",
")",
":",
"# First, collect all the dependencies into a sequence of (parent, child) tuples, like [('flake8', 'pep8'),",
"# ('flake8', 'mccabe'), ...]",
"return",
"lookup_table",
"(",
"(",
"key_from_req",
"(",
"Requiremen... | 34.375 | 21.875 |
def getConfig(option, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar, responseMimeType='application/json',
services={'mime-types': '/mime-types', 'detectors': '/detectors', 'parsers': '/parsers/details'}):
'''
Get the configuration of the Tika Server (parsers, detector... | [
"def",
"getConfig",
"(",
"option",
",",
"serverEndpoint",
"=",
"ServerEndpoint",
",",
"verbose",
"=",
"Verbose",
",",
"tikaServerJar",
"=",
"TikaServerJar",
",",
"responseMimeType",
"=",
"'application/json'",
",",
"services",
"=",
"{",
"'mime-types'",
":",
"'/mime... | 47.117647 | 34.058824 |
def nbytes_stored(self):
"""The total number of stored bytes of data for the array. This
includes storage required for configuration metadata and user
attributes."""
m = getsize(self._store, self._path)
if self._chunk_store is None:
return m
else:
... | [
"def",
"nbytes_stored",
"(",
"self",
")",
":",
"m",
"=",
"getsize",
"(",
"self",
".",
"_store",
",",
"self",
".",
"_path",
")",
"if",
"self",
".",
"_chunk_store",
"is",
"None",
":",
"return",
"m",
"else",
":",
"n",
"=",
"getsize",
"(",
"self",
".",... | 34.923077 | 13.307692 |
def global_confirm(question, default=True):
"""Shows a confirmation that applies to all hosts
by temporarily disabling parallel execution in Fabric
"""
if env.abort_on_prompts:
return True
original_parallel = env.parallel
env.parallel = False
result = confirm(question, default)
e... | [
"def",
"global_confirm",
"(",
"question",
",",
"default",
"=",
"True",
")",
":",
"if",
"env",
".",
"abort_on_prompts",
":",
"return",
"True",
"original_parallel",
"=",
"env",
".",
"parallel",
"env",
".",
"parallel",
"=",
"False",
"result",
"=",
"confirm",
... | 32.636364 | 9.181818 |
def accepts(**schemas):
"""Create a decorator for validating function parameters.
Example::
@accepts(a="number", body={"+field_ids": [int], "is_ok": bool})
def f(a, body):
print (a, body["field_ids"], body.get("is_ok"))
:param schemas: The schema for validating a given paramet... | [
"def",
"accepts",
"(",
"*",
"*",
"schemas",
")",
":",
"validate",
"=",
"parse",
"(",
"schemas",
")",
".",
"validate",
"@",
"decorator",
"def",
"validating",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"validate",
"(",
"inspect",... | 30.277778 | 21.166667 |
def _set_op(self, node):
"""
Translate a set operator node into SQLQuery.
:param node: a treebrd node
:return: a SQLQuery object for the tree rooted at node
"""
select_block = str(node.attributes)
from_block = '({left} {operator} ALL {right}) AS {name}'.format(
... | [
"def",
"_set_op",
"(",
"self",
",",
"node",
")",
":",
"select_block",
"=",
"str",
"(",
"node",
".",
"attributes",
")",
"from_block",
"=",
"'({left} {operator} ALL {right}) AS {name}'",
".",
"format",
"(",
"left",
"=",
"self",
".",
"translate",
"(",
"node",
"... | 47.75 | 16.083333 |
def _get_file_content(source):
"""Return a tuple, each value being a line of the source file.
Remove empty lines and comments (lines starting with a '#').
"""
filepath = os.path.join('siglists', source + '.txt')
lines = []
with resource_stream(__name__, filepath) as f:
for i, line in ... | [
"def",
"_get_file_content",
"(",
"source",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'siglists'",
",",
"source",
"+",
"'.txt'",
")",
"lines",
"=",
"[",
"]",
"with",
"resource_stream",
"(",
"__name__",
",",
"filepath",
")",
"as",
... | 29.15625 | 18.875 |
def rmon_alarm_entry_alarm_rising_event_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon")
alarm_entry = ET.SubElement(rmon, "alarm-entry")
alarm_index_key = ET.Su... | [
"def",
"rmon_alarm_entry_alarm_rising_event_index",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"rmon",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"rmon\"",
",",
"xmlns",
"=",
"\"urn... | 50.846154 | 21.846154 |
def moments_XXXY(X, Y, remove_mean=False, symmetrize=False, weights=None,
modify_data=False, sparse_mode='auto', sparse_tol=0.0,
column_selection=None, diag_only=False):
""" Computes the first two unnormalized moments of X and Y
If symmetrize is False, computes
.. math:
... | [
"def",
"moments_XXXY",
"(",
"X",
",",
"Y",
",",
"remove_mean",
"=",
"False",
",",
"symmetrize",
"=",
"False",
",",
"weights",
"=",
"None",
",",
"modify_data",
"=",
"False",
",",
"sparse_mode",
"=",
"'auto'",
",",
"sparse_tol",
"=",
"0.0",
",",
"column_se... | 47.255319 | 27.29078 |
def from_file(filename="feff.inp"):
"""
Creates a Feff_tag dictionary from a PARAMETER or feff.inp file.
Args:
filename: Filename for either PARAMETER or feff.inp file
Returns:
Feff_tag object
"""
with zopen(filename, "rt") as f:
line... | [
"def",
"from_file",
"(",
"filename",
"=",
"\"feff.inp\"",
")",
":",
"with",
"zopen",
"(",
"filename",
",",
"\"rt\"",
")",
"as",
"f",
":",
"lines",
"=",
"list",
"(",
"clean_lines",
"(",
"f",
".",
"readlines",
"(",
")",
")",
")",
"params",
"=",
"{",
... | 36.695652 | 16.478261 |
def run(self):
"""Run the process."""
environment = os.environ.copy()
# necessary for reading from processes that don't flush
# stdout automatically
environment["PYTHONUNBUFFERED"] = "1"
self.proc = Popen(self.command, env=environment, stdout=PIPE, stderr=PIPE)
Pr... | [
"def",
"run",
"(",
"self",
")",
":",
"environment",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"# necessary for reading from processes that don't flush",
"# stdout automatically",
"environment",
"[",
"\"PYTHONUNBUFFERED\"",
"]",
"=",
"\"1\"",
"self",
".",
"pr... | 42.625 | 13.625 |
def isEnabled(self):
"""
Returns whether or not this connection is enabled.
:sa disableWithLayer
:return <bool>
"""
if self._disableWithLayer and self._layer:
lenabled = self._layer.isEnabled()
elif self._inputNode and self._o... | [
"def",
"isEnabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"_disableWithLayer",
"and",
"self",
".",
"_layer",
":",
"lenabled",
"=",
"self",
".",
"_layer",
".",
"isEnabled",
"(",
")",
"elif",
"self",
".",
"_inputNode",
"and",
"self",
".",
"_outputNode"... | 30.25 | 17.125 |
def replace(needle, with_=None, in_=None):
"""Replace occurrences of string(s) with other string(s) in (a) string(s).
Unlike the built in :meth:`str.replace` method, this function provides
clean API that clearly distinguishes the "needle" (string to replace),
the replacement string, and the target stri... | [
"def",
"replace",
"(",
"needle",
",",
"with_",
"=",
"None",
",",
"in_",
"=",
"None",
")",
":",
"if",
"needle",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"replacement needle cannot be None\"",
")",
"if",
"not",
"needle",
":",
"raise",
"ValueError",
"(... | 38 | 21.945455 |
def _set_capabilities(self, v, load=False):
"""
Setter method for capabilities, mapped from YANG variable /capabilities (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_capabilities is considered as a private
method. Backends looking to populate this varia... | [
"def",
"_set_capabilities",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 75.818182 | 34.727273 |
def complete(self, query, current_url):
"""Called to interpret the server's response to an OpenID
request. It is called in step 4 of the flow described in the
consumer overview.
@param query: A dictionary of the query parameters for this
HTTP request.
@param current... | [
"def",
"complete",
"(",
"self",
",",
"query",
",",
"current_url",
")",
":",
"endpoint",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"_token_key",
")",
"message",
"=",
"Message",
".",
"fromPostArgs",
"(",
"query",
")",
"response",
"=",
"s... | 39.543478 | 22.630435 |
def decide(self, accepts, context_aware=False):
""" Returns what (mimetype,format) the client wants to receive
Parses the given Accept header and picks the best one that
we know how to output
Returns (mimetype, format)
An empty Accept will default to rdf+xml
An Accept with */* use rdf+xm... | [
"def",
"decide",
"(",
"self",
",",
"accepts",
",",
"context_aware",
"=",
"False",
")",
":",
"mimetype",
"=",
"self",
".",
"decide_mimetype",
"(",
"accepts",
",",
"context_aware",
")",
"# return what format to serialize as",
"if",
"mimetype",
"is",
"not",
"None",... | 43.588235 | 14.588235 |
def execute(opts, data, func, args, kwargs):
'''
Splay a salt function call execution time across minions over
a number of seconds (default: 300)
.. note::
You *probably* want to use --async here and look up the job results later.
If you're dead set on getting the output from the CLI co... | [
"def",
"execute",
"(",
"opts",
",",
"data",
",",
"func",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"'executor_opts'",
"in",
"data",
"and",
"'splaytime'",
"in",
"data",
"[",
"'executor_opts'",
"]",
":",
"splaytime",
"=",
"data",
"[",
"'executor_opts'",
... | 39.25 | 29.361111 |
def get_matrix(self):
"""Return a copy of the current transformation matrix (CTM)."""
matrix = Matrix()
cairo.cairo_get_matrix(self._pointer, matrix._pointer)
self._check_status()
return matrix | [
"def",
"get_matrix",
"(",
"self",
")",
":",
"matrix",
"=",
"Matrix",
"(",
")",
"cairo",
".",
"cairo_get_matrix",
"(",
"self",
".",
"_pointer",
",",
"matrix",
".",
"_pointer",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"matrix"
] | 38 | 14.5 |
def add_logger(self, cb, level='NORMAL', filters='ALL'):
'''Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component... | [
"def",
"add_logger",
"(",
"self",
",",
"cb",
",",
"level",
"=",
"'NORMAL'",
",",
"filters",
"=",
"'ALL'",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"obs",
"=",
"sdo",
".",
"RTCLogger",
"(",
"self",
",",
"cb",
")",
"uuid_val",
"=",
"uuid",
".",
... | 48.53125 | 19.65625 |
def rank_within_group_by(self, group_by_cols, sort_cols, ascending=[], new_col_name="New_Rank_column", sort_cols_sorted=False):
"""
This function will add a new column rank where the ranking is produced as follows:
1. sorts the H2OFrame by columns sorted in by columns specified in group_by_cols... | [
"def",
"rank_within_group_by",
"(",
"self",
",",
"group_by_cols",
",",
"sort_cols",
",",
"ascending",
"=",
"[",
"]",
",",
"new_col_name",
"=",
"\"New_Rank_column\"",
",",
"sort_cols_sorted",
"=",
"False",
")",
":",
"assert_is_type",
"(",
"group_by_cols",
",",
"s... | 77.735537 | 48.132231 |
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
jid='',
full_return=False,
kwarg=None,
**kwargs):
'''
Synchronously execute a command on targeted minions
... | [
"def",
"cmd",
"(",
"self",
",",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"timeout",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"jid",
"=",
"''",
",",
"full_return",
"=",
"False",
",",
"kwarg",
"=",
"None"... | 37.218543 | 21.827815 |
def estimate_parameters_rippe(
self, max_dist_kb, size_bin_kb, display_graph
):
"""
estimation by least square optimization of Rippe parameters on the
experimental data
:param max_dist_kb:
:param size_bin_kb:
"""
logger.info("estimation of the paramete... | [
"def",
"estimate_parameters_rippe",
"(",
"self",
",",
"max_dist_kb",
",",
"size_bin_kb",
",",
"display_graph",
")",
":",
"logger",
".",
"info",
"(",
"\"estimation of the parameters of the model\"",
")",
"self",
".",
"bins",
"=",
"np",
".",
"arange",
"(",
"size_bin... | 41.965318 | 17.433526 |
def cd(self, remote):
""" Change working directory on server """
try:
self.conn.cwd(remote)
except Exception:
return False
else:
return self.pwd() | [
"def",
"cd",
"(",
"self",
",",
"remote",
")",
":",
"try",
":",
"self",
".",
"conn",
".",
"cwd",
"(",
"remote",
")",
"except",
"Exception",
":",
"return",
"False",
"else",
":",
"return",
"self",
".",
"pwd",
"(",
")"
] | 25.875 | 15.375 |
def _generateMetricSpecs(options):
""" Generates the Metrics for a given InferenceType
Parameters:
-------------------------------------------------------------------------
options: ExpGenerator options
retval: (metricsList, optimizeMetricLabel)
metricsList: list of metric string names
... | [
"def",
"_generateMetricSpecs",
"(",
"options",
")",
":",
"inferenceType",
"=",
"options",
"[",
"'inferenceType'",
"]",
"inferenceArgs",
"=",
"options",
"[",
"'inferenceArgs'",
"]",
"predictionSteps",
"=",
"inferenceArgs",
"[",
"'predictionSteps'",
"]",
"metricWindow",... | 45.472906 | 22.20197 |
def account_id(self, value):
"""The account_id property.
Args:
value (string). the property value.
"""
if value == self._defaults['ai.user.accountId'] and 'ai.user.accountId' in self._values:
del self._values['ai.user.accountId']
else:
... | [
"def",
"account_id",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'ai.user.accountId'",
"]",
"and",
"'ai.user.accountId'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'ai.user.accountId... | 35.3 | 18.3 |
def latitude(self, latitude):
"""Setter for latiutde."""
if not (-90 <= latitude <= 90):
raise ValueError('latitude was {}, but has to be in [-90, 90]'
.format(latitude))
self._latitude = latitude | [
"def",
"latitude",
"(",
"self",
",",
"latitude",
")",
":",
"if",
"not",
"(",
"-",
"90",
"<=",
"latitude",
"<=",
"90",
")",
":",
"raise",
"ValueError",
"(",
"'latitude was {}, but has to be in [-90, 90]'",
".",
"format",
"(",
"latitude",
")",
")",
"self",
"... | 42.666667 | 10 |
def _init_iter(self, X, y, is_train):
"""Initialize the iterator given input."""
if isinstance(X, (np.ndarray, nd.NDArray)):
if y is None:
if is_train:
raise ValueError('y must be specified when X is numpy.ndarray')
else:
... | [
"def",
"_init_iter",
"(",
"self",
",",
"X",
",",
"y",
",",
"is_train",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"(",
"np",
".",
"ndarray",
",",
"nd",
".",
"NDArray",
")",
")",
":",
"if",
"y",
"is",
"None",
":",
"if",
"is_train",
":",
"raise... | 51.25 | 22 |
def ginga_to_matplotlib_cmap(cm, name=None):
"""Convert Ginga colormap to matplotlib's."""
if name is None:
name = cm.name
from matplotlib.colors import ListedColormap
carr = np.asarray(cm.clst)
mpl_cm = ListedColormap(carr, name=name, N=len(carr))
return mpl_cm | [
"def",
"ginga_to_matplotlib_cmap",
"(",
"cm",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"cm",
".",
"name",
"from",
"matplotlib",
".",
"colors",
"import",
"ListedColormap",
"carr",
"=",
"np",
".",
"asarray",
"(",
... | 35.875 | 12.5 |
def apply(self, fn, dtype=None, skip_na=True, seed=None):
"""
apply(fn, dtype=None, skip_na=True, seed=None)
Transform each element of the SArray by a given function. The result
SArray is of type ``dtype``. ``fn`` should be a function that returns
exactly one value which can be ... | [
"def",
"apply",
"(",
"self",
",",
"fn",
",",
"dtype",
"=",
"None",
",",
"skip_na",
"=",
"True",
",",
"seed",
"=",
"None",
")",
":",
"assert",
"callable",
"(",
"fn",
")",
",",
"\"Input function must be callable.\"",
"dryrun",
"=",
"[",
"fn",
"(",
"i",
... | 33.15 | 24.85 |
def get_jobs(self, project, **params):
"""
Gets jobs from project, filtered by parameters
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results
"""
return self._get_json_list(self.JOBS_ENDPOINT, project, **params) | [
"def",
"get_jobs",
"(",
"self",
",",
"project",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"_get_json_list",
"(",
"self",
".",
"JOBS_ENDPOINT",
",",
"project",
",",
"*",
"*",
"params",
")"
] | 39 | 16.75 |
def hello_rivescript():
"""Receive an inbound SMS and send a reply from RiveScript."""
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
reply = bot.reply(from_number,... | [
"def",
"hello_rivescript",
"(",
")",
":",
"from_number",
"=",
"request",
".",
"values",
".",
"get",
"(",
"\"From\"",
",",
"\"unknown\"",
")",
"message",
"=",
"request",
".",
"values",
".",
"get",
"(",
"\"Body\"",
")",
"reply",
"=",
"\"(Internal error)\"",
... | 28.066667 | 17.133333 |
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
... | [
"def",
"delete",
"(",
"Bucket",
",",
"MFA",
"=",
"None",
",",
"RequestPayer",
"=",
"None",
",",
"Force",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
"... | 32.72 | 26.4 |
def _process_tensor_event(self, event, thresholds):
"""Converts a TensorEvent into a dict that encapsulates information on it.
Args:
event: The TensorEvent to convert.
thresholds: An array of floats that ranges from 0 to 1 (in that
direction and inclusive of 0 and 1).
Returns:
A ... | [
"def",
"_process_tensor_event",
"(",
"self",
",",
"event",
",",
"thresholds",
")",
":",
"return",
"self",
".",
"_make_pr_entry",
"(",
"event",
".",
"step",
",",
"event",
".",
"wall_time",
",",
"tensor_util",
".",
"make_ndarray",
"(",
"event",
".",
"tensor_pr... | 32.0625 | 17.5 |
def convert(self, inp):
"""Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representin... | [
"def",
"convert",
"(",
"self",
",",
"inp",
")",
":",
"inp",
"=",
"self",
".",
"_preprocess",
"(",
"inp",
")",
"n",
"=",
"NumberService",
"(",
")",
".",
"longestNumber",
"(",
"inp",
")",
"units",
"=",
"self",
".",
"extractUnits",
"(",
"inp",
")",
"#... | 29.681818 | 19.818182 |
def eth_getStorageAt(self, address, position):
"""Get account storage data at position.
:param address:
:param position:
:return:
"""
account = self.reader._get_account(address)
return _encode_hex(
utils.zpad(utils.encode_int(account.get_storage_data(... | [
"def",
"eth_getStorageAt",
"(",
"self",
",",
"address",
",",
"position",
")",
":",
"account",
"=",
"self",
".",
"reader",
".",
"_get_account",
"(",
"address",
")",
"return",
"_encode_hex",
"(",
"utils",
".",
"zpad",
"(",
"utils",
".",
"encode_int",
"(",
... | 30.454545 | 18 |
def generate_transition_matrix(g, seed=None):
"""Generates a random transition matrix for the graph ``g``.
Parameters
----------
g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc.
Any object that :any:`DiGraph<networkx.DiGraph>` accepts.
seed : int (optional)
An integer... | [
"def",
"generate_transition_matrix",
"(",
"g",
",",
"seed",
"=",
"None",
")",
":",
"g",
"=",
"_test_graph",
"(",
"g",
")",
"if",
"isinstance",
"(",
"seed",
",",
"numbers",
".",
"Integral",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",... | 29.975 | 20.7 |
async def _send_rtcp_nack(self, media_ssrc, lost):
"""
Send an RTCP packet to report missing RTP packets.
"""
if self.__rtcp_ssrc is not None:
packet = RtcpRtpfbPacket(
fmt=RTCP_RTPFB_NACK, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc)
packet.lost ... | [
"async",
"def",
"_send_rtcp_nack",
"(",
"self",
",",
"media_ssrc",
",",
"lost",
")",
":",
"if",
"self",
".",
"__rtcp_ssrc",
"is",
"not",
"None",
":",
"packet",
"=",
"RtcpRtpfbPacket",
"(",
"fmt",
"=",
"RTCP_RTPFB_NACK",
",",
"ssrc",
"=",
"self",
".",
"__... | 40 | 9.333333 |
def searchForMessageIDs(self, query, offset=0, limit=5, thread_id=None):
"""
Find and get message IDs by query
:param query: Text to search for
:param offset: Number of messages to skip
:param limit: Max. number of messages to retrieve
:param thread_id: User/Group ID to ... | [
"def",
"searchForMessageIDs",
"(",
"self",
",",
"query",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"5",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"dat... | 35.419355 | 17.290323 |
def calculate_size(username, password, uuid, owner_uuid, is_owner_connection, client_type, serialization_version, client_hazelcast_version):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(username)
data_size += calculate_size_str(password)
data_size += BOOLE... | [
"def",
"calculate_size",
"(",
"username",
",",
"password",
",",
"uuid",
",",
"owner_uuid",
",",
"is_owner_connection",
",",
"client_type",
",",
"serialization_version",
",",
"client_hazelcast_version",
")",
":",
"data_size",
"=",
"0",
"data_size",
"+=",
"calculate_s... | 45.0625 | 14.6875 |
def calculate_subgraph_edge_overlap(
graph: BELGraph,
annotation: str = 'Subgraph'
) -> Tuple[
Mapping[str, EdgeSet],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, float]],
]:
"""Build a DatafFame to show the overlap between diffe... | [
"def",
"calculate_subgraph_edge_overlap",
"(",
"graph",
":",
"BELGraph",
",",
"annotation",
":",
"str",
"=",
"'Subgraph'",
")",
"->",
"Tuple",
"[",
"Mapping",
"[",
"str",
",",
"EdgeSet",
"]",
",",
"Mapping",
"[",
"str",
",",
"Mapping",
"[",
"str",
",",
"... | 38.108108 | 21.216216 |
def _trapped_signals(self, client):
"""A contextmanager that handles SIGINT (control-c) and SIGQUIT (control-\\) remotely."""
signal_handler = PailgunClientSignalHandler(
client,
timeout=self._bootstrap_options.for_global_scope().pantsd_pailgun_quit_timeout)
with ExceptionSink.trapped_signals(si... | [
"def",
"_trapped_signals",
"(",
"self",
",",
"client",
")",
":",
"signal_handler",
"=",
"PailgunClientSignalHandler",
"(",
"client",
",",
"timeout",
"=",
"self",
".",
"_bootstrap_options",
".",
"for_global_scope",
"(",
")",
".",
"pantsd_pailgun_quit_timeout",
")",
... | 48.571429 | 18.428571 |
def _raise_decomposition_errors(uvw, antenna1, antenna2,
chunks, ant_uvw, max_err):
""" Raises informative exception for an invalid decomposition """
start = 0
problem_str = []
for ci, chunk in enumerate(chunks):
end = start + chunk
ant1 = antenna1[sta... | [
"def",
"_raise_decomposition_errors",
"(",
"uvw",
",",
"antenna1",
",",
"antenna2",
",",
"chunks",
",",
"ant_uvw",
",",
"max_err",
")",
":",
"start",
"=",
"0",
"problem_str",
"=",
"[",
"]",
"for",
"ci",
",",
"chunk",
"in",
"enumerate",
"(",
"chunks",
")"... | 32.38 | 19.76 |
def get_origins(self, account_id, **kwargs):
"""Retrieves list of origin pull mappings for a specified CDN account.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask... | [
"def",
"get_origins",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"account",
".",
"getOriginPullMappingInformation",
"(",
"id",
"=",
"account_id",
",",
"*",
"*",
"kwargs",
")"
] | 47 | 22.7 |
def posterior_chromatogram_hypotheses_fast(experiment, prior_chrom_null):
""" Compute posterior probabilities for each chromatogram
For each chromatogram (each group_id / peptide precursor), all hypothesis of all peaks
being correct (and all others false) as well as the h0 (all peaks are
false) are com... | [
"def",
"posterior_chromatogram_hypotheses_fast",
"(",
"experiment",
",",
"prior_chrom_null",
")",
":",
"tg_ids",
"=",
"experiment",
".",
"df",
".",
"tg_num_id",
".",
"values",
"pp_values",
"=",
"1",
"-",
"experiment",
".",
"df",
"[",
"\"pep\"",
"]",
".",
"valu... | 36.222222 | 24.333333 |
def run_tasks(self):
'''
Runs all assigned task in separate green threads. If the task should not be run, schedule it
'''
pool = Pool(len(self.tasks))
for task in self.tasks:
# Launch a green thread to schedule the task
# A task will be managed by 2 green ... | [
"def",
"run_tasks",
"(",
"self",
")",
":",
"pool",
"=",
"Pool",
"(",
"len",
"(",
"self",
".",
"tasks",
")",
")",
"for",
"task",
"in",
"self",
".",
"tasks",
":",
"# Launch a green thread to schedule the task",
"# A task will be managed by 2 green thread: execution th... | 41.6 | 24.4 |
def forward_on_instances(self,
instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]:
"""
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into
arrays using this model's :class:`Vocabulary`, passes those arrays through
:f... | [
"def",
"forward_on_instances",
"(",
"self",
",",
"instances",
":",
"List",
"[",
"Instance",
"]",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"numpy",
".",
"ndarray",
"]",
"]",
":",
"batch_size",
"=",
"len",
"(",
"instances",
")",
"with",
"torch",
... | 50.191489 | 24.446809 |
def get_ticks_from_axis_limits(self, multiple=1):
"""
Taking self._axis_limits and self._boundary_scale get the scaled
ticks for all three axes and store them in self._ticks under the
keys 'b' for bottom, 'l' for left and 'r' for right axes.
"""
for k in ['b', 'l', 'r']:
... | [
"def",
"get_ticks_from_axis_limits",
"(",
"self",
",",
"multiple",
"=",
"1",
")",
":",
"for",
"k",
"in",
"[",
"'b'",
",",
"'l'",
",",
"'r'",
"]",
":",
"self",
".",
"_ticks",
"[",
"k",
"]",
"=",
"numpy",
".",
"linspace",
"(",
"self",
".",
"_axis_lim... | 43.083333 | 12.083333 |
def update(self, settings):
"""
Update object attributes from given settings
Args:
settings (dict): Dictionnary of elements to update settings.
Returns:
dict: Dictionnary of all current saved settings.
"""
settings = self.clean(settings)
... | [
"def",
"update",
"(",
"self",
",",
"settings",
")",
":",
"settings",
"=",
"self",
".",
"clean",
"(",
"settings",
")",
"# Update internal dict",
"self",
".",
"_settings",
".",
"update",
"(",
"settings",
")",
"# Push every setting items as class object attributes",
... | 24.75 | 20.85 |
def process_task(f):
"""Decorator to (optionally) run function in a process."""
sig = inspect.signature(f)
@wraps(f)
def wrapper(*args, **kwargs):
# get bound arguments for call
ba = sig.bind_partial(*args, **kwargs)
# when process is specified, remove from args and use to execu... | [
"def",
"process_task",
"(",
"f",
")",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"f",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# get bound arguments for call",
"ba",
"=",
"sig",... | 38 | 15.9 |
def get_resource(self, resource_wrapper=None):
"""
Returns a ``Resource`` instance.
:param resource_wrapper: A Resource subclass.
:return: A ``Resource`` instance.
:raises PoolEmptyError: If attempt to get resource fails or times
out.
"""
rtracker = ... | [
"def",
"get_resource",
"(",
"self",
",",
"resource_wrapper",
"=",
"None",
")",
":",
"rtracker",
"=",
"None",
"if",
"resource_wrapper",
"is",
"None",
":",
"resource_wrapper",
"=",
"self",
".",
"_resource_wrapper",
"if",
"self",
".",
"empty",
"(",
")",
":",
... | 33.283333 | 19.916667 |
def move_tmp_log(logger):
""" Move the temporary log file to the MultiQC data directory
if it exists. """
try:
# https://stackoverflow.com/questions/15435652/python-does-not-release-filehandles-to-logfile
logging.shutdown()
shutil.move(log_tmp_fn, os.path.join(config.data_dir, 'mult... | [
"def",
"move_tmp_log",
"(",
"logger",
")",
":",
"try",
":",
"# https://stackoverflow.com/questions/15435652/python-does-not-release-filehandles-to-logfile",
"logging",
".",
"shutdown",
"(",
")",
"shutil",
".",
"move",
"(",
"log_tmp_fn",
",",
"os",
".",
"path",
".",
"j... | 39.272727 | 22.181818 |
def geocoding(ctx, query, forward, include_headers, lat, lon,
place_type, output, dataset, country, bbox, features, limit):
"""This command returns places matching an address (forward mode) or
places matching coordinates (reverse mode).
In forward (the default) mode the query argument shall b... | [
"def",
"geocoding",
"(",
"ctx",
",",
"query",
",",
"forward",
",",
"include_headers",
",",
"lat",
",",
"lon",
",",
"place_type",
",",
"output",
",",
"dataset",
",",
"country",
",",
"bbox",
",",
"features",
",",
"limit",
")",
":",
"access_token",
"=",
"... | 38.114286 | 19.785714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.