content
stringlengths 35
762k
| sha1
stringlengths 40
40
| id
int64 0
3.66M
|
---|---|---|
import gzip
def read_consanguineous_samples(path, cutoff=0.05):
"""
Read inbreeding coefficients from a TSV file at the specified path.
Second column is sample id, 6th column is F coefficient. From PLINK:
FID, IID, O(HOM), E(HOM), N(NM), F
Additional columns may be present but will be ignored.
"""
consanguineous_samples = {}
myopen = gzip.open if path.endswith('.gz') else open
with myopen(path) as inf:
_ = inf.readline()
for line in inf:
cols = line.strip().split()
if float(cols[5]) > cutoff:
consanguineous_samples[cols[1]] = True
return consanguineous_samples
|
be3515e6704966ae927bfaff2594be9191063889
| 34,340 |
from re import T
def component(graph: Graph[T], node: T) -> Graph[T]:
"""Returns the connected component that contains the given vertex, as a new Graph object.
A vertex with no incident edges is itself a component.
A graph that is itself connected has exactly one component, consisting of the whole graph.
"""
res: Graph = Graph()
_component(graph, node, res, visited=set())
return res
|
6d1d23b28e35f291e79369f39e66d7444f0395ba
| 34,341 |
import six
from datetime import datetime
import typing
def _deserialize(data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if klass in six.integer_types or klass in (float, str, bool):
return _deserialize_primitive(data, klass)
if klass == object:
return _deserialize_object(data)
if klass == date:
return deserialize_date(data)
if klass == datetime:
return deserialize_datetime(data)
if isinstance(klass, typing.GenericMeta): # pylint: disable=no-member
if klass.__extra__ == list:
return _deserialize_list(data, klass.__args__[0])
if klass.__extra__ == dict:
return _deserialize_dict(data, klass.__args__[1])
else:
return deserialize_model(data, klass)
# I don't think we are supposed to be able to get here, but the
# above conditionals potentially make it possible, so return None
# explicitly here instead of falling out.
return None
|
7f008dc9edcdb433fe6561f5ad30695e8103c347
| 34,342 |
def smooth(data, fwhm, mask = 0):
""" smooth
Parameters
---------------------
data an object of class field
fwhm
mask a numpy.nd array,
with the same dimensions as the data
Returns
---------------------
An object of class field with
Examples
---------------------
# 1D example
f = pr.wfield(50,10)
smooth_f = pr.smooth(f, 8)
plt.plot(smooth_f.field)
# 2D example
f = pr.wfield((50,50), 10)
smooth_f = pr.smooth(f, 8)
plt.imshow(smooth_f.field[:,:,1])
# 2D example with mask
f = pr.wfield((50,50), 10)
mask = np.zeros((50,50), dtype = 'bool')
mask[15:35,15:35] = 1
smooth_f = pr.smooth(f, 8, mask)
plt.imshow(smooth_f.field[:,:,1])
"""
# Convert a numpy array to a field if necessary
if isinstance(data, np.ndarray):
data = pr.make_field(data)
# If a non-zero mask is supplied used this instead of the mask associated with data
if np.sum(np.ravel(mask)) > 0:
data.mask = mask
# Calculate the standard deviation from the fwhm
sigma = pr.fwhm2sigma(fwhm)
for i in np.arange(data.fibersize):
data.field[...,i] = gaussian_filter(data.field[...,i] * data.mask, sigma = sigma) * data.mask
return data
|
feba63fe44605c4c59ca9b83794daad046ac3244
| 34,343 |
def get_xy_coords(xda):
"""Return the dimension name for x and y coordinates
e.g. XC or XG
Parameters
----------
xda : xarray DataArray
with all grid information
Returns
-------
x,y : str
with e.g. 'XC' or 'YC'
"""
x = 'XC' if 'XC' in xda.coords else 'XG'
y = 'YC' if 'YC' in xda.coords else 'YG'
return x,y
|
6aca5de1eda17df617027c742a06f97cf77af1d5
| 34,344 |
def remote_docker(client_ip, docker_host, *args):
"""
Run ``docker`` on ``client_ip``.
:param bytes docker_host: The DOCKER_HOST environment variable to set
before running ``docker``.
:param args: Other command line arguments to supply to ``docker``.
:returns: A ``Deferred`` when the command has completed or failed.
"""
return remote_command(
client_ip,
('DOCKER_TLS_VERIFY=1', 'DOCKER_HOST={}'.format(docker_host),
'docker') + args,
)
|
cbbff3fdd1460c61dbbc48b4833bede2a60312aa
| 34,347 |
def aggregate_f(loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore):
"""
Compute aggregate metric for xView3 scoring
Args:
loc_fscore (float): F1 score for overall maritime object detection
length_acc (float): Aggregate percent error for vessel length estimation
vessel_fscore (float): F1 score for vessel vs. non-vessel task
fishing_fscore (float): F1 score for fishing vessel vs. non-fishing vessel task
loc_fscore_shore (float): F1 score for close-to-shore maritime object detection
Returns:
aggregate (float): aggregate metric for xView3 scoring
"""
# Note: should be between zero and one, and score should be heavily weighted on
# overall maritime object detection!
aggregate = loc_fscore * (1 + length_acc + vessel_fscore + fishing_fscore + loc_fscore_shore) / 5
return aggregate
|
c3120882e50710d6874def60ad85e7a8be47c5d7
| 34,349 |
def index(request):
"""
Index view: shows a form with a list of ticket that one can buy
"""
ticket_types = TicketType.objects.all()
form = TicketsForm(ticket_types,[], request.POST)
if form.is_valid():
data = form.cleaned_data
p = TicketPurchase()
print data
if data['coupon']:
coupon = Coupon.objects.get(data['coupon'])
p.coupon = coupon
p.additional_contribution = data['donation'] or 0
tickets = []
for type_ in ticket_types:
key = 'quantity:%d'%type_.id
if key in data:
for i in range(data[key]):
tickets.append(Ticket(ticket_type=type_))
request.session['purchase'] = p
request.session['tickets'] = tickets
return redirect('/register/')
return render_to_response(
"index.html",
dict(form=form),
context_instance=RequestContext(request))
|
997ed750187586077d5ca24d17326d5f5510382e
| 34,350 |
from typing import Union
def _on_vertex(
easting: Union[int, float], northing: Union[int, float], resolution: int
) -> bool:
"""Test if point lies on vertex."""
return (
True
if (int(easting) % resolution == 0) and (int(northing) % resolution == 0)
else False
)
|
06902474da9bfc49e209ada65d160c0fa7f28cbf
| 34,351 |
def add_jitter(df, jitter):
"""
Adds jitter to a data set based on a random normal
distribution.
Requirements: numpy, pandas
"""
return abs(df + np.random.normal(df, jitter, size=len(df)))
|
dc03d1506db3e21908a02a370122b8735167606b
| 34,352 |
import torch
import itertools
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (query, positive, negatives).
Args:
data: list of tuple (query, positive, negatives).
- query: torch tensor of shape (3, h, w).
- positive: torch tensor of shape (3, h, w).
- negative: torch tensor of shape (n, 3, h, w).
Returns:
query: torch tensor of shape (batch_size, 3, h, w).
positive: torch tensor of shape (batch_size, 3, h, w).
negatives: torch tensor of shape (batch_size, n, 3, h, w).
"""
batch = list(filter(lambda x: x is not None, batch))
if len(batch) == 0:
return None, None, None, None, None
query, positive, negatives, indices = zip(*batch)
query = data.dataloader.default_collate(query)
positive = data.dataloader.default_collate(positive)
neg_counts = data.dataloader.default_collate([x.shape[0] for x in negatives])
negatives = torch.cat(negatives, 0)
indices = list(itertools.chain(*indices))
return query, positive, negatives, neg_counts, indices
|
d6e4985b7b0e248f05e78684a2a09136da865799
| 34,353 |
def complete_graph(number_of_vertices, name="Complet graph", directed=False):
"""
Construction of a complete graph.
The number of edges is exactly n*(n-1)/2 (where n is the number of vertices)
:param number_of_vertices:
:param name:
:param directed: False for undirected graph
:return: the complete graph
"""
# The comprehension list is used to give every possible case of edge.
list_of_vertices = vertices_generation(number_of_vertices)
constructed_graph = Graph({s: {} for s in list_of_vertices}, name)
[constructed_graph.add_edge(s, t, directed)
for s in range(1, number_of_vertices + 1)
for t in range(s, number_of_vertices + 1)
if s != t]
return constructed_graph
|
e603583abcc6e1de10f057965bf587cde1eebcc0
| 34,354 |
def obv(df, price, volume, obv):
"""
The On Balance Volume (OBV) is a cumulative total of the up and down volume.
When the close is higher than the previous close, the volume is added to
the running total, and when the close is lower than the previous close,
the volume is subtracted from the running total.
Parameters:
df (pd.DataFrame): DataFrame which contain the asset price.
price (string): the column name of the price of the asset.
volume (string): the column name of the volume of the asset.
obv (string): the column name for the on balance volume values.
Returns:
df (pd.DataFrame): Dataframe with obv of the asset calculated.
"""
df["diff"] = df[price].diff()
df = df.fillna(1)
df.loc[df["diff"] > 0, obv + "_sign"] = 1
df.loc[df["diff"] < 0, obv + "_sign"] = -1
df.loc[df["diff"] == 0, obv + "_sign"] = 0
volume_sign = df[volume] * df[obv + "_sign"]
df[obv] = volume_sign.cumsum()
df.drop(["diff", obv + "_sign"], axis=1, inplace=True)
return df
|
19f4c456ed501523d2b349e2766d482bd1fef13b
| 34,355 |
def is_data(line):
"""
Function utilized by itertool's groupby method in determining
the delimiter between our blocks of data.
"""
return True if line.strip() else False
|
da3db970c5c5a3169446513cb4148ffedf598095
| 34,356 |
def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = licenses_api.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils.checked_api_call(
licenses_api,
'update',
id=int(license_id),
body=updated_license)
if response:
return utils.format_json(response.content)
|
c500224309e71d0e14a641980deaa75714a9c117
| 34,357 |
def _browse_device(device_id: MediaId, device: Device) -> BrowseMediaSource:
"""Return details for the specified device."""
device_info = NestDeviceInfo(device)
return BrowseMediaSource(
domain=DOMAIN,
identifier=device_id.identifier,
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type=MEDIA_TYPE_VIDEO,
children_media_class=MEDIA_CLASS_VIDEO,
title=DEVICE_TITLE_FORMAT.format(device_name=device_info.device_name),
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
)
|
76f36c2cf5eedad06f527d78aa45fac1d6ea6b11
| 34,358 |
def get_organization_suggestions(config, donl_type):
"""
Get organization suggestions for a given type
:param dict[str, Any] config: The configuration to use for selecting DONL
organizations
:param str donl_type: The DONL type to get suggestions for
:rtype: list of dict[str, any]
:return: The list of organization suggestions
"""
return get_uri_suggestions(config, 'authority', 'organization', donl_type)
|
6d306c49bc7671707479b5327e69a74320ebf3a6
| 34,359 |
def make_func_entry(func, name=None, description=None, params=None):
"""
Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is set then it's value is
used as the description instead of extracting it from func.
params - a parameter list that overrides using func.params.
"""
if params is None:
params = func.params
params = [prm.declname for prm in params]
if params:
sig = "Params: (%s)" % ", ".join(params)
else:
sig = "Params: (NONE)"
templ = "{description}\n\n" + sig
return make_entry(func, name=name, templ=utoascii(templ), description=description)
|
d5fb2067d0c69bc5cffc47376f3f91573c5cc1d4
| 34,360 |
import copy
def instance_update(context, instance_uuid, values, session=None):
"""Updates an existing VM instance in the Database"""
values = copy.deepcopy(values)
power_specs = values.pop('power_specs', None)
#Merge in the existing MetaData if they asked for Partial Updates
_instance_merge_metadata(context, instance_uuid, values)
#Delegate to the OpenStack method to actually update the Instance
inst_ref = db_api.instance_update(context, instance_uuid, values)
#If there were PowerSpecs provided, then insert them now
if power_specs is not None and inst_ref is not None:
instance_power_specs_update(
context, instance_uuid, power_specs, session)
#Query the Instance again to make sure the PowerSpecs is populated
inst_ref = db_api.instance_get_by_uuid(context, inst_ref['uuid'])
return inst_ref
|
80296ff02a320bdf3192802bbde50d8adc6778c5
| 34,361 |
from bs4 import BeautifulSoup
def xkcdt():
"""
Return the title of the
most recent xkcd, taken from
the wesite's source code.
"""
page=BeautifulSoup(urllib2.urlopen('https://xkcd.com'),'lxml')
return page.title.string
|
55f90a86d8e0410743a968bf1c3351f23709b728
| 34,363 |
import warnings
def log_cpm_hvg(adata: ad.AnnData, n_genes: int = 1000) -> ad.AnnData:
"""Normalize logCPM HVG
Normalize data to log counts per million and select n_genes highly
variable genes
"""
adata = log_cpm(adata)
if adata.n_vars < n_genes:
warnings.warn(
f"Less than {n_genes} genes, setting 'n_genes' to {int(adata.n_vars * 0.5)}"
)
n_genes = int(adata.n_vars * 0.5)
sc.pp.highly_variable_genes(adata, n_top_genes=n_genes, flavor="cell_ranger")
adata = adata[:, adata.var["highly_variable"]].copy()
return adata
|
ee9cda4caedde03d81fbc361a5c70d90c7bfc1f7
| 34,364 |
def c_string_arguments(encoding='UTF-8', *strings):
""" Convenience function intended to be passed to in_format which allows
easy arguments which are lists of null-terminated strings.
"""
payload = b""
# Add each string, followed by a null character.
for string in strings:
payload += string.encode(encoding)
payload += b"\0"
return payload
|
5c93afae01d199f31a27f658e133024c8fb9f92f
| 34,365 |
async def create_mirror(request):
"""
Create a debian aptly mirror.
---
description: Create a debian aptly mirror.
tags:
- Mirrors
consumes:
- application/x-www-form-urlencoded
parameters:
- name: name
in: query
required: true
type: string
description: name of the mirror
- name: url
in: query
required: true
type: string
description: http://host of source
- name: distribution
in: query
required: true
type: string
description: trusty, wheezy, jessie, etc.
- name: components
in: query
required: false
type: array
description: components to be mirrored
default: main
- name: keys
in: query
required: false
type: array
uniqueItems: true
collectionFormat: multi
allowEmptyValue: true
minItems: 0
items:
type: string
description: repository keys
- name: keyserver
in: query
required: false
type: string
description: host name where the keys are
- name: is_basemirror
in: query
required: false
type: boolean
description: use this mirror for chroot
- name: architectures
in: query
required: false
type: array
description: i386,amd64,arm64,armhf,...
- name: version
in: query
required: false
type: string
- name: armored_key_url
in: query
required: false
type: string
- name: basemirror_id
in: query
required: false
type: string
- name: download_sources
in: query
required: false
type: boolean
- name: download_installer
in: query
required: false
type: boolean
produces:
- text/json
responses:
"200":
description: successful
"400":
description: mirror creation failed.
"412":
description: key error.
"409":
description: mirror already exists.
"500":
description: internal server error.
"503":
description: aptly not available.
"501":
description: database error occurred.
"""
params = await request.json()
mirror = params.get("name")
url = params.get("url")
mirror_distribution = params.get("distribution")
components = params.get("components", [])
keys = params.get("keys", [])
keyserver = params.get("keyserver")
is_basemirror = params.get("is_basemirror")
architectures = params.get("architectures", [])
version = params.get("version")
key_url = params.get("armored_key_url")
basemirror_id = params.get("basemirror_id")
download_sources = params.get("download_sources")
download_installer = params.get("download_installer")
if not components:
components = ["main"]
if not isinstance(is_basemirror, bool):
return ErrorResponse("is_basemirror not a bool")
args = {
"create_mirror": [
mirror,
url,
mirror_distribution,
components,
keys,
keyserver,
is_basemirror,
architectures,
version,
key_url,
basemirror_id,
download_sources,
download_installer,
False,
"strict"
]
}
await enqueue_aptly(args)
return OKResponse("Mirror {} successfully created.".format(mirror))
|
b6e60120580f25a967f19ec5ec7fff3fd0fa9478
| 34,366 |
def anneal(c_max, step, iteration_threshold):
"""Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599).
Args:
c_max: Maximum capacity.
step: Current step.
iteration_threshold: How many iterations to reach c_max.
Returns:
Capacity annealed linearly until c_max.
"""
return min(c_max * 1.,
c_max * 1. * (step) / iteration_threshold)
|
ca6cbb5fe109e5d6b36870b398604ee79042827f
| 34,367 |
import json
def update_timer_interval(acq_state, chart_data_json_str, chart_info_json_str,
active_channels, samples_to_display):
"""
A callback function to update the timer interval. The timer is temporarily
disabled while processing data by setting the interval to 1 day and then
re-enabled when the data read has been plotted. The interval value when
enabled is calculated based on the data throughput necessary with a minimum
of 500 ms and maximum of 4 seconds.
Args:
acq_state (str): The application state of "idle", "configured",
"running" or "error" - triggers the callback.
chart_data_json_str (str): A string representation of a JSON object
containing the current chart data - triggers the callback.
chart_info_json_str (str): A string representation of a JSON object
containing the current chart status - triggers the callback.
active_channels ([int]): A list of integers corresponding to the user
selected active channel checkboxes.
samples_to_display (float): The number of samples to be displayed.
Returns:
"""
chart_data = json.loads(chart_data_json_str)
chart_info = json.loads(chart_info_json_str)
num_channels = int(len(active_channels))
refresh_rate = 1000*60*60*24 # 1 day
if acq_state == 'running':
# Activate the timer when the sample count displayed to the chart
# matches the sample count of data read from the HAT device.
if 0 < chart_info['sample_count'] == chart_data['sample_count']:
# Determine the refresh rate based on the amount of data being
# displayed.
refresh_rate = int(num_channels * samples_to_display / 2)
if refresh_rate < 500:
refresh_rate = 500 # Minimum of 500 ms
return refresh_rate
|
1bc695ab2e5d63d4734d27417efc3d17a5e3a471
| 34,368 |
def constant_change_luminance(img):
"""
luminance noise added to image
:param img: image: numpy input image
:return: blurred image
"""
# constant [-25, 25]
constant = np.random.randint(-25, 25, size=(img.shape[0], img.shape[1], 1))
new_img = np.clip(img.astype(np.float32) - constant, 0.0, 255.0).astype(np.uint8)
return new_img
|
e5e11a49db0c2ac051f7e8fb881f724ed94a1ad6
| 34,369 |
def rectify(x):
"""Rectify activation function :math:`\\varphi(x) = \\max(0, x)`
Parameters
----------
x : float32
The activation (the summed, weighted input of a neuron).
Returns
-------
float32
The output of the rectify function applied to the activation.
"""
# The following is faster than T.maximum(0, x),
# and it works with nonsymbolic inputs as well.
# Thanks to @SnipyHollow for pointing this out. Also see:
# https://github.com/Lasagne/Lasagne/pull/163#issuecomment-81765117
return 0.5 * (x + abs(x))
|
f781c4a382d211fbcadfe599c470523d3a59c2f1
| 34,370 |
def login_form():
"""Show login form."""
return render_template("login_form.html", loggingin=True)
|
9f70323f1936f9b68200e3e1c75dfd52c262bc44
| 34,371 |
from typing import Union
from typing import Sequence
def truncate_batches(*xl: Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]) \
-> Sequence[Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]]:
"""
Truncate a list of batched items so that all items have the batch size of the input with the smallest batch size.
Inputs can be of various types and would usually correspond to a single time step.
Assume that the batch elements with index 0 correspond across the inputs, so that batch elements will be truncated
from the top, i.e. starting with the highest-indexed batch elements.
Masks are not considered even if attached to a input of :class:`Batch` type.
Args:
*xl: batched timesteps of various types
Returns:
Copies of the inputs, truncated to consistent batch size.
"""
batch_sizes = []
for x in xl:
if isinstance(x, dy.Expression) or isinstance(x, expression_seqs.ExpressionSequence):
batch_sizes.append(x.dim()[1])
elif isinstance(x, Batch):
batch_sizes.append(len(x))
elif isinstance(x, Mask):
batch_sizes.append(x.batch_size())
elif isinstance(x, recurrent.UniLSTMState):
batch_sizes.append(x.output().dim()[1])
else:
raise ValueError(f"unsupported type {type(x)}")
assert batch_sizes[-1] > 0
ret = []
for i, x in enumerate(xl):
if batch_sizes[i] > min(batch_sizes):
if isinstance(x, dy.Expression) or isinstance(x, expression_seqs.ExpressionSequence):
ret.append(x[tuple([slice(None)]*len(x.dim()[0]) + [slice(min(batch_sizes))])])
elif isinstance(x, Batch):
ret.append(mark_as_batch(x[:min(batch_sizes)]))
elif isinstance(x, Mask):
ret.append(Mask(x.np_arr[:min(batch_sizes)]))
elif isinstance(x, recurrent.UniLSTMState):
ret.append(x[:,:min(batch_sizes)])
else:
raise ValueError(f"unsupported type {type(x)}")
else:
ret.append(x)
return ret
|
a39a4e8fec318b8e27ce6df1029051c07e058180
| 34,373 |
def get_loss_f(**kwargs_parse):
"""Return the loss function given the argparse arguments."""
return Loss(lamL1attr=kwargs_parse["lamL1attr"])
|
0389a9ca1799d7f98965caed7c0474543ed3c24a
| 34,374 |
def input_reading_mod(input_dir, input):
"""This helper convert input"""
with open('%s/%s' %(input_dir, input), 'r') as input_fid:
pred = input_fid.readlines()
det = [x.strip('\n') for x in pred]
return det
|
34fd8e5fe53d809ee1cc870c031bca8691756a63
| 34,376 |
async def connect(config, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
if config.identifier is None:
raise exceptions.DeviceIdMissingError("no device identifier")
service = config.main_service(protocol=protocol)
supported_implementations = {
const.PROTOCOL_DMAP: DmapAppleTV,
const.PROTOCOL_MRP: MrpAppleTV,
}
implementation = supported_implementations.get(service.protocol, None)
if not implementation:
raise exceptions.UnsupportedProtocolError()
# If no session is given, create a default one
if session is None:
session = await net.create_session(loop=loop)
# AirPlay service is the same for both DMAP and MRP
airplay = AirPlayAPI(config, loop)
atv = implementation(loop, session, config, airplay)
await atv.connect()
return atv
|
1f6357737ce93a69e0b75093a5da8c72aebbb660
| 34,377 |
def _is_none(s: str) -> bool:
"""Check if a value is a text None."""
if s == 'None':
return True
return False
|
b7a6118b2c04c965d808911405d23a168f0fbff3
| 34,378 |
def get_C_and_Ic(Cin_est, Icin_est, f01, f02on2):
"""Get the capacitance and critical current for a transmon of a certain
frequency and anharmonicity.
Args:
Cin_est (float): Initial guess for capacitance (in fF)
Icin_est (float): Initial guess for critical current (in nA)
f01 (float): Transmon frequency (in GHz)
f02on2 (float): 02/2 frequency (in GHz)
Returns:
tuple: [C,Ic] from levels_vs_ng_real_units that gives the
specified frequency and anharmonicity
"""
xrr = opt.minimize(lambda x: cos_to_mega_and_delta(x[0], x[1], f01, f02on2),
[Cin_est, Icin_est],
tol=1e-4,
options={
'maxiter': 100,
'disp': True
})
return xrr.x
|
ad7597b1e525a5d5818d6f79058cbe1213d38e2a
| 34,379 |
def read_positionfixes_postgis(sql, con, geom_col="geom", **kwargs):
"""Reads positionfixes from a PostGIS database.
Parameters
----------
sql : str
SQL query e.g. "SELECT * FROM positionfixes"
con : str, sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
Connection string or active connection to PostGIS database.
geom_col : str, default 'geom'
The geometry column of the table.
**kwargs
Further keyword arguments as available in GeoPanda's GeoDataFrame.from_postgis().
Returns
-------
GeoDataFrame
A GeoDataFrame containing the positionfixes.
Examples
--------
>>> pfs = ti.io.read_postifionfixes_postgis("SELECT * FROM postionfixes", con, geom_col="geom")
"""
pfs = gpd.GeoDataFrame.from_postgis(sql, con, geom_col, **kwargs)
return ti.io.read_positionfixes_gpd(pfs, geom_col=geom_col)
|
f55f6934f675c76a99e544243b0f1cf779820e44
| 34,380 |
import logging
def get_model(letters, max_length):
"""Create a LSTM model."""
logging.info("Create model")
input_dim = len(letters)
logging.info("input_dim=%i", input_dim)
model = Sequential()
model.add(LSTM(8,
return_sequences=True,
input_shape=(max_length, len(letters))))
model.add(Dropout(0.2))
model.add(LSTM(8, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
return model
|
0506c1f892ca2518b95c9edfc4deedfd8ebd4174
| 34,381 |
def _group_auto_update_helper(auto_update):
"""Helper that prepares the given group auto update for JSON
serialization.
:param GroupAutoUpdate auto_update: the auto update to serialize
:return: dictionary suitable for JSON serialization
:rtype: dict
"""
fields = {
'to': auto_update.recipient
}
if auto_update.add_word_pair[0]:
fields.setdefault('add', {})['first_word'] = \
auto_update.add_word_pair[0]
if auto_update.add_word_pair[1]:
fields.setdefault('add', {})['second_word'] = \
auto_update.add_word_pair[1]
if auto_update.remove_word_pair[0]:
fields.setdefault('remove', {})['first_word'] = \
auto_update.remove_word_pair[0]
if auto_update.remove_word_pair[1]:
fields.setdefault('remove', {})['second_word'] = \
auto_update.remove_word_pair[1]
return fields
|
fd95526cbea8d4888b7e581ab5eec5260f557517
| 34,383 |
import pyemd
def emd(hist1, hist2, cost_matrix='sift'):
"""
earth mover's distance by robjects(lpSovle::lp.transport)
require: lpsolve55-5.5.0.9.win32-py2.7.exe
CommandLine:
python -m vtool.distance --test-emd
Example:
>>> # DISABLE_DOCTEST
>>> from vtool.distance import * # NOQA
>>> hist1, hist2 = testdata_hist()
>>> emd_dists = emd(hist1, hist2)
>>> result = ub.repr2(emd_dists, precision=2)
>>> #xdoctest: +IGNORE_WHITESPACE
>>> print(result)
np.array([ 2063.99, 2078.02, 2109.03, 2011.99, 2130.99, 2089.01,
2030.99, 2294.98, 2026.02, 2426.01])
References:
pip install pyemd
https://github.com/andreasjansson/python-emd
http://www.cs.huji.ac.il/~werman/Papers/ECCV2008.pdf
http://stackoverflow.com/questions/15706339/compute-emd-2umpy-arrays-using-opencv
http://www.cs.huji.ac.il/~ofirpele/FastEMD/code/
http://www.cs.huji.ac.il/~ofirpele/publications/ECCV2008.pdf
"""
if cost_matrix == 'sift':
# Build cost matrix where bin-to-bin cost is 0,
# neighbor cost is 1, and other cost is 2
N = 8
cost_matrix = np.full((128, 128), 2)
i, j = np.meshgrid(np.arange(128), np.arange(128))
cost_matrix[i == j] = 0
absdiff = np.abs(i - j)
is_neighbor = np.abs(np.minimum(absdiff, N - absdiff)) == 1
cost_matrix[is_neighbor] = 1.0
# print(cost_matrix[0:16, 0:16])
if len(hist1.shape) == 2:
dist = np.array(
[
pyemd.emd(hist1_.astype(np.float), hist2_.astype(np.float), cost_matrix)
for hist1_, hist2_ in zip(hist1, hist2)
]
)
else:
dist = pyemd.emd(hist1.astype(np.float), hist2.astype(np.float), cost_matrix)
return dist
|
21a364ef673190ce2a25175154bd275ebc764506
| 34,385 |
def equal_angle_stereographic_projection_conv_YZ_plane(x,y,z):
"""Function to take 3D grid coords for a cartesian coord system and convert to 2D equal area projection."""
Y = y/(1+x)
Z = z/(1+x)
return Y,Z
|
121b24f20ef0ff7f0655a4b39c7ede70c632ef2a
| 34,386 |
def download_past_trees(test: bool, number: int):
"""
Download a number of past trees
:param number: number of trees to download from the latest
"""
trees = []
key = "badger-tree.json"
bucket = env_config.bucket
response = s3.list_object_versions(Prefix=key, Bucket=bucket)
versions = response["Versions"][:number]
for version in versions:
console.log(version["Key"], version["VersionId"])
s3_client_obj = s3.get_object(
Bucket=bucket, Key=version["Key"], VersionId=version["VersionId"]
)
trees.append(s3_client_obj["Body"].read())
return trees
|
810ebc9ca714e4b9377bb7dd5d0cba0e9dd4089f
| 34,387 |
import re
def read_init_values(srclines, init_names=None):
""" srclines - an ODE-file content in the list of strings,
if init_names is None all parameters will be read
init_names - the list of parameters names
return:
the dict of parameters, where keys=pars_names, values are parsed from srclines
"""
vars_list=[]
i_init_lines = np.nonzero([re.search('^ *(init) (.+)$', line, flags=re.IGNORECASE) is not None for line in srclines])[0]
for i in i_init_lines:
vars_list+=re.findall('([a-z0-9_]+) *= *([0-9\.e\-\+]+)', srclines[i].lower(), flags=re.IGNORECASE)
d = dict(vars_list)
if init_names is None:
return d
else:
return {pn:d[pn] for pn in init_names}
|
e793399c4d258134e3767c067b1754bcd820c430
| 34,388 |
def getCategorySentiments(termSentiData,trainLexicon,finalDF):
"""
Module to extract category-wise sentiment scores and
generate final dataframe with predicted and true sentiment
Args:
termSentiData: dictionary of aspect terms and its sentiment
trainLexicon: Lexicon of defining terms under each category
finalDF: data frame with predicted and true category labels
Returns:
finaDF: data frame with predicted and true category sentiment labels
"""
categorySentiScore={}
for key,values in termSentiData.iteritems():
if len(values)>0:
for k,v in values.iteritems():
for entKey,entVal in trainLexicon.iteritems():
if k in entVal:
if entKey in categorySentiScore:
categorySentiScore[entKey] += v
else:
categorySentiScore[entKey] = v
predictedCategory = finalDF['predictedCategory']
predictedCategorySentiment=[]
for category in predictedCategory:
if category in categorySentiScore.keys():
if categorySentiScore[category] > 0:
predictedCategorySentiment.append('pos')
elif categorySentiScore[category] == 0:
predictedCategorySentiment.append('neu')
elif categorySentiScore[category] < 0:
predictedCategorySentiment.append('neg')
else:
predictedCategorySentiment.append('neu')
finalDF['predictedCategorySentiment'] = predictedCategorySentiment
return finalDF
|
d8efc2ea0d1ffb18d3949f104c21ce6eae923a2e
| 34,389 |
def get_test_pipeline():
"""Return an arbitrary pipeline definition."""
return {
'sg1': [
'step1',
'step2',
{'step3key1': 'values3k1', 'step3key2': 'values3k2'},
'step4'
],
'sg2': False,
'sg3': 77,
'sg4': None
}
|
036cfdca7324be6940e1ed095292b0ac494ab771
| 34,390 |
def get_package_type(name):
"""
Returns the package type. Available package types are defined in PackageType.
Only ASR9K supports Service Packs concept
Example: asr9k-px-4.3.2.sp-1.0.0 or asr9k-px-4.3.2.k9-sp-1.0.0
"""
if name.find(SMU_INDICATOR) != -1:
return PackageType.SMU
elif name.find(SP_INDICATOR) != -1:
return PackageType.SERVICE_PACK
elif name.find(TAR_INDICATOR) != -1:
return PackageType.SOFTWARE
else:
return PackageType.PACKAGE
|
89543d14c83f666c102dd11f3e093552b03c84d9
| 34,391 |
def merge(df1, df2, on=None, how="left"):
"""
DESCRIPTION
-----------
Merge two pandas dataframes on a common field name or specified fields in
each frame.
PARAMETERS
----------
df1 : pd.DataFrame
A pandas dataframe instance
df2 : pd.DataFrame
A pandas dataframe instance
on : str, list
A string or list representing the field(s) to join on. If a list is passed,
it is assumed multiple values are passed for separate fields. Otherwise,
it is assumed that a common field name is present between the two dataframes.
how : str
The method of joining the two frames (left, right, outer, inner)
RETURNS
-------
A pandas dataframe instance merged from two provided dataframes
MODIFICATIONS
-------------
Created : 4/29/19
"""
if isinstance(on, list):
return pd.merge(df1, df2, left_on=on[0], right_on=on[1], how=how)
elif isinstance(on, str):
return pd.merge(df1, df2, on=on, how=how)
else:
raise ValueError(f"merge_df function expected a list or string object, got {type(on)}")
|
f297fcc005bdb6425ebb5306eae285c747ab46be
| 34,392 |
def resident_required(a_view):
"""居住者権限を持つユーザのみ実行を許可する
居住者権限を持つユーザとは 1 つ以上の community.Unit と関連づけられたユーザ.
不許可なら 403 Forbidden を返す.
Args:
a_view (func): ビュー関数
"""
def _wrapped_view(request, *args, **kwargs):
if request.user.unit_set.count():
return a_view(request, *args, **kwargs)
else:
return HttpResponseForbidden('resident required')
return login_required(_wrapped_view)
|
db211cb5861bfd1c47d23fc30b20a7ebf3080a4b
| 34,393 |
import logging
def _stdout_logging(level):
"""Setup logging to stdout and return logger's `info` method.
"""
formatter = logging.Formatter(
'%(levelname)s %(asctime)s %(module)s %(funcName)s(): %(message)s',
'%Y-%m-%d %H:%M:%S')
stdout = logging.StreamHandler()
stdout.setLevel(level)
stdout.setFormatter(formatter)
log.setLevel(level)
log.addHandler(stdout)
return log.info
|
a2fff81c0425b35f855c0372607d708f1c2aa3b4
| 34,395 |
def standardize_phone(raw: str) -> str:
"""Make sure it's 10 digits, remove everything else
>>> standardize_phone("(555) 555-1212")
'5555551212'
"""
raw = [x for x in raw if x.isnumeric()]
raw = "".join(raw)
if len(raw) != 10:
raw = None
return raw
|
a0d3afc2ffdaffee9d084ed7f50d49a1e3a023e0
| 34,396 |
async def find(req):
"""
Get a list of all existing group documents.
"""
cursor = req.app["db"].groups.find()
return json_response([virtool.utils.base_processor(d) async for d in cursor])
|
d78fb6d84c18cbcdf07ee6d3699d58bd539e5fb2
| 34,397 |
from typing import Union
from typing import List
from typing import Dict
from typing import Any
def template_readable_response(responses: Union[dict, List[dict], str]) -> Union[str, List[Dict[str, Any]]]:
"""
Creates a readable response for responses that have fields in the form of:
{
'defaultValue': null,
'editable': true,
'key': 'sr_type',
'keyCaption': 'Service Record Type',
'mandatory': false,
'type': 'list',
'value': 2
}
:param responses: The response to turn to human readable
"""
readable_response = []
if isinstance(responses, dict):
responses = [responses]
if isinstance(responses, str):
return responses
for response in responses:
if 'info' in response:
for response_info in response['info']:
response_entry = {}
for key in TEMPLATE_OUTPUTS:
response_entry[key] = response_info[key] if key in response_info else None
readable_response.append(response_entry)
return readable_response
|
56b416aae9e254453855c27910d2e4d20365b6fc
| 34,398 |
def rehtml(content):
"""
does unicode bullshit
:param content:
:return:
"""
doc = UnicodeDammit(content, is_html=True)
parser = ht.HTMLParser(encoding=doc.original_encoding)
root = ht.fromstring(content, parser=parser)
return root
|
157a1659c0b5af469acfddc175eb37376f1914af
| 34,399 |
def center_film(structure):
"""
Centers a film at z=0
Args:
structure: AiiDA structure
returns: AiiDA structure
"""
if structure.pbc != (True, True, False):
raise TypeError('Only film structures having surface normal to z are supported')
sorted_struc = sort_atoms_z_value(structure)
sites = sorted_struc.sites
shift = [0, 0, -(sites[0].position[2]+sites[-1].position[2])/2.0]
return move_atoms_incell(sorted_struc, shift)
|
121a9252e5a0da2e50f4b7fdf95a7c37a1245695
| 34,400 |
def get_stop_response():
""" end the session, user wants to quit the game """
speech_output = STOP_MESSAGE
return response(speech_response(speech_output, True))
|
4843b735859428a4d12337a7b26f42ed40900c2f
| 34,401 |
import re
def __extract_clusters_from_html(html):
"""Parse the clusters of a balancer manager page.
:param html: The raw HTML of the balancer manager page.
:returns: a list of clusters.
"""
clusters = []
for section in re.findall('(<h3>.+?)<hr />', html.replace('\n', '')):
cluster = _parse_cluster(section)
clusters.append(cluster)
return clusters
|
2c5077e264a7bf853886d55c2e9c64b149da40a0
| 34,402 |
from typing import Union
def _value_to_int(value: Union[int, str]) -> int:
"""String value to int."""
try:
return int(value)
except ValueError as error:
raise Exception("The value is not integer")
|
635afb6d75edec8df64b12dad8db7dd408502250
| 34,403 |
import calendar
def era5_temp_anomalies(obs_directory, save_directory, start_range='1999-01-01', end_range='2019-12-31',
save=False, author=None):
"""
Create ERA5 temperature hindcast anomalies.
Args:
obs_directory (str): Directory where files are located.
save_directory (str): Directory where to save files.
start (str): Start of hindcasts. Defaults to '1999-01-01'.
end (str): End of hindcasts. Defaults to '2020-12-31'.
save (boolean): Set to True if want to save climatology as netCDF. Defaults to False.
author (str): Author of file. Defaults to None.
"""
# -- open and smooth obs climo
clima = xr.open_dataset(f'{save_directory}era5_temp_clim_gpcp_data.nc')
climCyclical = xr.concat([clima['clim'], clima['clim'], clima['clim']], dim='time')
climSmooth = climCyclical.rolling(time=31, min_periods=1, center=True).mean(skipna=True).rolling(
time=31, min_periods=1, center=True).mean(skipna=True)
climSmooth = climSmooth.isel(time=slice(365,365 * 2))
climSmooth = climSmooth.transpose('time','lat','lon')
# -- reduce mem usage
del climCyclical
del clima
# -- add lead time to climo
climCyclicalObs = xr.concat([climSmooth, climSmooth, climSmooth], dim='time')
climFinal = np.zeros((climSmooth.shape[0],45,climSmooth.shape[1],climSmooth.shape[2]))
for i in range(365):
climFinal[i,:,:,:] = climCyclicalObs[365+i:365+i+45,:,:]
# -- create time arrays for subsequent indexing
d_mon = pd.date_range(start=start_range, end=end_range, freq='W-MON')
d_dly = pd.date_range(start=start_range, end=end_range, freq='D')
d_mon = d_mon[~((d_mon.day==29)&(d_mon.month==2))]
d_dly = d_dly[~((d_dly.day==29)&(d_dly.month==2))]
# -- create daily obs for final anom computation
d_daily = pd.date_range(start=start_range, end=str(int((end_range)[:4])+1)+'-12-31', freq='D')
d_daily = d_daily[~((d_daily.day==29)&(d_daily.month==2))]
for num, t in enumerate(d_daily):
tmax = xr.open_dataset(
f"{obs_directory}era5_tmax_regrid/e5.oper.fc.sfc.minmax.128_201_mx2t.ll025sc.{t.strftime('%Y%m%d')}.nc")['MX2T']
tmin = xr.open_dataset(
f"{obs_directory}era5_tmin_regrid/e5.oper.fc.sfc.minmax.128_202_mn2t.ll025sc.{t.strftime('%Y%m%d')}.nc")['MN2T']
avg_temp = (tmin + tmax) / 2
if num == 0:
varObs = np.zeros((len(d_daily),climSmooth.shape[1],climSmooth.shape[2]))
lats = tmin.y.values
lons = tmin.x.values
varObs[num,:,:] = avg_temp
# -- add lead time to daily obs
varFinal = np.zeros((int(len(d_mon)),45,climSmooth.shape[1],climSmooth.shape[2]))
for num, i in enumerate(d_mon):
varFinal[num,:,:,:] = varObs[int(np.argwhere(d_dly==np.datetime64(i))[0]):int(np.argwhere(d_dly==np.datetime64(i))[0])+45,:,:]
# -- compute obs anomalies
anom = np.zeros((int(len(d_mon)),45,climSmooth.shape[1],climSmooth.shape[2]))
for num, i in enumerate(d_mon):
doy_indx = i.dayofyear - 1
if calendar.isleap(int(i.year)) and i.month > 2:
doy_indx = doy_indx - 1
anom[num,:,:,:] = varFinal[num,:,:,:] - climFinal[doy_indx,:,:,:]
# --
data_assemble = xr.Dataset({
'anom': (['time','lead','lat','lon'], anom),
'date_range': (['date_range'], d_mon),
},
coords =
{'lead': (['lead'], np.arange(0,anom.shape[1],1)),
'time': (['time'], np.arange(1,anom.shape[0]+1,1)),
'lat' : (['lat'], lats),
'lon' : (['lon'], lons)
},
attrs =
{'File Author' : author})
if not save:
return data_assemble
if save:
data_assemble.to_netcdf(f'{save_directory}era5_temp_anom_gpcp_data.nc')
|
7c49cc3aad3c9b92e9520f0b709d4118f59afec3
| 34,404 |
def is_supported(browser):
"""
指定したブラウザがサポート対象かチェック
Attributes:
browser (str): チェック対象ブラウザ
Returns:
bool: ブラウザのサポート有無
"""
return browser in _browser_modules
|
d3e49446b8c333f72b5e652899491b46960fd2ae
| 34,405 |
from typing import Sequence
from typing import Tuple
import operator
def pie_marker(
ratios: Sequence[float],
res: int = 50,
direction: str = "+",
start: float = 0.0,
) -> Tuple[list, list]:
"""
Create each slice of pie as a separate marker.
Parameters:
ratios(list): List of ratios that add up to 1.
res: Number of points around the circle.
direction: '+' for counter-clockwise, or '-' for clockwise.
start: Starting position in radians.
Returns:
xys, ss: Tuple of list of xy points and sizes of each slice in the pie marker.
"""
if np.abs(np.sum(ratios) - 1) > 0.01:
print("Warning: Ratios do not add up to 1.")
if direction == '+':
op = operator.add
elif direction == '-':
op = operator.sub
xys = [] # list of xy points of each slice
ss = [] # list of size of each slice
start = float(start)
for ratio in ratios:
# points on the circle including the origin (0,0) and the slice
end = op(start, 2 * np.pi * ratio)
n = round(ratio * res) # number of points forming the arc
x = [0] + np.cos(np.linspace(start, end, n)).tolist()
y = [0] + np.sin(np.linspace(start, end, n)).tolist()
xy = np.column_stack([x, y])
xys.append(xy)
ss.append(np.abs(xy).max())
start = end
return xys, ss
|
61522394a5356f1a7c0e9e2e112c0025ae7dc9cc
| 34,406 |
def indref_dust_wolff_2009(wav):
"""
This function returns the index of refraction for dust.
The data used are nominally taken from Wolff (2009), which extends from 236 nm to 98.5423 micron. There are only 5 points in our wavelength region of interest.
For the moment, we use the compendium provided by the Ames GCM group at http://spacescience.arc.nasa.gov/mars-climate-modeling-group/brief.html. They assume an r_eff of 1.5 micron and a var_eff of 0.5, lognormal.
Input: wavelength in nm
Output: complex index of refraction, calculated using interpolation
For values outside the range encompassed by the data (i.e. <236 nm or >98.5423 micron) the constant value at 52 nm and 98.5423 micron respectively is used.
"""
refwav_um,N_r, N_i=np.genfromtxt('./Raw_Data/ComplexRefractionIndices/Dust_Refractive_Indicies.txt', skip_header=1, skip_footer=0, usecols=(0, 1, 2), unpack=True)#wavelength in microns, real refractive index, imaginary refractive index.
#index of refraction at 263 nm, for padding
refwav_um_minval=refwav_um[0]
N_r_minval=N_r[0]
N_i_minval=N_i[0]
#index of refraction at 98.5423 um, for padding
refwav_um_maxval=refwav_um[-1]
N_r_maxval=N_r[-1]
N_i_maxval=N_i[-1]
#Create functionalized forms of indices for linear interpolation
N_r_func=interp.interp1d(refwav_um, N_r, kind='linear')
N_i_func=interp.interp1d(refwav_um, N_i, kind='linear')
wav_um=wav*nm2micron
if (type(wav)==float or type(wav)==np.float64): #branch: have to treat floats and arrays separately.
if wav_um<refwav_um_minval:
return N_r_minval+1.j*N_i_minval
elif wav_um>refwav_um_maxval:
return N_r_maxval+1.j*N_i_maxval
else:
return N_r_func(wav_um)+1.j*N_i_func(wav_um)
else:
result=np.zeros(np.shape(wav_um), dtype=np.complex)
result[wav_um<refwav_um_minval]=N_r_minval+1.j*N_i_minval
result[wav_um>refwav_um_maxval]=N_r_maxval+1.j*N_i_maxval
inds=np.where((wav_um>=refwav_um_minval) & (wav_um<=refwav_um_maxval))
result[inds]=N_r_func(wav_um[inds])+1.j*N_i_func(wav_um[inds])
return result
|
864bc7efd908c9da47f050e82315f1ddd48ad500
| 34,407 |
def select_columns(
df: pd.DataFrame,
*args,
invert: bool = False,
) -> pd.DataFrame:
"""
Method-chainable selection of columns.
Not applicable to MultiIndex columns.
It accepts a string, shell-like glob strings `(*string*)`,
regex, slice, array-like object, or a list of the previous options.
This method does not mutate the original DataFrame.
Optional ability to invert selection of columns available as well.
Functional usage example:
```python
import pandas as pd
import janitor as jn
df = pd.DataFrame(...)
df = jn.select_columns('a', 'b', 'col_*',
invert=True)
```
Method-chaining example:
```python
df = (pd.DataFrame(...)
.select_columns('a', 'b', 'col_*',
invert=True))
```
:param df: A pandas DataFrame.
:param args: Valid inputs include: an exact column name to look for,
a shell-style glob string (e.g., `*_thing_*`),
a regular expression,
a callable which is applicable to each Series in the DataFrame,
or variable arguments of all the aforementioned.
A sequence of booleans is also acceptable.
:param invert: Whether or not to invert the selection.
This will result in the selection of the complement of the columns
provided.
:returns: A pandas DataFrame with the specified columns selected.
"""
# applicable for any
# list-like object (ndarray, Series, pd.Index, ...)
# excluding tuples, which are returned as is
search_column_names = []
for arg in args:
if is_list_like(arg) and (not isinstance(arg, tuple)):
search_column_names.extend([*arg])
else:
search_column_names.append(arg)
if len(search_column_names) == 1:
search_column_names = search_column_names[0]
full_column_list = _select_column_names(search_column_names, df)
if invert:
return df.drop(columns=full_column_list)
return df.loc[:, full_column_list]
|
a0881fbcf078f4c501b5dd0d706b7801ab47794d
| 34,409 |
def compute_distance(location_1, location_2):
"""
Euclidean distance between 3D points.
Parameters
----------
location_1 : carla.Location
Start point of the measurement.
location_2 : carla.Location
End point of the measurement.
"""
x = location_2.x - location_1.x
y = location_2.y - location_1.y
z = location_2.z - location_1.z
norm = np.linalg.norm([x, y, z]) + np.finfo(float).eps
return norm
|
8511a59cb949a355ceaaeb85035474285412ba49
| 34,410 |
def ewma_2d(x, halflife):
"""
Exponentially Weighted Moving Average,
optimised for 2D data sets.
"""
assert x.ndim == 2
assert np.isfinite(halflife) and halflife > 0
decay_coefficient = np.exp(np.log(0.5) / halflife)
out = np.empty_like(x, dtype=np.float64)
for i in range(out.shape[0]):
if i == 0:
out[i, :] = x[i, :]
sum_prior = 1
first_weight = 1
else:
first_weight *= decay_coefficient
sum_i = sum_prior + first_weight
for j in range(x.shape[1]):
out[i, j] = (decay_coefficient * out[i - 1, j] * sum_prior + x[i, j]) / sum_i
sum_prior = sum_i
return out
|
23232e3050dd6280a1a0819ad5261a8c9545cfd3
| 34,411 |
def DT2str(dt):
"""
convert a datetime to a string in the GNOME format.
"""
dt_string = "%3i, %3i, %5i, %3i, %3i"%(dt.day, dt.month, dt.year, dt.hour, dt.minute)
return dt_string
|
7d0b26c9d4517738be448e2ab897b1ffb419179f
| 34,412 |
def get_active_lines(lines, comment_char="#"):
"""
Returns lines, or parts of lines, from content that are not commented out
or completely empty. The resulting lines are all individually stripped.
This is useful for parsing many config files such as ifcfg.
Parameters:
lines (list): List of strings to parse.
comment_char (str): String indicating that all chars following
are part of a comment and will be removed from the output.
Returns:
list: List of valid lines remaining in the input.
Examples:
>>> lines = [
... 'First line',
... ' ',
... '# Comment line',
... 'Inline comment # comment',
... ' Whitespace ',
... 'Last line']
>>> get_active_lines(lines)
['First line', 'Inline comment', 'Whitespace', 'Last line']
"""
return list(filter(None, (line.split(comment_char, 1)[0].strip() for line in lines)))
|
b49c8cd034c8fa8e7dcf0b5153c8d5bcce52a1f3
| 34,413 |
def is_shutout(goalie_dict, goalies_in_game):
"""
Checks whether current goalie game can be considered a shutout.
"""
# only goalies that played and didn't concede any goals can have a shutout
if (goalie_dict['games_played'] and not goalie_dict['goals_against']):
# if more than two goalies (for both teams) were in the game, we
# have to check whether goalies shared a game with no goals against
if len(goalies_in_game) > 2:
# counting goalies per team
goalies_per_team_cnt = 0
for team, _ in goalies_in_game:
if team == goalie_dict['team']:
goalies_per_team_cnt += 1
# if current team had more than one goalie in the game, this can't
# be a personal shutout
if goalies_per_team_cnt > 1:
return False
# games lost in overtime or the shootout are no shutouts regardless
if goalie_dict['sl'] or goalie_dict['ol']:
return False
# only games solely played with no goals against throughout regulation,
# overtime, and shootout are shutouts
return True
return False
|
c9aa7adead449366e8845b562fd04b98396321cc
| 34,414 |
def phase_segmentation(image, threshold, area_bounds=[0.5, 6.0],
ip_dist=0.160):
"""
Segement a phase image and return the mask.
Parameters
----------
image : 2d-array
The phase image to be segmented. This image will be converted to a
float type.
threshold : float
Threshold value for the segmentation. This function will select objects
below this threshold value.
area_bounds : list, default=[0.5, 6.0]
Area bounds for identified objects. This should be a list of two entries.
ip_dist : int or float, default = 0.160
Interpixel distance for the camera. This should be in units of microns
per pixel.
Returns
-------
final_seg : 2d-array
Final, labeled segmentation mask.
"""
# First is to convert the image to a float.
im_float = (image - image.min()) / (image.max() - image.min())
# Do a background subtraction.
im_blur = skimage.filters.gaussian(im_float, sigma=50.0)
im_sub = im_float - im_blur
# Apply the threshold.
im_thresh = im_sub < threshold # Note that we are using the provided arg
# Label the image and apply the area bounds.
im_lab = skimage.measure.label(im_thresh)
props = skimage.measure.regionprops(im_lab)
approved_objects = np.zeros_like(im_lab)
for prop in props:
area = prop.area * ip_dist**2
if (area > area_bounds[0]) & (area < area_bounds[1]):
approved_objects += im_lab == prop.label
# Clear the border and relabel.
im_border = skimage.segmentation.clear_border(approved_objects > 0)
final_seg = skimage.measure.label(im_border)
# Return the final segmentation mask
return final_seg
|
a4eeb7dd8f9602c0dada2a62f3e2cabda3036950
| 34,415 |
from datetime import datetime
def _fix_other_columns(df):
"""
Fills all other columns using reasonably similar rows.
"""
cols_to_fill1 = [
"season",
"workingday",
"weathersit",
"temp",
"atemp",
"hum",
"windspeed",
"cnt",
]
dhour = datetime.timedelta(hours=1)
dday = datetime.timedelta(days=1)
null_idxs = df[df.isna().any(axis=1)].index
for idx in null_idxs:
if (idx - dhour).dayofweek == idx.dayofweek:
similar_row = df.loc[idx - dhour]
else:
similar_row = df.loc[idx + dhour]
if similar_row.isna().any():
similar_row = df.loc[idx - dday]
df.loc[idx, cols_to_fill1] = similar_row[cols_to_fill1]
cols_to_fill2 = ["season", "holiday"]
for idx in null_idxs:
candidates = df[
(~df.isna().any(axis=1))
& (df.index.day == idx.day)
& (df.index.month == idx.month)
& (df.index.year == idx.year)
]
similar_row = candidates.iloc[0, :]
df.loc[idx, cols_to_fill2] = similar_row[cols_to_fill2]
return df
|
c710d6342dbcf1c340479a7dc3b8eacfeee7cfb1
| 34,416 |
def storage_get_all_by_project(context, project_id, marker, limit, sort_key,
sort_dir):
"""Get all storages belonging to a project."""
return IMPL.storage_get_all_by_project(context, project_id, marker, limit,
sort_key, sort_dir)
|
aa8e20ce1fda6e80a7e9033ede16aa2f457557ce
| 34,417 |
def evaluate_parentheses(token):
"""
Evaluates parentheses.
Parameters
----------
token : ``Token``
Returns
-------
new_token : ``Token``
The final evaluated token.
"""
new_token = evaluate_tokens(token.sub_tokens)
new_token.start = token.start
new_token.end = token.end
return new_token
|
7f0b3044fd25c3d0ae958abadea668ca07dec3c3
| 34,418 |
def typprice(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of typical price for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): Ticker
timeframe (string): timeframe to use, for pyEX.chart
highcol (string): column to use to calculate
lowcol (string): column to use to calculate
closecol (string): column to use to calculate
Returns:
DataFrame: result
"""
df = client.chartDF(symbol, timeframe)
typ = t.TYPPRICE(df[highcol].values, df[lowcol].values, df[closecol].values)
return pd.DataFrame(
{
highcol: df[highcol].values,
lowcol: df[lowcol].values,
closecol: df[closecol].values,
"typprice": typ,
}
)
|
3d7e8621a9c85e48913df15d59944a480c0cda35
| 34,419 |
import json
def evaluate_grants(path_to_gt_json, path_to_test_json):
"""
This function measures the micro recall of the grantIDs identified by a system.
Input:
- gt_json: Path to ground truth .json file
- test_json: Path to user submitted .json file
Output:
- Float value of micro recall
ATTENTION: The .json files are expected to have the structure (keywords, number of elements etc.)
as explicitly mentioned in the corresponding guidelines
"""
# Load gt data from json
with open(path_to_gt_json, 'r') as f:
gt_json = json.load(f)
# Load test data from json
with open(path_to_test_json, 'r') as f:
test_json = json.load(f)
# Predicted True Positive Count
tp = 0
# True Positive
denom = 0
# Mapping between articles-grants in ground truth json
y_true = {}
# Mapping between articles-grants in test json
y_pred = {}
for i, ar in enumerate(gt_json['articles']):
# temporary list of grants for each article
tmp = []
for grant in ar['grantList']:
# if a specific grant is bound to some grantID
if 'grantID' in grant:
# !! LOWERCASE NORMALISATION !!
tmp.append(grant['grantID'].lower())
# Keep unique grantIDs for each article
y_true[ar['pmid']] = set(tmp)
# Do the same for the test .json. Lowercase and uniquify as well
y_pred[test_json['articles'][i]['pmid']] = set([gr['grantID'].lower() for gr in test_json['articles'][i]['grantList'] if 'grantID' in gr])
# For each article
for pmid, true in y_true.iteritems():
# Find the count of intersecting grantIDs between the
# ground truth and the predicted lists.
# These are the true predicted positive grantIDs
tp += len(true.intersection(y_pred[pmid]))
# True Positive count
denom += len(true)
return tp/float(denom)
|
465bfb885780983ac5df05d590f0570dee52d6bd
| 34,420 |
def read_puzzle(board, input_puzzle):
"""
Reads unsolved puzzle
If the string given is a filename with .txt of .sud suffix, the puzzle
is read from the file, otherwise a string containing the puzzle is considered
Expected format:
1 line, row-wise saved values where unknown cells are marked with
anything other than numbers 1-9
Example:
829.5...7.....2....64.7.1922.87364..7135..9.........3.64..1.8....52....113..6.2..
"""
if any(x in input_puzzle for x in [".txt", ".sud"]):
with open(input_puzzle, "rU") as f:
line = f.readline().rstrip()
else:
line = input_puzzle
for i in range(n):
for j in range(n):
if (line[i*n+j] in "123456789"):
board[i][j] = [int(line[i*n+j])]
return 0
|
b8c44230fdccebb6122ab16f924ee10dd6e3e171
| 34,421 |
from typing import get_args
import dataclasses
def dataclass_from_dict(klass, d):
"""
Converts a dictionary based on a dataclass, into an instance of that dataclass.
Recursively goes through lists, optionals, and dictionaries.
"""
if is_type_SpecificOptional(klass):
# Type is optional, data is either None, or Any
if not d:
return None
return dataclass_from_dict(get_args(klass)[0], d)
elif is_type_Tuple(klass):
# Type is tuple, can have multiple different types inside
i = 0
klass_properties = []
for item in d:
klass_properties.append(dataclass_from_dict(klass.__args__[i], item))
i = i + 1
return tuple(klass_properties)
elif dataclasses.is_dataclass(klass):
# Type is a dataclass, data is a dictionary
fieldtypes = {f.name: f.type for f in dataclasses.fields(klass)}
return klass(**{f: dataclass_from_dict(fieldtypes[f], d[f]) for f in d})
elif is_type_List(klass):
# Type is a list, data is a list
return [dataclass_from_dict(get_args(klass)[0], item) for item in d]
elif issubclass(klass, bytes):
# Type is bytes, data is a hex string
return klass(hexstr_to_bytes(d))
elif klass.__name__ in unhashable_types:
# Type is unhashable (bls type), so cast from hex string
return klass.from_bytes(hexstr_to_bytes(d))
else:
# Type is a primitive, cast with correct class
return klass(d)
|
434f05ba49db17016c175155b89986f044c914e3
| 34,422 |
def depolarization_factor(wl):
"""Bucholtz 95 Table 1
Depolarization factor as fct of wavelength in nm"""
rho = np.array([[0.200, 4.545],
[0.205, 4.384],
[0.210, 4.221],
[0.215, 4.113],
[0.220, 4.004],
[0.225, 3.895],
[0.230, 3.785],
[0.240, 3.675],
[0.250, 3.565],
[0.260, 3.455],
[0.270, 3.400],
[0.280, 3.289],
[0.290, 3.233],
[0.300, 3.178],
[0.310, 3.178],
[.32, 3.122],
[.33, 3.066],
[.34, 3.066],
[.35, 3.01],
[.37, 3.01],
[.38, 2.955],
[0.4, 2.955],
[0.45, 2.899],
[0.5, 2.842],
[0.55, 2.842],
[0.6, 2.786],
[0.75, 2.786],
[0.8, 2.73],
[1., 2.73]
]).transpose()
rho[0] *= 1000
rho[1] *= 0.01
idx = array_tools.find_closest(rho[0], wl)
return rho[1][idx]
|
ccc2212391e1439b74f5399e82a9bc8c7825b14b
| 34,423 |
def draw_line (surface, color, a, b, width=1):
"""draw_line (...) -> Rect
Draws a line on a surface.
The 'color' argument needs to match the pygame color style. 'a' and
'b' are sequences of the x- and y-coordinate on the surface and
'width' denotes the width of the line in pixels. The return value
is the bounding box of the affected area.
The following example would draw a horizontal black line on the
specified surface (the surface must be big enough):
draw_line (surface, (0, 0, 0), (5, 5), (5, 10))
Note: This function is just a wrapper around pygame.draw.line() and
thus all documentation about it can be applied to this function,
too.
"""
return draw.line (surface, color, a, b, width)
|
33519d943fad5979e5ccadb1ce03c4d35baea497
| 34,424 |
def judge_all_tests(judge: LocalJudge, verbose_level, score_dict, total_score):
"""Judge all tests for given program.
If `--input` is set, there is only one input in this judgement.
"""
judge.build()
report = Report(
report_verbose=verbose_level, score_dict=score_dict, total_score=total_score
)
for test in judge.tests:
returncode, output_filepath = judge.run(test.input_filepath)
accept, diff = judge.compare(output_filepath, test.answer_filepath, returncode)
report.table.append({"test": test.test_name, "accept": accept, "diff": diff})
return report.print_report()
|
9f442cdd9a38f17528f6802f76c6ceddabfe6022
| 34,426 |
import re
def generate_per_sample_fastq_command(forward_seqs, reverse_seqs, barcode_fps,
mapping_file, output_dir, params_str):
"""Generates the per-sample FASTQ split_libraries_fastq.py command
Parameters
----------
forward_seqs : list of str
The list of forward seqs filepaths
reverse_seqs : list of str
The list of reverse seqs filepaths
barcode_fps : list of str
The list of barcode filepaths
mapping_file : str
The path to the mapping file
output_dir : str
The path to the split libraries output directory
params_str : str
The string containing the parameters to pass to
split_libraries_fastq.py
Returns
-------
str
The CLI to execute
Raises
------
ValueError
- If barcode_fps is not an empty list
- If there are run prefixes in the mapping file that do not match
the sample names
"""
if barcode_fps:
raise ValueError('per_sample_FASTQ can not have barcodes: %s'
% (', '.join(basename(b) for b in barcode_fps)))
sn_by_rp = get_sample_names_by_run_prefix(mapping_file)
samples = []
errors = []
for fname in forward_seqs:
fn = basename(fname)
# removing extentions: fastq or fastq.gz
if 'fastq' in fn.lower().rsplit('.', 2):
f = fn[:fn.lower().rindex('.fastq')]
else:
f = fn
m = [v for v in sn_by_rp if f.startswith(v)]
# removing study_id, in case it's present
if re.match(r"^[0-9]+\_.*", f):
f = basename(fn).split('_', 1)[1]
mi = [v for v in sn_by_rp if f.startswith(v)]
# the matches is the largest between m/mi, if they are the same size
# we are gonna use m
matches = m if len(m) > len(mi) else mi
if matches:
len_matches = len(matches)
if len_matches != 1:
errors.append('%s has %s matches.' % (f, len_matches))
for m in matches:
samples.append(sn_by_rp[m])
del sn_by_rp[m]
else:
errors.append('%s has NO matches' % f)
if errors:
raise ValueError('Errors found:\n%s' % '\n'.join(errors))
cmd = str("split_libraries_fastq.py --store_demultiplexed_fastq "
"-i %s --sample_ids %s -o %s %s"
% (','.join(forward_seqs), ','.join(samples),
output_dir, params_str))
return cmd
|
44d3cef9cca598a8ce36a46637bfa288c49a5f98
| 34,427 |
def renderInlineStyle(d):
"""If d is a dict of styles, return a proper style string """
if isinstance(d, (str, int, float)):
result = str(d)
else:
style=[]
for k,v in d.items():
style.append("{}:{};".format(k, v))
separator = ' '
result = separator.join(style)
return result
|
f08ea415e4fa29404b7c879f2346832dc84d2e67
| 34,428 |
from typing import cast
def selftest(silent: bool=False) -> bool:
"""Run a simple self-test of DHParser.
"""
if not silent:
print("DHParser selftest...")
print("\nSTAGE I: Trying to compile EBNF-Grammar:\n")
builtin_ebnf_parser = get_ebnf_grammar()
docstring = str(builtin_ebnf_parser.__doc__) # type: str
i = docstring.find('::')
if i >= 0:
docstring = docstring[i + 2::]
ebnf_src = docstring[docstring.find('@'):]
ebnf_transformer = get_ebnf_transformer()
ebnf_compiler = get_ebnf_compiler('EBNF')
result, errors, _ = compile_source(
ebnf_src, None,
builtin_ebnf_parser, ebnf_transformer, ebnf_compiler)
generated_ebnf_parser = cast(str, result)
if has_errors(errors, ERROR):
if not silent:
print("Selftest FAILED :-(")
print("\n\n".join(str(err) for err in errors))
return False
if not silent:
print(generated_ebnf_parser)
print("\n\nSTAGE 2: Selfhosting-test: "
"Trying to compile EBNF-Grammar with generated parser...\n")
selfhosted_ebnf_parser = compileDSL(ebnf_src, None, generated_ebnf_parser,
ebnf_transformer, ebnf_compiler)
# ebnf_compiler.gen_transformer_skeleton()
if not silent:
print(selfhosted_ebnf_parser)
return True
|
6353abac840ee7a66b2a40133f427ec9ae91f8f2
| 34,429 |
def bounding_box(grid, cell_kji0, points_root = None, cache_cp_array = False):
"""Returns the xyz box which envelopes the specified cell, as a numpy array of shape (2, 3)."""
result = np.zeros((2, 3))
cp = grid.corner_points(cell_kji0, points_root = points_root, cache_cp_array = cache_cp_array)
result[0] = np.min(cp, axis = (0, 1, 2))
result[1] = np.max(cp, axis = (0, 1, 2))
return result
|
e526a4ee029a02d224bd264aee9c160a5ecdaa85
| 34,430 |
def test_dup_args_in_call(x):
"""The naive gradient update rule fails when a function's arguments
contain the same variable more than once."""
return x * x
|
978f4f6e901b4b4aba01bbad098c107eacab59f3
| 34,432 |
def snake_to_camel_case(snake_text):
"""
Converts snake case text into camel case
test_path --> testPath
:param snake_text:str
:return: str
"""
components = snake_text.split('_')
# We capitalize the first letter of each component except the first one with
# the 'title' method and join them together.
return components[0] + ''.join(x.title() for x in components[1:])
|
b42e1393cf99b88e2ebbcf4b38643c770e218ceb
| 34,433 |
def compute_accuracy(dist, labels, threshold):
"""
Compute the average accuracy over the given set of images.
dist: computed distance between pair of images.
labels: true class labels
threshold: decision threshold.
"""
trueclass = np.sum(np.logical_and((dist <= threshold).reshape(dist.shape[0], 1), labels == 1)
) + np.sum(np.logical_and((dist > threshold).reshape(dist.shape[0], 1), labels != 1))
accuracy = float(trueclass) / len(labels)
return accuracy
|
d59388c89fe5da610ca51fb7198cd52aa063502b
| 34,434 |
def http_take_solver():
"""Return the string of answer"""
request_data = request.get_json()
answers = ai.take_solver(request_data)
return jsonify({"answers": answers})
|
c11977b0180037f4e458f526533ce604ff10859a
| 34,436 |
def create_organization(
*, db_session: Session = Depends(get_db), organization_in: OrganizationCreate
):
"""
Create a new organization.
"""
organization = get_by_name(db_session=db_session, name=organization_in.name)
if organization:
raise HTTPException(
status_code=400, detail="An organization with this name already exists."
)
organization = create(db_session=db_session, organization_in=organization_in)
return organization
|
7511a20a1588b122f02d0c930c3a6e209907a482
| 34,437 |
import networkx
def check_all(logic_forms: list, checks=None, verbose=False) -> list:
""" Do all Logic Form Graph checking.
Parameter:
logic forms (list): logical forms
verbose (bool): enable printing details
Returns:
lf_graphs (list): dicts of id (int) and a graph (LogicalFormGraph)
"""
lf_graphs = lfg.create_logic_form_graphs_from_logic_forms(logic_forms)
num_lfs = {'base': len(lf_graphs)}
if verbose:
print_all(lf_graphs)
# check tree
if not all(networkx.is_tree(g['graph'].graph) for g in lf_graphs):
print("WARNING: not all Logic Form Graphs are trees!")
# do checks
if checks is None:
checks = CHECKS
for check in checks:
lf_graphs = cp.check_pred_all(lf_graphs, mode=check)
num_lfs[check] = len(lf_graphs)
if verbose:
print(f'# lfs after predicate {check}: {num_lfs[check]}')
# check equivalency
equivalent_ids = ce.check_logic_forms_eq(lf_graphs)
elem_num = sum(len(id_set) for id_set in equivalent_ids)
uniqlf_num = len(lf_graphs) - elem_num + len(equivalent_ids)
num_lfs['unique'] = uniqlf_num
if verbose:
print('Numbers of unique lfs: ', uniqlf_num)
sorted_ids = sorted([tuple(sorted(id_set))
for id_set in equivalent_ids])
print(f'Equivalent logical forms: {sorted_ids}')
print(f'LF check summary: {num_lfs}')
return lf_graphs
|
21bc30647ab379e98566bf7dc1e7dd3d0e88e86b
| 34,438 |
def remove_noise(line,minsize=8):
"""Remove small pixels from an image."""
if minsize==0: return line
bin = (line>0.5*amax(line))
labels,n = morph.label(bin)
sums = measurements.sum(bin,labels,range(n+1))
sums = sums[labels]
good = minimum(bin,1-(sums>0)*(sums<minsize))
return good
|
0ee16876ed90f84be1abcd911689dafafad7ef96
| 34,439 |
def get_wide_dword(*args):
"""
get_wide_dword(ea) -> uint64
Get two wide words (4 'bytes') of the program at 'ea'. Some processors
may access more than 8bit quantity at an address. These processors
have 32-bit byte organization from the IDA's point of view. This
function takes into account order of bytes specified in
\inf{is_be()}this function works incorrectly if \ph{nbits} > 16
@param ea (C++: ea_t)
"""
return _ida_bytes.get_wide_dword(*args)
|
4d8574128bfca6a48e595516c4e9bee6a9bbfc75
| 34,440 |
import copy
def corrupt(x, mask=None):
"""Take an input tensor and add uniform masking.
Parameters
----------
x : Tensor/Placeholder
Input to corrupt.
mask: none
Returns
-------
x_corrupted : Tensor
50 pct of values corrupted.
"""
cor = copy.deepcopy(x)
if mask is not None:
for i in range(x.shape[0]):
cor[i] *= mask[i]
shuffle_indices = np.random.permutation(np.arange(cor.shape[0]))
shuffle_data = cor[shuffle_indices]
x = x[shuffle_indices]
return shuffle_data, x
n = np.random.normal(0, 0.1, (x.shape[0], x.shape[1]))
# y = x + n
# fig, axs = plt.subplots(2, n_examples, figsize=(10, 2))
# for example_i in range(n_examples):
# axs[0][example_i].imshow(
# # np.reshape(test_xs[example_i, :], (28, 28)))
# np.reshape(y[example_i, :], (15, 15)))
# axs[1][example_i].imshow(
# # np.reshape([recon[example_i, :] + mean_img], (28, 28)))
# np.reshape([x[example_i, :]], (15, 15)))
# print ('Plot complete now showing...')
# fig.show()
# plt.draw()
# plt.title("1st function - dataset ones but used our dataset")
# plt.waitforbuttonpress()
return x + n
# return tf.multiply(x, tf.cast(tf.random_uniform(shape=tf.shape(x),
# minval=0,
# maxval=2,
# dtype=tf.int32), tf.float32))
|
f8b91f07012bd231570981824a0759b40f30f4b0
| 34,441 |
def bvi(model, guide, claims, learning_rate=1e-5, num_samples=1):
"""perform blackbox mean field variational inference on simpleLCA.
This methods take a simpleLCA model as input and perform blackbox variational
inference, and returns a list of posterior distributions of hidden truth and source
reliability.
Concretely, if s is a source then posterior(s) is the probability of s being honest.
And if o is an object, or more correctly, is a random variable that has the support as
the domain of an object, then posterior(o) is the distribution over these support.
The underlying truth value of an object could be computed as the mode of this
distribution.
"""
data = make_observation_mapper(claims)
conditioned_lca = pyro.condition(lca_model, data=data)
pyro.clear_param_store() # is it needed?
svi = pyro.infer.SVI(model=conditioned_lca,
guide=lca_guide,
optim=pyro.optim.Adam({
"lr": learning_rate,
"betas": (0.90, 0.999)
}),
loss=pyro.infer.TraceGraph_ELBO(),
num_samples=num_samples)
return svi
|
bb7469efd4615156219f0f514200784a50a84ad6
| 34,442 |
from pathlib import Path
import json
def load_metadata(bucket: str, prefix: str) -> dict[str, dict]:
"""
Get general export metadata file and table status metadatas. The
former contains column names / types as well as a string containig
schema and table name.
Export metadata contains info about the overall RDS snapshot export. For
example
{
'exportTaskIdentifier': 'v2-r1000-20210307-snapshot',
'sourceArn': 'arn:aws:rds:us-west-2:025524405457:cluster-snapshot:rds:v2-production-r1000-cluster-2021-03-07-08-50',
'exportOnly': [],
'snapshotTime': 'Mar 7, 2021 8:50:42 AM',
'taskStartTime': 'Mar 8, 2021 5:32:17 AM',
'taskEndTime': 'Mar 8, 2021 8:04:43 AM',
's3Bucket': 'skupos-partner-snowflake-121345678',
's3Prefix': 'v2-r1000-',
'exportedFilesPath': 'v2-r1000-/v2-r1000-20210307-snapshot',
'iamRoleArn': 'arn:aws:iam::025524405457:role/service-role/skuposRDS-export-s3-role',
'kmsKeyId': 'arn:aws:kms:us-west-2:025524405457:key/c86308ac-ca14-40b0-af6f-832e507461db',
'status': 'COMPLETE',
'percentProgress': 100,
'totalExportedDataInGB': 28057.983845219016,
}
Tables metadata is a list of dicts containing table metadata for tables in
the input schema. Each table metadata object for a successfully exported
table looks like
{
'tableStatistics': {
'extractionStartTime': 'Mar 8, 2021 7:35:14 AM',
'extractionEndTime': 'Mar 8, 2021 7:35:42 AM',
'partitioningInfo': {
'numberOfPartitions': 1,
'numberOfCompletedPartitions': 1,
},
},
'schemaMetadata': {
'originalTypeMappings': [
{
'columnName': 'stranscd',
'originalType': 'bigint',
'expectedExportedType': 'int64',
'originalCharMaxLength': 0,
'originalNumPrecision': 19,
'originalDateTimePrecision': 0,
},
{
'columnName': 'descrpt',
'originalType': 'text',
'expectedExportedType': 'binary (UTF8)',
'originalCharMaxLength': 65535,
'originalNumPrecision': 0,
'originalCharsetName': 'latin1',
'originalDateTimePrecision': 0,
},
],
},
'status': 'COMPLETE',
'sizeGB': 8.046627044677734e-07,
'target': 'tdlinx.tdlinx.stranscd',
# inferred keys
'schema': 'tdlinx',
'table': 'stranscd',
}
A skipped export still contains a 'target' key but might include
a 'warningMessage'.
There does not appear to be any retention of indices.
The type mappings are used to create tables.
We transform the metadata stored in s3 by converting some lists to
(order-preserving) dicts and renaming the column metadata fields.
The original metadata files generated by AWS are enveloped and cached at
`~/.cache/snowflow/{prefix}/metadata.json`
Args:
bucket: Bucket in which the RDS export is located. This should
be accessible by the Snowflake AWS Integration.
prefix: Export prefix pointing to the actual content dir containing
export metadata and data. For example, "snapshots/{rds_instance}/{date}"
Returns:
A dict containing general export metadata under the 'info' key
and table metadata under the 'tables_info' key.
The dict keyed by 'tables_info' contains a single key containg a list
of dicts. Each element contains metadata about a specific
table, namely the column names, datatypes, export status, and
"target". The "target" value typically looks like
"{{schema}}.{{schema}.{{table}}", and corresponds to
an s3 path fragment "{{schema}}/{{schema}}.{{table}}". Sometimes
"""
metapath = Path("~/.cache/snowflow", prefix, "metadata.json").expanduser()
metapath.parent.mkdir(parents=True, exist_ok=True)
# Grab the two export_*.json metadata files, combine into a single json
# file and cache the output.
if not metapath.exists():
logger.info(f"Pulling export metadata from s3://{bucket}/{prefix}.")
prefix = str(Path(prefix, "export_"))
summaries = boto3.resource("s3").Bucket(bucket).objects.filter(Prefix=prefix)
# Look for the "export_tables_info*" and "export_info*" json files and
# load them into a buffer.
buf = {}
for summary in summaries:
okey = summary.key
if "tables_info" in okey:
key = "tables"
elif "export_info" in okey:
key = "export"
else:
continue
obj = summary.get()
data = json.loads(obj["Body"].read().decode())
buf[key] = data
with metapath.open("w") as mfile:
logger.info(f"Caching metadata in {metapath}.")
json.dump(buf, mfile)
else:
logger.info(f"Loading cached export metadata from {metapath}.")
with metapath.open() as mfile:
buf = json.load(mfile)
if 'export' not in buf and 'tables' not in buf:
raise ValueError(f'No metadata found for RDS export at s3://{bucket}/{prefix}')
# Embed table status in main metadata, remove some extraneous layering.
# Convert table lists to lookups. Order is preserved.
meta = buf["export"]
schemas = meta.setdefault("schemas", {})
# Group the table metadata by schema and add some default objects.
for table in buf["tables"]["perTableStatus"]:
# Parse the "target" key for each table's metadata into "schema"
# and "table".
target = table["target"]
try:
_, schema, name = target.split(".")
except ValueError:
schema = target
name = target
table["schema"] = schema
table["name"] = name
# Some tables are skipped, e.g., if the db is empty, so they won't have
# type mappings. Add empty objects here.
table["columns"] = []
# Rename fields for each column metadata and convert list to dict.
for column in table.get("schemaMetadata", {}).pop("originalTypeMappings", []):
tcolumn = {
"name": column.pop("columnName", None),
"original_type": column.pop("originalType", None),
"exported_type": column.pop("expectedExportedType", None),
"char_max_length": column.pop("originalCharMaxLength", None),
"num_precision": column.pop("originalNumPrecision", None),
"datetime_precision": column.pop("originalDateTimePrecision", None),
"charset": column.pop("originalCharsetName", None),
}
table["columns"].append(column | tcolumn)
if schema not in schemas:
schemas[schema] = {"tables": []}
schemas[schema]["tables"].append(table)
return meta
|
578b7cb312d1490a9d9ded1574b9e5a445d93d5d
| 34,443 |
from datetime import datetime
def get_dbtbl(options: list):
"""Handles dbtbl (available lobby table) calls."""
main.terminate_incorrect_lobbies()
order = None
resort = None
for option in options:
option = option.strip("'")
if option.startswith("order="):
order = option[6:]
elif option.startswith("resort="):
resort = option[7:]
lastupdate = datetime.now()
lastupdate = lastupdate.strftime("%H:%M:%S")
entrypos = 0
currlobby = 0
buttonstring = ""
pingstring = ""
newlobbystring = data_from_file("dbtbl.dcml")
newlobbystring = newlobbystring.replace("//LASTUPDATE", lastupdate)
for (lid, lobj) in main.lobbies.items():
buttonstringtemp = "#apan[%APANLOBBYN](%SB[x:0,y:ENTRYPOS-2,w:100%,h:20]," \
"{GW|open&join_game.dcml\\00&delete_old=true^id_room=LOBBYID\\00|LW_lockall},8) " \
"#font(BC12,BC12,BC12)" \
"#ping[%PINGLOBBYN](%SB[x:86%+30,y:ENTRYPOS+4,w:14,h:20],IPADDR)"
buttonstringtemp = buttonstringtemp.replace("ENTRYPOS", str(entrypos))
buttonstringtemp = buttonstringtemp.replace("LOBBYID", str(lid))
buttonstringtemp = buttonstringtemp.replace("IPADDR", reverseip(lobj.ip_address))
buttonstringtemp = buttonstringtemp.replace("LOBBYN", str(currlobby))
buttonstring += buttonstringtemp
entrypos += 21
pingstringtemp = ''',21,"GAMETITLE","GAMEHOST","GAMETYPE","CURRENT_PLAYERS/MAX_PLAYERS",""'''
pingstringtemp = pingstringtemp.replace("GAMETITLE", lobj.game_title)
pingstringtemp = pingstringtemp.replace("GAMEHOST", lobj.host.player_name)
pingstringtemp = pingstringtemp.replace("GAMETYPE", GAME_TYPES[lobj.game_type])
pingstringtemp = pingstringtemp.replace("CURRENT_PLAYERS", str(lobj.players))
pingstringtemp = pingstringtemp.replace("MAX_PLAYERS", str(lobj.max_players))
currlobby += 1
pingstring += pingstringtemp
newlobbystring = newlobbystring.replace("//BUTTONSTRING", buttonstring)
newlobbystring = newlobbystring.replace("//PINGSTRING", pingstring)
return newlobbystring
|
f0c14f2cabc7a600b1296ed012b5c2b814a90708
| 34,444 |
def compare_parsed_text(seq_list, auto_stripped_text):
"""
This is a stupid workaround to the fact that bs4 parsers generally suck.
Tries to measure whether parsing was "successful" by looking at the
automatically scraped text of the policy to the text we parse here.
Note: can't match/replace entire elements at a time because of
weirdness in how certain things get scraped by bs4.
In: sequential list of elements, stripped text of policy HTML doc.
Out: sentence-tokenized version of remaining text.
"""
for element in seq_list:
element_segment_list = element.content_string.splitlines()
for segment in element_segment_list:
try:
auto_stripped_text = auto_stripped_text.replace(segment.strip(), "", 1)
except ValueError:
pass # do nothing!
return sent_tokenize(auto_stripped_text)
|
c1bc7b2fd87dbd90082a434f7193cfed08d3164d
| 34,445 |
import ctypes
def repmi(instr, marker, value, lenout=None):
"""
Replace a marker with an integer.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmi_c.html
:param instr: Input string.
:type instr: str
:param marker: Marker to be replaced.
:type marker: str
:param value: Replacement value.
:type value: int
:param lenout: Optional available space in output string.
:type lenout: int
:return: Output string.
:rtype: str
"""
if lenout is None:
lenout = ctypes.c_int(len(instr) + len(marker) + 15)
instr = stypes.stringToCharP(instr)
marker = stypes.stringToCharP(marker)
value = ctypes.c_int(value)
out = stypes.stringToCharP(lenout)
libspice.repmi_c(instr, marker, value, lenout, out)
return stypes.toPythonString(out)
|
c366f8a2077cc51bfff5f2d7e2f0b019e48c09f7
| 34,446 |
def _get_parameter_state(sender_owner, sender_type, param_name, component):
"""Return ParameterState for named parameter of a Mechanism requested by owner
"""
# Validate that component is a Mechanism or Projection
if not isinstance(component, (Mechanism, Projection)):
raise ParameterStateError("Request for {} of a component ({}) that is not a {} or {}".
format(PARAMETER_STATE, component, MECHANISM, PROJECTION))
try:
return component._parameter_states[param_name]
except KeyError:
# Check that param (named by str) is an attribute of the Mechanism
if not (hasattr(component, param_name) or hasattr(component.function, param_name)):
raise ParameterStateError("{} (in specification of {} {}) is not an attribute "
"of {} or its function"
.format(param_name, sender_type, sender_owner.name, component))
# Check that the Mechanism has a ParameterState for the param
if not param_name in component._parameter_states.names:
raise ParameterStateError("There is no ParameterState for the parameter ({}) of {} "
"specified in {} for {}".
format(param_name, component.name, sender_type, sender_owner.name))
|
11c72ad6bdf4bd28f25c771d4d4283b88522e1a2
| 34,447 |
def start_volume( mdserver_name ):
"""
Start up an existing metadata server for a volume. Return 1 on success.
"""
global conf
ctl_root = VOLUME_CTL_ROOT( conf, {'NAME': mdserver_name} )
config_file = VOLUME_CONF_PATH( ctl_root )
md_logfile = LOGFILE_PATH( ctl_root )
md_pidfile = PIDFILE_PATH( ctl_root )
# Get this server's configuration file
try:
md_conf = read_config( config_file )
except Exception, e:
raise MDMethodFailed( 'start_volume', "read config exception = '%s'" % e )
# make sure we're not running...
if is_volume_running( md_pidfile ):
return 1
try:
assert os.path.isdir( ctl_root ), "Control directory does not exist"
assert os.path.isfile( config_file ), "Config file does not exist"
assert os.path.isdir( md_conf['MDROOT'] ), "Master copy '%s' does not exist" % (md_conf['MDROOT'])
except AssertionError, e:
raise MDInternalError( "Server is not fully set up: %s" % str(e) )
try:
assert not os.path.isfile( md_pidfile )
except AssertionError, e:
raise MDInternalError( "Server is already running" )
# fire up the binary
md_proc = subprocess.Popen( [conf['MD_BINARY'], '-c', config_file, '-l', md_logfile ], close_fds = True )
rc = md_proc.wait()
if rc != 0:
# could not start the server
# make sure we remove runtime files, just in case
try:
os.unlink( md_pidfile )
except:
pass
raise MDMethodFailed( "start_volume", "rc = %s when starting metadata server" % rc )
return 1
|
1d8ed9310d9e67f3ca77f97eed935b0ff45661a6
| 34,448 |
from typing import Any
def _pycall_path_dest_only(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""A TDL function which samples the dest coordinate only."""
return ffi.from_handle(handle)(x2, y2)
|
808a50335bc3c70aa49f6fe198beb4817655dc8a
| 34,449 |
from datetime import datetime
def calculate_leap_seconds(year, month, day):
"""
get the leap seconds for the given year to convert GPS time to UTC time
.. note:: GPS time started in 1980
.. note:: GPS time is leap seconds ahead of UTC time, therefore you
should subtract leap seconds from GPS time to get UTC time.
=========================== ===============================================
Date Range Leap Seconds
=========================== ===============================================
1981-07-01 - 1982-07-01 1
1982-07-01 - 1983-07-01 2
1983-07-01 - 1985-07-01 3
1985-07-01 - 1988-01-01 4
1988-01-01 - 1990-01-01 5
1990-01-01 - 1991-01-01 6
1991-01-01 - 1992-07-01 7
1992-07-01 - 1993-07-01 8
1993-07-01 - 1994-07-01 9
1994-07-01 - 1996-01-01 10
1996-01-01 - 1997-07-01 11
1997-07-01 - 1999-01-01 12
1999-01-01 - 2006-01-01 13
2006-01-01 - 2009-01-01 14
2009-01-01 - 2012-07-01 15
2012-07-01 - 2015-07-01 16
2015-07-01 - 2017-01-01 17
2017-01-01 - ????-??-?? 18
=========================== ===============================================
"""
# make the date a datetime object, easier to test
given_date = datetime.date(int(year), int(month), int(day))
# made an executive decision that the date can be equal to the min, but
# not the max, otherwise get an error.
for leap_key in sorted(leap_second_dict.keys()):
if (
given_date < leap_second_dict[leap_key]["max"]
and given_date >= leap_second_dict[leap_key]["min"]
):
return int(leap_key)
return None
|
236d71d4827c4647999aef90e8f9f7ee49053f85
| 34,450 |
import re
def convert_vpc_name_to_vpc(possible_vpc_id, error_on_exit=True):
""" Convert a given VPC name into the VPC ID.
If the input VPC name looks like an existing VPC ID, then return the VPC immediately.
If the VPC with the given VPC name exists, then return the VPC.
If there is no such VPC, it prints an error and exits if error_on_exit.
Otherwise returns None
"""
if possible_vpc_id is None: raise NoneVPCID()
ec2 = get_ec2_connection()
if re.match(r'^vpc-[0-9a-f]+$', possible_vpc_id):
vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'vpc-id', 'Values': [possible_vpc_id]}]))
if len(vpcs) <= 0:
if error_on_exit: error_exit("Cannot find a VPC ID name '%s'" % possible_vpc_id)
return None
return vpcs[0]
vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'tag:Name', 'Values': [possible_vpc_id]}]))
if len(vpcs) <= 0:
if error_on_exit: error_exit("Cannot find a VPC '%s'" % possible_vpc_id)
return None
vpc_ids = [i.id for i in vpcs]
if 1 < len(vpc_ids):
if error_on_exit: error_exit("There are multiple VPCs with name='%s'.\nCandidates are:\n\t%s" % (possible_vpc_id, "\n\t".join(vpc_ids)))
return None
return vpcs[0]
|
3b5f644001bf12a3d2b1758a9bb045ee2e8e88b1
| 34,451 |
def preprocess_person(hh_dat, person_dat):
"""
This function preprocesses person-level features and merge with household data.
Nominal categorical variables, such as years of age are
transformed into continuous values.
Input:
Preprocessed household-level data
Original perosn-level data
Output:
A data frame with preprocessed household + person features
Each raw represents a unique household ID
<Person-level features and categories>
a. AGE: Each category was mapped using the middle point of the age range
1 -> 2.0 (0-4 years old)
2 -> 8.0 (5-11 years old)
3 -> 13.5 (12-15 years)
4 -> 16.5 (16-17 years)
5 -> 21.0 (18-24 years)
6 -> 29.5 (25-34 years)
7 -> 39.5 (35-44 years)
8 -> 49.5 (45-54 years)
9 -> 59.5 (55-64 years)
10 -> 69.5 (65-74 years)
11 -> 79.5 (75-84 years)
12 -> 89.5 (85 or years older)
b. RACE_WHITE: only for 18+ olds
0: Non-white
1: White
NaN: missing or N/A
c. RACE_BLACK: only for 18+ olds
0: Non-black
1: Black
NaN: missing or N/A
d. RACE_ASIAN: only for 18+ olds
0: Non-asian
1: Asian
NaN: missing or N/A
e. RACE_HISPANIC: only for 18+ olds
0: Non-hispanic
1: Hispanic
NaN: missing or N/A
f. YEARS_AFTERHIGH: calculated from education categories using discretion
1 -> 0.0 (Less than high school)
2 -> 0.0 (High school graduate)
3 -> 1.0 (Some college)
4 -> 2.0 (Vocational/technical training)
5 -> 2.0 (Associates degree)
6 -> 4.0 (Bachelor degree)
7 -> 6.0 (Graduate/post-graduate degree)
NaN -> missing or N/A
g. EMPLOYED:
0: Unemplyed (homemaker, retired, or not employed)
1: employed (full time, part time, self-employed, volunteer/intern)
h. STUDENT:
0: No
1: Yes (full time or part time student)
"""
ps = person_dat[[HOUSEHOLD_ID, PERSON_ID]].copy()
ps[AGE] = person[AGE].replace([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[2.0, 8.0, 13.5, 16.5, 21.0, 29.5, 39.5, 49.5, 59.5, 69.5, 79.5, 89.5])
ps[RACE_WHITE] = person[RACE_WHITE]
ps[RACE_BLACK] = person[RACE_BLACK]
ps[RACE_ASIAN] = person[RACE_ASIAN]
ps[RACE_HISPANIC] = person[RACE_HISPANIC]
ps[YEARS_AFTERHIGH] = person[EDUCATION].replace([1, 2, 3, 4, 5, 6, 7],
[0.0, 0.0, 1.0, 2.0, 2.0, 4.0, 6.0])
ps[EMPLOYED] = person[EMPLOYED].replace([1, 2, 3, 4, 5, 6, 7], [1, 1, 1, 1, 0, 0, 0])
ps[STUDENT] = person[STUDENT].replace([1, 2, 3], [0, 1, 1])
# Summarize personal level data to household level, by calculating means of each features
ps_household = ps.groupby([HOUSEHOLD_ID], as_index = False).agg(
{AGE: 'mean', RACE_WHITE: 'mean', YEARS_AFTERHIGH: 'mean',
RACE_BLACK: 'mean', RACE_ASIAN: 'mean', RACE_HISPANIC: 'mean',
EMPLOYED: 'mean', STUDENT: 'mean'})
# Rename the variables, as they are collapsed by averaging
ps_household.rename(columns={AGE: MEAN_AGE, RACE_WHITE: PROP_WHITE, RACE_BLACK: PROP_BLACK,
RACE_ASIAN: PROP_ASIAN, RACE_HISPANIC: PROP_HISPANIC,
YEARS_AFTERHIGH: YEAR_EDUCATION, EMPLOYED: PROP_EMPLOYED,
STUDENT: PROP_STUDENT, PERSON_ID: PERSON_COUNT}, inplace=True)
# merge person level data with household level
hh_plus_ps = pd.merge(left=hh_dat, right=ps_household, how='inner',
left_on=HOUSEHOLD_ID, right_on = HOUSEHOLD_ID)
return(hh_plus_ps)
|
5becaeb1141ad72a85128340d2c9f47e5899f0e9
| 34,452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.