text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def ChiSquared(target_frequency):
"""Score a text by comparing its frequency distribution against another.
Note:
It is easy to be penalised without knowing it when using this scorer.
English frequency ngrams are capital letters, meaning when using it
any text you score against must be a... | 0.004283 |
def _unwrap_to_layer(r, L, n=1):
"""For a set of points in a 2 dimensional periodic system, extend the set of
points to tile the points up to to a given period.
Parameters
----------
r: float array, shape (:, 2).
Set of points.
L: float array, shape (2,)
System lengths.
n: i... | 0.003185 |
def remove(self):
"""Remove duplicate lines from text files"""
num, sp, newfile = 0, "", []
if os.path.isfile(self.filename):
with open(self.filename, "r") as r:
oldfile = r.read().splitlines()
for line in oldfile:
if self.number:
... | 0.001657 |
def rpc_fix_code(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code(source, directory) | 0.009901 |
def _register_name(self, name):
"""Get register name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name) | 0.010929 |
def buildlist(self, enabled):
"""Run dialog buildlist
"""
choice = []
for item in self.data:
choice.append((item, False))
for item in enabled:
choice.append((item, True))
items = [(tag, tag, sta) for (tag, sta) in choice]
code, self.tags = ... | 0.003328 |
async def set_room_temperatures(self, room_id, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps."""
if sleep_temp is None and comfort_temp is None and away_temp is None:
return
room = self.rooms.get(room_id)
if room is... | 0.003236 |
def load(self):
""" Function load
Get the list of all objects
@return RETURN: A ForemanItem list
"""
return {x[self.index]: self.itemType(self.api, x['id'],
self.objName, self.payloadObj,
x... | 0.004566 |
def run(self, dag):
"""Expand 3+ qubit gates using their decomposition rules.
Args:
dag(DAGCircuit): input dag
Returns:
DAGCircuit: output dag with maximum node degrees of 2
Raises:
QiskitError: if a 3q+ gate is not decomposable
"""
fo... | 0.002573 |
def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0):
"""Patched 'getaddrinfo' with default family IPv4 (enabled by settings IPV4_ONLY=True)"""
return orig_getaddrinfo(host, port, family, socktype, proto, flags) | 0.011765 |
def run(self):
"""Run DDP greenlets."""
self.logger.debug('PostgresGreenlet run')
self.start()
self._stop_event.wait()
# wait for all threads to stop.
gevent.joinall(self.threads + [DDPLauncher.pgworker])
self.threads = [] | 0.007194 |
def score(self, data, data_ref, graph=None):
"""Compute the reconstruction loss over the test set.
Parameters
----------
data : array_like
Data to reconstruct.
data_ref : array_like
Reference data.
Returns
-------
float: Mean e... | 0.002618 |
def _signature_hash(self, tx_out_script, unsigned_txs_out_idx, hash_type):
"""
Return the canonical hash for a transaction. We need to
remove references to the signature, since it's a signature
of the hash before the signature is applied.
:param tx_out_script: the script the coi... | 0.003223 |
def processFolder(abfFolder):
"""call processAbf() for every ABF in a folder."""
if not type(abfFolder) is str or not len(abfFolder)>3:
return
files=sorted(glob.glob(abfFolder+"/*.abf"))
for i,fname in enumerate(files):
print("\n\n\n### PROCESSING {} of {}:".format(i,len(files)),os.path.... | 0.02005 |
def to_json(self):
"""Returns an input shard state for the remaining inputs.
Returns:
A JSON serializable version of the remaining input to read.
"""
params = dict(self.__params) # Shallow copy.
if self._PROTOTYPE_REQUEST_PARAM in params:
prototype_request = params[self._PROTOTYPE_REQ... | 0.007421 |
def frombinary(path, shape=None, dtype=None, ext='bin', start=None, stop=None, recursive=False, nplanes=None, npartitions=None, labels=None, conf='conf.json', order='C', engine=None, credentials=None):
"""
Load images from flat binary files.
Assumes one image per file, each with the shape and ordering as g... | 0.003352 |
def project_geometry(geometry, source, target):
"""Projects a shapely geometry object from the source to the target projection."""
project = partial(
pyproj.transform,
source,
target
)
return transform(project, geometry) | 0.007634 |
def update_all_apps(self):
"""
Loops through all app names contained in settings.INSTALLED_APPS and calls `update_app`
on each one. Handles any object deletions that happened after all apps have been initialized.
"""
for app in apps.get_app_configs():
self.update_app(... | 0.011091 |
def update_project(self, project_key, data, expand=None):
"""
Updates a project.
Update project: /rest/api/2/project/{projectIdOrKey}
:param project_key: project key of project that needs to be updated
:param data: dictionary containing the data to be updated
:param expa... | 0.006221 |
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
... | 0.00274 |
def check_file_encoding(self, input_file_path):
"""
Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking encoding of file '%s'", input_... | 0.002484 |
def prompt(self, prompt_msg=None, newline=False):
""" Writes prompt message to output stream and
reads line from standard input stream.
`prompt_msg`
Message to write.
`newline`
Append newline character to prompt message before writing.
... | 0.004049 |
def dynamics_from_bundle(b, times, compute=None, return_roche_euler=False, use_kepcart=False, **kwargs):
"""
Parse parameters in the bundle and call :func:`dynamics`.
See :func:`dynamics` for more detailed information.
NOTE: you must either provide compute (the label) OR all relevant options
as kw... | 0.005227 |
def page_for(self, member, page_size=DEFAULT_PAGE_SIZE):
'''
Determine the page where a member falls in the leaderboard.
@param member [String] Member name.
@param page_size [int] Page size to be used in determining page location.
@return the page where a member falls in the lea... | 0.007229 |
def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
"""
Plot a multidimensional dataset in 2D.
Each Series in the DataFrame is represented as a evenly distributed
slice on a circle. Each data point is rendered in the circle according to
the value on each Series. Highly corr... | 0.000217 |
def reset_index(
self, level=None, drop=False, inplace=False, col_level=0, col_fill=""
):
"""Reset this index to default and create column from current index.
Args:
level: Only remove the given levels from the index. Removes all
levels by default
... | 0.001959 |
def get_time_inqueue(self):
"""
:class:`timedelta` with the time spent in the Queue, None if the Task is not running
.. note:
This value is always greater than the real value computed by the resource manager
as we start to count only when check_status sets the `Task` st... | 0.01039 |
def manager(self, model):
'''Retrieve the :class:`Manager` for ``model`` which can be any of the
values valid for the :meth:`model` method.'''
try:
return self.router[model]
except KeyError:
meta = getattr(model, '_meta', model)
if meta.type == 'structu... | 0.00246 |
def _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None,
least_to_most=False):
"""Return words in `vocab` ordered by distinctiveness score."""
p_t = get_marginal_topic_distrib(doc_topic_distrib, doc_lengths)
distinct = get_wor... | 0.004535 |
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed."""
for cl in self.clients:
cl.close()
self.set_option('recent_notebooks', self.recent_notebooks)
return True | 0.007782 |
def update_brand(self) -> None:
"""Update brand group of parameters."""
self.update(path=URL_GET + GROUP.format(group=BRAND)) | 0.014184 |
def Receive(self, replytype, **kw):
'''Parse message, create Python object.
KeyWord data:
faults -- list of WSDL operation.fault typecodes
wsaction -- If using WS-Address, must specify Action value we expect to
receive.
'''
self.ReceiveSOAP(**k... | 0.006278 |
def copy( self ):
"""
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
... | 0.009242 |
def user(self, **params):
"""Stream user
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/user
"""
url = 'https://userstream.twitter.com/%s/user.json' \
% self.streamer.api_version
self.streamer._request(url, params=params) | 0.006579 |
def refreshUi( self ):
"""
Refreshes the interface based on the current settings.
"""
widget = self.uiContentsTAB.currentWidget()
is_content = isinstance(widget, QWebView)
if is_content:
self._currentContentsIndex = self.uiContentsTAB.currentInd... | 0.008893 |
def sparse_to_matrix(sparse):
"""
Take a sparse (n,3) list of integer indexes of filled cells,
turn it into a dense (m,o,p) matrix.
Parameters
-----------
sparse: (n,3) int, index of filled cells
Returns
------------
dense: (m,o,p) bool, matrix of filled cells
"""
sparse =... | 0.001372 |
def get_secchan_offs(type_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n927.
Positional arguments:
type_ -- corresponding `ieprinters` dictionary key for the instance.
data -- bytearray data to read.
"""
if data[0] < len(ht_secondary_offset):
... | 0.002392 |
def option_completer(cls, k,v):
"Tab completion hook for the %%opts cell magic."
line = v.text_until_cursor
completions = cls.setup_completer()
compositor_defs = {el.group:el.output_type.__name__
for el in Compositor.definitions if el.group}
return cls.... | 0.010811 |
def _fly(self, board, layers, things, the_plot):
"""Handles the behaviour of visible bolts flying toward the player."""
# Disappear if we've hit a bunker.
if self.character in the_plot['bunker_hitters']:
return self._teleport((-1, -1))
# End the game if we've hit the player.
if self.position =... | 0.007407 |
def upload_file(self, local_path, project_id, parent_data, existing_file_id=None, remote_filename=None):
"""
Upload a file under a specific location in DDSConnection possibly replacing an existing file.
:param local_path: str: path to a local file to upload
:param project_id: str: uuid o... | 0.007714 |
def add_ini_profile(self, cp, sec):
"""Add profile from configuration file.
Parameters
-----------
cp : ConfigParser object
The ConfigParser object holding the workflow configuration settings
sec : string
The section containing options for this job.
... | 0.002445 |
def get_extensions(cert_type):
'''
Fetch X509 and CSR extension definitions from tls:extensions:
(common|server|client) or set them to standard defaults.
.. versionadded:: 2015.8.0
cert_type:
The type of certificate such as ``server`` or ``client``.
CLI Example:
.. code-block:: b... | 0.000778 |
def plot_curvature(self, curv_type='mean', **kwargs):
"""
Plots the curvature of the external surface of the grid
Parameters
----------
curv_type : str, optional
One of the following strings indicating curvature types
- mean
- gaussian
... | 0.002717 |
def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):
"""
Get the summary of exceptions for component_name and list of instances.
Empty instance list will fetch all exceptions.
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
... | 0.006154 |
def _notify_add_at(self, index, length=1):
"""Notify about an AddChange at a caertain index and length."""
slice_ = self._slice_at(index, length)
self._notify_add(slice_) | 0.010309 |
def unpause_topic(self, topic):
"""Resume message flow to channels of an existing, paused, topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/unpause', fields={'topic': topic}) | 0.008658 |
def vcpu_pin(vm_, vcpu, cpus):
'''
Set which CPUs a VCPU can use.
CLI Example:
.. code-block:: bash
salt 'foo' virt.vcpu_pin domU-id 2 1
salt 'foo' virt.vcpu_pin domU-id 2 2-6
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if ... | 0.001114 |
def predict_maxprob(self, x, **kwargs):
"""
Most likely value. Generally equivalent to predict.
"""
return self.base_estimator_.predict(x.values, **kwargs) | 0.010695 |
def get_integrated_channels(self, options):
"""
Generates a list of active integrated channels for active customers, filtered from the given options.
Raises errors when invalid options are encountered.
See ``add_arguments`` for the accepted options.
"""
channel_classes ... | 0.005855 |
def acquisition_function(self,x):
"""
Takes an acquisition and weights it so the domain and cost are taken into account.
"""
f_acqu = self._compute_acq(x)
cost_x, _ = self.cost_withGradients(x)
return -(f_acqu*self.space.indicator_constraints(x))/cost_x | 0.013289 |
def parse_warc_record(self, record):
""" Parse warc record
"""
entry = self._create_index_entry(record.rec_type)
if record.rec_type == 'warcinfo':
entry['url'] = record.rec_headers.get_header('WARC-Filename')
entry['urlkey'] = entry['url']
entry['_wa... | 0.001007 |
def remove_entity(self, name):
"""Unload an entity"""
self.entities.remove(name)
self.padaos.remove_entity(name) | 0.014706 |
def title(s=None, additional='', stream=sys.stdout):
"""Utility function to display nice titles
It automatically extracts the name of the function/method it is called from
and you can add additional text. title() will then print the name
of the function/method and the additional text surrounded by tow lines
... | 0.005505 |
def plot_zeropoint(pars):
""" Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad
"""
from matplotlib import pyplot as plt
xp = pars['xp']
yp = pars['yp']
searchrad = int(pars['searchrad'] + 0.5)
plt.figure(num=pars['figu... | 0.000749 |
def clear_globals_reload_modules(self):
"""Clears globals and reloads modules"""
self.code_array.clear_globals()
self.code_array.reload_modules()
# Clear result cache
self.code_array.result_cache.clear() | 0.008163 |
def _connect(self):
"""
Connect to the MySQL server
"""
self._close()
self.conn = MySQLdb.Connect(host=self.hostname,
port=self.port,
user=self.username,
passwd=self.passwo... | 0.005305 |
def collapsedintervals(table, start='start', stop='stop', key=None):
"""
Utility function to collapse intervals in a table.
If no facet `key` is given, returns an iterator over `(start, stop)` tuples.
If facet `key` is given, returns an iterator over `(key, start, stop)`
tuples.
... | 0.010606 |
def crypto_aead_chacha20poly1305_ietf_encrypt(message, aad, nonce, key):
"""
Encrypt the given ``message`` using the IETF ratified chacha20poly1305
construction described in RFC7539.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
... | 0.000413 |
def chimera_anticluster(m, n=None, t=4, multiplier=3.0,
cls=BinaryQuadraticModel, subgraph=None, seed=None):
"""Generate an anticluster problem on a Chimera lattice.
An anticluster problem has weak interactions within a tile and strong
interactions between tiles.
Args:
... | 0.00157 |
def is_letter(char, strict=True):
"""
Check whether the character is a letter (as opposed to a diacritic or
suprasegmental).
In strict mode return True only if the letter is part of the IPA spec.
"""
if (char in chart.consonants) or (char in chart.vowels):
return True
if not strict:
return unicodedata.cate... | 0.029491 |
def create_transaction(self, to_account):
"""Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transacti... | 0.006459 |
def clear(self, correlation_id):
"""
Clears component state.
:param correlation_id: (optional) transaction id to trace execution through call chain.
"""
self._lock.acquire()
try:
self._cache = {}
finally:
self._lock.release() | 0.009804 |
def get_access_token(self) -> str:
"""
Returns the access token in case of successful authorization
"""
if self._service_token:
return self._service_token
if self._app_id and self._login and self._password:
try:
if self.login():
... | 0.003839 |
def get_by_type(
self, app_id, event_type, timespan=None, filter=None, search=None, orderby=None, select=None, skip=None, top=None, format=None, count=None, apply=None, custom_headers=None, raw=False, **operation_config):
"""Execute OData query.
Executes an OData query for events.
... | 0.002264 |
def easter(year=None):
"""
1900 - 2099 limit
:param year: int
:return: Easter day
"""
y = int(year) if year else _year
n = y - 1900
a = n % 19
q = n // 4
b = (7 * a + 1) // 19
m = (11 * a + 4 - b) % 29
w = (n + q + 31 - m) % 7
d = 25 - m - w
if d > 0:
retu... | 0.0025 |
async def StartUnitCompletion(self, entities, message):
'''
entities : typing.Sequence[~Entity]
message : str
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='UpgradeSeries',
req... | 0.00367 |
def resolve_pos(token):
"""If necessary, add a field to the POS tag for UD mapping.
Under Universal Dependencies, sometimes the same Unidic POS tag can
be mapped differently depending on the literal token or its context
in the sentence. This function adds information to the POS tag to
resolve ambigu... | 0.001289 |
def prepare_site_model(exposure_xml, sites_csv, vs30_csv,
z1pt0, z2pt5, vs30measured, grid_spacing=0,
assoc_distance=5, output='site_model.csv'):
"""
Prepare a site_model.csv file from exposure xml files/site csv files,
vs30 csv files and a grid spacing which ca... | 0.000249 |
def scratchpad():
"""Dummy page for styling tests."""
return render_template(
'demo.html',
config=dict(
project_name='Scratchpad',
style=request.args.get('style', 'default'),
),
title='Style Scratchpad',
) | 0.003663 |
def fmt_row(self, columns, dimensions, row, **settings):
"""
Format single table row.
"""
cells = []
i = 0
for column in columns:
cells.append(self.fmt_cell(
row[i],
dimensions[i],
column,
... | 0.008895 |
def frames(
self,
*,
callers: Optional[Union[str, List[str]]] = None,
callees: Optional[Union[str, List[str]]] = None,
kind: Optional[TraceKind] = None,
limit: Optional[int] = 10,
):
"""Display trace frames independent of the current issue.
Parameters... | 0.003171 |
def new_session(self, zipkin_trace_v2, v2_ui=False):
"""Creates a new SchedulerSession for this Scheduler."""
return SchedulerSession(self, self._native.new_session(
self._scheduler, zipkin_trace_v2, v2_ui, multiprocessing.cpu_count())
) | 0.003922 |
def get_archives(self, offset=None, count=None, session_id=None):
"""Returns an ArchiveList, which is an array of archives that are completed and in-progress,
for your API key.
:param int: offset Optional. The index offset of the first archive. 0 is offset
of the most recently started... | 0.005675 |
def create(name, url, backend, frequency=None, owner=None, org=None):
'''Create a new harvest source'''
log.info('Creating a new Harvest source "%s"', name)
source = actions.create_source(name, url, backend,
frequency=frequency,
owner=own... | 0.001634 |
def create_deamon(cmd, shell=False, root=False):
"""Usage:
Create servcice process.
"""
try:
if root:
cmd.insert(0, 'sudo')
LOG.info(cmd)
subproc = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE,
stderr=subprocess.PIPE... | 0.002439 |
def __parameter_descriptor(self, subfield_list):
"""Creates descriptor for a parameter using the subfields that define it.
Each parameter is defined by a list of fields, with all but the last being
a message field and the final being a simple (non-message) field.
Many of the fields in the descriptor a... | 0.005181 |
def read_bonedata(self, fid):
"""Read bone data from an acclaim skeleton file stream."""
bone_count = 0
lin = self.read_line(fid)
while lin[0]!=':':
parts = lin.split()
if parts[0] == 'begin':
bone_count += 1
self.vertices.append(v... | 0.009981 |
def load(args):
'''
%prog load gff_file fasta_file [--options]
Parses the selected features out of GFF, with subfeatures concatenated.
For example, to get the CDS sequences, do this:
$ %prog load athaliana.gff athaliana.fa --parents mRNA --children CDS
To get 500bp upstream of a genes Transcri... | 0.00798 |
def _encode(self, tokens: List[str], mean: bool) -> Union[List[np.ndarray], np.ndarray]:
"""
Embed one text sample
Args:
tokens: tokenized text sample
mean: whether to return mean embedding of tokens per sample
Returns:
list of embedded tokens or arr... | 0.002896 |
def _run(self, gates, n_qubits, args, kwargs):
"""Default implementation of `Backend.run`.
Backend developer shouldn't override this function, but override `run` instead of this.
The default flow of running is:
1. preprocessing
2. call the gate action which defined in ba... | 0.005102 |
def using_ios_stash():
''' returns true if sys path hints the install is running on ios '''
print('detected install path:')
print(os.path.dirname(__file__))
module_names = set(sys.modules.keys())
return 'stash' in module_names or 'stash.system' in module_names | 0.003571 |
def configfile_from_path(path, strict=True):
"""Get a ConfigFile object based on a file path.
This method will inspect the file extension and return the appropriate
ConfigFile subclass initialized with the given path.
Args:
path (str): The file path which represents the configuration file.
... | 0.00104 |
def parseExtn(extn=None):
"""
Parse a string representing a qualified fits extension name as in the
output of `parseFilename` and return a tuple ``(str(extname),
int(extver))``, which can be passed to `astropy.io.fits` functions using
the 'ext' kw.
Default return is the first extension in a fit... | 0.00246 |
def map(self, key_pattern, func, all_args, timeout=None):
'''Cache return value of multiple calls.
Args:
key_pattern (str): the key pattern to use for generating
keys for caches of the decorated function.
func (function): the function to call.
... | 0.00152 |
def atan(x, context=None):
"""
Return the inverse tangent of ``x``.
The mathematically exact result lies in the range [-π/2, π/2]. However,
note that as a result of rounding to the current context, it's possible
for the actual value to lie just outside this range.
"""
return _apply_functi... | 0.002227 |
def gen_password(password, crypt_salt=None, algorithm='sha512'):
'''
.. versionadded:: 2014.7.0
Generate hashed password
.. note::
When called this function is called directly via remote-execution,
the password argument may be displayed in the system's process list.
This may b... | 0.002449 |
def _get_user_provided_overrides(modules):
"""Load user-provided config overrides.
:param modules: stack modules to lookup in user overrides yaml file.
:returns: overrides dictionary.
"""
overrides = os.path.join(os.environ['JUJU_CHARM_DIR'],
'hardening.yaml')
if os... | 0.001153 |
def _update_system_file(system_file, name, new_kvs):
"""Update the bcbio_system.yaml file with new resource information.
"""
if os.path.exists(system_file):
bak_file = system_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
shutil.copyfile(system_file, bak_file)
... | 0.003135 |
def splitext_no_dot(filename):
"""
Wrap os.path.splitext to return the name and the extension
without the '.' (e.g., csv instead of .csv)
"""
name, ext = os.path.splitext(filename)
ext = ext.lower()
return name, ext.strip('.') | 0.003937 |
def _assign_database_backend(self, db):
"""Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databas... | 0.002105 |
def compare_SED(castroData1, castroData2, ylims, TS_thresh=4.0,
errSigma=1.0, specVals=[]):
""" Compare two SEDs
castroData1: A CastroData object, with the
log-likelihood v. normalization for each energy bin
castroData2: A CastroData object, with the
log... | 0.00339 |
def run_all(self, direction):
"""
Runs all registered migrations
:param direction: Can be on of two values, UP or DOWN
"""
for key in sorted(migration_registry.keys):
self.run(key, direction) | 0.008197 |
def clear_cache(ip=None):
"""Clear the client cache or remove key matching the given ip."""
if ip:
with ignored(Exception):
client = CLIENT_CACHE[ip]
del CLIENT_CACHE[ip]
client.close()
else:
for client in CLIENT_CACHE.values():
with ignored(Ex... | 0.002571 |
def epifreq(self,R):
"""
NAME:
epifreq
PURPOSE:
calculate the epicycle frequency at R in this potential
INPUT:
R - Galactocentric radius (can be Quantity)
OUTPUT:
e... | 0.036778 |
def preview(self, stream=sys.stdout):
"""A quick preview of docpie. Print all the parsed object"""
write = stream.write
write(('[Quick preview of Docpie %s]' % self._version).center(80, '='))
write('\n')
write(' sections '.center(80, '-'))
write('\n')
write(se... | 0.00112 |
def validate_request_timestamp(req_body, max_diff=150):
"""Ensure the request's timestamp doesn't fall outside of the
app's specified tolerance.
Returns True if this request is valid, False otherwise.
:param req_body: JSON object parsed out of the raw POST data of a request.
:param max_diff: Maxim... | 0.001126 |
async def _manage_connection(self):
"""Internal coroutine for managing the client connection."""
try:
while True:
message = await self._con.recv()
try:
unpacked = unpack(message)
except Exception: # pylint:disable=broad-e... | 0.006662 |
def _WriteIfcfg(self, interfaces, logger):
"""Write ifcfg files for multi-NIC support.
Overwrites the files. This allows us to update ifcfg-* in the future.
Disable the network setup to override this behavior and customize the
configurations.
Args:
interfaces: list of string, the output devi... | 0.00516 |
def clear(self, job_id=None, force=False):
"""
Clear the queue and the job data. If job_id is not given, clear out all
jobs marked COMPLETED. If job_id is given, clear out the given job's
data. This function won't do anything if the job's state is not COMPLETED or FAILED.
:type j... | 0.00523 |
def to_dict(self, omit=()):
"""
Return a (shallow) copy of self cast to a dictionary,
optionally omitting some key/value pairs.
"""
result = self.__dict__.copy()
for key in omit:
if key in result:
del result[key]
return result | 0.006452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.