text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _wrap_callback_parse_link_event(subscription, on_data, message):
"""
Wraps a user callback to parse LinkEvents
from a WebSocket data message
"""
if message.type == message.DATA:
if message.data.type == yamcs_pb2.LINK_EVENT:
link_message = getattr(message.data, 'linkEvent')
... | [
"def",
"_wrap_callback_parse_link_event",
"(",
"subscription",
",",
"on_data",
",",
"message",
")",
":",
"if",
"message",
".",
"type",
"==",
"message",
".",
"DATA",
":",
"if",
"message",
".",
"data",
".",
"type",
"==",
"yamcs_pb2",
".",
"LINK_EVENT",
":",
... | 38.923077 | 9.076923 |
def _load_cache(self):
"""
the method is implemented for the purpose of optimization, byte positions will not be re-read from a file
that has already been used, if the content of the file has changed, and the name has been left the same,
the old version of byte offsets will be loaded
... | [
"def",
"_load_cache",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"__cache_path",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"load",
"(",
"f",
")",
"except",
"FileNotFoundError",
":",
"return",
"except",
"IsADirectoryError",
"as... | 50.0625 | 24.5625 |
def change_db(self, db, user=None):
"""Change connect database."""
# Get original config and change database key
config = self._config
config['database'] = db
if user:
config['user'] = user
self.database = db
# Close current database connection
... | [
"def",
"change_db",
"(",
"self",
",",
"db",
",",
"user",
"=",
"None",
")",
":",
"# Get original config and change database key",
"config",
"=",
"self",
".",
"_config",
"config",
"[",
"'database'",
"]",
"=",
"db",
"if",
"user",
":",
"config",
"[",
"'user'",
... | 28.428571 | 13.714286 |
def get_values(item):
"""Extract value from regex hit."""
fracs = r'|'.join(r.UNI_FRAC)
value = item.group(2)
value = re.sub(ur'(?<=\d)(%s)10' % r.MULTIPLIERS, 'e', value)
value = re.sub(fracs, callback, value, re.IGNORECASE)
value = re.sub(' +', ' ', value)
range_separator = re.findall(ur... | [
"def",
"get_values",
"(",
"item",
")",
":",
"fracs",
"=",
"r'|'",
".",
"join",
"(",
"r",
".",
"UNI_FRAC",
")",
"value",
"=",
"item",
".",
"group",
"(",
"2",
")",
"value",
"=",
"re",
".",
"sub",
"(",
"ur'(?<=\\d)(%s)10'",
"%",
"r",
".",
"MULTIPLIERS... | 34.235294 | 19.088235 |
def create(dataset, target, features=None, l2_penalty=1e-2, l1_penalty=0.0,
solver='auto', feature_rescaling=True,
convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'],
step_size = _DEFAULT_SOLVER_OPTIONS['step_size'],
lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'... | [
"def",
"create",
"(",
"dataset",
",",
"target",
",",
"features",
"=",
"None",
",",
"l2_penalty",
"=",
"1e-2",
",",
"l1_penalty",
"=",
"0.0",
",",
"solver",
"=",
"'auto'",
",",
"feature_rescaling",
"=",
"True",
",",
"convergence_threshold",
"=",
"_DEFAULT_SOL... | 44.992248 | 29.232558 |
def getSimulations(self, times, **kwargs):
"""
A generator to quickly access many simulations.
The arguments are the same as for `getSimulation`.
"""
for t in times:
yield self.getSimulation(t, **kwargs) | [
"def",
"getSimulations",
"(",
"self",
",",
"times",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"t",
"in",
"times",
":",
"yield",
"self",
".",
"getSimulation",
"(",
"t",
",",
"*",
"*",
"kwargs",
")"
] | 35.714286 | 8.857143 |
def setup_addon_register(self, harpoon):
"""Setup our addon register"""
# Create the addon getter and register the crosshairs namespace
self.addon_getter = AddonGetter()
self.addon_getter.add_namespace("harpoon.crosshairs", Result.FieldSpec(), Addon.FieldSpec())
# Initiate the a... | [
"def",
"setup_addon_register",
"(",
"self",
",",
"harpoon",
")",
":",
"# Create the addon getter and register the crosshairs namespace",
"self",
".",
"addon_getter",
"=",
"AddonGetter",
"(",
")",
"self",
".",
"addon_getter",
".",
"add_namespace",
"(",
"\"harpoon.crosshair... | 41.666667 | 22.833333 |
def _pop_none(self, kwargs):
"""Remove default values (anything where the value is None). click is unfortunately bad at the way it
sends through unspecified defaults."""
for key, value in copy(kwargs).items():
# options with multiple=True return a tuple
if value is None o... | [
"def",
"_pop_none",
"(",
"self",
",",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"copy",
"(",
"kwargs",
")",
".",
"items",
"(",
")",
":",
"# options with multiple=True return a tuple",
"if",
"value",
"is",
"None",
"or",
"value",
"==",
"(",
")"... | 48.888889 | 5.666667 |
def to_pandas(self):
"""Convert to pandas MultiIndex.
Returns
-------
pandas.base.MultiIndex
"""
if not all(ind.is_raw() for ind in self.values):
raise ValueError('Cannot convert to pandas MultiIndex if not evaluated.')
from pandas import MultiIndex... | [
"def",
"to_pandas",
"(",
"self",
")",
":",
"if",
"not",
"all",
"(",
"ind",
".",
"is_raw",
"(",
")",
"for",
"ind",
"in",
"self",
".",
"values",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot convert to pandas MultiIndex if not evaluated.'",
")",
"from",
"pand... | 28.125 | 24.9375 |
def stream(repo_uri, stream_uri, verbose, assume, sort, before=None, after=None):
"""Stream git history policy changes to destination.
Default stream destination is a summary of the policy changes to stdout, one
per line. Also supported for stdout streaming is `jsonline`.
AWS Kinesis and SQS destinat... | [
"def",
"stream",
"(",
"repo_uri",
",",
"stream_uri",
",",
"verbose",
",",
"assume",
",",
"sort",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(messag... | 39.244898 | 24.77551 |
def shutdown(self, how=socket.SHUT_RDWR):
"""
Send a shutdown signal for both reading and writing, or whatever
socket.SHUT_* constant you like.
Shutdown differs from closing in that it explicitly changes the state of
the socket resource to closed, whereas closing will only decre... | [
"def",
"shutdown",
"(",
"self",
",",
"how",
"=",
"socket",
".",
"SHUT_RDWR",
")",
":",
"if",
"self",
".",
"_sock_send",
"is",
"not",
"None",
":",
"self",
".",
"_sock_send",
".",
"shutdown",
"(",
"how",
")",
"return",
"self",
".",
"sock",
".",
"shutdo... | 49.5 | 21.944444 |
def grabEmails(emails=None, emailsFile=None, nicks=None, nicksFile=None, domains=EMAIL_DOMAINS, excludeDomains=[]):
"""
Method that generates a list of emails.
Args:
-----
emails: Any premade list of emails.
emailsFile: Filepath to the emails file (one per line).
nicks: A list o... | [
"def",
"grabEmails",
"(",
"emails",
"=",
"None",
",",
"emailsFile",
"=",
"None",
",",
"nicks",
"=",
"None",
",",
"nicksFile",
"=",
"None",
",",
"domains",
"=",
"EMAIL_DOMAINS",
",",
"excludeDomains",
"=",
"[",
"]",
")",
":",
"email_candidates",
"=",
"[",... | 36.348837 | 16.627907 |
def patch_memcache():
"""Monkey patch python-memcached to implement our consistent hashring
in its node selection and operations.
"""
def _init(self, servers, *k, **kw):
self._old_init(servers, *k, **kw)
nodes = {}
for server in self.servers:
conf = {
... | [
"def",
"patch_memcache",
"(",
")",
":",
"def",
"_init",
"(",
"self",
",",
"servers",
",",
"*",
"k",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_old_init",
"(",
"servers",
",",
"*",
"k",
",",
"*",
"*",
"kw",
")",
"nodes",
"=",
"{",
"}",
"for... | 31.228571 | 13.4 |
def _hash(secret: bytes, data: bytes, alg: str) -> bytes:
"""
Create a new HMAC hash.
:param secret: The secret used when hashing data.
:type secret: bytes
:param data: The data to hash.
:type data: bytes
:param alg: The algorithm to use when hashing `data`.
:type alg: str
:return: ... | [
"def",
"_hash",
"(",
"secret",
":",
"bytes",
",",
"data",
":",
"bytes",
",",
"alg",
":",
"str",
")",
"->",
"bytes",
":",
"algorithm",
"=",
"get_algorithm",
"(",
"alg",
")",
"return",
"hmac",
".",
"new",
"(",
"secret",
",",
"msg",
"=",
"data",
",",
... | 27.588235 | 15.588235 |
def weave(target, advices, pointcut=None, depth=1, public=False):
"""Weave advices such as Advice objects."""
advices = (
advice if isinstance(advice, Advice) else Advice(advice)
for advice in advices
)
weave(
target=target, advices=advices, pointcut... | [
"def",
"weave",
"(",
"target",
",",
"advices",
",",
"pointcut",
"=",
"None",
",",
"depth",
"=",
"1",
",",
"public",
"=",
"False",
")",
":",
"advices",
"=",
"(",
"advice",
"if",
"isinstance",
"(",
"advice",
",",
"Advice",
")",
"else",
"Advice",
"(",
... | 30.666667 | 22.75 |
def main(self, args=None):
"""Enter filesystem service loop."""
if get_compat_0_1():
args = self.main_0_1_preamble()
d = {'multithreaded': self.multithreaded and 1 or 0}
d['fuse_args'] = args or self.fuse_args.assemble()
for t in 'file_class', 'dir_class':
... | [
"def",
"main",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"if",
"get_compat_0_1",
"(",
")",
":",
"args",
"=",
"self",
".",
"main_0_1_preamble",
"(",
")",
"d",
"=",
"{",
"'multithreaded'",
":",
"self",
".",
"multithreaded",
"and",
"1",
"or",
"0"... | 31.964286 | 19.035714 |
def choice(self, other):
'''(|) This combinator implements choice. The parser p | q first applies p.
If it succeeds, the value of p is returned.
If p fails **without consuming any input**, parser q is tried.
NOTICE: without backtrack.'''
@Parser
def choice_parser(text, in... | [
"def",
"choice",
"(",
"self",
",",
"other",
")",
":",
"@",
"Parser",
"def",
"choice_parser",
"(",
"text",
",",
"index",
")",
":",
"res",
"=",
"self",
"(",
"text",
",",
"index",
")",
"return",
"res",
"if",
"res",
".",
"status",
"or",
"res",
".",
"... | 46.4 | 18.8 |
def update():
'''
Update the cache file for the bucket.
'''
metadata = _init()
if S3_SYNC_ON_UPDATE:
# sync the buckets to the local cache
log.info('Syncing local cache from S3...')
for saltenv, env_meta in six.iteritems(metadata):
for bucket_files in _find_file... | [
"def",
"update",
"(",
")",
":",
"metadata",
"=",
"_init",
"(",
")",
"if",
"S3_SYNC_ON_UPDATE",
":",
"# sync the buckets to the local cache",
"log",
".",
"info",
"(",
"'Syncing local cache from S3...'",
")",
"for",
"saltenv",
",",
"env_meta",
"in",
"six",
".",
"i... | 39.666667 | 26.904762 |
def _save_config(self, filename=None):
"""
Save the given user configuration.
"""
if filename is None:
filename = self._config_filename
parent_path = os.path.dirname(filename)
if not os.path.isdir(parent_path):
os.makedirs(parent_path)
with... | [
"def",
"_save_config",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"_config_filename",
"parent_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"not",
... | 35.272727 | 3.818182 |
def transfer(self, new_region_slug):
"""
Transfer the image
"""
return self.get_data(
"images/%s/actions/" % self.id,
type=POST,
params={"type": "transfer", "region": new_region_slug}
) | [
"def",
"transfer",
"(",
"self",
",",
"new_region_slug",
")",
":",
"return",
"self",
".",
"get_data",
"(",
"\"images/%s/actions/\"",
"%",
"self",
".",
"id",
",",
"type",
"=",
"POST",
",",
"params",
"=",
"{",
"\"type\"",
":",
"\"transfer\"",
",",
"\"region\"... | 28.555556 | 11.444444 |
def validate_wrap(self, value):
''' Validates the type and length of ``value`` '''
if not isinstance(value, basestring):
self._fail_validation_type(value, basestring)
if self.regex.match(value) is None:
self._fail_validation(value, 'Value does not match regular expression... | [
"def",
"validate_wrap",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"self",
".",
"_fail_validation_type",
"(",
"value",
",",
"basestring",
")",
"if",
"self",
".",
"regex",
".",
"match",
"(",
... | 52.833333 | 15.833333 |
def volume_disk_temp_max(self, volume):
"""Maximum temperature of all disks making up the volume"""
volume = self._get_volume(volume)
if volume is not None:
vol_disks = volume["disks"]
if vol_disks is not None:
max_temp = 0
for vol... | [
"def",
"volume_disk_temp_max",
"(",
"self",
",",
"volume",
")",
":",
"volume",
"=",
"self",
".",
"_get_volume",
"(",
"volume",
")",
"if",
"volume",
"is",
"not",
"None",
":",
"vol_disks",
"=",
"volume",
"[",
"\"disks\"",
"]",
"if",
"vol_disks",
"is",
"not... | 38.357143 | 11.928571 |
def unfreeze(label, pop=False, environ=None):
"""Reset the environment to its state before it was frozen by :func:`freeze`.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow unfreeze once.
:param dict environ: The environment to work on; de... | [
"def",
"unfreeze",
"(",
"label",
",",
"pop",
"=",
"False",
",",
"environ",
"=",
"None",
")",
":",
"environ",
"=",
"os",
".",
"environ",
"if",
"environ",
"is",
"None",
"else",
"environ",
"diff",
"=",
"_get_diff",
"(",
"environ",
",",
"label",
",",
"po... | 30.73913 | 23.173913 |
def maybe_thenable(obj, on_resolve):
"""
Execute a on_resolve function once the thenable is resolved,
returning the same type of object inputed.
If the object is not thenable, it should return on_resolve(obj)
"""
if isawaitable(obj) and not isinstance(obj, Promise):
return await_and_exec... | [
"def",
"maybe_thenable",
"(",
"obj",
",",
"on_resolve",
")",
":",
"if",
"isawaitable",
"(",
"obj",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"Promise",
")",
":",
"return",
"await_and_execute",
"(",
"obj",
",",
"on_resolve",
")",
"if",
"is_thenable"... | 35.133333 | 14.733333 |
def get_sections_with_students_in_course(self, course_id, params={}):
"""
Return list of sections including students for the passed course ID.
"""
include = params.get("include", [])
if "students" not in include:
include.append("students")
params["include"] = ... | [
"def",
"get_sections_with_students_in_course",
"(",
"self",
",",
"course_id",
",",
"params",
"=",
"{",
"}",
")",
":",
"include",
"=",
"params",
".",
"get",
"(",
"\"include\"",
",",
"[",
"]",
")",
"if",
"\"students\"",
"not",
"in",
"include",
":",
"include"... | 38.1 | 13.9 |
def restore(self, image):
"""
Restore the droplet to the specified backup image
A Droplet restoration will rebuild an image using a backup image.
The image ID that is passed in must be a backup of the current
Droplet instance. The operation will leave any embedded S... | [
"def",
"restore",
"(",
"self",
",",
"image",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"Image",
")",
":",
"image",
"=",
"image",
".",
"id",
"return",
"self",
".",
"act",
"(",
"type",
"=",
"'restore'",
",",
"image",
"=",
"image",
")"
] | 41.7 | 20.6 |
def reverse_readline(m_file, blk_size=4096, max_mem=4000000):
"""
Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.... | [
"def",
"reverse_readline",
"(",
"m_file",
",",
"blk_size",
"=",
"4096",
",",
"max_mem",
"=",
"4000000",
")",
":",
"# Check if the file stream is a bit stream or not",
"is_text",
"=",
"isinstance",
"(",
"m_file",
",",
"io",
".",
"TextIOWrapper",
")",
"try",
":",
... | 37.807229 | 20.216867 |
def fetch_celery_task_state(celery_task):
"""
Fetch and return the state of the given celery task. The scope of this function is
global so that it can be called by subprocesses in the pool.
:param celery_task: a tuple of the Celery task key and the async Celery object used
to fetch the task's s... | [
"def",
"fetch_celery_task_state",
"(",
"celery_task",
")",
":",
"try",
":",
"with",
"timeout",
"(",
"seconds",
"=",
"2",
")",
":",
"# Accessing state property of celery task will make actual network request",
"# to get the current state of the task.",
"res",
"=",
"(",
"cele... | 44.681818 | 24.045455 |
def get_nodes(environment=None):
"""Gets all nodes found in the nodes/ directory"""
if not os.path.exists('nodes'):
return []
nodes = []
for filename in sorted(
[f for f in os.listdir('nodes')
if (not os.path.isdir(f)
and f.endswith(".json") and not f.st... | [
"def",
"get_nodes",
"(",
"environment",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'nodes'",
")",
":",
"return",
"[",
"]",
"nodes",
"=",
"[",
"]",
"for",
"filename",
"in",
"sorted",
"(",
"[",
"f",
"for",
"f",
"in"... | 39.785714 | 16.357143 |
def index(self, columnnames, sort=True):
"""Return a tableindex object.
:class:`tableindex` lets one get the row numbers of the rows holding
given values for the columns for which the index is created.
It uses an in-memory index on which a binary search is done.
By default the t... | [
"def",
"index",
"(",
"self",
",",
"columnnames",
",",
"sort",
"=",
"True",
")",
":",
"from",
".",
"tableindex",
"import",
"tableindex",
"return",
"tableindex",
"(",
"self",
",",
"columnnames",
",",
"sort",
")"
] | 36.444444 | 21.722222 |
def _next_datetime_with_utc_hour(table_name, utc_hour):
'''
Datapipeline API is throttling us, as all the pipelines are started at the same time.
We would like to uniformly distribute the startTime over a 60 minute window.
Return the next future utc datetime where
hour == utc_hour
minut... | [
"def",
"_next_datetime_with_utc_hour",
"(",
"table_name",
",",
"utc_hour",
")",
":",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"# The minute and second values generated are deterministic, as we do not want",
"# pipeline definition to change for every run.",
... | 36.892857 | 23.321429 |
def run_sync(self):
"""
Runs the message loop until the Pebble disconnects. This method will block until the watch disconnects or
a fatal error occurs.
For alternatives that don't block forever, see :meth:`pump_reader` and :meth:`run_async`.
"""
while self.connected:
... | [
"def",
"run_sync",
"(",
"self",
")",
":",
"while",
"self",
".",
"connected",
":",
"try",
":",
"self",
".",
"pump_reader",
"(",
")",
"except",
"PacketDecodeError",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"\"Packet decode failed: %s\"",
",",
"e",
")",... | 37 | 20.714286 |
def panels():
"""Show all panels for a case."""
if request.method == 'POST':
# update an existing panel
csv_file = request.files['csv_file']
content = csv_file.stream.read()
lines = None
try:
if b'\n' in content:
lines = content.decode('utf-8',... | [
"def",
"panels",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"# update an existing panel",
"csv_file",
"=",
"request",
".",
"files",
"[",
"'csv_file'",
"]",
"content",
"=",
"csv_file",
".",
"stream",
".",
"read",
"(",
")",
"lines",
... | 42.387097 | 21.048387 |
def experiments_create(self, subject_id, image_group_id, properties):
"""Create an experiment object with subject, and image group. Objects
are referenced by their unique identifiers. The API ensure that at time
of creation all referenced objects exist. Referential consistency,
however, ... | [
"def",
"experiments_create",
"(",
"self",
",",
"subject_id",
",",
"image_group_id",
",",
"properties",
")",
":",
"# Ensure that reference subject exists",
"if",
"self",
".",
"subjects_get",
"(",
"subject_id",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'u... | 42.515152 | 22.393939 |
def __get_query_basic(cls, date_field=None, start=None, end=None,
filters={}):
"""
Create a es_dsl query object with the date range and filters.
:param date_field: field with the date value
:param start: date with the from value, should be a datetime.datetime o... | [
"def",
"__get_query_basic",
"(",
"cls",
",",
"date_field",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"filters",
"=",
"{",
"}",
")",
":",
"query_basic",
"=",
"Search",
"(",
")",
"query_filters",
"=",
"cls",
".",
"__get_query_... | 44.473684 | 23.947368 |
def _get_token_type_enum(self):
"""Builds the python source code for the Parser TokenType enum."""
fmt = "class TokenType(Enum):\n" \
"{indent}\"\"\"The token types for parse nodes generated by the Parser.\"\"\"\n" \
"{indent}" + \
"\n{indent}".join("{1} = {0}".format(num + 1, r.na... | [
"def",
"_get_token_type_enum",
"(",
"self",
")",
":",
"fmt",
"=",
"\"class TokenType(Enum):\\n\"",
"\"{indent}\\\"\\\"\\\"The token types for parse nodes generated by the Parser.\\\"\\\"\\\"\\n\"",
"\"{indent}\"",
"+",
"\"\\n{indent}\"",
".",
"join",
"(",
"\"{1} = {0}\"",
".",
"f... | 56.571429 | 20 |
def _stub_task(self, description, tags=None, **kw):
""" Given a description, stub out a task dict. """
# If whitespace is not removed here, TW will do it when we pass the
# task to it.
task = {"description": description.strip()}
# Allow passing "tags" in as part of kw.
... | [
"def",
"_stub_task",
"(",
"self",
",",
"description",
",",
"tags",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"# If whitespace is not removed here, TW will do it when we pass the",
"# task to it.",
"task",
"=",
"{",
"\"description\"",
":",
"description",
".",
"stri... | 28.428571 | 21.380952 |
def download_sample(job, sample, inputs):
"""
Download the input sample
:param JobFunctionWrappingJob job: passed by Toil automatically
:param tuple sample: Tuple containing (UUID,URL) of a sample
:param Namespace inputs: Stores input arguments (see main)
"""
uuid, url = sample
job.file... | [
"def",
"download_sample",
"(",
"job",
",",
"sample",
",",
"inputs",
")",
":",
"uuid",
",",
"url",
"=",
"sample",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Downloading sample: {}'",
".",
"format",
"(",
"uuid",
")",
")",
"# Download sample",
"tar_id"... | 43.555556 | 18.444444 |
async def create_email_identity(self,
client_id, identity, passwd, *,
user_id=None # 如果设置用户ID,则创建该用户的新登录身份
) -> SessionIdentity :
""" 创建使用电子邮件地址和密码登录的用户身份 """
assert passwd
value, _ = await self._client.get(f"/users/identity/{identity}")
if val... | [
"async",
"def",
"create_email_identity",
"(",
"self",
",",
"client_id",
",",
"identity",
",",
"passwd",
",",
"*",
",",
"user_id",
"=",
"None",
"# 如果设置用户ID,则创建该用户的新登录身份",
")",
"->",
"SessionIdentity",
":",
"assert",
"passwd",
"value",
",",
"_",
"=",
"await",
... | 30.1 | 22.033333 |
def _get_library_search_paths():
"""
Returns a list of library search paths, considering of the current working
directory, default paths and paths from environment variables.
"""
search_paths = [
'',
'/usr/lib64',
'/usr/local/lib64',
'/usr/lib', '/usr/local/lib',
... | [
"def",
"_get_library_search_paths",
"(",
")",
":",
"search_paths",
"=",
"[",
"''",
",",
"'/usr/lib64'",
",",
"'/usr/local/lib64'",
",",
"'/usr/lib'",
",",
"'/usr/local/lib'",
",",
"'/run/current-system/sw/lib'",
",",
"'/usr/lib/x86_64-linux-gnu/'",
",",
"os",
".",
"pa... | 33.227273 | 17.045455 |
def create(self, service_name, json, **kwargs):
"""Create a new AppNexus object"""
return self._send(requests.post, service_name, json, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"service_name",
",",
"json",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_send",
"(",
"requests",
".",
"post",
",",
"service_name",
",",
"json",
",",
"*",
"*",
"kwargs",
")"
] | 53 | 12.333333 |
def add_route(app, fn, context=default_context):
"""
a decorator that adds a transmute route to the application.
"""
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add... | [
"def",
"add_route",
"(",
"app",
",",
"fn",
",",
"context",
"=",
"default_context",
")",
":",
"transmute_func",
"=",
"TransmuteFunction",
"(",
"fn",
",",
"args_not_from_request",
"=",
"[",
"\"request\"",
"]",
")",
"handler",
"=",
"create_handler",
"(",
"transmu... | 35.8125 | 13.8125 |
def _family_id_to_superclass(self, family_id):
"""
Temporary hardcoded mapping from serialized family id to either `class :XBlock:` or `:XBlockAside`
"""
for family in [XBlock, XBlockAside]:
if family_id == family.entry_point:
return family
raise Value... | [
"def",
"_family_id_to_superclass",
"(",
"self",
",",
"family_id",
")",
":",
"for",
"family",
"in",
"[",
"XBlock",
",",
"XBlockAside",
"]",
":",
"if",
"family_id",
"==",
"family",
".",
"entry_point",
":",
"return",
"family",
"raise",
"ValueError",
"(",
"'No s... | 44.75 | 14.75 |
def entries(self):
"""
Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the give... | [
"def",
"entries",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Getting entries\"",
")",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"This container does not exist. Wrong path?\"",
",",
"None",
",",
"True",
",",
... | 46.1875 | 19.6875 |
def submit_property_batch(
self, name_id, timeout=60, operations=None, custom_headers=None, raw=False, **operation_config):
"""Submits a property batch.
Submits a batch of property operations. Either all or none of the
operations will be committed.
:param name_id: The Servi... | [
"def",
"submit_property_batch",
"(",
"self",
",",
"name_id",
",",
"timeout",
"=",
"60",
",",
"operations",
"=",
"None",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"operation_config",
")",
":",
"property_batch_description_list"... | 43.644737 | 26.947368 |
def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"poolmanager",
".",
"clear",
"(",
")",
"for",
"proxy",
"in",
"self",
".",
"proxy_manager",
".",
"values",
"(",
")",
":",
"proxy",
".",
"clear",
"(",
")"
] | 32.666667 | 15 |
def handle_data(self, context, data, dt):
"""
Calls the callable only when the rule is triggered.
"""
if self.rule.should_trigger(dt):
self.callback(context, data) | [
"def",
"handle_data",
"(",
"self",
",",
"context",
",",
"data",
",",
"dt",
")",
":",
"if",
"self",
".",
"rule",
".",
"should_trigger",
"(",
"dt",
")",
":",
"self",
".",
"callback",
"(",
"context",
",",
"data",
")"
] | 33.666667 | 3.333333 |
def _sanitize_dates(start, end):
"""
Return (datetime_start, datetime_end) tuple
if start is None - default is 2015/01/01
if end is None - default is today
"""
if isinstance(start, int):
# regard int as year
start = datetime(start, 1, 1)
start = to_datetime(start)
... | [
"def",
"_sanitize_dates",
"(",
"start",
",",
"end",
")",
":",
"if",
"isinstance",
"(",
"start",
",",
"int",
")",
":",
"# regard int as year\r",
"start",
"=",
"datetime",
"(",
"start",
",",
"1",
",",
"1",
")",
"start",
"=",
"to_datetime",
"(",
"start",
... | 28.136364 | 12.590909 |
def convert(word):
"""This method converts given `word` to UTF-8 encoding and `bytes` type for the
SWIG wrapper."""
if six.PY2:
if isinstance(word, unicode):
return word.encode('utf-8')
else:
return word.decode('utf-8').encode('utf-8') # make sure it is real utf8, ... | [
"def",
"convert",
"(",
"word",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"isinstance",
"(",
"word",
",",
"unicode",
")",
":",
"return",
"word",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"word",
".",
"decode",
"(",
"'utf-8'",
")... | 38.916667 | 17.583333 |
def load_config(self, argv=None, aliases=None, flags=None):
"""Parse the configuration and generate the Config object.
After loading, any arguments that are not key-value or
flags will be stored in self.extra_args - a list of
unparsed command-line arguments. This is used for
ar... | [
"def",
"load_config",
"(",
"self",
",",
"argv",
"=",
"None",
",",
"aliases",
"=",
"None",
",",
"flags",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"config",
".",
"configurable",
"import",
"Configurable",
"self",
".",
"clear",
"(",
")",
"if",
"argv"... | 40.868421 | 18.118421 |
def activate_program(self, program):
"""
Called by program which desires to manipulate this actuator, when it is activated.
"""
self.logger.debug("activate_program %s", program)
if program in self.program_stack:
return
with self._program_lock:
... | [
"def",
"activate_program",
"(",
"self",
",",
"program",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"activate_program %s\"",
",",
"program",
")",
"if",
"program",
"in",
"self",
".",
"program_stack",
":",
"return",
"with",
"self",
".",
"_program_loc... | 38.25 | 15.416667 |
def histogram_pb(tag, data, buckets=None, description=None):
"""Create a histogram summary protobuf.
Arguments:
tag: String tag for the summary.
data: A `np.array` or array-like form of any shape. Must have type
castable to `float`.
buckets: Optional positive `int`. The output will have this
... | [
"def",
"histogram_pb",
"(",
"tag",
",",
"data",
",",
"buckets",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"bucket_count",
"=",
"DEFAULT_BUCKET_COUNT",
"if",
"buckets",
"is",
"None",
"else",
"buckets",
"data",
"=",
"np",
".",
"array",
"(",
"... | 40.288462 | 18.903846 |
def estimate_tx_gas(self, safe_address: str, to: str, value: int, data: bytes, operation: int) -> int:
"""
Estimate tx gas. Use the max of calculation using safe method and web3 if operation == CALL or
use just the safe calculation otherwise
"""
# Costs to route through the proxy... | [
"def",
"estimate_tx_gas",
"(",
"self",
",",
"safe_address",
":",
"str",
",",
"to",
":",
"str",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
",",
"operation",
":",
"int",
")",
"->",
"int",
":",
"# Costs to route through the proxy and nested calls",
"p... | 55.083333 | 28.5 |
def track_statistic(self, name, description='', max_rows=None):
"""
Create a Statistic object in the Tracker.
"""
if name in self._tables:
raise TableConflictError(name)
if max_rows is None:
max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE
self.... | [
"def",
"track_statistic",
"(",
"self",
",",
"name",
",",
"description",
"=",
"''",
",",
"max_rows",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"_tables",
":",
"raise",
"TableConflictError",
"(",
"name",
")",
"if",
"max_rows",
"is",
"None",
... | 43.8 | 13.6 |
def get_draft_page_by_id(self, page_id, status='draft'):
"""
Provide content by id with status = draft
:param page_id:
:param status:
:return:
"""
url = 'rest/api/content/{page_id}?status={status}'.format(page_id=page_id, status=status)
return self.get(url... | [
"def",
"get_draft_page_by_id",
"(",
"self",
",",
"page_id",
",",
"status",
"=",
"'draft'",
")",
":",
"url",
"=",
"'rest/api/content/{page_id}?status={status}'",
".",
"format",
"(",
"page_id",
"=",
"page_id",
",",
"status",
"=",
"status",
")",
"return",
"self",
... | 34.777778 | 17 |
def patched_context(*module_names, **kwargs):
"""apply emulation patches only for a specific context
:param module_names: var-args for the modules to patch, as in :func:`patch`
:param local:
if True, unpatching is done on every switch-out, and re-patching on
every switch-in, so that they ar... | [
"def",
"patched_context",
"(",
"*",
"module_names",
",",
"*",
"*",
"kwargs",
")",
":",
"local",
"=",
"kwargs",
".",
"pop",
"(",
"'local'",
",",
"False",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"patched_context() got an unexpected keyword \"",
"+... | 33.3 | 21.866667 |
def get_dataset(self, key, info, out=None):
"""Get a dataset from the file."""
logger.debug("Reading %s.", key.name)
values = self.file_content[key.name]
selected = np.array(self.selected)
if key.name in ("Latitude", "Longitude"):
values = values / 10000.
if ... | [
"def",
"get_dataset",
"(",
"self",
",",
"key",
",",
"info",
",",
"out",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Reading %s.\"",
",",
"key",
".",
"name",
")",
"values",
"=",
"self",
".",
"file_content",
"[",
"key",
".",
"name",
"]",
"... | 35 | 15.071429 |
def get_git_version(path):
"""Get the GIT version."""
branch_name = get_git_cleaned_branch_name(path)
# Determine whether working copy is dirty (i.e. contains modified files)
mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
dirty = '.dirty' if mods else ''
# Get a lis... | [
"def",
"get_git_version",
"(",
"path",
")",
":",
"branch_name",
"=",
"get_git_cleaned_branch_name",
"(",
"path",
")",
"# Determine whether working copy is dirty (i.e. contains modified files)",
"mods",
"=",
"run_cmd",
"(",
"path",
",",
"'git'",
",",
"'status'",
",",
"'-... | 47.25 | 19.068182 |
def get_argval(argstr_, type_=None, default=None, help_=None, smartcast=True,
return_specified=None, argv=None, verbose=None,
debug=None, return_was_specified=False, pos=None):
r"""
Returns a value of an argument specified on the command line after some flag
Args:
args... | [
"def",
"get_argval",
"(",
"argstr_",
",",
"type_",
"=",
"None",
",",
"default",
"=",
"None",
",",
"help_",
"=",
"None",
",",
"smartcast",
"=",
"True",
",",
"return_specified",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"verbose",
"=",
"None",
",",
"... | 46.639706 | 21.959559 |
def _entity_list_as_bel(entities: Iterable[BaseEntity]) -> str:
"""Stringify a list of BEL entities."""
return ', '.join(
e.as_bel()
for e in entities
) | [
"def",
"_entity_list_as_bel",
"(",
"entities",
":",
"Iterable",
"[",
"BaseEntity",
"]",
")",
"->",
"str",
":",
"return",
"', '",
".",
"join",
"(",
"e",
".",
"as_bel",
"(",
")",
"for",
"e",
"in",
"entities",
")"
] | 29.166667 | 19 |
def create_resumable_upload_session(
self, content_type=None, size=None, origin=None, client=None
):
"""Create a resumable upload session.
Resumable upload sessions allow you to start an upload session from
one client and complete the session in another. This method is called
... | [
"def",
"create_resumable_upload_session",
"(",
"self",
",",
"content_type",
"=",
"None",
",",
"size",
"=",
"None",
",",
"origin",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"extra_headers",
"=",
"{",
"}",
"if",
"origin",
"is",
"not",
"None",
":",... | 42.478261 | 23.847826 |
def get_files(self):
"""
Read and parse files from a directory,
return a dictionary of path => post
"""
files = {}
for filename in os.listdir(self.source):
path = os.path.join(self.source, filename)
files[filename] = frontmatter.load(path,
... | [
"def",
"get_files",
"(",
"self",
")",
":",
"files",
"=",
"{",
"}",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"source",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"source",
",",
"filename",
")",... | 31.538462 | 12.461538 |
def copy_to_file(self, name, fp_dest, callback=None):
"""Write cur_dir/name to file-like `fp_dest`.
Args:
name (str): file name, located in self.curdir
fp_dest (file-like): must support write() method
callback (function, optional):
Called like ... | [
"def",
"copy_to_file",
"(",
"self",
",",
"name",
",",
"fp_dest",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"compat",
".",
"is_native",
"(",
"name",
")",
"def",
"_write_to_file",
"(",
"data",
")",
":",
"# print(\"_write_to_file() {} bytes.\".format(len(da... | 35.45 | 18.65 |
def etd_ms_py2dict(elements):
"""Convert a Python object into a Python dictionary."""
metadata_dict = {}
# Loop through all elements in the Python object.
for element in elements.children:
# Start an empty element list if an entry for the element
# list hasn't been made in the dictionary... | [
"def",
"etd_ms_py2dict",
"(",
"elements",
")",
":",
"metadata_dict",
"=",
"{",
"}",
"# Loop through all elements in the Python object.",
"for",
"element",
"in",
"elements",
".",
"children",
":",
"# Start an empty element list if an entry for the element",
"# list hasn't been ma... | 43.742857 | 11.257143 |
def read_chunk(filename, offset=-1, length=-1, escape_data=False):
"""
Read a chunk of a file from an offset upto the length.
"""
try:
length = int(length)
offset = int(offset)
except ValueError:
return {}
if not os.path.isfile(filename):
return {}
try:
fstat = os.stat(filename)
ex... | [
"def",
"read_chunk",
"(",
"filename",
",",
"offset",
"=",
"-",
"1",
",",
"length",
"=",
"-",
"1",
",",
"escape_data",
"=",
"False",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"length",
")",
"offset",
"=",
"int",
"(",
"offset",
")",
"except",
... | 19.805556 | 22.416667 |
def set_icon(self, icon, qtgui_module):
"""Save the icon and set its attributes."""
if self._use_fallback:
icon.addFile(self._fallback)
else:
for role, pixmap in self._roles.items():
if role.endswith("off"):
mode = role[:-3]
... | [
"def",
"set_icon",
"(",
"self",
",",
"icon",
",",
"qtgui_module",
")",
":",
"if",
"self",
".",
"_use_fallback",
":",
"icon",
".",
"addFile",
"(",
"self",
".",
"_fallback",
")",
"else",
":",
"for",
"role",
",",
"pixmap",
"in",
"self",
".",
"_roles",
"... | 33.708333 | 17.083333 |
def verify_create_instance(self, **kwargs):
"""Verifies an instance creation command.
Without actually placing an order.
See :func:`create_instance` for a list of available options.
Example::
new_vsi = {
'domain': u'test01.labs.sftlyr.ws',
'... | [
"def",
"verify_create_instance",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"pop",
"(",
"'tags'",
",",
"None",
")",
"create_options",
"=",
"self",
".",
"_generate_create_dict",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"gue... | 36.375 | 15.0625 |
def zip_job(job_ini, archive_zip='', risk_ini='', oq=None, log=logging.info):
"""
Zip the given job.ini file into the given archive, together with all
related files.
"""
if not os.path.exists(job_ini):
sys.exit('%s does not exist' % job_ini)
archive_zip = archive_zip or 'job.zip'
if ... | [
"def",
"zip_job",
"(",
"job_ini",
",",
"archive_zip",
"=",
"''",
",",
"risk_ini",
"=",
"''",
",",
"oq",
"=",
"None",
",",
"log",
"=",
"logging",
".",
"info",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"job_ini",
")",
":",
"sys"... | 44.333333 | 14.666667 |
def assert_between(lower_bound, upper_bound, expr, msg_fmt="{msg}"):
"""Fail if an expression is not between certain bounds (inclusive).
>>> assert_between(5, 15, 5)
>>> assert_between(5, 15, 15)
>>> assert_between(5, 15, 4.9)
Traceback (most recent call last):
...
AssertionError: 4.9 i... | [
"def",
"assert_between",
"(",
"lower_bound",
",",
"upper_bound",
",",
"expr",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"if",
"not",
"lower_bound",
"<=",
"expr",
"<=",
"upper_bound",
":",
"msg",
"=",
"\"{!r} is not between {} and {}\"",
".",
"format",
"(",
"... | 30.461538 | 17 |
def requires_grad(m:nn.Module, b:Optional[bool]=None)->Optional[bool]:
"If `b` is not set return `requires_grad` of first param, else set `requires_grad` on all params as `b`"
ps = list(m.parameters())
if not ps: return None
if b is None: return ps[0].requires_grad
for p in ps: p.requires_grad=b | [
"def",
"requires_grad",
"(",
"m",
":",
"nn",
".",
"Module",
",",
"b",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"ps",
"=",
"list",
"(",
"m",
".",
"parameters",
"(",
")",
")",
"if",
"not",
"ps"... | 51.833333 | 22.166667 |
def restore_point(cls, cluster_id_label, s3_location, backup_id, table_names, overwrite=True, automatic=True):
"""
Restoring cluster from a given hbase snapshot id
"""
conn = Qubole.agent(version=Cluster.api_version)
parameters = {}
parameters['s3_location'] = s3_location... | [
"def",
"restore_point",
"(",
"cls",
",",
"cluster_id_label",
",",
"s3_location",
",",
"backup_id",
",",
"table_names",
",",
"overwrite",
"=",
"True",
",",
"automatic",
"=",
"True",
")",
":",
"conn",
"=",
"Qubole",
".",
"agent",
"(",
"version",
"=",
"Cluste... | 48.833333 | 16.5 |
def node_is_embedded_doc_attr(node):
"""Checks if a node is a valid field or method in a embedded document.
"""
embedded_doc = get_field_embedded_doc(node.last_child())
name = node.attrname
try:
r = bool(embedded_doc.lookup(name)[1][0])
except IndexError:
r = False
return r | [
"def",
"node_is_embedded_doc_attr",
"(",
"node",
")",
":",
"embedded_doc",
"=",
"get_field_embedded_doc",
"(",
"node",
".",
"last_child",
"(",
")",
")",
"name",
"=",
"node",
".",
"attrname",
"try",
":",
"r",
"=",
"bool",
"(",
"embedded_doc",
".",
"lookup",
... | 28.090909 | 17.272727 |
def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata is... | [
"def",
"import_obj",
"(",
"cls",
",",
"i_datasource",
",",
"import_time",
"=",
"None",
")",
":",
"def",
"lookup_sqlatable",
"(",
"table",
")",
":",
"return",
"db",
".",
"session",
".",
"query",
"(",
"SqlaTable",
")",
".",
"join",
"(",
"Database",
")",
... | 46.6 | 19.15 |
def precision_series(y_true, y_score, k=None):
"""
Returns series of length k whose i-th entry is the precision in the top i
TODO: extrapolate here
"""
y_true, y_score = to_float(y_true, y_score)
top = _argsort(y_score, k)
n = np.nan_to_num(y_true[top]).cumsum() # fill missing labels with ... | [
"def",
"precision_series",
"(",
"y_true",
",",
"y_score",
",",
"k",
"=",
"None",
")",
":",
"y_true",
",",
"y_score",
"=",
"to_float",
"(",
"y_true",
",",
"y_score",
")",
"top",
"=",
"_argsort",
"(",
"y_score",
",",
"k",
")",
"n",
"=",
"np",
".",
"n... | 39.727273 | 17.363636 |
def juliandate(time: datetime) -> float:
"""
Python datetime to Julian time
from D.Vallado Fundamentals of Astrodynamics and Applications p.187
and J. Meeus Astronomical Algorithms 1991 Eqn. 7.1 pg. 61
Parameters
----------
time : datetime.datetime
time to convert
Results
... | [
"def",
"juliandate",
"(",
"time",
":",
"datetime",
")",
"->",
"float",
":",
"times",
"=",
"np",
".",
"atleast_1d",
"(",
"time",
")",
"assert",
"times",
".",
"ndim",
"==",
"1",
"jd",
"=",
"np",
".",
"empty",
"(",
"times",
".",
"size",
")",
"for",
... | 22.075 | 21.775 |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
n=pa... | [
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"TEL\"",
",",
"None",
")",
"for",
"t",
"in",
"(",
"\"home\"",
",",
"\"work\"",
",",
"\"voice\"",
",",
"\"fax\"",
",",
"\"pager\"",
",",
... | 36.294118 | 15.647059 |
def genty(target_cls):
"""
This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class`
""... | [
"def",
"genty",
"(",
"target_cls",
")",
":",
"tests",
"=",
"_expand_tests",
"(",
"target_cls",
")",
"tests_with_datasets",
"=",
"_expand_datasets",
"(",
"tests",
")",
"tests_with_datasets_and_repeats",
"=",
"_expand_repeats",
"(",
"tests_with_datasets",
")",
"_add_new... | 31.222222 | 22.111111 |
def backward(self, diff_x, influences, activations, **kwargs):
"""
Backward pass through the network, including update.
Parameters
----------
diff_x : numpy array
A matrix containing the differences between the input and neurons.
influences : numpy array
... | [
"def",
"backward",
"(",
"self",
",",
"diff_x",
",",
"influences",
",",
"activations",
",",
"*",
"*",
"kwargs",
")",
":",
"bmu",
"=",
"self",
".",
"_get_bmu",
"(",
"activations",
")",
"influence",
"=",
"influences",
"[",
"bmu",
"]",
"update",
"=",
"np",... | 34.32 | 19.36 |
def __process_warc_gz_file(self, path_name):
"""
Iterates all transactions in one WARC file and for each transaction tries to extract an article object.
Afterwards, each article is checked against the filter criteria and if all are passed, the function
on_valid_article_extracted is invok... | [
"def",
"__process_warc_gz_file",
"(",
"self",
",",
"path_name",
")",
":",
"counter_article_total",
"=",
"0",
"counter_article_passed",
"=",
"0",
"counter_article_discarded",
"=",
"0",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"with",
"open",
"(",
"path_n... | 48.57377 | 25.491803 |
def _apply_padding(lhs_arr, rhs_arr, offset, pad_mode, direction):
"""Apply padding to ``lhs_arr`` according to ``pad_mode``.
This helper assigns the values in the excess parts (if existent)
of ``lhs_arr`` according to the provided padding mode.
This applies to the following values for ``pad_mode``:
... | [
"def",
"_apply_padding",
"(",
"lhs_arr",
",",
"rhs_arr",
",",
"offset",
",",
"pad_mode",
",",
"direction",
")",
":",
"if",
"pad_mode",
"not",
"in",
"(",
"'periodic'",
",",
"'symmetric'",
",",
"'order0'",
",",
"'order1'",
")",
":",
"return",
"full_slc",
"="... | 44.941463 | 21.443902 |
def name_resolve(self, name=None, recursive=False,
nocache=False, **kwargs):
"""Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, th... | [
"def",
"name_resolve",
"(",
"self",
",",
"name",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"nocache",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"recursive\"",
":",
"recursive",
",... | 38.548387 | 22.516129 |
def _delete_nve_db(self, vni, device_id, mcast_group, host_id):
"""Delete the nexus NVE database entry.
Called during delete precommit port event.
"""
rows = nxos_db.get_nve_vni_deviceid_bindings(vni, device_id)
for row in rows:
nxos_db.remove_nexusnve_binding(vni, r... | [
"def",
"_delete_nve_db",
"(",
"self",
",",
"vni",
",",
"device_id",
",",
"mcast_group",
",",
"host_id",
")",
":",
"rows",
"=",
"nxos_db",
".",
"get_nve_vni_deviceid_bindings",
"(",
"vni",
",",
"device_id",
")",
"for",
"row",
"in",
"rows",
":",
"nxos_db",
"... | 42.125 | 18.875 |
def getTableName(self, tableClass):
"""
Retrieve the fully qualified name of the table holding items
of a particular class in this store. If the table does not
exist in the database, it will be created as a side-effect.
@param tableClass: an Item subclass
@raises axiom... | [
"def",
"getTableName",
"(",
"self",
",",
"tableClass",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"tableClass",
",",
"type",
")",
"and",
"issubclass",
"(",
"tableClass",
",",
"item",
".",
"Item",
")",
")",
":",
"raise",
"errors",
".",
"ItemClassesOnl... | 43.238095 | 23.428571 |
def error(self, msg, file=None):
"""
Outputs the error msg to the file if specified, or to the
io_manager's stderr if available, or to sys.stderr.
"""
self.error_encountered = True
file.write(self.error_prefix)
file.write(msg)
file.write('\n')
file... | [
"def",
"error",
"(",
"self",
",",
"msg",
",",
"file",
"=",
"None",
")",
":",
"self",
".",
"error_encountered",
"=",
"True",
"file",
".",
"write",
"(",
"self",
".",
"error_prefix",
")",
"file",
".",
"write",
"(",
"msg",
")",
"file",
".",
"write",
"(... | 31.9 | 11.1 |
def check_tune_params_list(tune_params):
""" raise an exception if a tune parameter has a forbidden name """
forbidden_names = ("grid_size_x", "grid_size_y", "grid_size_z")
forbidden_name_substr = ("time", "times")
for name, param in tune_params.items():
if name in forbidden_names:
r... | [
"def",
"check_tune_params_list",
"(",
"tune_params",
")",
":",
"forbidden_names",
"=",
"(",
"\"grid_size_x\"",
",",
"\"grid_size_y\"",
",",
"\"grid_size_z\"",
")",
"forbidden_name_substr",
"=",
"(",
"\"time\"",
",",
"\"times\"",
")",
"for",
"name",
",",
"param",
"... | 69 | 26.9 |
def mean(self):
"""Compute mean of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
"""
if self._can_use_new_school():
self._prep_spark_sql_groupby()
import pyspark.sql.functions as func
return self._use... | [
"def",
"mean",
"(",
"self",
")",
":",
"if",
"self",
".",
"_can_use_new_school",
"(",
")",
":",
"self",
".",
"_prep_spark_sql_groupby",
"(",
")",
"import",
"pyspark",
".",
"sql",
".",
"functions",
"as",
"func",
"return",
"self",
".",
"_use_aggregation",
"("... | 39.461538 | 11.230769 |
def _walk(directory, enable_scandir=False, **kwargs):
"""
Internal function to return walk generator either from os or scandir
:param directory: directory to traverse
:param enable_scandir: on python < 3.5 enable external scandir package
:param kwargs: arguments to pass to walk function
:return... | [
"def",
"_walk",
"(",
"directory",
",",
"enable_scandir",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"walk",
"=",
"os",
".",
"walk",
"if",
"python_version",
"<",
"(",
"3",
",",
"5",
")",
"and",
"enable_scandir",
":",
"import",
"scandir",
"walk",
... | 34.928571 | 15.357143 |
def evolve(self, new_date):
"""
evolve to the new process state at the next date
:param date new_date: date or point in time of the new state
:return State:
"""
if self.state.date == new_date and not self.initial_state.date == new_date:
return self.state
... | [
"def",
"evolve",
"(",
"self",
",",
"new_date",
")",
":",
"if",
"self",
".",
"state",
".",
"date",
"==",
"new_date",
"and",
"not",
"self",
".",
"initial_state",
".",
"date",
"==",
"new_date",
":",
"return",
"self",
".",
"state",
"if",
"self",
".",
"_l... | 37.4375 | 19.6875 |
def forall(self, vars_list: List[str]) -> 'TensorFluent':
'''Returns the TensorFluent for the forall aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the forall aggregation function.
'''
... | [
"def",
"forall",
"(",
"self",
",",
"vars_list",
":",
"List",
"[",
"str",
"]",
")",
"->",
"'TensorFluent'",
":",
"return",
"self",
".",
"_aggregation_op",
"(",
"tf",
".",
"reduce_all",
",",
"self",
",",
"vars_list",
")"
] | 37.1 | 29.1 |
def main():
"""Program entry point.
"""
global cf_verbose, cf_show_comment, cf_charset
global cf_extract, cf_test_read, cf_test_unrar
global cf_test_memory
psw = None
# parse args
try:
opts, args = getopt.getopt(sys.argv[1:], 'p:C:hvcxtRM')
except getopt.error as ex:
... | [
"def",
"main",
"(",
")",
":",
"global",
"cf_verbose",
",",
"cf_show_comment",
",",
"cf_charset",
"global",
"cf_extract",
",",
"cf_test_read",
",",
"cf_test_unrar",
"global",
"cf_test_memory",
"psw",
"=",
"None",
"# parse args",
"try",
":",
"opts",
",",
"args",
... | 22.931034 | 19.137931 |
def get_element(self, tag_name, attribute, **attribute_filter):
"""
Return element in xml files which match with the tag name and the specific attribute
:param tag_name: specify the tag name
:type tag_name: string
:param attribute: specify the attribute
... | [
"def",
"get_element",
"(",
"self",
",",
"tag_name",
",",
"attribute",
",",
"*",
"*",
"attribute_filter",
")",
":",
"for",
"i",
"in",
"self",
".",
"xml",
":",
"if",
"self",
".",
"xml",
"[",
"i",
"]",
"is",
"None",
":",
"continue",
"tag",
"=",
"self"... | 33.575758 | 17.393939 |
def get_key(self, key, bucket_name=None):
"""
Returns a boto3.s3.Object
:param key: the path to the key
:type key: str
:param bucket_name: the name of the bucket
:type bucket_name: str
"""
if not bucket_name:
(bucket_name, key) = self.parse_s3... | [
"def",
"get_key",
"(",
"self",
",",
"key",
",",
"bucket_name",
"=",
"None",
")",
":",
"if",
"not",
"bucket_name",
":",
"(",
"bucket_name",
",",
"key",
")",
"=",
"self",
".",
"parse_s3_url",
"(",
"key",
")",
"obj",
"=",
"self",
".",
"get_resource_type",... | 28.133333 | 15.066667 |
def send_job_and_wait(self, message, body_params=None, timeout=None, raises=False):
""".. versionchanged:: 0.8.4
Send a message as a job and wait for the response.
.. note::
Not all messages are jobs, you'll have to find out which are which
:param message: a message instanc... | [
"def",
"send_job_and_wait",
"(",
"self",
",",
"message",
",",
"body_params",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"raises",
"=",
"False",
")",
":",
"job_id",
"=",
"self",
".",
"send_job",
"(",
"message",
",",
"body_params",
")",
"response",
"="... | 43.458333 | 18.666667 |
def get_functionalHome(self, functionalHomeType: type) -> FunctionalHome:
""" gets the specified functionalHome
Args:
functionalHome(type): the type of the functionalHome which should be returned
Returns:
the FunctionalHome or None if it couldn't be found... | [
"def",
"get_functionalHome",
"(",
"self",
",",
"functionalHomeType",
":",
"type",
")",
"->",
"FunctionalHome",
":",
"for",
"x",
"in",
"self",
".",
"functionalHomes",
":",
"if",
"isinstance",
"(",
"x",
",",
"functionalHomeType",
")",
":",
"return",
"x",
"retu... | 32.857143 | 22.285714 |
def mysql(
self,
tableName,
filepath=None,
createStatement=None
):
"""*Render the dataset as a series of mysql insert statements*
**Key Arguments:**
- ``tableName`` -- the name of the mysql db table to assign the insert statements to.
- ``file... | [
"def",
"mysql",
"(",
"self",
",",
"tableName",
",",
"filepath",
"=",
"None",
",",
"createStatement",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``csv`` method'",
")",
"import",
"re",
"if",
"createStatement",
"and",
"\"create... | 40.758065 | 34.290323 |
def install_modules(wip):
"""Install the plugin modules"""
def install_module(hfos_module):
"""Install a single module via setuptools"""
try:
setup = Popen(
[
sys.executable,
'setup.py',
'develop'
... | [
"def",
"install_modules",
"(",
"wip",
")",
":",
"def",
"install_module",
"(",
"hfos_module",
")",
":",
"\"\"\"Install a single module via setuptools\"\"\"",
"try",
":",
"setup",
"=",
"Popen",
"(",
"[",
"sys",
".",
"executable",
",",
"'setup.py'",
",",
"'develop'",... | 25.818182 | 22.141414 |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
"""Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows ... | [
"def",
"ExtractEvents",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
",",
"*",
"*",
"kwargs",
")",
":",
"values_dict",
"=",
"{",
"}",
"if",
"registry_key",
".",
"number_of_values",
">",
"0",
":",
"for",
"registry_value",
"in",
"registry_key",
".... | 37.926606 | 20.238532 |
def get_vt_xml(self, vt_id):
""" Gets a single vulnerability test information in XML format.
@return: String of single vulnerability test information in XML format.
"""
if not vt_id:
return Element('vt')
vt = self.vts.get(vt_id)
name = vt.get('name')
... | [
"def",
"get_vt_xml",
"(",
"self",
",",
"vt_id",
")",
":",
"if",
"not",
"vt_id",
":",
"return",
"Element",
"(",
"'vt'",
")",
"vt",
"=",
"self",
".",
"vts",
".",
"get",
"(",
"vt_id",
")",
"name",
"=",
"vt",
".",
"get",
"(",
"'name'",
")",
"vt_xml",... | 37.428571 | 19.428571 |
def _request(self, url, params, first_request_time=None, retry_counter=0,
base_url=_DEFAULT_BASE_URL, accepts_clientid=True,
extract_body=None, requests_kwargs=None, post_json=None):
"""Performs HTTP GET/POST with credentials, returning the body as
JSON.
:param url: UR... | [
"def",
"_request",
"(",
"self",
",",
"url",
",",
"params",
",",
"first_request_time",
"=",
"None",
",",
"retry_counter",
"=",
"0",
",",
"base_url",
"=",
"_DEFAULT_BASE_URL",
",",
"accepts_clientid",
"=",
"True",
",",
"extract_body",
"=",
"None",
",",
"reques... | 42.366972 | 23.376147 |
def nunique(self, dropna=True):
"""
Return number of unique elements in the group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = '... | [
"def",
"nunique",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"ids",
",",
"_",
",",
"_",
"=",
"self",
".",
"grouper",
".",
"group_info",
"val",
"=",
"self",
".",
"obj",
".",
"get_values",
"(",
")",
"try",
":",
"sorter",
"=",
"np",
".",
"... | 32.017857 | 17.517857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.