text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_exception_for_response(
cls,
response_code,
messages,
response_id
):
"""
:type response_code: int
:type messages: list[str]
:type response_id: str
:return: The exception according to the status code.
:rtype: ... | [
"def",
"create_exception_for_response",
"(",
"cls",
",",
"response_code",
",",
"messages",
",",
"response_id",
")",
":",
"error_message",
"=",
"cls",
".",
"_generate_message_error",
"(",
"response_code",
",",
"messages",
",",
"response_id",
")",
"if",
"response_code... | 29.637681 | 16.362319 |
def fetch(self, is_dl_forced=False):
"""
:param is_dl_forced: boolean, force download
:return:
"""
(files_to_download, ftp) = self._get_file_list(
self.files['anat_entity']['path'],
self.files['anat_entity']['pattern'])
LOG.info(
'Wil... | [
"def",
"fetch",
"(",
"self",
",",
"is_dl_forced",
"=",
"False",
")",
":",
"(",
"files_to_download",
",",
"ftp",
")",
"=",
"self",
".",
"_get_file_list",
"(",
"self",
".",
"files",
"[",
"'anat_entity'",
"]",
"[",
"'path'",
"]",
",",
"self",
".",
"files"... | 40.130435 | 22.391304 |
def make_default_docstr(func, with_args=True, with_ret=True,
with_commandline=True, with_example=True,
with_header=False, with_debug=False):
r"""
Tries to make a sensible default docstr so the user
can fill things in without typing too much
# TODO: Interl... | [
"def",
"make_default_docstr",
"(",
"func",
",",
"with_args",
"=",
"True",
",",
"with_ret",
"=",
"True",
",",
"with_commandline",
"=",
"True",
",",
"with_example",
"=",
"True",
",",
"with_header",
"=",
"False",
",",
"with_debug",
"=",
"False",
")",
":",
"im... | 34.742424 | 16.727273 |
def build_docker(ctx, image):
"""
build docker images
"""
if image not in DOCKER_IMGS:
print('Error: unknown docker image "{0}"!'.format(image), file=sys.stderr)
sys.exit(1)
dinfo = DOCKER_IMGS[image]
ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True)
dinfo_work_d... | [
"def",
"build_docker",
"(",
"ctx",
",",
"image",
")",
":",
"if",
"image",
"not",
"in",
"DOCKER_IMGS",
":",
"print",
"(",
"'Error: unknown docker image \"{0}\"!'",
".",
"format",
"(",
"image",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
... | 41.142857 | 21.142857 |
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs):
"""List of one or more terms to search for in the Whois record,
as a Python list or separated with the pipe character ( | ).
"""
return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited... | [
"def",
"reverse_whois",
"(",
"self",
",",
"query",
",",
"exclude",
"=",
"[",
"]",
",",
"scope",
"=",
"'current'",
",",
"mode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_results",
"(",
"'reverse-whois'",
",",
"'/v1/reverse... | 68.833333 | 28.5 |
def branch_lines(self):
"""Returns a list of line numbers that have more than one exit."""
exit_counts = self.parser.exit_counts()
return [l1 for l1,count in iitems(exit_counts) if count > 1] | [
"def",
"branch_lines",
"(",
"self",
")",
":",
"exit_counts",
"=",
"self",
".",
"parser",
".",
"exit_counts",
"(",
")",
"return",
"[",
"l1",
"for",
"l1",
",",
"count",
"in",
"iitems",
"(",
"exit_counts",
")",
"if",
"count",
">",
"1",
"]"
] | 53 | 13 |
def strip_comments(tokens):
"""Drop comment tokens from a `tokenize` stream.
Comments on lines 1-2 are kept, to preserve hashbang and encoding.
Trailing whitespace is remove from all lines.
"""
prev_typ = None
prev_end_col = 0
for typ, tok, (start_row, start_col), (end_row, end_col), line i... | [
"def",
"strip_comments",
"(",
"tokens",
")",
":",
"prev_typ",
"=",
"None",
"prev_end_col",
"=",
"0",
"for",
"typ",
",",
"tok",
",",
"(",
"start_row",
",",
"start_col",
")",
",",
"(",
"end_row",
",",
"end_col",
")",
",",
"line",
"in",
"tokens",
":",
"... | 37.5 | 16.65 |
def _extract(self, item):
""" Extracts a handler and handler's arguments that can be provided
as list or dictionary. If arguments are provided as list, they are
considered to have this sequence: (handler, memoize, timeout)
Examples:
event += handler
... | [
"def",
"_extract",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"item",
":",
"raise",
"ValueError",
"(",
"'Invalid arguments'",
")",
"handler",
"=",
"None",
"memoize",
"=",
"False",
"timeout",
"=",
"0",
"if",
"not",
"isinstance",
"(",
"item",
",",
... | 38.266667 | 14.3 |
def _set_K_H(self, k, h):
"used by a kex object to set the K (root key) and H (exchange hash)"
self.K = k
self.H = h
if self.session_id == None:
self.session_id = h | [
"def",
"_set_K_H",
"(",
"self",
",",
"k",
",",
"h",
")",
":",
"self",
".",
"K",
"=",
"k",
"self",
".",
"H",
"=",
"h",
"if",
"self",
".",
"session_id",
"==",
"None",
":",
"self",
".",
"session_id",
"=",
"h"
] | 33.833333 | 18.166667 |
def parse_timespan(timedef):
"""
Convert a string timespan definition to seconds, for example converting
'1m30s' to 90. If *timedef* is already an int, the value will be returned
unmodified.
:param timedef: The timespan definition to convert to seconds.
:type timedef: int, str
:return: The converted value in se... | [
"def",
"parse_timespan",
"(",
"timedef",
")",
":",
"if",
"isinstance",
"(",
"timedef",
",",
"int",
")",
":",
"return",
"timedef",
"converter_order",
"=",
"(",
"'w'",
",",
"'d'",
",",
"'h'",
",",
"'m'",
",",
"'s'",
")",
"converters",
"=",
"{",
"'w'",
... | 23.409091 | 19.954545 |
def add_filter(self, ftype, func):
''' Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. '''
if not isinstance(ftype, type):
raise TypeError("Expected type object, got %s" % type(ftype))
self.castfilter = [(t, f... | [
"def",
"add_filter",
"(",
"self",
",",
"ftype",
",",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"ftype",
",",
"type",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected type object, got %s\"",
"%",
"type",
"(",
"ftype",
")",
")",
"self",
".",
"castf... | 54.5 | 18.75 |
def recompute_table_revnums(self):
'''
Recomputes the revnums for the csetLog table
by creating a new table, and copying csetLog to
it. The INTEGER PRIMARY KEY in the temp table auto increments
as rows are added.
IMPORTANT: Only call this after acquiring the
... | [
"def",
"recompute_table_revnums",
"(",
"self",
")",
":",
"with",
"self",
".",
"conn",
".",
"transaction",
"(",
")",
"as",
"t",
":",
"t",
".",
"execute",
"(",
"'''\n CREATE TABLE temp (\n revnum INTEGER PRIMARY KEY,\n revision... | 34.615385 | 18.846154 |
def ctrl(char):
"""
Calculate the control code for a given key. For example, this converts
"a" to 1 (which is the code for ctrl-a).
:param char: The key to convert to a control code.
:return: The control code as an integer or None if unknown.
"""
# Convert strin... | [
"def",
"ctrl",
"(",
"char",
")",
":",
"# Convert string to int... assuming any non-integer is a string.",
"# TODO: Consider asserting a more rigorous test without falling back to past basestring.",
"if",
"not",
"isinstance",
"(",
"char",
",",
"int",
")",
":",
"char",
"=",
"ord"... | 43 | 21.8 |
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of x in the observed input data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
assert len(x) == self.dim_x
k_x = min(k, self.size... | [
"def",
"nn_x",
"(",
"self",
",",
"x",
",",
"k",
"=",
"1",
",",
"radius",
"=",
"np",
".",
"inf",
",",
"eps",
"=",
"0.0",
",",
"p",
"=",
"2",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"self",
".",
"dim_x",
"k_x",
"=",
"min",
"(",
"k",... | 51.9 | 14.5 |
def delete_collection(db_name, collection_name, host='localhost', port=27017):
"""Almost exclusively for testing."""
client = MongoClient("mongodb://%s:%d" % (host, port))
client[db_name].drop_collection(collection_name) | [
"def",
"delete_collection",
"(",
"db_name",
",",
"collection_name",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"27017",
")",
":",
"client",
"=",
"MongoClient",
"(",
"\"mongodb://%s:%d\"",
"%",
"(",
"host",
",",
"port",
")",
")",
"client",
"[",
"db_... | 57.25 | 17 |
def main():
"""Runs the test sender."""
stream_config = spead2.send.StreamConfig(
max_packet_size=16356, rate=1000e6, burst_size=10, max_heaps=1)
item_group = spead2.send.ItemGroup(flavour=spead2.Flavour(4, 64, 48, 0))
# Add item descriptors to the heap.
num_baselines = (512 * 513) // 2
... | [
"def",
"main",
"(",
")",
":",
"stream_config",
"=",
"spead2",
".",
"send",
".",
"StreamConfig",
"(",
"max_packet_size",
"=",
"16356",
",",
"rate",
"=",
"1000e6",
",",
"burst_size",
"=",
"10",
",",
"max_heaps",
"=",
"1",
")",
"item_group",
"=",
"spead2",
... | 40.050847 | 17.355932 |
def create_forward_model(self, encoded_state, encoded_next_state):
"""
Creates forward model TensorFlow ops for Curiosity module.
Predicts encoded future state based on encoded current state and given action.
:param encoded_state: Tensor corresponding to encoded current state.
:p... | [
"def",
"create_forward_model",
"(",
"self",
",",
"encoded_state",
",",
"encoded_next_state",
")",
":",
"combined_input",
"=",
"tf",
".",
"concat",
"(",
"[",
"encoded_state",
",",
"self",
".",
"selected_actions",
"]",
",",
"axis",
"=",
"1",
")",
"hidden",
"="... | 73.875 | 42.5 |
def disconnectMsToNet(Facility_presence=0, UserUser_presence=0,
SsVersionIndicator_presence=0):
"""Disconnect Section 9.3.7.2"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x25) # 00100101
c = Cause()
packet = a / b / c
if Facility_presence is 1:
d = FacilityHdr(ieiF... | [
"def",
"disconnectMsToNet",
"(",
"Facility_presence",
"=",
"0",
",",
"UserUser_presence",
"=",
"0",
",",
"SsVersionIndicator_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x25",
... | 36.176471 | 13.470588 |
def load_blocks(self, location, blocks, ranges, query):
""" Load one or more blocks of compressed cdx lines, return
a line iterator which decompresses and returns one line at a time,
bounded by query.key and query.end_key
"""
if (logging.getLogger().getEffectiveLevel() <= logging... | [
"def",
"load_blocks",
"(",
"self",
",",
"location",
",",
"blocks",
",",
"ranges",
",",
"query",
")",
":",
"if",
"(",
"logging",
".",
"getLogger",
"(",
")",
".",
"getEffectiveLevel",
"(",
")",
"<=",
"logging",
".",
"DEBUG",
")",
":",
"msg",
"=",
"'Loa... | 36.151515 | 20.212121 |
def plot_chain(chain, joints, ax, target=None, show=False):
"""Plots the chain"""
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (in... | [
"def",
"plot_chain",
"(",
"chain",
",",
"joints",
",",
"ax",
",",
"target",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"# LIst of nodes and orientations",
"nodes",
"=",
"[",
"]",
"axes",
"=",
"[",
"]",
"transformation_matrixes",
"=",
"chain",
".",
... | 42.5 | 27.615385 |
def upvoters(self):
"""获取答案点赞用户,返回生成器.
:return: 点赞用户
:rtype: Author.Iterable
"""
self._make_soup()
next_req = '/answer/' + str(self.aid) + '/voters_profile'
while next_req != '':
data = self._session.get(Zhihu_URL + next_req).json()
next_r... | [
"def",
"upvoters",
"(",
"self",
")",
":",
"self",
".",
"_make_soup",
"(",
")",
"next_req",
"=",
"'/answer/'",
"+",
"str",
"(",
"self",
".",
"aid",
")",
"+",
"'/voters_profile'",
"while",
"next_req",
"!=",
"''",
":",
"data",
"=",
"self",
".",
"_session"... | 33.571429 | 13.071429 |
def list_statistics(self, begin_date, end_date, shop_id=-1):
"""
Wi-Fi数据统计
详情请参考
http://mp.weixin.qq.com/wiki/8/dfa2b756b66fca5d9b1211bc18812698.html
:param begin_date: 起始日期时间,最长时间跨度为30天
:param end_date: 结束日期时间戳,最长时间跨度为30天
:param shop_id: 可选,门店 ID,按门店ID搜索,-1为总统计... | [
"def",
"list_statistics",
"(",
"self",
",",
"begin_date",
",",
"end_date",
",",
"shop_id",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"begin_date",
",",
"(",
"datetime",
",",
"date",
")",
")",
":",
"begin_date",
"=",
"begin_date",
".",
"strftime",... | 32.115385 | 15.576923 |
def write_module_file(name, path, package):
'''Creates an RST file for the module name passed in. It places it in the
path defined
'''
file_path = join(path, '%s.rst' % name)
mod_file = open(file_path, 'w')
mod_file.write('%s\n' % AUTOGEN)
mod_file.write('%s\n' % name.title())
mod_file.... | [
"def",
"write_module_file",
"(",
"name",
",",
"path",
",",
"package",
")",
":",
"file_path",
"=",
"join",
"(",
"path",
",",
"'%s.rst'",
"%",
"name",
")",
"mod_file",
"=",
"open",
"(",
"file_path",
",",
"'w'",
")",
"mod_file",
".",
"write",
"(",
"'%s\\n... | 36.588235 | 12.235294 |
def oauth_client_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/oauth_clients#show-client"
api_path = "/api/v2/oauth/clients/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"oauth_client_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/oauth/clients/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_p... | 52.6 | 12.6 |
def task_or_dryrun(*args, **kwargs):
"""
Decorator declaring the wrapped function to be a new-style task.
May be invoked as a simple, argument-less decorator (i.e. ``@task``) or
with arguments customizing its behavior (e.g. ``@task(alias='myalias')``).
Please see the :ref:`new-style task <task-dec... | [
"def",
"task_or_dryrun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"invoked",
"=",
"bool",
"(",
"not",
"args",
"or",
"kwargs",
")",
"task_class",
"=",
"kwargs",
".",
"pop",
"(",
"\"task_class\"",
",",
"WrappedCallableTask",
")",
"# if invoke... | 34.935484 | 21.451613 |
def replace(self, resource, id_, document):
"""Replace document in index."""
args = self._es_args(resource, refresh=True)
document.pop('_id', None)
document.pop('_type', None)
self._update_parent_args(resource, args, document)
return self.elastic(resource).index(body=docu... | [
"def",
"replace",
"(",
"self",
",",
"resource",
",",
"id_",
",",
"document",
")",
":",
"args",
"=",
"self",
".",
"_es_args",
"(",
"resource",
",",
"refresh",
"=",
"True",
")",
"document",
".",
"pop",
"(",
"'_id'",
",",
"None",
")",
"document",
".",
... | 47.857143 | 11.285714 |
def _get_indicators_for_report_page_generator(self, report_id, start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_pa... | [
"def",
"_get_indicators_for_report_page_generator",
"(",
"self",
",",
"report_id",
",",
"start_page",
"=",
"0",
",",
"page_size",
"=",
"None",
")",
":",
"get_page",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"get_indicators_for_report_page",
",",
"report_... | 49.916667 | 29.583333 |
def parse_filter(args, analog=False, sample_rate=None):
"""Parse arbitrary input args into a TF or ZPK filter definition
Parameters
----------
args : `tuple`, `~scipy.signal.lti`
filter definition, normally just captured positional ``*args``
from a function call
analog : `bool`, op... | [
"def",
"parse_filter",
"(",
"args",
",",
"analog",
"=",
"False",
",",
"sample_rate",
"=",
"None",
")",
":",
"if",
"analog",
"and",
"not",
"sample_rate",
":",
"raise",
"ValueError",
"(",
"\"Must give sample_rate frequency to convert \"",
"\"analog filter to digital\"",... | 31.754098 | 20.786885 |
def registration_error(self, stanza):
"""Handle in-band registration error.
[client only]
:Parameters:
- `stanza`: the error stanza received or `None` on timeout.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
self.lock.acquire()
try:
... | [
"def",
"registration_error",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"err",
"=",
"stanza",
".",
"get_error",
"(",
")",
"ae",
"=",
"err",
".",
"xpath_eval",
"(",
"\"e:*\"",
",",
"{",
"\"e\"",
... | 31.55 | 19.15 |
def get_node(self, *node_ids, node_attr=NONE):
"""
Returns a sub node of a dispatcher.
:param node_ids:
A sequence of node ids or a single node id. The id order identifies
a dispatcher sub-level.
:type node_ids: str
:param node_attr:
Output n... | [
"def",
"get_node",
"(",
"self",
",",
"*",
"node_ids",
",",
"node_attr",
"=",
"NONE",
")",
":",
"kw",
"=",
"{",
"}",
"from",
".",
"sol",
"import",
"Solution",
"if",
"node_attr",
"is",
"NONE",
":",
"node_attr",
"=",
"'output'",
"if",
"isinstance",
"(",
... | 31.930233 | 23.069767 |
def main():
''' Execute the "bokeh" command line program.
'''
import sys
from bokeh.command.bootstrap import main as _main
# Main entry point (see setup.py)
_main(sys.argv) | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
"from",
"bokeh",
".",
"command",
".",
"bootstrap",
"import",
"main",
"as",
"_main",
"# Main entry point (see setup.py)",
"_main",
"(",
"sys",
".",
"argv",
")"
] | 21 | 23.888889 |
def refresh_decorations(self, force=False):
"""
Refresh decorations colors. This function is called by the syntax
highlighter when the style changed so that we may update our
decorations colors according to the new style.
"""
cursor = self.editor.textCursor()
if (... | [
"def",
"refresh_decorations",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"cursor",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
"if",
"(",
"self",
".",
"_prev_cursor",
"is",
"None",
"or",
"force",
"or",
"self",
".",
"_prev_cursor",
... | 48.058824 | 12.176471 |
def rgb(color,default=(0,0,0)):
""" return rgb tuple for named color in rgb.txt or a hex color """
c = color.lower()
if c[0:1] == '#' and len(c)==7:
r,g,b = c[1:3], c[3:5], c[5:]
r,g,b = [int(n, 16) for n in (r, g, b)]
return (r,g,b)
if c.find(' ')>-1: c = c.replace(' ','')
... | [
"def",
"rgb",
"(",
"color",
",",
"default",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
":",
"c",
"=",
"color",
".",
"lower",
"(",
")",
"if",
"c",
"[",
"0",
":",
"1",
"]",
"==",
"'#'",
"and",
"len",
"(",
"c",
")",
"==",
"7",
":",
"r",
... | 36.166667 | 13 |
def register_extension(self, module, extension):
"""
Function registers into self.commands from module extension.
All extension subcommands are registered using the name convention
'extension:command'
Example:
If you have a redis extension namely 'gredis', the extens... | [
"def",
"register_extension",
"(",
"self",
",",
"module",
",",
"extension",
")",
":",
"if",
"module",
"is",
"not",
"None",
":",
"cmds",
"=",
"self",
".",
"retrieve_commands",
"(",
"module",
")",
"commands",
"=",
"[",
"]",
"for",
"c",
"in",
"cmds",
":",
... | 33.115385 | 17.807692 |
def connectionMade(self):
"""Register with the stomp server.
"""
cmd = self.sm.connect()
self.transport.write(cmd) | [
"def",
"connectionMade",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"sm",
".",
"connect",
"(",
")",
"self",
".",
"transport",
".",
"write",
"(",
"cmd",
")"
] | 28.4 | 6.2 |
def step_state(self, state, successor_func=None, **run_args):
"""
Don't use this function manually - it is meant to interface with exploration techniques.
"""
try:
successors = self.successors(state, successor_func=successor_func, **run_args)
stashes = {None: succ... | [
"def",
"step_state",
"(",
"self",
",",
"state",
",",
"successor_func",
"=",
"None",
",",
"*",
"*",
"run_args",
")",
":",
"try",
":",
"successors",
"=",
"self",
".",
"successors",
"(",
"state",
",",
"successor_func",
"=",
"successor_func",
",",
"*",
"*",
... | 41.095238 | 22.047619 |
def stats_per_key(self):
"""
Return statistics calculated for each key in the container.
Note:
The feature container has to be opened in advance.
Returns:
dict: A dictionary containing a DataStats object for each key.
"""
self.raise_error_if_not_... | [
"def",
"stats_per_key",
"(",
"self",
")",
":",
"self",
".",
"raise_error_if_not_open",
"(",
")",
"all_stats",
"=",
"{",
"}",
"for",
"key",
",",
"data",
"in",
"self",
".",
"_file",
".",
"items",
"(",
")",
":",
"data",
"=",
"data",
"[",
"(",
")",
"]"... | 31.956522 | 21.956522 |
def plot_decorate_rebits(basis=None, rebit_axes=REBIT_AXES):
"""
Decorates a figure with the boundary of rebit state space
and basis labels drawn from a :ref:`~qinfer.tomography.TomographyBasis`.
:param qinfer.tomography.TomographyBasis basis: Basis to use in
labeling axes.
:param list rebi... | [
"def",
"plot_decorate_rebits",
"(",
"basis",
"=",
"None",
",",
"rebit_axes",
"=",
"REBIT_AXES",
")",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"basis",
"is",
"not",
"None",
":",
"labels",
"=",
"list",
"(",
"map",
"(",
"r'$\\langle\\!\\langle {} ... | 35.25 | 21.5 |
def internal_files(self):
"""Return a list of the intermediate files produced by this link.
This returns all files that were explicitly marked as internal files.
"""
ret_list = []
for key, val in self.file_dict.items():
# For internal files we only want files that we... | [
"def",
"internal_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For internal files we only want files that were marked as",
"# internal",
"if",
"val",
"&",
"Fi... | 37.583333 | 16.083333 |
def shortsum(ctx, app_id, review_file,
json_flag, review, length, request_id):
# type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA
"""Summarize reviews into a short summary."""
app_id = clean_app_id(app_id)
review_list = clean_review(review, review_file... | [
"def",
"shortsum",
"(",
"ctx",
",",
"app_id",
",",
"review_file",
",",
"json_flag",
",",
"review",
",",
"length",
",",
"request_id",
")",
":",
"# type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA",
"app_id",
"=",
"clean_app_id",
"(",
... | 30.095238 | 20.52381 |
def compile_sass(self, sass_filename, sass_fileurl):
"""
Compile the given SASS file into CSS
"""
compile_kwargs = {
'filename': sass_filename,
'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS,
'custom_functions': get_custom_functions()... | [
"def",
"compile_sass",
"(",
"self",
",",
"sass_filename",
",",
"sass_fileurl",
")",
":",
"compile_kwargs",
"=",
"{",
"'filename'",
":",
"sass_filename",
",",
"'include_paths'",
":",
"SassProcessor",
".",
"include_paths",
"+",
"APPS_INCLUDE_DIRS",
",",
"'custom_funct... | 44.5 | 15.722222 |
def Java(env, target, source, *args, **kw):
"""
A pseudo-Builder wrapper around the separate JavaClass{File,Dir}
Builders.
"""
if not SCons.Util.is_List(target):
target = [target]
if not SCons.Util.is_List(source):
source = [source]
# Pad the target list with repetitions of ... | [
"def",
"Java",
"(",
"env",
",",
"target",
",",
"source",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"target",
")",
":",
"target",
"=",
"[",
"target",
"]",
"if",
"not",
"SCons",
".",
... | 31.114286 | 14.714286 |
def _deriv_hypot(x, y):
"""Derivative of numpy hypot function"""
r = np.hypot(x, y)
df_dx = x / r
df_dy = y / r
return np.hstack([df_dx, df_dy]) | [
"def",
"_deriv_hypot",
"(",
"x",
",",
"y",
")",
":",
"r",
"=",
"np",
".",
"hypot",
"(",
"x",
",",
"y",
")",
"df_dx",
"=",
"x",
"/",
"r",
"df_dy",
"=",
"y",
"/",
"r",
"return",
"np",
".",
"hstack",
"(",
"[",
"df_dx",
",",
"df_dy",
"]",
")"
] | 26.5 | 14.166667 |
def random_tickers(
length, n_tickers, endswith=None, letters=None, slicer=itertools.islice
):
"""Generate a length-n_tickers list of unique random ticker symbols.
Parameters
----------
length : int
The length of each ticker string.
n_tickers : int
Number of tickers to... | [
"def",
"random_tickers",
"(",
"length",
",",
"n_tickers",
",",
"endswith",
"=",
"None",
",",
"letters",
"=",
"None",
",",
"slicer",
"=",
"itertools",
".",
"islice",
")",
":",
"# The trick here is that we need uniqueness. That defeats the\r",
"# purpose of using Num... | 31.735849 | 20.962264 |
def clear(self):
"""Release the semaphore of all of its bounds, setting the internal
counter back to its original bind limit. Notify an equivalent amount
of threads that they can run."""
with self._cond:
to_notify = self._initial - self._value
self._value = self._... | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_cond",
":",
"to_notify",
"=",
"self",
".",
"_initial",
"-",
"self",
".",
"_value",
"self",
".",
"_value",
"=",
"self",
".",
"_initial",
"self",
".",
"_cond",
".",
"notify",
"(",
"to_notify... | 45.125 | 11 |
def save_to_file(self, filename, remap_dim0=None, remap_dim1=None):
"""Saves matrix to the file.
Args:
filename: name of the file where to save matrix
remap_dim0: dictionary with mapping row indices to row names which should
be saved to file. If none then indices will be used as names.
... | [
"def",
"save_to_file",
"(",
"self",
",",
"filename",
",",
"remap_dim0",
"=",
"None",
",",
"remap_dim1",
"=",
"None",
")",
":",
"# rows - first index",
"# columns - second index",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fobj",
":",
"columns",
... | 39.5 | 17.875 |
def encode_request(name, max_size):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, max_size))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_in... | [
"def",
"encode_request",
"(",
"name",
",",
"max_size",
")",
":",
"client_message",
"=",
"ClientMessage",
"(",
"payload_size",
"=",
"calculate_size",
"(",
"name",
",",
"max_size",
")",
")",
"client_message",
".",
"set_message_type",
"(",
"REQUEST_TYPE",
")",
"cli... | 43.333333 | 8.555556 |
def on_add(self, widget, new_dict=False):
"""" Adds a new entry to the semantic data of a state. Reloads the tree store.
:param widget: The source widget of the action
:param bool new_dict: A flag to indicate if the new value is of type dict
:return:
"""
self.semantic_da... | [
"def",
"on_add",
"(",
"self",
",",
"widget",
",",
"new_dict",
"=",
"False",
")",
":",
"self",
".",
"semantic_data_counter",
"+=",
"1",
"treeiter",
",",
"path",
"=",
"self",
".",
"get_selected_object",
"(",
")",
"value",
"=",
"dict",
"(",
")",
"if",
"ne... | 38.935484 | 22.580645 |
def crc(self):
"""
A CRC of the current vertices and entities.
Returns
------------
crc: int, CRC of entity points and vertices
"""
# first CRC the points in every entity
target = caching.crc32(bytes().join(e._bytes()
... | [
"def",
"crc",
"(",
"self",
")",
":",
"# first CRC the points in every entity",
"target",
"=",
"caching",
".",
"crc32",
"(",
"bytes",
"(",
")",
".",
"join",
"(",
"e",
".",
"_bytes",
"(",
")",
"for",
"e",
"in",
"self",
".",
"entities",
")",
")",
"# add t... | 31.214286 | 14.642857 |
def gen_uid(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
data_uid - UID in string format (16 characters 0..9,a..f)
}
... | [
"def",
"gen_uid",
"(",
"i",
")",
":",
"import",
"uuid",
"import",
"random",
"uid",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")",
"if",
"len",
"(",
"uid",
")",
"!=",
"32",
":",
"return",
"{",
"'return'",
":",
"1",
",",
"'erro... | 23.68 | 26.4 |
def command_start(self, daemonize=False):
'''
Start a server::
./manage.py flup:start [--daemonize]
'''
if daemonize:
safe_makedirs(self.logfile, self.pidfile)
flup_fastcgi(self.app, bind=self.bind, pidfile=self.pidfile,
logfile=self.... | [
"def",
"command_start",
"(",
"self",
",",
"daemonize",
"=",
"False",
")",
":",
"if",
"daemonize",
":",
"safe_makedirs",
"(",
"self",
".",
"logfile",
",",
"self",
".",
"pidfile",
")",
"flup_fastcgi",
"(",
"self",
".",
"app",
",",
"bind",
"=",
"self",
".... | 37.727273 | 21.909091 |
def clean_int(x) -> int:
"""
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
"""
try:
return int(x)
except ValueError:
raise forms.ValidationError(
"Cannot convert to integer: {}".format(repr(x))) | [
"def",
"clean_int",
"(",
"x",
")",
"->",
"int",
":",
"try",
":",
"return",
"int",
"(",
"x",
")",
"except",
"ValueError",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Cannot convert to integer: {}\"",
".",
"format",
"(",
"repr",
"(",
"x",
")",
"... | 27.2 | 12.2 |
def delete_changed(self, settings, key, user_data):
"""If the gconf var compat_delete be changed, this method
will be called and will change the binding configuration in
all terminals open.
"""
for i in self.guake.notebook_manager.iter_terminals():
i.set_delete_bindin... | [
"def",
"delete_changed",
"(",
"self",
",",
"settings",
",",
"key",
",",
"user_data",
")",
":",
"for",
"i",
"in",
"self",
".",
"guake",
".",
"notebook_manager",
".",
"iter_terminals",
"(",
")",
":",
"i",
".",
"set_delete_binding",
"(",
"self",
".",
"getEr... | 51.857143 | 16.142857 |
def bread(stream):
""" Decode a file or stream to an object.
"""
if hasattr(stream, "read"):
return bdecode(stream.read())
else:
handle = open(stream, "rb")
try:
return bdecode(handle.read())
finally:
handle.close() | [
"def",
"bread",
"(",
"stream",
")",
":",
"if",
"hasattr",
"(",
"stream",
",",
"\"read\"",
")",
":",
"return",
"bdecode",
"(",
"stream",
".",
"read",
"(",
")",
")",
"else",
":",
"handle",
"=",
"open",
"(",
"stream",
",",
"\"rb\"",
")",
"try",
":",
... | 25.181818 | 12.454545 |
def _doy_to_datetimeindex(doy, epoch_year=2014):
"""
Convert a day of year scalar or array to a pd.DatetimeIndex.
Parameters
----------
doy : numeric
Contains days of the year
Returns
-------
pd.DatetimeIndex
"""
doy = np.atleast_1d(doy).astype('float')
epoch = pd.T... | [
"def",
"_doy_to_datetimeindex",
"(",
"doy",
",",
"epoch_year",
"=",
"2014",
")",
":",
"doy",
"=",
"np",
".",
"atleast_1d",
"(",
"doy",
")",
".",
"astype",
"(",
"'float'",
")",
"epoch",
"=",
"pd",
".",
"Timestamp",
"(",
"'{}-12-31'",
".",
"format",
"(",... | 26.705882 | 18.941176 |
async def _restart_on_cancel(logger, agent):
""" Restarts an agent when it is cancelled """
while True:
try:
await agent.run()
except asyncio.CancelledError:
logger.exception("Restarting agent")
pass | [
"async",
"def",
"_restart_on_cancel",
"(",
"logger",
",",
"agent",
")",
":",
"while",
"True",
":",
"try",
":",
"await",
"agent",
".",
"run",
"(",
")",
"except",
"asyncio",
".",
"CancelledError",
":",
"logger",
".",
"exception",
"(",
"\"Restarting agent\"",
... | 31.5 | 12.75 |
def make_cache_key(*args, **kwargs):
"""
Used by cache to get a unique key per URL
"""
path = request.path
args = str(hash(frozenset(request.args.items())))
return (path + args).encode('ascii', 'ignore') | [
"def",
"make_cache_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"request",
".",
"path",
"args",
"=",
"str",
"(",
"hash",
"(",
"frozenset",
"(",
"request",
".",
"args",
".",
"items",
"(",
")",
")",
")",
")",
"return",
"(... | 31.571429 | 7 |
def encrypt(message, modN, e, blockSize):
"""given a string message, public keys and blockSize, encrypt using
RSA algorithms."""
numList = string2numList(message)
numBlocks = numList2blocks(numList, blockSize) # only one block
message = numBlocks[0]
# return [modExp(blocks, e, modN) for blocks ... | [
"def",
"encrypt",
"(",
"message",
",",
"modN",
",",
"e",
",",
"blockSize",
")",
":",
"numList",
"=",
"string2numList",
"(",
"message",
")",
"numBlocks",
"=",
"numList2blocks",
"(",
"numList",
",",
"blockSize",
")",
"# only one block",
"message",
"=",
"numBlo... | 45.25 | 9.125 |
def sync_labels(self, repo):
"""Creates a local map of github labels/milestones to asana tags."""
logging.info("syncing new github.com labels to tags")
# create label tag map
ltm = self.app.data.get("label-tag-map", {})
# loop over labels, if they don't have tags, make them
... | [
"def",
"sync_labels",
"(",
"self",
",",
"repo",
")",
":",
"logging",
".",
"info",
"(",
"\"syncing new github.com labels to tags\"",
")",
"# create label tag map",
"ltm",
"=",
"self",
".",
"app",
".",
"data",
".",
"get",
"(",
"\"label-tag-map\"",
",",
"{",
"}",... | 38.166667 | 20.888889 |
def abspath(path, **kwargs):
"""Return the absolute path of *path*"""
import os.path
return os.path.abspath(path, **kwargs) | [
"def",
"abspath",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"os",
".",
"path",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
",",
"*",
"*",
"kwargs",
")"
] | 33 | 9 |
def items (self):
"""Return list of items, not updating usage count."""
return [(key, value[1]) for key, value in super(LFUCache, self).items()] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"key",
",",
"value",
"[",
"1",
"]",
")",
"for",
"key",
",",
"value",
"in",
"super",
"(",
"LFUCache",
",",
"self",
")",
".",
"items",
"(",
")",
"]"
] | 52.666667 | 21 |
def close(self):
"""
Closes the popup widget and central widget.
"""
widget = self.centralWidget()
if widget and not widget.close():
return
super(XPopupWidget, self).close() | [
"def",
"close",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"centralWidget",
"(",
")",
"if",
"widget",
"and",
"not",
"widget",
".",
"close",
"(",
")",
":",
"return",
"super",
"(",
"XPopupWidget",
",",
"self",
")",
".",
"close",
"(",
")"
] | 27.333333 | 9.777778 |
def prepare_decoder(targets, hparams):
"""Prepare decoder for images."""
targets_shape = common_layers.shape_list(targets)
channels = hparams.num_channels
curr_infer_length = None
# during training, images are [batch, IMG_LEN, IMG_LEN, 3].
# At inference, they are [batch, curr_infer_length, 1, 1]
if hpar... | [
"def",
"prepare_decoder",
"(",
"targets",
",",
"hparams",
")",
":",
"targets_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"targets",
")",
"channels",
"=",
"hparams",
".",
"num_channels",
"curr_infer_length",
"=",
"None",
"# during training, images are [batch,... | 47.844828 | 17.344828 |
def list(self, name, platform='', genre=''):
""" The name argument is required for this method as per the API
server specification. This method also provides the platform and genre
optional arguments as filters.
"""
data_list = self.db.get_data(self.list_path, name=name,
... | [
"def",
"list",
"(",
"self",
",",
"name",
",",
"platform",
"=",
"''",
",",
"genre",
"=",
"''",
")",
":",
"data_list",
"=",
"self",
".",
"db",
".",
"get_data",
"(",
"self",
".",
"list_path",
",",
"name",
"=",
"name",
",",
"platform",
"=",
"platform",... | 51.7 | 11.8 |
def getPermutedTensors(W, kw, n, m2, noisePct):
"""
Generate m2 noisy versions of W. Noisy
version of W is generated by randomly permuting noisePct of the non-zero
components to other components.
:param W:
:param n:
:param m2:
:param noisePct:
:return:
"""
W2 = W.repeat(m2, 1)
nz = W[0].nonzer... | [
"def",
"getPermutedTensors",
"(",
"W",
",",
"kw",
",",
"n",
",",
"m2",
",",
"noisePct",
")",
":",
"W2",
"=",
"W",
".",
"repeat",
"(",
"m2",
",",
"1",
")",
"nz",
"=",
"W",
"[",
"0",
"]",
".",
"nonzero",
"(",
")",
"numberToZero",
"=",
"int",
"(... | 22.857143 | 19.333333 |
def get_full_year():
""" Returns percentages of peak load for all hours of the year.
@return:
Numpy array of doubles with length 8736.
"""
weekly = get_weekly()
daily = get_daily()
hourly_winter_wkdy, hourly_winter_wknd = get_winter_hourly()
hourly_summer_wkdy, hourly_summer_wknd = ... | [
"def",
"get_full_year",
"(",
")",
":",
"weekly",
"=",
"get_weekly",
"(",
")",
"daily",
"=",
"get_daily",
"(",
")",
"hourly_winter_wkdy",
",",
"hourly_winter_wknd",
"=",
"get_winter_hourly",
"(",
")",
"hourly_summer_wkdy",
",",
"hourly_summer_wknd",
"=",
"get_summe... | 36.625 | 18 |
def get_profile(self, component):
"""
Gets given Component profile.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.get_profile("core.tests_component_a")
<manager.components_mana... | [
"def",
"get_profile",
"(",
"self",
",",
"component",
")",
":",
"components",
"=",
"self",
".",
"filter_components",
"(",
"r\"^{0}$\"",
".",
"format",
"(",
"component",
")",
")",
"if",
"components",
"!=",
"[",
"]",
":",
"return",
"self",
".",
"__components"... | 32.47619 | 20.571429 |
def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501
"""Download dataset file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_download(owner_slug, ... | [
"def",
"datasets_download",
"(",
"self",
",",
"owner_slug",
",",
"dataset_slug",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return... | 47.636364 | 23.590909 |
def parse(readDataInstance, arrayType, arrayLength):
"""
Returns a new L{Array} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: The L{ReadData} object containing the array data.
@type arrayType: int
@param arrayType: The type of L{... | [
"def",
"parse",
"(",
"readDataInstance",
",",
"arrayType",
",",
"arrayLength",
")",
":",
"newArray",
"=",
"Array",
"(",
"arrayType",
")",
"dataLength",
"=",
"len",
"(",
"readDataInstance",
")",
"if",
"arrayType",
"is",
"TYPE_DWORD",
":",
"toRead",
"=",
"arra... | 36.653846 | 17.923077 |
def build_overviews(source_file, factors=None, minsize=256, external=False,
blocksize=256, interleave='pixel', compress='lzw',
resampling=Resampling.gauss, **kwargs):
"""Build overviews at one or more decimation factors for all
bands of the dataset.
Parameters
--... | [
"def",
"build_overviews",
"(",
"source_file",
",",
"factors",
"=",
"None",
",",
"minsize",
"=",
"256",
",",
"external",
"=",
"False",
",",
"blocksize",
"=",
"256",
",",
"interleave",
"=",
"'pixel'",
",",
"compress",
"=",
"'lzw'",
",",
"resampling",
"=",
... | 38.244898 | 19.44898 |
def size(self, destination):
"""
Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int}
"""
if not destination in... | [
"def",
"size",
"(",
"self",
",",
"destination",
")",
":",
"if",
"not",
"destination",
"in",
"self",
".",
"queue_metadata",
":",
"return",
"0",
"else",
":",
"return",
"len",
"(",
"self",
".",
"queue_metadata",
"[",
"destination",
"]",
"[",
"'frames'",
"]"... | 30.714286 | 18.285714 |
def _init_field(self, setting, field_class, name, code=None):
"""
Initialize a field whether it is built with a custom name for a
specific translation language or not.
"""
kwargs = {
"label": setting["label"] + ":",
"required": setting["type"] in (int, flo... | [
"def",
"_init_field",
"(",
"self",
",",
"setting",
",",
"field_class",
",",
"name",
",",
"code",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"\"label\"",
":",
"setting",
"[",
"\"label\"",
"]",
"+",
"\":\"",
",",
"\"required\"",
":",
"setting",
"[",
"\"t... | 43.714286 | 14.761905 |
def status_bar(self):
"""Top view bar status
"""
print("")
self.msg.template(78)
print("| Repository Status")
self.msg.template(78) | [
"def",
"status_bar",
"(",
"self",
")",
":",
"print",
"(",
"\"\"",
")",
"self",
".",
"msg",
".",
"template",
"(",
"78",
")",
"print",
"(",
"\"| Repository Status\"",
")",
"self",
".",
"msg",
".",
"template",
"(",
"78",
")"
] | 25.857143 | 9.714286 |
def show(i):
"""
Input: {
(data_uoa) - repo UOA
(reset) - if 'yes', reset repos
(stable) - take stable version (highly experimental)
(version) - checkout version (default - stable)
}
Output: {
return - return c... | [
"def",
"show",
"(",
"i",
")",
":",
"import",
"os",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"curdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"duoa",
"=",
"i",
".",
"get",
"(",
"'data_uoa'",
",",
"''",
")",
"reset",
"=",
"i",
".... | 28.02439 | 25.520325 |
def setUpClassDef(self, service):
'''use soapAction dict for WS-Action input, setup wsAction
dict for grabbing WS-Action output values.
'''
assert isinstance(service, WSDLTools.Service), \
'expecting WSDLTools.Service instance'
s = self._services[service.name].classd... | [
"def",
"setUpClassDef",
"(",
"self",
",",
"service",
")",
":",
"assert",
"isinstance",
"(",
"service",
",",
"WSDLTools",
".",
"Service",
")",
",",
"'expecting WSDLTools.Service instance'",
"s",
"=",
"self",
".",
"_services",
"[",
"service",
".",
"name",
"]",
... | 49.166667 | 21.833333 |
def construct_sign_and_send_raw_middleware(private_key_or_account):
"""Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.Loca... | [
"def",
"construct_sign_and_send_raw_middleware",
"(",
"private_key_or_account",
")",
":",
"accounts",
"=",
"gen_normalized_accounts",
"(",
"private_key_or_account",
")",
"def",
"sign_and_send_raw_middleware",
"(",
"make_request",
",",
"w3",
")",
":",
"format_and_fill_tx",
"... | 32.857143 | 19.285714 |
def allow_headers(self, domain, headers, secure=True):
"""
Allows ``domain`` to push data via the HTTP headers named in
``headers``.
As with ``allow_domain``, ``domain`` may be either a full
domain name or a wildcard. Again, use of wildcards is
discouraged for security r... | [
"def",
"allow_headers",
"(",
"self",
",",
"domain",
",",
"headers",
",",
"secure",
"=",
"True",
")",
":",
"if",
"self",
".",
"site_control",
"==",
"SITE_CONTROL_NONE",
":",
"raise",
"TypeError",
"(",
"METAPOLICY_ERROR",
".",
"format",
"(",
"\"allow headers fro... | 39.708333 | 22.625 |
def _PrintSessionsDetails(self, storage_reader):
"""Prints the details of the sessions.
Args:
storage_reader (BaseStore): storage.
"""
for session_number, session in enumerate(storage_reader.GetSessions()):
session_identifier = uuid.UUID(hex=session.identifier)
session_identifier = '{... | [
"def",
"_PrintSessionsDetails",
"(",
"self",
",",
"storage_reader",
")",
":",
"for",
"session_number",
",",
"session",
"in",
"enumerate",
"(",
"storage_reader",
".",
"GetSessions",
"(",
")",
")",
":",
"session_identifier",
"=",
"uuid",
".",
"UUID",
"(",
"hex",... | 42.104478 | 21.58209 |
def ceil_nearest(x, dx=1):
"""
ceil a number to within a given rounding accuracy
"""
precision = get_sig_digits(dx)
return round(math.ceil(float(x) / dx) * dx, precision) | [
"def",
"ceil_nearest",
"(",
"x",
",",
"dx",
"=",
"1",
")",
":",
"precision",
"=",
"get_sig_digits",
"(",
"dx",
")",
"return",
"round",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"x",
")",
"/",
"dx",
")",
"*",
"dx",
",",
"precision",
")"
] | 30.833333 | 8.5 |
def name_for_number(numobj, lang, script=None, region=None):
"""Returns a carrier name for the given PhoneNumber object, in the
language provided.
The carrier name is the one the number was originally allocated to,
however if the country supports mobile number portability the number might
not belon... | [
"def",
"name_for_number",
"(",
"numobj",
",",
"lang",
",",
"script",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"ntype",
"=",
"number_type",
"(",
"numobj",
")",
"if",
"_is_mobile",
"(",
"ntype",
")",
":",
"return",
"name_for_valid_number",
"(",
"... | 46.814815 | 25.740741 |
def _data(self, copy=False):
"""
Get all data associated with the container as key value pairs.
"""
data = {}
for key, obj in self.__dict__.items():
if isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)):
if copy:
... | [
"def",
"_data",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"obj",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"pd",
".",
"Series",
",",
... | 34.916667 | 15.75 |
def start(self) -> None:
"""Starts the timer."""
# Looking up the IOLoop here allows to first instantiate the
# PeriodicCallback in another thread, then start it using
# IOLoop.add_callback().
self.io_loop = IOLoop.current()
self._running = True
self._next_timeout... | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"# Looking up the IOLoop here allows to first instantiate the",
"# PeriodicCallback in another thread, then start it using",
"# IOLoop.add_callback().",
"self",
".",
"io_loop",
"=",
"IOLoop",
".",
"current",
"(",
")",
"self... | 40.444444 | 12.111111 |
def almost_eq(a, b, bits=32, tol=1, ignore_type=True, pad=0.):
"""
Almost equal, based on the amount of floating point significand bits.
Alternative to "a == b" for float numbers and iterables with float numbers,
and tests for sequence contents (i.e., an elementwise a == b, that also
works with generators, n... | [
"def",
"almost_eq",
"(",
"a",
",",
"b",
",",
"bits",
"=",
"32",
",",
"tol",
"=",
"1",
",",
"ignore_type",
"=",
"True",
",",
"pad",
"=",
"0.",
")",
":",
"if",
"not",
"(",
"ignore_type",
"or",
"type",
"(",
"a",
")",
"==",
"type",
"(",
"b",
")",... | 39.787879 | 20.454545 |
def predict_proba(self, X, lengths=None):
"""Compute the posterior probability for each state in the model.
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequences, ), optional
Lengths of t... | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
",",
"lengths",
"=",
"None",
")",
":",
"_",
",",
"posteriors",
"=",
"self",
".",
"score_samples",
"(",
"X",
",",
"lengths",
")",
"return",
"posteriors"
] | 38.117647 | 19.647059 |
def get_file_size(filename):
"""
Get size of all files in gigabytes (Gb).
:param str | collections.Iterable[str] filename: A space-separated
string or list of space-separated strings of absolute file paths.
:return float: size of file(s), in gigabytes.
"""
if filename is None:
r... | [
"def",
"get_file_size",
"(",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
":",
"return",
"float",
"(",
"0",
")",
"if",
"type",
"(",
"filename",
")",
"is",
"list",
":",
"return",
"float",
"(",
"sum",
"(",
"[",
"get_file_size",
"(",
"x",
")",
... | 33.35 | 18.35 |
def reciprocal(x, a, b, n):
"""
reciprocal function to the power n to fit convergence data
"""
if n < 1:
n = 1
elif n > 5:
n = 5
if isinstance(x, list):
y_l = []
for x_v in x:
y_l.append(a + b / x_v ** n)
y = np.array(y_l)
else:
y =... | [
"def",
"reciprocal",
"(",
"x",
",",
"a",
",",
"b",
",",
"n",
")",
":",
"if",
"n",
"<",
"1",
":",
"n",
"=",
"1",
"elif",
"n",
">",
"5",
":",
"n",
"=",
"5",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"y_l",
"=",
"[",
"]",
"for",... | 20.8125 | 17.8125 |
def select_from_cluster(idx_key, idx_list, measure_vect):
""" Select a single source from a cluster and make it the new cluster key
Parameters
----------
idx_key : int
index of the current key for a cluster
idx_list : [int,...]
list of the other source indices in the cluster
measu... | [
"def",
"select_from_cluster",
"(",
"idx_key",
",",
"idx_list",
",",
"measure_vect",
")",
":",
"best_idx",
"=",
"idx_key",
"best_measure",
"=",
"measure_vect",
"[",
"idx_key",
"]",
"out_list",
"=",
"[",
"idx_key",
"]",
"+",
"idx_list",
"for",
"idx",
",",
"mea... | 32.962963 | 17.481481 |
def get_map(name, map_type, number, reverse=False):
"""
Return a `BrewerMap` representation of the specified color map.
Parameters
----------
name : str
Name of color map. Use `print_maps` to see available color maps.
map_type : {'Sequential', 'Diverging', 'Qualitative'}
Select ... | [
"def",
"get_map",
"(",
"name",
",",
"map_type",
",",
"number",
",",
"reverse",
"=",
"False",
")",
":",
"number",
"=",
"str",
"(",
"number",
")",
"map_type",
"=",
"map_type",
".",
"lower",
"(",
")",
".",
"capitalize",
"(",
")",
"# check for valid type",
... | 34.086207 | 20.189655 |
def numeric(_, n):
"""
NBASE = 1000
ndigits = total number of base-NBASE digits
weight = base-NBASE weight of first digit
sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan
dscale = decimal digits after decimal place
"""
try:
nt = n.as_tuple()
except AttributeError:... | [
"def",
"numeric",
"(",
"_",
",",
"n",
")",
":",
"try",
":",
"nt",
"=",
"n",
".",
"as_tuple",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"'numeric field requires Decimal value (got %r)'",
"%",
"n",
")",
"digits",
"=",
"[",
"]",
... | 31.166667 | 15.666667 |
def get(self, repi, mag):
"""
:param repi: an array of epicentral distances in the range self.repi
:param mag: a magnitude in the range self.mags
:returns: an array of equivalent distances
"""
mag_idx = numpy.abs(mag - self.mags).argmin()
dists = []
for di... | [
"def",
"get",
"(",
"self",
",",
"repi",
",",
"mag",
")",
":",
"mag_idx",
"=",
"numpy",
".",
"abs",
"(",
"mag",
"-",
"self",
".",
"mags",
")",
".",
"argmin",
"(",
")",
"dists",
"=",
"[",
"]",
"for",
"dist",
"in",
"repi",
":",
"repi_idx",
"=",
... | 39.083333 | 13.75 |
def _get_principal(self, app: FlaskUnchained) -> Principal:
"""
Get an initialized instance of Flask Principal's.
:class:~flask_principal.Principal`.
"""
principal = Principal(app, use_sessions=False)
principal.identity_loader(self._identity_loader)
return princip... | [
"def",
"_get_principal",
"(",
"self",
",",
"app",
":",
"FlaskUnchained",
")",
"->",
"Principal",
":",
"principal",
"=",
"Principal",
"(",
"app",
",",
"use_sessions",
"=",
"False",
")",
"principal",
".",
"identity_loader",
"(",
"self",
".",
"_identity_loader",
... | 39.375 | 10.625 |
def create(self, body):
"""Creates a new connection.
Args:
body (dict): Attributes used to create the connection. Mandatory
attributes are: 'name' and 'strategy'.
See: https://auth0.com/docs/api/management/v2#!/Connections/post_connections
"""
... | [
"def",
"create",
"(",
"self",
",",
"body",
")",
":",
"return",
"self",
".",
"client",
".",
"post",
"(",
"self",
".",
"_url",
"(",
")",
",",
"data",
"=",
"body",
")"
] | 36 | 24.1 |
def find_eggs_in_zip(importer, path_item, only=False):
"""
Find eggs in zip files; possibly multiple nested eggs.
"""
if importer.archive.endswith('.whl'):
# wheels are not supported with this finder
# they don't have PKG-INFO metadata, and won't ever contain eggs
return
meta... | [
"def",
"find_eggs_in_zip",
"(",
"importer",
",",
"path_item",
",",
"only",
"=",
"False",
")",
":",
"if",
"importer",
".",
"archive",
".",
"endswith",
"(",
"'.whl'",
")",
":",
"# wheels are not supported with this finder",
"# they don't have PKG-INFO metadata, and won't ... | 42.6 | 14.92 |
def parse_event(data, attendees=None, photos=None):
"""
Parse a ``MeetupEvent`` from the given response data.
Returns
-------
A ``pythonkc_meetups.types.MeetupEvent``.
"""
return MeetupEvent(
id=data.get('id', None),
name=data.get('name', None),
description=data.get... | [
"def",
"parse_event",
"(",
"data",
",",
"attendees",
"=",
"None",
",",
"photos",
"=",
"None",
")",
":",
"return",
"MeetupEvent",
"(",
"id",
"=",
"data",
".",
"get",
"(",
"'id'",
",",
"None",
")",
",",
"name",
"=",
"data",
".",
"get",
"(",
"'name'",... | 33.791667 | 15.958333 |
def disconnect(self, callback):
"""
Disconnects a callback from this signal.
:param callback: The callback to disconnect.
:param weak: A flag that must have the same value than the one
specified during the call to `connect`.
.. warning::
If the callback ... | [
"def",
"disconnect",
"(",
"self",
",",
"callback",
")",
":",
"try",
":",
"self",
".",
"_callbacks",
".",
"remove",
"(",
"callback",
")",
"except",
"ValueError",
":",
"self",
".",
"_callbacks",
".",
"remove",
"(",
"ref",
"(",
"callback",
")",
")"
] | 32.894737 | 18.473684 |
def wrap(cls, socket, hostname, session=None):
"""
Takes an existing socket and adds TLS
:param socket:
A socket.socket object to wrap with TLS
:param hostname:
A unicode string of the hostname or IP the socket is connected to
:param session:
... | [
"def",
"wrap",
"(",
"cls",
",",
"socket",
",",
"hostname",
",",
"session",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"socket",
",",
"socket_",
".",
"socket",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n soc... | 32.36 | 20.88 |
def get_axis(self, undefined=np.zeros(3)):
"""Get the axis or vector about which the quaternion rotation occurs
For a null rotation (a purely real quaternion), the rotation angle will
always be `0`, but the rotation axis is undefined.
It is by default assumed to be `[0, 0, 0]`.
... | [
"def",
"get_axis",
"(",
"self",
",",
"undefined",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
")",
":",
"tolerance",
"=",
"1e-17",
"self",
".",
"_normalise",
"(",
")",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"vector",
")",
"i... | 46.111111 | 29.555556 |
def get_vtt_files(inputfile):
"""Return a list of vtt files."""
vtts = []
for f in inputfile:
filename = f.split('.')
filename = '.'.join(filename[0:-1])
vtt = glob(filename + '*.vtt')
if len(vtt) > 0:
vtts.append({'vtt': vtt[0], 'video': f})
if len(vtts) ==... | [
"def",
"get_vtt_files",
"(",
"inputfile",
")",
":",
"vtts",
"=",
"[",
"]",
"for",
"f",
"in",
"inputfile",
":",
"filename",
"=",
"f",
".",
"split",
"(",
"'.'",
")",
"filename",
"=",
"'.'",
".",
"join",
"(",
"filename",
"[",
"0",
":",
"-",
"1",
"]"... | 24.5 | 17.8125 |
def poisson(x, a, b, c, d=0):
'''
Poisson function
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation
d -> offset
'''
from scipy.misc import factorial #save startup time
lamb = 1
X = (x/(2*c)).astype(int)
return a * ((... | [
"def",
"poisson",
"(",
"x",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
"=",
"0",
")",
":",
"from",
"scipy",
".",
"misc",
"import",
"factorial",
"#save startup time\r",
"lamb",
"=",
"1",
"X",
"=",
"(",
"x",
"/",
"(",
"2",
"*",
"c",
")",
")",
".",... | 29.333333 | 17.333333 |
def pad(self, esp):
"""
Add the correct amount of padding so that the data to encrypt is
exactly a multiple of the algorithm's block size.
Also, make sure that the total ESP packet length is a multiple of 4
bytes.
@param esp: an unencrypted _ESPPlain packet
... | [
"def",
"pad",
"(",
"self",
",",
"esp",
")",
":",
"# 2 extra bytes for padlen and nh",
"data_len",
"=",
"len",
"(",
"esp",
".",
"data",
")",
"+",
"2",
"# according to the RFC4303, section 2.4. Padding (for Encryption)",
"# the size of the ESP payload must be a multiple of 32 b... | 35.205882 | 23.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.