content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def prepositionalPhrase():
"""Builds and returns a prepositional phrase."""
return random.choice(prepositions) + " " + nounPhrase()
| 7,700 |
def output_yaml_key(dictionary, yaml_key, hierarchy_regex):
"""
Fancy print function that prints out a key in the global dictionary with the hierarchy ordered as defined in
hiera.yaml
"""
print("%s:" % yaml_key)
if len(dictionary[yaml_key]) > 1:
# convert all 2nd level dict into ordereddict keys so that we can maintain hierarchy order awareness
for yaml_key in global_dict.keys():
ordered_dict = OrderedDict(sorted(global_dict[yaml_key].items(), key=lambda x: get_regex_order(x[0], hierarchy_regex)))
pp.pprint(ordered_dict)
else:
pp.pprint(dictionary[yaml_key])
print()
| 7,701 |
def check_possible_dtype(df):
"""Guess dtypes for each column in a dataframe, where dataframe must contains only string values.
Raise an exception if dataframe contains non-string values.
:param df: a DataFrame whose all values must be strings.
"""
column = []
int_cnt = []
dec_cnt = []
str_cnt = []
d = {"column": column, "int_cnt": int_cnt, "dec_cnt": dec_cnt, "str_cnt": str_cnt}
for i in df.columns:
ser = df[i].drop_duplicates()
column.append(i)
int_cnt.append(ser.apply(lambda x: is_int_str(x)).sum())
dec_cnt.append(ser.apply(lambda x: is_dec_str(x)).sum())
str_cnt.append(ser.apply(lambda x: not is_number_str(x)).sum())
dtype_options_df = pd.DataFrame(d, columns=["column", "int_cnt", "dec_cnt", "str_cnt"])
# Best-effort guess on dtype
guessed_dtype = dtype_options_df.apply(guess_dtype, axis=1).rename("guessed_type_for_non_nan")
return pd.concat([dtype_options_df, guessed_dtype], axis=1)
| 7,702 |
def display_image(img, heatmap, vectmap):
"""
Displays an image and associated heatmaps and pafs (all)
:param img:
:param heatmap:
:param vectmap:
:return:
"""
fig = plt.figure()
a = fig.add_subplot(2, 2, 1)
a.set_title('Image')
plt.imshow(_get_bgimg(img))
a = fig.add_subplot(2, 2, 2)
a.set_title('Heatmap')
plt.imshow(_get_bgimg(img, target_size=(heatmap.shape[1], heatmap.shape[0])), alpha=0.5)
tmp = np.amax(heatmap, axis=2)
plt.imshow(tmp, cmap=plt.cm.gray, alpha=0.5)
plt.colorbar()
tmp2 = vectmap.transpose((2, 0, 1))
tmp2_odd = np.amax(np.absolute(tmp2[::2, :, :]), axis=0)
tmp2_even = np.amax(np.absolute(tmp2[1::2, :, :]), axis=0)
a = fig.add_subplot(2, 2, 3)
a.set_title('paf-x')
plt.imshow(_get_bgimg(img, target_size=(vectmap.shape[1], vectmap.shape[0])), alpha=0.5)
plt.imshow(tmp2_odd, cmap=plt.cm.gray, alpha=0.5)
plt.colorbar()
a = fig.add_subplot(2, 2, 4)
a.set_title('paf-y')
plt.imshow(_get_bgimg(img, target_size=(vectmap.shape[1], vectmap.shape[0])), alpha=0.5)
plt.imshow(tmp2_even, cmap=plt.cm.gray, alpha=0.5)
plt.colorbar()
plt.show()
| 7,703 |
def filter_objects_avoiding_duplicated(objects: List[Object],
max_distance: int = 20) -> List[Object]:
"""Filtra los objetos evitando aquellas posibles que sean detecciones múltiples.
El fundamento del algoritmo es que si se detectan dos objetos con un centroide muy cercano, a
una distancia máxima indicada por ``max_distance``, entonces es una detección múltiple.
El conflicto se resuelve eliminando las detecciones múltiple y escogiendo la que mejor
puntuación ha obtenido en la detección.
:param objects: lista de objetos.
:param max_distance: máxima distancia entre centros para considerar que ese objeto puede ser
un duplicado.
:return: lista de objetos filtrados.
"""
# Lista de las posiciones en 'objects' de los objetos eliminados.
removed_objects_id = list()
# Buscar los posibles candidatos para cada objeto.
for obj_id, obj_detection in enumerate(objects):
for candidate_id, candidate_detection in enumerate(objects):
# Ignorar el mismo objeto como posible candidato.
if obj_id == candidate_id:
continue
# Ignorar si alguno de los que se está comparando ha sido eliminado ya.
if obj_id in removed_objects_id or candidate_id in removed_objects_id:
continue
# Calcular la distancia euclídea entre ambas detecciones.
p = np.array(obj_detection.center)
q = np.array(candidate_detection.center)
distance = np.linalg.norm(p - q)
# Si hay poca distancia, puede ser el mismo objeto.
if distance <= max_distance:
# Eliminar el que menos puntuación tiene.
if obj_detection.score > candidate_detection.score:
removed_objects_id.append(candidate_id)
else:
removed_objects_id.append(obj_id)
# Lista de los objetos que han pasado el filtro.
objects_filtered: List[Object] = list()
for obj_id, obj_detection in enumerate(objects):
if obj_id not in removed_objects_id:
objects_filtered.append(obj_detection)
return objects_filtered
| 7,704 |
def splitall(path):
"""
Credit goes to Trent Mick
SOURCE:
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch04s16.html
"""
allparts = []
while 1:
parts = os.path.split(path)
if parts[0] == path: # sentinel for absolute paths
allparts.insert(0, parts[0])
break
elif parts[1] == path: # sentinel for relative paths
allparts.insert(0, parts[1])
break
else:
path = parts[0]
allparts.insert(0, parts[1])
return allparts
| 7,705 |
def netstat():
"""
Return list of all connections.
Return list of TCP listenning connections and UDP connections.
All localhost connections are filtered out.
This script must run as root in order to be able to obtain PID values
of all processes. For more information see:
https://unix.stackexchange.com/questions/226276/read-proc-to-know-if-a-process-has-opened-a-port
:return: List of connections
"""
uid = os.getuid()
assert uid == 0, "This script must run as root"
tcp4_list = netstat_tcp4()
udp4_list = netstat_udp4()
tcp6_list = netstat_tcp6()
udp6_list = netstat_udp6()
raw_list = netstat_raw()
return tcp4_list + udp4_list + tcp6_list + udp6_list + raw_list
| 7,706 |
def print_hdr(soup, hdr, file = None):
"""
:param soup: [bs4.BeautifulSoup] document context
:param hdr: [dict] header node to process
:param file: [stream] I/O stream to print to
:return: [stream] pass on the I/O stream so descent continues
"""
tag = hdr['tag']
tag_id = tag['id']
indent = (hdr['level'] - 1) * ' '
# do this replacement for (relative) readability
content_tags = ["<%s>" % (h.name) if h.name else h.string for h in hdr['content']]
print("%s%s - %s %s" % (indent, tag.name, tag_id, content_tags), file=file)
return file
| 7,707 |
def usage():
"""
Prints usage information
"""
print("usage: %s <title> <gof_fileroot> <indir> <outdir> <cutoff>" %
(sys.argv[0]))
| 7,708 |
def test_peekleft_child_empty_deque():
"""Test peekleft_child on an empty deque."""
test_deque = Deque()
peek_value = test_deque.peekleft_child()
assert peek_value is None
| 7,709 |
def __empty_2():
""" Empty used as parent of cube_2 """
obj = Mock()
obj.name = 'empty_2'
obj.mode = 'OBJECT'
obj.to_mesh.return_value = None
obj.matrix_world = Matrix.Identity(4)
obj.visible_get.return_value = False
obj.hide_viewport = True
obj.hide_render = True
return obj
| 7,710 |
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="A scaffolding program for developer notes")
parser.add_argument(
"-v",
"--version",
action="version",
version="nota {ver}".format(ver=__version__))
parser.add_argument(
dest="name",
help="name of new note",
metavar="<name>")
parser.add_argument(
"-c",
"--config",
dest="config",
help="configuration file location")
parser.add_argument(
"-t",
"--template",
dest="template",
help="custom template file location")
parser.add_argument(
"-i",
"--identifier",
dest="identifier",
help="custom note identifier")
parser.add_argument(
"--directories",
dest="dirs",
help="additional directories to create",
action="append",
nargs="+")
parser.add_argument(
"--filename",
dest="filename",
help="custom note filename")
parser.add_argument(
"-l",
"--list",
dest="list",
help="lists all notes available",
action="store_true")
parser.add_argument(
"-r",
"--root",
dest="root",
help="root directory for all notes")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"-d",
"--defect",
dest="note_type",
help="create a defect note",
action="store_const",
const=NoteType.Defect)
group.add_argument(
"-b",
"--bug",
dest="note_type",
help="create a bug note",
action="store_const",
const=NoteType.Bug)
group.add_argument(
"-s",
"--story",
dest="note_type",
help="create a story note",
action="store_const",
const=NoteType.Story)
group.add_argument(
"-f",
"--feature",
dest="note_type",
help="create a feature note",
action="store_const",
const=NoteType.Feature)
group.add_argument(
"-o",
"--option",
dest="custom",
help="create a custom note")
return parser.parse_args(args)
| 7,711 |
def get_gradient(bf_data: np.ndarray, smooth=10):
"""
Removes first dimension,
Computes gradient of the image,
applies gaussian filter
Returns SegmentedImage object
"""
data = strip_dimensions(bf_data)
gradient = get_2d_gradient(data)
smoothed_gradient = gaussian_filter(gradient, smooth)
# sm = multiwell.gaussian_filter(well, smooth)
return smoothed_gradient.reshape(bf_data.shape)
| 7,712 |
def sum_seq(seq):
""" Lambda wrapper for sum. """
return K.sum(seq, axis=1, keepdims=False)
| 7,713 |
def p_opt_visible_order_spec(t):
"""opt_visible_order_spec : LPAREN visible_order_spec RPAREN"""
t[0] = t[2]
| 7,714 |
async def test_sensors(hass, setup_entry):
"""Test the SleepIQ binary sensors for a bed with two sides."""
entity_registry = er.async_get(hass)
state = hass.states.get("sensor.sleepnumber_ile_test1_sleepnumber")
assert state.state == "40"
assert state.attributes.get(ATTR_ICON) == "mdi:bed"
assert (
state.attributes.get(ATTR_FRIENDLY_NAME) == "SleepNumber ILE Test1 SleepNumber"
)
entry = entity_registry.async_get("sensor.sleepnumber_ile_test1_sleepnumber")
assert entry
assert entry.unique_id == "-31_Test1_sleep_number"
# If account type is set, only a single bed account was created and there will
# not be a second entity
if setup_entry["account_type"]:
return
state = hass.states.get("sensor.sleepnumber_ile_test2_sleepnumber")
assert state.state == "80"
assert state.attributes.get(ATTR_ICON) == "mdi:bed"
assert (
state.attributes.get(ATTR_FRIENDLY_NAME) == "SleepNumber ILE Test2 SleepNumber"
)
entry = entity_registry.async_get("sensor.sleepnumber_ile_test2_sleepnumber")
assert entry
assert entry.unique_id == "-31_Test2_sleep_number"
| 7,715 |
def split_by_time(files_rad):
"""Separate a list of files by their timestamp"""
out = {}
if type(files_rad) == dict:
for k in files_rad.keys():
out[k] = _split_by_time(files_rad[k])
else:
out = _split_by_time(files_rad)
return out
| 7,716 |
def make_general_csv_rows(general_csv_dict):
"""
Method for make list of metrics from general metrics dict.
Rows using in general metrics writer
:param general_csv_dict: dict with all metrics
:type general_csv_dict: dict
:return: all metrics as rows
:rtype: list
"""
rows = []
for key, value in general_csv_dict.items():
row = [key[0], key[1]]
row.extend(value)
rows.append(row)
return rows
| 7,717 |
def build_hstwcs(crval1, crval2, crpix1, crpix2, naxis1, naxis2, pscale, orientat):
""" Create an HSTWCS object for a default instrument without distortion
based on user provided parameter values.
"""
wcsout = wcsutil.HSTWCS()
wcsout.wcs.crval = np.array([crval1,crval2])
wcsout.wcs.crpix = np.array([crpix1,crpix2])
wcsout.naxis1 = naxis1
wcsout.naxis2 = naxis2
wcsout.wcs.cd = fileutil.buildRotMatrix(orientat)*[-1,1]*pscale/3600.0
# Synchronize updates with PyWCS/WCSLIB objects
wcsout.wcs.set()
wcsout.setPscale()
wcsout.setOrient()
wcsout.wcs.ctype = ['RA---TAN','DEC--TAN']
return wcsout
| 7,718 |
def build_regressor_for_ranking_positive_class(dataset, features, regression_target=TARGET_COLUMN):
"""This function builds a regressor based exclusively on positive class'
examples present in the dataset
"""
if regression_target in features:
print('The target for the regression task cannot be one of the features')
return
positive_examples = dataset.loc[dataset[TARGET_COLUMN] > ALPHA]
X = positive_examples[features]
y = positive_examples[regression_target]
regressor = RandomForestRegressor(random_state=20)
regressor.fit(X, y)
return regressor
| 7,719 |
def get_speakable_timestamp(timestamp):
"""Return a 'speakable' timestamp, e.g. 8am, noon, 9pm, etc."""
speakable = f"{timestamp.strftime('%I').lstrip('0')} {timestamp.strftime('%p')}"
if speakable == '12 PM':
return 'noon'
elif speakable == '12 AM':
return 'midnight'
return speakable
| 7,720 |
def compute_save_stat(outdir, trn_dict, dec_dict, wavlen_dict, declen_dict, fwlen_dict):
"""
Save computed statistics e.g. WER, decoding length, wave length
Args:
outdir(str): path to directory for the generated log files are saved.
trn_dict(dict): (Wave name, transcription) dictionary
dec_dict(dict): (Wave name, decoded transcription) dictionary
wavlen_dict(dict): (Wave name, Wave length) dictionary
declen_dict(dict): (Wave name, (decoding time + extraction time)) dictionary
fwlen_dict(dict): (Wave name, decoding time) dictionary
"""
compute_rt_factor(outdir, trn_dict, dec_dict, wavlen_dict, declen_dict, fwlen_dict)
reference = os.path.join(outdir, 'ref_trn.txt')
hypothesis = os.path.join(outdir, 'dec_trn.txt')
score(reference, hypothesis)
| 7,721 |
def createColor(red: int, green: int, blue: int) -> tuple:
"""
Create color
Parameters:
red -> 0-255
green -> 0-255
blue -> 0-255
"""
return tuple(
max(min(red, 255), 0),
max(min(green, 255), 0),
max(min(blue, 255), 0)
)
| 7,722 |
def export_nodeclass_list(node_classes: List[NodeClass]) -> str:
"""Writes the Node data as a XML string. Does not write
to a file -- use ``with open(output_file) as out_stream:`` etc.
"""
# This is the data string, the rest is formalities
node_classes_string = '\n'.join([str(c) for c in node_classes])
lines = list()
lines.append('<?xml version="1.0" encoding="utf-8"?>')
lines.append('<NodeClasses noNamespaceSchema="mff-muscima-mlclasses.xsd">')
lines.append(node_classes_string)
lines.append('</NodeClasses>')
return '\n'.join(lines)
| 7,723 |
def recognition(request):
"""
style transform service
"""
if request.method == 'POST':
name = ''
predicitons = ''
try:
# load image
now = time.localtime()
img = request.FILES['image']
image_name = '{}{}{}{}{}object.jpg'.format(now[1], now[2], now[3], now[4], now[5])
# get prediction
predicitons = predict_app(img)
# save to database
Image = ContentImage()
Image.name = 'static/images/predict/' + image_name
Image.save()
# save to disk
addr = BASE_DIR + 'predict/' + image_name
save_to_disk(addr, img)
image_url = 'images/predict/' + image_name
except Exception as e:
print(e)
return render(request, 'recognition/basic.html', {})
return render(request, 'recognition/basic.html', {'image_url':image_url, 'predictions': predicitons})
if request.method == 'GET':
return render(request, 'recognition/basic.html', {})
| 7,724 |
def url(s):
"""Validate url input"""
u = urlparse(s)
if u.scheme not in ["http", "https"]:
raise ValueError(s)
return u.geturl()
| 7,725 |
def getGPLCs(df, savepath='./',plotpath='./', bands='ugrizY', ts='0000000', fn='GPSet'):
"""Short summary.
Parameters
----------
df : type
Description of parameter `df`.
savepath : type
Description of parameter `savepath`.
plotpath : type
Description of parameter `plotpath`.
bands : type
Description of parameter `bands`.
ts : type
Description of parameter `ts`.
fn : type
Description of parameter `fn`.
Returns
-------
type
Description of returned object.
"""
#num_bands = len(np.unique(band_idx))
Npt = 100
tmin = -30
tmax = 150
num_bands = len(bands)
GP_dict = {}
# make our plots look nice
stylePlots()
for idx, row in df.iterrows():
t = np.array(row["T"])
f = np.array(row["Flux"])
f[f<0.] = 0. #getting rid of negative flux
#the magnitude-like array for the sake of the conversion
y = np.log(f + 1)
yerr = np.array(row["Flux_Err"]) / np.array(row["Flux"])
t_test = np.linspace(tmin, tmax, Npt)
band = row["Filter"]
band_idx = pd.Series(row['Filter']).astype('category').cat.codes.values
matrix = [t_test]
def build_gp(params):
time_kernel = tinygp.kernels.Matern32(jnp.exp(params["log_scale"]))
kernel = Multiband(time_kernel, jnp.exp(params["log_diagonal"]), params["off_diagonal"])
diag = yerr ** 2 + jnp.exp(2 * params["log_jitter"][X[1]])
return tinygp.GaussianProcess(kernel, X, diag=diag, mean=lambda x: params["mean"][x[1]])
#the GP parameters
@jax.jit
def loss(params):
return -build_gp(params).condition(y)
X = (t, band_idx)
solver = jaxopt.ScipyMinimize(fun=loss)
soln = solver.run(params)
gp = build_gp(soln.params)
df_t = []
df_flux = []
df_flux_err = []
df_filt = []
if idx%50 == 0:
plt.figure(figsize=(10,7))
for n in np.unique(band_idx):
m = band_idx == n
plt.errorbar(t[m], np.exp(y[m])-1,yerr=row['Flux_Err'][m], fmt="o", color=f"C{n}")
mu, var = gp.predict(y, X_test=(t_test, np.full_like(t_test, n, dtype=int)), return_var=True)
std = np.sqrt(var)
if idx%50 == 0:
plt.plot(t_test, np.exp(mu)-1, '.-', ms=2, color=f"C{n}")
plt.fill_between(t_test,np.exp(mu - std)-1, np.exp(mu + std)+1, color=f"C{n}", alpha=0.3, label=bands[n])
#going in order of band here--don't forget it!
matrix.append(np.exp(mu)-1)
matrix.append(std)
if idx%50 == 0:
plt.xlim((t_test[0], t_test[-1]))
plt.xlabel("Phase from Trigger (Days)")
plt.ylabel("Flux")
plt.legend()
plt.savefig(plotpath + "/GP_%i.png"%row.CID,dpi=200, bbox_inches='tight')
stacked = np.vstack(matrix)
GP_dict[row.CID] = stacked
with open(savepath + '/%s_%i.pkl'%(fn, ts), 'wb') as f:
pickle.dump(GP_dict, f)
return GP_dict
| 7,726 |
async def db_async_test_data(db_async_session):
"""A fixture to fill the DB with test data.
Use this in asynchronous tests.
"""
async with db_async_session.begin():
for obj in _gen_test_data_objs():
db_async_session.add(obj)
| 7,727 |
def prepare_embeddings():
"""
Prepares fastText embeddings (available at https://fasttext.cc/docs/en/english-vectors.html) for use in the model.
Function expects unarchived fastText embedding file.
"""
file_in = io.open(cnf.embedding_file, 'r', encoding="utf-8", newline='\n', errors='ignore')
n, d = list(map(int, file_in.readline().split(' '))) # Dimensions of embedding
print("Preparing embedding with dimensions:", n, d)
word_to_id = {"C_PAD": 0, "C_UNK": 1}
word_to_vec = [['0' for _ in range(d)], [str(random.random()) for _ in range(d)]]
word_id = 2
with open(cnf.emb_vector_file, "w") as vector_file:
for line in file_in:
tokens = line.rstrip().split()
word_to_vec.append(tokens[1:])
word_to_id[tokens[0]] = word_id
if word_id % 100000 == 0:
vector_file.writelines([" ".join(word) + "\n" for word in word_to_vec])
word_to_vec = []
print("Done with", word_id, "word")
word_id += 1
vector_file.writelines([" ".join(word) + "\n" for word in word_to_vec])
with open(cnf.emb_word_dictionary, "wb") as id_out:
pickle.dump(word_to_id, id_out) # For faster load times save numpy array as binary file
print('Pickled word dictionary')
vector_file = np.loadtxt(cnf.emb_vector_file, dtype=np.float)
with open(cnf.emb_vector_file, "wb") as emb_file_bin: # For faster load times save numpy array as binary file
pickle.dump(vector_file, emb_file_bin)
print('Pickled embedding')
| 7,728 |
def _featurize(inputs,model):
"""
Helper function used to featurize exemplars before feeding into
buffer.
"""
with torch.no_grad():
# Forward pass
outputs = model(*inputs).detach() #Featurize raw exem
return outputs
| 7,729 |
def ligth_condition(img, args):
"""
Change ligthning condition in the image
Inputs:
img: Image to change ligthning
args: Dictionary with "gamma" argument
Return:
Image with ligthning values changed
"""
invGamma = 1.0 / args["gamma"]
table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(img, table)
| 7,730 |
def calc_RMSE(varx,vary,lats,lons,weight):
"""
Calculates root mean square weighted average
Parameters
----------
varx : 2d array
vary : 2d array
lons : 1d array of latitude
weight : string (yes or no)
Returns
-------
rmse : 1d array
Usage
-----
rmse = calc_RMSE(varx,vary,lats,lons)
"""
print('\n>>> Using calc_RMSE function!')
### Import modules
import numpy as np
from sklearn.metrics import mean_squared_error
if weight == 'yes': # Computed weighted correlation coefficient
### mask
mask = 'yes'
if mask == 'yes':
latq = np.where(lats > 30)[0]
lats = lats[latq]
varx = varx[latq,:]
vary = vary[latq,:]
print('MASKING LATITUDES!')
### Create 2d meshgrid for weights
lon2,lat2 = np.meshgrid(lons,lats)
### Create 2d array of weights based on latitude
gw = np.cos(np.deg2rad(lat2))
### Calculate rmse
sq_err = (varx - vary)**2
rmse = np.sqrt((np.sum(sq_err*gw))/np.sum(gw))
elif weight == 'no':
### Root mean square error from sklearn (not weighted)
rmse = np.sqrt(mean_squared_error(varx.ravel(),vary.ravel()))
print('Completed: Computed NON-weighted correlation!')
else:
ValueError('Wrong weighted arguement in function!')
print('*Completed: Finished calc_RMSE function!')
return rmse
| 7,731 |
def sample(internal_nodes, alpha=0.5, beta=0.5, only_tree=False):
""" Generates a junction tree with order internal nodes with the junction tree expander.
Args:
internal_nodes (int): number of nodes in the underlying graph
alpha (float): parameter for the subtree kernel
beta (float): parameter for the subtree kernel
directory (string): path to
Returns:
NetworkX graph: a junction tree
"""
import trilearn.graph.decomposable as dlib
nodes = None
if type(internal_nodes) is int:
nodes = range(internal_nodes)
else:
nodes = internal_nodes
tree = JunctionTree()
#from trilearn.graph.junction_tree_gt import JunctionTreeGT
#tree = JunctionTreeGT()
tree.add_node(frozenset([nodes[0]]))
# print tree.nodes()
# for n in tree.nodes():
# lab = tuple(n)
# if len(n) == 1:
# lab = "("+str(list(n)[0])+")"
# tree.node[n] = {"color": "black", "label": lab}
for j in nodes[1:]:
if only_tree:
jte.sample(tree, j, alpha, beta, only_tree=only_tree)
else:
(tree, _, _, _, _, _) = jte.sample(tree, j, alpha, beta, only_tree=only_tree)
#print("vert dict: " + str(tree.gp.vert_dict))
#print("nodes: " + str(list(tree.vp.nodes)))
return tree
| 7,732 |
def _get_version_tuple():
"""
version as a tuple
"""
return major, minor, revision
| 7,733 |
def compare_activity_to_sector_flowamounts(fba_load, fbs_load,
activity_set, config):
"""
Function to compare the loaded flowbyactivity with the final flowbysector
by activityname (if exists) to target sector level
output, checking for data loss
:param fba_load: df, FBA loaded and mapped using FEDEFL
:param fbs_load: df, final FBS df
:param activity_set: str, activity set
:param config: dictionary, method yaml
:return: printout data differences between loaded FBA and FBS output,
save results as csv in local directory
"""
if check_activities_sector_like(fba_load):
vLog.debug('Not comparing loaded FlowByActivity to FlowBySector '
'ratios for a dataset with sector-like activities because '
'if there are modifications to flowamounts for a sector, '
'then the ratios will be different')
else:
# subset fba df
fba = fba_load[['Class', 'MetaSources', 'Flowable', 'Unit', 'FlowType',
'ActivityProducedBy', 'ActivityConsumedBy', 'Context',
'Location', 'LocationSystem', 'Year',
'FlowAmount']].drop_duplicates().reset_index(drop=True)
fba.loc[:, 'Location'] = US_FIPS
group_cols = ['ActivityProducedBy', 'ActivityConsumedBy', 'Flowable',
'Unit', 'FlowType', 'Context',
'Location', 'LocationSystem', 'Year']
fba_agg = aggregator(fba, group_cols)
fba_agg.rename(columns={'FlowAmount': 'FBA_amount'}, inplace=True)
# subset fbs df
fbs = fbs_load[['Class', 'SectorSourceName', 'Flowable', 'Unit',
'FlowType', 'SectorProducedBy', 'SectorConsumedBy',
'ActivityProducedBy', 'ActivityConsumedBy',
'Context', 'Location', 'LocationSystem', 'Year',
'FlowAmount']].drop_duplicates().reset_index(drop=True)
fbs = replace_NoneType_with_empty_cells(fbs)
fbs['ProducedLength'] = fbs['SectorProducedBy'].str.len()
fbs['ConsumedLength'] = fbs['SectorConsumedBy'].str.len()
fbs['SectorLength'] = fbs[['ProducedLength',
'ConsumedLength']].max(axis=1)
fbs.loc[:, 'Location'] = US_FIPS
group_cols = ['ActivityProducedBy', 'ActivityConsumedBy', 'Flowable',
'Unit', 'FlowType', 'Context', 'Location',
'LocationSystem', 'Year', 'SectorLength']
fbs_agg = aggregator(fbs, group_cols)
fbs_agg.rename(columns={'FlowAmount': 'FBS_amount'}, inplace=True)
# merge compare 1 and compare 2
df_merge = fba_agg.merge(
fbs_agg, left_on=['ActivityProducedBy', 'ActivityConsumedBy',
'Flowable', 'Unit', 'FlowType', 'Context',
'Location', 'LocationSystem', 'Year'],
right_on=['ActivityProducedBy', 'ActivityConsumedBy',
'Flowable', 'Unit', 'FlowType', 'Context',
'Location', 'LocationSystem', 'Year'],
how='left')
df_merge['Ratio'] = df_merge['FBS_amount'] / df_merge['FBA_amount']
# reorder
df_merge = df_merge[['ActivityProducedBy', 'ActivityConsumedBy',
'Flowable', 'Unit', 'FlowType', 'Context',
'Location', 'LocationSystem', 'Year',
'SectorLength', 'FBA_amount', 'FBS_amount',
'Ratio']]
# keep onlyrows of specified sector length
comparison = df_merge[
df_merge['SectorLength'] == sector_level_key[
config['target_sector_level']]].reset_index(drop=True)
tolerance = 0.01
comparison2 = comparison[(comparison['Ratio'] < 1 - tolerance) |
(comparison['Ratio'] > 1 + tolerance)]
if len(comparison2) > 0:
vLog.info('There are %s combinations of flowable/context/sector '
'length where the flowbyactivity to flowbysector ratio '
'is less than or greater than 1 by %s',
len(comparison2), str(tolerance))
# include df subset in the validation log
# only print rows where flowamount ratio is less t
# han 1 (round flowamountratio)
df_v = comparison2[comparison2['Ratio'].apply(
lambda x: round(x, 3) < 1)].reset_index(drop=True)
# save to validation log
log.info('Save the comparison of FlowByActivity load '
'to FlowBySector ratios for %s in validation log',
activity_set)
# if df not empty, print, if empty, print string
if df_v.empty:
vLogDetailed.info('Ratios for %s all round to 1', activity_set)
else:
vLogDetailed.info('Comparison of FlowByActivity load to '
'FlowBySector ratios for %s: '
'\n {}'.format(df_v.to_string()), activity_set)
| 7,734 |
def _fit_seasonal_model_with_gibbs_sampling(observed_time_series,
seasonal_structure,
num_warmup_steps=50,
num_results=100,
seed=None):
"""Builds a seasonality-as-regression model and fits it by Gibbs sampling."""
with tf.name_scope('fit_seasonal_model_with_gibbs_sampling'):
observed_time_series = sts_util.canonicalize_observed_time_series_with_mask(
observed_time_series)
dtype = observed_time_series.time_series.dtype
design_matrix = seasonality_util.build_fixed_effects(
num_steps=ps.shape(observed_time_series.time_series)[-2],
seasonal_structure=seasonal_structure,
dtype=dtype)
# Default priors.
# pylint: disable=protected-access
one = tf.ones([], dtype=dtype)
level_variance_prior = tfd.InverseGamma(concentration=16,
scale=16. * 0.001**2 * one)
level_variance_prior._upper_bound = one
slope_variance_prior = tfd.InverseGamma(concentration=16,
scale=16. * 0.05**2 * one)
slope_variance_prior._upper_bound = 0.01 * one
observation_noise_variance_prior = tfd.InverseGamma(
concentration=0.05, scale=0.05 * one)
observation_noise_variance_prior._upper_bound = 1.2 * one
# pylint: enable=protected-access
model = gibbs_sampler.build_model_for_gibbs_fitting(
observed_time_series=observed_time_series,
design_matrix=design_matrix,
weights_prior=tfd.Normal(loc=0., scale=one),
level_variance_prior=level_variance_prior,
slope_variance_prior=slope_variance_prior,
observation_noise_variance_prior=observation_noise_variance_prior)
return [
model,
gibbs_sampler.fit_with_gibbs_sampling(model,
observed_time_series,
num_results=num_results,
num_warmup_steps=num_warmup_steps,
seed=seed)
]
| 7,735 |
def deskew(data, angle, dx, dz, rotate=True, return_resolution=True, out=None):
"""
Args:
data (ndarray): 3-D array to apply deskew
angle (float): angle between the objective and coverslip, in degree
dx (float): X resolution
dz (float): Z resolution
rotate (bool, optional): rotate and crop the output
return_resolution (bool, optional): return deskewed X/Z resolution
out (ndarray, optional): array to store the result
"""
angle = radians(angle)
# shift along X axis, in pixels
shift = dz * cos(angle) / dx
logger.debug(f"layer shift: {shift:.04f} px")
# estimate new size
nw, nv, nu = data.shape
nz, ny, nx = nw, nv, nu + ceil(shift * (nw - 1))
# upload texture
ch = ChannelFormatDescriptor(32, 0, 0, 0, runtime.cudaChannelFormatKindFloat)
arr = CUDAarray(ch, nu, nw)
res = ResourceDescriptor(runtime.cudaResourceTypeArray, cuArr=arr)
address_mode = (runtime.cudaAddressModeBorder, runtime.cudaAddressModeBorder)
tex = TextureDescriptor(
address_mode, runtime.cudaFilterModeLinear, runtime.cudaReadModeElementType
)
# transpose
data = np.swapaxes(data, 0, 1)
data = np.ascontiguousarray(data)
data_in = data.astype(np.float32)
data_out = cp.empty((ny, nz, nx), np.float32)
for i, layer in enumerate(data_in):
arr.copy_from(layer) # TODO use stream
texobj = TextureObject(res, tex)
kernels["shear_kernel"](
(ceil(nx / 16), ceil(nz / 16)),
(16, 16),
(data_out[i, ...], texobj, nx, nz, nu, np.float32(shift)),
)
data_out = cp.swapaxes(data_out, 0, 1)
data_out = cp.asnumpy(data_out)
data_out = data_out.astype(data.dtype)
if return_resolution:
# new resolution
dz *= sin(angle)
return data_out, (dz, dx)
else:
return data_out
| 7,736 |
def process_data(path,stage = 'train'):
"""
train
test
sample_submission
"""
# loading the data
df = pd.read_csv(os.path.join(path,f'{stage}.csv'))
MASK = -1 # fill NA with -1
T_HIST = 10 # time history, last 10 games
# for cols "date", change to datatime
for col in df.filter(regex='date', axis=1).columns:
df[col] = pd.to_datetime(df[col])
# Creating some feature engineering
print('processing hitorical data...')
for i in tqdm(range(1, 11)): # range from 1 to 10
# Feat. difference of days
df[f'home_team_history_match_DIFF_day_{i}'] = (df['match_date'] - df[f'home_team_history_match_date_{i}']).dt.days
df[f'away_team_history_match_DIFF_days_{i}'] = (df['match_date'] - df[f'away_team_history_match_date_{i}']).dt.days
# Feat. difference of scored goals
df[f'home_team_history_DIFF_goal_{i}'] = df[f'home_team_history_goal_{i}'] - df[f'home_team_history_opponent_goal_{i}']
df[f'away_team_history_DIFF_goal_{i}'] = df[f'away_team_history_goal_{i}'] - df[f'away_team_history_opponent_goal_{i}']
# Results: multiple nested where
df[f'home_team_result_{i}'] = np.where(df[f'home_team_history_DIFF_goal_{i}'] > 0, 1,
(np.where(df[f'home_team_history_DIFF_goal_{i}'] == 0, 0,
np.where(df[f'home_team_history_DIFF_goal_{i}'].isna(),np.nan, -1))))
df[f'away_team_result_{i}'] = np.where(df[f'away_team_history_DIFF_goal_{i}'] > 0, 1,
(np.where(df[f'away_team_history_DIFF_goal_{i}'] == 0, 0,
np.where(df[f'away_team_history_DIFF_goal_{i}'].isna(), np.nan, -1))))
# Feat. difference of rating ("modified" ELO RATING)
df[f'home_team_history_ELO_rating_{i}'] = 1 / (1 + 10 ** ((df[f'home_team_history_opponent_rating_{i}'] - df[f'home_team_history_rating_{i}']) / 10))
df[f'away_team_history_ELO_rating_{i}'] = 1 / (1 + 10 ** ((df[f'away_team_history_opponent_rating_{i}'] - df[f'away_team_history_rating_{i}']) / 10))
# df[f'away_team_history_DIFF_rating_{i}'] = - df[f'away_team_history_opponent_rating_{i}']
# Feat. same coach id
df[f'home_team_history_SAME_coaX_{i}'] = np.where(df['home_team_coach_id'] == df[f'home_team_history_coach_{i}'], 1, 0)
df[f'away_team_history_SAME_coaX_{i}'] = np.where(df['away_team_coach_id'] == df[f'away_team_history_coach_{i}'], 1, 0)
# Feat. same league id
#df[f'home_team_history_SAME_leaG_{i}'] = np.where(df['league_id'] == df[f'home_team_history_league_id_{i}'],1, 0)
#df[f'away_team_history_SAME_leaG_{i}'] = np.where(df['league_id'] == df[f'away_team_history_league_id_{i}'],1, 0)
# Fill NA with -1
print('done')
df.fillna(MASK, inplace=True)
# le = LabelEncoder()
# df['home_team_name'] = le.fit_transform(df['home_team_name'])
# df['away_team_name'] = le.fit_transform(df['away_team_name'])
# df['league_name'] = le.fit_transform(df['league_name'])
# save targets
# y_train = train[['target_int']].to_numpy().reshape(-1, 1)
id = df['id'].copy()
drop_list = ['id', 'target', 'home_team_name', 'away_team_name']
if stage =='train':
y = df['target'].copy()
drop_list.append('target')
else:
y = None
# keep only some features
df.drop(drop_list, axis=1, inplace=True)
df['is_cup'] = df['is_cup'].replace({True: 1, False: 0})
# Exclude all date, league, coach columns
df.drop(df.filter(regex='date').columns, axis=1, inplace=True)
df.drop(df.filter(regex='league').columns, axis=1, inplace=True)
df.drop(df.filter(regex='coach').columns, axis=1, inplace=True)
# Store feature names
feature_names = list(df.columns)
# Scale features using statistics that are robust to outliers
RS = RobustScaler()
df = RS.fit_transform(df)
# Back to pandas.dataframe
df = pd.DataFrame(df, columns=feature_names)
df = pd.concat([id, df], axis=1)
# Pivot dataframe to create an input array for the LSTM network
feature_groups = ["home_team_history_is_play_home", "home_team_history_is_cup",
"home_team_history_goal", "home_team_history_opponent_goal",
"home_team_history_rating", "home_team_history_opponent_rating",
"away_team_history_is_play_home", "away_team_history_is_cup",
"away_team_history_goal", "away_team_history_opponent_goal",
"away_team_history_rating", "away_team_history_opponent_rating",
"home_team_history_match_DIFF_day", "away_team_history_match_DIFF_days",
"home_team_history_DIFF_goal", "away_team_history_DIFF_goal",
"home_team_history_ELO_rating", "away_team_history_ELO_rating",
"home_team_history_SAME_coaX", "away_team_history_SAME_coaX",
"home_team_history_SAME_leaG", "away_team_history_SAME_leaG",
"home_team_result", "away_team_result"]
# Pivot dimension (id*features) x time_history
x_pivot = pd.wide_to_long(df, stubnames=feature_groups,i='id', j='time', sep='_', suffix='\d+')
# Trying to keep the same id order
x = pd.merge(id, x_pivot, on="id")
x = x.drop(['id'], axis=1).to_numpy().reshape(-1, T_HIST, x_pivot.shape[-1])
return x,y
| 7,737 |
def rm_standard_dev(var,window):
"""
Smoothed standard deviation
"""
import pandas as pd
import numpy as np
print('\n\n-----------STARTED: Rolling std!\n\n')
rollingstd = np.empty((var.shape))
for ens in range(var.shape[0]):
for i in range(var.shape[2]):
for j in range(var.shape[3]):
series = pd.Series(var[ens,:,i,j])
rollingstd[ens,:,i,j] = series.rolling(window).std().to_numpy()
newdata = rollingstd[:,window:,:,:]
print('-----------COMPLETED: Rolling std!\n\n')
return newdata
| 7,738 |
def enable_scope(daq: ziDAQServer, device_id: str, *, single: int) -> None:
"""Enables the scope.
Args:
daq: Instance of a Zurich Instruments API session connected to a Data
Server. The device with identifier device_id is assumed to already
be connected to this instance.
device_id: SHFQA device identifier, e.g. `dev12004` or 'shf-dev12004'.
single: 0 = continuous mode, 1 = single-shot.
"""
daq.setInt(f"/{device_id}/scopes/0/single", single)
path = f"/{device_id}/scopes/0/enable"
if daq.getInt(path) == 1:
daq.syncSetInt(path, 0)
wait_for_state_change(daq, path, 0)
daq.syncSetInt(path, 1)
wait_for_state_change(daq, path, 1)
| 7,739 |
def test_outdated_local(tmpdir, local, remote):
"""Test with remote changes not pulled.
:param tmpdir: pytest fixture.
:param local: conftest fixture.
:param remote: conftest fixture.
"""
# Setup separate local repo now before pushing changes to it from the primary local repo.
local_outdated = tmpdir.ensure_dir('local_outdated')
pytest.run(local_outdated, ['git', 'clone', '--branch', 'master', remote, '.'])
sha = pytest.run(local_outdated, ['git', 'rev-parse', 'HEAD']).strip()
remotes = list_remote(str(local_outdated))
expected = [
[sha, 'feature', 'heads'],
[sha, 'master', 'heads'],
[sha, 'annotated_tag', 'tags'],
[sha, 'light_tag', 'tags'],
]
assert remotes == expected
# Make changes from primary local and push to common remote.
local.join('README').write('changed')
pytest.run(local, ['git', 'commit', '-am', 'Changed'])
pytest.run(local, ['git', 'push', 'origin', 'master'])
sha2 = pytest.run(local, ['git', 'rev-parse', 'HEAD']).strip()
remotes = list_remote(str(local))
expected = [
[sha, 'feature', 'heads'],
[sha2, 'master', 'heads'],
[sha, 'annotated_tag', 'tags'],
[sha, 'light_tag', 'tags'],
]
assert remotes == expected
# Run list_remote() on outdated repo and verify it still gets latest refs.
remotes = list_remote(str(local_outdated))
assert remotes == expected
| 7,740 |
def load_letter(folder, min_num_images):
"""Load the data for a single letter label."""
image_files = os.listdir(folder)
dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
dtype=np.float32)
image_index = 0
print(folder)
for image in os.listdir(folder):
image_file = os.path.join(folder, image)
try:
image_data = (ndimage.imread(image_file).astype(float) -
pixel_depth / 2) / pixel_depth
if image_data.shape != (image_size, image_size):
raise Exception('Unexpected image shape: %s' % str(image_data.shape))
dataset[image_index, :, :] = image_data
image_index += 1
except IOError as e:
print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.')
num_images = image_index
dataset = dataset[0:num_images, :, :]
if num_images < min_num_images:
raise Exception('Many fewer images than expected: %d < %d' %
(num_images, min_num_images))
print('Full dataset tensor:', dataset.shape)
print('Mean:', np.mean(dataset))
print('Standard deviation:', np.std(dataset))
return dataset
| 7,741 |
def visualizeTimeSeriesCategorization(dataName, saveDir, numberOfLagsToDraw=3, autocorrelationBased=True):
"""Visualize time series classification.
Parameters:
dataName: str
Data name, e.g. "myData_1"
saveDir: str
Path of directories pointing to data storage
numberOfLagsToDraw: boolean, Default 3
First top-N lags (or frequencies) to draw
autocorrelationBased: boolean, Default True
Whether autocorrelation or frequency based
Returns:
None
Usage:
visualizeTimeSeriesClassification('myData_1', '/dir1/dir2/')
"""
info = 'Autocorrelations' if autocorrelationBased else 'Periodograms'
def internal(className):
print('\n\n%s of Time Series:'%(className))
clusteringObject = dataStorage.read(saveDir + 'consolidatedGroupsSubgroups/' + dataName + '_%s_%s'%(className,info) + '_GroupsSubgroups')
if clusteringObject is None:
print('Clustering object not found')
return
print('Plotting Dendrogram with Heatmaps.')
visualizationFunctions.makeDendrogramHeatmapOfClusteringObject(clusteringObject, saveDir, dataName + '_%s_%sBased'%(className,info), AutocorrNotPeriodogr=autocorrelationBased)
return
for lag in range(1,numberOfLagsToDraw + 1):
internal('LAG%s'%(lag))
internal('SpikeMax')
internal('SpikeMin')
return None
| 7,742 |
def refund(payment_information: Dict, connection_params) -> Dict:
"""Refund a payment using the culqi client.
But it first check if the given payment instance is supported
by the gateway.
It first retrieve a `charge` transaction to retrieve the
payment id to refund. And return an error with a failed transaction
if the there is no such transaction, or if an error
from culqi occurs during the refund."""
error = check_payment_supported(payment_information=payment_information)
response_has_errors = False
if error:
response = get_error_response(
payment_information.amount, error=error)
else:
setup_client(**connection_params)
try:
payload = format_culqui_payload(
payment_information, TransactionKind.REFUND)
response = culqipy.Refund.create(payload)
print(f"DATA::response::{response}")
# Fix: get specific errors
except Exception as error:
response_has_errors = True
response = get_error_response(
payment_information.amount, error=error)
if not response_has_errors:
if response.get('object', None) == 'error':
error = response.get('user_message', None)
if error is None:
error = response.get('merchant_message', None)
if error is None:
error = 'Unkonw error!'
response = get_error_response(
payment_information.amount, error=error,
id=payment_information.token)
else:
clean_culqi_response(response)
return _generate_response(
payment_information=payment_information,
kind=TransactionKind.REFUND, data=response)
| 7,743 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Howler',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text',
metavar='str',
help='Input text or file')
parser.add_argument('-o',
'--outfile',
help='Output filename',
metavar='str',
type=str,
default='')
args = parser.parse_args()
#if the args.text is a file name (checks using os.path.isfile)
if os.path.isfile(args.text):
args.text = open(args.text).read().rstrip()
#then open args.text, read its name and strip the whitespace out
return args
| 7,744 |
def main ():
"""The function that is called in a command line context. """
# Make sure we aren't unintentionally overwriting an input file
nonOverlapping([featListFile,inputFile,featDefsFile],[outputFile,templateFile])
# Initialize whatever script variables have to be initialized
initializeScriptData()
# Define the script's built-in features
defineBuiltInFeatures()
# Read any additional feature definitions that may have been specified
if (featDefsFile):
readExtraFeatDefsFile(featDefsFile)
# Read the list of feature entries we will be working with
readFeatureListFile(featListFile)
# Print them out if we are in 'verbose' mode.
if (verbose):
printFeatsUsed()
# Featurize the file.
writeFeatMatrixFile(inputFile,outputFile,labeled)
# Write out the template file if a template file argument was provided.
if (templateFile):
writeTemplateFile(templateFile)
| 7,745 |
def _ssim_map(
X: torch.Tensor,
Y: torch.Tensor,
data_range: float,
win: torch.Tensor,
K: Tuple[float, float] = (0.01, 0.03),
scales: Tuple[float, float, float] = (1, 1, 1),
gradient_based: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given two tensors it calculates the resulting SSIM and contrast sensitivity maps.
Args:
X (torch.Tensor): images
Y (torch.Tensor): images
data_range (float): value range of input images.
win (torch.Tensor): 1-D gauss kernel
K (Tuple[float,float]): stability constants (K1, K2). Defaults to (0.01, 0.03).
gradient_based (bool): whether or not to use gradient based ssim.
Returns:
torch.Tensor: SSIM map
torch.Tensor: contrast sensitivity map
References:
[1] Wang, Z., Bovik, A.C., Sheikh, H.R. and Simoncelli, E.P., 2004.
Image quality assessment: from error visibility to structural similarity.
IEEE transactions on image processing, 13(4), pp.600-612.
"""
K1, K2 = K
alpha, beta, gamma = scales
C1 = (K1 * data_range) ** 2
C2 = (K2 * data_range) ** 2
C3 = C2 / 2
win = win.to(X.device, dtype=X.dtype)
# TODO: Replace this with fftconvolution
mu1 = _gaussian_filter(X, win)
mu2 = _gaussian_filter(Y, win)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
print(f"mu1: {torch.isnan(mu1).any()}")
print(f"mu2: {torch.isnan(mu2).any()}")
print(f"mu1_sq: {torch.isnan(mu1_sq).any()}")
print(f"mu2_sq: {torch.isnan(mu2_sq).any()}")
print(f"mu1_mu2: {torch.isnan(mu1_mu2).any()}")
# Ref 1 - Sec 3.B - Eq 6
luminance = (2 * mu1_mu2 + C1) / (mu1_sq + mu2_sq + C1)
print(f"Luminance: {torch.isnan(luminance).any()}")
if gradient_based:
X = _gradient_map(input=X)
Y = _gradient_map(input=Y)
mu1 = _gaussian_filter(X, win)
mu2 = _gaussian_filter(Y, win)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2
# TODO: Understand why it is squared
sigma1_sq = _gaussian_filter(X * X, win) - mu1_sq
sigma2_sq = _gaussian_filter(Y * Y, win) - mu2_sq
sigma12 = _gaussian_filter(X * Y, win) - mu1_mu2
print(torch.min(sigma1_sq))
print(torch.min(sigma2_sq))
sigma1 = torch.sqrt(sigma1_sq)
sigma2 = torch.sqrt(sigma2_sq)
print(f"sigma1: {torch.isnan(sigma1).any()}")
print(f"sigma2: {torch.isnan(sigma2).any()}")
print(f"sigma12: {torch.isnan(sigma12).any()}")
print(f"sigma1_sq: {torch.isnan(sigma1_sq).any()}")
print(f"sigma2_sq: {torch.isnan(sigma2_sq).any()}")
# Ref 1 - Sec 3.B - Eq 9
contrast = (2 * sigma1 * sigma2 + C2) / (sigma1_sq + sigma2_sq + C2)
print(f"Contrast: {torch.isnan(contrast).any()}")
# Ref 1 - Sec 3.B - Eq 10
structure = (sigma12 + C3) / (sigma1 * sigma2 + C3)
print(f"Structure {torch.isnan(structure).any()}")
# Ref 1 - Sec 3.B - Eq 12
luminance = torch.pow(luminance, alpha)
contrast = torch.pow(contrast, beta)
structure = torch.pow(structure, gamma)
ssim_map = luminance * contrast * structure
return ssim_map, contrast
| 7,746 |
def check_random_state(seed):
"""Turn `seed` into a `np.random.RandomState` instance.
Parameters
----------
seed : {None, int, `numpy.random.Generator`,
`numpy.random.RandomState`}, optional
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
singleton is used.
If `seed` is an int, a new ``RandomState`` instance is used,
seeded with `seed`.
If `seed` is already a ``Generator`` or ``RandomState`` instance then
that instance is used.
Returns
-------
seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
Random number generator.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, (numbers.Integral, np.integer)):
return np.random.default_rng(seed)
if isinstance(seed, (np.random.RandomState, np.random.Generator)):
return seed
raise ValueError(
"%r cannot be used to seed a numpy.random.RandomState" " instance" % seed
)
| 7,747 |
def power3_sum_2method():
"""
Input:
nothing, it have everything it needs.
Output:
sum: summ of all numbers which is power of 3
and fit in between 0 and upper bound == 1000000
"""
k = 0
sum = 0
while True:
a = 3**k
k += 1
if a < 1000000:
sum += a
else:
break
return sum
| 7,748 |
def bitwise_right_shift(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None):
"""
The BitwiseRightShift operation
The arguments for this function are as follows:
:param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string
:param extent_type: one of "FirstOf", "IntersectionOf", "UnionOf", "LastOf"
:param cellsize_type: one of "FirstOf", "MinOf", "MaxOf, "MeanOf", "LastOf"
:param astype: output pixel type
:return: the output raster
"""
return local(rasters, 15, extent_type=extent_type, cellsize_type=cellsize_type, astype=astype)
| 7,749 |
def strip_comments(line):
"""Strips comments from a line and return None if the line is empty
or else the contents of line with leading and trailing spaces removed
and all other whitespace collapsed"""
commentIndex = line.find('//')
if commentIndex is -1:
commentIndex = len(line)
line = re.sub(r'\s+', ' ', line[:commentIndex].strip())
if line == '':
return None
else:
return line
| 7,750 |
def fft_pxscale(header,wave):
"""Compute conversion scale from telescope space to sky space.
Parameters
----------
ima : array
2D Telescope pupil model.
Returns
-------
fftscale : float
The frequency scale in sky space.
Example
-------
.. code-block:: python
fftscale = fft_pxscale(ima)
"""
#size of the image. This should be taken from the header.
gridsize = header['NAXIS1']
#pixel scale of the image. This should be taken from the header.
pxscale_mod = header['PIXSCALE'] #in meters/px
#1D FFT of the gridsize.
fft_freq=np.fft.fftfreq(gridsize,pxscale_mod)
#wavelength of the desires psf. This is a input of the user, wavelength in microns
wave = (getQuantity(wave,recognized_units=UNITS['WAVE']))
lam = wave.to(u.m) #in meters
#re-orginizing the 1D FFT to match with the grid.
roll=np.floor(gridsize//2).astype("int")
freq = np.fft.fftshift(fft_freq)
##
## pxscale -> fftscale
fftscale=np.diff(freq)[0] ## cycles / mas per pixel in FFT image
mas2rad=np.deg2rad(1./3600000.) ## mas per rad
fftscale = fftscale/mas2rad * lam ## meters baseline per px in FFT image at a given wavelength
logging.info("Pixel scale in PSF image is: %g mas per pixel" % fftscale.value)
return fftscale.value
| 7,751 |
def parse_git_submodules(gitmodules_data):
"""Parse a .gitmodules file to extract a { name -> url } map from it."""
result = {}
# NOTE: configparser.ConfigParser() doesn't seem to like the file
# (i.e. read_string() always returns None), so do the parsing
# manually here.
section_name = None
in_submodule_section = False
submodule_name = None
submodule_prefix = 'submodule "'
urls = {}
branches = {}
for line in gitmodules_data.splitlines():
if line.startswith('['):
section_name = line[1:-1]
is_submodule_section = section_name.startswith(submodule_prefix)
if is_submodule_section:
submodule_name = section_name[len(submodule_prefix):-1]
elif is_submodule_section:
key, _, value = line.strip().partition('=')
if not value:
continue
key = key.strip()
value = value.strip()
if key == 'url':
urls[submodule_name] = value
elif key == 'branch':
branches[submodule_name] = value
result = {}
for submodule, url in urls.iteritems():
branch = branches.get(submodule)
if not branch:
branch = get_git_remote_ref(url, 'heads/master')
result[submodule] = '%s@%s' % (url, branch)
return result
| 7,752 |
def get_model_cases(dir_path: pathlib.Path) -> Dict[str, Dict[str, str]]:
"""
Returns the Zen model case for each test if it exists.
:param dir_path: The path to the directory containing the DIFFERENCES directory.
"""
model_cases = defaultdict(dict) # type: Dict[str, Dict[str, str]]
queries_dir = dir_path / QUERIES
expected_res_dir = dir_path / QUERY_RESPONSES
tag_dir = None
if queries_dir.exists() and queries_dir.is_dir():
tag_dir = queries_dir
elif expected_res_dir.exists() and expected_res_dir.is_dir():
tag_dir = expected_res_dir
if isinstance(tag_dir, pathlib.Path):
for queries_file in tag_dir.iterdir():
with open(queries_file, 'r') as qf_fp:
queries_info = json.load(qf_fp)
for qinfo in queries_info:
if "ZenResponseTag" in qinfo:
query_str = qinfo["Query"]["Name"] + ":" +\
qinfo["Query"]["Type"]
model_cases[queries_file.stem][query_str] = qinfo["ZenResponseTag"]
return model_cases
| 7,753 |
def _format_date(event):
"""Returns formated date json object for event"""
old_date = event["date"]
term = event["term"]
dates = old_date.split("-")
if len(dates) == 1:
is_range = False
else:
is_range = True
is_range = (len(dates) > 1)
if is_range:
start_date = dates[0]
end_date = dates[-1]
else:
start_date = dates[0]
end_date = dates[0]
new_start_date = _format_date_string(start_date, term)
new_end_date = _format_date_string(end_date, term)
date = {
"start_date": new_start_date,
"end_date": new_end_date,
"range": is_range,
}
return date
| 7,754 |
def fetch(bibcode, filename=None, replace=None):
"""
Attempt to fetch a PDF file from ADS. If successful, then
add it into the database. If the fetch succeeds but the bibcode is
not in th database, download file to current folder.
Parameters
----------
bibcode: String
ADS bibcode of entry to update.
filename: String
Filename to assign to the PDF file. If None, get from
guess_name() funcion.
Replace: Bool
If True, enforce replacing a PDF regardless of a pre-existing one.
If None (default), only ask when fetched PDF comes from arxiv.
Returns
-------
filename: String
If successful, return the full path of the file name.
If not, return None.
"""
arxiv = False
print('Fetching PDF file from Journal website:')
req = request_ads(bibcode, source='journal')
if req is None:
return
if req.status_code != 200:
print('Fetching PDF file from ADS website:')
req = request_ads(bibcode, source='ads')
if req is None:
return
if req.status_code != 200:
print('Fetching PDF file from ArXiv website:')
req = request_ads(bibcode, source='arxiv')
arxiv = True
if replace is None:
replace = False
if req is None:
return
if replace is None:
replace = True
if req.status_code == 200:
if bm.find(bibcode=bibcode) is None:
if filename is None:
filename = f'{bibcode}.pdf'
with builtin_open(filename, 'wb') as f:
f.write(req.content)
print(f"Saved PDF to: '{filename}'.\n"
"(Note that BibTex entry is not in the Bibmanager database)")
else:
filename = set_pdf(
bibcode, bin_pdf=req.content, filename=filename, arxiv=arxiv,
replace=replace)
return filename
print('Could not fetch PDF from any source.')
| 7,755 |
def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop multiple images.
Parameters
----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.crop``.
Returns
-------
numpy.array
A list of processed images.
"""
h, w = x[0].shape[row_index], x[0].shape[col_index]
if (h < hrg) or (w < wrg):
raise AssertionError("The size of cropping should smaller than or equal to the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg))
w_offset = int(np.random.uniform(0, w - wrg))
results = []
for data in x:
results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset])
return np.asarray(results)
else:
# central crop
h_offset = int(np.floor((h - hrg) / 2.))
w_offset = int(np.floor((w - wrg) / 2.))
results = []
for data in x:
results.append(data[h_offset:h - h_offset, w_offset:w - w_offset])
return np.asarray(results)
| 7,756 |
def read_payload_hiding_places(data, orig_filename, vm, vba_code, vba):
"""
Read in text values from all of the various places in Office
97/2000+ that text values can be hidden. This reads values from
things like ActiveX captions, embedded image alternate text,
document variables, form variables, etc.
@param (data) The contents (bytes) of the Office file being
analyzed.
@param orig_filename (str) The name of the Office file being
analyzed.
@param vm (ViperMonkey object) The ViperMonkey emulation engine
object that will do the emulation. The read values will be saved
in the given emulation engine.
@param vba_code (str) The VB code that will be emulated.
@param vba (VBA_Parser object) The olevba VBA_Parser object for
reading the Office file being analyzed.
"""
# Pull out document variables.
_read_payload_doc_vars(data, orig_filename, vm)
# Pull text associated with document comments.
_read_payload_doc_comments(data, vm)
# Pull text associated with Shapes() objects.
_read_payload_shape_text(data, vm)
# Pull embedded files.
_get_embedded_files(data, vm)
# Pull text associated with InlineShapes() objects.
_read_payload_inline_shape_text(data, vm)
# Pull out embedded OLE form textbox text.
_read_payload_textbox_text(data, vba_code, vm)
# Pull out custom document properties.
_read_payload_custom_doc_props(data, vm)
# Pull text associated with embedded objects.
_read_payload_embedded_obj_text(data, vm)
# Pull out the document text.
log.info("Reading document text and tables...")
vm.doc_text, vm.doc_tables = _read_doc_text('', data=data)
# Read text from form variables.
_read_payload_form_vars(vba, vm)
# Save the form strings.
#sys.exit(0)
_read_payload_form_strings(vba, vm)
# Save DefaultTargetFrame value. This only works for 2007+ files.
_read_payload_default_target_frame(data, vm)
| 7,757 |
def value_loss_given_predictions(value_prediction,
rewards,
reward_mask,
gamma,
epsilon,
value_prediction_old=None):
"""Computes the value loss given the prediction of the value function.
Args:
value_prediction: np.ndarray of shape (B, RT+1, 1)
rewards: np.ndarray of shape (B, RT) of rewards.
reward_mask: np.ndarray of shape (B, RT), the mask over rewards.
gamma: float, discount factor.
epsilon: float, clip-fraction, used if value_value_prediction_old isn't None
value_prediction_old: np.ndarray of shape (B, RT+1, 1) of value predictions
using the old parameters. If provided, we incorporate this in the loss as
well. This is from the OpenAI baselines implementation.
Returns:
Pair (value_loss, summaries), where value_loss is the average L2 value loss,
averaged over instances where reward_mask is 1. Summaries is a dict of
summaries collected during value loss computation.
"""
B, RT = rewards.shape # pylint: disable=invalid-name
assert (B, RT) == reward_mask.shape
assert (B, RT + 1) == value_prediction.shape
value_prediction = value_prediction[:, :-1] * reward_mask # (B, RT)
r2g = rewards_to_go(rewards, reward_mask, gamma=gamma) # (B, RT)
loss = (value_prediction - r2g)**2
# From the baselines implementation.
if value_prediction_old is not None:
value_prediction_old = value_prediction_old[:, :-1] * reward_mask # (B, RT)
v_clipped = value_prediction_old + np.clip(
value_prediction - value_prediction_old, -epsilon, epsilon)
v_clipped_loss = (v_clipped - r2g)**2
loss = np.maximum(v_clipped_loss, loss)
# Take an average on only the points where mask != 0.
value_loss = np.sum(loss) / np.sum(reward_mask)
summaries = {
'value_loss': value_loss,
}
return (value_loss, summaries)
| 7,758 |
def build_pkt(pkt):
"""Build and return a packet and eth type from a dict."""
def serialize(layers):
"""Concatenate packet layers and serialize."""
result = packet.Packet()
for layer in reversed(layers):
result.add_protocol(layer)
result.serialize()
return result
layers = []
assert 'eth_dst' in pkt and 'eth_src' in pkt
ethertype = None
if 'arp_source_ip' in pkt and 'arp_target_ip' in pkt:
ethertype = ether.ETH_TYPE_ARP
arp_code = pkt.get('arp_code', arp.ARP_REQUEST)
layers.append(arp.arp(
src_ip=pkt['arp_source_ip'],
dst_ip=pkt['arp_target_ip'],
opcode=arp_code))
elif 'ipv6_src' in pkt and 'ipv6_dst' in pkt:
ethertype = ether.ETH_TYPE_IPV6
if 'router_solicit_ip' in pkt:
layers.append(icmpv6.icmpv6(
type_=icmpv6.ND_ROUTER_SOLICIT))
elif 'neighbor_advert_ip' in pkt:
layers.append(icmpv6.icmpv6(
type_=icmpv6.ND_NEIGHBOR_ADVERT,
data=icmpv6.nd_neighbor(
dst=pkt['neighbor_advert_ip'],
option=icmpv6.nd_option_sla(hw_src=pkt['eth_src']))))
elif 'neighbor_solicit_ip' in pkt:
layers.append(icmpv6.icmpv6(
type_=icmpv6.ND_NEIGHBOR_SOLICIT,
data=icmpv6.nd_neighbor(
dst=pkt['neighbor_solicit_ip'],
option=icmpv6.nd_option_sla(hw_src=pkt['eth_src']))))
elif 'echo_request_data' in pkt:
layers.append(icmpv6.icmpv6(
type_=icmpv6.ICMPV6_ECHO_REQUEST,
data=icmpv6.echo(id_=1, seq=1, data=pkt['echo_request_data'])))
layers.append(ipv6.ipv6(
src=pkt['ipv6_src'],
dst=pkt['ipv6_dst'],
nxt=inet.IPPROTO_ICMPV6))
elif 'ipv4_src' in pkt and 'ipv4_dst' in pkt:
ethertype = ether.ETH_TYPE_IP
proto = inet.IPPROTO_IP
if 'echo_request_data' in pkt:
echo = icmp.echo(id_=1, seq=1, data=pkt['echo_request_data'])
layers.append(icmp.icmp(type_=icmp.ICMP_ECHO_REQUEST, data=echo))
proto = inet.IPPROTO_ICMP
net = ipv4.ipv4(src=pkt['ipv4_src'], dst=pkt['ipv4_dst'], proto=proto)
layers.append(net)
elif 'actor_system' in pkt and 'partner_system' in pkt:
ethertype = ether.ETH_TYPE_SLOW
layers.append(slow.lacp(
version=1,
actor_system=pkt['actor_system'],
actor_port=1,
partner_system=pkt['partner_system'],
partner_port=1,
actor_key=1,
partner_key=1,
actor_system_priority=65535,
partner_system_priority=1,
actor_port_priority=255,
partner_port_priority=255,
actor_state_defaulted=0,
partner_state_defaulted=0,
actor_state_expired=0,
partner_state_expired=0,
actor_state_timeout=1,
partner_state_timeout=1,
actor_state_collecting=1,
partner_state_collecting=1,
actor_state_distributing=1,
partner_state_distributing=1,
actor_state_aggregation=1,
partner_state_aggregation=1,
actor_state_synchronization=pkt['actor_state_synchronization'],
partner_state_synchronization=1,
actor_state_activity=0,
partner_state_activity=0))
elif 'chassis_id' in pkt and 'port_id' in pkt:
ethertype = ether.ETH_TYPE_LLDP
return valve_packet.lldp_beacon(
pkt['eth_src'], pkt['chassis_id'], str(pkt['port_id']), 1,
org_tlvs=pkt.get('org_tlvs', None),
system_name=pkt.get('system_name', None))
assert ethertype is not None, pkt
if 'vid' in pkt:
tpid = ether.ETH_TYPE_8021Q
layers.append(vlan.vlan(vid=pkt['vid'], ethertype=ethertype))
else:
tpid = ethertype
eth = ethernet.ethernet(
dst=pkt['eth_dst'],
src=pkt['eth_src'],
ethertype=tpid)
layers.append(eth)
result = serialize(layers)
return result
| 7,759 |
def make_file_prefix(run, component_name):
"""
Compose the run number and component name into string prefix
to use with filenames.
"""
return "{}_{}".format(component_name, run)
| 7,760 |
def identifier_needs_escaping(text):
"""
Slightly slow, but absolutely correct determination if a given symbol _must_ be escaped.
Necessary when you might be generating column names that could be a reserved keyword.
>>> identifier_needs_escaping("my_column")
False
>>> identifier_needs_escaping("my_column3424")
False
>>> identifier_needs_escaping("my column with spaces")
True
>>> identifier_needs_escaping("mycolumn;")
True
>>> identifier_needs_escaping("SELECT")
True
>>> identifier_needs_escaping("my_column.blah")
True
>>> identifier_needs_escaping("UPDATE")
True
>>> identifier_needs_escaping("column ")
True
"""
# TODO: Replace with custom caching decorator?
global _ident_needs_escaping_cache
if text not in _ident_needs_escaping_cache:
try:
ast = sql_subexpr_ast(text, "identifier")
_ident_needs_escaping_cache[text] = not (
isinstance(ast, Identifier) and ast.text == text
)
except Exception as e:
_ident_needs_escaping_cache[text] = True
return _ident_needs_escaping_cache[text]
| 7,761 |
def initialize_lock_and_key_ciphers() -> Dict[str, VigenereCipher]:
"""[summary]
Returns:
Dict[VigenereCipher]: [description]"""
ciphers = {}
with open(CIPHER_RESOURCE, "r") as cipher_resource_file:
cipher_data = load(cipher_resource_file, Loader=FullLoader)
for cipher_key_name, cipher_keys in cipher_data.items():
ciphers[cipher_key_name] = VigenereCipher(key=cipher_keys['key'], alphabet=cipher_keys['alphabet'])
return ciphers
| 7,762 |
def download(redownload=False):
"""Download webpages of retsinformation.dk.
Parameters
----------
redownload : bool, optional
Controls whether the webpages should be redownloaded.
Notes
-----
This function uses the `wget` program, so it will need to be installed.
Download may take considerable time. There is a wait of 5 seconds between
requests.
PDF and print pages are left out, e.g.,
https://www.retsinformation.dk/print.aspx?id=206363
https://www.retsinformation.dk/pdfPrint.aspx?id=206363
There seems to be lots of pages where reporting "Last-modified header
missing" which means the page is downloaded a new.
"""
logger = logging.getLogger(__name__)
make_data_directory()
test_filename = join(
data_directory(), 'www.retsinformation.dk', 'Forms',
'R0710.aspx?id=207290')
if not redownload and isfile(test_filename):
message = 'Not downloading as the file {} exists'
logger.debug(message.format(test_filename))
return
directory = data_directory()
logger.info('Downloading Retsinformation.dk corpus to {}'.format(
directory))
call(['wget',
'-w', '5', # Wait five seconds
'--recursive',
'-l', 'inf',
# '--no-clobber',
'--timestamping',
'--exclude-directories', '/includes,/js',
'--reject-regex', '"(print)|(pdfPrint)"',
DOWNLOAD_URL],
cwd=directory)
logger.debug('Retsinformation.dk corpus downloaded')
| 7,763 |
def add_service():
"""
Used to register a new service
"""
form = ServiceForm()
if form.validate_on_submit():
try:
srv = Services()
srv.populate_from_form(form)
srv.authentication.value = {"db":request.form.get('authdb'),"user":request.form.get('authuser'),"pswd":request.form.get("authpass")}
srv.save()
flash('Datele au fost adaugate!', category='alert-success')
return redirect(url_for('services.list_services'))
except Exception as err:
flash('Datele nu pot fi adaugate!', category='alert-danger')
return render_template('services/settings/add.html', pagetitle='Adauga serviciu', form=form)
| 7,764 |
def f_columnas_pips(datos):
"""
Parameters
----------
datos : pandas.DataFrame : df con información de transacciones ejecutadas en Oanda,
después de haber ejecutado f_columnas_tiempos
Returns
-------
datos : pandas.DataFrame : df modificado
Debugging
-------
datos = 'f_leer_archivo("archivo_tradeview_1.csv")
"""
datos['pips'] = [(datos.closeprice[i]-datos.openprice[i])*f_pip_size(datos.symbol[i]) for i in range(len(datos))]
datos['pips'][datos.type=='sell'] *= -1
datos['pips_acm'] = datos.pips.cumsum()
datos['profit_acm'] = datos['profit'].cumsum()
return datos.copy()
| 7,765 |
def parse_resolution(resolution):
"""
return: width, height, resolution
"""
resolution = resolution.strip()
splits = resolution.split(',')
return int(splits[0]), int(splits[1]), int(splits[2])
| 7,766 |
def link_cube(cube, locale, provider=None, namespace=None,
ignore_missing=False):
"""Links dimensions to the `cube` in the `context` object. The `context`
object should implement a function `dimension(name, locale, namespace,
provider)`. Modifies cube in place, returns the cube.
"""
# TODO: change this to: link_cube(cube, locale, namespace, provider)
# Assumption: empty cube
linked = set()
for dim_name in list(cube.dimension_links.keys()):
if dim_name in linked:
raise ModelError("Dimension '{}' linked twice"
.format(dim_name))
try:
dim = find_dimension(dim_name, locale,
provider=provider,
namespace=namespace)
except TemplateRequired as e:
raise ModelError("Dimension template '%s' missing" % dim_name)
if not dim and not ignore_missing:
raise CubesError("Dimension '{}' not found.".format(dim_name))
cube.link_dimension(dim)
return cube
| 7,767 |
def _parser() -> argparse.Namespace:
"""Take care of all the argparse stuff.
:returns: the args
"""
# parser = GooeyParser(description='Remove : from data files')
parser = argparse.ArgumentParser(description='Combines Nods using ')
parser.add_argument('listspectra', help='List of spectra to combine.', default=False)
parser.add_argument('-o', "--optimal-nods", help="Optimal nod bool matrix file.")
parser.add_argument("-s", "--spectralcoords", default=False, action="store_true",
help="Turn spectra into spectral coordinates first before adding. Default=False")
parser.add_argument("-n", "--nod_num", help="Number of nods in the nod cycle, default=8", default=8, type=int)
parser.add_argument("-c", "--combination", help="Nod combination method, default=all means do all three.",
default="all", choices=["all", "optimal", "non-opt", "mix"])
parser.add_argument("-u", "--unnorm", help="Combine the un-normalized nods.", action="store_true")
parser.add_argument("--snr", help="Show snr of continuum.", action="store_true")
parser.add_argument("-p", "--plot", help="Show the plots.", action="store_true")
parser.add_argument("--output_verify", help="Fits file verification mode", default="fix+warn")
parser.add_argument("-r", "--overwrite", help="Overwrite output file if already exists", action="store_true")
args = parser.parse_args()
return args
| 7,768 |
def get_arguments(func):
"""Returns list of arguments this function has."""
if hasattr(func, '__code__'):
# Regular function.
return inspect.getargspec(func).args
elif hasattr(func, '__call__'):
# Callable object.
print(func)
return _get_arguments(func.__call__)
elif hasattr(func, 'func'):
# Partial function.
return _get_arguments(func.func)
| 7,769 |
def _check(isamAppliance, name):
"""
Check if suffix exists
"""
ret_obj = get(isamAppliance)
check_value, warnings = False, ret_obj['warnings']
if warnings == []:
for suffix in ret_obj['data']:
if suffix['name'] == name:
logger.info("Suffix found in embedded ldap: " + name)
check_value = True
return check_value, suffix['id'], warnings
logger.info("Suffix *not* found in embedded ldap: " + name)
return check_value, None, warnings
| 7,770 |
def check_listening_address(address: str) -> bool:
"""Check entered ip address for validity."""
if address == 'localhost':
return True
return address in get_local_addresses()
| 7,771 |
def multibase_b64decode(data):
"""
Follow forge's base64 urlsafe encode convention to decode string
Args:
data(string): encoded string
Returns: bytes
Examples:
>>> multibase_b64decode('aGVsbG8')
b'hello'
"""
if isinstance(data, str):
data = data.encode()
return base64.urlsafe_b64decode(
(data + b'=' * (-len(data) % 4)))
| 7,772 |
async def test_turn_off(hass):
"""Test that turn off service calls function."""
mock_entity_id = await setup_mock_component(hass)
mock_func = "{}{}".format(
"homeassistant.components.ps4.media_player.", "pyps4.Ps4Async.standby"
)
with patch(mock_func) as mock_call:
await hass.services.async_call(
"media_player", "turn_off", {ATTR_ENTITY_ID: mock_entity_id}
)
await hass.async_block_till_done()
assert len(mock_call.mock_calls) == 1
| 7,773 |
def parse_ordering_params(param: List[str]) -> List[str]:
"""
Ignores the request to sort by "ord".
Returns a sorting order based on the params and includes "readable_id"
sorting in passed params if the sorting request contains title
otherwise, it returns the requested order.
"""
if "ord" in param:
order = []
elif "title" in param:
prefix = "-" if param[0] == "-" else ""
order = ["{prefix}coursepage__course__readable_id".format(prefix=prefix), param]
else:
order = [param]
return order
| 7,774 |
def find_requests(from_dt=None, to_dt=None, contribs_and_sessions=True):
"""Finds requests matching certain criteria.
:param from_dt: earliest event/contribution to include
:param to_dt: latest event/contribution to include
:param contribs_and_sessions: whether it should return contributions and sessions or only request
"""
from .definition import VCAssistanceRequest
query = Request.query.join(Event).filter(~Event.is_deleted,
Request.type == VCAssistanceRequest.name,
Request.state == RequestState.accepted)
if from_dt is not None or to_dt is not None:
query = query.filter(Event.happens_between(from_dt, to_dt))
# We only want the latest one for each event
query = limit_groups(query, Request, Request.event_id, Request.created_dt.desc(), 1)
query = query.options(joinedload('event'))
for req in query:
event = req.event
if to_dt is not None and event.start_dt > to_dt:
continue
if not contribs_and_sessions:
yield req
else:
contribs = [x[0] for x in get_capable(req, get_contributions)]
session_blocks = [x[0] for x in get_capable(req, get_session_blocks)]
yield req, contribs, session_blocks
| 7,775 |
def file_senzing_rabbitmq():
"""#!/usr/bin/env bash
# --- Functions ---------------------------------------------------------------
function up {
echo -ne "\033[2K${CONTAINER_NAME} status: starting...\r"
mkdir -p ${RABBITMQ_DIR}
chmod 777 ${RABBITMQ_DIR}
if [ "${CONTAINER_VERSION}" == "latest" ]
then
${SENZING_SUDO} docker pull ${SENZING_DOCKER_REGISTRY_URL}/bitnami/rabbitmq:${CONTAINER_VERSION} >> ${CONTAINER_LOG} 2>&1
fi
${SENZING_SUDO} docker run \\
--detach \\
--env RABBITMQ_PASSWORD=${SENZING_RABBITMQ_PASSWORD} \\
--env RABBITMQ_USERNAME=${SENZING_RABBITMQ_USERNAME} \\
--interactive \\
--name ${CONTAINER_NAME} \\
--publish ${CONTAINER_PORT}:15672 \\
--publish ${SENZING_DOCKER_PORT_RABBITMQ}:5672 \\
--restart always \\
--tty \\
--volume ${RABBITMQ_DIR}:/bitnami \\
${SENZING_DOCKER_RUN_PARAMETERS_GLOBAL} \\
${SENZING_DOCKER_RUN_PARAMETERS_RABBITMQ} \\
${SENZING_NETWORK_PARAMETER} \\
${SENZING_PRIVILEGED_PARAMETER} \\
bitnami/rabbitmq:${CONTAINER_VERSION} \\
>> ${CONTAINER_LOG} 2>&1
COUNTER=0
COUNTER_NOTICE=5
TIME_STRING=".."
CONTAINER_STATUS="$( docker container inspect -f '{{.State.Status}}' ${CONTAINER_NAME})"
while [ "${CONTAINER_STATUS}" != "running" ]; do
COUNTER=$((${COUNTER}+1))
if [ "${COUNTER}" -eq "${COUNTER_NOTICE}" ]; then
echo -ne "\033[2K"
echo ""
echo "To see what is happening behind-the-scenes, view the log at"
echo "${CONTAINER_LOG}"
echo "and/or run 'docker logs ${CONTAINER_NAME}'"
echo ""
fi
TIME_STRING="${TIME_STRING}."
echo -ne "\033[2K${CONTAINER_NAME} status: ${CONTAINER_STATUS}${TIME_STRING}\r"
sleep 5
CONTAINER_STATUS="$( docker container inspect -f '{{.State.Status}}' ${CONTAINER_NAME})"
done
sleep 10
echo "${SENZING_HORIZONTAL_RULE}"
echo "${SENZING_HORIZONTAL_RULE:0:2} ${CONTAINER_NAME} running on http://${SENZING_DOCKER_HOST_IP_ADDR}:${CONTAINER_PORT}"
echo "${SENZING_HORIZONTAL_RULE:0:2} Username: ${SENZING_RABBITMQ_USERNAME} Password: ${SENZING_RABBITMQ_PASSWORD}"
echo "${SENZING_HORIZONTAL_RULE:0:2} Mount information: (Format: in container > on host)"
echo "${SENZING_HORIZONTAL_RULE:0:2} /bitnami > ${RABBITMQ_DIR}"
echo "${SENZING_HORIZONTAL_RULE:0:2} Logs:"
echo "${SENZING_HORIZONTAL_RULE:0:2} ${CONTAINER_LOG}"
echo "${SENZING_HORIZONTAL_RULE:0:2} and/or run 'docker logs ${CONTAINER_NAME}'"
echo "${SENZING_HORIZONTAL_RULE:0:2} For more information:"
echo "${SENZING_HORIZONTAL_RULE:0:2} ${SENZING_REFERENCE_URL}#senzing-rabbitmq"
echo "${SENZING_HORIZONTAL_RULE}"
}
function down {
${SENZING_SUDO} docker stop ${CONTAINER_NAME} >> ${CONTAINER_LOG} 2>&1
${SENZING_SUDO} docker rm ${CONTAINER_NAME} >> ${CONTAINER_LOG} 2>&1
}
function usage {
echo "usage: $0 [up | down | restart]"
echo "For more information:"
echo "${SENZING_REFERENCE_URL}#senzing-rabbitmq"
}
# --- Main --------------------------------------------------------------------
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source ${SCRIPT_DIR}/docker-environment-vars.sh
CONTAINER_LOG="${SENZING_LOG_RABBITMQ}"
CONTAINER_NAME="${SENZING_DOCKER_CONTAINER_NAME_RABBITMQ}"
CONTAINER_PORT="${SENZING_DOCKER_PORT_RABBITMQ_UI}"
CONTAINER_VERSION="${SENZING_DOCKER_IMAGE_VERSION_RABBITMQ}"
if [ "$1" == "up" ]; then
up
elif [ "$1" == "down" ]; then
down
elif [ "$1" == "restart" ]; then
down
up
else
usage
fi
"""
return 0
| 7,776 |
def mse(predictions, targets):
"""Calculate MSE: (Mean squared error)
"""
return ((predictions - targets) ** 2).mean()
| 7,777 |
def export1d(hist):
"""Export a 1-dimensional `Hist` object to uproot
This allows one to write a coffea histogram into a ROOT file, via uproot.
Parameters
----------
hist : Hist
A 1-dimensional histogram object
Returns
-------
out
A ``uproot_methods.classes.TH1`` object
Examples
--------
Creating a coffea histogram, filling, and writing to a file::
import coffea, uproot, numpy
h = coffea.hist.Hist("Events", coffea.hist.Bin("var", "some variable", 20, 0, 1))
h.fill(var=numpy.random.normal(size=100))
fout = uproot.create('output.root')
fout['myhist'] = coffea.hist.export1d(h)
fout.close()
"""
if hist.dense_dim() != 1:
raise ValueError("export1d() can only support one dense dimension")
if hist.sparse_dim() != 0:
raise ValueError("export1d() expects zero sparse dimensions")
axis = hist.axes()[0]
sumw, sumw2 = hist.values(sumw2=True, overflow='all')[()]
edges = axis.edges(overflow='none')
out = TH1.__new__(TH1)
out._fXaxis = TAxis(len(edges) - 1, edges[0], edges[-1])
out._fXaxis._fName = axis.name
out._fXaxis._fTitle = axis.label
if not axis._uniform:
out._fXaxis._fXbins = edges.astype(">f8")
centers = (edges[:-1] + edges[1:]) / 2.0
out._fEntries = out._fTsumw = out._fTsumw2 = sumw[1:-1].sum()
out._fTsumwx = (sumw[1:-1] * centers).sum()
out._fTsumwx2 = (sumw[1:-1] * centers**2).sum()
out._fName = "histogram"
out._fTitle = hist.label
out._classname = b"TH1D"
out.extend(sumw.astype(">f8"))
out._fSumw2 = sumw2.astype(">f8")
return out
| 7,778 |
def filter_words(w_map, emb_array, ck_filenames):
""" delete word in w_map but not in the current corpus """
vocab = set()
for filename in ck_filenames:
for line in open(filename, 'r'):
if not (line.isspace() or (len(line) > 10 and line[0:10] == '-DOCSTART-')):
line = line.rstrip('\n').split()
assert len(line) >= 3, 'wrong ck file format'
word = line[0]
vocab.add(word)
word = word.lower()
vocab.add(word)
new_w_map = {}
new_emb_array = []
for (word, idx) in w_map.items():
if word in vocab or word in ['<unk>', '<s>', '< >', '<\n>']:
assert word not in new_w_map
new_w_map[word] = len(new_emb_array)
new_emb_array.append(emb_array[idx])
print('filtered %d --> %d' % (len(emb_array), len(new_emb_array)))
return new_w_map, new_emb_array
| 7,779 |
def take(data, indices, dim):
"""Takes elements from an input array along the given dim.
Parameters
----------
data : Tensor
The data tensor.
indices : Tensor
The indices tensor.
dim : Tensor
The dimension to gather along.
"""
pass
| 7,780 |
def get_cache_template(sources, grids, geopackage, table_name="tiles"):
"""
Returns the cache template which is "controlled" settings for the application.
The intent is to allow the user to configure certain things but impose specific behavior.
:param sources: A name for the source
:param grids: specific grid for the data source
:param geopackage: Location for the geopackage
:return: The dict template
"""
if sources == ["None"]:
sources = []
return {
"sources": sources,
"cache": {"type": "geopackage", "filename": str(geopackage), "table_name": table_name},
"grids": [grid for grid in grids if grid == "default"] or grids,
"format": "mixed",
"request_format": "image/png",
}
| 7,781 |
def plotter(fdict):
""" Go """
pgconn = get_dbconn('coop')
ccursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
lagmonths = ctx['lag']
months = ctx['months']
month = ctx['month']
highyears = [int(x) for x in ctx['year'].split(",")]
h = ctx['h']
wantmonth = month + lagmonths
yearoffset = 0
if month + lagmonths < 1:
wantmonth = 12 - (month + lagmonths)
yearoffset = 1
wanted = []
deltas = []
for m in range(month, month+months):
if m < 13:
wanted.append(m)
deltas.append(0)
else:
wanted.append(m-12)
deltas.append(-1)
table = "alldata_%s" % (station[:2],)
nt = network.Table("%sCLIMATE" % (station[:2],))
elnino = {}
ccursor.execute("""SELECT monthdate, soi_3m, anom_34 from elnino""")
for row in ccursor:
if row[0].month != wantmonth:
continue
elnino[row[0].year + yearoffset] = dict(soi_3m=row[1], anom_34=row[2])
ccursor.execute("""
SELECT year, month, sum(precip), avg((high+low)/2.)
from """ + table + """
where station = %s GROUP by year, month
""", (station, ))
yearly = {}
for row in ccursor:
(_year, _month, _precip, _temp) = row
if _month not in wanted:
continue
effectiveyear = _year + deltas[wanted.index(_month)]
nino = elnino.get(effectiveyear, {}).get('soi_3m', None)
if nino is None:
continue
data = yearly.setdefault(effectiveyear, dict(precip=0, temp=[],
nino=nino))
data['precip'] += _precip
data['temp'].append(float(_temp))
fig = plt.figure(figsize=(10, 6))
ax = plt.axes([0.1, 0.12, 0.5, 0.75])
msg = ("[%s] %s\n%s\n%s SOI (3 month average)"
) % (station, nt.sts[station]['name'], title(wanted),
datetime.date(2000, wantmonth, 1).strftime("%B"))
ax.set_title(msg)
cmap = plt.get_cmap("RdYlGn")
zdata = np.arange(-2.0, 2.1, 0.5)
norm = mpcolors.BoundaryNorm(zdata, cmap.N)
rows = []
xs = []
ys = []
for year in yearly:
x = yearly[year]['precip']
y = np.average(yearly[year]['temp'])
xs.append(x)
ys.append(y)
val = yearly[year]['nino']
c = cmap(norm([val])[0])
if h == 'hide' and val > -0.5 and val < 0.5:
ax.scatter(x, y, facecolor='#EEEEEE', edgecolor='#EEEEEE', s=30,
zorder=2, marker='s')
else:
ax.scatter(x, y, facecolor=c, edgecolor='k', s=60, zorder=3,
marker='o')
if year in highyears:
ax.text(x, y + 0.2, "%s" % (year, ), ha='center', va='bottom',
zorder=5)
rows.append(dict(year=year, precip=x, tmpf=y, soi3m=val))
ax.axhline(np.average(ys), lw=2, color='k', linestyle='-.', zorder=2)
ax.axvline(np.average(xs), lw=2, color='k', linestyle='-.', zorder=2)
sm = plt.cm.ScalarMappable(norm, cmap)
sm.set_array(zdata)
cb = plt.colorbar(sm, extend='both')
cb.set_label("<-- El Nino :: SOI :: La Nina -->")
ax.grid(True)
ax.set_xlim(left=-0.01)
ax.set_xlabel("Total Precipitation [inch], Avg: %.2f" % (np.average(xs),))
ax.set_ylabel((r"Average Temperature $^\circ$F, "
"Avg: %.1f") % (np.average(ys), ))
df = pd.DataFrame(rows)
ax2 = plt.axes([0.67, 0.6, 0.28, 0.35])
ax2.scatter(df['soi3m'].values, df['tmpf'].values)
ax2.set_xlabel("<-- El Nino :: SOI :: La Nina -->")
ax2.set_ylabel(r"Avg Temp $^\circ$F")
slp, intercept, r_value, _, _ = stats.linregress(df['soi3m'].values,
df['tmpf'].values)
y1 = -2.0 * slp + intercept
y2 = 2.0 * slp + intercept
ax2.plot([-2, 2], [y1, y2])
ax2.text(0.97, 0.9, "R$^2$=%.2f" % (r_value**2, ),
ha='right', transform=ax2.transAxes, bbox=dict(color='white'))
ax2.grid(True)
ax3 = plt.axes([0.67, 0.1, 0.28, 0.35])
ax3.scatter(df['soi3m'].values, df['precip'].values)
ax3.set_xlabel("<-- El Nino :: SOI :: La Nina -->")
ax3.set_ylabel("Total Precip [inch]")
slp, intercept, r_value, _, _ = stats.linregress(df['soi3m'].values,
df['precip'].values)
y1 = -2.0 * slp + intercept
y2 = 2.0 * slp + intercept
ax3.plot([-2, 2], [y1, y2])
ax3.text(0.97, 0.9, "R$^2$=%.2f" % (r_value**2, ),
ha='right', transform=ax3.transAxes, bbox=dict(color='white'))
ax3.grid(True)
return fig, df
| 7,782 |
def output_folder_fixture():
"""Creates the necessary folder and cleans up after test is done."""
if not os.path.exists(OUTPUT_FOLDER):
os.mkdir(OUTPUT_FOLDER)
yield OUTPUT_FOLDER
shutil.rmtree(OUTPUT_FOLDER, ignore_errors=True)
| 7,783 |
def _action_spec():
"""Returns the action spec."""
paddle_action_spec = dm_env_rpc_pb2.TensorSpec(
dtype=dm_env_rpc_pb2.INT8, name=_ACTION_PADDLE)
tensor_spec_utils.set_bounds(
paddle_action_spec,
minimum=np.min(_VALID_ACTIONS),
maximum=np.max(_VALID_ACTIONS))
return {1: paddle_action_spec}
| 7,784 |
def test_split_stats_manual() -> None:
"""
Test that `get_split_statistics()` correctly computes the z-score over the pairwise
differences in task gradients for manually computed values.
"""
# Set up case.
settings = dict(V1_SETTINGS)
settings["num_layers"] = 1
settings["num_tasks"] = 4
settings["ema_alpha"] = 0.8
input_size = 1
output_size = 2
settings["hidden_size"] = 2
ema_threshold = alpha_to_threshold(settings["ema_alpha"])
# Construct a sequence of task gradients. The network gradient statistics will be
# updated with these task gradients, and the z-scores will be computed from these
# statistics.
task_grads = torch.Tensor(
[
[
[[-0.117, 0.08, -0.091, -0.008]],
[[0, 0, 0, 0]],
[[-0.053, 0.078, -0.046, 0.017]],
[[0, 0, 0, 0]],
],
[
[[-0.006, 0.083, -0.065, -0.095]],
[[0.037, 0.051, 0.009, -0.075]],
[[0.107, 0.264, -0.072, 0.143]],
[[0.049, 0.03, -0.051, -0.012]],
],
[
[[0.106, -0.092, -0.015, 0.159]],
[[0, 0, 0, 0]],
[[0.055, 0.115, -0.096, 0.032]],
[[-0.21, 0.11, -0.091, -0.014]],
],
[
[[-0.116, 0.079, 0.087, 0.041]],
[[0.094, 0.143, -0.015, -0.008]],
[[-0.056, -0.054, 0.01, 0.073]],
[[0.103, -0.085, -0.008, -0.018]],
],
[
[[-0.147, -0.067, -0.063, -0.022]],
[[-0.098, 0.059, 0.064, 0.045]],
[[-0.037, 0.138, 0.06, -0.056]],
[[0, 0, 0, 0]],
],
[
[[-0.062, 0.001, 0.106, -0.176]],
[[-0.007, 0.013, -0.095, 0.082]],
[[-0.003, 0.066, 0.106, -0.17]],
[[-0.035, -0.027, -0.105, 0.058]],
],
[
[[0.114, -0.191, -0.054, -0.122]],
[[0.053, 0.004, -0.019, 0.053]],
[[0.155, -0.027, 0.054, -0.015]],
[[0.073, 0.042, -0.08, 0.056]],
],
[
[[0.094, 0.002, 0.078, -0.049]],
[[-0.116, 0.205, 0.175, -0.026]],
[[-0.178, 0.013, -0.012, 0.136]],
[[-0.05, 0.105, 0.114, -0.053]],
],
[
[[0, 0, 0, 0]],
[[-0.171, -0.001, 0.069, -0.077]],
[[0.11, 0.053, 0.039, -0.005]],
[[-0.097, 0.046, 0.124, 0.072]],
],
]
)
total_steps = len(task_grads)
# Set expected values of gradient statistics.
expected_grad_diff_mean = torch.Tensor(
[
[[0, 0, 0.00675, 0], [0, 0, 0, 0], [0.00675, 0, 0, 0], [0, 0, 0, 0]],
[
[0, 0.008749, 0.0544865, 0.012919],
[0.008749, 0, 0.104354, 0.008154],
[0.0544865, 0.104354, 0, 0.082586],
[0.012919, 0.008154, 0.082586, 0],
],
[
[0, 0.008749, 0.05903766667, 0.094642],
[0.008749, 0, 0.104354, 0.008154],
[0.05903766667, 0.104354, 0, 0.0774885],
[0.094642, 0.008154, 0.0774885, 0],
],
[
[0, 0.034875, 0.05133875, 0.09221566667],
[0.034875, 0, 0.0864245, 0.030184],
[0.05133875, 0.0864245, 0, 0.06327466667],
[0.09221566667, 0.030184, 0.06327466667, 0],
],
[
[0, 0.036215, 0.055153, 0.09221566667],
[0.036215, 0, 0.06434266667, 0.030184],
[0.055153, 0.06434266667, 0, 0.06327466667],
[0.09221566667, 0.030184, 0.06327466667, 0],
],
[
[0, 0.05469475, 0.0456708, 0.09435925],
[0.05469475, 0, 0.0749395, 0.02114266667],
[0.0456708, 0.0749395, 0, 0.0740005],
[0.09435925, 0.02114266667, 0.0740005, 0],
],
[
[0, 0.058475, 0.04687464, 0.0931534],
[0.058475, 0, 0.0642152, 0.0172505],
[0.04687464, 0.0642152, 0, 0.0660968],
[0.0931534, 0.0172505, 0.0660968, 0],
],
[
[0, 0.0658294, 0.060785712, 0.08105412],
[0.0658294, 0, 0.07175636, 0.0175616],
[0.060785712, 0.07175636, 0, 0.06816644],
[0.08105412, 0.0175616, 0.06816644, 0],
],
[
[0, 0.0658294, 0.060785712, 0.08105412],
[0.0658294, 0, 0.074997288, 0.02063148],
[0.060785712, 0.074997288, 0, 0.065743552],
[0.08105412, 0.02063148, 0.065743552, 0],
],
]
)
expected_grad_diff_mean = expected_grad_diff_mean.unsqueeze(-1)
expected_grad_mean = torch.Tensor(
[
[-0.034, 0, -0.001, 0],
[-0.027375, 0.0055, 0.05475, 0.004],
[-0.005083333333, 0.0055, 0.04533333333, -0.023625],
[0.001875, 0.0295, 0.0323125, -0.01641666667],
[-0.01345, 0.0255, 0.0311, -0.01641666667],
[-0.01731, 0.0186875, 0.02483, -0.019125],
[-0.026498, 0.0195, 0.028214, -0.01075],
[-0.0149484, 0.0275, 0.0205212, -0.0028],
[-0.0149484, 0.013, 0.02626696, 0.00501],
]
)
expected_grad_var = torch.Tensor(
[
[0.0059525, 0, 0.0028235, 0],
[0.005326734375, 0.00238875, 0.0117619375, 0.0014955],
[0.007792076389, 0.00238875, 0.009992055556, 0.008282234375],
[0.007669109375, 0.004036, 0.008708839844, 0.007142576389],
[0.0074847475, 0.004221083333, 0.00819259, 0.007142576389],
[0.0081357339, 0.004302214844, 0.0089363611, 0.006214734375],
[0.009410001996, 0.00364065, 0.008241032204, 0.0059802875],
[0.008732512137, 0.00679957, 0.009333179951, 0.00633534],
[0.008732512137, 0.007872256, 0.007936236492, 0.0066536939],
]
)
expected_z = torch.Tensor(
[
[
[-1.414213562, 0, -1.142280405, 0],
[0, 0, 0, 0],
[-1.142280405, 0, -1.414213562, 0],
[0, 0, 0, 0],
],
[
[-2, -1.170405699, 0.1473023578, -1.054200557],
[-1.170405699, -1.414213562, 1.493813156, -1.186986529],
[0.1473023578, 1.493813156, -2, 0.8872055932],
[-1.054200557, -1.186986529, 0.8872055932, -1.414213562],
],
[
[-2.449489743, -1.221703287, -0.1994752765, 0.9450617525],
[-1.221703287, -1.414213562, 0.8819594016, -1.234795482],
[-0.1994752765, 0.8819594016, -2.449489743, 0.4112805901],
[0.9450617525, -1.234795482, 0.4112805901, -2],
],
[
[-2.828427125, -0.8070526312, -0.3449088766, 1.413801122],
[-0.8070526312, -2, 0.9562689571, -0.9675147418],
[-0.3449088766, 0.9562689571, -2.828427125, 0.2013444437],
[1.413801122, -0.9675147418, 0.2013444437, -2.449489743],
],
[
[-3.16227766, -0.8721406803, -0.06105579169, 1.566975682],
[-0.8721406803, -2.449489743, 0.3529635209, -0.926578017],
[-0.06105579169, 0.3529635209, -3.16227766, 0.3064466412],
[1.566975682, -0.926578017, 0.3064466412, -2.449489743],
],
[
[-3.16227766, -0.09688841312, -0.6121886259, 1.884016833],
[-0.09688841312, -2.828427125, 0.9141650853, -1.535056275],
[-0.6121886259, 0.9141650853, -3.16227766, 0.8672700021],
[1.884016833, -1.535056275, 0.8672700021, -2.828427125],
],
[
[-3.16227766, 0.227909676, -0.4446408767, 2.238448753],
[0.227909676, -3.16227766, 0.56070751, -1.933886337],
[-0.4446408767, 0.56070751, -3.16227766, 0.6697964624],
[2.238448753, -1.933886337, 0.6697964624, -3.16227766],
],
[
[-3.16227766, 0.1737291325, -0.08186756787, 0.9452653965],
[0.1737291325, -3.16227766, 0.4740870094, -2.272316383],
[-0.08186756787, 0.4740870094, -3.16227766, 0.2921622538],
[0.9452653965, -2.272316383, 0.2921622538, -3.16227766],
],
[
[-3.16227766, 0.1743604677, -0.08128460407, 0.946042744],
[0.1743604677, -3.16227766, 0.6390453145, -2.116547594],
[-0.08128460407, 0.6390453145, -3.16227766, 0.170009164],
[0.946042744, -2.116547594, 0.170009164, -3.16227766],
],
]
)
expected_z = expected_z.unsqueeze(-1)
expected_sample_size = torch.Tensor(
[
[1, 0, 1, 0],
[2, 1, 2, 1],
[3, 1, 3, 2],
[4, 2, 4, 3],
[5, 3, 5, 3],
[5, 4, 5, 4],
[5, 5, 5, 5],
[5, 5, 5, 5],
[5, 5, 5, 5],
]
)
expected_pair_sample_size = torch.Tensor(
[
[[1, 0, 1, 0], [0, 0, 0, 0], [1, 0, 1, 0], [0, 0, 0, 0]],
[[2, 1, 2, 1], [1, 1, 1, 1], [2, 1, 2, 1], [1, 1, 1, 1]],
[[3, 1, 3, 2], [1, 1, 1, 1], [3, 1, 3, 2], [2, 1, 2, 2]],
[[4, 2, 4, 3], [2, 2, 2, 2], [4, 2, 4, 3], [3, 2, 3, 3]],
[[5, 3, 5, 3], [3, 3, 3, 2], [5, 3, 5, 3], [3, 2, 3, 3]],
[[5, 4, 5, 4], [4, 4, 4, 3], [5, 4, 5, 4], [4, 3, 4, 4]],
[[5, 5, 5, 5], [5, 5, 5, 4], [5, 5, 5, 5], [5, 4, 5, 5]],
[[5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]],
[[5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]],
]
)
expected_pair_sample_size = expected_pair_sample_size.unsqueeze(-1)
# Instantiate network.
network = MultiTaskSplittingNetworkV1(
input_size=input_size,
output_size=output_size,
num_tasks=settings["num_tasks"],
num_layers=settings["num_layers"],
hidden_size=settings["hidden_size"],
ema_alpha=settings["ema_alpha"],
)
# Update gradient statistics for each step.
for step in range(total_steps):
network.num_steps += 1
network.update_grad_stats(task_grads[step])
z = network.get_split_statistics()
# Compare network statistics to expected values.
assert torch.all(network.grad_stats.sample_size == expected_sample_size[step])
assert torch.all(
network.grad_diff_stats.sample_size == expected_pair_sample_size[step]
)
assert torch.allclose(
network.grad_diff_stats.mean, expected_grad_diff_mean[step]
)
assert torch.allclose(network.grad_stats.mean, expected_grad_mean[step])
assert torch.allclose(network.grad_stats.var, expected_grad_var[step])
assert torch.allclose(z, expected_z[step], atol=TOL)
| 7,785 |
def test_cli_compile(patch, runner, echo, app):
"""
Ensures the compile command compiles a story.
"""
patch.object(click, 'style')
runner.invoke(Cli.compile, [])
App.compile.assert_called_with(os.getcwd(), ebnf=None,
ignored_path=None, concise=False,
first=False)
click.style.assert_called_with('Script syntax passed!', fg='green')
click.echo.assert_called_with(click.style())
| 7,786 |
def test_kms_key_policy():
"""
To test that key policy is applied is passed in
"""
template = Template()
key_admins = "arn:aws:iam::111122223333:user/admin1"
key_users = ["arn:aws:iam::111122223333:user/user1", "arn:aws:iam::444455556666:user/user2"]
kms_key = (KmsKey(key_title='MyTestKey',
key_rotation=True,
key_admins=key_admins,
key_users=key_users,
template=template))
# Test policy is dict
assert_equals(type(kms_key.k_key.KeyPolicy), dict)
# TODO assert user in key policy
# Test user are in policy
for num, key_admin in enumerate(key_admins):
admin_dict_key = kms_key.k_key.KeyPolicy['Statement'][0]['Principal']['AWS'][num]
assert_in(key_admin, admin_dict_key)
for num, key_user in enumerate(key_users):
users_dict_key = kms_key.k_key.KeyPolicy['Statement'][1]['Principal']['AWS'][num]
assert_in(key_user, users_dict_key)
| 7,787 |
async def uptime(ctx: commands.Context):
"""Tells how long the bot has been online."""
delta = datetime.timedelta(seconds=int(time.time() - botstart))
await ctx.send("**Uptime:** {}".format(str(delta)))
| 7,788 |
def stdin(sys_stdin):
"""
Imports standard input.
"""
inputs = [x.strip("[]\n") for x in sys_stdin]
a = [int(x) for x in inputs[0].split(",")]
x = int(inputs[1][0])
return a, x
| 7,789 |
def _row_key(row):
"""
:param row: a normalized row from STATEMENT_METRICS_QUERY
:return: a tuple uniquely identifying this row
"""
return row['database_name'], row['user_name'], row['query_signature'], row['query_hash'], row['query_plan_hash']
| 7,790 |
def is_packet_length(outter_key, inner_key) -> None:
"""Prints packet length"""
if outter_key == "packet":
if inner_key.get('length').get('min') is not None:
make_list = is_instance(inner_key.get('length').get('min'))
print(f"{'Pkt Length(min):':>15} {', '.join(make_list)}")
if inner_key.get('length').get('max') is not None:
make_list = is_instance(inner_key.get('length').get('max'))
print(f"{'Pkt Length(max):':>15} {', '.join(make_list)}")
| 7,791 |
def get (url, user_agent=UA, referrer=None):
"""Make a GET request of the url using pycurl and return the data
(which is None if unsuccessful)"""
data = None
databuffer = StringIO()
curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
curl.setopt(pycurl.FOLLOWLOCATION, 1)
curl.setopt(pycurl.CONNECTTIMEOUT, 5)
curl.setopt(pycurl.TIMEOUT, 8)
curl.setopt(pycurl.WRITEFUNCTION, databuffer.write)
curl.setopt(pycurl.COOKIEFILE, '')
if user_agent:
curl.setopt(pycurl.USERAGENT, user_agent)
if referrer is not None:
curl.setopt(pycurl.REFERER, referrer)
try:
curl.perform()
data = databuffer.getvalue()
except Exception:
pass
curl.close()
return data
| 7,792 |
def detect_callec(tree):
"""Collect names of escape continuations from call_ec invocations in tree.
Currently supported and unsupported cases::
# use as decorator, supported
@call_ec
def result(ec): # <-- we grab name "ec" from here
...
# use directly on a literal lambda, supported
result = call_ec(lambda ec: ...) # <-- we grab name "ec" from here
# use as a function, **NOT supported**
def g(ec): # <-- should grab from here
...
...
result = call_ec(g) # <-- but this is here; g could be in another module
"""
# literal function names that are always interpreted as an ec.
# "brk" is needed to combo with unpythonic.fploop.breakably_looped.
fallbacks = ["ec", "brk"]
iscallec = partial(isx, make_isxpred("call_ec"))
@Walker
def detect(tree, *, collect, **kw):
# TODO: add support for general use of call_ec as a function (difficult)
if type(tree) in (FunctionDef, AsyncFunctionDef) and any(iscallec(deco) for deco in tree.decorator_list):
fdef = tree
collect(fdef.args.args[0].arg) # FunctionDef.arguments.(list of arg objects).arg
elif is_decorated_lambda(tree, mode="any"):
decorator_list, thelambda = destructure_decorated_lambda(tree)
if any(iscallec(decocall.func) for decocall in decorator_list):
collect(thelambda.args.args[0].arg) # we assume it's the first arg, as that's what call_ec expects.
return tree
return fallbacks + detect.collect(tree)
| 7,793 |
def test_distributed_evaluation_multiprocessing(do_mwcp=True):
"""
Full test run using the Distributed Evaluator (fake nodes using processes).
Note that this is not a very good test for the
DistributedEvaluator, because we still work on
one machine, not across multiple machines.
We emulate the other machines using subprocesses
created using the multiprocessing module.
"""
addr = ("localhost", random.randint(12000, 30000))
authkey = b"abcd1234"
mp = multiprocessing.Process(
name="Primary evaluation process",
target=run_primary,
args=(addr, authkey, 19), # 19 because stagnation is at 20
)
mp.start()
if do_mwcp:
mwcp = multiprocessing.Process(
name="Child evaluation process (multiple workers)",
target=run_secondary,
args=(addr, authkey, 2),
)
swcp = multiprocessing.Process(
name="Child evaluation process (direct evaluation)",
target=run_secondary,
args=(addr, authkey, 1),
)
swcp.daemon = True # we cannot set this on mwcp
if do_mwcp:
mwcp.start()
swcp.start()
try:
print("Joining primary process")
sys.stdout.flush()
mp.join()
if mp.exitcode != 0:
raise Exception("Primary-process exited with status {s}!".format(s=mp.exitcode))
if do_mwcp:
if not mwcp.is_alive():
print("mwcp is not 'alive'")
print("children: {c}".format(c=multiprocessing.active_children()))
print("Joining multiworker-secondary process")
sys.stdout.flush()
mwcp.join()
if mwcp.exitcode != 0:
raise Exception("Multiworker-secondary-process exited with status {s}!".format(s=mwcp.exitcode))
if not swcp.is_alive():
print("swcp is not 'alive'")
print("Joining singleworker-secondary process")
sys.stdout.flush()
swcp.join()
if swcp.exitcode != 0:
raise Exception("Singleworker-secondary-process exited with status {s}!".format(s=swcp.exitcode))
finally:
if mp.is_alive():
mp.terminate()
if do_mwcp and mwcp.is_alive():
mwcp.terminate()
if swcp.is_alive():
swcp.terminate()
| 7,794 |
def apply_filters(
stream: StreamMeta, filters: List[Tuple[str, str]], config: Any
) -> StreamMeta:
"""Apply enabled filters ordered by priority on item"""
filter_pool = get_filter_pool(filters, config)
for filter_instance in filter(
lambda x: x.enabled, sorted(filter_pool, key=lambda x: x.priority)
):
filter_instance.apply(stream)
return stream
| 7,795 |
def threading_d(func):
"""
A decorator to run function in background on thread
Args:
func:``function``
Function with args
Return:
background_thread: ``Thread``
"""
@wraps(func)
def wrapper(*args, **kwags):
background_thread = Thread(target=func, args=(*args,))
background_thread.daemon = True
background_thread.start()
return background_thread
return wrapper
| 7,796 |
def create_anchors_3d_stride(
feature_size,
sizes=[1.6, 3.9, 1.56],
anchor_strides=[0.4, 0.4, 0.0],
anchor_offsets=[0.2, -39.8, -1.78],
rotations=[0, np.pi / 2],
velocities=[],
dtype=np.float32,
):
"""
Args:
feature_size: list [D, H, W](zyx)
sizes: [N, 3] list of list or array, size of anchors, xyz
Returns:
anchors: [*feature_size, num_sizes, num_rots, 7] tensor.
"""
# almost 2x faster than v1
x_stride, y_stride, z_stride = anchor_strides
x_offset, y_offset, z_offset = anchor_offsets
z_centers = np.arange(feature_size[0], dtype=dtype)
y_centers = np.arange(feature_size[1], dtype=dtype)
x_centers = np.arange(feature_size[2], dtype=dtype)
z_centers = z_centers * z_stride + z_offset
y_centers = y_centers * y_stride + y_offset
x_centers = x_centers * x_stride + x_offset
sizes = np.reshape(np.array(sizes, dtype=dtype), [-1, 3])
rotations = np.array(rotations, dtype=dtype)
velocities = np.array(velocities, dtype=dtype).reshape([-1, 2])
combines = np.hstack([sizes, velocities]).reshape([-1, 5])
rets = np.meshgrid(x_centers, y_centers, z_centers, rotations, indexing="ij")
tile_shape = [1] * 5
tile_shape[-2] = int(sizes.shape[0])
for i in range(len(rets)):
rets[i] = np.tile(rets[i][..., np.newaxis, :], tile_shape)
rets[i] = rets[i][..., np.newaxis] # for concat
# sizes = np.reshape(sizes, [1, 1, 1, -1, 1, 3])
combines = np.reshape(combines, [1, 1, 1, -1, 1, 5])
tile_size_shape = list(rets[0].shape)
tile_size_shape[3] = 1
# sizes = np.tile(sizes, tile_size_shape)
combines = np.tile(combines, tile_size_shape)
# rets.insert(3, sizes)
rets.insert(3, combines)
ret = np.concatenate(rets, axis=-1)
return np.transpose(ret, [2, 1, 0, 3, 4, 5])
| 7,797 |
def test_mnemonic_inventory():
"""Test the retrieval of the mnemonic inventory."""
all_mnemonics = mnemonic_inventory()[0]
assert len(all_mnemonics) > 1000
| 7,798 |
def sha1_file(filename):
"""
Return the hex string representation of the SHA1 checksum of the filename
"""
import hashlib
s = hashlib.sha1()
with open(filename, "rb") as f:
for line in f:
s.update(line)
return s.hexdigest()
| 7,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.