text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def upload_metadata(directory, create_csv='', review='',
max_size='128m', verbose=False, debug=False):
"""
Draft or review metadata files for uploading files to Open Humans.
The target directory should either represent files for a single member (no
subdirectories), or contain a subdi... | [
"def",
"upload_metadata",
"(",
"directory",
",",
"create_csv",
"=",
"''",
",",
"review",
"=",
"''",
",",
"max_size",
"=",
"'128m'",
",",
"verbose",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"set_log_level",
"(",
"debug",
",",
"verbose",
")",
... | 44.40625 | 0.000689 |
def find_all_output_in_range(self, ifo, currSeg, useSplitLists=False):
"""
Return all files that overlap the specified segment.
"""
if not useSplitLists:
# Slower, but simpler method
outFiles = [i for i in self if ifo in i.ifo_list]
outFiles = [i for i... | [
"def",
"find_all_output_in_range",
"(",
"self",
",",
"ifo",
",",
"currSeg",
",",
"useSplitLists",
"=",
"False",
")",
":",
"if",
"not",
"useSplitLists",
":",
"# Slower, but simpler method",
"outFiles",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
"if",
"ifo",
"in... | 48.147059 | 0.01018 |
def decode(self, encoded_packet):
"""Decode a transmitted package."""
b64 = False
if not isinstance(encoded_packet, binary_types):
encoded_packet = encoded_packet.encode('utf-8')
elif not isinstance(encoded_packet, bytes):
encoded_packet = bytes(encoded_packet)
... | [
"def",
"decode",
"(",
"self",
",",
"encoded_packet",
")",
":",
"b64",
"=",
"False",
"if",
"not",
"isinstance",
"(",
"encoded_packet",
",",
"binary_types",
")",
":",
"encoded_packet",
"=",
"encoded_packet",
".",
"encode",
"(",
"'utf-8'",
")",
"elif",
"not",
... | 42.216216 | 0.001252 |
def attempt_advance(self, blocksize, timeout=10):
""" Attempt to advance the frame buffer. Retry upon failure, except
if the frame file is beyond the timeout limit.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
... | [
"def",
"attempt_advance",
"(",
"self",
",",
"blocksize",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"self",
".",
"force_update_cache",
":",
"self",
".",
"update_cache",
"(",
")",
"try",
":",
"if",
"self",
".",
"increment_update_cache",
":",
"self",
".",
... | 36.114286 | 0.002311 |
def mutating_join(*args, **kwargs):
""" generic function for mutating dplyr-style joins
"""
# candidate for improvement
left = args[0]
right = args[1]
if 'by' in kwargs:
left_cols, right_cols = get_join_cols(kwargs['by'])
else:
left_cols, right_cols = None, None
if 'suffixes' in kwargs:
dsuf... | [
"def",
"mutating_join",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# candidate for improvement",
"left",
"=",
"args",
"[",
"0",
"]",
"right",
"=",
"args",
"[",
"1",
"]",
"if",
"'by'",
"in",
"kwargs",
":",
"left_cols",
",",
"right_cols",
"=",... | 34.478261 | 0.017178 |
def _MarkerFactory(marker_code, stream, offset):
"""
Return |_Marker| or subclass instance appropriate for marker at *offset*
in *stream* having *marker_code*.
"""
if marker_code == JPEG_MARKER_CODE.APP0:
marker_cls = _App0Marker
elif marker_code == JPEG_MARKER_CODE.APP1:
marker_... | [
"def",
"_MarkerFactory",
"(",
"marker_code",
",",
"stream",
",",
"offset",
")",
":",
"if",
"marker_code",
"==",
"JPEG_MARKER_CODE",
".",
"APP0",
":",
"marker_cls",
"=",
"_App0Marker",
"elif",
"marker_code",
"==",
"JPEG_MARKER_CODE",
".",
"APP1",
":",
"marker_cls... | 36.928571 | 0.001887 |
def size_of_varint_2(value):
""" Number of bytes needed to encode an integer in variable-length format.
"""
value = (value << 1) ^ (value >> 63)
if value <= 0x7f:
return 1
if value <= 0x3fff:
return 2
if value <= 0x1fffff:
return 3
if value <= 0xfffffff:
retur... | [
"def",
"size_of_varint_2",
"(",
"value",
")",
":",
"value",
"=",
"(",
"value",
"<<",
"1",
")",
"^",
"(",
"value",
">>",
"63",
")",
"if",
"value",
"<=",
"0x7f",
":",
"return",
"1",
"if",
"value",
"<=",
"0x3fff",
":",
"return",
"2",
"if",
"value",
... | 24.478261 | 0.001709 |
def set_path(self, path, val):
"""
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format.
"""
path = tuple(path.split('.')) if isinstance(path , str) else tuple(path)
disallowed = [p for p in path if not type(self)._... | [
"def",
"set_path",
"(",
"self",
",",
"path",
",",
"val",
")",
":",
"path",
"=",
"tuple",
"(",
"path",
".",
"split",
"(",
"'.'",
")",
")",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
"else",
"tuple",
"(",
"path",
")",
"disallowed",
"=",
"[",... | 44.0625 | 0.008333 |
def full_name(self):
"""
str: func_name(type1,type2)
Return the function signature without the return values
"""
name, parameters, _ = self.signature
return name+'('+','.join(parameters)+')' | [
"def",
"full_name",
"(",
"self",
")",
":",
"name",
",",
"parameters",
",",
"_",
"=",
"self",
".",
"signature",
"return",
"name",
"+",
"'('",
"+",
"','",
".",
"join",
"(",
"parameters",
")",
"+",
"')'"
] | 34.285714 | 0.00813 |
def get(self, block=True, timeout=None):
"""Get item from underlying queue."""
return self._queue.get(block, timeout) | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_queue",
".",
"get",
"(",
"block",
",",
"timeout",
")"
] | 43.666667 | 0.015038 |
def argument_count(self):
"""
Uses the command line arguments to fill the count function and call it.
"""
arguments, _ = self.argparser.parse_known_args()
return self.count(**vars(arguments)) | [
"def",
"argument_count",
"(",
"self",
")",
":",
"arguments",
",",
"_",
"=",
"self",
".",
"argparser",
".",
"parse_known_args",
"(",
")",
"return",
"self",
".",
"count",
"(",
"*",
"*",
"vars",
"(",
"arguments",
")",
")"
] | 38.333333 | 0.012766 |
def save_function(self, obj, name=None):
""" Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately.
"""
try:
should_special_case = ob... | [
"def",
"save_function",
"(",
"self",
",",
"obj",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"should_special_case",
"=",
"obj",
"in",
"_BUILTIN_TYPE_CONSTRUCTORS",
"except",
"TypeError",
":",
"# Methods of builtin types aren't hashable in python 2.",
"should_special... | 41.393617 | 0.001004 |
def represent_as_string(iterable):
"""
Represent a number in the form of a string.
(8, 6, 8, '.', 0, 15) -> "868.0F"
Args:
iterable - Number represented as an iterable container of digits.
Returns:
Number represented as a string of digits.
>>> represent_as_string((8, ... | [
"def",
"represent_as_string",
"(",
"iterable",
")",
":",
"keep",
"=",
"(",
"\".\"",
",",
"\"[\"",
",",
"\"]\"",
")",
"return",
"\"\"",
".",
"join",
"(",
"tuple",
"(",
"int_to_str_digit",
"(",
"i",
")",
"if",
"i",
"not",
"in",
"keep",
"else",
"i",
"fo... | 30.25 | 0.002004 |
def _set_initial(self, C_in, scale_in):
r"""Set the initial values for parameters and Wilson coefficients at
the scale `scale_in`."""
self.C_in = C_in
self.scale_in = scale_in | [
"def",
"_set_initial",
"(",
"self",
",",
"C_in",
",",
"scale_in",
")",
":",
"self",
".",
"C_in",
"=",
"C_in",
"self",
".",
"scale_in",
"=",
"scale_in"
] | 40.6 | 0.009662 |
def distance(line, point):
"""
infinite line to point or line to line distance
is point is given as line - use middle point of that liune
"""
x0, y0, x1, y1 = line
try:
p1, p2 = point
except ValueError:
# line is given instead of point
p1, p2 = middle(point)
n1 = ... | [
"def",
"distance",
"(",
"line",
",",
"point",
")",
":",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"=",
"line",
"try",
":",
"p1",
",",
"p2",
"=",
"point",
"except",
"ValueError",
":",
"# line is given instead of point",
"p1",
",",
"p2",
"=",
"middle",
"(... | 28 | 0.002304 |
def htseq_counts_chart (self):
""" Make the HTSeq Count assignment rates plot """
cats = OrderedDict()
cats['assigned'] = { 'name': 'Assigned' }
cats['ambiguous'] = { 'name': 'Ambiguous' }
cats['alignment_not_unique'] = { 'name': 'Alignment Not Unique' }
cats['no... | [
"def",
"htseq_counts_chart",
"(",
"self",
")",
":",
"cats",
"=",
"OrderedDict",
"(",
")",
"cats",
"[",
"'assigned'",
"]",
"=",
"{",
"'name'",
":",
"'Assigned'",
"}",
"cats",
"[",
"'ambiguous'",
"]",
"=",
"{",
"'name'",
":",
"'Ambiguous'",
"}",
"cats",
... | 45.058824 | 0.024297 |
def sorted_bfs_edges(G, source=None):
"""Produce edges in a breadth-first-search starting at source.
Neighbors appear in the order a linguist would expect in a syntax tree.
The result will only contain edges that express a dominance or spanning
relation, i.e. edges expressing pointing or precedence rel... | [
"def",
"sorted_bfs_edges",
"(",
"G",
",",
"source",
"=",
"None",
")",
":",
"if",
"source",
"is",
"None",
":",
"source",
"=",
"G",
".",
"root",
"xpos",
"=",
"horizontal_positions",
"(",
"G",
",",
"source",
")",
"visited",
"=",
"set",
"(",
"[",
"source... | 33.487805 | 0.000708 |
def compute_vest_stat(vest_dict, ref_aa, somatic_aa, codon_pos,
stat_func=np.mean,
default_val=0.0):
"""Compute missense VEST score statistic.
Note: non-missense mutations are intentially not filtered out and will take
a default value of zero.
Parameters
... | [
"def",
"compute_vest_stat",
"(",
"vest_dict",
",",
"ref_aa",
",",
"somatic_aa",
",",
"codon_pos",
",",
"stat_func",
"=",
"np",
".",
"mean",
",",
"default_val",
"=",
"0.0",
")",
":",
"# return default value if VEST scores are missing",
"if",
"vest_dict",
"is",
"Non... | 28.761905 | 0.000801 |
def estimate_cpd(self, node):
"""
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
Returns
-------
CPD: Tabula... | [
"def",
"estimate_cpd",
"(",
"self",
",",
"node",
")",
":",
"state_counts",
"=",
"self",
".",
"state_counts",
"(",
"node",
")",
"# if a column contains only `0`s (no states observed for some configuration",
"# of parents' states) fill that column uniformly instead",
"state_counts"... | 37.410714 | 0.002326 |
def update(self,dt):
"""
Should be called regularly to move the actor.
This method does nothing if the :py:attr:`enabled` property is set to False.
This method is called automatically and should not be called manually.
"""
if not self.enabled:
... | [
"def",
"update",
"(",
"self",
",",
"dt",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"return",
"dy",
"=",
"self",
".",
"speed",
"*",
"dt",
"*",
"self",
".",
"move",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"actor",
".",
"_pos",
"new... | 31.857143 | 0.021786 |
def create_entry(i):
"""
Input: {
path - path where to create an entry
(data_uoa) - data UOA
(data_uid) - if uoa is an alias, we can force data UID
(force) - if 'yes', force creation even if directory already exists
}
Output: {
... | [
"def",
"create_entry",
"(",
"i",
")",
":",
"p0",
"=",
"i",
".",
"get",
"(",
"'path'",
",",
"''",
")",
"d",
"=",
"i",
".",
"get",
"(",
"'data_uoa'",
",",
"''",
")",
"di",
"=",
"i",
".",
"get",
"(",
"'data_uid'",
",",
"''",
")",
"xforce",
"=",
... | 27.389313 | 0.04411 |
def CDQ(cpu):
"""
EDX:EAX = sign-extend of EAX
"""
cpu.EDX = Operators.EXTRACT(Operators.SEXTEND(cpu.EAX, 32, 64), 32, 32) | [
"def",
"CDQ",
"(",
"cpu",
")",
":",
"cpu",
".",
"EDX",
"=",
"Operators",
".",
"EXTRACT",
"(",
"Operators",
".",
"SEXTEND",
"(",
"cpu",
".",
"EAX",
",",
"32",
",",
"64",
")",
",",
"32",
",",
"32",
")"
] | 30 | 0.012987 |
def do_init_cached_fields(self):
"""
Initialize each fields of the fields_desc dict, or use the cached
fields information
"""
cls_name = self.__class__
# Build the fields information
if Packet.class_default_fields.get(cls_name, None) is None:
self.pr... | [
"def",
"do_init_cached_fields",
"(",
"self",
")",
":",
"cls_name",
"=",
"self",
".",
"__class__",
"# Build the fields information",
"if",
"Packet",
".",
"class_default_fields",
".",
"get",
"(",
"cls_name",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"pre... | 39.818182 | 0.00223 |
def ext_import(soname, module_subpath=""):
"""
Loads a turicreate toolkit module (a shared library) into the
tc.extensions namespace.
Toolkit module created via SDK can either be directly imported,
e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import("example.so")``.
Use `... | [
"def",
"ext_import",
"(",
"soname",
",",
"module_subpath",
"=",
"\"\"",
")",
":",
"unity",
"=",
"_get_unity",
"(",
")",
"import",
"os",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"soname",
")",
":",
"soname",
"=",
"os",
".",
"path",
".",
"abspath",... | 34.071429 | 0.001019 |
def fft_convolve(in1, in2, conv_device="cpu", conv_mode="linear", store_on_gpu=False):
"""
This function determines the convolution of two inputs using the FFT. Contains an implementation for both CPU
and GPU.
INPUTS:
in1 (no default): Array containing one set of data, possibl... | [
"def",
"fft_convolve",
"(",
"in1",
",",
"in2",
",",
"conv_device",
"=",
"\"cpu\"",
",",
"conv_mode",
"=",
"\"linear\"",
",",
"store_on_gpu",
"=",
"False",
")",
":",
"# NOTE: Circular convolution assumes a periodic repetition of the input. This can cause edge effects. Linear",... | 37.464286 | 0.00836 |
def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if... | [
"def",
"http_auth_required",
"(",
"realm",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_http_auth",
"(",
")",
":",
"return",
"f... | 33.727273 | 0.001311 |
def build_access_required(function_or_param_name):
"""Decorator ensures user has access to the build ID in the request.
May be used in two ways:
@build_access_required
def my_func(build):
...
@build_access_required('custom_build_id_param')
def my_func(build):
... | [
"def",
"build_access_required",
"(",
"function_or_param_name",
")",
":",
"def",
"get_wrapper",
"(",
"param_name",
",",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | 32.166667 | 0.001006 |
def render(self, compress=False):
"""Return a rendered representation of the color. If `compress` is
true, the shortest possible representation is used; otherwise, named
colors are rendered as names and all others are rendered as hex (or
with the rgba function).
"""
if ... | [
"def",
"render",
"(",
"self",
",",
"compress",
"=",
"False",
")",
":",
"if",
"not",
"compress",
"and",
"self",
".",
"original_literal",
":",
"return",
"self",
".",
"original_literal",
"candidates",
"=",
"[",
"]",
"# TODO this assumes CSS resolution is 8-bit per ch... | 34.522727 | 0.001921 |
def file_exists(self,
filename,
directory=False,
note=None,
loglevel=logging.DEBUG):
"""Return True if file exists on the target host, else False
@param filename: Filename to determine the existence of.
@param directory: Indicate that the fil... | [
"def",
"file_exists",
"(",
"self",
",",
"filename",
",",
"directory",
"=",
"False",
",",
"note",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"shutit",
".",
"handle_note",
"(",
"note",
",",... | 39.297297 | 0.034899 |
def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes,
**kwargs):
"""A block of separable convolutions."""
return conv_block_internal(separable_conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | [
"def",
"separable_conv_block",
"(",
"inputs",
",",
"filters",
",",
"dilation_rates_and_kernel_sizes",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"conv_block_internal",
"(",
"separable_conv",
",",
"inputs",
",",
"filters",
",",
"dilation_rates_and_kernel_sizes",
",",... | 56.6 | 0.010453 |
def tuple_to_qfont(tup):
"""
Create a QFont from tuple:
(family [string], size [int], italic [bool], bold [bool])
"""
if not isinstance(tup, tuple) or len(tup) != 4 \
or not is_text_string(tup[0]) \
or not isinstance(tup[1], int) \
or not isinstance(tup[2], bool) \
or... | [
"def",
"tuple_to_qfont",
"(",
"tup",
")",
":",
"if",
"not",
"isinstance",
"(",
"tup",
",",
"tuple",
")",
"or",
"len",
"(",
"tup",
")",
"!=",
"4",
"or",
"not",
"is_text_string",
"(",
"tup",
"[",
"0",
"]",
")",
"or",
"not",
"isinstance",
"(",
"tup",
... | 29.444444 | 0.001828 |
def get(self, session, **kwargs):
'''taobao.fenxiao.cooperation.get 获取供应商的合作关系信息
获取供应商的合作关系信息'''
request = TOPRequest('taobao.fenxiao.cooperation.get')
for k, v in kwargs.iteritems():
if k not in ('status', 'start_date', 'end_date', 'trade_type', 'page_no', 'page_siz... | [
"def",
"get",
"(",
"self",
",",
"session",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.cooperation.get'",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"... | 52.6 | 0.018692 |
def page(self, course, errors=None, saved=False):
""" Get all data and display the page """
return self.template_helper.get_renderer().course_admin.settings(course, errors, saved) | [
"def",
"page",
"(",
"self",
",",
"course",
",",
"errors",
"=",
"None",
",",
"saved",
"=",
"False",
")",
":",
"return",
"self",
".",
"template_helper",
".",
"get_renderer",
"(",
")",
".",
"course_admin",
".",
"settings",
"(",
"course",
",",
"errors",
",... | 64.333333 | 0.015385 |
def open(self):
"""initialize visit variables"""
self.stats = self.linter.add_stats()
self._returns = []
self._branches = defaultdict(int)
self._stmts = [] | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"stats",
"=",
"self",
".",
"linter",
".",
"add_stats",
"(",
")",
"self",
".",
"_returns",
"=",
"[",
"]",
"self",
".",
"_branches",
"=",
"defaultdict",
"(",
"int",
")",
"self",
".",
"_stmts",
"=",
... | 31.666667 | 0.010256 |
def check_ns_run_threads(run):
"""Check thread labels and thread_min_max have expected properties.
Parameters
----------
run: dict
Nested sampling run to check.
Raises
------
AssertionError
If run does not have expected properties.
"""
assert run['thread_labels'].dt... | [
"def",
"check_ns_run_threads",
"(",
"run",
")",
":",
"assert",
"run",
"[",
"'thread_labels'",
"]",
".",
"dtype",
"==",
"int",
"uniq_th",
"=",
"np",
".",
"unique",
"(",
"run",
"[",
"'thread_labels'",
"]",
")",
"assert",
"np",
".",
"array_equal",
"(",
"np"... | 41.03125 | 0.000744 |
def update(gandi, address, dest_add, dest_del):
"""Update a domain mail forward."""
source, domain = address
if not dest_add and not dest_del:
gandi.echo('Nothing to update: you must provide destinations to '
'update, use --dest-add/-a or -dest-del/-d parameters.')
return... | [
"def",
"update",
"(",
"gandi",
",",
"address",
",",
"dest_add",
",",
"dest_del",
")",
":",
"source",
",",
"domain",
"=",
"address",
"if",
"not",
"dest_add",
"and",
"not",
"dest_del",
":",
"gandi",
".",
"echo",
"(",
"'Nothing to update: you must provide destina... | 33.25 | 0.002439 |
def _augment_book(self, uuid, event):
"""
Checks if the newly created object is a book and only has an ISBN.
If so, tries to fetch the book data off the internet.
:param uuid: uuid of book to augment
:param client: requesting client
"""
try:
if not is... | [
"def",
"_augment_book",
"(",
"self",
",",
"uuid",
",",
"event",
")",
":",
"try",
":",
"if",
"not",
"isbnmeta",
":",
"self",
".",
"log",
"(",
"\"No isbntools found! Install it to get full \"",
"\"functionality!\"",
",",
"lvl",
"=",
"warn",
")",
"return",
"new_b... | 40.506667 | 0.000964 |
def Unlock(fd, path):
"""Release the lock on the file.
Args:
fd: int, the file descriptor of the file to unlock.
path: string, the name of the file to lock.
Raises:
IOError, raised from flock while attempting to release a file lock.
"""
try:
fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)
e... | [
"def",
"Unlock",
"(",
"fd",
",",
"path",
")",
":",
"try",
":",
"fcntl",
".",
"flock",
"(",
"fd",
",",
"fcntl",
".",
"LOCK_UN",
"|",
"fcntl",
".",
"LOCK_NB",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
... | 30.529412 | 0.013084 |
def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -config file path:
objParser.add_argument('-config', required=True,
metavar='/path/to/config.csv',
... | [
"def",
"get_arg_parse",
"(",
")",
":",
"# Create parser object:",
"objParser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# Add argument to namespace -config file path:",
"objParser",
".",
"add_argument",
"(",
"'-config'",
",",
"required",
"=",
"True",
",",
"m... | 44.035714 | 0.000397 |
def pidfile(self):
"""Get the absolute path of the pidfile."""
return os.path.abspath(
os.path.expandvars(
os.path.expanduser(
self._pidfile,
),
),
) | [
"def",
"pidfile",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"_pidfile",
",",
")",
",",
")",
",",
")"
] | 26.777778 | 0.008032 |
def xrify_tuples(self, tup):
"""Make xarray.DataArray from tuple."""
return xr.DataArray(tup,
dims=['bands'],
coords={'bands': self.data['bands']}) | [
"def",
"xrify_tuples",
"(",
"self",
",",
"tup",
")",
":",
"return",
"xr",
".",
"DataArray",
"(",
"tup",
",",
"dims",
"=",
"[",
"'bands'",
"]",
",",
"coords",
"=",
"{",
"'bands'",
":",
"self",
".",
"data",
"[",
"'bands'",
"]",
"}",
")"
] | 43 | 0.009132 |
def winddir_text(pts):
"Convert wind direction from 0..15 to compass point text"
global _winddir_text_array
if pts is None:
return None
if not isinstance(pts, int):
pts = int(pts + 0.5) % 16
if not _winddir_text_array:
_ = pywws.localisation.translation.ugettext
_wind... | [
"def",
"winddir_text",
"(",
"pts",
")",
":",
"global",
"_winddir_text_array",
"if",
"pts",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"pts",
",",
"int",
")",
":",
"pts",
"=",
"int",
"(",
"pts",
"+",
"0.5",
")",
"%",
"16",
... | 36.5625 | 0.001667 |
def comments(self, limit=None):
"""GETs user's comments. Calls :meth:`narwal.Reddit.user_comments`.
:param limit: max number of comments to get
"""
return self._reddit.user_comments(self.name, limit=limit) | [
"def",
"comments",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"_reddit",
".",
"user_comments",
"(",
"self",
".",
"name",
",",
"limit",
"=",
"limit",
")"
] | 40.333333 | 0.012146 |
def api_url(self):
'''return the api url of this request'''
return pathjoin(Request.path, self.id, url=self.bin.api_url) | [
"def",
"api_url",
"(",
"self",
")",
":",
"return",
"pathjoin",
"(",
"Request",
".",
"path",
",",
"self",
".",
"id",
",",
"url",
"=",
"self",
".",
"bin",
".",
"api_url",
")"
] | 44.666667 | 0.014706 |
def visit_addresses(frame, return_addresses):
"""
Visits all of the addresses, returns a new dict
which contains just the addressed elements
Parameters
----------
frame
return_addresses: a dictionary,
keys will be column names of the resulting dataframe, and are what the
us... | [
"def",
"visit_addresses",
"(",
"frame",
",",
"return_addresses",
")",
":",
"outdict",
"=",
"dict",
"(",
")",
"for",
"real_name",
",",
"(",
"pyname",
",",
"address",
")",
"in",
"return_addresses",
".",
"items",
"(",
")",
":",
"if",
"address",
":",
"xrval"... | 28.6875 | 0.002107 |
def _get_section_name(cls, parser):
"""Parse options from relevant section."""
for section_name in cls.POSSIBLE_SECTION_NAMES:
if parser.has_section(section_name):
return section_name
return None | [
"def",
"_get_section_name",
"(",
"cls",
",",
"parser",
")",
":",
"for",
"section_name",
"in",
"cls",
".",
"POSSIBLE_SECTION_NAMES",
":",
"if",
"parser",
".",
"has_section",
"(",
"section_name",
")",
":",
"return",
"section_name",
"return",
"None"
] | 34.571429 | 0.008065 |
def show_driver(devname):
'''
Queries the specified network device for associated driver information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_driver <devname>
'''
try:
module = ethtool.get_module(devname)
except IOError:
log.error('Driver informatio... | [
"def",
"show_driver",
"(",
"devname",
")",
":",
"try",
":",
"module",
"=",
"ethtool",
".",
"get_module",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Driver information not implemented on %s'",
",",
"devname",
")",
"return",
"'Not... | 21.448276 | 0.001538 |
def create_application_configuration(self, name, properties, description=None):
"""Create an application configuration.
Args:
name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a
.. versionadded 1.12
"... | [
"def",
"create_application_configuration",
"(",
"self",
",",
"name",
",",
"properties",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'applicationConfigurations'",
")",
":",
"raise",
"NotImplementedError",
"(",
")",
"cv",
... | 43.411765 | 0.009284 |
def cache_id(service, name, sub_resource=None, resource_id=None,
invalidate=False, region=None, key=None, keyid=None,
profile=None):
'''
Cache, invalidate, or retrieve an AWS resource id keyed by name.
.. code-block:: python
__utils__['boto.cache_id']('ec2', 'myinstance',... | [
"def",
"cache_id",
"(",
"service",
",",
"name",
",",
"sub_resource",
"=",
"None",
",",
"resource_id",
"=",
"None",
",",
"invalidate",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"... | 31.861111 | 0.001692 |
def register(cls, use_admin=True):
"""Register with the API a :class:`sandman.model.Model` class and
associated endpoint.
:param cls: User-defined class derived from :class:`sandman.model.Model` to
be registered with the endpoint returned by :func:`endpoint()`
:type cls: :class:`sandman... | [
"def",
"register",
"(",
"cls",
",",
"use_admin",
"=",
"True",
")",
":",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"if",
"getattr",
"(",
"current_app",
",",
"'class_references'",
",",
"None",
")",
"is",
"None",
":",
"current_app",
".",
"class_refe... | 38.368421 | 0.001339 |
def _Triple(S):
"""Procedure to calculate the triple point pressure and temperature for
seawater
Parameters
----------
S : float
Salinity, [kg/kg]
Returns
-------
prop : dict
Dictionary with the triple point properties:
* Tt: Triple point temperature, [K]
... | [
"def",
"_Triple",
"(",
"S",
")",
":",
"def",
"f",
"(",
"parr",
")",
":",
"T",
",",
"P",
"=",
"parr",
"pw",
"=",
"_Region1",
"(",
"T",
",",
"P",
")",
"gw",
"=",
"pw",
"[",
"\"h\"",
"]",
"-",
"T",
"*",
"pw",
"[",
"\"s\"",
"]",
"pv",
"=",
... | 22.487805 | 0.00104 |
def gradient_angle(self):
"""Angle in float degrees of line of a linear gradient.
Read/Write. May be |None|, indicating the angle is inherited from the
style hierarchy. An angle of 0.0 corresponds to a left-to-right
gradient. Increasing angles represent clockwise rotation of the line,
... | [
"def",
"gradient_angle",
"(",
"self",
")",
":",
"# ---case 1: gradient path is explicit, but not linear---",
"path",
"=",
"self",
".",
"_gradFill",
".",
"path",
"if",
"path",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'not a linear gradient'",
")",
"# --... | 44.225806 | 0.001428 |
def _activate(self):
"""ShuffledMux's activate is similar to StochasticMux,
but there is no 'n_active', since all the streams are always available.
"""
self.streams_ = [None] * self.n_streams
# Weights of the active streams.
# Once a stream is exhausted, it is set to 0.
... | [
"def",
"_activate",
"(",
"self",
")",
":",
"self",
".",
"streams_",
"=",
"[",
"None",
"]",
"*",
"self",
".",
"n_streams",
"# Weights of the active streams.",
"# Once a stream is exhausted, it is set to 0.",
"# Upon activation, this is just a copy of self.weights.",
"self",
... | 41.789474 | 0.002463 |
def _clean(self):
"""Run by housekeeper thread"""
now = time.time()
for jwt in self.jwts.keys():
if (now - self.jwts[jwt]) > (self.age * 2):
del self.jwts[jwt] | [
"def",
"_clean",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"jwt",
"in",
"self",
".",
"jwts",
".",
"keys",
"(",
")",
":",
"if",
"(",
"now",
"-",
"self",
".",
"jwts",
"[",
"jwt",
"]",
")",
">",
"(",
"self",
".",... | 34.333333 | 0.009479 |
def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remo... | [
"def",
"disconnect_handler",
"(",
"remote",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"return",
"current_app",
".",
"login_manager",
".",
"unauthorized",
"(",
")",
"with",
"db",
".",
"se... | 33.652174 | 0.001256 |
def _set_error_handler_callbacks(self, app):
"""
Sets the error handler callbacks used by this extension
"""
@app.errorhandler(NoAuthorizationError)
def handle_auth_error(e):
return self._unauthorized_callback(str(e))
@app.errorhandler(CSRFError)
def ... | [
"def",
"_set_error_handler_callbacks",
"(",
"self",
",",
"app",
")",
":",
"@",
"app",
".",
"errorhandler",
"(",
"NoAuthorizationError",
")",
"def",
"handle_auth_error",
"(",
"e",
")",
":",
"return",
"self",
".",
"_unauthorized_callback",
"(",
"str",
"(",
"e",
... | 38.390625 | 0.001587 |
def main():
"""Define the CLI inteface/commands."""
arguments = docopt(__doc__)
cfg_filename = pkg_resources.resource_filename(
'knowledge_base',
'config/virtuoso.ini'
)
kb = KnowledgeBase(cfg_filename)
# the user has issued a `find` command
if arguments["find"]:
sea... | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"docopt",
"(",
"__doc__",
")",
"cfg_filename",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"'knowledge_base'",
",",
"'config/virtuoso.ini'",
")",
"kb",
"=",
"KnowledgeBase",
"(",
"cfg_filename",
")",
"# th... | 29.736842 | 0.001713 |
def _assign_clusters(self):
"""Assign the samples to the closest centroids to create clusters
"""
self.clusters = np.array([self._closest_centroid(x) for x in self._X]) | [
"def",
"_assign_clusters",
"(",
"self",
")",
":",
"self",
".",
"clusters",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"_closest_centroid",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_X",
"]",
")"
] | 47.25 | 0.010417 |
def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPDate()
if "defaultValue" in j:
v.value = j['defaultValue']
else:
v.value = j['value']
if 'paramName' in j:
v.paramName = j['paramName']
... | [
"def",
"fromJSON",
"(",
"value",
")",
":",
"j",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"v",
"=",
"GPDate",
"(",
")",
"if",
"\"defaultValue\"",
"in",
"j",
":",
"v",
".",
"value",
"=",
"j",
"[",
"'defaultValue'",
"]",
"else",
":",
"v",
".",
... | 30.947368 | 0.013201 |
def popall(self, key, default=_marker):
"""Remove all occurrences of key and return the list of corresponding
values.
If key is not found, default is returned if given, otherwise
KeyError is raised.
"""
found = False
identity = self._title(key)
ret = []
... | [
"def",
"popall",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_marker",
")",
":",
"found",
"=",
"False",
"identity",
"=",
"self",
".",
"_title",
"(",
"key",
")",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"... | 30.038462 | 0.002481 |
def min(self):
"""
Returns the minimum value of the domain.
:rtype: `float` or `np.inf`
"""
return int(self._min) if not np.isinf(self._min) else self._min | [
"def",
"min",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"_min",
")",
"if",
"not",
"np",
".",
"isinf",
"(",
"self",
".",
"_min",
")",
"else",
"self",
".",
"_min"
] | 27.142857 | 0.010204 |
def init_from_fcnxs(ctx, fcnxs_symbol, fcnxs_args_from, fcnxs_auxs_from):
""" use zero initialization for better convergence, because it tends to oputut 0,
and the label 0 stands for background, which may occupy most size of one image.
"""
fcnxs_args = fcnxs_args_from.copy()
fcnxs_auxs = fcnxs_auxs_... | [
"def",
"init_from_fcnxs",
"(",
"ctx",
",",
"fcnxs_symbol",
",",
"fcnxs_args_from",
",",
"fcnxs_auxs_from",
")",
":",
"fcnxs_args",
"=",
"fcnxs_args_from",
".",
"copy",
"(",
")",
"fcnxs_auxs",
"=",
"fcnxs_auxs_from",
".",
"copy",
"(",
")",
"for",
"k",
",",
"v... | 47.952381 | 0.010219 |
def determine_name(func):
"""
Given a function, returns the name of the function.
Ex::
from random import choice
determine_name(choice) # Returns 'choice'
:param func: The callable
:type func: function
:returns: Name string
"""
if hasattr(func, '__name__'):
re... | [
"def",
"determine_name",
"(",
"func",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'__name__'",
")",
":",
"return",
"func",
".",
"__name__",
"elif",
"hasattr",
"(",
"func",
",",
"'__class__'",
")",
":",
"return",
"func",
".",
"__class__",
".",
"__name__... | 23.347826 | 0.001789 |
def generate_keywords(additional_keywords=None):
"""Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
... | [
"def",
"generate_keywords",
"(",
"additional_keywords",
"=",
"None",
")",
":",
"# Shallow copy",
"keywords",
"=",
"dict",
"(",
"BABEL_KEYWORDS",
")",
"keywords",
".",
"update",
"(",
"{",
"'_lazy'",
":",
"None",
",",
"'gettext_lazy'",
":",
"None",
",",
"'ugette... | 25.490909 | 0.000687 |
def create_snapshots(self, volumes, **kwargs):
"""Create snapshots of the listed volumes.
:param volumes: List of names of the volumes to snapshot.
:type volumes: list of str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the ... | [
"def",
"create_snapshots",
"(",
"self",
",",
"volumes",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"\"source\"",
":",
"volumes",
",",
"\"snap\"",
":",
"True",
"}",
"data",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"_request",
... | 37.294118 | 0.009231 |
def addr(self):
"""
Get the concrete address of the instruction pointer, without triggering SimInspect breakpoints or generating
SimActions. An integer is returned, or an exception is raised if the instruction pointer is symbolic.
:return: an int
"""
ip = self.regs._ip
... | [
"def",
"addr",
"(",
"self",
")",
":",
"ip",
"=",
"self",
".",
"regs",
".",
"_ip",
"if",
"isinstance",
"(",
"ip",
",",
"SootAddressDescriptor",
")",
":",
"return",
"ip",
"return",
"self",
".",
"solver",
".",
"eval_one",
"(",
"self",
".",
"regs",
".",
... | 35.916667 | 0.00905 |
def flush(self, safe=None):
''' Perform all database operations currently in the queue'''
result = None
for index, op in enumerate(self.queue):
try:
result = op.execute()
except:
self.clear_queue()
self.clear_cache()
raise
self.clear_queue()
return result | [
"def",
"flush",
"(",
"self",
",",
"safe",
"=",
"None",
")",
":",
"result",
"=",
"None",
"for",
"index",
",",
"op",
"in",
"enumerate",
"(",
"self",
".",
"queue",
")",
":",
"try",
":",
"result",
"=",
"op",
".",
"execute",
"(",
")",
"except",
":",
... | 23 | 0.04878 |
def get_package_hashes(
package,
version=None,
algorithm=DEFAULT_ALGORITHM,
python_versions=(),
verbose=False,
include_prereleases=False,
lookup_memory=None,
index_url=DEFAULT_INDEX_URL,
):
"""
Gets the hashes for the given package.
>>> get_package_hashes('hashin')
{
... | [
"def",
"get_package_hashes",
"(",
"package",
",",
"version",
"=",
"None",
",",
"algorithm",
"=",
"DEFAULT_ALGORITHM",
",",
"python_versions",
"=",
"(",
")",
",",
"verbose",
"=",
"False",
",",
"include_prereleases",
"=",
"False",
",",
"lookup_memory",
"=",
"Non... | 30.352941 | 0.001877 |
def launch(self,
argv=None,
showusageonnoargs=False,
width=0,
helphint="Use with --help for more information.\n",
debug_parser=False):
"""Do the usual stuff to initiallize the program.
Read config files and parse argumen... | [
"def",
"launch",
"(",
"self",
",",
"argv",
"=",
"None",
",",
"showusageonnoargs",
"=",
"False",
",",
"width",
"=",
"0",
",",
"helphint",
"=",
"\"Use with --help for more information.\\n\"",
",",
"debug_parser",
"=",
"False",
")",
":",
"if",
"showusageonnoargs",
... | 40.9 | 0.009074 |
def ellipse(data, channels,
center, a, b, theta=0,
log=False, full_output=False):
"""
Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates... | [
"def",
"ellipse",
"(",
"data",
",",
"channels",
",",
"center",
",",
"a",
",",
"b",
",",
"theta",
"=",
"0",
",",
"log",
"=",
"False",
",",
"full_output",
"=",
"False",
")",
":",
"# Extract channels in which to gate",
"if",
"len",
"(",
"channels",
")",
"... | 32.033708 | 0.002382 |
def is_allowed(self, user_agent, url, syntax=GYM2008):
"""True if the user agent is permitted to visit the URL. The syntax
parameter can be GYM2008 (the default) or MK1996 for strict adherence
to the traditional standard.
"""
if PY_MAJOR_VERSION < 3:
# The r... | [
"def",
"is_allowed",
"(",
"self",
",",
"user_agent",
",",
"url",
",",
"syntax",
"=",
"GYM2008",
")",
":",
"if",
"PY_MAJOR_VERSION",
"<",
"3",
":",
"# The robot rules are stored internally as Unicode. The two lines ",
"# below ensure that the parameters passed to this function... | 53.451613 | 0.008892 |
def what_if_I_upgrade(conn, pkg_name='openquake.server.db.schema.upgrades',
extract_scripts='extract_upgrade_scripts'):
"""
:param conn:
a DB API 2 connection
:param str pkg_name:
the name of the package with the upgrade scripts
:param extract_scripts:
name ... | [
"def",
"what_if_I_upgrade",
"(",
"conn",
",",
"pkg_name",
"=",
"'openquake.server.db.schema.upgrades'",
",",
"extract_scripts",
"=",
"'extract_upgrade_scripts'",
")",
":",
"msg_safe_",
"=",
"'\\nThe following scripts can be applied safely:\\n%s'",
"msg_slow_",
"=",
"'\\nPlease ... | 43.089286 | 0.000405 |
def decompress(input_dir, dcm_pattern='*.dcm'):
""" Decompress all *.dcm files recursively found in DICOM_DIR.
This uses 'gdcmconv --raw'.
It works when 'dcm2nii' shows the `Unsupported Transfer Syntax` error. This error is
usually caused by lack of JPEG2000 support in dcm2nii compilation.
Read mor... | [
"def",
"decompress",
"(",
"input_dir",
",",
"dcm_pattern",
"=",
"'*.dcm'",
")",
":",
"dcmfiles",
"=",
"sorted",
"(",
"recursive_glob",
"(",
"input_dir",
",",
"dcm_pattern",
")",
")",
"for",
"dcm",
"in",
"dcmfiles",
":",
"cmd",
"=",
"'gdcmconv --raw -i \"{0}\" ... | 33.807692 | 0.002212 |
def signature(self):
"""Get data signature"""
self._data.sort()
str_to_sign = self._delimiter.join(self._data)
return hashlib.sha1(str_to_sign).hexdigest() | [
"def",
"signature",
"(",
"self",
")",
":",
"self",
".",
"_data",
".",
"sort",
"(",
")",
"str_to_sign",
"=",
"self",
".",
"_delimiter",
".",
"join",
"(",
"self",
".",
"_data",
")",
"return",
"hashlib",
".",
"sha1",
"(",
"str_to_sign",
")",
".",
"hexdi... | 36.6 | 0.010695 |
def load_market_data(trading_day=None, trading_days=None, bm_symbol='SPY',
environ=None):
"""
Load benchmark returns and treasury yield curves for the given calendar and
benchmark symbol.
Benchmarks are downloaded as a Series from IEX Trading. Treasury curves
are US Treasury B... | [
"def",
"load_market_data",
"(",
"trading_day",
"=",
"None",
",",
"trading_days",
"=",
"None",
",",
"bm_symbol",
"=",
"'SPY'",
",",
"environ",
"=",
"None",
")",
":",
"if",
"trading_day",
"is",
"None",
":",
"trading_day",
"=",
"get_calendar",
"(",
"'XNYS'",
... | 35.74026 | 0.000354 |
def host_events(self, host):
'''
Given a host name, this will return all task events executed on that host
'''
all_host_events = filter(lambda x: 'event_data' in x and 'host' in x['event_data'] and x['event_data']['host'] == host,
self.events)
ret... | [
"def",
"host_events",
"(",
"self",
",",
"host",
")",
":",
"all_host_events",
"=",
"filter",
"(",
"lambda",
"x",
":",
"'event_data'",
"in",
"x",
"and",
"'host'",
"in",
"x",
"[",
"'event_data'",
"]",
"and",
"x",
"[",
"'event_data'",
"]",
"[",
"'host'",
"... | 47.571429 | 0.011799 |
def generate_certificates(base_dir, *peer_names, pubKeyDir=None,
secKeyDir=None, sigKeyDir=None,
verkeyDir=None, clean=True):
''' Generate client and server CURVE certificate files'''
pubKeyDir = pubKeyDir or 'public_keys'
secKeyDir = secKeyDir or 'private... | [
"def",
"generate_certificates",
"(",
"base_dir",
",",
"*",
"peer_names",
",",
"pubKeyDir",
"=",
"None",
",",
"secKeyDir",
"=",
"None",
",",
"sigKeyDir",
"=",
"None",
",",
"verkeyDir",
"=",
"None",
",",
"clean",
"=",
"True",
")",
":",
"pubKeyDir",
"=",
"p... | 39.976744 | 0.000568 |
def _lookup_abs(self, p, klass, create=1):
"""
Fast (?) lookup of a *normalized* absolute path.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the FS.Entry(), FS.Dir() or FS.File() methods.
The ca... | [
"def",
"_lookup_abs",
"(",
"self",
",",
"p",
",",
"klass",
",",
"create",
"=",
"1",
")",
":",
"k",
"=",
"_my_normcase",
"(",
"p",
")",
"try",
":",
"result",
"=",
"self",
".",
"_lookupDict",
"[",
"k",
"]",
"except",
"KeyError",
":",
"if",
"not",
"... | 43.219512 | 0.002208 |
def create_csv(filename, csv_data, mode="w"):
"""
Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file.... | [
"def",
"create_csv",
"(",
"filename",
",",
"csv_data",
",",
"mode",
"=",
"\"w\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
"csv_data",
".",
"replace",
"(",
"\"_\"",
",",
"r\"\\_\"",
")",
"f",
".",
"write",
"(",
"... | 33.714286 | 0.002062 |
def experiment(self):
"""The identifier or the experiment that is currently processed"""
if self._experiment is None:
self._experiment = list(self.config.experiments.keys())[-1]
return self._experiment | [
"def",
"experiment",
"(",
"self",
")",
":",
"if",
"self",
".",
"_experiment",
"is",
"None",
":",
"self",
".",
"_experiment",
"=",
"list",
"(",
"self",
".",
"config",
".",
"experiments",
".",
"keys",
"(",
")",
")",
"[",
"-",
"1",
"]",
"return",
"sel... | 46.6 | 0.008439 |
def status(name, maximum=None, minimum=None, absolute=False, free=False):
'''
Return the current disk usage stats for the named mount point
name
Disk mount or directory for which to check used space
maximum
The maximum disk utilization
minimum
The minimum disk utilization
... | [
"def",
"status",
"(",
"name",
",",
"maximum",
"=",
"None",
",",
"minimum",
"=",
"None",
",",
"absolute",
"=",
"False",
",",
"free",
"=",
"False",
")",
":",
"# Monitoring state, no changes will be made so no test interface needed",
"ret",
"=",
"{",
"'name'",
":",... | 32.614035 | 0.000522 |
def _lookup_nexus_bindings(query_type, session=None, **bfilter):
"""Look up 'query_type' Nexus bindings matching the filter.
:param query_type: 'all', 'one' or 'first'
:param session: db session
:param bfilter: filter for bindings query
:returns: bindings if query gave a result, else
r... | [
"def",
"_lookup_nexus_bindings",
"(",
"query_type",
",",
"session",
"=",
"None",
",",
"*",
"*",
"bfilter",
")",
":",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"bc",
".",
"get_reader_session",
"(",
")",
"query_method",
"=",
"getattr",
"(",
"sessio... | 35.65 | 0.001366 |
def guess_rank(M_E):
'''Guess the rank of the incomplete matrix '''
n, m = M_E.shape
epsilon = np.count_nonzero(M_E) / np.sqrt(m * n)
_, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1))
S0 = np.diag(S0)
S1 = S0[:-1] - S0[1:]
S1_ = S1 / np.mean(S1[-10:])
r1 = 0
la... | [
"def",
"guess_rank",
"(",
"M_E",
")",
":",
"n",
",",
"m",
"=",
"M_E",
".",
"shape",
"epsilon",
"=",
"np",
".",
"count_nonzero",
"(",
"M_E",
")",
"/",
"np",
".",
"sqrt",
"(",
"m",
"*",
"n",
")",
"_",
",",
"S0",
",",
"_",
"=",
"svds_descending",
... | 28.178571 | 0.001225 |
def rsem_mapped_reads_plot(self):
""" Make the rsem assignment rates plot """
# Plot categories
keys = OrderedDict()
keys['Unique'] = { 'color': '#437bb1', 'name': 'Aligned uniquely to a gene' }
keys['Multi'] = { 'color': '#e63491', 'name': 'Aligned to multiple genes'... | [
"def",
"rsem_mapped_reads_plot",
"(",
"self",
")",
":",
"# Plot categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'Unique'",
"]",
"=",
"{",
"'color'",
":",
"'#437bb1'",
",",
"'name'",
":",
"'Aligned uniquely to a gene'",
"}",
"keys",
"[",
"'Mult... | 40.8 | 0.024904 |
def chunk_count(self):
"""Return a count of the chunks in this world folder."""
c = 0
for r in self.iter_regions():
c += r.chunk_count()
return c | [
"def",
"chunk_count",
"(",
"self",
")",
":",
"c",
"=",
"0",
"for",
"r",
"in",
"self",
".",
"iter_regions",
"(",
")",
":",
"c",
"+=",
"r",
".",
"chunk_count",
"(",
")",
"return",
"c"
] | 30.666667 | 0.010582 |
def randomize(self, force = 0):
"""
Initialize node biases to random values in the range [-max, max].
"""
if force or not self.frozen:
self.weight = randomArray(self.size, self._maxRandom) | [
"def",
"randomize",
"(",
"self",
",",
"force",
"=",
"0",
")",
":",
"if",
"force",
"or",
"not",
"self",
".",
"frozen",
":",
"self",
".",
"weight",
"=",
"randomArray",
"(",
"self",
".",
"size",
",",
"self",
".",
"_maxRandom",
")"
] | 37.833333 | 0.017241 |
def add_model(self, propname, model, regen_mode='normal', **kwargs):
r"""
Adds a new model to the models dictionary (``object.models``)
Parameters
----------
propname : string
The name of the property to be calculated by the model.
model : function
... | [
"def",
"add_model",
"(",
"self",
",",
"propname",
",",
"model",
",",
"regen_mode",
"=",
"'normal'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"propname",
"in",
"kwargs",
".",
"values",
"(",
")",
":",
"# Prevent infinite loops of look-ups",
"raise",
"Exception... | 44.255814 | 0.001028 |
def gru(name, input, state, kernel_r, kernel_u, kernel_c, bias_r, bias_u, bias_c, new_state, number_of_gates = 2):
''' - zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz)
- rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr)
- ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh)
- Ht = (1-zt).ht + zt.Ht_1
'''
... | [
"def",
"gru",
"(",
"name",
",",
"input",
",",
"state",
",",
"kernel_r",
",",
"kernel_u",
",",
"kernel_c",
",",
"bias_r",
",",
"bias_u",
",",
"bias_c",
",",
"new_state",
",",
"number_of_gates",
"=",
"2",
")",
":",
"nn",
"=",
"Build",
"(",
"name",
")",... | 31.115385 | 0.008393 |
def header(self):
"""Generates HTTP header for this cookie."""
if self._send_cookie:
morsel = Morsel()
cookie_value = Session.encode_sid(self._config.secret, self._sid)
if self._config.encrypt_key:
cipher = AESCipher(self._config.encrypt_key)
... | [
"def",
"header",
"(",
"self",
")",
":",
"if",
"self",
".",
"_send_cookie",
":",
"morsel",
"=",
"Morsel",
"(",
")",
"cookie_value",
"=",
"Session",
".",
"encode_sid",
"(",
"self",
".",
"_config",
".",
"secret",
",",
"self",
".",
"_sid",
")",
"if",
"se... | 32.820513 | 0.002276 |
def replace_row(self, line, ndx):
"""
replace a grids row at index 'ndx' with 'line'
"""
for col in range(len(line)):
self.set_tile(ndx, col, line[col]) | [
"def",
"replace_row",
"(",
"self",
",",
"line",
",",
"ndx",
")",
":",
"for",
"col",
"in",
"range",
"(",
"len",
"(",
"line",
")",
")",
":",
"self",
".",
"set_tile",
"(",
"ndx",
",",
"col",
",",
"line",
"[",
"col",
"]",
")"
] | 32.166667 | 0.020202 |
def write_to_influxdb(received_data):
'''
Convert data into RuuviCollecor naming schme and scale
'''
dataFormat = received_data[1]["data_format"] if ('data_format' in received_data[1]) else None
fields = {}
fields["temperature"] = received_data[1]["temperature"] if ('temperature' i... | [
"def",
"write_to_influxdb",
"(",
"received_data",
")",
":",
"dataFormat",
"=",
"received_data",
"[",
"1",
"]",
"[",
"\"data_format\"",
"]",
"if",
"(",
"'data_format'",
"in",
"received_data",
"[",
"1",
"]",
")",
"else",
"None",
"fields",
"=",
"{",
"}",
"fie... | 67.758621 | 0.012544 |
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQ... | [
"def",
"__do_query_into_hash",
"(",
"conn",
",",
"sql_str",
")",
":",
"mod",
"=",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_code",
".",
"co_name",
"log",
".",
"debug",
"(",
"'%s<--(%s)'",
",",
"mod",
",",
"sql_str",
")",
"rtn_results",
"=",
"[",
"]",
... | 22.772727 | 0.000957 |
def map_as_completed(func, *iterables, **kwargs):
"""map_as_completed(func, *iterables)
Equivalent to map, but the results are returned as soon as they are made
available.
:param func: Any picklable callable object (function or class object with
*__call__* method); this object will be called to... | [
"def",
"map_as_completed",
"(",
"func",
",",
"*",
"iterables",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Handle timeout",
"for",
"future",
"in",
"as_completed",
"(",
"_mapFuture",
"(",
"func",
",",
"*",
"iterables",
")",
")",
":",
"yield",
"future",
".",... | 46.315789 | 0.001114 |
def _num_required_args(func):
""" Number of args for func
>>> def foo(a, b, c=None):
... return a + b + c
>>> _num_required_args(foo)
2
>>> def bar(*args):
... return sum(args)
>>> print(_num_required_args(bar))
None
borrowed from: https:/... | [
"def",
"_num_required_args",
"(",
"func",
")",
":",
"try",
":",
"spec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"spec",
".",
"varargs",
":",
"return",
"None",
"num_defaults",
"=",
"len",
"(",
"spec",
".",
"defaults",
")",
"if",
"spec... | 23.2 | 0.001656 |
def _osquery(sql, format='json'):
'''
Helper function to run raw osquery queries
'''
ret = {
'result': True,
}
cmd = ['osqueryi'] + ['--json'] + [sql]
res = __salt__['cmd.run_all'](cmd)
if res['stderr']:
ret['result'] = False
ret['error'] = res['stderr']
else... | [
"def",
"_osquery",
"(",
"sql",
",",
"format",
"=",
"'json'",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"True",
",",
"}",
"cmd",
"=",
"[",
"'osqueryi'",
"]",
"+",
"[",
"'--json'",
"]",
"+",
"[",
"sql",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run... | 24.117647 | 0.002347 |
def strict_parse(cls, query_str, *specs, extra_parameters=True):
""" Parse query and return :class:`.WStrictURIQuery` object
:param query_str: query component of URI to parse
:param specs: list of parameters specifications
:param extra_parameters: whether parameters that was not specified in "specs" are allowe... | [
"def",
"strict_parse",
"(",
"cls",
",",
"query_str",
",",
"*",
"specs",
",",
"extra_parameters",
"=",
"True",
")",
":",
"plain_result",
"=",
"cls",
".",
"parse",
"(",
"query_str",
")",
"return",
"WStrictURIQuery",
"(",
"plain_result",
",",
"*",
"specs",
",... | 46.5 | 0.025316 |
def upgrade_account(self, account=None, **kwargs):
""" Upgrade an account to Lifetime membership
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not account:
if "default_account" in self.config:
... | [
"def",
"upgrade_account",
"(",
"self",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"account",
":",
"if",
"\"default_account\"",
"in",
"self",
".",
"config",
":",
"account",
"=",
"self",
".",
"config",
"[",
"\"default_acco... | 40.714286 | 0.002286 |
def implied_vol(self, value, precision=1.0e-5, iters=100):
"""Get implied vol at the specified price using an iterative approach.
There is no closed-form inverse of BSM-value as a function of sigma,
so start at an anchoring volatility level from Brenner & Subrahmanyam
(1988) and wo... | [
"def",
"implied_vol",
"(",
"self",
",",
"value",
",",
"precision",
"=",
"1.0e-5",
",",
"iters",
"=",
"100",
")",
":",
"vol",
"=",
"np",
".",
"sqrt",
"(",
"2.0",
"*",
"np",
".",
"pi",
"/",
"self",
".",
"T",
")",
"*",
"(",
"value",
"/",
"self",
... | 35.75 | 0.001946 |
def query(self, dataset='hsapiens_gene_ensembl', attributes=[],
filters={}, filename=None):
"""mapping ids using BioMart.
:param dataset: str, default: 'hsapiens_gene_ensembl'
:param attributes: str, list, tuple
:param filters: dict, {'filter name': list(filter value)}
... | [
"def",
"query",
"(",
"self",
",",
"dataset",
"=",
"'hsapiens_gene_ensembl'",
",",
"attributes",
"=",
"[",
"]",
",",
"filters",
"=",
"{",
"}",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"attributes",
":",
"attributes",
"=",
"[",
"'ensembl_gene_i... | 45.559322 | 0.009104 |
def com_adobe_fonts_check_cff2_call_depth(ttFont):
"""Is the CFF2 subr/gsubr call depth > 10?"""
any_failures = False
cff = ttFont['CFF2'].cff
for top_dict in cff.topDictIndex:
for fd_index, font_dict in enumerate(top_dict.FDArray):
if hasattr(font_dict, 'Private'):
... | [
"def",
"com_adobe_fonts_check_cff2_call_depth",
"(",
"ttFont",
")",
":",
"any_failures",
"=",
"False",
"cff",
"=",
"ttFont",
"[",
"'CFF2'",
"]",
".",
"cff",
"for",
"top_dict",
"in",
"cff",
".",
"topDictIndex",
":",
"for",
"fd_index",
",",
"font_dict",
"in",
... | 36.647059 | 0.001565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.