text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def interactive():
"""Interactive classifier."""
global n
if request.method == 'GET' and request.args.get('heartbeat', '') != "":
return request.args.get('heartbeat', '')
if request.method == 'POST':
logging.warning('POST to /interactive is deprecated. '
'Use /wor... | [
"def",
"interactive",
"(",
")",
":",
"global",
"n",
"if",
"request",
".",
"method",
"==",
"'GET'",
"and",
"request",
".",
"args",
".",
"get",
"(",
"'heartbeat'",
",",
"''",
")",
"!=",
"\"\"",
":",
"return",
"request",
".",
"args",
".",
"get",
"(",
... | 39.181818 | 16 |
def get_license_manager(service_instance):
'''
Returns the license manager.
service_instance
The Service Instance Object from which to obrain the license manager.
'''
log.debug('Retrieving license manager')
try:
lic_manager = service_instance.content.licenseManager
except v... | [
"def",
"get_license_manager",
"(",
"service_instance",
")",
":",
"log",
".",
"debug",
"(",
"'Retrieving license manager'",
")",
"try",
":",
"lic_manager",
"=",
"service_instance",
".",
"content",
".",
"licenseManager",
"except",
"vim",
".",
"fault",
".",
"NoPermis... | 33.347826 | 17 |
def uninstall(args):
" Uninstall site. "
site = find_site(args.PATH)
site.run_remove()
site.clean()
if not listdir(op.dirname(site.deploy_dir)):
call('sudo rm -rf %s' % op.dirname(site.deploy_dir)) | [
"def",
"uninstall",
"(",
"args",
")",
":",
"site",
"=",
"find_site",
"(",
"args",
".",
"PATH",
")",
"site",
".",
"run_remove",
"(",
")",
"site",
".",
"clean",
"(",
")",
"if",
"not",
"listdir",
"(",
"op",
".",
"dirname",
"(",
"site",
".",
"deploy_di... | 27.375 | 19.625 |
def generate_distance_matrix(source, target, weights=None):
"""Generates a local distance matrix for use in dynamic time warping.
Parameters
----------
source : 2D array
Source matrix with features in the second dimension.
target : 2D array
Target matrix with features in the second ... | [
"def",
"generate_distance_matrix",
"(",
"source",
",",
"target",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"ones",
"(",
"(",
"source",
".",
"shape",
"[",
"1",
"]",
",",
"1",
")",
")",
"sLen",
"=",
"s... | 27.28 | 19.76 |
def type_names(prefix, sizerange):
"""
Helper for type name generation, like: bytes1 .. bytes32
"""
namelist = []
for i in sizerange: namelist.append(prefix + str(i))
return tuple(namelist) | [
"def",
"type_names",
"(",
"prefix",
",",
"sizerange",
")",
":",
"namelist",
"=",
"[",
"]",
"for",
"i",
"in",
"sizerange",
":",
"namelist",
".",
"append",
"(",
"prefix",
"+",
"str",
"(",
"i",
")",
")",
"return",
"tuple",
"(",
"namelist",
")"
] | 33 | 11.285714 |
def run_query(
self,
parent,
structured_query=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Ru... | [
"def",
"run_query",
"(",
"self",
",",
"parent",
",",
"structured_query",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"new_transaction",
"=",
"None",
",",
"read_time",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
... | 44.522124 | 26.327434 |
def setMaxDaysBack(self, maxDaysBack):
"""
what is the maximum allowed age of the results?
"""
assert isinstance(maxDaysBack, int), "maxDaysBack value has to be a positive integer"
assert maxDaysBack >= 1
self.topicPage["maxDaysBack"] = maxDaysBack | [
"def",
"setMaxDaysBack",
"(",
"self",
",",
"maxDaysBack",
")",
":",
"assert",
"isinstance",
"(",
"maxDaysBack",
",",
"int",
")",
",",
"\"maxDaysBack value has to be a positive integer\"",
"assert",
"maxDaysBack",
">=",
"1",
"self",
".",
"topicPage",
"[",
"\"maxDaysB... | 41.428571 | 12.857143 |
def _words_at_the_beginning(word, tree, prefix=""):
'''
We return all portions of the tree corresponding to the beginning
of `word`. This is used recursively, so we pass the prefix so we
can return meaningful words+translations.
'''
l = []
if "" in tree:
l.append([prefix, tree[""]])
... | [
"def",
"_words_at_the_beginning",
"(",
"word",
",",
"tree",
",",
"prefix",
"=",
"\"\"",
")",
":",
"l",
"=",
"[",
"]",
"if",
"\"\"",
"in",
"tree",
":",
"l",
".",
"append",
"(",
"[",
"prefix",
",",
"tree",
"[",
"\"\"",
"]",
"]",
")",
"if",
"len",
... | 30.9375 | 18.4375 |
def _getFuncArgs(func):
r"""Gives the details on the args of the given func.
Args:
func (function): The function to get details on.
"""
code = func.func_code
Defaults = func.func_defaults
nargs = code.co_argcount
ArgNames = code.co_varnames[:nargs]
Args = OrderedDict()
argCount = len(ArgNames)
... | [
"def",
"_getFuncArgs",
"(",
"func",
")",
":",
"code",
"=",
"func",
".",
"func_code",
"Defaults",
"=",
"func",
".",
"func_defaults",
"nargs",
"=",
"code",
".",
"co_argcount",
"ArgNames",
"=",
"code",
".",
"co_varnames",
"[",
":",
"nargs",
"]",
"Args",
"="... | 22.166667 | 19.625 |
def destination_uris(self):
"""
The fully-qualified URIs that point to your data in Google Cloud
Storage. Each URI can contain one '*' wildcard character and it must
come after the 'bucket' name.
Wildcarded destinationUris in GCSQueryTarget might not be resolved
correctl... | [
"def",
"destination_uris",
"(",
"self",
")",
":",
"return",
"[",
"x",
".",
"path",
"for",
"x",
"in",
"luigi",
".",
"task",
".",
"flatten",
"(",
"self",
".",
"output",
"(",
")",
")",
"]"
] | 46.583333 | 22.583333 |
def is_ordered_mapping(obj):
"""Checks whether given object is an ordered mapping,
e.g. a :class:`OrderedDict`.
:return: ``True`` if argument is an ordered mapping, ``False`` otherwise
"""
if not (is_mapping(obj) and hasattr(obj, '__reversed__')):
return False
# PyPy has a bug where the... | [
"def",
"is_ordered_mapping",
"(",
"obj",
")",
":",
"if",
"not",
"(",
"is_mapping",
"(",
"obj",
")",
"and",
"hasattr",
"(",
"obj",
",",
"'__reversed__'",
")",
")",
":",
"return",
"False",
"# PyPy has a bug where the standard :class:`dict` has the ``__reversed__``",
"... | 33.0625 | 21.1875 |
def result_sort(result_list, start_index=0):
"""Sorts a list of results in O(n) in place (since every run is unique)
:param result_list: List of tuples [(run_idx, res), ...]
:param start_index: Index with which to start, every entry before `start_index` is ignored
"""
if len(result_list) < 2:
... | [
"def",
"result_sort",
"(",
"result_list",
",",
"start_index",
"=",
"0",
")",
":",
"if",
"len",
"(",
"result_list",
")",
"<",
"2",
":",
"return",
"result_list",
"to_sort",
"=",
"result_list",
"[",
"start_index",
":",
"]",
"minmax",
"=",
"[",
"x",
"[",
"... | 33.541667 | 14.875 |
def _add_from_list(self, l):
"""Add locations from a list of either strings or lists or tuples.
Lists of lists and tuples are passed to the Location constructor
"""
for item in l:
if isinstance(item, (str, ustr)):
self._add_from_str(item)
elif is... | [
"def",
"_add_from_list",
"(",
"self",
",",
"l",
")",
":",
"for",
"item",
"in",
"l",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"str",
",",
"ustr",
")",
")",
":",
"self",
".",
"_add_from_str",
"(",
"item",
")",
"elif",
"isinstance",
"(",
"item"... | 35.5 | 13.416667 |
def updateIndexConfiguration(self,
indexerHost="localhost",
indexerPort=7199):
"""
You can use this operation to change the connection information for
the indexing service. By default, Portal for ArcGIS runs an
indexing se... | [
"def",
"updateIndexConfiguration",
"(",
"self",
",",
"indexerHost",
"=",
"\"localhost\"",
",",
"indexerPort",
"=",
"7199",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/indexer/update\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"indexerHost\... | 45.111111 | 18.37037 |
def error(self, msg, n):
"""Raise a SyntaxError with the lineno and col_offset set to n's."""
raise SyntaxError(msg, n.lineno, n.col_offset,
filename=self.compile_info.filename) | [
"def",
"error",
"(",
"self",
",",
"msg",
",",
"n",
")",
":",
"raise",
"SyntaxError",
"(",
"msg",
",",
"n",
".",
"lineno",
",",
"n",
".",
"col_offset",
",",
"filename",
"=",
"self",
".",
"compile_info",
".",
"filename",
")"
] | 54 | 13 |
def _set_lsp_secpath_auto_bandwidth(self, v, load=False):
"""
Setter method for lsp_secpath_auto_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth (container)
If this variable is read-only (config: false) in the
source YANG file,... | [
"def",
"_set_lsp_secpath_auto_bandwidth",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v... | 106 | 51.590909 |
def get_limit_queryset(self):
"""
返回分页之后的queryset
"""
queryset = self.get_queryset()
limit_queryset = queryset.all()[self.get_slice_start() :self.get_slice_end()] #等增加排序
return limit_queryset | [
"def",
"get_limit_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"limit_queryset",
"=",
"queryset",
".",
"all",
"(",
")",
"[",
"self",
".",
"get_slice_start",
"(",
")",
":",
"self",
".",
"get_slice_end",
"(",
")... | 33.428571 | 13.142857 |
def _add_file_mask(self, start, method_str, method):
"""Adds a raw file mask for dynamic requests.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to trigger ... | [
"def",
"_add_file_mask",
"(",
"self",
",",
"start",
",",
"method_str",
",",
"method",
")",
":",
"fm",
"=",
"self",
".",
"_f_mask",
".",
"get",
"(",
"method_str",
",",
"[",
"]",
")",
"fm",
".",
"append",
"(",
"(",
"start",
",",
"method",
")",
")",
... | 45.75 | 22.821429 |
def raise_403(instance, msg=None):
"""Abort the current request with a 403 (Forbidden) response code. If the
message is given it's output as an error message in the response body
(correctly converted to the requested MIME type).
:param instance: Resource instance (used to access the response)
:type... | [
"def",
"raise_403",
"(",
"instance",
",",
"msg",
"=",
"None",
")",
":",
"instance",
".",
"response",
".",
"status",
"=",
"403",
"if",
"msg",
":",
"instance",
".",
"response",
".",
"body_raw",
"=",
"{",
"'error'",
":",
"msg",
"}",
"raise",
"ResponseExce... | 44.307692 | 16.461538 |
def reset_mock(self, visited=None):
"""Reset the default tell/read/write/etc side effects."""
# In some versions of the mock library, `reset_mock` takes an argument
# and in some it doesn't. We try to handle all situations.
if visited is not None:
super(FileLikeMock, self).re... | [
"def",
"reset_mock",
"(",
"self",
",",
"visited",
"=",
"None",
")",
":",
"# In some versions of the mock library, `reset_mock` takes an argument",
"# and in some it doesn't. We try to handle all situations.",
"if",
"visited",
"is",
"not",
"None",
":",
"super",
"(",
"FileLikeM... | 44.166667 | 17.75 |
def generate_window(length, window=None, dtype='float64'):
"""Generate a time-domain window for use in a LAL FFT
Parameters
----------
length : `int`
length of window in samples.
window : `str`, `tuple`
name of window to generate, default: ``('kaiser', 24)``. Give
`str` for... | [
"def",
"generate_window",
"(",
"length",
",",
"window",
"=",
"None",
",",
"dtype",
"=",
"'float64'",
")",
":",
"from",
".",
".",
".",
"utils",
".",
"lal",
"import",
"(",
"find_typed_function",
",",
"to_lal_type_str",
")",
"if",
"window",
"is",
"None",
":... | 29.466667 | 19.2 |
def _validate(self):
"""
Actual validation.
"""
try:
self._resolve_workspace()
if 'mets_unique_identifier' not in self.skip:
self._validate_mets_unique_identifier()
if 'mets_file_group_names' not in self.skip:
self._vali... | [
"def",
"_validate",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_resolve_workspace",
"(",
")",
"if",
"'mets_unique_identifier'",
"not",
"in",
"self",
".",
"skip",
":",
"self",
".",
"_validate_mets_unique_identifier",
"(",
")",
"if",
"'mets_file_group_names'... | 39.1 | 12.1 |
def _split_one_shard_to_multiple(client, project, logstore, shard_info, count, current_shard_count):
"""return new_rw_shards_list, increased_shard_count """
distance = shard_info['length'] // count
if distance <= 0 or count <= 1:
return [shard_info['info']], 0
rw_shards, increased_shard_count =... | [
"def",
"_split_one_shard_to_multiple",
"(",
"client",
",",
"project",
",",
"logstore",
",",
"shard_info",
",",
"count",
",",
"current_shard_count",
")",
":",
"distance",
"=",
"shard_info",
"[",
"'length'",
"]",
"//",
"count",
"if",
"distance",
"<=",
"0",
"or",... | 45.727273 | 25.393939 |
def update(self, configuration=values.unset, unique_name=values.unset):
"""
Update the InstalledAddOnInstance
:param dict configuration: The JSON object representing the configuration
:param unicode unique_name: The string that uniquely identifies this Add-on installation
:retu... | [
"def",
"update",
"(",
"self",
",",
"configuration",
"=",
"values",
".",
"unset",
",",
"unique_name",
"=",
"values",
".",
"unset",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'Configuration'",
":",
"serialize",
".",
"object",
"(",
"configuratio... | 39.578947 | 28.842105 |
def run(app: web.Application, **kwargs):
"""Run an `aiohttp.web.Application` using gunicorn.
:param app: The app to run.
:param str app_uri: Import path to `app`. Takes the form
``$(MODULE_NAME):$(VARIABLE_NAME)``.
The module name can be a full dotted path.
The variable name refers ... | [
"def",
"run",
"(",
"app",
":",
"web",
".",
"Application",
",",
"*",
"*",
"kwargs",
")",
":",
"runner",
"=",
"Runner",
"(",
"app",
",",
"*",
"*",
"kwargs",
")",
"runner",
".",
"run",
"(",
")"
] | 42.578947 | 13.421053 |
def ConfigureLazyWorkers(self):
""" Lazy workers are instances that are running and reachable but failed to
register with the cldb to join the mapr cluster. This trys to find these
missing workers and add them to the cluster. """
lazy_worker_instances = self.__GetMissingWorkers()
if not lazy_worke... | [
"def",
"ConfigureLazyWorkers",
"(",
"self",
")",
":",
"lazy_worker_instances",
"=",
"self",
".",
"__GetMissingWorkers",
"(",
")",
"if",
"not",
"lazy_worker_instances",
":",
"return",
"reachable_states",
"=",
"self",
".",
"__AreInstancesReachable",
"(",
"lazy_worker_in... | 51.384615 | 18.769231 |
def encode(self, text: str) -> str:
"""Encode @username into <@id> or <!alias>."""
def callback(match: Match) -> str:
name = match.group("name").lower()
if name in ["here", "everyone", "channel"]:
return f"<!{name}>"
else:
for user in ... | [
"def",
"encode",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"str",
":",
"def",
"callback",
"(",
"match",
":",
"Match",
")",
"->",
"str",
":",
"name",
"=",
"match",
".",
"group",
"(",
"\"name\"",
")",
".",
"lower",
"(",
")",
"if",
"name",
... | 35.785714 | 11.928571 |
def listen(self, markAlive=None):
"""
Initializes and runs the listening loop continually
:param markAlive: Whether this should ping the Facebook server each time the loop runs
:type markAlive: bool
"""
if markAlive is not None:
self.setActiveStatus(markAlive... | [
"def",
"listen",
"(",
"self",
",",
"markAlive",
"=",
"None",
")",
":",
"if",
"markAlive",
"is",
"not",
"None",
":",
"self",
".",
"setActiveStatus",
"(",
"markAlive",
")",
"self",
".",
"startListening",
"(",
")",
"self",
".",
"onListening",
"(",
")",
"w... | 27.294118 | 19.647059 |
def to_unicode(value):
"""
Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isins... | [
"def",
"to_unicode",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_TO_UNICODE_TYPES",
")",
":",
"return",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected bytes, unicode, or Non... | 38.083333 | 14.583333 |
def _get_config_file_path(xdg_config_dir, xdg_config_file):
"""Search ``XDG_CONFIG_DIRS`` for a config file and return the first found.
Search each of the standard XDG configuration directories for a
configuration file. Return as soon as a configuration file is found. Beware
that by the time client cod... | [
"def",
"_get_config_file_path",
"(",
"xdg_config_dir",
",",
"xdg_config_file",
")",
":",
"for",
"config_dir",
"in",
"BaseDirectory",
".",
"load_config_paths",
"(",
"xdg_config_dir",
")",
":",
"path",
"=",
"join",
"(",
"config_dir",
",",
"xdg_config_file",
")",
"if... | 46 | 25.076923 |
def get_page_dpi(pageinfo, options):
"Get the DPI when nonsquare DPI is tolerable"
xres = max(
pageinfo.xres or VECTOR_PAGE_DPI,
options.oversample or 0,
VECTOR_PAGE_DPI if pageinfo.has_vector else 0,
)
yres = max(
pageinfo.yres or VECTOR_PAGE_DPI,
options.oversam... | [
"def",
"get_page_dpi",
"(",
"pageinfo",
",",
"options",
")",
":",
"xres",
"=",
"max",
"(",
"pageinfo",
".",
"xres",
"or",
"VECTOR_PAGE_DPI",
",",
"options",
".",
"oversample",
"or",
"0",
",",
"VECTOR_PAGE_DPI",
"if",
"pageinfo",
".",
"has_vector",
"else",
... | 32 | 14 |
def setInstitutionLogo(self, pathList: tuple):
"""
takes one or more [logo].svg paths
if logo should be clickable, set
pathList = (
(my_path1.svg,www.something1.html),
(my_path2.svg,www.something2.html),
...)
"""... | [
"def",
"setInstitutionLogo",
"(",
"self",
",",
"pathList",
":",
"tuple",
")",
":",
"for",
"p",
"in",
"pathList",
":",
"url",
"=",
"None",
"if",
"type",
"(",
"p",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"p",
",",
"url",
"=",
"p",
"logo",
... | 35.090909 | 10.272727 |
def delete(self, key, cas=0):
"""
Delete a key/value from server. If key does not exist, it returns True.
:param key: Key's name to be deleted
:param cas: CAS of the key
:return: True in case o success and False in case of failure.
"""
server = self._get_server(k... | [
"def",
"delete",
"(",
"self",
",",
"key",
",",
"cas",
"=",
"0",
")",
":",
"server",
"=",
"self",
".",
"_get_server",
"(",
"key",
")",
"return",
"server",
".",
"delete",
"(",
"key",
",",
"cas",
")"
] | 35.3 | 13.3 |
def bind(self, instance):
"""Bind an instance to this Pangler.
Returns a clone of this Pangler, with the only difference being that
the new Pangler is bound to the provided instance. Both will have the
same `id`, but new hooks will not be shared.
"""
p = self.clone()
... | [
"def",
"bind",
"(",
"self",
",",
"instance",
")",
":",
"p",
"=",
"self",
".",
"clone",
"(",
")",
"p",
".",
"instance",
"=",
"weakref",
".",
"ref",
"(",
"instance",
")",
"return",
"p"
] | 30.583333 | 21.833333 |
def raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
"""
for er... | [
"def",
"raise_for_status",
"(",
"response",
")",
":",
"for",
"err_name",
"in",
"web_exceptions",
".",
"__all__",
":",
"err",
"=",
"getattr",
"(",
"web_exceptions",
",",
"err_name",
")",
"if",
"err",
".",
"status_code",
"==",
"response",
".",
"status",
":",
... | 35.52381 | 18.571429 |
def drange(start: Decimal, stop: Decimal, num: int):
'''
A simplified version of numpy.linspace with default options
'''
delta = stop - start
step = delta / (num - 1)
yield from (start + step * Decimal(tick) for tick in range(0, num)) | [
"def",
"drange",
"(",
"start",
":",
"Decimal",
",",
"stop",
":",
"Decimal",
",",
"num",
":",
"int",
")",
":",
"delta",
"=",
"stop",
"-",
"start",
"step",
"=",
"delta",
"/",
"(",
"num",
"-",
"1",
")",
"yield",
"from",
"(",
"start",
"+",
"step",
... | 36 | 22.857143 |
def set_blacklisted_directories(self,
directories,
remove_from_stored_directories=True):
"""
Sets the `directories` to be blacklisted. Blacklisted directories will
not be returned or searched recursively when calling
... | [
"def",
"set_blacklisted_directories",
"(",
"self",
",",
"directories",
",",
"remove_from_stored_directories",
"=",
"True",
")",
":",
"absolute_paths",
"=",
"util",
".",
"to_absolute_paths",
"(",
"directories",
")",
"self",
".",
"blacklisted_directories",
"=",
"absolut... | 44.52381 | 18.619048 |
def _execute_callback(self, status, message, job, res, err, stacktrace):
"""Execute the callback.
:param status: Job status. Possible values are "invalid" (job could not
be deserialized or was malformed), "failure" (job raised an error),
"timeout" (job timed out), or "success" (... | [
"def",
"_execute_callback",
"(",
"self",
",",
"status",
",",
"message",
",",
"job",
",",
"res",
",",
"err",
",",
"stacktrace",
")",
":",
"if",
"self",
".",
"_callback",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_logger",
".",
"info",
"(",
... | 47.384615 | 18.576923 |
def eval_ast(self, ast):
"""Eval the ast, replacing symbols by their last value in the model.
"""
# If there was no last value, it was not constrained, so we can use
# anything.
new_ast = ast.replace_dict(self.replacements, leaf_operation=self._leaf_op)
return backends.co... | [
"def",
"eval_ast",
"(",
"self",
",",
"ast",
")",
":",
"# If there was no last value, it was not constrained, so we can use",
"# anything.",
"new_ast",
"=",
"ast",
".",
"replace_dict",
"(",
"self",
".",
"replacements",
",",
"leaf_operation",
"=",
"self",
".",
"_leaf_op... | 48.571429 | 18.142857 |
def _mac_ver():
"""
Returns Mac version as a tuple of integers, making it easy to do proper
version comparisons. On non-Macs, it returns an empty tuple.
"""
import platform
import sys
if sys.platform == 'darwin':
ver_str = platform.mac_ver()[0]
return tuple([int(v) for v in v... | [
"def",
"_mac_ver",
"(",
")",
":",
"import",
"platform",
"import",
"sys",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"ver_str",
"=",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
"return",
"tuple",
"(",
"[",
"int",
"(",
"v",
")",
"f... | 29.666667 | 17.666667 |
def get_metadata(session, games):
"""Get metadata for games (only ladder data right now)."""
for data in games.values():
parsed = make_scrape_request(session, data['url'])
return {
'ladders': get_ladders_metadata(session, parsed)
} | [
"def",
"get_metadata",
"(",
"session",
",",
"games",
")",
":",
"for",
"data",
"in",
"games",
".",
"values",
"(",
")",
":",
"parsed",
"=",
"make_scrape_request",
"(",
"session",
",",
"data",
"[",
"'url'",
"]",
")",
"return",
"{",
"'ladders'",
":",
"get_... | 36.714286 | 16.142857 |
def message(self, data, kind="info"):
"""Convert message to json and send it to the clients"""
message = pd.io.json.dumps({'kind': kind, 'data': data})
print("Sent {0} bytes.".format(len(message)))
self.write_message(message) | [
"def",
"message",
"(",
"self",
",",
"data",
",",
"kind",
"=",
"\"info\"",
")",
":",
"message",
"=",
"pd",
".",
"io",
".",
"json",
".",
"dumps",
"(",
"{",
"'kind'",
":",
"kind",
",",
"'data'",
":",
"data",
"}",
")",
"print",
"(",
"\"Sent {0} bytes.\... | 50.6 | 9 |
def view_or_add(self, title):
'''
To judge if there is a post of the title.
Then, to show, or to add.
'''
postinfo = MWiki.get_by_wiki(title)
if postinfo:
if postinfo.kind == self.kind:
self.view(postinfo)
else:
retu... | [
"def",
"view_or_add",
"(",
"self",
",",
"title",
")",
":",
"postinfo",
"=",
"MWiki",
".",
"get_by_wiki",
"(",
"title",
")",
"if",
"postinfo",
":",
"if",
"postinfo",
".",
"kind",
"==",
"self",
".",
"kind",
":",
"self",
".",
"view",
"(",
"postinfo",
")... | 27.769231 | 14.384615 |
def add_error(self, property_name, message):
"""Add an error for the given property."""
if property_name not in self.errors:
self.errors[property_name] = []
self.errors[property_name].append(message) | [
"def",
"add_error",
"(",
"self",
",",
"property_name",
",",
"message",
")",
":",
"if",
"property_name",
"not",
"in",
"self",
".",
"errors",
":",
"self",
".",
"errors",
"[",
"property_name",
"]",
"=",
"[",
"]",
"self",
".",
"errors",
"[",
"property_name",... | 42.6 | 2.6 |
def decode_seq(self, inputs, states, valid_length=None):
"""Decode given the input sequence.
Parameters
----------
inputs : NDArray
states : list of NDArrays
valid_length : NDArray or None, default None
Returns
-------
output : NDArray
... | [
"def",
"decode_seq",
"(",
"self",
",",
"inputs",
",",
"states",
",",
"valid_length",
"=",
"None",
")",
":",
"outputs",
",",
"states",
",",
"additional_outputs",
"=",
"self",
".",
"decoder",
".",
"decode_seq",
"(",
"inputs",
"=",
"self",
".",
"tgt_embed",
... | 36.333333 | 17.416667 |
def visit_Index(self, node: ast.Index) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | [
"def",
"visit_Index",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Index",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"value",
")",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"r... | 32.833333 | 12.333333 |
def pkey(self):
"""Returns the private key for quick authentication on the SSH server."""
if self._pkey is None:
self._pkey = self._get_pkey()
return self._pkey | [
"def",
"pkey",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pkey",
"is",
"None",
":",
"self",
".",
"_pkey",
"=",
"self",
".",
"_get_pkey",
"(",
")",
"return",
"self",
".",
"_pkey"
] | 32 | 15.166667 |
def summarize_url(url, num_sentences=4, fmt='default'):
'''returns: tuple containing
* single-line summary candidate
* key points
in the format specified.
'''
title, meta, full_text = goose_extractor(url)
if not full_text:
raise ArticleExtractionFail("Couldn't extract: {}... | [
"def",
"summarize_url",
"(",
"url",
",",
"num_sentences",
"=",
"4",
",",
"fmt",
"=",
"'default'",
")",
":",
"title",
",",
"meta",
",",
"full_text",
"=",
"goose_extractor",
"(",
"url",
")",
"if",
"not",
"full_text",
":",
"raise",
"ArticleExtractionFail",
"(... | 32.37931 | 19.482759 |
def strToBytes(value):
'''
:type value: ``str``
:param value: value to encode
'''
kassert.is_of_types(value, (bytes, bytearray, six.string_types))
if isinstance(value, six.string_types):
return bytes(bytearray([ord(x) for x in value]))
elif isinstance(value, bytearray):
retur... | [
"def",
"strToBytes",
"(",
"value",
")",
":",
"kassert",
".",
"is_of_types",
"(",
"value",
",",
"(",
"bytes",
",",
"bytearray",
",",
"six",
".",
"string_types",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"retu... | 31 | 17.545455 |
def from_array(array):
"""
Deserialize a new PassportData from a given dictionary.
:return: new PassportData instance.
:rtype: PassportData
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_nam... | [
"def",
"from_array",
"(",
"array",
")",
":",
"if",
"array",
"is",
"None",
"or",
"not",
"array",
":",
"return",
"None",
"# end if",
"assert_type_or_raise",
"(",
"array",
",",
"dict",
",",
"parameter_name",
"=",
"\"array\"",
")",
"data",
"=",
"{",
"}",
"da... | 32.388889 | 21.5 |
def fcoe_get_login_output_fcoe_login_list_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
output = ET.SubElement(fcoe_get_login, "output")
fcoe_login_lis... | [
"def",
"fcoe_get_login_output_fcoe_login_list_interface_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe_get_login",
"=",
"ET",
".",
"Element",
"(",
"\"fcoe_get_login\"",
")",
"config",
"="... | 49.8 | 20.533333 |
def save_cursor(self):
"""Push the current cursor position onto the stack."""
self.savepoints.append(Savepoint(copy.copy(self.cursor),
self.g0_charset,
self.g1_charset,
self.charset... | [
"def",
"save_cursor",
"(",
"self",
")",
":",
"self",
".",
"savepoints",
".",
"append",
"(",
"Savepoint",
"(",
"copy",
".",
"copy",
"(",
"self",
".",
"cursor",
")",
",",
"self",
".",
"g0_charset",
",",
"self",
".",
"g1_charset",
",",
"self",
".",
"cha... | 55.5 | 17.25 |
def check_indexing(data):
"""Perform a check how incoming data should be indexed and return an
appropriate indexing function with signature f(data, index).
This is useful for determining upfront how data should be indexed
instead of doing it repeatedly for each batch, thus saving some
time.
""... | [
"def",
"check_indexing",
"(",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"_indexing_none",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"# dictionary of containers",
"return",
"_indexing_dict",
"if",
"isinstance",
"(",
"data",
",",... | 33.085714 | 18.657143 |
def sayHelloAsync(self, name="Not given", message="nothing"):
"""
Implementation of IHello.sayHelloAsync.
This method will be executed via some thread, and the remote caller
will not block.
This method should return either a String result (since the return type
of IHello.... | [
"def",
"sayHelloAsync",
"(",
"self",
",",
"name",
"=",
"\"Not given\"",
",",
"message",
"=",
"\"nothing\"",
")",
":",
"print",
"(",
"\"Python.sayHelloAsync called by: {0} \"",
"\"with message: '{1}'\"",
".",
"format",
"(",
"name",
",",
"message",
")",
")",
"return... | 42.411765 | 21 |
def modflow_pval_to_template_file(pval_file,tpl_file=None):
"""write a template file for a modflow parameter value file.
Uses names in the first column in the pval file as par names.
Parameters
----------
pval_file : str
parameter value file
tpl_file : str, optional
template fil... | [
"def",
"modflow_pval_to_template_file",
"(",
"pval_file",
",",
"tpl_file",
"=",
"None",
")",
":",
"if",
"tpl_file",
"is",
"None",
":",
"tpl_file",
"=",
"pval_file",
"+",
"\".tpl\"",
"pval_df",
"=",
"pd",
".",
"read_csv",
"(",
"pval_file",
",",
"delim_whitespac... | 40.235294 | 21.735294 |
def _get_snpeff_cmd(cmd_name, datadir, data, out_file):
"""Retrieve snpEff base command line.
"""
resources = config_utils.get_resources("snpeff", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx3g"])
# scale by cores, defaulting to 2x base usage to ensure we have enough memor... | [
"def",
"_get_snpeff_cmd",
"(",
"cmd_name",
",",
"datadir",
",",
"data",
",",
"out_file",
")",
":",
"resources",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"snpeff\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"jvm_opts",
"=",
"resources",
".",
"get",
... | 68.85 | 32.05 |
def get_explore_grouping_hierarchy(self):
'''**Description**
Return the user's current grouping hierarchy as visible in the Explore tab of Sysdig Monitor.
**Success Return Value**
A list containing the list of the user's Explore grouping criteria.
**Example**
... | [
"def",
"get_explore_grouping_hierarchy",
"(",
"self",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
"+",
"'/api/groupConfigurations'",
",",
"headers",
"=",
"self",
".",
"hdrs",
",",
"verify",
"=",
"self",
".",
"ssl_verify",
")",
"i... | 36.90625 | 27.34375 |
def _entry_offset(self, index, entries, description):
'''
Gets the offset of the first entry that matches the description.
@index - Index into the entries list to begin searching.
@entries - Dictionary of result entries.
@description - Case insensitive description.
... | [
"def",
"_entry_offset",
"(",
"self",
",",
"index",
",",
"entries",
",",
"description",
")",
":",
"description",
"=",
"description",
".",
"lower",
"(",
")",
"for",
"(",
"offset",
",",
"infos",
")",
"in",
"entries",
"[",
"index",
":",
"]",
":",
"for",
... | 37.833333 | 22.055556 |
def diabetes(display=False):
""" Return the diabetes data in a nice package. """
d = sklearn.datasets.load_diabetes()
df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101
return df, d.target | [
"def",
"diabetes",
"(",
"display",
"=",
"False",
")",
":",
"d",
"=",
"sklearn",
".",
"datasets",
".",
"load_diabetes",
"(",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"data",
"=",
"d",
".",
"data",
",",
"columns",
"=",
"d",
".",
"feature_names",
... | 38.166667 | 18.666667 |
def from_object(updates):
"Update same name (or prefixed) settings."
import sys
config = sys.modules[__name__]
prefix = config.__name__.split('.')[0].upper()
keys = [k for k in config.__dict__ if \
k != from_object.__name__ and not k.startswith('_')]
get_value = lambda c, k: hasattr... | [
"def",
"from_object",
"(",
"updates",
")",
":",
"import",
"sys",
"config",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"prefix",
"=",
"config",
".",
"__name__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"keys",
"="... | 40.461538 | 16.307692 |
def _trim_css_to_bounds(css, image_shape):
"""
Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image.
:param css: plain tuple representation of the rect in (top, right, bottom, left) order
:param image_shape: numpy shape of the image array
:return: a trimmed plain... | [
"def",
"_trim_css_to_bounds",
"(",
"css",
",",
"image_shape",
")",
":",
"return",
"max",
"(",
"css",
"[",
"0",
"]",
",",
"0",
")",
",",
"min",
"(",
"css",
"[",
"1",
"]",
",",
"image_shape",
"[",
"1",
"]",
")",
",",
"min",
"(",
"css",
"[",
"2",
... | 54.333333 | 30.555556 |
def _fD(self, neg_pairs, A):
"""The value of the dissimilarity constraint function.
f = f(\sum_{ij \in D} distance(x_i, x_j))
i.e. distance can be L1: \sqrt{(x_i-x_j)A(x_i-x_j)'}
"""
diff = neg_pairs[:, 0, :] - neg_pairs[:, 1, :]
return np.log(np.sum(np.sqrt(np.sum(np.dot(diff, A) * diff, axis... | [
"def",
"_fD",
"(",
"self",
",",
"neg_pairs",
",",
"A",
")",
":",
"diff",
"=",
"neg_pairs",
"[",
":",
",",
"0",
",",
":",
"]",
"-",
"neg_pairs",
"[",
":",
",",
"1",
",",
":",
"]",
"return",
"np",
".",
"log",
"(",
"np",
".",
"sum",
"(",
"np",... | 40.75 | 15.625 |
def getSlotInfo(self, slot):
"""
C_GetSlotInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_SLOT_INFO` object
"""
slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO()
rv = self.lib.C_GetSlotInfo(slot, slotInfo)
... | [
"def",
"getSlotInfo",
"(",
"self",
",",
"slot",
")",
":",
"slotInfo",
"=",
"PyKCS11",
".",
"LowLevel",
".",
"CK_SLOT_INFO",
"(",
")",
"rv",
"=",
"self",
".",
"lib",
".",
"C_GetSlotInfo",
"(",
"slot",
",",
"slotInfo",
")",
"if",
"rv",
"!=",
"CKR_OK",
... | 31.809524 | 16.666667 |
def cudnnGetConvolutionForwardAlgorithm(handle, srcDesc, wDesc,
convDesc, destDesc, preference, memoryLimitInbytes):
""""
This function returns the best algorithm to choose for the forward convolution
depending on the critera expressed in the cudnnConvolutionFwdPrefer... | [
"def",
"cudnnGetConvolutionForwardAlgorithm",
"(",
"handle",
",",
"srcDesc",
",",
"wDesc",
",",
"convDesc",
",",
"destDesc",
",",
"preference",
",",
"memoryLimitInbytes",
")",
":",
"algo",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcudnn",
".",... | 43.375 | 24.05 |
def _reschedule(self, node):
"""Maybe schedule new items on the node.
If there are any globally pending work units left then this will check
if the given node should be given any more tests.
"""
# Do not add more work to a node shutting down
if node.shutting_down:
... | [
"def",
"_reschedule",
"(",
"self",
",",
"node",
")",
":",
"# Do not add more work to a node shutting down",
"if",
"node",
".",
"shutting_down",
":",
"return",
"# Check that more work is available",
"if",
"not",
"self",
".",
"workqueue",
":",
"node",
".",
"shutdown",
... | 31.52 | 20.76 |
def run2(data, samples, force, ipyclient):
"""
Filter for samples that are already finished with this step, allow others
to run, pass them to parallel client function to filter with cutadapt.
"""
## create output directories
data.dirs.edits = os.path.join(os.path.realpath(
... | [
"def",
"run2",
"(",
"data",
",",
"samples",
",",
"force",
",",
"ipyclient",
")",
":",
"## create output directories ",
"data",
".",
"dirs",
".",
"edits",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"data",
".",
... | 40.473684 | 19.921053 |
def ingest(cls, resource):
""" Ingest a list of DTS Citation object (as parsed JSON-LD) and
creates the Citation Graph
:param resource: List of Citation objects from the
DTS Collection Endpoint (as expanded JSON-LD)
:type resource: list
:return: Citation Graph
... | [
"def",
"ingest",
"(",
"cls",
",",
"resource",
")",
":",
"_set",
"=",
"cls",
"(",
")",
"for",
"data",
"in",
"resource",
":",
"_set",
".",
"add_child",
"(",
"cls",
".",
"CitationClass",
".",
"ingest",
"(",
"data",
",",
"root",
"=",
"_set",
")",
")",
... | 32.133333 | 15 |
def main():
"""The command line interface for the ``pip-accel`` program."""
arguments = sys.argv[1:]
# If no arguments are given, the help text of pip-accel is printed.
if not arguments:
usage()
sys.exit(0)
# If no install subcommand is given we pass the command line straight
# t... | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"# If no arguments are given, the help text of pip-accel is printed.",
"if",
"not",
"arguments",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"# If no install... | 39.666667 | 17.435897 |
def show(self, viewer=None, **kwargs):
"""
Display the current scene.
Parameters
-----------
viewer: str 'gl': open a pyglet window
str,'notebook': return ipython.display.HTML
None: automatically pick based on whether or not
... | [
"def",
"show",
"(",
"self",
",",
"viewer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"viewer",
"is",
"None",
":",
"# check to see if we are in a notebook or not",
"from",
".",
".",
"viewer",
"import",
"in_notebook",
"viewer",
"=",
"[",
"'gl'",
... | 36.482759 | 15.793103 |
def create_tables(args):
"""Creates all necessary tables (only to be used at the first time)"""
from bob.db.utils import create_engine_try_nolock
engine = create_engine_try_nolock(args.type, args.files[0], echo=(args.verbose > 2))
Base.metadata.create_all(engine) | [
"def",
"create_tables",
"(",
"args",
")",
":",
"from",
"bob",
".",
"db",
".",
"utils",
"import",
"create_engine_try_nolock",
"engine",
"=",
"create_engine_try_nolock",
"(",
"args",
".",
"type",
",",
"args",
".",
"files",
"[",
"0",
"]",
",",
"echo",
"=",
... | 44.5 | 19.833333 |
def parse_type(cls, type_string):
"""Parse KATCP formatted type code into Sensor type constant.
Parameters
----------
type_string : str
KATCP formatted type code.
Returns
-------
sensor_type : Sensor type constant
The corresponding Sensor... | [
"def",
"parse_type",
"(",
"cls",
",",
"type_string",
")",
":",
"if",
"type_string",
"in",
"cls",
".",
"SENSOR_TYPE_LOOKUP",
":",
"return",
"cls",
".",
"SENSOR_TYPE_LOOKUP",
"[",
"type_string",
"]",
"else",
":",
"raise",
"KatcpSyntaxError",
"(",
"\"Invalid sensor... | 29.789474 | 17.684211 |
def pending(self):
'''
Returns an array of updates that are currently in the buffer for an
individual social media profile.
'''
pending_updates = []
url = PATHS['GET_PENDING'] % self.profile_id
response = self.api.get(url=url)
for update in response['updates']:
pending_update... | [
"def",
"pending",
"(",
"self",
")",
":",
"pending_updates",
"=",
"[",
"]",
"url",
"=",
"PATHS",
"[",
"'GET_PENDING'",
"]",
"%",
"self",
".",
"profile_id",
"response",
"=",
"self",
".",
"api",
".",
"get",
"(",
"url",
"=",
"url",
")",
"for",
"update",
... | 26.3125 | 22.6875 |
def encrypt(self, wif):
""" Encrypt the content according to BIP38
:param str wif: Unencrypted key
"""
if not self.unlocked():
raise WalletLocked
return format(bip38.encrypt(str(wif), self.masterkey), "encwif") | [
"def",
"encrypt",
"(",
"self",
",",
"wif",
")",
":",
"if",
"not",
"self",
".",
"unlocked",
"(",
")",
":",
"raise",
"WalletLocked",
"return",
"format",
"(",
"bip38",
".",
"encrypt",
"(",
"str",
"(",
"wif",
")",
",",
"self",
".",
"masterkey",
")",
",... | 32.5 | 13.875 |
def convert_lightcurves_to_observered_frame(
log,
snLightCurves,
rawLightCurveDict,
redshiftArray,
snTypesArray,
peakMagnitudesArray,
hostExtinctionArray,
kCorrectionArray,
galacticExtinctionArray,
restFrameFilter,
pathToOutputDirec... | [
"def",
"convert_lightcurves_to_observered_frame",
"(",
"log",
",",
"snLightCurves",
",",
"rawLightCurveDict",
",",
"redshiftArray",
",",
"snTypesArray",
",",
"peakMagnitudesArray",
",",
"hostExtinctionArray",
",",
"kCorrectionArray",
",",
"galacticExtinctionArray",
",",
"re... | 41.982143 | 17.369048 |
def get_all_spaces(self, start=0, limit=500):
"""
Get all spaces with provided limit
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
... | [
"def",
"get_all_spaces",
"(",
"self",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"500",
")",
":",
"url",
"=",
"'rest/api/space'",
"params",
"=",
"{",
"}",
"if",
"limit",
":",
"params",
"[",
"'limit'",
"]",
"=",
"limit",
"if",
"start",
":",
"params",
... | 41.785714 | 18.357143 |
def com_google_fonts_check_kerning_for_non_ligated_sequences(ttFont, ligatures, has_kerning_info):
"""Is there kerning info for non-ligated sequences?"""
def look_for_nonligated_kern_info(table):
for pairpos in table.SubTable:
for i, glyph in enumerate(pairpos.Coverage.glyphs):
if not hasattr(pai... | [
"def",
"com_google_fonts_check_kerning_for_non_ligated_sequences",
"(",
"ttFont",
",",
"ligatures",
",",
"has_kerning_info",
")",
":",
"def",
"look_for_nonligated_kern_info",
"(",
"table",
")",
":",
"for",
"pairpos",
"in",
"table",
".",
"SubTable",
":",
"for",
"i",
... | 40.145833 | 17.479167 |
def remove_chain(self, chain=-1):
"""
Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone!
Parameters
----------
chain : int|str, list[str|int]
The chain(s) to remove. You can pass in either the chain index, or the chain ... | [
"def",
"remove_chain",
"(",
"self",
",",
"chain",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"chain",
",",
"str",
")",
"or",
"isinstance",
"(",
"chain",
",",
"int",
")",
":",
"chain",
"=",
"[",
"chain",
"]",
"chain",
"=",
"sorted",
"(",
"[... | 33.193548 | 27.258065 |
def createdb():
"""Create database tables from sqlalchemy models"""
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision() | [
"def",
"createdb",
"(",
")",
":",
"manager",
".",
"db",
".",
"engine",
".",
"echo",
"=",
"True",
"manager",
".",
"db",
".",
"create_all",
"(",
")",
"set_alembic_revision",
"(",
")"
] | 31.2 | 11.8 |
def createModel(self, model, context, owner='', includeReferences=True):
"""
Creates a new table in the database based cff the inputted
schema information. If the dryRun flag is specified, then
the SQLConnection will only be logged to the current logger, and not
actually execute... | [
"def",
"createModel",
"(",
"self",
",",
"model",
",",
"context",
",",
"owner",
"=",
"''",
",",
"includeReferences",
"=",
"True",
")",
":",
"CREATE",
"=",
"self",
".",
"statement",
"(",
"'CREATE'",
")",
"sql",
",",
"data",
"=",
"CREATE",
"(",
"model",
... | 37.92 | 20.08 |
def _get_down_up_string(self):
"""Return a string that will show whether the string is up or down
return 'down' if the key is a press only
return 'up' if the key is up only
return '' if the key is up & down (as default)
"""
down_up = ""
if not (self.down and self... | [
"def",
"_get_down_up_string",
"(",
"self",
")",
":",
"down_up",
"=",
"\"\"",
"if",
"not",
"(",
"self",
".",
"down",
"and",
"self",
".",
"up",
")",
":",
"if",
"self",
".",
"down",
":",
"down_up",
"=",
"\"down\"",
"elif",
"self",
".",
"up",
":",
"dow... | 32.214286 | 11.428571 |
def _write_log(*msg, end='\n'):
"""Write message to log output, ignoring the verbosity level.
This is the most basic function.
Parameters
----------
*msg :
One or more arguments to be formatted as string. Same behavior as print
function.
"""
from .settings import logfile
... | [
"def",
"_write_log",
"(",
"*",
"msg",
",",
"end",
"=",
"'\\n'",
")",
":",
"from",
".",
"settings",
"import",
"logfile",
"if",
"logfile",
"==",
"''",
":",
"print",
"(",
"*",
"msg",
",",
"end",
"=",
"end",
")",
"else",
":",
"out",
"=",
"''",
"for",... | 27.722222 | 16.166667 |
def scan_and_reimport(mod_type: str) -> List[Tuple[str, str]]:
"""Scans folder for modules."""
mod_enabled, mod_disabled = get_modules(mod_type)
errors = []
for mod in mod_enabled + mod_disabled:
if mod in sys.modules:
msg = safe_reload(sys.modules[mod])
else:
msg... | [
"def",
"scan_and_reimport",
"(",
"mod_type",
":",
"str",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"mod_enabled",
",",
"mod_disabled",
"=",
"get_modules",
"(",
"mod_type",
")",
"errors",
"=",
"[",
"]",
"for",
"mod",
"in",
... | 34.166667 | 12.75 |
def write(self, chunk):
"""WSGI callable to write unbuffered data to the client.
This method is also used internally by start_response (to write
data from the iterable returned by the WSGI application).
"""
if not self.started_response:
raise AssertionError('WSGI wri... | [
"def",
"write",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"not",
"self",
".",
"started_response",
":",
"raise",
"AssertionError",
"(",
"'WSGI write called before start_response.'",
")",
"chunklen",
"=",
"len",
"(",
"chunk",
")",
"rbo",
"=",
"self",
".",
"re... | 37.058824 | 18.970588 |
def walkSignalPorts(rootPort: LPort):
"""
recursively walk ports without any children
"""
if rootPort.children:
for ch in rootPort.children:
yield from walkSignalPorts(ch)
else:
yield rootPort | [
"def",
"walkSignalPorts",
"(",
"rootPort",
":",
"LPort",
")",
":",
"if",
"rootPort",
".",
"children",
":",
"for",
"ch",
"in",
"rootPort",
".",
"children",
":",
"yield",
"from",
"walkSignalPorts",
"(",
"ch",
")",
"else",
":",
"yield",
"rootPort"
] | 25.777778 | 8.888889 |
def savemat(filename, data):
"""Save data to MAT-file:
savemat(filename, data)
The filename argument is either a string with the filename, or
a file like object.
The parameter ``data`` shall be a dict with the variables.
A ``ValueError`` exception is raised if data has invalid format, or if ... | [
"def",
"savemat",
"(",
"filename",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Mapping",
")",
":",
"raise",
"ValueError",
"(",
"'Data should be a dict of variable arrays'",
")",
"if",
"isinstance",
"(",
"filename",
",",
"basestring",
"... | 25.413793 | 23.206897 |
def fromHumanly(klass, humanStr, tzinfo=None, now=None):
"""Return a new Time instance from a string a human might type.
@param humanStr: the string to be parsed.
@param tzinfo: A tzinfo instance indicating the timezone to assume if
none is specified in humanStr. If None, assume UTC.
... | [
"def",
"fromHumanly",
"(",
"klass",
",",
"humanStr",
",",
"tzinfo",
"=",
"None",
",",
"now",
"=",
"None",
")",
":",
"humanStr",
"=",
"humanStr",
".",
"strip",
"(",
")",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"Time",
"(",
")",
"if",
"tzinfo",
... | 38.677419 | 20.16129 |
def get_stops(records, group_dist):
"""
Group records arounds stop locations and returns a list of
dict(location, records) for each stop.
Parameters
----------
records : list
A list of Record objects ordered by non-decreasing datetime
group_dist : float
Minimum distance (in ... | [
"def",
"get_stops",
"(",
"records",
",",
"group_dist",
")",
":",
"def",
"traverse",
"(",
"start",
",",
"next",
")",
":",
"position_prev",
"=",
"records",
"[",
"next",
"-",
"1",
"]",
".",
"position",
".",
"location",
"position_next",
"=",
"records",
"[",
... | 29.121212 | 19.909091 |
def inline(self, article):
"""
Returns all inline attachments associated with article_id where (Such attachments has ``inline=True`` flag).
Inline attachments and its url can be referenced in the HTML body of the article.
:param article: Numeric article id or :class:`Article` object.
... | [
"def",
"inline",
"(",
"self",
",",
"article",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"inline",
",",
"'article_attachment'",
",",
"id",
"=",
"article",
")"
] | 47.9 | 32.5 |
async def set_access_string(self, **params):
"""Writes content access string to database
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
cid = int(params.get("cid", "0"))
seller_access_string = params.get("seller_access_string")
seller_pubkey = params.get("seller_pubkey")... | [
"async",
"def",
"set_access_string",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"params",
".",
"get",
"(",
"\"message\"",
")",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"params",
".",
"get",
"(",
"\"message\"",
",",
"\"{}\"",
")",
")"... | 30 | 19.264706 |
def flush(self):
"""Flush all finished jobs (completed and dead) from lists.
Running jobs are never flushed.
It first calls _status_new(), to update info. If any jobs have
completed since the last _status_new() call, the flush operation
aborts."""
# Remove the finished... | [
"def",
"flush",
"(",
"self",
")",
":",
"# Remove the finished jobs from the master dict",
"alljobs",
"=",
"self",
".",
"all",
"for",
"job",
"in",
"self",
".",
"completed",
"+",
"self",
".",
"dead",
":",
"del",
"(",
"alljobs",
"[",
"job",
".",
"num",
"]",
... | 35.421053 | 17.578947 |
def from_api_repr(cls, resource):
"""Factory: construct instance from resource.
:type resource: dict
:param resource: mapping as returned from API call.
:rtype: :class:`LifecycleRuleDelete`
:returns: Instance created from resource.
"""
action = resource["action... | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
")",
":",
"action",
"=",
"resource",
"[",
"\"action\"",
"]",
"instance",
"=",
"cls",
"(",
"action",
"[",
"\"storageClass\"",
"]",
",",
"_factory",
"=",
"True",
")",
"instance",
".",
"update",
"(",
"res... | 33.076923 | 13.923077 |
def multiply(self, other, out=None):
"""Return ``out = self * other``.
If ``out`` is provided, the result is written to it.
See Also
--------
LinearSpace.multiply
"""
return self.space.multiply(self, other, out=out) | [
"def",
"multiply",
"(",
"self",
",",
"other",
",",
"out",
"=",
"None",
")",
":",
"return",
"self",
".",
"space",
".",
"multiply",
"(",
"self",
",",
"other",
",",
"out",
"=",
"out",
")"
] | 26.4 | 18 |
def _cursor(self, offset=0, limit=0, fields=None, sort=None, **kwargs):
"""Return a cursor on a filtered list of documents in a collection.
:param offset: for pagination, which record to start attribute
:param limit: for pagination, how many records to return
:param fields: list of fiel... | [
"def",
"_cursor",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"0",
",",
"fields",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"projection",
"=",
"{",
"'_id'",
":",
"False",
"}",
"if",
"fields",
":",
"p... | 45.666667 | 22.111111 |
def kube_node_status_condition(self, metric, scraper_config):
""" The ready status of a cluster node. v1.0+"""
base_check_name = scraper_config['namespace'] + '.node'
metric_name = scraper_config['namespace'] + '.nodes.by_condition'
by_condition_counter = Counter()
for sample in... | [
"def",
"kube_node_status_condition",
"(",
"self",
",",
"metric",
",",
"scraper_config",
")",
":",
"base_check_name",
"=",
"scraper_config",
"[",
"'namespace'",
"]",
"+",
"'.node'",
"metric_name",
"=",
"scraper_config",
"[",
"'namespace'",
"]",
"+",
"'.nodes.by_condi... | 48.769231 | 23.846154 |
def size_of_generator(generator, memory_efficient=True):
"""Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficient=True的方法可以避免将生成器中的
所有... | [
"def",
"size_of_generator",
"(",
"generator",
",",
"memory_efficient",
"=",
"True",
")",
":",
"if",
"memory_efficient",
":",
"counter",
"=",
"0",
"for",
"_",
"in",
"generator",
":",
"counter",
"+=",
"1",
"return",
"counter",
"else",
":",
"return",
"len",
"... | 28.833333 | 19.833333 |
def restart_complete(self, state, new_address):
'''
Called when we get notified that the restart has been completed by
some agent who has volontureed to do so.
'''
if state.timeout_call_id:
state.agent.cancel_delayed_call(state.timeout_call_id)
state.timeo... | [
"def",
"restart_complete",
"(",
"self",
",",
"state",
",",
"new_address",
")",
":",
"if",
"state",
".",
"timeout_call_id",
":",
"state",
".",
"agent",
".",
"cancel_delayed_call",
"(",
"state",
".",
"timeout_call_id",
")",
"state",
".",
"timeout_call_id",
"=",
... | 43.555556 | 18 |
def c2l(c):
"char[4] to unsigned long"
l = U32(c[0])
l = l | (U32(c[1]) << 8)
l = l | (U32(c[2]) << 16)
l = l | (U32(c[3]) << 24)
return l | [
"def",
"c2l",
"(",
"c",
")",
":",
"l",
"=",
"U32",
"(",
"c",
"[",
"0",
"]",
")",
"l",
"=",
"l",
"|",
"(",
"U32",
"(",
"c",
"[",
"1",
"]",
")",
"<<",
"8",
")",
"l",
"=",
"l",
"|",
"(",
"U32",
"(",
"c",
"[",
"2",
"]",
")",
"<<",
"16... | 22.285714 | 17.714286 |
def minimumLabelHeight(self):
"""
Returns the minimum height that will be required based on this font size
and labels list.
"""
metrics = QFontMetrics(self.labelFont())
return max(self._minimumLabelHeight,
metrics.height() + self.verticalLabelPad... | [
"def",
"minimumLabelHeight",
"(",
"self",
")",
":",
"metrics",
"=",
"QFontMetrics",
"(",
"self",
".",
"labelFont",
"(",
")",
")",
"return",
"max",
"(",
"self",
".",
"_minimumLabelHeight",
",",
"metrics",
".",
"height",
"(",
")",
"+",
"self",
".",
"vertic... | 40 | 13.25 |
def get_columns(self, connection, table_name, schema=None, **kw):
"""
Return information about columns in `table_name`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_columns`.
"""
cols = self._get_redshift_columns(connection, table_name, schema, **... | [
"def",
"get_columns",
"(",
"self",
",",
"connection",
",",
"table_name",
",",
"schema",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"cols",
"=",
"self",
".",
"_get_redshift_columns",
"(",
"connection",
",",
"table_name",
",",
"schema",
",",
"*",
"*",
"... | 41.210526 | 17.736842 |
def data_sessions(self):
"""
Access the data_sessions
:returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList
:rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList
"""
if self._data_sessions is None:
self._data_sessions = DataSessionList... | [
"def",
"data_sessions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_sessions",
"is",
"None",
":",
"self",
".",
"_data_sessions",
"=",
"DataSessionList",
"(",
"self",
".",
"_version",
",",
"sim_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
... | 39.4 | 19.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.