text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def recount_view(request):
"""
Recount number_of_messages for all threads and number_of_responses for all requests.
Also set the change_date for every thread to the post_date of the latest message
associated with that thread.
"""
requests_changed = 0
for req in Request.objects.all():
... | [
"def",
"recount_view",
"(",
"request",
")",
":",
"requests_changed",
"=",
"0",
"for",
"req",
"in",
"Request",
".",
"objects",
".",
"all",
"(",
")",
":",
"recount",
"=",
"Response",
".",
"objects",
".",
"filter",
"(",
"request",
"=",
"req",
")",
".",
... | 42.117647 | 15 |
def translatePoints(points, movex, movey):
"""
Returns a generator that produces all of the (x, y) tuples in `points` moved over by `movex` and `movey`.
>>> points = [(0, 0), (5, 10), (25, 25)]
>>> list(translatePoints(points, 1, -3))
[(1, -3), (6, 7), (26, 22)]
"""
# Note: There is no tra... | [
"def",
"translatePoints",
"(",
"points",
",",
"movex",
",",
"movey",
")",
":",
"# Note: There is no translatePoint() function because that's trivial.",
"_checkForIntOrFloat",
"(",
"movex",
")",
"_checkForIntOrFloat",
"(",
"movey",
")",
"try",
":",
"for",
"x",
",",
"y"... | 34.842105 | 19.052632 |
def update_field(self, name, value):
"""Changes the definition of a KV Store field.
:param name: name of field to change
:type name: ``string``
:param value: new field definition
:type value: ``string``
:return: Result of POST request
"""
kwargs = {}
... | [
"def",
"update_field",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
"[",
"'field.'",
"+",
"name",
"]",
"=",
"value",
"return",
"self",
".",
"post",
"(",
"*",
"*",
"kwargs",
")"
] | 29.153846 | 10.615385 |
def admin_link(obj):
"""
Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj:... | [
"def",
"admin_link",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_admin_link'",
")",
":",
"return",
"mark_safe",
"(",
"obj",
".",
"get_admin_link",
"(",
")",
")",
"return",
"mark_safe",
"(",
"admin_link_fn",
"(",
"obj",
")",
")"
] | 24.863636 | 20.136364 |
def update(self, **kwargs):
"""
Updates the matching objects for specified fields.
Note:
Post/pre save hooks and signals will NOT triggered.
Unlike RDBMS systems, this method makes individual save calls
to backend DB store. So this is exists as more of a com... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"do_simple_update",
"=",
"kwargs",
".",
"get",
"(",
"'simple_update'",
",",
"True",
")",
"no_of_updates",
"=",
"0",
"for",
"model",
"in",
"self",
":",
"no_of_updates",
"+=",
"1",
"model",
... | 31.827586 | 22.172414 |
def CreateMock(self, class_to_mock):
"""Create a new mock object.
Args:
# class_to_mock: the class to be mocked
class_to_mock: class
Returns:
MockObject that can be used as the class_to_mock would be.
"""
new_mock = MockObject(class_to_mock)
self._mock_objects.append(new_moc... | [
"def",
"CreateMock",
"(",
"self",
",",
"class_to_mock",
")",
":",
"new_mock",
"=",
"MockObject",
"(",
"class_to_mock",
")",
"self",
".",
"_mock_objects",
".",
"append",
"(",
"new_mock",
")",
"return",
"new_mock"
] | 23.5 | 17.714286 |
def minimum_entropy_match_sequence(password, matches):
"""
Returns minimum entropy
Takes a list of overlapping matches, returns the non-overlapping sublist with
minimum entropy. O(nm) dp alg for length-n password with m candidate matches.
"""
bruteforce_cardinality = calc_bruteforce_cardinality... | [
"def",
"minimum_entropy_match_sequence",
"(",
"password",
",",
"matches",
")",
":",
"bruteforce_cardinality",
"=",
"calc_bruteforce_cardinality",
"(",
"password",
")",
"# e.g. 26 for lowercase",
"up_to_k",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"password",
")",
"# min... | 40 | 21.376623 |
def dy(self):
"""Y-axis sample separation
:type: `~astropy.units.Quantity` scalar
"""
try:
return self._dy
except AttributeError:
try:
self._yindex
except AttributeError:
self._dy = Quantity(1, self.yunit)
... | [
"def",
"dy",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_dy",
"except",
"AttributeError",
":",
"try",
":",
"self",
".",
"_yindex",
"except",
"AttributeError",
":",
"self",
".",
"_dy",
"=",
"Quantity",
"(",
"1",
",",
"self",
".",
"yuni... | 32.210526 | 14.631579 |
def generic_filename(path):
'''
Extract filename of given path os-indepently, taking care of known path
separators.
:param path: path
:return: filename
:rtype: str or unicode (depending on given path)
'''
for sep in common_path_separators:
if sep in path:
_, path = ... | [
"def",
"generic_filename",
"(",
"path",
")",
":",
"for",
"sep",
"in",
"common_path_separators",
":",
"if",
"sep",
"in",
"path",
":",
"_",
",",
"path",
"=",
"path",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"return",
"path"
] | 24.428571 | 22.428571 |
def UploadItem(filename, gallery, desiredName=None, progress_cb=None):
"""filename is the full file location and name of the file
WARNING: If your desiredName doesn't have a proper file extension (SHOULD
be the same as the filename) it'll still upload, but you won't be able to
download it or view it onl... | [
"def",
"UploadItem",
"(",
"filename",
",",
"gallery",
",",
"desiredName",
"=",
"None",
",",
"progress_cb",
"=",
"None",
")",
":",
"# Must have the ? because urlencode doesn't add that on itself",
"url",
"=",
"'http://min.us/api/UploadItem?'",
"if",
"desiredName",
":",
"... | 35.351351 | 24.135135 |
def linear_warp(X, d, n, *args):
r"""Warp inputs with a linear transformation.
Applies the warping
.. math::
w(x) = \frac{x-a}{b-a}
to each dimension. If you set `a=min(X)` and `b=max(X)` then this is a
convenient way to map your inputs to the unit hypercube.
... | [
"def",
"linear_warp",
"(",
"X",
",",
"d",
",",
"n",
",",
"*",
"args",
")",
":",
"X",
"=",
"scipy",
".",
"asarray",
"(",
"X",
",",
"dtype",
"=",
"float",
")",
"a",
"=",
"args",
"[",
"2",
"*",
"d",
"]",
"b",
"=",
"args",
"[",
"2",
"*",
"d",... | 28.75 | 21.027778 |
def minimum_bracketing(fct, initial_value=0.0, natural_length=1.0 + DOUBLE_TOL):
'''
Given a function func, and given distinct inital points ax and bx, this routine searches
in the downhill direction (defined by the function as evaluated at the initial points)
and returns new points at ax, bx, cx that b... | [
"def",
"minimum_bracketing",
"(",
"fct",
",",
"initial_value",
"=",
"0.0",
",",
"natural_length",
"=",
"1.0",
"+",
"DOUBLE_TOL",
")",
":",
"def",
"_minimum_bracketing",
"(",
"a",
",",
"b",
",",
"fct",
")",
":",
"v",
"=",
"mn_brak",
"(",
"a",
",",
"b",
... | 38.565217 | 23.782609 |
def greplines(pattern, lines):
"""Given a list of strings *lines* return the lines that match
pattern.
"""
res = []
for line in lines:
match = re.search(pattern, line)
if match is not None:
res.append(line)
return res | [
"def",
"greplines",
"(",
"pattern",
",",
"lines",
")",
":",
"res",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"match",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"line",
")",
"if",
"match",
"is",
"not",
"None",
":",
"res",
".",
"append... | 23.636364 | 15.727273 |
def parse(self):
"""Parse the data."""
if self._filename:
with open(self._filename) as ifile:
self._data = ifile.read()
with QasmParser(self._filename) as qasm_p:
qasm_p.parse_debug(False)
return qasm_p.parse(self._data) | [
"def",
"parse",
"(",
"self",
")",
":",
"if",
"self",
".",
"_filename",
":",
"with",
"open",
"(",
"self",
".",
"_filename",
")",
"as",
"ifile",
":",
"self",
".",
"_data",
"=",
"ifile",
".",
"read",
"(",
")",
"with",
"QasmParser",
"(",
"self",
".",
... | 32.111111 | 11.333333 |
def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a GET request to url with optional authentication
"""
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | [
"def",
"rest_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
",",
... | 48.428571 | 17.571429 |
def discardTxns(self, count: int):
"""
The number of txns in `uncommittedTxns` which have to be
discarded
:param count:
:return:
"""
# TODO: This can be optimised if multiple discards are combined
# together since merkle root computation will be done only ... | [
"def",
"discardTxns",
"(",
"self",
",",
"count",
":",
"int",
")",
":",
"# TODO: This can be optimised if multiple discards are combined",
"# together since merkle root computation will be done only once.",
"if",
"count",
"==",
"0",
":",
"return",
"if",
"count",
">",
"len",
... | 46.961538 | 20.5 |
def binding_of(self, typevar):
"""Returns the type the typevar is bound to, or None."""
if typevar in self._ns:
return self._ns[typevar]
if self._instance_ns and typevar in self._instance_ns:
return self._instance_ns[typevar]
return None | [
"def",
"binding_of",
"(",
"self",
",",
"typevar",
")",
":",
"if",
"typevar",
"in",
"self",
".",
"_ns",
":",
"return",
"self",
".",
"_ns",
"[",
"typevar",
"]",
"if",
"self",
".",
"_instance_ns",
"and",
"typevar",
"in",
"self",
".",
"_instance_ns",
":",
... | 41 | 10.142857 |
def created(self):
'return datetime.datetime'
return dateutil.parser.parse(str(self.f.currentRevision.created)) | [
"def",
"created",
"(",
"self",
")",
":",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"str",
"(",
"self",
".",
"f",
".",
"currentRevision",
".",
"created",
")",
")"
] | 41.666667 | 20.333333 |
def copy_item(self, erase_original=False):
"""Copy item"""
indexes = self.selectedIndexes()
if not indexes:
return
idx_rows = unsorted_unique([idx.row() for idx in indexes])
if len(idx_rows) > 1 or not indexes[0].isValid():
return
orig_key ... | [
"def",
"copy_item",
"(",
"self",
",",
"erase_original",
"=",
"False",
")",
":",
"indexes",
"=",
"self",
".",
"selectedIndexes",
"(",
")",
"if",
"not",
"indexes",
":",
"return",
"idx_rows",
"=",
"unsorted_unique",
"(",
"[",
"idx",
".",
"row",
"(",
")",
... | 40.142857 | 12.785714 |
def process(in_path, out_file, n_jobs, framesync):
"""Computes the features for the selected dataset or file."""
if os.path.isfile(in_path):
# Single file mode
# Get (if they exitst) or compute features
file_struct = msaf.io.FileStruct(in_path)
file_struct.features_file = out_fil... | [
"def",
"process",
"(",
"in_path",
",",
"out_file",
",",
"n_jobs",
",",
"framesync",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"in_path",
")",
":",
"# Single file mode",
"# Get (if they exitst) or compute features",
"file_struct",
"=",
"msaf",
".",
... | 41.4 | 16.133333 |
def scale_neg_1_to_1_with_zero_mean_log_abs_max(v):
'''
!!! not working
'''
df = pd.DataFrame({'v':v,
'sign': (v > 0) * 2 - 1})
df['lg'] = np.log(np.abs(v)) / np.log(1.96)
df['exclude'] = (np.isinf(df.lg) | np.isneginf(df.lg))
for mask in [(df['sign'] == -1) & (df['exclude'] == False),
... | [
"def",
"scale_neg_1_to_1_with_zero_mean_log_abs_max",
"(",
"v",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'v'",
":",
"v",
",",
"'sign'",
":",
"(",
"v",
">",
"0",
")",
"*",
"2",
"-",
"1",
"}",
")",
"df",
"[",
"'lg'",
"]",
"=",
"np",
... | 36.791667 | 14.708333 |
def query_func_module(self, func):
"""Query the module name of the specified function."""
exp = self.session.query(Export).filter_by(
func=func).first()
if exp:
return exp
logging.debug(_('Function not found: %s'), func)
alt = func + 'A'
exp = self... | [
"def",
"query_func_module",
"(",
"self",
",",
"func",
")",
":",
"exp",
"=",
"self",
".",
"session",
".",
"query",
"(",
"Export",
")",
".",
"filter_by",
"(",
"func",
"=",
"func",
")",
".",
"first",
"(",
")",
"if",
"exp",
":",
"return",
"exp",
"loggi... | 36.866667 | 15.4 |
def _create_ucsm_host_to_service_profile_mapping(self):
"""Reads list of Service profiles and finds associated Server."""
ucsm_ips = list(CONF.ml2_cisco_ucsm.ucsms)
for ucsm_ip in ucsm_ips:
with self.ucsm_connect_disconnect(ucsm_ip) as handle:
try:
... | [
"def",
"_create_ucsm_host_to_service_profile_mapping",
"(",
"self",
")",
":",
"ucsm_ips",
"=",
"list",
"(",
"CONF",
".",
"ml2_cisco_ucsm",
".",
"ucsms",
")",
"for",
"ucsm_ip",
"in",
"ucsm_ips",
":",
"with",
"self",
".",
"ucsm_connect_disconnect",
"(",
"ucsm_ip",
... | 60.125 | 21.333333 |
def _dqtoi(self, dq):
"""Convert dotquad or hextet to long."""
# hex notation
if dq.startswith('0x'):
return self._dqtoi_hex(dq)
# IPv6
if ':' in dq:
return self._dqtoi_ipv6(dq)
elif len(dq) == 32:
# Assume full heximal notation
... | [
"def",
"_dqtoi",
"(",
"self",
",",
"dq",
")",
":",
"# hex notation",
"if",
"dq",
".",
"startswith",
"(",
"'0x'",
")",
":",
"return",
"self",
".",
"_dqtoi_hex",
"(",
"dq",
")",
"# IPv6",
"if",
"':'",
"in",
"dq",
":",
"return",
"self",
".",
"_dqtoi_ipv... | 25.157895 | 16.421053 |
def shell_expand_to_popen(template, values):
"""
Expand a template like "cp $SOURCE $TARGET/blah" into a list of popen arguments.
"""
return [expand_variables(item, values) for item in shlex.split(template)] | [
"def",
"shell_expand_to_popen",
"(",
"template",
",",
"values",
")",
":",
"return",
"[",
"expand_variables",
"(",
"item",
",",
"values",
")",
"for",
"item",
"in",
"shlex",
".",
"split",
"(",
"template",
")",
"]"
] | 42.2 | 16.2 |
def getSerializedResponse(self):
"""
Returns a string version of the SearchResponse that has
been built by this SearchResponseBuilder.
"""
self._protoObject.next_page_token = pb.string(self._nextPageToken)
s = protocol.toJson(self._protoObject)
return s | [
"def",
"getSerializedResponse",
"(",
"self",
")",
":",
"self",
".",
"_protoObject",
".",
"next_page_token",
"=",
"pb",
".",
"string",
"(",
"self",
".",
"_nextPageToken",
")",
"s",
"=",
"protocol",
".",
"toJson",
"(",
"self",
".",
"_protoObject",
")",
"retu... | 37.75 | 13 |
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine):
"""
Add top-level template condition that combines the given list of conditions.
:param dict template_dict: SAM template dictionary
:param string condition_name: Name of top-level templa... | [
"def",
"_add_combined_condition_to_template",
"(",
"self",
",",
"template_dict",
",",
"condition_name",
",",
"conditions_to_combine",
")",
":",
"# defensive precondition check",
"if",
"not",
"conditions_to_combine",
"or",
"len",
"(",
"conditions_to_combine",
")",
"<",
"2"... | 58.941176 | 32 |
def save_cfg_vals_to_git_cfg(**cfg_map):
"""Save a set of options into Git config."""
for cfg_key_suffix, cfg_val in cfg_map.items():
cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git", "config", "--local", cfg_key, cfg_val
subprocess.check_call(cmd, stderr=subproc... | [
"def",
"save_cfg_vals_to_git_cfg",
"(",
"*",
"*",
"cfg_map",
")",
":",
"for",
"cfg_key_suffix",
",",
"cfg_val",
"in",
"cfg_map",
".",
"items",
"(",
")",
":",
"cfg_key",
"=",
"f'cherry-picker.{cfg_key_suffix.replace(\"_\", \"-\")}'",
"cmd",
"=",
"\"git\"",
",",
"\"... | 54.333333 | 13 |
def translation_instances(self):
"""
Returns translation instances.
"""
return [
instance
for k, v in six.iteritems(self.instance._linguist_translations)
for instance in v.values()
] | [
"def",
"translation_instances",
"(",
"self",
")",
":",
"return",
"[",
"instance",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"instance",
".",
"_linguist_translations",
")",
"for",
"instance",
"in",
"v",
".",
"values",
"(",
")"... | 27.777778 | 13.555556 |
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
""" Computes additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W... | [
"def",
"additive_self_attention",
"(",
"units",
",",
"n_hidden",
"=",
"None",
",",
"n_output_features",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"n_input_features",
"=",
"units",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"2",... | 54.653846 | 28.615385 |
def calc(request, calc_id):
"""
Get a JSON blob containing all of parameters for the given calculation
(specified by ``calc_id``). Also includes the current job status (
executing, complete, etc.).
"""
try:
info = logs.dbcmd('calc_info', calc_id)
if not utils.user_has_permission(... | [
"def",
"calc",
"(",
"request",
",",
"calc_id",
")",
":",
"try",
":",
"info",
"=",
"logs",
".",
"dbcmd",
"(",
"'calc_info'",
",",
"calc_id",
")",
"if",
"not",
"utils",
".",
"user_has_permission",
"(",
"request",
",",
"info",
"[",
"'user_name'",
"]",
")"... | 39.461538 | 15.461538 |
def start(self):
"""
Launch DagFileProcessorManager processor and start DAG parsing loop in manager.
"""
self._process = self._launch_process(self._dag_directory,
self._file_paths,
self._max_runs,
... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_process",
"=",
"self",
".",
"_launch_process",
"(",
"self",
".",
"_dag_directory",
",",
"self",
".",
"_file_paths",
",",
"self",
".",
"_max_runs",
",",
"self",
".",
"_processor_factory",
",",
"self",
... | 55.923077 | 24.076923 |
def get_title(src_name, src_type=None):
"""Normalizes a source name as a string to be used for viewer's title."""
if src_type == 'tcp':
return '{0}:{1}'.format(*src_name)
return os.path.basename(src_name) | [
"def",
"get_title",
"(",
"src_name",
",",
"src_type",
"=",
"None",
")",
":",
"if",
"src_type",
"==",
"'tcp'",
":",
"return",
"'{0}:{1}'",
".",
"format",
"(",
"*",
"src_name",
")",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"src_name",
")"
] | 44 | 4.2 |
def get_subject(self, msg):
"""Extracts the subject line from an EmailMessage object."""
text, encoding = decode_header(msg['subject'])[-1]
try:
text = text.decode(encoding)
# If it's already decoded, ignore error
except AttributeError:
pass
re... | [
"def",
"get_subject",
"(",
"self",
",",
"msg",
")",
":",
"text",
",",
"encoding",
"=",
"decode_header",
"(",
"msg",
"[",
"'subject'",
"]",
")",
"[",
"-",
"1",
"]",
"try",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"encoding",
")",
"# If it's alrea... | 24.384615 | 21.615385 |
async def sinterstore(self, dest, keys, *args):
"""
Store the intersection of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
"""
args = list_or_args(keys, args)
return await self.execute_command('SINTERSTORE', dest, *... | [
"async",
"def",
"sinterstore",
"(",
"self",
",",
"dest",
",",
"keys",
",",
"*",
"args",
")",
":",
"args",
"=",
"list_or_args",
"(",
"keys",
",",
"args",
")",
"return",
"await",
"self",
".",
"execute_command",
"(",
"'SINTERSTORE'",
",",
"dest",
",",
"*"... | 45.571429 | 14.142857 |
def p_InDecrement(p):
'''
InDecrement : INDECREMENT Expression
| Expression INDECREMENT
'''
from .helper import isString
if isString(p[1]):
p[0] = InDecrement(p[1], p[2], False)
else:
p[0] = InDecrement(p[2], p[1], True) | [
"def",
"p_InDecrement",
"(",
"p",
")",
":",
"from",
".",
"helper",
"import",
"isString",
"if",
"isString",
"(",
"p",
"[",
"1",
"]",
")",
":",
"p",
"[",
"0",
"]",
"=",
"InDecrement",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"Fals... | 26.7 | 15.1 |
def format_parameter(element):
"""
Formats a particular parameter. Essentially the same as built-in formatting except using 'i' instead of 'j' for
the imaginary number.
:param element: {int, float, long, complex, Parameter} Formats a parameter for Quil output.
"""
if isinstance(element, integer... | [
"def",
"format_parameter",
"(",
"element",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"integer_types",
")",
"or",
"isinstance",
"(",
"element",
",",
"np",
".",
"int_",
")",
":",
"return",
"repr",
"(",
"element",
")",
"elif",
"isinstance",
"(",
"e... | 30.380952 | 17.904762 |
def tomography_set(meas_qubits,
meas_basis='Pauli',
prep_qubits=None,
prep_basis=None):
"""
Generate a dictionary of tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state ... | [
"def",
"tomography_set",
"(",
"meas_qubits",
",",
"meas_basis",
"=",
"'Pauli'",
",",
"prep_qubits",
"=",
"None",
",",
"prep_basis",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"meas_qubits",
",",
"list",
")",
":",
"raise",
"QiskitError",
"(",
"'... | 43.169355 | 19.153226 |
def hessian(self, x, y, amp, sigma_x, sigma_y, center_x = 0, center_y = 0):
"""
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
"""
f_ = self.function(x, y, amp, sigma_x, sigma_y, center_x, center_y)
f_xx = f_ * ( (-1./sigma_x**2) + (center_x-x)**2/sigma_x**4 )
... | [
"def",
"hessian",
"(",
"self",
",",
"x",
",",
"y",
",",
"amp",
",",
"sigma_x",
",",
"sigma_y",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
")",
":",
"f_",
"=",
"self",
".",
"function",
"(",
"x",
",",
"y",
",",
"amp",
",",
"sigma_x",
... | 53.555556 | 22 |
def get_content_descendants(self, content_id, expand=None, callback=None):
"""
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
... | [
"def",
"get_content_descendants",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\"expand\"",
"]",
"=",
"expand",
"return",
"self",
".",
... | 73.272727 | 43.727273 |
def list_backups(self, encrypted=None, compressed=None, content_type=None,
database=None, servername=None):
"""
List stored files except given filter. If filter is None, it won't be
used. ``content_type`` must be ``'db'`` for database backups or
``'media'`` for media... | [
"def",
"list_backups",
"(",
"self",
",",
"encrypted",
"=",
"None",
",",
"compressed",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"database",
"=",
"None",
",",
"servername",
"=",
"None",
")",
":",
"if",
"content_type",
"not",
"in",
"(",
"'db'",
... | 40 | 19.043478 |
def check_extensions(self, supported):
"""
"extensionsRequired": ["KHR_draco_mesh_compression"],
"extensionsUsed": ["KHR_draco_mesh_compression"]
"""
if self.data.get('extensionsRequired'):
for ext in self.data.get('extensionsRequired'):
if ext not in ... | [
"def",
"check_extensions",
"(",
"self",
",",
"supported",
")",
":",
"if",
"self",
".",
"data",
".",
"get",
"(",
"'extensionsRequired'",
")",
":",
"for",
"ext",
"in",
"self",
".",
"data",
".",
"get",
"(",
"'extensionsRequired'",
")",
":",
"if",
"ext",
"... | 44.071429 | 14.214286 |
def make_series(x, *args, **kwargs):
"""Coerce a provided array/sequence/generator into a pandas.Series object
FIXME: Deal with CSR, COO, DOK and other sparse matrices like this:
pd.Series(csr.toarray()[:,0])
or, if csr.shape[1] == 2
pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0])... | [
"def",
"make_series",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Series",
")",
":",
"return",
"x",
"try",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"'pk'",
"not",
... | 35.576923 | 20 |
def check(self, triggers, data_reader):
""" Look for a single detector trigger that passes the thresholds in
the current data.
"""
if len(triggers['snr']) == 0:
return None
i = triggers['snr'].argmax()
# This uses the pycbc live convention of chisq always mea... | [
"def",
"check",
"(",
"self",
",",
"triggers",
",",
"data_reader",
")",
":",
"if",
"len",
"(",
"triggers",
"[",
"'snr'",
"]",
")",
"==",
"0",
":",
"return",
"None",
"i",
"=",
"triggers",
"[",
"'snr'",
"]",
".",
"argmax",
"(",
")",
"# This uses the pyc... | 40.291667 | 14.25 |
def invoke(self, args, kwargs):
"""
Send the required soap message to invoke the specified method
@param args: A list of args for the method invoked.
@type args: list
@param kwargs: Named (keyword) args for the method invoked.
@type kwargs: dict
@return: The resul... | [
"def",
"invoke",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"simulation",
"=",
"kwargs",
"[",
"self",
".",
"injkey",
"]",
"msg",
"=",
"simulation",
".",
"get",
"(",
"'msg'",
")",
"reply",
"=",
"simulation",
".",
"get",
"(",
"'reply'",
")",
... | 39.043478 | 11.217391 |
def parse_barcode_file(fp, primer=None, header=False):
"""
Load label, barcode, primer records from a CSV file.
Returns a map from barcode -> label
Any additional columns are ignored
"""
tr = trie.trie()
reader = csv.reader(fp)
if header:
# Skip header
next(reader)
... | [
"def",
"parse_barcode_file",
"(",
"fp",
",",
"primer",
"=",
"None",
",",
"header",
"=",
"False",
")",
":",
"tr",
"=",
"trie",
".",
"trie",
"(",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
"fp",
")",
"if",
"header",
":",
"# Skip header",
"next",
... | 26.90625 | 19.34375 |
def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
"""
cluster_config = get_hacluster_config()
vip_group = []
vips_to... | [
"def",
"update_hacluster_vip",
"(",
"service",
",",
"relation_data",
")",
":",
"cluster_config",
"=",
"get_hacluster_config",
"(",
")",
"vip_group",
"=",
"[",
"]",
"vips_to_delete",
"=",
"[",
"]",
"for",
"vip",
"in",
"cluster_config",
"[",
"'vip'",
"]",
".",
... | 38.666667 | 16.773333 |
def _match_one(self, rec, tests):
"""Check if a specific record matches tests."""
for key,test in tests.iteritems():
if not test(rec.get(key, None)):
return False
return True | [
"def",
"_match_one",
"(",
"self",
",",
"rec",
",",
"tests",
")",
":",
"for",
"key",
",",
"test",
"in",
"tests",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"test",
"(",
"rec",
".",
"get",
"(",
"key",
",",
"None",
")",
")",
":",
"return",
"Fal... | 36.833333 | 7.666667 |
def get_host(url):
"""
Given a url, return its scheme, host and port (None if it's not there).
For example: ::
>>> get_host('http://google.com/mail/')
('http', 'google.com', None)
>>> get_host('google.com:80')
('http', 'google.com', 80)
"""
# This code is actually s... | [
"def",
"get_host",
"(",
"url",
")",
":",
"# This code is actually similar to urlparse.urlsplit, but much",
"# simplified for our needs.",
"port",
"=",
"None",
"scheme",
"=",
"'http'",
"if",
"'//'",
"in",
"url",
":",
"scheme",
",",
"url",
"=",
"url",
".",
"split",
... | 27.565217 | 15.565217 |
def _build_tree_string(root, curr_index, index=False, delimiter='-'):
"""Recursively walk down the binary tree and build a pretty-print string.
In each recursive call, a "box" of characters visually representing the
current (sub)tree is constructed line by line. Each line is padded with
whitespaces to ... | [
"def",
"_build_tree_string",
"(",
"root",
",",
"curr_index",
",",
"index",
"=",
"False",
",",
"delimiter",
"=",
"'-'",
")",
":",
"if",
"root",
"is",
"None",
":",
"return",
"[",
"]",
",",
"0",
",",
"0",
",",
"0",
"line1",
"=",
"[",
"]",
"line2",
"... | 42 | 22.357143 |
def register(name=None, exprresolver=None, params=None, reg=None):
"""Register an expression resolver.
Can be used such as a decorator.
For example all remainding expressions are the same.
.. code-block:: python
@register('myresolver')
def myresolver(**kwargs): pass
.. code-bloc... | [
"def",
"register",
"(",
"name",
"=",
"None",
",",
"exprresolver",
"=",
"None",
",",
"params",
"=",
"None",
",",
"reg",
"=",
"None",
")",
":",
"def",
"_register",
"(",
"exprresolver",
",",
"_name",
"=",
"name",
",",
"_params",
"=",
"params",
")",
":",... | 24.977273 | 23.125 |
def add_compliance_task(self, name, module_name='docker-bench-security', schedule='06:00:00Z/PT12H', scope=None, enabled=True):
'''**Description**
Add a new compliance task.
**Arguments**
- name: The name of the task e.g. 'Check Docker Compliance'.
- module_name: The... | [
"def",
"add_compliance_task",
"(",
"self",
",",
"name",
",",
"module_name",
"=",
"'docker-bench-security'",
",",
"schedule",
"=",
"'06:00:00Z/PT12H'",
",",
"scope",
"=",
"None",
",",
"enabled",
"=",
"True",
")",
":",
"task",
"=",
"{",
"\"id\"",
":",
"None",
... | 56.916667 | 39.5 |
def srflood(x, promisc=None, filter=None, iface=None, nofilter=None, *args, **kargs): # noqa: E501
"""Flood and receive packets at layer 3
prn: function applied to packets received
unique: only consider packets whose print
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: ... | [
"def",
"srflood",
"(",
"x",
",",
"promisc",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"iface",
"=",
"None",
",",
"nofilter",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"# noqa: E501",
"s",
"=",
"conf",
".",
"L3socket",
"... | 47.636364 | 17.818182 |
def _get_cached(self):
"""Gets a list of statements that the operation will affect during the real
time update."""
lines = self.context.cachedstr[self.icached[0]:self.icached[1]]
return self._get_statements(lines, self.icached[0]) | [
"def",
"_get_cached",
"(",
"self",
")",
":",
"lines",
"=",
"self",
".",
"context",
".",
"cachedstr",
"[",
"self",
".",
"icached",
"[",
"0",
"]",
":",
"self",
".",
"icached",
"[",
"1",
"]",
"]",
"return",
"self",
".",
"_get_statements",
"(",
"lines",
... | 51.6 | 13.6 |
def functions(self):
"""
A list of functions declared or defined in this module.
"""
return [v for v in self.globals.values()
if isinstance(v, values.Function)] | [
"def",
"functions",
"(",
"self",
")",
":",
"return",
"[",
"v",
"for",
"v",
"in",
"self",
".",
"globals",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"values",
".",
"Function",
")",
"]"
] | 33.833333 | 10.166667 |
def read(self, ncfile, timegrid_data) -> None:
"""Read the data from the given NetCDF file.
The argument `timegrid_data` defines the data period of the
given NetCDF file.
See the general documentation on class |NetCDFVariableFlat|
for some examples.
"""
array = ... | [
"def",
"read",
"(",
"self",
",",
"ncfile",
",",
"timegrid_data",
")",
"->",
"None",
":",
"array",
"=",
"query_array",
"(",
"ncfile",
",",
"self",
".",
"name",
")",
"idxs",
":",
"Tuple",
"[",
"Any",
"]",
"=",
"(",
"slice",
"(",
"None",
")",
",",
"... | 44.321429 | 17.285714 |
def get_bit_num(bit_pattern):
"""Returns the lowest bit num from a given bit pattern. Returns None if no
bits set.
:param bit_pattern: The bit pattern.
:type bit_pattern: int
:returns: int -- the bit number
:returns: None -- no bits set
>>> pifacecommon.core.get_bit_num(0)
None
>>>... | [
"def",
"get_bit_num",
"(",
"bit_pattern",
")",
":",
"if",
"bit_pattern",
"==",
"0",
":",
"return",
"None",
"bit_num",
"=",
"0",
"# assume bit 0",
"while",
"(",
"bit_pattern",
"&",
"1",
")",
"==",
"0",
":",
"bit_pattern",
"=",
"bit_pattern",
">>",
"1",
"b... | 23.321429 | 17.428571 |
def set_params(self, **params):
"""
Set the parameters of this estimator.
Valid parameter keys can be listed with ``get_params()``.
Returns
-------
self
"""
items = self.steps
names, _ = zip(*items)
keys = list(six.iterkeys(params))
... | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"items",
"=",
"self",
".",
"steps",
"names",
",",
"_",
"=",
"zip",
"(",
"*",
"items",
")",
"keys",
"=",
"list",
"(",
"six",
".",
"iterkeys",
"(",
"params",
")",
")",
"for",
"n... | 28.827586 | 17.931034 |
def duration(self):
"""
Calculates '(time_end-time_start)' and return the resulting
'datetime.timedelta' object.
"""
if self.time_end is None or self.time_start is None:
return timedelta(seconds=0)
else:
return self.time_end - self.time_start | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"time_end",
"is",
"None",
"or",
"self",
".",
"time_start",
"is",
"None",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"0",
")",
"else",
":",
"return",
"self",
".",
"time_end",
"-",
"sel... | 34 | 12.222222 |
def suggest(self, utility_function):
"""Most promissing point to probe next"""
if len(self._space) == 0:
return self._space.array_to_params(self._space.random_sample())
# Sklearn's GP throws a large number of warnings at times, but
# we don't really need to see them here.
... | [
"def",
"suggest",
"(",
"self",
",",
"utility_function",
")",
":",
"if",
"len",
"(",
"self",
".",
"_space",
")",
"==",
"0",
":",
"return",
"self",
".",
"_space",
".",
"array_to_params",
"(",
"self",
".",
"_space",
".",
"random_sample",
"(",
")",
")",
... | 37.619048 | 15.47619 |
def forward(self, query, context):
"""
Args:
query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of
queries to query the context.
context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data
ove... | [
"def",
"forward",
"(",
"self",
",",
"query",
",",
"context",
")",
":",
"batch_size",
",",
"output_len",
",",
"dimensions",
"=",
"query",
".",
"size",
"(",
")",
"query_len",
"=",
"context",
".",
"size",
"(",
"1",
")",
"if",
"self",
".",
"attention_type"... | 46.1875 | 25.229167 |
def update_event_types(self):
"""Update event types in event type box."""
self.idx_evt_type.clear()
self.idx_evt_type.setSelectionMode(QAbstractItemView.ExtendedSelection)
event_types = sorted(self.parent.notes.annot.event_types,
key=str.lower)
for t... | [
"def",
"update_event_types",
"(",
"self",
")",
":",
"self",
".",
"idx_evt_type",
".",
"clear",
"(",
")",
"self",
".",
"idx_evt_type",
".",
"setSelectionMode",
"(",
"QAbstractItemView",
".",
"ExtendedSelection",
")",
"event_types",
"=",
"sorted",
"(",
"self",
"... | 41.1 | 14 |
def _get_spec_value(self, form, uid, key, default=''):
"""Returns the value assigned to the passed in key for the analysis
service uid from the passed in form.
If check_floatable is true, will return the passed in default if the
obtained value is not floatable
:param form: form ... | [
"def",
"_get_spec_value",
"(",
"self",
",",
"form",
",",
"uid",
",",
"key",
",",
"default",
"=",
"''",
")",
":",
"if",
"not",
"form",
"or",
"not",
"uid",
":",
"return",
"default",
"values",
"=",
"form",
".",
"get",
"(",
"key",
",",
"None",
")",
"... | 45.15 | 13.85 |
def from_address(text):
"""Convert an IPv4 or IPv6 address in textual form into a Name object whose
value is the reverse-map domain name of the address.
@param text: an IPv4 or IPv6 address in textual form (e.g. '127.0.0.1',
'::1')
@type text: str
@rtype: dns.name.Name object
"""
try:
... | [
"def",
"from_address",
"(",
"text",
")",
":",
"try",
":",
"parts",
"=",
"list",
"(",
"dns",
".",
"ipv6",
".",
"inet_aton",
"(",
"text",
")",
".",
"encode",
"(",
"'hex_codec'",
")",
")",
"origin",
"=",
"ipv6_reverse_domain",
"except",
"Exception",
":",
... | 38.6875 | 17.8125 |
def walk_instructions(self, mapping=identity):
"""Iterate over instructions.
:return: an iterator over :class:`instructions in grid
<InstructionInGrid>`
:param mapping: funcion to map the result
.. code:: python
for pos, c in layout.walk_instructions(lambda i: (i... | [
"def",
"walk_instructions",
"(",
"self",
",",
"mapping",
"=",
"identity",
")",
":",
"instructions",
"=",
"chain",
"(",
"*",
"self",
".",
"walk_rows",
"(",
"lambda",
"row",
":",
"row",
".",
"instructions",
")",
")",
"return",
"map",
"(",
"mapping",
",",
... | 33.8 | 20.733333 |
def get(self, url, data=None):
""" Executes an HTTP GET request for the given URL.
``data`` should be a dictionary of url parameters
"""
response = self.http.get(url,
headers=self.headers,
params=data,
... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"params",
"=",
"data",
",",
"*",
"*",
"self",
".",
"reque... | 39 | 11.2 |
def p_path(self, p):
"""path : additive_path"""
if len(p[1].children) == 1:
p[0] = p[1].children[0]
else:
p[0] = p[1] | [
"def",
"p_path",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
"[",
"1",
"]",
".",
"children",
")",
"==",
"1",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
".",
"children",
"[",
"0",
"]",
"else",
":",
"p",
"[",
"0",
"]",
... | 26.666667 | 12.333333 |
def update(self, ipv4s):
"""
Method to update ipv4's
:param ipv4s: List containing ipv4's desired to updated
:return: None
"""
data = {'ips': ipv4s}
ipv4s_ids = [str(ipv4.get('id')) for ipv4 in ipv4s]
return super(ApiIPv4, self).put('api/v3/ipv4/%s/' %
... | [
"def",
"update",
"(",
"self",
",",
"ipv4s",
")",
":",
"data",
"=",
"{",
"'ips'",
":",
"ipv4s",
"}",
"ipv4s_ids",
"=",
"[",
"str",
"(",
"ipv4",
".",
"get",
"(",
"'id'",
")",
")",
"for",
"ipv4",
"in",
"ipv4s",
"]",
"return",
"super",
"(",
"ApiIPv4"... | 28.769231 | 20.153846 |
def get_type(self):
"""!
@brief Returns algorithm type that corresponds to specified enumeration value.
@return (type) Algorithm type for cluster analysis.
"""
if self == silhouette_ksearch_type.KMEANS:
return kmeans
elif self == silhouette_ksearch_... | [
"def",
"get_type",
"(",
"self",
")",
":",
"if",
"self",
"==",
"silhouette_ksearch_type",
".",
"KMEANS",
":",
"return",
"kmeans",
"elif",
"self",
"==",
"silhouette_ksearch_type",
".",
"KMEDIANS",
":",
"return",
"kmedians",
"elif",
"self",
"==",
"silhouette_ksearc... | 31.6 | 19.133333 |
def _log_likelihood_transit_plus_line(theta, params, model, t, data_flux,
err_flux, priorbounds):
'''
Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
... | [
"def",
"_log_likelihood_transit_plus_line",
"(",
"theta",
",",
"params",
",",
"model",
",",
"t",
",",
"data_flux",
",",
"err_flux",
",",
"priorbounds",
")",
":",
"u",
"=",
"[",
"]",
"for",
"ix",
",",
"key",
"in",
"enumerate",
"(",
"sorted",
"(",
"priorbo... | 27.472727 | 19.690909 |
def delete_composition(self, composition_id):
"""Deletes a ``Composition``.
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition`` to remove
raise: NotFound - ``composition_id`` not found
raise: NullArgument - ``composition_id`` is ``null``
rais... | [
"def",
"delete_composition",
"(",
"self",
",",
"composition_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'repository'",
",",
"collection",
"=",
"'Composition'",
... | 50.44 | 21.4 |
def _to_int(value_str, min_value, rep_digit, field_name, dtarg):
"""
Convert value_str into an integer, replacing right-consecutive
asterisks with rep_digit, and an all-asterisk value with min_value.
field_name and dtarg are passed only for informational purposes.
"""
if... | [
"def",
"_to_int",
"(",
"value_str",
",",
"min_value",
",",
"rep_digit",
",",
"field_name",
",",
"dtarg",
")",
":",
"if",
"'*'",
"in",
"value_str",
":",
"first",
"=",
"value_str",
".",
"index",
"(",
"'*'",
")",
"after",
"=",
"value_str",
".",
"rindex",
... | 49.057143 | 19.628571 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Setting(key)
if key not in Setting._member_map_:
extend_enum(Setting, key, default)
return Setting[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Setting",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Setting",
".",
"_member_map_",
":",
"extend_enum",
"(",
"Setti... | 36.285714 | 7.714286 |
def find_sdk_dir(self):
"""Try to find the MS SDK from the registry.
Return None if failed or the directory does not exist.
"""
if not SCons.Util.can_read_reg:
debug('find_sdk_dir(): can not read registry')
return None
hkey = self.HKEY_FMT % self.hkey_da... | [
"def",
"find_sdk_dir",
"(",
"self",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"can_read_reg",
":",
"debug",
"(",
"'find_sdk_dir(): can not read registry'",
")",
"return",
"None",
"hkey",
"=",
"self",
".",
"HKEY_FMT",
"%",
"self",
".",
"hkey_data",
"d... | 33.066667 | 21.5 |
def _hasReturnValue(self, node):
"""
Determine whether the given method or function has a return statement.
@param node: the node currently checks
"""
returnFound = False
for subnode in node.body:
if type(subnode) == node_classes.Return and subnode.value:
... | [
"def",
"_hasReturnValue",
"(",
"self",
",",
"node",
")",
":",
"returnFound",
"=",
"False",
"for",
"subnode",
"in",
"node",
".",
"body",
":",
"if",
"type",
"(",
"subnode",
")",
"==",
"node_classes",
".",
"Return",
"and",
"subnode",
".",
"value",
":",
"r... | 32.416667 | 15.083333 |
def get_dex_names(self):
"""
Return the names of all DEX files found in the APK.
This method only accounts for "offical" dex files, i.e. all files
in the root directory of the APK named classes.dex or classes[0-9]+.dex
:rtype: a list of str
"""
dexre = re.compile... | [
"def",
"get_dex_names",
"(",
"self",
")",
":",
"dexre",
"=",
"re",
".",
"compile",
"(",
"r\"classes(\\d*).dex\"",
")",
"return",
"filter",
"(",
"lambda",
"x",
":",
"dexre",
".",
"match",
"(",
"x",
")",
",",
"self",
".",
"get_files",
"(",
")",
")"
] | 39.8 | 19 |
def validate_context(self, context):
"""
Checks to see if we're working with a valid lambda context object.
:returns: True if valid, False if not
:rtype: bool
"""
return all(
[
hasattr(context, attr)
for attr in [
... | [
"def",
"validate_context",
"(",
"self",
",",
"context",
")",
":",
"return",
"all",
"(",
"[",
"hasattr",
"(",
"context",
",",
"attr",
")",
"for",
"attr",
"in",
"[",
"\"aws_request_id\"",
",",
"\"function_name\"",
",",
"\"function_version\"",
",",
"\"get_remaini... | 32.181818 | 11.909091 |
async def close(self, *, timeout=None):
"""Close the connection gracefully.
:param float timeout:
Optional timeout value in seconds.
.. versionchanged:: 0.14.0
Added the *timeout* parameter.
"""
try:
if not self.is_closed():
aw... | [
"async",
"def",
"close",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"is_closed",
"(",
")",
":",
"await",
"self",
".",
"_protocol",
".",
"close",
"(",
"timeout",
")",
"except",
"Exception",
":... | 28.833333 | 14.722222 |
def user_create(name, password, email, tenant_id=None,
enabled=True, profile=None, project_id=None, description=None, **connection_args):
'''
Create a user (keystone user-create)
CLI Examples:
.. code-block:: bash
salt '*' keystone.user_create name=jack password=zero email=jac... | [
"def",
"user_create",
"(",
"name",
",",
"password",
",",
"email",
",",
"tenant_id",
"=",
"None",
",",
"enabled",
"=",
"True",
",",
"profile",
"=",
"None",
",",
"project_id",
"=",
"None",
",",
"description",
"=",
"None",
",",
"*",
"*",
"connection_args",
... | 39.766667 | 20.166667 |
def parse(self):
""" Parse the options. """
# Run the parser
opt, arg = self.parser.parse_known_args(self.arguments)
self.opt = opt
self.arg = arg
self.check()
# Enable --all if no particular stat or group selected
opt.all = not any([
getattr(... | [
"def",
"parse",
"(",
"self",
")",
":",
"# Run the parser",
"opt",
",",
"arg",
"=",
"self",
".",
"parser",
".",
"parse_known_args",
"(",
"self",
".",
"arguments",
")",
"self",
".",
"opt",
"=",
"opt",
"self",
".",
"arg",
"=",
"arg",
"self",
".",
"check... | 37 | 17.5 |
def nsorted(to_sort, key=None):
"""Returns a naturally sorted list"""
if key is None:
key_callback = _natural_keys
else:
def key_callback(item):
return _natural_keys(key(item))
return sorted(to_sort, key=key_callback) | [
"def",
"nsorted",
"(",
"to_sort",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"key_callback",
"=",
"_natural_keys",
"else",
":",
"def",
"key_callback",
"(",
"item",
")",
":",
"return",
"_natural_keys",
"(",
"key",
"(",
"item",
")... | 28.222222 | 13.444444 |
def _parse_content_type_header(header):
"""Returns content type and parameters from given header
:param header: string
:return: tuple containing content type and dictionary of
parameters
"""
tokens = header.split(';')
content_type, params = tokens[0].strip(), tokens[1:]
params_dic... | [
"def",
"_parse_content_type_header",
"(",
"header",
")",
":",
"tokens",
"=",
"header",
".",
"split",
"(",
"';'",
")",
"content_type",
",",
"params",
"=",
"tokens",
"[",
"0",
"]",
".",
"strip",
"(",
")",
",",
"tokens",
"[",
"1",
":",
"]",
"params_dict",... | 32.652174 | 15.913043 |
def close_files(self):
"""Close all files with an activated disk flag."""
for name in self:
if getattr(self, '_%s_diskflag' % name):
file_ = getattr(self, '_%s_file' % name)
file_.close() | [
"def",
"close_files",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
":",
"if",
"getattr",
"(",
"self",
",",
"'_%s_diskflag'",
"%",
"name",
")",
":",
"file_",
"=",
"getattr",
"(",
"self",
",",
"'_%s_file'",
"%",
"name",
")",
"file_",
".",
"close... | 40.333333 | 12 |
def qualify(ref, resolvers, defns=Namespace.default):
"""
Get a reference that is I{qualified} by namespace.
@param ref: A referenced schema type name.
@type ref: str
@param resolvers: A list of objects to be used to resolve types.
@type resolvers: [L{sax.element.Element},]
@param defns: An ... | [
"def",
"qualify",
"(",
"ref",
",",
"resolvers",
",",
"defns",
"=",
"Namespace",
".",
"default",
")",
":",
"ns",
"=",
"None",
"p",
",",
"n",
"=",
"splitPrefix",
"(",
"ref",
")",
"if",
"p",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
... | 34.655172 | 14.724138 |
def remove_by_score(self, low, high=None):
"""
Remove elements from the ZSet by their score.
:param low: Lower bound.
:param high: Upper bound.
"""
if high is None:
high = low
return self.database.zremrangebyscore(self.key, low, high) | [
"def",
"remove_by_score",
"(",
"self",
",",
"low",
",",
"high",
"=",
"None",
")",
":",
"if",
"high",
"is",
"None",
":",
"high",
"=",
"low",
"return",
"self",
".",
"database",
".",
"zremrangebyscore",
"(",
"self",
".",
"key",
",",
"low",
",",
"high",
... | 29.4 | 13 |
def run(self, host=None, port=None, debug=None, **options):
"""Runs the application on a local development server. If the
:attr:`debug` flag is set the server will automatically reload
for code changes and show a debugger in case an exception happened.
If you want to run the applicatio... | [
"def",
"run",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"debug",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"from",
"werkzeug",
".",
"serving",
"import",
"run_simple",
"if",
"host",
"is",
"None",
":",
"host",
"=",
... | 47.857143 | 22.053571 |
def _map_hash(self):
"""Compute a map hash based on a combination of map attributes.
- Elevation
- Map name
- Player names, colors, and civilizations
"""
elevation_bytes = bytes([tile.elevation for tile in self._header.map_info.tile])
map_name_bytes = self._map.n... | [
"def",
"_map_hash",
"(",
"self",
")",
":",
"elevation_bytes",
"=",
"bytes",
"(",
"[",
"tile",
".",
"elevation",
"for",
"tile",
"in",
"self",
".",
"_header",
".",
"map_info",
".",
"tile",
"]",
")",
"map_name_bytes",
"=",
"self",
".",
"_map",
".",
"name"... | 48.466667 | 23.933333 |
def is_inexact(arg):
'''
is_inexact(x) yields True if x is a number represented by floating-point data (i.e., either a
non-integer real number or a complex number) and False otherwise.
'''
return (is_inexact(mag(arg)) if is_quantity(arg) else
is_npscalar(u, np.inexact) or is_npvalue(ar... | [
"def",
"is_inexact",
"(",
"arg",
")",
":",
"return",
"(",
"is_inexact",
"(",
"mag",
"(",
"arg",
")",
")",
"if",
"is_quantity",
"(",
"arg",
")",
"else",
"is_npscalar",
"(",
"u",
",",
"np",
".",
"inexact",
")",
"or",
"is_npvalue",
"(",
"arg",
",",
"n... | 47 | 31.571429 |
def dict_of(validate_key, validate_item):
"""Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes
as input to the provided validators validate_key and validate_item, respectively.
:param callable validate_key: the validator function for keys in t... | [
"def",
"dict_of",
"(",
"validate_key",
",",
"validate_item",
")",
":",
"def",
"validate",
"(",
"value",
",",
"should_raise",
"=",
"True",
")",
":",
"validate_type",
"=",
"is_type",
"(",
"dict",
")",
"if",
"not",
"validate_type",
"(",
"value",
",",
"should_... | 41.03125 | 21.0625 |
def get_stacks_payment(state_engine, nameop, state_op_type):
"""
Find out how many tokens were paid for this nameop, if any.
You need to have called state_create_put_preorder() *before* calling this on a NAME_REGISTRATION.
Return {'status': True, 'token_units': ..., 'tokens_paid': ...} on success
R... | [
"def",
"get_stacks_payment",
"(",
"state_engine",
",",
"nameop",
",",
"state_op_type",
")",
":",
"token_units",
"=",
"None",
"tokens_paid",
"=",
"None",
"name",
"=",
"nameop",
"[",
"'name'",
"]",
"token_fee",
"=",
"nameop",
".",
"get",
"(",
"'token_fee'",
",... | 44.591837 | 27.408163 |
def visit_Compare(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s operators and operands as inlined expression."""
# all comparison operators have the same precedence,
# we just take the first one as representative
first_op = node.ops[0]
with self.op_man(fir... | [
"def",
"visit_Compare",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"# all comparison operators have the same precedence,",
"# we just take the first one as representative",
"first_op",
"=",
"node",
".",
... | 56.363636 | 16 |
def write_weight_map(self, model_name):
"""Save the counts model map to a FITS file.
Parameters
----------
model_name : str
String that will be append to the name of the output file.
Returns
-------
"""
maps = [c.write_weight_map(model_name)... | [
"def",
"write_weight_map",
"(",
"self",
",",
"model_name",
")",
":",
"maps",
"=",
"[",
"c",
".",
"write_weight_map",
"(",
"model_name",
")",
"for",
"c",
"in",
"self",
".",
"components",
"]",
"outfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
... | 29.782609 | 21.565217 |
def all(self, data={}, **kwargs):
""""
Fetch all Order entities
Returns:
Dictionary of Order data
"""
return super(Order, self).all(data, **kwargs) | [
"def",
"all",
"(",
"self",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Order",
",",
"self",
")",
".",
"all",
"(",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 24.125 | 12 |
def observable_timestamp_compare(instance):
"""Ensure cyber observable timestamp properties with a comparison
requirement are valid.
"""
for key, obj in instance['objects'].items():
compares = enums.TIMESTAMP_COMPARE_OBSERVABLE.get(obj.get('type', ''), [])
print(compares)
for fir... | [
"def",
"observable_timestamp_compare",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"compares",
"=",
"enums",
".",
"TIMESTAMP_COMPARE_OBSERVABLE",
".",
"get",
"(",
"obj",
".",
"g... | 46.5 | 15.625 |
def prepare_image_question_encoder(image_feat, question, hparams):
"""Prepare encoder.
Args:
image_feat: a Tensor.
question: a Tensor.
hparams: run hyperparameters
Returns:
encoder_input: a Tensor, bottom of encoder stack
encoder_self_attention_bias: a bias tensor for use in encoder self-att... | [
"def",
"prepare_image_question_encoder",
"(",
"image_feat",
",",
"question",
",",
"hparams",
")",
":",
"encoder_input",
"=",
"tf",
".",
"concat",
"(",
"[",
"image_feat",
",",
"question",
"]",
",",
"axis",
"=",
"1",
")",
"encoder_padding",
"=",
"common_attentio... | 36.1 | 20.1 |
def connect_external_kernel(self, shellwidget):
"""
Connect an external kernel to the Variable Explorer and Help, if
it is a Spyder kernel.
"""
sw = shellwidget
kc = shellwidget.kernel_client
if self.main.help is not None:
self.main.help.set_sh... | [
"def",
"connect_external_kernel",
"(",
"self",
",",
"shellwidget",
")",
":",
"sw",
"=",
"shellwidget",
"kc",
"=",
"shellwidget",
".",
"kernel_client",
"if",
"self",
".",
"main",
".",
"help",
"is",
"not",
"None",
":",
"self",
".",
"main",
".",
"help",
"."... | 42.4 | 9.6 |
def _assert_path_is_rw(self):
"""
Make sure, that `self.path` exists, is directory a readable/writeable.
Raises:
IOError: In case that any of the assumptions failed.
ValueError: In case that `self.path` is not set.
"""
if not self.path:
raise ... | [
"def",
"_assert_path_is_rw",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"path",
":",
"raise",
"ValueError",
"(",
"\"`path` argument must be set!\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"raise",
"I... | 34.571429 | 21.333333 |
def parse(bin_payload, block_height):
"""
Interpret a block's nulldata back into a name. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload.
The name will be directly represented by the bytes given.
This works for registrations and renewals.
Record format (pre... | [
"def",
"parse",
"(",
"bin_payload",
",",
"block_height",
")",
":",
"# pre F-day 2017: bin_payload is the name.",
"# post F-day 2017: bin_payload is the name and possibly the update hash",
"# STACKs phase 1: bin_payload possibly has a token burn attached to the end",
"epoch_features",
"=",
... | 42.301075 | 28.451613 |
def _set_l2_spf_timer(self, v, load=False):
"""
Setter method for l2_spf_timer, mapped from YANG variable /isis_state/router_isis_config/l2_spf_timer (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_l2_spf_timer is considered as a private
method. Backends ... | [
"def",
"_set_l2_spf_timer",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 75.666667 | 37 |
def get_home(self):
'''get home location'''
if 'HOME_POSITION' in self.master.messages:
h = self.master.messages['HOME_POSITION']
return mavutil.mavlink.MAVLink_mission_item_message(self.target_system,
self.target_co... | [
"def",
"get_home",
"(",
"self",
")",
":",
"if",
"'HOME_POSITION'",
"in",
"self",
".",
"master",
".",
"messages",
":",
"h",
"=",
"self",
".",
"master",
".",
"messages",
"[",
"'HOME_POSITION'",
"]",
"return",
"mavutil",
".",
"mavlink",
".",
"MAVLink_mission_... | 60.857143 | 28.857143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.