content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
async def send_e_wechat_request(method, request_url, data):
"""
发送企业微信请求
:param method: string 请求方法
:param request_url: string 请求地址
:param data: json 数据
:return: result, err
"""
if method == 'GET':
try:
async with aiohttp.ClientSession() as session:
async with session.get(request_url, data=json.dumps(data)) as response:
try:
result = await response.json(encoding='utf-8')
except Exception as e:
return {}, e
except Exception as e:
return {}, e
if method == 'POST':
try:
async with aiohttp.ClientSession() as session:
async with session.post(request_url, data=json.dumps(data)) as response:
try:
result = await response.json(encoding='utf-8')
except Exception as e:
return {}, e
except Exception as e:
return {}, e
return result, None
| 8,500 |
def bottom(iterable, key=operator.identity):
"""Generates elements from min to max.
>>> tuple(bottom((3, 2, 1)))
(1, 2, 3)
>>> tuple(bottom((1, 2, 3, 4), lambda x: x % 2 == 0))
(1, 3, 2, 4)
"""
h = []
for i, value in enumerate(iterable):
# Use the index as a tie breaker.
heapq.heappush(h, (key(value), i, value))
while h:
yield operator.nth(2)(heapq.heappop(h))
| 8,501 |
def no_missing_terms(formula_name, term_set):
"""
Returns true if the set is not missing terms corresponding to the
entries in Appendix D, False otherwise. The set of terms should be exactly
equal, and not contain more or less terms than expected.
"""
reqd_terms = dimless_vertical_coordinates[formula_name]
def has_all_terms(reqd_termset):
return len(reqd_termset ^ term_set) == 0
if isinstance(reqd_terms, set):
return has_all_terms(reqd_terms)
# if it's not a set, it's likely some other form of iterable with multiple
# possible definitions i.e. a/ap are interchangeable in
else:
return any(has_all_terms(req) for req in reqd_terms)
| 8,502 |
def initialize(X, num_clusters):
"""
initialize cluster centers
:param X: (torch.tensor) matrix
:param num_clusters: (int) number of clusters
:return: (np.array) initial state
"""
num_samples = X.shape[1]
bs = X.shape[0]
indices = torch.empty(X.shape[:-1], device=X.device, dtype=torch.long)
for i in range(bs):
indices[i] = torch.randperm(num_samples, device=X.device)
initial_state = torch.gather(X, 1, indices.unsqueeze(-1).repeat(1, 1, X.shape[-1])).reshape(bs, num_clusters, -1, X.shape[-1]).mean(dim=-2)
return initial_state
| 8,503 |
def run_ansible(ansible_playbook, artifacts_directory):
"""
:param ansible_playbook: dict which is equal to Ansible playbook in YAML
:return: empty
"""
random_id = get_random_int(1000, 9999)
os.makedirs(TMP_DIR, exist_ok=True)
tmp_current_dir = os.path.join(TMP_DIR, str(random_id))
os.makedirs(tmp_current_dir)
playbook_path = os.path.join(tmp_current_dir, 'ansible_playbook.yaml')
with open(playbook_path, 'w') as playbook_file:
playbook_file.write(yaml.dump(ansible_playbook, default_flow_style=False, sort_keys=False))
if not os.path.isabs(artifacts_directory):
tmp_artifacts_directory = os.path.join(tmp_current_dir, artifacts_directory)
os.makedirs(tmp_artifacts_directory)
copy_tree(artifacts_directory, tmp_artifacts_directory)
am = argument_maker()
r = runner(playbook_path, am)
while r.has_next_play():
current_play = r.get_cur_play_name()
# print("PLAY:", current_play)
while r.has_next_task():
next_task = r.get_next_task_name()
# print("\tTASK:", next_task)
r.run_next_task()
r.finish_ansible()
| 8,504 |
def check_workspace_id(workspace_id):
"""
Validate that workspace_id matches the GUID regex
"""
if workspace_id is None:
raise ParameterMissingException('Workspace ID must be provided')
search = re.compile(GUIDOnlyRegex, re.M)
if not search.match(workspace_id):
raise InvalidParameterError('Workspace ID is invalid')
| 8,505 |
def test_exceptions() -> None:
"""Test if writer raises correct exceptions when needed
"""
# create without reader or name
exception_flag = False
try:
writer1 = Writer()
print(writer1)
writer1.release()
except AssertionError as _:
exception_flag = True
assert exception_flag, "Failed to raise proper exception."
# create with unsupported ext
exception_flag = False
try:
writer2 = Writer(name='test', ext='jst')
print(writer2)
writer2.release()
except NotImplementedError as _:
exception_flag = True
assert exception_flag, "Failed to raise proper exception."
| 8,506 |
def unflatten_satisfies(old_satisfies):
""" Convert satisfies from v2 to v1 """
new_satisfies = {}
for element in old_satisfies:
new_element = {}
# Handle exsiting data
add_if_exists(
new_data=new_element,
old_data=element,
field='narrative'
)
add_if_exists(
new_data=new_element,
old_data=element,
field='implementation_status'
)
# Handle covered_by
references = transform_covered_by(element.get('covered_by', {}))
control_key = element['control_key']
standard_key = element['standard_key']
if references:
new_element['references'] = references
# Unflatten
if standard_key not in new_satisfies:
new_satisfies[standard_key] = {}
if control_key not in new_satisfies[standard_key]:
new_satisfies[standard_key][control_key] = new_element
return new_satisfies
| 8,507 |
def require_backend(required_backend):
"""
Raise ``SkipTest`` unless the functional test configuration has
``required_backend``.
:param unicode required_backend: The name of the required backend.
:returns: A function decorator.
"""
def decorator(undecorated_object):
@wraps(undecorated_object)
def wrapper(*args, **kwargs):
config = get_blockdevice_config()
configured_backend = config.pop('backend')
skipper = skipUnless(
configured_backend == required_backend,
'The backend in the supplied configuration '
'is not suitable for this test. '
'Found: {!r}. Required: {!r}.'.format(
configured_backend, required_backend
)
)
decorated_object = skipper(undecorated_object)
result = decorated_object(*args, **kwargs)
return result
return wrapper
return decorator
| 8,508 |
def clip(src, shp):
"""
:param src: shapefile class with karst polygons. sinks.shp in db.
:param shp: shapefile class with basin boundary.
:return: shapefile output and class with karst.
"""
driver = ogr.GetDriverByName("ESRI Shapefile")
src_ds = driver.Open(src.path, 0)
src_layer = src_ds.GetLayer()
clip_ds = driver.Open(shp.path, 0)
clip_layer = clip_ds.GetLayer()
clip_prj = clip_layer.GetSpatialRef()
src_prj = src_layer.GetSpatialRef()
if src.prj4 != shp.prj4:
to_fill = ogr.GetDriverByName('Memory')
ds = to_fill.CreateDataSource("project")
out_layer = ds.CreateLayer('poly', src_prj, ogr.wkbPolygon)
feature = shp.lyr.GetFeature(0)
transform = osr.CoordinateTransformation(clip_prj, src_prj)
transformed = feature.GetGeometryRef()
transformed.Transform(transform)
geom = ogr.CreateGeometryFromWkb(transformed.ExportToWkb())
defn = out_layer.GetLayerDefn()
feat = ogr.Feature(defn)
feat.SetGeometry(geom)
out_layer.CreateFeature(feat.Clone())
clip_layer = out_layer
srs = osr.SpatialReference()
srs.ImportFromProj4(src.prj4)
out_path = shp.path[:-4] + '_karst.shp'
if os.path.exists(out_path):
driver.DeleteDataSource(out_path)
out_ds = driver.CreateDataSource(out_path)
out_layer = out_ds.CreateLayer('FINAL', srs=srs, geom_type=ogr.wkbMultiPolygon)
ogr.Layer.Clip(src_layer, clip_layer, out_layer)
out_ds = None
karstshp = dbShp(path=out_path)
return karstshp
| 8,509 |
def app_advertise_complete():
"""executed on disconnect of BLE
"""
print("app_advertise_complete")
| 8,510 |
def fixed_data(input_df, level, db_name):
"""修复日期、股票代码、数量单位及规范列名称"""
# 避免原地修改
df = input_df.copy()
df = _special_fix(df, level, db_name)
df = _fix_code(df)
df = _fix_date(df)
df = _fix_num_unit(df)
df = _fix_col_name(df)
return df
| 8,511 |
def get_nsg_e(ocp: AcadosOcp):
""" number of slack variables for linear constraints on terminal state and controls """
return int(ocp.constraints.idxsg_e.shape[0])
| 8,512 |
def generate_test_samples(y, input_seq_len, output_seq_len):
"""
Generate all the test samples at one time
:param x: df
:param y:
:param input_seq_len:
:param output_seq_len:
:return:
"""
total_samples = y.shape[0]
input_batch_idxs = [list(range(i, i + input_seq_len+output_seq_len)) for i in
range((total_samples - input_seq_len - output_seq_len+1))]
input_seq = np.take(y, input_batch_idxs, axis=0)
return input_seq
| 8,513 |
def ancestors(graph, *args, stop=None):
"""Iterate over all ancestor nodes in a DiGraph given
one or more initial Nodes.
"""
if stop is None:
stop = set()
for node in args:
if node in stop:
pass
else:
yield node
stop.add(node)
preds = graph.predecessors(node)
yield from ancestors(graph, *preds, stop=stop)
| 8,514 |
def get_tv_torrent_torrentz( name, maxnum = 10, verify = True ):
"""
Returns a :py:class:`tuple` of candidate episode Magnet links found using the Torrentz_ torrent service and the string ``"SUCCESS"``, if successful.
:param str name: the episode string on which to search.
:param int maxnum: optional argument, the maximum number of magnet links to return. Default is 10. Must be :math:`\ge 5`.
:param bool verify: optional argument, whether to verify SSL connections. Default is ``True``.
:returns: if successful, then returns a two member :py:class:`tuple` the first member is a :py:class:`list` of elements that match the searched episode, ordered from *most* seeds and leechers to least. The second element is the string ``"SUCCESS"``. The keys in each element of the list are,
* ``title`` is the name of the candidate episode to download.
* ``seeders`` is the number of seeds for this Magnet link.
* ``leechers`` is the number of leeches for this Magnet link.
* ``link`` is the Magnet URI link.
If this is unsuccessful, then returns an error :py:class:`tuple` of the form returned by :py:meth:`return_error_raw <howdy.core.return_error_raw>`.
:rtype: tuple
.. warning:: As of |date|, I cannot get it to work when giving it valid episode searches, such as ``"The Simpsons S31E01"``. See :numref:`table_working_tvtorrents`.
.. _Torrentz: https://en.wikipedia.org/wiki/Torrentz
"""
names_of_trackers = map(lambda tracker: tracker.replace(':', '%3A').replace('/', '%2F'), [
'udp://tracker.opentrackr.org:1337/announce',
'udp://open.demonii.com:1337',
'udp://tracker.pomf.se:80/announce',
'udp://torrent.gresille.org:80/announce',
'udp://11.rarbg.com/announce',
'udp://11.rarbg.com:80/announce',
'udp://open.demonii.com:1337/announce',
'udp://tracker.openbittorrent.com:80',
'http://tracker.ex.ua:80/announce',
'http://tracker.ex.ua/announce',
'http://bt.careland.com.cn:6969/announce',
'udp://glotorrents.pw:6969/announce'
])
tracklist = ''.join(map(lambda tracker: '&tr=%s' % tracker, names_of_trackers ) )
#
def try_int( candidate, default_value=0):
"""
Try to convert ``candidate`` to int, or return the ``default_value``.
:param candidate: The value to convert to int
:param default_value: The value to return if the conversion fails
:return: ``candidate`` as int, or ``default_value`` if the conversion fails
"""
try:
return int(candidate)
except (ValueError, TypeError):
return default_value
def _split_description(description):
match = re.findall(r'[0-9]+', description)
return int(match[0]) * 1024 ** 2, int(match[1]), int(match[2])
#
url = 'https://torrentz2.eu/feed'
search_params = {'f': name }
scraper = cfscrape.create_scraper( )
response = scraper.get( url, params = search_params, verify = verify )
if response.status_code != 200:
return return_error_raw( 'FAILURE, request for %s did not work.' % name )
if not response.content.startswith(b'<?xml'):
return return_error_raw( 'ERROR, request content is not a valid XML block.' )
html = BeautifulSoup( response.content, 'lxml' )
items = []
for item in html('item'):
if item.category and 'tv' not in item.category.get_text(strip=True).lower():
continue
title = item.title.get_text(strip=True)
t_hash = item.guid.get_text(strip=True).rsplit('/', 1)[-1]
if not all([title, t_hash]):
continue
download_url = "magnet:?xt=urn:btih:" + t_hash + "&dn=" + '+'.join(title.split()) + tracklist
torrent_size, seeders, leechers = _split_description(item.find('description').text)
if get_maximum_matchval( title, name ) < 80: continue
myitem = {'title': title, 'link': download_url, 'seeders': seeders,
'leechers': leechers }
items.append(myitem)
if len( items ) == 0:
return return_error_raw(
'Failure, no tv shows or series satisfying criteria for getting %s.' % name)
items.sort(key=lambda d: try_int(d.get('seeders', 0)) +
try_int(d.get('leechers')), reverse=True)
items = items[:maxnum]
return items, 'SUCCESS'
| 8,515 |
def plot_diagram_density(dgm, lognorm=True, diagonal=True,
show=False, labels=False, ax=None, **hist_style):
"""
Plot the histogram of point density.
Arguments:
dgm (Diagram): See for example `init_diagrams`.
Keyword Arguments:
bins (int): bins for histogram, see `ax.hist2d` (Default: 200)
lognorm (bool): Use logarithmic norm (Default: True)
diagonal (bool): (Default: True)
show (bool): Display the plot. (Default: False)
labels (bool): Set axis labels. (Default: False)
ax (AxesSubplot): Axes that should be used for plotting (Default: None)
**hist_style: Arguments passed to `ax.hist2d` for style of the histogram.
(Defaults: bins=200)
"""
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, Normalize
hist_kwargs = {'bins': 200}
hist_kwargs.update(hist_style)
if lognorm:
norm = LogNorm()
else:
norm = Normalize()
inf = float('inf')
min_birth = min(p.birth for p in dgm if p.birth != inf)
#max_birth = max(p.birth for p in dgm if p.birth != inf)
#min_death = min(p.death for p in dgm if p.death != inf)
max_death = max(p.death for p in dgm if p.death != inf)
if ax is None:
_, ax = plt.subplots()
hist2d, histx, histy, im = ax.hist2d([p.birth for p in dgm if p.birth != inf and p.death != inf], [p.death for p in dgm if p.birth != inf and p.death != inf], norm=norm, **hist_kwargs)
ax.set_aspect('equal', 'datalim')
if labels:
ax.set_xlabel('birth')
ax.set_ylabel('death')
if diagonal:
ax.plot([min_birth, max_death], [min_birth, max_death])
## clip the view
#plt.axes().set_xlim([min_birth, max_birth])
#plt.axes().set_ylim([min_death, max_death])
if labels:
plt.colorbar(im, ax=ax, label='overlap quantity')
else:
plt.colorbar(im, ax=ax)
if show:
plt.show()
| 8,516 |
def errfunc(p, x, y, numpoly, numharm):
""" function to calc the difference between input values and function """
return y - fitFunc(p, x, numpoly, numharm)
| 8,517 |
def create_token_column(col):
"""
Creates a cleaned and tokenised column
based on a sentence column in a dataframe
"""
# Convert it to lowercase
col = col.str.lower()
# Remove all non-alphanumeric characters
col = col.replace(r"\W", " ", regex=True)
# Collapse repeated spaces
col = col.replace(r"\s{2,}", " ", regex=True).str.strip()
# Split the strings into tokens
col = col.apply(word_tokenize)
# Lemmatise the column
col = lemmatise(col)
# Remove boring words
col = remove_simple(col)
# Rejoin the token lists into strings
col = col.apply(lambda x: " ".join(x))
# Return the final, cleaned version
return col
| 8,518 |
def get_browser(request, ):
"""
获取浏览器名
:param request:
:param args:
:param kwargs:
:return:
"""
ua_string = request.META['HTTP_USER_AGENT']
user_agent = parse(ua_string)
return user_agent.get_browser()
| 8,519 |
def test_transformer_pipeline_empty():
"""Test that the pipeline doesn't fail with empty input"""
orig_config = Config().from_str(cfg_string)
nlp = util.load_model_from_config(orig_config, auto_fill=True, validate=True)
tagger = nlp.get_pipe("tagger")
train_examples = []
for t in TRAIN_DATA:
train_examples.append(Example.from_dict(nlp.make_doc(t[0]), t[1]))
for tag in t[1]["tags"]:
tagger.add_label(tag)
# train on empty doc
optimizer = nlp.initialize()
losses = {}
empty_train_example = Example.from_dict(nlp.make_doc(""), {})
nlp.update(train_examples, sgd=optimizer, losses=losses)
nlp.update([empty_train_example], sgd=optimizer, losses=losses)
train_examples.append(empty_train_example)
nlp.update(train_examples, sgd=optimizer, losses=losses)
# predict empty doc
doc = nlp("")
_assert_empty(doc._.trf_data)
docs = nlp.pipe(["", ""])
for doc in docs:
_assert_empty(doc._.trf_data)
nlp.pipe([])
# predict combination of empty and non-empty
doc = nlp("This is a sentence")
normal_tags = [t.tag_ for t in doc]
docs = list(nlp.pipe(["", "This is a sentence", "", ""]))
_assert_empty(docs[0]._.trf_data)
assert [t.tag_ for t in docs[0]] == []
assert [t.tag_ for t in docs[1]] == normal_tags
_assert_empty(docs[2]._.trf_data)
_assert_empty(docs[3]._.trf_data)
| 8,520 |
def predict(X, centroids, ccov, mc):
"""Predict the entries in X, which contains NaNs.
Parameters
----------
X : np array
2d np array containing the inputs. Target are specified with numpy NaNs.
The NaNs will be replaced with the most probable result according to the
GMM model provided.
centroids : list
List of cluster centers - [ [x1,y1,..],..,[xN, yN,..] ]
ccov : list
List of cluster co-variances DxD matrices
mc : list
Mixing cofficients for each cluster (must sum to one) by default equal
for each cluster.
Returns
-------
var : list
List of variance
"""
samples, D = X.shape
variance_list = []
for i in range(samples):
row = X[i, :]
targets = np.isnan(row)
num_targets = np.sum(targets)
cen_cond, cov_cond, mc_cond = cond_dist(row, centroids, ccov, mc)
X[i, targets] = np.zeros(np.sum(targets))
vara = np.zeros((num_targets, num_targets))
varb = np.zeros((num_targets, num_targets))
for j in range(len(cen_cond)):
X[i,targets] = X[i,targets] + (cen_cond[j]*mc_cond[j])
vara = vara + mc_cond[j] * \
(np.dot(cen_cond[j], cen_cond[j]) + cov_cond[j])
varb = varb + mc_cond[j] * cen_cond[j]
variance_list.append(vara - np.dot(varb, varb))
return variance_list
| 8,521 |
def info(*msgs):
#===============================================================================
"""
Display INFO level messages.
"""
display_messages(msgs, tag = 'INFO')
| 8,522 |
def rotate_image(img, angle):
""" Rotate an image around its center
# Arguments
img: image to be rotated (np array)
angle: angle of rotation
returns: rotated image
"""
image_center = tuple(np.array(img.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
transformed_image = cv2.warpAffine(img, rot_mat, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return transformed_image
| 8,523 |
def standardize_1d(self, func, *args, autoformat=None, **kwargs):
"""
Interpret positional arguments for the "1D" plotting methods so usage is
consistent. Positional arguments are standardized as follows:
* If a 2D array is passed, the corresponding plot command is called for
each column of data (except for ``boxplot`` and ``violinplot``, in which
case each column is interpreted as a distribution).
* If *x* and *y* or *latitude* and *longitude* coordinates were not
provided, and a `~pandas.DataFrame` or `~xarray.DataArray`, we
try to infer them from the metadata. Otherwise,
``np.arange(0, data.shape[0])`` is used.
Parameters
----------
%(standardize.autoformat)s
See also
--------
cycle_changer
Note
----
This function wraps {methods}
"""
# Sanitize input
# TODO: Add exceptions for methods other than 'hist'?
name = func.__name__
autoformat = _not_none(autoformat, rc['autoformat'])
_load_objects()
if not args:
return func(self, *args, **kwargs)
elif len(args) == 1:
x = None
y, *args = args
elif len(args) <= 4: # max signature is x, y, z, color
x, y, *args = args
else:
raise ValueError(
f'{name}() takes up to 4 positional arguments but {len(args)} was given.'
)
vert = kwargs.get('vert', None)
if vert is not None:
orientation = ('vertical' if vert else 'horizontal')
else:
orientation = kwargs.get('orientation', 'vertical')
# Iterate through list of ys that we assume are identical
# Standardize based on the first y input
if len(args) >= 1 and 'fill_between' in name:
ys, args = (y, args[0]), args[1:]
else:
ys = (y,)
ys = [_to_arraylike(y) for y in ys]
# Auto x coords
y = ys[0] # test the first y input
if x is None:
axis = int(
name in ('hist', 'boxplot', 'violinplot')
or any(kwargs.get(s, None) for s in ('means', 'medians'))
)
x, _ = _axis_labels_title(y, axis=axis)
x = _to_arraylike(x)
if x.ndim != 1:
raise ValueError(
f'x coordinates must be 1-dimensional, but got {x.ndim}.'
)
# Auto formatting
x_index = None # index version of 'x'
if not hasattr(self, 'projection'):
# First handle string-type x-coordinates
kw = {}
xname = 'y' if orientation == 'horizontal' else 'x'
yname = 'x' if xname == 'y' else 'y'
if _is_string(x):
if name in ('hist',):
kwargs.setdefault('labels', list(x))
else:
x_index = np.arange(len(x))
kw[xname + 'locator'] = mticker.FixedLocator(x_index)
kw[xname + 'formatter'] = mticker.IndexFormatter(x)
kw[xname + 'minorlocator'] = mticker.NullLocator()
if name == 'boxplot': # otherwise IndexFormatter is overridden
kwargs['labels'] = x
# Next handle labels if 'autoformat' is on
# NOTE: Do not overwrite existing labels!
if autoformat:
# Ylabel
y, label = _axis_labels_title(y)
iname = xname if name in ('hist',) else yname
if label and not getattr(self, f'get_{iname}label')():
# For histograms, this label is used for *x* coordinates
kw[iname + 'label'] = label
if name not in ('hist',):
# Xlabel
x, label = _axis_labels_title(x)
if label and not getattr(self, f'get_{xname}label')():
kw[xname + 'label'] = label
# Reversed axis
if name not in ('scatter',):
if x_index is None and len(x) > 1 and x[1] < x[0]:
kw[xname + 'reverse'] = True
# Appply
if kw:
self.format(**kw)
# Standardize args
if x_index is not None:
x = x_index
if name in ('boxplot', 'violinplot'):
ys = [_to_ndarray(yi) for yi in ys] # store naked array
kwargs['positions'] = x
# Basemap shift x coordiantes without shifting y, we fix this!
if getattr(self, 'name', '') == 'basemap' and kwargs.get('latlon', None):
ix, iys = x, []
xmin, xmax = self.projection.lonmin, self.projection.lonmax
for y in ys:
# Ensure data is monotonic and falls within map bounds
ix, iy = _enforce_bounds(*_fix_latlon(x, y), xmin, xmax)
iys.append(iy)
x, ys = ix, iys
# WARNING: For some functions, e.g. boxplot and violinplot, we *require*
# cycle_changer is also applied so it can strip 'x' input.
with rc.context(autoformat=autoformat):
return func(self, x, *ys, *args, **kwargs)
| 8,524 |
def build_transformer_crf_model(config):
"""
"""
src_vocab_size = config["src_vocab_size"]
src_max_len = config["src_max_len"]
n_heads = config["n_heads"]
d_model = config["d_model"]
d_ff = config["d_ff"]
d_qk = config.get("d_qk", d_model//n_heads)
d_v = config.get("d_v", d_model//n_heads)
n_enc_layers = config["n_enc_layers"]
dropout = config.get("dropout", 0)
n_labels = config["n_labels"]
share_layer_params = config.get("share_layer_params", False)
n_share_across_layers = config.get("n_share_across_layers", 1)
embedding_size = config.get("embedding_size", None)
use_pre_norm = config.get("use_pre_norm", True)
activation = config.get("activation", "relu")
scale_embedding = config.get("scale_embedding", False)
transformer = TransformerCRF(config["symbol2id"],
src_vocab_size,
src_max_len,
n_heads,
d_model,
d_ff,
d_qk,
d_v,
n_enc_layers,
dropout,
n_labels,
embedding_size,
share_layer_params,
n_share_across_layers,
use_pre_norm,
activation,
scale_embedding)
return transformer
| 8,525 |
def test_resource_without_path(config: Config, db: SQLAlchemy):
"""Test resources that don't have url_prefix."""
class FooDef(Resource):
VIEW = View
__type__ = 'Foo'
def __init__(self, app,
import_name=__name__.split('.')[0],
static_folder=None,
static_url_path=None,
template_folder=None,
url_prefix='', # We set url_prefix to empty string
subdomain=None,
url_defaults=None,
root_path=None):
super().__init__(app, import_name, static_folder, static_url_path, template_folder,
url_prefix, subdomain, url_defaults, root_path)
config.RESOURCE_DEFINITIONS = FooDef,
app = Teal(config=config, db=db)
with app.test_request_context():
assert url_for_resource(FooDef) == '/'
assert url_for_resource(FooDef, 1) == '/1'
| 8,526 |
def frac_mole_to_weight(nfrac, MM):
"""
Args:
nfrac(np.array): mole fraction of each compound
MM(np.array): molar mass of each compound
"""
return nfrac * MM / (nfrac * MM).sum()
| 8,527 |
def get_close_hour_local():
"""
gets closing hour in local machine time (4 pm Eastern)
"""
eastern_tz = timezone('US/Eastern')
eastern_close = datetime.datetime(year=2018, month=6, day=29, hour=16)
eastern_close = eastern_tz.localize(eastern_close)
return str(eastern_close.astimezone().hour)
| 8,528 |
def parse_structure(node):
"""Turn a collapsed node in an OverlayGraph into a heirchaical grpah structure."""
if node is None:
return None
structure = node.sub_structure
if structure is None:
return node.name
elif structure.structure_type == "Sequence":
return {"Sequence" : [parse_structure(n) for n in structure.structure["sequence"]]}
elif structure.structure_type == "HeadBranch":
return {"Sequence" : [
{"Branch" : [parse_structure(n) for n in structure.structure["branches"]] },
parse_structure(structure.structure["head"])
]}
elif structure.structure_type == "TailBranch":
return {"Sequence" : [
parse_structure(structure.structure["tail"]),
{"Branch" : [parse_structure(n) for n in structure.structure["branches"]] },
]}
else:
data = {}
for k in structure.structure:
if isinstance(structure.structure[k], list):
data[k] = [parse_structure(n) for n in structure.structure[k]]
else:
data[k] = parse_structure(structure.structure[k])
return {structure.structure_type : data}
| 8,529 |
def softmax_kl_loss(input_logits, target_logits, sigmoid=False):
"""Takes softmax on both sides and returns KL divergence
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to inputs but not the targets.
"""
assert input_logits.size() == target_logits.size()
if sigmoid:
input_log_softmax = torch.log(torch.sigmoid(input_logits))
target_softmax = torch.sigmoid(target_logits)
else:
input_log_softmax = F.log_softmax(input_logits, dim=1)
target_softmax = F.softmax(target_logits, dim=1)
# return F.kl_div(input_log_softmax, target_softmax)
kl_div = F.kl_div(input_log_softmax, target_softmax, reduction='mean')
# mean_kl_div = torch.mean(0.2*kl_div[:,0,...]+0.8*kl_div[:,1,...])
return kl_div
| 8,530 |
def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
"""Initialize network weights.
Args:
module_list (list[nn.Module] | nn.Module): Modules to be initialized.
scale (float): Scale initialized weights, especially for residual
blocks. Default: 1.
bias_fill (float): The value to fill bias. Default: 0
kwargs (dict): Other arguments for initialization function.
"""
if not isinstance(module_list, list):
module_list = [module_list]
for m in module_list:
if isinstance(m, nn.Conv2D):
kaiming_normal_(m.weight, **kwargs)
scale_weight = scale * m.weight
m.weight.set_value(scale_weight)
if m.bias is not None:
constant_(m.bias, bias_fill)
elif isinstance(m, nn.Linear):
kaiming_normal_(m.weight, **kwargs)
scale_weight = scale * m.weight
m.weight.set_value(scale_weight)
if m.bias is not None:
constant_(m.bias, bias_fill)
| 8,531 |
def cut_rod_top_down_cache(p, n):
"""
Only difference from book is creating the array to n+1 since range doesn't
include the end bound.
"""
r = [-100000 for i in range(n + 1)]
return cut_rod_top_down_cache_helper(p, n, r)
| 8,532 |
def column_ids_to_names(convert_table, sharepoint_row):
""" Replace the column ID used by SharePoint by their column names for use in DSS"""
return {convert_table[key]: value for key, value in sharepoint_row.items() if key in convert_table}
| 8,533 |
def recursive_olsresiduals(res, skip=None, lamda=0.0, alpha=0.95,
order_by=None):
"""
Calculate recursive ols with residuals and Cusum test statistic
Parameters
----------
res : RegressionResults
Results from estimation of a regression model.
skip : int, default None
The number of observations to use for initial OLS, if None then skip is
set equal to the number of regressors (columns in exog).
lamda : float, default 0.0
The weight for Ridge correction to initial (X'X)^{-1}.
alpha : {0.90, 0.95, 0.99}, default 0.95
Confidence level of test, currently only two values supported,
used for confidence interval in cusum graph.
order_by : array_like, default None
Integer array specifying the order of the residuals. If not provided,
the order of the residuals is not changed. If provided, must have
the same number of observations as the endogenous variable.
Returns
-------
rresid : ndarray
The recursive ols residuals.
rparams : ndarray
The recursive ols parameter estimates.
rypred : ndarray
The recursive prediction of endogenous variable.
rresid_standardized : ndarray
The recursive residuals standardized so that N(0,sigma2) distributed,
where sigma2 is the error variance.
rresid_scaled : ndarray
The recursive residuals normalize so that N(0,1) distributed.
rcusum : ndarray
The cumulative residuals for cusum test.
rcusumci : ndarray
The confidence interval for cusum test using a size of alpha.
Notes
-----
It produces same recursive residuals as other version. This version updates
the inverse of the X'X matrix and does not require matrix inversion during
updating. looks efficient but no timing
Confidence interval in Greene and Brown, Durbin and Evans is the same as
in Ploberger after a little bit of algebra.
References
----------
jplv to check formulas, follows Harvey
BigJudge 5.5.2b for formula for inverse(X'X) updating
Greene section 7.5.2
Brown, R. L., J. Durbin, and J. M. Evans. “Techniques for Testing the
Constancy of Regression Relationships over Time.”
Journal of the Royal Statistical Society. Series B (Methodological) 37,
no. 2 (1975): 149-192.
"""
y = res.model.endog
x = res.model.exog
order_by = array_like(order_by, "order_by", dtype="int", optional=True,
ndim=1, shape=(y.shape[0],))
# intialize with skip observations
if order_by is not None:
x = x[order_by]
y = y[order_by]
nobs, nvars = x.shape
if skip is None:
skip = nvars
rparams = np.nan * np.zeros((nobs, nvars))
rresid = np.nan * np.zeros(nobs)
rypred = np.nan * np.zeros(nobs)
rvarraw = np.nan * np.zeros(nobs)
x0 = x[:skip]
if np.linalg.matrix_rank(x0) < x0.shape[1]:
err_msg = """\
"The initial regressor matrix, x[:skip], issingular. You must use a value of
skip large enough to ensure that the first OLS estimator is well-defined.
"""
raise ValueError(err_msg)
y0 = y[:skip]
# add Ridge to start (not in jplv)
xtxi = np.linalg.inv(np.dot(x0.T, x0) + lamda * np.eye(nvars))
xty = np.dot(x0.T, y0) # xi * y #np.dot(xi, y)
beta = np.dot(xtxi, xty)
rparams[skip - 1] = beta
yipred = np.dot(x[skip - 1], beta)
rypred[skip - 1] = yipred
rresid[skip - 1] = y[skip - 1] - yipred
rvarraw[skip - 1] = 1 + np.dot(x[skip - 1], np.dot(xtxi, x[skip - 1]))
for i in range(skip, nobs):
xi = x[i:i + 1, :]
yi = y[i]
# get prediction error with previous beta
yipred = np.dot(xi, beta)
rypred[i] = yipred
residi = yi - yipred
rresid[i] = residi
# update beta and inverse(X'X)
tmp = np.dot(xtxi, xi.T)
ft = 1 + np.dot(xi, tmp)
xtxi = xtxi - np.dot(tmp, tmp.T) / ft # BigJudge equ 5.5.15
beta = beta + (tmp * residi / ft).ravel() # BigJudge equ 5.5.14
rparams[i] = beta
rvarraw[i] = ft
rresid_scaled = rresid / np.sqrt(rvarraw) # N(0,sigma2) distributed
nrr = nobs - skip
# sigma2 = rresid_scaled[skip-1:].var(ddof=1) #var or sum of squares ?
# Greene has var, jplv and Ploberger have sum of squares (Ass.:mean=0)
# Gretl uses: by reverse engineering matching their numbers
sigma2 = rresid_scaled[skip:].var(ddof=1)
rresid_standardized = rresid_scaled / np.sqrt(sigma2) # N(0,1) distributed
rcusum = rresid_standardized[skip - 1:].cumsum()
# confidence interval points in Greene p136 looks strange. Cleared up
# this assumes sum of independent standard normal, which does not take into
# account that we make many tests at the same time
if alpha == 0.90:
a = 0.850
elif alpha == 0.95:
a = 0.948
elif alpha == 0.99:
a = 1.143
else:
raise ValueError("alpha can only be 0.9, 0.95 or 0.99")
# following taken from Ploberger,
# crit = a * np.sqrt(nrr)
rcusumci = (a * np.sqrt(nrr) + 2 * a * np.arange(0, nobs - skip) / np.sqrt(
nrr)) * np.array([[-1.], [+1.]])
return (rresid, rparams, rypred, rresid_standardized, rresid_scaled,
rcusum, rcusumci)
| 8,534 |
def main():
"""Fetches and saves attachments from emails using Gmail API.
Creates a Gmail API service object and applies custom query,
then fetches all attachments and saves them along message metadata into
seperate folders.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
messages = get_messages(service, query='from:nihan has:attachment')
if not messages:
print('No messages with current criteria were found.')
else:
print('Found {} messages. Now fetching attachments'.format(
len(messages)))
msg_counts = defaultdict(int)
for message in messages:
cur_message_id = message['id']
cur_message = service.users().messages().get(
userId='me', id=cur_message_id).execute()
cur_message_date = get_message_date(cur_message)
cur_message_attchs = get_files_attached(cur_message)
if cur_message_attchs:
msg_counts[cur_message_date] += 1
msg_dir = "{}_{:03d}".format(
cur_message_date, msg_counts[cur_message_date])
msg_path = "{}/message.json".format(msg_dir)
try:
os.mkdir(msg_dir)
except OSError:
print("Found '{}', using it!".format(msg_dir))
if not os.path.isfile(msg_path):
with open(msg_path, 'w') as f:
json.dump(cur_message, f, indent=3,
separators=(',', ': '))
else:
print("Found a message in {}, skipping it".format(msg_dir))
for attch in cur_message_attchs:
file_name = "{}/{}".format(
msg_dir, unicode(attch['filename']).encode("utf-8"))
if not os.path.isfile(file_name):
with open(file_name, 'w') as f:
file_data = base64.urlsafe_b64decode(
get_attachment(service, cur_message_id,
attch['attchId']))
f.write(file_data)
else:
print("Found attachment '{}', skipping it".format(
file_name))
| 8,535 |
def is_RationalField(x):
"""
Check to see if ``x`` is the rational field.
EXAMPLES::
sage: from sage.rings.rational_field import is_RationalField as is_RF
sage: is_RF(QQ)
True
sage: is_RF(ZZ)
False
"""
return isinstance(x, RationalField)
| 8,536 |
def add_nearest_neighbor_value_field(ptype, coord_name, sampled_field, registry):
"""
This adds a nearest-neighbor field, where values on the mesh are assigned
based on the nearest particle value found. This is useful, for instance,
with voronoi-tesselations.
"""
field_name = ("deposit", f"{ptype}_nearest_{sampled_field}")
field_units = registry[ptype, sampled_field].units
unit_system = registry.ds.unit_system
def _nearest_value(field, data):
pos = data[ptype, coord_name]
pos = pos.convert_to_units("code_length")
value = data[ptype, sampled_field].in_base(unit_system.name)
rv = data.smooth(
pos, [value], method="nearest", create_octree=True, nneighbors=1
)
rv = data.apply_units(rv, field_units)
return rv
registry.add_field(
field_name,
sampling_type="cell",
function=_nearest_value,
validators=[ValidateSpatial(0)],
units=field_units,
)
return [field_name]
| 8,537 |
def create_directory_if_not_exists(dir_path):
""" Create directory path if it doesn't exist """
if not path_exists(dir_path):
mkdir_p(dir_path)
print('Creating {}'.format(dir_path))
return True
return False
| 8,538 |
def test_hel_gal():
"""
Note: slight offsets between Astropy / gary transformation and
this transformation are expected because this assumes (l,b)=(0,0)
is the Galactic center. Astropy uses a more modern measurement of
the position of the GC.
"""
np.random.seed(42)
RSUN = 8.*u.kpc
VCIRC = 240.*u.km/u.s
VLSR = [0,0,0.] * u.km/u.s
gc_frame = coord.Galactocentric(z_sun=0.*u.pc,
galcen_distance=RSUN)
l = np.random.uniform(0.,360.,size=n)*u.degree
b = np.random.uniform(-90.,90.,size=n)*u.degree
d = np.random.uniform(0.,100.,size=n)*u.kpc
mul_cosb = np.random.normal(0., 300., size=n)*u.km/u.s/d * np.cos(b)
mub = np.random.normal(0., 300., size=n)*u.km/u.s/d
vr = np.random.normal(0., 300., size=n)*u.km/u.s
mul_cosb = mul_cosb.to(u.mas/u.yr, equivalencies=u.dimensionless_angles())
mub = mub.to(u.mas/u.yr, equivalencies=u.dimensionless_angles())
c = coord.Galactic(l=l, b=b, distance=d)
vxyz = gc.vhel_to_gal(c, (mul_cosb,mub), vr,
vcirc=VCIRC, vlsr=VLSR,
galactocentric_frame=gc_frame)
xyz = c.transform_to(gc_frame).cartesian.xyz
x,y,z = xyz.decompose(galactic).value
vx,vy,vz = vxyz.decompose(galactic).value
X = hel_to_gal(np.vstack((l.decompose(galactic).value,
b.decompose(galactic).value,
d.decompose(galactic).value,
mul_cosb.decompose(galactic).value,
mub.decompose(galactic).value,
vr.decompose(galactic).value)).T,
Vcirc=VCIRC.decompose(galactic).value,
Rsun=RSUN.decompose(galactic).value)
x1,y1,z1,vx1,vy1,vz1 = X.T
assert np.allclose(x1, x, rtol=1E-2)
assert np.allclose(y1, y, rtol=1E-2)
assert np.allclose(z1, z, rtol=1E-2)
assert np.allclose(vx1, vx, rtol=1E-2)
assert np.allclose(vy1, vy, rtol=1E-2)
assert np.allclose(vz1, vz, rtol=1E-2)
| 8,539 |
def rdkit_smiles():
"""Assign the SMILES by RDKit on the new structure."""
new_smiles = ""
mol = Chem.MolFromMolFile("output.sdf")
new_smiles = Chem.MolToSmiles(mol, isomericsmiles=False)
return new_smiles
| 8,540 |
def load_ref_case(fname, name):
"""Loads PV power or Load from the reference cases
:param fname: Path to mat file
:type fname: string
:param name: Identifier for PV Power or Load
:type name: string
:return: Returns PV power or load from the reference case
:rtype: numpy array
"""
with open(fname, 'rb') as f:
a = np.load(f)
data = a[name]
return data
| 8,541 |
def make_unique_id():
"""Make a new UniqueId."""
return uuid.uuid4()
# return UniqueId(uuid.uuid4())
| 8,542 |
def read_uni(filename):
"""
Read a '*.uni' file. Returns the header as a dictionary and the content as
a numpy-array.
"""
with gzip.open(filename, 'rb') as bytestream:
header = _read_uni_header(bytestream)
array = _read_uni_array(bytestream, header)
return header, array
| 8,543 |
def _F(startmat,endmat):
"""Calculate the deformation tensor
to go from start to end
:startmat: ndarray
:endmat: ndarray
:returns: ndarray
"""
F=np.dot(endmat,np.linalg.inv(startmat))
return F
| 8,544 |
def get_docstrings(target, functions):
""" Proceses functions in target module and prompts user for documentation if none exists.
:param target: Loaded target python module
:param functions: List of defined functions in target module
:returns: Dict containing raw comments entered by user
"""
new_docs = {}
for funcname, theclass in functions.items():
# Init dict for this function's params
func_docs = OrderedDict()
func_docs['description'] = input('Enter brief function description for {0}: '.format(funcname))
if theclass is 'noclass':
myfunc = getattr(target, funcname)
if myfunc.__doc__ is None:
# Init dict for this function's params
myfunc = getattr(target, funcname)
sig = signature(myfunc)
logging.info('Ingesting doc for {0} with signature {1}'.format(funcname, str(sig)))
params = sig.parameters
for p in params:
p = 'param:'+p
func_docs[p] = input('Enter type and description for parameter {0} in {1}: '.format(p, funcname))
# Ingest return value doc
ret_doc = input('Enter return value description: ')
func_docs['returns'] = ret_doc
# Place param comment dict into return new_docs dict
new_docs[funcname] = func_docs
else:
myfunc = getattr(theclass, funcname)
if myfunc.__doc__ is None:
sig = signature(myfunc)
logging.info('Ingesting doc for {0} with signature {1}'.format(funcname, str(sig)))
params = sig.parameters
for p in params:
p = 'param:'+p
func_docs[p] = input('Enter type and description for parameter {0} in {1}: '.format(p, funcname))
# Ingest return value doc
ret_doc = input('Enter return value description: ')
func_docs['returns'] = ret_doc
# Place param comment dict into return new_docs dict
new_docs[funcname] = func_docs
return new_docs
| 8,545 |
def calculatePredictions(ReviewsD, userIDTest, scoreTest, simmilarities):
"""
Function finds userIDTest in all simmilar items and uses all the
scores for prediction calculation
Returns actualScore and predictedScore for further calculations
of finding rmse and mse values
"""
score = 0
sim = 0
sumB = 0
sumN = 0
# go over entire dictionary without testing(removed) item
for itemID, userScoreOther in ReviewsD.items():
# if same users were found
if (userIDTest in userScoreOther):
# find simmilarity and score
if (itemID in simmilarities):
sim = simmilarities[itemID]
if (sim == -1):
continue
score = userScoreOther[userIDTest]
# calculations for prediction
sumB += (score*sim)
sumN += math.fabs(sim)
if (sumB != 0 and sumN != 0):
print("User: ", userIDTest)
print("Actual score: ", scoreTest)
print("Predicted score: ", math.fabs(sumB/sumN))
actualScore = scoreTest
predictedScore = math.fabs(sumB/sumN)
print(" ")
# if predictions are found
return (actualScore, predictedScore)
else:
# no predictions found
return None
| 8,546 |
def plotPSD():
"""Enter plot menu"""
freq_range= ui.PSDEdit.text()
msg=subprocess.run(["python", os.path.join(script_dir,r"cli.py"), "plot", "--freq", freq_range, '--plot_type','psd'])
if msg.returncode != 0:
ui.errorBrowser.setText(_translate("SAKEDSP","Check Terminal for Errors"))
| 8,547 |
def ensure_absolute_url(query_url):
"""This function adds the base URL to the beginning of a query URL if not already present.
.. versionadded:: 3.2.0
:param query_url: The query URL that will be utilized in an API request
:type query_url: str
:returns: The query URL that includes a top-level domain
:raises: :py:exc:`TypeError`
"""
if not base_url:
raise errors.exceptions.MissingBaseUrlError()
if query_url and not query_url.startswith('http'):
query_url = f"{base_url}{query_url}" if query_url.startswith('/') else f"{base_url}/{query_url}"
return query_url
| 8,548 |
def create_data_source(
simiotics_client: Simiotics,
source_id: str,
s3_root: str,
) -> data_pb2.Source:
"""
Registers an S3 data source against a Simiotics data registry
Args:
simiotics_client
Simiotics client -- see the simiotics.client module
source_id
String identifying the source you would like to register
s3_root
Root under which all source samples may be found
Returns: Source object
"""
source = data_pb2.Source(
id=source_id,
source_type=data_pb2.Source.SourceType.SOURCE_S3,
data_access_spec=s3_root,
)
request = data_pb2.RegisterSourceRequest(
version=simiotics_client.client_version,
source=source,
)
response = simiotics_client.data_registry.RegisterSource(request)
return response.source
| 8,549 |
def func_2(x: float, c: float, d: float) -> float:
""" Test function 2. """
return x + c + d
| 8,550 |
async def async_get(server: t.Union[Server, str], view_or_url: str, view_data: Kwargs = None,
session: aiohttp.ClientSession = None,
params: Kwargs = None, **kwargs) -> Response:
"""Sends a GET request."""
return await async_request('get', server, view_or_url, view_data=view_data, session=session, params=params,
**kwargs)
| 8,551 |
def DictionaryAddSchemaVersion(builder, schemaVersion):
"""This method is deprecated. Please switch to AddSchemaVersion."""
return AddSchemaVersion(builder, schemaVersion)
| 8,552 |
def test_generate_model_circuit():
"""Test that a model circuit is randomly generated."""
model_circuit = quantum_volume.generate_model_circuit(
3, 3, random_state=np.random.RandomState(1))
assert len(model_circuit) == 24
# Ensure there are no measurement gates.
assert list(
model_circuit.findall_operations_with_gate_type(
cirq.MeasurementGate)) == []
| 8,553 |
def isInner(x1, y1, x2, y2, scale):
"""
Currently, it's a rectangular kernal
Other options:
rectangular
f(x) = 1 if a <= scale <= b else 0
I don't get the rest of them
http://saravananthirumuruganathan.wordpress.com/2010/04/01/introduction-to-mean-shift-algorithm/
"""
distance = math.sqrt( ((x1-x2)**2) + ((y1-y2)**2) )
return distance <= scale
| 8,554 |
def main(args):
"""
Main function that calls all other functions
Parameters
----------
args:
Input arguments to the script
"""
global model_init
global survey
global path_to_figures
global mf_type
survey = args.survey
machine = args.machine
nproc = args.nproc
mf_type = args.mf_type
ver = 2.0 # No more .dat
dict_of_paths = cwpaths.cookiecutter_paths()
path_to_raw = dict_of_paths['raw_dir']
path_to_proc = dict_of_paths['proc_dir']
path_to_data = dict_of_paths['data_dir']
path_to_figures = dict_of_paths['plot_dir']
path_to_external = dict_of_paths['ext_dir']
if machine == 'bender':
halo_catalog = '/home/asadm2/.astropy/cache/halotools/halo_catalogs/'\
'vishnu/rockstar/vishnu_rockstar_test.hdf5'
elif machine == 'mac':
halo_catalog = path_to_raw + 'vishnu_rockstar_test.hdf5'
if mf_type == 'smf':
path_to_proc = path_to_proc + 'smhm_run6/'
elif mf_type == 'bmf':
path_to_proc = path_to_proc + 'bmhm_run3/'
chi2_file = path_to_proc + '{0}_chi2.txt'.format(survey)
if mf_type == 'smf' and survey == 'eco' and ver == 1.0:
chain_file = path_to_proc + 'mcmc_{0}.dat'.format(survey)
else:
chain_file = path_to_proc + 'mcmc_{0}_raw.txt'.format(survey)
if survey == 'eco':
catl_file = path_to_raw + 'eco/eco_all.csv'
path_to_mocks = path_to_data + 'mocks/m200b/eco/'
elif survey == 'resolvea' or survey == 'resolveb':
catl_file = path_to_raw + 'RESOLVE_liveJune2019.csv'
if survey == 'resolvea':
path_to_mocks = path_to_external + 'RESOLVE_A_mvir_catls/'
else:
path_to_mocks = path_to_external + 'RESOLVE_B_mvir_catls/'
print('Reading chi-squared file')
chi2 = read_chi2(chi2_file)
print('Reading mcmc chain file')
mcmc_table = read_mcmc(chain_file)
print('Reading catalog')
catl, volume, cvar, z_median = read_data_catl(catl_file, survey)
print('Getting data in specific percentile')
mcmc_table_pctl, bf_params, bf_chi2 = \
get_paramvals_percentile(mcmc_table, 68, chi2)
print('Retrieving stellar mass from catalog')
stellar_mass_arr = catl.logmstar.values
if mf_type == 'smf':
maxis_data, phi_data, err_data_, bins_data, counts_data = \
diff_smf(stellar_mass_arr, volume, False)
elif mf_type == 'bmf':
gas_mass_arr = catl.logmgas.values
bary_mass_arr = calc_bary(stellar_mass_arr, gas_mass_arr)
maxis_data, phi_data, err_data_, bins_data, counts_data = \
diff_bmf(bary_mass_arr, volume, False)
print('Getting error in data')
err_data_mf = get_err_data(survey, path_to_mocks)
print('Initial population of halo catalog')
model_init = halocat_init(halo_catalog, z_median)
print('Retrieving Behroozi 2010 centrals')
model_init.mock.populate()
if survey == 'eco' or survey == 'resolvea':
if mf_type == 'smf':
limit = np.round(np.log10((10**8.9) / 2.041), 1)
elif mf_type == 'bmf':
limit = np.round(np.log10((10**9.4) / 2.041), 1)
elif survey == 'resolveb':
if mf_type == 'smf':
limit = np.round(np.log10((10**8.7) / 2.041), 1)
elif mf_type == 'bmf':
limit = np.round(np.log10((10**9.1) / 2.041), 1)
sample_mask = model_init.mock.galaxy_table['stellar_mass'] >= 10**limit
gals_b10 = model_init.mock.galaxy_table[sample_mask]
cen_gals_b10, cen_halos_b10 = get_centrals_mock(gals_b10)
print('Retrieving survey centrals')
cen_gals_data, cen_halos_data = get_centrals_data(catl)
# Need following two lines ONLY if using groupmass_s for RESOLVE-A
# cen_halos_data = np.array(list(cen_halos_data.values[:65]) + list(cen_halos_data.values[66:]))
# cen_gals_data = np.array(list(cen_gals_data.values[:65]) + list(cen_gals_data.values[66:]))
print('Multiprocessing')
result = mp_init(mcmc_table_pctl, nproc)
print('Getting best fit model and centrals')
maxis_bf, phi_bf, err_tot_bf, counts_bf, cen_gals_bf, cen_halos_bf = \
get_best_fit_model(bf_params)
print('Plotting MF')
plot_mf(result, maxis_bf, phi_bf, err_tot_bf, maxis_data, phi_data,
err_data_mf, bf_chi2)
print('Plotting XMHM')
plot_xmhm(result, cen_gals_bf, cen_halos_bf, cen_gals_data, cen_halos_data,
cen_gals_b10, cen_halos_b10, bf_chi2)
# xmhm_mocks = get_xmhm_mocks(survey, path_to_mocks, mf_type)
# plot_xmhm_data_mocks(cen_gals_data, cen_halos_data,
# xmhm_mocks, cen_gals_bf, cen_halos_bf)
| 8,555 |
def add_sulci(fig, dataview, extents=None, height=None, with_labels=True, overlay_file=None, **kwargs):
"""Add sulci layer to figure
Parameters
----------
fig : figure or ax
figure into which to plot image of curvature
dataview : cortex.Dataview object
dataview containing data to be plotted, subject (surface identifier), and transform.
extents : array-like
4 values for [Left, Right, Top, Bottom] extents of image plotted. None defaults to
extents of images already present in figure.
height : scalar
Height of image. None defaults to height of images already present in figure.
with_labels : bool
Whether to display text labels for sulci
Other Parameters
----------------
kwargs : keyword arguments
Keywords args govern line appearance in final plot. Allowable kwargs are : linewidth,
linecolor
Returns
-------
img : matplotlib.image.AxesImage
matplotlib axes image object for plotted data
"""
svgobject = db.get_overlay(dataview.subject, overlay_file=overlay_file)
svg_kws = _convert_svg_kwargs(kwargs)
layer_kws = _parse_defaults('sulci_paths')
layer_kws.update(svg_kws)
sulc = svgobject.get_texture('sulci', height, labels=with_labels, **layer_kws)
if extents is None:
extents = _get_extents(fig)
_, ax = _get_fig_and_ax(fig)
img = ax.imshow(sulc,
aspect='equal',
interpolation='bicubic',
extent=extents,
label='sulci',
zorder=5)
return img
| 8,556 |
def build_puller_tdwhdfs_config_param(
cluster_name,
connector,
data_id,
topic,
kafka_bs,
fs_default_name,
hadoop_job_ugi,
hdfs_data_dir,
username,
secure_id,
secure_key,
):
"""
tdw 数据拉取任务配置
:param cluster_name: 集群名
:param connector: 任务名
:param data_id: dataid
:param topic: 目标topic
:param kafka_bs: 目标kafka地址
:param fs_default_name: hdfs地址
:param hadoop_job_ugi: 内部版tdw的ugi
:param hdfs_data_dir: 数据目录
:param username: tdw提供的用户名
:param secure_id: tdw提供的secure_id
:param secure_key: tdw提供的secure_key
:return: config
"""
task_config = {
"connector": connector,
"dataId": "%s" % data_id,
"fsDefaultName": fs_default_name,
"hadoopJobUgi": hadoop_job_ugi,
"hdfsDataDir": hdfs_data_dir,
"hdfsConfDir": dataapi_settings.HDFS_DEFAULT_PULSAR_CONF_DIR,
}
tenant = settings.PULSAR_OUTER_TENANT
namespace = settings.PULSAR_OUTER_NAMESPACE
pulsar_topic = "persistent://{}/{}/{}".format(tenant, namespace, topic)
config = {
"topicName": pulsar_topic,
"parallelism": 1,
"archive": "builtin://databus_tdw_puller",
"schemaType": "STRING",
"configs": task_config,
}
return config
| 8,557 |
def generate_error_reply(message):
"""
Send an error to the user
"""
# Construct
header, question = ORIGINAL_HEADER, ORIGINAL_QUESTION
header._rcode = Header.RCODE_SRVFAIL
reply = header.pack() + question.pack()
# Send
ss.sendto(reply, ORIGINAL_ADDRESS)
| 8,558 |
def make_url(issue, sites=[]):
""" Compose search terms and sites with url safe encoding. """
print('issue', issue)
terms = issue.strip().split()
terms = [quote(x, safe='') for x in terms] # TODO test with just spaces
url = 'https://duckduckgo.com/?q=' + '+'.join(terms)
if sites:
url += '+' + quote('site:' + ','.join(sites)) + '&ia=web'
print(url)
return url
| 8,559 |
def order_by_digestibility(sv_reg, pft_id_set, aoi_path):
"""Calculate the order of feed types according to their digestibility.
During diet selection, animals select among feed types in descending order
by feed type digestibility. Because digestibility is linearly related to
crude protein content, the order of feed types may be estimated from their
nitrogen to carbon ratios. Order feed types by digestibility according to
the mean nitrogen to carbon ratio of each feed type across the study area
aoi.
Parameters:
sv_reg (dict): map of key, path pairs giving paths to state
variables for the previous month, including C and N in aboveground
live and standing dead
pft_id_set (set): set of integers identifying plant functional types
aoi_path (string): path to vector layer giving the spatial extent of
the model
Returns:
ordered_feed_types, a list of strings where each string designates a
feed type by a combination of pft_i and fraction (aboveground live
or standing dead), in descending order of digestibility
"""
def calc_nc_ratio(cstatv_path, nstatv_path, aoi_path):
"""Calculate the mean nitrogen to carbon ratio of a biomass fraction.
Calculate the mean nitrogen to carbon ratio of a biomass fraction
falling inside the study area aoi. The ratio is calculated from the
state variables representing carbon and nitrogen content of that
biomass fraction. If the area of interest vector dataset contains more
than one polygon feature, the average ratio is calculated across
features.
Parameters:
cstatv_path (string): path to raster containing carbon in the
biomass fraction
nstatv_path (string): path to raster containing nitrogen in the
biomass fraction
aoi_path (string): path to vector layer defining the study area of
interest
Returns:
nc_ratio, the ratio of mean nitrogen to mean carbon for this state
variable inside the model area of interest
"""
carbon_zonal_stat_df = pandas.DataFrame.from_dict(
pygeoprocessing.zonal_statistics((cstatv_path, 1), aoi_path),
orient='index')
if carbon_zonal_stat_df['count'].sum() == 0:
return 0
else:
mean_carbon = (
carbon_zonal_stat_df['sum'].sum() /
carbon_zonal_stat_df['count'].sum())
nitrogen_zonal_stat_df = pandas.DataFrame.from_dict(
pygeoprocessing.zonal_statistics((nstatv_path, 1), aoi_path),
orient='index')
if nitrogen_zonal_stat_df['count'].sum() == 0:
mean_nitrogen = 0
else:
mean_nitrogen = (
nitrogen_zonal_stat_df['sum'].sum() /
nitrogen_zonal_stat_df['count'].sum())
return (mean_nitrogen / mean_carbon)
nc_ratio_dict = {}
for pft_i in pft_id_set:
for statv in ['agliv', 'stded']:
cstatv_path = sv_reg['{}c_{}_path'.format(statv, pft_i)]
nstatv_path = sv_reg['{}e_1_{}_path'.format(statv, pft_i)]
nc_ratio = calc_nc_ratio(cstatv_path, nstatv_path, aoi_path)
nc_ratio_dict['{}_{}'.format(statv, pft_i)] = nc_ratio
# order the dictionary by descending N/C ratio keys, get list from values
sorted_list = sorted(
[(ratio, feed_type) for (feed_type, ratio) in
nc_ratio_dict.items()], reverse=True)
ordered_feed_types = [feed_type for (ratio, feed_type) in sorted_list]
return ordered_feed_types
| 8,560 |
def match(pattern, sexp, known_bindings={}):
"""
Determine if sexp matches the pattern, with the given known bindings already applied.
Returns None if no match, or a (possibly empty) dictionary of bindings if there is a match
Patterns look like this:
($ . $) matches the literal "$", no bindings (mostly useless)
(: . :) matches the literal ":", no bindings (mostly useless)
($ . A) matches B iff B is an atom; and A is bound to B
(: . A) matches B always; and A is bound to B
(A . B) matches (C . D) iff A matches C and B matches D
and bindings are the unification (as long as unification is possible)
"""
if not pattern.listp():
if sexp.listp():
return None
return known_bindings if pattern.as_atom() == sexp.as_atom() else None
left = pattern.first()
right = pattern.rest()
atom = sexp.as_atom()
if left == ATOM_MATCH:
if sexp.listp():
return None
if right == ATOM_MATCH:
if atom == ATOM_MATCH:
return {}
return None
return unify_bindings(known_bindings, right.as_atom(), sexp)
if left == SEXP_MATCH:
if right == SEXP_MATCH:
if atom == SEXP_MATCH:
return {}
return None
return unify_bindings(known_bindings, right.as_atom(), sexp)
if not sexp.listp():
return None
new_bindings = match(left, sexp.first(), known_bindings)
if new_bindings is None:
return new_bindings
return match(right, sexp.rest(), new_bindings)
| 8,561 |
def who_is_it(image_path, database, model):
"""
Implements face recognition for the happy house by finding who is the person on the image_path image.
Arguments:
image_path -- path to an image
database -- database containing image encodings along with the name of the person on the image
model -- your Inception model instance in Keras
Returns:
min_dist -- the minimum distance between image_path encoding and the encodings from the database
identity -- string, the name prediction for the person on image_path
"""
### START CODE HERE ###
## Step 1: Compute the target "encoding" for the image. Use img_to_encoding() see example above. ## (≈ 1 line)
encoding = img_to_encoding(image_path, model)
## Step 2: Find the closest encoding ##
# Initialize "min_dist" to a large value, say 100 (≈1 line)
min_dist = 100
# Loop over the database dictionary's names and encodings.
for (name, db_enc) in database.items():
# Compute L2 distance between the target "encoding" and the current "emb" from the database. (≈ 1 line)
dist = np.linalg.norm(encoding - db_enc)
# If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines)
if dist < min_dist:
min_dist = dist
identity = name
### END CODE HERE ###
if min_dist > 0.7:
print("Not in the database.")
else:
print ("it's " + str(identity) + ", the distance is " + str(min_dist))
return min_dist, identity
| 8,562 |
def generate_map_bin(geo, img_shape):
"""Create a q map and the pixel resolution bins
Parameters
----------
geo : pyFAI.geometry.Geometry instance
The calibrated geometry
img_shape : tuple, optional
The shape of the image, if None pull from the mask. Defaults to None.
Returns
-------
q : ndarray
The q map
qbin : ndarray
The pixel resolution bins
"""
r = geo.rArray(img_shape)
q = geo.qArray(img_shape) / 10 # type: np.ndarray
q_dq = geo.deltaQ(img_shape) / 10 # type: np.ndarray
pixel_size = [getattr(geo, a) for a in ["pixel1", "pixel2"]]
rres = np.hypot(*pixel_size)
rbins = np.arange(np.min(r) - rres / 2., np.max(r) + rres / 2., rres / 2.)
rbinned = BinnedStatistic1D(r.ravel(), statistic=np.max, bins=rbins)
qbin_sizes = rbinned(q_dq.ravel())
qbin_sizes = np.nan_to_num(qbin_sizes)
qbin = np.cumsum(qbin_sizes)
qbin[0] = np.min(q_dq)
if np.max(q) > qbin[-1]:
qbin[-1] = np.max(q)
return q, qbin
| 8,563 |
def parse_pileup(instream):
"""
Given a stream of the output of samtools mpileup, count
the number of reads at each position supporting the
reference allele and the number supporting a
non-reference allele.
Arguments:
- instream: input file stream containing samtools
mpileup output
Yields: tuples containing:
- chromosome/sequence name
- position in sequence
- coverage at this position
"""
for line in instream:
splits = line.strip().split("\t")
coverage = int(splits[3])
chrom = splits[0]
position = int(splits[1])
yield (chrom, position, coverage)
| 8,564 |
def read_poly_data(filename):
"""
This function..
:param filename:
:return:
"""
# Check which PolyData reader should be used
if ".vtk" in filename:
reader = vtk.vtkPolyDataReader()
reader.SetFileName(filename)
reader.Update()
return reader.GetOutput()
elif ".vtp" in filename:
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(filename)
reader.Update()
return reader.GetOutput()
else:
print("ERROR: Failed to read in polydata")
return sys.exit(os.EX_IOERR)
| 8,565 |
def main():
"""Clean and convert pandas DataFrame main data, and save it as .csv. Function is used
in github acrion. For details look at .github/workflows/dataloader.yml
"""
file_id = '1iAgNVDOUa-g22_VcuEAedR2tcfTlUcbFnXV5fMiqCR8'
file_url = 'https://docs.google.com/spreadsheets/d/{file_id}/gviz/tq?tqx=out:csv&sheet={sheet_name}'
sheets = ['data', 'destrib', 'rosstat']
loaded = {}
for sheet_name in sheets:
loaded[sheet_name] = dl.loader(file_id, file_url, sheet_name)
# table data preparing
data = loaded['data']
# replace nan to zeros
data.fillna(0, inplace=True)
# replace , by . in float numeric
data['infection rate'] = data['infection rate'].apply(lambda x: str(x))
data['IR7'] = data['IR7'].apply(lambda x: str(x))
data['infection rate'] = data['infection rate'].apply(lambda x: x.replace(',', '.'))
data['IR7'] = data['IR7'].apply(lambda x: x.replace(',', '.'))
# calculate cumulative metrics
data['кумул. случаи'] = data['всего'].cumsum()
data['кумул.умерли'] = data['умерли от ковид'].cumsum()
data['кумул.выписаны'] = data['выписали'].cumsum()
data['кумул.активные'] = data['кумул. случаи'].sub(data['кумул.выписаны']).sub(data['кумул.умерли'])
# scaling for tests
data['кол-во тестов / 10'] = data['кол-во тестов'] / 10
# region columns
data['все кроме Калининграда'] = data.filter(regex='округ').sum(axis=1)
# drop textual data
data.drop(['учебные учреждения'], axis=1, inplace=True)
# calculate attitude for infection rate
data['infection rate'] = data['infection rate'].astype(np.float16)
data['plus'] = data[data['infection rate'] >= 1]['infection rate']
data['minus'] = data[data['infection rate'] < 1]['infection rate']
data['plus'] = data['plus'].mask(data['plus'] >= 0, 1)
data['minus'] = data['minus'].mask(data['minus'] >= 0, 1)
data['plus'] = data['plus'].cumsum()
data['minus'] = data['minus'].cumsum()
data[['plus', 'minus']] = data[['plus', 'minus']].astype("object").fillna(method='ffill')
data['отношение'] = data['plus'] / data['minus']
data.drop(['plus', 'minus'], axis=1, inplace=True)
# minimize numerics memory sizes
data['IR7'] = data['IR7'].astype(np.float16)
data['отношение'] = data['отношение'].astype(np.float16)
data['отношение'] = data['отношение'].apply(lambda x: round(x, 2))
data['кол-во тестов кумул'] = data['кол-во тестов кумул'].astype(np.int32)
data['поступило кумулятивно'] = data['поступило кумулятивно'].astype(np.int32)
data['компонент 1'] = data['компонент 1'].astype(np.int32)
data['компонент 2'] = data['компонент 2'].astype(np.int32)
for i in data.columns.difference(['дата',
'infection rate',
'IR7', 'отношение',
'кол-во тестов / 10',
'кол-во тестов кумул',
'поступило кумулятивно',
'компонент 1',
'компонент 2',
]):
data[i] = data[i].astype(np.int16)
# flush
data.to_csv(dl.pathMaker('data'), index=False)
# table destrib preparing
destrib = loaded['destrib']
destrib.fillna(0, inplace=True)
for i in destrib.columns.difference(['дата']):
destrib[i] = destrib[i].astype(np.int8)
destrib.to_csv(dl.pathMaker('destrib'), index=False)
# table rosstat preparing
rosstat = loaded['rosstat']
rosstat.fillna(0, inplace=True)
for i in rosstat.columns.difference(['Месяц']):
rosstat[i] = rosstat[i].astype(np.int16)
rosstat.to_csv(dl.pathMaker('rosstat'), index=False)
| 8,566 |
def wklobjective_converged(qsum, f0, plansum, epsilon, gamma):
"""Compute finale wkl value after convergence."""
obj = gamma * (plansum + qsum)
obj += epsilon * f0
obj += - (epsilon + 2 * gamma) * plansum
return obj
| 8,567 |
def addFavDirections(request):
"""
Add favourite stop of currently logged in user by number.
Currently works with the URL: http://localhost:8000/api/add-fav-stop/<number>
"""
try:
user = request.user
origin = str(request.query_params.get('origin'))
destination = str(request.query_params.get('destination'))
url = str(request.query_params.get('url'))
r = FavouriteDirections(user=user,
origin=origin,
destination=destination,
url=url)
r.save()
return HttpResponse(status=status.HTTP_201_CREATED)
except IntegrityError as e:
return HttpResponse(
"Error: Stop is already a favourite for this user.")
except AssertionError as e:
return HttpResponse("Error: Stop number does not exist.")
| 8,568 |
def hpat_pandas_dataframe_index(df):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.index
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_index.py
:language: python
:lines: 27-
:caption: The index (row labels) of the DataFrame.
:name: ex_dataframe_index
.. command-output:: python ./dataframe/dataframe_index.py
:cwd: ../../../examples
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame attribute :attr:`pandas.DataFrame.index` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_index*
"""
ty_checker = TypeChecker('Attribute index.')
ty_checker.check(df, DataFrameType)
if isinstance(df.index, types.NoneType):
empty_df = not df.columns
def hpat_pandas_df_index_none_impl(df):
if empty_df == True: # noqa
return numpy.arange(0)
else:
return pandas.RangeIndex(len(df))
return hpat_pandas_df_index_none_impl
else:
def hpat_pandas_df_index_impl(df):
return df._index
return hpat_pandas_df_index_impl
| 8,569 |
def divide(a, b): # pragma: no cover
"""Divide two tensors.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: `a` divided by `b`.
"""
| 8,570 |
def _get_should_cache_fn(conf, group):
"""Build a function that returns a config group's caching status.
For any given object that has caching capabilities, a boolean config option
for that object's group should exist and default to ``True``. This
function will use that value to tell the caching decorator if caching for
that object is enabled. To properly use this with the decorator, pass this
function the configuration group and assign the result to a variable.
Pass the new variable to the caching decorator as the named argument
``should_cache_fn``.
:param conf: config object, must have had :func:`configure` called on it.
:type conf: oslo_config.cfg.ConfigOpts
:param group: name of the configuration group to examine
:type group: string
:returns: function reference
"""
def should_cache(value):
if not conf.cache.enabled:
return False
conf_group = getattr(conf, group)
return getattr(conf_group, 'caching', True)
return should_cache
| 8,571 |
def set_difference(lst1, lst2):
"""returns the elements and indicies of elements in lst1 that are not in lst2"""
elements = []
indicies = []
for indx, item in enumerate(lst1):
if item not in lst2:
elements.append(item)
indicies.append(indx)
return elements, indicies
| 8,572 |
def test_split_sentences():
""" Test shallow tokenization """
s = (
"3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000. \n"
"200.000 manns mótmæltu.\n"
"Hér byrjar ný setning"
)
g = t.split_into_sentences(s)
sents = list(g)
assert len(sents) == 4
assert sents[0] == "3. janúar sl. keypti ég 64kWst rafbíl ."
assert sents[1] == "Hann kostaði €30.000 ."
assert sents[2] == "200.000 manns mótmæltu ."
assert sents[3] == "Hér byrjar ný setning"
# Test using a generator as input into split_into_sentences()
s = (
"3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000. \n",
"200.000 manns mótmæltu\n",
"\n",
"Hér byrjar ný setning\n",
)
def gen(s):
for line in s:
yield line
g = t.split_into_sentences(gen(s))
sents = list(g)
assert len(sents) == 4
assert sents[0] == "3. janúar sl. keypti ég 64kWst rafbíl ."
assert sents[1] == "Hann kostaði €30.000 ."
assert sents[2] == "200.000 manns mótmæltu"
assert sents[3] == "Hér byrjar ný setning"
# Test the normalize option
s = (
"Hún sagði: \"Þú ert leiðinlegur\"! Hann svaraði engu -- "
"en hætti við ferðina. \n"
)
g = t.split_into_sentences(s, normalize=True)
sents = list(g)
assert len(sents) == 2
assert sents[0] == "Hún sagði : „ Þú ert leiðinlegur “ !"
assert sents[1] == "Hann svaraði engu - - en hætti við ferðina ."
g = t.split_into_sentences(s, normalize=False)
sents = list(g)
assert len(sents) == 2
assert sents[0] == "Hún sagði : \" Þú ert leiðinlegur \" !"
assert sents[1] == "Hann svaraði engu - - en hætti við ferðina ."
g = t.split_into_sentences(
"Aðalsteinn Jónsson SU á leið til hafnar í "
"Reykjavík.Flutningaskipið Selfoss kom til Reykjavíkur.Rósin sigldi með "
"ferðamenn í hvalaskoðun."
)
sents = list(g)
assert len(sents) == 3
assert sents == [
'Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík .',
'Flutningaskipið Selfoss kom til Reykjavíkur .',
'Rósin sigldi með ferðamenn í hvalaskoðun .',
]
g = t.split_into_sentences(
s for s in [
"Aðalsteinn Jónsson SU á leið til hafnar í ",
"Reykjavík.Flutningaskipið Selfoss kom til Reykjavíkur.Rósin sigldi með ",
"ferðamenn í hvalaskoðun.",
]
)
sents = list(g)
assert len(sents) == 3
assert sents == [
'Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík .',
'Flutningaskipið Selfoss kom til Reykjavíkur .',
'Rósin sigldi með ferðamenn í hvalaskoðun .',
]
g = t.split_into_sentences(
s for s in [
"Aðalsteinn Jónsson SU á leið \n til hafnar í ",
"Reykjavík.\nFlutningaskipið Selfoss \nkom til Reykjavíkur.Rósin sigldi með ",
"ferðamenn í\nhvalaskoðun.\n\n\n",
]
)
sents = list(g)
assert len(sents) == 3
assert sents == [
'Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík .',
'Flutningaskipið Selfoss kom til Reykjavíkur .',
'Rósin sigldi með ferðamenn í hvalaskoðun .'
]
g = t.split_into_sentences(
s for s in [
"Aðalsteinn Jónsson SU á leið \n til hafnar í ",
"Reykjavík\n \t \nFlutningaskipið Selfoss \nkom til Reykjavíkur",
"",
"Rósin sigldi með ",
"ferðamenn í\nhvalaskoðun\n\n\nVigur kom með fullfermi að landi",
]
)
sents = list(g)
assert len(sents) == 4
assert sents == [
'Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík',
'Flutningaskipið Selfoss kom til Reykjavíkur',
'Rósin sigldi með ferðamenn í hvalaskoðun',
"Vigur kom með fullfermi að landi",
]
| 8,573 |
def dub(
videoFile, outputDir, srcLang, targetLangs=[],
storageBucket=None, phraseHints=[], dubSrc=False,
speakerCount=1, voices={}, srt=False,
newDir=False, genAudio=False, noTranslate=False):
"""Translate and dub a movie.
Args:
videoFile (String): File to dub
outputDir (String): Directory to write output files
srcLang (String): Language code to translate from (i.e. "fi")
targetLangs (list, optional): Languages to translate too, i.e. ["en", "fr"]
storageBucket (String, optional): GCS bucket for temporary file storage. Defaults to None.
phraseHints (list, optional): "Hints" for words likely to appear in audio. Defaults to [].
dubSrc (bool, optional): Whether to generate dubs in the source language. Defaults to False.
speakerCount (int, optional): How many speakers in the video. Defaults to 1.
voices (dict, optional): Which voices to use for dubbing, i.e. {"en": "en-AU-Standard-A"}. Defaults to {}.
srt (bool, optional): Path of SRT transcript file, if it exists. Defaults to False.
newDir (bool, optional): Whether to start dubbing from scratch or use files in outputDir. Defaults to False.
genAudio (bool, optional): Generate new audio, even if it's already been generated. Defaults to False.
noTranslate (bool, optional): Don't translate. Defaults to False.
Raises:
void : Writes dubbed video and intermediate files to outputDir
"""
baseName = os.path.split(videoFile)[-1].split('.')[0]
if newDir:
shutil.rmtree(outputDir)
if not os.path.exists(outputDir):
os.mkdir(outputDir)
outputFiles = os.listdir(outputDir)
if not f"{baseName}.wav" in outputFiles:
print("Extracting audio from video")
fn = os.path.join(outputDir, baseName + ".wav")
decode_audio(videoFile, fn)
print(f"Wrote {fn}")
if not f"transcript.json" in outputFiles:
storageBucket = storageBucket if storageBucket else os.environ['STORAGE_BUCKET']
if not storageBucket:
raise Exception(
"Specify variable STORAGE_BUCKET in .env or as an arg")
print("Transcribing audio")
print("Uploading to the cloud...")
storage_client = storage.Client()
bucket = storage_client.bucket(storageBucket)
tmpFile = os.path.join("tmp", str(uuid.uuid4()) + ".wav")
blob = bucket.blob(tmpFile)
# Temporary upload audio file to the cloud
blob.upload_from_filename(os.path.join(
outputDir, baseName + ".wav"), content_type="audio/wav")
print("Transcribing...")
transcripts = get_transcripts_json(os.path.join(
"gs://", storageBucket, tmpFile), srcLang,
phraseHints=phraseHints,
speakerCount=speakerCount)
json.dump(transcripts, open(os.path.join(
outputDir, "transcript.json"), "w"))
sentences = parse_sentence_with_speaker(transcripts, srcLang)
fn = os.path.join(outputDir, baseName + ".json")
with open(fn, "w") as f:
json.dump(sentences, f)
print(f"Wrote {fn}")
print("Deleting cloud file...")
blob.delete()
srtPath = os.path.join(outputDir, "subtitles.srt") if srt else None
if srt:
transcripts = json.load(
open(os.path.join(outputDir, "transcript.json")))
subtitles = toSrt(transcripts)
with open(srtPath, "w") as f:
f.write(subtitles)
print(
f"Wrote srt subtitles to {os.path.join(outputDir, 'subtitles.srt')}")
sentences = json.load(open(os.path.join(outputDir, baseName + ".json")))
sentence = sentences[0]
if not noTranslate:
for lang in targetLangs:
print(f"Translating to {lang}")
for sentence in sentences:
sentence[lang] = translate_text(
sentence[srcLang], lang, srcLang)
# Write the translations to json
fn = os.path.join(outputDir, baseName + ".json")
with open(fn, "w") as f:
json.dump(sentences, f)
audioDir = os.path.join(outputDir, "audioClips")
if not "audioClips" in outputFiles:
os.mkdir(audioDir)
# whether or not to also dub the source language
if dubSrc:
targetLangs += [srcLang]
for lang in targetLangs:
languageDir = os.path.join(audioDir, lang)
if os.path.exists(languageDir):
if not genAudio:
continue
shutil.rmtree(languageDir)
os.mkdir(languageDir)
print(f"Synthesizing audio for {lang}")
for i, sentence in enumerate(sentences):
voiceName = voices[lang] if lang in voices else None
audio = speakUnderDuration(
sentence[lang], lang, sentence['end_time'] -
sentence['start_time'],
voiceName=voiceName)
with open(os.path.join(languageDir, f"{i}.mp3"), 'wb') as f:
f.write(audio)
dubbedDir = os.path.join(outputDir, "dubbedVideos")
if not "dubbedVideos" in outputFiles:
os.mkdir(dubbedDir)
for lang in targetLangs:
print(f"Dubbing audio for {lang}")
outFile = os.path.join(dubbedDir, lang + ".mp4")
stitch_audio(sentences, os.path.join(
audioDir, lang), videoFile, outFile, srtPath=srtPath)
print("Done")
| 8,574 |
def _get_dict(path):
"""
Parameters
__________
path: string or array
Path to json file. In case a list of paths is provided instead,
read them all and merge then into a single dict. Assumes depth two.
Returns
_______
d: dict
Dictionary containing marker information.
d = {
key: {
subkey: [...],
...
},
...
}
"""
# TODO straighten up the spaghetti
if isinstance(path, str):
with open(path, "r") as f:
return json.load(f)
else:
d = {}
for path in path:
with open(path, "r") as f:
d_part = json.load(f)
for key in d_part:
if key in d:
for subkey in d_part[key]:
if subkey in d[key]:
# to remove duplicates
d[key][subkey] = list(set().union(
d[key][subkey], d_part[key][subkey]))
else:
d[key][subkey] = d_part[key][subkey]
else:
d[key] = d_part[key]
return d
| 8,575 |
def _super_check(args, names, op, fmt, msg, val_err):
"""
A flexible function is used to check whether type or value of variables is valid,
which supports in both graph/pynative mode.
Args:
args(any): 'args' is used as one of argument for operation function and format function.
names(any): 'names' is used as one of argument for format function.
op(str): 'op' is a string to specify an operation. This operation will be obtained
an actual function from a StringDict object, with 'args' as argument.
fmt(str): 'fmt' is a string to specify a format. This format will be obtained
an actual function from a StringDict object, with 'args' and 'names' as arguments.
msg(str, tuple): 'msg' is used the case where format function is not necessary. When 'msg' is
not None, we will throw the 'msg' as the error message.
val_err(bool): Determine the type of TypeError/ValueError. When 'val_err' is True, raises
ValueError, otherwise TypeError.
Note:
This function does not contain any parameter checks.
"""
op_fn = _op_dict.get(op)
if not op_fn(args):
if not msg:
fmt_fn = _fmt_dict.get(fmt)
msg = fmt_fn(args, names)
if val_err:
_raise_value_error(*_tuple(msg))
else:
_raise_type_error(*_tuple(msg))
return args
| 8,576 |
def train(*args, **kwargs):
"""Generate a training request """
yield from _generate(*args, **kwargs)
req = jina_pb2.Request()
req.request_id = 1
req.train.flush = True
yield req
| 8,577 |
def obter_novo_username() -> str:
"""
-> Pede um novo nome de usuário.
:return: Retorna o novo nome de usuário.
"""
username = input('Qual é o seu nome? ')
arquivo = 'arquivos_json/nome_de_usuario.json'
with open(arquivo, 'w') as obj_arq:
json.dump(username, obj_arq)
return username
| 8,578 |
def print_head(df):
"""
Print the first five lines of df.
Parameters
----------
df : pandas dataframe
"""
print(df.head(n=5))
| 8,579 |
def BDD100K_MOT2020(path: str) -> Dataset:
"""`BDD100K_MOT2020 <https://bdd-data.berkeley.edu>`_ dataset.
The file structure should be like::
<path>
bdd100k_box_track_20/
images/
train/
00a0f008-3c67908e/
00a0f008-3c67908e-0000001.jpg
...
...
val/
b1c9c847-3bda4659/
b1c9c847-3bda4659-0000001.jpg
...
...
test/
cabc30fc-e7726578/
cabc30fc-e7726578-0000001.jpg
...
...
labels/
train/
00a0f008-3c67908e.json
...
val/
b1c9c847-3bda4659.json
...
Arguments:
path: The root directory of the dataset.
Returns:
Loaded :class:`~tensorbay.dataset.dataset.Dataset` instance.
"""
return _tracking_loader(path, "mot")
| 8,580 |
def _parse_block_postheader(line):
"""
(209)**************!*****************!!*************...
"""
parts = line[1:].split(')', 1)
qlen = int(parts[0])
if not len(parts[1]) == qlen:
logging.warn("postheader expected %d-long query, found %d",
qlen, len(parts[1]))
return qlen, parts[1]
| 8,581 |
def _remove_dimer_outliers(bond_lengths, energies, zscore_cutoff=3.0):
"""Removes outliers
"""
z_score = stats.zscore(energies)
idx_keep = np.where(z_score < zscore_cutoff)[0]
return bond_lengths[idx_keep], energies[idx_keep]
| 8,582 |
def get_auth_token(cmd_args=None):
"""
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: The current user's token
"""
r = Result("whoami")
r.add_action(oc_action(cur_context(), "whoami", cmd_args=['-t', cmd_args]))
r.fail_if("Unable to determine current token")
return r.out().strip()
| 8,583 |
def _is_toplevel_repository_dir(directory):
"""Returns if a directory is a git or mercurial directory.
This works by searching for a file or directory named `.git` or `.hg` in
the directory. This works for both submodules and normal repositories.
"""
return (os.path.exists(os.path.join(directory, ".git")) or
os.path.exists(os.path.join(directory, ".hg")))
| 8,584 |
def breakOnException(func=None, *, exceptionList=Exception, debugger='pdb'):
"""
A function wrapper that causes debug mode to be entered when the
wrapped function throws a specified exception.
Parameters
----------
func : The function to wrap.
exceptionList : An exception or tuple of exceptions to break on.
debugger : The debugger used when debug mode is entered. This can
be either the debugging module itself or a string containing
the name of the debugging module. Currently, pdb and ipdb are
supported.
"""
if func is None:
return partial(breakOnException, exceptionList=exceptionList,
debugger=debugger)
debugger = import_(debugger)
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exceptionList as e:
debug_frame = sys._getframe().f_back
set_trace(debug_frame, debugger)
return wrapper
| 8,585 |
def hash_sid(sid: str) -> str:
"""
Hash a SID preserving well-known SIDs and the RID.
Parameters
----------
sid : str
SID string
Returns
-------
str
Hashed SID
"""
if re.match(WK_SID_PATTERN, sid):
return sid
usr_sid = re.match(SID_PATTERN, sid)
if usr_sid:
return (
f"{usr_sid.groups()[0]}{hash_item(usr_sid.groups()[1], delim='-')}"
+ f"{usr_sid.groups()[2]}"
)
return sid
| 8,586 |
def horizontal_move(t, h_speed=-2/320):
"""Probe moves horizontally at h_speed [cm/s]"""
return 0.*t, h_speed*t, 2/16 + 0*t
| 8,587 |
def fix_pdp_post(monkeypatch):
"""monkeyed request /decision/v1 to PDP"""
def monkeyed_policy_rest_post(uri, json=None, **kwargs):
"""monkeypatch for the POST to policy-engine"""
return MockHttpResponse("post", uri, json=json, **kwargs)
_LOGGER.info("setup fix_pdp_post")
pdp_client.PolicyRest._lazy_inited = False
pdp_client.PolicyRest._lazy_init()
monkeypatch.setattr('policyhandler.pdp_client.PolicyRest._requests_session.post',
monkeyed_policy_rest_post)
yield fix_pdp_post
_LOGGER.info("teardown fix_pdp_post")
| 8,588 |
def del_project():
"""
@api {post} /v1/interfaceproject/del InterfaceProject_删除项目
@apiName interfaceProDel
@apiGroup Interface
@apiDescription 删除项目
@apiParam {int} id 子项目id
@apiParam {int} all_project_id 总项目id
@apiParamExample {json} Request-Example:
{
"id": 1,
"all_project_id": 4
}
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
"data": {
"environment_choice": "first",
"headers": [],
"host": [
"http://sx.api.mengtuiapp.com"
],
"host_four": [],
"host_three": [],
"host_two": [],
"principal": null,
"pro_name": "mengtui",
"user_id": 3,
"variables": []
},
"status": 1
}
"""
data = request.json
ids = data.get('id')
all_project_id = data.get('all_project_id')
jsondata = InterfaceProjectBusiness.del_project(ids, all_project_id)
return jsondata
| 8,589 |
def draw_pattern_fill(viewport, psd, desc):
"""
Create a pattern fill.
"""
pattern_id = desc[Enum.Pattern][Key.ID].value.rstrip('\x00')
pattern = psd._get_pattern(pattern_id)
if not pattern:
logger.error('Pattern not found: %s' % (pattern_id))
return None, None
panel = get_pattern(pattern)
assert panel.shape[0] > 0
scale = float(desc.get(Key.Scale, 100.)) / 100.
if scale != 1.:
from skimage.transform import resize
new_shape = (
max(1, int(panel.shape[0] * scale)),
max(1, int(panel.shape[1] * scale))
)
panel = resize(panel, new_shape)
height, width = viewport[3] - viewport[1], viewport[2] - viewport[0]
reps = (
int(np.ceil(float(height) / panel.shape[0])),
int(np.ceil(float(width) / panel.shape[1])),
1,
)
channels = EXPECTED_CHANNELS.get(pattern.image_mode)
pixels = np.tile(panel, reps)[:height, :width, :]
if pixels.shape[2] > channels:
return pixels[:, :, :channels], pixels[:, :, -1:]
return pixels, None
| 8,590 |
def register_post():
"""Registriraj novega uporabnika."""
username = bottle.request.forms.username
password1 = bottle.request.forms.password1
password2 = bottle.request.forms.password2
# Ali uporabnik že obstaja?
c = baza.cursor()
c.execute("SELECT 1 FROM uporabnik WHERE username=%s", [username])
if c.fetchone():
# Uporabnik že obstaja
return bottle.template("registracija.html",
username='',
napaka='To uporabniško ime je že zavzeto')
elif not password1 == password2:
# Gesli se ne ujemata
return bottle.template("registracija.html",
username='',
napaka='Gesli se ne ujemata')
else:
# Vse je v redu, vstavi novega uporabnika v bazo
password = password_md5(password1)
print('tukaj sem')
c.execute("INSERT INTO uporabnik (username, password) VALUES (%s, %s)",
(username, password))
bottle.redirect("/prijava/")
| 8,591 |
def check_format_input_vector(
inp,
dims,
shape_m1,
sig_name,
sig_type,
reshape=False,
allow_None=False,
forbid_negative0=False,
):
"""checks vector input and returns in formatted form
- inp must be array_like
- convert inp to ndarray with dtype float
- inp shape must be given by dims and shape_m1
- print error msg with signature arguments
- if reshape=True: returns shape (n,3) - required for position init and setter
- if allow_None: return None
- if extend_dim_to2: add a dimension if input is only (1,2,3) - required for sensor pixel
"""
if allow_None:
if inp is None:
return None
is_array_like(
inp,
f"Input parameter `{sig_name}` must be {sig_type}.\n"
f"Instead received type {type(inp)}.",
)
inp = make_float_array(
inp,
f"Input parameter `{sig_name}` must contain only float compatible entries.\n",
)
check_array_shape(
inp,
dims=dims,
shape_m1=shape_m1,
msg=(
f"Input parameter `{sig_name}` must be {sig_type}.\n"
f"Instead received array_like with shape {inp.shape}."
),
)
if reshape:
return np.reshape(inp, (-1, 3))
if forbid_negative0:
if np.any(inp <= 0):
raise MagpylibBadUserInput(
f"Input parameter `{sig_name}` cannot have values <= 0."
)
return inp
| 8,592 |
def get_proyecto_from_short_url(short_url):
"""
:param short_url:
:return: item for Proyecto
"""
item = Proyecto.objects.get(short_url=short_url)
if item.iniciativas_agrupadas is not None and \
item.iniciativas_agrupadas != '' and '{' in \
item.iniciativas_agrupadas:
iniciativas = item.iniciativas_agrupadas.replace("{", "")
iniciativas = iniciativas.replace("}", "")
item.iniciativas_agrupadas = iniciativas.split(",")
item.congresistas_with_links = hiperlink_congre(item.congresistas)
item.fecha_presentacion = convert_string_to_time(item.fecha_presentacion)
item.fecha_presentacion_human = arrow.get(item.fecha_presentacion).format('DD MMMM, YYYY', locale='es_es')
item.numero_congresistas = len(item.congresistas.split(";"))
return item
| 8,593 |
def select_x(data, order=None):
"""
Helper function that does a best effort of selecting an automatic x axis.
Returns None if it cannot find x axis.
"""
if data is None:
return None
if len(data) < 1:
return None
if order is None:
order = ['T', 'O', 'N', 'Q']
else:
_validate_custom_order(order)
d = _classify_data_by_type(data, order)
chosen_x = None
for typ in order:
if len(d[typ]) >= 1:
chosen_x = d[typ][0]
break
return chosen_x
| 8,594 |
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {"state": 0, "child": 1, "all": 2}
if not vm_info:
return DEFAULT_CLONE_MODE
if "clonemode" not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info["clonemode"] in mode_map:
return mode_map[vm_info["clonemode"]]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(
",".join(mode_map.keys())
)
)
| 8,595 |
def update_dashboard(dashboard_slug):
"""Update Dashboard
Update an existing Dashboard
---
tags:
- "Dashboards"
parameters:
- name: dashboard_slug
in: path
type: string
required: true
- name: name
in: body
schema:
type: object
required:
- name
properties:
name:
type: string
description: new name for dashboard
responses:
200:
description: Success
schema:
type: object
properties:
message:
type: string
dashboard:
$ref: '#/definitions/Dashboard'
400:
$ref: '#/responses/Error'
"""
dashboard = Dashboard.query.filter_by(
slug=dashboard_slug, owner=current_user
).first()
name = request.json.get("name", None)
if not name:
return jsonify(error="Name is required."), 400
if Dashboard.query.filter_by(slug=slugify(name), owner=current_user).first():
return jsonify(error="A dashboard with that name already exists!"), 400
if dashboard:
dashboard.set_name(name)
db.session.commit()
return jsonify(
message="Dashboard updated successfully!", dashboard=dashboard.to_dict()
)
else:
return jsonify(error="Dashboard doesn't exist!"), 400
| 8,596 |
def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995,
target=100.0, model='checkpoint.pth'):
"""Deep Q-Learning.
Params
======
n_episodes (int): maximum number of training episodes
max_t (int): maximum number of timesteps per episode
eps_start (float): starting value of epsilon, for epsilon-greedy action selection
eps_end (float): minimum value of epsilon
eps_decay (float): multiplicative factor (per episode) for decreasing epsilon
target (float): desired minimal average per 100 episodes
model (str): path to save model
"""
scores = [] # list containing scores from each episode
scores_window = deque(maxlen=100) # last 100 scores
eps = eps_start # initialize epsilon
for i_episode in range(1, n_episodes+1):
env_info = env.reset(train_mode=True)[brain_name] # reset the environment
state = env_info.vector_observations[0]
score = 0
for t in range(max_t):
action = agent.act(state, eps)
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
agent.step(state, action, reward, next_state, done)
state = next_state
score += reward
if done:
break
scores_window.append(score) # save most recent score
scores.append(score) # save most recent score
eps = max(eps_end, eps_decay*eps) # decrease epsilon
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
if i_episode % 100 == 0:
print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))
if np.mean(scores_window) >= target:
print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window)))
torch.save(agent.qnetwork_local.state_dict(), model)
break
return scores
| 8,597 |
def latLon2XY(xr, yr, lat, lon, ieast=1, azimuth=0):
"""
Calculate the cartesian distance between consecutive lat,lon
points. Will bomb at North and South Poles. Assumes geographical
coordinates and azimuth in decimal degrees, local Cartesian
coordinates in km.
:param xr: Reference longitude, normally 0.
:param yr: Reference latitude, normally 0.
:param lat: Array of latitudes.
:param lon: Array of longitudes.
:param int ieast: 1 if longitude increases toward the East
(normal case), -1 if longitude increases
toward the West.
:param int azimuth: local coordinate system constructed with
origin at latr,lonr, X axis ('North') in
direction of azimuth, and Y axis such that X x
Y = Z(down) when going from (lat,lon) to (x,y)
scalar or array.
:returns: Array of northward and eastward distances between
consecutive points. use :func:`xy2r` to convert to a
distance between consecutive points.
"""
#if len(lat) != len(lon):
# raise ArrayMismatch, "Input array sizes do not match"
radius = 6367.0 # Earth radius (km)
lat = np.radians(lat)
lon = np.radians(lon)
# Is azimuth fixed or variable?
if np.size(azimuth) == 1:
angle = np.radians(azimuth)*np.ones(lat.size - 1)
else:
angle = np.radians(azimuth)
cosazi = np.cos(angle)
sinazi = np.sin(angle)
xntru = xr + radius * (np.diff(lat))
yetru = yr + ieast * radius * (np.diff(lon)) * np.cos(lat[1:])
xn = xntru * cosazi + yetru * sinazi
ye = -xntru * sinazi + yetru * cosazi
return xn, ye
| 8,598 |
def create_pipeline_opts(args):
"""Create standard Pipeline Options for Beam"""
options = pipeline_options.PipelineOptions()
options.view_as(pipeline_options.StandardOptions).runner = args.runner
google_cloud_options = options.view_as(pipeline_options.GoogleCloudOptions)
google_cloud_options.project = args.project
if args.runner == 'DataflowRunner':
google_cloud_options.job_name = args.job_name
google_cloud_options.temp_location = '{}/temp'.format(args.storage_bucket)
google_cloud_options.staging_location = '{}/staging'.format(args.storage_bucket)
worker_options = options.view_as(pipeline_options.WorkerOptions)
worker_options.num_workers = args.num_workers
worker_options.max_num_workers = args.max_num_workers
worker_options.machine_type = args.machine_type
setup_options = options.view_as(pipeline_options.SetupOptions)
setup_options.setup_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setup.py')
return options
| 8,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.