text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def write_extent(self):
"""After the extent selection, save the extent and disconnect signals.
"""
self.extent_dialog.accept()
self.extent_dialog.clear_extent.disconnect(
self.parent.dock.extent.clear_user_analysis_extent)
self.extent_dialog.extent_defined.disconnect(... | [
"def",
"write_extent",
"(",
"self",
")",
":",
"self",
".",
"extent_dialog",
".",
"accept",
"(",
")",
"self",
".",
"extent_dialog",
".",
"clear_extent",
".",
"disconnect",
"(",
"self",
".",
"parent",
".",
"dock",
".",
"extent",
".",
"clear_user_analysis_exten... | 48.166667 | 11.083333 |
def unwrap(value):
"""Iterate an NTTable
:returns: An iterator yielding an OrderedDict for each column
"""
ret = []
# build lists of column names, and value
lbl, cols = [], []
for cname, cval in value.value.items():
lbl.append(cname)
cols... | [
"def",
"unwrap",
"(",
"value",
")",
":",
"ret",
"=",
"[",
"]",
"# build lists of column names, and value",
"lbl",
",",
"cols",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"cname",
",",
"cval",
"in",
"value",
".",
"value",
".",
"items",
"(",
")",
":",
"lbl",... | 28.105263 | 18.842105 |
def read_excel(file_name, offset=1, sheet_index=0):
"""
读取 Excel
:param sheet_index:
:param file_name:
:param offset: 偏移,一般第一行是表头,不需要读取数据
:return:
"""
try:
workbook = xlrd.open_workbook(file_name)
except Exception as e:
return None
if len(workbook.sheets()) <= 0:... | [
"def",
"read_excel",
"(",
"file_name",
",",
"offset",
"=",
"1",
",",
"sheet_index",
"=",
"0",
")",
":",
"try",
":",
"workbook",
"=",
"xlrd",
".",
"open_workbook",
"(",
"file_name",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"None",
"if",
"le... | 21.025641 | 18.358974 |
def _traverse_parent_objs(self, goobj_child):
"""Traverse from source GO up parents."""
child_id = goobj_child.id
# mark child as seen
self.seen_cids.add(child_id)
self.godag.go2obj[child_id] = goobj_child
# Loop through parents of child object
for parent_obj in g... | [
"def",
"_traverse_parent_objs",
"(",
"self",
",",
"goobj_child",
")",
":",
"child_id",
"=",
"goobj_child",
".",
"id",
"# mark child as seen",
"self",
".",
"seen_cids",
".",
"add",
"(",
"child_id",
")",
"self",
".",
"godag",
".",
"go2obj",
"[",
"child_id",
"]... | 44.461538 | 7.769231 |
def app_list(**kwargs):
"""
Show uploaded applications.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) | [
"def",
"app_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:list'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_service",
"(",
"... | 25 | 12 |
def pretty(self, start, end, e, messages=None):
"""Pretties up the output error message so it is readable
and designates where the error came from"""
log.debug("Displaying document from lines '%i' to '%i'", start, end)
errorlist = []
if len(e.context) > 0:
errorlist... | [
"def",
"pretty",
"(",
"self",
",",
"start",
",",
"end",
",",
"e",
",",
"messages",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\"Displaying document from lines '%i' to '%i'\"",
",",
"start",
",",
"end",
")",
"errorlist",
"=",
"[",
"]",
"if",
"len",... | 47.806897 | 24.572414 |
def add_record(post_id, catalog_id, order=0):
'''
Create the record of post 2 tag, and update the count in g_tag.
'''
rec = MPost2Catalog.__get_by_info(post_id, catalog_id)
if rec:
entry = TabPost2Tag.update(
order=order,
# For migrati... | [
"def",
"add_record",
"(",
"post_id",
",",
"catalog_id",
",",
"order",
"=",
"0",
")",
":",
"rec",
"=",
"MPost2Catalog",
".",
"__get_by_info",
"(",
"post_id",
",",
"catalog_id",
")",
"if",
"rec",
":",
"entry",
"=",
"TabPost2Tag",
".",
"update",
"(",
"order... | 32.521739 | 16.956522 |
def DbGetHostList(self, argin):
""" Get host list with name matching the specified filter
:param argin: The filter
:type: tango.DevString
:return: Host name list
:rtype: tango.DevVarStringArray """
self._log.debug("In DbGetHostList()")
argin = replace_wildcard(ar... | [
"def",
"DbGetHostList",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbGetHostList()\"",
")",
"argin",
"=",
"replace_wildcard",
"(",
"argin",
")",
"return",
"self",
".",
"db",
".",
"get_host_list",
"(",
"argin",
")"
] | 35.9 | 8.5 |
def process_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-I', type=str,
metavar='<Include directory>',
action='append',
help='Directory to be searched for included files... | [
"def",
"process_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-I'",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"'<Include directory>'",
",",
"action",
"=",
"'append'",
",",
"help"... | 38.5 | 17.458333 |
def hash(self):
"signatures are non deterministic"
if self.sender is None:
raise MissingSignatureError()
class HashSerializable(rlp.Serializable):
fields = [(field, sedes) for field, sedes in self.fields
if field not in ('v', 'r', 's')] + [('_sender... | [
"def",
"hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"sender",
"is",
"None",
":",
"raise",
"MissingSignatureError",
"(",
")",
"class",
"HashSerializable",
"(",
"rlp",
".",
"Serializable",
")",
":",
"fields",
"=",
"[",
"(",
"field",
",",
"sedes",
")... | 40.4 | 18.2 |
def clean_meta(self, meta):
"""Removes unwanted metadata
Parameters
----------
meta : dict
Notebook metadata.
"""
if not self.verbose_metadata:
default_kernel_name = (self.default_kernel_name or
self._km.kernel_... | [
"def",
"clean_meta",
"(",
"self",
",",
"meta",
")",
":",
"if",
"not",
"self",
".",
"verbose_metadata",
":",
"default_kernel_name",
"=",
"(",
"self",
".",
"default_kernel_name",
"or",
"self",
".",
"_km",
".",
"kernel_name",
")",
"if",
"(",
"meta",
".",
"g... | 27.526316 | 18.105263 |
def from_section(cls, config, section, **kwargs):
"""
Creates a :class:`~vsgen.project.VSGProject` from a :class:`~configparser.ConfigParser` section.
:param ConfigParser config: A :class:`~configparser.ConfigParser` instance.
:param str section: A :class:`~configparser.Conf... | [
"def",
"from_section",
"(",
"cls",
",",
"config",
",",
"section",
",",
"*",
"*",
"kwargs",
")",
":",
"p",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"p",
".",
"Name",
"=",
"config",
".",
"get",
"(",
"section",
",",
"'name'",
",",
"fallback",
"=",
... | 68.75 | 43.4375 |
def str_get(x, i):
"""Extract a character from each sample at the specified position from a string column.
Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan.
:param int i: The index location, at which to extract the character.
:re... | [
"def",
"str_get",
"(",
"x",
",",
"i",
")",
":",
"x",
"=",
"_to_string_sequence",
"(",
"x",
")",
"if",
"i",
"==",
"-",
"1",
":",
"sl",
"=",
"x",
".",
"slice_string_end",
"(",
"-",
"1",
")",
"else",
":",
"sl",
"=",
"x",
".",
"slice_string",
"(",
... | 28.361111 | 25.083333 |
def desc(self):
"""Get a short description of the automation."""
# Auto Away (1) - Location - Enabled
active = 'inactive'
if self.is_active:
active = 'active'
return '{0} (ID: {1}) - {2} - {3}'.format(
self.name, self.automation_id, self.type, active) | [
"def",
"desc",
"(",
"self",
")",
":",
"# Auto Away (1) - Location - Enabled",
"active",
"=",
"'inactive'",
"if",
"self",
".",
"is_active",
":",
"active",
"=",
"'active'",
"return",
"'{0} (ID: {1}) - {2} - {3}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"sel... | 34.222222 | 15.333333 |
def update_search_space(self, search_space):
"""
Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict
"""
self.json = sea... | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"self",
".",
"json",
"=",
"search_space",
"search_space_instance",
"=",
"json2space",
"(",
"self",
".",
"json",
")",
"rstate",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")",
... | 39.1 | 17.7 |
def population_analysis_summary_report(feature, parent):
"""Retrieve an HTML population analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_population['key'])
if analysis_dir:
return get_impact_report_as_string(an... | [
"def",
"population_analysis_summary_report",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"analysis_dir",
"=",
"get_analysis_dir",
"(",
"exposure_population",
"[",
"'key'",
"]",
")",
"if",
"analysis_dir",
":",
"return",
... | 37.666667 | 15.111111 |
def items2file(items, filename, encoding='utf-8', modifier='w'):
"""
json array to file, canonical json format
"""
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_ke... | [
"def",
"items2file",
"(",
"items",
",",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"modifier",
"=",
"'w'",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"modifier",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"for",
... | 40.375 | 12.125 |
def Nu_Ornatsky(Re, Pr_b, Pr_w, rho_w=None, rho_b=None):
r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_ as
shown in both [2]_ and [3]_.
.. math::
Nu_b = 0.023Re_b^{0.8}(\min(Pr_b, Pr_w))^{0.... | [
"def",
"Nu_Ornatsky",
"(",
"Re",
",",
"Pr_b",
",",
"Pr_w",
",",
"rho_w",
"=",
"None",
",",
"rho_b",
"=",
"None",
")",
":",
"Nu",
"=",
"0.023",
"*",
"Re",
"**",
"0.8",
"*",
"min",
"(",
"Pr_b",
",",
"Pr_w",
")",
"**",
"0.8",
"if",
"rho_w",
"and",... | 38.166667 | 25.233333 |
def _validate_options(cls, options):
"""Validate the mutually exclusive options.
Return `True` iff only zero or one of `BASE_ERROR_SELECTION_OPTIONS`
was selected.
"""
for opt1, opt2 in \
itertools.permutations(cls.BASE_ERROR_SELECTION_OPTIONS, 2):
i... | [
"def",
"_validate_options",
"(",
"cls",
",",
"options",
")",
":",
"for",
"opt1",
",",
"opt2",
"in",
"itertools",
".",
"permutations",
"(",
"cls",
".",
"BASE_ERROR_SELECTION_OPTIONS",
",",
"2",
")",
":",
"if",
"getattr",
"(",
"options",
",",
"opt1",
")",
... | 41.05 | 22.45 |
def deletePartials(self):
""" Delete any old partial uploads/downloads in path. """
if self.dryrun:
self._client.listPartials()
else:
self._client.deletePartials() | [
"def",
"deletePartials",
"(",
"self",
")",
":",
"if",
"self",
".",
"dryrun",
":",
"self",
".",
"_client",
".",
"listPartials",
"(",
")",
"else",
":",
"self",
".",
"_client",
".",
"deletePartials",
"(",
")"
] | 34.333333 | 10.166667 |
def do_OP_RIGHT(vm):
"""
>>> s = [b'abcdef', b'\\3']
>>> do_OP_RIGHT(s, require_minimal=True)
>>> print(s==[b'def'])
True
>>> s = [b'abcdef', b'\\0']
>>> do_OP_RIGHT(s, require_minimal=False)
>>> print(s==[b''])
True
"""
pos = vm.pop_nonnegative()
if pos > 0:
vm.a... | [
"def",
"do_OP_RIGHT",
"(",
"vm",
")",
":",
"pos",
"=",
"vm",
".",
"pop_nonnegative",
"(",
")",
"if",
"pos",
">",
"0",
":",
"vm",
".",
"append",
"(",
"vm",
".",
"pop",
"(",
")",
"[",
"-",
"pos",
":",
"]",
")",
"else",
":",
"vm",
".",
"pop",
... | 22.117647 | 15.058824 |
def parse_paragraphs(self, markup):
""" Returns a list of paragraphs in the markup.
A paragraph has a title and multiple lines of plain text.
A paragraph might have parent and child paragraphs,
denoting subtitles or bigger chapters.
A paragraph might ha... | [
"def",
"parse_paragraphs",
"(",
"self",
",",
"markup",
")",
":",
"# Paragraphs to exclude.",
"refs",
"=",
"[",
"\"references\"",
",",
"\"notes\"",
",",
"\"notes and references\"",
",",
"\"external links\"",
",",
"\"further reading\"",
"]",
"exclude",
"=",
"[",
"\"se... | 46.461538 | 21.56044 |
def qry_helper(flag_id, qry_string, param_str, flag_filt=False, filt_st=""):
"""Dynamically add syntaxtical elements to query.
This functions adds syntactical elements to the query string, and
report title, based on the types and number of items added thus far.
Args:
flag_filt (bool): at least... | [
"def",
"qry_helper",
"(",
"flag_id",
",",
"qry_string",
",",
"param_str",
",",
"flag_filt",
"=",
"False",
",",
"filt_st",
"=",
"\"\"",
")",
":",
"if",
"flag_id",
"or",
"flag_filt",
":",
"qry_string",
"+=",
"\", \"",
"param_str",
"+=",
"\", \"",
"if",
"not"... | 39.72 | 24.2 |
def from_headers(self, headers):
"""Generate a SpanContext object from B3 propagation headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from B3 propagation headers.
... | [
"def",
"from_headers",
"(",
"self",
",",
"headers",
")",
":",
"if",
"headers",
"is",
"None",
":",
"return",
"SpanContext",
"(",
"from_header",
"=",
"False",
")",
"trace_id",
",",
"span_id",
",",
"sampled",
"=",
"None",
",",
"None",
",",
"None",
"state",
... | 35.174603 | 18.095238 |
def cached(fn, size=32):
''' this decorator creates a type safe lru_cache
around the decorated function. Unlike
functools.lru_cache, this will not crash when
unhashable arguments are passed to the function'''
assert callable(fn)
assert isinstance(size, int)
return overload(fn)(lru_cache(size... | [
"def",
"cached",
"(",
"fn",
",",
"size",
"=",
"32",
")",
":",
"assert",
"callable",
"(",
"fn",
")",
"assert",
"isinstance",
"(",
"size",
",",
"int",
")",
"return",
"overload",
"(",
"fn",
")",
"(",
"lru_cache",
"(",
"size",
",",
"typed",
"=",
"True"... | 41.375 | 11.625 |
def makeServoIDPacket(curr_id, new_id):
"""
Given the current ID, returns a packet to set the servo to a new ID
"""
pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id])
return pkt | [
"def",
"makeServoIDPacket",
"(",
"curr_id",
",",
"new_id",
")",
":",
"pkt",
"=",
"Packet",
".",
"makeWritePacket",
"(",
"curr_id",
",",
"xl320",
".",
"XL320_ID",
",",
"[",
"new_id",
"]",
")",
"return",
"pkt"
] | 31.666667 | 13.666667 |
def add_elasticache_replication_group(self, replication_group, region):
''' Adds an ElastiCache replication group to the inventory and index '''
# Only want available clusters unless all_elasticache_replication_groups is True
if not self.all_elasticache_replication_groups and replication_group[... | [
"def",
"add_elasticache_replication_group",
"(",
"self",
",",
"replication_group",
",",
"region",
")",
":",
"# Only want available clusters unless all_elasticache_replication_groups is True",
"if",
"not",
"self",
".",
"all_elasticache_replication_groups",
"and",
"replication_group"... | 43.72549 | 30.196078 |
def pelix_infos(self):
"""
Basic information about the Pelix framework instance
"""
framework = self.__context.get_framework()
return {
"version": framework.get_version(),
"properties": framework.get_properties(),
} | [
"def",
"pelix_infos",
"(",
"self",
")",
":",
"framework",
"=",
"self",
".",
"__context",
".",
"get_framework",
"(",
")",
"return",
"{",
"\"version\"",
":",
"framework",
".",
"get_version",
"(",
")",
",",
"\"properties\"",
":",
"framework",
".",
"get_properti... | 31 | 13.666667 |
def timestamp_with_tzinfo(dt):
"""
Serialize a date/time value into an ISO8601 text representation
adjusted (if needed) to UTC timezone.
For instance:
>>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391))
'2012-04-10T22:38:20.604391Z'
"""
utc = tzutc()
if dt.tzinfo:
... | [
"def",
"timestamp_with_tzinfo",
"(",
"dt",
")",
":",
"utc",
"=",
"tzutc",
"(",
")",
"if",
"dt",
".",
"tzinfo",
":",
"dt",
"=",
"dt",
".",
"astimezone",
"(",
"utc",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"return",
"dt",
".",
"isoforma... | 27.428571 | 17.142857 |
def detect(self, text):
"""Detect language of the input text
:param text: The source text(s) whose language you want to identify.
Batch detection is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, gener... | [
"def",
"detect",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"text",
":",
"lang",
"=",
"self",
".",
"detect",
"(",
"item",
")",
"result",
".",
"append",... | 36.576923 | 19.942308 |
def on_setButton_pressed(self):
"""
Start recording a key combination when the user clicks on the setButton.
The button itself is automatically disabled during the recording process.
"""
self.keyLabel.setText("Press a key or combination...") # TODO: i18n
logger.debug("Us... | [
"def",
"on_setButton_pressed",
"(",
"self",
")",
":",
"self",
".",
"keyLabel",
".",
"setText",
"(",
"\"Press a key or combination...\"",
")",
"# TODO: i18n",
"logger",
".",
"debug",
"(",
"\"User starts to record a key combination.\"",
")",
"self",
".",
"grabber",
"=",... | 48 | 19.111111 |
def execute(self, env, args):
""" Prints task information.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
start = self._fuzzy_time_parse(args.start)
if not start:
raise errors.... | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"start",
"=",
"self",
".",
"_fuzzy_time_parse",
"(",
"args",
".",
"start",
")",
"if",
"not",
"start",
":",
"raise",
"errors",
".",
"FocusError",
"(",
"u'Invalid start period provided'",
")",... | 29.2 | 17.533333 |
def loadMetadata(self):
""" #TODO: docstring """
#TODO: change that spectra dont have to be iterated to extract metadata
#node
if self._parsed:
raise TypeError('Mzml file already parsed.')
[None for _ in self._parseMzml()]
self._parsed = True | [
"def",
"loadMetadata",
"(",
"self",
")",
":",
"#TODO: change that spectra dont have to be iterated to extract metadata",
"#node",
"if",
"self",
".",
"_parsed",
":",
"raise",
"TypeError",
"(",
"'Mzml file already parsed.'",
")",
"[",
"None",
"for",
"_",
"in",
"self",
"... | 36.875 | 16.125 |
def setup(applicationName,
applicationType=None,
style='plastique',
splash='',
splashType=None,
splashTextColor='white',
splashTextAlign=None,
theme=''):
"""
Wrapper system for the QApplication creation process to handle all proper
... | [
"def",
"setup",
"(",
"applicationName",
",",
"applicationType",
"=",
"None",
",",
"style",
"=",
"'plastique'",
",",
"splash",
"=",
"''",
",",
"splashType",
"=",
"None",
",",
"splashTextColor",
"=",
"'white'",
",",
"splashTextAlign",
"=",
"None",
",",
"theme"... | 36.292683 | 18.097561 |
def new(self, log_block_size):
# type: (int) -> None
'''
Create a new Version Volume Descriptor.
Parameters:
log_block_size - The size of one extent.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalE... | [
"def",
"new",
"(",
"self",
",",
"log_block_size",
")",
":",
"# type: (int) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'This Version Volume Descriptor is already initialized'",
")",
"self",
".",
"_dat... | 29.8 | 22.6 |
def mod(self, other, axis="columns", level=None, fill_value=None):
"""Mods this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the mod against this.
axis: The axis to mod over.
level: The Multilevel index level to app... | [
"def",
"mod",
"(",
"self",
",",
"other",
",",
"axis",
"=",
"\"columns\"",
",",
"level",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"return",
"self",
".",
"_binary_op",
"(",
"\"mod\"",
",",
"other",
",",
"axis",
"=",
"axis",
",",
"level",
... | 38.2 | 20.066667 |
def gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False):
"""Estimate the paramaters for the Generalized Pareto Distribution (GPD)
Returns empirical Bayes estimate for the parameters of the two-parameter
generalized Parato distribution given the data.
Parameters
----------
x :... | [
"def",
"gpdfitnew",
"(",
"x",
",",
"sort",
"=",
"True",
",",
"sort_in_place",
"=",
"False",
",",
"return_quadrature",
"=",
"False",
")",
":",
"if",
"x",
".",
"ndim",
"!=",
"1",
"or",
"len",
"(",
"x",
")",
"<=",
"1",
":",
"raise",
"ValueError",
"(",... | 26.950413 | 21.603306 |
def getLogs(self, CorpNum, ItemCode, MgtKey):
""" 전자명세서 문서이력 목록 확인
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너... | [
"def",
"getLogs",
"(",
"self",
",",
"CorpNum",
",",
"ItemCode",
",",
"MgtKey",
")",
":",
"if",
"MgtKey",
"==",
"None",
"or",
"MgtKey",
"==",
"\"\"",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"관리번호가 입력되지 않았습니다.\")\r",
"",
"if",
"ItemCod... | 40.052632 | 15.473684 |
def update_user(self, user, email=None, username=None,
uid=None, defaultRegion=None, enabled=None):
"""
Allows you to update settings for a given user.
"""
user_id = utils.get_id(user)
uri = "users/%s" % user_id
upd = {"id": user_id}
if email is not No... | [
"def",
"update_user",
"(",
"self",
",",
"user",
",",
"email",
"=",
"None",
",",
"username",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"defaultRegion",
"=",
"None",
",",
"enabled",
"=",
"None",
")",
":",
"user_id",
"=",
"utils",
".",
"get_id",
"(",
... | 38.772727 | 9.863636 |
def _handle_tag_space(self, data, text):
"""Handle whitespace (*text*) inside of an HTML open tag."""
ctx = data.context
end_of_value = ctx & data.CX_ATTR_VALUE and not ctx & (data.CX_QUOTED | data.CX_NOTE_QUOTE)
if end_of_value or (ctx & data.CX_QUOTED and ctx & data.CX_NOTE_SPACE):
... | [
"def",
"_handle_tag_space",
"(",
"self",
",",
"data",
",",
"text",
")",
":",
"ctx",
"=",
"data",
".",
"context",
"end_of_value",
"=",
"ctx",
"&",
"data",
".",
"CX_ATTR_VALUE",
"and",
"not",
"ctx",
"&",
"(",
"data",
".",
"CX_QUOTED",
"|",
"data",
".",
... | 50.333333 | 11.777778 |
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
Not... | [
"def",
"getclosurevars",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"elif",
"not",
"inspect",
".",
"isroutine",
"(",
"func",
")",
":",
"raise",
"TypeError",
"(",
"\"'{!r}' is not ... | 36.412698 | 20.507937 |
def create_policy(policyName, policyDocument,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create a policy.
Returns {created: true} if the policy was created and returns
{created: False} if the policy was not created.
CLI Example:
.. code-block:: bas... | [
"def",
"create_policy",
"(",
"policyName",
",",
"policyDocument",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",... | 37.228571 | 24.771429 |
def websocket_query(self, path, params={}):
"""
Open a websocket connection
:param path: Endpoint in API
:param params: Parameters added as a query arg
:returns: Websocket
"""
url = "http://docker/v" + self._api_version + "/" + path
connection = yield fr... | [
"def",
"websocket_query",
"(",
"self",
",",
"path",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"\"http://docker/v\"",
"+",
"self",
".",
"_api_version",
"+",
"\"/\"",
"+",
"path",
"connection",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
... | 37 | 17.857143 |
def add(self, data, name=None):
''' Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the c... | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"n",
"=",
"len",
"(",
"self",
".",
"data",
")",
"while",
"\"Series %d\"",
"%",
"n",
"in",
"self",
".",
"data",
":",
"n",
"+=",
"1",
"... | 28.368421 | 19.315789 |
def write(self, data):
"""! @brief Write bytes into the connection."""
# If nobody is connected, act like all data was written anyway.
if self.connected is None:
return 0
data = to_bytes_safe(data)
size = len(data)
remaining = size
while remaining:
... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"# If nobody is connected, act like all data was written anyway.",
"if",
"self",
".",
"connected",
"is",
"None",
":",
"return",
"0",
"data",
"=",
"to_bytes_safe",
"(",
"data",
")",
"size",
"=",
"len",
"(",
"d... | 33.571429 | 13.785714 |
async def AddToUnit(self, storages):
'''
storages : typing.Sequence[~StorageAddParams]
Returns -> typing.Sequence[~AddStorageResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Storage',
request='AddToUnit',
... | [
"async",
"def",
"AddToUnit",
"(",
"self",
",",
"storages",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Storage'",
",",
"request",
"=",
"'AddToUnit'",
",",
"version",
"=",
"4",
",",
"... | 32.357143 | 11.357143 |
def path(self):
"""
Build the path (prefix) leading up to this namespace.
"""
return "/".join([
part
for part in [
self.version,
self.qualifier,
]
if part
]) | [
"def",
"path",
"(",
"self",
")",
":",
"return",
"\"/\"",
".",
"join",
"(",
"[",
"part",
"for",
"part",
"in",
"[",
"self",
".",
"version",
",",
"self",
".",
"qualifier",
",",
"]",
"if",
"part",
"]",
")"
] | 20.461538 | 18.307692 |
def stderr_redirected(to=os.devnull):
"""
import os
with stderr_redirected(to=filename):
print("from Python")
os.system("echo non-Python applications are also supported")
"""
fd = sys.stderr.fileno()
# assert that Python and C stdio write using the same file descriptor
... | [
"def",
"stderr_redirected",
"(",
"to",
"=",
"os",
".",
"devnull",
")",
":",
"fd",
"=",
"sys",
".",
"stderr",
".",
"fileno",
"(",
")",
"# assert that Python and C stdio write using the same file descriptor",
"# assert libc.fileno(ctypes.c_void_p.in_dll(libc, \"stderr\")) == fd... | 33.68 | 18.48 |
def build_instruction_coverage_plugin() -> LaserPlugin:
""" Creates an instance of the instruction coverage plugin"""
from mythril.laser.ethereum.plugins.implementations.coverage import (
InstructionCoveragePlugin,
)
return InstructionCoveragePlugin() | [
"def",
"build_instruction_coverage_plugin",
"(",
")",
"->",
"LaserPlugin",
":",
"from",
"mythril",
".",
"laser",
".",
"ethereum",
".",
"plugins",
".",
"implementations",
".",
"coverage",
"import",
"(",
"InstructionCoveragePlugin",
",",
")",
"return",
"InstructionCov... | 41.428571 | 18.142857 |
def setValue(self, key, value, channel=1):
"""
Some devices allow to directly set values to perform a specific task.
"""
if channel in self.CHANNELS:
return self.CHANNELS[channel].setValue(key, value)
LOG.error("HMDevice.setValue: channel not found %i!" % channel) | [
"def",
"setValue",
"(",
"self",
",",
"key",
",",
"value",
",",
"channel",
"=",
"1",
")",
":",
"if",
"channel",
"in",
"self",
".",
"CHANNELS",
":",
"return",
"self",
".",
"CHANNELS",
"[",
"channel",
"]",
".",
"setValue",
"(",
"key",
",",
"value",
")... | 38.75 | 17 |
def _split_section_and_key(key):
"""Return a tuple with config section and key."""
parts = key.split('.')
if len(parts) > 1:
return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:])
return 'renku', key | [
"def",
"_split_section_and_key",
"(",
"key",
")",
":",
"parts",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"return",
"'renku \"{0}\"'",
".",
"format",
"(",
"parts",
"[",
"0",
"]",
")",
",",
"'.'",
".",... | 37 | 13.833333 |
def execute(self, **kwargs):
"""
Execute the interactive guessing procedure.
:param show: Whether or not to show the figure. Useful for testing.
:type show: bool
:param block: Blocking call to matplotlib
:type show: bool
Any additional keyword arguments are pass... | [
"def",
"execute",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"show",
"=",
"kwargs",
".",
"pop",
"(",
"'show'",
")",
"if",
"show",
":",
"# self.fig.show() # Apparently this does something else,",
"# see https://github.com/matplotlib/matplotlib/issues/6138",
"plt",
... | 34 | 17.647059 |
def _slice2rows(self, start, stop, step=None):
"""
Convert a slice to an explicit array of rows
"""
nrows = self._info['nrows']
if start is None:
start = 0
if stop is None:
stop = nrows
if step is None:
step = 1
tstart ... | [
"def",
"_slice2rows",
"(",
"self",
",",
"start",
",",
"stop",
",",
"step",
"=",
"None",
")",
":",
"nrows",
"=",
"self",
".",
"_info",
"[",
"'nrows'",
"]",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"0",
"if",
"stop",
"is",
"None",
":",
"stop... | 33.047619 | 13.428571 |
def normalized_axes_tuple(axes, ndim):
"""Return a tuple of ``axes`` converted to positive integers.
This function turns negative entries into equivalent positive
ones according to standard Python indexing "from the right".
Parameters
----------
axes : int or sequence of ints
Single in... | [
"def",
"normalized_axes_tuple",
"(",
"axes",
",",
"ndim",
")",
":",
"try",
":",
"axes",
",",
"axes_in",
"=",
"(",
"int",
"(",
"axes",
")",
",",
")",
",",
"axes",
"except",
"TypeError",
":",
"axes",
",",
"axes_in",
"=",
"tuple",
"(",
"int",
"(",
"ax... | 31.62069 | 22.034483 |
def syndic_cmd(self, data):
'''
Take the now clear load and forward it on to the client cmd
'''
# Set up default tgt_type
if 'tgt_type' not in data:
data['tgt_type'] = 'glob'
kwargs = {}
# optionally add a few fields to the publish data
for fi... | [
"def",
"syndic_cmd",
"(",
"self",
",",
"data",
")",
":",
"# Set up default tgt_type",
"if",
"'tgt_type'",
"not",
"in",
"data",
":",
"data",
"[",
"'tgt_type'",
"]",
"=",
"'glob'",
"kwargs",
"=",
"{",
"}",
"# optionally add a few fields to the publish data",
"for",
... | 38.225806 | 16.096774 |
def ParseFileLNKFile(
self, parser_mediator, file_object, display_name):
"""Parses a Windows Shortcut (LNK) file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): fi... | [
"def",
"ParseFileLNKFile",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
",",
"display_name",
")",
":",
"lnk_file",
"=",
"pylnk",
".",
"file",
"(",
")",
"lnk_file",
".",
"set_ascii_codepage",
"(",
"parser_mediator",
".",
"codepage",
")",
"try",
":",... | 43.94 | 19.89 |
def plot_border(mask, should_plot_border, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):
"""Plot the borders of the mask or the array on the figure.
Parameters
-----------t.
mask : ndarray of data.array.mask.Mask
The mask applied to the array, the edge of which is plotted as a set of po... | [
"def",
"plot_border",
"(",
"mask",
",",
"should_plot_border",
",",
"units",
",",
"kpc_per_arcsec",
",",
"pointsize",
",",
"zoom_offset_pixels",
")",
":",
"if",
"should_plot_border",
"and",
"mask",
"is",
"not",
"None",
":",
"plt",
".",
"gca",
"(",
")",
"borde... | 47.310345 | 30.275862 |
def all(self):
"""
Returns a list of cached instances.
"""
class_list = list(self.get_class_list())
if not class_list:
self.cache = []
return []
if self.cache is not None:
return self.cache
results = []
for cls_path in... | [
"def",
"all",
"(",
"self",
")",
":",
"class_list",
"=",
"list",
"(",
"self",
".",
"get_class_list",
"(",
")",
")",
"if",
"not",
"class_list",
":",
"self",
".",
"cache",
"=",
"[",
"]",
"return",
"[",
"]",
"if",
"self",
".",
"cache",
"is",
"not",
"... | 29.642857 | 16.071429 |
def from_array(array):
"""
Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict... | [
"def",
"from_array",
"(",
"array",
")",
":",
"if",
"array",
"is",
"None",
"or",
"not",
"array",
":",
"return",
"None",
"# end if",
"assert_type_or_raise",
"(",
"array",
",",
"dict",
",",
"parameter_name",
"=",
"\"array\"",
")",
"from",
"pytgbot",
".",
"api... | 33.473684 | 19.157895 |
def fix_logging_path(config, main_section):
"""
Expand environment variables and user home (~) in the log.file and return
as relative path.
"""
log_file = config.get(main_section, 'log.file')
if log_file:
log_file = os.path.expanduser(os.path.expandvars(log_file))
if os.path.isab... | [
"def",
"fix_logging_path",
"(",
"config",
",",
"main_section",
")",
":",
"log_file",
"=",
"config",
".",
"get",
"(",
"main_section",
",",
"'log.file'",
")",
"if",
"log_file",
":",
"log_file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"pa... | 35.545455 | 14.090909 |
def ffmpeg_works():
"""Tries to encode images with ffmpeg to check if it works."""
images = np.zeros((2, 32, 32, 3), dtype=np.uint8)
try:
_encode_gif(images, 2)
return True
except (IOError, OSError):
return False | [
"def",
"ffmpeg_works",
"(",
")",
":",
"images",
"=",
"np",
".",
"zeros",
"(",
"(",
"2",
",",
"32",
",",
"32",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"try",
":",
"_encode_gif",
"(",
"images",
",",
"2",
")",
"return",
"True",
... | 28.125 | 17.625 |
def _initialise_classifier(self, comparison_vectors):
"""Set the centers of the clusters."""
# Set the start point of the classifier.
self.kernel.init = numpy.array(
[[0.05] * len(list(comparison_vectors)),
[0.95] * len(list(comparison_vectors))]) | [
"def",
"_initialise_classifier",
"(",
"self",
",",
"comparison_vectors",
")",
":",
"# Set the start point of the classifier.",
"self",
".",
"kernel",
".",
"init",
"=",
"numpy",
".",
"array",
"(",
"[",
"[",
"0.05",
"]",
"*",
"len",
"(",
"list",
"(",
"comparison... | 41.571429 | 12.428571 |
def _validate_charset(data, charset):
""""Validate that the charset is correct and throw an error if it isn't."""
if len(charset) > 1:
charset_data_length = 0
for symbol_charset in charset:
if symbol_charset not in ('A', 'B', 'C'):
raise Code12... | [
"def",
"_validate_charset",
"(",
"data",
",",
"charset",
")",
":",
"if",
"len",
"(",
"charset",
")",
">",
"1",
":",
"charset_data_length",
"=",
"0",
"for",
"symbol_charset",
"in",
"charset",
":",
"if",
"symbol_charset",
"not",
"in",
"(",
"'A'",
",",
"'B'... | 45.733333 | 7.933333 |
def create(cls, parent=None, **kwargs):
"""Create an object and return it"""
if parent is None:
raise Exception("Parent class is required")
route = copy(parent.route)
if cls.ID_NAME is not None:
route[cls.ID_NAME] = ""
obj = cls(key=parent.key, route=ro... | [
"def",
"create",
"(",
"cls",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parent",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Parent class is required\"",
")",
"route",
"=",
"copy",
"(",
"parent",
".",
"route",
")",
"if",... | 31.04 | 20.64 |
def lstm_unroll(num_lstm_layer, seq_len, num_hidden, num_label, loss_type=None):
"""
Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training
if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc'
Parameters
----------
num_lstm_layer: int
... | [
"def",
"lstm_unroll",
"(",
"num_lstm_layer",
",",
"seq_len",
",",
"num_hidden",
",",
"num_label",
",",
"loss_type",
"=",
"None",
")",
":",
"# Create the base (shared between training and inference) and add loss to the end",
"pred",
"=",
"_lstm_unroll_base",
"(",
"num_lstm_l... | 30.814815 | 24.666667 |
def values(self):
"""
Return the list of values.
"""
def collect(d):
if d is None or d.get('FIRST') is None:
return []
vals = [d['FIRST']]
vals.extend(collect(d.get('REST')))
return vals
return collect(self) | [
"def",
"values",
"(",
"self",
")",
":",
"def",
"collect",
"(",
"d",
")",
":",
"if",
"d",
"is",
"None",
"or",
"d",
".",
"get",
"(",
"'FIRST'",
")",
"is",
"None",
":",
"return",
"[",
"]",
"vals",
"=",
"[",
"d",
"[",
"'FIRST'",
"]",
"]",
"vals",... | 27.363636 | 10.636364 |
def parent_folder(self):
# type: () -> Folder
""" Returns the :class:`Folder <pyOutlook.core.folder.Folder>` this message is in
>>> account = OutlookAccount('')
>>> message = account.get_messages()[0]
>>> message.parent_folder
Inbox
>>> messag... | [
"def",
"parent_folder",
"(",
"self",
")",
":",
"# type: () -> Folder",
"if",
"self",
".",
"__parent_folder",
"is",
"None",
":",
"self",
".",
"__parent_folder",
"=",
"self",
".",
"account",
".",
"get_folder_by_id",
"(",
"self",
".",
"__parent_folder_id",
")",
"... | 32.888889 | 19 |
def update_app(self, app):
"""
Loads and runs `update_initial_data` of the specified app. Any dependencies contained within the
initial data class will be run recursively. Dependency cycles are checked for and a cache is built
for updated apps to prevent updating the same app more than o... | [
"def",
"update_app",
"(",
"self",
",",
"app",
")",
":",
"# don't update this app if it has already been updated",
"if",
"app",
"in",
"self",
".",
"updated_apps",
":",
"return",
"# load the initial data class",
"try",
":",
"initial_data_class",
"=",
"self",
".",
"load_... | 44.9 | 28.06 |
def sendHeartbeat(self):
"""
Posts the current state to the server.
:param serverURL: the URL to ping.
:return:
"""
for name, md in self.cfg.recordingDevices.items():
try:
data = marshal(md, recordingDeviceFields)
data['serviceU... | [
"def",
"sendHeartbeat",
"(",
"self",
")",
":",
"for",
"name",
",",
"md",
"in",
"self",
".",
"cfg",
".",
"recordingDevices",
".",
"items",
"(",
")",
":",
"try",
":",
"data",
"=",
"marshal",
"(",
"md",
",",
"recordingDeviceFields",
")",
"data",
"[",
"'... | 49.2 | 22.5 |
async def blobize(self, elem=None, elem_type=None, params=None):
"""
Main blobbing
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
await self.field(elem=elem, elem_type=elem_type, params=params)
return by... | [
"async",
"def",
"blobize",
"(",
"self",
",",
"elem",
"=",
"None",
",",
"elem_type",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"await",
"self",
".",
"field",
"(",
"elem",
"=",
"elem",
",",
"elem_type",
"="... | 32.769231 | 18.615385 |
def populate_local_sch_cache(self, fw_dict):
"""Populate the local cache from FW DB after restart. """
for fw_id in fw_dict:
fw_data = fw_dict.get(fw_id)
mgmt_ip = fw_data.get('fw_mgmt_ip')
dev_status = fw_data.get('device_status')
if dev_status == 'SUCCES... | [
"def",
"populate_local_sch_cache",
"(",
"self",
",",
"fw_dict",
")",
":",
"for",
"fw_id",
"in",
"fw_dict",
":",
"fw_data",
"=",
"fw_dict",
".",
"get",
"(",
"fw_id",
")",
"mgmt_ip",
"=",
"fw_data",
".",
"get",
"(",
"'fw_mgmt_ip'",
")",
"dev_status",
"=",
... | 47.823529 | 14.352941 |
def DeregisterOutput(cls, output_class):
"""Deregisters an output class.
The output classes are identified based on their NAME attribute.
Args:
output_class (type): output module class.
Raises:
KeyError: if output class is not set for the corresponding data type.
"""
output_class_... | [
"def",
"DeregisterOutput",
"(",
"cls",
",",
"output_class",
")",
":",
"output_class_name",
"=",
"output_class",
".",
"NAME",
".",
"lower",
"(",
")",
"if",
"output_class_name",
"in",
"cls",
".",
"_disabled_output_classes",
":",
"class_dict",
"=",
"cls",
".",
"_... | 28.458333 | 20.208333 |
def vssa(self):
r'''The volume-specific surface area of a particle size distribution.
Note this uses the diameters provided by the method `Dis`.
.. math::
\text{VSSA} = \sum_i \text{fraction}_i \frac{SA_i}{V_i}
Returns
-------
VSSA : float
... | [
"def",
"vssa",
"(",
"self",
")",
":",
"ds",
"=",
"self",
".",
"Dis",
"Vs",
"=",
"[",
"pi",
"/",
"6",
"*",
"di",
"**",
"3",
"for",
"di",
"in",
"ds",
"]",
"SAs",
"=",
"[",
"pi",
"*",
"di",
"**",
"2",
"for",
"di",
"in",
"ds",
"]",
"SASs",
... | 37.695652 | 24.478261 |
def parity_discover_next_available_nonce(
web3: Web3,
address: AddressHex,
) -> Nonce:
"""Returns the next available nonce for `address`."""
next_nonce_encoded = web3.manager.request_blocking('parity_nextNonce', [address])
return Nonce(int(next_nonce_encoded, 16)) | [
"def",
"parity_discover_next_available_nonce",
"(",
"web3",
":",
"Web3",
",",
"address",
":",
"AddressHex",
",",
")",
"->",
"Nonce",
":",
"next_nonce_encoded",
"=",
"web3",
".",
"manager",
".",
"request_blocking",
"(",
"'parity_nextNonce'",
",",
"[",
"address",
... | 40.857143 | 16.142857 |
def _recv_loop(self):
"""
Waits for data forever and feeds the input queue.
"""
while True:
try:
data = self._socket.recv(4096)
self._ibuffer += data
while '\r\n' in self._ibuffer:
line, self._ibuffer = self.... | [
"def",
"_recv_loop",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"data",
"=",
"self",
".",
"_socket",
".",
"recv",
"(",
"4096",
")",
"self",
".",
"_ibuffer",
"+=",
"data",
"while",
"'\\r\\n'",
"in",
"self",
".",
"_ibuffer",
":",
"line",
... | 32.846154 | 12.230769 |
def add_candidate_peer_endpoints(self, peer_endpoints):
"""Adds candidate endpoints to the list of endpoints to
attempt to peer with.
Args:
peer_endpoints ([str]): A list of public uri's which the
validator can attempt to peer with.
"""
if self._topol... | [
"def",
"add_candidate_peer_endpoints",
"(",
"self",
",",
"peer_endpoints",
")",
":",
"if",
"self",
".",
"_topology",
":",
"self",
".",
"_topology",
".",
"add_candidate_peer_endpoints",
"(",
"peer_endpoints",
")",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"\"Coul... | 40.769231 | 19.538462 |
def limit_mem(limit=(4 * 1024**3)):
"Set soft memory limit"
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
resource.setrlimit(rsrc, (limit, hard)) # 4GB
softnew, _ = resource.getrlimit(rsrc)
assert softnew == limit
_log = logging.getLogger(__name__)
_log.debug('Set s... | [
"def",
"limit_mem",
"(",
"limit",
"=",
"(",
"4",
"*",
"1024",
"**",
"3",
")",
")",
":",
"rsrc",
"=",
"resource",
".",
"RLIMIT_DATA",
"soft",
",",
"hard",
"=",
"resource",
".",
"getrlimit",
"(",
"rsrc",
")",
"resource",
".",
"setrlimit",
"(",
"rsrc",
... | 35.4 | 11.8 |
def add_from_depend(self, node, from_module):
"""add dependencies created by from-imports
"""
mod_name = node.root().name
obj = self.module(mod_name)
if from_module not in obj.node.depends:
obj.node.depends.append(from_module) | [
"def",
"add_from_depend",
"(",
"self",
",",
"node",
",",
"from_module",
")",
":",
"mod_name",
"=",
"node",
".",
"root",
"(",
")",
".",
"name",
"obj",
"=",
"self",
".",
"module",
"(",
"mod_name",
")",
"if",
"from_module",
"not",
"in",
"obj",
".",
"nod... | 38.857143 | 4.285714 |
def extract_attr_for_match(items, **kwargs):
"""Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb... | [
"def",
"extract_attr_for_match",
"(",
"items",
",",
"*",
"*",
"kwargs",
")",
":",
"# find the value of attribute to return",
"query_arg",
"=",
"None",
"for",
"arg",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"-",
"1",
"... | 30.769231 | 20.333333 |
def __register_driver(self, channel, webdriver):
"Register webdriver to a channel."
# Add to list of webdrivers to cleanup.
if not self.__registered_drivers.has_key(channel):
self.__registered_drivers[channel] = [] # set to new empty array
self.__registered_drivers[channel... | [
"def",
"__register_driver",
"(",
"self",
",",
"channel",
",",
"webdriver",
")",
":",
"# Add to list of webdrivers to cleanup.",
"if",
"not",
"self",
".",
"__registered_drivers",
".",
"has_key",
"(",
"channel",
")",
":",
"self",
".",
"__registered_drivers",
"[",
"c... | 38.636364 | 20.454545 |
def send_email_confirmation_instructions(self, user):
"""
Sends the confirmation instructions email for the specified user.
Sends signal `confirm_instructions_sent`.
:param user: The user to send the instructions to.
"""
token = self.security_utils_service.generate_conf... | [
"def",
"send_email_confirmation_instructions",
"(",
"self",
",",
"user",
")",
":",
"token",
"=",
"self",
".",
"security_utils_service",
".",
"generate_confirmation_token",
"(",
"user",
")",
"confirmation_link",
"=",
"url_for",
"(",
"'security_controller.confirm_email'",
... | 46.578947 | 23.210526 |
def _remove_empty_items(d, required):
"""Return a new dict with any empty items removed.
Note that this is not a deep check. If d contains a dictionary which
itself contains empty items, those are never checked.
This method exists to make to_serializable() functions cleaner.
We could revisit this some day, ... | [
"def",
"_remove_empty_items",
"(",
"d",
",",
"required",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"required",
":",
"new_dict",
"[",
"k",
"]",
"=",
"v",
"elif",
"isinstance... | 28.821429 | 22.571429 |
def _init_object(self, catalog_id, proxy, runtime, db_name, cat_name, cat_class):
"""Initialize this session an OsidObject based session."""
self._catalog_identifier = None
self._init_proxy_and_runtime(proxy, runtime)
uses_cataloging = False
if catalog_id is not None and catalog... | [
"def",
"_init_object",
"(",
"self",
",",
"catalog_id",
",",
"proxy",
",",
"runtime",
",",
"db_name",
",",
"cat_name",
",",
"cat_class",
")",
":",
"self",
".",
"_catalog_identifier",
"=",
"None",
"self",
".",
"_init_proxy_and_runtime",
"(",
"proxy",
",",
"run... | 58.431818 | 33.431818 |
def add(self, line):
"""
Append 'line' to contents
where 'line' is an entire line or a list of lines.
If self.unique is False it will add regardless of contents.
Multi-line strings are converted to a list delimited by new lines.
:param line: String or List of Strin... | [
"def",
"add",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"unique",
"is",
"not",
"False",
"and",
"self",
".",
"unique",
"is",
"not",
"True",
":",
"raise",
"AttributeError",
"(",
"\"Attribute 'unique' is not True or False.\"",
")",
"self",
".",
"... | 41.965517 | 21 |
def add_view_menu(self, name):
"""
Adds a view or menu to the backend, model view_menu
param name:
name of the view menu to add
"""
view_menu = self.find_view_menu(name)
if view_menu is None:
try:
view_menu = self.viewme... | [
"def",
"add_view_menu",
"(",
"self",
",",
"name",
")",
":",
"view_menu",
"=",
"self",
".",
"find_view_menu",
"(",
"name",
")",
"if",
"view_menu",
"is",
"None",
":",
"try",
":",
"view_menu",
"=",
"self",
".",
"viewmenu_model",
"(",
")",
"view_menu",
".",
... | 36.111111 | 9.888889 |
def examples(self):
"""Return examples from all sub-spaces."""
for examples in product(*[spc.examples for spc in self.spaces]):
name = ', '.join(name for name, _ in examples)
element = self.element([elem for _, elem in examples])
yield (name, element) | [
"def",
"examples",
"(",
"self",
")",
":",
"for",
"examples",
"in",
"product",
"(",
"*",
"[",
"spc",
".",
"examples",
"for",
"spc",
"in",
"self",
".",
"spaces",
"]",
")",
":",
"name",
"=",
"', '",
".",
"join",
"(",
"name",
"for",
"name",
",",
"_",... | 49.666667 | 17.333333 |
def exhaustive_ontology_ilx_diff_row_only( self, ontology_row: dict ) -> dict:
''' WARNING RUNTIME IS AWEFUL '''
results = []
header = ['Index'] + list(self.existing_ids.columns)
for row in self.existing_ids.itertuples():
row = {header[i]:val for i, val in enumerate(row)}
... | [
"def",
"exhaustive_ontology_ilx_diff_row_only",
"(",
"self",
",",
"ontology_row",
":",
"dict",
")",
"->",
"dict",
":",
"results",
"=",
"[",
"]",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"existing_ids",
".",
"columns",
")",
"for",
... | 43.529412 | 19.764706 |
def retrieve_bicluster(self, df, row_no, column_no):
"""
Extracts the bicluster at the given row bicluster number and the column bicluster number from the input dataframe.
:param df: the input dataframe whose values were biclustered
:param row_no: the number of the row bicluster
... | [
"def",
"retrieve_bicluster",
"(",
"self",
",",
"df",
",",
"row_no",
",",
"column_no",
")",
":",
"res",
"=",
"df",
"[",
"self",
".",
"model",
".",
"biclusters_",
"[",
"0",
"]",
"[",
"row_no",
"]",
"]",
"bicluster",
"=",
"res",
"[",
"res",
".",
"colu... | 48.833333 | 23 |
def quality(self):
"""Return a dict filled with metrics related to the inner
quality of the dataset:
* number of tags
* description length
* and so on
"""
from udata.models import Discussion # noqa: Prevent circular imports
result = {}
... | [
"def",
"quality",
"(",
"self",
")",
":",
"from",
"udata",
".",
"models",
"import",
"Discussion",
"# noqa: Prevent circular imports",
"result",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"id",
":",
"# Quality is only relevant on saved Datasets",
"return",
"result",
"... | 39.742857 | 16.657143 |
def add_options(self):
""" Add program options.
"""
super(RtorrentQueueManager, self).add_options()
self.jobs = None
self.httpd = None
# basic options
self.add_bool_option("-n", "--dry-run",
help="advise jobs not to do any real work, just tell what wo... | [
"def",
"add_options",
"(",
"self",
")",
":",
"super",
"(",
"RtorrentQueueManager",
",",
"self",
")",
".",
"add_options",
"(",
")",
"self",
".",
"jobs",
"=",
"None",
"self",
".",
"httpd",
"=",
"None",
"# basic options",
"self",
".",
"add_bool_option",
"(",
... | 51.722222 | 25.555556 |
def calc_requiredremoterelease_v2(self):
"""Get the required remote release of the last simulation step.
Required log sequence:
|LoggedRequiredRemoteRelease|
Calculated flux sequence:
|RequiredRemoteRelease|
Basic equation:
:math:`RequiredRemoteRelease = LoggedRequiredRemoteRelease`... | [
"def",
"calc_requiredremoterelease_v2",
"(",
"self",
")",
":",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"log",
"=",
"self",
".",
"sequences",
".",
"logs",
".",
"fastaccess",
"flu",
".",
"requiredremoterelease",
"=",
"log",
".",... | 29.958333 | 15.958333 |
def threshold_image(img, bkground_thresh, bkground_value=0.0):
"""
Thresholds a given image at a value or percentile.
Replacement value can be specified too.
Parameters
-----------
image_in : ndarray
Input image
bkground_thresh : float
a threshold value to identify the ba... | [
"def",
"threshold_image",
"(",
"img",
",",
"bkground_thresh",
",",
"bkground_value",
"=",
"0.0",
")",
":",
"if",
"bkground_thresh",
"is",
"None",
":",
"return",
"img",
"if",
"isinstance",
"(",
"bkground_thresh",
",",
"str",
")",
":",
"try",
":",
"thresh_perc... | 25.021739 | 23.23913 |
def show_disk(name, call=None):
'''
Show the disk details of the instance
CLI Examples:
.. code-block:: bash
salt-cloud -a show_disk aliyun myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_disks action must be called with -a or --action.'
... | [
"def",
"show_disk",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_disks action must be called with -a or --action.'",
")",
"ret",
"=",
"{",
"}",
"params",
"=",
"{",
"'Action'... | 22.142857 | 22.714286 |
def show_network(self):
"""!
@brief Shows structure of the network: neurons and connections between them.
"""
dimension = len(self.__location[0])
if (dimension != 3) and (dimension != 2):
raise NameError('Network that is located in different ... | [
"def",
"show_network",
"(",
"self",
")",
":",
"dimension",
"=",
"len",
"(",
"self",
".",
"__location",
"[",
"0",
"]",
")",
"if",
"(",
"dimension",
"!=",
"3",
")",
"and",
"(",
"dimension",
"!=",
"2",
")",
":",
"raise",
"NameError",
"(",
"'Network that... | 53.392857 | 35.357143 |
def _update_class(self, oldclass, newclass):
"""Update a class object."""
olddict = oldclass.__dict__
newdict = newclass.__dict__
oldnames = set(olddict)
newnames = set(newdict)
for name in newnames - oldnames:
setattr(oldclass, name, newdict[name])
... | [
"def",
"_update_class",
"(",
"self",
",",
"oldclass",
",",
"newclass",
")",
":",
"olddict",
"=",
"oldclass",
".",
"__dict__",
"newdict",
"=",
"newclass",
".",
"__dict__",
"oldnames",
"=",
"set",
"(",
"olddict",
")",
"newnames",
"=",
"set",
"(",
"newdict",
... | 40 | 20.592593 |
def get_next_version() -> str:
"""
Returns: next version for this Git repository
"""
LOGGER.info('computing next version')
should_be_alpha = bool(CTX.repo.get_current_branch() != 'master')
LOGGER.info('alpha: %s', should_be_alpha)
calver = _get_calver()
LOGGER.info('current calver: %s', ... | [
"def",
"get_next_version",
"(",
")",
"->",
"str",
":",
"LOGGER",
".",
"info",
"(",
"'computing next version'",
")",
"should_be_alpha",
"=",
"bool",
"(",
"CTX",
".",
"repo",
".",
"get_current_branch",
"(",
")",
"!=",
"'master'",
")",
"LOGGER",
".",
"info",
... | 40.882353 | 15.470588 |
def get_victoria_day(self, year):
"""
Return Victoria Day for Edinburgh.
Set to the Monday strictly before May 24th. It means that if May 24th
is a Monday, it's shifted to the week before.
"""
may_24th = date(year, 5, 24)
# Since "MON(day) == 0", it's either the ... | [
"def",
"get_victoria_day",
"(",
"self",
",",
"year",
")",
":",
"may_24th",
"=",
"date",
"(",
"year",
",",
"5",
",",
"24",
")",
"# Since \"MON(day) == 0\", it's either the difference between MON and the",
"# current weekday (starting at 0), or 7 days before the May 24th",
"shi... | 42.538462 | 15 |
def download(url, tries=DEFAULT_TRIES, retry_delay=RETRY_DELAY,
try_timeout=None, proxies=None, verify=True):
"""
Descarga un archivo a través del protocolo HTTP, en uno o más intentos.
Args:
url (str): URL (schema HTTP) del archivo a descargar.
tries (int): Intentos a realizar... | [
"def",
"download",
"(",
"url",
",",
"tries",
"=",
"DEFAULT_TRIES",
",",
"retry_delay",
"=",
"RETRY_DELAY",
",",
"try_timeout",
"=",
"None",
",",
"proxies",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"for",
"i",
"in",
"range",
"(",
"tries",
")",... | 36.344828 | 21.862069 |
def post_login(cookie, tokens, username, password, rsakey, verifycode='',
codestring=''):
'''登录验证.
password - 使用RSA加密后的base64字符串
rsakey - 与public_key相匹配的rsakey
verifycode - 验证码, 默认为空
@return (status, info). 其中, status表示返回的状态:
0 - 正常, 这里, info里面存放的是auth_cookie
-1 - 未知... | [
"def",
"post_login",
"(",
"cookie",
",",
"tokens",
",",
"username",
",",
"password",
",",
"rsakey",
",",
"verifycode",
"=",
"''",
",",
"codestring",
"=",
"''",
")",
":",
"url",
"=",
"const",
".",
"PASSPORT_LOGIN",
"data",
"=",
"''",
".",
"join",
"(",
... | 33.059701 | 16.671642 |
def load_term_config(filter_name,
term_name,
filter_options=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
revision_id=None,
r... | [
"def",
"load_term_config",
"(",
"filter_name",
",",
"term_name",
",",
"filter_options",
"=",
"None",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"revision_id",
"=",
"None... | 32.785714 | 22.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.