content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def transform_stamped_to_pq(msg):
"""Convert a C{geometry_msgs/TransformStamped} into position/quaternion np arrays
@param msg: ROS message to be converted
@return:
- p: position as a np.array
- q: quaternion as a numpy array (order = [x,y,z,w])
"""
return transform_to_pq(msg.transform) | 345946e47993972dc11bd017b663f07bf874b238 | 3,626,100 |
def parse_args():
"""Parsing command line arguments. """
parser = ArgumentParser()
parser.add_argument('--postgres-pass', dest='postgres_pass', type=str,
help='PostgreSQL user password', default='')
parser.add_argument('--postgres-user', dest='postgres_user', type=str,
... | 4305830ffaecb546936b88e768dc79722cc6f054 | 3,626,101 |
def run(bsuite_id: Text) -> Text:
"""Runs a BDQN agent on a given bsuite environment, logging to CSV."""
env = bsuite.load_and_record(
bsuite_id=bsuite_id,
save_path=FLAGS.save_path,
logging_mode=FLAGS.logging_mode,
overwrite=FLAGS.overwrite,
)
num_features = 32 #fixed param now, TODO: ... | b4d94a44481818b1df229f35e200527b6bc38c23 | 3,626,102 |
from typing import OrderedDict
def recursive_module_dict(model: nn.Module) -> OrderedDict:
"""Recursively generates an OrderedDict representing the module structure in a nn.Module.
:param model: The (sub-)module for which to generate the structure
:type model: torch.nn.Module
:return: Structure of th... | 061f29b55582147d07822d64ef23ba1f5e519efa | 3,626,103 |
from cntk.ops.cntk1 import ReduceMin
def reduce_min(value, axis=0, name=None):
"""
For axis < rank computes the minimum of a tensor along the specifed axis. In the result the corresponding axis is dropped, i.e. the rank of the result tensore is smaller that the rank of the input tensor.
if axis==rank, the... | f25f106b4b9ae18e33ff580464ca782201ac6f28 | 3,626,104 |
def sparse_js_distance(p, q):
"""Compute the Jensen-Shannon distance between two discrete distributions.
NOTE: JS divergence is not a metric but the sqrt of JS divergence is a
metric and is called the JS distance.
Parameters
----------
p : np.array
probability mass array (sums to 1)
... | 7b05f567594a8cfcc3907006569fe73ede153343 | 3,626,105 |
def key_or_none(value):
"""
Attempts to parse a value into an instance of an `ndb.Key`.
:returns: None if value cannot be converted to an `ndb.Key`.
"""
if not value:
return None
if isinstance(value, str) and len(value) < 1:
return None
return ndb.Key(urlsafe=value) | 60480c7841cd87c762bb3debb0e212eb0011c0d3 | 3,626,106 |
def get_training_dataset(workspace, class_count, vocab, max_chapter_len=50, max_para_len=50):
"""
Get the GB h2 chapter training dataset.
:param workspace: The workspace directory where the TFRecords are kept.
:param class_count: The number of classes to be classified.
:param vocab: the set of vocab... | 14d135dde973f155ee0f5883297f5c2a376ba61a | 3,626,107 |
def get_https_host(request):
"""Common enabler code for returning https urls
This is to map links to HTTPS to avoid Mixed Content warnings from Chrome browsers
SECURE_PROXY_SSL_HEADER is referenced because it is used in redirecting URLs - if
it is changed it may affect this code.
Using relative lin... | f48445ae0fd12c81b175543c4445f11155302f75 | 3,626,108 |
from typing import Callable
def start(action: QueryAction) -> Callable:
"""Initialize the query for a given action, ensuring no action has started."""
def wrapper(fn):
def wrapped(self, *args, **kwargs):
if self._action != QueryAction.unset:
raise BuildError(f"query alread... | 2d9d2e92803405ae40758b1b1c28ac7275ff7b5b | 3,626,109 |
def xtea_decrypt_all(data, key, endian="!"):
"""Decrypt a entire string using XTEA block cypher"""
newdata = ''
data_s = len(data)
data_p = data_s%8
if data_p:
data_pl = 8-data_p
data+=(data_pl*chr(0))
data_s+=data_pl
for i in xrange(data_s/8):
block = data[i*8:(i*8)+8]
newdata+=xtea_decrypt(block, key,... | 19fdfb1bdca3033bf7dd6d7a84641a936d32b7aa | 3,626,110 |
import subprocess
import sys
def subprocess_call(args, cwd, capture_output=False, **kwargs):
"""Calls a subprocess, possibly capturing output."""
try:
if capture_output:
return subprocess.check_output(args, cwd=cwd, **kwargs)
else:
return subprocess.check_call(args, cwd=cwd, **kwargs)
except... | 956837dae6e7b74f1e51cd87e4c920bfe08eb2d0 | 3,626,111 |
def enthalpy_Shomate(T, hCP):
"""
enthalpy_Shomate(T, hCP)
NIST vapor, liquid, and solid phases
heat capacity correlation
H - H_ref (kJ/mol) = A*t + 1/2*B*t^2 + 1/3*C*t^3 +
1/4*D*t^4 - E*1/t + F - H
t (K) = T/1000.0
H_ref is enthalpy in kJ/mol at 298.15 K... | 05e3f3a35a87f767a44e2e1f4e35e768e12662f7 | 3,626,112 |
from typing import Union
from typing import List
import array
def hz_to_mel(frequencies: Union[float, List[float], array],
htk: bool = False) -> array:
"""Convert Hz to Mels
This function is aligned with librosa.
"""
freq = np.asanyarray(frequencies)
if htk:
return 2595.0 *... | 16373a9358e4bbae3baef02567c80abc4ba48c83 | 3,626,113 |
def _std_to_grib1_field_name(field_name, pressure_level_mb=None):
"""Converts field name from standard to grib1 format.
:param field_name: Field name in standard format (must be accepted by
`processed_narr_io.check_field_name`).
:param pressure_level_mb: Pressure level (millibars). For surface fie... | f5f63a61d81f919f814a7e85465afd42a10f6b19 | 3,626,114 |
import os
import json
def get_package_index(url, session=setup_session()):
"""Return the Elm package index and also store it in PACKAGE_ROOT."""
logger.info('Fetching package index...')
data = session.get(url).text
with open(os.path.join(PACKAGE_ROOT, 'all-packages'), 'w') as out:
out.write(da... | 1e025c629d0fbbda4bab1778fc2fb09922ae5e3b | 3,626,115 |
def get_acres(grid, coordinates):
"""Get acres from coordinates on grid."""
acres = []
for row, column in coordinates:
if 0 <= row < len(grid) and 0 <= column < len(grid[0]):
acres.append(grid[row][column])
return acres | e4ba6aabe07d8859481aefaba4d4559f1ec25e96 | 3,626,116 |
import os
import pathlib
def get_path_infos(path):
"""Get basic informations from a path"""
path = fspath(path)
path = os.path.abspath(path)
path = pathlib.PurePath(path)
return PathInfos(
path.drive,
str(path.parent),
path.name,
path.stem,
path.suffix,
... | 865b30a696dcae526594a51784dc1f859da4c441 | 3,626,117 |
def parse_noj():
"""
Parsing Nojabrsk (NOJ) airport arrivals and departure data
:return: list [list of dicts arrivals, list of dicts departures]
"""
print('parse_noj')
json_data = get_json(NOJ_URL).get('result').get('response').get('airport').get('pluginData').get('schedule')
arr_data = get... | 601ac9f1bc5d6f2fed4f08f8fb91e095bceadf7f | 3,626,118 |
def _filter_unlabeled_sentences(
characterwise_predicted_label_names_per_sentence, words_per_sentence,
unlabeled_sentence_filter):
"""Filters sentences without any predicted labels. Keeps every nth entry."""
sentences_without_label = 0
filtered_characterwise_predicted_label_names_per_sentenc... | a17a0dc3ba61ce542585cba31c87621f5a772e20 | 3,626,119 |
def highest_mag(slide):
"""Returns the highest magnification for the slide
"""
return int(slide.properties['aperio.AppMag']) | d42361c979a5addf0ebf4c7081a284c9bc0477ec | 3,626,120 |
def is_crud(crud):
"""Check if item is subclass of <GQL>"""
its_crud = False
try:
if not crud == GQL:
its_crud = issubclass(crud, GQL)
except TypeError:
pass
return its_crud | 2e817cdb0adaa880d7f027a4020ff490b76c5f56 | 3,626,121 |
from typing import Dict
def matrixProfile(ts: Matrix,
**kwargs: Dict[str, VALID_INPUT_TYPES]):
"""
Builtin function that computes the MatrixProfile of a time series efficiently
using the SCRIMP++ algorithm.
.. code-block:: txt
References:
Yan Zhu et al.. 20... | 860060b2dfde01b82e66754274a59616e8d45e40 | 3,626,122 |
import sys
def create_evaluations(model_or_ensemble_ids, datasets, evaluation_args,
args, api=None,
path=None, session_file=None, log=None,
existing_evaluations=0):
"""Create evaluations for a list of models
``model_or_ensemble_ids``: li... | 895968d1a39503c1d798e0be4258a709598fbe75 | 3,626,123 |
def pegar_por_href(navegador, link):
"""Encontrar o elemento `a` com o link `link`.
Argumentos:
- browser = Instancia do browser [firefox, chrome, ...]
- link = link (ou parte dele) que será procurado em toda as tags `a`
"""
elementos = chrome.find_elements_by_tag_name('a')
for e... | 8c3ea4ebc42b03d61c79f6a6666b82d41cb36902 | 3,626,124 |
def import_txt(file_name, two_dimensional=False, **kwargs):
""" Reads control points from a text file and generates a 1-dimensional list of control points.
The following code examples illustrate importing different types of text files for curves and surfaces:
.. code-block:: python
:linenos:
... | 5b17f8fe85de759ad240b36544b4c9231afdcda9 | 3,626,125 |
def sizeAbove(resource, value):
"""
Check if the contentSize attribute of the <contentInstance> resource is
equal to or greater than the specified value.
:param resource:
:type resource:
:param value:
:type value:
:return:
:rtype:
"""
try:
return resource.contentSize ... | 50e92811c9c8ee13db615137f6d92c4a3edabfda | 3,626,126 |
from typing import Dict
def decode_delegate_call_trace(trace: Dict[str, any], next_trace: Dict[str, any]) -> DecodedCallTrace:
"""
Takes a trace and decodes it. It needs next trace for return value
Structure for CALL and CALLCODE:
gas | addr | argsOffset | argsLength | retOffset | retLength
"""
... | a7292043934fb62323f617587b953277a64686d4 | 3,626,127 |
import re
def enumerate_destination_file_name(destination_file_name):
"""
Append a * to the end of the provided destination file name.
Only used when query output is too big and Google returns an error
requesting multiple file names.
"""
if re.search(r'\.', destination_file_name):
dest... | 6b398597db26a175e305446ac39c363a5077ba96 | 3,626,128 |
def Flux_Quad(wpert, thetapert):
"""
Separates fluxes into quadrants
Arguments:
wpert -- array of w perturbations
thetapert -- array of theta perturbations
Returns:
[up_warm, down_warm, up_cold, down_cold] -- arrays, np.nans are fillers
"""
[rows, columnsx, columnsy] = ... | d1f6a278deb60507cd05ed367b0c6dd13704ad28 | 3,626,129 |
def demistoVersion():
"""Retrieves server version and build number
Returns:
dict: Objects contains server version and build number
"""
return {
'version': '5.5.0',
'buildNumber': '12345'
} | 39ef34f88f44ecfad9d30a80bcdb74ad1833c3ae | 3,626,130 |
def classification_metric(all_real, all_pred, all_prob):
""" Metric used for experiments
Args:
all_real (list): real labels (ground truth) with n values
all_pred (list): predictions for n predictions
all_prob (list or np.array): probabilities (confidence).
If it is ... | 69f03e92c298e951b56ec32fd268fe859d66927e | 3,626,131 |
def camel_to_human(s, lower=True):
"""
Converts camel case to 'human' case
Arguments:
----------
lower: bool (default: False)
Convert output to lower
"""
ret = start_of_camel.sub(r" \1", s).strip()
if lower:
ret = ret.lower()
return ret | c00c21f469bca03af484a8d9ada86bfa3ed7e6b7 | 3,626,132 |
import random
def dice_game ():
"""
Function for manage all the game.
@rtype: None
@return: Return None when the game is ended
"""
scores = { TypeOfPlayers.PLAYER: 0, TypeOfPlayers.COMPUTER: 0 }
who_play = TypeOfPlayers.COMPUTER
while not game_is_ended(scores):
print('------------------... | d5940ac0d2c4aec3ba225b72e30de4da443080df | 3,626,133 |
import os
def create_work_name(name):
""" Remove ".nzb" and ".par(2)" """
strip_ext = ['.nzb', '.par', '.par2']
name = name.strip()
if name.find('://') < 0:
name_base, ext = os.path.splitext(name)
# In case it was one of these, there might be more
while ext.lower() in strip_ext... | 5e5405505a7c342ebb372ea53ad8330919b0979a | 3,626,134 |
def edit_affiliations(request, affiliation_formset):
"""
Edit affiliation information
Helper function for `project_authors`.
"""
if affiliation_formset.is_valid():
affiliation_formset.save()
messages.success(request, 'Your author affiliations have been updated')
return True
... | 04cfddd8be2299531d27baf8cb74c909ef40da19 | 3,626,135 |
import json
def tojson(x):
"""
python2/3 compatible conversion to json string
"""
return tobytes(json.dumps(x)) | 94ec37a5c5a22516369d69a4b60f63c4196cb329 | 3,626,136 |
def prob_remap_bcg(upid, host_halo_mass,
mhalo_table=(13.5, 13.75, 14, 15), prob_table=(0, 0.1, 0.5, 1)):
"""
"""
ngals = len(upid)
prob_remap = np.interp(np.log10(host_halo_mass), mhalo_table, prob_table)
uran = np.random.rand(ngals)
uran[upid != -1] = 1.0
return uran < prob_re... | 0e2c4bdd6f57e9f751b80a8ac366737d2756ae4c | 3,626,137 |
def rsf_score(year, flu_space, sections, section_neighbors, buildings,
access_variables):
"""
Scores/weights for single family development.
"""
# get projects
projs = flu_space.to_frame(['building_type', 'project_type',
'total_units', 'built_units', 'p... | 563ccfdafa86c4248558f66feab97edf8252a660 | 3,626,138 |
from typing import List
import requests
import json
def retrieve_all_plans() -> List[str]:
"""Return the names of all plans stored in the plan engine."""
url = _plan()
response = requests.get(url=url)
_raise_for_status(response)
plans: List[str] = json.loads(response.text)
return plans | e915cf64f5e17fca6ac0fcf17b3f2b68b2fb615a | 3,626,139 |
from typing import List
def load_task_names(path: str) -> List[str]:
"""
Loads the task names a model was trained with.
:param path: Path where model checkpoint is saved.
:return: A list of the task names that the model was trained with.
"""
return load_args(path).task_names | b9feb1e91d3449bbc98aa376a60ba40ac7d440b2 | 3,626,140 |
def sample_seq2seq(news_config: LMConfig, initial_context, eos_token, ignore_ids=None, p_for_topp=0.95,
do_topk=False, max_len=1025):
"""
Sample multiple outputs for a model in a seq2seq way.
:param news_config: Configuration used to construct the model
:param initial_context: [batch... | a9e5d3beb052acbb9cd8b753df5975ac319fac34 | 3,626,141 |
def unquote_plus(s):
"""unquote('%7e/abc+def') -> '~/abc def'"""
s = s.replace('+', ' ')
return unquote(s) | 2ffe054ae8fbec96d6435e242bf88ec7c871270e | 3,626,142 |
def _rankf(x):
""" Return an integer valuation of float32 x """
shift = int32(31)
mask = int32((1 << 31) - 1)
i32 = x.view(int32)
value = i32 >> shift
value &= mask
value ^= i32
return value | 841d49acd08b39dba716b6c41bdb3316208a9c43 | 3,626,143 |
import pip.utils.ui
import pip.utils.ui
import pip
import logging
import tempfile
import os
import shutil
def extract_package_to_dir(package_url):
"""
Extracts a pip package to a temporary directory.
:param package_url: the URL to the package source.
:return: the directory the package was extracted ... | ceb749532ccc200967cf5a9e5881e1e685c18901 | 3,626,144 |
from typing import List
def reorder_tables(openapi_yaml: sy.YAML) -> List[sy.Str]:
"""Orders the tables so no table references another table that might be defined after.
Parameters
----------
openapi_yaml
Contains the openapi format describing the database schema
Returns
-------
t... | a16f496effe1b52a685c8d82a7f85a3ecc6282e7 | 3,626,145 |
def video_feed():
"""
Video streaming route. Put this in the src attribute of an
img tag.
"""
txt = 'multipart/x-mixed-replace; boundary=frame'
# WS added passing a message to the Camera class
return Response(gen(Camera(message=msg)), mimetype=txt) | e5626cf86617beecd54afe173eb052629cd58179 | 3,626,146 |
def bias_act(x, b=None, dim=1, gain=None, clamp=None):
"""Slow reference implementation of `bias_act()`
"""
# spec = activation_funcs[act]
# alpha = float(alpha if alpha is not None else 0)
gain = float(gain if gain is not None else 1)
clamp = float(clamp if clamp is not None else -1)
# Add... | 3e98d5941d29c78ecd5c46c9ec960f14cedc36e9 | 3,626,147 |
import click
import io
import yaml
def init():
"""Return top level command handler."""
ctx = {}
@click.group()
@click.option('--cell', required=True,
envvar='TREADMILL_CELL',
callback=cli.handle_context_opt,
expose_value=False)
@click.option(... | b19e0b358f2b1288aeda6c963240de4f0369d187 | 3,626,148 |
def process_json_file(file_name, grounding_ns=None, extract_filter=None,
grounding_mode=default_grounding_mode):
"""Return an EidosProcessor by processing the given Eidos JSON-LD file.
This function is useful if the output from Eidos is saved as a file and
needs to be processed.
... | e8dedc0adad8e1e22199e6c6b83c3489f20c0570 | 3,626,149 |
def accumulate_ip_for_certificate(value):
"""
A convenience function that wraps the results of 'search_ip_for_certificate' into a Python list.
:param value: The certificate value for which to search
:return: The list of IP addresses
:raises LookupException: If there was an error performing the look... | 80664c1111bb113237247a7b35e4dafb60fdd4f5 | 3,626,150 |
def combine_envs(*envs):
"""Combine zero or more dictionaries containing environment variables.
Environment variables later from dictionaries later in the list take
priority over those earlier in the list. For variables ending with
``PATH``, we prepend (and add a colon) rather than overwriting.
If... | feb6e00b9c0b1262220339feac6c5ac2ae6b6b17 | 3,626,151 |
import logging
def get_request_data() -> dict:
"""
Get keys & values from request.
(Note that this method parse requests with
content type "application/x-www-form-urlencoded")
"""
data = dict(request.values)
logging.info(f"received request: {data}")
return data | 0f3b2a104d0282a6846031ed84e68af1e91071ac | 3,626,152 |
import torch
def generate_square_subsequent_mask(sz):
"""
Generate attention mask using triu (triangle) attention
"""
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = (
mask.float()
.masked_fill(mask == 0, float("-inf"))
.masked_fill(mask == 1, float(0.0)... | 5631e89a275eee13c4b01a7b856421f6b45c2588 | 3,626,153 |
def tree_graph(data, attrs=_attrs):
"""Return graph from tree data format.
Parameters
----------
data : dict
Tree formatted graph data
Returns
-------
G : NetworkX OrderedDiGraph
attrs : dict
A dictionary that contains two keys 'id' and 'children'. The
correspo... | 2cc012b7ffc32f1bd0ac5db0ac5bd912dec81c75 | 3,626,154 |
def retry_on_mysql_lock_fail(metric=None, metric_tags=None):
"""Function decorator to backoff and retry on MySQL lock failures.
This handles these MySQL errors:
* (1205) Lock wait timeout exceeded
* (1213) Deadlock when trying to get lock
In both cases, restarting the transaction may work.
It... | 91c2d82401677e6cdab1d4131a9f02be26cbbbf8 | 3,626,155 |
from datetime import datetime
def eot(date: datetime.date, offset: int = 0) -> datetime.date:
"""
Returns the end of the calendar trimester, i.e. one of
30 April, 31 August or 31 December, then optionally offsets it
by :code:`offset` trimesters
Parameters
----------
date : datetime.date... | 5594d60c7e5ebe8c1f2686f6b8eb68f89ddb0987 | 3,626,156 |
def generate_activation_url(token_name: str, token_value: str) -> str:
"""
Generates url with token_name=token_value embedded in it.
:param token_name:
:param token_value:
:return:
"""
return Config.FRONT_END_URL + "?" + f"{token_name}={token_value}" | db58a3d4b55276229486dbddb86ea51383393a10 | 3,626,157 |
import struct
def native_type_range(fmt):
"""Return range of a native type."""
if fmt == 'c':
lh = (0, 256)
elif fmt == '?':
lh = (0, 2)
elif fmt == 'f':
lh = (-(1<<63), 1<<63)
elif fmt == 'd':
lh = (-(1<<1023), 1<<1023)
else:
for exp in (128, 127, 64, 6... | dc8362aadece611b45b05f775cd0a95eefabcad7 | 3,626,158 |
def get_action(affordance_map, epsilon, open_scales):
"""Get action based on affordance_map.
Args:
affordance_map: [S, K, W, H]
epsilon: random aciton based on prob VS choose best aciton. If epsilon < 0: get action with best score
open_scales: list of open_scales [S]
Returns:
... | df34e426ba85198bd84f81046969b92dec9013a8 | 3,626,159 |
def drop_shadow(image, offset=(5, 5), background=0xffffff, shadow=0x444444,
border=8, iterations=5):
"""
Add a gaussian blur drop shadow to an image.
image - The image to overlay on top of the shadow.
offset - Offset of the shadow from the image as an (x,y) tuple. Can be
... | f8bb75d7e648144bf351527f43c74c801e1a7120 | 3,626,160 |
import random
import tqdm
def get_s_test(z_test_grad, z_losses, params, damp=0.01, scale=25.0, recursion_depth=20000, threshold=1e-8):
"""s_test can be precomputed for each test point of interest, and then
multiplied with grad_z to get the desired value for each training point.
Here, strochastic estimatio... | cdf460d305ade66cc106f53ca0b7bd687c1dcf3e | 3,626,161 |
def to_fft_image(fft_mat, is_shift=False):
"""Convert frequency matrix to visual image"""
if is_shift:
fft_mat = np.fft.fftshift(fft_mat)
log_mat = 20*np.log(np.abs(fft_mat))
return np.uint8(np.around(log_mat)) | f1bd9c50879a32a0624db62587463a94e3cbbd09 | 3,626,162 |
def np_normal(shape, random_state, scale=0.01):
"""
Builds a numpy variable filled with normal random values
Parameters
----------
shape, tuple of ints or tuple of tuples
shape of values to initialize
tuple of ints should be single shape
tuple of tuples is primarily for conv... | b12b82602d2d465195f0576bdb29446a6a7b9331 | 3,626,163 |
from typing import Optional
from typing import Callable
from typing import Awaitable
def head(
path: str, /, *, name: Optional[str] = None, include_in_schema: bool = True
) -> Callable[[Callable[[Request], Awaitable[Response]]], Route]:
"""decorator to create a Starlette Route for HEAD requests from an endpoi... | 162ea8d05926e3fad6a285ff8b6db86efb800bd5 | 3,626,164 |
def api_hash_key(*args, **kwargs):
"""参考cachetools hashkey实现,对WSGIRequest参数对象进行特殊处理"""
new_args, _ = deal_request_args(False, *args)
return hashkey(*new_args, **kwargs) | 15527ebd43b809d27919aec1648aa24802d61826 | 3,626,165 |
def len_column(table):
"""
Add length column containing the length of the original entry in the seq column.
Insert a number column with numbered entries for each row.
"""
for pos, i in enumerate(table):
i.insert(0, pos)
i.append(len(i[1]))
return table | 5a9215bc2feade70873de6adccd2b4c4b6acfed9 | 3,626,166 |
def _binary_roc_auc_score(y_true, y_score, sample_weight=None, max_fpr=None):
"""Binary roc auc score"""
if len(np.unique(y_true)) != 2:
raise ValueError("Only one class present in y_true. ROC AUC score "
"is not defined in that case.")
fpr, tpr, _ = roc_curve(y_true, y_sco... | a21058fb927fb5dfa9d727eaa5f8251ebc9a0c5e | 3,626,167 |
import logging
def build_service_set(gtfs_data):
"""Based on the calendar, figure out which service IDs should run for
each date"""
# The master dict of days
# Keys are the dates, the values are a list of service IDs that run for
# that day
service_days = {}
# Loop through each service ID... | 16bab43dd5607e94e4775428b87fb7836fe6ec13 | 3,626,168 |
def manage_org_users(request):
"""
View to manage the users of an organisation
Should only be accessed by admin users of the organisation
"""
if request.user.is_org_admin:
context_dict = {}
context_dict['organisation_users'] = request.user.organisation.get_users()
context_dic... | def1899fc8c6afb50166361ec80b7355a71f2773 | 3,626,169 |
def get_confusion_noise_robson19(f, t_obs=4 * u.yr):
"""Calculate the confusion noise using the model from Robson+19 Eq. 14 and Table 1
Also note that this fit is designed based on LISA sensitivity and so it is likely not sensible to apply
it to TianQin or other missions.
Parameters
----------
... | f58dcf51c1cb499d5bf04155c38d12263179b277 | 3,626,170 |
def default():
"""
Simply calls :func:`get` for the default endpoint.
"""
return get() | 45ed6b65d6d3191688d1f21556500dfe5bb14c48 | 3,626,171 |
import torch
def direct_1d(x, x_s, dx, dt, c, f):
"""Use the 1D Green's function to determine the wavefield at a given
location due to the given source.
"""
r = torch.abs(x - x_s).item()
t_shift = (r / c) / dt
u = dx * dt * c / 2 * torch.Tensor(np.cumsum(shift(f, t_shift)))
return u | 6eaf3754b95ad0202cbd6ef5bbdeda86acfa8ef9 | 3,626,172 |
def test_basic_state_transition(circuit):
"""Test the basic FSM function."""
class B123(edzed.FSM):
STATES = 'S1 S2 S3'.split()
EVENTS = [
('step', ['S1'], 'S2'),
['step', None, 'S3'], # default rule has lower precedence
('step', 'S3', 'S1') # single stat... | 47e9ad590e03515ac2c790a8e4b8fda071179c6e | 3,626,173 |
def home():
""" Home Page """
print("### Home Page Loaded ###")
return render_template('index.html', page="Home") | 21e47410da3113ecc56a3211a7f855c39a82cac7 | 3,626,174 |
def group_conv(N, H, W, CI, CO, group, KH, KW, PAD_H, PAD_W, SH, SW, cutH, cutCo, cutM, cutK, cutN, block_size, use_bias=False, kernel_name='conv'):
"""
split channels of FeatureMap to some groups,every group has its filter-kernel
Args:
args1:a list,the size is 3 if use_bias else the size is 2;
... | 96534916b0c1b575771402ba008a5060c9da70db | 3,626,175 |
import math
import torch
def read_alignment(
filename, format=None, *, max_taxa=math.inf, max_characters=math.inf
):
"""
Reads a single alignment file to a torch tensor of probabilites.
:param str filename: Name of input file.
:param str format: Optional input format, e.g. "nexus" or "fasta".
... | dc6d724fc9a8ece4ac9d6a06394d01310a9fa5bc | 3,626,176 |
def auto_load_processed(path):
"""Load processed BEEP .json files regardless of their class.
Enables loadfn capability for legacy BEEP files, since calling
loadfn on legacy files will return dictionaries instead of objects
or will outright fail.
Examples:
auto_load_processed("maccor_file_... | 322c501719e7c6d33b9509cb357651bec4254f55 | 3,626,177 |
def grating_linear_dispersion(
spec_inclusion_angle,
spec_focal_length,
spec_focal_length_tilt,
spec_grooves_per_mm,
spec_central_wavelength,
spec_order,
number_of_pixels,
pixel_width,
calibration_pixel,
):
"""
Parameters
----------
spec_inclusion_angle : float
... | 589044391cebea828a28927810e0c9ed15121456 | 3,626,178 |
from functools import reduce
def merge_columns_starting_positions(starting_positions, strict=True):
"""merging all lines starting positions"""
starting_positions = tuple(set(starting_positions))
# If only one is provided, or all equals, return it
if len(starting_positions) == 1:
return starti... | dc2830816ea00fc93ff4c68844500b4663acc743 | 3,626,179 |
def fin_FoM_optbd(n,d,bc,a,b,cini=None,imprecision=10**-2,bdlmax=100,alwaysbdlmax=False,lherm=True):
"""
Optimization of FoM over SLD MPO and also check of convergence in bond dimension. Function for finite size systems.
Parameters:
n: number of sites in TN
d: dimension of local Hilbert spa... | 32ccaf247614d8a5a1ec98fbc6b5bf1b616b93fd | 3,626,180 |
def create_cylinder(position, radius, height, orientation=(0,0,0), color=None, texture=None, mass=1, friction=0.1, client=0, isCollision=True):
"""
create cylinder in physical scene.
----------------------
position[3-element tuple]: Center position of the cylinder
orientation[3-element tuple]: Euler... | 413bdc1a5fcc74df2b2b04cecdfafcf1a88bd5fd | 3,626,181 |
def read_maze(file_name):
"""
Reads a maze stored in a text file and returns a 2d list containing the maze representation.
"""
try:
with open(file_name) as fh:
maze = [[char for char in line.strip("\n")] for line in fh]
num_cols_top_row = len(maze[0])
for row ... | 373e121a9dc827307fc6b56350f8b19247115651 | 3,626,182 |
def tokenize_batch_question_answering(pre_baskets, tokenizer, indices):
"""
Tokenizes text data for question answering tasks. Tokenization means splitting words into subwords, depending on the
tokenizer's vocabulary.
- We first tokenize all documents in batch mode. (When using FastTokenizers Rust multi... | b63c581b0a3d696883aab76bacca32f82dfbb646 | 3,626,183 |
def format(number):
"""Reformat the number to the standard presentation format."""
number = compact(number)
return (number[:-7] + '.' + number[-7:-4] + '.' +
number[-4:-1] + '-' + number[-1]) | c4bb448ee035c99bdbd3148be4bfef129209bd3c | 3,626,184 |
def user_register(**kwargs):
"""
swagger_from_file: Swagger/user/register.yml
"""
data = kwargs['data']
data['password'] = UserInfo.generate_hash(data['password'])
try:
obj = dynamic_modify(UserInfo(), data).create()
except Exception as e:
return response(ResponseEnum.INVALID... | c1340fca05349ce94143ca7c6f9c875c755b62c2 | 3,626,185 |
def _check(sample, data):
"""Get input sample for each chip bam file."""
if dd.get_chip_method(sample).lower() == "atac":
return [sample]
if dd.get_phenotype(sample) == "input":
return None
for origin in data:
if dd.get_batch(sample) in dd.get_batch(origin[0]) and dd.get_phenotyp... | 47c17783b852ece100e5f7c9d04e9a0f6bb69650 | 3,626,186 |
def step_update(x, P, a, b, sd):
"""
Apply 'observation' of form
a'x = b + N(0, sd^2)
to obtain new x, P, useful for building priors
:param x: n_k, n
:param P: n_k, n, n
:param a: n
:param b: n_k,
:param sd:
:return:
"""
PCt = P @ a # n_k, n
CPC_Q = PCt @ a + sd ** 2... | 91e52a0c2696e1561c558f761e8d318ca51e64b8 | 3,626,187 |
def validate_single_message(schema, input_file, verbose):
"""Validate single message stored in input file."""
processed = 0
valid = 0
invalid = 0
error = 0
try:
payload = load_json_from_file(input_file, verbose)
processed = 1
validate(schema, payload, verbose)
va... | 1ef1854c9873e4df9ff6c61303a1a8d9e35e98d4 | 3,626,188 |
def sns_certificate(*args):
""" Mock requests to retrieve the SNS signing certificate """
with open('tests/files/certificate.pem') as cert_file:
cert = cert_file.read()
return cert | 6d1198c7ea3c29be28dbecf6affe5c31ab51267a | 3,626,189 |
from scipy.spatial import cKDTree as KDTree
def kldivergence(x, y):
"""Compute the Kullback-Leibler divergence between two multivariate samples.
Parameters
----------
x : 2D array (n,d)
Samples from distribution P, which typically represents the true
distribution.
y : 2D array (m,d)
... | 55a512b6d720d065f32aa4a1877f10a8f9e03168 | 3,626,190 |
def match_any_if_key_matches(audit_id, result_to_compare, args):
"""
We want to compare things if we found our interested key
Even if the list does not have my interested name, it will pass
Match dictionary elements dynamically. Match from a list of available dictionaries
There is an argument: matc... | 0f96d2dc8d535dd91df9c2ef00e2a0c860803c10 | 3,626,191 |
def get_municipio_near_geo(geo_points, max_meters=15e+3):
"""
Parameters
-----------
geo_points: list
List containing (latitude, longitude) coordinates.
max_meters: int, float
Max. number of meters from the geo_points to the municipio centroid
used to filter municipios.
... | 5c16ff7174eb65639ab130b0b796c770c3ef9a5e | 3,626,192 |
def replace_text_in_tables(page):
"""
Replace <p> tags with their contents because `html2text` has troubles with p
tags inside tables.
"""
tables = page.find('body').find_all('table')
has_colspan = False
for table in tables:
rows = table.find_all(["th", "tr"])
for row in rows... | eae9ba731b21bae36b018c80450d5060ed69fc35 | 3,626,193 |
def get_mirror_table (left, right, miraxis='x'):
"""
Return a mirror table between two object on chosen axis
:param str left: object to compare to slave
:param str right: object to compare to master
:param str miraxis: 'x'(default) chosen world axis on wich mirror is wanted
:return: list: return... | c35cb05282ac4486338916dfccf248e6531f30d2 | 3,626,194 |
def work_callback(ctx, param, value):
"""
Load correct work plugin and add it into the context
"""
plugin_name = plugin_callback(ctx, param, value)
plugin_cls = get_work_plugins()[plugin_name]
plugin = plugin_cls(config=ctx.obj["config"])
ctx.obj[param.name] = plugin
return plugin | 89c0a8f129c3ce450bb0d4e4534c482fea4f68c9 | 3,626,195 |
import numpy as np
import math
def wmh( flair, t1, t1seg, mmfromconvexhull = 12 ) :
"""
Outputs the WMH probability mask and a summary single measurement
Arguments
---------
flair : ANTsImage
input 3-D FLAIR brain image (not skull-stripped).
t1 : ANTsImage
input 3-D T1 brain image (not skull-st... | 70eba2400fde4bb8faa25b2ab85ce55a03ae3f2c | 3,626,196 |
def translate_delta(mat, dx, dy):
"""
Return matrix with elements translated by dx and dy, filling the would-be
empty spaces with 0. I feel this method may not be the most efficient.
"""
rows, cols = len(mat), len(mat[0])
# Filter out simple deltas
if (dx == 0 and dy == 0):
return m... | 38492c874bc7bbd59787f4b2d94c2ea0150e69f8 | 3,626,197 |
def upscale_x(
inputs,
scale=4,
scope='upscale_x'
):
"""mimic the tensorflow bilinear-upscaling for a fix ratio of x."""
with tf.variable_scope(scope):
size = tf.shape(inputs)
b = size[0]
h = size[1]
w = size[2]
c = size[3]
p_inputs = tf.concat((inputs, inputs[:, -1:, :, :]), ax... | f967d74db805d1aa04e96ef406caa56818df4080 | 3,626,198 |
import logging
import json
def audio_rttm_map(manifest):
"""
This function creates AUDIO_RTTM_MAP which is used by all diarization components to extract embeddings,
cluster and unify time stamps
input: manifest file that contains keys audio_filepath, rttm_filepath if exists, text, num_speakers if kno... | b7828393b5571c7b8ed67748ef9b188c00f90731 | 3,626,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.