content
stringlengths 35
762k
| sha1
stringlengths 40
40
| id
int64 0
3.66M
|
---|---|---|
from cache_requests import Memoize
def test_bust_cache_reevaluates_function(redis_mock):
""":type redis_mock: mock.MagicMock"""
# LOCAL TEST HELPER
# ------------------------------------------------------------------------
def call_count():
try:
return redis_mock.get.call_count, redis_mock.set.call_count
finally:
redis_mock.reset_mock()
# LOCAL SETUP
# ------------------------------------------------------------------------
result = {
'test': 'sample text'
}
@Memoize(connection=redis_mock)
def hello(*_):
return result.get('test')
# TEST LOCAL SETUP
# ------------------------------------------------------------------------
assert call_count() == (0, 0)
# 1 get, 1 set
assert hello('hello', 'world') == 'sample text'
assert call_count() == (1, 1)
assert call_count() == (0, 0)
# TEST GETTING RESULTS FROM CACHE
# ------------------------------------------------------------------------
result['test'] = 'bad cache target'
# 1 get, 0 sets
assert hello('hello', 'world') == 'sample text'
assert call_count() == (1, 0)
# TEST BUSTING CACHE
# ------------------------------------------------------------------------
# 0 gets, 1 set
assert hello('hello', 'world', bust_cache=True) == 'bad cache target'
assert call_count() == (0, 1)
# TEST GETTING RESULTS FROM CACHE AFTER BUST
# ------------------------------------------------------------------------
# 1 get, 0 sets
assert hello('hello', 'world') == 'bad cache target'
# NO FUNNY BUSINESS
result['test'] = 'really bad cache target'
# 1 get, 0 sets
assert hello('hello', 'world') == 'bad cache target'
assert call_count() == (2, 0)
|
7d61180ea48be9985f9f861777d33e95640795e6
| 35,147 |
from scipy.sparse import csc_matrix
def read_ccs(fname):
"""
Read a CCS matrix from file into a scipy csc matrix.
This routine uses the CCS matrix files that CheSS generates.
Args:
fname (str): name of the file.
Result:
scipy.sparse.csc_matrix: the matrix in the file.
"""
data = []
indices = []
indptr = []
with open(fname, "r") as ifile:
# Read the meta data.
line = next(ifile)
split = line.split()
matdim = int(split[0])
nel = int(split[2])
split = next(ifile).split()
# Read in the index pointers.
indptr = []
indntx = [int(x) - 1 for x in split]
indptr += indntx
while len(indntx) == 10000:
split = next(ifile).split()
indntx = [int(x) - 1 for x in split]
indptr += indntx
# Read the indices.
added = 0
while(added < nel):
split = next(ifile).split()
values = [int(x) - 1 for x in split]
indices.extend(values)
added += len(values)
# Read the data
for line in ifile:
data.append(float(line))
matrix = csc_matrix((data, indices, indptr), shape=(matdim, matdim))
return matrix
|
74d893eeb7176b5dfa967fe1ad009cc64e7e9a4e
| 35,149 |
def demo__google_result_open_in_new_tab(raw_text, content_mime):
"""Force google search's result to open in new tab. to avoid iframe problem
在新标签页中打开google搜索结果
"""
def hexlify_to_json(ascii_str):
_buff = ''
for char in ascii_str:
if char in '\'\"<>&=':
_buff += r'\x' + hex(ord(char))[2:]
else:
_buff += char
_buff = _buff.replace('\\', '\\\\')
_buff = _buff.replace('/', r'\/')
return _buff
if content_mime == 'application/json':
raw_text = raw_text.replace(
hexlify_to_json('<h3 class="r"><a href="'),
hexlify_to_json('<h3 class="r"><a target="_blank" href="')
)
raw_text = raw_text.replace(
hexlify_to_json('<h3 class="r"><a class="l" href="'),
hexlify_to_json('<h3 class="r"><a target="_blank" class="l" href="')
)
else:
raw_text = raw_text.replace('<h3 class="r"><a href="', '<h3 class="r"><a target="_blank" href="')
raw_text = raw_text.replace('<h3 class="r"><a class="l" href="', '<h3 class="r"><a target="_blank" class="l" href="')
return raw_text
|
9e11f59ab66d037887c60fa0e5b636af2c5fc0c8
| 35,150 |
def to_location_via_telescope_name(self):
"""Calculate the observatory location via the telescope name.
Returns
-------
loc : `astropy.coordinates.EarthLocation`
Location of the observatory.
"""
return EarthLocation.of_site(self.to_telescope())
|
928fa0afa141dc4a974eb29ad4302b751ab4793b
| 35,151 |
def mailmangle_linked(email):
"""
Weakly obfuscates an email address using JavaScript and displays it
with a mailto link. If JS not present (i.e. what's in ``<noscript>``),
displays a link to a reCAPTCHA.
"""
encoded = _encoder(
'<a href="mailto:{0}" class="email">'
'{0}'
'</a>'
.format(email))
mh = _mailhide(email)
return mark_safe(MAIL_PAYLOAD.format(b64enc=encoded, noscript=mh))
|
b6b7a3edfd8e3f714ec3de70e428b1551f3635ac
| 35,152 |
def hamiltonian(ncomp, freq, controls):
"""Assemble hf for one spin, given a detuning freq, the control amplitudes
controls, and ncomp components of the control pulse."""
nc = 2 * ncomp + 1 # number of components in hf
hf = np.zeros((nc, 2, 2), dtype=np.complex128)
for k in range(ncomp):
# Controls are ordered in reverse compared to how they are placed in hf
a = controls[-2 * k - 2]
b = controls[-2 * k - 1]
# The controls are placed symmetrically around
# the centre of hf, so we can place them at the
# same time to save us some work!
hf[k,:,:] = np.array([[0.0, 0.25 * (1j * a + b)],
[0.25 * (1j * a - b), 0.0]])
hf[-k - 1,:,:] = np.array([[0.0, -0.25 * (1j * a + b)],
[0.25 * (-1j * a + b), 0.0]])
# Set centre (with Fourier index 0)
hf[ncomp] = np.array([[0.5 * freq, 0.0],
[0.0, -0.5 * freq]], dtype=np.complex128)
return hf
|
50d2c938319d7f817f7272761e3c29799f7b686b
| 35,153 |
def delete_database_cluster(rds_client, db_identifier):
"""Function to delete RDS instance.
Args:
rds_client (Client): AWS RDS Client object.
db_instance_identifier (str): RDS instance to delete
Returns:
bool: True if instance was deleted successfully or does not exist,
False otherwise.
Raises:
MaskopyResourceException: Exception used when trying to access a resource
that cannot be accessed.
MaskopyThrottlingException: Exception used to catch throttling from AWS.
Used to implement a back off strategy.
"""
db_cluster_identifier=db_identifier['DBClusterIdentifier']
db_instance_identifier=db_identifier['DBInstanceIdentifier']
if db_cluster_identifier.startswith('Maskopy'):
print(f"Deleting RDS cluster in destination account: {db_cluster_identifier}")
try:
rds_client.delete_db_instance(
DBInstanceIdentifier=db_instance_identifier,
SkipFinalSnapshot=True)
rds_client.delete_db_cluster(
DBClusterIdentifier=db_cluster_identifier,
SkipFinalSnapshot=True)
return True
except ClientError as err:
# Check if error code is DBSnapshotNotFound. If so, ignore the error.
if err.response['Error']['Code'] == 'DBClusterNotFound':
print(f'RDS cluster, {db_cluster_identifier}, already deleted.')
return True
# Check if error code is due to RDS not being in an available state.
if err.response['Error']['Code'] == 'InvalidDBClusterState':
print(f"{db_cluster_identifier}: RDS cluster is not in available state.")
raise MaskopyResourceException(err)
# Check if error code is due to throttling.
if err.response['Error']['Code'] == 'Throttling':
print(f"Throttling occurred when deleting database: {db_cluster_identifier}.")
raise MaskopyThrottlingException(err)
if err.response['Error']['Code'] == 'DBInstanceNotFound':
print(f'RDS instance, {db_instance_identifier}, already deleted.')
return True
# Check if error code is due to RDS not being in an available state.
if err.response['Error']['Code'] == 'InvalidDBInstanceState':
print(f"{db_instance_identifier}: RDS instance is not in available state.")
raise MaskopyResourceException(err)
print(f"Error deleting database cluster, {db_cluster_identifier}: {err.response['Error']['Code']}")
print(err)
return False
|
6469dbb722cb5f546dedbae0a228719e068b668a
| 35,154 |
def get_nbow_vecotr(word_string, label_dict):
"""
Calc nBOW vector
:param word_string:
:param label_dict:
:return:
"""
n_bow = label_dict.transform([word_string]) # nBOW vector
n_bow = n_bow.toarray().ravel()
n_bow = n_bow.astype(np.double)
n_bow /= n_bow.sum()
return n_bow
|
453a0b9754aef2742aba29f1680bc9d4b99200b6
| 35,155 |
import base64
def google_audio_settings_to_mod9(google_audio_settings):
"""
Map from Google-style audio input to Mod9 TCP server-style audio
input.
Args:
google_audio_settings (dict):
Google-style audio.
Returns:
Union[str, Iterable[bytes]]:
Mod9-style audio to pass to Mod9 ASR Engine TCP Server.
"""
if not google_audio_settings:
return None
# Require one, and only one, of 'uri' or 'content'.
if 'uri' in google_audio_settings and 'content' in google_audio_settings:
raise ConflictingGoogleAudioSettingsError("Got both 'uri' and 'content' keys.")
if 'uri' not in google_audio_settings and 'content' not in google_audio_settings:
raise KeyError("Got neither 'uri' nor 'content' key.")
if 'uri' in google_audio_settings:
mod9_audio_settings = google_audio_settings['uri']
utils.uri_exists(mod9_audio_settings)
else:
# Decode google_audio_settings byte string if Base64 encoded; send chunks in generator.
try:
byte_string = base64.b64decode(google_audio_settings['content'], validate=True)
except BinasciiError:
byte_string = google_audio_settings['content']
mod9_audio_settings = (
byte_string[i:i+CHUNKSIZE] for i in range(0, len(byte_string), CHUNKSIZE)
)
return mod9_audio_settings
|
65e81e26316201e0032db68ad4cad161e93fc69b
| 35,156 |
def get_sequence_lengths(sequence_batch: Array, eos_id: int) -> Array:
"""Returns the length of each one-hot sequence, including the EOS token."""
# sequence_batch.shape = (batch_size, seq_length, vocab_size)
eos_row = sequence_batch[:, :, eos_id]
eos_idx = jnp.argmax(eos_row, axis=-1) # returns first occurrence
# `eos_idx` is 0 if EOS is not present, so we use full length in that case.
return jnp.where(
eos_row[jnp.arange(eos_row.shape[0]), eos_idx],
eos_idx + 1,
sequence_batch.shape[1] # if there is no EOS, use full length
)
|
7db2c66c19ad08033126773d8575bac2ee62654d
| 35,157 |
def Shift(parent, shift, da_mode="nearest", constant=0.0, name=""):
"""\
Shift the input image.
:param parent: parent layer
:param shift: list of maximum absolute fraction for the horizontal and
vertical translations
:param da_mode: one of "nearest", "constant"
:param constant: fill value for the area outside the resized image, used
for all channels
:return: Shift layer
"""
return _eddl.Shift(parent, shift, da_mode, constant, name)
|
8b7d4aa4909bab9dd937d2df03e937c87dcfcf21
| 35,159 |
def iterations_for_terms(terms):
"""
Parameters
----------
terms : int
Number of terms in the singular value expansion.
Returns
-------
Int
The number of iterations of the power method needed to produce
reasonably good image qualit for the given number of terms in the singular value expansion.
By "reasonably good" we mean that using larger number of terms will not produce noticeably
better image, thus it is wasteful.
"""
if terms <= 20:
return 10
if terms <= 50:
return 5
if terms <= 100:
return 3
return 1
|
4142d8325f132e16e0525c36d114dd989873870f
| 35,160 |
def explained_variance(y_pred, y):
"""
Returns 1 - Var[y - y_pred] / Var[y]
"""
assert y.ndim == 1 and y_pred.ndim == 1
variance = np.var(y)
return np.nan if variance == 0 else 1 - np.var(y - y_pred) / variance
|
80ea05c9d83f3d48cfe49a038b81f9712a04df16
| 35,161 |
import itertools
def get_3d_points_from_multiple_observation(candidate_sets, camera_matrixs, fundamental_matrixs, threshold_sv = 15.0):
"""
param candidate_sets : [[np.array{2}, ...], ...] list of candidate sets(list) in cameras
param camera_matrixs : np.array{ v x 3 x 4 }
return : [np.array{3}, ...] the corresponding points in 3d space
"""
for candidate_set in candidate_sets:
candidate_set.append(None)
combinations = list(itertools.product(*candidate_sets))
combinations = [(combination, len([combination[i] for i in range(len(combination)) if combination[i] != None])) for combination in combinations]
combinations = sorted(combinations, key=itemgetter(1), reverse = True)
combinations = [combination[0] for combination in combinations]
combinations_used = []
res = []
for combination in combinations:
combination_valid = [combination[i] for i in range(len(combination)) if combination[i] != None]
if len(combination_valid) >= 2:
isSubset = False
for combination_used in combinations_used: #if not subset of previous
isSubset = True
for pt_tgt, pt_used in zip(combination, combination_used):
if pt_tgt != pt_used and not pt_tgt == None:
isSubset = False
break
if isSubset:
break
# if not isSubset:
# idx_valid = np.array([i for i in range(len(combination)) if combination[i] != None])
# combination_valid = [combination[i] for i in idx_valid]
# camera_matrixs_valid = camera_matrixs[idx_valid]
# if test_epipolar_constraints(np.vstack(combination_valid), fundamental_matrixs, idx_valid):
# xyz, s = get_triangulation(np.vstack(combination_valid), camera_matrixs_valid)
# s /= len(camera_matrixs_valid)
# if s < threshold_sv and np.all(is_front_of_view(xyz, camera_matrixs_valid)):
# combinations_used.append(combination)
# res.append(xyz)
if not isSubset:
camera_matrixs_valid = np.array([camera_matrixs[i] for i in range(len(combination)) if combination[i] != None])
xyz, s = get_triangulation(np.vstack(combination_valid), camera_matrixs_valid)
s /= len(camera_matrixs_valid) # to reward points with many views
if s < threshold_sv and np.all(is_front_of_view(xyz, camera_matrixs_valid)):
combinations_used.append(combination)
res.append(xyz)
return res
|
3e1171c798c0ab7f0a587d94ff262d9fafda4b8a
| 35,162 |
def get_macro(macro_name):
"""
Get the configured macro
:param macro_name: The name of the macro to add
:return: The macro itself in string form
"""
return MACROS[macro_name]
|
624bc6912ce1d32d68ffd11c029b6c84e2bf563f
| 35,163 |
def part_1(input_data: str) -> int:
"""What do you get if you multiply your final horizontal position by your final depth?
Returns:
int: [final horizontal position * final depth]
"""
h_pos, depth = 0, 0 # Your horizontal position and depth both start at 0.
commands = parse_input(input_data)
for command, value in commands:
if command == "forward":
h_pos += value
elif command == "up":
depth -= value
elif command == "down":
depth += value
else:
print(f"ERROR: unrecognised command ({command})")
break
return h_pos * depth
|
4ae988405c568d8f409935dee1eb6413fc68e8a5
| 35,164 |
def preprocess_image(img, cam_values):
"""
Function to prepare image for lane extraction:
1. undistort image
2. crop a region of interest
3. convert image to hsv
4. Get binary gradient image using sobel
5. transfer binary image using the roi
Args:
img ([type]): [description]
"""
#define a vertices which includes the lane
vertices = np.array([[
((img.shape[1]/2 - 80),img.shape[0]/1.59),
((img.shape[1]/2 + 80),img.shape[0]/1.59),
((img.shape[1] - 150 ),img.shape[0] - 40),
(0 + 225,img.shape[0] - 40)]], dtype=np.int32)
#define a destination vertice to warp the image
dst = np.array([[
(95, 0),
((img.shape[1] -95),0),
((img.shape[1] - 265),img.shape[0]),
(265,img.shape[0])]], dtype=np.int32)
undist = cv2.undistort(img, cam_values['mtx'], cam_values['dist'], None, cam_values['mtx'])
# cv2.imwrite('undist.png', undist)
bin_image_thresh = abs_sobel_thresh(undist, orient='x', thresh_min = 10, thresh_max = 100)
# cv2.imwrite('bin_image_sobel.png', bin_image_thresh*255)
bin_image_hls = svalues_mask(undist, s_min = 120, s_max = 255)
# cv2.imwrite('bin_image_hls.png', bin_image_hls*255)
#combine both bin images
bin_image = np.zeros_like(bin_image_thresh)
bin_image[(bin_image_thresh == 1) | (bin_image_hls == 1)] = 1
cv2.imwrite('bin_image.png', bin_image*255)
bin_image_crop = region_of_interest(bin_image, vertices)
# cv2.imwrite('bin_image_cropped.png', bin_image_crop*255)
src = np.float32([[vertices[0][0]],[vertices[0][1]], [vertices[0][2]],[vertices[0][3]]])
bin_image_warped = warp_perpsective(bin_image_crop, src, np.float32(dst))
# cv2.imwrite('bin_image_warp.png', bin_image_warped*255)
#get inverse matrix to ba able to recalulate the found lines/points of the warped image
Minv = cv2.getPerspectiveTransform(np.float32(dst), src)
return undist, bin_image_warped, Minv
|
b4d132144629de64c4556c9f16fa16ce9a54a23d
| 35,165 |
import struct
import tqdm
def init_compress_eigerdata(
images,
mask,
md,
filename,
bad_pixel_threshold=1e15,
hot_pixel_threshold=2 ** 30,
bad_pixel_low_threshold=0,
nobytes=4,
bins=1,
with_pickle=True,
reverse=True,
rot90=False,
direct_load_data=False,
data_path=None,
images_per_file=100,
):
"""
Compress the eiger data
Create a new mask by remove hot_pixel
Do image average
Do each image sum
Find badframe_list for where image sum above bad_pixel_threshold
Generate a compressed data with filename
if bins!=1, will bin the images with bin number as bins
Header contains 1024 bytes ['Magic value', 'beam_center_x', 'beam_center_y', 'count_time', 'detector_distance',
'frame_time', 'incident_wavelength', 'x_pixel_size', 'y_pixel_size',
bytes per pixel (either 2 or 4 (Default)),
Nrows, Ncols, Rows_Begin, Rows_End, Cols_Begin, Cols_End ]
Return
mask
avg_img
imsum
bad_frame_list
"""
fp = open(filename, "wb")
# Make Header 1024 bytes
# md = images.md
if bins != 1:
nobytes = 8
if "count_time" not in list(md.keys()):
md["count_time"] = 0
if "detector_distance" not in list(md.keys()):
md["detector_distance"] = 0
if "frame_time" not in list(md.keys()):
md["frame_time"] = 0
if "incident_wavelength" not in list(md.keys()):
md["incident_wavelength"] = 0
if "y_pixel_size" not in list(md.keys()):
md["y_pixel_size"] = 0
if "x_pixel_size" not in list(md.keys()):
md["x_pixel_size"] = 0
if "beam_center_x" not in list(md.keys()):
md["beam_center_x"] = 0
if "beam_center_y" not in list(md.keys()):
md["beam_center_y"] = 0
if not rot90:
Header = struct.pack(
"@16s8d7I916x",
b"Version-COMP0001",
md["beam_center_x"],
md["beam_center_y"],
md["count_time"],
md["detector_distance"],
md["frame_time"],
md["incident_wavelength"],
md["x_pixel_size"],
md["y_pixel_size"],
nobytes,
md["pixel_mask"].shape[1],
md["pixel_mask"].shape[0],
0,
md["pixel_mask"].shape[1],
0,
md["pixel_mask"].shape[0],
)
else:
Header = struct.pack(
"@16s8d7I916x",
b"Version-COMP0001",
md["beam_center_x"],
md["beam_center_y"],
md["count_time"],
md["detector_distance"],
md["frame_time"],
md["incident_wavelength"],
md["x_pixel_size"],
md["y_pixel_size"],
nobytes,
md["pixel_mask"].shape[0],
md["pixel_mask"].shape[1],
0,
md["pixel_mask"].shape[0],
0,
md["pixel_mask"].shape[1],
)
fp.write(Header)
Nimg_ = len(images)
avg_img = np.zeros_like(images[0], dtype=np.float)
Nopix = float(avg_img.size)
n = 0
good_count = 0
frac = 0.0
if nobytes == 2:
dtype = np.int16
elif nobytes == 4:
dtype = np.int32
elif nobytes == 8:
dtype = np.float64
else:
print("Wrong type of nobytes, only support 2 [np.int16] or 4 [np.int32]")
dtype = np.int32
Nimg = Nimg_ // bins
time_edge = np.array(create_time_slice(N=Nimg_, slice_num=Nimg, slice_width=bins))
imgsum = np.zeros(Nimg)
if bins != 1:
print("The frames will be binned by %s" % bins)
for n in tqdm(range(Nimg)):
t1, t2 = time_edge[n]
img = np.average(images[t1:t2], axis=0)
mask &= img < hot_pixel_threshold
p = np.where((np.ravel(img) > 0) & np.ravel(mask))[0] # don't use masked data
v = np.ravel(np.array(img, dtype=dtype))[p]
dlen = len(p)
imgsum[n] = v.sum()
if (imgsum[n] > bad_pixel_threshold) or (imgsum[n] <= bad_pixel_low_threshold):
# if imgsum[n] >=bad_pixel_threshold :
dlen = 0
fp.write(struct.pack("@I", dlen))
else:
np.ravel(avg_img)[p] += v
good_count += 1
frac += dlen / Nopix
# s_fmt ='@I{}i{}{}'.format( dlen,dlen,'ih'[nobytes==2])
fp.write(struct.pack("@I", dlen))
fp.write(struct.pack("@{}i".format(dlen), *p))
if bins == 1:
if nobytes != 8:
fp.write(struct.pack("@{}{}".format(dlen, "ih"[nobytes == 2]), *v))
else:
fp.write(struct.pack("@{}{}".format(dlen, "dd"[nobytes == 2]), *v))
else:
fp.write(struct.pack("@{}{}".format(dlen, "dd"[nobytes == 2]), *v))
# n +=1
fp.close()
frac /= good_count
print("The fraction of pixel occupied by photon is %6.3f%% " % (100 * frac))
avg_img /= good_count
bad_frame_list = np.where(
(np.array(imgsum) > bad_pixel_threshold)
| (np.array(imgsum) <= bad_pixel_low_threshold)
)[0]
# bad_frame_list1 = np.where( np.array(imgsum) > bad_pixel_threshold )[0]
# bad_frame_list2 = np.where( np.array(imgsum) < bad_pixel_low_threshold )[0]
# bad_frame_list = np.unique( np.concatenate( [bad_frame_list1, bad_frame_list2]) )
if len(bad_frame_list):
print("Bad frame list are: %s" % bad_frame_list)
else:
print("No bad frames are involved.")
if with_pickle:
pkl.dump([mask, avg_img, imgsum, bad_frame_list], open(filename + ".pkl", "wb"))
return mask, avg_img, imgsum, bad_frame_list
|
71d60adabb48e1b6566e7888dbeca06d54647d88
| 35,166 |
import re
def parseTomEval(inFile, strand):
"""parse the tomtotm.txt file and return a dict of e-values between motifs """
#dict between query and target Ids
matchDict = {}
#read the tomtom.txt file and see if any known are found
with open(inFile, 'rb') as handler:
for line in handler:
line = line.strip()
if re.search(r'Query', line):
continue
#skip if the target is reverse compliment
lineSplit = line.split('\t')
#when making the dict, the targets are usually motif IDs as digits so check them, otherwise they are strings/names
if lineSplit[0].isdigit():
query = int(lineSplit[0])
else:
query = lineSplit[0]
if lineSplit[1].isdigit():
target = int(lineSplit[1])
else:
target = lineSplit[1]
eVal = float(lineSplit[4])
overlap = int(lineSplit[6])
strand = lineSplit[9]
#if strand != '+':
#continue
if query not in matchDict:
matchDict[query] = {}
if target not in matchDict[query] and target != query:
matchDict[query][target]=eVal
#for query in matchDict:
#print 'query:', query
#for target in matchDict[query]:
#print '\ttarget:', target,'eval:', matchDict[query][target]
return matchDict
|
d9394111d35444199f93bf97e7de606d919b9bb3
| 35,167 |
from typing import Dict
from typing import Union
from pathlib import Path
import tqdm
import warnings
def prepare_peoples_speech(
corpus_dir: Pathlike,
output_dir: Pathlike,
) -> Dict[str, Union[RecordingSet, SupervisionSet]]:
"""
Prepare :class:`~lhotse.RecordingSet` and :class:`~lhotse.SupervisionSet` manifests
for The People's Speech.
The metadata is read lazily and written to manifests in a stream to minimize
the CPU RAM usage. If you want to convert this data to a :class:`~lhotse.CutSet`
without using excessive memory, we suggest to call it like::
>>> peoples_speech = prepare_peoples_speech(corpus_dir=..., output_dir=...)
>>> cuts = CutSet.from_manifests(
... recordings=peoples_speech["recordings"],
... supervisions=peoples_speech["supervisions"],
... output_path=...,
... lazy=True,
... )
:param corpus_dir: Pathlike, the path of the main data dir.
:param output_dir: Pathlike, the path where to write the manifests.
:return: a dict with keys "recordings" and "supervisions" with lazily opened manifests.
"""
corpus_dir = Path(corpus_dir)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
recs_path = output_dir / "peoples-speech_recordings_all.jsonl.gz"
sups_path = output_dir / "peoples-speech_supervisions_all.jsonl.gz"
if recs_path.is_file() and sups_path.is_file():
# Nothing to do: just open the manifests in lazy mode.
return {
"recordings": RecordingSet.from_jsonl_lazy(recs_path),
"supervisions": SupervisionSet.from_jsonl_lazy(sups_path),
}
exist = 0
tot = 0
err = 0
with RecordingSet.open_writer(recs_path,) as rec_writer, SupervisionSet.open_writer(
sups_path,
) as sup_writer:
for item in tqdm(
# Note: People's Speech manifest.json is really a JSONL.
load_jsonl(corpus_dir / "manifest.json"),
desc="Converting People's Speech manifest.json to Lhotse manifests",
):
for duration_ms, text, audio_path in zip(*item["training_data"].values()):
full_path = corpus_dir / audio_path
tot += 1
if not full_path.exists():
# If we can't find some data, we'll just continue and some items
# were missing later.
continue
exist += 1
try:
audio_info = info(full_path)
duration = duration_ms / 1000
r = Recording(
id=full_path.stem,
sampling_rate=audio_info.samplerate,
num_samples=compute_num_samples(
duration, audio_info.samplerate
),
duration=duration,
sources=[
AudioSource(
type="file",
channels=[0],
source=str(full_path),
)
],
)
s = SupervisionSegment(
id=r.id,
recording_id=r.id,
start=0,
duration=r.duration,
channel=0,
text=text,
language="English",
custom={"session_id": item["identifier"]},
)
validate_recordings_and_supervisions(recordings=r, supervisions=s)
rec_writer.write(r)
sup_writer.write(s)
except Exception as e:
# If some files are missing (e.g. somebody is working on a subset
# of 30.000 hours), we won't interrupt processing; we will only
# do so for violated assertions.
if isinstance(e, AssertionError):
raise
err += 1
continue
if exist < tot or err > 0:
warnings.warn(
f"We finished preparing The People's Speech Lhotse manifests. "
f"Out of {tot} entries in the original manifest, we found {exist} "
f"audio files existed, out of which {err} had errors during processing."
)
return {
"recordings": rec_writer.open_manifest(),
"supervisions": sup_writer.open_manifest(),
}
|
48605c9511824a5fbe0e130fa4df0368228a8d0a
| 35,168 |
def process_edit_distances(mx, reference_counter, reference_values, search_values):
"""Extract search values that has minimum edit distance from reference values. Multiple hits are enabled."""
min_distances = mx.min(axis=1)
matches = []
for i in range(mx.shape[0]):
min_dist = min_distances[i]
min_indices = np.argwhere(mx[i,:] == min_dist)
min_indices = list(min_indices[:,0])#convert array to column
for idx in min_indices:
reference, min_match = reference_values[i], search_values[idx]
matches.append((reference, reference_counter[reference], min_match, min_dist))
return matches
|
87ea6d8adfd6810c8aa56eb248bb3126acf25022
| 35,169 |
def get_jobs():
"""Get a list of jobs"""
query = "SELECT * FROM urls"
result = db.execute(query)
return jsonify(result)
|
03b2987a8a11c88b493c6e6e435434b96e0741db
| 35,170 |
def get_leaf_nodes(struct):
""" Get the list of leaf nodes.
"""
leaf_list = []
for idx, node in enumerate(struct):
if node['is_leaf']:
leaf_list.append(idx)
return leaf_list
|
90c66e49bac0c49ef5d2c75b4c1cbe6f4fdd4b83
| 35,171 |
def cg_build_w_env(A, B, i):
""" Build the environment for constructing the ith HOTRG isometry
for A and B.
"""
A_indices1 = [1,2,3,4,5,-11]
A_indices2 = [1,2,3,4,5,-12]
A_indices1[i] = -1
A_indices2[i] = -2
A2 = ncon((A, A.conjugate()), (A_indices1, A_indices2))
B_indices1 = [1,2,3,4,-11,6]
B_indices2 = [1,2,3,4,-12,6]
B_indices1[i] = -1
B_indices2[i] = -2
B2 = ncon((B, B.conjugate()), (B_indices1, B_indices2))
env = ncon((A2, B2), ([-1,-11,1,2], [-2,-12,1,2]))
return env
|
4ea4e660dc1dc95cebcb2612c1d9a46d0d7d85ac
| 35,172 |
def get_node_edge(docs, w2d_score, d2d_score):
"""
:param docs:
:param w2d_score:
:param d2d_score:
:return:
"""
wid2wnid = {}
w_id, d_idx = [], []
w_d_wnid, w_d_dnid = [], []
w_d_feat = {"score": [], 'dtype': []}
d_d_dnid1, d_d_dnid2 = [], []
d_d_feat = {"score": [], 'dtype': []}
wnid, dnid = 0, 0
for di, (_, wd_scores) in enumerate(zip(docs, w2d_score)):
for wid, wd_score in wd_scores.items():
if wid not in wid2wnid:
wid2wnid[wid] = wnid
w_id.append(wid)
wnid += 1
w_d_wnid.append(wid2wnid[wid])
w_d_dnid.append(dnid)
w_d_feat["score"].append(wd_score)
w_d_feat["dtype"].append(0)
d_idx.append(di)
dnid += 1
if di > 0:
d_d_dnid1.append(0)
d_d_dnid2.append(di)
# d_d_feat["score"].append(max(0, min(round(math.log(d2d_score[di-1])), 9)))
d_d_feat["score"].append(d2d_score[di - 1])
d_d_feat["dtype"].append(1)
utils = {"w_id": w_id,
"d_idx": d_idx,
"w_d_wnid": w_d_wnid,
"w_d_dnid": w_d_dnid,
"w_d_feat": w_d_feat,
"d_d_dnid1": d_d_dnid1,
"d_d_dnid2": d_d_dnid2,
"d_d_feat": d_d_feat
}
return utils
|
40e4d0a11fdd671971319ae8d463ad94a7e3ca9a
| 35,173 |
def get_elixier_org_by_id_local(id_local):
""" ..liefert den zu id_local passenden Datensatz """
items = DmsElixierOrg.objects.filter(id_local=id_local)
if len(items) > 0:
return items[0]
else:
return None
|
fdecff1dbc8cda34da994b87fb197b1c88515a75
| 35,174 |
def nearest_approach_to_any_vehicle(traj, vehicles):
"""
Calculates the closest distance to any vehicle during a trajectory.
"""
closest = 999999
for v in vehicles.values():
d = nearest_approach(traj, v)
if d < closest:
closest = d
return closest
|
de09f23d0886f48ce34c455a41f12c0bb435d216
| 35,175 |
def getAllQuery():
""" This will get all the records in the userQuery table
"""
rows = []
with engine.begin() as conn:
sel = userQuery.select()
rows = conn.execute(sel).fetchall()
return rows
|
d7800ea523877e930f7e0e0d4c4d70e70ad608ca
| 35,176 |
def testingParameters(cal_file = None):
"""
Create a Spliner parameters object.
"""
params = parameters.ParametersSpliner()
params.setAttr("max_frame", "int", -1)
params.setAttr("start_frame", "int", -1)
params.setAttr("background_sigma", "float", 8.0)
if cal_file is not None:
params.setAttr("camera_calibration", "filename", cal_file)
else:
params.setAttr("camera_gain", "float", settings.camera_gain)
params.setAttr("camera_offset", "float", settings.camera_offset)
params.setAttr("find_max_radius", "int", 5)
params.setAttr("fit_error_model", "string", settings.fit_error_model)
params.setAttr("iterations", "int", settings.iterations)
params.setAttr("no_fitting", "int", 0)
params.setAttr("pixel_size", "float", settings.pixel_size)
params.setAttr("sigma", "float", 1.5)
params.setAttr("spline", "filename", "psf.spline")
params.setAttr("threshold", "float", 6.0)
# Don't do tracking.
params.setAttr("descriptor", "string", "1")
params.setAttr("radius", "float", "0.0")
# Don't do drift-correction.
params.setAttr("d_scale", "int", 2)
params.setAttr("drift_correction", "int", 0)
params.setAttr("frame_step", "int", 500)
params.setAttr("z_correction", "int", 0)
# 'peak_locations' testing.
if hasattr(settings, "peak_locations") and (settings.peak_locations is not None):
params.setAttr("peak_locations", "filename", settings.peak_locations)
return params
|
fbd5c4a20ce036274bf221d4fb9e16933b94d332
| 35,177 |
def fetch_labels(k, kmeans_history, offset=-1):
"""This fetches the original edges of a hierarchical mean.
"""
labels = kmeans_history[1]
passes = labels.shape[0]
indices = np.array([k])
for i in range(offset, -(passes + 1), -1):
try:
indices = np.array([np.nonzero(labels[i] == j)[0]
for j in indices])
indices = np.hstack(indices)
except IndexError:
return np.array(indices)
return indices
|
b6752505be9cd6b2c849a79ef9e7f9ef6528651f
| 35,178 |
def _reshape(t: 'Tensor', shape) -> 'Tensor':
"""
Also see
---------
:param t:
:param shape:
:return:
"""
data = t.data.reshape(shape)
requires_grad = t.requires_grad
if requires_grad:
def grad_f(grad: 'np.ndarray') -> 'np.ndarray':
return grad.reshape(t.shape)
depends_on = [Dependency(tensor = t, grad_fn = grad_f)]
else:
depends_on = []
return Tensor(data,
requires_grad,
depends_on)
|
46677d4bbe6fb384fa1759b8c7e08ae481bba5e7
| 35,179 |
from datetime import datetime
def get_target_month(month_count, utc_now=None):
"""
Return datetime object for number of *full* months older than
`month_count` from now, or `utc_now`, if provided.
:arg month_count: Number of *full* months
:arg utc_now: Used for testing. Overrides current time with specified time.
:rtype: Datetime object
"""
utc_now = date(utc_now.year, utc_now.month, 1) if utc_now else date.today()
target_date = date(utc_now.year, utc_now.month, 1)
if month_count < 0:
for i in range(0, month_count, -1):
if target_date.month == 12:
target_date = date(target_date.year+1, 1, 1)
else:
target_date = date(target_date.year, target_date.month+1, 1)
else:
for i in range(0, month_count):
if target_date.month == 1:
target_date = date(target_date.year-1, 12, 1)
else:
target_date = date(target_date.year, target_date.month-1, 1)
return datetime(target_date.year, target_date.month, target_date.day)
|
c2a8f79add91cb176d537cf7a523f70d8c3ec2c2
| 35,180 |
from datetime import datetime
def mark_notifications_read(db: orm.Session = Depends(get_db)):
"""Mark all the notifications as read
Returns:
List of schema.Notification: A list of all the notifications updated to read
"""
notifications = db.query(model.Notification).all()
for notification in notifications:
if notification.has_read:
pass
else:
notification.has_read = True
notification.last_updated = datetime.utcnow()
db.commit()
db.refresh(notification)
return list(map(schema.Notification.from_orm, notifications))
|
bb659f1d5676c9442aba4a0bc00c810f51493bad
| 35,181 |
import copy
def created_task(result, status=202, mimetype='application/vnd.task-v1+json',
headers={}):
"""
Created response for celery result by creating a task representation and
adding a link header.
:param result:
:type result: AsyncResult
:param status: Http status code. Defaults to 202 (Accepted) as celery
executes task asynchronously.
:type status: int
:param mimetype: Response mimetype. Defaults to
'application/vnd.task-v1+json'
:type mimetype: str
:param headers: Dictionary containing http headers. By default, Location
header is added.
:type headers: dict
:return: Tuple containing Flask Response, Status code, Http headers.
:rtype: tuple
"""
headers = copy.deepcopy(headers or {})
task_id = str(result)
headers.setdefault('Location', url_for('.tasks', id=task_id))
output = {
'task_id': task_id
}
return build_response(output, status=status, mimetype=mimetype,
headers=headers)
|
ef56fdb129585e5b078bc20a0a449204c75705d7
| 35,182 |
def _get_dir_list(names):
"""This function obtains a list of all "named"-directory [name1-yes_name2-no, name1-no_name2-yes, etc]
The list's building occurs dynamically, depending on your list of names (and its order) in config.yaml.
The entire algorithm is described in "img" in the root directory and in the Readme.md.
:param names: the names of judges, they have to be in the same order as they arranged in a filename.
For example: if a file calls "name1-yes_name2-no_", therefore the name's list looks like [name1, name2]
:return: list of compiled directories.
"""
# Number of columns
n = len(names)
# Number of lines
num_lines = 2**n
# fill the result with '\0'
dir_list = ['' for i in range(num_lines)]
# In our case a name represents a column.
for name in names:
column_index = names.index(name)
# The partition_index is the cue when we should to switch 0 to 1 (no to yes) and vise versa.
partition_index = num_lines / (2**(column_index + 1))
# yes_mode means that we add '-yes_' up to a name, otherwise add '-no_'.
yes_mode = True
line = 0
while line < num_lines:
path_part = name
# Switch the mode to the opposite one.
if line % partition_index == 0:
yes_mode = not yes_mode
# Sets a decision to a name
if not yes_mode:
path_part += '-no_'
else:
path_part += '-yes_'
# Add a path's part (column by column) to the list
dir_list[line] += path_part
line += 1
return dir_list
|
284c328878c2c8d0e0ae273c140798e2884ef13f
| 35,183 |
def mapCardToImagePath(card):
"""
Given a card, return the relative path to its image
"""
if card == "01c":
return 'src/imgs/2C.png'
if card == "02c":
return 'src/imgs/3C.png'
if card == "03c":
return 'src/imgs/4C.png'
if card == "04c":
return 'src/imgs/5C.png'
if card == "05c":
return 'src/imgs/6C.png'
if card == "06c":
return 'src/imgs/7C.png'
if card == "07c":
return 'src/imgs/8C.png'
if card == "08c":
return 'src/imgs/9C.png'
if card == "09c":
return 'src/imgs/10C.png'
if card == "10c":
return 'src/imgs/JC.png'
if card == "11c":
return 'src/imgs/QC.png'
if card == "12c":
return 'src/imgs/KC.png'
if card == "13c":
return 'src/imgs/AC.png'
if card == "01d":
return 'src/imgs/2D.png'
if card == "02d":
return 'src/imgs/3D.png'
if card == "03d":
return 'src/imgs/4D.png'
if card == "04d":
return 'src/imgs/5D.png'
if card == "05d":
return 'src/imgs/6D.png'
if card == "06d":
return 'src/imgs/7D.png'
if card == "07d":
return 'src/imgs/8D.png'
if card == "08d":
return 'src/imgs/9D.png'
if card == "09d":
return 'src/imgs/10D.png'
if card == "10d":
return 'src/imgs/JD.png'
if card == "11d":
return 'src/imgs/QD.png'
if card == "12d":
return 'src/imgs/KD.png'
if card == "13d":
return 'src/imgs/AD.png'
if card == "01s":
return 'src/imgs/2S.png'
if card == "02s":
return 'src/imgs/3S.png'
if card == "03s":
return 'src/imgs/4S.png'
if card == "04s":
return 'src/imgs/5S.png'
if card == "05s":
return 'src/imgs/6S.png'
if card == "06s":
return 'src/imgs/7S.png'
if card == "07s":
return 'src/imgs/8S.png'
if card == "08s":
return 'src/imgs/9S.png'
if card == "09s":
return 'src/imgs/10S.png'
if card == "10s":
return 'src/imgs/JS.png'
if card == "11s":
return 'src/imgs/QS.png'
if card == "12s":
return 'src/imgs/KS.png'
if card == "13s":
return 'src/imgs/AS.png'
if card == "01h":
return 'src/imgs/2H.png'
if card == "02h":
return 'src/imgs/3H.png'
if card == "03h":
return 'src/imgs/4H.png'
if card == "04h":
return 'src/imgs/5H.png'
if card == "05h":
return 'src/imgs/6H.png'
if card == "06h":
return 'src/imgs/7H.png'
if card == "07h":
return 'src/imgs/8H.png'
if card == "08h":
return 'src/imgs/9H.png'
if card == "09h":
return 'src/imgs/10H.png'
if card == "10h":
return 'src/imgs/JH.png'
if card == "11h":
return 'src/imgs/QH.png'
if card == "12h":
return 'src/imgs/KH.png'
if card == "13h":
return 'src/imgs/AH.png'
else:
return 'INVALID CARD'
|
f2a8d4918b26617335a274a536a0569c845cb526
| 35,184 |
from typing import Optional
def update_partition(chain_parent_in: list, job_id: str, partition_name: str) -> Optional[dict]:
"""
NOTE: This task is part of a chain(). At very first, it is evaluated if the previous tasks contain any errors.
:param chain_parent_in: Output of parent task.
:param job_id:
:param partition_name:
:return:
"""
fac = utilities.HookFactory()
glue_hook = fac.create(type_hook='glue').create_client(custom_region='eu-central-1')
sync_athena = PermitsAthena(current_uuid=job_id)
table_info = None
# -------------------- STEP 1: Verify head_object and target stack resources are valid----------
for response in chain_parent_in:
if 'error' in response.keys():
table_info = {'error': 'CustomTaskException',
'message': 'Source file or target not valid. Update partition failed.'}
return table_info
try:
glue_tbl_r = glue_hook.get_table(DatabaseName=sync_athena.permits_database,
Name=sync_athena.permits_table)
# logger.info(f"glue_table: {glue_tbl_r}")
except ClientError as e:
table_info = {'error': str(e)}
return table_info
else:
table_info = glue_tbl_r
# -------------------- STEP 2: Verify that partition does not exist-----------------------------
try:
get_glue_part_r = glue_hook.get_partition(DatabaseName=sync_athena.permits_database,
TableName=sync_athena.permits_table,
# PartitionValues=['2019-09-07'])
PartitionValues=[f"{partition_name}"])
logger.info(f"table_info: {table_info}, \t partition_name: {partition_name}, \t glue_partition: {get_glue_part_r}")
except ClientError as e:
logger.info(f"message: partitiontime='{partition_name}' not found. Create new partition '{partition_name}'")
if 'GetPartition operation: Cannot find partition.' in str(e):
# ------------- STEP 3: Parsing table info required to create partitions from table----
try:
part_input_dict = {'Values': [f'{partition_name}'],
'StorageDescriptor': {
'Location': f"{table_info['Table']['StorageDescriptor']['Location']}/partitiontime={partition_name}/",
'InputFormat': table_info['Table']['StorageDescriptor']['InputFormat'],
'OutputFormat': table_info['Table']['StorageDescriptor']['OutputFormat'],
'SerdeInfo': table_info['Table']['StorageDescriptor']['SerdeInfo']
}}
# partition_keys = table_info['Table']['PartitionKeys']
except KeyError as e:
table_info = {'error': str(e), 'message': 'Could not retrieve Keys from Glue::Table.'}
except BaseException as e:
table_info = {'error': 'Unexpected error', 'message': str(e)}
else:
# ------- STEP 4: Create new partition----------------------------------------
try:
create_glue_part_r = glue_hook.create_partition(DatabaseName=sync_athena.permits_database,
TableName=sync_athena.permits_table,
PartitionInput=part_input_dict)
except ClientError as e:
table_info = {'error': 'Unexpected error when creating partition', 'message': str(e)}
except BotoCoreError as e:
logger.info(f"Unknown BotoCoreError: {e}")
table_info = {'error': str(e)}
else:
get_part_info = create_glue_part_r
logger.info(f"Create new partition: {get_part_info}")
finally:
if table_info is not None:
return table_info
else:
return {'error': 'UnknownError.', 'message': 'Unable to retrieve table information.'}
except BotoCoreError as e:
logger.info(f"Unknown BotoCoreError: {e}")
return {'error': str(e)}
else:
return table_info
|
72aa1ba409cb83d179cc178daad7677db6f17504
| 35,185 |
def consolidate_gauge(df):
""" takes in gauge columns and normalizes them all to stiches per inch """
try:
df['gauge_per_inch'] = df.loc[:,'gauge']/df.loc[:,'gauge_divisor']
except:
print("Error occured when consolidating gauge")
return df
|
a3a1eecec97b521c19bc50f2d1496f1aba9fbce6
| 35,187 |
import time
def parse_data(driver):
"""Return a float of the current price given the driver open to the TMX page of the specific symbol."""
# The driver needs time to load the page before it can be parsed.
time.sleep(5)
content_obj = driver.find_element(by="id", value="root")
content_text = content_obj.text
price_string = content_text.split("PRICE")[1].split("CHANGE")[0].strip()
try:
price_float = float(price_string.replace("$", "").replace(",", ""))
return price_float
except ValueError as e:
raise e
|
289a71909753278336c414a0b3c3854aeb60b05f
| 35,188 |
def grab_images_and_videos(adir):
"""Grabs image and video files
Args:
adir: directory with images
Returns:
files: image and video files
"""
return grab_images(adir) + grab_videos(adir)
|
6acf0559c8e26dde8b179e170693210bc72b43de
| 35,189 |
def _get_default_siaf(instrument, aper_name):
"""
Create instance of pysiaf for the input instrument and aperture
to be used later to pull SIAF values like distortion polynomial
coefficients and rotation.
Parameters
----------
instrument : str
The name of the instrument
aper_name : str
The name of the specific instrument aperture
Returns
-------
aper : instance of pysiaf
"""
# Create new naming because SIAF requires special capitalization
if instrument == "NIRCAM":
siaf_name = "NIRCam"
elif instrument == "NIRSPEC":
siaf_name = "NIRSpec"
else:
siaf_name = instrument
# Select a single SIAF aperture
siaf = pysiaf.Siaf(siaf_name)
aper = siaf.apertures[aper_name]
return aper
|
d0b4d72d8bd1323521552452a8531a5339c26f56
| 35,191 |
def add_shift_steps_unbalanced(
im_label_list_all, shift_step=0):
"""
Appends a fixed shift step to each large image (ROI)
Args:
im_label_list_all - list of tuples of [(impath, lblpath),]
Returns:
im_label_list_all but with an added element to each tuple (shift step)
"""
return [(j[0], j[1], shift_step) for j in im_label_list_all]
|
63fc45bc14e54ec5af473ec955bd45602f3c7041
| 35,192 |
def load_img_embeddings(source_file):
""" Load image embeddings saved as pickle file
:param source_file: The pickle file where the embeddings are stored
:return: a list of image embeddings
"""
img_embeddings = load_pickle_file(source_file)
img_embed = list(img_embeddings.values())
img_embed = np.array(img_embed)
img_embed = img_embed.reshape((img_embed.shape[0], img_embed.shape[2]))
return img_embed
|
775b965d9b90a4aed4e5d68658d9877ca3a24c81
| 35,193 |
def are_aabb_colliding(a, b):
"""
Return True if given AABB are colliding.
:param AABBCollider a: AABB a
:param AABBCollider b: AABB b
:return: True if AABB are colliding
:rtype bool:
"""
a_min = [a.center[i] - a.size3[i] / 2 for i in range(3)]
a_max = [a.center[i] + a.size3[i] / 2 for i in range(3)]
b_min = [b.center[i] - b.size3[i] / 2 for i in range(3)]
b_max = [b.center[i] + b.size3[i] / 2 for i in range(3)]
return (a_min[0] <= b_max[0] and a_max[0] >= b_min[0]) and \
(a_min[1] <= b_max[1] and a_max[1] >= b_min[1]) and \
(a_min[2] <= b_max[2] and a_max[2] >= b_min[2])
|
e4d3174cbde1bcffb8e43a710ad2434fb9e4e783
| 35,194 |
def edit_distance(str1, str2):
"""
Given two sequences, return the edit distance normalized by the max length.
"""
matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1) + 1):
for j in range(1, len(str2) + 1):
if (str1[i - 1] == str2[j - 1]):
d = 0
else:
d = 1
matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d)
# return matrix
return matrix[len(str1)][len(str2)] / max([len(str1), len(str2)])
|
df8f2b5cd6ef2b20c9f8440fe2f65cc0a6185fcf
| 35,195 |
import logging
def scoped_logger(module_name: str, config_name: str = "maestral") -> logging.Logger:
"""
Returns a logger for the module ``module_name``, scoped to the given config.
:param module_name: Module name.
:param config_name: Config name.
:returns: Logger instances scoped to the config.
"""
return logging.getLogger(scoped_logger_name(module_name, config_name))
|
30bf30f1502ad4b89ed2ef0dc006aa12f1db0bff
| 35,196 |
def parse (line):
"""Parse line into an array of numbers (`EMPTY`, `OCCUPIED`, or `FLOOR`)
for each spot in the seatring area.
"""
return [ CharToInt[c] for c in line.strip() ]
|
708a446fb24e595fb4d8fd7b096543f3a56af1e0
| 35,197 |
def aic(X, k, likelihood_func):
"""Akaike information criterion.
Args:
X (np.ndarray): Data to fit on.
k (int): Free parameters.
likelihood_func (function): Log likelihood function that takes X as input.
"""
return 2 * k - 2 * likelihood_func(X)
|
18ec376d15bdb8190818730b4676febdc01bd476
| 35,198 |
from typing import Callable
from typing import Any
def lazy_formatter_gettext(
string: str, lazy_formatter: Callable[[str], str], **variables: Any
) -> LazyString:
"""Formats a lazy_gettext string with a custom function
Example::
def custom_formatter(string: str) -> str:
if current_app.config["CONDITIONAL_KEY"]:
string += " . Condition key is on"
return string
hello = lazy_formatter_gettext(u'Hello World', custom_formatter)
@app.route('/')
def index():
return unicode(hello)
"""
return LazyString(_wrap_lazy_formatter_gettext, string, lazy_formatter, **variables)
|
d9a1a88a146443ba7b4d8b2dc114a4f613128573
| 35,199 |
def render_color_palette(color: tuple) -> Image.Image:
"""
Assembles the entire color palette preview from all the render pieces.
:param color: the color to lookup
:return: the preview image
"""
pixel, ratio = get_cast_color_info(color)
reticle_preview = render_reticle(CAST_COLOR_IMAGE, pixel)
gradient = generate_gradient(lookup_pixel(CAST_COLOR_IMAGE, pixel), get_average_gray(color), GRADIENT_SIZE)
gradient_bar = _render_gradient(gradient, GRADIENT_SIZE)
slider = _render_slider(gradient_bar, ratio)
color_location = int((1 - ratio) * len(gradient))
color_preview = _render_color(gradient[color_location], slider, 23)
preview = _render_preview(reticle_preview, color_preview)
window_ui = _render_window_ui(preview)
return window_ui
|
c4eb383262f66650f5240b4a52fd92fbb8527acb
| 35,200 |
def heightmap_get_interpolated_value(hm: np.ndarray,
x: float, y: float) -> float:
"""Return the interpolated height at non integer coordinates.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
x (float): A floating point x coordinate.
y (float): A floating point y coordinate.
Returns:
float: The value at ``x``, ``y``.
"""
return lib.TCOD_heightmap_get_interpolated_value(_heightmap_cdata(hm),
x, y)
|
7319edf4f3adb08bd6e382612c917f579e7ff0b5
| 35,201 |
def construct_policy(
bucket_name: str,
home_directory: str,
):
"""
Create the user-specific IAM policy.
Docs: https://docs.aws.amazon.com/transfer/latest/userguide/
custom-identity-provider-users.html#authentication-api-method
"""
return {
'Version': '2012-10-17',
'Statement': [{
'Condition': {
'StringLike': {
's3:prefix': [
f'{home_directory}/*',
f'{home_directory}/',
f'{home_directory}',
],
},
},
'Resource': f'arn:aws:s3:::{bucket_name}',
'Action': 's3:ListBucket',
'Effect': 'Allow',
'Sid': 'ListHomeDir',
}, {
"Sid": "AWSTransferRequirements",
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:GetBucketLocation",
],
"Resource": "*",
}, {
'Resource': 'arn:aws:s3:::*',
'Action': [
's3:PutObject',
's3:GetObject',
's3:DeleteObjectVersion',
's3:DeleteObject',
's3:GetObjectVersion',
's3:GetObjectACL',
's3:PutObjectACL',
],
'Effect': 'Allow',
'Sid': 'HomeDirObjectAccess',
}],
}
|
650459810d01b28cc82d320a3b42592d3bb51170
| 35,202 |
def read_b2fgmtry(fileloc):
"""
Modified from omfit_solps.py
"""
with open(fileloc, 'r') as f:
tmp = f.read()
tmp = tmp.replace('\n', ' ')
tmp = tmp.split("*c")
tmp = [[f for f in x.split(' ') if f] for x in tmp]
m = {'int': int, 'real': float, 'char': str}
b2fgmtry = {}
for line in tmp[1:]:
if len(line) > 4:
b2fgmtry[line[3]] = np.array(list(map(m[line[1]], line[4:])))
else:
b2fgmtry[line[3]] = None
return b2fgmtry
|
5a198ed94442f40af7a0f823ac5a4b1ac43488a1
| 35,203 |
def random_rotation_matrix(rand=None, key=None):
"""Return uniform random rotation matrix.
rand: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
"""
return quaternion_matrix(random_quaternion(rand, key))
|
7e25403afbe758029fa9773cf8bdbeecb54c076f
| 35,204 |
def vea_create(context, values, session=None):
"""Creates a new VEA instance in the Database"""
# If we weren't given a session, then we need to create a new one
if not session:
session = nova_db_sa_api.get_session()
# Create a Transaction around the insert in the Database
with session.begin():
vea_ref = pvc_models.VirtualEthernetAdapterDTO()
vea_ref.update(values)
vea_ref.save(session=session)
# Convert the object to a Dictionary before it is returned
return jsonutils.to_primitive(vea_ref)
|
d3d6ea7a6a26df8f0de5d630cadf33e668523ca2
| 35,205 |
from orphics import stats
def binned_power(imap,bin_edges=None,binner=None,fc=None,modlmap=None,imap2=None,mask=1):
"""Get the binned power spectrum of a map in one line of code.
(At the cost of flexibility and reusability of expensive parts)"""
shape,wcs = imap.shape,imap.wcs
modlmap = enmap.modlmap(shape,wcs) if modlmap is None else modlmap
fc = FourierCalc(shape,wcs) if fc is None else fc
binner = stats.bin2D(modlmap,bin_edges) if binner is None else binner
p2d,_,_ = fc.power2d(imap*mask,imap2*mask if imap2 is not None else None)
cents,p1d = binner.bin(p2d)
return cents,p1d/np.mean(mask**2.)
|
2731935a1acbacea0f5a776ae72ef56f631df043
| 35,206 |
import logging
def batch_to_dict(batch):
"""
Batch file contains two columns:
FULL/PATH/TO/SAMPLE_bin.13.fa SAMPLE_bin.13
Create a dict with [sample_bin_name] = ["Tigname1", "Tigname2"]
:param batch: full path to batch file
:return batch_dict: dict described above
:return bin_list: list of bin names
"""
logging.info("Parsing batch file.")
batch_dict, batch_paths, bin_list = {}, {}, []
with open(batch, 'r') as fh:
for line in fh:
parts = line.strip().split('\t')
records = SeqIO.index(parts[0], "fasta")
tigs = sorted(list(records))
batch_dict[parts[1]] = tigs
bin_list.append(parts[1])
logging.info("{} = {}.".format(parts[1], ", ".join(tigs)))
batch_paths[parts[1]] = parts[0]
return batch_dict, bin_list, batch_paths
|
eabfff643ceb0afeee8825863a52d9d740fd97af
| 35,207 |
def md_link(name: str, url: str) -> str:
"""Makes strings easier to read when defining markdown links."""
return f"[{name}]({url})"
|
7fcef4e75e8fd77f81ddca23957fe326db869a01
| 35,208 |
def extract_uhs(dstore, what):
"""
Extracts uniform hazard spectra. Use it as /extract/uhs/mean or
/extract/uhs/rlz-0, etc
"""
oq = dstore['oqparam']
mesh = get_mesh(dstore['sitecol'])
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
dic = {}
for kind, hcurves in getters.PmapGetter(dstore, rlzs_assoc).items(what):
dic[kind] = calc.make_uhs(hcurves, oq.imtls, oq.poes, len(mesh))
return hazard_items(dic, mesh, investigation_time=oq.investigation_time)
|
97209cbe923e1e237bfcacabcb9f5611866cb82c
| 35,209 |
def geocode_presidents(town):
"""
Returns a list of all intersections where a numbered street crosses a street
named after the corresponding president ("1st and Washington", etc.)
Each item in the resulting list is a tuple, with item[0] holding the name
of the intersection ("1st and Washington"), and item[1] holding a tuple
containing the latitude and longitude of the intersection.
Args:
town is typically formatted like "City, State, Country", but Google will
accept other formats
"""
points = []
for i in PRESIDENTS:
streets = geocoder.get_ordinal_string(i) + " and " + PRESIDENTS[i]
intersections = geocoder.geocode_intersection(streets, town)
for point in intersections:
points.append((streets, point))
return points
|
b1b257f02b1f78b1af509d30e78a003bb0d71e6a
| 35,210 |
def _check_numeric(*, check_func, obj, name, base, func, positive, minimum,
maximum, allow_none, default):
"""Helper function for check_float and check_int."""
obj = check_type(obj, name=name, base=base, func=func,
allow_none=allow_none, default=default)
if obj is None:
return None
positive = check_bool(positive, name='positive')
if positive and obj <= 0:
if name is None:
message = 'Parameter must be positive.'
else:
message = f'Parameter \'{name}\' must be positive.'
raise ValueError(message)
if minimum is not None:
minimum = check_func(minimum, name='minimum')
if obj < minimum:
if name is None:
message = f'Parameter must be at least {minimum}.'
else:
message = f'Parameter \'{name}\' must be at least {minimum}.'
raise ValueError(message)
if maximum is not None:
maximum = check_func(maximum, name='minimum')
if obj > maximum:
if name is None:
message = f'Parameter must be at most {maximum}.'
else:
message = f'Parameter \'{name}\' must be at most {maximum}.'
raise ValueError(message)
return obj
|
c3a62c5c95efe44dfb5a7dcd2f36a875f3dcdda1
| 35,212 |
import sh
def cli(args, cook_url=None, flags=None, stdin=None, env=None, wait_for_exit=True):
"""Runs a CLI command with the given URL, flags, and stdin"""
url_flag = f'--url {cook_url} ' if cook_url else ''
other_flags = f'{flags} ' if flags else ''
cp = sh(f'{command()} {url_flag}{other_flags}{args}', stdin, env, wait_for_exit)
return cp
|
0159cc37314c3804dd616e6a8e3068a1bcc90520
| 35,213 |
def cleanup(sender=None, dictionary=None):
"""Perform a platform-specific cleanup after the test."""
return True
|
655a4f7192d36aa9b73eca40e587eefd3e37f65d
| 35,214 |
def dB2(N,s,ρ=0.5,seed=0):
"""
Get random numbers for two correlated rBergomi processes, each having
N paths and s steps.
"""
np.random.seed(0)
# Following assumes orthogonal variance components equivalent
rn = np.random.normal(size=(N,6*s))
# In what follows the 3 indices correspond to process, factor, hybrid
# Skew
dB111 = rn[:,0*s:1*s]
dB112 = rn[:,1*s:2*s]
# Curvature
dB121 = rn[:,4*s:5*s]
dB122 = rn[:,5*s:6*s]
# Correlated skew
dB211 = ρ*rn[:,0*s:1*s]+np.sqrt(1-ρ**2)*rn[:,2*s:3*s]
dB212 = ρ*rn[:,1*s:2*s]+np.sqrt(1-ρ**2)*rn[:,3*s:4*s]
# Same curvature
dB221 = rn[:,4*s:5*s]
dB222 = rn[:,5*s:6*s]
# Now prepare 4 hybrid 2D Bms
dB11 = np.zeros((N,s,2,1)) # α for first
dB11[:,:,0,0] = dB111
dB11[:,:,1,0] = dB112
dB12 = np.zeros((N,s,2,1)) # β for first
dB12[:,:,0,0] = dB121
dB12[:,:,1,0] = dB122
dB21 = np.zeros((N,s,2,1)) # α for second
dB21[:,:,0,0] = dB211
dB21[:,:,1,0] = dB212
dB22 = np.zeros((N,s,2,1)) # β for second
dB22[:,:,0,0] = dB221
dB22[:,:,1,0] = dB222
# Return nicely
return np.array([[dB11,dB12],[dB21,dB22]])
|
2dfe2172bb50fd9b566860f263778f237affcfe9
| 35,215 |
def karaoke_perceptual_metric(reference_timestamps, estimated_timestamps):
"""Metric based on human synchronicity perception as measured in the paper
"User-centered evaluation of lyrics to audio alignment" [#lizemasclef2021]
The parameters of this function were tuned on data collected through a user Karaoke-like
experiment
It reflects human judgment of how "synchronous" lyrics and audio stimuli are perceived
in that setup.
Beware that this metric is non-symmetrical and by construction it is also not equal to 1 at 0.
Examples
--------
>>> reference_timestamps = mir_eval.io.load_events('reference.txt')
>>> estimated_timestamps = mir_eval.io.load_events('estimated.txt')
>>> score = mir_eval.align.karaoke_perceptual_metric(reference_onsets, estimated_timestamps)
Parameters
----------
reference_timestamps : np.ndarray
reference timestamps, in seconds
estimated_timestamps : np.ndarray
estimated timestamps, in seconds
Returns
-------
perceptual_score : float
Perceptual score, averaged over all timestamps
"""
validate(reference_timestamps, estimated_timestamps)
offsets = estimated_timestamps - reference_timestamps
# Score offsets using a certain skewed normal distribution
skewness = 1.12244251
localisation = -0.22270315
scale = 0.29779424
normalisation_factor = 1.6857
perceptual_scores = (1.0 / normalisation_factor) * skewnorm.pdf(
offsets, skewness, loc=localisation, scale=scale
)
return np.mean(perceptual_scores)
|
830e6ae8cde5dd96aa53beabe0ffabca1e2bfa15
| 35,216 |
def buildTraceback(frames, modules):
"""
Build a chain of mock traceback objects from a serialized Error (or other
exception) object, and return the head of the chain.
"""
last = None
first = None
for func, fname, ln in frames:
fname = modules.get(fname.split('/')[-1], fname)
frame = JSFrame(func, fname, ln)
tb = JSTraceback(frame, ln)
if last:
last.tb_next = tb
else:
first = tb
last = tb
return first
|
e6fa610265af765f23588cbb1cae66830007d4a5
| 35,217 |
def deployment_update(uuid, values):
"""Update a deployment by values.
:param uuid: UUID of the deployment.
:param values: dict with items to update.
:raises DeploymentNotFound: if the deployment does not exist.
:returns: a dict with data on the deployment.
"""
return get_impl().deployment_update(uuid, values)
|
0589a453cdd6d6503b973a0571c58ec8fd476dad
| 35,218 |
from typing import List
from typing import Tuple
def navigate_part_two(commands: List[Tuple[str, int]]) -> Tuple[int, int]:
"""Navigate and return the horizontal position and depth."""
horizontal: int = 0
depth: int = 0
aim: int = 0
for command, units in commands:
if command == 'forward':
horizontal += units
depth += aim * units
elif command == 'down':
aim += units
elif command == 'up':
aim -= units
return horizontal, depth
|
379c31e668ba63fb8bc3b98c28c2cd3087f66c51
| 35,219 |
import time
from faker import Faker
import random
def _generate_events_for_day(date):
"""Generates events for a given day."""
# Use date as seed.
seed = int(time.mktime(date.timetuple()))
Faker.seed(seed)
random_state = random.RandomState(seed)
# Determine how many users and how many events we will have.
n_users = random_state.randint(low=50, high=100)
n_events = random_state.randint(low=200, high=2000)
# Generate a bunch of users.
fake = Faker()
users = [fake.ipv4() for _ in range(n_users)]
return pd.DataFrame(
{
"user": random_state.choice(users, size=n_events, replace=True),
"date": pd.to_datetime(date),
}
)
|
0ebf0d524460d010fbbf29957276fbf81729cc6e
| 35,220 |
def _hessian_vector_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-vector product.
The returned function has arguments (*args, vector, **kwargs). Note,
this function will be incorporated into autograd, with name
hessian_vector_product. Once it has been this function can be
deleted."""
fun_grad = grad(fun, argnum)
def vector_dot_grad(*args, **kwargs):
args, vector = args[:-1], args[-1]
try:
return np.tensordot(fun_grad(*args, **kwargs), vector,
axes=vector.ndim)
except AttributeError:
# Assume we are on the product manifold.
return np.sum([np.tensordot(fun_grad(*args, **kwargs)[k],
vector[k], axes=vector[k].ndim)
for k in range(len(vector))])
# Grad wrt original input.
return grad(vector_dot_grad, argnum)
|
0b4506645b8b5ae1572006f6b64873bf8fa129b2
| 35,221 |
def check_for_tags(*tag_args, msg="Inkluderar inte någon av de givna taggarna"):
"""
Compares the user tags and the test_case tags to see which tests
should be be ran.
"""
def skip_function():
"""
replaces test_cases so they are skipped
"""
raise SkipTest(msg)
def decorator(f):
"""Decorator for overwriting test_case functions"""
@wraps(f)
def wrapper(self, *args, **kwargs):
"""Wrapper"""
user_tags = set(self.USER_TAGS)
if user_tags:
test_case_tags = set(tag_args)
if not user_tags.intersection(test_case_tags):
return skip_function()
return f(self, *args, **kwargs)
wrapper.__wrapped__ = f # used to assert that method has been decorated
return wrapper
return decorator
|
5ddf41d0eb1ce3f8ee5b9c08db027af8e896fce6
| 35,222 |
def find_n_max_vals(list_, num):
"""Function searches the num-biggest values of a given list of numbers.
Returns the num maximas list and the index list wrapped up in a list.
"""
li_ = list_.copy()
max_vals = [] #the values
max_ind = []# the index of the value, can be used to get the param
while num > 0:
max_val = max(li_)
max_id = li_.index(max_val)
max_vals.append(max_val)
max_ind.append(max_id)
li_[max_id] = 0 #better than deleting
num -= 1 # count down
return [max_vals, max_ind]
|
48e274a2e2feac04b285b883ce5948c8f39caff3
| 35,223 |
def color_burn(im1, im2):
"""Darkens the backdrop color to reflect the source color.
The color burn formula is defined as:
if(Cb == 1)
B(Cb, Cs) = 1
else if(Cs == 0)
B(Cb, Cs) = 0
else
B(Cb, Cs) = 1 - min(1, (1 - Cb) / Cs)
See the W3C document:
https://www.w3.org/TR/compositing-1/#blendingcolorburn
Arguments:
im1: A backdrop image (RGB or RGBA).
im2: A source image (RGB or RGBA).
Returns:
The output image.
"""
return alpha_blend(im1, im2, _color_burn)
|
04dd7510d14fb88643fd512fc5020924c5163387
| 35,224 |
def G_2_by_2(a, b, c, d, williams=1, directional=1):
"""G test for independence in a 2 x 2 table.
Usage: G, prob = G_2_by_2(a, b, c, d, willliams, directional)
Cells are in the order:
a b
c d
a, b, c, and d can be int, float, or long.
williams is a boolean stating whether to do the Williams correction.
directional is a boolean stating whether the test is 1-tailed.
Briefly, computes sum(f ln f) for cells - sum(f ln f) for
rows and columns + f ln f for the table.
Always has 1 degree of freedom
To generalize the test to r x c, use the same protocol:
2*(cells - rows/cols + table), then with (r-1)(c-1) df.
Note that G is always positive: to get a directional test,
the appropriate ratio (e.g. a/b > c/d) must be tested
as a separate procedure. Find the probability for the
observed G, and then either halve or halve and subtract from
one depending on whether the directional prediction was
upheld.
The default test is now one-tailed (Rob Knight 4/21/03).
See Sokal & Rohlf (1995), ch. 17. Specifically, see box 17.6 (p731).
"""
cells = [a, b, c, d]
n = npsum(cells)
# return 0 if table was empty
if not n:
return (0, 1)
# raise error if any counts were negative
if min(cells) < 0:
raise ValueError("G_2_by_2 got negative cell counts(s): must all be >= 0.")
G = 0
# Add x ln x for items, adding zero for items whose counts are zero
for i in [_f for _f in cells if _f]:
G += i * log(i)
# Find totals for rows and cols
ab = a + b
cd = c + d
ac = a + c
bd = b + d
rows_cols = [ab, cd, ac, bd]
# exit if we are missing a row or column entirely: result counts as
# never significant
if min(rows_cols) == 0:
return (0, 1)
# Subtract x ln x for rows and cols
for i in [_f for _f in rows_cols if _f]:
G -= i * log(i)
# Add x ln x for table
G += n * log(n)
# Result needs to be multiplied by 2
G *= 2
# apply Williams correction
if williams:
q = 1 + ((((n / ab) + (n / cd)) - 1) * (((n / ac) + (n / bd)) - 1)) / (6 * n)
G /= q
p = chi_high(max(G, 0), 1)
# find which tail we were in if the test was directional
if directional:
is_high = (b == 0) or (d != 0 and (a / b > c / d))
p = tail(p, is_high)
if not is_high:
G = -G
return G, p
|
57150b32a0c5b6416dc3c0a1ef8ee0dc7b357b14
| 35,226 |
def test_elapsed_duration(monkeypatch):
"""
.
"""
@counter_wrapper
def duration(interval: float):
"""
.
"""
return interval
monkeypatch.setattr(print_utils, "current_unix_timestamp", lambda: 123)
monkeypatch.setattr(print_utils, "readable_duration", duration)
assert (
print_utils.elapsed_duration(120) == 3
), "Interval returned using current time"
assert (
print_utils.elapsed_duration(120.123, 122.123) == 2
), "Interval returned using specific end time"
|
0ac8491ff88e09a09b952273413c51855621e3f8
| 35,227 |
def solve(y1,y2) :
""" solve SIS lens equation with
y1,y2 : relative source position with respect to the lens
return : phi,x image position in polar coordinate as arrays of length 2 or 4
"""
eq = lambda phi : eq2(phi,y1,y2)
step = 0.1
phiTest = np.arange(0,2*np.pi+step,step)
test = eq(phiTest)>0
phiI = []
for phi0 in phiTest[np.where(test[:-1] != test[1:])]:
root = optimize.brentq(eq,phi0,phi0+step)
phiI.append(root%(2*np.pi))
phiI = np.array(phiI)
rI = radius(phiI,y1,y2)
return phiI,rI
|
e24bd5935f5c8be3700f00cd4a51d122a0b43215
| 35,228 |
def makeNme(segID: int, N, CA, C, O, geo: NmeGeo) -> Residue:
"""Creates a NME capping residue"""
res = makeGly(segID, N, CA, C, O, geo)
res.resname = "NME"
return res
|
9335b22a7c578a7eb026d04ba0980d239995ffb7
| 35,229 |
import resource
def sobjects_metadata_resource(client: Client):
"""Return resource representing SObject metadata."""
path = f"{client.resources['sobjects']}"
@resource
class SObjectMetadataResource:
"""..."""
def __init__(self, name):
self.name = name
@query
async def describe(self) -> SObject:
"""Get SObject metadata."""
async with client.request(
method="GET", path=f"{path}/{self.name}/describe"
) as response:
metadata = get_codec(JSON, SObject).decode(await response.json())
if metadata.name != self.name:
raise NotFoundError
return metadata
@resource
class SObjectsMetadataResource:
"""..."""
@operation
async def get(self) -> SObjects:
"""Get a list of objects."""
async with client.request(method="GET", path=f"{path}/") as response:
return get_codec(JSON, SObjects).decode(await response.json())
def __getitem__(self, name: str) -> SObjectMetadataResource:
return SObjectMetadataResource(name)
return SObjectsMetadataResource()
|
3c7cd711e0fb01692d43c3b726a8d9e01357b680
| 35,232 |
def makeDrinkInfo(rec_id):
""" Permet de dresser les infos de la boissons passees en argument
:param arg1: id de la boissons (recette)
:type arg1: int
:return: le nom, prix et les informations utiles (alcool, chaud ou froid) de la boissons
:rtype: Json
"""
price = calculePriceRec(rec_id)
nom = recupNameRecFromId(rec_id)
alcohol = hasAlcohol(rec_id)
cold = isCold(rec_id)
drinkInfo = { "name" : nom, "price" : price, "hasAlcohol" :alcohol, "isCold" : cold }
return (drinkInfo)
|
b428c55b71ab2045b8d660f6cb1e587da4723b13
| 35,233 |
def get_vars(host):
"""
parse ansible variables
- defaults/main.yml
- vars/main.yml
- molecule/${MOLECULE_SCENARIO_NAME}/group_vars/all/vars.yml
"""
base_dir, molecule_dir = base_directory()
file_defaults = "file={}/defaults/main.yml name=role_defaults".format(base_dir)
file_vars = "file={}/vars/main.yml name=role_vars".format(base_dir)
file_molecule = "file={}/group_vars/all/vars.yml name=test_vars".format(molecule_dir)
defaults_vars = host.ansible("include_vars", file_defaults).get("ansible_facts").get("role_defaults")
vars_vars = host.ansible("include_vars", file_vars).get("ansible_facts").get("role_vars")
molecule_vars = host.ansible("include_vars", file_molecule).get("ansible_facts").get("test_vars")
ansible_vars = defaults_vars
ansible_vars.update(vars_vars)
ansible_vars.update(molecule_vars)
templar = Templar(loader=DataLoader(), variables=ansible_vars)
result = templar.template(ansible_vars, fail_on_undefined=False)
return result
|
e2498edda87bc879b7fe571a6c21674ebf3a9164
| 35,234 |
def get_smem_args(smem_args, params):
""" return a dict with kernel instance specific size """
result = smem_args.copy()
if 'size' in result:
size = result['size']
if callable(size):
size = size(params)
elif isinstance(size, str):
size = replace_param_occurrences(size, params)
size = int(eval(size))
result['size'] = size
return result
|
52a77346798a7bd8cf417eb729a2a1a2d5b1059e
| 35,235 |
from typing import Optional
from typing import Iterable
from re import T
from typing import Sequence
from typing import Callable
def fork_procs(variant_arg: Optional[Iterable[T]] = None,
variant_args: Optional[Iterable[Sequence]] = None) \
-> Callable[[Callable], process.Handle]:
""" A decorate to create and fork multiple processes """
procs_dec = procs(variant_arg, variant_args)
def decorator(fn: Callable) -> process.Handle:
procs = procs_dec(fn)
return procs.fork()
return decorator
|
149055123de138388b62e52244e9bbab9f13ebe3
| 35,237 |
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:ocs
-------
model_list : List of LDA topic models
coherence_values : Coherence values corresponding to the LDA model with respective number of topics
"""
coherence_values = []
model_list = []
for num_topics in range(start, limit, step):
model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=num_topics, id2word=dictionary)
model_list.append(model)
coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')
coherence_values.append(coherencemodel.get_coherence())
return model_list, coherence_values
|
3b2391aecc67353f6d60bb68f027713ad7e4ea52
| 35,238 |
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre):
"""detector and beam are dxtbx objects,
mosflm_beam_centre is a tuple of mm coordinates.
supports 2-theta offset detectors, assumes correct centre provided
for 2-theta=0
"""
return set_slow_fast_beam_centre_mm(detector, beam, mosflm_beam_centre)
|
a7b0ed140a4beb05766734fe838351f5cfa0c255
| 35,239 |
def getNumColors(path):
"""
Detect the number of colors in the supplied image
(Only up to 8 colors not including the background)
NOTE: This feature is experimental and may not work
well for ALL images
"""
im = Image.open(path)
# Resize to reduce processing time
w, h = im.size
wSmall = int(66 * w / max(w, h))
hSmall = int(66 * h / max(w, h))
im = im.resize((wSmall, hSmall))
# Convert into numpy data structure
im = im.convert('RGB')
im = np.array(im)
# Filter to remove non-unique colors
# This sequence of filters was experimentally determined
# And may not work well for ALL images
for i in range(10):
im = denoise_bilateral(im, sigma_color=0.025, sigma_spatial=4, multichannel = True)
for i in range(5):
im = denoise_bilateral(im, sigma_color=0.035, sigma_spatial=4, multichannel = True)
for i in range(3):
im = denoise_bilateral(im, sigma_color=0.05, sigma_spatial=4, multichannel = True)
for i in range(2):
im = denoise_bilateral(im, sigma_color=0.06, sigma_spatial=4, multichannel = True)
# skio.imshow(im)
# skio.show()
# return
# Reshape into a list of pixels
imArray = im.reshape((im.shape[0] * im.shape[1], 3))
bestSilhouette = -1
bestNumClusters = 0
for numClusters in range(2,9):
# Cluster the colors
clt = KMeans(n_clusters = numClusters)
clt.fit(imArray)
# Calculate Silhouette Coefficient
silhouette = metrics.silhouette_score(imArray, clt.labels_, metric = 'euclidean')
# Find the best one
if silhouette > bestSilhouette:
bestSilhouette = silhouette
bestNumClusters = numClusters
return bestNumClusters - 1
|
7b49dbb48c25910220bcf8ec7b9c267c9d0934b0
| 35,241 |
def reduce_precision_np(x, npp):
"""
Reduce the precision of image, the numpy version.
:param x: a float tensor, which has been scaled to [0, 1].
:param npp: number of possible values per pixel. E.g. it's 256 for 8-bit gray-scale image, and 2 for binarized image.
:return: a tensor representing image(s) with lower precision.
"""
# Note: 0 is a possible value too.
npp_int = npp - 1
x_int = np.rint(x * npp_int)
x_float = x_int / npp_int
return x_float
|
eb322b81976ea3a2b56c408ce0b9f5eb11580f04
| 35,242 |
from typing import Callable
from typing import Union
from typing import Optional
from typing import Tuple
import functools
def multi_dut_argument(func) -> Callable[..., Union[Optional[str], Tuple[Optional[str]]]]:
"""
Used for parse the multi-dut argument according to the `count` amount.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
return parse_multi_dut_args(_COUNT, func(*args, **kwargs))
return wrapper
|
ce7523c9e63cdc076dc4ec326ce3bc4572042a54
| 35,243 |
def ts2wws(C):
"""
Convert a stiffness tensor into a skew notation stiffness matrix
"""
Cv = zeros(3,6)
for i in range(3):
for j in range(6):
ma = skew_mults[i]
mb = mandel_mults[j]
Cv[i,j] = C[skew_inds[i] + mandel[j]] * ma * mb
return Cv
|
55fb55d32af033c6eeb082ffd2740c40376de1ee
| 35,244 |
def _get_oauth2_client_id_and_secret(settings_instance):
"""Initializes client id and client secret based on the settings"""
secret_json = getattr(django.conf.settings,
'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)
if secret_json is not None:
return _load_client_secrets(secret_json)
else:
client_id = getattr(settings_instance, "GOOGLE_OAUTH2_CLIENT_ID",
None)
client_secret = getattr(settings_instance,
"GOOGLE_OAUTH2_CLIENT_SECRET", None)
if client_id is not None and client_secret is not None:
return client_id, client_secret
else:
raise exceptions.ImproperlyConfigured(
"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or "
"both GOOGLE_OAUTH2_CLIENT_ID and "
"GOOGLE_OAUTH2_CLIENT_SECRET in settings.py")
|
1cdb02999af3ab289f262de316bc4afc17add8ac
| 35,246 |
def lpp_transform(X, V, ncomp=2):
"""
Args:
--------------
X: n x d. Data matrix
V: d x m. Each column of V is a LPP direction.
ncomp (<= m <= d): The dimension of transformed data
Returns:
--------------
tr_X: n x ncomp
"""
_, m = V.shape
if ncomp > m:
ncomp = m
tr_X = np.dot(X, V[:,0:ncomp])
return tr_X
|
44b362932e420252689fb87e845665a3bdfe332e
| 35,248 |
def U_net(optimizer, activation, metrics):
"""
Parameters:
- optimizer (String): Keras optimizer to use
- activation (String): Keras layer activation function to use in hidden
layers
- metrics to use for model evaluation
Returns: (Model)
a compiled U-net designed for binary segmentation.
"""
inputs = tf.keras.Input(shape = (2100, 1400, 3))
# downsampling layers
conv_1 = Conv2D(64, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(inputs)
conv_2 = Conv2D(64, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_1)
pool_1 = MaxPool2D((2,2))(conv_2)
conv_3 = Conv2D(128, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(pool_1)
conv_4 = Conv2D(128, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_3)
pool_2 = MaxPool2D((2,2))(conv_4)
conv_5 = Conv2D(256, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(pool_2)
conv_6 = Conv2D(256, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_5)
pool_3 = MaxPool2D((2,2))(conv_6)
conv_7 = Conv2D(512, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(pool_3)
conv_8 = Conv2D(512, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_7)
pool_4 = MaxPool2D((2,2))(conv_8)
conv_9 = Conv2D(1024, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(pool_4)
conv_10 = Conv2D(1024, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_9)
# upsampling layers
upconv_1 = Conv2DTranspose(512, (2,2), strides = (2, 2), padding = 'same')(conv_10)
upconv_1 = ZeroPadding2D(padding = ((0, 0), (0, 1)))(upconv_1) # we need to padd with zeroes on the right
merge_1 = concatenate([conv_8, upconv_1])
conv_11 = Conv2D(512, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(merge_1)
conv_12 = Conv2D(512, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_11)
upconv_2 = Conv2DTranspose(256, (2, 2), strides = (2, 2), padding='same')(conv_12)
upconv_2 = ZeroPadding2D(padding = ((0,1),(0,0)))(upconv_2) # we need to padd with zeroes on top
merge_2 = concatenate([conv_6, upconv_2])
conv_13 = Conv2D(256, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(merge_2)
conv_14 = Conv2D(256, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_13)
upconv_3 = Conv2DTranspose(128, (2, 2), strides = (2, 2), padding='same')(conv_14)
merge_3 = concatenate([conv_4, upconv_3])
conv_15 = Conv2D(128, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(merge_3)
conv_16 = Conv2D(128, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_15)
upconv_4 = Conv2DTranspose(64, (2, 2), strides = (2, 2), padding='same')(conv_16)
merge_4 = concatenate([conv_2, upconv_4])
conv_17 = Conv2D(64, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(merge_4)
conv_18 = Conv2D(64, (3,3), activation = activation,
kernel_initializer = 'he_normal', padding = 'same')(conv_17)
output = Dense(4, activation = 'softmax')(conv_18)
model = tf.keras.Model(inputs, output)
model.compile(optimizer = optimizer, loss = 'categorical_crossentropy',
metrics = metrics)
return model
|
009eea82f105d6b5975a83739f52e43855274481
| 35,249 |
def create_environment(env_name='',
stacked=False,
representation='extracted',
rewards='scoring',
enable_goal_videos=False,
enable_full_episode_videos=False,
render=False,
write_video=False,
dump_frequency=1,
logdir='',
extra_players=None,
number_of_left_players_agent_controls=1,
number_of_right_players_agent_controls=0,
enable_sides_swap=False,
channel_dimensions=(
observation_preprocessing.SMM_WIDTH,
observation_preprocessing.SMM_HEIGHT)):
"""Creates a Google Research Football environment.
Args:
env_name: a name of a scenario to run, e.g. "11_vs_11_stochastic".
The list of scenarios can be found in directory "scenarios".
stacked: If True, stack 4 observations, otherwise, only the last
observation is returned by the environment.
Stacking is only possible when representation is one of the following:
"pixels", "pixels_gray" or "extracted".
In that case, the stacking is done along the last (i.e. channel)
dimension.
representation: String to define the representation used to build
the observation. It can be one of the following:
'pixels': the observation is the rendered view of the football field
downsampled to 'channel_dimensions'. The observation size is:
'channel_dimensions'x3 (or 'channel_dimensions'x12 when "stacked" is
True).
'pixels_gray': the observation is the rendered view of the football field
in gray scale and downsampled to 'channel_dimensions'. The observation
size is 'channel_dimensions'x1 (or 'channel_dimensions'x4 when stacked
is True).
'extracted': also referred to as super minimap. The observation is
composed of 4 planes of size 'channel_dimensions'.
Its size is then 'channel_dimensions'x4 (or 'channel_dimensions'x16 when
stacked is True).
The first plane P holds the position of the 11 player of the left
team, P[y,x] is one if there is a player at position (x,y), otherwise,
its value is zero.
The second plane holds in the same way the position of the 11 players
of the right team.
The third plane holds the active player of the left team.
The last plane holds the position of the ball.
'simple115': the observation is a vector of size 115. It holds:
- the ball_position and the ball_direction as (x,y,z)
- one hot encoding of who controls the ball.
[1, 0, 0]: nobody, [0, 1, 0]: left team, [0, 0, 1]: right team.
- one hot encoding of size 11 to indicate who is the active player
in the left team.
- 11 (x,y) positions for each player of the left team.
- 11 (x,y) motion vectors for each player of the left team.
- 11 (x,y) positions for each player of the right team.
- 11 (x,y) motion vectors for each player of the right team.
- one hot encoding of the game mode. Vector of size 7 with the
following meaning:
{NormalMode, KickOffMode, GoalKickMode, FreeKickMode,
CornerMode, ThrowInMode, PenaltyMode}.
Can only be used when the scenario is a flavor of normal game
(i.e. 11 versus 11 players).
rewards: Comma separated list of rewards to be added.
Currently supported rewards are 'scoring' and 'checkpoints'.
enable_goal_videos: whether to dump traces up to 200 frames before goals.
enable_full_episode_videos: whether to dump traces for every episode.
render: whether to render game frames.
Must be enable when rendering videos or when using pixels
representation.
write_video: whether to dump videos when a trace is dumped.
dump_frequency: how often to write dumps/videos (in terms of # of episodes)
Sub-sample the episodes for which we dump videos to save some disk space.
logdir: directory holding the logs.
extra_players: A list of extra players to use in the environment.
Each player is defined by a string like:
"$player_name:left_players=?,right_players=?,$param1=?,$param2=?...."
number_of_left_players_agent_controls: Number of left players an agent
controls.
number_of_right_players_agent_controls: Number of right players an agent
controls.
enable_sides_swap: Whether to randomly pick a field side at the beginning of
each episode for the team that the agent controls.
channel_dimensions: (width, height) tuple that represents the dimensions of
SMM or pixels representation.
Returns:
Google Research Football environment.
"""
assert env_name
players = [('agent:left_players=%d,right_players=%d' % (
number_of_left_players_agent_controls,
number_of_right_players_agent_controls))]
if extra_players is not None:
players.extend(extra_players)
c = config.Config({
'enable_sides_swap': enable_sides_swap,
'dump_full_episodes': enable_full_episode_videos,
'dump_scores': enable_goal_videos,
'players': players,
'level': env_name,
'render': render,
'tracesdir': logdir,
'write_video': write_video,
})
env = football_env.FootballEnv(c)
if dump_frequency > 1:
env = wrappers.PeriodicDumpWriter(env, dump_frequency)
assert 'scoring' in rewards.split(',')
if "fast" in rewards.split(","):
env = wrappers.FastRewardWrapper(env)
if "roles" in rewards.split(","):
env = wrappers.RoleRewardWrapper(env)
if 'checkpoints' in rewards.split(','):
env = wrappers.CheckpointRewardWrapper(env)
if "reduce" in rewards.split(","):
env = wrappers.ReduceRewardWrapper(env)
if representation.startswith('pixels'):
env = wrappers.PixelsStateWrapper(env, 'gray' in representation,
channel_dimensions)
elif representation == 'simple115':
env = wrappers.Simple115StateWrapper(env)
elif representation == 'extracted':
env = wrappers.SMMWrapper(env, channel_dimensions)
else:
raise ValueError('Unsupported representation: {}'.format(representation))
if (number_of_left_players_agent_controls +
number_of_right_players_agent_controls == 1):
env = wrappers.SingleAgentObservationWrapper(env)
env = wrappers.SingleAgentRewardWrapper(env)
if stacked:
env = wrappers.FrameStack(env, 4)
return env
|
548449ddcb9dd35161ebb7ab65f564b9644fa438
| 35,250 |
def self_biosample_id():
"""本人的样品编号"""
return SELF_BIOSAMPLE_ID
|
d2fdf081de5248284b0317051d9d2dcc63e4913b
| 35,251 |
def exp_process_image_20(img):
"""Get multiprocess experiment."""
return process_image(
img, imgclf.ImageClassifier(), segments_no=20,
sample_size=100, random_seed=42)
|
4cd686fee485106a6004abb4f04fddda7aa722f4
| 35,252 |
import json
import requests
def get_lol_version():
""" Get current League of Legends version """
versions = json.loads(requests.get(
"https://ddragon.leagueoflegends.com/api/versions.json").text)
# reformats from 10.14.5 to 10.14
latest = ".".join(versions[0].split(".")[:2])
return latest
|
2702b3375cee503cea561f2965bbafdb17a3f232
| 35,253 |
def retrieve_domain_name(module, client, name):
"""
Retrieve domain name by provided name
:return: Result matching the provided domain name or an empty hash
"""
resp = None
try:
resp = backoff_get_domain_name(client, name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NotFoundException':
resp = None
else:
module.fail_json(msg="Error when getting domain_name from boto3: {}".format(e))
except botocore.exceptions.BotoCoreError as e:
module.fail_json(msg="Error when getting domain_name from boto3: {}".format(e))
return resp
|
e88959843c9973c9ac8071316cef9dcaec8ccf91
| 35,254 |
def create_BIP122_uri(chain_id, resource_type, resource_identifier):
"""
See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki
"""
if resource_type not in {BLOCK, TRANSACTION}:
raise ValueError("Invalid resource_type. Must be one of 'block' or 'transaction'")
elif not is_block_or_transaction_hash(resource_identifier):
raise ValueError("Invalid resource_identifier. Must be a hex encoded 32 byte value")
elif not is_block_or_transaction_hash(chain_id):
raise ValueError("Invalid chain_id. Must be a hex encoded 32 byte value")
return parse.urlunsplit([
'blockchain',
remove_0x_prefix(chain_id),
"{0}/{1}".format(resource_type, remove_0x_prefix(resource_identifier)),
'',
'',
])
|
fc6ca06c094082f748c14250cf67da416aaf5fb9
| 35,255 |
import time
def draw_down(x, y, threshold, timeout):
"""
Draws the line down.
:param x: X coordinate of click
:param y: Y coordinate of click
:param threshold: pixel gradient threshold
:param timeout: timeout (sec)
:return: Y coordinate where pixel gradient is hit
"""
y_position = y
while y_position != height - 1:
y_position += 1
if time.time() > timeout:
break
# Setting the value of the compare image
if y_position > height - 11:
down_y_compare = height - 11
else:
down_y_compare = y_position + 10
# Getting intensities
current_intensity = int(image[y_position, x, 0]) # the current intensity of pixel
compare_intensity = int(image[down_y_compare, x, 0]) # intensity of pixel you want to compare
if abs(current_intensity - compare_intensity) > threshold:
return down_y_compare
return height
|
2bfa7a7fbdeea2c5e4b974cf69b473c44273ab61
| 35,256 |
def read_read_basis(input_string):
"""
"""
pattern = ('ReadBasis' +
one_or_more(SPACE) + capturing(LOGICAL))
block = _get_functional_form_section(input_string)
keyword = first_capture(pattern, block)
assert keyword is not None
return keyword
|
6e2f0a59bdddb2ac34ec8cf730f9a778a67e8d59
| 35,257 |
def _Ipr7ConfigRead(config):
"""Extracts DPA and grants from IPR7 config JSON.
Args:
config: A JSON dictionary.
Returns:
A tuple (dpas, grants) where:
dpas: a list of objects of type |dpa_mgr.Dpa|.
grants: a list of |data.CbsdGrantInfo|.
"""
if 'portalDpa' in config:
dpa_tag = 'portalDpa'
elif 'escDpa' in config:
dpa_tag = 'escDpa'
else:
raise ValueError('Unsupported config file. Please use a IPR7 config file')
# Build the DPA
dpa_id = config[dpa_tag]['dpaId']
try: dpa_kml_file = config['dpaDatabaseConfig']['filePath']
except KeyError: dpa_kml_file = None
points_builder = config[dpa_tag]['points_builder']
dpa = dpa_mgr.BuildDpa(dpa_id, protection_points_method=points_builder,
portal_dpa_filename=dpa_kml_file)
freq_range_mhz = (config[dpa_tag]['frequencyRange']['lowFrequency'] / 1.e6,
config[dpa_tag]['frequencyRange']['highFrequency'] / 1.e6)
dpa.ResetFreqRange([freq_range_mhz])
# - add extra properties for the geometry and margin
dpa.margin_db = config[dpa_tag]['movelistMargin']
try: dpa_zone = zones.GetCoastalDpaZones()[dpa_id]
except KeyError: dpa_zone = zones.GetPortalDpaZones(kml_path=dpa_kml_file)[dpa_id]
dpa.geometry = dpa_zone.geometry
# Read the CBSDs, assuming all granted, into list of |CbsdGrantInfo|.
grants = []
# - first the SAS UUT
for domain_proxy_config in config['domainProxies']:
grant_requests = domain_proxy_config['grantRequests']
reg_requests = MergeConditionalData(domain_proxy_config['registrationRequests'],
domain_proxy_config['conditionalRegistrationData'])
grants.extend(data.getGrantsFromRequests(reg_requests, grant_requests,
is_managing_sas=True))
# - now the peer SASes.
for th_config in config['sasTestHarnessConfigs']:
dump_records = th_config['fullActivityDumpRecords'][0]
grants.extend(data.getAllGrantInfoFromCbsdDataDump(
dump_records, is_managing_sas=False))
return grants, [dpa]
|
78f9288be544c6a66845eadb42bef30fcf84632c
| 35,258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.