text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def normalize_path_out(self, path):
"""Normalizes path sent to client
:param path: path to normalize
:return: normalized path
"""
if path.startswith(self._CWD):
normalized_path = path[len(self._CWD):]
else:
normalized_path = path
# For remo... | 0.005254 |
def load(self, d3mds):
"""Load X, y and context from D3MDS."""
X, y = d3mds.get_data()
return Dataset(d3mds.dataset_id, X, y) | 0.013333 |
def wildcards_overlap(name1, name2):
"""Return true if two wildcard patterns can match the same string."""
if not name1 and not name2:
return True
if not name1 or not name2:
return False
for matched1, matched2 in _character_matches(name1, name2):
if wildcards_overlap(name1[matche... | 0.002597 |
def create_folder(dirpath, overwrite=False):
""" Will create dirpath folder. If dirpath already exists and overwrite is False,
will append a '+' suffix to dirpath until dirpath does not exist."""
if not overwrite:
while op.exists(dirpath):
dirpath += '+'
os.m... | 0.007916 |
def conference_kick(self, call_params):
"""REST Conference Kick helper
"""
path = '/' + self.api_version + '/ConferenceKick/'
method = 'POST'
return self.request(path, method, call_params) | 0.008772 |
def _partition_all_internal(s, sep):
"""
Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings.
:param s: The string to split.
:param sep: A separator string.
:return: A list of parts split by sep
"""
parts = list(s.partition(sep))
... | 0.003356 |
def get_port(self):
""" Return a port to use to talk to this cluster. """
if len(self.client_nodes) > 0:
node = self.client_nodes[0]
else:
node = self.nodes[0]
return node.get_port() | 0.008403 |
def _comprise(dict1,dict2):
'''
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'b':2,'c':3}
_comprise(dict1,dict2)
'''
len_1 = dict1.__len__()
len_2 = dict2.__len__()
if(len_2>len_1):
return(False)
else:
for k2 in dict2:
v2 = dict2[k2]
... | 0.005618 |
def integrate_drag_sphere(D, rhop, rho, mu, t, V=0, Method=None,
distance=False):
r'''Integrates the velocity and distance traveled by a particle moving
at a speed which will converge to its terminal velocity.
Performs an integration of the following expression for acceleration:
... | 0.004172 |
def recoverMemory(buffer, size):
"""parse an XML in-memory block and build a tree. In the case
the document is not Well Formed, an attempt to build a tree
is tried anyway """
ret = libxml2mod.xmlRecoverMemory(buffer, size)
if ret is None:raise treeError('xmlRecoverMemory() failed')
return x... | 0.008955 |
def reset(target, settings):
"""
重置设置
:param target:
:param settings:
:return:
"""
target_settings = _import_module(target)
for k, v in settings.items():
if hasattr(target_settings, k):
setattr(target_settings, k, _get_value(getattr(target_settings, k), v))
el... | 0.006667 |
def generate(converter, input_file, format='xml', encoding='utf8'):
"""
Given a converter (as returned by compile()), this function reads
the given input file and converts it to the requested output format.
Supported output formats are 'xml', 'yaml', 'json', or 'none'.
:type converter: compiler.C... | 0.001264 |
def get_relation_type(self, relation_type):
"""
Get all the items of the given relationship type related to this item.
"""
qs = self.get_queryset()
return qs.filter(relation_type=relation_type) | 0.008584 |
def get_content_metadata(id, version, cursor):
"""Return metadata related to the content from the database."""
# Do the module lookup
args = dict(id=id, version=version)
# FIXME We are doing two queries here that can hopefully be
# condensed into one.
cursor.execute(SQL['get-module-metadat... | 0.000908 |
def remap_status(val):
"""Convert status integer value to appropriate bitmask."""
status = 0
bad = BAD_DATA if val & 0xF0 else 0
val &= 0x0F
if val == 0:
status = START_ELEVATION
elif val == 1:
status = 0
elif val == 2:
status = END_ELEVATION
elif val == 3:
... | 0.001931 |
def execute(self, env, args):
""" Removes a task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
# extract args
task_name = args.task_name
force = args.force
if env.task.a... | 0.001936 |
def scroll_event(self, widget, event):
"""
Called when a mouse is turned in the widget (and maybe for
finger scrolling in the trackpad).
Adjust method signature as appropriate for callback.
"""
x, y = event.x, event.y
num_degrees = 0
direction = 0
... | 0.002387 |
def datetime2ole(dt):
"""converts from datetime object to ole datetime float"""
delta = dt - OLE_TIME_ZERO
delta_float = delta / datetime.timedelta(days=1) # trick from SO
return delta_float | 0.004831 |
def one_of(s):
'''Parser a char from specified string.'''
@Parser
def one_of_parser(text, index=0):
if index < len(text) and text[index] in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'one of {}'.format(s))
return one_of_parse... | 0.003115 |
def start(self):
"""
The main method that starts the service. This is blocking.
"""
self._initial_setup()
self.on_service_start()
self.app = self.make_tornado_app()
enable_pretty_logging()
self.app.listen(self.port, address=self.host)
self._star... | 0.004255 |
def apply_units_to_cache(self, data):
"""
Apply units to :class:`ParameterizedXLS` data reader.
"""
# parameter
parameter_name = self.parameters['parameter']['name']
parameter_units = str(self.parameters['parameter']['units'])
data[parameter_name] *= UREG(paramete... | 0.004386 |
def _convert(cls, name, module, filter, source=None):
"""
Create a new Enum subclass that replaces a collection of global constants
"""
# convert all constants from source (or module) that pass filter() to
# a new Enum called name, and export the enum and its members back to
# module;
# also... | 0.002491 |
def update_port_postcommit(self, context):
"""Update port non-database commit event."""
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment, context.bottom_bound_segment)
orig_vlan_segment, orig_vxlan_segment = self._get_segments(
context.original_... | 0.001592 |
def _outside_contraction_fn(objective_function,
simplex,
objective_values,
face_centroid,
best_index,
worst_index,
reflected,
... | 0.006112 |
def ingest_zip(path, engine=None):
"""Given a path to a zip file created with `export()`, recreate the
database with the data stored in the included .csv files.
"""
import_order = [
"network",
"participant",
"node",
"info",
"notification",
"question",
... | 0.001183 |
def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | 0.007752 |
def eclean_dist(destructive=False, package_names=False, size_limit=0,
time_limit=0, fetch_restricted=False,
exclude_file='/etc/eclean/distfiles.exclude'):
'''
Clean obsolete portage sources
destructive
Only keep minimum for reinstallation
package_names
P... | 0.000367 |
def _change_sel_color(self, event):
"""Respond to motion of the color selection cross."""
(r, g, b), (h, s, v), color = self.square.get()
self.red.set(r)
self.green.set(g)
self.blue.set(b)
self.saturation.set(s)
self.value.set(v)
self.hexa.delete(0, "end")... | 0.003478 |
def reference(self, symbol, count=1):
"""
However, if referenced, ensure that the counter is applied to
the catch symbol.
"""
if symbol == self.catch_symbol:
self.catch_symbol_usage += count
else:
self.parent.reference(symbol, count) | 0.006536 |
def copy(self):
"""Return a shallow copy of this object.
"""
new = self.__class__()
new.__dict__ = dict(self.__dict__)
return new | 0.011765 |
def get_public_key(self):
"""Get the PublicKey for this PrivateKey."""
return PublicKey.from_verifying_key(
self._private_key.get_verifying_key(),
network=self.network, compressed=self.compressed) | 0.008475 |
def multiply(lhs, rhs):
"""Returns element-wise product of the input arrays with broadcasting.
Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_mul(lhs, rhs)``
..... | 0.001176 |
def __set_route(self, type_route, route):
"""
Sets the given type_route and route to the route mapping
:rtype: object
"""
if type_route in self.__routes:
if not self.verify_route_already_bound(type_route, route):
self.__routes[type_route].append(route)... | 0.004878 |
def createuser(self, email, name='', password=''):
"""
Return a bugzilla User for the given username
:arg email: The email address to use in bugzilla
:kwarg name: Real name to associate with the account
:kwarg password: Password to set for the bugzilla account
:raises XM... | 0.002976 |
def evolve(self, rho: Density) -> Density:
"""Apply the action of this channel upon a density"""
N = rho.qubit_nb
qubits = rho.qubits
indices = list([qubits.index(q) for q in self.qubits]) + \
list([qubits.index(q) + N for q in self.qubits])
tensor = bk.tensormul(se... | 0.004975 |
def solve(self):
"""Start (or re-start) optimisation. This method implements the
framework for the alternation between `X` and `D` updates in a
dictionary learning algorithm. There is sufficient flexibility
in specifying the two updates that it calls that it is
usually not necess... | 0.002082 |
def download_api(branch=None) -> str:
"""download API documentation from _branch_ of Habitica\'s repo on Github"""
habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'
if not branch:
branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name']
curl = local... | 0.007776 |
def ObjectInitializedEventHandler(obj, event):
"""Object has been created
"""
# only snapshot supported objects
if not supports_snapshots(obj):
return
# object has already snapshots
if has_snapshots(obj):
return
# take a new snapshot
take_snapshot(obj, action="create") | 0.003125 |
def EncodeForCSV(x):
"Encodes one value for CSV."
k = x.encode('utf-8')
if ',' in k or '"' in k:
return '"%s"' % k.replace('"', '""')
else:
return k | 0.030488 |
def MultiDestroyFlowStates(self, session_ids, request_limit=None):
"""Deletes all requests and responses for the given flows.
Args:
session_ids: A lists of flows to destroy.
request_limit: A limit on the number of requests to delete.
Returns:
A list of requests that were deleted.
"""... | 0.004421 |
def purge_old_user_tasks():
"""
Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``.
Intended to be run as a scheduled task.
"""
limit = now() - settings.USER_TASKS_MAX_AGE
# UserTaskArtifacts will also be removed via deletion cascading
UserTask... | 0.00542 |
def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields):
"""
Changes a given `changed_fields` on each object in a given `iterable`, saves objects
and returns the changed objects.
"""
return [
change_and_save(obj, update_only_changed_fields=upd... | 0.008989 |
def get(self, key, alt=None):
"""If dictionary contains _key_ return the associated value,
otherwise return _alt_.
"""
with self.lock:
if key in self:
return self.getitem(key)
else:
return alt | 0.007117 |
def _handle_value(self, value):
"""
Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)
"""
if self._inspec:
# Parsing a configspec so don't handle comments
return (value, '')
# do we look for list... | 0.001033 |
def gen_req_sfc(lat_x, lon_x, start, end, grid=[0.125, 0.125], scale=0):
'''generate a dict of reqs kwargs for (lat_x,lon_x) spanning [start, end]
Parameters
----------
lat_x : [type]
[description]
lon_x : [type]
[description]
start : [type]
[description]
end : [type... | 0.001976 |
def p_expression_cond(self, p):
'expression : expression COND expression COLON expression'
p[0] = Cond(p[1], p[3], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.010363 |
def analyzeAll(self):
"""analyze every unanalyzed ABF in the folder."""
searchableData=str(self.files2)
self.log.debug("considering analysis for %d ABFs",len(self.IDs))
for ID in self.IDs:
if not ID+"_" in searchableData:
self.log.debug("%s needs analysis",ID)... | 0.01461 |
def nonoverlap(item_a, time_a, item_b, time_b, max_value):
"""
Percentage of pixels in each object that do not overlap with the other object
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in Object... | 0.006431 |
def check_type(self):
"""Make sure each stochastic has a correct type, and identify discrete stochastics."""
self.isdiscrete = {}
for stochastic in self.stochastics:
if stochastic.dtype in integer_dtypes:
self.isdiscrete[stochastic] = True
elif stochastic.... | 0.007605 |
def to_jd(year, month, day):
'''Convert a Positivist date to Julian day count.'''
legal_date(year, month, day)
gyear = year + YEAR_EPOCH - 1
return (
gregorian.EPOCH - 1 + (365 * (gyear - 1)) +
floor((gyear - 1) / 4) + (-floor((gyear - 1) / 100)) +
floor((gyear - 1) / 400) + (mo... | 0.002899 |
def init_argparser_working_dir(
self, argparser,
explanation='',
help_template=(
'the working directory; %(explanation)s'
'default is current working directory (%(cwd)s)'),
):
"""
Subclass could an extra expanation on how th... | 0.002535 |
def from_parfiles(cls,pst,parfile_names,real_names=None):
""" create a parameter ensemble from parfiles. Accepts parfiles with less than the
parameters in the control (get NaNs in the ensemble) or extra parameters in the
parfiles (get dropped)
Parameters:
pst : pyemu.Pst
... | 0.010282 |
def exception(message):
"""Exception method convenience wrapper."""
def decorator(method):
"""Inner decorator so we can accept arguments."""
@wraps(method)
def wrapper(self, *args, **kwargs):
"""Innermost decorator wrapper - this is confusing."""
if self.message... | 0.003106 |
def run(self):
"""
Esegue il montaggio delle varie condivisioni chiedendo all'utente
username e password di dominio.
"""
logging.info('start run with "{}" at {}'.format(
self.username, datetime.datetime.now()))
progress = Progress(text="Controllo requisiti sof... | 0.000391 |
def task(func):
"""Decorator to run the decorated function as a Task
"""
def task_wrapper(*args, **kwargs):
return spawn(func, *args, **kwargs)
return task_wrapper | 0.005348 |
def get_sphinx_ref(self, url, label=None):
"""
Get an internal sphinx cross reference corresponding to `url`
into the online docs, associated with a link with label `label`
(if not None).
"""
# A url is assumed to correspond to a citation if it contains
# 'zrefer... | 0.001623 |
def from_key_bytes(cls, algorithm, key_bytes):
"""Builds a `Signer` from an algorithm suite and a raw signing key.
:param algorithm: Algorithm on which to base signer
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key_bytes: Raw signing key
:rtype: aws_en... | 0.005894 |
def char2features(sentence, i):
'''
Returns features of char at position `i` in given sentence
When it possible, result features list also includes features for 2 characters
ahead and behind current position (like bigrams, or something like it)
Currently, used features is:
1. lower-cased value o... | 0.001127 |
def _lookup_hashes(self, full_hashes):
"""Lookup URL hash in blacklists
Returns names of lists it was found in.
"""
full_hashes = list(full_hashes)
cues = [fh[0:4] for fh in full_hashes]
result = []
matching_prefixes = {}
matching_full_hashes = set()
... | 0.004957 |
def install_signal_handlers(self):
""" Handle events like Ctrl-C from the command line. """
self.graceful_stop = False
def request_shutdown_now():
self.shutdown_now()
def request_shutdown_graceful():
# Second time CTRL-C, shutdown now
if self.grace... | 0.002747 |
def create_mon_path(path, uid=-1, gid=-1):
"""create the mon path if it does not exist"""
if not os.path.exists(path):
os.makedirs(path)
os.chown(path, uid, gid); | 0.010753 |
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False):
"""Raises ValidationException if value is not a USA state.
Returns the capitalized state abbreviation, unless returnStateName is True
in which case it returns the titlecased s... | 0.007404 |
def _numeric_handler_factory(charset, transition, assertion, illegal_before_underscore, parse_func,
illegal_at_end=(None,), ion_type=None, append_first_if_not=None, first_char=None):
"""Generates a handler co-routine which tokenizes a numeric component (a token or sub-token).
Args:... | 0.007026 |
def wrap_iterable(obj):
"""
Returns:
wrapped_obj, was_scalar
"""
was_scalar = not isiterable(obj)
wrapped_obj = [obj] if was_scalar else obj
return wrapped_obj, was_scalar | 0.004926 |
def keypress(self, size, key):
"""allow subclasses to intercept keystrokes"""
key = self.__super.keypress(size, key)
if key:
key = self.unhandled_keys(size, key)
return key | 0.009259 |
def resolve_using_maximal_coverage(matches):
"""Given a list of matches, select a subset of matches
such that there are no overlaps and the total number of
covered characters is maximal.
Parameters
----------
matches: list of Match
Returns
--------
list of Match
"""
if len(... | 0.003812 |
def insert_rows(self, row, no_rows=1):
"""Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array... | 0.005587 |
def set_options_values(self, options, parse=False, strict=False):
""" Set the options from a dict of values (in string).
:param option_values: the values of options (in format `{"opt_name": "new_value"}`)
:type option_values: dict
:param parse: whether to parse the given value
... | 0.006705 |
def find_files(globs):
"""Find files to include."""
last_cwd = os.getcwd()
os.chdir(config.cwd)
gex, gin = separate_globs(globs)
# Find excluded files
exclude = []
for glob in gex:
parse_glob(glob, exclude)
files = []
include = []
order = 0
# Find included files and removed excluded files
for glob in... | 0.042226 |
def log_transform(rates):
""" log transform a numeric value, unless it is zero, or negative
"""
transformed = []
for key in ['missense', 'nonsense', 'splice_lof', 'splice_region',
'synonymous']:
try:
value = math.log10(rates[key])
except ValueError:
... | 0.012448 |
def _config_win32_nameservers(self, nameservers):
"""Configure a NameServer registry entry."""
# we call str() on nameservers to convert it from unicode to ascii
nameservers = str(nameservers)
split_char = self._determine_split_char(nameservers)
ns_list = nameservers.split(split_... | 0.006834 |
def read_bim(file_name):
"""Reads the BIM file to gather marker names.
:param file_name: the name of the ``bim`` file.
:type file_name: str
:returns: a :py:class:`dict` containing the chromosomal location of each
marker on the sexual chromosomes.
It uses the :py:func:`encode_chr` t... | 0.001346 |
def get(self, name=None):
"""Print a list of all jupyterHubs."""
# Print a list of hubs.
if name is None:
hubs = self.get_hubs()
print("Running Jupyterhub Deployments (by name):")
for hub_name in hubs:
hub = Hub(namespace=hub_name)
... | 0.00354 |
def usearch_chimera_filter_de_novo(
fasta_filepath,
output_chimera_filepath=None,
output_non_chimera_filepath=None,
abundance_skew=2.0,
log_name="uchime_de_novo_chimera_filtering.log",
usersort=False,
HALT_EXEC=False,
save_intermediate_files=False,
... | 0.000521 |
def parse(self, data=None, table_name=None):
"""Parse the lines from index i
:param data: optional, store the parsed result to it when specified
:param table_name: when inside a table array, it is the table name
"""
temp = self.dict_()
sub_table = None
is_array =... | 0.000637 |
def _parse_authors(html_chunk):
"""
Parse authors of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.
"""
authors_tags = html_chunk.match... | 0.002415 |
def JsonResponseModel(self):
"""In this context, return raw JSON instead of proto."""
old_model = self.response_type_model
self.__response_type_model = 'json'
yield
self.__response_type_model = old_model | 0.00823 |
def _store(self, offset, value, size=1):
"""Stores value in memory as a big endian"""
self.memory.write_BE(offset, value, size)
for i in range(size):
self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8)) | 0.010563 |
def redraw(self, whence=0):
"""Redraw the canvas.
Parameters
----------
whence
See :meth:`get_rgb_object`.
"""
with self._defer_lock:
whence = min(self._defer_whence, whence)
if not self.defer_redraw:
if self._hold_re... | 0.001521 |
def restore_model(cls, data):
"""Returns instance of ``cls`` with attributed loaded
from ``data`` dict.
"""
obj = cls()
for field in data:
setattr(obj, field, data[field][Field.VALUE])
return obj | 0.004386 |
def update(self, new_vals):
"""Add a dictionary of values to the current step without writing it to disk.
"""
for k, v in six.iteritems(new_vals):
k = k.strip()
if k in self.row:
warnings.warn("Adding history key ({}) that is already set in this step".form... | 0.010127 |
def list_subdomains_previous_page(self):
"""
When paging through subdomain results, this will return the previous
page, using the same limit. If there are no more results, a
NoMoreResults exception will be raised.
"""
uri = self._paging.get("subdomain", {}).get("prev_uri"... | 0.008 |
def add_forwarding_rules(self, forwarding_rules):
"""
Adds new forwarding rules to a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
"""
rules_dict = [rule.__dict__ for rule in forwarding_rules]
return self.get_data(
... | 0.004329 |
def _get_sghead(expnum):
"""
Use the data web service to retrieve the stephen's astrometric header.
:param expnum: CFHT exposure number you want the header for
:rtype : list of astropy.io.fits.Header objects.
"""
version = 'p'
key = "{}{}".format(expnum, version)
if key in sgheaders:
... | 0.001908 |
def inference(self, kern, X, likelihood, Y, Y_metadata=None):
"""
Returns a GridPosterior class containing essential quantities of the posterior
"""
N = X.shape[0] #number of training points
D = X.shape[1] #number of dimensions
Kds = np.zeros(D, dtype=object) #vector fo... | 0.014428 |
def event_return(events):
'''
Return event data via SMTP
'''
for event in events:
ret = event.get('data', False)
if ret:
returner(ret) | 0.005556 |
def set_status(self, value):
"""
Set the status of the motor to the specified value if not already set.
"""
if not self._status == value:
old = self._status
self._status = value
logger.info("{} changing status from {} to {}".format(self, old.name, valu... | 0.008065 |
def create(self):
"""
Creates a new record for a domain.
Args:
type (str): The type of the DNS record (e.g. A, CNAME, TXT).
name (str): The host name, alias, or service being defined by the
record.
data (int): Variable data depending on record... | 0.002266 |
def filter_from_options(key, options):
"""
:param key: Key str in options
:param options: Mapping object
:return:
New mapping object from 'options' in which the item with 'key' filtered
>>> filter_from_options('a', dict(a=1, b=2))
{'b': 2}
"""
return anyconfig.utils.filter_optio... | 0.00241 |
def managed(name, port, services=None, user=None, password=None, bypass_domains=None, network_service='Ethernet'):
'''
Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should us... | 0.00416 |
def _trade(self, event):
"内部函数"
print('==================================market enging: trade')
print(self.order_handler.order_queue.pending)
print('==================================')
self.order_handler._trade()
print('done') | 0.007273 |
def _parse_request_method(request: web.Request):
"""Parse Access-Control-Request-Method header of the preflight request
"""
method = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_METHOD)
if method is None:
raise web.HTTPForbidden(
text="CORS preflight reques... | 0.00365 |
def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the conten... | 0.00289 |
def create_connection():
"""Sets up a redis configuration"""
global _cached_connection
settings = oz.settings
if settings["redis_cache_connections"] and _cached_connection != None:
return _cached_connection
else:
conn = redis.StrictRedis(
host=settings["redis_host"],
... | 0.00223 |
def clean_addresses(addresses):
"""
Cleans email address.
:param addresses: List of strings (email addresses)
:return: List of strings (cleaned email addresses)
"""
if addresses is None:
return []
addresses = addresses.replace("\'", "")
address_list = re.split('[,;]', addresses)
... | 0.002033 |
def get_acc_list(self):
"""
:return: (ret, data)
"""
query_processor = self._get_sync_query_processor(
GetAccountList.pack_req, GetAccountList.unpack_rsp)
kargs = {
'user_id': self.get_login_user_id(),
'conn_id': self.get_sync_conn_id()
... | 0.002137 |
def Y(self, value):
""" sets the Y coordinate """
if isinstance(value, (int, float,
long, types.NoneType)):
self._y = value | 0.01105 |
def output_thread(log, stdout, stderr, timeout_event, is_alive, quit,
stop_output_event):
""" this function is run in a separate thread. it reads from the
process's stdout stream (a streamreader), and waits for it to claim that
its done """
poller = Poller()
if stdout is not None:
... | 0.00227 |
def _check_fpos(self, fp_, fpos, offset, block):
"""Check file position matches blocksize"""
if (fp_.tell() + offset != fpos):
warnings.warn("Actual "+block+" header size does not match expected")
return | 0.012552 |
def resizeEvent(self, event):
"""Override from QAbstractScrollArea.
Resize the viewer widget when the viewport is resized."""
vp = self.viewport()
rect = vp.geometry()
x1, y1, x2, y2 = rect.getCoords()
width = x2 - x1 + 1
height = y2 - y1 + 1
self.v_w.res... | 0.005917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.