content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getLambdaFasta():
"""
Returns the filename of the FASTA of the lambda phage reference.
"""
return _getAbsPath('lambdaNEB.fa') | 4cb351d874087da71d8f726802a5bb86438dacd1 | 15,006 |
def Rotation_ECL_EQD(time):
"""Calculates a rotation matrix from ecliptic J2000 (ECL) to equatorial of-date (EQD).
This is one of the family of functions that returns a rotation matrix
for converting from one orientation to another.
Source: ECL = ecliptic system, using equator at J2000 epoch.
Targe... | d140e2c03e62fba2168faf9c3599afa6e41bb774 | 15,008 |
def _make_players_away(team_size):
"""Construct away team of `team_size` players."""
away_players = []
for i in range(team_size):
away_players.append(
Player(Team.AWAY, _make_walker("away%d" % i, i, _RGBA_RED)))
return away_players | b0beff6f06fc52f870c143c01c14d18eb77d0cc5 | 15,009 |
import json
def store_barbican_secret_for_coriolis(
barbican, secret_info, name='Coriolis Secret'):
""" Stores secret connection info in Barbican for Coriolis.
:param barbican: barbican_client.Client instance
:param secret_info: secret info to store
:return: the HREF (URL) of the newly-create... | 218bf941203dd12bc78fc7a87d6a2f9f21761d57 | 15,010 |
import random
def padding():
"""Return 16-200 random bytes"""
return URANDOM(random.randrange(16, PAD_MAX)) | 65a52c19c3b39344bd1959c58f2cd7950b0a19e4 | 15,012 |
def find():
"""Prints user message and returns the number of HP-49 connected.
"""
hps = com.find()
if len( hps ) == 0:
print "No HP49-compatible devices connected."
sys.stdout.flush()
else:
print "Number of HP49-compatible devices: %d" % len( hps )
sys.stdout.flush()
retu... | 8530fc9d6d904e8c4fe061c237af57f9874a2ea2 | 15,014 |
def get_children_templates(pvc_enabled=False):
"""
Define a list of all resources that should be created.
"""
children_templates = {
"service": "service.yaml",
"ingress": "ingress.yaml",
"statefulset": "statefulset.yaml",
"configmap": "configmap.yaml",
"secret": "... | 25db24b03542b1365529bbf1814e2fb801337022 | 15,015 |
def sort_as_int(environment, value, reverse=False, attribute=None):
"""Sort collection after converting the attribute value to an int"""
def convert_to_int(x):
val = str(x)
# Test if this is a string representation of a float.
# This is what the copy rig does and it's annoying
if... | 13e7727d1337bbfddec1a0661552c51d7015e58b | 15,016 |
def get_pretty_table_for_item(item, output_fields):
"""
"""
x = PrettyTable(["Attribute", "Value"])
attrs = _filter_attributes(item.get_attributes(), output_fields)
for attr in attrs:
row = []
row.append(attr)
row.append(getattr(item, attr))
x.add_row(row)
return... | 48d7b4c1a53884dc65de8da1167762cbf0143d2c | 15,017 |
def create_t1_based_unwarp(name='unwarp'):
"""
Unwarp an fMRI time series based on non-linear registration to T1.
NOTE: AS IT STANDS THIS METHOD DID NOT PRODUCE ACCEPTABLE RESULTS
IF BRAIN COVERAGE IS NOT COMPLETE ON THE EPI IMAGE.
ALSO: NEED TO ADD AUTOMATIC READING OF EPI RESOLUTION TO... | cbf3180e2899ac6314cde3c30ca3619ca4d3e125 | 15,018 |
def get_qnode(caching, diff_method="finite-diff", interface="autograd"):
"""Creates a simple QNode"""
dev = qml.device("default.qubit.autograd", wires=3)
@qnode(dev, caching=caching, diff_method=diff_method, interface=interface)
def qfunc(x, y):
qml.RX(x, wires=0)
qml.RX(y, wires=1)
... | 3a8cb0f47e8846338338d21896e59cba475e8351 | 15,019 |
def segment_relative_timestamps(segment_start, segment_end, timestamps):
""" Converts timestamps for a global recording to timestamps in a segment given the segment boundaries
Args:
segment_start (float): segment start time in seconds
segment_end (float): segment end time in seconds
tim... | 743938adfb8ee1450c2140f76dbbdfb88c2a3c7f | 15,020 |
def compare_dataframes_mtmc(gts, ts):
"""Compute ID-based evaluation metrics for MTMCT
Return:
df (pandas.DataFrame): Results of the evaluations in a df with only the 'idf1', 'idp', and 'idr' columns.
"""
gtds = []
tsds = []
gtcams = gts['CameraId'].drop_duplicates().tolist()
tscams ... | 002333c2be971a453727f43c257b46a99b0451cb | 15,021 |
def fetch_xml(url):
"""
Fetch a URL and parse it as XML using ElementTree
"""
resp=urllib2.urlopen(url)
tree=ET.parse(resp)
return tree | d0f4f5b7fe19692675cba1254f6bfa63f07e45a5 | 15,023 |
def update_hirsch_index(depth_node_dict, minimum_hirsch_value, maximum_hirsch_value):
"""
Calculates the Hirsch index for a radial tree.
Note that we have a slightly different definition of the Hirsch index to the one found in:
Gómez, V., Kaltenbrunner, A., & López, V. (2008, April).
Statistical an... | 2fdf5ca6aa216eacb3f18cd2f91875d02e0740ea | 15,024 |
def get_E_E_fan_H_d_t(P_fan_rtd_H, V_hs_vent_d_t, V_hs_supply_d_t, V_hs_dsgn_H, q_hs_H_d_t):
"""(37)
Args:
P_fan_rtd_H: 定格暖房能力運転時の送風機の消費電力(W)
V_hs_vent_d_t: 日付dの時刻tにおける熱源機の風量のうちの全般換気分(m3/h)
V_hs_supply_d_t: param V_hs_dsgn_H:暖房時の設計風量(m3/h)
q_hs_H_d_t: 日付dの時刻tにおける1時間当たりの熱源機の平均暖房能力(-)
... | 0e2ceb9f8fbedd95d44f1c307cfb0d9ea17ea370 | 15,027 |
def load_func(func_string):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if func_string is None:
return None
elif isinstance(func_string, str):
return import_from_string(func_string)
return func_string | 99fdf6889936c95d7680ed5a70a2095474e02a9b | 15,028 |
def normalize(features):
"""
Scale data in provided series into [0,1] range.
:param features:
:return:
"""
return (features - features.min()) / (features.max() - features.min()) | a85d77e37e71c732471d7dcd42ae1aef2181f6dc | 15,029 |
def get_gitlab_template_version(response):
"""Return version number of gitlab template."""
return glom(response, 'ref', default=False).replace('refs/tags/', '') | 95e1be93ef6f14d24757e07d0ba644ce89bc0dc9 | 15,030 |
def getConfigXmlString(version, name, protocol, user, host, port, path):
"""! Arguments -> XML String. """
tag_root = ET.Element(TAG_ROOT)
tag_root.set(ATTR_VERSION, version)
tag_remote = ET.Element(TAG_REMOTE)
tag_remote.set(ATTR_NAME, name)
tag_root.append(tag_remote)
appendElement(tag_r... | da0546a2e276c16820e09807930c981bf7d5406c | 15,031 |
from typing import Optional
def phase_angle(A: Entity,
B: Entity,
C: Entity) -> Optional[float]:
"""The orbital phase angle, between A-B-C, of the angle at B.
i.e. the angle between the ref-hab vector and the ref-targ vector."""
# Code from Newton Excel Bach blog, 2014, "th... | ddbbc75909977350f89748c0afdb242ed9d741b6 | 15,032 |
def upper(string): # pragma: no cover
"""Lower."""
new_string = []
for c in string:
o = ord(c)
new_string.append(chr(o - 32) if LC_A <= o <= LC_Z else c)
return ''.join(new_string) | c13b1cc49a608bcc65a3afa87ca94f73f0deeb0b | 15,034 |
def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except AttributeError: # nosec(cjschaef): 'obj' doe... | 43160e6dd61ddc2e8e0559925bf2a35def79eb3f | 15,035 |
from datetime import datetime
import time
def dateToUsecs(datestring):
"""Convert Date String to Unix Epoc Microseconds"""
dt = datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
return int(time.mktime(dt.timetuple())) * 1000000 | cba081ae63523c86572463249b4324f2183fcaaa | 15,036 |
def _compute_applied_axial(R_od, t_wall, m_stack, section_mass):
"""Compute axial stress for spar from z-axis loading
INPUTS:
----------
params : dictionary of input parameters
section_mass : float (scalar/vector), mass of each spar section as axial loading increases with spar depth
OUT... | 35c9a92b22b3639b6d1236ba45dd797388e25b07 | 15,037 |
def categorical(p, rng=None, size=()):
"""Draws i with probability p[i]"""
if len(p) == 1 and isinstance(p[0], np.ndarray):
p = p[0]
p = np.asarray(p)
if size == ():
size = (1,)
elif isinstance(size, (int, np.number)):
size = (size,)
else:
size = tuple(size)
... | 1cee8c996206284f36f3bf72f8c6729037489f4d | 15,039 |
from typing import List
def covariance_distance(covariances: List[Covariance],
x: np.ndarray) -> np.ndarray:
"""Euclidean distance of all pairs gp_models.
:param covariances:
:param x:
:return:
"""
# For each pair of kernel matrices, compute Euclidean distance
n_ke... | 7bfe0337c89b8476285797d1fdec394ffcd04479 | 15,042 |
def create_inputs(im, im_info, model_arch='YOLO'):
"""generate input for different model type
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
model_arch (str): model type
Returns:
inputs (dict): input of model
"""
inputs = {}
inputs['image'... | 940563f6c48cfe54e328339b0efcd44e03ad67d8 | 15,043 |
def multiplex(n, q, **kwargs):
""" Convert one queue into several equivalent Queues
>>> q1, q2, q3 = multiplex(3, in_q)
"""
out_queues = [Queue(**kwargs) for i in range(n)]
def f():
while True:
x = q.get()
for out_q in out_queues:
out_q.put(x)
t =... | ee9dac3506acb5159580a39d64e3cb046c44b204 | 15,044 |
import xml.etree.ElementTree as ET
def select_project(FILENAME):
"""
lee el fichero xml FILENAME, muestra los proyectos para que el usuario
escoja uno de ellos
input
FILENAME: fichero xml de estructura adecuada situada donde se encuentran
los scripts del programa
return:
... | 0ef7ddd4b320e2ca577c253522f512e2802569e1 | 15,045 |
def compute_average(arr):
"""Compute average value for given matrix
Args:
arr (numpy array): a numpy array
Return:
float: average value
"""
val_avg = np.average(arr)
return val_avg | c69d17f53e946f693242cfd9d90877847e7c7cc6 | 15,046 |
from typing import Callable
def ta_series(func: Callable, *args, **kwargs) -> QFSeries:
"""
Function created to allow using TA-Lib functions with QFSeries.
Parameters
----------
func
talib function: for example talib.MA
args
time series arguments to the function. They are all ... | c3e4e644fd3e6ce7853cbe99441fe6c8a5ca2679 | 15,048 |
def find_trendline(
df_data: pd.DataFrame, y_key: str, high_low: str = "high"
) -> pd.DataFrame:
"""Attempts to find a trend line based on y_key column from a given stock ticker data frame.
Parameters
----------
df_data : DataFrame
The stock ticker data frame with at least date_id, y_key co... | dbe995fab1436a1c212780eebf123dc39f27f234 | 15,049 |
def find_core(read, core, core_position_sum, core_position_count, start = -1):
"""
Find the core sequence, trying "average" position first for efficiency.
"""
if start < 0 and core_position_count > 0:
core_position = round(core_position_sum/core_position_count)
if len(read) > core_po... | 3a0de472194db00fac4e65a2b0e15cfa351eb70f | 15,050 |
from functools import reduce
def clambda(n):
"""
clambda(n)
Returns Carmichael's lambda function for positive integer n.
Relies on factoring n
"""
smallvalues=[1,1,2,2,4,2,6,2,6,4,10,2,12,6,4,4,16,6,18,4,6,10,22,2,20,12,18,\
6,28,4,30,8,10,16,12,6,36,18,12,4,40,6,42,10,12,22,46,4,42,20,16,... | 0da59a30e6d7376731a868ae81aed8e1cb42e8ce | 15,051 |
def dashboard():
"""
Render the dashboard template on the /dashboard route
"""
return render_template('page/home/dashboard.html', title="Dashboard") | 12e1750a6c0b90aa8fcda29b78a463805abd45f3 | 15,052 |
import json
def get_port_status(cluster, lswitch_id, port_id):
"""Retrieve the operational status of the port"""
try:
r = do_single_request("GET",
"/ws.v1/lswitch/%s/lport/%s/status" %
(lswitch_id, port_id), cluster=cluster)
r = json.... | f5c6fdf7d23fef17f402525cbfe9c3892012e3f0 | 15,053 |
import scipy
import tqdm
import logging
def make_nearest_neighbors_graph(data, k, n=1000):
"""Build exact k-nearest neighbors graph from numpy data.
Args:
data: Data to compute nearest neighbors of, each column is one point
k: number of nearest neighbors to compute
n (optional): number of neighbors t... | dd99b42c306ac963232aeca4e86ef7e0449126ca | 15,054 |
import multiprocessing
def read_examples(input_files, batch_size, shuffle, num_epochs=None):
"""Creates readers and queues for reading example protos."""
files = []
for e in input_files:
for path in e.split(','):
files.extend(file_io.get_matching_files(path))
thread_count = multiprocessing.cpu_count... | 5265e14d02b53d7b7c8754f980573b8d8c9667ea | 15,055 |
def gen_context(n=10):
"""
method returns a random matrix which can be used to produce private prices over a bunch of items
"""
return np.random.randint(-3,4,size=(n,n)) | 51b3cf2a64530147eddacf628c8b593b7e923402 | 15,056 |
def _parallel_binning_fit(split_feat, _self, X, y,
weights, support_sample_weight,
bins, loss):
"""Private function to find the best column splittings within a job."""
n_sample, n_feat = X.shape
feval = CRITERIA[_self.criterion]
split_t = None
spl... | 5889993b9ad1ca49ac9e8ce541262ff716dea18f | 15,057 |
def checkkeywords(keywordsarr, mdtype):
""" Check the keywords
Datasets: for Check 9
Services: for Check 9
Logic: there must be at least one keyword to get a score = 2. If keywords contain comma's (","), then a maimum of score = 1 is possible.
"""
score = 0
# keywordsarr is an array of objec... | cb165689ce820c1ead3622ed562260ee76558205 | 15,059 |
def compute_presence_ratios(
sorting,
duration_in_frames,
sampling_frequency=None,
unit_ids=None,
**kwargs
):
"""
Computes and returns the presence ratios for the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be... | f270ff52c2d60296db25887bcbb7d203bfc23c07 | 15,060 |
def img_box_match(bboxes_gt, bboxes_pre, iou_threshold):
"""
Goal:
Returns info for mAP calculation (Precision recall curve)
Precision = TP / (TP + FP)
Recall = TP / (TP + FN)
Returns:
list of [TP/FP, conf]
num_gt_bboxes : int
Notes:
For each prediction ... | 09a7c9e9739f491777f1b0f48f745858281a0953 | 15,061 |
def random_char():
"""Return a random character."""
return Char(choice(_possible_chars)) | aca30fc1e6b7039cd5187264b89bca4d2899d169 | 15,062 |
def bond(self, atom:Atom, nBonds:int=1, main=False) -> Atom:
"""Like :meth:`__call__`, but returns the atom passed in instead, so you
can form the main loop quickly."""
self(atom, nBonds, main); return atom | e8d065f55110c37b4db06ca394c741d98ffbd446 | 15,063 |
def train_list():
"""
Return a sorted list of all train patients
"""
patients = listdir_no_hidden(INPUT_PATH)
patients.sort()
l = []
for patient in patients:
if labels[patient] != None:
l.append(patient)
return l | 7977e8ea72e826e18b4138391e812c15f3cfb6c0 | 15,064 |
def split_data(X, Y):
"""
This function split the features and the target into training and test set
Params:
X- (df containing predictors)
y- (series conatining Target)
Returns:
X_train, y_train, X_test, y_test
"""
X_train, X_test, Y_train, Y_test = train_test_split(
... | c8dbc5a6e63f0b24abf3547ba208ad0a24e5594b | 15,065 |
def get_bucket(client=None, **kwargs):
"""
Get bucket object.
:param client: client object to use.
:type client: Google Cloud Storage client
:returns: Bucket object
:rtype: ``object``
"""
bucket = client.lookup_bucket(kwargs['Bucket'])
return bucket | b71891eec3a9f7c8f9b8fad134b2dd02bfb65e51 | 15,066 |
def remove_macros(xml_tree: etree._ElementTree) -> etree._ElementTree:
"""Removes the macros section from the tool tree.
Args:
xml_tree (etree._ElementTree): The tool element tree.
Returns:
etree.ElementTree: The tool element tree without the macros section.
"""
to_remove = []
... | 77fed7e85dadbe8b2ec7511ad3b4cf7c272807a4 | 15,067 |
def flight_time_movies_2_binary_search(movie_lengths, flight_length):
"""
Solution: Sort the list of movies, then iterate it, conducting a binary
search on each item for different item, when added together, equals the
flight length.
Complexity:
Time: O(n * lg{n})
Space: O(1)
"""
if len(movie_lengths) < 2:
... | ac7e8ad340e677f6c51f1841aab61262d8c4e226 | 15,068 |
def find_vertical_bounds(hp, T):
"""
Finds the upper and lower bounds of the characters' zone on the plate based on threshold value T
:param hp: horizontal projection (axis=1) of the plate image pixel intensities
:param T: Threshold value for bound detection
:return: upper and lower bounds
"""
N = len(hp)
# F... | 8520c3b638cafe1cfb2d86cc7ce8c3f28d132512 | 15,069 |
import base64
def executeCmd(cmd,arg):
""" the meat: how we react to the SNI-based logic and execute the underlying command """
global currentPath
global currentDirList
global currentFileList
global currentFileSizeList
global agentName
commands = initCmd(cmd)
for testedCommand, alias... | b257e77c2f7c692d63aa4140cc5ce6ccc2213273 | 15,070 |
from typing import Union
from typing import Tuple
import re
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = ... | dbdc6436c94d57aa2d1eb910dc18e4afeeadf689 | 15,071 |
def get_dosage_ann():
""" Convenience function for getting the dosage and snp annotation
"""
dos = {}
s_ann = {}
dos_path =\
("/export/home/barnarj/CCF_1000G_Aug2013_DatABEL/CCF_1000G_Aug2013_Chr"
"{0}.dose.double.ATB.RNASeq_MEQTL.txt")
SNP_ANNOT =\
("/proj/ge... | 792caa3c9b6326178ca5a706b694c52cf1bddccc | 15,072 |
import types
import typing
import re
def function_arguments(function_name: str, services_module: types.ModuleType) -> typing.List[str]:
"""Get function arguments for stan::services `function_name`.
This function parses a function's docstring to get argument names. This is
an inferior method to using `ins... | 01a12d97c6b154159c4ba2d142e1374a008befe3 | 15,073 |
def cost_n_moves(prev_cost: int, weight: int = 1) -> int:
""" 'g(n)' cost function that adds a 'weight' to each move."""
return prev_cost + weight | 77a737d68f2c74eaba484b36191b95064b05e1a9 | 15,074 |
import io
def get_gaussian_fundamentals(s, nfreq=None):
"""
Parses harmonic and anharmonic frequencies from gaussian
log file.
Input:
s: String containing the log file output.
nfreq : number of vibrational frequencies
Returns:
If successful:
Numpy 2D array of size: nfreq x 2
... | 0da2acf3eb1ca0e057da8935ad772a2c65fd251a | 15,076 |
def uniform_selection_tensor(tensor_data: np.ndarray,
p: int,
n_bits: int,
per_channel: bool = False,
channel_axis: int = 1,
n_iter: int = 10,
min... | 17f5e13443fc23ce4d0dafc0fb69de226e93fc56 | 15,077 |
def calculate_bin_P(P, x, cal_type='pes'):
""" Calculate the virtual, binary transition function.
That is, this function is to calculate the transition function which
a state and action pair may visit the virtual state $z$
"""
n, m = x.world_shape
# P_z is defined for the n*m states $s$ and a vi... | db7908f2ac0f20d72a70a920c412b895bf4ccef4 | 15,079 |
def makeYbus(baseMVA, bus, branch):
"""Builds the bus admittance matrix and branch admittance matrices.
Returns the full bus admittance matrix (i.e. for all buses) and the
matrices C{Yf} and C{Yt} which, when multiplied by a complex voltage
vector, yield the vector currents injected into each line from... | 8068d6a17c99f747e8d95b0b3ba1ac65735be382 | 15,080 |
import numpy
def list_blob(math_engine, batch_len, batch_width, list_size, channels, dtype="float32"):
"""Creates a blob with one-dimensional Height * Width * Depth elements.
Parameters
---------
math_engine : object
The math engine that works with this blob.
batch_len : int, > 0
... | dab3b45173fcca32f2cfc7bfbc585e002ff34f37 | 15,081 |
def skip_on_pypy_because_cache_next_works_differently(func):
"""Not sure what happens there but on PyPy CacheNext doesn't work like on
CPython.
"""
return _skipif_wrapper(func, IS_PYPY,
reason='PyPy works differently with __next__ cache.') | b2f765f1cad292948bb456aa841e92f180222061 | 15,082 |
import random
def get_life_of_brian():
"""
Get lines from test_LifeOfBrian.
"""
count = 0
monty_list = ['coconut']
try:
with open(LIFE_OF_BRIAN_SCRIPT) as f:
lines = f.readlines()
for line in lines:
count += 1
#print(line)
... | 5b6007888f51b0b2a38eea6381bdaa5187624dda | 15,083 |
def ackley_func(x):
"""Ackley's objective function.
Has a global minimum at :code:`f(0,0,...,0)` with a search
domain of [-32, 32]
Parameters
----------
x : numpy.ndarray
set of inputs of shape :code:`(n_particles, dimensions)`
Returns
-------
numpy.ndarray
compute... | f00b729f57fbaa1534bb78589e1a64912b08b4a3 | 15,084 |
def validate_listable_type(*atype):
"""Validate a list of atype.
@validate_listable_type(str)
def example_func(a_list):
return a_list
@validate_listable_type(int)
def example_int_func(a_list):
return a_list
"""
if len(atype) != 1:
raise ValueError("Expected... | 691737184fca8bdcc7f4c3779af86b9a041b71dc | 15,085 |
def meh(captcha):
"""Returns the sum of the digits which match the next one in the captcha
input string.
>>> meh('1122')
3
>>> meh('1111')
4
>>> meh('1234')
0
>>> meh('91212129')
9
"""
result = 0
for n in range(len(captcha)):
if captcha[n] == captcha[(n + 1) ... | 2ff68455b7bb826a81392dba3bc8899374cbcc3e | 15,086 |
def check_cli(module, cli):
"""
This method checks if vRouter exists on the target node.
This method also checks for idempotency using the vrouter-bgp-show command.
If the given vRouter exists, return VROUTER_EXISTS as True else False.
If the given neighbor exists on the given vRouter, return NEIGHB... | fdeb4dafad83562a48d0d22871fb6dc5a845fc2b | 15,087 |
def is_prime(n):
""" from
https://stackoverflow.com/questions/15285534/isprime-function-for-python-language
"""
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if ... | e992badd0648d0896097df71186fee2895d20119 | 15,088 |
def load(file, encoding=None):
"""load(file,encoding=None) -> object
This function reads a tnetstring from a file and parses it into a
python object. The file must support the read() method, and this
function promises not to read more data than necessary.
"""
# Read the length prefix one char... | 939cc6f7a42daa35552e256a1e2725826d44c01c | 15,089 |
import ispyb.model.datacollection
import ispyb.model.processingprogram
import logging
import configparser
def enable(configuration_file, section="ispyb"):
"""Enable access to features that are currently under development."""
global _db, _db_cc, _db_config
if _db_config:
if _db_config == configur... | 2aa613694f01c290f4cfeea8d8a470e87000021f | 15,090 |
def MakeMsgCmd(cmdName,argList):
"""
Take a command name and an argList of tuples consisting of
pairs of the form (argName, argValue), and return a string
representing the corresponding dibs command.
"""
body = MakeStartTag(dibs_constants.cmdTagName,{'id':cmdName}) + '\n'
for argPair in arg... | 63fd4c2695c005fa7ff465cd1975285d15dd4faf | 15,091 |
def preprocess(tweet):
"""
Substitures urls with the string URL. Removes leading and trailing whitespaces
Removes non latin characters
:param tweet:
:return:
"""
# remove URL
line = remove_url(str(tweet.strip()))
# remove non Latin characters
stripped_text = ''
for c in line:... | 44bc9f9c66c6abc8f95acdf1666f9ded7c6aa610 | 15,092 |
def read_xml_file(input_file, elem):
"""Reads xml data and extracts specified elements
Parameters
----------
input_file : str
The OTA xml file
elem : str
Specified elements to be extracted
Returns
-------
list
a list of xml seat data
"""
tree = ET.parse(... | 58b8e4b86f1400d0d77856cb57e6823f0c538487 | 15,093 |
from .application import Application, ApplicationEnv
from .operator import Operator, OperatorEnv
from typing import Optional
from typing import Union
from typing import List
def env(pip_packages: Optional[Union[str, List[str]]] = None):
"""A decorator that adds an environment specification to either Operator or A... | 9404d28e56a0d8824c9f05a0fa601b9ba181c98f | 15,094 |
import time
def test_trace_propagation(
endpoint, transport, encoding, enabled, expect_spans, expect_baggage,
http_patchers, tracer, mock_server, thrift_service,
app, http_server, base_url, http_client):
"""
Main TChannel-OpenTracing integration test, using basictracer as
implement... | afd85ef71b14a263f4480a0c0f81e019dc680e34 | 15,095 |
def cost_stage_grads(x, u, target, lmbda):
"""
x: (n_states, )
u: (n_controls,)
target: (n_states, )
lmbda: penalty on controls
"""
dL = jacrev(cost_stage, (0,1)) #l_x, l_u
d2L = jacfwd(dL, (0,1)) # l_xx etc
l_x, l_u = dL(x, u, target, lmbda)
d2Ldx, d2Ldu = d2L(x, u, t... | a6137653adcb3579775a9bcc9e8ddf03bb6f2cda | 15,096 |
def create_rotation_matrix(angles):
"""
Returns a rotation matrix that will produce the given Euler angles
:param angles: (roll, pitch, yaw)
"""
R_x = Matrix([[1, 0, 0],
[0, cos(q), -sin(q)],
[0, sin(q), cos(q)]]).evalf(subs={q: angles[0]})
R_y = Matrix([[cos... | 8431dce383a83d431f9951f76624723f5697cf83 | 15,097 |
def goodput_for_range(endpoint, first_packet, last_packet):
"""Computes the goodput (in bps) achieved between observing two specific packets"""
if first_packet == last_packet or \
first_packet.timestamp_us == last_packet.timestamp_us:
return 0
byte_count = 0
seen_first = False
for pa... | aea56993771c1a250dacdfccf8328c7a0d3ce50b | 15,098 |
from typing import Sequence
def validate_scopes(
required_scopes: Sequence[str], token_scopes: Sequence[str]
) -> bool:
"""Validates that all require scopes are present in the token scopes"""
missing_scopes = set(required_scopes) - set(token_scopes)
if missing_scopes:
raise SecurityException(f... | e979cdd2eb73c89084f72fd4f70390dfe3109c17 | 15,099 |
def skip_after_postgres(*ver):
"""Skip a test on PostgreSQL after (including) a certain version."""
ver = ver + (0,) * (3 - len(ver))
def skip_after_postgres_(f):
@wraps(f)
def skip_after_postgres__(self):
if self.conn.server_version >= int("%d%02d%02d" % ver):
re... | 075aecad4bcdd2340ec57089124143cc3642a38b | 15,101 |
def make_order_embeddings(max_word_length, order_arr):
"""
根据笔顺表生成具有最大字长约束的笔顺embeddings
:param max_word_length:
:param order_arr:
:return:
"""
order_arr = [
row + [0] * (max_word_length - len(row)) if len(row) <= max_word_length
else row[:max_word_length - 1] + [row[-1]]
... | a2f2ac2d0576b2a22145e583cc1e5b8fa9c1cc77 | 15,103 |
import numpy
def agg_double_list(l):
"""
@param l:
@type l:
@return:
@rtype:
"""
# l: [ [...], [...], [...] ]
# l_i: result of each step in the i-th episode
s = [numpy.sum(numpy.array(l_i), 0) for l_i in l]
s_mu = numpy.mean(numpy.array(s), 0)
s_std = numpy.std(numpy.array(s), 0)
return s_mu, s_std | 82b67e70caccb1f5d430e8e9f0a9c75348d3bc7a | 15,104 |
def get_string_from_bytes(byte_data, encoding="ascii"):
"""Decodes a string from DAT file byte data.
Note that in byte form these strings are 0 terminated and this 0 is removed
Args:
byte_data (bytes) : the binary data to convert to a string
encoding (string) : optional, the encoding type to... | c07523139e2509fcc19b2ce1d9a933fcb648abfd | 15,105 |
def default_component():
"""Return a default component."""
return {
'host': '192.168.0.1',
'port': 8090,
'name': 'soundtouch'
} | 780dd84ff613f2bccb56f560e5de77e9d57d9d5a | 15,106 |
from pathlib import Path
def check_series_duplicates(patches_dir, series_path=Path('series')):
"""
Checks if there are duplicate entries in the series file
series_path is a pathlib.Path to the series file relative to the patches_dir
returns True if there are duplicate entries; False otherwise.
"... | 58a5b6fbcf6867d770693938a2fc8308d644d54b | 15,107 |
def is_free(board: list, pos: int) -> bool:
"""checks if pos is free or filled"""
return board[pos] == " " | 64b75aa5d5b22887495e631e235632e080646422 | 15,108 |
def rc_from_blocks(blocks):
"""
Computes the x and y dimensions of each block
:param blocks:
:return:
"""
dc = np.array([np.diff(b[:, 0]).max() for b in blocks])
dr = np.array([np.diff(b[:, 1]).max() for b in blocks])
return dc, dr | 0837367eca7a7668a3f0b0078cf8699f5e5bc4d6 | 15,109 |
def serialize_measurement(measurement):
"""Serializes a `openff.evaluator.unit.Measurement` into a dictionary of the form
`{'value', 'error'}`.
Parameters
----------
measurement : openff.evaluator.unit.Measurement
The measurement to serialize
Returns
-------
dict of str and str... | 69eedd9006c63f5734c762d6113495a913d5a8c4 | 15,111 |
from exifpy.objects import Ratio
def nikon_ev_bias(seq):
"""
http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp
First digit seems to be in steps of 1/6 EV.
Does the third value mean the step size? It is usually 6,
but it is 12 for the ExposureDifference.
Check for an error conditi... | 09a91fc3d82851bb6411b549c282a16f02470e88 | 15,112 |
import json
def process_message(schema, publisher, data):
"""
Method to process messsages for all the bases that uses
Google's Pub/Sub.
Args:
schema (:obj:`dict`, required): A JSON schema for contract
validation. JSON Schema is a vocabulary that allows you
... | 01e396355e6f7fd6913eaff786af39c95da64718 | 15,113 |
def rename_record_columns(records, columns_to_rename):
"""
Renames columns for better desc and to match Socrata column names
:param records: list - List of record dicts
:param columns_to_rename: dict - Dict of Hasura columns and matching Socrata columns
"""
for record in records:
for col... | 41d5cc90a368f61e8ce138c54e9f5026bacd62b9 | 15,114 |
import requests
import json
def request_similar_resource(token, data_):
"""If a similar resource to the data_ passed exists, this method gets and returns it """
headers = {'Authorization': 'Token {}'.format(token.token)}
# get the resource endpoint
url_check_res = URL.DB_URL + 'getSimilarResource/' ... | 84981ff2520050651b0cb83b11198a2fc1117582 | 15,115 |
def total (initial, *positionals, **keywords):
""" Simply sums up all the passed numbers. """
count = initial
for n in positionals:
count += n
for n in keywords:
count += keywords[n]
return count | 2df0b37ddec7e4bcdd30d302d1b7297cec0ef3cc | 15,116 |
def login_required(f):
"""Ensures user is logged in before action
Checks of token is provided in header
decodes the token then returns current user info
"""
@wraps(f)
def wrap(*args, **kwargs):
token = None
if 'x-access-token' in request.headers:
token = request.heade... | 68b36213830f9fad7f6bcf7ec5951534331c5507 | 15,117 |
def loop_to_unixtime(looptime, timediff=None):
"""Convert event loop time to standard Unix time."""
if timediff is None:
timediff = _get_timediff()
return looptime + timediff | c2da70e961a5802c2da37f04094baec2c6c88f3c | 15,118 |
def groups(column: str) -> "pli.Expr":
"""
Syntactic sugar for `pl.col("foo").agg_groups()`.
"""
return col(column).agg_groups() | 30fd3eae7abb4c47ce5d12d0c5d17184d5c25770 | 15,119 |
def filter_roidb(roidb, config):
""" remove roidb entries without usable rois """
def is_valid(entry):
""" valid images have at least 1 fg or bg roi """
overlaps = entry['max_overlaps']
fg_inds = np.where(overlaps >= config.TRAIN.FG_THRESH)[0]
bg_inds = np.where((overlaps < conf... | e93c4e2236c1febd773e216f109cd2657c94084e | 15,121 |
def seebeck_thermometry(T_Kelvin):
"""
This function returns the Seebeck coefficient of the thermocouple
concerned (by default type "E") at a certain temperature. The input of the
function is a temperature in Kelvin, but the coefficient below are for a
polynomial function with T in Celsius. The output is S in [V... | 8fca07e7e6488a98c96cc76c68d4ab1b656951e5 | 15,123 |
def correlation_permutation_test(
x, y, f, side, n=10000, confidence=0.99, plot=None, cores=1, seed=None
):
"""This function carries out Monte Carlo permutation tests comparing whether the correlation between two variables is statistically significant
:param x: An iterable of X values observed
:param y... | bc6667985d3046f5b97dd01f109c94449f044bf9 | 15,124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.