content
stringlengths 35
762k
| sha1
stringlengths 40
40
| id
int64 0
3.66M
|
---|---|---|
def can_login(email, password):
"""Validation login parameter(email, password) with rules.
return validation result True/False.
"""
login_user = User.find_by_email(email)
return login_user is not None and argon2.verify(password, login_user.password_hash) | 41908f753efa1075d6583ee8a6159011bd8af661 | 14,300 |
def toPlanar(arr: np.ndarray, shape: tuple = None) -> np.ndarray:
"""
Converts interleaved frame into planar
Args:
arr (numpy.ndarray): Interleaved frame
shape (tuple, optional): If provided, the interleaved frame will be scaled to specified shape before converting into planar
Returns:
numpy.ndarray: Planar frame
"""
if shape is None:
return arr.transpose(2, 0, 1)
return cv2.resize(arr, shape).transpose(2, 0, 1) | 0f54b14b72a05fe0b20bdfd14c31084aa9c917ca | 14,301 |
import os
import subprocess
def _convert_client_cert():
"""
Convert the client certificate pfx to crt/rsa required by nginx.
If the certificate does not exist then no action is taken.
"""
cert_file = os.path.join(SECRETS, 'streams-certs', 'client.pfx')
if not os.path.exists(cert_file):
return
pwd_file = os.path.join(SECRETS, 'streams-certs', 'client.pass')
certs_dir = os.path.join(OPT, 'streams-certs')
if not os.path.exists(certs_dir):
os.mkdir(certs_dir)
crt = os.path.join(certs_dir, 'client.crt')
rsa = os.path.join(certs_dir, 'client.rsa')
args = ['/usr/bin/openssl', 'pkcs12', '-in', cert_file, '-password', 'file:' + pwd_file]
subprocess.run(args + ['-clcerts', '-nokeys', '-out', crt], check=True)
subprocess.run(args + ['-nocerts', '-nodes', '-out', rsa], check=True)
return crt, rsa | 55856e92d018e506999d519913a7aed58a8d3d33 | 14,302 |
def downsample_grid(
xg: np.ndarray, yg: np.ndarray, distance: float, mask: np.ndarray = None
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Downsample grid locations to approximate spacing provided by 'distance'.
Notes
-----
This implementation is more efficient than the 'downsample_xy' function
for locations on a regular grid.
:param xg: Meshgrid-like array of Easting coordinates.
:param yg: Meshgrid-like array of Northing coordinates.
:param distance: Desired coordinate spacing.
:param mask: Optionally provide an existing mask and return the union
of the two masks and it's effect on xg and yg.
:return: mask: Boolean mask that was applied to xg, and yg.
:return: xg[mask]: Masked input array xg.
:return: yg[mask]: Masked input array yg.
"""
u_diff = lambda u: np.unique(np.diff(u, axis=1))[0]
v_diff = lambda v: np.unique(np.diff(v, axis=0))[0]
du = np.linalg.norm(np.c_[u_diff(xg), u_diff(yg)])
dv = np.linalg.norm(np.c_[v_diff(xg), v_diff(yg)])
u_ds = np.max([int(np.rint(distance / du)), 1])
v_ds = np.max([int(np.rint(distance / dv)), 1])
downsample_mask = np.zeros_like(xg, dtype=bool)
downsample_mask[::v_ds, ::u_ds] = True
if mask is not None:
downsample_mask &= mask
return downsample_mask, xg[downsample_mask], yg[downsample_mask] | 6ba36486bc081b85670918c63b8c1f183c284503 | 14,303 |
def convert_12bit_to_type(image, desired_type=np.uint8):
"""
Converts the 12-bit tiff from a 6X sensor to a numpy compatible form
:param desired_type: The desired type
:return: The converted image in numpy.array format
"""
image = image / MAX_VAL_12BIT # Scale to 0-1
image = np.iinfo(desired_type).max * image # Scale back to desired type
return image.astype(desired_type) | 6a3287946d1f56f57c6a44fc3f797753ebcd251a | 14,304 |
def dm_hdu(hdu):
""" Compute DM HDU from the actual FITS file HDU."""
if lsst.afw.__version__.startswith('12.0'):
return hdu + 1
return hdu | 87d93549f3d45ae060ced0f103065b6221e343db | 14,305 |
def get_hdf_filepaths(hdf_dir):
"""Get a list of downloaded HDF files which is be used for iterating through hdf file conversion."""
print "Building list of downloaded HDF files..."
hdf_filename_list = []
hdf_filepath_list = []
for dir in hdf_dir:
for dir_path, subdir, files in os.walk(dir):
for f in files:
if f.endswith(".hdf"):
hdf_filename_list.append(os.path.splitext(f)[0])
hdf_filepath_list.append(os.path.join(dir_path, f))
return hdf_filename_list, hdf_filepath_list | a64aa83d06b218a0faf3372e09c2ac337ce106aa | 14,306 |
def mask_depth_image(depth_image, min_depth, max_depth):
""" mask out-of-range pixel to zero """
ret, depth_image = cv2.threshold(
depth_image, min_depth, 100000, cv2.THRESH_TOZERO)
ret, depth_image = cv2.threshold(
depth_image, max_depth, 100000, cv2.THRESH_TOZERO_INV)
depth_image = np.expand_dims(depth_image, 2)
return depth_image | 39fde62083666a9bb4a546c29aa736a23724e25f | 14,307 |
import copy
import os
def database_exists(url):
"""Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_database('postgres://postgres@localhost/name')
database_exists('postgres://postgres@localhost/name') #=> True
Supports checking against a constructed URL as well. ::
engine = create_engine('postgres://postgres@localhost/name')
database_exists(engine.url) #=> False
create_database(engine.url)
database_exists(engine.url) #=> True
"""
url = copy(make_url(url))
database = url.database
if url.drivername.startswith('postgresql'):
url.database = 'template1'
else:
url.database = None
engine = sa.create_engine(url)
if engine.dialect.name == 'postgresql':
text = "SELECT 1 FROM pg_database WHERE datname='%s'" % database
return bool(engine.execute(text).scalar())
elif engine.dialect.name == 'mysql':
text = ("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "
"WHERE SCHEMA_NAME = '%s'" % database)
return bool(engine.execute(text).scalar())
elif engine.dialect.name == 'sqlite':
return database == ':memory:' or os.path.exists(database)
else:
text = 'SELECT 1'
try:
url.database = database
engine = sa.create_engine(url)
engine.execute(text)
return True
except (ProgrammingError, OperationalError):
return False | c04fe11fc9a8bf1e8cce767bcb2326eafdcd3c3a | 14,308 |
def prompt_for_password(prompt=None):
"""Fake prompt function that just returns a constant string"""
return 'promptpass' | 49499970c7698b08f38078c557637907edef3223 | 14,309 |
def heading(start, end):
"""
Find how to get from the point on a planet specified as a tuple start
to a point specified in the tuple end
"""
start = ( radians(start[0]), radians(start[1]))
end = ( radians(end[0]), radians(end[1]))
delta_lon = end[1] - start[1]
delta_lat = log(tan(pi/4 + end[0]/2)/tan(pi/4 + start[0]/2))
return int(round((360 + degrees(atan2(delta_lon, delta_lat))) % 360)) | 97bd69fc308bdf1a484901ad25b415def20f25ee | 14,310 |
def get_frame_list(video, jump_size = 6, **kwargs):
"""
Returns list of frame numbers including first and last frame.
"""
frame_numbers =\
[frame_number for frame_number in range(0, video.frame_count, jump_size)]
last_frame_number = video.frame_count - 1;
if frame_numbers[-1] != last_frame_number:
frame_numbers.append(last_frame_number)
return frame_numbers | 786de04b4edf224045216de226ac61fdd42b0d7b | 14,311 |
def build_xlsx_response(wb, title="report"):
""" Take a workbook and return a xlsx file response """
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % title
response['Content-Length'] = myfile.tell()
return response | c9990c818b45fc68646ff28d39ea0b914e362db1 | 14,312 |
def top_k(*args, **kwargs):
""" See https://www.tensorflow.org/api_docs/python/tf/nn/top_k .
"""
return tensorflow.nn.top_k(*args, **kwargs) | 0b0a9f250a466f439301d840af2213f6b2758656 | 14,313 |
def determine_d_atoms_without_connectivity(zmat, coords, a_atoms, n):
"""
A helper function to determine d_atoms without connectivity information.
Args:
zmat (dict): The zmat.
coords (list, tuple): Just the 'coords' part of the xyz dict.
a_atoms (list): The determined a_atoms.
n (int): The 0-index of the atom in the zmat to be added.
Returns:
list: The d_atoms.
"""
d_atoms = [atom for atom in a_atoms]
for i in reversed(range(n)):
if i not in d_atoms and i in list(zmat['map'].keys()) and (i >= len(zmat['symbols']) or not is_dummy(zmat, i)):
angle = calculate_angle(coords=coords, atoms=[zmat['map'][z_index] for z_index in d_atoms[1:] + [i]])
if not is_angle_linear(angle):
d_atoms.append(i)
break
if len(d_atoms) < 4:
# try again and consider dummies
for i in reversed(range(n)):
if i not in d_atoms and i in list(zmat['map'].keys()):
angle = calculate_angle(coords=coords, atoms=[zmat['map'][z_index] for z_index in d_atoms[1:] + [i]])
if not is_angle_linear(angle):
d_atoms.append(i)
break
return d_atoms | 8b2a60f6092e24b9bc6f71e4ad8753e06c2e6373 | 14,314 |
def all_of_them():
"""
Return page with all products with given name from API.
"""
if 'username' in session:
return render_template('productsearch.html', username=escape(session['username']), vars=lyst)
else:
return "Your are not logged in" | cee22ba57e108edaedc9330c21caa9cb60968aa5 | 14,315 |
def is_blank(line):
"""Determines if a selected line consists entirely of whitespace."""
return whitespace_re.match(line) is not None | 1120d7a70ce5c08eb5f179cd3d2a258af5cd3bc2 | 14,316 |
import re
import collections
import urllib
def _gff_line_map(line, params):
"""Map part of Map-Reduce; parses a line of GFF into a dictionary.
Given an input line from a GFF file, this:
- decides if the file passes our filtering limits
- if so:
- breaks it into component elements
- determines the type of attribute (flat, parent, child or annotation)
- generates a dictionary of GFF info which can be serialized as JSON
"""
gff3_kw_pat = re.compile("\w+=")
def _split_keyvals(keyval_str):
"""Split key-value pairs in a GFF2, GTF and GFF3 compatible way.
GFF3 has key value pairs like:
count=9;gene=amx-2;sequence=SAGE:aacggagccg
GFF2 and GTF have:
Sequence "Y74C9A" ; Note "Clone Y74C9A; Genbank AC024206"
name "fgenesh1_pg.C_chr_1000003"; transcriptId 869
"""
quals = collections.defaultdict(list)
if keyval_str is None:
return quals
# ensembl GTF has a stray semi-colon at the end
if keyval_str[-1] == ';':
keyval_str = keyval_str[:-1]
# GFF2/GTF has a semi-colon with at least one space after it.
# It can have spaces on both sides; wormbase does this.
# GFF3 works with no spaces.
# Split at the first one we can recognize as working
parts = keyval_str.split(" ; ")
if len(parts) == 1:
parts = keyval_str.split("; ")
if len(parts) == 1:
parts = keyval_str.split(";")
# check if we have GFF3 style key-vals (with =)
is_gff2 = True
if gff3_kw_pat.match(parts[0]):
is_gff2 = False
key_vals = [p.split('=') for p in parts]
# otherwise, we are separated by a space with a key as the first item
else:
pieces = [p.strip().split(" ") for p in parts]
key_vals = [(p[0], " ".join(p[1:])) for p in pieces]
for key, val in key_vals:
val = (val[1:-1] if (len(val) > 0 and val[0] == '"'
and val[-1] == '"') else val)
if val:
quals[key].extend(val.split(','))
# if we don't have a value, make this a key=True/False style
# attribute
else:
quals[key].append('true')
for key, vals in quals.items():
quals[key] = [urllib.unquote(v) for v in vals]
return quals, is_gff2
def _nest_gff2_features(gff_parts):
"""Provide nesting of GFF2 transcript parts with transcript IDs.
exons and coding sequences are mapped to a parent with a transcript_id
in GFF2. This is implemented differently at different genome centers
and this function attempts to resolve that and map things to the GFF3
way of doing them.
"""
# map protein or transcript ids to a parent
for transcript_id in ["transcript_id", "transcriptId", "proteinId"]:
try:
gff_parts["quals"]["Parent"] = \
gff_parts["quals"][transcript_id]
break
except KeyError:
pass
# case for WormBase GFF -- everything labelled as Transcript
if gff_parts["quals"].has_key("Transcript"):
# parent types
if gff_parts["type"] in ["Transcript"]:
if not gff_parts["id"]:
gff_parts["id"] = gff_parts["quals"]["Transcript"][0]
# children types
elif gff_parts["type"] in ["intron", "exon", "three_prime_UTR",
"coding_exon", "five_prime_UTR", "CDS", "stop_codon",
"start_codon"]:
gff_parts["quals"]["Parent"] = gff_parts["quals"]["Transcript"]
return gff_parts
strand_map = {'+' : 1, '-' : -1, '?' : None, None: None}
line = line.strip()
if line[:2] == "##":
return [('directive', line[2:])]
elif line[0] != "#":
parts = line.split('\t')
should_do = True
if params.limit_info:
for limit_name, limit_values in params.limit_info.items():
cur_id = tuple([parts[i] for i in
params.filter_info[limit_name]])
if cur_id not in limit_values:
should_do = False
break
if should_do:
assert len(parts) >= 9, line
gff_parts = [(None if p == '.' else p) for p in parts]
gff_info = dict()
# collect all of the base qualifiers for this item
quals, is_gff2 = _split_keyvals(gff_parts[8])
gff_info["is_gff2"] = is_gff2
if gff_parts[1]:
quals["source"].append(gff_parts[1])
if gff_parts[5]:
quals["score"].append(gff_parts[5])
if gff_parts[7]:
quals["phase"].append(gff_parts[7])
gff_info['quals'] = dict(quals)
gff_info['rec_id'] = gff_parts[0]
# if we are describing a location, then we are a feature
if gff_parts[3] and gff_parts[4]:
gff_info['location'] = [int(gff_parts[3]) - 1,
int(gff_parts[4])]
gff_info['type'] = gff_parts[2]
gff_info['id'] = quals.get('ID', [''])[0]
gff_info['strand'] = strand_map[gff_parts[6]]
if is_gff2:
gff_info = _nest_gff2_features(gff_info)
# features that have parents need to link so we can pick up
# the relationship
if gff_info['quals'].has_key('Parent'):
final_key = 'child'
elif gff_info['id']:
final_key = 'parent'
# Handle flat features
else:
final_key = 'feature'
# otherwise, associate these annotations with the full record
else:
final_key = 'annotation'
return [(final_key, (simplejson.dumps(gff_info) if params.jsonify
else gff_info))]
return [] | 555ca7d4ce455563e7230d4b85f4f4404fa839bc | 14,317 |
def smoothEvolve(problem, orig_point, first_ref, second_ref):
"""Evolves using RVEA with abrupt change of reference vectors."""
pop = Population(problem, assign_type="empty", plotting=False)
try:
pop.evolve(slowRVEA, {"generations_per_iteration": 200, "iterations": 15})
except IndexError:
return pop.archive
try:
pop.evolve(
slowRVEA,
{
"generations_per_iteration": 10,
"iterations": 20,
"old_point": orig_point,
"ref_point": first_ref,
},
)
except IndexError:
return pop.archive
try:
pop.evolve(
slowRVEA,
{
"generations_per_iteration": 10,
"iterations": 20,
"old_point": first_ref,
"ref_point": second_ref,
},
)
except IndexError:
return pop.archive
return pop.archive | fd7f7e82e8b029597affd63ec04da3d40c049c98 | 14,318 |
def combine_color_channels(discrete_rgb_images):
"""
Combine discrete r,g,b images to RGB iamges.
:param discrete_rgb_images:
:return:
"""
color_imgs = []
for r, g, b in zip(*discrete_rgb_images):
# pca output is float64, positive and negative. normalize the images to [0, 255] rgb
r = (255 * (r - np.max(r)) / -np.ptp(r)).astype(int)
g = (255 * (g - np.max(g)) / -np.ptp(g)).astype(int)
b = (255 * (b - np.max(b)) / -np.ptp(b)).astype(int)
color_imgs.append(cv2.merge((r, g, b)))
return color_imgs | 246653a698c997faffade25405b1dfafb8236510 | 14,319 |
def decohere_earlier_link(tA, tB, wA, wB, T_coh):
"""Applies decoherence to the earlier generated of the two links.
Parameters
----------
tA : float
Waiting time of one of the links.
wA : float
Corresponding fidelity
tB : float
Waiting time of the other link.
wB : float
Corresponding fidelity
t_both : float
Time both links experience decoherence (e.g. communication time)
T_coh : float
Memory coherence time. If set to 0, there is no decay.
Returns
-------
Tuple (float : tA, float : tB, float : wA, float : wB) after decoherence.
"""
delta_t = abs(tA - tB)
if(tA < tB):
wA = wern_after_memory_decoherence(wA, delta_t, T_coh)
elif(tB < tA):
wB = wern_after_memory_decoherence(wB, delta_t, T_coh)
return wA, wB | 0ec19f50d1673f69211ac7af21ab942612fe8a67 | 14,320 |
import torch
def train(
network: RNN,
data: np.ndarray,
epochs: int = 10,
_n_seqs: int = 10,
_n_steps: int = 50,
lr: int = 0.001,
clip: int = 5,
val_frac: int = 0.2,
cuda: bool = True,
print_every: int = 10,
):
"""Train RNN."""
network.train()
opt = torch.optim.Adam(network.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
val_idx = int(len(data) * (1 - val_frac))
data, val_data = data[:val_idx], data[val_idx:]
if cuda:
network.cuda()
step = 0
train_loss = []
validation_loss = []
for i in range(epochs):
h = network.init_hidden(_n_seqs)
for x, y in get_batches(data, _n_seqs, _n_steps):
step += 1
# One-hot encode, make Torch tensors
x = one_hot_encode(x, network.vocab)
inputs, targets = torch.from_numpy(x), torch.from_numpy(y)
if cuda:
inputs, targets = inputs.cuda(), targets.cuda()
h = tuple([m.data for m in h])
network.zero_grad()
output, h = network.forward(inputs, h)
loss = criterion(output, targets.view(_n_seqs * _n_steps))
loss.backward()
# Avoid exploding gradients
nn.utils.clip_grad_norm_(network.parameters(), clip)
opt.step()
if step % print_every == 0:
# Validation loss
val_h = network.init_hidden(_n_seqs)
val_losses = []
for x, y in get_batches(val_data, _n_seqs, _n_steps):
x = one_hot_encode(x, network.vocab)
x, y = torch.from_numpy(x), torch.from_numpy(y)
val_h = tuple([m.data for m in val_h])
inputs, targets = x, y
if cuda:
inputs, targets = inputs.cuda(), targets.cuda()
output, val_h = network.forward(inputs, val_h)
val_loss = criterion(output, targets.view(_n_seqs * _n_steps))
val_losses.append(val_loss.item())
train_loss.append(loss.item())
validation_loss.append(np.mean(val_losses))
print(
f"Epoch: {i + 1} / {epochs},",
f"Step: {step},",
f"Loss: {loss.item():.4f},",
"Val Loss: {:.4f}".format(np.mean(val_losses)),
)
return train_loss, validation_loss | 97c642c0b2849cb530121d914c586bc6ee76a26b | 14,321 |
def simple_lunar_phase(jd):
"""
This just does a quick-and-dirty estimate of the Moon's phase given the date.
"""
lunations = (jd - 2451550.1) / LUNAR_PERIOD
percent = lunations - int(lunations)
phase_angle = percent * 360.
delta_t = phase_angle * LUNAR_PERIOD / 360.
moon_day = int(delta_t + 0.5)
phase = get_phase_description(phase_angle)
bgcolor = get_moon_color(delta_t)
return dict(
angle = phase_angle,
day = moon_day,
phase = phase,
days_since_new_moon = delta_t,
bgcolor = bgcolor,
) | 539d407241a0390b140fad4b67e2173ff1dee66c | 14,322 |
def fetch_traj(data, sample_index, colum_index):
""" Returns the state sequence. It also deletes the middle index, which is
the transition point from history to future.
"""
# data shape: [sample_index, time, feature]
traj = np.delete(data[sample_index, :, colum_index:colum_index+1], history_len-1, axis=1)
return traj.flatten() | da373d3890f2c89754e36f78b78fb582b429109d | 14,323 |
from datetime import datetime
def validate_date(period: str, start: bool = False) -> pd.Timestamp:
"""Validate the format of date passed as a string.
:param period: Date in string. If None, date of today is assigned.
:type period: str
:param start: Whether argument passed is a starting date or an ending date,
defaults to False.
:type start: bool, optional
:raises IntegerDateInputError: If integer type object is passed.
:return: Date with format YYYY-MM-DD or YY-MM-DD.
:rtype: pandas.Timestamp
"""
if isinstance(period, int):
raise IntegerDateInputError('Input type of period should be in string.')
if period is None:
date = _convert_none_to_date(start)
else:
try:
date_format = '%y-%m-%d'
period = datetime.strptime(period, date_format)
except ValueError:
date_format = '%Y-%m-%d'
finally:
date = string_to_date(period, date_format)
return date | 99c76ee2e23beaff92a8ad67bf38b26c5f33f4bd | 14,324 |
import copy
def rec_module_mic(echograms, mic_specs):
"""
Apply microphone directivity gains to a set of given echograms.
Parameters
----------
echograms : ndarray, dtype = Echogram
Target echograms. Dimension = (nSrc, nRec)
mic_specs : ndarray
Microphone directions and directivity factor. Dimension = (nRec, 4)
Returns
-------
rec_echograms : ndarray, dtype = Echogram
Echograms subjected to microphone gains. Dimension = (nSrc, nRec)
Raises
-----
TypeError, ValueError: if method arguments mismatch in type, dimension or value.
Notes
-----
Each row of `mic_specs` is expected to be described as [x, y, z, alpha],
with (x, y, z) begin the unit vector of the mic orientation.
`alpha` must be contained in the range [0(dipole), 1(omni)],
so that directivity is expressed as: d(theta) = a + (1-a)*cos(theta).
"""
nSrc = echograms.shape[0]
nRec = echograms.shape[1]
_validate_echogram_array(echograms)
_validate_ndarray_2D('mic_specs', mic_specs, shape0=nRec, shape1=C+1)
mic_vecs = mic_specs[:,:C]
mic_coeffs = mic_specs[:,-1]
rec_echograms = copy.copy(echograms)
# Do nothing if all orders are zeros(omnis)
if not np.all(mic_coeffs == 1):
for ns in range(nSrc):
for nr in range(nRec):
nRefl = len(echograms[ns, nr].value)
# Get vectors from source to receiver
rec_vecs = echograms[ns, nr].coords
rec_vecs = rec_vecs / np.sqrt(np.sum(np.power(rec_vecs,2), axis=1))[:,np.newaxis]
mic_gains = mic_coeffs[nr] + (1 - mic_coeffs[nr]) * np.sum(rec_vecs * mic_vecs[nr,:], axis=1)
rec_echograms[ns, nr].value = echograms[ns, nr].value * mic_gains[:,np.newaxis]
_validate_echogram_array(rec_echograms)
return rec_echograms | 91abe86095cab7ccb7d3f2f001892df4a809106b | 14,325 |
def is_string_like(obj): # from John Hunter, types-free version
"""Check if obj is string."""
try:
obj + ''
except (TypeError, ValueError):
return False
return True | cb7682f91009794011c7c663f98e539d8543c8fd | 14,326 |
import platform
def get_firefox_start_cmd():
"""Return the command to start firefox."""
start_cmd = ""
if platform.system() == "Darwin":
start_cmd = ("/Applications/Firefox.app/Contents/MacOS/firefox-bin")
elif platform.system() == "Windows":
start_cmd = _find_exe_in_registry() or _default_windows_location()
else:
# Maybe iceweasel (Debian) is another candidate...
for ffname in ["firefox2", "firefox", "firefox-3.0", "firefox-4.0"]:
LOGGER.debug("Searching for '%s'...", ffname)
start_cmd = which(ffname)
if start_cmd is not None:
break
return start_cmd | 8a1dd5fea8e1197c16f4a8c26e9029265e9b83c5 | 14,327 |
def divide():
"""Handles division, returns a string of the answer"""
a = int(request.args["a"])
b = int(request.args["b"])
quotient = str(int(operations.div(a, b)))
return quotient | 50c48f9802b3f11e3322b88a45068cad7e354637 | 14,328 |
def ax2cu(ax):
"""Axis angle pair to cubochoric vector."""
return Rotation.ho2cu(Rotation.ax2ho(ax)) | 6f1c6e181d1e25a2bf28605f01d66fa6a8ffcd45 | 14,329 |
from typing import Optional
import urllib
from typing import Dict
import logging
import requests
import os
import shutil
def download_and_store(
feed_url: Text,
ignore_file: Optional[Text],
storage_path: Text,
proxy_string: Optional[Text],
link: urllib.parse.ParseResult) -> Dict:
"""Download and store a link. Storage defined in args"""
# check if the actual url is in the ignore file. If so, no download will take place.
if analyze.in_ignore_file(link.geturl(), ignore_file):
logging.info("Download link [%s] in ignore file.", link.geturl())
return {}
logging.info("downloading %s", link.geturl())
# if netloc does not contain a hostname, assume a relative path to the feed url
if link.netloc == '':
parsed_feed_url = urllib.parse.urlparse(feed_url)
link = link._replace(scheme=parsed_feed_url.scheme,
netloc=parsed_feed_url.netloc,
path=link.path)
logging.info("possible relative path %s, trying to append host: %s",
link.path, parsed_feed_url.netloc)
try:
req = requests.get(link.geturl(),
proxies=proxies(proxy_string),
headers=default_headers(),
verify=False,
stream=True,
timeout=60)
except requests.exceptions.ReadTimeout:
logging.info("%s timed out", link.geturl())
return {}
except requests.exceptions.ConnectionError:
logging.info("%s connection error", link.geturl())
return {}
except requests.exceptions.MissingSchema:
logging.info("%s missing schema", link.geturl())
return {}
if req.status_code >= 400:
logging.info("Status %s - %s", req.status_code, link)
return {}
basename = extract.safe_filename(os.path.basename(link.path))
fname = os.path.join(storage_path,
"download",
basename)
# check if the filename on disk is in the ignore file. If so, do not return filename
# for upload. This differ from URL in the ignore file as the file is in fact downloaded by
# the feed worker, but not uploaded to Scio.
if analyze.in_ignore_file(basename, ignore_file):
logging.info("Ignoring %s based on %s", fname, ignore_file)
return {}
with open(fname, "wb") as download_file:
logging.info("Writing %s", fname)
req.raw.decode_content = True
shutil.copyfileobj(req.raw, download_file)
return {'filename': fname, 'uri': link.geturl()} | dd5a87dcdae78f036cd1c1a86efd49b5b63066b4 | 14,330 |
def define_genom_loc(current_loc, pstart, p_center, pend, hit_start, hit_end, hit_strand, ovl_range):
""" [Local] Returns location label to be given to the annotated peak, if upstream/downstream or overlapping one edge of feature."""
all_pos = ["start", "end"]
closest_pos, dmin = distance_to_peak_center(
p_center, hit_start, hit_end, hit_strand, all_pos)
if current_loc == "not.specified": # Not internal
if closest_pos == "end" and any(ovl_range):
return "overlapEnd"
elif closest_pos == "start" and any(ovl_range):
return "overlapStart"
elif not any(ovl_range):
# Check about direction :"upstream", "downstream"
current_loc = find_peak_dir(
hit_start, hit_end, hit_strand, pstart, p_center, pend)
return current_loc
return current_loc | 87f89a1d392935a008b7997930bf16dda96cf36b | 14,331 |
from typing import List
import re
import argparse
def define_macro(preprocessor: Preprocessor, name: str, args: List[str], text: str) -> None:
"""Defines a macro.
Inputs:
- preprocessor - the object to which the macro is added
- name: str - the name of the new macro
- args: List[str] - List or arguments name
- text: str - the text the command prints. Occurences of args will
be replaced by the corresponding value during the call.
will only replace occurence that aren't part of a larger word
"""
# replace arg occurences with placeholder
for i, arg in enumerate(args):
text = re.sub(
REGEX_IDENTIFIER_WRAPPED.format(re.escape(arg)), # pattern
"\\1{}\\3".format("\000(arg {})\000".format(i)), # placeholder
text,
flags = re.MULTILINE
)
# define the command
def cmd(pre: Preprocessor, cmd_args: List[str], text: str = text, ident: str = name) -> str:
"""a defined macro command"""
for i, arg in enumerate(cmd_args):
pattern = re.escape("\000(arg {})\000".format(i))
text = re.sub(pattern, arg, text, flags=re.MULTILINE)
pre.context.update(
pre.current_position.cmd_argbegin,
'in expansion of defined command {}'.format(ident)
)
parsed = pre.parse(text)
pre.context.pop()
return parsed
cmd.doc = "{} {}".format(name, " ".join(args)) # type: ignore
# place it in command_vars
if "def" not in preprocessor.command_vars:
preprocessor.command_vars["def"] = dict()
preprocessor.command_vars["def"]["{}:{}".format(name, len(args))] = cmd
overloads = []
usages = []
for key, val in preprocessor.command_vars["def"].items():
if key.startswith(name+":"):
overloads.append(int(key[key.find(":") + 1]))
usages.append(val.doc)
usage = "usage: " + "\n ".join(usages)
overload_nb = rreplace(", ".join(str(x) for x in sorted(overloads)), ", ", " or ")
# overwrite defined command
def defined_cmd(pre: Preprocessor, args_string: str) -> str:
"""This is the actual command, parses arguments
and calls the correct overload"""
split = pre.split_args(args_string)
try:
arguments = macro_parser.parse_args(split)
except argparse.ArgumentError:
pre.send_error("invalid-argument",
"invalid argument for macro.\n{}".format(usage)
)
if len(arguments.vars) not in overloads:
pre.send_error("invalid-argument",(
"invalid number of arguments for macro.\nexpected {} got {}.\n"
"{}").format(overload_nb, len(arguments.vars), usage)
)
return pre.command_vars["def"]["{}:{}".format(name, len(arguments.vars))](
pre, arguments.vars
)
defined_cmd.__doc__ = "Defined command for {} (expects {} arguments)\n{}".format(
name, overload_nb, usage
)
defined_cmd.doc = defined_cmd.__doc__ # type: ignore
defined_cmd.__name__ = """def_cmd_{}""".format(name)
preprocessor.commands[name] = defined_cmd | 56ff5bc64b733d6cadfee3252ca3a7b8a06233c5 | 14,332 |
import torch
def actp(Gij, X0, jacobian=False):
""" action on point cloud """
X1 = Gij[:,:,None,None] * X0
if jacobian:
X, Y, Z, d = X1.unbind(dim=-1)
o = torch.zeros_like(d)
B, N, H, W = d.shape
if isinstance(Gij, SE3):
Ja = torch.stack([
d, o, o, o, Z, -Y,
o, d, o, -Z, o, X,
o, o, d, Y, -X, o,
o, o, o, o, o, o,
], dim=-1).view(B, N, H, W, 4, 6)
elif isinstance(Gij, Sim3):
Ja = torch.stack([
d, o, o, o, Z, -Y, X,
o, d, o, -Z, o, X, Y,
o, o, d, Y, -X, o, Z,
o, o, o, o, o, o, o
], dim=-1).view(B, N, H, W, 4, 7)
return X1, Ja
return X1, None | 87f85a713b72de65064224086d9c4715f704d800 | 14,333 |
def isPalindrome(s):
"""Assumes s is a str
Returns True if s is a palindrome; False otherwise.
Punctuation marks, blanks, and capitalization are ignored."""
def toChars(s):
s = s.lower()
letters = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
letters = letters + c
return letters
def isPal(s):
print(' isPal called with', s)
if len(s) <= 1:
print(' About to return True from base case')
return True
else:
answer = s[0] == s[-1] and isPal(s[1:-1])
print(' About to return', answer, 'for', s)
return answer
return isPal(toChars(s)) | 496f5fa92088a5ecb1b99be811e68501513ee3a4 | 14,334 |
import os
def find_make_workdir(subdir, despike, spm, logger=None):
""" generates realign directory to query based on flags
and if it exists and create new workdir
"""
rlgn_dir = utils.defaults['realign_ants']
if spm:
rlgn_dir = utils.defaults['realign_spm']
if despike:
rlgn_dir = utils.defaults['despike'] + rlgn_dir
rlgn_dir = os.path.join(subdir, rlgn_dir)
if not os.path.isdir(rlgn_dir):
if logger:
logger.error('{0} doesnt exist skipping'.format(rlgn_dir))
raise IOError('{0} doesnt exist skipping'.format(rlgn_dir))
if logger:
logger.info(rlgn_dir)
workdirnme = utils.defaults['coreg']
workdir, exists = utils.make_dir(rlgn_dir, workdirnme)
if not exists:
if logger:
logger.error('{0}: skipping {1} doesnt exist'.format(subdir, workdir))
raise IOError('{0}: MISSING, Skipping'.format(workdir))
bpdirnme = utils.defaults['bandpass']
bpdir, exists = utils.make_dir(workdir, bpdirnme)
if exists:
if logger:
logger.error('{0}: skipping {1} existS'.format(subdir, bpdir))
raise IOError('{0}: EXISTS, Skipping'.format(bpdir))
return rlgn_dir, workdir, bpdir | a306745583555e1488e77fea11d90e45630d7f5e | 14,335 |
import logging
def compute_irs(ground_truth_data,
representation_function,
random_state,
diff_quantile=0.99,
num_train=gin.REQUIRED,
batch_size=gin.REQUIRED):
"""Computes the Interventional Robustness Score.
Args:
ground_truth_data: GroundTruthData to be sampled from.
representation_function: Function that takes observations as input and
outputs a dim_representation sized representation for each observation.
random_state: Numpy random state used for randomness.
diff_quantile: Float value between 0 and 1 to decide what quantile of diffs
to select (use 1.0 for the version in the paper).
num_train: Number of points used for training.
batch_size: Batch size for sampling.
Returns:
Dict with IRS and number of active dimensions.
"""
logging.info("Generating training set.")
mus, ys = utils.generate_batch_factor_code(ground_truth_data,
representation_function, num_train,
random_state, batch_size)
assert mus.shape[1] == num_train
ys_discrete = utils.make_discretizer(ys)
active_mus = _drop_constant_dims(mus)
if not active_mus.any():
irs_score = 0.0
else:
irs_score = scalable_disentanglement_score(ys_discrete.T, active_mus.T,
diff_quantile)["avg_score"]
score_dict = {}
score_dict["IRS"] = irs_score
score_dict["num_active_dims"] = np.sum(active_mus)
return score_dict | 0ff37699367946fa099f4a5a48cbc66d89af8a29 | 14,336 |
def Grab_Pareto_Min_Max(ref_set_array, objective_values, num_objs, num_dec_vars, objectives_names=[],
create_txt_file='No'):
"""
Purposes: Identifies the operating policies producing the best and worst performance in each objective.
Gets called automatically by processing_reference_set.Reference_Set()
Required Args:
1. ref_set_array: an array of P arrays, P=number of points in the reference set. Each of the P
arrays contains N=num_objs+num_vars (number of objective values in optimization problem and number of
decision variables). Decision variables come first, followed by objective values.
2. objective_values: The objective value portion of the ref_set_array. It is also an array of P arrays,
where each of the P arrays is of length num_objs.
3. num_objs = integer number of objective values (e.g., 5)
4. num_dec_vars: integer number of decision variable values (e.g., 30)
Optional Args:
5. objectives_names: (list of names of objectives for objective_values returned from Reference_Set,
as defined above). Example: ['Sediment', 'Hydropower']. Used to name .txt file and provide output dictionary
keys.
6. create_text_file: String of 'Yes' or 'No'. Indicates whether users wants function to produce text files of
operating policies.
Returns:
1. indices of ref_set_array that correspond to the points of the highest and lowest value in each of the
objectives.
2. Various text files that store the DPS parameters corresponding to the operating policy, if the user wishes
to create such files.
"""
# Find operating policy parameters corresponding to the largest objective
# List of index of (1) highest and (2) lowest values (column in objective_values array)
indices = [[0 for i in range(2)] for j in range(num_objs)]
indices_dict = {}
for obj in range(num_objs):
indices[obj][0] = np.argmin(objective_values[obj]) # MIN for each objective
indices[obj][1] = np.argmax(objective_values[obj]) # MAX for each objective
if create_txt_file == 'Yes':
# Save max and min policies so PySedSim can import them.
np.savetxt('RBF_Parameters_max_' + objectives_names[obj] + '.txt',
ref_set_array[indices[1][obj]][0:num_dec_vars], newline=' ')
np.savetxt('RBF_Parameters_min_' + objectives_names[obj] + '.txt',
ref_set_array[indices[0][obj]][0:num_dec_vars], newline=' ')
indices = np.asarray(indices) # cast list as array
indices_dict[objectives_names[obj]] = {'Min': indices[obj][0], 'Max': indices[obj][1]}
return indices_dict | 882ba260576550d2c9de20e950594d5369410187 | 14,337 |
def edist(x, y):
""" Compute the Euclidean distance between two samples x, y \in R^d."""
try:
dist = np.sqrt(np.sum((x-y)**2))
except ValueError:
print 'Dimensionality of samples must match!'
else:
return dist | e0b0e586b49bf3e19eafa2cbf271fb3b1ddc2b99 | 14,338 |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import six
def figure(fnum=None, pnum=(1, 1, 1), title=None, figtitle=None, doclf=False,
docla=False, projection=None, **kwargs):
"""
http://matplotlib.org/users/gridspec.html
Args:
fnum (int): fignum = figure number
pnum (int, str, or tuple(int, int, int)): plotnum = plot tuple
title (str): (default = None)
figtitle (None): (default = None)
docla (bool): (default = False)
doclf (bool): (default = False)
Returns:
mpl.Figure: fig
CommandLine:
python -m plottool.custom_figure --exec-figure:0 --show
python -m plottool.custom_figure --exec-figure:1 --show
Example:
>>> fnum = 1
>>> fig = figure(fnum, (2, 2, 1))
>>> gca().text(0.5, 0.5, "ax1", va="center", ha="center")
>>> fig = figure(fnum, (2, 2, 2))
>>> gca().text(0.5, 0.5, "ax2", va="center", ha="center")
>>> ut.show_if_requested()
Example:
>>> fnum = 1
>>> fig = figure(fnum, (2, 2, 1))
>>> gca().text(0.5, 0.5, "ax1", va="center", ha="center")
>>> fig = figure(fnum, (2, 2, 2))
>>> gca().text(0.5, 0.5, "ax2", va="center", ha="center")
>>> fig = figure(fnum, (2, 4, (1, slice(1, None))))
>>> gca().text(0.5, 0.5, "ax3", va="center", ha="center")
>>> ut.show_if_requested()
"""
def ensure_fig(fnum=None):
if fnum is None:
try:
fig = plt.gcf()
except Exception as ex:
fig = plt.figure()
else:
try:
fig = plt.figure(fnum)
except Exception as ex:
fig = plt.gcf()
return fig
def _convert_pnum_int_to_tup(int_pnum):
# Convert pnum to tuple format if in integer format
nr = int_pnum // 100
nc = int_pnum // 10 - (nr * 10)
px = int_pnum - (nr * 100) - (nc * 10)
pnum = (nr, nc, px)
return pnum
def _pnum_to_subspec(pnum):
if isinstance(pnum, six.string_types):
pnum = list(pnum)
nrow, ncols, plotnum = pnum
# if kwargs.get('use_gridspec', True):
# Convert old pnums to gridspec
gs = gridspec.GridSpec(nrow, ncols)
if isinstance(plotnum, (tuple, slice, list)):
subspec = gs[plotnum]
else:
subspec = gs[plotnum - 1]
return (subspec,)
def _setup_subfigure(pnum):
if isinstance(pnum, int):
pnum = _convert_pnum_int_to_tup(pnum)
if doclf:
fig.clf()
axes_list = fig.get_axes()
if docla or len(axes_list) == 0:
if pnum is not None:
assert pnum[0] > 0, 'nRows must be > 0: pnum=%r' % (pnum,)
assert pnum[1] > 0, 'nCols must be > 0: pnum=%r' % (pnum,)
subspec = _pnum_to_subspec(pnum)
ax = fig.add_subplot(*subspec, projection=projection)
if len(axes_list) > 0:
ax.cla()
else:
ax = plt.gca()
else:
if pnum is not None:
subspec = _pnum_to_subspec(pnum)
ax = plt.subplot(*subspec)
else:
ax = plt.gca()
fig = ensure_fig(fnum)
if pnum is not None:
_setup_subfigure(pnum)
# Set the title / figtitle
if title is not None:
ax = plt.gca()
ax.set_title(title)
if figtitle is not None:
fig.suptitle(figtitle)
return fig | a37e688a12713b2f4770708e34084601e2c308bb | 14,339 |
def allsec_preorder(h):
"""
Alternative to using h.allsec(). This returns all sections in order from
the root. Traverses the topology each neuron in "pre-order"
"""
#Iterate over all sections, find roots
roots = root_sections(h)
# Build list of all sections
sec_list = []
for r in roots:
add_pre(h,sec_list,r)
return sec_list | 0407bd37c3f975ba91a51b3058d6c619813f2526 | 14,340 |
def get_func_bytes(*args):
"""get_func_bytes(func_t pfn) -> int"""
return _idaapi.get_func_bytes(*args) | 56000602c9d1d98fb1b76c809cce6c3458a3f426 | 14,341 |
def balanced_accuracy(y_true, y_score):
"""Compute accuracy using one-hot representaitons."""
if isinstance(y_true, list) and isinstance(y_score, list):
# Online scenario
if y_true[0].ndim == 2 and y_score[0].ndim == 2:
# Flatten to single (very long prediction)
y_true = np.concatenate(y_true, axis=0)
y_score = np.concatenate(y_score, axis=0)
if y_score.ndim == 3 and y_score.shape[-1] == 1:
y_score = np.ravel(y_score)
y_true = np.ravel(y_true).astype(int)
y_score = np.around(y_score).astype(int)
if y_true.ndim == 2 and y_true.shape[-1] != 1:
y_true = np.argmax(y_true, axis=-1)
if y_true.ndim == 2 and y_true.shape[-1] == 1:
y_true = np.round(y_true).astype(int)
if y_score.ndim == 2 and y_score.shape[-1] != 1:
y_score = np.argmax(y_score, axis=-1)
if y_score.ndim == 2 and y_score.shape[-1] == 1:
y_score = np.round(y_score).astype(int)
return balanced_accuracy_score(y_true, y_score) | 9745769ac047863b902f0e74f17680f9ccee5a53 | 14,342 |
import json
from dateutil import tz
from datetime import datetime
async def get_weather(weather):
""" For .weather command, gets the current weather of a city. """
if not OWM_API:
await weather.reply(
f"`{JAVES_NNAME}:` **Get an API key from** https://openweathermap.org/ `first.`")
return
APPID = OWM_API
if not weather.pattern_match.group(1):
CITY = DEFCITY
if not CITY:
await weather.reply(
f"`{JAVES_NNAME}:` **Please specify a city or set one as default using the WEATHER_DEFCITY config variable.**"
)
return
else:
CITY = weather.pattern_match.group(1)
timezone_countries = {
timezone: country
for country, timezones in c_tz.items() for timezone in timezones
}
if "," in CITY:
newcity = CITY.split(",")
if len(newcity[1]) == 2:
CITY = newcity[0].strip() + "," + newcity[1].strip()
else:
country = await get_tz((newcity[1].strip()).title())
try:
countrycode = timezone_countries[f'{country}']
except KeyError:
await weather.reply("`Invalid country.`")
return
CITY = newcity[0].strip() + "," + countrycode.strip()
url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}'
request = get(url)
result = json.loads(request.text)
if request.status_code != 200:
await weather.reply(f"`Invalid country.`")
return
cityname = result['name']
curtemp = result['main']['temp']
humidity = result['main']['humidity']
min_temp = result['main']['temp_min']
max_temp = result['main']['temp_max']
desc = result['weather'][0]
desc = desc['main']
country = result['sys']['country']
sunrise = result['sys']['sunrise']
sunset = result['sys']['sunset']
wind = result['wind']['speed']
winddir = result['wind']['deg']
ctimezone = tz(c_tz[country][0])
time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
fullc_n = c_n[f"{country}"]
dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
div = (360 / len(dirs))
funmath = int((winddir + (div / 2)) / div)
findir = dirs[funmath % len(dirs)]
kmph = str(wind * 3.6).split(".")
mph = str(wind * 2.237).split(".")
def fahrenheit(f):
temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
return temp[0]
def celsius(c):
temp = str((c - 273.15)).split(".")
return temp[0]
def sun(unix):
xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
return xx
await weather.reply(
f"**Temperature:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
+
f"**Min. Temp.:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
+
f"**Max. Temp.:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
+ f"**Humidity:** `{humidity}%`\n" +
f"**Wind:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
f"**Sunrise:** `{sun(sunrise)}`\n" +
f"**Sunset:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" +
f"`{cityname}, {fullc_n}`\n" + f"`{time}`") | b93c21eadefa2b4504708ae2663bfdcbf0555668 | 14,343 |
def read_table(source, columns=None, nthreads=1, metadata=None,
use_pandas_metadata=False):
"""
Read a Table from Parquet format
Parameters
----------
source: str or pyarrow.io.NativeFile
Location of Parquet dataset. If a string passed, can be a single file
name or directory name. For passing Python file objects or byte
buffers, see pyarrow.io.PythonFileInterface or pyarrow.io.BufferReader.
columns: list
If not None, only these columns will be read from the file.
nthreads : int, default 1
Number of columns to read in parallel. Requires that the underlying
file source is threadsafe
metadata : FileMetaData
If separately computed
use_pandas_metadata : boolean, default False
If True and file has custom pandas schema metadata, ensure that
index columns are also loaded
Returns
-------
pyarrow.Table
Content of the file as a table (of columns)
"""
if is_string(source):
fs = LocalFileSystem.get_instance()
if fs.isdir(source):
return fs.read_parquet(source, columns=columns,
metadata=metadata)
pf = ParquetFile(source, metadata=metadata)
return pf.read(columns=columns, nthreads=nthreads,
use_pandas_metadata=use_pandas_metadata) | 0d0e4990e88c39920e380cca315332f7c36f6ee8 | 14,344 |
def preprocess_img(image, segnet_stream='fstream'):
"""Preprocess the image to adapt it to network requirements
Args:
Image we want to input the network in (W,H,3) or (W,H,4) numpy array
Returns:
Image ready to input to the network of (1,W,H,3) or (1,W,H,4) shape
Note:
This is really broken if the input is a file path for the astream since there is no motion flow attached...
TODO How would you fix this?
"""
if type(image) is not np.ndarray:
image = np.array(Image.open(image), dtype=np.uint8)
if segnet_stream == 'astream':
input = np.subtract(image.astype(np.float32), np.array((104.00699, 116.66877, 122.67892, 128.), dtype=np.float32))
else:
# input = image -> this leads to NaNs
input = np.subtract(image.astype(np.float32), np.array((0., 0., 128.), dtype=np.float32))
# TODO What preprocessing should we apply to "low amplitude" optical flows and "high amplitude" warped mask
# input = tf.subtract(tf.cast(input, tf.float32), np.array((104.00699, 116.66877, 122.67892), dtype=np.float32))
input = np.expand_dims(input, axis=0)
return input | a3371b69179fb5f53583fb39a3ac458b9c9bbe5d | 14,345 |
def _export_cert_from_task_keystore(
task, keystore_path, alias, password=KEYSTORE_PASS):
"""
Retrieves certificate from the keystore with given alias by executing
a keytool in context of running container and loads the certificate to
memory.
Args:
task (str): Task id of container that contains the keystore
keystore_path (str): Path inside container to keystore containing
the certificate
alias (str): Alias of the certificate in the keystore
Returns:
x509.Certificate object
"""
args = ['-rfc']
if password:
args.append('-storepass "{password}"'.format(password=password))
args_str = ' '.join(args)
cert_bytes = sdk_tasks.task_exec(
task, _keystore_export_command(keystore_path, alias, args_str)
)[1].encode('ascii')
return x509.load_pem_x509_certificate(
cert_bytes, DEFAULT_BACKEND) | 8ae8a0e1d46f121597d70aff35a26ce15c448399 | 14,346 |
def eta_expand(
path: qlast.Path,
stype: s_types.Type,
*,
ctx: context.ContextLevel,
) -> qlast.Expr:
"""η-expansion of an AST path"""
if not ALWAYS_EXPAND and not stype.contains_object(ctx.env.schema):
# This isn't strictly right from a "fully η expanding" perspective,
# but for our uses, we only need to make sure that objects are
# exposed to the output, so we can skip anything not containing one.
return path
if isinstance(stype, s_types.Array):
return eta_expand_array(path, stype, ctx=ctx)
elif isinstance(stype, s_types.Tuple):
return eta_expand_tuple(path, stype, ctx=ctx)
else:
return path | 294e9b0e2aa158dc4e8d57917031986f824fd55d | 14,347 |
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
import timeit
def NBAccuracy(features_train, labels_train, features_test, labels_test):
""" compute the accuracy of your Naive Bayes classifier """
# create classifier
clf = GaussianNB()
# fit the classifier on the training features and labels
timeit(lambda: clf.fit(features_train, labels_train), "fit")
# use the trained classifier to predict labels for the test features
labels_pred = timeit(lambda: clf.predict(features_test), "predict")
# calculate and return the accuracy on the test data
# this is slightly different than the example,
# where we just print the accuracy
# you might need to import an sklearn module
accuracy = accuracy_score(labels_test, labels_pred)
return accuracy | c4c6d5a37341a811023bb0040616ebeb1c44be13 | 14,348 |
import json
def verify(body): # noqa: E501
"""verify
Verifies user with given user id. # noqa: E501
:param body: User id that is required for verification.
:type body: dict | bytes
:rtype: UserVerificationResponse
"""
if connexion.request.is_json:
body = VerifyUser.from_dict(connexion.request.get_json()) # noqa: E501
user_id = body.user_id
user_json = store.value_of(user_id)
if user_json == None:
response = Error(code=400, message="Invalid user id.")
return response, 400
user_dict = json.loads(user_json)
user = User.from_dict(user_dict)
texts = get_texts(user_id)
if not texts:
response = Error(
code=400, message="Can not recognize characters from identity card."
)
return response, 400
language = body.language
doc_text_label = get_doc(texts, language=language)
user_text_label = create_user_text_label(user)
text_validation_point = validate_text_label(doc_text_label, user_text_label)
print("text_validation_point: " + str(text_validation_point))
names = recognize_face(user_id)
if not names:
response = Error(
code=400, message="Can not recognize face from identity card."
)
return response, 400
face_validation_point = point_on_recognition(names, user_id)
print("face_validation_point: " + str(face_validation_point))
verification_rate = text_validation_point + face_validation_point
response = UserVerificationResponse(
code=200, verification_rate=verification_rate
)
return response, 200
else:
error = Error(code=400, message="Provide a json payload that contains userId")
return error, 400 | 76b2ad631dffbf59b1c2ffeb12069983d0540b51 | 14,349 |
def load_interface(interface_name, data):
"""
Load an interface
:param interface_name: a string representing the name of the interface
:param data: a dictionary of arguments to be used for initializing the interface
:return: an Interface object of the appropriate type
"""
if interface_name not in _interfaces:
raise Exception('Unknown interface')
return load_class_from_data(_interfaces[interface_name], data) | e57e0710d5ad5080b2da1f734581d1b205aedc77 | 14,350 |
def as_observation_matrix(cnarr, variants=None):
"""Extract HMM fitting values from `cnarr`.
For each chromosome arm, extract log2 ratios as a numpy array.
Future: If VCF of variants is given, or 'baf' column has already been
added to `cnarr` from the same, then the BAF values are a second row/column
in each numpy array.
Returns: List of numpy.ndarray, one per chromosome arm.
"""
# TODO incorporate weights -- currently handled by smoothing
# TODO incorporate inter-bin distances
observations = [arm.log2.values
for _c, arm in cnarr.by_arm()]
return observations | 74def8f4ecf398c389a6b2a857096a599ef05a15 | 14,351 |
def get_full_word(*args):
"""get_full_word(ea_t ea) -> ulonglong"""
return _idaapi.get_full_word(*args) | 8eb45586888fc836146441bb00bc3c3096ea2c5e | 14,352 |
def full_setup(battery_chemistry):
"""This function gets the baseline vehicle and creates modifications for different
configurations, as well as the mission and analyses to go with those configurations."""
# Collect baseline vehicle data and changes when using different configuration settings
vehicle = vehicle_setup()
# Modify Battery
net = vehicle.networks.battery_propeller
bat = net.battery
if battery_chemistry == 'NMC':
bat = SUAVE.Components.Energy.Storages.Batteries.Constant_Mass.Lithium_Ion_LiNiMnCoO2_18650()
elif battery_chemistry == 'LFP':
bat = SUAVE.Components.Energy.Storages.Batteries.Constant_Mass.Lithium_Ion_LiFePO4_18650()
bat.mass_properties.mass = 500. * Units.kg
bat.max_voltage = 500.
initialize_from_mass(bat)
# Assume a battery pack module shape. This step is optional but
# required for thermal analysis of the pack
number_of_modules = 10
bat.module_config.total = int(np.ceil(bat.pack_config.total/number_of_modules))
bat.module_config.normal_count = int(np.ceil(bat.module_config.total/bat.pack_config.series))
bat.module_config.parallel_count = int(np.ceil(bat.module_config.total/bat.pack_config.parallel))
net.battery = bat
net.battery = bat
net.voltage = bat.max_voltage
configs = configs_setup(vehicle)
# Get the analyses to be used when different configurations are evaluated
configs_analyses = analyses_setup(configs)
# Create the mission that will be flown
mission = mission_setup(configs_analyses, vehicle)
missions_analyses = missions_setup(mission)
# Add the analyses to the proper containers
analyses = SUAVE.Analyses.Analysis.Container()
analyses.configs = configs_analyses
analyses.missions = missions_analyses
return configs, analyses | 9335521ad5a238ab0a566c80d1443cc5c052a37a | 14,353 |
def sph_yn_exact(n, z):
"""Return the value of y_n computed using the exact formula.
The expression used is http://dlmf.nist.gov/10.49.E4 .
"""
zm = mpmathify(z)
s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1))
s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(0, int((n-1)/2) + 1))
return -cos(zm - n*pi/2)*s1 + sin(zm - n*pi/2)*s2 | 490c31a3311fb922f5d33337aaeb70f167b25772 | 14,354 |
def f_bis(n1 : float, n2 : float, n3 : float) -> str:
""" ... cf ci-dessus ...
"""
if n1 < n2:
if n2 < n3:
return 'cas 1'
elif n1 < n3:
return 'cas 2'
else:
return 'cas 5'
elif n1 < n3:
return 'cas 3'
elif n2 < n3:
return 'cas 4'
else:
return 'cas 6' | e46c147a5baef02878700e546b11b7ae44b8909a | 14,355 |
def calc_B_effective(*B_phasors):
"""It calculates the effective value of the magnetic induction field B
(microTesla) in a given point, considering the magnetic induction of
all the cables provided.
Firstly, the function computes the resulting real and imaginary parts
of the x and y magnetic induction field components considering all the
contributing cables given as input (typically three or six cables).
The 'B_components' 2x2 numpy matrix indicates this intermediate step.
Secondly, the module of the effective magnetic induction field B is
calculated as the squared root of the sum of the squares of the
components mentioned above.
Lastly, the result is transformed from Tesla units to micro Tesla units.
Parameters
-------------------
*B_phasors : numpy.ndarray
Respectively the real and imaginary part (columns) of the
x and y components (rows) of the magnetic induction field B
produced by a single cable in a given point
Returns
-------------------
B_effective_microT : float
Effective magnetic induction field B (microTesla) calculated in the given point
Notes
-------------------
The current function implements the calculations present both in
[1]_"Norma Italiana CEI 106-11" formulas (3-4) and [2]_"Norma Italiana
CEI 211-4" formulas (17).
References
-------------------
..[1] Norma Italiana CEI 106-11, "Guide for the determination of
the respect widths for power lines and substations according to
DPCM 8 July 2003 (Clause 6) - Part 1: Overhead lines and cables",
first edition, 2006-02.
..[2] Norma Italiana CEI 211-4, "Guide to calculation methods of
electric and magnetic fields generated by power-lines and electrical
substations", second edition, 2008-09.
"""
B_components = 0
for B_phasor in B_phasors:
B_components += B_phasor
B_effective_T = np.sqrt(np.sum(B_components**2))
B_effective_microT = B_effective_T*10**(6)
return B_effective_microT | a24ae9330018f9dc24ebbba66ccc4bc4bd79a7cb | 14,356 |
def elision_count(l):
"""Returns the number of elisions in a given line
Args:
l (a bs4 <line>): The line
Returns:
(int): The number of elisions
"""
return sum([(1 if _has_elision(w) else 0) for w in l("word")]) | c031765089a030328d68718577872a6d2f70b88d | 14,357 |
def get_final_df(model, data):
"""
This function takes the `model` and `data` dict to
construct a final dataframe that includes the features along
with true and predicted prices of the testing dataset
"""
# if predicted future price is higher than the current,
# then calculate the true future price minus the current price, to get the buy profit
buy_profit = lambda current, pred_future, true_future: true_future - current if pred_future > current else 0
# if the predicted future price is lower than the current price,
# then subtract the true future price from the current price
sell_profit = lambda current, pred_future, true_future: current - true_future if pred_future < current else 0
X_test = data["X_test"]
y_test = data["y_test"]
# perform prediction and get prices
y_pred = model.predict(X_test)
if SCALE:
y_test = np.squeeze(data["column_scaler"]["adjclose"].inverse_transform(np.expand_dims(y_test, axis=0)))
y_pred = np.squeeze(data["column_scaler"]["adjclose"].inverse_transform(y_pred))
test_df = data["test_df"]
# add predicted future prices to the dataframe
test_df[f"adjclose_{LOOKUP_STEP}"] = y_pred
# add true future prices to the dataframe
test_df[f"true_adjclose_{LOOKUP_STEP}"] = y_test
# sort the dataframe by date
test_df.sort_index(inplace=True)
final_df = test_df
# add the buy profit column
final_df["buy_profit"] = list(map(buy_profit,
final_df["adjclose"],
final_df[f"adjclose_{LOOKUP_STEP}"],
final_df[f"true_adjclose_{LOOKUP_STEP}"])
# since we don't have profit for last sequence, add 0's
)
# add the sell profit column
final_df["sell_profit"] = list(map(sell_profit,
final_df["adjclose"],
final_df[f"adjclose_{LOOKUP_STEP}"],
final_df[f"true_adjclose_{LOOKUP_STEP}"])
# since we don't have profit for last sequence, add 0's
)
return final_df | e28f19c5072693872bf17a89cf39cc6afa74517b | 14,358 |
def read_fragment_groups(input_string,natoms,num_channels):
""" read in the fragment groups for each channel
"""
inp_line = _get_integer_line(input_string,'FragmentGroups',natoms)
assert inp_line is not None
out=' '.join(inp_line)
return out | 81ae922add4d0c1680bbeb5223ad85a265ac3040 | 14,359 |
import os
import warnings
import sys
import pickle
def save(program, model_path, protocol=4, **configs):
"""
:api_attr: Static Graph
This function save parameters, optimizer information and network description to model_path.
The parameters contains all the trainable Tensor, will save to a file with suffix ".pdparams".
The optimizer information contains all the Tensor used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. All the information will save to a file with suffix ".pdopt". (If the optimizer have no Tensor need to save (like SGD), the fill will not generated).
The network description is the description of the program. It's only used for deployment. The description will save to a file with a suffix ".pdmodel".
Args:
program(Program) : The program to saved.
model_path(str): the file prefix to save the program. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised
protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5.
Default: 4
configs(dict, optional) : optional keyword arguments.
Returns:
None
Examples:
.. code-block:: python
import paddle
import paddle.static as static
paddle.enable_static()
x = static.data(name="x", shape=[10, 10], dtype='float32')
y = static.nn.fc(x, 10)
z = static.nn.fc(y, 10)
place = paddle.CPUPlace()
exe = static.Executor(place)
exe.run(static.default_startup_program())
prog = static.default_main_program()
static.save(prog, "./temp")
"""
base_name = os.path.basename(model_path)
assert base_name != "", \
"The input model_path MUST be format of dirname/filename [dirname\\filename in Windows system], but received model_path is empty string."
if 'pickle_protocol' in configs:
protocol = configs['pickle_protocol']
warnings.warn(
"'pickle_protocol' is a deprecated argument. Please use 'protocol' instead."
)
if not isinstance(protocol, int):
raise ValueError("The 'protocol' MUST be `int`, but received {}".format(
type(protocol)))
if protocol < 2 or protocol > 4:
raise ValueError("Expected 1<'protocol'<5, but received protocol={}".
format(protocol))
dir_name = os.path.dirname(model_path)
if dir_name and not os.path.exists(dir_name):
os.makedirs(dir_name)
def get_tensor(var):
t = global_scope().find_var(var.name).get_tensor()
return np.array(t)
parameter_list = list(filter(is_parameter, program.list_vars()))
param_dict = {p.name: get_tensor(p) for p in parameter_list}
param_dict = _unpack_saved_dict(param_dict, protocol)
# When value of dict is lager than 4GB ,there is a Bug on 'MAC python3'
if sys.platform == 'darwin' and sys.version_info.major == 3:
pickle_bytes = pickle.dumps(param_dict, protocol=protocol)
with open(model_path + ".pdparams", 'wb') as f:
max_bytes = 2**30
for i in range(0, len(pickle_bytes), max_bytes):
f.write(pickle_bytes[i:i + max_bytes])
else:
with open(model_path + ".pdparams", 'wb') as f:
pickle.dump(param_dict, f, protocol=protocol)
optimizer_var_list = list(
filter(is_belong_to_optimizer, program.list_vars()))
opt_dict = {p.name: get_tensor(p) for p in optimizer_var_list}
with open(model_path + ".pdopt", 'wb') as f:
pickle.dump(opt_dict, f, protocol=protocol)
main_program = program.clone()
program.desc.flush()
main_program.desc._set_version()
paddle.fluid.core.save_op_version_info(program.desc)
with open(model_path + ".pdmodel", "wb") as f:
f.write(program.desc.serialize_to_string()) | 4352e700fee3b24652ae51adf6108a72866f9a26 | 14,360 |
def pad_tile_on_edge(tile, tile_row, tile_col, tile_size, ROI):
""" add the padding to the tile on the edges. If the tile's center is
outside of ROI, move it back to the edge
Args:
tile: tile value
tile_row: row number of the tile relative to its ROI
tile_col: col number of the tile relative to its ROI
tile_size: default tile size which may be different from the input
tile
ROI: ROI value which contains the input tile
Return:
the padded tile
"""
tile_height, tile_width, tile_channel = tile.shape
tile_row_lower = tile_row
tile_row_upper = tile_row + tile_height
tile_col_lower = tile_col
tile_col_upper = tile_col + tile_width
# if the tile's center is outside of ROI, move it back to the edge,
# and then add the padding
if tile_height < tile_size / 2:
tile_row_lower = tile_row_upper - tile_size // 2
tile_height = tile_size // 2
if tile_width < tile_size / 2:
tile_col_lower = tile_col_upper - tile_size // 2
tile_width = tile_size // 2
tile = ROI[tile_row_lower: tile_row_upper, tile_col_lower: tile_col_upper, ]
padding = ((0, tile_size - tile_height), (0, tile_size - tile_width), (0, 0))
return np.pad(tile, padding, "reflect") | bf829ead79f6347423dae8f4c534352d648a3845 | 14,361 |
def calc_kfold_score(model, df, y, n_splits=3, shuffle=True):
"""
Calculate crossvalidation score for the given model and data. Uses sklearn's KFold with shuffle=True.
:param model: an instance of sklearn-model
:param df: the dataframe with training data
:param y: dependent value
:param n_splits: the amount of splits (i.e. K in K-fold)
:param shuffle: whether to shuffle or not
:return: mean, std
"""
kf = KFold(n_splits=n_splits, shuffle=shuffle)
scores = list(calc_kfold_score_helper(model, kf, df, y))
mean = np.mean(scores)
std = np.std(scores)
return mean, std | 09e646d40b245be543c5183b8c964fe8ee4f699f | 14,362 |
def obter_forca (unidade):
"""Esta funcao devolve a forca de ataque da unidade dada como argumento"""
return unidade[2] | 34fe4acac8e0e3f1964faf8e4b26fa31148cf2a6 | 14,363 |
from typing import Dict
def get_default_configuration(cookiecutter_json: CookiecutterJson) -> Dict[str, str]:
"""
Get the default values for the cookiecutter configuration.
"""
default_options = dict()
for key, value in cookiecutter_json.items():
if isinstance(value, str) and "{{" not in value: # ignore templated values
default_options[key] = value
elif isinstance(value, list):
assert len(value) > 0, "Option list must have at least one element"
default_options[key] = value[0]
return default_options | 8a8e3a9b80d3440f1e6031498c210b7b5577aa03 | 14,364 |
def random_nodes_generator(num_nodes, seed=20):
"""
:param int num_nodes: An Integer denoting the number of nodes
:param int seed: (Optional) Integer specifying the seed for controlled randomization.
:return: A dictionary containing the coordinates.
:rtype: dict
"""
np.random.seed(seed)
max_coord_val = num_nodes
num_coord_grid = max_coord_val * max_coord_val
index = np.arange(max_coord_val * max_coord_val)
np.random.shuffle(index)
random_slice_start = np.random.randint(0, num_coord_grid - num_nodes)
coord_index = index[random_slice_start:random_slice_start + num_nodes]
x_array = np.arange(max_coord_val).repeat(max_coord_val)
y_array = np.tile(np.arange(max_coord_val), max_coord_val)
node_coord = np.empty((num_nodes, 2), dtype=np.int32)
node_coord[:, 0] = x_array[coord_index]
node_coord[:, 1] = y_array[coord_index]
node_dict = {}
for i in range(num_nodes):
node_dict[i] = (x_array[coord_index[i]], y_array[coord_index[i]])
return node_dict | 5fa08ccc2cd3a4c34962a29ca9a7566ca5e64592 | 14,365 |
def OpenDocumentTextMaster():
""" Creates a text master document """
doc = OpenDocument('application/vnd.oasis.opendocument.text-master')
doc.text = Text()
doc.body.addElement(doc.text)
return doc | 6813f527ced0f1cd89e0824ac10aeb78d06799a4 | 14,366 |
def get_visible_desktops():
"""
Returns a list of visible desktops.
The first desktop is on Xinerama screen 0, the second is on Xinerama
screen 1, etc.
:return: A list of visible desktops.
:rtype: util.PropertyCookie (CARDINAL[]/32)
"""
return util.PropertyCookie(util.get_property(root, '_NET_VISIBLE_DESKTOPS')) | 9fba922a5c83ed4635391f6ed5319fcfe4fd424d | 14,367 |
import os
def get_env_string(env_key, fallback):
"""
reads boolean literal from environment. (does not use literal compilation
as far as env returns always a string value
Please note that 0, [], {}, '' treats as False
:param str env_key: key to read
:param str fallback: fallback value
:rtype: str
:return: environment value typed in string
"""
assert isinstance(fallback, str), "fallback should be str instance"
return os.environ.get(env_key) or fallback | af136c32b22b1cad30a65e517828dfaf01cb597d | 14,368 |
def spherical_noise(
gridData=None, order_max=8, kind="complex", spherical_harmonic_bases=None
):
"""Returns order-limited random weights on a spherical surface.
Parameters
----------
gridData : io.SphericalGrid
SphericalGrid containing azimuth and colatitude
order_max : int, optional
Spherical order limit [Default: 8]
kind : {'complex', 'real'}, optional
Spherical harmonic coefficients data type [Default: 'complex']
spherical_harmonic_bases : array_like, optional
Spherical harmonic base coefficients (not yet weighted by spatial
sampling grid) [Default: None]
Returns
-------
noisy_weights : array_like, complex
Noisy weights
"""
if spherical_harmonic_bases is None:
if gridData is None:
raise TypeError(
"Either a grid or the spherical harmonic bases have to be provided."
)
gridData = SphericalGrid(*gridData)
spherical_harmonic_bases = sph_harm_all(
order_max, gridData.azimuth, gridData.colatitude, kind=kind
)
else:
order_max = _np.int(_np.sqrt(spherical_harmonic_bases.shape[1]) - 1)
return _np.inner(
spherical_harmonic_bases,
_np.random.randn((order_max + 1) ** 2)
+ 1j * _np.random.randn((order_max + 1) ** 2),
) | 82ef238ef0d72100435306267bf8248f82b70fd8 | 14,369 |
def rollback_command():
"""Command to perform a rollback fo the repo."""
return Command().command(_rollback_command).require_clean().require_migration().with_database() | abfed20ff8cfa08af084fc8c956ebb8d312c985f | 14,370 |
import numpy
def circumcenter(vertices):
"""
Compute the circumcenter of a triangle (the center of the circle which passes through all the vertices of the
triangle).
:param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the
space)).
:returns: The triangle circumcenter.
:rtype: n-dimensional vector
"""
# Compute trilinear coordinates
trilinear = numpy.zeros(3)
for i in range(3):
trilinear[i] = numpy.cos(angle(vertices, i))
bary = trilinear_to_barycentric(trilinear, vertices)
return barycentric_to_cartesian(bary, vertices) | 314e7650b6fec6c82880541de32c1378e720c8c8 | 14,371 |
import subprocess
def testing_submodules_repo(testing_workdir, request):
"""Initialize a new git directory with two submodules."""
subprocess.check_call(['git', 'init'])
# adding a commit for a readme since git diff behaves weird if
# submodules are the first ever commit
subprocess.check_call(['touch', 'readme.txt'])
with open('readme.txt', 'w') as readme:
readme.write('stuff')
subprocess.check_call(['git', 'add', '.'])
subprocess.check_call(['git', 'commit', '-m', 'Added readme'])
subprocess.check_call(['git', 'submodule', 'add',
'https://github.com/conda-forge/conda-feedstock.git'])
subprocess.check_call(['git', 'submodule', 'add',
'https://github.com/conda-forge/conda-build-feedstock.git'])
subprocess.check_call(['git', 'add', '.'])
subprocess.check_call(['git', 'commit', '-m', 'Added conda and cb submodules'])
# a second commit, for testing trips back in history
subprocess.check_call(['git', 'submodule', 'add',
'https://github.com/conda-forge/conda-build-all-feedstock.git'])
subprocess.check_call(['git', 'add', '.'])
subprocess.check_call(['git', 'commit', '-m', 'Added cba submodule'])
return testing_workdir | 3a09e30447d7ebdb041ff1d4ad7f28c8483db41a | 14,372 |
def get_ROC_curve_naive(values, classes):
""" Naive implementation of a ROC curve generator that iterates over a number of thresholds.
"""
# get number of positives and negatives:
n_values = len(values);
totalP = len(np.where(classes > 0)[0]);
totalN = n_values - totalP;
min_val = np.min(values);
max_val = np.max(values);
thresholds = np.arange(min_val, max_val, 1.0);
n_thresholds = len(thresholds);
TP = np.zeros([n_thresholds, 1]);
FP = np.zeros([n_thresholds, 1]);
for t in range(n_thresholds):
inds = np.where(values >= thresholds[t]);
P = np.sum(classes[inds[0]]);
TP[t] = P / totalP;
F = len(inds[0]) - P;
FP[t] = F / totalN;
return TP, FP; | 5950c207746c39c4787b3a472c83fbca5599d654 | 14,373 |
import re
def worker(path, opt):
"""Worker for each process.
Args:
path (str): Image path.
opt (dict): Configuration dict. It contains:
crop_size (int): Crop size.
step (int): Step for overlapped sliding window.
thresh_size (int): Threshold size. Patches whose size is smaller
than thresh_size will be dropped.
save_folder (str): Path to save folder.
compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION.
Returns:
process_info (str): Process information displayed in progress bar.
"""
crop_size = opt['crop_size']
step = opt['step']
thresh_size = opt['thresh_size']
img_name, extension = osp.splitext(osp.basename(path))
# remove the x2, x3, x4 and x8 in the filename for DIV2K
img_name = re.sub('x[2348]', '', img_name)
img = mmcv.imread(path, flag='unchanged')
if img.ndim == 2 or img.ndim == 3:
h, w = img.shape[:2]
else:
raise ValueError(f'Image ndim should be 2 or 3, but got {img.ndim}')
h_space = np.arange(0, h - crop_size + 1, step)
if h - (h_space[-1] + crop_size) > thresh_size:
h_space = np.append(h_space, h - crop_size)
w_space = np.arange(0, w - crop_size + 1, step)
if w - (w_space[-1] + crop_size) > thresh_size:
w_space = np.append(w_space, w - crop_size)
index = 0
for x in h_space:
for y in w_space:
index += 1
cropped_img = img[x:x + crop_size, y:y + crop_size, ...]
cv2.imwrite(
osp.join(opt['save_folder'],
f'{img_name}_s{index:03d}{extension}'), cropped_img,
[cv2.IMWRITE_PNG_COMPRESSION, opt['compression_level']])
process_info = f'Processing {img_name} ...'
return process_info | 68b43995cb147bedad7b94c6f4960cef2646ed87 | 14,374 |
def RobotNet(images,dropout):
"""
Build the model for Robot where it will be used as RobotNet.
Args:
images: 4-D tensor with shape [batch_size, height, width, channals].
dropout: A Python float. The probability that each element is kept.
Returns:
Output tensor with the computed classes.
"""
# _X = tf.reshape(images, shape=[-1, IMAGE_HEIGTH, IMAGE_WIDTH, IMAGE_CHANNAL])
# X = tf.cast(_X, tf.float32)
X = tf.cast(images, tf.float32)
weights1=tf.Variable(tf.random_normal([11, 11, 3, 96],stddev=0.01))
biases1=tf.Variable(tf.zeros([96]))
conv1 = conv2d('conv1', X, weights1, biases1,stride=[4,4],padding='SAME')
norm1 = norm('norm1', conv1, lsize=2)
pool1= max_pool('pool1', norm1, 3, 2)
weights2=tf.Variable(tf.random_normal([5, 5, 96, 256],stddev=0.01))
biases2=tf.Variable(tf.constant(0.1,shape=[256]))
conv2 = conv2d('conv2', pool1, weights2, biases2,stride=[1,1],padding='SAME')
norm2 = norm('norm2', conv2, lsize=2)
pool2= max_pool('pool2', norm2, 3, 2)
weights3=tf.Variable(tf.random_normal([3, 3, 256, 384],stddev=0.01))
biases3=tf.Variable(tf.zeros([384]))
conv3 = conv2d('conv3', pool2, weights3, biases3,stride=[1,1],padding='SAME')
weights4=tf.Variable(tf.random_normal([3, 3, 384, 384],stddev=0.01))
biases4=tf.Variable(tf.constant(0.1,shape=[384]))
conv4 = conv2d('conv4', conv3, weights4, biases4,stride=[1,1],padding='SAME')
weights5=tf.Variable(tf.random_normal([3, 3, 384, 256],stddev=0.01))
biases5=tf.Variable(tf.constant(0.1,shape=[256]))
conv5 = conv2d('conv5', conv4, weights5, biases5,stride=[1,1],padding='SAME')
pool5= max_pool('pool5', conv5, 3, 2)
p_h=pool5.get_shape().as_list()[1]
p_w=pool5.get_shape().as_list()[2]
print('p_h:',p_h)
print('p_w:',p_w)
weights6=tf.Variable(tf.random_normal([p_h*p_w*256, 4096],stddev=0.005))
biases6=tf.Variable(tf.constant(0.1,shape=[4096]))
dense1 = tf.reshape(pool5, [-1, weights6.get_shape().as_list()[0]])
fc6= tf.nn.relu(tf.matmul(dense1, weights6) + biases6, name='fc6')
drop6=tf.nn.dropout(fc6, dropout)
weights7=tf.Variable(tf.random_normal([4096, 4096],stddev=0.005))
biases7=tf.Variable(tf.constant(0.1,shape=[4096]))
fc7= tf.nn.relu(tf.matmul(drop6, weights7) + biases7, name='fc7')
drop7=tf.nn.dropout(fc7, dropout)
weights8=tf.Variable(tf.random_normal([4096, 2],stddev=0.01))
biases8=tf.Variable(tf.zeros([2]))
net_out= tf.matmul(drop7, weights8) + biases8
saver = tf.train.Saver({v.op.name: v for v in [weights1,biases1,weights2,biases2,weights3,biases3,
weights4,biases4,weights5,biases5,weights6,biases6,
weights7,biases7,weights8,biases8]})
return net_out,saver | 9bab69a9a0a01436c9b4225ec882231dc561c204 | 14,375 |
def cvReleaseMemStorage(*args):
"""cvReleaseMemStorage(PyObject obj)"""
return _cv.cvReleaseMemStorage(*args) | a11985f756672ab7b7c5ed58336daad1a975c0d2 | 14,376 |
import os
from sys import path
def run_config_filename(conf_filename):
""" Runs xNormal using the path to a configuration file. """
retcode = os.system("\"%s\" %s" % (path, conf_filename))
return retcode | a68fdbefc4e6d4459073243996d0706111ec4a36 | 14,377 |
import typing
def GetCommitsInOrder(
repo: git.Repo,
head_ref: str = "HEAD",
tail_ref: typing.Optional[str] = None) -> typing.List[git.Commit]:
"""Get a list of all commits, in chronological order from old to new.
Args:
repo: The repo to list the commits of.
head_ref: The starting point for iteration, e.g. the commit closest to
head.
tail_ref: The end point for iteration, e.g. the commit closest to tail.
This commit is NOT included in the returned values.
Returns:
A list of git.Commit objects.
"""
def TailCommitIterator():
stop_commit = repo.commit(tail_ref)
for commit in repo.iter_commits(head_ref):
if commit == stop_commit:
break
yield commit
if tail_ref:
commit_iter = TailCommitIterator()
else:
commit_iter = repo.iter_commits(head_ref)
try:
return list(reversed(list(commit_iter)))
except git.GitCommandError:
# If HEAD is not found, an exception is raised.
return [] | 57db975d44af80a5c6a8e251842182f6a0f572af | 14,378 |
def sell():
"""Sell shares of stock"""
# return apology("TODO")
if request.method == 'GET':
return render_template('sell_stock.html')
else:
symbol = request.form['symbol']
shares = int(request.form['shares'])
return sell_stock(Symbol=symbol, Shares=shares, id=session['user_id']) | 66e53465f1c7fc9bb695f2b63867f24a9429018f | 14,379 |
def return_sw_checked(softwareversion, osversion):
"""
Check software existence, return boolean.
:param softwareversion: Software release version.
:type softwareversion: str
:param osversion: OS version.
:type osversion: str
"""
if softwareversion is None:
serv = bbconstants.SERVERS["p"]
softwareversion = networkutils.sr_lookup(osversion, serv)
softwareversion, swchecked = sw_check_contingency(softwareversion)
else:
swchecked = True
return softwareversion, swchecked | 9f7efb06150468e553ac6a066b2c7750fd233d4c | 14,380 |
from re import A
import copy
def apply(
f: tp.Callable[..., None],
obj: A,
*rest: A,
inplace: bool = False,
_top_inplace: tp.Optional[bool] = None,
_top_level: bool = True,
) -> A:
"""
Applies a function to all `to.Tree`s in a Pytree. Works very similar to `jax.tree_map`,
but its values are `to.Tree`s instead of leaves, also `f` should apply the changes inplace to Tree object.
Arguments:
f: The function to apply.
obj: a pytree possibly containing Trees.
*rest: additional pytrees.
inplace: If `True`, the input `obj` is mutated.
Returns:
A new pytree with the updated Trees or the same input `obj` if `inplace` is `True`.
"""
if _top_inplace is None:
_top_inplace = inplace
if _top_level:
rest = copy(rest)
if not inplace:
obj = copy(obj)
objs = (obj,) + rest
def nested_fn(obj, *rest):
if isinstance(obj, Tree):
apply(
f,
obj,
*rest,
inplace=True,
_top_inplace=_top_inplace,
_top_level=False,
)
jax.tree_map(
nested_fn,
*objs,
is_leaf=lambda x: isinstance(x, Tree) and not x in objs,
)
if isinstance(obj, Tree):
if _top_inplace or obj._mutable:
f(obj, *rest)
else:
with _make_mutable_toplevel(obj):
f(obj, *rest)
return obj | 9a4d29546eb47ba4838fccb58f78495411c99e1c | 14,381 |
import requests
def imageSearch(query, top=10):
"""Returns the decoded json response content
:param query: query for search
:param top: number of search result
"""
# set search url
query = '%27' + parse.quote_plus(query) + '%27'
# web result only base url
base_url = 'https://api.datamarket.azure.com/Bing/Search/v1/Image'
url = base_url + '?Query=' + query + '&$top=' + str(top) + '&$format=json&ImageFilters=%27Aspect%3ASquare%27'
# create credential for authentication
user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36"
# create auth object
auth = HTTPBasicAuth("", API_KEY)
# set headers
headers = {'User-Agent': user_agent}
# get response from search url
response_data = requests.get(url, headers=headers, auth=auth)
# decode json response content
json_result = response_data.json()
return json_result['d']['results'] | 4c731b0ead57e5ec4ab290c9afc67d6066cce093 | 14,382 |
def pack_inputs(inputs):
"""Pack a list of `inputs` tensors to a tuple.
Args:
inputs: a list of tensors.
Returns:
a tuple of tensors. if any input is None, replace it with a special constant
tensor.
"""
inputs = tf.nest.flatten(inputs)
outputs = []
for x in inputs:
if x is None:
outputs.append(tf.constant(0, shape=[], dtype=tf.int32))
else:
outputs.append(x)
return tuple(outputs) | 2801929a1109cd3c416d8b3229399a0a9b73a38f | 14,383 |
def entries_as_dict(month_index):
"""Convert index xml list to list of dictionaries."""
# Search path
findentrylist = etree.ETXPath("//section[@id='month-index']/ul/li")
# Extract data
entries_xml = findentrylist(month_index)
entries = [to_entry_dict(entry_index_xml)
for entry_index_xml in entries_xml]
return entries | 2fba6699457ca9726d4ce93b480e722bb6c8223d | 14,384 |
def resnet50():
"""Constructs a ResNet-50 model.
"""
return Bottleneck, [3, 4, 6, 3] | 197dc833c966146226721e56315d3f12d9c13398 | 14,385 |
def build_service_job_mapping(client, configured_jobs):
"""
:param client: A Chronos client used for getting the list of running jobs
:param configured_jobs: A list of jobs configured in Paasta, i.e. jobs we
expect to be able to find
:returns: A dict of {(service, instance): last_chronos_job}
where last_chronos_job is the latest job matching (service, instance)
or None if there is no such job
"""
service_job_mapping = {}
all_chronos_jobs = client.list()
for job in configured_jobs:
# find all the jobs belonging to each service
matching_jobs = chronos_tools.filter_chronos_jobs(
jobs=all_chronos_jobs,
service=job[0],
instance=job[1],
include_disabled=True,
include_temporary=True,
)
matching_jobs = chronos_tools.sort_jobs(matching_jobs)
# Only consider the most recent one
service_job_mapping[job] = matching_jobs[0] if len(matching_jobs) > 0 else None
return service_job_mapping | 58cdf0a7f7561d1383f8f4c4e4cdd0f46ccfad0c | 14,386 |
def _validate_labels(labels, lon=True):
"""
Convert labels argument to length-4 boolean array.
"""
if labels is None:
return [None] * 4
which = 'lon' if lon else 'lat'
if isinstance(labels, str):
labels = (labels,)
array = np.atleast_1d(labels).tolist()
if all(isinstance(_, str) for _ in array):
bool_ = [False] * 4
opts = ('left', 'right', 'bottom', 'top')
for string in array:
if string in opts:
string = string[0]
elif set(string) - set('lrbt'):
raise ValueError(
f'Invalid {which}label string {string!r}. Must be one of '
+ ', '.join(map(repr, opts))
+ " or a string of single-letter characters like 'lr'."
)
for char in string:
bool_['lrbt'.index(char)] = True
array = bool_
if len(array) == 1:
array.append(False) # default is to label bottom or left
if len(array) == 2:
if lon:
array = [False, False, *array]
else:
array = [*array, False, False]
if len(array) != 4 or any(isinstance(_, str) for _ in array):
raise ValueError(f'Invalid {which}label spec: {labels}.')
return array | 6b4f4870692b3c89f2c51f920892852eeecc418d | 14,387 |
def celsius_to_fahrenheit(temperature_C):
""" converts C -> F """
return temperature_C * 9.0 / 5.0 + 32.0 | 47c789c560c5b7d035252418bd7fb0819b7631a4 | 14,388 |
import re
from datetime import datetime
def _parse_date_time(date):
"""Parse time string.
This matches 17:29:43.
Args:
date (str): the date string to be parsed.
Returns:
A tuple of the format (date_time, nsec), where date_time is a
datetime.time object and nsec is 0.
Raises:
ValueError: if the date format does not match.
"""
pattern = re.compile(
r'^(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})$'
)
if not pattern.match(date):
raise ValueError('Wrong date format: {}'.format(date))
hour = pattern.search(date).group('hour')
minute = pattern.search(date).group('min')
sec = pattern.search(date).group('sec')
nsec = 0
time = datetime.time(int(hour), int(minute), int(sec))
return time, nsec | 2d7f4b067d1215623c2e8e4217c98591a1794481 | 14,389 |
def parsed_user(request, institute_obj):
"""Return user info"""
user_info = {
'email': '[email protected]',
'name': 'John Doe',
'location': 'here',
'institutes': [institute_obj['internal_id']],
'roles': ['admin']
}
return user_info | 773363dc41f599abe27a5913434f88d1a20c131d | 14,390 |
def lastFromUT1(ut1, longitude):
"""Convert from universal time (MJD)
to local apparent sidereal time (deg).
Inputs:
- ut1 UT1 MJD
- longitude longitude east (deg)
Returns:
- last local apparent sideral time (deg)
History:
2002-08-05 ROwen First version, loosely based on the TCC's tut_LAST.
2014-04-25 ROwen Add from __future__ import division, absolute_import and use relative import.
"""
# convert UT1 to local mean sidereal time, in degrees
lmst = lmstFromUT1(ut1, longitude)
# find apparent - mean sidereal time, in degrees
# note: this wants the TDB date, but UT1 is probably close enough
appMinusMean = llv.eqeqx(ut1) / opscore.RO.PhysConst.RadPerDeg
# find local apparent sideral time, in degrees, in range [0, 360)
return opscore.RO.MathUtil.wrapPos (lmst + appMinusMean) | 0ba587125c0c422349acf7bb9753b09956fd9bed | 14,391 |
import os
import torch
def get_dataset(opts):
""" Dataset And Augmentation
"""
train_transform = transform.Compose([
transform.RandomResizedCrop(opts.crop_size, (0.5, 2.0)),
transform.RandomHorizontalFlip(),
transform.ToTensor(),
transform.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
if opts.crop_val:
val_transform = transform.Compose([
transform.Resize(size=opts.crop_size),
transform.CenterCrop(size=opts.crop_size),
transform.ToTensor(),
transform.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
else:
# no crop, batch size = 1
val_transform = transform.Compose([
transform.ToTensor(),
transform.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
labels, labels_old, path_base = tasks.get_task_labels(opts.dataset, opts.task, opts.step)
labels_cum = labels_old + labels
if opts.dataset == 'voc':
dataset = VOCSegmentationIncremental
elif opts.dataset == 'ade':
dataset = AdeSegmentationIncremental
else:
raise NotImplementedError
if opts.overlap:
path_base += "-ov"
if not os.path.exists(path_base):
os.makedirs(path_base, exist_ok=True)
train_dst = dataset(root=opts.data_root, train=True, transform=train_transform,
labels=list(labels), labels_old=list(labels_old),
idxs_path=path_base + f"/train-{opts.step}.npy",
masking=not opts.no_mask, overlap=opts.overlap)
if not opts.no_cross_val: # if opts.cross_val:
train_len = int(0.8 * len(train_dst))
val_len = len(train_dst)-train_len
train_dst, val_dst = torch.utils.data.random_split(train_dst, [train_len, val_len])
else: # don't use cross_val
val_dst = dataset(root=opts.data_root, train=False, transform=val_transform,
labels=list(labels), labels_old=list(labels_old),
idxs_path=path_base + f"/val-{opts.step}.npy",
masking=not opts.no_mask, overlap=True)
image_set = 'train' if opts.val_on_trainset else 'val'
test_dst = dataset(root=opts.data_root, train=opts.val_on_trainset, transform=val_transform,
labels=list(labels_cum),
idxs_path=path_base + f"/test_on_{image_set}-{opts.step}.npy")
return train_dst, val_dst, test_dst, len(labels_cum) | 610d656f356ec710e7873998e8566685da262ab9 | 14,392 |
import itertools
def strip_translations_header(translations: str) -> str:
"""
Strip header from translations generated by ``xgettext``.
Header consists of multiple lines separated from the body by an empty line.
"""
return "\n".join(itertools.dropwhile(len, translations.splitlines())) | b96c964502724008306d627d785224be08bddb86 | 14,393 |
import random
def sample_targets_and_primes(targets, primes, n_rounds,
already_sampled_targets=None, already_sampled_primes=None):
"""
Sample targets `targets` and primes `primes` for `n_rounds` number of rounds. Omit already sampled targets
or primes which can be passed as sets `already_sampled_targets` and `already_sampled_primes`.
`targets` and `primes` must be dicts with class -> [files] mapping (as delivered from `get_amp_images`.
Will return a sample of size "num. of target classes * number of targets per class // `n_rounds`" as list of
4-tuples with:
- target class
- target file
- prime class
- prime file
This function makes sure that you present N targets in random order split into R rounds, where each prime of each
prime class is matched with a random target *per target class* by calling it as such:
```
# round 1:
sample_round_1 = sample_targets_and_primes(targets, primes, Constants.num_rounds)
# round 2:
sample_round_2 = sample_targets_and_primes(targets, primes, Constants.num_rounds,
already_sampled_targets=<targets from sample_round_1>)
...
```
"""
# set defaults
if not already_sampled_targets:
already_sampled_targets = set()
if not already_sampled_primes:
already_sampled_primes = set()
# make sure we have sets
if not isinstance(already_sampled_targets, set):
raise ValueError('`already_sampled_targets` must be a set.')
if not isinstance(already_sampled_primes, set):
raise ValueError('`already_sampled_primes` must be a set.')
# get number of classes
n_prime_classes = len(primes)
n_target_classes = len(targets)
if not n_prime_classes:
raise ValueError('No target images found.')
if not n_target_classes:
raise ValueError('No prime images found.')
# create a list of primes with 2-tuples: (class, file)
# order of primes is random inside prime class
primes_list = []
for primes_classname, class_primes in primes.items():
class_primes = list(set(class_primes) - already_sampled_primes) # omit already sampled primes
# random order of primes inside class
random.shuffle(class_primes)
primes_list.extend(zip([primes_classname] * len(class_primes), class_primes))
n_primes = len(primes_list)
targets_round = [] # holds the output list with 4-tuples
# construct a sample of targets per target class
for target_classname, class_targets in targets.items():
n_targets = len(class_targets)
if n_targets % n_rounds != 0:
raise ValueError('Number of targets in class (%d in "%s") must be a multiple of'
' number of rounds (%d)'
% (n_targets, target_classname, n_rounds))
# omit already sampled targets
class_targets = set(class_targets) - already_sampled_targets
# get a sample of class targets as random sample without replacement of size "number of targets divided
# by number of rounds" so that you can split targets into several rounds
targets_sample = random.sample(class_targets, n_targets // n_rounds)
n_targets_sample = len(targets_sample)
if n_targets_sample % n_primes != 0:
raise ValueError('Number of sampled targets in class (%d in "%s") must be a multiple of'
' number of primes (%d)'
% (n_targets_sample, target_classname, n_primes))
# primes sample is the primes list repeated so that it matches the length of targets in this target class
# this makes sure that for each target class all primes will be shown
primes_sample = primes_list * (n_targets_sample // n_primes)
primes_sample_classes, primes_sample_prime = list(zip(*primes_sample))
assert len(primes_sample) == n_targets_sample
# add targets-primes combinations for this round
targets_round.extend(zip([target_classname] * n_targets_sample, targets_sample,
primes_sample_classes, primes_sample_prime))
# random order of targets-primes combinations
random.shuffle(targets_round)
return targets_round | 6b73cdadf3016f1dc248deb2625eae1dd620553b | 14,394 |
def getsign(num):
"""input the raw num string, return a tuple (sign_num, num_abs).
"""
sign_num = ''
if num.startswith('±'):
sign_num = plus_minus
num_abs = num.lstrip('±+-')
if not islegal(num_abs):
return sign_num, ''
else:
try:
temp = float(num)
if (temp < 0) and (sign_num == ''):
sign_num = sign_negative
elif (temp > 0) and (sign_num == ''):
if ('+' in num):
sign_num = sign_positive
else:
if num.startswith('-'):
sign_num = sign_negative
if num.startswith('+'):
sign_num = sign_positive
num_abs = num.lstrip('+-')
except ValueError:
raise
return sign_num, num_abs | 46fc5a7ac8e366479c40e2ccc1a33f57a736b343 | 14,395 |
from typing import Mapping
from typing import Union
def _convert_actions_to_commands(
subvol: Subvol,
build_appliance: Subvol,
action_to_names_or_rpms: Mapping[RpmAction, Union[str, _LocalRpm]],
) -> Mapping[YumDnfCommand, Union[str, _LocalRpm]]:
"""
Go through the list of RPMs to install and change the action to
downgrade if it is a local RPM with a lower version than what is
installed.
Also use `local_install` and `local_remove` for _LocalRpm.
See the docs in `YumDnfCommand` for the rationale.
"""
cmd_to_names_or_rpms = {}
for action, names_or_rpms in action_to_names_or_rpms.items():
for nor in names_or_rpms:
cmd, new_nor = _action_to_command(
subvol, build_appliance, action, nor
)
if cmd == YumDnfCommand.noop:
continue
if cmd is None: # pragma: no cover
raise AssertionError(f"Unsupported {action}, {nor}")
cmd_to_names_or_rpms.setdefault(cmd, set()).add(new_nor)
return cmd_to_names_or_rpms | 519d09754b18bcabef405f3d39a959b1296d3c6c | 14,396 |
def fit_DBscan (image_X,
eps,
eps_grain_boundary,
min_sample,
min_sample_grain_boundary,
filter_boundary,
remove_large_clusters,
remove_small_clusters,
binarize_bdr_coord,
binarize_grain_coord,
):
""" Function to measure counts and average sizes of instances within an image
args:
image_X: np array containing a preporcessed image
eps: float, parameter for the DBscan algorithm from sklearn
eps_grain_boundary:float, parameter for the DBscan algorithm from sklearn
min_sample: int, parameter for the DBscan algorithm from sklearn
min_sample_grain_boundary: int float, parameter for the DBscan algorithm from sklearn
filter_boundary:int, threshold to apply while finding the grain boundaries
remove_large_clusters: int indicating how many of the largest clusters
shall be removed
remove_small_clusters:int indicating how many of the smallest clusters
shall be removed
binarize_bdr_coord: int for the binarization of the grain boundaries
binarize_grain_coord:: int for the binarization of the grain interiors
returns:
m_CL: float, log10(mean (predicted cluster radius in pixels))
s_CL: float, log10(predicted cluster count)
"""
print('Finding grain boundaries')
bdr_coord=np.array(binarize_array_high(image_X, binarize_bdr_coord))
bdr_coord=find_grain_boundaries(bdr_coord, eps=eps_grain_boundary, min_sample=min_sample_grain_boundary, filter_boundary=filter_boundary)
bdr_coord_df=pd.DataFrame(bdr_coord)
bdr_coord_df.columns=['X','Y']
bdr_coord_df['Z']=255
df_grain=pd.pivot_table(bdr_coord_df, index='X', columns='Y', values='Z', fill_value=0)
df_grain=df_grain.to_numpy()
print('Measuring grains')
grain_coord = np.array(binarize_array(df_grain, binarize_grain_coord))
(m_CL, s_CL, clusters)=find_grains(grain_coord, eps, min_sample, remove_large_clusters, remove_small_clusters)
return (m_CL, s_CL, clusters) | b32218e6d45dc766d749af9247ee1d343236fef0 | 14,397 |
def get_today_timestring():
"""Docen."""
return pd.Timestamp.today().strftime('%Y-%m-%d') | f749a5a63f7c55053918eb3f95bb56c2325f4362 | 14,398 |
from pathlib import Path
import json
def load_json(filepath):
"""
Load a json file
:param filepath: path to json file
"""
fp = Path(filepath)
if not fp.exists():
raise ValueError("Unrecognized file path: {}".format(filepath))
with open(filepath) as f:
data = json.load(f)
return data | 657509a50961f7b9c83536a8973884eef5bbed5e | 14,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.