text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _read_loop_polling(self):
"""Read packets by polling the Engine.IO server."""
while self.state == 'connected':
self.logger.info(
'Sending polling GET request to ' + self.base_url)
r = self._send_request(
'GET', self.base_url + self._get_url_tim... | [
"def",
"_read_loop_polling",
"(",
"self",
")",
":",
"while",
"self",
".",
"state",
"==",
"'connected'",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Sending polling GET request to '",
"+",
"self",
".",
"base_url",
")",
"r",
"=",
"self",
".",
"_send_reques... | 40.35 | 0.00121 |
def _ftp_retrlines_native(self, command, callback, encoding):
"""A re-implementation of ftp.retrlines that returns lines as native `str`.
This is needed on Python 3, where `ftp.retrlines()` returns unicode `str`
by decoding the incoming command response using `ftp.encoding`.
This w... | [
"def",
"_ftp_retrlines_native",
"(",
"self",
",",
"command",
",",
"callback",
",",
"encoding",
")",
":",
"LF",
"=",
"b\"\\n\"",
"buffer",
"=",
"b\"\"",
"# needed to access buffer accross function scope\r",
"local_var",
"=",
"{",
"\"buffer\"",
":",
"buffer",
"}",
"... | 38.752941 | 0.001776 |
def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, request_uri, soapaction, **kw):
'''Resend the initial request w/http digest authorization headers.
The SOAP server has requested authorization. Fetch the challenge,
generate the authdict for building a response.
'''
... | [
"def",
"SendSOAPDataHTTPDigestAuth",
"(",
"self",
",",
"response",
",",
"soapdata",
",",
"url",
",",
"request_uri",
",",
"soapaction",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"trace",
":",
"print",
">>",
"self",
".",
"trace",
",",
"\"------ Dig... | 45.314286 | 0.014815 |
def console_list_load_xp(
filename: str
) -> Optional[List[tcod.console.Console]]:
"""Return a list of consoles from a REXPaint `.xp` file."""
tcod_list = lib.TCOD_console_list_from_xp(filename.encode("utf-8"))
if tcod_list == ffi.NULL:
return None
try:
python_list = []
lib.T... | [
"def",
"console_list_load_xp",
"(",
"filename",
":",
"str",
")",
"->",
"Optional",
"[",
"List",
"[",
"tcod",
".",
"console",
".",
"Console",
"]",
"]",
":",
"tcod_list",
"=",
"lib",
".",
"TCOD_console_list_from_xp",
"(",
"filename",
".",
"encode",
"(",
"\"u... | 34.647059 | 0.001653 |
def stats(args):
"""
cdstarcat stats
Print summary statistics of bitstreams in the catalog to stdout.
"""
cat = _catalog(args)
print('Summary:')
print(' {0:,} objects with {1:,} bitstreams of total size {2}'.format(
len(cat), sum(len(obj.bitstreams) for obj in cat), cat.size_h))
... | [
"def",
"stats",
"(",
"args",
")",
":",
"cat",
"=",
"_catalog",
"(",
"args",
")",
"print",
"(",
"'Summary:'",
")",
"print",
"(",
"' {0:,} objects with {1:,} bitstreams of total size {2}'",
".",
"format",
"(",
"len",
"(",
"cat",
")",
",",
"sum",
"(",
"len",
... | 39.916667 | 0.002039 |
def sortedby(item_list, key_list, reverse=False):
""" sorts ``item_list`` using key_list
Args:
list_ (list): list to sort
key_list (list): list to sort by
reverse (bool): sort order is descending (largest first)
if reverse is True else acscending (smallest first)... | [
"def",
"sortedby",
"(",
"item_list",
",",
"key_list",
",",
"reverse",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"item_list",
")",
"==",
"len",
"(",
"key_list",
")",
",",
"(",
"'Expected same len. Got: %r != %r'",
"%",
"(",
"len",
"(",
"item_list",
")",... | 31.548387 | 0.000992 |
def get_routertypes(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Lists defined router types."""
pass | [
"def",
"get_routertypes",
"(",
"self",
",",
"context",
",",
"filters",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"sorts",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"page_reverse",
"=",
"False",
")",
":",
"pass"
] | 43.6 | 0.018018 |
def ltouches(self, span):
"""
Returns true if the end of this span touches the left (starting) side of the given span.
"""
if isinstance(span, list):
return [sp for sp in span if self._ltouches(sp)]
return self._ltouches(span) | [
"def",
"ltouches",
"(",
"self",
",",
"span",
")",
":",
"if",
"isinstance",
"(",
"span",
",",
"list",
")",
":",
"return",
"[",
"sp",
"for",
"sp",
"in",
"span",
"if",
"self",
".",
"_ltouches",
"(",
"sp",
")",
"]",
"return",
"self",
".",
"_ltouches",
... | 34 | 0.010753 |
def get_product(membersuite_id, client=None):
"""Return a Product object by ID.
"""
if not membersuite_id:
return None
client = client or get_new_client(request_session=True)
object_query = "SELECT Object() FROM PRODUCT WHERE ID = '{}'".format(
membersuite_id)
result = client.... | [
"def",
"get_product",
"(",
"membersuite_id",
",",
"client",
"=",
"None",
")",
":",
"if",
"not",
"membersuite_id",
":",
"return",
"None",
"client",
"=",
"client",
"or",
"get_new_client",
"(",
"request_session",
"=",
"True",
")",
"object_query",
"=",
"\"SELECT O... | 30 | 0.001468 |
def bbox(self):
"""returns a bounding box for the segment in the form
(xmin, xmax, ymin, ymax)."""
# a(t) = radians(self.theta + self.delta*t)
# = (2*pi/360)*(self.theta + self.delta*t)
# x'=0: ~~~~~~~~~
# -rx*cos(phi)*sin(a(t)) = ry*sin(phi)*cos(a(t))
# -(rx... | [
"def",
"bbox",
"(",
"self",
")",
":",
"# a(t) = radians(self.theta + self.delta*t)",
"# = (2*pi/360)*(self.theta + self.delta*t)",
"# x'=0: ~~~~~~~~~",
"# -rx*cos(phi)*sin(a(t)) = ry*sin(phi)*cos(a(t))",
"# -(rx/ry)*cot(phi)*tan(a(t)) = 1",
"# a(t) = arctan(-(ry/rx)tan(phi)) + pi*k === at... | 38.319149 | 0.001083 |
def errprt(op, lenout, inlist):
"""
Retrieve or set the list of error message items to be output when an
error is detected.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errprt_c.html
:param op: The operation, "GET" or "SET".
:type op: str
:param lenout: Length of list for output... | [
"def",
"errprt",
"(",
"op",
",",
"lenout",
",",
"inlist",
")",
":",
"lenout",
"=",
"ctypes",
".",
"c_int",
"(",
"lenout",
")",
"op",
"=",
"stypes",
".",
"stringToCharP",
"(",
"op",
")",
"inlist",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"str",
... | 35.681818 | 0.001241 |
def list_connected_devices(self, **kwargs):
"""List connected devices.
Example usage, listing all registered devices in the catalog:
.. code-block:: python
filters = {
'created_at': {'$gte': datetime.datetime(2017,01,01),
'$lte': date... | [
"def",
"list_connected_devices",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO(pick one of these)",
"filter_or_filters",
"=",
"'filter'",
"if",
"'filter'",
"in",
"kwargs",
"else",
"'filters'",
"kwargs",
".",
"setdefault",
"(",
"filter_or_filters",
",",
"... | 36.58 | 0.001597 |
def pages(self, page_from, page_to):
"""
Yield torrents in range from page_from to page_to
"""
if not all([page_from < self.url.max_page, page_from > 0,
page_to <= self.url.max_page, page_to > page_from]):
raise IndexError("Invalid page numbers")
... | [
"def",
"pages",
"(",
"self",
",",
"page_from",
",",
"page_to",
")",
":",
"if",
"not",
"all",
"(",
"[",
"page_from",
"<",
"self",
".",
"url",
".",
"max_page",
",",
"page_from",
">",
"0",
",",
"page_to",
"<=",
"self",
".",
"url",
".",
"max_page",
","... | 28.789474 | 0.001768 |
def parse_args():
"""Parses command line arguments."""
parser = ArgumentParser(description="ModelBase builder")
subparsers = parser.add_subparsers()
sql_parser = subparsers.add_parser(
"get-query",
description="Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " +
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"ModelBase builder\"",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"sql_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"get-query\"",
",... | 38.307692 | 0.01763 |
def get_effective_agent_id_with_proxy(proxy):
"""Given a Proxy, returns the Id of the effective Agent"""
if is_authenticated_with_proxy(proxy):
if proxy.has_effective_agent():
return proxy.get_effective_agent_id()
else:
return proxy.get_authentication().get_agent_id()
... | [
"def",
"get_effective_agent_id_with_proxy",
"(",
"proxy",
")",
":",
"if",
"is_authenticated_with_proxy",
"(",
"proxy",
")",
":",
"if",
"proxy",
".",
"has_effective_agent",
"(",
")",
":",
"return",
"proxy",
".",
"get_effective_agent_id",
"(",
")",
"else",
":",
"r... | 38 | 0.002141 |
def _make_default_privileges_list_query(name, object_type, prepend):
'''
Generate the SQL required for specific object type
'''
if object_type == 'table':
query = (' '.join([
'SELECT defacl.defaclacl AS name',
'FROM pg_default_acl defacl',
'JOIN pg_authid aid'... | [
"def",
"_make_default_privileges_list_query",
"(",
"name",
",",
"object_type",
",",
"prepend",
")",
":",
"if",
"object_type",
"==",
"'table'",
":",
"query",
"=",
"(",
"' '",
".",
"join",
"(",
"[",
"'SELECT defacl.defaclacl AS name'",
",",
"'FROM pg_default_acl defac... | 35.229508 | 0.000453 |
def _make_request(
self, api_resource, method='GET', params=None, **kwargs):
"""
Shortcut for a generic request to the Toshl API
:param url: The URL resource part
:param method: REST method
:param parameters: Querystring parameters
:return: requests.Response
... | [
"def",
"_make_request",
"(",
"self",
",",
"api_resource",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'json'",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'... | 32.081081 | 0.001635 |
def _getLaplaceCovar(self):
"""
Internal function for estimating parameter uncertainty
Returns:
the
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Sigma'] is None:
... | [
"def",
"_getLaplaceCovar",
"(",
"self",
")",
":",
"assert",
"self",
".",
"init",
",",
"'GP not initialised'",
"assert",
"self",
".",
"fast",
"==",
"False",
",",
"'Not supported for fast implementation'",
"if",
"self",
".",
"cache",
"[",
"'Sigma'",
"]",
"is",
"... | 33.916667 | 0.009569 |
def get_int_noerr(self, arg):
"""Eval arg and it is an integer return the value. Otherwise
return None"""
if self.curframe:
g = self.curframe.f_globals
l = self.curframe.f_locals
else:
g = globals()
l = locals()
pass
try... | [
"def",
"get_int_noerr",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"curframe",
":",
"g",
"=",
"self",
".",
"curframe",
".",
"f_globals",
"l",
"=",
"self",
".",
"curframe",
".",
"f_locals",
"else",
":",
"g",
"=",
"globals",
"(",
")",
"l",... | 30.2 | 0.008565 |
def build_lattice(self, x):
""" Construct the list of nodes and edges for input features. """
I, J, _ = x.shape
lattice = self._subset_independent_lattice((I, J))
return lattice | [
"def",
"build_lattice",
"(",
"self",
",",
"x",
")",
":",
"I",
",",
"J",
",",
"_",
"=",
"x",
".",
"shape",
"lattice",
"=",
"self",
".",
"_subset_independent_lattice",
"(",
"(",
"I",
",",
"J",
")",
")",
"return",
"lattice"
] | 41 | 0.009569 |
def archive_bird_conf(config_file, changes_counter):
"""Keep a history of Bird configuration files.
Arguments:
config_file (str): file name of bird configuration
changes_counter (int): number of configuration files to keep in the
history
"""
log = logging.getLogger(PROGRAM_NAME)... | [
"def",
"archive_bird_conf",
"(",
"config_file",
",",
"changes_counter",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"history_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_fi... | 37.96875 | 0.000803 |
def plotres(psr,deleted=False,group=None,**kwargs):
"""Plot residuals, compute unweighted rms residual."""
res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs
if (not deleted) and N.any(psr.deleted != 0):
res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0]
... | [
"def",
"plotres",
"(",
"psr",
",",
"deleted",
"=",
"False",
",",
"group",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
",",
"t",
",",
"errs",
"=",
"psr",
".",
"residuals",
"(",
")",
",",
"psr",
".",
"toas",
"(",
")",
",",
"psr",
"."... | 36.9375 | 0.019786 |
def timer(fn, miniter=3, minwall=3.0):
"""Runs fn() multiple times and returns the results.
Runs for at least ``miniter`` iterations and ``minwall`` wall time.
"""
results = []
count = 0
# Ideally a monotonic clock, but doesn't matter too much.
wall_begin = time.time()
while True:
... | [
"def",
"timer",
"(",
"fn",
",",
"miniter",
"=",
"3",
",",
"minwall",
"=",
"3.0",
")",
":",
"results",
"=",
"[",
"]",
"count",
"=",
"0",
"# Ideally a monotonic clock, but doesn't matter too much.",
"wall_begin",
"=",
"time",
".",
"time",
"(",
")",
"while",
... | 21.5 | 0.001112 |
def element_by_href_as_smcresult(href, params=None):
""" Get specified element returned as an SMCResult object
:param href: href direct link to object
:return: :py:class:`smc.api.web.SMCResult` with etag, href and
element field holding json, else None
"""
if href:
element = fet... | [
"def",
"element_by_href_as_smcresult",
"(",
"href",
",",
"params",
"=",
"None",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
",",
"params",
"=",
"params",
")",
"if",
"element",
":",
"return",
"element"
] | 35.727273 | 0.002481 |
def _get_action_urls(self):
"""Get the url patterns that route each action to a view."""
actions = {}
model_name = self.model._meta.model_name
# e.g.: polls_poll
base_url_name = '%s_%s' % (self.model._meta.app_label, model_name)
# e.g.: polls_poll_actions
model_a... | [
"def",
"_get_action_urls",
"(",
"self",
")",
":",
"actions",
"=",
"{",
"}",
"model_name",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"model_name",
"# e.g.: polls_poll",
"base_url_name",
"=",
"'%s_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
... | 44.142857 | 0.001583 |
def format_volume(citation_elements):
"""format volume number (roman numbers to arabic)
When the volume number is expressed in roman numbers (CXXII),
they are converted to their equivalent in arabic numbers (42)
"""
re_roman = re.compile(re_roman_numbers + u'$', re.UNICODE)
for el in citation_e... | [
"def",
"format_volume",
"(",
"citation_elements",
")",
":",
"re_roman",
"=",
"re",
".",
"compile",
"(",
"re_roman_numbers",
"+",
"u'$'",
",",
"re",
".",
"UNICODE",
")",
"for",
"el",
"in",
"citation_elements",
":",
"if",
"el",
"[",
"'type'",
"]",
"==",
"'... | 43.909091 | 0.002028 |
def changed(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Output 1 when the value changed, 0 when null or the same
Example::
&target=changed(Server01.connections.handled)
"""
for series in seriesList:
series.name = series.pathExpression = 'changed(%... | [
"def",
"changed",
"(",
"requestContext",
",",
"seriesList",
")",
":",
"for",
"series",
"in",
"seriesList",
":",
"series",
".",
"name",
"=",
"series",
".",
"pathExpression",
"=",
"'changed(%s)'",
"%",
"series",
".",
"name",
"previous",
"=",
"None",
"for",
"... | 32.55 | 0.001493 |
def get_agc_value(self):
"""
Returns sensor's Automatic Gain Control actual value.
0 - Represents high magtetic field
0xFF - Represents low magnetic field
"""
LOGGER.debug("Reading RPS01A sensor's AGC settings",)
return self.bus.read_byte_data(self.a... | [
"def",
"get_agc_value",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Reading RPS01A sensor's AGC settings\"",
",",
")",
"return",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"self",
".",
"address",
",",
"self",
".",
"AGC_reg",
")"
] | 41.75 | 0.01173 |
def stem_frequencies(self):
"""Frequencies of each stem ([k-1]-mer)"""
stemfreq = self.array.sum(axis=1).astype(np.float)
stemfreq /= stemfreq.sum()
return stemfreq | [
"def",
"stem_frequencies",
"(",
"self",
")",
":",
"stemfreq",
"=",
"self",
".",
"array",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"stemfreq",
"/=",
"stemfreq",
".",
"sum",
"(",
")",
"return",
"stemfreq"
] | 38.4 | 0.010204 |
def _ttl(self):
"""Returns ttl or hlim, depending on the IP version"""
return self.hlim if isinstance(self, scapy.layers.inet6.IPv6) else self.ttl | [
"def",
"_ttl",
"(",
"self",
")",
":",
"return",
"self",
".",
"hlim",
"if",
"isinstance",
"(",
"self",
",",
"scapy",
".",
"layers",
".",
"inet6",
".",
"IPv6",
")",
"else",
"self",
".",
"ttl"
] | 53.333333 | 0.018519 |
def _FormatSocketInet128Token(self, token_data):
"""Formats an Internet socket token as a dictionary of values.
Args:
token_data (bsm_token_data_sockinet64): AUT_SOCKINET128 token data.
Returns:
dict[str, str]: token values.
"""
protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_f... | [
"def",
"_FormatSocketInet128Token",
"(",
"self",
",",
"token_data",
")",
":",
"protocol",
"=",
"bsmtoken",
".",
"BSM_PROTOCOLS",
".",
"get",
"(",
"token_data",
".",
"socket_family",
",",
"'UNKNOWN'",
")",
"ip_address",
"=",
"self",
".",
"_FormatPackedIPv6Address",... | 34.5 | 0.001764 |
def _ast_to_code(self, node, **kwargs):
"""Convert an abstract syntax tree to python source code."""
if isinstance(node, OptreeNode):
return self._ast_optree_node_to_code(node, **kwargs)
elif isinstance(node, Identifier):
return self._ast_identifier_to_code(node, **kwargs)
elif isinstance(no... | [
"def",
"_ast_to_code",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"OptreeNode",
")",
":",
"return",
"self",
".",
"_ast_optree_node_to_code",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
"elif",
"isi... | 47.222222 | 0.010381 |
def IsEnabled(self, *args, **kwargs):
"check if all menu items are enabled"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
if not it.IsEnabled():
return False
return True | [
"def",
"IsEnabled",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetMenuItemCount",
"(",
")",
")",
":",
"it",
"=",
"self",
".",
"FindItemByPosition",
"(",
"i",
")",
"if",
"not",
"... | 37.285714 | 0.011236 |
def is_homogeneous(self):
"""True if all the elements of the array are the same."""
hom_base = isinstance(self.base_value, (int, long, numpy.integer, float, bool)) \
or type(self.base_value) == self.dtype \
or (isinstance(self.dtype, type) and isinstance(self.base_v... | [
"def",
"is_homogeneous",
"(",
"self",
")",
":",
"hom_base",
"=",
"isinstance",
"(",
"self",
".",
"base_value",
",",
"(",
"int",
",",
"long",
",",
"numpy",
".",
"integer",
",",
"float",
",",
"bool",
")",
")",
"or",
"type",
"(",
"self",
".",
"base_valu... | 66.714286 | 0.014799 |
def generate(minimum, maximum, local_random=random.Random()):
"""
Generate a random date.
The generated dates are uniformly distributed.
Parameters
----------
minimum : datetime object
maximum : datetime object
local_random : random.Random
Returns
-------
generated_date : ... | [
"def",
"generate",
"(",
"minimum",
",",
"maximum",
",",
"local_random",
"=",
"random",
".",
"Random",
"(",
")",
")",
":",
"if",
"not",
"(",
"minimum",
"<",
"maximum",
")",
":",
"raise",
"ValueError",
"(",
"'{} is not smaller than {}'",
".",
"format",
"(",
... | 30.702703 | 0.000853 |
def generate_table_shared_access_signature(self, table_name, permission=None,
expiry=None, start=None, id=None,
ip=None, protocol=None,
start_pk=None, start_rk=None,
... | [
"def",
"generate_table_shared_access_signature",
"(",
"self",
",",
"table_name",
",",
"permission",
"=",
"None",
",",
"expiry",
"=",
"None",
",",
"start",
"=",
"None",
",",
"id",
"=",
"None",
",",
"ip",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"st... | 54.071429 | 0.010162 |
def validate_changeset(changeset):
"""Validate a changeset is compatible with Amazon's API spec.
Args: changeset: lxml.etree.Element (<ChangeResourceRecordSetsRequest>)
Returns: [ errors ] list of error strings or []."""
errors = []
changes = changeset.findall('.//{%s}Change' % R53_XMLNS)
num_changes = len... | [
"def",
"validate_changeset",
"(",
"changeset",
")",
":",
"errors",
"=",
"[",
"]",
"changes",
"=",
"changeset",
".",
"findall",
"(",
"'.//{%s}Change'",
"%",
"R53_XMLNS",
")",
"num_changes",
"=",
"len",
"(",
"changes",
")",
"if",
"num_changes",
"==",
"0",
":... | 41.391304 | 0.01848 |
def usePointsForInterpolation(self,cNrm,mNrm,interpolator):
'''
Constructs a basic solution for this period, including the consumption
function and marginal value function.
Parameters
----------
cNrm : np.array
(Normalized) consumption points for interpolatio... | [
"def",
"usePointsForInterpolation",
"(",
"self",
",",
"cNrm",
",",
"mNrm",
",",
"interpolator",
")",
":",
"# Construct the unconstrained consumption function",
"cFuncNowUnc",
"=",
"interpolator",
"(",
"mNrm",
",",
"cNrm",
")",
"# Combine the constrained and unconstrained fu... | 41.1875 | 0.008895 |
def deprecated(message, exception=PendingDeprecationWarning):
"""Throw a warning when a function/method will be soon deprecated
Supports passing a ``message`` and an ``exception`` class
(uses ``PendingDeprecationWarning`` by default). This is useful if you
want to alternatively pass a ``DeprecationWarn... | [
"def",
"deprecated",
"(",
"message",
",",
"exception",
"=",
"PendingDeprecationWarning",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnin... | 36.9375 | 0.000824 |
def to_json(self, indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json string
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are exclude... | [
"def",
"to_json",
"(",
"self",
",",
"indent",
":",
"int",
"=",
"None",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"util",
".",
"dump_json",
"(",
"traverse",
"(",
"sel... | 44.086957 | 0.011583 |
def set_y2label(self, s, delay_draw=False):
"set plot ylabel"
self.conf.relabel(y2label=s, delay_draw=delay_draw) | [
"def",
"set_y2label",
"(",
"self",
",",
"s",
",",
"delay_draw",
"=",
"False",
")",
":",
"self",
".",
"conf",
".",
"relabel",
"(",
"y2label",
"=",
"s",
",",
"delay_draw",
"=",
"delay_draw",
")"
] | 42.333333 | 0.015504 |
def per_from_id_except(s, flavors=chat_flavors+inline_flavors):
"""
:param s:
a list or set of from id
:param flavors:
``all`` or a list of flavors
:return:
a seeder function that returns the from id only if the from id is *not* in ``s``
and message flavor is in ``flavo... | [
"def",
"per_from_id_except",
"(",
"s",
",",
"flavors",
"=",
"chat_flavors",
"+",
"inline_flavors",
")",
":",
"return",
"_wrap_none",
"(",
"lambda",
"msg",
":",
"msg",
"[",
"'from'",
"]",
"[",
"'id'",
"]",
"if",
"(",
"flavors",
"==",
"'all'",
"or",
"flavo... | 33.625 | 0.01085 |
def get_submissions():
"""API endpoint to get submissions in JSON format"""
print(request.args.to_dict())
print(request.args.get('search[value]'))
print(request.args.get('draw', 1))
# submissions = session.query(Submission).all()
if request.args.get('correct_filter', 'all') == 'all':
co... | [
"def",
"get_submissions",
"(",
")",
":",
"print",
"(",
"request",
".",
"args",
".",
"to_dict",
"(",
")",
")",
"print",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'search[value]'",
")",
")",
"print",
"(",
"request",
".",
"args",
".",
"get",
"(",
... | 39.454545 | 0.009556 |
def attention_lm_moe_memory_efficient():
"""Memory-efficient version."""
hparams = attention_lm_moe_large()
hparams.diet_experts = True
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.layer_prepostprocess_dropout = 0.0
hparams.memory_efficient_ffn = True
hparams... | [
"def",
"attention_lm_moe_memory_efficient",
"(",
")",
":",
"hparams",
"=",
"attention_lm_moe_large",
"(",
")",
"hparams",
".",
"diet_experts",
"=",
"True",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"n\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\... | 35.916667 | 0.027149 |
def parse_xml_data(content, raincontent, latitude=52.091579,
longitude=5.119734, timeframe=60):
"""Parse the raw data and return as data dictionary."""
result = {SUCCESS: False, MESSAGE: None, DATA: None}
if timeframe < 5 or timeframe > 120:
raise ValueError("Timeframe must be >=... | [
"def",
"parse_xml_data",
"(",
"content",
",",
"raincontent",
",",
"latitude",
"=",
"52.091579",
",",
"longitude",
"=",
"5.119734",
",",
"timeframe",
"=",
"60",
")",
":",
"result",
"=",
"{",
"SUCCESS",
":",
"False",
",",
"MESSAGE",
":",
"None",
",",
"DATA... | 39.117647 | 0.001468 |
def main():
"""Main `ybt` console script entry point - run YABT from command-line."""
conf = init_and_get_conf()
logger = make_logger(__name__)
logger.info('YaBT version {}', __version__)
handlers = {
'build': YabtCommand(func=cmd_build, requires_project=True),
'dot': YabtCommand(fun... | [
"def",
"main",
"(",
")",
":",
"conf",
"=",
"init_and_get_conf",
"(",
")",
"logger",
"=",
"make_logger",
"(",
"__name__",
")",
"logger",
".",
"info",
"(",
"'YaBT version {}'",
",",
"__version__",
")",
"handlers",
"=",
"{",
"'build'",
":",
"YabtCommand",
"("... | 43.619048 | 0.001068 |
def dAbr_dV(dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):
""" Partial derivatives of squared flow magnitudes w.r.t voltage.
Computes partial derivatives of apparent power w.r.t active and
reactive power flows. Partial derivative must equal 1 for lines
with zero flow to avoid division by zer... | [
"def",
"dAbr_dV",
"(",
"dSf_dVa",
",",
"dSf_dVm",
",",
"dSt_dVa",
",",
"dSt_dVm",
",",
"Sf",
",",
"St",
")",
":",
"dAf_dPf",
"=",
"spdiag",
"(",
"2",
"*",
"Sf",
".",
"real",
"(",
")",
")",
"dAf_dQf",
"=",
"spdiag",
"(",
"2",
"*",
"Sf",
".",
"im... | 42.391304 | 0.001003 |
def update(self, values, **context):
"""
Updates the model with the given dictionary of values.
:param values: <dict>
:param context: <orb.Context>
:return: <int>
"""
schema = self.schema()
column_updates = {}
other_updates = {}
for key, ... | [
"def",
"update",
"(",
"self",
",",
"values",
",",
"*",
"*",
"context",
")",
":",
"schema",
"=",
"self",
".",
"schema",
"(",
")",
"column_updates",
"=",
"{",
"}",
"other_updates",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"values",
".",
"item... | 30.1 | 0.002146 |
def do_ls(self, line):
"""ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents.
"""
args = self.line_to_args(line)
if len(args.filenames) == 0:
args.filenames = ['.']
for idx, fn i... | [
"def",
"do_ls",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"line_to_args",
"(",
"line",
")",
"if",
"len",
"(",
"args",
".",
"filenames",
")",
"==",
"0",
":",
"args",
".",
"filenames",
"=",
"[",
"'.'",
"]",
"for",
"idx",
",",
... | 42.77551 | 0.002332 |
def getLinks(page):
"""Create a list of all links contained in a PDF page.
Notes:
see PyMuPDF ducmentation for details.
"""
CheckParent(page)
ln = page.firstLink
links = []
while ln:
nl = getLinkDict(ln)
if nl["kind"] == LINK_GOTO:
if type(nl["to"]) ... | [
"def",
"getLinks",
"(",
"page",
")",
":",
"CheckParent",
"(",
"page",
")",
"ln",
"=",
"page",
".",
"firstLink",
"links",
"=",
"[",
"]",
"while",
"ln",
":",
"nl",
"=",
"getLinkDict",
"(",
"ln",
")",
"if",
"nl",
"[",
"\"kind\"",
"]",
"==",
"LINK_GOTO... | 29.259259 | 0.002451 |
def demean(self, mask=NotSpecified, groupby=NotSpecified):
"""
Construct a Factor that computes ``self`` and subtracts the mean from
row of the result.
If ``mask`` is supplied, ignore values where ``mask`` returns False
when computing row means, and output NaN anywhere the mask ... | [
"def",
"demean",
"(",
"self",
",",
"mask",
"=",
"NotSpecified",
",",
"groupby",
"=",
"NotSpecified",
")",
":",
"return",
"GroupedRowTransform",
"(",
"transform",
"=",
"demean",
",",
"transform_args",
"=",
"(",
")",
",",
"factor",
"=",
"self",
",",
"groupby... | 38.073171 | 0.000416 |
def std(a, axis=None, ddof=0):
"""
Request the standard deviation of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
... | [
"def",
"std",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"ddof",
"=",
"0",
")",
":",
"axes",
"=",
"_normalise_axis",
"(",
"axis",
",",
"a",
")",
"if",
"axes",
"is",
"None",
"or",
"len",
"(",
"axes",
")",
"!=",
"1",
":",
"msg",
"=",
"\"This operat... | 45.241379 | 0.000746 |
def get(self,path):
"""
permet de récupérer une config
Args:
path (String): Nom d'une config
Returns:
type: String
la valeur de la config ou None
"""
path = path.upper()
if path in self._configCache:
re... | [
"def",
"get",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"upper",
"(",
")",
"if",
"path",
"in",
"self",
".",
"_configCache",
":",
"return",
"self",
".",
"_configCache",
"[",
"path",
"]",
"else",
":",
"return",
"self",
".",
"_find... | 24.375 | 0.009877 |
def predict(self, data, initial_args=None):
"""Return the inference from the specified endpoint.
Args:
data (object): Input data for which you want the model to provide inference.
If a serializer was specified when creating the RealTimePredictor, the result of the
... | [
"def",
"predict",
"(",
"self",
",",
"data",
",",
"initial_args",
"=",
"None",
")",
":",
"request_args",
"=",
"self",
".",
"_create_request_args",
"(",
"data",
",",
"initial_args",
")",
"response",
"=",
"self",
".",
"sagemaker_session",
".",
"sagemaker_runtime_... | 56.85 | 0.008651 |
def get_parchg(self, poscar, kpoint, band, spin=None, phase=False,
scale=2):
"""
Generates a Chgcar object, which is the charge density of the specified
wavefunction.
This function generates a Chgcar object with the charge density of the
wavefunction specified... | [
"def",
"get_parchg",
"(",
"self",
",",
"poscar",
",",
"kpoint",
",",
"band",
",",
"spin",
"=",
"None",
",",
"phase",
"=",
"False",
",",
"scale",
"=",
"2",
")",
":",
"if",
"phase",
"and",
"not",
"np",
".",
"all",
"(",
"self",
".",
"kpoints",
"[",
... | 48.042857 | 0.000874 |
def multiple_outputs_from_file(cls, filename, keep_sub_files=True):
"""
Parses a QChem output file with multiple calculations
1.) Seperates the output into sub-files
e.g. qcout -> qcout.0, qcout.1, qcout.2 ... qcout.N
a.) Find delimeter for multiple calcua... | [
"def",
"multiple_outputs_from_file",
"(",
"cls",
",",
"filename",
",",
"keep_sub_files",
"=",
"True",
")",
":",
"to_return",
"=",
"[",
"]",
"with",
"zopen",
"(",
"filename",
",",
"'rt'",
")",
"as",
"f",
":",
"text",
"=",
"re",
".",
"split",
"(",
"r'\\s... | 42.958333 | 0.001898 |
def percentile(self, percentile):
"""Calculate a given spectral percentile for this `Spectrogram`.
Parameters
----------
percentile : `float`
percentile (0 - 100) of the bins to compute
Returns
-------
spectrum : `~gwpy.frequencyseries.FrequencySerie... | [
"def",
"percentile",
"(",
"self",
",",
"percentile",
")",
":",
"out",
"=",
"scipy",
".",
"percentile",
"(",
"self",
".",
"value",
",",
"percentile",
",",
"axis",
"=",
"0",
")",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"name",
"=",
"'{}:... | 40.086957 | 0.002119 |
def send_packet(self, pkt):
"""Low-level interface to queue a packet on the wire (encoded as wire
protocol"""
self.put_client_msg(packet.encode(pkt, self.json_dumps)) | [
"def",
"send_packet",
"(",
"self",
",",
"pkt",
")",
":",
"self",
".",
"put_client_msg",
"(",
"packet",
".",
"encode",
"(",
"pkt",
",",
"self",
".",
"json_dumps",
")",
")"
] | 46.75 | 0.010526 |
def repeat(f, dt=1/60):
""" 重复执行函数f,时间间隔dt """
stop(f)
pyglet.clock.schedule_interval(f, dt) | [
"def",
"repeat",
"(",
"f",
",",
"dt",
"=",
"1",
"/",
"60",
")",
":",
"stop",
"(",
"f",
")",
"pyglet",
".",
"clock",
".",
"schedule_interval",
"(",
"f",
",",
"dt",
")"
] | 25.25 | 0.009615 |
def index_of_nearest(p, hot_points, distance_f=distance):
"""Given a point and a set of hot points it found the hot point
nearest to the given point. An arbitrary distance function can
be specified
:return the index of the nearest hot points, or None if the list of hot
points is empty
""... | [
"def",
"index_of_nearest",
"(",
"p",
",",
"hot_points",
",",
"distance_f",
"=",
"distance",
")",
":",
"min_dist",
"=",
"None",
"nearest_hp_i",
"=",
"None",
"for",
"i",
",",
"hp",
"in",
"enumerate",
"(",
"hot_points",
")",
":",
"dist",
"=",
"distance_f",
... | 36.866667 | 0.001764 |
def _access_rule(method,
ip=None,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
'''
Handles the cmd execution for allow and deny commands.
'''
if _status... | [
"def",
"_access_rule",
"(",
"method",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'d'",
",",
"comment",
"=",
"''",
")",
":",
"i... | 40.928571 | 0.01364 |
def _read_config(cfg_file):
"""
Return a ConfigParser object populated from the settings.cfg file.
:return: A Config Parser object.
"""
config = ConfigParser()
# maintain case of options
config.optionxform = lambda option: option
if not os.path.exists(cfg_file):
# Create an empt... | [
"def",
"_read_config",
"(",
"cfg_file",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"# maintain case of options",
"config",
".",
"optionxform",
"=",
"lambda",
"option",
":",
"option",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cfg_file",
")"... | 29.5 | 0.002053 |
def get_conn(opts, profile=None, host=None, port=None):
'''
Return a conn object for accessing memcached
'''
if not (host and port):
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
... | [
"def",
"get_conn",
"(",
"opts",
",",
"profile",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"(",
"host",
"and",
"port",
")",
":",
"opts_pillar",
"=",
"opts",
".",
"get",
"(",
"'pillar'",
",",
"{",
"}",
... | 29.483871 | 0.001059 |
def add_role(self, databaseName, roleName, collectionName=None):
"""Add one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
Raises:
Er... | [
"def",
"add_role",
"(",
"self",
",",
"databaseName",
",",
"roleName",
",",
"collectionName",
"=",
"None",
")",
":",
"role",
"=",
"{",
"\"databaseName\"",
":",
"databaseName",
",",
"\"roleName\"",
":",
"roleName",
"}",
"if",
"collectionName",
":",
"role",
"["... | 39.925926 | 0.013587 |
def _setup_dmtf_schema(self):
"""
Install the DMTF CIM schema from the DMTF web site if it is not already
installed. This includes downloading the DMTF CIM schema zip file from
the DMTF web site and expanding that file into a subdirectory defined
by `schema_mof_dir`.
Onc... | [
"def",
"_setup_dmtf_schema",
"(",
"self",
")",
":",
"def",
"print_verbose",
"(",
"msg",
")",
":",
"\"\"\"\n Inner method prints msg if self.verbose is `True`.\n \"\"\"",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"msg",
")",
"if",
"not",
"o... | 40.55814 | 0.00056 |
def iter_decode(input, fallback_encoding, errors='replace'):
"""
"Pull"-based decoder.
:param input:
An iterable of byte strings.
The input is first consumed just enough to determine the encoding
based on the precense of a BOM,
then consumed on demand when the return value ... | [
"def",
"iter_decode",
"(",
"input",
",",
"fallback_encoding",
",",
"errors",
"=",
"'replace'",
")",
":",
"decoder",
"=",
"IncrementalDecoder",
"(",
"fallback_encoding",
",",
"errors",
")",
"generator",
"=",
"_iter_decode_generator",
"(",
"input",
",",
"decoder",
... | 37 | 0.001013 |
def get_slice_bound(self, label, side, kind):
"""
Calculate slice bound that corresponds to given label.
Returns leftmost (one-past-the-rightmost if ``side=='right'``) position
of given label.
Parameters
----------
label : object
side : {'left', 'right'}... | [
"def",
"get_slice_bound",
"(",
"self",
",",
"label",
",",
"side",
",",
"kind",
")",
":",
"assert",
"kind",
"in",
"[",
"'ix'",
",",
"'loc'",
",",
"'getitem'",
",",
"None",
"]",
"if",
"side",
"not",
"in",
"(",
"'left'",
",",
"'right'",
")",
":",
"rai... | 34.912281 | 0.000978 |
def get_options(config=None):
"""Build the options from the config object."""
if config is None:
from . import config
config.get = lambda key, default=None: getattr(config, key, default)
base = {
"components": config.get("COMPONENTS"),
"signatures": config.get("SIGNATURES"),... | [
"def",
"get_options",
"(",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"from",
".",
"import",
"config",
"config",
".",
"get",
"=",
"lambda",
"key",
",",
"default",
"=",
"None",
":",
"getattr",
"(",
"config",
",",
"key",
",",
... | 41.03125 | 0.000744 |
def get_next_url(request, redirect_field_name):
"""Retrieves next url from request
Note: This verifies that the url is safe before returning it. If the url
is not safe, this returns None.
:arg HttpRequest request: the http request
:arg str redirect_field_name: the name of the field holding the nex... | [
"def",
"get_next_url",
"(",
"request",
",",
"redirect_field_name",
")",
":",
"next_url",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"redirect_field_name",
")",
"if",
"next_url",
":",
"kwargs",
"=",
"{",
"'url'",
":",
"next_url",
",",
"'require_https'",
":"... | 30.357143 | 0.00114 |
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the en... | [
"def",
"_render_cmd",
"(",
"cmd",
",",
"cwd",
",",
"template",
",",
"saltenv",
"=",
"'base'",
",",
"pillarenv",
"=",
"None",
",",
"pillar_override",
"=",
"None",
")",
":",
"if",
"not",
"template",
":",
"return",
"(",
"cmd",
",",
"cwd",
")",
"# render t... | 33.2 | 0.00117 |
def translit(src, table=UkrainianKMU, preserve_case=True):
u""" Transliterates given unicode `src` text
to transliterated variant according to a given transliteration table.
Official ukrainian transliteration is used by default
:param src: string to transliterate
:type src: str
:param table: tr... | [
"def",
"translit",
"(",
"src",
",",
"table",
"=",
"UkrainianKMU",
",",
"preserve_case",
"=",
"True",
")",
":",
"src",
"=",
"text_type",
"(",
"src",
")",
"src_is_upper",
"=",
"src",
".",
"isupper",
"(",
")",
"if",
"hasattr",
"(",
"table",
",",
"\"DELETE... | 30.578947 | 0.000278 |
def get_channel_embeddings(io_depth, targets, hidden_size, name="channel"):
"""Get separate embedding for each of the channels."""
targets_split = tf.split(targets, io_depth, axis=3)
rgb_embedding_var = tf.get_variable("rgb_target_emb_%s" % name,
[256 * io_depth, hidden_size]... | [
"def",
"get_channel_embeddings",
"(",
"io_depth",
",",
"targets",
",",
"hidden_size",
",",
"name",
"=",
"\"channel\"",
")",
":",
"targets_split",
"=",
"tf",
".",
"split",
"(",
"targets",
",",
"io_depth",
",",
"axis",
"=",
"3",
")",
"rgb_embedding_var",
"=",
... | 51.25 | 0.010778 |
def p_field_optional2_1(self, p):
"""
field : name directives selection_set
"""
p[0] = Field(name=p[1], directives=p[2], selections=p[3]) | [
"def",
"p_field_optional2_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Field",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"directives",
"=",
"p",
"[",
"2",
"]",
",",
"selections",
"=",
"p",
"[",
"3",
"]",
")"
] | 33 | 0.011834 |
def save_repo_cache(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
r=save_json_to_file({'json_file':work['dir_cache_repo_uoa'],... | [
"def",
"save_repo_cache",
"(",
"i",
")",
":",
"r",
"=",
"save_json_to_file",
"(",
"{",
"'json_file'",
":",
"work",
"[",
"'dir_cache_repo_uoa'",
"]",
",",
"'dict'",
":",
"cache_repo_uoa",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",... | 28.111111 | 0.026769 |
def data_chunk(data, chunk, with_overlap=False):
"""Get a data chunk."""
assert isinstance(chunk, tuple)
if len(chunk) == 2:
i, j = chunk
elif len(chunk) == 4:
if with_overlap:
i, j = chunk[:2]
else:
i, j = chunk[2:]
else:
raise ValueError("'ch... | [
"def",
"data_chunk",
"(",
"data",
",",
"chunk",
",",
"with_overlap",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"chunk",
",",
"tuple",
")",
"if",
"len",
"(",
"chunk",
")",
"==",
"2",
":",
"i",
",",
"j",
"=",
"chunk",
"elif",
"len",
"(",
... | 30.357143 | 0.002283 |
def lookup_hostname(self, ip):
"""Look up a lease object with given ip address and return the associated client hostname.
@type ip: str
@rtype: str or None
@raises ValueError:
@raises OmapiError:
@raises OmapiErrorNotFound: if no lease object with the given ip address could be found
@raises OmapiErrorAtt... | [
"def",
"lookup_hostname",
"(",
"self",
",",
"ip",
")",
":",
"res",
"=",
"self",
".",
"lookup_by_lease",
"(",
"ip",
"=",
"ip",
")",
"if",
"\"client-hostname\"",
"not",
"in",
"res",
":",
"raise",
"OmapiErrorAttributeNotFound",
"(",
")",
"return",
"res",
"[",... | 37.533333 | 0.031196 |
def extract_source_planes_strikes_dips(src):
"""
Extract strike and dip angles for source defined by multiple planes.
"""
if "characteristicFaultSource" not in src.tag:
strikes = dict([(key, None) for key, _ in PLANES_STRIKES_PARAM])
dips = dict([(key, None) for key, _ in PLANES_DIPS_PAR... | [
"def",
"extract_source_planes_strikes_dips",
"(",
"src",
")",
":",
"if",
"\"characteristicFaultSource\"",
"not",
"in",
"src",
".",
"tag",
":",
"strikes",
"=",
"dict",
"(",
"[",
"(",
"key",
",",
"None",
")",
"for",
"key",
",",
"_",
"in",
"PLANES_STRIKES_PARAM... | 40.275862 | 0.000836 |
def proximal_huber(space, gamma):
"""Proximal factory of the Huber norm.
Parameters
----------
space : `TensorSpace`
The domain of the functional
gamma : float
The smoothing parameter of the Huber norm functional.
Returns
-------
prox_factory : function
Factory ... | [
"def",
"proximal_huber",
"(",
"space",
",",
"gamma",
")",
":",
"gamma",
"=",
"float",
"(",
"gamma",
")",
"class",
"ProximalHuber",
"(",
"Operator",
")",
":",
"\"\"\"Proximal operator of Huber norm.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"sigma",
")",
":"... | 27.983333 | 0.000575 |
def intSubset(self):
"""Get the internal subset of a document """
ret = libxml2mod.xmlGetIntSubset(self._o)
if ret is None:raise treeError('xmlGetIntSubset() failed')
__tmp = xmlDtd(_obj=ret)
return __tmp | [
"def",
"intSubset",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetIntSubset",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlGetIntSubset() failed'",
")",
"__tmp",
"=",
"xmlDtd",
"(",
"_obj",
"... | 39.833333 | 0.016393 |
def _series_ome(self):
"""Return image series in OME-TIFF file(s)."""
from xml.etree import cElementTree as etree # delayed import
omexml = self.pages[0].description
try:
root = etree.fromstring(omexml)
except etree.ParseError as exc:
# TODO: test badly e... | [
"def",
"_series_ome",
"(",
"self",
")",
":",
"from",
"xml",
".",
"etree",
"import",
"cElementTree",
"as",
"etree",
"# delayed import",
"omexml",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"description",
"try",
":",
"root",
"=",
"etree",
".",
"fromstr... | 46.37561 | 0.000206 |
def run_pipeline(self, pipeline, start_date, end_date):
"""
Compute a pipeline.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline to run.
start_date : pd.Timestamp
Start date of the computed matrix.
end_date : pd.Time... | [
"def",
"run_pipeline",
"(",
"self",
",",
"pipeline",
",",
"start_date",
",",
"end_date",
")",
":",
"# See notes at the top of this module for a description of the",
"# algorithm implemented here.",
"if",
"end_date",
"<",
"start_date",
":",
"raise",
"ValueError",
"(",
"\"s... | 33.152778 | 0.000814 |
def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -i parameter
data -- list of lines
"""
if data:
self.Parameters['-i']\
.on(super(CD_HIT,self)._input_as_multiline_string(data))
return '' | [
"def",
"_input_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'-i'",
"]",
".",
"on",
"(",
"super",
"(",
"CD_HIT",
",",
"self",
")",
".",
"_input_as_multiline_string",
"(",
"data",
")",
")",
... | 31.333333 | 0.010345 |
def get_state(self, minimal:bool=True):
"Return the inner state of the `Callback`, `minimal` or not."
to_remove = ['exclude', 'not_min'] + getattr(self, 'exclude', []).copy()
if minimal: to_remove += getattr(self, 'not_min', []).copy()
return {k:v for k,v in self.__dict__.items() if k no... | [
"def",
"get_state",
"(",
"self",
",",
"minimal",
":",
"bool",
"=",
"True",
")",
":",
"to_remove",
"=",
"[",
"'exclude'",
",",
"'not_min'",
"]",
"+",
"getattr",
"(",
"self",
",",
"'exclude'",
",",
"[",
"]",
")",
".",
"copy",
"(",
")",
"if",
"minimal... | 66.2 | 0.026866 |
def build_type_dict(converters):
"""
Builds type dictionary for user-defined type converters,
used by :mod:`parse` module.
This requires that each type converter has a "name" attribute.
:param converters: List of type converters (parse_types)
:return: Type converter dictionary
"""
more_... | [
"def",
"build_type_dict",
"(",
"converters",
")",
":",
"more_types",
"=",
"{",
"}",
"for",
"converter",
"in",
"converters",
":",
"assert",
"callable",
"(",
"converter",
")",
"more_types",
"[",
"converter",
".",
"name",
"]",
"=",
"converter",
"return",
"more_... | 32.428571 | 0.002141 |
def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | [
"def",
"update_cache",
"(",
"self",
",",
"data",
")",
":",
"UTILS",
".",
"update",
"(",
"self",
".",
"_cache",
",",
"data",
")",
"self",
".",
"_save_cache",
"(",
")"
] | 32.5 | 0.015038 |
def get_prefix(self, el):
"""Get prefix."""
prefix = self.get_prefix_name(el)
return util.lower(prefix) if prefix is not None and not self.is_xml else prefix | [
"def",
"get_prefix",
"(",
"self",
",",
"el",
")",
":",
"prefix",
"=",
"self",
".",
"get_prefix_name",
"(",
"el",
")",
"return",
"util",
".",
"lower",
"(",
"prefix",
")",
"if",
"prefix",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"is_xml",
"else"... | 35.6 | 0.016484 |
def return_type(self) -> Type:
"""
Gives the final return type for this function. If the function takes a single argument,
this is just ``self.second``. If the function takes multiple arguments and returns a basic
type, this should be the final ``.second`` after following all complex t... | [
"def",
"return_type",
"(",
"self",
")",
"->",
"Type",
":",
"return_type",
"=",
"self",
".",
"second",
"while",
"isinstance",
"(",
"return_type",
",",
"ComplexType",
")",
":",
"return_type",
"=",
"return_type",
".",
"second",
"return",
"return_type"
] | 54.583333 | 0.009009 |
def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first a... | [
"def",
"invoke",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
",",
"callback",
"=",
"args",
"[",
":",
"2",
"]",
"ctx",
"=",
"self",
"# This is just to improve the error message in cases where old",
"# code incorrectly invoked this method. This will ev... | 46.293103 | 0.000729 |
def permute(self, qubits: Qubits) -> 'Channel':
"""Return a copy of this channel with qubits in new order"""
vec = self.vec.permute(qubits)
return Channel(vec.tensor, qubits=vec.qubits) | [
"def",
"permute",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'Channel'",
":",
"vec",
"=",
"self",
".",
"vec",
".",
"permute",
"(",
"qubits",
")",
"return",
"Channel",
"(",
"vec",
".",
"tensor",
",",
"qubits",
"=",
"vec",
".",
"qubits",
... | 51.5 | 0.009569 |
def _phir(self, rho, T, x):
"""Residual contribution to the free Helmholtz energy
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
x : float
Mole fraction of ammonia in mixture, [mol/mol]
Returns
... | [
"def",
"_phir",
"(",
"self",
",",
"rho",
",",
"T",
",",
"x",
")",
":",
"# Temperature reducing value, Eq 4",
"Tc12",
"=",
"0.9648407",
"/",
"2",
"*",
"(",
"IAPWS95",
".",
"Tc",
"+",
"NH3",
".",
"Tc",
")",
"Tn",
"=",
"(",
"1",
"-",
"x",
")",
"**",... | 36.131579 | 0.000709 |
def reverse(self):
""" Returns a new BBox object where x and y coordinates are switched
:return: New BBox object with switched coordinates
:rtype: BBox
"""
return BBox((self.min_y, self.min_x, self.max_y, self.max_x), crs=self.crs) | [
"def",
"reverse",
"(",
"self",
")",
":",
"return",
"BBox",
"(",
"(",
"self",
".",
"min_y",
",",
"self",
".",
"min_x",
",",
"self",
".",
"max_y",
",",
"self",
".",
"max_x",
")",
",",
"crs",
"=",
"self",
".",
"crs",
")"
] | 38 | 0.011029 |
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout):
"""Submit all the jobs in job_dict """
if link is None:
return JobStatus.no_job
if job_dict is None:
job_keys = link.jobs.keys()
else:
job_keys = sorted(job_dict.keys())
... | [
"def",
"submit_jobs",
"(",
"self",
",",
"link",
",",
"job_dict",
"=",
"None",
",",
"job_archive",
"=",
"None",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"link",
"is",
"None",
":",
"return",
"JobStatus",
".",
"no_job",
"if",
"job_dict",
... | 38.171875 | 0.001596 |
def main(sniffer_instance=None, test_args=(), progname=sys.argv[0],
args=sys.argv[1:]):
"""
Runs the program. This is used when you want to run this program standalone.
``sniffer_instance`` A class (usually subclassed of Sniffer) that hooks into the
scanner and handles running ... | [
"def",
"main",
"(",
"sniffer_instance",
"=",
"None",
",",
"test_args",
"=",
"(",
")",
",",
"progname",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
",",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"parser",
"=",
"OptionParser",
"(",... | 46.6 | 0.002335 |
def _add_unique_file(self, item):
"""
adds a file in self.config['files'] only if not present already
"""
if item not in self.config['files']:
self.config['files'].append(item) | [
"def",
"_add_unique_file",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"not",
"in",
"self",
".",
"config",
"[",
"'files'",
"]",
":",
"self",
".",
"config",
"[",
"'files'",
"]",
".",
"append",
"(",
"item",
")"
] | 35.833333 | 0.009091 |
def conference_undeaf(self, call_params):
"""REST Conference Undeaf helper
"""
path = '/' + self.api_version + '/ConferenceUndeaf/'
method = 'POST'
return self.request(path, method, call_params) | [
"def",
"conference_undeaf",
"(",
"self",
",",
"call_params",
")",
":",
"path",
"=",
"'/'",
"+",
"self",
".",
"api_version",
"+",
"'/ConferenceUndeaf/'",
"method",
"=",
"'POST'",
"return",
"self",
".",
"request",
"(",
"path",
",",
"method",
",",
"call_params"... | 38.166667 | 0.008547 |
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the RevokeRequestPayload object and decode it
into its constituent parts.
Args:
istream (Stream): A data stream containing encoded object data,
supporting a read metho... | [
"def",
"read",
"(",
"self",
",",
"istream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"RevokeRequestPayload",
",",
"self",
")",
".",
"read",
"(",
"istream",
",",
"kmip_version",
"=",
"kmip_version",
")"... | 41.272727 | 0.001435 |
def _nonzero_intersection(m, m_hat):
"""Count the number of nonzeros in and between m and m_hat.
Returns
----------
m_nnz : number of nonzeros in m (w/o diagonal)
m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)
intersection_nnz : number of nonzeros in intersection of m/m_hat
... | [
"def",
"_nonzero_intersection",
"(",
"m",
",",
"m_hat",
")",
":",
"n_features",
",",
"_",
"=",
"m",
".",
"shape",
"m_no_diag",
"=",
"m",
".",
"copy",
"(",
")",
"m_no_diag",
"[",
"np",
".",
"diag_indices",
"(",
"n_features",
")",
"]",
"=",
"0",
"m_hat... | 29.185185 | 0.002457 |
def list(self, request):
"""
Retrieve logged in user info
"""
serializer = self.get_serializer(request.user)
return Response(serializer.data, status=status.HTTP_200_OK) | [
"def",
"list",
"(",
"self",
",",
"request",
")",
":",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
"request",
".",
"user",
")",
"return",
"Response",
"(",
"serializer",
".",
"data",
",",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")"
] | 33.833333 | 0.009615 |
def _maybe_null_out(result, axis, mask, min_count=1):
"""
xarray version of pandas.core.nanops._maybe_null_out
"""
if hasattr(axis, '__len__'): # if tuple or list
raise ValueError('min_count is not available for reduction '
'with more than one dimensions.')
if axis... | [
"def",
"_maybe_null_out",
"(",
"result",
",",
"axis",
",",
"mask",
",",
"min_count",
"=",
"1",
")",
":",
"if",
"hasattr",
"(",
"axis",
",",
"'__len__'",
")",
":",
"# if tuple or list",
"raise",
"ValueError",
"(",
"'min_count is not available for reduction '",
"'... | 37.619048 | 0.001235 |
def next(self):
"""
Returns the next result from the chained iterables given ``"stride"``.
"""
if self.s:
self.s -= 1
else:
self.s = self.stride - 1
self.i = (self.i + 1) % self.l # new iterable
return self.iterables[self.i].ne... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"s",
":",
"self",
".",
"s",
"-=",
"1",
"else",
":",
"self",
".",
"s",
"=",
"self",
".",
"stride",
"-",
"1",
"self",
".",
"i",
"=",
"(",
"self",
".",
"i",
"+",
"1",
")",
"%",
"self",... | 28.545455 | 0.012346 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.