_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q232200 | PasteAsDialog.get_max_dim | train | def get_max_dim(self, obj):
"""Returns maximum dimensionality over which obj is iterable <= 2"""
try:
iter(obj)
except TypeError:
return 0
try:
for o in obj:
iter(o)
break
except TypeError:
return... | python | {
"resource": ""
} |
q232201 | DgraphClientStub.alter | train | def alter(self, operation, timeout=None, metadata=None, credentials=None):
"""Runs alter operation."""
return self.stub.Alter(operation, timeout=timeout, metadata=metadata,
credentials=credentials) | python | {
"resource": ""
} |
q232202 | DgraphClientStub.query | train | def query(self, req, timeout=None, metadata=None, credentials=None):
"""Runs query operation."""
return self.stub.Query(req, timeout=timeout, metadata=metadata,
credentials=credentials) | python | {
"resource": ""
} |
q232203 | DgraphClientStub.mutate | train | def mutate(self, mutation, timeout=None, metadata=None, credentials=None):
"""Runs mutate operation."""
return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata,
credentials=credentials) | python | {
"resource": ""
} |
q232204 | DgraphClientStub.commit_or_abort | train | def commit_or_abort(self, ctx, timeout=None, metadata=None,
credentials=None):
"""Runs commit or abort operation."""
return self.stub.CommitOrAbort(ctx, timeout=timeout, metadata=metadata,
credentials=credentials) | python | {
"resource": ""
} |
q232205 | DgraphClientStub.check_version | train | def check_version(self, check, timeout=None, metadata=None,
credentials=None):
"""Returns the version of the Dgraph instance."""
return self.stub.CheckVersion(check, timeout=timeout,
metadata=metadata,
cred... | python | {
"resource": ""
} |
q232206 | DgraphClient.alter | train | def alter(self, operation, timeout=None, metadata=None, credentials=None):
"""Runs a modification via this client."""
new_metadata = self.add_login_metadata(metadata)
try:
return self.any_client().alter(operation, timeout=timeout,
metadata=... | python | {
"resource": ""
} |
q232207 | DgraphClient.txn | train | def txn(self, read_only=False, best_effort=False):
"""Creates a transaction."""
return txn.Txn(self, read_only=read_only, best_effort=best_effort) | python | {
"resource": ""
} |
q232208 | Txn.query | train | def query(self, query, variables=None, timeout=None, metadata=None,
credentials=None):
"""Adds a query operation to the transaction."""
new_metadata = self._dg.add_login_metadata(metadata)
req = self._common_query(query, variables=variables)
try:
res = self._dc.... | python | {
"resource": ""
} |
q232209 | Txn.mutate | train | def mutate(self, mutation=None, set_obj=None, del_obj=None, set_nquads=None,
del_nquads=None, commit_now=None, ignore_index_conflict=None,
timeout=None, metadata=None, credentials=None):
"""Adds a mutate operation to the transaction."""
mutation = self._common_mutate(
... | python | {
"resource": ""
} |
q232210 | Txn.commit | train | def commit(self, timeout=None, metadata=None, credentials=None):
"""Commits the transaction."""
if not self._common_commit():
return
new_metadata = self._dg.add_login_metadata(metadata)
try:
self._dc.commit_or_abort(self._ctx, timeout=timeout,
... | python | {
"resource": ""
} |
q232211 | Txn.discard | train | def discard(self, timeout=None, metadata=None, credentials=None):
"""Discards the transaction."""
if not self._common_discard():
return
new_metadata = self._dg.add_login_metadata(metadata)
try:
self._dc.commit_or_abort(self._ctx, timeout=timeout,
... | python | {
"resource": ""
} |
q232212 | Txn.merge_context | train | def merge_context(self, src=None):
"""Merges context from this instance with src."""
if src is None:
# This condition will be true only if the server doesn't return a
# txn context after a query or mutation.
return
if self._ctx.start_ts == 0:
self... | python | {
"resource": ""
} |
q232213 | RandomStringTokenGenerator.generate_token | train | def generate_token(self, *args, **kwargs):
""" generates a pseudo random code using os.urandom and binascii.hexlify """
# determine the length based on min_length and max_length
length = random.randint(self.min_length, self.max_length)
# generate the token using os.urandom and hexlify
... | python | {
"resource": ""
} |
q232214 | HtmlEmitter.get_text | train | def get_text(self, node):
"""Try to emit whatever text is in the node."""
try:
return node.children[0].content or ""
except (AttributeError, IndexError):
return node.content or "" | python | {
"resource": ""
} |
q232215 | HtmlEmitter.emit_children | train | def emit_children(self, node):
"""Emit all the children of a node."""
return "".join([self.emit_node(child) for child in node.children]) | python | {
"resource": ""
} |
q232216 | HtmlEmitter.emit_node | train | def emit_node(self, node):
"""Emit a single node."""
emit = getattr(self, "%s_emit" % node.kind, self.default_emit)
return emit(node) | python | {
"resource": ""
} |
q232217 | ajax_preview | train | def ajax_preview(request, **kwargs):
"""
Currently only supports markdown
"""
data = {
"html": render_to_string("pinax/blog/_preview.html", {
"content": parse(request.POST.get("markup"))
})
}
return JsonResponse(data) | python | {
"resource": ""
} |
q232218 | Semaphore.set_system_lock | train | def set_system_lock(cls, redis, name, timeout):
"""
Set system lock for the semaphore.
Sets a system lock that will expire in timeout seconds. This
overrides all other locks. Existing locks cannot be renewed
and no new locks will be permitted until the system lock
expire... | python | {
"resource": ""
} |
q232219 | Semaphore.acquire | train | def acquire(self):
"""
Obtain a semaphore lock.
Returns: Tuple that contains True/False if the lock was acquired and number of
locks in semaphore.
"""
acquired, locks = self._semaphore(keys=[self.name],
args=[self.lock_... | python | {
"resource": ""
} |
q232220 | NewStyleLock.renew | train | def renew(self, new_timeout):
"""
Sets a new timeout for an already acquired lock.
``new_timeout`` can be specified as an integer or a float, both
representing the number of seconds.
"""
if self.local.token is None:
raise LockError("Cannot extend an unlocked ... | python | {
"resource": ""
} |
q232221 | TaskTiger.task | train | def task(self, _fn=None, queue=None, hard_timeout=None, unique=None,
lock=None, lock_key=None, retry=None, retry_on=None,
retry_method=None, schedule=None, batch=False,
max_queue_size=None):
"""
Function decorator that defines the behavior of the function when it i... | python | {
"resource": ""
} |
q232222 | TaskTiger.run_worker | train | def run_worker(self, queues=None, module=None, exclude_queues=None,
max_workers_per_queue=None, store_tracebacks=None):
"""
Main worker entry point method.
The arguments are explained in the module-level run_worker() method's
click options.
"""
try:
... | python | {
"resource": ""
} |
q232223 | TaskTiger.delay | train | def delay(self, func, args=None, kwargs=None, queue=None,
hard_timeout=None, unique=None, lock=None, lock_key=None,
when=None, retry=None, retry_on=None, retry_method=None,
max_queue_size=None):
"""
Queues a task. See README.rst for an explanation of the options... | python | {
"resource": ""
} |
q232224 | TaskTiger.get_queue_sizes | train | def get_queue_sizes(self, queue):
"""
Get the queue's number of tasks in each state.
Returns dict with queue size for the QUEUED, SCHEDULED, and ACTIVE
states. Does not include size of error queue.
"""
states = [QUEUED, SCHEDULED, ACTIVE]
pipeline = self.connect... | python | {
"resource": ""
} |
q232225 | TaskTiger.get_queue_system_lock | train | def get_queue_system_lock(self, queue):
"""
Get system lock timeout
Returns time system lock expires or None if lock does not exist
"""
key = self._key(LOCK_REDIS_KEY, queue)
return Semaphore.get_system_lock(self.connection, key) | python | {
"resource": ""
} |
q232226 | TaskTiger.set_queue_system_lock | train | def set_queue_system_lock(self, queue, timeout):
"""
Set system lock on a queue.
Max workers for this queue must be used for this to have any effect.
This will keep workers from processing tasks for this queue until
the timeout has expired. Active tasks will continue processing... | python | {
"resource": ""
} |
q232227 | Worker._install_signal_handlers | train | def _install_signal_handlers(self):
"""
Sets up signal handlers for safely stopping the worker.
"""
def request_stop(signum, frame):
self._stop_requested = True
self.log.info('stop requested, waiting for task to finish')
signal.signal(signal.SIGINT, reques... | python | {
"resource": ""
} |
q232228 | Worker._uninstall_signal_handlers | train | def _uninstall_signal_handlers(self):
"""
Restores default signal handlers.
"""
signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGTERM, signal.SIG_DFL) | python | {
"resource": ""
} |
q232229 | Worker._filter_queues | train | def _filter_queues(self, queues):
"""
Applies the queue filter to the given list of queues and returns the
queues that match. Note that a queue name matches any subqueues
starting with the name, followed by a date. For example, "foo" will
match both "foo" and "foo.bar".
"... | python | {
"resource": ""
} |
q232230 | Worker._worker_queue_scheduled_tasks | train | def _worker_queue_scheduled_tasks(self):
"""
Helper method that takes due tasks from the SCHEDULED queue and puts
them in the QUEUED queue for execution. This should be called
periodically.
"""
queues = set(self._filter_queues(self.connection.smembers(
sel... | python | {
"resource": ""
} |
q232231 | Worker._wait_for_new_tasks | train | def _wait_for_new_tasks(self, timeout=0, batch_timeout=0):
"""
Check activity channel and wait as necessary.
This method is also used to slow down the main processing loop to reduce
the effects of rapidly sending Redis commands. This method will exit
for any of these conditions... | python | {
"resource": ""
} |
q232232 | Worker._execute_forked | train | def _execute_forked(self, tasks, log):
"""
Executes the tasks in the forked process. Multiple tasks can be passed
for batch processing. However, they must all use the same function and
will share the execution entry.
"""
success = False
execution = {}
as... | python | {
"resource": ""
} |
q232233 | Worker._get_queue_batch_size | train | def _get_queue_batch_size(self, queue):
"""Get queue batch size."""
# Fetch one item unless this is a batch queue.
# XXX: It would be more efficient to loop in reverse order and break.
batch_queues = self.config['BATCH_QUEUES']
batch_size = 1
for part in dotted_parts(que... | python | {
"resource": ""
} |
q232234 | Worker._get_queue_lock | train | def _get_queue_lock(self, queue, log):
"""Get queue lock for max worker queues.
For max worker queues it returns a Lock if acquired and whether
it failed to acquire the lock.
"""
max_workers = self.max_workers_per_queue
# Check if this is single worker queue
for... | python | {
"resource": ""
} |
q232235 | Worker._heartbeat | train | def _heartbeat(self, queue, task_ids):
"""
Updates the heartbeat for the given task IDs to prevent them from
timing out and being requeued.
"""
now = time.time()
self.connection.zadd(self._key(ACTIVE, queue),
**{task_id: now for task_id in tas... | python | {
"resource": ""
} |
q232236 | Worker._execute | train | def _execute(self, queue, tasks, log, locks, queue_lock, all_task_ids):
"""
Executes the given tasks. Returns a boolean indicating whether
the tasks were executed successfully.
"""
# The tasks must use the same function.
assert len(tasks)
task_func = tasks[0].ser... | python | {
"resource": ""
} |
q232237 | Worker._process_queue_message | train | def _process_queue_message(self, message_queue, new_queue_found, batch_exit,
start_time, timeout, batch_timeout):
"""Process a queue message from activity channel."""
for queue in self._filter_queues([message_queue]):
if queue not in self._queue_set:
... | python | {
"resource": ""
} |
q232238 | Worker._process_queue_tasks | train | def _process_queue_tasks(self, queue, queue_lock, task_ids, now, log):
"""Process tasks in queue."""
processed_count = 0
# Get all tasks
serialized_tasks = self.connection.mget([
self._key('task', task_id) for task_id in task_ids
])
# Parse tasks
ta... | python | {
"resource": ""
} |
q232239 | Worker._process_from_queue | train | def _process_from_queue(self, queue):
"""
Internal method to process a task batch from the given queue.
Args:
queue: Queue name to be processed
Returns:
Task IDs: List of tasks that were processed (even if there was an
error so that cli... | python | {
"resource": ""
} |
q232240 | Worker._execute_task_group | train | def _execute_task_group(self, queue, tasks, all_task_ids, queue_lock):
"""
Executes the given tasks in the queue. Updates the heartbeat for task
IDs passed in all_task_ids. This internal method is only meant to be
called from within _process_from_queue.
"""
log = self.log... | python | {
"resource": ""
} |
q232241 | Worker._finish_task_processing | train | def _finish_task_processing(self, queue, task, success):
"""
After a task is executed, this method is called and ensures that
the task gets properly removed from the ACTIVE queue and, in case of an
error, retried or marked as failed.
"""
log = self.log.bind(queue=queue, t... | python | {
"resource": ""
} |
q232242 | Worker.run | train | def run(self, once=False, force_once=False):
"""
Main loop of the worker.
Use once=True to execute any queued tasks and then exit.
Use force_once=True with once=True to always exit after one processing
loop even if tasks remain queued.
"""
self.log.info('ready',... | python | {
"resource": ""
} |
q232243 | RedisScripts.can_replicate_commands | train | def can_replicate_commands(self):
"""
Whether Redis supports single command replication.
"""
if not hasattr(self, '_can_replicate_commands'):
info = self.redis.info('server')
version_info = info['redis_version'].split('.')
major, minor = int(version_in... | python | {
"resource": ""
} |
q232244 | RedisScripts.zpoppush | train | def zpoppush(self, source, destination, count, score, new_score,
client=None, withscores=False, on_success=None,
if_exists=None):
"""
Pops the first ``count`` members from the ZSET ``source`` and adds them
to the ZSET ``destination`` with a score of ``new_score`... | python | {
"resource": ""
} |
q232245 | RedisScripts.execute_pipeline | train | def execute_pipeline(self, pipeline, client=None):
"""
Executes the given Redis pipeline as a Lua script. When an error
occurs, the transaction stops executing, and an exception is raised.
This differs from Redis transactions, where execution continues after an
error. On success,... | python | {
"resource": ""
} |
q232246 | gen_unique_id | train | def gen_unique_id(serialized_name, args, kwargs):
"""
Generates and returns a hex-encoded 256-bit ID for the given task name and
args. Used to generate IDs for unique tasks or for task locks.
"""
return hashlib.sha256(json.dumps({
'func': serialized_name,
'args': args,
'kwarg... | python | {
"resource": ""
} |
q232247 | serialize_func_name | train | def serialize_func_name(func):
"""
Returns the dotted serialized path to the passed function.
"""
if func.__module__ == '__main__':
raise ValueError('Functions from the __main__ module cannot be '
'processed by workers.')
try:
# This will only work on Python ... | python | {
"resource": ""
} |
q232248 | dotted_parts | train | def dotted_parts(s):
"""
For a string "a.b.c", yields "a", "a.b", "a.b.c".
"""
idx = -1
while s:
idx = s.find('.', idx+1)
if idx == -1:
yield s
break
yield s[:idx] | python | {
"resource": ""
} |
q232249 | reversed_dotted_parts | train | def reversed_dotted_parts(s):
"""
For a string "a.b.c", yields "a.b.c", "a.b", "a".
"""
idx = -1
if s:
yield s
while s:
idx = s.rfind('.', 0, idx)
if idx == -1:
break
yield s[:idx] | python | {
"resource": ""
} |
q232250 | tasktiger_processor | train | def tasktiger_processor(logger, method_name, event_dict):
"""
TaskTiger structlog processor.
Inject the current task id for non-batch tasks.
"""
if g['current_tasks'] is not None and not g['current_task_is_batch']:
event_dict['task_id'] = g['current_tasks'][0].id
return event_dict | python | {
"resource": ""
} |
q232251 | Task.should_retry_on | train | def should_retry_on(self, exception_class, logger=None):
"""
Whether this task should be retried when the given exception occurs.
"""
for n in (self.retry_on or []):
try:
if issubclass(exception_class, import_attribute(n)):
return True
... | python | {
"resource": ""
} |
q232252 | Task.update_scheduled_time | train | def update_scheduled_time(self, when):
"""
Updates a scheduled task's date to the given date. If the task is not
scheduled, a TaskNotFound exception is raised.
"""
tiger = self.tiger
ts = get_timestamp(when)
assert ts
pipeline = tiger.connection.pipeline... | python | {
"resource": ""
} |
q232253 | Task.n_executions | train | def n_executions(self):
"""
Queries and returns the number of past task executions.
"""
pipeline = self.tiger.connection.pipeline()
pipeline.exists(self.tiger._key('task', self.id))
pipeline.llen(self.tiger._key('task', self.id, 'executions'))
exists, n_executions... | python | {
"resource": ""
} |
q232254 | Noise.set_input | train | def set_input(self, nr=2, qd=1, b=0):
""" Set inputs after initialization
Parameters
-------
nr: integer
length of generated time-series
number must be power of two
qd: float
discrete variance
b: float
noise type:
... | python | {
"resource": ""
} |
q232255 | Noise.generateNoise | train | def generateNoise(self):
""" Generate noise time series based on input parameters
Returns
-------
time_series: np.array
Time series with colored noise.
len(time_series) == nr
"""
# Fill wfb array with white noise based on given discrete variance
... | python | {
"resource": ""
} |
q232256 | Noise.adev | train | def adev(self, tau0, tau):
""" return predicted ADEV of noise-type at given tau
"""
prefactor = self.adev_from_qd(tau0=tau0, tau=tau)
c = self.c_avar()
avar = pow(prefactor, 2)*pow(tau, c)
return np.sqrt(avar) | python | {
"resource": ""
} |
q232257 | Noise.mdev | train | def mdev(self, tau0, tau):
""" return predicted MDEV of noise-type at given tau
"""
prefactor = self.mdev_from_qd(tau0=tau0, tau=tau)
c = self.c_mvar()
mvar = pow(prefactor, 2)*pow(tau, c)
return np.sqrt(mvar) | python | {
"resource": ""
} |
q232258 | scipy_psd | train | def scipy_psd(x, f_sample=1.0, nr_segments=4):
""" PSD routine from scipy
we can compare our own numpy result against this one
"""
f_axis, psd_of_x = scipy.signal.welch(x, f_sample, nperseg=len(x)/nr_segments)
return f_axis, psd_of_x | python | {
"resource": ""
} |
q232259 | iterpink | train | def iterpink(depth=20):
"""Generate a sequence of samples of pink noise.
pink noise generator
from http://pydoc.net/Python/lmj.sound/0.1.1/lmj.sound.noise/
Based on the Voss-McCartney algorithm, discussion and code examples at
http://www.firstpr.com.au/dsp/pink-noise/
depth: Use this many sam... | python | {
"resource": ""
} |
q232260 | plotline | train | def plotline(plt, alpha, taus, style,label=""):
""" plot a line with the slope alpha """
y = [pow(tt, alpha) for tt in taus]
plt.loglog(taus, y, style,label=label) | python | {
"resource": ""
} |
q232261 | b1_noise_id | train | def b1_noise_id(x, af, rate):
""" B1 ratio for noise identification
ratio of Standard Variace to AVAR
"""
(taus,devs,errs,ns) = at.adev(x,taus=[af*rate],data_type="phase", rate=rate)
oadev_x = devs[0]
y = np.diff(x)
y_cut = np.array( y[:len(y)-(len(y)%af)] ) # cut to length
ass... | python | {
"resource": ""
} |
q232262 | Plot.plot | train | def plot(self, atDataset,
errorbars=False,
grid=False):
""" use matplotlib methods for plotting
Parameters
----------
atDataset : allantools.Dataset()
a dataset with computed data
errorbars : boolean
Plot errorbars. Defaults to F... | python | {
"resource": ""
} |
q232263 | greenhall_table2 | train | def greenhall_table2(alpha, d):
""" Table 2 from Greenhall 2004 """
row_idx = int(-alpha+2) # map 2-> row0 and -4-> row6
assert(row_idx in [0, 1, 2, 3, 4, 5])
col_idx = int(d-1)
table2 = [[(3.0/2.0, 1.0/2.0), (35.0/18.0, 1.0), (231.0/100.0, 3.0/2.0)], # alpha=+2
[(78.6, 25.2), (790.0, ... | python | {
"resource": ""
} |
q232264 | greenhall_table1 | train | def greenhall_table1(alpha, d):
""" Table 1 from Greenhall 2004 """
row_idx = int(-alpha+2) # map 2-> row0 and -4-> row6
col_idx = int(d-1)
table1 = [[(2.0/3.0, 1.0/3.0), (7.0/9.0, 1.0/2.0), (22.0/25.0, 2.0/3.0)], # alpha=+2
[(0.840, 0.345), (0.997, 0.616), (1.141, 0.843)],
[... | python | {
"resource": ""
} |
q232265 | edf_mtotdev | train | def edf_mtotdev(N, m, alpha):
""" Equivalent degrees of freedom for Modified Total Deviation
NIST SP1065 page 41, Table 8
"""
assert(alpha in [2, 1, 0, -1, -2])
NIST_SP1065_table8 = [(1.90, 2.1), (1.20, 1.40), (1.10, 1.2), (0.85, 0.50), (0.75, 0.31)]
#(b, c) = NIST_SP1065_table8[ abs(al... | python | {
"resource": ""
} |
q232266 | edf_simple | train | def edf_simple(N, m, alpha):
"""Equivalent degrees of freedom.
Simple approximate formulae.
Parameters
----------
N : int
the number of phase samples
m : int
averaging factor, tau = m * tau0
alpha: int
exponent of f for the frequency PSD:
'wp' returns white p... | python | {
"resource": ""
} |
q232267 | example1 | train | def example1():
"""
Compute the GRADEV of a white phase noise. Compares two different
scenarios. 1) The original data and 2) ADEV estimate with gap robust ADEV.
"""
N = 1000
f = 1
y = np.random.randn(1,N)[0,:]
x = [xx for xx in np.linspace(1,len(y),len(y))]
x_ax, y_ax, (err_l, err_h... | python | {
"resource": ""
} |
q232268 | example2 | train | def example2():
"""
Compute the GRADEV of a nonstationary white phase noise.
"""
N=1000 # number of samples
f = 1 # data samples per second
s=1+5/N*np.arange(0,N)
y=s*np.random.randn(1,N)[0,:]
x = [xx for xx in np.linspace(1,len(y),len(y))]
x_ax, y_ax, (err_l, err_h) , ns = allan.gra... | python | {
"resource": ""
} |
q232269 | tdev | train | def tdev(data, rate=1.0, data_type="phase", taus=None):
""" Time deviation.
Based on modified Allan variance.
.. math::
\\sigma^2_{TDEV}( \\tau ) = { \\tau^2 \\over 3 }
\\sigma^2_{MDEV}( \\tau )
Note that TDEV has a unit of seconds.
Parameters
----------
data: np.arra... | python | {
"resource": ""
} |
q232270 | mdev | train | def mdev(data, rate=1.0, data_type="phase", taus=None):
""" Modified Allan deviation.
Used to distinguish between White and Flicker Phase Modulation.
.. math::
\\sigma^2_{MDEV}(m\\tau_0) = { 1 \\over 2 (m \\tau_0 )^2 (N-3m+1) }
\\sum_{j=1}^{N-3m+1} \\lbrace
\\sum_{i=j}^{j+m-1... | python | {
"resource": ""
} |
q232271 | adev | train | def adev(data, rate=1.0, data_type="phase", taus=None):
""" Allan deviation.
Classic - use only if required - relatively poor confidence.
.. math::
\\sigma^2_{ADEV}(\\tau) = { 1 \\over 2 \\tau^2 }
\\langle ( {x}_{n+2} - 2x_{n+1} + x_{n} )^2 \\rangle
= { 1 \\over 2 (N-2) \\tau^2... | python | {
"resource": ""
} |
q232272 | ohdev | train | def ohdev(data, rate=1.0, data_type="phase", taus=None):
""" Overlapping Hadamard deviation.
Better confidence than normal Hadamard.
.. math::
\\sigma^2_{OHDEV}(m\\tau_0) = { 1 \\over 6 (m \\tau_0 )^2 (N-3m) }
\\sum_{i=1}^{N-3m} ( {x}_{i+3m} - 3x_{i+2m} + 3x_{i+m} - x_{i} )^2
wher... | python | {
"resource": ""
} |
q232273 | calc_hdev_phase | train | def calc_hdev_phase(phase, rate, mj, stride):
""" main calculation fungtion for HDEV and OHDEV
Parameters
----------
phase: np.array
Phase data in seconds.
rate: float
The sampling rate for phase or frequency, in Hz
mj: int
M index value for stride
stride: int
... | python | {
"resource": ""
} |
q232274 | totdev | train | def totdev(data, rate=1.0, data_type="phase", taus=None):
""" Total deviation.
Better confidence at long averages for Allan.
.. math::
\\sigma^2_{TOTDEV}( m\\tau_0 ) = { 1 \\over 2 (m\\tau_0)^2 (N-2) }
\\sum_{i=2}^{N-1} ( {x}^*_{i-m} - 2x^*_{i} + x^*_{i+m} )^2
Where :math:`x^... | python | {
"resource": ""
} |
q232275 | mtotdev | train | def mtotdev(data, rate=1.0, data_type="phase", taus=None):
""" PRELIMINARY - REQUIRES FURTHER TESTING.
Modified Total deviation.
Better confidence at long averages for modified Allan
FIXME: bias-correction http://www.wriley.com/CI2.pdf page 6
The variance is scaled up (divided by t... | python | {
"resource": ""
} |
q232276 | htotdev | train | def htotdev(data, rate=1.0, data_type="phase", taus=None):
""" PRELIMINARY - REQUIRES FURTHER TESTING.
Hadamard Total deviation.
Better confidence at long averages for Hadamard deviation
FIXME: bias corrections from http://www.wriley.com/CI2.pdf
W FM 0.995 alpha= 0
F... | python | {
"resource": ""
} |
q232277 | theo1 | train | def theo1(data, rate=1.0, data_type="phase", taus=None):
""" PRELIMINARY - REQUIRES FURTHER TESTING.
Theo1 is a two-sample variance with improved confidence and
extended averaging factor range.
.. math::
\\sigma^2_{THEO1}(m\\tau_0) = { 1 \\over (m \\tau_0 )^2 (N-m) }
... | python | {
"resource": ""
} |
q232278 | tierms | train | def tierms(data, rate=1.0, data_type="phase", taus=None):
""" Time Interval Error RMS.
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional).
rate: float
The sampling rate for data, in Hz. Defaults to 1.0
data_type:... | python | {
"resource": ""
} |
q232279 | mtie | train | def mtie(data, rate=1.0, data_type="phase", taus=None):
""" Maximum Time Interval Error.
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional).
rate: float
The sampling rate for data, in Hz. Defaults to 1.0
data_typ... | python | {
"resource": ""
} |
q232280 | mtie_phase_fast | train | def mtie_phase_fast(phase, rate=1.0, data_type="phase", taus=None):
""" fast binary decomposition algorithm for MTIE
See: STEFANO BREGNI "Fast Algorithms for TVAR and MTIE Computation in
Characterization of Network Synchronization Performance"
"""
rate = float(rate)
phase = np.asarray(p... | python | {
"resource": ""
} |
q232281 | gradev | train | def gradev(data, rate=1.0, data_type="phase", taus=None,
ci=0.9, noisetype='wp'):
""" gap resistant overlapping Allan deviation
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional). Warning : phase data works better (fr... | python | {
"resource": ""
} |
q232282 | input_to_phase | train | def input_to_phase(data, rate, data_type):
""" Take either phase or frequency as input and return phase
"""
if data_type == "phase":
return data
elif data_type == "freq":
return frequency2phase(data, rate)
else:
raise Exception("unknown data_type: " + data_type) | python | {
"resource": ""
} |
q232283 | trim_data | train | def trim_data(x):
"""
Trim leading and trailing NaNs from dataset
This is done by browsing the array from each end and store the index of the
first non-NaN in each case, the return the appropriate slice of the array
"""
# Find indices for first and last valid data
first = 0
while np.isna... | python | {
"resource": ""
} |
q232284 | three_cornered_hat_phase | train | def three_cornered_hat_phase(phasedata_ab, phasedata_bc,
phasedata_ca, rate, taus, function):
"""
Three Cornered Hat Method
Given three clocks A, B, C, we seek to find their variances
:math:`\\sigma^2_A`, :math:`\\sigma^2_B`, :math:`\\sigma^2_C`.
We measure three phase ... | python | {
"resource": ""
} |
q232285 | frequency2phase | train | def frequency2phase(freqdata, rate):
""" integrate fractional frequency data and output phase data
Parameters
----------
freqdata: np.array
Data array of fractional frequency measurements (nondimensional)
rate: float
The sampling rate for phase or frequency, in Hz
Returns
-... | python | {
"resource": ""
} |
q232286 | phase2radians | train | def phase2radians(phasedata, v0):
""" Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians
"""
fi = [2... | python | {
"resource": ""
} |
q232287 | frequency2fractional | train | def frequency2fractional(frequency, mean_frequency=-1):
""" Convert frequency in Hz to fractional frequency
Parameters
----------
frequency: np.array
Data array of frequency in Hz
mean_frequency: float
(optional) The nominal mean frequency, in Hz
if omitted, defaults to mean... | python | {
"resource": ""
} |
q232288 | Dataset.set_input | train | def set_input(self, data,
rate=1.0, data_type="phase", taus=None):
""" Optionnal method if you chose not to set inputs on init
Parameters
----------
data: np.array
Input data. Provide either phase or frequency (fractional,
adimensional)
... | python | {
"resource": ""
} |
q232289 | Dataset.compute | train | def compute(self, function):
"""Evaluate the passed function with the supplied data.
Stores result in self.out.
Parameters
----------
function: str
Name of the :mod:`allantools` function to evaluate
Returns
-------
result: dict
T... | python | {
"resource": ""
} |
q232290 | many_psds | train | def many_psds(k=2,fs=1.0, b0=1.0, N=1024):
""" compute average of many PSDs """
psd=[]
for j in range(k):
print j
x = noise.white(N=2*4096,b0=b0,fs=fs)
f, tmp = noise.numpy_psd(x,fs)
if j==0:
psd = tmp
else:
psd = psd + tmp
return f, psd/k | python | {
"resource": ""
} |
q232291 | OrganizationCommand.list_my | train | def list_my(self):
""" Find organization that has the current identity as the owner or as the member """
org_list = self.call_contract_command("Registry", "listOrganizations", [])
rez_owner = []
rez_member = []
for idx, org_id in enumerate(org_list):
(found, org_id,... | python | {
"resource": ""
} |
q232292 | MPEServiceMetadata.add_group | train | def add_group(self, group_name, payment_address):
""" Return new group_id in base64 """
if (self.is_group_name_exists(group_name)):
raise Exception("the group \"%s\" is already present"%str(group_name))
group_id_base64 = base64.b64encode(secrets.token_bytes(32))
self.m["group... | python | {
"resource": ""
} |
q232293 | MPEServiceMetadata.is_group_name_exists | train | def is_group_name_exists(self, group_name):
""" check if group with given name is already exists """
groups = self.m["groups"]
for g in groups:
if (g["group_name"] == group_name):
return True
return False | python | {
"resource": ""
} |
q232294 | MPEServiceMetadata.get_group_name_nonetrick | train | def get_group_name_nonetrick(self, group_name = None):
""" In all getter function in case of single payment group, group_name can be None """
groups = self.m["groups"]
if (len(groups) == 0):
raise Exception("Cannot find any groups in metadata")
if (not group_name):
... | python | {
"resource": ""
} |
q232295 | get_from_ipfs_and_checkhash | train | def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True):
"""
Get file from ipfs
We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise
"""
if validate:
from snet_cli.resources.proto.unixfs_pb2 import Data
from snet_cli.resources... | python | {
"resource": ""
} |
q232296 | hash_to_bytesuri | train | def hash_to_bytesuri(s):
"""
Convert in and from bytes uri format used in Registry contract
"""
# TODO: we should pad string with zeros till closest 32 bytes word because of a bug in processReceipt (in snet_cli.contract.process_receipt)
s = "ipfs://" + s
return s.encode("ascii").ljust(32 * (len(... | python | {
"resource": ""
} |
q232297 | MPETreasurerCommand._get_stub_and_request_classes | train | def _get_stub_and_request_classes(self, service_name):
""" import protobuf and return stub and request class """
# Compile protobuf if needed
codegen_dir = Path.home().joinpath(".snet", "mpe_client", "control_service")
proto_dir = Path(__file__).absolute().parent.joinpath("resources", ... | python | {
"resource": ""
} |
q232298 | MPETreasurerCommand._start_claim_channels | train | def _start_claim_channels(self, grpc_channel, channels_ids):
""" Safely run StartClaim for given channels """
unclaimed_payments = self._call_GetListUnclaimed(grpc_channel)
unclaimed_payments_dict = {p["channel_id"] : p for p in unclaimed_payments}
to_claim = []
for channel_id i... | python | {
"resource": ""
} |
q232299 | MPETreasurerCommand._claim_in_progress_and_claim_channels | train | def _claim_in_progress_and_claim_channels(self, grpc_channel, channels):
""" Claim all 'pending' payments in progress and after we claim given channels """
# first we get the list of all 'payments in progress' in case we 'lost' some payments.
payments = self._call_GetListInProgress(grpc_channel)... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.