text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def find_host_by_name(self, si, path, name):
"""
Finds datastore in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore name ... | [
"def",
"find_host_by_name",
"(",
"self",
",",
"si",
",",
"path",
",",
"name",
")",
":",
"return",
"self",
".",
"find_obj_by_path",
"(",
"si",
",",
"path",
",",
"name",
",",
"self",
".",
"Host",
")"
] | 44.111111 | 0.007407 |
def create_fw_db(self, fw_id, fw_name, tenant_id):
"""Create FW dict. """
fw_dict = {'fw_id': fw_id, 'name': fw_name, 'tenant_id': tenant_id}
# FW DB is already created by FW Mgr
# self.add_fw_db(fw_id, fw_dict)
self.update_fw_dict(fw_dict) | [
"def",
"create_fw_db",
"(",
"self",
",",
"fw_id",
",",
"fw_name",
",",
"tenant_id",
")",
":",
"fw_dict",
"=",
"{",
"'fw_id'",
":",
"fw_id",
",",
"'name'",
":",
"fw_name",
",",
"'tenant_id'",
":",
"tenant_id",
"}",
"# FW DB is already created by FW Mgr",
"# sel... | 45.833333 | 0.007143 |
def common_segment_count(path, value):
"""Return the number of path segments common to both"""
i = 0
if len(path) <= len(value):
for x1, x2 in zip(path, value):
if x1 == x2:
i += 1
else:
return 0
return i | [
"def",
"common_segment_count",
"(",
"path",
",",
"value",
")",
":",
"i",
"=",
"0",
"if",
"len",
"(",
"path",
")",
"<=",
"len",
"(",
"value",
")",
":",
"for",
"x1",
",",
"x2",
"in",
"zip",
"(",
"path",
",",
"value",
")",
":",
"if",
"x1",
"==",
... | 27.5 | 0.003521 |
def mainloop(self):
""" The main loop.
"""
self.check_for_connection()
# Enter REPL if no args
if len(self.args) < 1:
return self.do_repl()
# Check for bad options
if self.options.repr and self.options.xml:
self.parser.error("You cannot c... | [
"def",
"mainloop",
"(",
"self",
")",
":",
"self",
".",
"check_for_connection",
"(",
")",
"# Enter REPL if no args",
"if",
"len",
"(",
"self",
".",
"args",
")",
"<",
"1",
":",
"return",
"self",
".",
"do_repl",
"(",
")",
"# Check for bad options",
"if",
"sel... | 29.84 | 0.002597 |
def sort_by_mem_per_proc(self, reverse=False):
"""Sort the configurations in place. items with lowest memory per proc come first."""
# Avoid sorting if mem_per_cpu is not available.
if any(c.mem_per_proc > 0.0 for c in self):
self._confs.sort(key=lambda c: c.mem_per_proc, reverse=rev... | [
"def",
"sort_by_mem_per_proc",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"# Avoid sorting if mem_per_cpu is not available.",
"if",
"any",
"(",
"c",
".",
"mem_per_proc",
">",
"0.0",
"for",
"c",
"in",
"self",
")",
":",
"self",
".",
"_confs",
".",
"s... | 56.666667 | 0.008696 |
def get_queue(queue, flags=FLAGS.ALL, **conn):
"""
Orchestrates all the calls required to fully fetch details about an SQS Queue:
{
"Arn": ...,
"Region": ...,
"Name": ...,
"Url": ...,
"Attributes": ...,
"Tags": ...,
"DeadLetterSourceQueues": ...,
... | [
"def",
"get_queue",
"(",
"queue",
",",
"flags",
"=",
"FLAGS",
".",
"ALL",
",",
"*",
"*",
"conn",
")",
":",
"# Check if this is a Queue URL or a queue name:",
"if",
"queue",
".",
"startswith",
"(",
"\"https://\"",
")",
"or",
"queue",
".",
"startswith",
"(",
"... | 31.966667 | 0.004049 |
def symlink_list(self, load):
'''
Return a dict of all symlinks based on a given path in the repo
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not salt.utils.stringutils.is_hex(load['saltenv']) \
and lo... | [
"def",
"symlink_list",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"not",
"salt",
".",
"utils",
".",
"stringutils",
".",
"is_hex",
"(",
"... | 35.105263 | 0.00292 |
def get_canonical_absolute_expanded_path(path):
"""Get the canonical form of the absolute path from a possibly relative path
(which may have symlinks, etc.)"""
return os.path.normcase(
os.path.normpath(
os.path.realpath( # remove any symbolic links
os... | [
"def",
"get_canonical_absolute_expanded_path",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"# remove any symbolic links",
"os",
".",
"path",
".",
... | 53.625 | 0.011468 |
def DirectoryStimuliFactory(loader):
"""
Takes an input path to the images folder of an experiment and generates
automatically the category - filenumber list needed to construct an
appropriate _categories object.
Parameters :
loader : Loader object which contains
impath : s... | [
"def",
"DirectoryStimuliFactory",
"(",
"loader",
")",
":",
"impath",
"=",
"loader",
".",
"impath",
"ftrpath",
"=",
"loader",
".",
"ftrpath",
"# checks whether user has reading permission for the path",
"assert",
"os",
".",
"access",
"(",
"impath",
",",
"os",
".",
... | 45.4 | 0.007546 |
def decode(cls, root_element):
"""
Decode the object to the object
:param root_element: the parsed xml Element
:type root_element: xml.etree.ElementTree.Element
:return: the decoded Element as object
:rtype: object
"""
new_object = cls()
field_nam... | [
"def",
"decode",
"(",
"cls",
",",
"root_element",
")",
":",
"new_object",
"=",
"cls",
"(",
")",
"field_names_to_attributes",
"=",
"new_object",
".",
"_get_field_names_to_attributes",
"(",
")",
"for",
"child_element",
"in",
"root_element",
":",
"new_object",
".",
... | 37.571429 | 0.005566 |
def _to_edit(self, infoid):
'''
render the HTML page for post editing.
'''
postinfo = MPost.get_by_uid(infoid)
if postinfo:
pass
else:
return self.show404()
if 'def_cat_uid' in postinfo.extinfo:
catid = postinfo.extinfo['def_... | [
"def",
"_to_edit",
"(",
"self",
",",
"infoid",
")",
":",
"postinfo",
"=",
"MPost",
".",
"get_by_uid",
"(",
"infoid",
")",
"if",
"postinfo",
":",
"pass",
"else",
":",
"return",
"self",
".",
"show404",
"(",
")",
"if",
"'def_cat_uid'",
"in",
"postinfo",
"... | 29.84127 | 0.00206 |
def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
APFSContainerPathSpec: a path specification.
"""
# Only the virtual root file has directory entries.
volume_index = ... | [
"def",
"_EntriesGenerator",
"(",
"self",
")",
":",
"# Only the virtual root file has directory entries.",
"volume_index",
"=",
"apfs_helper",
".",
"APFSContainerPathSpecGetVolumeIndex",
"(",
"self",
".",
"path_spec",
")",
"if",
"volume_index",
"is",
"not",
"None",
":",
... | 34.96 | 0.004454 |
def palette(hues, saturations, values):
"""Generate a palette.
Parameters
----------
hues : `int`
Number of hues.
saturations : `int`
Number of saturations.
values : `int`
Number of values.
Raises
------
ValueError
If `hues` * `saturations` * `values... | [
"def",
"palette",
"(",
"hues",
",",
"saturations",
",",
"values",
")",
":",
"size",
"=",
"hues",
"*",
"saturations",
"*",
"values",
"if",
"size",
">",
"256",
":",
"raise",
"ValueError",
"(",
"'palette size > 256: {0}'",
".",
"format",
"(",
"size",
")",
"... | 29 | 0.000654 |
def rmdir(path):
"""Safe rmdir (non-recursive) which doesn't throw if the directory is not empty."""
try:
os.rmdir(path)
except OSError as exc:
print(str(exc)) | [
"def",
"rmdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"rmdir",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"print",
"(",
"str",
"(",
"exc",
")",
")"
] | 30.333333 | 0.010695 |
def select_catalogue(self, valid_id):
'''
Method to post-process the catalogue based on the selection options
:param numpy.ndarray valid_id:
Boolean vector indicating whether each event is selected (True)
or not (False)
:returns:
Catalogue of selecte... | [
"def",
"select_catalogue",
"(",
"self",
",",
"valid_id",
")",
":",
"if",
"not",
"np",
".",
"any",
"(",
"valid_id",
")",
":",
"# No events selected - create clean instance of class",
"output",
"=",
"Catalogue",
"(",
")",
"output",
".",
"processes",
"=",
"self",
... | 33.310345 | 0.002012 |
def roc_values(fg_vals, bg_vals):
"""
Return fpr (x) and tpr (y) of the ROC curve.
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
Returns
-------
fpr : array
... | [
"def",
"roc_values",
"(",
"fg_vals",
",",
"bg_vals",
")",
":",
"if",
"len",
"(",
"fg_vals",
")",
"==",
"0",
":",
"return",
"0",
"y_true",
",",
"y_score",
"=",
"values_to_labels",
"(",
"fg_vals",
",",
"bg_vals",
")",
"fpr",
",",
"tpr",
",",
"_thresholds... | 20.62963 | 0.006861 |
def apply_transformer_types(network):
"""Calculate transformer electrical parameters x, r, b, g from
standard types.
"""
trafos_with_types_b = network.transformers.type != ""
if trafos_with_types_b.zsum() == 0:
return
missing_types = (pd.Index(network.transformers.loc[trafos_with_type... | [
"def",
"apply_transformer_types",
"(",
"network",
")",
":",
"trafos_with_types_b",
"=",
"network",
".",
"transformers",
".",
"type",
"!=",
"\"\"",
"if",
"trafos_with_types_b",
".",
"zsum",
"(",
")",
"==",
"0",
":",
"return",
"missing_types",
"=",
"(",
"pd",
... | 37.880952 | 0.008578 |
def node_predicate(f: Callable[[BaseEntity], bool]) -> NodePredicate: # noqa: D202
"""Tag a node predicate that takes a dictionary to also accept a pair of (BELGraph, node).
Apply this as a decorator to a function that takes a single argument, a PyBEL node, to make
sure that it can also accept a pair of a... | [
"def",
"node_predicate",
"(",
"f",
":",
"Callable",
"[",
"[",
"BaseEntity",
"]",
",",
"bool",
"]",
")",
"->",
"NodePredicate",
":",
"# noqa: D202",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"x",
"=",
"args",
"[",
"0... | 31.052632 | 0.006579 |
def new(self, user, name, description=None):
"""
Creates a new Feed object
:param user: feed username
:param name: feed name
:param description: feed description
:return: dict
"""
uri = self.client.remote + '/users/{0}/feeds'.format(user)
data = ... | [
"def",
"new",
"(",
"self",
",",
"user",
",",
"name",
",",
"description",
"=",
"None",
")",
":",
"uri",
"=",
"self",
".",
"client",
".",
"remote",
"+",
"'/users/{0}/feeds'",
".",
"format",
"(",
"user",
")",
"data",
"=",
"{",
"'feed'",
":",
"{",
"'na... | 24.25 | 0.003968 |
def tile_x_size(self, zoom):
"""
Width of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_x_size is deprecated"))
validate_zoom(zoom)
return round(self.x_size / self.matrix_width(zoom), ROUND) | [
"def",
"tile_x_size",
"(",
"self",
",",
"zoom",
")",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"\"tile_x_size is deprecated\"",
")",
")",
"validate_zoom",
"(",
"zoom",
")",
"return",
"round",
"(",
"self",
".",
"x_size",
"/",
"self",
".",
... | 32.333333 | 0.006689 |
def get_datacenter_by_name(self, name, depth=1):
"""
Retrieves a data center by its name.
Either returns the data center response or raises an Exception
if no or more than one data center was found with the name.
The search for the name is done in this relaxing way:
- e... | [
"def",
"get_datacenter_by_name",
"(",
"self",
",",
"name",
",",
"depth",
"=",
"1",
")",
":",
"all_data_centers",
"=",
"self",
".",
"list_datacenters",
"(",
"depth",
"=",
"depth",
")",
"[",
"'items'",
"]",
"data_center",
"=",
"find_item_by_name",
"(",
"all_da... | 42.333333 | 0.002799 |
def render(self, name, value, attrs=None, *args, **kwargs):
"""Handle a few expected values for rendering the current choice.
Extracts the state name from StateWrapper and State object.
"""
if isinstance(value, base.StateWrapper):
state_name = value.state.name
elif i... | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"base",
".",
"StateWrapper",
")",
":",
"state_name",
"=",
"value",
".",
... | 42.75 | 0.005725 |
def is_corrupted(l, sym, input_v):
"""
This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
... | [
"def",
"is_corrupted",
"(",
"l",
",",
"sym",
",",
"input_v",
")",
":",
"# If version is just a number, read the version document",
"input_v",
"=",
"l",
".",
"_versions",
".",
"find_one",
"(",
"{",
"'symbol'",
":",
"sym",
",",
"'version'",
":",
"input_v",
"}",
... | 43.066667 | 0.004542 |
def get_other_keys(self, key, including_current=False):
""" Returns list of other keys that are mapped to the same value as specified key.
@param key - key for which other keys should be returned.
@param including_current if set to True - key will also appear on this list."""
... | [
"def",
"get_other_keys",
"(",
"self",
",",
"key",
",",
"including_current",
"=",
"False",
")",
":",
"other_keys",
"=",
"[",
"]",
"if",
"key",
"in",
"self",
":",
"other_keys",
".",
"extend",
"(",
"self",
".",
"__dict__",
"[",
"str",
"(",
"type",
"(",
... | 52.6 | 0.009346 |
def _ols_fit(self):
""" Performs OLS
Returns
----------
None (stores latent variables)
"""
# TO DO - A lot of things are VAR specific here; might need to refactor in future, or just move to VAR script
method = 'OLS'
self.use_ols_covariance = True
... | [
"def",
"_ols_fit",
"(",
"self",
")",
":",
"# TO DO - A lot of things are VAR specific here; might need to refactor in future, or just move to VAR script",
"method",
"=",
"'OLS'",
"self",
".",
"use_ols_covariance",
"=",
"True",
"res_z",
"=",
"self",
".",
"_create_B_direct",
"(... | 38.976744 | 0.01979 |
def render_build_args(options, ns):
"""Get docker build args dict, rendering any templated args.
Args:
options (dict):
The dictionary for a given image from chartpress.yaml.
Fields in `options['buildArgs']` will be rendered and returned,
if defined.
ns (dict): the namespace used... | [
"def",
"render_build_args",
"(",
"options",
",",
"ns",
")",
":",
"build_args",
"=",
"options",
".",
"get",
"(",
"'buildArgs'",
",",
"{",
"}",
")",
"for",
"key",
",",
"value",
"in",
"build_args",
".",
"items",
"(",
")",
":",
"build_args",
"[",
"key",
... | 36.071429 | 0.001931 |
def _progress_register(self, amount_of_work, description='', stage=0, tqdm_args=None):
""" Registers a progress which can be reported/displayed via a progress bar.
Parameters
----------
amount_of_work : int
Amount of steps the underlying algorithm has to perform.
des... | [
"def",
"_progress_register",
"(",
"self",
",",
"amount_of_work",
",",
"description",
"=",
"''",
",",
"stage",
"=",
"0",
",",
"tqdm_args",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"show_progress",
":",
"return",
"if",
"tqdm_args",
"is",
"None",
":... | 44 | 0.004561 |
def segment(self, document):
"""
document: list[str]
return list[int],
i-th element denotes whether exists a boundary right before paragraph i(0 indexed)
"""
# ensure document is not empty and every element is an instance of str
assert(len(document) > 0 and le... | [
"def",
"segment",
"(",
"self",
",",
"document",
")",
":",
"# ensure document is not empty and every element is an instance of str",
"assert",
"(",
"len",
"(",
"document",
")",
">",
"0",
"and",
"len",
"(",
"[",
"d",
"for",
"d",
"in",
"document",
"if",
"not",
"i... | 39.34375 | 0.002325 |
def build_list(self, manifests):
"""
Builds a manifest list or OCI image out of the given manifests
"""
media_type = manifests[0]['media_type']
if (not all(m['media_type'] == media_type for m in manifests)):
raise PluginFailedException('worker manifests have inconsis... | [
"def",
"build_list",
"(",
"self",
",",
"manifests",
")",
":",
"media_type",
"=",
"manifests",
"[",
"0",
"]",
"[",
"'media_type'",
"]",
"if",
"(",
"not",
"all",
"(",
"m",
"[",
"'media_type'",
"]",
"==",
"media_type",
"for",
"m",
"in",
"manifests",
")",
... | 39.090909 | 0.003026 |
def from_dict(d):
"""
Builds a new instance of FileRecordSearch from a dict
:param Object d: the dict to parse
:return: a new FileRecordSearch based on the supplied dict
"""
obstory_ids = _value_from_dict(d, 'obstory_ids')
lat_min = _value_from_dict(d, 'lat_min')... | [
"def",
"from_dict",
"(",
"d",
")",
":",
"obstory_ids",
"=",
"_value_from_dict",
"(",
"d",
",",
"'obstory_ids'",
")",
"lat_min",
"=",
"_value_from_dict",
"(",
"d",
",",
"'lat_min'",
")",
"lat_max",
"=",
"_value_from_dict",
"(",
"d",
",",
"'lat_max'",
")",
"... | 54.857143 | 0.003582 |
def get_url(self, routename, **kargs):
""" Return a string that matches a named route """
scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
location = self.router.build(routename, **kargs).lstrip('/')
return urljoin(urljoin('/', scriptname), location) | [
"def",
"get_url",
"(",
"self",
",",
"routename",
",",
"*",
"*",
"kargs",
")",
":",
"scriptname",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
",",
"''",
")",
".",
"strip",
"(",
"'/'",
")",
"+",
"'/'",
"location",
"=",
"self",
"... | 59.6 | 0.006623 |
def get_all(kind='2'):
'''
Get All the records.
'''
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.valid == 1)
).order_by(
TabPost.time_update.desc()
) | [
"def",
"get_all",
"(",
"kind",
"=",
"'2'",
")",
":",
"return",
"TabPost",
".",
"select",
"(",
")",
".",
"where",
"(",
"(",
"TabPost",
".",
"kind",
"==",
"kind",
")",
"&",
"(",
"TabPost",
".",
"valid",
"==",
"1",
")",
")",
".",
"order_by",
"(",
... | 24.4 | 0.007905 |
def p_color(self, p):
""" color : css_color
| css_color t_ws
"""
try:
p[0] = Color().fmt(p[1])
if len(p) > 2:
p[0] = [p[0], p[2]]
except ValueError:
self.handle_error('Illegal color ... | [
"def",
"p_color",
"(",
"self",
",",
"p",
")",
":",
"try",
":",
"p",
"[",
"0",
"]",
"=",
"Color",
"(",
")",
".",
"fmt",
"(",
"p",
"[",
"1",
"]",
")",
"if",
"len",
"(",
"p",
")",
">",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
... | 33.333333 | 0.004866 |
def draw(self, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):
"""
Draw the mesh using the assigned mesh program
:param projection_matrix: projection_matrix (bytes)
:param view_matrix: view_matrix (bytes)
:param camera_matrix: camera_matrix (bytes)
... | [
"def",
"draw",
"(",
"self",
",",
"projection_matrix",
"=",
"None",
",",
"view_matrix",
"=",
"None",
",",
"camera_matrix",
"=",
"None",
",",
"time",
"=",
"0",
")",
":",
"if",
"self",
".",
"mesh_program",
":",
"self",
".",
"mesh_program",
".",
"draw",
"(... | 36 | 0.005076 |
def streaming_init(self):
"""
Send out initialization variables and process init from modules
Returns
-------
None
"""
system = self.system
config = self.config
if system.config.dime_enable:
config.compute_flows = True
syst... | [
"def",
"streaming_init",
"(",
"self",
")",
":",
"system",
"=",
"self",
".",
"system",
"config",
"=",
"self",
".",
"config",
"if",
"system",
".",
"config",
".",
"dime_enable",
":",
"config",
".",
"compute_flows",
"=",
"True",
"system",
".",
"streaming",
"... | 30.125 | 0.004024 |
def _get_or_update_or_create_related_instance(
self, ModelClass, fieldname, field_data
):
"""
Handle lookup, update, or creation of related instances based on the
field data provided and the field's `writable_related_fields` settings
as defined on the serializer's `Meta`.... | [
"def",
"_get_or_update_or_create_related_instance",
"(",
"self",
",",
"ModelClass",
",",
"fieldname",
",",
"field_data",
")",
":",
"writable_related_fields",
"=",
"getattr",
"(",
"self",
".",
"Meta",
",",
"'writable_related_fields'",
",",
"{",
"}",
")",
"# Get setti... | 45.234848 | 0.000492 |
def main():
""" Main function for command line usage """
usage = "usage: %(prog)s [options] "
description = "Merge a set of Fermi-LAT files."
parser = argparse.ArgumentParser(usage=usage, description=description)
parser.add_argument('-o', '--output', default=None, type=str,
... | [
"def",
"main",
"(",
")",
":",
"usage",
"=",
"\"usage: %(prog)s [options] \"",
"description",
"=",
"\"Merge a set of Fermi-LAT files.\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"usage",
"=",
"usage",
",",
"description",
"=",
"description",
")",
"parse... | 41.269231 | 0.001821 |
def recache( methodname=None, filename=None ):
"""
Deletes entries corresponding to methodname in filename. If no arguments are passed it recaches the entire table.
:param str methodname: The name of the method to target. This will delete ALL entries this method appears in the stack trace for.
:param s... | [
"def",
"recache",
"(",
"methodname",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"methodname",
"and",
"not",
"filename",
":",
"hashes",
"=",
"get_unique_hashes",
"(",
")",
"deleted",
"=",
"0",
"for",
"hash",
"in",
"hashes",
":",
"... | 36.896552 | 0.016393 |
def _build(self, src, path, dest, mtime):
"""Calls `build` after testing that at least one output file (as
returned by `_outputs()` does not exist or is older than `mtime`. If
the build fails, the build time is recorded and no other builds will be
attempted on `input` until this method i... | [
"def",
"_build",
"(",
"self",
",",
"src",
",",
"path",
",",
"dest",
",",
"mtime",
")",
":",
"input_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src",
",",
"path",
")",
"output_paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dest",
... | 45.615385 | 0.000825 |
def get(self, url, params=None, callback=None, retry=0, **kwargs):
"""Similar to `requests.get`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", True)
return self.request(
"get", url=url, params=params, callback=callback, retry=retry, **kwargs
) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"retry",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"allow_redirects\"",
",",
"True",
")",
"return",
"self",
... | 50.166667 | 0.009804 |
def _value(self, obj, cls=None):
"""The state value (called from the wrapper)"""
if obj is not None:
return getattr(obj, self.propname)
else:
return getattr(cls, self.propname) | [
"def",
"_value",
"(",
"self",
",",
"obj",
",",
"cls",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"return",
"getattr",
"(",
"obj",
",",
"self",
".",
"propname",
")",
"else",
":",
"return",
"getattr",
"(",
"cls",
",",
"self",
"."... | 36.5 | 0.008929 |
def _is_blacklisted_filename(filepath):
"""Checks if the filename matches filename_blacklist
blacklist is a list of filenames(str) and/or file patterns(dict)
string, specifying an exact filename to ignore
[".DS_Store", "Thumbs.db"]
mapping(dict), where each dict contains:
'match' - (if th... | [
"def",
"_is_blacklisted_filename",
"(",
"filepath",
")",
":",
"if",
"not",
"cfg",
".",
"CONF",
".",
"filename_blacklist",
":",
"return",
"False",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"fname",
"=",
"os",
".",
"path",
... | 32.267857 | 0.000537 |
def fave_mentions(api, dry_run=None):
'''
Fave (aka like) recent mentions from user authenicated in 'api'.
:api twitter_bot_utils.api.API
:dry_run bool don't actually favorite, just report
'''
f = api.favorites(include_entities=False, count=150)
favs = [m.id_str for m in f]
try:
... | [
"def",
"fave_mentions",
"(",
"api",
",",
"dry_run",
"=",
"None",
")",
":",
"f",
"=",
"api",
".",
"favorites",
"(",
"include_entities",
"=",
"False",
",",
"count",
"=",
"150",
")",
"favs",
"=",
"[",
"m",
".",
"id_str",
"for",
"m",
"in",
"f",
"]",
... | 38.483871 | 0.002453 |
def FromString(val):
"""
Create a ContractParameterType object from a str
Args:
val (str): the value to be converted to a ContractParameterType.
val can be hex encoded (b'07'), int (7), string int ("7"), or string literal ("String")
Returns:
Contract... | [
"def",
"FromString",
"(",
"val",
")",
":",
"# first, check if the value supplied is the string literal of the enum (e.g. \"String\")",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"val",
"=",
"val",
".",
"decode",
"(",
"'utf-8'",
")",
"try",
":",
"return"... | 35.090909 | 0.004202 |
def copy(self, source, dest):
"""Implementation of :meth:`~simplekv.CopyMixin.copy`.
Copies the data in the backing store and removes the destination key from the cache,
in case it was already populated.
Does not work when the backing store does not implement copy.
""... | [
"def",
"copy",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"try",
":",
"k",
"=",
"self",
".",
"_dstore",
".",
"copy",
"(",
"source",
",",
"dest",
")",
"finally",
":",
"self",
".",
"cache",
".",
"delete",
"(",
"dest",
")",
"return",
"k"
] | 36.75 | 0.00885 |
def get(self):
"""
Get a JSON-ready representation of this Personalization.
:returns: This Personalization, ready for use in a request body.
:rtype: dict
"""
personalization = {}
for key in ['tos', 'ccs', 'bccs']:
value = getattr(self, key)
... | [
"def",
"get",
"(",
"self",
")",
":",
"personalization",
"=",
"{",
"}",
"for",
"key",
"in",
"[",
"'tos'",
",",
"'ccs'",
",",
"'bccs'",
"]",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"value",
":",
"personalization",
"[",
"key"... | 30.178571 | 0.002294 |
def gpg_list_profile_keys( blockchain_id, proxy=None, wallet_keys=None, config_dir=None ):
"""
List all GPG keys in a user profile:
Return a list of {'identifier': key ID, 'contentUrl': URL to the key data} on success
Raise on error
Return {'error': ...} on failure
"""
config_dir = get_conf... | [
"def",
"gpg_list_profile_keys",
"(",
"blockchain_id",
",",
"proxy",
"=",
"None",
",",
"wallet_keys",
"=",
"None",
",",
"config_dir",
"=",
"None",
")",
":",
"config_dir",
"=",
"get_config_dir",
"(",
"config_dir",
")",
"client_config_path",
"=",
"os",
".",
"path... | 28.27027 | 0.013863 |
def validate_url(cls, url: str) -> Optional[Match[str]]:
"""Check if the Extractor can handle the given url."""
match = re.match(cls._VALID_URL, url)
return match | [
"def",
"validate_url",
"(",
"cls",
",",
"url",
":",
"str",
")",
"->",
"Optional",
"[",
"Match",
"[",
"str",
"]",
"]",
":",
"match",
"=",
"re",
".",
"match",
"(",
"cls",
".",
"_VALID_URL",
",",
"url",
")",
"return",
"match"
] | 45.75 | 0.010753 |
def _scons_internal_warning(e):
"""Slightly different from _scons_user_warning in that we use the
*current call stack* rather than sys.exc_info() to get our stack trace.
This is used by the warnings framework to print warnings."""
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extr... | [
"def",
"_scons_internal_warning",
"(",
"e",
")",
":",
"filename",
",",
"lineno",
",",
"routine",
",",
"dummy",
"=",
"find_deepest_user_frame",
"(",
"traceback",
".",
"extract_stack",
"(",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\nscons: warning:... | 66.714286 | 0.006342 |
def dump_img(fname):
""" output the image as text """
img = Image.open(fname)
width, _ = img.size
txt = ''
pixels = list(img.getdata())
for col in range(width):
txt += str(pixels[col:col+width])
return txt | [
"def",
"dump_img",
"(",
"fname",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"fname",
")",
"width",
",",
"_",
"=",
"img",
".",
"size",
"txt",
"=",
"''",
"pixels",
"=",
"list",
"(",
"img",
".",
"getdata",
"(",
")",
")",
"for",
"col",
"in",
... | 25.888889 | 0.004149 |
def makeCertHokTokenLoginMethod(stsUrl, stsCert=None):
'''Return a function that will call the vim.SessionManager.LoginByToken()
after obtaining a HoK SAML token from the STS. The result of this function
can be passed as the "loginMethod" to a SessionOrientedStub constructor.
@param stsUrl: URL... | [
"def",
"makeCertHokTokenLoginMethod",
"(",
"stsUrl",
",",
"stsCert",
"=",
"None",
")",
":",
"assert",
"(",
"stsUrl",
")",
"def",
"_doLogin",
"(",
"soapStub",
")",
":",
"from",
".",
"import",
"sso",
"cert",
"=",
"soapStub",
".",
"schemeArgs",
"[",
"'cert_fi... | 38.617647 | 0.017831 |
def get_task_cost(self, task_name):
"""
Get task cost
:param task_name: name of the task
:return: task cost
:rtype: Instance.TaskCost
:Example:
>>> cost = instance.get_task_cost(instance.get_task_names()[0])
>>> cost.cpu_cost
200
>>> cos... | [
"def",
"get_task_cost",
"(",
"self",
",",
"task_name",
")",
":",
"summary",
"=",
"self",
".",
"get_task_summary",
"(",
"task_name",
")",
"if",
"summary",
"is",
"None",
":",
"return",
"None",
"if",
"'Cost'",
"in",
"summary",
":",
"task_cost",
"=",
"summary"... | 24.9 | 0.002577 |
def move(self, d_xyz, inplace=False):
"""
Translate the whole Space in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:param inplace: If True, the moved ``pyny.Space`` is copied and
added to the cu... | [
"def",
"move",
"(",
"self",
",",
"d_xyz",
",",
"inplace",
"=",
"False",
")",
":",
"state",
"=",
"Polygon",
".",
"verify",
"Polygon",
".",
"verify",
"=",
"False",
"if",
"len",
"(",
"d_xyz",
")",
"==",
"2",
":",
"d_xyz",
"=",
"(",
"d_xyz",
"[",
"0"... | 33.888889 | 0.008502 |
async def async_current_transfer_human_readable(
self, use_cache=True):
"""Gets current transfer rates in a human readable format."""
rx, tx = await self.async_get_current_transfer_rates(use_cache)
return "%s/s" % convert_size(rx), "%s/s" % convert_size(tx) | [
"async",
"def",
"async_current_transfer_human_readable",
"(",
"self",
",",
"use_cache",
"=",
"True",
")",
":",
"rx",
",",
"tx",
"=",
"await",
"self",
".",
"async_get_current_transfer_rates",
"(",
"use_cache",
")",
"return",
"\"%s/s\"",
"%",
"convert_size",
"(",
... | 48.166667 | 0.006803 |
def get_config(self, hostname):
"""
Returns a configuration for hostname.
"""
version, config = self._get(
self.associations.get(hostname)
)
return config | [
"def",
"get_config",
"(",
"self",
",",
"hostname",
")",
":",
"version",
",",
"config",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"associations",
".",
"get",
"(",
"hostname",
")",
")",
"return",
"config"
] | 23 | 0.009302 |
def get(cls, schedule_payment_batch_id, note_text_schedule_payment_batch_id,
monetary_account_id=None, custom_headers=None):
"""
:type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type schedule_payment_batch_id: int
:type ... | [
"def",
"get",
"(",
"cls",
",",
"schedule_payment_batch_id",
",",
"note_text_schedule_payment_batch_id",
",",
"monetary_account_id",
"=",
"None",
",",
"custom_headers",
"=",
"None",
")",
":",
"if",
"custom_headers",
"is",
"None",
":",
"custom_headers",
"=",
"{",
"}... | 45.518519 | 0.004781 |
def validate_amendment(obj, retain_deprecated=True, **kwargs):
"""Takes an `obj` that is an amendment object.
`retain_deprecated` if False, then `obj` may be modified to replace
deprecated constructs with new syntax. If it is True, the `obj` will
not be modified.
Returns the pair:
er... | [
"def",
"validate_amendment",
"(",
"obj",
",",
"retain_deprecated",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Gather and report errors in a simple list",
"errors",
"=",
"[",
"]",
"n",
"=",
"create_validation_adaptor",
"(",
"obj",
",",
"errors",
",",
"*",... | 45.625 | 0.004027 |
def GetNumCoresOnHosts(hosts, private_key):
""" Returns list of the number of cores for each host requested in hosts. """
results = runner.Runner(host_list=hosts, private_key=private_key,
module_name='setup').run()
num_cores_list = []
for _, props in results['contacted'].iteritems():
... | [
"def",
"GetNumCoresOnHosts",
"(",
"hosts",
",",
"private_key",
")",
":",
"results",
"=",
"runner",
".",
"Runner",
"(",
"host_list",
"=",
"hosts",
",",
"private_key",
"=",
"private_key",
",",
"module_name",
"=",
"'setup'",
")",
".",
"run",
"(",
")",
"num_co... | 35.714286 | 0.015595 |
def failure_message(self):
""" str: A message describing the query failure. """
return (
"Expected node to have styles {expected}. "
"Actual styles were {actual}").format(
expected=desc(self.expected_styles),
actual=desc(self.actual_styles)) | [
"def",
"failure_message",
"(",
"self",
")",
":",
"return",
"(",
"\"Expected node to have styles {expected}. \"",
"\"Actual styles were {actual}\"",
")",
".",
"format",
"(",
"expected",
"=",
"desc",
"(",
"self",
".",
"expected_styles",
")",
",",
"actual",
"=",
"desc"... | 43.857143 | 0.00639 |
def get_common_path(pathlist):
"""Return common path for all paths in pathlist"""
common = osp.normpath(osp.commonprefix(pathlist))
if len(common) > 1:
if not osp.isdir(common):
return abspardir(common)
else:
for path in pathlist:
if not osp.is... | [
"def",
"get_common_path",
"(",
"pathlist",
")",
":",
"common",
"=",
"osp",
".",
"normpath",
"(",
"osp",
".",
"commonprefix",
"(",
"pathlist",
")",
")",
"if",
"len",
"(",
"common",
")",
">",
"1",
":",
"if",
"not",
"osp",
".",
"isdir",
"(",
"common",
... | 40.230769 | 0.001869 |
def parse_field(fld, selectable, aggregated=True, default_aggregation='sum'):
""" Parse a field object from yaml into a sqlalchemy expression """
# An aggregation is a callable that takes a single field expression
# None will perform no aggregation
aggregation_lookup = {
'sum': func.sum,
... | [
"def",
"parse_field",
"(",
"fld",
",",
"selectable",
",",
"aggregated",
"=",
"True",
",",
"default_aggregation",
"=",
"'sum'",
")",
":",
"# An aggregation is a callable that takes a single field expression",
"# None will perform no aggregation",
"aggregation_lookup",
"=",
"{"... | 35.785714 | 0.000243 |
def guess_type(typ):
'''Guess the atom type from purely heuristic considerations.'''
# Strip useless numbers
match = re.match("([a-zA-Z]+)\d*", typ)
if match:
typ = match.groups()[0]
return typ | [
"def",
"guess_type",
"(",
"typ",
")",
":",
"# Strip useless numbers",
"match",
"=",
"re",
".",
"match",
"(",
"\"([a-zA-Z]+)\\d*\"",
",",
"typ",
")",
"if",
"match",
":",
"typ",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"return",
"typ"
] | 31.285714 | 0.008889 |
def convert_cg3_to_conll( lines, **kwargs ):
''' Converts the output of VISL_CG3 based syntactic parsing into CONLL format.
Expects that the output has been cleaned ( via method cleanup_lines() ).
Returns a list of CONLL format lines;
Parameters
-----------
lines : l... | [
"def",
"convert_cg3_to_conll",
"(",
"lines",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"lines",
",",
"list",
")",
":",
"raise",
"Exception",
"(",
"'(!) Unexpected type of input argument! Expected a list of strings.'",
")",
"fix_selfrefs",
"=... | 43.710784 | 0.015461 |
def autofit(ts, maxp=5, maxd=2, maxq=5, sc=None):
"""
Utility function to help in fitting an automatically selected ARIMA model based on approximate
Akaike Information Criterion (AIC) values. The model search is based on the heuristic
developed by Hyndman and Khandakar (2008) and described in [[http://w... | [
"def",
"autofit",
"(",
"ts",
",",
"maxp",
"=",
"5",
",",
"maxd",
"=",
"2",
",",
"maxq",
"=",
"5",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing SparkContext\"",
"jmodel",
"=",
"sc",
".",
"_jvm",
".",
"com",
".",
... | 46.472222 | 0.011124 |
def set(self, section, option, value=None):
"""Set an option. Extend ConfigParser.set: check for string values."""
# The only legal non-string value if we allow valueless
# options is None, so we need to check if the value is a
# string if:
# - we do not allow valueless options,... | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
"=",
"None",
")",
":",
"# The only legal non-string value if we allow valueless",
"# options is None, so we need to check if the value is a",
"# string if:",
"# - we do not allow valueless options, or",
"# - ... | 53.65 | 0.002747 |
def europepmc_api_to_publication(ext_id, id_type):
# https://europepmc.org/docs/EBI_Europe_PMC_Web_Service_Reference.pdf
assert id_type in Publication.ID_TYPES, "id_type must be in {}".format(Publication.ID_TYPES.keys())
# Request the data
if id_type == "pmcid":
url = 'https://www.ebi.ac.uk/euro... | [
"def",
"europepmc_api_to_publication",
"(",
"ext_id",
",",
"id_type",
")",
":",
"# https://europepmc.org/docs/EBI_Europe_PMC_Web_Service_Reference.pdf",
"assert",
"id_type",
"in",
"Publication",
".",
"ID_TYPES",
",",
"\"id_type must be in {}\"",
".",
"format",
"(",
"Publicati... | 40.947368 | 0.002092 |
def check_perms(parser, token):
"""
Returns a list of permissions (as ``codename`` strings) for a given
``user``/``group`` and ``obj`` (Model instance).
Parses ``check_perms`` tag which should be in format::
{% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %}
or
... | [
"def",
"check_perms",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"format",
"=",
"'{% check_perms \"perm1[, perm2, ...]\" for user in slug as \"context_var\" %}'",
"if",
"len",
"(",
"bits",
")",
"!=",
"8",
"or",
"b... | 38.272727 | 0.003474 |
def model_to_data(self, sigma=0.0):
""" Switch out the data for the model's recreation of the data. """
im = self.model.copy()
im += sigma*np.random.randn(*im.shape)
self.set_image(util.NullImage(image=im)) | [
"def",
"model_to_data",
"(",
"self",
",",
"sigma",
"=",
"0.0",
")",
":",
"im",
"=",
"self",
".",
"model",
".",
"copy",
"(",
")",
"im",
"+=",
"sigma",
"*",
"np",
".",
"random",
".",
"randn",
"(",
"*",
"im",
".",
"shape",
")",
"self",
".",
"set_i... | 46.8 | 0.008403 |
def _right_click(self, event):
"""Function bound to right click event for marker canvas"""
iid = self.current_iid
if iid is None:
if self._menu is not None:
self._menu.post(event.x, event.y)
return
args = (iid, (event.x_root, event.y_root))
... | [
"def",
"_right_click",
"(",
"self",
",",
"event",
")",
":",
"iid",
"=",
"self",
".",
"current_iid",
"if",
"iid",
"is",
"None",
":",
"if",
"self",
".",
"_menu",
"is",
"not",
"None",
":",
"self",
".",
"_menu",
".",
"post",
"(",
"event",
".",
"x",
"... | 38.75 | 0.00315 |
def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin
name, default, help, lower_bound=None, upper_bound=None,
flag_values=_flagvalues.FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.... | [
"def",
"DEFINE_integer",
"(",
"# pylint: disable=invalid-name,redefined-builtin",
"name",
",",
"default",
",",
"help",
",",
"lower_bound",
"=",
"None",
",",
"upper_bound",
"=",
"None",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
",",
"*",
"*",
"args",
... | 46 | 0.006776 |
def thresholdBlocks(self, blocks, recall_weight=1.5): # pragma: nocover
"""
Returns the threshold that maximizes the expected F score, a
weighted average of precision and recall for a sample of
blocked data.
Arguments:
blocks -- Sequence of tuples of records, where eac... | [
"def",
"thresholdBlocks",
"(",
"self",
",",
"blocks",
",",
"recall_weight",
"=",
"1.5",
")",
":",
"# pragma: nocover",
"candidate_records",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"self",
".",
"_blockedPairs",
"(",
"blocks",
")",
")",
"proba... | 37.325581 | 0.001821 |
def contains(string):
"""Checks if the string value contains another string."""
def contains_str(value):
validate(text, value)
if string not in value:
raise ValueError("'{0}' does not contain '{1}'".format(value, string))
return True
return contains_str | [
"def",
"contains",
"(",
"string",
")",
":",
"def",
"contains_str",
"(",
"value",
")",
":",
"validate",
"(",
"text",
",",
"value",
")",
"if",
"string",
"not",
"in",
"value",
":",
"raise",
"ValueError",
"(",
"\"'{0}' does not contain '{1}'\"",
".",
"format",
... | 32.666667 | 0.006623 |
def send_private_msg(self, *, user_id, message, auto_escape=False):
'''
发送私聊消息
------------
:param int user_id: 对方 QQ 号
:param str | list[ dict[ str, unknown ] ] message: 要发送的内容
:param bool auto_escape: 消息内容是否作为纯文本发送(即不解析 CQ 码),`message` 数据类型为 `list` 时无效
:return... | [
"def",
"send_private_msg",
"(",
"self",
",",
"*",
",",
"user_id",
",",
"message",
",",
"auto_escape",
"=",
"False",
")",
":",
"return",
"super",
"(",
")",
".",
"__getattr__",
"(",
"'send_private_msg'",
")",
"(",
"user_id",
"=",
"user_id",
",",
"message",
... | 36.285714 | 0.007678 |
def cli(ctx, organism, export_type="FASTA", seq_type="peptide", export_format="text", export_gff3_fasta=False, sequences=None, region=""):
"""Prepare a download for an organism
Output:
a dictionary containing download information
"""
return ctx.gi.io.write_downloadable(organism, export_type=export_typ... | [
"def",
"cli",
"(",
"ctx",
",",
"organism",
",",
"export_type",
"=",
"\"FASTA\"",
",",
"seq_type",
"=",
"\"peptide\"",
",",
"export_format",
"=",
"\"text\"",
",",
"export_gff3_fasta",
"=",
"False",
",",
"sequences",
"=",
"None",
",",
"region",
"=",
"\"\"",
... | 54.5 | 0.006772 |
def urlparts(self):
''' Return a :class:`urlparse.SplitResult` tuple that can be used
to reconstruct the full URL as requested by the client.
The tuple contains: (scheme, host, path, query_string, fragment).
The fragment is always empty because it is not visible to the server... | [
"def",
"urlparts",
"(",
"self",
")",
":",
"env",
"=",
"self",
".",
"environ",
"http",
"=",
"env",
".",
"get",
"(",
"'wsgi.url_scheme'",
",",
"'http'",
")",
"host",
"=",
"env",
".",
"get",
"(",
"'HTTP_X_FORWARDED_HOST'",
")",
"or",
"env",
".",
"get",
... | 52.315789 | 0.003953 |
def getSchedulesBuffer(self, period_group):
""" Return the requested tariff schedule :class:`~ekmmeters.SerialBlock` for meter.
Args:
period_group (int): A :class:`~ekmmeters.ReadSchedules` value.
Returns:
SerialBlock: The requested tariff schedules for meter.
... | [
"def",
"getSchedulesBuffer",
"(",
"self",
",",
"period_group",
")",
":",
"empty_return",
"=",
"SerialBlock",
"(",
")",
"if",
"period_group",
"==",
"ReadSchedules",
".",
"Schedules_1_To_4",
":",
"return",
"self",
".",
"m_schd_1_to_4",
"elif",
"period_group",
"==",
... | 36.6875 | 0.004983 |
def get_selected_terms(term_doc_matrix, scores, num_term_to_keep=None):
'''
Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep betwe... | [
"def",
"get_selected_terms",
"(",
"term_doc_matrix",
",",
"scores",
",",
"num_term_to_keep",
"=",
"None",
")",
":",
"num_term_to_keep",
"=",
"AutoTermSelector",
".",
"_add_default_num_terms_to_keep",
"(",
"num_term_to_keep",
")",
"term_doc_freq",
"=",
"term_doc_matrix",
... | 42.913043 | 0.02775 |
def add_partitioning_indexes(portal):
"""Adds the indexes for partitioning
"""
logger.info("Adding partitioning indexes")
add_index(portal, catalog_id=CATALOG_ANALYSIS_LISTING,
index_name="getAncestorsUIDs",
index_attribute="getAncestorsUIDs",
index_metatype="K... | [
"def",
"add_partitioning_indexes",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Adding partitioning indexes\"",
")",
"add_index",
"(",
"portal",
",",
"catalog_id",
"=",
"CATALOG_ANALYSIS_LISTING",
",",
"index_name",
"=",
"\"getAncestorsUIDs\"",
",",
"index_... | 37.428571 | 0.001862 |
def get_data(search_string, search_by='ip'):
"""
Download data from talosintelligence.com for the given IP
Return tabbed data text
"""
r_details = requests.get('https://talosintelligence.com/sb_api/query_lookup',
headers={
'Referer':'https://talosintelligence.com/reputat... | [
"def",
"get_data",
"(",
"search_string",
",",
"search_by",
"=",
"'ip'",
")",
":",
"r_details",
"=",
"requests",
".",
"get",
"(",
"'https://talosintelligence.com/sb_api/query_lookup'",
",",
"headers",
"=",
"{",
"'Referer'",
":",
"'https://talosintelligence.com/reputation... | 48.970149 | 0.018823 |
def getfieldindex(data, commdct, objkey, fname):
"""given objkey and fieldname, return its index"""
objindex = data.dtls.index(objkey)
objcomm = commdct[objindex]
for i_index, item in enumerate(objcomm):
try:
if item['field'] == [fname]:
break
except KeyError ... | [
"def",
"getfieldindex",
"(",
"data",
",",
"commdct",
",",
"objkey",
",",
"fname",
")",
":",
"objindex",
"=",
"data",
".",
"dtls",
".",
"index",
"(",
"objkey",
")",
"objcomm",
"=",
"commdct",
"[",
"objindex",
"]",
"for",
"i_index",
",",
"item",
"in",
... | 32.090909 | 0.002755 |
def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, verifier_name, template): # pragma: no cover
""" Initialize a new role for use with Molecule. """
command_args = {
'dependency_name': dependency_name,
'driver_name': driver_name,
'lint_name': li... | [
"def",
"role",
"(",
"ctx",
",",
"dependency_name",
",",
"driver_name",
",",
"lint_name",
",",
"provisioner_name",
",",
"role_name",
",",
"verifier_name",
",",
"template",
")",
":",
"# pragma: no cover",
"command_args",
"=",
"{",
"'dependency_name'",
":",
"dependen... | 32.857143 | 0.001056 |
def reply_bytes(self, request):
"""Take a `Request` and return an OP_MSG message as bytes."""
flags = struct.pack("<I", self._flags)
payload_type = struct.pack("<b", 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_i... | [
"def",
"reply_bytes",
"(",
"self",
",",
"request",
")",
":",
"flags",
"=",
"struct",
".",
"pack",
"(",
"\"<I\"",
",",
"self",
".",
"_flags",
")",
"payload_type",
"=",
"struct",
".",
"pack",
"(",
"\"<b\"",
",",
"0",
")",
"payload_data",
"=",
"bson",
"... | 39 | 0.003854 |
def update(gandi, fqdn, name, type, value, ttl, file):
"""Update record entry for a domain.
--file option will ignore other parameters and overwrite current zone
content with provided file content.
"""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not i... | [
"def",
"update",
"(",
"gandi",
",",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
",",
"file",
")",
":",
"domains",
"=",
"gandi",
".",
"dns",
".",
"list",
"(",
")",
"domains",
"=",
"[",
"domain",
"[",
"'fqdn'",
"]",
"for",
"domain",... | 33.833333 | 0.000958 |
def show_system_monitor_output_switch_status_switch_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
... | [
"def",
"show_system_monitor_output_switch_status_switch_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_system_monitor",
"=",
"ET",
".",
"Element",
"(",
"\"show_system_monitor\"",
")",
"con... | 44.846154 | 0.003361 |
def options(
self,
alias,
uri,
headers=None,
allow_redirects=None,
timeout=None):
""" **Deprecated- See Options Request now**
Send an OPTIONS request on the session object found using the
given `alias`
``alias`` th... | [
"def",
"options",
"(",
"self",
",",
"alias",
",",
"uri",
",",
"headers",
"=",
"None",
",",
"allow_redirects",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"logger",
".",
"warn",
"(",
"\"Deprecation Warning: Use Options Request in the future\"",
")",
"se... | 33.807692 | 0.003319 |
def _defaggr(name, type, func):
'Define aggregator `name` that calls func(col, rows)'
func.type=type
func.__name__ = name
return func | [
"def",
"_defaggr",
"(",
"name",
",",
"type",
",",
"func",
")",
":",
"func",
".",
"type",
"=",
"type",
"func",
".",
"__name__",
"=",
"name",
"return",
"func"
] | 29 | 0.013423 |
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values fo... | [
"def",
"getquerydict",
"(",
"self",
",",
"sep",
"=",
"'&'",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"dict",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"name",
",",
"value",
"in",
"self",
".",
"... | 46 | 0.003876 |
def permissions_for(self, user=None):
"""Handles permission resolution for a :class:`User`.
This function is there for compatibility with other channel types.
Actual direct messages do not really have the concept of permissions.
This returns all the Text related permissions set to tru... | [
"def",
"permissions_for",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"base",
"=",
"Permissions",
".",
"text",
"(",
")",
"base",
".",
"send_tts_messages",
"=",
"False",
"base",
".",
"manage_messages",
"=",
"False",
"return",
"base"
] | 30.892857 | 0.002242 |
def display(self, image):
"""
Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the PCD8544
LCD display.
"""
assert(image.mode == self.mode)
assert(image.size == self.size)
image = self.preprocess(image)
self.command(0x20, 0x80, 0x40)
buf = byte... | [
"def",
"display",
"(",
"self",
",",
"image",
")",
":",
"assert",
"(",
"image",
".",
"mode",
"==",
"self",
".",
"mode",
")",
"assert",
"(",
"image",
".",
"size",
"==",
"self",
".",
"size",
")",
"image",
"=",
"self",
".",
"preprocess",
"(",
"image",
... | 25.380952 | 0.003617 |
def eval_adiabatic_limit(YABFGN, Ytilde, P0):
"""Compute the limiting SLH model for the adiabatic approximation
Args:
YABFGN: The tuple (Y, A, B, F, G, N)
as returned by prepare_adiabatic_limit.
Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0.
P0: The projector o... | [
"def",
"eval_adiabatic_limit",
"(",
"YABFGN",
",",
"Ytilde",
",",
"P0",
")",
":",
"Y",
",",
"A",
",",
"B",
",",
"F",
",",
"G",
",",
"N",
"=",
"YABFGN",
"Klim",
"=",
"(",
"P0",
"*",
"(",
"B",
"-",
"A",
"*",
"Ytilde",
"*",
"A",
")",
"*",
"P0"... | 34 | 0.001244 |
def verify_crl(cert, path, validation_context, use_deltas=True, cert_description=None, end_entity_name_override=None):
"""
Verifies a certificate against a list of CRLs, checking to make sure the
certificate has not been revoked. Uses the algorithm from
https://tools.ietf.org/html/rfc5280#section-6.3 as... | [
"def",
"verify_crl",
"(",
"cert",
",",
"path",
",",
"validation_context",
",",
"use_deltas",
"=",
"True",
",",
"cert_description",
"=",
"None",
",",
"end_entity_name_override",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"cert",
",",
"x509",
".",
... | 38.34609 | 0.001776 |
def copy(self):
"""
Make a copy of this runnable.
@return: Copy of this runnable.
@rtype: lems.sim.runnable.Runnable
"""
if self.debug: print("Coping....."+self.id)
r = Runnable(self.id, self.component, self.parent)
copies = dict()
# Copy simulat... | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Coping.....\"",
"+",
"self",
".",
"id",
")",
"r",
"=",
"Runnable",
"(",
"self",
".",
"id",
",",
"self",
".",
"component",
",",
"self",
".",
"parent",
")",
"co... | 38.614213 | 0.007433 |
def rg(self):
"""
Brazilian RG, return plain numbers.
Check: https://www.ngmatematica.com/2014/02/como-determinar-o-digito-verificador-do.html
"""
digits = self.generator.random.sample(range(0, 9), 8)
checksum = sum(i * digits[i - 2] for i in range(2, 10))
last_... | [
"def",
"rg",
"(",
"self",
")",
":",
"digits",
"=",
"self",
".",
"generator",
".",
"random",
".",
"sample",
"(",
"range",
"(",
"0",
",",
"9",
")",
",",
"8",
")",
"checksum",
"=",
"sum",
"(",
"i",
"*",
"digits",
"[",
"i",
"-",
"2",
"]",
"for",
... | 30.333333 | 0.005329 |
def get_variable_value_for_variation(self, variable, variation):
""" Get the variable value for the given variation.
Args:
variable: The Variable for which we are getting the value.
variation: The Variation for which we are getting the variable value.
Returns:
The variable value or None ... | [
"def",
"get_variable_value_for_variation",
"(",
"self",
",",
"variable",
",",
"variation",
")",
":",
"if",
"not",
"variable",
"or",
"not",
"variation",
":",
"return",
"None",
"if",
"variation",
".",
"id",
"not",
"in",
"self",
".",
"variation_variable_usage_map",... | 30.325581 | 0.008915 |
def _login(session):
"""Login to UPS."""
resp = session.get(LOGIN_URL, params=_get_params(session.auth.locale))
parsed = BeautifulSoup(resp.text, HTML_PARSER)
csrf = parsed.find(CSRF_FIND_TAG, CSRF_FIND_ATTR).get(VALUE_ATTR)
resp = session.post(LOGIN_URL, {
'userID': session.auth.username,
... | [
"def",
"_login",
"(",
"session",
")",
":",
"resp",
"=",
"session",
".",
"get",
"(",
"LOGIN_URL",
",",
"params",
"=",
"_get_params",
"(",
"session",
".",
"auth",
".",
"locale",
")",
")",
"parsed",
"=",
"BeautifulSoup",
"(",
"resp",
".",
"text",
",",
"... | 39.842105 | 0.00129 |
def _eval_binop(self, node):
"""
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.left),
self._eval(node.right)) | [
"def",
"_eval_binop",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"operators",
"[",
"type",
"(",
"node",
".",
"op",
")",
"]",
"(",
"self",
".",
"_eval",
"(",
"node",
".",
"left",
")",
",",
"self",
".",
"_eval",
"(",
"node",
".",
... | 34.555556 | 0.00627 |
def uninitialize_ui(self):
"""
Uninitializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Uninitializing '{0}' Component ui.".format(self.__class__.__name__))
self.__remove_actions()
# Signals / Slots.
self.Port_s... | [
"def",
"uninitialize_ui",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Uninitializing '{0}' Component ui.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"__remove_actions",
"(",
")",
"# Signals / Slots.",
"s... | 36.75 | 0.009284 |
def bytes_to_number(b, endian='big'):
"""
Convert a string to an integer.
:param b:
String or bytearray to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of str... | [
"def",
"bytes_to_number",
"(",
"b",
",",
"endian",
"=",
"'big'",
")",
":",
"if",
"endian",
"==",
"'big'",
":",
"b",
"=",
"reversed",
"(",
"b",
")",
"n",
"=",
"0",
"for",
"i",
",",
"ch",
"in",
"enumerate",
"(",
"bytearray",
"(",
"b",
")",
")",
"... | 22.057143 | 0.001241 |
def asset_asset_swap(
self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees):
"""
Creates a transaction for swapping an asset for another asset.
:param bytes asset1_id: The ID of the first asset.
:param TransferParameters asset1_transfer_spec: The para... | [
"def",
"asset_asset_swap",
"(",
"self",
",",
"asset1_id",
",",
"asset1_transfer_spec",
",",
"asset2_id",
",",
"asset2_transfer_spec",
",",
"fees",
")",
":",
"btc_transfer_spec",
"=",
"TransferParameters",
"(",
"asset1_transfer_spec",
".",
"unspent_outputs",
",",
"asse... | 55.631579 | 0.006512 |
def multi_future(children, quiet_exceptions=()):
"""Wait for multiple asynchronous futures in parallel.
This function is similar to `multi`, but does not support
`YieldPoints <YieldPoint>`.
.. versionadded:: 4.0
.. versionchanged:: 4.2
If multiple ``Futures`` fail, any exceptions after the... | [
"def",
"multi_future",
"(",
"children",
",",
"quiet_exceptions",
"=",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"children",
",",
"dict",
")",
":",
"keys",
"=",
"list",
"(",
"children",
".",
"keys",
"(",
")",
")",
"children",
"=",
"children",
".",
... | 33.181818 | 0.000532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.