text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def cancel(self, job_ids):
"""Cancel jobs specified by a list of job ids.
Parameters
----------
list of str
List of identifiers of jobs which should be canceled.
Returns
-------
list of bool
For each entry, True if the cancel operation is... | [
"def",
"cancel",
"(",
"self",
",",
"job_ids",
")",
":",
"for",
"job_id",
"in",
"job_ids",
":",
"try",
":",
"self",
".",
"deployer",
".",
"destroy",
"(",
"self",
".",
"resources",
".",
"get",
"(",
"job_id",
")",
")",
"return",
"True",
"except",
"e",
... | 30.428571 | 21.238095 |
def generator(ngf, nc, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12, z_dim=100, activation='sigmoid'):
'''The genrator is a CNN which takes 100 dimensional embedding as input
and reconstructs the input image given to the encoder
'''
BatchNorm = mx.sym.BatchNorm
rand = mx.sym.Variable('rand')
... | [
"def",
"generator",
"(",
"ngf",
",",
"nc",
",",
"no_bias",
"=",
"True",
",",
"fix_gamma",
"=",
"True",
",",
"eps",
"=",
"1e-5",
"+",
"1e-12",
",",
"z_dim",
"=",
"100",
",",
"activation",
"=",
"'sigmoid'",
")",
":",
"BatchNorm",
"=",
"mx",
".",
"sym... | 57 | 41.275862 |
def adjustChildren(self, delta, secs=False):
"""
Shifts the children for this item by the inputed number of days.
:param delta | <int>
"""
if self.adjustmentsBlocked('children'):
return
if self.itemStyle() != self.ItemStyle.... | [
"def",
"adjustChildren",
"(",
"self",
",",
"delta",
",",
"secs",
"=",
"False",
")",
":",
"if",
"self",
".",
"adjustmentsBlocked",
"(",
"'children'",
")",
":",
"return",
"if",
"self",
".",
"itemStyle",
"(",
")",
"!=",
"self",
".",
"ItemStyle",
".",
"Gro... | 33.653846 | 15.346154 |
def outer_left_join(self, join_streamlet, window_config, join_function):
"""Return a new Streamlet by left join_streamlet with this streamlet
"""
from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt
join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_LEFT, window_config,
... | [
"def",
"outer_left_join",
"(",
"self",
",",
"join_streamlet",
",",
"window_config",
",",
"join_function",
")",
":",
"from",
"heronpy",
".",
"streamlet",
".",
"impl",
".",
"joinbolt",
"import",
"JoinStreamlet",
",",
"JoinBolt",
"join_streamlet_result",
"=",
"JoinSt... | 55.888889 | 17.777778 |
def _postprocess(self, x, out=None):
"""Return the post-processed version of ``x``.
C2C: use ``tmp_f`` (C2C operation)
R2C: use ``tmp_f`` (C2C operation)
HALFC: use ``tmp_f`` (C2C operation)
The result is stored in ``out`` if given, otherwise in
a temporary or a new arr... | [
"def",
"_postprocess",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"if",
"self",
".",
"domain",
".",
"field",
"==",
"ComplexNumbers",
"(",
")",
":",
"out",
"=",
"self",
".",
"_tmp_r",
"if",
"self",
".... | 40.052632 | 15.578947 |
def migrateProvPre010(self, newslab):
'''
Check for any pre-010 provstacks and migrate those to the new slab.
'''
did_migrate = self._migrate_db_pre010('prov', newslab)
if not did_migrate:
return
self._migrate_db_pre010('provs', newslab) | [
"def",
"migrateProvPre010",
"(",
"self",
",",
"newslab",
")",
":",
"did_migrate",
"=",
"self",
".",
"_migrate_db_pre010",
"(",
"'prov'",
",",
"newslab",
")",
"if",
"not",
"did_migrate",
":",
"return",
"self",
".",
"_migrate_db_pre010",
"(",
"'provs'",
",",
"... | 32.222222 | 22.444444 |
def features(sentence, i):
"""Features for i'th token in sentence.
Currently baseline named-entity recognition features, but these can
easily be changed to do POS tagging or chunking.
"""
word = sentence[i]
yield "word:{}" + word.lower()
if word[0].isupper():
yield "CAP"
if ... | [
"def",
"features",
"(",
"sentence",
",",
"i",
")",
":",
"word",
"=",
"sentence",
"[",
"i",
"]",
"yield",
"\"word:{}\"",
"+",
"word",
".",
"lower",
"(",
")",
"if",
"word",
"[",
"0",
"]",
".",
"isupper",
"(",
")",
":",
"yield",
"\"CAP\"",
"if",
"i"... | 27.409091 | 19.863636 |
def setup(self):
"""Method runs the plugin"""
if self.dry_run is not True:
self.client = self._get_client()
self._disable_access_key() | [
"def",
"setup",
"(",
"self",
")",
":",
"if",
"self",
".",
"dry_run",
"is",
"not",
"True",
":",
"self",
".",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"self",
".",
"_disable_access_key",
"(",
")"
] | 34 | 6.8 |
def get_verba_link_for_schedule(self, schedule):
"""
Returns a link to verba. The link varies by campus and schedule.
Multiple calls to this with the same schedule may result in
different urls.
"""
dao = Book_DAO()
url = self.get_verba_url(schedule)
res... | [
"def",
"get_verba_link_for_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"dao",
"=",
"Book_DAO",
"(",
")",
"url",
"=",
"self",
".",
"get_verba_url",
"(",
"schedule",
")",
"response",
"=",
"dao",
".",
"getURL",
"(",
"url",
",",
"{",
"\"Accept\"",
":"... | 36.190476 | 19.428571 |
def json_error_formatter(body, status, title, environ):
"""A json_formatter for webob exceptions."""
body = webob.exc.strip_tags(body)
status_code = int(status.split(None, 1)[0])
error_dict = {
'status': status_code,
'title': title,
'detail': body
}
return {'errors': [err... | [
"def",
"json_error_formatter",
"(",
"body",
",",
"status",
",",
"title",
",",
"environ",
")",
":",
"body",
"=",
"webob",
".",
"exc",
".",
"strip_tags",
"(",
"body",
")",
"status_code",
"=",
"int",
"(",
"status",
".",
"split",
"(",
"None",
",",
"1",
"... | 32 | 13.2 |
def get_batch_children(self):
"""
Retrieves batch child tasks for this task if its a batch task.
:return: Collection instance.
:raises SbError if task is not a batch task.
"""
if not self.batch:
raise SbgError("This task is not a batch task.")
return s... | [
"def",
"get_batch_children",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"batch",
":",
"raise",
"SbgError",
"(",
"\"This task is not a batch task.\"",
")",
"return",
"self",
".",
"query",
"(",
"parent",
"=",
"self",
".",
"id",
",",
"api",
"=",
"self",... | 39.111111 | 11.777778 |
def fetch_logs_from_host(hostname, install_path, prefix, logs, directory, pattern):
""" Static method Copies logs from specified host on the specified install path
:Parameter hostname the remote host from where we need to fetch the logs
:Parameter install_path path where the app is installed
:Parameter... | [
"def",
"fetch_logs_from_host",
"(",
"hostname",
",",
"install_path",
",",
"prefix",
",",
"logs",
",",
"directory",
",",
"pattern",
")",
":",
"if",
"hostname",
"is",
"not",
"None",
":",
"with",
"get_sftp_client",
"(",
"hostname",
",",
"username",
"=",
"runtim... | 50.391304 | 24.043478 |
def _bounds_dist(self, p):
"""Get the lower and upper bound distances. Negative is bad."""
prob = self.problem
lb_dist = (p - prob.variable_bounds[0, ]).min()
ub_dist = (prob.variable_bounds[1, ] - p).min()
if prob.bounds.shape[0] > 0:
const = prob.inequalities.dot(... | [
"def",
"_bounds_dist",
"(",
"self",
",",
"p",
")",
":",
"prob",
"=",
"self",
".",
"problem",
"lb_dist",
"=",
"(",
"p",
"-",
"prob",
".",
"variable_bounds",
"[",
"0",
",",
"]",
")",
".",
"min",
"(",
")",
"ub_dist",
"=",
"(",
"prob",
".",
"variable... | 38.333333 | 16.4 |
def compute_agreement_score(num_matches, num1, num2):
"""
Agreement score is used as a criteria to match unit1 and unit2.
"""
denom = num1 + num2 - num_matches
if denom == 0:
return 0
return num_matches / denom | [
"def",
"compute_agreement_score",
"(",
"num_matches",
",",
"num1",
",",
"num2",
")",
":",
"denom",
"=",
"num1",
"+",
"num2",
"-",
"num_matches",
"if",
"denom",
"==",
"0",
":",
"return",
"0",
"return",
"num_matches",
"/",
"denom"
] | 29.375 | 12.375 |
def _positionalArgumentKeyValueList(self,
originalConstructorExpectedArgList,
syntheticMemberList,
argTuple):
"""Transforms args tuple to a dictionary mapping argument names to values using or... | [
"def",
"_positionalArgumentKeyValueList",
"(",
"self",
",",
"originalConstructorExpectedArgList",
",",
"syntheticMemberList",
",",
"argTuple",
")",
":",
"# First, the list of expected arguments is set to original constructor's arg spec. ",
"expectedArgList",
"=",
"copy",
".",
"copy... | 53.107143 | 27.357143 |
def _analyzeDontMeasure(self, chunkSize, willMeasureLater, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
nodes = [None]
height = 1
def sortKey(node):
if node is None:
return None
return (node.intermediate, s... | [
"def",
"_analyzeDontMeasure",
"(",
"self",
",",
"chunkSize",
",",
"willMeasureLater",
",",
"*",
"sinks",
")",
":",
"nodes",
"=",
"[",
"None",
"]",
"height",
"=",
"1",
"def",
"sortKey",
"(",
"node",
")",
":",
"if",
"node",
"is",
"None",
":",
"return",
... | 39.008621 | 20.767241 |
def build_message(self, checker):
"""Builds the checker's error message to report"""
solution = ' (%s)' % checker.solution if self.with_solutions else ''
return '{} {}{}'.format(checker.code,
checker.msg,
solution) | [
"def",
"build_message",
"(",
"self",
",",
"checker",
")",
":",
"solution",
"=",
"' (%s)'",
"%",
"checker",
".",
"solution",
"if",
"self",
".",
"with_solutions",
"else",
"''",
"return",
"'{} {}{}'",
".",
"format",
"(",
"checker",
".",
"code",
",",
"checker"... | 49.5 | 8.833333 |
def from_conf(cls, path=None, **overrides):
'''Initialize instance from YAML configuration file,
writing updates (only to keys, specified by "conf_update_keys") back to it.'''
from onedrive import portalocker
import yaml
if path is None:
path = cls.conf_path_default
log.debug('Using default state-file... | [
"def",
"from_conf",
"(",
"cls",
",",
"path",
"=",
"None",
",",
"*",
"*",
"overrides",
")",
":",
"from",
"onedrive",
"import",
"portalocker",
"import",
"yaml",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"cls",
".",
"conf_path_default",
"log",
".",
"d... | 40.844444 | 21.777778 |
def _is_reference(bpe):
"""Return True if the element is an entity reference."""
if isinstance(bpe, _bp('ProteinReference')) or \
isinstance(bpe, _bpimpl('ProteinReference')) or \
isinstance(bpe, _bp('SmallMoleculeReference')) or \
isinstance(bpe, _bpimpl('SmallMoleculeReference')) or \
... | [
"def",
"_is_reference",
"(",
"bpe",
")",
":",
"if",
"isinstance",
"(",
"bpe",
",",
"_bp",
"(",
"'ProteinReference'",
")",
")",
"or",
"isinstance",
"(",
"bpe",
",",
"_bpimpl",
"(",
"'ProteinReference'",
")",
")",
"or",
"isinstance",
"(",
"bpe",
",",
"_bp"... | 43.692308 | 15.846154 |
def clip(obj, lower=0, upper=127):
"""
Return a copy of the object with piano-roll(s) clipped by a lower bound
and an upper bound specified by `lower` and `upper`, respectively.
Parameters
----------
lower : int or float
The lower bound to clip the piano-roll. Default to 0.
upper : ... | [
"def",
"clip",
"(",
"obj",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"127",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"clip",
"(",
"lower",
",",
"upper",
")",
"return",
"copied"
] | 28.823529 | 20.117647 |
def remove_custom_field_setting(self, project, params={}, **options):
"""Remove a custom field setting on the project.
Parameters
----------
project : {Id} The project to associate the custom field with
[data] : {Object} Data for the request
- [custom_field] : {Id} Th... | [
"def",
"remove_custom_field_setting",
"(",
"self",
",",
"project",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/projects/%s/removeCustomFieldSetting\"",
"%",
"(",
"project",
")",
"return",
"self",
".",
"client",
".",
"po... | 45.363636 | 21.818182 |
def timeout_selecting(self):
"""Timeout of selecting on SELECTING state.
Not specifiyed in [:rfc:`7844`].
See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.
"""
logger.debug('C2.1: T In %s, timeout receiving response to select.',
self.current_st... | [
"def",
"timeout_selecting",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'C2.1: T In %s, timeout receiving response to select.'",
",",
"self",
".",
"current_state",
")",
"if",
"len",
"(",
"self",
".",
"offers",
")",
">=",
"MAX_OFFERS_COLLECTED",
":",
"logg... | 42.066667 | 18.733333 |
def get_firewall_rules(self, server):
"""
Return all FirewallRule objects based on a server instance or uuid.
"""
server_uuid, server_instance = uuid_and_instance(server)
url = '/server/{0}/firewall_rule'.format(server_uuid)
res = self.get_request(url)
return [
... | [
"def",
"get_firewall_rules",
"(",
"self",
",",
"server",
")",
":",
"server_uuid",
",",
"server_instance",
"=",
"uuid_and_instance",
"(",
"server",
")",
"url",
"=",
"'/server/{0}/firewall_rule'",
".",
"format",
"(",
"server_uuid",
")",
"res",
"=",
"self",
".",
... | 35 | 21.461538 |
def is_address_executable_and_writeable(self, address):
"""
Determines if an address belongs to a commited, writeable and
executable page. The page may or may not have additional permissions.
Looking for writeable and executable pages is important when
exploiting a software vuln... | [
"def",
"is_address_executable_and_writeable",
"(",
"self",
",",
"address",
")",
":",
"try",
":",
"mbi",
"=",
"self",
".",
"mquery",
"(",
"address",
")",
"except",
"WindowsError",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"e"... | 33.392857 | 20.607143 |
def blink(self, status):
"""Turn blink cursor visibility on/off"""
self._display_control = ByteUtil.apply_flag(self._display_control, Command.BLINKING_ON, status)
self.command(self._display_control) | [
"def",
"blink",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"_display_control",
"=",
"ByteUtil",
".",
"apply_flag",
"(",
"self",
".",
"_display_control",
",",
"Command",
".",
"BLINKING_ON",
",",
"status",
")",
"self",
".",
"command",
"(",
"self",
... | 54.75 | 20.5 |
def removePoint(self, point, preserveCurve=False):
"""
Remove the point from the contour.
point can be a point object or an index.
If ``preserveCurve`` is set to ``True`` an attempt
will be made to preserve the shape of the curve
if the environment supports that functiona... | [
"def",
"removePoint",
"(",
"self",
",",
"point",
",",
"preserveCurve",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"point",
",",
"int",
")",
":",
"point",
"=",
"self",
".",
"points",
".",
"index",
"(",
"point",
")",
"point",
"=",
"normali... | 45.6 | 9.733333 |
def diff(compiled_requirements, installed_dists):
"""
Calculate which packages should be installed or uninstalled, given a set
of compiled requirements and a list of currently installed modules.
"""
requirements_lut = {r.link or key_from_req(r.req): r for r in compiled_requirements}
satisfied =... | [
"def",
"diff",
"(",
"compiled_requirements",
",",
"installed_dists",
")",
":",
"requirements_lut",
"=",
"{",
"r",
".",
"link",
"or",
"key_from_req",
"(",
"r",
".",
"req",
")",
":",
"r",
"for",
"r",
"in",
"compiled_requirements",
"}",
"satisfied",
"=",
"set... | 39.444444 | 20.037037 |
def not_implemented(self, context, **response_kwargs):
'''
If DEBUG: raise NotImplemented Exception.
If not, raise 404.
:raises:`django.http.Http404` if production environment.
:raises:`NotImplementedError` if ``settings.DEBUG`` is True
'''
if settings.DEBUG:
... | [
"def",
"not_implemented",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"NotImplementedError",
"(",
"_",
"(",
"'This export type ({})is not yet supported.'",
".",
"format",
"(",
"self",
"."... | 43.5 | 24.5 |
def device_product_str(self, indent):
"""Convenience to string method.
"""
s = "Vendor: {}\n".format(self.vendor)
s += indent + "Product: {}\n".format((self.product and product_map[self.product]) or "Unknown")
s += indent + "Version: {}\n".format(self.version)
return s | [
"def",
"device_product_str",
"(",
"self",
",",
"indent",
")",
":",
"s",
"=",
"\"Vendor: {}\\n\"",
".",
"format",
"(",
"self",
".",
"vendor",
")",
"s",
"+=",
"indent",
"+",
"\"Product: {}\\n\"",
".",
"format",
"(",
"(",
"self",
".",
"product",
"and",
"pro... | 44.428571 | 16.285714 |
def _wait_fd(conn, read=True):
'''Wait for an event on file descriptor ``fd``.
:param conn: file descriptor
:param read: wait for a read event if ``True``, otherwise a wait
for write event.
This function must be invoked from a coroutine with parent, therefore
invoking it from the main gree... | [
"def",
"_wait_fd",
"(",
"conn",
",",
"read",
"=",
"True",
")",
":",
"current",
"=",
"getcurrent",
"(",
")",
"parent",
"=",
"current",
".",
"parent",
"assert",
"parent",
",",
"'\"_wait_fd\" must be called by greenlet with a parent'",
"try",
":",
"fileno",
"=",
... | 35.62963 | 22.814815 |
def get_results_sig(self):
"""Get significant results."""
# Only print results when uncorrected p-value < this value.
print("{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\n".format(
N=sum(1 for r in self.results_all if r.p_uncorrected < self.args.pval),
... | [
"def",
"get_results_sig",
"(",
"self",
")",
":",
"# Only print results when uncorrected p-value < this value.",
"print",
"(",
"\"{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\\n\"",
".",
"format",
"(",
"N",
"=",
"sum",
"(",
"1",
"for",
"r",
"in",
"self",
... | 52.4 | 21.2 |
def scan(self):
'''Metascript that calls other scripts to tune the FE.
Parameters
----------
cfg_name : string
Name of the config to be created. This config holds the tuning results.
target_threshold : int
The target threshold value in PlsrDAC.
... | [
"def",
"scan",
"(",
"self",
")",
":",
"for",
"iteration",
"in",
"range",
"(",
"0",
",",
"self",
".",
"global_iterations",
")",
":",
"# tune iteratively with decreasing range to save time\r",
"if",
"self",
".",
"stop_run",
".",
"is_set",
"(",
")",
":",
"break",... | 54.086022 | 26.946237 |
def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]:
""" Determine whether val is a valid instance of this array
:returns: Success indicator and error list """
errors = []
if not isinstance(val, list):
errors.append(f"{self._variable_name}:... | [
"def",
"_validate",
"(",
"self",
",",
"val",
":",
"list",
",",
"log",
":",
"Optional",
"[",
"Logger",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"bool",
",",
"List",
"[",
"str",
"]",
"]",
":",
"errors",
"=",
"[",
"]",
"if",
"not",
"isinstance",
... | 46.92 | 25.52 |
def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
"""Confirm only allowed settings are present."""
for setting_key in application_config.keys():
if setting_key not in allowed_settings:
raise ImproperlyConfigured(
"Platform {}, app {} does not support the settin... | [
"def",
"_validate_allowed_settings",
"(",
"self",
",",
"application_id",
",",
"application_config",
",",
"allowed_settings",
")",
":",
"for",
"setting_key",
"in",
"application_config",
".",
"keys",
"(",
")",
":",
"if",
"setting_key",
"not",
"in",
"allowed_settings",... | 40.5 | 23.1 |
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, **kwargs):
"""
Present the PTY of the container inside the current process.
This is just a wrapper for PseudoTerminal(client, container).start()
"""
PseudoTerminal(client, container, interactive=interactive, stdou... | [
"def",
"start",
"(",
"client",
",",
"container",
",",
"interactive",
"=",
"True",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"PseudoTerminal",
"(",
"client",
",",
"container",
... | 45.75 | 34 |
def vfolders(access_key):
'''
List and manage virtual folders.
'''
fields = [
('Name', 'name'),
('Created At', 'created_at'),
('Last Used', 'last_used'),
('Max Files', 'max_files'),
('Max Size', 'max_size'),
]
if access_key is None:
q = 'query { vf... | [
"def",
"vfolders",
"(",
"access_key",
")",
":",
"fields",
"=",
"[",
"(",
"'Name'",
",",
"'name'",
")",
",",
"(",
"'Created At'",
",",
"'created_at'",
")",
",",
"(",
"'Last Used'",
",",
"'last_used'",
")",
",",
"(",
"'Max Files'",
",",
"'max_files'",
")",... | 31.84 | 17.36 |
def on_step_begin(self, step, logs):
""" Print metrics if interval is over """
if self.step % self.interval == 0:
if len(self.episode_rewards) > 0:
metrics = np.array(self.metrics)
assert metrics.shape == (self.interval, len(self.metrics_names))
... | [
"def",
"on_step_begin",
"(",
"self",
",",
"step",
",",
"logs",
")",
":",
"if",
"self",
".",
"step",
"%",
"self",
".",
"interval",
"==",
"0",
":",
"if",
"len",
"(",
"self",
".",
"episode_rewards",
")",
">",
"0",
":",
"metrics",
"=",
"np",
".",
"ar... | 63.28 | 28.2 |
def get_file_hash(filename):
'''find the SHA256 hash string of a file
'''
hasher = hashlib.sha256()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest() | [
"def",
"get_file_hash",
"(",
"filename",
")",
":",
"hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"409... | 32.125 | 12.125 |
def calculate(cls, calc, formula_reg, data_reg, out_reg,
timestep=None, idx=None):
"""
Execute calculation
:param calc: calculation, with formula, args and return keys
:type calc: dict
:param formula_reg: Registry of formulas.
:type formula_reg: :class:... | [
"def",
"calculate",
"(",
"cls",
",",
"calc",
",",
"formula_reg",
",",
"data_reg",
",",
"out_reg",
",",
"timestep",
"=",
"None",
",",
"idx",
"=",
"None",
")",
":",
"# get the formula-key from each static calc",
"formula",
"=",
"calc",
"[",
"'formula'",
"]",
"... | 47.268817 | 15.849462 |
def parse_schema_string(schema_string):
"""
Load and return a PySchema class from an avsc string
"""
if isinstance(schema_string, str):
schema_string = schema_string.decode("utf8")
schema_struct = json.loads(schema_string)
return AvroSchemaParser().parse_schema_struct(schema_struct) | [
"def",
"parse_schema_string",
"(",
"schema_string",
")",
":",
"if",
"isinstance",
"(",
"schema_string",
",",
"str",
")",
":",
"schema_string",
"=",
"schema_string",
".",
"decode",
"(",
"\"utf8\"",
")",
"schema_struct",
"=",
"json",
".",
"loads",
"(",
"schema_s... | 34.222222 | 11.111111 |
def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500,
method='gz', delete=False, access_key=None, secret_key=None):
'''
Compresses data and uploads to S3.
S3 upload uses ``s3cmd``, so you must either:
1) Manually configure ``s3cmd`` prior to use (typically using ... | [
"def",
"compress_and_upload",
"(",
"data",
",",
"compressed_file",
",",
"s3_path",
",",
"multipart_chunk_size_mb",
"=",
"500",
",",
"method",
"=",
"'gz'",
",",
"delete",
"=",
"False",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
... | 36.842105 | 30.070175 |
def hbold(*content, sep=' '):
"""
Make bold text (HTML)
:param content:
:param sep:
:return:
"""
return _md(quote_html(_join(*content, sep=sep)), symbols=MD_SYMBOLS[4]) | [
"def",
"hbold",
"(",
"*",
"content",
",",
"sep",
"=",
"' '",
")",
":",
"return",
"_md",
"(",
"quote_html",
"(",
"_join",
"(",
"*",
"content",
",",
"sep",
"=",
"sep",
")",
")",
",",
"symbols",
"=",
"MD_SYMBOLS",
"[",
"4",
"]",
")"
] | 21 | 19.444444 |
def squared_error(y, y_pred):
"""Calculates the sum of the squared
differences between target and prediction.
Parameters:
-----------
y : vector, shape (n_samples,)
The target values.
y_pred : vector, shape (n_samples,)
The predicted values.
Returns:
--------
error... | [
"def",
"squared_error",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"return",
"np",
".",
"sum",
"(",
"(",
"y",
"-",
"y_pred",
")",
"**",
"2",
")"
] | 22.761905 | 17.571429 |
def register(self, model=None, include_fields=[], exclude_fields=[], mapping_fields={}):
"""
Register a model with auditlog. Auditlog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to... | [
"def",
"register",
"(",
"self",
",",
"model",
"=",
"None",
",",
"include_fields",
"=",
"[",
"]",
",",
"exclude_fields",
"=",
"[",
"]",
",",
"mapping_fields",
"=",
"{",
"}",
")",
":",
"def",
"registrar",
"(",
"cls",
")",
":",
"\"\"\"Register models for a ... | 39.628571 | 19.742857 |
def start_watching(self):
""" Begins watching etcd for changes. """
# Don't create a new watcher thread if we already have one running
if self.watcher and self.watcher.is_alive():
return
# Create a new watcher thread and start it
self.watcher = Watcher()
self... | [
"def",
"start_watching",
"(",
"self",
")",
":",
"# Don't create a new watcher thread if we already have one running",
"if",
"self",
".",
"watcher",
"and",
"self",
".",
"watcher",
".",
"is_alive",
"(",
")",
":",
"return",
"# Create a new watcher thread and start it",
"self... | 36.444444 | 17 |
def _compute(self):
"""Compute y min and max and y scale and set labels"""
x_len = self._len
y_len = self._order
self._box.xmax = x_len
self._box.ymax = y_len
self._x_pos = [n / 2 for n in range(1, 2 * x_len, 2)]
self._y_pos = [n / 2 for n in reversed(range(1, 2 ... | [
"def",
"_compute",
"(",
"self",
")",
":",
"x_len",
"=",
"self",
".",
"_len",
"y_len",
"=",
"self",
".",
"_order",
"self",
".",
"_box",
".",
"xmax",
"=",
"x_len",
"self",
".",
"_box",
".",
"ymax",
"=",
"y_len",
"self",
".",
"_x_pos",
"=",
"[",
"n"... | 37.076923 | 18.307692 |
def lookUpFieldType(field_type):
""" Converts the ArcGIS REST field types to Python Types
Input:
field_type - string - type of field as string
Output:
Python field type as string
"""
if field_type == "esriFieldTypeDate":
return "DATE"
elif field_type == "esr... | [
"def",
"lookUpFieldType",
"(",
"field_type",
")",
":",
"if",
"field_type",
"==",
"\"esriFieldTypeDate\"",
":",
"return",
"\"DATE\"",
"elif",
"field_type",
"==",
"\"esriFieldTypeInteger\"",
":",
"return",
"\"LONG\"",
"elif",
"field_type",
"==",
"\"esriFieldTypeSmallInteg... | 31.689655 | 12.482759 |
def authenticate(self):
"""
Indicate to the client that it needs to authenticate via a 401.
"""
if request.headers.get('Authorization') or request.args.get('access_token'):
realm = 'Bearer realm="%s", error="invalid_token"' % __package__
else:
realm = 'Bea... | [
"def",
"authenticate",
"(",
"self",
")",
":",
"if",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
")",
"or",
"request",
".",
"args",
".",
"get",
"(",
"'access_token'",
")",
":",
"realm",
"=",
"'Bearer realm=\"%s\", error=\"invalid_token\"'",
"... | 48.7 | 23.3 |
def get_self_uri(self, content_type):
"return the first self uri with the content_type"
try:
return [self_uri for self_uri in self.self_uri_list
if self_uri.content_type == content_type][0]
except IndexError:
return None | [
"def",
"get_self_uri",
"(",
"self",
",",
"content_type",
")",
":",
"try",
":",
"return",
"[",
"self_uri",
"for",
"self_uri",
"in",
"self",
".",
"self_uri_list",
"if",
"self_uri",
".",
"content_type",
"==",
"content_type",
"]",
"[",
"0",
"]",
"except",
"Ind... | 40.285714 | 18 |
def _prm_make_description(self, data, fullname):
""" Returns a description dictionary for pytables table creation"""
def _convert_lists_and_tuples(series_of_data):
"""Converts lists and tuples to numpy arrays"""
if isinstance(series_of_data[0],
(list, t... | [
"def",
"_prm_make_description",
"(",
"self",
",",
"data",
",",
"fullname",
")",
":",
"def",
"_convert_lists_and_tuples",
"(",
"series_of_data",
")",
":",
"\"\"\"Converts lists and tuples to numpy arrays\"\"\"",
"if",
"isinstance",
"(",
"series_of_data",
"[",
"0",
"]",
... | 43.625 | 26.375 |
def _table_arg_to_table_ref(value, default_project=None):
"""Helper to convert a string or Table to TableReference.
This function keeps TableReference and other kinds of objects unchanged.
"""
if isinstance(value, six.string_types):
value = TableReference.from_string(value, default_project=defa... | [
"def",
"_table_arg_to_table_ref",
"(",
"value",
",",
"default_project",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"TableReference",
".",
"from_string",
"(",
"value",
",",
"default_project"... | 42.2 | 18 |
def get_webhook(self, **kwargs): # noqa: E501
"""Check callback URL # noqa: E501
Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes... | [
"def",
"get_webhook",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"get_webhook_with_http_info",... | 47.8 | 24.8 |
def string_match(self, datastring, findstring, flags=None):
"""
Returns position of findstring in datastring or None if not found.
Flags is a list of strings. Supported strings are:
* "MATCH_CASE": The case has to match for valid find
* "WHOLE_WORD": The word has to be surround... | [
"def",
"string_match",
"(",
"self",
",",
"datastring",
",",
"findstring",
",",
"flags",
"=",
"None",
")",
":",
"if",
"type",
"(",
"datastring",
")",
"is",
"IntType",
":",
"# Empty cell",
"return",
"None",
"if",
"flags",
"is",
"None",
":",
"flags",
"=",
... | 32.731707 | 18.829268 |
def compile_pattern_list(self, patterns):
'''This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
might do this if waiting for an EOF or TIM... | [
"def",
"compile_pattern_list",
"(",
"self",
",",
"patterns",
")",
":",
"if",
"patterns",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"patterns",
",",
"list",
")",
":",
"patterns",
"=",
"[",
"patterns",
"]",
"# Allow dot to match ... | 39.12766 | 18.829787 |
def iter_left_col_tcs(self):
"""Generate each `a:tc` element in leftmost column of range."""
col_idx = self._left
for tr in self._tbl.tr_lst[self._top:self._bottom]:
yield tr.tc_lst[col_idx] | [
"def",
"iter_left_col_tcs",
"(",
"self",
")",
":",
"col_idx",
"=",
"self",
".",
"_left",
"for",
"tr",
"in",
"self",
".",
"_tbl",
".",
"tr_lst",
"[",
"self",
".",
"_top",
":",
"self",
".",
"_bottom",
"]",
":",
"yield",
"tr",
".",
"tc_lst",
"[",
"col... | 44.4 | 9.4 |
def align_to_target(self, target_term_doc_mat):
'''
Parameters
----------
target_term_doc_mat : TermDocMatrix
Returns
-------
PriorFactory
'''
self.priors = self.priors[target_term_doc_mat.get_terms()].fillna(0)
return self | [
"def",
"align_to_target",
"(",
"self",
",",
"target_term_doc_mat",
")",
":",
"self",
".",
"priors",
"=",
"self",
".",
"priors",
"[",
"target_term_doc_mat",
".",
"get_terms",
"(",
")",
"]",
".",
"fillna",
"(",
"0",
")",
"return",
"self"
] | 19.416667 | 26.75 |
def text_entry(self, ucs, name):
"""
Display a single column segment row describing ``(ucs, name)``.
:param ucs: target unicode point character string.
:param name: name of unicode point.
:rtype: unicode
"""
style = self.screen.style
if len(name) > style.... | [
"def",
"text_entry",
"(",
"self",
",",
"ucs",
",",
"name",
")",
":",
"style",
"=",
"self",
".",
"screen",
".",
"style",
"if",
"len",
"(",
"name",
")",
">",
"style",
".",
"name_len",
":",
"idx",
"=",
"max",
"(",
"0",
",",
"style",
".",
"name_len",... | 40.071429 | 13.880952 |
def create(ctx, to, amount, symbol, secret, hash, account, expiration):
""" Create an HTLC contract
"""
ctx.blockchain.blocking = True
tx = ctx.blockchain.htlc_create(
Amount(amount, symbol),
to,
secret,
hash_type=hash,
expiration=expiration,
account=accou... | [
"def",
"create",
"(",
"ctx",
",",
"to",
",",
"amount",
",",
"symbol",
",",
"secret",
",",
"hash",
",",
"account",
",",
"expiration",
")",
":",
"ctx",
".",
"blockchain",
".",
"blocking",
"=",
"True",
"tx",
"=",
"ctx",
".",
"blockchain",
".",
"htlc_cre... | 27.777778 | 15.222222 |
def on_train_begin(self, epoch:int, **kwargs:Any)->None:
"Initialize the schedulers for training."
res = {'epoch':self.start_epoch} if self.start_epoch is not None else None
self.start_epoch = ifnone(self.start_epoch, epoch)
self.scheds = [p.scheds for p in self.phases]
self.opt ... | [
"def",
"on_train_begin",
"(",
"self",
",",
"epoch",
":",
"int",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"res",
"=",
"{",
"'epoch'",
":",
"self",
".",
"start_epoch",
"}",
"if",
"self",
".",
"start_epoch",
"is",
"not",
"None",
"e... | 43.454545 | 15.090909 |
def _Execute(self, funcname, *args, **kwargs):
"""Send an RPC request to the gdb-internal python.
Blocks for 3 seconds by default and returns any results.
Args:
funcname: the name of the function to call.
*args: the function's arguments.
**kwargs: Only the key 'wait_for_completion' is ins... | [
"def",
"_Execute",
"(",
"self",
",",
"funcname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"wait_for_completion",
"=",
"kwargs",
".",
"get",
"(",
"'wait_for_completion'",
",",
"False",
")",
"rpc_dict",
"=",
"{",
"'func'",
":",
"funcname",
",",... | 37.225806 | 19.129032 |
def value(self):
'''
Return the counter value
Returns:
long: The counter value
'''
(counter_type, value) = win32pdh.GetFormattedCounterValue(
self.handle, win32pdh.PDH_FMT_DOUBLE)
self.type = counter_type
return value | [
"def",
"value",
"(",
"self",
")",
":",
"(",
"counter_type",
",",
"value",
")",
"=",
"win32pdh",
".",
"GetFormattedCounterValue",
"(",
"self",
".",
"handle",
",",
"win32pdh",
".",
"PDH_FMT_DOUBLE",
")",
"self",
".",
"type",
"=",
"counter_type",
"return",
"v... | 26.181818 | 20.181818 |
def validation_tween_factory(handler, registry):
"""Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view.
"""
settings = load_settings(registry)
route_mapper = registry.queryUtility(IRoute... | [
"def",
"validation_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"settings",
"=",
"load_settings",
"(",
"registry",
")",
"route_mapper",
"=",
"registry",
".",
"queryUtility",
"(",
"IRoutesMapper",
")",
"validation_context",
"=",
"_get_validation_context",... | 35.551724 | 21.517241 |
def flat_matches(self, key):
""" Yield all 'value' targets, without priority """
for val in self.dispatch(key):
for el in val:
yield el[1] # only value, no priority
return | [
"def",
"flat_matches",
"(",
"self",
",",
"key",
")",
":",
"for",
"val",
"in",
"self",
".",
"dispatch",
"(",
"key",
")",
":",
"for",
"el",
"in",
"val",
":",
"yield",
"el",
"[",
"1",
"]",
"# only value, no priority",
"return"
] | 36.333333 | 11.166667 |
def request(self, path, method='GET', params=None, type=REST_TYPE):
"""Builds a request, gets a response and decodes it."""
response_text = self._get_http_client(type).request(path, method, params)
if not response_text:
return response_text
response_json = json.loads(respon... | [
"def",
"request",
"(",
"self",
",",
"path",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"type",
"=",
"REST_TYPE",
")",
":",
"response_text",
"=",
"self",
".",
"_get_http_client",
"(",
"type",
")",
".",
"request",
"(",
"path",
",",
"... | 36.307692 | 24.384615 |
def iter_follower_file(fname):
""" Iterator from a file of follower information and return a tuple of screen_name, follower ids.
File format is:
<iso timestamp> <screen_name> <follower_id1> <follower_ids2> ...
"""
with open(fname, 'rt') as f:
for line in f:
parts = line.split()
... | [
"def",
"iter_follower_file",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'rt'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"parts",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"parts",
")",
">",
"3",
":",
"yi... | 41.1 | 13.3 |
def save_package_contents(self, root, team, owner, pkgname):
"""
Saves the in-memory contents to a file in the local
package repository.
"""
assert isinstance(root, RootNode)
instance_hash = hash_contents(root)
pkg_path = self.package_path(team, owner, pkgname)
... | [
"def",
"save_package_contents",
"(",
"self",
",",
"root",
",",
"team",
",",
"owner",
",",
"pkgname",
")",
":",
"assert",
"isinstance",
"(",
"root",
",",
"RootNode",
")",
"instance_hash",
"=",
"hash_contents",
"(",
"root",
")",
"pkg_path",
"=",
"self",
".",... | 42.92 | 17.56 |
def _set_metadata(self):
"""
Internal helper to set metadata attributes.
"""
meta = QueryDbMeta()
with self._engine.connect() as conn:
meta.bind = conn
meta.reflect()
self._meta = meta
# Set an inspect attribute, whose subattributes
... | [
"def",
"_set_metadata",
"(",
"self",
")",
":",
"meta",
"=",
"QueryDbMeta",
"(",
")",
"with",
"self",
".",
"_engine",
".",
"connect",
"(",
")",
"as",
"conn",
":",
"meta",
".",
"bind",
"=",
"conn",
"meta",
".",
"reflect",
"(",
")",
"self",
".",
"_met... | 38.594595 | 16.594595 |
def same_guid(post, parameter=DEFAULT_SIMILARITY_TIMESPAN):
'''Skip posts with exactly same GUID.
Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).'''
from feedjack.models import Post
if isinstance(parameter, types.StringTypes): parameter = int(parameter.strip())
similar = Post.objects.filtere... | [
"def",
"same_guid",
"(",
"post",
",",
"parameter",
"=",
"DEFAULT_SIMILARITY_TIMESPAN",
")",
":",
"from",
"feedjack",
".",
"models",
"import",
"Post",
"if",
"isinstance",
"(",
"parameter",
",",
"types",
".",
"StringTypes",
")",
":",
"parameter",
"=",
"int",
"... | 51.9 | 20.1 |
def server(name='proxy-server', headers_middleware=None,
server_software=None, **kwargs):
'''Function to Create a WSGI Proxy Server.'''
if headers_middleware is None:
headers_middleware = [x_forwarded_for]
wsgi_proxy = ProxyServerWsgiHandler(headers_middleware)
kwargs['server_software... | [
"def",
"server",
"(",
"name",
"=",
"'proxy-server'",
",",
"headers_middleware",
"=",
"None",
",",
"server_software",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"headers_middleware",
"is",
"None",
":",
"headers_middleware",
"=",
"[",
"x_forwarded_for... | 51.5 | 13 |
def reassemble(self, blueprint, fields, documents):
"""
Reassemble the given set of fields for a list of pre-assembed documents.
NOTE: Reassembly is done in place, since the data you send the method
should be JSON type safe, if you need to retain the existing document
it is reco... | [
"def",
"reassemble",
"(",
"self",
",",
"blueprint",
",",
"fields",
",",
"documents",
")",
":",
"# Reset the blueprint",
"blueprint",
".",
"reset",
"(",
")",
"# Reassemble the documents",
"for",
"document",
"in",
"documents",
":",
"blueprint",
".",
"reassemble",
... | 36.4 | 21.333333 |
def transform_data(self, project, logstore, config, from_time, to_time=None,
to_client=None, to_project=None, to_logstore=None,
shard_list=None,
batch_size=None, compress=None,
cg_name=None, c_name=None,
... | [
"def",
"transform_data",
"(",
"self",
",",
"project",
",",
"logstore",
",",
"config",
",",
"from_time",
",",
"to_time",
"=",
"None",
",",
"to_client",
"=",
"None",
",",
"to_project",
"=",
"None",
",",
"to_logstore",
"=",
"None",
",",
"shard_list",
"=",
"... | 53.710526 | 37.710526 |
async def send(self, request: ClientRequest, **config: Any) -> AsyncClientResponse:
"""Send the request using this HTTP sender.
Will pre-load the body into memory to be available with a sync method.
pass stream=True to avoid this behavior.
"""
result = await self._session.reques... | [
"async",
"def",
"send",
"(",
"self",
",",
"request",
":",
"ClientRequest",
",",
"*",
"*",
"config",
":",
"Any",
")",
"->",
"AsyncClientResponse",
":",
"result",
"=",
"await",
"self",
".",
"_session",
".",
"request",
"(",
"request",
".",
"method",
",",
... | 37.133333 | 16.866667 |
def distance(latitude_1, longitude_1, latitude_2, longitude_2):
"""
Distance between two points.
"""
coef = mod_math.cos(latitude_1 / 180. * mod_math.pi)
x = latitude_1 - latitude_2
y = (longitude_1 - longitude_2) * coef
return mod_math.sqrt(x * x + y * y) * ONE_DEGREE | [
"def",
"distance",
"(",
"latitude_1",
",",
"longitude_1",
",",
"latitude_2",
",",
"longitude_2",
")",
":",
"coef",
"=",
"mod_math",
".",
"cos",
"(",
"latitude_1",
"/",
"180.",
"*",
"mod_math",
".",
"pi",
")",
"x",
"=",
"latitude_1",
"-",
"latitude_2",
"y... | 29 | 15 |
def substitute_environ(self):
"""
Substitute environment variables into settings.
"""
for attr_name in dir(self):
if attr_name.startswith('_') or attr_name.upper() != attr_name:
continue
orig_value = getattr(self, attr_name)
is_require... | [
"def",
"substitute_environ",
"(",
"self",
")",
":",
"for",
"attr_name",
"in",
"dir",
"(",
"self",
")",
":",
"if",
"attr_name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"attr_name",
".",
"upper",
"(",
")",
"!=",
"attr_name",
":",
"continue",
"orig_value"... | 51.448276 | 18.758621 |
def user_info(self, verbose=False):
'''
Get information about the currently authenticated user
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
'''
url = '{}/{}'.format(self.rest_url, 'user')
return self.__auth_req_get(url, verbose=verbose) | [
"def",
"user_info",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"rest_url",
",",
"'user'",
")",
"return",
"self",
".",
"__auth_req_get",
"(",
"url",
",",
"verbose",
"=",
"verbose",
")"
] | 43.571429 | 21.571429 |
def encoded_words_to_text(self, in_encoded_words: str):
"""Pull out the character set, encoding, and encoded text from the input
encoded words. Next, it decodes the encoded words into a byte string,
using either the quopri module or base64 module as determined by the
encoding. Finally, i... | [
"def",
"encoded_words_to_text",
"(",
"self",
",",
"in_encoded_words",
":",
"str",
")",
":",
"# handle RFC2047 quoting",
"if",
"'\"'",
"in",
"in_encoded_words",
":",
"in_encoded_words",
"=",
"in_encoded_words",
".",
"strip",
"(",
"'\"'",
")",
"# regex",
"encoded_word... | 40.588235 | 19.970588 |
def create_fw(self, tenant_id, data):
"""Top level routine called when a FW is created. """
try:
return self._create_fw(tenant_id, data)
except Exception as exc:
LOG.error("Failed to create FW for device native, tenant "
"%(tenant)s data %(data)s Exc... | [
"def",
"create_fw",
"(",
"self",
",",
"tenant_id",
",",
"data",
")",
":",
"try",
":",
"return",
"self",
".",
"_create_fw",
"(",
"tenant_id",
",",
"data",
")",
"except",
"Exception",
"as",
"exc",
":",
"LOG",
".",
"error",
"(",
"\"Failed to create FW for dev... | 46.444444 | 16.333333 |
def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
s = super(Block, self).Size() + GetVarSize(self.Transactions)
return s | [
"def",
"Size",
"(",
"self",
")",
":",
"s",
"=",
"super",
"(",
"Block",
",",
"self",
")",
".",
"Size",
"(",
")",
"+",
"GetVarSize",
"(",
"self",
".",
"Transactions",
")",
"return",
"s"
] | 23.333333 | 18.888889 |
def send(self, msg):
"""send message to client."""
assert isinstance(msg, str), "String is required"
if self._debug:
log.info("outgoing message: %s, %s", self.id, str(msg)[:200])
if self.state != STATE_OPEN:
return
self._feed(FRAME_MESSAGE, msg) | [
"def",
"send",
"(",
"self",
",",
"msg",
")",
":",
"assert",
"isinstance",
"(",
"msg",
",",
"str",
")",
",",
"\"String is required\"",
"if",
"self",
".",
"_debug",
":",
"log",
".",
"info",
"(",
"\"outgoing message: %s, %s\"",
",",
"self",
".",
"id",
",",
... | 27.454545 | 21.363636 |
def _generate_main_files_header(notebook_object, notebook_title="Notebook Title",
notebook_description="Notebook Description"):
"""
Internal function that is used for generation of the 'MainFiles' notebooks header.
----------
Parameters
----------
notebook_object... | [
"def",
"_generate_main_files_header",
"(",
"notebook_object",
",",
"notebook_title",
"=",
"\"Notebook Title\"",
",",
"notebook_description",
"=",
"\"Notebook Description\"",
")",
":",
"# =================================== Creation of Header =======================================",
"h... | 43.037037 | 31.333333 |
def isdir(path, message):
"""
Raise an exception if the given directory does not exist.
:param path: The path to a directory to be tested
:param message: A custom message to report in the exception
:raises: FileNotFoundError
"""
if not os.path.isdir(path):
raise FileNotFoundError(
... | [
"def",
"isdir",
"(",
"path",
",",
"message",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"FileNotFoundError",
"(",
"errno",
".",
"ENOENT",
",",
"\"{}: {}\"",
".",
"format",
"(",
"message",
",",
"os",
".",
... | 31.076923 | 17.230769 |
def print_row_failures(failing_items, verbose=False, outfile_name=None):
"""
Take output from get_row_failures (DataFrame), and output it to
stdout, an outfile, or both.
"""
if outfile_name:
outfile = open(outfile_name, "w")
outfile.write("\t".join(["name", "row_number", "problem_typ... | [
"def",
"print_row_failures",
"(",
"failing_items",
",",
"verbose",
"=",
"False",
",",
"outfile_name",
"=",
"None",
")",
":",
"if",
"outfile_name",
":",
"outfile",
"=",
"open",
"(",
"outfile_name",
",",
"\"w\"",
")",
"outfile",
".",
"write",
"(",
"\"\\t\"",
... | 39.733333 | 17.733333 |
def username_user_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
name_key = ET.SubElement(username, "name")
name_key.text = kwargs.pop('name')
... | [
"def",
"username_user_password",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"username",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"username\"",
",",
"xmlns",
"=",
"\"urn:brocade.co... | 42.916667 | 14.833333 |
def blank(columns=1, name=None):
"""
Creates the grammar for a blank field.
These are for constant empty strings which should be ignored, as they are
used just as fillers.
:param columns: number of columns, which is the required number of
whitespaces
:param name: name for the field
:re... | [
"def",
"blank",
"(",
"columns",
"=",
"1",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'Blank Field'",
"field",
"=",
"pp",
".",
"Regex",
"(",
"'[ ]{'",
"+",
"str",
"(",
"columns",
")",
"+",
"'}'",
")",
"field... | 24.227273 | 19.863636 |
def reference_id_from_html(html):
"""\
Extracts the cable's reference identifier from the provided HTML string.
`html`
The HTML page of the cable.
"""
m = _REFERENCE_ID_FROM_HTML_PATTERN.search(html)
if m:
return m.group(1)
raise ValueError("Cannot extract the cable's refere... | [
"def",
"reference_id_from_html",
"(",
"html",
")",
":",
"m",
"=",
"_REFERENCE_ID_FROM_HTML_PATTERN",
".",
"search",
"(",
"html",
")",
"if",
"m",
":",
"return",
"m",
".",
"group",
"(",
"1",
")",
"raise",
"ValueError",
"(",
"\"Cannot extract the cable's reference ... | 28.909091 | 18.090909 |
def can_execute(self):
"""True if we can execute the callback."""
return not self._disabled and all(dep.status == dep.node.S_OK for dep in self.deps) | [
"def",
"can_execute",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"_disabled",
"and",
"all",
"(",
"dep",
".",
"status",
"==",
"dep",
".",
"node",
".",
"S_OK",
"for",
"dep",
"in",
"self",
".",
"deps",
")"
] | 54.333333 | 23 |
def get_config_from_package(package):
""" Breaks a package string in module and class.
:param package: A package string.
:return: A config dict with class and module.
"""
package_x = package.split('.')
package_conf = {}
package_conf['class'] = package_x[-1]
package_conf['module'] = '.'.... | [
"def",
"get_config_from_package",
"(",
"package",
")",
":",
"package_x",
"=",
"package",
".",
"split",
"(",
"'.'",
")",
"package_conf",
"=",
"{",
"}",
"package_conf",
"[",
"'class'",
"]",
"=",
"package_x",
"[",
"-",
"1",
"]",
"package_conf",
"[",
"'module'... | 32.454545 | 10.363636 |
def write_tables(fname, table_names=None, prefix=None, compress=False, local=False):
"""
Writes tables to a pandas.HDFStore file.
Parameters
----------
fname : str
File name for HDFStore. Will be opened in append mode and closed
at the end of this function.
table_names: list of ... | [
"def",
"write_tables",
"(",
"fname",
",",
"table_names",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"compress",
"=",
"False",
",",
"local",
"=",
"False",
")",
":",
"if",
"table_names",
"is",
"None",
":",
"table_names",
"=",
"list_tables",
"(",
")",
... | 36.891892 | 20.837838 |
def append_records(self, owner, id, stream_id, body, **kwargs):
"""
Append records to a stream.
This endpoint appends JSON data to a stream associated with a dataset. Streams don't need to be created before you can append data to it. They will be created on-demand, the first time they are used. ... | [
"def",
"append_records",
"(",
"self",
",",
"owner",
",",
"id",
",",
"stream_id",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"retu... | 90.75 | 63.75 |
def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1):
"""Sync files whose filename attribute is highest in alphanumeric order"""
remote_files = command.map_files_raw(remote_dir=remote_dir)
local_files = list_local_files(*filters, local_dir=local_dir)
greatest = sorted(local_fi... | [
"def",
"up_by_name",
"(",
"*",
"filters",
",",
"local_dir",
"=",
"\".\"",
",",
"remote_dir",
"=",
"DEFAULT_REMOTE_DIR",
",",
"count",
"=",
"1",
")",
":",
"remote_files",
"=",
"command",
".",
"map_files_raw",
"(",
"remote_dir",
"=",
"remote_dir",
")",
"local_... | 59 | 16.75 |
def secondary_query(self, query, mongo_query, secondary_filter=None):
"""Creates a secondary query object based on secondary parameters specified by user
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is goin... | [
"def",
"secondary_query",
"(",
"self",
",",
"query",
",",
"mongo_query",
",",
"secondary_filter",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"'Creating a query object with secondary parameters'",
")",
"mongo_secondary_query",
"=",
"[",
"]",
"# loop over secondar... | 41.144654 | 21.559748 |
def get_nearest_site(self, latitude=None, longitude=None):
"""
Deprecated. This function returns nearest Site object to the specified
coordinates.
"""
warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead'
warn(warning_message, Deprecati... | [
"def",
"get_nearest_site",
"(",
"self",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
")",
":",
"warning_message",
"=",
"'This function is deprecated. Use get_nearest_forecast_site() instead'",
"warn",
"(",
"warning_message",
",",
"DeprecationWarning",
",",... | 44.888889 | 24.666667 |
def fill_form_field(self, field_name, field_value):
"""Fills given field with given value
:param field_name: name of field to fill
:param field_value: value with which to fill field
"""
self.browser.execute_script(
"document.getElementsByName(\"" + str(
... | [
"def",
"fill_form_field",
"(",
"self",
",",
"field_name",
",",
"field_value",
")",
":",
"self",
".",
"browser",
".",
"execute_script",
"(",
"\"document.getElementsByName(\\\"\"",
"+",
"str",
"(",
"field_name",
")",
"+",
"\"\\\")[0].value = \\\"\"",
"+",
"str",
"("... | 41.666667 | 14.111111 |
def run_docker(self, commands):
"""Run App in Docker Container.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command.
"""
try:
import docker
except ImportError:
pri... | [
"def",
"run_docker",
"(",
"self",
",",
"commands",
")",
":",
"try",
":",
"import",
"docker",
"except",
"ImportError",
":",
"print",
"(",
"'{}{}Could not import docker module (try \"pip install docker\").'",
".",
"format",
"(",
"c",
".",
"Style",
".",
"BRIGHT",
","... | 37.188235 | 21.658824 |
def Exists(self, maxSearchSeconds: float = 5, searchIntervalSeconds: float = SEARCH_INTERVAL, printIfNotExist: bool = False) -> bool:
"""
maxSearchSeconds: float
searchIntervalSeconds: float
Find control every searchIntervalSeconds seconds in maxSearchSeconds seconds.
Return bool... | [
"def",
"Exists",
"(",
"self",
",",
"maxSearchSeconds",
":",
"float",
"=",
"5",
",",
"searchIntervalSeconds",
":",
"float",
"=",
"SEARCH_INTERVAL",
",",
"printIfNotExist",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_element",
"an... | 55.27451 | 27.470588 |
def iplot(figure,validate=True,sharing=None,filename='',
online=None,asImage=False,asUrl=False,asPlot=False,
dimensions=None,display_image=True,**kwargs):
"""
Plots a figure in IPython, creates an HTML or generates an Image
figure : figure
Plotly figure to be charted
validate : bool
If True then all va... | [
"def",
"iplot",
"(",
"figure",
",",
"validate",
"=",
"True",
",",
"sharing",
"=",
"None",
",",
"filename",
"=",
"''",
",",
"online",
"=",
"None",
",",
"asImage",
"=",
"False",
",",
"asUrl",
"=",
"False",
",",
"asPlot",
"=",
"False",
",",
"dimensions"... | 30.503497 | 22.363636 |
def approximate_eig(self, epsilon=1e-6):
""" Compute low-rank approximation of the eigenvalue decomposition of target matrix.
If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive.
Parameters
----------
epsilon : float, o... | [
"def",
"approximate_eig",
"(",
"self",
",",
"epsilon",
"=",
"1e-6",
")",
":",
"L",
"=",
"self",
".",
"approximate_cholesky",
"(",
"epsilon",
"=",
"epsilon",
")",
"LL",
"=",
"np",
".",
"dot",
"(",
"L",
".",
"T",
",",
"L",
")",
"s",
",",
"V",
"=",
... | 39.225 | 26.6 |
def clear_cached_authc_info(self, identifier):
"""
When cached credentials are no longer needed, they can be manually
cleared with this method. However, account credentials may be
cached with a short expiration time (TTL), making the manual clearing
of cached credentials an alte... | [
"def",
"clear_cached_authc_info",
"(",
"self",
",",
"identifier",
")",
":",
"msg",
"=",
"\"Clearing cached authc_info for [{0}]\"",
".",
"format",
"(",
"identifier",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"self",
".",
"cache_handler",
".",
"delete",
"(",
... | 47.428571 | 25.142857 |
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
else:
raise FieldError('... | [
"def",
"has_changed",
"(",
"self",
",",
"field",
")",
":",
"if",
"not",
"self",
".",
"instance",
".",
"pk",
":",
"return",
"True",
"elif",
"field",
"in",
"self",
".",
"saved_data",
":",
"return",
"self",
".",
"previous",
"(",
"field",
")",
"!=",
"sel... | 43.125 | 14.625 |
def _merge(left, right, path=None, conflict=_Conflict.error):
"""
Merges values in place from *right* into *left*.
:param left: mapping to merge into
:param right: mapping to merge from
:param path: `list` of keys processed before (used for error reporting
only, should only need to be provi... | [
"def",
"_merge",
"(",
"left",
",",
"right",
",",
"path",
"=",
"None",
",",
"conflict",
"=",
"_Conflict",
".",
"error",
")",
":",
"path",
"=",
"path",
"or",
"[",
"]",
"conflict",
"=",
"_Conflict",
"(",
"conflict",
")",
"for",
"key",
"in",
"right",
"... | 45.882353 | 23.411765 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.