text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def delete_episode(db, aid, episode):
"""Delete an episode."""
db.cursor().execute(
'DELETE FROM episode WHERE aid=:aid AND type=:type AND number=:number',
{
'aid': aid,
'type': episode.type,
'number': episode.number,
}) | [
"def",
"delete_episode",
"(",
"db",
",",
"aid",
",",
"episode",
")",
":",
"db",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"'DELETE FROM episode WHERE aid=:aid AND type=:type AND number=:number'",
",",
"{",
"'aid'",
":",
"aid",
",",
"'type'",
":",
"episode",
... | 31.111111 | 16.222222 |
def describe_object(self, obj):
"""
Get the description of an object from Salesforce.
This description is the object's schema and
some extra metadata that Salesforce stores for each object.
:param obj: The name of the Salesforce object that we are getting a description of.
... | [
"def",
"describe_object",
"(",
"self",
",",
"obj",
")",
":",
"conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"return",
"conn",
".",
"__getattr__",
"(",
"obj",
")",
".",
"describe",
"(",
")"
] | 35.428571 | 19.142857 |
def echo_to_output_stream(self, email_messages):
""" Write all messages to the stream in a thread-safe way. """
if not email_messages:
return
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
... | [
"def",
"echo_to_output_stream",
"(",
"self",
",",
"email_messages",
")",
":",
"if",
"not",
"email_messages",
":",
"return",
"with",
"self",
".",
"_lock",
":",
"try",
":",
"stream_created",
"=",
"self",
".",
"open",
"(",
")",
"for",
"message",
"in",
"email_... | 38.266667 | 11.2 |
def _read_section(self):
"""Read and return an entire section"""
lines = [self._last[self._last.find(":")+1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline()
... | [
"def",
"_read_section",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"self",
".",
"_last",
"[",
"self",
".",
"_last",
".",
"find",
"(",
"\":\"",
")",
"+",
"1",
":",
"]",
"]",
"self",
".",
"_last",
"=",
"self",
".",
"_f",
".",
"readline",
"(",
")",... | 41.5 | 10.875 |
def _shorten_version(ver, num_components=2):
"""
If ``ver`` is a dot-separated string with at least (num_components +1)
components, return only the first two. Else return the original string.
:param ver: version string
:type ver: str
:return: shortened (major, minor) ver... | [
"def",
"_shorten_version",
"(",
"ver",
",",
"num_components",
"=",
"2",
")",
":",
"parts",
"=",
"ver",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"<=",
"num_components",
":",
"return",
"ver",
"return",
"'.'",
".",
"join",
"(",
"pa... | 34.714286 | 15 |
def send_voice(self, *args, **kwargs):
"""See :func:`send_voice`"""
return send_voice(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"send_voice",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"send_voice",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | 49 | 11.666667 |
def _check_bullets(lines, **kwargs):
"""Check that the bullet point list is well formatted.
Each bullet point shall have one space before and after it. The bullet
character is the "*" and there is no space before it but one after it
meaning the next line are starting with two blanks spaces to respect t... | [
"def",
"_check_bullets",
"(",
"lines",
",",
"*",
"*",
"kwargs",
")",
":",
"max_length",
"=",
"kwargs",
".",
"get",
"(",
"\"max_length\"",
",",
"72",
")",
"labels",
"=",
"{",
"l",
"for",
"l",
",",
"_",
"in",
"kwargs",
".",
"get",
"(",
"\"commit_msg_la... | 35.209677 | 18.419355 |
def t_quotedvar_DOLLAR_OPEN_CURLY_BRACES(t):
r'\$\{'
if re.match(r'[A-Za-z_]', peek(t.lexer)):
t.lexer.begin('varname')
else:
t.lexer.begin('php')
return t | [
"def",
"t_quotedvar_DOLLAR_OPEN_CURLY_BRACES",
"(",
"t",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'[A-Za-z_]'",
",",
"peek",
"(",
"t",
".",
"lexer",
")",
")",
":",
"t",
".",
"lexer",
".",
"begin",
"(",
"'varname'",
")",
"else",
":",
"t",
".",
"lexe... | 25.857143 | 16.714286 |
def is_valid(self):
"""
Is every geometry connected to the root node.
Returns
-----------
is_valid : bool
Does every geometry have a transform
"""
if len(self.geometry) == 0:
return True
try:
referenced = {self.graph[i][... | [
"def",
"is_valid",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"geometry",
")",
"==",
"0",
":",
"return",
"True",
"try",
":",
"referenced",
"=",
"{",
"self",
".",
"graph",
"[",
"i",
"]",
"[",
"1",
"]",
"for",
"i",
"in",
"self",
".",
... | 25.956522 | 18.565217 |
def set_redraw_lag(self, lag_sec):
"""Set lag time for redrawing the canvas.
Parameters
----------
lag_sec : float
Number of seconds to wait.
"""
self.defer_redraw = (lag_sec > 0.0)
if self.defer_redraw:
self.defer_lagtime = lag_sec | [
"def",
"set_redraw_lag",
"(",
"self",
",",
"lag_sec",
")",
":",
"self",
".",
"defer_redraw",
"=",
"(",
"lag_sec",
">",
"0.0",
")",
"if",
"self",
".",
"defer_redraw",
":",
"self",
".",
"defer_lagtime",
"=",
"lag_sec"
] | 25.25 | 13.583333 |
def init(filename, order=3, tokenizer=None):
"""Initialize a brain. This brain's file must not already exist.
Keyword arguments:
order -- Order of the forward/reverse Markov chains (integer)
tokenizer -- One of Cobe, MegaHAL (default Cobe). See documentation
for cobe.tokenizers for details. (strin... | [
"def",
"init",
"(",
"filename",
",",
"order",
"=",
"3",
",",
"tokenizer",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Initializing a cobe brain: %s\"",
"%",
"filename",
")",
"if",
"tokenizer",
"is",
"None",
":",
"tokenizer",
"=",
"\"Cobe\"",
"if",
... | 36.25 | 19.1 |
def genl_ctrl_resolve(sk, name):
"""Resolve Generic Netlink family name to numeric identifier.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L429
Resolves the Generic Netlink family name to the corresponding numeric family identifier. This function queries the
kernel directly, use ... | [
"def",
"genl_ctrl_resolve",
"(",
"sk",
",",
"name",
")",
":",
"family",
"=",
"genl_ctrl_probe_by_name",
"(",
"sk",
",",
"name",
")",
"if",
"family",
"is",
"None",
":",
"return",
"-",
"NLE_OBJ_NOTFOUND",
"return",
"int",
"(",
"genl_family_get_id",
"(",
"famil... | 36.65 | 24.75 |
def doppler_width(transition, Temperature):
r"""Return the Doppler width of a transition at a given temperature
(in angular frequency).
The usual Doppler FWHM of the rubidium D2 line (in MHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2)
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> t = Tr... | [
"def",
"doppler_width",
"(",
"transition",
",",
"Temperature",
")",
":",
"atom",
"=",
"Atom",
"(",
"transition",
".",
"e1",
".",
"element",
",",
"transition",
".",
"e1",
".",
"isotope",
")",
"m",
"=",
"atom",
".",
"mass",
"omega",
"=",
"transition",
".... | 33.888889 | 17 |
def set_trace(frame=None, skip=0, server=None, port=None):
"""Set trace on current line, or on given frame"""
frame = frame or sys._getframe().f_back
for i in range(skip):
if not frame.f_back:
break
frame = frame.f_back
wdb = Wdb.get(server=server, port=port)
wdb.set_trac... | [
"def",
"set_trace",
"(",
"frame",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"frame",
"=",
"frame",
"or",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
"for",
"i",
"in",
"range",
"(",
... | 33.4 | 12.8 |
def use_project(self, project_id):
"""Creates an instance of [ProjectClient](#projectclient),
providing session authentication.
Parameters:
* `project_id` - project identifier.
Returns:
Instance of [ProjectClient](#projectclient) with
session authentication.
... | [
"def",
"use_project",
"(",
"self",
",",
"project_id",
")",
":",
"return",
"ProjectClient",
"(",
"base_uri",
"=",
"get_base_uri",
"(",
"project",
"=",
"project_id",
",",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"secure... | 26.756757 | 17.864865 |
def doc(func):
"""
Find the message shown when someone calls the help command
Parameters
----------
func : function
the function
Returns
-------
str
The help message for this command
"""
stripped_chars = " \t"
if hasattr(func, '__doc__'):
docstr... | [
"def",
"doc",
"(",
"func",
")",
":",
"stripped_chars",
"=",
"\" \\t\"",
"if",
"hasattr",
"(",
"func",
",",
"'__doc__'",
")",
":",
"docstring",
"=",
"func",
".",
"__doc__",
".",
"lstrip",
"(",
"\" \\n\\t\"",
")",
"if",
"\"\\n\"",
"in",
"docstring",
":",
... | 21.8 | 20.44 |
def retrieve_config_file(self):
"""
Retrieve config file
"""
try:
if self.args["configfile"]:
return self.args["configfile"]
except KeyError:
pass
return os.path.expanduser('~/.config/greg/greg.conf') | [
"def",
"retrieve_config_file",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"args",
"[",
"\"configfile\"",
"]",
":",
"return",
"self",
".",
"args",
"[",
"\"configfile\"",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"os",
".",
"path",
".",
... | 27.9 | 11.7 |
def is_gvcf_file(in_file):
"""Check if an input file is raw gVCF
"""
to_check = 100
n = 0
with utils.open_gzipsafe(in_file) as in_handle:
for line in in_handle:
if not line.startswith("##"):
if n > to_check:
break
n += 1
... | [
"def",
"is_gvcf_file",
"(",
"in_file",
")",
":",
"to_check",
"=",
"100",
"n",
"=",
"0",
"with",
"utils",
".",
"open_gzipsafe",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"if",
"not",
"line",
".",
"startswith",
"... | 32.458333 | 11.791667 |
def notify_slaves(self):
"""Checks to see if slaves should be notified, and notifies them if needed"""
if self.disable_slave_notify is not None:
LOGGER.debug('Slave notifications disabled')
return False
if self.zone_data()['kind'] == 'Master':
response_code =... | [
"def",
"notify_slaves",
"(",
"self",
")",
":",
"if",
"self",
".",
"disable_slave_notify",
"is",
"not",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'Slave notifications disabled'",
")",
"return",
"False",
"if",
"self",
".",
"zone_data",
"(",
")",
"[",
"'kind'"... | 45.333333 | 20.466667 |
def _add_logical_operator(self, operator):
"""Adds a logical operator in query
:param operator: logical operator (str)
:raise:
- QueryExpressionError: if a expression hasn't been set
"""
if not self.c_oper:
raise QueryExpressionError("Logical operators m... | [
"def",
"_add_logical_operator",
"(",
"self",
",",
"operator",
")",
":",
"if",
"not",
"self",
".",
"c_oper",
":",
"raise",
"QueryExpressionError",
"(",
"\"Logical operators must be preceded by an expression\"",
")",
"self",
".",
"current_field",
"=",
"None",
"self",
... | 30.882353 | 21.117647 |
def schema_create(conn):
"""Create the index for storing profiles.
This is idempotent; it can be called every time a database is opened to
make sure it's ready to use and up-to-date.
:param conn: A connection to an SQLite3 database.
"""
conn.execute(dedent("""\
CREATE TABLE IF NOT EXISTS p... | [
"def",
"schema_create",
"(",
"conn",
")",
":",
"conn",
".",
"execute",
"(",
"dedent",
"(",
"\"\"\"\\\n CREATE TABLE IF NOT EXISTS profiles\n (id INTEGER PRIMARY KEY,\n name TEXT NOT NULL UNIQUE,\n data BLOB NOT NULL,\n selected BOOLEAN NOT NULL DEFAULT FALSE)\n \... | 42 | 15.407407 |
def lastpayout(delegate_address, blacklist=None):
'''
Assumes that all send transactions from a delegate are payouts.
Use blacklist to remove rewardwallet and other transactions if the
address is not a voter. blacklist can contain both addresses and transactionIds'''
if blacklist... | [
"def",
"lastpayout",
"(",
"delegate_address",
",",
"blacklist",
"=",
"None",
")",
":",
"if",
"blacklist",
"and",
"len",
"(",
"blacklist",
")",
">",
"1",
":",
"command_blacklist",
"=",
"'NOT IN '",
"+",
"str",
"(",
"tuple",
"(",
"blacklist",
")",
")",
"el... | 42.157895 | 19.815789 |
def present(name,
protocol=None,
service_address=None,
scheduler='wlc',
):
'''
Ensure that the named service is present.
name
The LVS service name
protocol
The service protocol
service_address
The LVS service address
sche... | [
"def",
"present",
"(",
"name",
",",
"protocol",
"=",
"None",
",",
"service_address",
"=",
"None",
",",
"scheduler",
"=",
"'wlc'",
",",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
... | 37.558442 | 24.285714 |
def version_cmp(ver_a, ver_b):
"""
Compares two version strings in the dotted-numeric-label format.
Returns -1 if a < b, 0 if a == b, and +1 if a > b.
Inputs may include a prefix string that matches '^\w+[_-]', but
both strings must start with the same prefix. If present, it
is ignored for pu... | [
"def",
"version_cmp",
"(",
"ver_a",
",",
"ver_b",
")",
":",
"if",
"ver_a",
"is",
"None",
"and",
"ver_b",
"is",
"None",
":",
"return",
"0",
"if",
"ver_a",
"is",
"None",
":",
"return",
"-",
"1",
"elif",
"ver_b",
"is",
"None",
":",
"return",
"1",
"try... | 29.044776 | 20.477612 |
def pack_small_tensors(tower_grads, max_bytes=0):
"""Concatenate gradients together more intelligently.
Does binpacking
Args:
tower_grads: List of lists of (gradient, variable) tuples.
max_bytes: Int giving max number of bytes in a tensor that
may be considered small.
"""
assert max_bytes >... | [
"def",
"pack_small_tensors",
"(",
"tower_grads",
",",
"max_bytes",
"=",
"0",
")",
":",
"assert",
"max_bytes",
">=",
"0",
"orig_grads",
"=",
"[",
"g",
"for",
"g",
",",
"_",
"in",
"tower_grads",
"[",
"0",
"]",
"]",
"# Check to make sure sizes are accurate; not e... | 37.078125 | 16.828125 |
def interp_head_addr(self):
"""Returns PtrTo(PtrTo(PyInterpreterState)) value"""
if self._interp_head_addr is not None:
return self._interp_head_addr
try:
interp_head_addr = self.get_interp_head_addr_through_symbol()
except SymbolNotFound:
logger.debug... | [
"def",
"interp_head_addr",
"(",
"self",
")",
":",
"if",
"self",
".",
"_interp_head_addr",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_interp_head_addr",
"try",
":",
"interp_head_addr",
"=",
"self",
".",
"get_interp_head_addr_through_symbol",
"(",
")",
"ex... | 45.166667 | 16.5 |
def param_id(self, param, i):
"""Parse a node name in parameter list"""
param.pair = (self.value(i), parsing.Node)
return True | [
"def",
"param_id",
"(",
"self",
",",
"param",
",",
"i",
")",
":",
"param",
".",
"pair",
"=",
"(",
"self",
".",
"value",
"(",
"i",
")",
",",
"parsing",
".",
"Node",
")",
"return",
"True"
] | 33.75 | 10.5 |
def create(self, username, password, tags=''):
"""Create User.
:param str username: Username
:param str password: Password
:param str tags: Comma-separate list of tags (e.g. monitoring)
:rtype: None
"""
user_payload = json.dumps({
'password': passwor... | [
"def",
"create",
"(",
"self",
",",
"username",
",",
"password",
",",
"tags",
"=",
"''",
")",
":",
"user_payload",
"=",
"json",
".",
"dumps",
"(",
"{",
"'password'",
":",
"password",
",",
"'tags'",
":",
"tags",
"}",
")",
"return",
"self",
".",
"http_c... | 30.6 | 15.533333 |
def _process_current(self, handle, op, dest_path=None, dest_name=None):
"""Process current member with 'op' operation."""
unrarlib.RARProcessFileW(handle, op, dest_path, dest_name) | [
"def",
"_process_current",
"(",
"self",
",",
"handle",
",",
"op",
",",
"dest_path",
"=",
"None",
",",
"dest_name",
"=",
"None",
")",
":",
"unrarlib",
".",
"RARProcessFileW",
"(",
"handle",
",",
"op",
",",
"dest_path",
",",
"dest_name",
")"
] | 64.666667 | 19 |
def margin(file_, geometry_string):
"""
Returns the calculated margin for an image and geometry
"""
if not file_ or (sorl_settings.THUMBNAIL_DUMMY or isinstance(file_, DummyImageFile)):
return 'auto'
margin = [0, 0, 0, 0]
image_file = default.kvstore.get_or_set(ImageFile(file_))
... | [
"def",
"margin",
"(",
"file_",
",",
"geometry_string",
")",
":",
"if",
"not",
"file_",
"or",
"(",
"sorl_settings",
".",
"THUMBNAIL_DUMMY",
"or",
"isinstance",
"(",
"file_",
",",
"DummyImageFile",
")",
")",
":",
"return",
"'auto'",
"margin",
"=",
"[",
"0",
... | 22.25 | 23.821429 |
def horizontal_angle(C, P):
"""Return the angle to the horizontal for the connection from C to P.
This uses the arcus sine function and resolves its inherent ambiguity by
looking up in which quadrant vector S = P - C is located.
"""
S = Point(P - C).unit # unit ... | [
"def",
"horizontal_angle",
"(",
"C",
",",
"P",
")",
":",
"S",
"=",
"Point",
"(",
"P",
"-",
"C",
")",
".",
"unit",
"# unit vector 'C' -> 'P'",
"alfa",
"=",
"math",
".",
"asin",
"(",
"abs",
"(",
"S",
".",
"y",
")",
")",
"# absolute angle from horizontal"... | 49.166667 | 19.277778 |
def changed(self, selection='all'):
'''
Returns the list of changed values.
The key is added to each item.
selection
Specifies the desired changes.
Supported values are
``all`` - all changed items are included in the output
``inter... | [
"def",
"changed",
"(",
"self",
",",
"selection",
"=",
"'all'",
")",
":",
"changed",
"=",
"[",
"]",
"if",
"selection",
"==",
"'all'",
":",
"for",
"recursive_item",
"in",
"self",
".",
"_get_recursive_difference",
"(",
"type",
"=",
"'all'",
")",
":",
"# We ... | 47.194444 | 22.527778 |
def make_gtf_url(ensembl_release, species, server=ENSEMBL_FTP_SERVER):
"""
Returns a URL and a filename, which can be joined together.
"""
ensembl_release, species, _ = \
normalize_release_properties(ensembl_release, species)
subdir = _species_subdir(
ensembl_release,
species... | [
"def",
"make_gtf_url",
"(",
"ensembl_release",
",",
"species",
",",
"server",
"=",
"ENSEMBL_FTP_SERVER",
")",
":",
"ensembl_release",
",",
"species",
",",
"_",
"=",
"normalize_release_properties",
"(",
"ensembl_release",
",",
"species",
")",
"subdir",
"=",
"_speci... | 34.5625 | 12.3125 |
async def stop(self, **kwargs):
"""Stop pairing server and unpublish service."""
_LOGGER.debug('Shutting down pairing server')
if self._web_server is not None:
await self._web_server.shutdown()
self._server.close()
if self._server is not None:
await s... | [
"async",
"def",
"stop",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Shutting down pairing server'",
")",
"if",
"self",
".",
"_web_server",
"is",
"not",
"None",
":",
"await",
"self",
".",
"_web_server",
".",
"shutdown",
... | 37.444444 | 9.222222 |
def add_members(self, rtcs):
'''Add other RT Components to this composite component as members.
This component must be a composite component.
'''
if not self.is_composite:
raise exceptions.NotCompositeError(self.name)
for rtc in rtcs:
if self.is_member(r... | [
"def",
"add_members",
"(",
"self",
",",
"rtcs",
")",
":",
"if",
"not",
"self",
".",
"is_composite",
":",
"raise",
"exceptions",
".",
"NotCompositeError",
"(",
"self",
".",
"name",
")",
"for",
"rtc",
"in",
"rtcs",
":",
"if",
"self",
".",
"is_member",
"(... | 37.666667 | 19.933333 |
def _invalid_docstring_quote(self, quote, row, col=None):
"""Add a message for an invalid docstring quote.
Args:
quote: The quote characters that were found.
row: The row number the quote characters were found on.
col: The column the quote characters were found on.
... | [
"def",
"_invalid_docstring_quote",
"(",
"self",
",",
"quote",
",",
"row",
",",
"col",
"=",
"None",
")",
":",
"self",
".",
"add_message",
"(",
"'invalid-docstring-quote'",
",",
"line",
"=",
"row",
",",
"args",
"=",
"(",
"quote",
",",
"TRIPLE_QUOTE_OPTS",
".... | 37.642857 | 18.571429 |
def volume_attach(name, server_name, device='/dev/xvdb', **kwargs):
'''
Attach block volume
'''
conn = get_conn()
return conn.volume_attach(
name,
server_name,
device,
timeout=300
) | [
"def",
"volume_attach",
"(",
"name",
",",
"server_name",
",",
"device",
"=",
"'/dev/xvdb'",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"get_conn",
"(",
")",
"return",
"conn",
".",
"volume_attach",
"(",
"name",
",",
"server_name",
",",
"device",
",",... | 20.636364 | 24.272727 |
def getAppExt(self, loops=float('inf')):
""" getAppExt(loops=float('inf'))
Application extension. This part specifies the amount of loops.
If loops is 0 or inf, it goes on infinitely.
"""
if loops == 0 or loops == float('inf'):
loops = 2 ** 16 - 1
bb = b""
... | [
"def",
"getAppExt",
"(",
"self",
",",
"loops",
"=",
"float",
"(",
"'inf'",
")",
")",
":",
"if",
"loops",
"==",
"0",
"or",
"loops",
"==",
"float",
"(",
"'inf'",
")",
":",
"loops",
"=",
"2",
"**",
"16",
"-",
"1",
"bb",
"=",
"b\"\"",
"if",
"loops"... | 32.666667 | 17.555556 |
def _fit_spatial(noise,
noise_temporal,
mask,
template,
spatial_sd,
temporal_sd,
noise_dict,
fit_thresh,
fit_delta,
iterations,
):
"""
Fit... | [
"def",
"_fit_spatial",
"(",
"noise",
",",
"noise_temporal",
",",
"mask",
",",
"template",
",",
"spatial_sd",
",",
"temporal_sd",
",",
"noise_dict",
",",
"fit_thresh",
",",
"fit_delta",
",",
"iterations",
",",
")",
":",
"# Pull out information that is needed",
"dim... | 35.576923 | 22.653846 |
def get_value_prob(self, attr_name, value):
"""
Returns the value probability of the given attribute at this node.
"""
if attr_name not in self._attr_value_count_totals:
return
n = self._attr_value_counts[attr_name][value]
d = self._attr_value_count_totals[att... | [
"def",
"get_value_prob",
"(",
"self",
",",
"attr_name",
",",
"value",
")",
":",
"if",
"attr_name",
"not",
"in",
"self",
".",
"_attr_value_count_totals",
":",
"return",
"n",
"=",
"self",
".",
"_attr_value_counts",
"[",
"attr_name",
"]",
"[",
"value",
"]",
"... | 38.333333 | 13 |
def intervalCreateSimulateAnalyze (netParams=None, simConfig=None, output=False, interval=None):
''' Sequence of commands create, simulate and analyse network '''
import os
from .. import sim
(pops, cells, conns, stims, rxd, simData) = sim.create(netParams, simConfig, output=True)
try:
if si... | [
"def",
"intervalCreateSimulateAnalyze",
"(",
"netParams",
"=",
"None",
",",
"simConfig",
"=",
"None",
",",
"output",
"=",
"False",
",",
"interval",
"=",
"None",
")",
":",
"import",
"os",
"from",
".",
".",
"import",
"sim",
"(",
"pops",
",",
"cells",
",",
... | 36.526316 | 21.368421 |
def rs_correct_msg_nofsynd(msg_in, nsym, fcr=0, generator=2, erase_pos=None, only_erasures=False):
'''Reed-Solomon main decoding function, without using the modified Forney syndromes'''
global field_charac
if len(msg_in) > field_charac:
raise ValueError("Message is too long (%i when max is %i)" % (l... | [
"def",
"rs_correct_msg_nofsynd",
"(",
"msg_in",
",",
"nsym",
",",
"fcr",
"=",
"0",
",",
"generator",
"=",
"2",
",",
"erase_pos",
"=",
"None",
",",
"only_erasures",
"=",
"False",
")",
":",
"global",
"field_charac",
"if",
"len",
"(",
"msg_in",
")",
">",
... | 56.867925 | 36.679245 |
def tdSensor(self):
"""Get the next sensor while iterating.
:return: a dict with the keys: protocol, model, id, datatypes.
"""
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(proto... | [
"def",
"tdSensor",
"(",
"self",
")",
":",
"protocol",
"=",
"create_string_buffer",
"(",
"20",
")",
"model",
"=",
"create_string_buffer",
"(",
"20",
")",
"sid",
"=",
"c_int",
"(",
")",
"datatypes",
"=",
"c_int",
"(",
")",
"self",
".",
"_lib",
".",
"tdSe... | 37.866667 | 17.066667 |
def stress(syllabified_simplex_word):
'''Assign primary and secondary stress to 'syllabified_simplex_word'.'''
syllables = syllabified_simplex_word.split('.')
stressed = '\'' + syllables[0] # primary stress
try:
n = 0
medial = syllables[1:-1]
for i, syll in enumerate(medial):
... | [
"def",
"stress",
"(",
"syllabified_simplex_word",
")",
":",
"syllables",
"=",
"syllabified_simplex_word",
".",
"split",
"(",
"'.'",
")",
"stressed",
"=",
"'\\''",
"+",
"syllables",
"[",
"0",
"]",
"# primary stress",
"try",
":",
"n",
"=",
"0",
"medial",
"=",
... | 24.705882 | 20.705882 |
def bit_by_bit(self, in_data):
"""
Classic simple and slow CRC implementation. This function iterates bit
by bit over the augmented input message and returns the calculated CRC
value at the end.
"""
# If the input data is a string, convert to bytes.
if isinstance... | [
"def",
"bit_by_bit",
"(",
"self",
",",
"in_data",
")",
":",
"# If the input data is a string, convert to bytes.",
"if",
"isinstance",
"(",
"in_data",
",",
"str",
")",
":",
"in_data",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"in_data",
"]",
"register... | 36.586207 | 15.068966 |
def get_impls(interfaces):
"""Get impls from their interfaces."""
if interfaces is None:
return None
elif isinstance(interfaces, Mapping):
return {name: interfaces[name]._impl for name in interfaces}
elif isinstance(interfaces, Sequence):
return [interfaces._impl for interfaces... | [
"def",
"get_impls",
"(",
"interfaces",
")",
":",
"if",
"interfaces",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"interfaces",
",",
"Mapping",
")",
":",
"return",
"{",
"name",
":",
"interfaces",
"[",
"name",
"]",
".",
"_impl",
"for",
... | 28.153846 | 20.153846 |
def refill(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False):
"""
Refill wallets with the necessary fuel to perform spool transactions
Args:
from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All tra... | [
"def",
"refill",
"(",
"self",
",",
"from_address",
",",
"to_address",
",",
"nfees",
",",
"ntokens",
",",
"password",
",",
"min_confirmations",
"=",
"6",
",",
"sync",
"=",
"False",
")",
":",
"path",
",",
"from_address",
"=",
"from_address",
"verb",
"=",
"... | 62.733333 | 39.133333 |
def get_index(self, value):
"""
Return the index (or indices) of the given value (or values) in
`state_values`.
Parameters
----------
value
Value(s) to get the index (indices) for.
Returns
-------
idx : int or ndarray(int)
... | [
"def",
"get_index",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"state_values",
"is",
"None",
":",
"state_values_ndim",
"=",
"1",
"else",
":",
"state_values_ndim",
"=",
"self",
".",
"state_values",
".",
"ndim",
"values",
"=",
"np",
".",
"asar... | 29.441176 | 18.5 |
def replace_random_tokens_bow(self,
n_samples, # type: int
replacement='', # type: str
random_state=None,
min_replace=1, # type: Union[int, float]
... | [
"def",
"replace_random_tokens_bow",
"(",
"self",
",",
"n_samples",
",",
"# type: int",
"replacement",
"=",
"''",
",",
"# type: str",
"random_state",
"=",
"None",
",",
"min_replace",
"=",
"1",
",",
"# type: Union[int, float]",
"max_replace",
"=",
"1.0",
",",
"# typ... | 52.242424 | 20.606061 |
def r_large(self, x, r0):
"""
Approximate trajectory function for large (:math:`r_0 > \\sigma_r`) oscillations.
"""
return r0*_np.cos(x*self.omega_big(r0)) | [
"def",
"r_large",
"(",
"self",
",",
"x",
",",
"r0",
")",
":",
"return",
"r0",
"*",
"_np",
".",
"cos",
"(",
"x",
"*",
"self",
".",
"omega_big",
"(",
"r0",
")",
")"
] | 36.6 | 14.2 |
def reset(self):
"""Remove all the information from previous dataset before loading a
new dataset.
"""
# store current dataset
max_dataset_history = self.value('max_dataset_history')
keep_recent_datasets(max_dataset_history, self.info)
# reset all the widgets
... | [
"def",
"reset",
"(",
"self",
")",
":",
"# store current dataset",
"max_dataset_history",
"=",
"self",
".",
"value",
"(",
"'max_dataset_history'",
")",
"keep_recent_datasets",
"(",
"max_dataset_history",
",",
"self",
".",
"info",
")",
"# reset all the widgets",
"self",... | 29.411765 | 16.058824 |
def list_user_participants(self, appointment_group, **kwargs):
"""
List user participants in this appointment group.
.. warning::
.. deprecated:: 0.10.0
Use :func:`canvasapi. canvas.Canvas.get_user_participants` instead.
:calls: `GET /api/v1/appointment_grou... | [
"def",
"list_user_participants",
"(",
"self",
",",
"appointment_group",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`list_user_participants` is being deprecated and will be removed in a future version.\"",
"\" Use `get_user_participants` instead\"",
",",
... | 42.956522 | 30.26087 |
def create_menu(self, menu_data):
"""
创建自定义菜单 ::
# -*- coding: utf-8 -*-
wechat = WechatBasic(appid='appid', appsecret='appsecret')
wechat.create_menu({
'button':[
{
'type': 'click',
... | [
"def",
"create_menu",
"(",
"self",
",",
"menu_data",
")",
":",
"menu_data",
"=",
"self",
".",
"_transcoding_dict",
"(",
"menu_data",
")",
"return",
"self",
".",
"request",
".",
"post",
"(",
"url",
"=",
"'https://api.weixin.qq.com/cgi-bin/menu/create'",
",",
"dat... | 34.693878 | 13.102041 |
def _get_dbid2goids(associations):
"""Return gene2go data for user-specified taxids."""
id2gos = cx.defaultdict(set)
for ntd in associations:
id2gos[ntd.DB_ID].add(ntd.GO_ID)
return dict(id2gos) | [
"def",
"_get_dbid2goids",
"(",
"associations",
")",
":",
"id2gos",
"=",
"cx",
".",
"defaultdict",
"(",
"set",
")",
"for",
"ntd",
"in",
"associations",
":",
"id2gos",
"[",
"ntd",
".",
"DB_ID",
"]",
".",
"add",
"(",
"ntd",
".",
"GO_ID",
")",
"return",
... | 38.833333 | 5.833333 |
def parse_pair_results(data, sample, res):
""" parse results from cutadapt for paired data"""
LOGGER.info("in parse pair mod results\n%s", res)
## set default values
sample.stats_dfs.s2["trim_adapter_bp_read1"] = 0
sample.stats_dfs.s2["trim_adapter_bp_read2"] = 0
sample.stats_dfs.s2["trim... | [
"def",
"parse_pair_results",
"(",
"data",
",",
"sample",
",",
"res",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"in parse pair mod results\\n%s\"",
",",
"res",
")",
"## set default values",
"sample",
".",
"stats_dfs",
".",
"s2",
"[",
"\"trim_adapter_bp_read1\"",
"]",... | 39.560606 | 19.924242 |
def configure_sbi(self, sbi_config: dict, schema_path: str = None):
"""Add a new SBI to the database associated with this subarray.
Args:
sbi_config (dict): SBI configuration.
schema_path (str, optional): Path to the SBI config schema.
"""
if not self.active:
... | [
"def",
"configure_sbi",
"(",
"self",
",",
"sbi_config",
":",
"dict",
",",
"schema_path",
":",
"str",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to add SBIs to inactive subarray!\"",
")",
"sbi_config",
... | 40.071429 | 20.214286 |
def _export_table(dataset, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True):
"""
:param DatasetLocal dataset: dataset to export
:param str path: path for file
:param lis[str] column_names: list of column names to export or None for... | [
"def",
"_export_table",
"(",
"dataset",
",",
"column_names",
"=",
"None",
",",
"byteorder",
"=",
"\"=\"",
",",
"shuffle",
"=",
"False",
",",
"selection",
"=",
"False",
",",
"progress",
"=",
"None",
",",
"virtual",
"=",
"True",
",",
"sort",
"=",
"None",
... | 41.972603 | 22.547945 |
def _set_dpi_awareness(self):
""" Set DPI aware to capture full screen on Hi-DPI monitors. """
version = sys.getwindowsversion()[:2] # pylint: disable=no-member
if version >= (6, 3):
# Windows 8.1+
# Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:
# ... | [
"def",
"_set_dpi_awareness",
"(",
"self",
")",
":",
"version",
"=",
"sys",
".",
"getwindowsversion",
"(",
")",
"[",
":",
"2",
"]",
"# pylint: disable=no-member",
"if",
"version",
">=",
"(",
"6",
",",
"3",
")",
":",
"# Windows 8.1+",
"# Here 2 = PROCESS_PER_MON... | 51.857143 | 20.428571 |
def thing_type_exists(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, check to see if the given thing type exists
Returns True if the given thing type exists and returns False if the
given thing type does not exist.
.. versionadded:: 2016.1... | [
"def",
"thing_type_exists",
"(",
"thingTypeName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"... | 30.5 | 23.966667 |
def get_groups_of_account_apikey(self, account_id, api_key, **kwargs): # noqa: E501
"""Get groups of the API key. # noqa: E501
An endpoint for retrieving groups of the API key. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apiKey}/groups -H 'Authoriz... | [
"def",
"get_groups_of_account_apikey",
"(",
"self",
",",
"account_id",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
... | 63.076923 | 35.153846 |
def dist_abs(self, src, tar, max_offset=5, max_distance=0):
"""Return the "common" Sift4 distance between two terms.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
max_offset : int
T... | [
"def",
"dist_abs",
"(",
"self",
",",
"src",
",",
"tar",
",",
"max_offset",
"=",
"5",
",",
"max_distance",
"=",
"0",
")",
":",
"if",
"not",
"src",
":",
"return",
"len",
"(",
"tar",
")",
"if",
"not",
"tar",
":",
"return",
"len",
"(",
"src",
")",
... | 31.117117 | 17.990991 |
def get_mapping_format(self):
"""Dictating the corresponding mapping to the format."""
if self.format == DataFormat.json or self.format == DataFormat.avro:
return self.format.name
else:
return DataFormat.csv.name | [
"def",
"get_mapping_format",
"(",
"self",
")",
":",
"if",
"self",
".",
"format",
"==",
"DataFormat",
".",
"json",
"or",
"self",
".",
"format",
"==",
"DataFormat",
".",
"avro",
":",
"return",
"self",
".",
"format",
".",
"name",
"else",
":",
"return",
"D... | 42.5 | 13.5 |
def get_min_max_mag(self):
"""
:returns: minumum and maximum magnitudes from the underlying MFDs
"""
m1s, m2s = [], []
for mfd in self:
m1, m2 = mfd.get_min_max_mag()
m1s.append(m1)
m2s.append(m2)
return min(m1s), max(m2s) | [
"def",
"get_min_max_mag",
"(",
"self",
")",
":",
"m1s",
",",
"m2s",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"mfd",
"in",
"self",
":",
"m1",
",",
"m2",
"=",
"mfd",
".",
"get_min_max_mag",
"(",
")",
"m1s",
".",
"append",
"(",
"m1",
")",
"m2s",
".",
... | 29.7 | 11.5 |
def lilypond(point):
"""
Generate lilypond representation for a point
"""
#If lilypond already computed, leave as is
if "lilypond" in point:
return point
#Defaults:
pitch_string = ""
octave_string = ""
duration_string = ""
preamble = ""
dynamic_string = ""
if "pi... | [
"def",
"lilypond",
"(",
"point",
")",
":",
"#If lilypond already computed, leave as is",
"if",
"\"lilypond\"",
"in",
"point",
":",
"return",
"point",
"#Defaults:",
"pitch_string",
"=",
"\"\"",
"octave_string",
"=",
"\"\"",
"duration_string",
"=",
"\"\"",
"preamble",
... | 29.62069 | 16.758621 |
def _set_advertisement_interval(self, v, load=False):
"""
Setter method for advertisement_interval, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/neighbor/af_ipv4_vrf_neighbor_address_holder/af_ipv4_neighbor_addr/advertisement_interval (container)
If thi... | [
"def",
"_set_advertisement_interval",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 94.090909 | 47.272727 |
def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Argumen... | [
"def",
"predict",
"(",
"self",
",",
"user_ids",
",",
"item_ids",
",",
"item_features",
"=",
"None",
",",
"user_features",
"=",
"None",
",",
"num_threads",
"=",
"1",
")",
":",
"self",
".",
"_check_initialized",
"(",
")",
"if",
"not",
"isinstance",
"(",
"u... | 36.117647 | 23.882353 |
def new_event(event):
"""
Wrap a raw gRPC event in a friendlier containing class.
This picks the appropriate class from one of PutEvent or DeleteEvent and
returns a new instance.
"""
op_name = event.EventType.DESCRIPTOR.values_by_number[event.type].name
if op_name == 'PUT':
cls = Pu... | [
"def",
"new_event",
"(",
"event",
")",
":",
"op_name",
"=",
"event",
".",
"EventType",
".",
"DESCRIPTOR",
".",
"values_by_number",
"[",
"event",
".",
"type",
"]",
".",
"name",
"if",
"op_name",
"==",
"'PUT'",
":",
"cls",
"=",
"PutEvent",
"elif",
"op_name"... | 27.6875 | 19.5625 |
def shareItem(sharedItem, toRole=None, toName=None, shareID=None,
interfaces=ALL_IMPLEMENTED):
"""
Share an item with a given role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
This API is slated for deprecation. Prefer L{Role.shareItem} in new... | [
"def",
"shareItem",
"(",
"sharedItem",
",",
"toRole",
"=",
"None",
",",
"toName",
"=",
"None",
",",
"shareID",
"=",
"None",
",",
"interfaces",
"=",
"ALL_IMPLEMENTED",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use Role.shareItem() instead of sharing.shareItem().\"... | 39.342857 | 24.257143 |
def notify(self, name, job):
"""
Concrete method of Subject.notify().
Notify to change the status of Subject for observer.
This method call Observer.update().
In this program, ConfigReader.notify() call JobObserver.update().
For exmaple, register threads.redis.ConcreateJo... | [
"def",
"notify",
"(",
"self",
",",
"name",
",",
"job",
")",
":",
"for",
"observer",
"in",
"self",
".",
"_observers",
":",
"observer",
".",
"update",
"(",
"name",
",",
"job",
")"
] | 42.5 | 11.1 |
def passwordReset1to2(old):
"""
Power down and delete the item
"""
new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None)
for iface in new.store.interfacesFor(new):
new.store.powerDown(new, iface)
new.deleteFromStore() | [
"def",
"passwordReset1to2",
"(",
"old",
")",
":",
"new",
"=",
"old",
".",
"upgradeVersion",
"(",
"old",
".",
"typeName",
",",
"1",
",",
"2",
",",
"installedOn",
"=",
"None",
")",
"for",
"iface",
"in",
"new",
".",
"store",
".",
"interfacesFor",
"(",
"... | 31.375 | 8.375 |
def send(self, group_id=None, message_dict=None):
"""
Send this current message to a group.
`message_dict` can be a dictionary formatted according to http://docs.fiesta.cc/list-management-api.html#messages
If message is provided, this method will ignore object-level variables.
"... | [
"def",
"send",
"(",
"self",
",",
"group_id",
"=",
"None",
",",
"message_dict",
"=",
"None",
")",
":",
"if",
"self",
".",
"group",
"is",
"not",
"None",
"and",
"self",
".",
"group",
".",
"id",
"is",
"not",
"None",
":",
"group_id",
"=",
"self",
".",
... | 34.138889 | 20.194444 |
def _set_task_uuid(self, dependencies):
"""Adds universally unique user ids (UUID) to each task of the workflow.
:param dependencies: The list of dependencies between tasks defining the computational graph
:type dependencies: list(Dependency)
:return: A dictionary mapping UUID to d... | [
"def",
"_set_task_uuid",
"(",
"self",
",",
"dependencies",
")",
":",
"uuid_dict",
"=",
"{",
"}",
"for",
"dep",
"in",
"dependencies",
":",
"task",
"=",
"dep",
".",
"task",
"if",
"task",
".",
"private_task_config",
".",
"uuid",
"in",
"uuid_dict",
":",
"rai... | 42.944444 | 21.222222 |
def from_status(cls, http_status, code_index=0, message=None, developer_message=None, meta=None):
# type: (HTTPStatus, int, AnyStr, AnyStr, dict) -> Error
"""
Automatically build an HTTP response from the HTTP Status code.
:param http_status:
:param code_index:
... | [
"def",
"from_status",
"(",
"cls",
",",
"http_status",
",",
"code_index",
"=",
"0",
",",
"message",
"=",
"None",
",",
"developer_message",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"# type: (HTTPStatus, int, AnyStr, AnyStr, dict) -> Error",
"return",
"cls",
... | 37.235294 | 19.117647 |
def detail(self):
"""
个人信息,如果未调用过``get_detail()``会自动调用
:return: information of student
:rtype: dict
"""
if hasattr(self, '_detail'):
return self._detail
else:
self.get_detail()
return self._detail | [
"def",
"detail",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_detail'",
")",
":",
"return",
"self",
".",
"_detail",
"else",
":",
"self",
".",
"get_detail",
"(",
")",
"return",
"self",
".",
"_detail"
] | 23.166667 | 12 |
def get_top_sentences(self):
''' getter '''
if isinstance(self.__top_sentences, int) is False:
raise TypeError("The type of __top_sentences must be int.")
return self.__top_sentences | [
"def",
"get_top_sentences",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"__top_sentences",
",",
"int",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"\"The type of __top_sentences must be int.\"",
")",
"return",
"self",
".",
"__top_sentences... | 42.8 | 16.8 |
def rgb_tuple_from_str(color_string):
"""Convert color in format 'rgb(RRR,GGG,BBB)', 'rgba(RRR,GGG,BBB,alpha)',
'#RRGGBB', or limited English color name (eg 'red') to tuple (RRR, GGG, BBB)
"""
try:
# English color names (limited)
rgb_string = common_html_colors[color_string]
re... | [
"def",
"rgb_tuple_from_str",
"(",
"color_string",
")",
":",
"try",
":",
"# English color names (limited)",
"rgb_string",
"=",
"common_html_colors",
"[",
"color_string",
"]",
"return",
"tuple",
"(",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"re",
".",
"fin... | 41.263158 | 19.684211 |
def evaluate(self, text):
"""
Given a string of `text`, compute confusion matrix for the
classification task.
"""
cx = BinaryConfusion()
for (L, P, R, gold, _) in Detector.candidates(text):
guess = self.predict(L, P, R)
cx.update(gold, guess)
... | [
"def",
"evaluate",
"(",
"self",
",",
"text",
")",
":",
"cx",
"=",
"BinaryConfusion",
"(",
")",
"for",
"(",
"L",
",",
"P",
",",
"R",
",",
"gold",
",",
"_",
")",
"in",
"Detector",
".",
"candidates",
"(",
"text",
")",
":",
"guess",
"=",
"self",
".... | 38.357143 | 13.357143 |
def _numeric_summary(arg, exact_nunique=False, prefix=None):
"""
Compute a set of summary metrics from the input numeric value expression
Parameters
----------
arg : numeric value expression
exact_nunique : boolean, default False
prefix : string, default None
String prefix for metric ... | [
"def",
"_numeric_summary",
"(",
"arg",
",",
"exact_nunique",
"=",
"False",
",",
"prefix",
"=",
"None",
")",
":",
"metrics",
"=",
"[",
"arg",
".",
"count",
"(",
")",
",",
"arg",
".",
"isnull",
"(",
")",
".",
"sum",
"(",
")",
".",
"name",
"(",
"'nu... | 25.516129 | 20.612903 |
def RCL(input_shape,
rec_conv_layers,
dense_layers,
output_layer=[1, 'sigmoid'],
padding='same',
optimizer='adam',
loss='binary_crossentropy'):
"""Summary
Args:
input_shape (tuple): The shape of the input layer.
output_nodes (int): Number of... | [
"def",
"RCL",
"(",
"input_shape",
",",
"rec_conv_layers",
",",
"dense_layers",
",",
"output_layer",
"=",
"[",
"1",
",",
"'sigmoid'",
"]",
",",
"padding",
"=",
"'same'",
",",
"optimizer",
"=",
"'adam'",
",",
"loss",
"=",
"'binary_crossentropy'",
")",
":",
"... | 37.774194 | 20.274194 |
def run(self,
ipyclient=None,
):
"""
Run a batch of dstat tests on a list of tests, where each test is
a dictionary mapping sample names to {p1 - p4} (and sometimes p5).
Parameters modifying the behavior of the run, such as the number
of bootstrap replicates (n... | [
"def",
"run",
"(",
"self",
",",
"ipyclient",
"=",
"None",
",",
")",
":",
"self",
".",
"results_table",
",",
"self",
".",
"results_boots",
"=",
"batch",
"(",
"self",
",",
"ipyclient",
")",
"## skip this for 5-part test results",
"if",
"not",
"isinstance",
"("... | 41.714286 | 23.047619 |
def heatmap_seaborn(dfr, outfilename=None, title=None, params=None):
"""Returns seaborn heatmap with cluster dendrograms.
- dfr - pandas DataFrame with relevant data
- outfilename - path to output file (indicates output format)
"""
# Decide on figure layout size: a minimum size is required for
... | [
"def",
"heatmap_seaborn",
"(",
"dfr",
",",
"outfilename",
"=",
"None",
",",
"title",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"# Decide on figure layout size: a minimum size is required for",
"# aesthetics, and a maximum to avoid core dumps on rendering.",
"# If we ... | 34 | 19.921053 |
def from_page_xml(cls, page_xml):
"""
Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block.
:Parameters:
page_xml : `str` | `file`
Either a plain string or a file containing <page> block XML to
process
"""
header = """
... | [
"def",
"from_page_xml",
"(",
"cls",
",",
"page_xml",
")",
":",
"header",
"=",
"\"\"\"\n <mediawiki xmlns=\"http://www.mediawiki.org/xml/export-0.5/\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.mediawiki.o... | 36.136364 | 21.545455 |
def stop_volume(name, force=False):
'''
Stop a gluster volume
name
Volume name
force
Force stop the volume
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.stop_volume mycluster
'''
volinfo = info()
if name not in v... | [
"def",
"stop_volume",
"(",
"name",
",",
"force",
"=",
"False",
")",
":",
"volinfo",
"=",
"info",
"(",
")",
"if",
"name",
"not",
"in",
"volinfo",
":",
"log",
".",
"error",
"(",
"'Cannot stop non-existing volume %s'",
",",
"name",
")",
"return",
"False",
"... | 19.967742 | 23.903226 |
def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_name... | [
"def",
"rename_tables",
"(",
"db",
",",
"table_mapping",
",",
"reverse",
"=",
"False",
")",
":",
"from",
"django",
".",
"db",
"import",
"connection",
"if",
"reverse",
":",
"table_mapping",
"=",
"[",
"(",
"dst",
",",
"src",
")",
"for",
"src",
",",
"dst"... | 51.933333 | 23.133333 |
def warning_implicit_type(lineno, id_, type_=None):
""" Warning: Using default implicit type 'x'
"""
if OPTIONS.strict.value:
syntax_error_undeclared_type(lineno, id_)
return
if type_ is None:
type_ = global_.DEFAULT_TYPE
warning(lineno, "Using default implicit type '%s' fo... | [
"def",
"warning_implicit_type",
"(",
"lineno",
",",
"id_",
",",
"type_",
"=",
"None",
")",
":",
"if",
"OPTIONS",
".",
"strict",
".",
"value",
":",
"syntax_error_undeclared_type",
"(",
"lineno",
",",
"id_",
")",
"return",
"if",
"type_",
"is",
"None",
":",
... | 30.272727 | 18.181818 |
def find_best_instruction(addr, cpu_name, meta=None):
"""Given an instruction and meta information this attempts to find
the best instruction for the frame. In some circumstances we can
fix it up a bit to improve the accuracy. For more information see
`symbolize_frame`.
"""
addr = rv = parse_a... | [
"def",
"find_best_instruction",
"(",
"addr",
",",
"cpu_name",
",",
"meta",
"=",
"None",
")",
":",
"addr",
"=",
"rv",
"=",
"parse_addr",
"(",
"addr",
")",
"# In case we're not on the crashing frame we apply a simple heuristic:",
"# since we're most likely dealing with return... | 46.7 | 21.133333 |
def _c_base_var(self):
"""Return the name of the module base variable."""
if self.opts.no_structs:
return self.name
return 'windll->{}.{}'.format(
self.name, self.opts.base
) | [
"def",
"_c_base_var",
"(",
"self",
")",
":",
"if",
"self",
".",
"opts",
".",
"no_structs",
":",
"return",
"self",
".",
"name",
"return",
"'windll->{}.{}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"opts",
".",
"base",
")"
] | 32 | 10.571429 |
def booklet_nup_pdf(input_filename: str, output_filename: str,
latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str:
"""
Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4).
The booklet can be folded like a book and the final pages will be in order.
Returns the output fil... | [
"def",
"booklet_nup_pdf",
"(",
"input_filename",
":",
"str",
",",
"output_filename",
":",
"str",
",",
"latex_paper_size",
":",
"str",
"=",
"LATEX_PAPER_SIZE_A4",
")",
"->",
"str",
":",
"log",
".",
"info",
"(",
"\"Creating booklet\"",
")",
"log",
".",
"debug",
... | 38.636364 | 14.515152 |
def get_many(self, content_id_list):
'''Yield (content_id, data) tuples for ids in list.
As with :meth:`get`, if a content_id in the list is missing,
then it is yielded with a data value of `None`.
:type content_id_list: list<str>
:rtype: yields tuple(str, :class:`dossier.fc.Fe... | [
"def",
"get_many",
"(",
"self",
",",
"content_id_list",
")",
":",
"content_id_keys",
"=",
"[",
"tuplify",
"(",
"x",
")",
"for",
"x",
"in",
"content_id_list",
"]",
"for",
"row",
"in",
"self",
".",
"kvl",
".",
"get",
"(",
"self",
".",
"TABLE",
",",
"*"... | 37.058824 | 19.294118 |
def theta_limit(theta):
"""
Angle theta is periodic with period pi.
Constrain theta such that -pi/2<theta<=pi/2.
Parameters
----------
theta : float
Input angle.
Returns
-------
theta : float
Rotate angle.
"""
while theta <= -1 * np.pi / 2:
theta += ... | [
"def",
"theta_limit",
"(",
"theta",
")",
":",
"while",
"theta",
"<=",
"-",
"1",
"*",
"np",
".",
"pi",
"/",
"2",
":",
"theta",
"+=",
"np",
".",
"pi",
"while",
"theta",
">",
"np",
".",
"pi",
"/",
"2",
":",
"theta",
"-=",
"np",
".",
"pi",
"retur... | 18.75 | 19.05 |
def addBlock(self,branch=None,btype=None,mtype=None,attributes=None):
'''
Add block definition to list of blocks in material
Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root, False otherwise),
material name (string if root, F... | [
"def",
"addBlock",
"(",
"self",
",",
"branch",
"=",
"None",
",",
"btype",
"=",
"None",
",",
"mtype",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"if",
"branch",
"==",
"0",
":",
"attributes",
"=",
"self",
".",
"attributes",
"blk",
"=",
"{... | 45.285714 | 25.857143 |
def sanitize_for_archive(url, headers, payload):
"""Sanitize payload of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:r... | [
"def",
"sanitize_for_archive",
"(",
"url",
",",
"headers",
",",
"payload",
")",
":",
"if",
"DiscourseClient",
".",
"PKEY",
"in",
"payload",
":",
"payload",
".",
"pop",
"(",
"DiscourseClient",
".",
"PKEY",
")",
"return",
"url",
",",
"headers",
",",
"payload... | 35.142857 | 12.571429 |
def to_mesh(self):
"""
Return a copy of the Primitive object as a Trimesh object.
"""
result = Trimesh(vertices=self.vertices.copy(),
faces=self.faces.copy(),
face_normals=self.face_normals.copy(),
process=False)
... | [
"def",
"to_mesh",
"(",
"self",
")",
":",
"result",
"=",
"Trimesh",
"(",
"vertices",
"=",
"self",
".",
"vertices",
".",
"copy",
"(",
")",
",",
"faces",
"=",
"self",
".",
"faces",
".",
"copy",
"(",
")",
",",
"face_normals",
"=",
"self",
".",
"face_no... | 37 | 12.777778 |
def _assemble_flowtable(self, values):
""" generate a flowtable from a tuple of descriptors.
"""
values = map(lambda x: [] if x is None else x, values)
src = values[0] + values[1]
dst = values[2] + values[3]
thistable = dict()
for s in src:
thistable[... | [
"def",
"_assemble_flowtable",
"(",
"self",
",",
"values",
")",
":",
"values",
"=",
"map",
"(",
"lambda",
"x",
":",
"[",
"]",
"if",
"x",
"is",
"None",
"else",
"x",
",",
"values",
")",
"src",
"=",
"values",
"[",
"0",
"]",
"+",
"values",
"[",
"1",
... | 31.181818 | 12.090909 |
def qtag(tag):
"""
Return fully qualified (Clark notation) tagname corresponding to
short-form prefixed tagname *tag*.
"""
prefix, tagroot = tag.split(':')
uri = nsmap[prefix]
return '{%s}%s' % (uri, tagroot) | [
"def",
"qtag",
"(",
"tag",
")",
":",
"prefix",
",",
"tagroot",
"=",
"tag",
".",
"split",
"(",
"':'",
")",
"uri",
"=",
"nsmap",
"[",
"prefix",
"]",
"return",
"'{%s}%s'",
"%",
"(",
"uri",
",",
"tagroot",
")"
] | 28.625 | 10.125 |
def model_counts_map(self, name=None, exclude=None, use_mask=False):
"""Return the model counts map for a single source, a list of
sources, or for the sum of all sources in the ROI. The
exclude parameter can be used to exclude one or more
components when generating the model map.
... | [
"def",
"model_counts_map",
"(",
"self",
",",
"name",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"use_mask",
"=",
"False",
")",
":",
"maps",
"=",
"[",
"c",
".",
"model_counts_map",
"(",
"name",
",",
"exclude",
",",
"use_mask",
"=",
"use_mask",
")",
... | 35.322581 | 22.677419 |
def _check_and_execute(func, *args, **kwargs):
"""
Check the type of all parameters with type information, converting
as appropriate and then execute the function.
"""
convargs = []
#Convert and validate all arguments
for i, arg in enumerate(args):
val = func.metadata.convert_posit... | [
"def",
"_check_and_execute",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"convargs",
"=",
"[",
"]",
"#Convert and validate all arguments",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"val",
"=",
"func",
".",
... | 32.772727 | 23.5 |
def _QueryHash(self, digest):
"""Queries the Viper Server for a specfic hash.
Args:
digest (str): hash to look up.
Returns:
dict[str, object]: JSON response or None on error.
"""
if not self._url:
self._url = '{0:s}://{1:s}:{2:d}/file/find'.format(
self._protocol, self.... | [
"def",
"_QueryHash",
"(",
"self",
",",
"digest",
")",
":",
"if",
"not",
"self",
".",
"_url",
":",
"self",
".",
"_url",
"=",
"'{0:s}://{1:s}:{2:d}/file/find'",
".",
"format",
"(",
"self",
".",
"_protocol",
",",
"self",
".",
"_host",
",",
"self",
".",
"_... | 26.64 | 20.64 |
def logp_gradient(variable, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to variable.
Calculation of the log posterior is restricted to the variables in calculation_set.
"""
return variable.logp_partial_gradient(variable, calculation_set) + sum(
... | [
"def",
"logp_gradient",
"(",
"variable",
",",
"calculation_set",
"=",
"None",
")",
":",
"return",
"variable",
".",
"logp_partial_gradient",
"(",
"variable",
",",
"calculation_set",
")",
"+",
"sum",
"(",
"[",
"child",
".",
"logp_partial_gradient",
"(",
"variable"... | 57.428571 | 26.857143 |
def add_exception(self, exception, stack, remote=False):
"""
Add an exception to trace entities.
:param Exception exception: the catched exception.
:param list stack: the output from python built-in
`traceback.extract_stack()`.
:param bool remote: If False it means i... | [
"def",
"add_exception",
"(",
"self",
",",
"exception",
",",
"stack",
",",
"remote",
"=",
"False",
")",
":",
"self",
".",
"_check_ended",
"(",
")",
"self",
".",
"add_fault_flag",
"(",
")",
"if",
"hasattr",
"(",
"exception",
",",
"'_recorded'",
")",
":",
... | 34.227273 | 17.136364 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.