text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def clear():
"""Clears the current context figure of all marks axes and grid lines."""
fig = _context['figure']
if fig is not None:
fig.marks = []
fig.axes = []
setattr(fig, 'axis_registry', {})
_context['scales'] = {}
key = _context['current_key']
if key is n... | [
"def",
"clear",
"(",
")",
":",
"fig",
"=",
"_context",
"[",
"'figure'",
"]",
"if",
"fig",
"is",
"not",
"None",
":",
"fig",
".",
"marks",
"=",
"[",
"]",
"fig",
".",
"axes",
"=",
"[",
"]",
"setattr",
"(",
"fig",
",",
"'axis_registry'",
",",
"{",
... | 33.363636 | 11.636364 |
def get_request(self, url):
"""Send a get request.
warning: old api.
:return: a dict or raise Exception.
"""
resp = self.session.get(url, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
... | [
"def",
"get_request",
"(",
"self",
",",
"url",
")",
":",
"resp",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"result",
"=",
"resp",
".",
"json",... | 30.333333 | 15.466667 |
def get_fault(fault_id=None):
"""Retrieve a randomly-generated error message as a unicode string.
:param fault_id:
Allows you to optionally specify an integer representing the fault_id
from the database table. This allows you to retrieve a specific fault
each time, albeit... | [
"def",
"get_fault",
"(",
"fault_id",
"=",
"None",
")",
":",
"counts",
"=",
"__get_table_limits",
"(",
")",
"result",
"=",
"None",
"id_",
"=",
"0",
"try",
":",
"if",
"isinstance",
"(",
"fault_id",
",",
"int",
")",
":",
"id_",
"=",
"fault_id",
"elif",
... | 33.222222 | 17.822222 |
def _parse_dict(element, definition):
"""Parse xml element by a definition given in dict format.
:param element: ElementTree element
:param definition: definition schema
:type definition: dict
:return: parsed xml
:rtype: dict
"""
sub_dict = {}
for name, subdef in viewitems(definiti... | [
"def",
"_parse_dict",
"(",
"element",
",",
"definition",
")",
":",
"sub_dict",
"=",
"{",
"}",
"for",
"name",
",",
"subdef",
"in",
"viewitems",
"(",
"definition",
")",
":",
"(",
"name",
",",
"required",
")",
"=",
"_parse_name",
"(",
"name",
")",
"sub_di... | 25.823529 | 17.411765 |
def verify(self):
'''Check that the database accurately describes the state of the repository'''
c = self.database.cursor()
non_exist = set()
no_db_entry = set(os.listdir(self.cache_dir))
try:
no_db_entry.remove('file_database.db')
no_db_entry.remove('fi... | [
"def",
"verify",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
")",
"non_exist",
"=",
"set",
"(",
")",
"no_db_entry",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"self",
".",
"cache_dir",
")",
")",
"try",
":",
"no_... | 32.34375 | 22.28125 |
def sents(self, fileids=None) -> Generator[str, str, None]:
"""
:param fileids:
:return: A generator of sentences
"""
for para in self.paras(fileids):
sentences = self._sent_tokenizer.tokenize(para)
for sentence in sentences:
yield sentence | [
"def",
"sents",
"(",
"self",
",",
"fileids",
"=",
"None",
")",
"->",
"Generator",
"[",
"str",
",",
"str",
",",
"None",
"]",
":",
"for",
"para",
"in",
"self",
".",
"paras",
"(",
"fileids",
")",
":",
"sentences",
"=",
"self",
".",
"_sent_tokenizer",
... | 34.666667 | 7.555556 |
def check_output(self, make_ndx_output, message=None, err=None):
"""Simple tests to flag problems with a ``make_ndx`` run."""
if message is None:
message = ""
else:
message = '\n' + message
def format(output, w=60):
hrule = "====[ GromacsError (diagnos... | [
"def",
"check_output",
"(",
"self",
",",
"make_ndx_output",
",",
"message",
"=",
"None",
",",
"err",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"\"\"",
"else",
":",
"message",
"=",
"'\\n'",
"+",
"message",
"def",
"format... | 45.76 | 21.28 |
def create_widget(self, dim, holomap=None, editable=False):
""""
Given a Dimension creates bokeh widgets to select along that
dimension. For numeric data a slider widget is created which
may be either discrete, if a holomap is supplied or the
Dimension.values are set, or a contin... | [
"def",
"create_widget",
"(",
"self",
",",
"dim",
",",
"holomap",
"=",
"None",
",",
"editable",
"=",
"False",
")",
":",
"label",
",",
"mapping",
"=",
"None",
",",
"None",
"if",
"holomap",
"is",
"None",
":",
"if",
"dim",
".",
"values",
":",
"if",
"di... | 51.831461 | 22.606742 |
def set_data_dir(directory=None, create=False, save=False):
"""Set vispy data download directory
Parameters
----------
directory : str | None
The directory to use.
create : bool
If True, create directory if it doesn't exist.
save : bool
If True, save the configuration to... | [
"def",
"set_data_dir",
"(",
"directory",
"=",
"None",
",",
"create",
"=",
"False",
",",
"save",
"=",
"False",
")",
":",
"if",
"directory",
"is",
"None",
":",
"directory",
"=",
"_data_path",
"if",
"_data_path",
"is",
"None",
":",
"raise",
"IOError",
"(",
... | 34.44 | 17.36 |
def store_file(self, path, data, fast_lane=True):
"""
Store the file in temp folder and stream it to server if online.
This makes sure that we have all newest data of this file on the server directly.
This method always overwrites the content of path. If you want to a... | [
"def",
"store_file",
"(",
"self",
",",
"path",
",",
"data",
",",
"fast_lane",
"=",
"True",
")",
":",
"self",
".",
"stream_files_lock",
".",
"acquire",
"(",
")",
"try",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"temp... | 42.2 | 29.8 |
def timestamp_to_datetime(timestamp):
'''
1514736000 --> datetime object
:param int timestamp: unix timestamp (int)
:return: datetime object or None
:rtype: datetime or None
'''
if isinstance(timestamp, (int, float, str)):
try:
timest... | [
"def",
"timestamp_to_datetime",
"(",
"timestamp",
")",
":",
"if",
"isinstance",
"(",
"timestamp",
",",
"(",
"int",
",",
"float",
",",
"str",
")",
")",
":",
"try",
":",
"timestamp",
"=",
"float",
"(",
"timestamp",
")",
"if",
"timestamp",
".",
"is_integer"... | 26.071429 | 17.857143 |
def _scatter_ndarray(ar, axis=-1, destination=None, blocksize=None):
"""Turn a numpy ndarray into a DistArray or RemoteArray
Args:
ar (array_like)
axis (int, optional): specifies along which axis to split the array to
distribute it. The default is to split along the last axis. `None` means
... | [
"def",
"_scatter_ndarray",
"(",
"ar",
",",
"axis",
"=",
"-",
"1",
",",
"destination",
"=",
"None",
",",
"blocksize",
"=",
"None",
")",
":",
"from",
".",
"arrays",
"import",
"DistArray",
",",
"RemoteArray",
"shape",
"=",
"ar",
".",
"shape",
"ndim",
"=",... | 42.066667 | 19.933333 |
def enable(self):
"""Return True|False if the AMP is enabled in the configuration file (enable=true|false)."""
ret = self.get('enable')
if ret is None:
return False
else:
return ret.lower().startswith('true') | [
"def",
"enable",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"get",
"(",
"'enable'",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"False",
"else",
":",
"return",
"ret",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'true'",
")"
] | 36.857143 | 14.285714 |
def estimateHE(args):
"""
%prog estimateHE clustSfile
Estimate heterozygosity (H) and error rate (E). Idea borrowed heavily from
the PyRad paper.
"""
p = OptionParser(estimateHE.__doc__)
add_consensus_options(p)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(no... | [
"def",
"estimateHE",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"estimateHE",
".",
"__doc__",
")",
"add_consensus_options",
"(",
"p",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"... | 25.75 | 19.694444 |
def ang_sep(row, ra1, dec1):
"""
Calculate angular separation between two coordinates
Uses Vicenty Formula (http://en.wikipedia.org/wiki/Great-circle_distance) and adapts from astropy's SkyCoord
Written to be used within the Database.search() method
Parameters
----------
row: dict, pandas R... | [
"def",
"ang_sep",
"(",
"row",
",",
"ra1",
",",
"dec1",
")",
":",
"factor",
"=",
"math",
".",
"pi",
"/",
"180",
"sdlon",
"=",
"math",
".",
"sin",
"(",
"(",
"row",
"[",
"'ra'",
"]",
"-",
"ra1",
")",
"*",
"factor",
")",
"# RA is longitude",
"cdlon",... | 33.558824 | 20.382353 |
def _git(*command_parts, **kwargs):
""" Convenience function for running git commands. Automatically deals with exceptions and unicode. """
# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html
git_kwargs = {'_tty_out': False}
git_kwargs.update(kwargs)
try:
res... | [
"def",
"_git",
"(",
"*",
"command_parts",
",",
"*",
"*",
"kwargs",
")",
":",
"# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html",
"git_kwargs",
"=",
"{",
"'_tty_out'",
":",
"False",
"}",
"git_kwargs",
".",
"update",
"(",
"kwargs",
")... | 59.5 | 28.090909 |
def write_config(self, initialize_indices=False):
"""
Write the current config to disk to store them.
"""
if not os.path.exists(self.config_dir):
os.mkdir(self.config_dir)
with open(self.config_file, 'w') as configfile:
self.config.write(configfile)
... | [
"def",
"write_config",
"(",
"self",
",",
"initialize_indices",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"config_dir",
")",
":",
"os",
".",
"mkdir",
"(",
"self",
".",
"config_dir",
")",
"with",
"open",
"... | 41.809524 | 13.904762 |
def check_against_chunks(self, chunks):
# type: (Iterator[bytes]) -> None
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in iterkeys(self._allowed):
try:
... | [
"def",
"check_against_chunks",
"(",
"self",
",",
"chunks",
")",
":",
"# type: (Iterator[bytes]) -> None",
"gots",
"=",
"{",
"}",
"for",
"hash_name",
"in",
"iterkeys",
"(",
"self",
".",
"_allowed",
")",
":",
"try",
":",
"gots",
"[",
"hash_name",
"]",
"=",
"... | 31.782609 | 16.434783 |
def cache_component_verify_ticket(self, msg, signature, timestamp, nonce):
"""
处理 wechat server 推送的 component_verify_ticket消息
:params msg: 加密内容
:params signature: 消息签名
:params timestamp: 时间戳
:params nonce: 随机数
"""
warnings.warn('`cache_component_verify_ti... | [
"def",
"cache_component_verify_ticket",
"(",
"self",
",",
"msg",
",",
"signature",
",",
"timestamp",
",",
"nonce",
")",
":",
"warnings",
".",
"warn",
"(",
"'`cache_component_verify_ticket` method of `WeChatComponent` is deprecated,'",
"'Use `parse_message` instead'",
",",
"... | 43.875 | 18.5 |
def implied_feature (implicit_value):
""" Returns the implicit feature associated with the given implicit value.
"""
assert isinstance(implicit_value, basestring)
components = implicit_value.split('-')
if components[0] not in __implicit_features:
raise InvalidValue ("'%s' is not a value of ... | [
"def",
"implied_feature",
"(",
"implicit_value",
")",
":",
"assert",
"isinstance",
"(",
"implicit_value",
",",
"basestring",
")",
"components",
"=",
"implicit_value",
".",
"split",
"(",
"'-'",
")",
"if",
"components",
"[",
"0",
"]",
"not",
"in",
"__implicit_fe... | 39.6 | 15.7 |
def sX(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
"""Return the Pauli sigma_X operator acting on the given qubit"""
return Pauli.sigma(qubit, 'X', coefficient) | [
"def",
"sX",
"(",
"qubit",
":",
"Qubit",
",",
"coefficient",
":",
"complex",
"=",
"1.0",
")",
"->",
"Pauli",
":",
"return",
"Pauli",
".",
"sigma",
"(",
"qubit",
",",
"'X'",
",",
"coefficient",
")"
] | 58 | 8.333333 |
def get_lab_managers_formatted_emails(self):
"""Returns a list with lab managers formatted emails
"""
users = api.get_users_by_roles("LabManager")
users = map(lambda user: (user.getProperty("fullname"),
user.getProperty("email")), users)
return m... | [
"def",
"get_lab_managers_formatted_emails",
"(",
"self",
")",
":",
"users",
"=",
"api",
".",
"get_users_by_roles",
"(",
"\"LabManager\"",
")",
"users",
"=",
"map",
"(",
"lambda",
"user",
":",
"(",
"user",
".",
"getProperty",
"(",
"\"fullname\"",
")",
",",
"u... | 49.857143 | 11.142857 |
def between_time(self, start_time, end_time, include_start=True,
include_end=True, axis=None):
"""
Select values between particular times of the day (e.g., 9:00-9:30 AM).
By setting ``start_time`` to be later than ``end_time``,
you can get the times that are *not* b... | [
"def",
"between_time",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"include_start",
"=",
"True",
",",
"include_end",
"=",
"True",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"self",
".",
"_stat_axis_number"... | 32.277778 | 19.666667 |
def old_signing_text(self):
"""Return the text needed for signing using SignatureVersion 1."""
result = []
lower_cmp = lambda x, y: cmp(x[0].lower(), y[0].lower())
for key, value in sorted(self.params.items(), cmp=lower_cmp):
result.append("%s%s" % (key, value))
retur... | [
"def",
"old_signing_text",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"lower_cmp",
"=",
"lambda",
"x",
",",
"y",
":",
"cmp",
"(",
"x",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"y",
"[",
"0",
"]",
".",
"lower",
"(",
")",
")",
"for",
... | 47.285714 | 15 |
def parse_package(self, p_term):
"""Parses package fields."""
# Check there is a pacakge name
if not (p_term, self.spdx_namespace['name'], None) in self.graph:
self.error = True
self.logger.log('Package must have a name.')
# Create dummy package so that we may... | [
"def",
"parse_package",
"(",
"self",
",",
"p_term",
")",
":",
"# Check there is a pacakge name",
"if",
"not",
"(",
"p_term",
",",
"self",
".",
"spdx_namespace",
"[",
"'name'",
"]",
",",
"None",
")",
"in",
"self",
".",
"graph",
":",
"self",
".",
"error",
... | 58.818182 | 26.757576 |
def extract_init_args(instance):
"""
Given an instance, and under the assumption that member variables have the
same name as the __init__ arguments, extract the arguments so they can
be used to reconstruct the instance when deserializing
"""
cls = instance.__class__
args = [x for x in inspec... | [
"def",
"extract_init_args",
"(",
"instance",
")",
":",
"cls",
"=",
"instance",
".",
"__class__",
"args",
"=",
"[",
"x",
"for",
"x",
"in",
"inspect",
".",
"getargspec",
"(",
"cls",
".",
"__init__",
")",
".",
"args",
"if",
"x",
"!=",
"'self'",
"]",
"re... | 45.666667 | 17.444444 |
def segwit_sighash(self, index, script, prevout_value=None,
sighash_type=None, anyone_can_pay=False):
'''
this function sets up sighash in BIP143 style
https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
https://ricette.giallozafferano.it/Spaghetti-alla-... | [
"def",
"segwit_sighash",
"(",
"self",
",",
"index",
",",
"script",
",",
"prevout_value",
"=",
"None",
",",
"sighash_type",
"=",
"None",
",",
"anyone_can_pay",
"=",
"False",
")",
":",
"data",
"=",
"ByteData",
"(",
")",
"# 1. nVersion of the transaction (4-byte li... | 38.928571 | 24.97619 |
def request_port_forward(self, address, port, handler=None):
"""
Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives.... | [
"def",
"request_port_forward",
"(",
"self",
",",
"address",
",",
"port",
",",
"handler",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"SSHException",
"(",
"'SSH session not active'",
")",
"address",
"=",
"str",
"(",
"address",
"... | 41.590909 | 23.5 |
def modify_replication_group(ReplicationGroupId=None, ReplicationGroupDescription=None, PrimaryClusterId=None, SnapshottingClusterId=None, AutomaticFailoverEnabled=None, CacheSecurityGroupNames=None, SecurityGroupIds=None, PreferredMaintenanceWindow=None, NotificationTopicArn=None, CacheParameterGroupName=None, Notific... | [
"def",
"modify_replication_group",
"(",
"ReplicationGroupId",
"=",
"None",
",",
"ReplicationGroupDescription",
"=",
"None",
",",
"PrimaryClusterId",
"=",
"None",
",",
"SnapshottingClusterId",
"=",
"None",
",",
"AutomaticFailoverEnabled",
"=",
"None",
",",
"CacheSecurity... | 49.027322 | 35.005464 |
def _fetch_stock_data(self, stock_list):
"""因为 timekline 的返回没有带对应的股票代码,所以要手动带上"""
res = super()._fetch_stock_data(stock_list)
with_stock = []
for stock, resp in zip(stock_list, res):
if resp is not None:
with_stock.append((stock, resp))
return with_st... | [
"def",
"_fetch_stock_data",
"(",
"self",
",",
"stock_list",
")",
":",
"res",
"=",
"super",
"(",
")",
".",
"_fetch_stock_data",
"(",
"stock_list",
")",
"with_stock",
"=",
"[",
"]",
"for",
"stock",
",",
"resp",
"in",
"zip",
"(",
"stock_list",
",",
"res",
... | 35 | 11.888889 |
def cli(env, ack_all):
"""Summary and acknowledgement of upcoming and ongoing maintenance events"""
manager = AccountManager(env.client)
events = manager.get_upcoming_events()
if ack_all:
for event in events:
result = manager.ack_event(event['id'])
event['acknowledgedFl... | [
"def",
"cli",
"(",
"env",
",",
"ack_all",
")",
":",
"manager",
"=",
"AccountManager",
"(",
"env",
".",
"client",
")",
"events",
"=",
"manager",
".",
"get_upcoming_events",
"(",
")",
"if",
"ack_all",
":",
"for",
"event",
"in",
"events",
":",
"result",
"... | 32.454545 | 14.636364 |
def serialize(self, user=None):
"""
Serializes message for given user.
Note:
Should be called before first save(). Otherwise "is_update" will get wrong value.
Args:
user: User object
Returns:
Dict. JSON serialization ready dictionary object
... | [
"def",
"serialize",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"return",
"{",
"'content'",
":",
"self",
".",
"body",
",",
"'type'",
":",
"self",
".",
"typ",
",",
"'updated_at'",
":",
"self",
".",
"updated_at",
",",
"'timestamp'",
":",
"self",
"... | 32.206897 | 16.965517 |
def upload_image(self,
image_file,
referer_url=None,
title=None,
desc=None,
created_at=None,
collection_id=None):
"""Upload an image
:param image_file: File-like object of an im... | [
"def",
"upload_image",
"(",
"self",
",",
"image_file",
",",
"referer_url",
"=",
"None",
",",
"title",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"created_at",
"=",
"None",
",",
"collection_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"upload_u... | 35.228571 | 10.628571 |
def compound_statements(logical_line):
"""
Compound statements (multiple statements on the same line) are
generally discouraged.
"""
line = logical_line
found = line.find(':')
if -1 < found < len(line) - 1:
before = line[:found]
if (before.count('{') <= before.count('}') and ... | [
"def",
"compound_statements",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"found",
"=",
"line",
".",
"find",
"(",
"':'",
")",
"if",
"-",
"1",
"<",
"found",
"<",
"len",
"(",
"line",
")",
"-",
"1",
":",
"before",
"=",
"line",
"[",
":"... | 40.875 | 17.5 |
def reset(self):
"""Reset coincidence counter"""
self.counts = defaultdict(partial(np.zeros, (465, self.tmax * 2 + 1)))
self.n_timeslices = defaultdict(int) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"counts",
"=",
"defaultdict",
"(",
"partial",
"(",
"np",
".",
"zeros",
",",
"(",
"465",
",",
"self",
".",
"tmax",
"*",
"2",
"+",
"1",
")",
")",
")",
"self",
".",
"n_timeslices",
"=",
"defaultdic... | 44.25 | 16.5 |
def check_applied(result):
"""
Raises LWTException if it looks like a failed LWT request. A LWTException
won't be raised in the special case in which there are several failed LWT
in a :class:`~cqlengine.query.BatchQuery`.
"""
try:
applied = result.was_applied
except Exception:
... | [
"def",
"check_applied",
"(",
"result",
")",
":",
"try",
":",
"applied",
"=",
"result",
".",
"was_applied",
"except",
"Exception",
":",
"applied",
"=",
"True",
"# result was not LWT form",
"if",
"not",
"applied",
":",
"raise",
"LWTException",
"(",
"result",
"."... | 34.5 | 15 |
def _available_formats_helper(count_flag, format_flag):
"""Helper for available_formats() and available_subtypes()."""
count = _ffi.new("int*")
_snd.sf_command(_ffi.NULL, count_flag, count, _ffi.sizeof("int"))
for format_int in range(count[0]):
yield _format_info(format_int, format_flag) | [
"def",
"_available_formats_helper",
"(",
"count_flag",
",",
"format_flag",
")",
":",
"count",
"=",
"_ffi",
".",
"new",
"(",
"\"int*\"",
")",
"_snd",
".",
"sf_command",
"(",
"_ffi",
".",
"NULL",
",",
"count_flag",
",",
"count",
",",
"_ffi",
".",
"sizeof",
... | 51.166667 | 11.5 |
async def handle(self, record):
"""
Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied.
"""
if (not self.disabled) and self.filter(record):
... | [
"async",
"def",
"handle",
"(",
"self",
",",
"record",
")",
":",
"if",
"(",
"not",
"self",
".",
"disabled",
")",
"and",
"self",
".",
"filter",
"(",
"record",
")",
":",
"await",
"self",
".",
"callHandlers",
"(",
"record",
")"
] | 39 | 16.333333 |
def list_ingress_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_ingress_for_all_namespaces # noqa: E501
list or watch objects of kind Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=Tr... | [
"def",
"list_ingress_for_all_namespaces",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_ingres... | 164.137931 | 135.068966 |
def main(self, config_filename):
"""
The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred.
:param str config_filename: The name of the configuration file.
:rtype: int
"""
self._read_configuration_file(config_filename)
if s... | [
"def",
"main",
"(",
"self",
",",
"config_filename",
")",
":",
"self",
".",
"_read_configuration_file",
"(",
"config_filename",
")",
"if",
"self",
".",
"_wrapper_class_name",
":",
"self",
".",
"_io",
".",
"title",
"(",
"'Wrapper'",
")",
"self",
".",
"__genera... | 27.666667 | 22.777778 |
def generator(self, Xgen, Xexc, Xgov, Vgen):
""" Generator model.
Based on Generator.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
generators = self.dyn_gene... | [
"def",
"generator",
"(",
"self",
",",
"Xgen",
",",
"Xexc",
",",
"Xgov",
",",
"Vgen",
")",
":",
"generators",
"=",
"self",
".",
"dyn_generators",
"omegas",
"=",
"2",
"*",
"pi",
"*",
"self",
".",
"freq",
"F",
"=",
"zeros",
"(",
"Xgen",
".",
"shape",
... | 30.142857 | 19.873016 |
def report(function, *args, **kwds):
"""Run a function, catch, report and discard exceptions"""
try:
function(*args, **kwds)
except Exception:
traceback.print_exc() | [
"def",
"report",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"try",
":",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")"
] | 31.166667 | 12.5 |
def _get_cells_headers_ids(self, hed, index):
"""
Returns a list with ids of rows of same column.
:param hed: The list that represents the table header.
:type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:param index: The index of columns.
:type inde... | [
"def",
"_get_cells_headers_ids",
"(",
"self",
",",
"hed",
",",
"index",
")",
":",
"# pylint: disable=no-self-use",
"ids",
"=",
"[",
"]",
"for",
"row",
"in",
"hed",
":",
"if",
"row",
"[",
"index",
"]",
".",
"get_tag_name",
"(",
")",
"==",
"'TH'",
":",
"... | 34.111111 | 17 |
def trainable_params_(m):
""" Returns a list of trainable parameters in the model m. (i.e., those that require gradients.) """
if isinstance(m, collections.Sequence):
return [p for p in m if p.requires_grad]
else:
return [p for p in m.parameters() if p.requires_grad] | [
"def",
"trainable_params_",
"(",
"m",
")",
":",
"if",
"isinstance",
"(",
"m",
",",
"collections",
".",
"Sequence",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"m",
"if",
"p",
".",
"requires_grad",
"]",
"else",
":",
"return",
"[",
"p",
"for",
"p... | 48.333333 | 13 |
def parse_line(self, line):
"""Parse a line of input.
The input line is tokenized using the same rules as the way bash shell
tokenizes inputs. All quoting and escaping rules from the bash shell
apply here too.
The following cases are handled by __exec_line__():
1. ... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"toks",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"# Safe to index the 0-th element because this line would have been",
"# parsed by __exec_line__ if toks is an empty list.",
"return",
"(",
"toks",
"[",
"0",
"... | 42.818182 | 24.636364 |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the EnclavePermissions object.
""... | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"d",
"=",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"remove_nones",
")",
"d",
".",
"update",
"(",
"{",
"'read'",
":",
"self",
".",
"read",
",",
"'create'",... | 30 | 24.117647 |
def sde(self):
"""
Return the state space representation of the covariance.
"""
variance = float(self.variance.values)
lengthscale = float(self.lengthscale.values)
lamda = np.sqrt(5.0)/lengthscale
kappa = 5.0/3.0*variance/lengthscale**2
... | [
"def",
"sde",
"(",
"self",
")",
":",
"variance",
"=",
"float",
"(",
"self",
".",
"variance",
".",
"values",
")",
"lengthscale",
"=",
"float",
"(",
"self",
".",
"lengthscale",
".",
"values",
")",
"lamda",
"=",
"np",
".",
"sqrt",
"(",
"5.0",
")",
"/"... | 42.272727 | 18.545455 |
def _CreateTaskStorageWriter(self, path, task):
"""Creates a task storage writer.
Args:
path (str): path to the storage file.
task (Task): task.
Returns:
SQLiteStorageFileWriter: storage writer.
"""
return SQLiteStorageFileWriter(
self._session, path,
storage_type... | [
"def",
"_CreateTaskStorageWriter",
"(",
"self",
",",
"path",
",",
"task",
")",
":",
"return",
"SQLiteStorageFileWriter",
"(",
"self",
".",
"_session",
",",
"path",
",",
"storage_type",
"=",
"definitions",
".",
"STORAGE_TYPE_TASK",
",",
"task",
"=",
"task",
")"... | 26.923077 | 16.153846 |
def polyfit2d(x, y, z, order=3 #bounds=None
):
'''
fit unstructured data
'''
ncols = (order + 1)**2
G = np.zeros((x.size, ncols))
ij = itertools.product(list(range(order+1)), list(range(order+1)))
for k, (i,j) in enumerate(ij):
G[:,k] = x**i * y**j
m = np... | [
"def",
"polyfit2d",
"(",
"x",
",",
"y",
",",
"z",
",",
"order",
"=",
"3",
"#bounds=None\r",
")",
":",
"ncols",
"=",
"(",
"order",
"+",
"1",
")",
"**",
"2",
"G",
"=",
"np",
".",
"zeros",
"(",
"(",
"x",
".",
"size",
",",
"ncols",
")",
")",
"i... | 28.75 | 17.083333 |
def solution(self, x0, y0):
""" Create a solution function ``y(x)`` such that ``y(x0) = y0``.
A list of solution values ``[y(x0), y(x1) ...]`` is returned if the
function is called with a list ``[x0, x1 ...]`` of ``x`` values.
"""
def soln(x):
if numpy.size(x) > 1:
... | [
"def",
"solution",
"(",
"self",
",",
"x0",
",",
"y0",
")",
":",
"def",
"soln",
"(",
"x",
")",
":",
"if",
"numpy",
".",
"size",
"(",
"x",
")",
">",
"1",
":",
"x",
"=",
"[",
"soln",
".",
"x",
"]",
"+",
"list",
"(",
"x",
")",
"ans",
"=",
"... | 33.55 | 15.85 |
def fillkeys(Recs):
"""
reconciles keys of dictionaries within Recs.
"""
keylist, OutRecs = [], []
for rec in Recs:
for key in list(rec.keys()):
if key not in keylist:
keylist.append(key)
for rec in Recs:
for key in keylist:
if key not in l... | [
"def",
"fillkeys",
"(",
"Recs",
")",
":",
"keylist",
",",
"OutRecs",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"rec",
"in",
"Recs",
":",
"for",
"key",
"in",
"list",
"(",
"rec",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
"not",
"in",
"keylist",
... | 27.2 | 9.866667 |
def create_script_fact(self):
"""
appends the CREATE TABLE, index etc to self.ddl_text
"""
self.ddl_text += '---------------------------------------------\n'
self.ddl_text += '-- CREATE Fact Table - ' + self.fact_table + '\n'
self.ddl_text += '----------------------------... | [
"def",
"create_script_fact",
"(",
"self",
")",
":",
"self",
".",
"ddl_text",
"+=",
"'---------------------------------------------\\n'",
"self",
".",
"ddl_text",
"+=",
"'-- CREATE Fact Table - '",
"+",
"self",
".",
"fact_table",
"+",
"'\\n'",
"self",
".",
"ddl_text",
... | 57.666667 | 25.833333 |
def extrair_logs(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.extrair_logs`.
:return: Uma resposta SAT especializada em ``ExtrairLogs``.
:rtype: satcfe.resposta.extrairlogs.RespostaExtrairLogs
"""
resp = self._http_post('extrairlogs')
conteudo = resp.json()
... | [
"def",
"extrair_logs",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_http_post",
"(",
"'extrairlogs'",
")",
"conteudo",
"=",
"resp",
".",
"json",
"(",
")",
"return",
"RespostaExtrairLogs",
".",
"analisar",
"(",
"conteudo",
".",
"get",
"(",
"'retorno'"... | 41.333333 | 16.666667 |
def get_temperature(self):
"""
Returns the current environment temperature.
Attention: Returns None if the value can't be queried or is unknown.
"""
#raise NotImplementedError("This should work according to the AVM docs, but don't...")
value = self.box.homeautoswitch("get... | [
"def",
"get_temperature",
"(",
"self",
")",
":",
"#raise NotImplementedError(\"This should work according to the AVM docs, but don't...\")",
"value",
"=",
"self",
".",
"box",
".",
"homeautoswitch",
"(",
"\"gettemperature\"",
",",
"self",
".",
"actor_id",
")",
"if",
"value... | 41.166667 | 17.333333 |
def install_documentation(path="./Litho1pt0-Notebooks"):
"""Install the example notebooks for litho1pt0 in the given location
WARNING: If the path exists, the Notebook files will be written into the path
and will overwrite any existing files with which they collide. The default
path ("./Litho1pt0-Noteb... | [
"def",
"install_documentation",
"(",
"path",
"=",
"\"./Litho1pt0-Notebooks\"",
")",
":",
"## Question - overwrite or not ? shutils fails if directory exists.",
"Notebooks_Path",
"=",
"_pkg_resources",
".",
"resource_filename",
"(",
"'litho1pt0'",
",",
"'Notebooks'",
")",
"ct",
... | 37.206897 | 31.586207 |
def __get_gui_handle(self, root_dir):
""" get the filepath and filehandle to the .env file for the environment """
gui_path = os.path.join(root_dir, '.gui')
fh = open(gui_path, "w+")
return (gui_path, fh) | [
"def",
"__get_gui_handle",
"(",
"self",
",",
"root_dir",
")",
":",
"gui_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'.gui'",
")",
"fh",
"=",
"open",
"(",
"gui_path",
",",
"\"w+\"",
")",
"return",
"(",
"gui_path",
",",
"fh",
")"... | 46.4 | 6 |
def verify(self, obj):
"""Verify that the object conforms to this verifier's schema.
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the object, a
ValidationError is thrown with at least the reason k... | [
"def",
"verify",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"not",
"in",
"self",
".",
"options",
":",
"raise",
"ValidationError",
"(",
"\"Object is not in list of enumerated options\"",
",",
"reason",
"=",
"'not in list of enumerated options'",
",",
"object",
... | 37.529412 | 27.764706 |
def getbyuuid(self, uuid):
"""Get a schema by given uuid.
:param str uuid: schema uuid to retrieve.
:rtype: Schema
:raises: KeyError if uuid is not registered already.
"""
if uuid not in self._schbyuuid:
raise KeyError('uuid {0} not registered'.format(uuid))
... | [
"def",
"getbyuuid",
"(",
"self",
",",
"uuid",
")",
":",
"if",
"uuid",
"not",
"in",
"self",
".",
"_schbyuuid",
":",
"raise",
"KeyError",
"(",
"'uuid {0} not registered'",
".",
"format",
"(",
"uuid",
")",
")",
"return",
"self",
".",
"_schbyuuid",
"[",
"uui... | 31.545455 | 15.636364 |
def get_layer_by_name(self, name):
"""Return a layer by name
:param name: Name of layer. Case-sensitive.
:rtype: Layer object if found, otherwise ValueError
"""
try:
return self.layernames[name]
except KeyError:
msg = 'Layer "{0}" not found.'
... | [
"def",
"get_layer_by_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"self",
".",
"layernames",
"[",
"name",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"'Layer \"{0}\" not found.'",
"logger",
".",
"debug",
"(",
"msg",
".",
"format",
"(",
... | 31.416667 | 11.416667 |
def get_service_framework_id(
service_name,
inactive=False,
completed=False
):
""" Get the framework ID for a service
:param service_name: the service name
:type service_name: str
:param inactive: whether to include inactive services
:type inactive: bool
... | [
"def",
"get_service_framework_id",
"(",
"service_name",
",",
"inactive",
"=",
"False",
",",
"completed",
"=",
"False",
")",
":",
"service",
"=",
"get_service",
"(",
"service_name",
",",
"inactive",
",",
"completed",
")",
"if",
"service",
"is",
"not",
"None",
... | 26.565217 | 18.521739 |
def getCallSetByName(self, name):
"""
Returns a CallSet with the specified name, or raises a
CallSetNameNotFoundException if it does not exist.
"""
if name not in self._callSetNameMap:
raise exceptions.CallSetNameNotFoundException(name)
return self._callSetNam... | [
"def",
"getCallSetByName",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_callSetNameMap",
":",
"raise",
"exceptions",
".",
"CallSetNameNotFoundException",
"(",
"name",
")",
"return",
"self",
".",
"_callSetNameMap",
"[",
"name",
... | 40.375 | 9.375 |
def find_channel_groups(chan):
"""Channels are often organized in groups (different grids / strips or
channels in different brain locations), so we use a simple heuristic to
get these channel groups.
Parameters
----------
chan : instance of Channels
channels to group
Returns
--... | [
"def",
"find_channel_groups",
"(",
"chan",
")",
":",
"labels",
"=",
"chan",
".",
"return_label",
"(",
")",
"group_names",
"=",
"{",
"match",
"(",
"'([A-Za-z ]+)\\d+'",
",",
"label",
")",
".",
"group",
"(",
"1",
")",
"for",
"label",
"in",
"labels",
"}",
... | 28.875 | 24.333333 |
def fromxml(node):
"""Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
... | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"if",
"node",
".",
"tag",
".",
"lower",
"(... | 39.541667 | 13.791667 |
def list_pkgs(versions_as_list=False,
jail=None,
chroot=None,
root=None,
with_origin=False,
**kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
jail
List the packages in the s... | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"jail",
"=",
"None",
",",
"chroot",
"=",
"None",
",",
"root",
"=",
"None",
",",
"with_origin",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# not yet implemented or not applicable",
"if",
... | 30.564706 | 19.905882 |
def main():
"""
NAME
mst_magic.py
DESCRIPTION
converts MsT data (T,M) to measurements format files
SYNTAX
mst_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
-f FILE: specify T... | [
"def",
"main",
"(",
")",
":",
"#",
"# get command line arguments",
"#",
"args",
"=",
"sys",
".",
"argv",
"if",
"\"-h\"",
"in",
"args",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"dir_path",
"=",
"pmag",
".",
"get_na... | 41.652778 | 22.875 |
def get_order_line_item_by_id(cls, order_line_item_id, **kwargs):
"""Find OrderLineItem
Return single instance of OrderLineItem by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_o... | [
"def",
"get_order_line_item_by_id",
"(",
"cls",
",",
"order_line_item_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_order... | 45.142857 | 22.761905 |
def constraints(self):
"""
Returns full :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances, after
a successful :meth:`build`
:return: list of named :class:`Constraint <cqparts.constraint.Constraint>` instances
:rtype: :class:`list`
For more i... | [
"def",
"constraints",
"(",
"self",
")",
":",
"if",
"self",
".",
"_constraints",
"is",
"None",
":",
"self",
".",
"build",
"(",
"recursive",
"=",
"False",
")",
"return",
"self",
".",
"_constraints"
] | 37.846154 | 21.846154 |
def safe_joinall(greenlets, timeout=None, raise_error=False):
"""
Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it
joins for.
"""
greenlets = list(greenlets)
try:
gevent.joinall(greenlets, timeout=timeout, raise_error=raise_erro... | [
"def",
"safe_joinall",
"(",
"greenlets",
",",
"timeout",
"=",
"None",
",",
"raise_error",
"=",
"False",
")",
":",
"greenlets",
"=",
"list",
"(",
"greenlets",
")",
"try",
":",
"gevent",
".",
"joinall",
"(",
"greenlets",
",",
"timeout",
"=",
"timeout",
","... | 37.833333 | 23.833333 |
def random(self, namespace=0):
"""
Returns query string for random page
"""
query = self.LIST.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
LIST='random')
query += "&rnlimit=1&rnnamespace=%d" % namespace
emoji = [
u'\U... | [
"def",
"random",
"(",
"self",
",",
"namespace",
"=",
"0",
")",
":",
"query",
"=",
"self",
".",
"LIST",
".",
"substitute",
"(",
"WIKI",
"=",
"self",
".",
"uri",
",",
"ENDPOINT",
"=",
"self",
".",
"endpoint",
",",
"LIST",
"=",
"'random'",
")",
"query... | 28.678571 | 14.107143 |
def _statsd_address(self):
"""Return a tuple of host and port for the statsd server to send
stats to.
:return: tuple(host, port)
"""
return (self.application.settings.get('statsd',
{}).get('host',
... | [
"def",
"_statsd_address",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"application",
".",
"settings",
".",
"get",
"(",
"'statsd'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'host'",
",",
"self",
".",
"STATSD_HOST",
")",
",",
"self",
".",
"applicat... | 41.230769 | 19.923077 |
def register_plugin(self, name, plugin):
"""
Add a new plugin ``plugin`` with name ``name`` to the active plugins.
"""
if self.has_plugin(name):
self.release_plugin(name)
self._active_plugins[name] = plugin
setattr(self, name, plugin)
return plugin | [
"def",
"register_plugin",
"(",
"self",
",",
"name",
",",
"plugin",
")",
":",
"if",
"self",
".",
"has_plugin",
"(",
"name",
")",
":",
"self",
".",
"release_plugin",
"(",
"name",
")",
"self",
".",
"_active_plugins",
"[",
"name",
"]",
"=",
"plugin",
"seta... | 34.222222 | 8.222222 |
def generate_py_units(data):
"""Generate the list of units in units.py."""
units = collections.defaultdict(list)
for unit in sorted(data.units, key=lambda a: a.name):
if unit.unit_id in static_data.UNIT_TYPES:
units[unit.race].append(unit)
def print_race(name, race):
print("class %s(enum.IntEnum)... | [
"def",
"generate_py_units",
"(",
"data",
")",
":",
"units",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"unit",
"in",
"sorted",
"(",
"data",
".",
"units",
",",
"key",
"=",
"lambda",
"a",
":",
"a",
".",
"name",
")",
":",
"if",
"... | 34.055556 | 10.5 |
def netconf_state_statistics_out_notifications(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
statistics = ET.SubElement(netconf_state, "... | [
"def",
"netconf_state_statistics_out_notifications",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"netconf_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"netconf-state\"",
",",
"xmln... | 50.272727 | 23.272727 |
def GetNeighbors(ID, model = None, neighbors = None, mag_range = None,
cdpp_range = None, aperture_name = None,
cadence = 'lc', **kwargs):
'''
Return `neighbors` random bright stars on the same module as `EPIC`.
:param int ID: The target ID number
:param str model: The :py... | [
"def",
"GetNeighbors",
"(",
"ID",
",",
"model",
"=",
"None",
",",
"neighbors",
"=",
"None",
",",
"mag_range",
"=",
"None",
",",
"cdpp_range",
"=",
"None",
",",
"aperture_name",
"=",
"None",
",",
"cadence",
"=",
"'lc'",
",",
"*",
"*",
"kwargs",
")",
"... | 52.222222 | 33 |
def get_east_asian_width_property(value, is_bytes=False):
"""Get `EAST ASIAN WIDTH` property."""
obj = unidata.ascii_east_asian_width if is_bytes else unidata.unicode_east_asian_width
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['eastasianwidth'].get(ne... | [
"def",
"get_east_asian_width_property",
"(",
"value",
",",
"is_bytes",
"=",
"False",
")",
":",
"obj",
"=",
"unidata",
".",
"ascii_east_asian_width",
"if",
"is_bytes",
"else",
"unidata",
".",
"unicode_east_asian_width",
"if",
"value",
".",
"startswith",
"(",
"'^'",... | 35.916667 | 28.083333 |
def sell(self, no, price, value):
''' 賣 '''
self.money += price*value
try:
self.store[no] += -value
except:
self.store[no] = -value
try:
self.avgprice[no]['sell'] += [price]
except:
try:
self.avgprice[no]['sell'] = [price]
except:
self.avgprice[no] =... | [
"def",
"sell",
"(",
"self",
",",
"no",
",",
"price",
",",
"value",
")",
":",
"self",
".",
"money",
"+=",
"price",
"*",
"value",
"try",
":",
"self",
".",
"store",
"[",
"no",
"]",
"+=",
"-",
"value",
"except",
":",
"self",
".",
"store",
"[",
"no"... | 23.533333 | 17.533333 |
def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name,
logging_level, conn_send, func_running, log_queue):
"""
to be executed as a separate process (that's why this functions is declared static)
"""
prefix = get_identifier(name) +... | [
"def",
"_loop_wrapper_func",
"(",
"func",
",",
"args",
",",
"shared_mem_run",
",",
"shared_mem_pause",
",",
"interval",
",",
"sigint",
",",
"sigterm",
",",
"name",
",",
"logging_level",
",",
"conn_send",
",",
"func_running",
",",
"log_queue",
")",
":",
"prefix... | 33.704918 | 21.737705 |
def build(self):
'''Constructs the term doc matrix.
Returns
-------
TermDocMatrix
'''
X_factory = CSRMatrixFactory()
mX_factory = CSRMatrixFactory()
term_idx_store = IndexStore()
metadata_idx_store = IndexStore()
parse_pipeline = ParsePi... | [
"def",
"build",
"(",
"self",
")",
":",
"X_factory",
"=",
"CSRMatrixFactory",
"(",
")",
"mX_factory",
"=",
"CSRMatrixFactory",
"(",
")",
"term_idx_store",
"=",
"IndexStore",
"(",
")",
"metadata_idx_store",
"=",
"IndexStore",
"(",
")",
"parse_pipeline",
"=",
"Pa... | 42.666667 | 22.666667 |
def return_job(self, job):
"""
Returns a job to its source job set to be run again later.
"""
if self._closed:
return
js = self._job_sources[job]
if len(self._ready_callbacks) > 0:
callback = self._ready_callbacks.popleft()
callback(j... | [
"def",
"return_job",
"(",
"self",
",",
"job",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"js",
"=",
"self",
".",
"_job_sources",
"[",
"job",
"]",
"if",
"len",
"(",
"self",
".",
"_ready_callbacks",
")",
">",
"0",
":",
"callback",
"=",
"s... | 26.2 | 15.533333 |
def get_current(self):
"""
Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change
"""
where = slice(self._oldest_frame_idx(), self._pos)
major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='ut... | [
"def",
"get_current",
"(",
"self",
")",
":",
"where",
"=",
"slice",
"(",
"self",
".",
"_oldest_frame_idx",
"(",
")",
",",
"self",
".",
"_pos",
")",
"major_axis",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"deepcopy",
"(",
"self",
".",
"date_buf",
"[",
"wher... | 45.4 | 22.8 |
def _get_version_mode(self, mode=None):
"""Return a VersionMode for a mode name.
When the mode is None, we are working with the 'base' mode.
"""
version_mode = self._version_modes.get(mode)
if not version_mode:
version_mode = self._version_modes[mode] = VersionMode(n... | [
"def",
"_get_version_mode",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"version_mode",
"=",
"self",
".",
"_version_modes",
".",
"get",
"(",
"mode",
")",
"if",
"not",
"version_mode",
":",
"version_mode",
"=",
"self",
".",
"_version_modes",
"[",
"mode"... | 38.777778 | 15.777778 |
def get_objective_lookup_session_for_objective_bank(self, objective_bank_id=None):
"""Gets the OsidSession associated with the objective lookup
service for the given objective bank.
arg: objectiveBankId (osid.id.Id): the Id of the objective
bank
return: (osid.learning... | [
"def",
"get_objective_lookup_session_for_objective_bank",
"(",
"self",
",",
"objective_bank_id",
"=",
"None",
")",
":",
"if",
"not",
"objective_bank_id",
":",
"raise",
"NullArgument",
"if",
"not",
"self",
".",
"supports_objective_lookup",
"(",
")",
":",
"raise",
"Un... | 41.774194 | 17.225806 |
def princomp(x):
"""Determine the principal components of a vector of measurements
Determine the principal components of a vector of measurements
x should be a M x N numpy array composed of M observations of n variables
The output is:
coeffs - the NxN correlation matrix that can be used to tran... | [
"def",
"princomp",
"(",
"x",
")",
":",
"(",
"M",
",",
"N",
")",
"=",
"x",
".",
"shape",
"Mean",
"=",
"x",
".",
"mean",
"(",
"0",
")",
"y",
"=",
"x",
"-",
"Mean",
"cov",
"=",
"numpy",
".",
"dot",
"(",
"y",
".",
"transpose",
"(",
")",
",",
... | 35.142857 | 23.238095 |
def _find_players(self, year):
"""
Find all player IDs for the requested team.
For the requested team and year (if applicable), pull the roster table
and parse the player ID for all players on the roster and create an
instance of the Player class for the player. All player insta... | [
"def",
"_find_players",
"(",
"self",
",",
"year",
")",
":",
"if",
"not",
"year",
":",
"year",
"=",
"utils",
".",
"_find_year_for_season",
"(",
"'nhl'",
")",
"url",
"=",
"self",
".",
"_create_url",
"(",
"year",
")",
"page",
"=",
"self",
".",
"_pull_team... | 38.90625 | 18.71875 |
def num_features_model(m:nn.Module)->int:
"Return the number of output features for `model`."
sz = 64
while True:
try: return model_sizes(m, size=(sz,sz))[-1][1]
except Exception as e:
sz *= 2
if sz > 2048: raise | [
"def",
"num_features_model",
"(",
"m",
":",
"nn",
".",
"Module",
")",
"->",
"int",
":",
"sz",
"=",
"64",
"while",
"True",
":",
"try",
":",
"return",
"model_sizes",
"(",
"m",
",",
"size",
"=",
"(",
"sz",
",",
"sz",
")",
")",
"[",
"-",
"1",
"]",
... | 32.125 | 15.625 |
def requested_perm(self, perm, obj, check_groups=True):
"""
Check if user requested a permission for the given object
"""
return self.has_perm(perm, obj, check_groups, False) | [
"def",
"requested_perm",
"(",
"self",
",",
"perm",
",",
"obj",
",",
"check_groups",
"=",
"True",
")",
":",
"return",
"self",
".",
"has_perm",
"(",
"perm",
",",
"obj",
",",
"check_groups",
",",
"False",
")"
] | 40.4 | 12 |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List CPCs."""
query_str = uri_parms[0]
result_cpcs = []
filter_args = parse_query_parms(method, uri, query_str)
for cpc in hmc.cpcs.list(filter_args):
result_cpc = {}
for prop in cpc.prope... | [
"def",
"get",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"logon_required",
")",
":",
"query_str",
"=",
"uri_parms",
"[",
"0",
"]",
"result_cpcs",
"=",
"[",
"]",
"filter_args",
"=",
"parse_query_parms",
"(",
"method",
",",
"uri",
",",
... | 43 | 10.416667 |
def timeslide_durations(start1, start2, end1, end2, timeslide_offsets):
""" Find the coincident time for each timeslide.
Find the coincident time for each timeslide, where the first time vector
is slid to the right by the offset in the given timeslide_offsets vector.
Parameters
----------
star... | [
"def",
"timeslide_durations",
"(",
"start1",
",",
"start2",
",",
"end1",
",",
"end2",
",",
"timeslide_offsets",
")",
":",
"from",
".",
"import",
"veto",
"durations",
"=",
"[",
"]",
"seg2",
"=",
"veto",
".",
"start_end_to_segments",
"(",
"start2",
",",
"end... | 37.580645 | 21.483871 |
def update_tab_label(self, state_m):
"""Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier not in self.tabs and state_identifier ... | [
"def",
"update_tab_label",
"(",
"self",
",",
"state_m",
")",
":",
"state_identifier",
"=",
"self",
".",
"get_state_identifier",
"(",
"state_m",
")",
"if",
"state_identifier",
"not",
"in",
"self",
".",
"tabs",
"and",
"state_identifier",
"not",
"in",
"self",
"."... | 54.454545 | 31.454545 |
def console_host(self, new_host):
"""
If allow remote connection we need to bind console host to 0.0.0.0
"""
server_config = Config.instance().get_section_config("Server")
remote_console_connections = server_config.getboolean("allow_remote_console")
if remote_console_conn... | [
"def",
"console_host",
"(",
"self",
",",
"new_host",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"remote_console_connections",
"=",
"server_config",
".",
"getboolean",
"(",
"\"allow_remote... | 43.909091 | 15.727273 |
async def put(self, cid):
"""Update description for content
Accepts:
Query string args:
- "cid" - int
Request body parameters:
- message (signed dict):
- "description" - str
- "coinid" - str
Returns:
dict with following fields:
- "confirmed": None
- "txid" - str
- "descrip... | [
"async",
"def",
"put",
"(",
"self",
",",
"cid",
")",
":",
"if",
"settings",
".",
"SIGNATURE_VERIFICATION",
":",
"super",
"(",
")",
".",
"verify",
"(",
")",
"try",
":",
"body",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"request",
".",
"body",
")"... | 27.536082 | 18.773196 |
def alter_columns(op, name, *columns, **kwargs):
"""Alter columns from a table.
Parameters
----------
name : str
The name of the table.
*columns
The new columns to have.
selection_string : str, optional
The string to use in the selection. If not provided, it will select ... | [
"def",
"alter_columns",
"(",
"op",
",",
"name",
",",
"*",
"columns",
",",
"*",
"*",
"kwargs",
")",
":",
"selection_string",
"=",
"kwargs",
".",
"pop",
"(",
"'selection_string'",
",",
"None",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'alter_co... | 31.918367 | 21.530612 |
def generate_relay_config(project):
"""
Generate Relay Proxy Configuration.
Generate a ld-relay.conf file to quickly spin up a relay proxy.
Right now this is mostly used for integration testing.
:param project: LaunchDarkly project key
"""
ld_api = LaunchDarklyApi(
os.environ.get('... | [
"def",
"generate_relay_config",
"(",
"project",
")",
":",
"ld_api",
"=",
"LaunchDarklyApi",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'LD_API_KEY'",
")",
",",
"project_key",
"=",
"project",
")",
"config",
"=",
"ConfigGenerator",
"(",
")",
"envs",
"=",
"... | 27.411765 | 14.823529 |
def lr(self, lis, op):
"""performs this operation on a list from *left to right*
op must take 2 args
a,b,c => op(op(a, b), c)"""
it = iter(lis)
res = trans(it.next())
for e in it:
e = trans(e)
res = op(res, e)
return res | [
"def",
"lr",
"(",
"self",
",",
"lis",
",",
"op",
")",
":",
"it",
"=",
"iter",
"(",
"lis",
")",
"res",
"=",
"trans",
"(",
"it",
".",
"next",
"(",
")",
")",
"for",
"e",
"in",
"it",
":",
"e",
"=",
"trans",
"(",
"e",
")",
"res",
"=",
"op",
... | 29.2 | 12.9 |
def s2a(s):
"""
convert 6 element "s" list to 3,3 a matrix (see Tauxe 1998)
"""
a = np.zeros((3, 3,), 'f') # make the a matrix
for i in range(3):
a[i][i] = s[i]
a[0][1], a[1][0] = s[3], s[3]
a[1][2], a[2][1] = s[4], s[4]
a[0][2], a[2][0] = s[5], s[5]
return a | [
"def",
"s2a",
"(",
"s",
")",
":",
"a",
"=",
"np",
".",
"zeros",
"(",
"(",
"3",
",",
"3",
",",
")",
",",
"'f'",
")",
"# make the a matrix",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"a",
"[",
"i",
"]",
"[",
"i",
"]",
"=",
"s",
"[",
... | 26.818182 | 13.545455 |
def multipart_listuploads(self, bucket):
"""List objects in a bucket.
:param bucket: A :class:`invenio_files_rest.models.Bucket` instance.
:returns: The Flask response.
"""
return self.make_response(
data=MultipartObject.query_by_bucket(bucket).limit(1000).all(),
... | [
"def",
"multipart_listuploads",
"(",
"self",
",",
"bucket",
")",
":",
"return",
"self",
".",
"make_response",
"(",
"data",
"=",
"MultipartObject",
".",
"query_by_bucket",
"(",
"bucket",
")",
".",
"limit",
"(",
"1000",
")",
".",
"all",
"(",
")",
",",
"con... | 32.5 | 15.428571 |
def parseUri(stream, uri=None):
"""Read an XML document from a URI, and return a :mod:`lxml.etree`
document."""
return etree.parse(stream, parser=_get_xmlparser(), base_url=uri) | [
"def",
"parseUri",
"(",
"stream",
",",
"uri",
"=",
"None",
")",
":",
"return",
"etree",
".",
"parse",
"(",
"stream",
",",
"parser",
"=",
"_get_xmlparser",
"(",
")",
",",
"base_url",
"=",
"uri",
")"
] | 46.5 | 9.5 |
def _convert_choices(self, choices):
"""Auto create display values then call super method"""
final_choices = []
for choice in choices:
if isinstance(choice, ChoiceEntry):
final_choices.append(choice)
continue
original_choice = choice
... | [
"def",
"_convert_choices",
"(",
"self",
",",
"choices",
")",
":",
"final_choices",
"=",
"[",
"]",
"for",
"choice",
"in",
"choices",
":",
"if",
"isinstance",
"(",
"choice",
",",
"ChoiceEntry",
")",
":",
"final_choices",
".",
"append",
"(",
"choice",
")",
... | 34.883721 | 22.395349 |
def sync_code(self):
"""Sync in code files and the meta file, avoiding syncing the larger files"""
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.BUILD, File.BSFILE.MET... | [
"def",
"sync_code",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"file",
"import",
"File",
"from",
"ambry",
".",
"bundle",
".",
"files",
"import",
"BuildSourceFile",
"self",
".",
"dstate",
"=",
"self",
".",
"STATES",
".",
"BUILDING",
"synced"... | 39.809524 | 24.714286 |
def decode_tx_packet(packet: str) -> dict:
"""Break packet down into primitives, and do basic interpretation.
>>> decode_packet('10;Kaku;ID=41;SWITCH=1;CMD=ON;') == {
... 'node': 'gateway',
... 'protocol': 'kaku',
... 'id': '000041',
... 'switch': '1',
... 'command': 'on... | [
"def",
"decode_tx_packet",
"(",
"packet",
":",
"str",
")",
"->",
"dict",
":",
"node_id",
",",
"protocol",
",",
"attrs",
"=",
"packet",
".",
"split",
"(",
"DELIM",
",",
"2",
")",
"data",
"=",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
... | 27.060606 | 18.969697 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.