id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1616025 | import numpy as np
from sklearn.model_selection import train_test_split
from utilities_test import get_data, \
get_feature_vector_from_mfcc
_DATA_PATH = '../korean_dataset'
_CLASS_LABELS = ("angry", "disappoint", "fear", "neutral", "sad", "surrender")
def extract_data(flatten):
data, labels = get_data(_DATA_PATH, class_labels=_CLASS_LABELS,
flatten=flatten)
x_train, x_test, y_train, y_test = train_test_split(
data,
labels,
test_size=0.2,
random_state=42)
return np.array(x_train), np.array(x_test), np.array(y_train), np.array(
y_test), len(_CLASS_LABELS)
def get_feature_vector(file_path, flatten):
return get_feature_vector_from_mfcc(file_path, flatten, mfcc_len=39)
| StarcoderdataPython |
73868 | <reponame>tupui/batman
# coding: utf8
"""
Refinement Class
================
This class defines all resampling strategies that can be used.
It implements the following methods:
- :func:`Refiner.func`
- :func:`Refiner.func_sigma`
- :func:`Refiner.pred_sigma`
- :func:`Refiner.distance_min`
- :func:`Refiner.hypercube`
- :func:`Refiner.sigma`
- :func:`Refiner.leave_one_out_sigma`
- :func:`Refiner.leave_one_out_sobol`
- :func:`Refiner.extrema`
- :func:`Refiner.hybrid`
- :func:`Refiner.optimization`
:Example::
>> corners = ((10, 400), (18, 450))
>> resample = Refiner(pod, corners)
>> new_point = resample.sigma()
"""
import logging
import copy
import warnings
from scipy.optimize import (differential_evolution, basinhopping)
from scipy.stats import norm
from scipy.spatial.distance import cdist
import numpy as np
from sklearn import preprocessing
import batman as bat
from .sampling import Doe
from ..misc import optimization
class Refiner:
"""Resampling the space of parameters."""
logger = logging.getLogger(__name__)
def __init__(self, data, corners, delta_space=0.08, discrete=None, pod=None):
"""Initialize the refiner with the Surrogate and space corners.
Points data are scaled between ``[0, 1]`` based on the size of the
corners taking into account a :param:``delta_space`` factor.
:param data: Surrogate or space
:type data: :class:`batman.surrogate.SurrogateModel` or
:class:`batman.space.Space`.
:param array_like corners: hypercube ([min, n_features], [max, n_features]).
:param float delta_space: Shrinking factor for the parameter space.
:param int discrete: index of the discrete variable.
:param pod: POD instance.
:type pod: :class:`batman.pod.Pod`.
"""
if isinstance(data, bat.surrogate.SurrogateModel):
self.surrogate = data
else:
max_points_nb = data.shape[0]
self.surrogate = bat.surrogate.SurrogateModel('kriging', data.corners, max_points_nb)
self.space = data
self.logger.debug("Using Space instance instead of SurrogateModel "
"-> restricted to discrepancy refiner")
self.pod_S = 1 if pod is None else pod.S
self.space = self.surrogate.space
self.points = copy.deepcopy(self.space[:])
self.discrete = discrete
self.corners = np.array(corners).T
self.dim = len(self.corners)
# Prevent delta space contraction on discrete
_dim = list(range(self.dim))
if self.discrete is not None:
_dim.pop(self.discrete)
# Inner delta space contraction: delta_space * 2 factor
for i in _dim:
self.corners[i, 0] = self.corners[i, 0] + delta_space\
* (self.corners[i, 1]-self.corners[i, 0])
self.corners[i, 1] = self.corners[i, 1] - delta_space\
* (self.corners[i, 1]-self.corners[i, 0])
# Data scaling
self.scaler = preprocessing.MinMaxScaler()
self.scaler.fit(self.corners.T)
self.points = self.scaler.transform(self.points)
def func(self, coords, sign=1):
r"""Get the prediction for a given point.
Retrieve Gaussian Process estimation. The function returns plus or
minus the function depending on the sign.
`-1` if we want to find the max and `1` if we want the min.
:param lst(float) coords: coordinate of the point
:param float sign: -1. or 1.
:return: L2 norm of the function at the point
:rtype: float
"""
f, _ = self.surrogate(coords)
modes_weights = np.array(self.pod_S ** 2).reshape(-1, 1)
sum_f = np.average(f, weights=modes_weights)
return sign * sum_f
def pred_sigma(self, coords):
"""Prediction and sigma.
Same as :func:`Refiner.func` and :func:`Refiner.func_sigma`.
Function prediction and sigma are weighted using POD modes.
:param lst(float) coords: coordinate of the point
:returns: sum_f and sum_sigma
:rtype: floats
"""
f, sigma = self.surrogate(coords)
modes_weights = np.array(self.pod_S ** 2).reshape(-1, 1)
sum_f = np.average(f, weights=modes_weights)
sum_sigma = np.average(sigma, weights=modes_weights)
return sum_f, sum_sigma
def distance_min(self, point):
"""Get the distance of influence.
Compute the Chebyshev distance, max Linf norm between the anchor point
and every sampling points. Linf allows to add this lenght to all
coordinates and ensure that no points will be within this hypercube.
It returns the minimal distance. :attr:`point` will be scaled by
:attr:`self.corners` so the returned distance is scaled.
:param array_like point: Anchor point.
:return: The distance to the nearest point.
:rtype: float.
"""
point = self.scaler.transform(point.reshape(1, -1))[0]
distances = cdist([point], self.points, 'chebyshev')[0]
# Do not get itself
distances = distances[np.nonzero(distances)]
distance = min(distances)
self.logger.debug("Distance min: {}".format(distance))
return distance
def hypercube_distance(self, point, distance):
"""Get the hypercube to add a point in.
Propagate the distance around the anchor.
:attr:`point` will be scaled by :attr:`self.corners` and input distance
has to be already scalled. Ensure that new values are bounded by
corners.
:param array_like point: Anchor point.
:param float distance: The distance of influence.
:return: The hypercube around the point.
:rtype: array_like.
"""
point = self.scaler.transform(point.reshape(1, -1))[0]
hypercube = np.array([point - distance, point + distance])
hypercube = self.scaler.inverse_transform(hypercube)
hypercube = hypercube.T
self.logger.debug("Prior Hypercube:\n{}".format(hypercube))
hypercube[:, 0] = np.minimum(hypercube[:, 0], self.corners[:, 1])
hypercube[:, 0] = np.maximum(hypercube[:, 0], self.corners[:, 0])
hypercube[:, 1] = np.minimum(hypercube[:, 1], self.corners[:, 1])
hypercube[:, 1] = np.maximum(hypercube[:, 1], self.corners[:, 0])
self.logger.debug("Post Hypercube:\n{}".format(hypercube))
return hypercube
def hypercube_optim(self, point):
"""Get the hypercube to add a point in.
Compute the largest hypercube around the point based on the *L2-norm*.
Ensure that only the *leave-one-out* point lies within it.
Ensure that new values are bounded by corners.
:param np.array point: Anchor point.
:return: The hypercube around the point (a point per column).
:rtype: array_like.
"""
distance = self.distance_min(point) * 0.99
x0 = self.hypercube_distance(point, distance).flatten('F')
point = np.minimum(point, self.corners[:, 1])
point = np.maximum(point, self.corners[:, 0])
point = self.scaler.transform(point.reshape(1, -1))[0]
gen = [p for p in self.points if not np.allclose(p, point)]
def min_norm(hypercube):
"""Compute euclidean distance.
:param np.array hypercube: [x1, y1, x2, y2, ...]
:return: distance of between hypercube points
:rtype: float
"""
hypercube = hypercube.reshape(2, self.dim)
try:
hypercube = self.scaler.transform(hypercube)
except ValueError: # If the hypercube is nan
return np.inf
# Sort coordinates
for i in range(self.dim):
hypercube[:, i] = hypercube[hypercube[:, i].argsort()][:, i]
hypercube = hypercube.T
diff = hypercube[:, 1] - hypercube[:, 0]
n = - np.linalg.norm(diff)
# Check aspect ratio
aspect = abs(diff)
with np.errstate(divide='ignore', invalid='ignore'):
aspect = abs(np.divide(np.power(np.max(aspect), self.dim),
np.prod(aspect)))
aspect = np.power(aspect, 1 / self.dim)
if not aspect <= 1.5:
return np.inf
# Verify that LOO point is inside
insiders = (hypercube[:, 0] <= point).all() & (point <= hypercube[:, 1]).all()
if not insiders:
return np.inf
# Verify that no other point is inside
insiders = np.array([True if (hypercube[:, 0] <= p).all() &
(p <= hypercube[:, 1]).all() else False
for p in gen]).any()
if insiders:
return np.inf
return n
bounds = np.reshape([self.corners] * 2, (self.dim * 2, 2))
# results = differential_evolution(min_norm, bounds, popsize=100)
minimizer_kwargs = {"method": "L-BFGS-B", "bounds": bounds}
results = basinhopping(min_norm, x0,
niter=1000, minimizer_kwargs=minimizer_kwargs)
hypercube = results.x.reshape(2, self.dim)
for i in range(self.dim):
hypercube[:, i] = hypercube[hypercube[:, i].argsort()][:, i]
hypercube = hypercube.T
self.logger.debug("Corners:\n{}".format(self.corners))
self.logger.debug("Optimization Hypercube:\n{}".format(hypercube))
return hypercube
def discrepancy(self):
"""Find the point that minimize the discrepancy.
:return: The coordinate of the point to add.
:rtype: lst(float).
"""
self.logger.debug("Discrepancy strategy")
init_discrepancy = bat.space.Space.discrepancy(self.space,
self.space.corners)
@optimization(self.corners, self.discrete)
def func_discrepancy(coords):
"""Discrepancy of the augmented space."""
sample = np.vstack([self.space[:], coords])
return bat.space.Space.discrepancy(sample)
min_x, new_discrepancy = func_discrepancy()
rel_change = (new_discrepancy - init_discrepancy) / init_discrepancy
self.logger.debug("Relative change in discrepancy: {}%".format(rel_change))
return min_x
def sigma(self, hypercube=None):
"""Find the point at max Sigma.
It returns the point where the variance (sigma) is maximum.
To do so, it uses Gaussian Process information.
A genetic algorithm get the global maximum of the function.
:param array_like hypercube: Corners of the hypercube.
:return: The coordinate of the point to add.
:rtype: lst(float).
"""
if hypercube is None:
hypercube = self.corners
self.logger.debug("Sigma strategy")
@optimization(hypercube, self.discrete)
def func_sigma(coords):
r"""Get the Sigma for a given point.
Retrieve Gaussian Process estimation of sigma.
A composite indicator is constructed using POD's modes.
.. math:: \sum S_i^2 \times \sigma_i
Function returns `- sum_sigma` in order to have a minimization
problem.
:param lst(float) coords: coordinate of the point.
:return: - sum_sigma.
:rtype: float.
"""
_, sigma = self.surrogate(coords)
sum_sigma = np.sum(self.pod_S ** 2 * sigma)
return - sum_sigma
min_x, _ = func_sigma()
return min_x
def leave_one_out_sigma(self, point_loo):
"""Mixture of Leave-one-out and Sigma.
Estimate the quality of the POD by *leave-one-out cross validation*
(LOOCV), and add a point arround the max error point.
The point is added within an hypercube around the max error point.
The size of the hypercube is equal to the distance with
the nearest point.
:param tuple point_loo: leave-one-out point.
:return: The coordinate of the point to add.
:rtype: lst(float).
"""
self.logger.info("Leave-one-out + Sigma strategy")
# Get the point of max error by LOOCV
point = np.array(point_loo)
# Construct the hypercube around the point
# distance = self.distance_min(point)
# hypercube = self.hypercube_distance(point, distance)
hypercube = self.hypercube_optim(point)
# Global search of the point within the hypercube
point = self.sigma(hypercube)
return point
def leave_one_out_sobol(self, point_loo, dists):
"""Mixture of Leave-one-out and Sobol' indices.
Same as function :func:`leave_one_out_sigma` but change the shape
of the hypercube. Using Sobol' indices, the corners are shrinked
by the corresponding percentage of the total indices.
:param tuple point_loo: leave-one-out point.
:param lst(str) dists: List of valid openturns distributions as string.
:return: The coordinate of the point to add.
:rtype: lst(float).
"""
self.logger.info("Leave-one-out + Sobol strategy")
# Get the point of max error by LOOCV
point = np.array(point_loo)
# Get Sobol' indices
analyse = bat.uq.UQ(self.surrogate, dists=dists)
indices = analyse.sobol()[2]
indices = indices * (indices > 0)
indices = preprocessing.normalize(indices.reshape(1, -1), norm='max')
# Prevent indices inferior to 0.1
indices[indices < 0.1] = 0.1
# Construct the hypercube around the point
hypercube = self.hypercube_optim(point)
# Modify the hypercube with Sobol' indices
for i in range(self.dim):
hypercube[i, 0] = hypercube[i, 0] + (1 - indices[0, i])\
* (hypercube[i, 1]-hypercube[i, 0]) / 2
hypercube[i, 1] = hypercube[i, 1] - (1 - indices[0, i])\
* (hypercube[i, 1]-hypercube[i, 0]) / 2
self.logger.debug("Post Hypercube:\n{}".format(hypercube))
# Global search of the point within the hypercube
point = self.sigma(hypercube)
return point
def extrema(self, refined_points):
"""Find the min or max point.
Using an anchor point based on the extremum value at sample points,
search the hypercube around it. If a new extremum is found,it uses
*Nelder-Mead* method to add a new point.
The point is then bounded back by the hypercube.
:return: The coordinate of the point to add
:rtype: lst(float)
"""
self.logger.info("Extrema strategy")
points = np.delete(self.points, refined_points, 0)
point = None
new_points = []
# Get max-max and max-min then min-max and min-min
for sign in [-1., 1.]:
self.logger.debug("Sign (-1 : Maximum ; 1 : Minimum) -> {}"
.format(sign))
# Get a sample point where there is an extrema around
while point is None:
# Get min or max point
evaluations = np.array([self.func(ref_point, sign)
for _, ref_point in enumerate(points)])
try:
min_idx = np.argmin(evaluations)
except ValueError:
point = True
break
point = points[min_idx]
point_eval = min(evaluations) * sign
self.logger.debug("Extremum located at sample point: {} -> {}"
.format(point, point_eval))
# Construct the hypercube around the point
distance = self.distance_min(point)
hypercube = self.hypercube_distance(point, distance)
# Global search of the point within the hypercube
first_extremum = differential_evolution(self.func,
hypercube,
args=(sign,))
first_extremum.fun *= sign
self.logger.debug("Optimization first extremum: {} -> {}"
.format(first_extremum.x,
first_extremum.fun))
second_extremum = differential_evolution(self.func,
hypercube,
args=(-sign,))
second_extremum.fun *= - sign
self.logger.debug("Optimization second extremum: {} -> {}"
.format(second_extremum.x,
second_extremum.fun))
# Check for new extrema, compare with the sample point
if sign * first_extremum.fun < sign * point_eval:
# Nelder-Mead expansion
first_extremum = np.array([first_extremum.x +
(first_extremum.x - point)])
# Constrain to the hypercube
first_extremum = np.maximum(first_extremum,
hypercube[:, 0])
first_extremum = np.minimum(first_extremum,
hypercube[:, 1])
new_points.append(first_extremum[0].tolist())
self.logger.debug("Extremum-max: {}"
.format(first_extremum[0]))
if sign * second_extremum.fun > sign * point_eval:
second_extremum = np.array([second_extremum.x +
(second_extremum.x - point)])
second_extremum = np.maximum(second_extremum,
hypercube[:, 0])
second_extremum = np.minimum(second_extremum,
hypercube[:, 1])
if (second_extremum != first_extremum).all():
new_points.append(second_extremum[0].tolist())
self.logger.debug("Extremum-min: {}"
.format(second_extremum[0]))
else:
self.logger.debug("Extremum-min egal: not added.")
else:
point = None
points = np.delete(points, min_idx, 0)
point = None
refined_points.append(min_idx)
return new_points, refined_points
def hybrid(self, refined_points, point_loo, method, dists):
"""Composite resampling strategy.
Uses all methods one after another to add new points.
It uses the navigator defined within settings file.
:param lst(int) refined_points: points idx not to consider for extrema
:param point_loo: leave one out point
:type point_loo: :class:`batman.space.point.Point`
:param str strategy: resampling method
:param lst(str) dists: List of valid openturns distributions as string.
:return: The coordinate of the point to add
:rtype: lst(float)
"""
self.logger.info(">>---Hybrid strategy---<<")
if method == 'sigma':
new_point = self.sigma()
elif method == 'sigma':
new_point = self.discrepancy()
elif method == 'loo_sigma':
new_point = self.leave_one_out_sigma(point_loo)
elif method == 'loo_sobol':
new_point = self.leave_one_out_sobol(point_loo, dists)
elif method == 'extrema':
new_point, refined_points = self.extrema(refined_points)
elif method == 'discrepancy':
new_point = self.discrepancy()
elif method == 'optimization':
new_point = self.optimization()
else:
self.logger.exception("Resampling method does't exits")
raise SystemExit
return new_point, refined_points
def optimization(self, method='EI', extremum='min'):
"""Maximization of the Probability/Expected Improvement.
:param str method: Flag ['EI', 'PI'].
:param str extremum: minimization or maximization objective
['min', 'max'].
:return: The coordinate of the point to add.
:rtype: lst(float).
"""
sign = 1 if extremum == 'min' else -1
gen = [self.func(x, sign=sign)
for x in self.scaler.inverse_transform(self.points)]
arg_min = np.argmin(gen)
min_value = gen[arg_min]
min_x = self.points[arg_min]
self.logger.info('Current extrema value is: f(x)={} for x={}'
.format(sign * min_value, min_x))
# Do not check point is close on the discrete parameter
if self.discrete is not None:
no_discrete = [list(range(self.points.shape[1]))]
no_discrete[0].pop(self.discrete)
else:
no_discrete = None
@optimization(self.corners, self.discrete)
def probability_improvement(x):
"""Do probability of improvement."""
x_scaled = self.scaler.transform(x.reshape(1, -1))
too_close = np.array([True if np.linalg.norm(
x_scaled[0][no_discrete] - p[no_discrete], -1) < 0.02
else False for p in self.points]).any()
if too_close:
return np.inf
pred, sigma = self.pred_sigma(x)
pred = sign * pred
std_dev = np.sqrt(sigma)
pi = norm.cdf((target - pred) / std_dev)
return - pi
@optimization(self.corners, self.discrete)
def expected_improvement(x):
"""Do expected improvement."""
x_scaled = self.scaler.transform(x.reshape(1, -1))
too_close = np.array([True if np.linalg.norm(
x_scaled[0][no_discrete] - p[no_discrete], -1) < 0.02
else False for p in self.points]).any()
if too_close:
return np.inf
pred, sigma = self.pred_sigma(x)
pred = sign * pred
std_dev = np.sqrt(sigma)
diff = min_value - pred
ei = diff * norm.cdf(diff / std_dev)\
+ std_dev * norm.pdf(diff / std_dev)
return - ei
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if method == 'PI':
target = min_value - 0.1 * np.abs(min_value)
max_ei, _ = probability_improvement()
else:
max_ei, _ = expected_improvement()
return max_ei
def sigma_discrepancy(self, weights=None):
"""Maximization of the composite indicator: sigma - discrepancy.
:param list(float) weights: respectively weights of sigma and discrepancy.
:return: The coordinate of the point to add.
:rtype: lst(float).
"""
weights = [0.5, 0.5] if weights is None else weights
doe = Doe(500, self.corners, 'halton')
sample = doe.generate()
_, sigma = zip(*[self.pred_sigma(s) for s in sample])
disc = [1 / bat.space.Space.discrepancy(np.vstack([self.space, p]),
self.space.corners)
for p in sample]
sigma = np.array(sigma).reshape(-1, 1)
disc = np.array(disc).reshape(-1, 1)
scale_sigma = preprocessing.StandardScaler().fit(sigma)
scale_disc = preprocessing.StandardScaler().fit(disc)
@optimization(self.corners, self.discrete)
def f_obj(x):
"""Maximize the inverse of the discrepancy plus sigma."""
_, sigma = self.pred_sigma(x)
sigma = scale_sigma.transform(sigma.reshape(1, -1))
disc = 1 / bat.space.Space.discrepancy(np.vstack([self.space, x]),
self.space.corners)
disc = scale_disc.transform(disc.reshape(1, -1))
sigma_disc = sigma * weights[0] + disc * weights[1]
return - sigma_disc
max_sigma_disc, _ = f_obj()
return max_sigma_disc
| StarcoderdataPython |
101566 | '''Container module that instantiate classes to accomplish IoC role'''
from templatizator.domain.repository import ConfigurationRepository, \
VariableRepository, TemplateRepository, TemplateFileRepository, \
ConfigurableRepository, ConfigurableFileRepository
from templatizator.domain.service import ProjectService, \
ConfigurationService, VariableService, TemplateService, ConfigurableService
from templatizator.domain.application import ProjectApplication, \
VariableApplication, TemplateApplication, ConfigurableFileApplication
from templatizator.domain.helper import Event
# pylint: disable=too-few-public-methods
class Container:
'''Static container class that holds the important instances available
for presentation layer
'''
def __init__(self):
raise Exception('Static class is not instantiable')
@staticmethod
def configure():
'''Instantiate events, and DDD layers'''
# events
project_changed_event = Event()
configuration_changed_event = Event()
# repository layer
configuration_repository = ConfigurationRepository()
variable_repository = VariableRepository()
template_repository = TemplateRepository()
template_file_repository = TemplateFileRepository()
configurable_repository = ConfigurableRepository()
configurable_file_repository = ConfigurableFileRepository()
# service layer
# the order affects the event subscribe and publish into the services
variable_service = VariableService(
variable_repository,
project_changed_event
)
template_service = TemplateService(
template_repository,
template_file_repository,
project_changed_event
)
configurable_service = ConfigurableService(
configurable_repository,
configurable_file_repository,
project_changed_event
)
project_service = ProjectService(
configuration_repository, variable_repository, template_repository,
configurable_repository, template_file_repository,
configurable_file_repository, configuration_changed_event,
project_changed_event
)
configuration_service = ConfigurationService(
configuration_repository,
configuration_changed_event
)
# application layer
Container.project_application = ProjectApplication(
project_service,
configuration_service
)
Container.variable_application = VariableApplication(variable_service)
Container.template_application = TemplateApplication(template_service)
Container.configurable_file_application = ConfigurableFileApplication(
configurable_service
)
| StarcoderdataPython |
1624779 | <filename>src/sysinfo.py
#!/usr/bin/env python3
""" sysinfo.py: Collection of classes to read Linux system information. """
__author__ = '<NAME>'
__copyright__ = '(C) 2019 ' + __author__
__license__ = "MIT"
__version__ = '1.0.0'
from collections import namedtuple
from datetime import timedelta
import os
import pwd
class SystemInfoError(Exception):
"""Raised when error occur during system information access"""
pass
class Cpu:
"""
Calculates CPU usage based on /proc/stat file data
Class retrieves CPU statistics from /proc/stat file and provides public
methods for easy access to CPU usage.
Attributes:
update(): Retrieves fresh CPU statistics.
cpu_usage: List of CPUs usage per CPU measured between last two update() calls.
.. PROC(5)
http://man7.org/linux/man-pages/man5/proc.5.html
"""
CpuStat = namedtuple('CpuStat', ['name', 'user', 'nice', 'system', 'idle', 'iowait',
'irq', 'softirq', 'steal', 'guest', 'guest_nice'])
def __init__(self):
self.prev_stat = Cpu._read_file()
self.curr_stat = self.prev_stat
def update(self):
""" Retrieves fresh CPU statistics and stores previous statistics. """
self.prev_stat = self.curr_stat
self.curr_stat = Cpu._read_file()
@property
def cpu_usage(self) -> list:
""":obj:`list` of :obj:`float`: List of CPU usage per CPU measured between last two update() calls."""
cpu_usage = []
for prev, new in zip(self.prev_stat, self.curr_stat):
idle_prev = prev.idle + prev.iowait
non_idle_prev = prev.user + prev.nice + prev.system + prev.irq + prev.softirq + prev.steal
total_prev = idle_prev + non_idle_prev
idle_new = new.idle + new.iowait
non_idle_new = new.user + new.nice + new.system + new.irq + new.softirq + new.steal
total_new = idle_new + non_idle_new
total_diff = total_new - total_prev
idle_diff = idle_new - idle_prev
if total_diff <= 0:
cpu_usage.append(0.0)
continue
cpu_usage_pct = (total_diff - idle_diff) * 100 / total_diff
cpu_usage.append(cpu_usage_pct)
return cpu_usage
@staticmethod
def _read_file() -> list:
lst = []
with open('/proc/stat') as file:
for line in file:
if line.startswith('cpu '):
continue
elif line.startswith('cpu'):
name, *values = line.split()
values = map(int, values)
temp_tuple = Cpu.CpuStat(name, *values)
lst.append(temp_tuple)
if not lst:
raise SystemInfoError('Cannot parse /proc/stat file')
return lst
class LoadAverage:
"""
The load average over 1, 5, and 15 minutes.
Class holds load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O
(state D) averaged over 1, 5, and 15 minutes.
Attributes:
update(): Retrieves actual load average value from /proc/loadavg.
load_average: Returns load average over 1, 5, and 15 minutes.
load_average_as_string: Returns load average as a formatted string 'x.xx x.xx x.xx'.
.. PROC(5)
http://man7.org/linux/man-pages/man5/proc.5.html
"""
def __init__(self):
self._load_average = LoadAverage._read_file()
def update(self):
"""Retrieves actual load average value from /proc/loadavg."""
self._load_average = LoadAverage._read_file()
@staticmethod
def _read_file():
with open('/proc/loadavg') as file:
try:
t1, t5, t15, *_ = file.read().split()
values = map(float, [t1, t5, t15])
return tuple(values)
except (ValueError, TypeError):
raise SystemInfoError('Cannot parse /proc/loadavg file')
# TODO(AOS): change load_average to field from property
@property
def load_average(self):
""":obj:`tuple` of :obj:`float`: Returns load average over 1, 5, and 15 minutes."""
return self._load_average
@property
def load_average_as_string(self):
""":obj:`str`: Returns load average as a formatted string 'x.xx x.xx x.xx'."""
return f"{self._load_average[0]} {self._load_average[1]} {self._load_average[2]}"
class Uptime:
"""
The uptime of the system
Class holds system uptime (including time spent in suspend) fetched from /proc/uptime file.
Attributes:
update(): Retrieves actual uptime value from /proc/uptime.
uptime: Returns system uptime (including time spent in suspend) in seconds.
uptime_as_string: Returns uptime as a formatted string 'dd hh:mm:ss'
.. PROC(5)
http://man7.org/linux/man-pages/man5/proc.5.html
"""
def __init__(self):
self._uptime = Uptime._read_file()
def update(self):
"""Retrieves actual uptime value from /proc/uptime."""
self._uptime = Uptime._read_file()
@staticmethod
def _read_file():
with open('/proc/uptime') as file:
try:
value = file.read().split()[0]
return int(float(value))
except (IndexError, ValueError, TypeError):
raise SystemInfoError('Cannot parse /proc/uptime file')
@property
def uptime(self):
""":obj:`int`: Returns system uptime (including time spent in suspend) in seconds."""
return self._uptime
@property
def uptime_as_string(self):
""":obj:`str`: Returns uptime as a formatted string 'dd hh:mm:ss'"""
uptime = timedelta(seconds=self._uptime)
return f"{uptime}"
class MemInfo:
"""
Information about memory usage, both physical and swap.
Class retrieves statistics about memory usage on the system and provides public
properties for easy access to the amount of free and used memory (both physical and swap).
Attributes:
update(): Retrieves actual memory statistics from /proc/meminfo.
total_memory(): Returns total amount of RAM space available.
used_memory(): Returns amount of RAM space that is currently used.
total_swap(): Returns total amount of swap space available.
used_swap(): Returns amount of swap space that is currently used.
.. PROC(5)
http://man7.org/linux/man-pages/man5/proc.5.html
"""
def __init__(self):
self._total_memory = None
self._used_memory = None
self._total_swap = None
self._used_swap = None
self.update()
def update(self):
"""Retrieves actual memory information from /proc/meminfo.
.. Stackoverflow htop author explanation
https://stackoverflow.com/a/41251290
"""
info = MemInfo._read_file()
try:
self._total_memory = info['MemTotal']
# See link for calculation explanation
used_memory = info['MemTotal'] - info['MemFree'] - info['Buffers'] - info['Cached'] - \
info['SReclaimable'] + info['Shmem']
self._used_memory = used_memory
self._total_swap = info['SwapTotal']
self._used_swap = info['SwapTotal'] - info['SwapFree']
except KeyError:
raise SystemInfoError('Cannot parse /proc/meminfo file')
@property
def total_memory(self):
""":obj:'int': Returns total amount of RAM space available."""
return self._total_memory
@property
def used_memory(self):
""":obj:'int': Returns amount of RAM space that is currently used."""
return self._used_memory
@property
def total_swap(self):
""":obj:'int': Returns total amount of swap space available."""
return self._total_swap
@property
def used_swap(self):
""":obj:'int': Returns amount of swap space that is currently used."""
return self._used_swap
@staticmethod
def _read_file():
meaningful_fields = ['MemTotal', 'MemFree', 'Buffers', 'Cached', 'SReclaimable',
'Shmem', 'SwapTotal', 'SwapFree']
values = {}
with open('/proc/meminfo') as file:
for line in file:
try:
field, value, *unit = line.split()
name = field[:-1]
if name in meaningful_fields:
values[name] = int(value)
except (IndexError, ValueError, TypeError):
raise SystemInfoError('Cannot parse /proc/meminfo file')
return values
class Process:
"""
Information about running process with PID.
Class retrieves all statistics (state, niceness, priority, user, time, memory and cpu usage)
for a running process and provides public properties for easy access.
Example:
>>> Process.set_uptime(obj) # requires object with uptime attribute holding actual uptime
>>> Process.set_memory_info(value) # requires to set memory size
>>> proc = Process(4)
>>> proc.pid, proc.priority, proc.niceness
(1, 20, 0)
Attributes:
update(): Retrieves actual process statistics from /proc/[pid]/ subdirectory.
pid: process PID
user: process user
priority: process kernel-space priority
niceness: process user-space niceness
virtual_memory: virtual memory requested by process
resident_memory: resident memory usage (currently being used)
shared_memory: shared memory used
state: process state
cpu_usage: percentage of CPU time process is currently using
memory_usage: task's current share of the phisical memory
time(): returns processor time used by process
command: command that launched process
.. PROC(5)
http://man7.org/linux/man-pages/man5/proc.5.html
"""
_proc_folder = '/proc'
_clock_ticks_per_second = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
_uptime = None
_total_memory = None
def __init__(self, pid):
self.pid = pid
self.user = None
self.priority = None
self.niceness = None
self.virtual_memory = 0 # memory must be initialized with 0
self.resident_memory = 0
self.shared_memory = 0
self.state = None
self.cpu_usage = 0.0
self.memory_usage = 0.0
self._time = 0.0
self.command = ''
self._time_ticks_old = None
self._uptime_old = None
self.kthread = False # TODO(AOS) What for?
self.update()
def update(self):
"""Retrieves actual process statistics from /proc/[pid]/ subdirectory."""
try:
self._read_cmdline()
self._read_stat()
self._read_status()
except (ValueError, IndexError):
raise SystemInfoError('Error while parsing /proc/[pid]/ subdirectory')
def _read_cmdline(self):
filename = f'{Process._proc_folder}/{self.pid}/cmdline'
with open(filename, 'r') as file:
self.command = Process._remove_whitespaces(file.read())
def _read_stat(self):
filename = f'{Process._proc_folder}/{self.pid}/stat'
with open(filename, 'r') as file:
values = ['Reserved']
values += file.read().split()
if not self.command:
self.command = Process._remove_whitespaces(values[2][1:-1])
self.kthread = True if int(values[9]) & 0x00200000 else False
self.priority = values[18]
self.niceness = values[19]
time_ticks = sum(map(int, values[14:18]))
uptime = Process._uptime.uptime
if self._time_ticks_old is None:
self._time_ticks_old = time_ticks
if self._uptime_old is None:
self._uptime_old = uptime
seconds = uptime - self._uptime_old
if seconds <= 0:
self.cpu_usage = 0.0
else:
ticks_diff = time_ticks - self._time_ticks_old
self.cpu_usage = 100 * ((ticks_diff / self._clock_ticks_per_second) / seconds)
self._time_ticks_old = time_ticks
self._uptime_old = uptime
process_time_ticks = int(values[14]) + int(values[15])
self._time = process_time_ticks / self._clock_ticks_per_second
def _read_status(self):
filename = f'{Process._proc_folder}/{self.pid}/status'
status = {}
with open(filename, 'r') as file:
for line in file:
temp = line.split()
name = temp[0][:-1]
if name in ('Name', 'State'):
status[name] = temp[1]
if name in ('Uid', 'VmSize', 'VmRSS', 'RssShmem'):
status[name] = int(temp[1])
# mandatory properties raise exception
if not self.command:
self.command = status['Name']
self.state = status['State']
user_id = status['Uid']
# self.user = pwd.getpwuid( int(user_id)).pw_name # TODO(AOS) Pycharm creates local environment where there are no other user
# optional properties
self.virtual_memory = status.get('VmSize', 0)
self.resident_memory = status.get('VmRSS', 0)
self.shared_memory = status.get('RssShmem', 0)
memory_usage = self.resident_memory * 100 / Process._total_memory
self.memory_usage = round(memory_usage, 1)
@property
def time(self):
""":obj:'str': Returns processor time used by process."""
d = timedelta(seconds=float(self._time))
hours, remainder = divmod(d.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
if hours > 0.0:
return '%dh%d:%d' % (int(hours), int(minutes), int(seconds))
else:
return '%.0f:%05.2f' % (minutes, seconds)
@staticmethod
def set_uptime(obj):
"""Process class requires object with uptime attribute holding actual uptime"""
Process._uptime = obj
@staticmethod
def set_memory_info(total_memory):
"""Process class requires to know total RAM size (int value)"""
Process._total_memory = total_memory
@staticmethod
def _remove_whitespaces(string):
return string.replace('\x00', ' ').rstrip()
class ProcessesController:
# TODO(AOS) Add docstrings
_proc_folder = '/proc/'
def __init__(self, uptime, memory):
self._processes = set()
self._previous_procceses = set()
Process.set_uptime(uptime)
Process.set_memory_info(memory)
self.update()
def update(self):
actual_processes = {name for name in os.listdir(ProcessesController._proc_folder)
if os.path.isdir(ProcessesController._proc_folder + name) and name.isdigit()}
obsolete = self._previous_procceses - actual_processes
new = actual_processes - self._previous_procceses
for process in self._processes:
if process.name in obsolete:
del process
for pid in new:
self._processes.add(Process(pid))
self._previous_procceses = actual_processes
@property
def processes(self):
return self._processes
@property
def proccesses_number(self):
return len(self._processes)
@property
def processes_pid(self):
return [int(process.pid) for process in self._processes]
class Utility:
"""
Class provides utility methods.
Attributes:
kb_to_xb(): Converts memory size in kB into string representation.
"""
@staticmethod
def kb_to_xb(kb):
"""Converts memory size in kB into string representation."""
if not isinstance(kb, int):
raise TypeError
if kb < 100 * 1024:
return f'{kb}'
elif kb < 1024 * 1024:
return f'{kb // 1024}M'
else:
return f'{kb // (1024 * 1024)}G'
| StarcoderdataPython |
1772870 | <filename>cla_public/libs/api_proxy.py<gh_stars>1-10
# coding: utf-8
"""Decorator for API proxy views"""
import functools
import json
import logging
from requests.exceptions import ConnectTimeout, ReadTimeout
TIMEOUT_RESPONSE = json.dumps({"error": "Request timeout."})
log = logging.getLogger(__name__)
def on_timeout(response=TIMEOUT_RESPONSE):
"Decorator for view functions which proxy API calls"
def view(view_func):
"Wrapped view function"
@functools.wraps(view_func)
def wrapper(*args, **kwargs):
"Wraps the view function with API timeout handling"
try:
return view_func(*args, **kwargs)
except ConnectTimeout as conn_exception:
log.exception("Connection timeout for API: %s", conn_exception)
except ReadTimeout as read_exception:
log.exception("Read timeout for API: %s", read_exception)
return response
return wrapper
return view
| StarcoderdataPython |
1716202 | <reponame>scpwiki/2stacks
import json
import config
import helpers
import requests
from time import sleep
from xmlrpc.client import ServerProxy
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
for record in event['Records']:
callback_url = record['messageAttributes']['callback_url']['stringValue']
slugs = record['messageAttributes']['page_slug']['stringValue'].split(',')
wikidot_site = record['messageAttributes']['wikidot_site']['stringValue']
# A typical payload has 100 slugs. We're going to make a pages.get_one request for each slug so we get the most recent revision data as well as the other metadata stuff.
for slug in slugs:
# Hit Wikidot's API
s = ServerProxy('https://' + config.wikidot_username + ':' + config.wikidot_api_key + '@www.wikidot.com/xml-rpc-api.php')
wp = s.pages.get_one({'site': wikidot_site, 'page': slug})
logger.info(wp)
# Be Nice
sleep(0.25)
# Send all this stuff to SCUTTLE to sort through.
output = json.dumps(wp)
# logger.info(output)
headers = {"Authorization": "Bearer " + config.scuttle_token, "Content-Type": "application/json"}
r = requests.put(callback_url + '/2stacks/scheduled/page/metadata', data=output, headers=headers)
return {
'job': 'complete'
}
| StarcoderdataPython |
3212352 | <gh_stars>0
import asyncio
import PIL
from PIL import ImageTk, Image
import tkinter
import traceback
from common import ROOM_HEIGHT_IN_TILES, ROOM_WIDTH_IN_TILES, TILE_SIZE
from .util import tile_to_text, ScrollableFrame
# The DROD room size is 836x704, use half that for canvas to preserve aspect ratio
_CANVAS_WIDTH = 418
_CANVAS_HEIGHT = 352
_LARGE_CANVAS_WIDTH = 836
_LARGE_CANVAS_HEIGHT = 704
class InterpretScreenApp(tkinter.Frame):
"""This app is used to debug the interpretation of the screenshots.
It takes screenshots and shows them at specified steps in the image
processing process.
Parameters
----------
root
The parent of the tkinter Frame.
event_loop
The asyncio event loop for the backend thread.
backend
The backend that contains the play interface.
"""
def __init__(self, root, event_loop, backend):
super().__init__(root)
self._event_loop = event_loop
self._backend = backend
self._selected_view_step = tkinter.StringVar(self)
self._enlarged_view = False
self._debug_images = None
self._radio_buttons = []
self._room = None
# Create widgets
self._canvas = tkinter.Canvas(
self, width=_CANVAS_WIDTH, height=_CANVAS_HEIGHT, bg="white"
)
self._canvas.bind("<Button-1>", self._clicked_canvas)
self._canvas.pack(side=tkinter.LEFT)
self._control_panel = tkinter.Frame(self)
self._control_panel.pack(side=tkinter.RIGHT)
self._tile_content = tkinter.Label(self._control_panel, text="")
self._tile_content.pack(side=tkinter.TOP)
self._room_text = tkinter.Label(self._control_panel, text="")
self._room_text.pack(side=tkinter.TOP)
self._get_view_buttons = tkinter.Frame(self._control_panel)
self._get_view_buttons.pack(side=tkinter.TOP)
self._get_view_button = tkinter.Button(
self._get_view_buttons, text="Get view", command=self._get_view
)
self._get_view_button.pack(side=tkinter.LEFT)
self._move_then_get_view_button = tkinter.Button(
self._get_view_buttons,
text="Move E, get view",
command=self._move_then_get_view,
)
self._move_then_get_view_button.pack(side=tkinter.LEFT)
self._toggle_view_size_button = tkinter.Button(
self._control_panel, text="Enlarge view", command=self._toggle_view_size
)
self._toggle_view_size_button.pack(side=tkinter.TOP)
self._debug_step_frame = ScrollableFrame(self._control_panel)
self._debug_step_frame.pack(side=tkinter.TOP)
self._set_debug_steps()
def set_data(self, debug_images, room, room_text):
"""Set the data to show in the app.
Parameters
----------
debug_images
A list of (name, image) pairs.
room
The room interpreted from the screenshot.
room_text
The text that popped up when entering the room.
"""
self._debug_images = debug_images
self._room = room
self._room_text.config(text=f"Room text: {room_text.value}")
self._set_debug_steps()
self._draw_view()
def _set_debug_steps(self):
debug_steps = (
[name for name, image in self._debug_images]
if self._debug_images is not None
else ["Screenshot"]
)
if self._selected_view_step.get() not in debug_steps:
self._selected_view_step.set("Screenshot")
for radio_button in self._radio_buttons:
radio_button.pack_forget()
self._radio_buttons = [
tkinter.Radiobutton(
self._debug_step_frame.scrollable_frame,
text=step,
value=step,
variable=self._selected_view_step,
command=self._draw_view,
)
for step in debug_steps
]
for radio_button in self._radio_buttons:
radio_button.pack(side=tkinter.TOP)
def _draw_view(self):
if self._debug_images is not None:
step = self._selected_view_step.get()
image = next(image for name, image in self._debug_images if name == step)
pil_image = PIL.Image.fromarray(image)
resized_image = pil_image.resize(
(int(self._canvas["width"]), int(self._canvas["height"])), Image.NEAREST
)
# Assign to self._view to prevent from being garbage collected
self._view = ImageTk.PhotoImage(image=resized_image)
self._canvas.create_image(0, 0, image=self._view, anchor=tkinter.NW)
def _run_coroutine(self, coroutine):
async def wrapped_coroutine():
try:
await coroutine
except Exception:
traceback.print_exc()
asyncio.run_coroutine_threadsafe(wrapped_coroutine(), self._event_loop)
def _get_view(self):
self._run_coroutine(self._backend.get_view())
def _move_then_get_view(self):
self._run_coroutine(self._backend.move_then_get_view())
def _toggle_view_size(self):
if self._enlarged_view:
self._enlarged_view = False
self._canvas.configure(height=_CANVAS_HEIGHT, width=_CANVAS_WIDTH)
self._toggle_view_size_button.configure(text="Enlarge view")
self._draw_view()
else:
self._enlarged_view = True
self._canvas.configure(
height=_LARGE_CANVAS_HEIGHT, width=_LARGE_CANVAS_WIDTH
)
self._toggle_view_size_button.configure(text="Ensmall view")
self._draw_view()
def _clicked_canvas(self, event):
if self._enlarged_view:
x = event.x // TILE_SIZE
y = event.y // TILE_SIZE
else:
x = event.x // (TILE_SIZE // 2)
y = event.y // (TILE_SIZE // 2)
step = self._selected_view_step.get()
image = next(image for name, image in self._debug_images if name == step)
if image.shape == (
ROOM_HEIGHT_IN_TILES * TILE_SIZE,
ROOM_WIDTH_IN_TILES * TILE_SIZE,
3,
):
tile = self._room.get_tile((x, y))
self._tile_content.config(text=tile_to_text(tile))
elif step == "Extract minimap":
color = next(
image for name, image in self._debug_images if name == "Extract minimap"
)[y, x, :]
self._tile_content.config(text=str(color))
| StarcoderdataPython |
3232078 | #!/usr/bin/env python3
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Create Cloud Trace Service Tracker
"""
import openstack
openstack.enable_logging(True)
conn = openstack.connect(cloud='otc')
attrs = {
"bucket_name": "cloudtraceservice",
"file_prefix_name": "file-",
"lts": {
"is_lts_enabled": True,
"log_group_name": "CTS",
"log_topic_name": "system-trace",
"log_group_id": "1186622b-78ec-11ea-997c-286ed488c87f",
"log_topic_id": "751f0409-78ec-11ea-90c7-286ed488c880"
},
"status": "enabled",
"tracker_name": "system",
"detail": ""
}
tracker = conn.cts.create_tracker(**attrs)
print(tracker)
| StarcoderdataPython |
1609137 | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import json
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import InvalidNonce
class bitz (Exchange):
def describe(self):
return self.deep_extend(super(bitz, self).describe(), {
'id': 'bitz',
'name': 'Bit-Z',
'countries': 'HK',
'rateLimit': 1000,
'version': 'v1',
'userAgent': self.userAgents['chrome'],
'has': {
'fetchTickers': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'1d': '1d',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/35862606-4f554f14-0b5d-11e8-957d-35058c504b6f.jpg',
'api': 'https://www.bit-z.com/api_v1',
'www': 'https://www.bit-z.com',
'doc': 'https://www.bit-z.com/api.html',
'fees': 'https://www.bit-z.com/about/fee',
},
'api': {
'public': {
'get': [
'ticker',
'tickerall',
'depth',
'orders',
'kline',
],
},
'private': {
'post': [
'balances',
'tradeAdd',
'tradeCancel',
'openOrders',
],
},
},
'fees': {
'trading': {
'maker': 0.001,
'taker': 0.001,
},
'funding': {
'withdraw': {
'BTC': '0.5%',
'DKKT': '0.5%',
'ETH': 0.01,
'USDT': '0.5%',
'LTC': '0.5%',
'FCT': '0.5%',
'LSK': '0.5%',
'HXI': '0.8%',
'ZEC': '0.5%',
'DOGE': '0.5%',
'MZC': '0.5%',
'ETC': '0.5%',
'GXS': '0.5%',
'XPM': '0.5%',
'PPC': '0.5%',
'BLK': '0.5%',
'XAS': '0.5%',
'HSR': '0.5%',
'NULS': 5.0,
'VOISE': 350.0,
'PAY': 1.5,
'EOS': 0.6,
'YBCT': 35.0,
'OMG': 0.3,
'OTN': 0.4,
'BTX': '0.5%',
'QTUM': '0.5%',
'DASH': '0.5%',
'GAME': '0.5%',
'BCH': '0.5%',
'GNT': 9.0,
'SSS': 1500.0,
'ARK': '0.5%',
'PART': '0.5%',
'LEO': '0.5%',
'DGB': '0.5%',
'ZSC': 130.0,
'VIU': 350.0,
'BTG': '0.5%',
'ARN': 10.0,
'VTC': '0.5%',
'BCD': '0.5%',
'TRX': 200.0,
'HWC': '0.5%',
'UNIT': '0.5%',
'OXY': '0.5%',
'MCO': 0.3500,
'SBTC': '0.5%',
'BCX': '0.5%',
'ETF': '0.5%',
'PYLNT': 0.4000,
'XRB': '0.5%',
'ETP': '0.5%',
},
},
},
'precision': {
'amount': 8,
'price': 8,
},
'options': {
'lastNonceTimestamp': 0,
},
})
def fetch_markets(self):
response = self.publicGetTickerall()
markets = response['data']
ids = list(markets.keys())
result = []
for i in range(0, len(ids)):
id = ids[i]
market = markets[id]
baseId, quoteId = id.split('_')
base = baseId.upper()
quote = quoteId.upper()
base = self.common_currency_code(base)
quote = self.common_currency_code(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': True,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostBalances(params)
data = response['data']
balances = self.omit(data, 'uid')
result = {'info': response}
keys = list(balances.keys())
for i in range(0, len(keys)):
id = keys[i]
idHasUnderscore = (id.find('_') >= 0)
if not idHasUnderscore:
code = id.upper()
if id in self.currencies_by_id:
code = self.currencies_by_id[id]['code']
account = self.account()
usedField = id + '_lock'
account['used'] = self.safe_float(balances, usedField)
account['total'] = self.safe_float(balances, id)
account['free'] = account['total'] - account['used']
result[code] = account
return self.parse_balance(result)
def parse_ticker(self, ticker, market=None):
timestamp = ticker['date'] * 1000
symbol = market['symbol']
last = float(ticker['last'])
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'bidVolume': None,
'ask': float(ticker['sell']),
'askVolume': None,
'vwap': None,
'open': None,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['vol']),
'quoteVolume': None,
'info': ticker,
}
def fetch_ticker(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTicker(self.extend({
'coin': market['id'],
}, params))
return self.parse_ticker(response['data'], market)
def fetch_tickers(self, symbols=None, params={}):
self.load_markets()
response = self.publicGetTickerall(params)
tickers = response['data']
result = {}
ids = list(tickers.keys())
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_ticker(tickers[id], market)
return result
def fetch_order_book(self, symbol, limit=None, params={}):
self.load_markets()
response = self.publicGetDepth(self.extend({
'coin': self.market_id(symbol),
}, params))
orderbook = response['data']
timestamp = orderbook['date'] * 1000
return self.parse_order_book(orderbook, timestamp)
def parse_trade(self, trade, market=None):
hkt = self.sum(self.milliseconds(), 28800000)
utcDate = self.iso8601(hkt)
utcDate = utcDate.split('T')
utcDate = utcDate[0] + ' ' + trade['t'] + '+08'
timestamp = self.parse8601(utcDate)
price = float(trade['p'])
amount = float(trade['n'])
symbol = market['symbol']
cost = self.price_to_precision(symbol, amount * price)
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'id': None,
'order': None,
'type': 'limit',
'side': trade['s'],
'price': price,
'amount': amount,
'cost': cost,
'fee': None,
'info': trade,
}
def fetch_trades(self, symbol, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetOrders(self.extend({
'coin': market['id'],
}, params))
trades = response['data']['d']
return self.parse_trades(trades, market, since, limit)
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetKline(self.extend({
'coin': market['id'],
'type': self.timeframes[timeframe],
}, params))
ohlcv = json.loads(response['data']['datas']['data'])
return self.parse_ohlcvs(ohlcv, market, timeframe, since, limit)
def parse_order(self, order, market=None):
symbol = None
if market is not None:
symbol = market['symbol']
side = self.safe_string(order, 'side')
if side is None:
side = self.safe_string(order, 'type')
if side is not None:
side = 'buy' if (side == 'in') else 'sell'
timestamp = None
iso8601 = None
if 'datetime' in order:
timestamp = self.parse8601(order['datetime'])
iso8601 = self.iso8601(timestamp)
return {
'id': order['id'],
'datetime': iso8601,
'timestamp': timestamp,
'status': 'open',
'symbol': symbol,
'type': 'limit',
'side': side,
'price': order['price'],
'cost': None,
'amount': order['number'],
'filled': None,
'remaining': None,
'trades': None,
'fee': None,
'info': order,
}
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
orderType = 'in' if (side == 'buy') else 'out'
request = {
'coin': market['id'],
'type': orderType,
'price': self.price_to_precision(symbol, price),
'number': self.amount_to_string(symbol, amount),
'tradepwd': self.password,
}
response = self.privatePostTradeAdd(self.extend(request, params))
id = response['data']['id']
order = self.parse_order({
'id': id,
'price': price,
'number': amount,
'side': side,
}, market)
self.orders[id] = order
return order
def cancel_order(self, id, symbol=None, params={}):
self.load_markets()
response = self.privatePostTradeCancel(self.extend({
'id': id,
}, params))
return response
def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privatePostOpenOrders(self.extend({
'coin': market['id'],
}, params))
return self.parse_orders(response['data'], market, since, limit)
def nonce(self):
currentTimestamp = self.seconds()
if currentTimestamp > self.options['lastNonceTimestamp']:
self.options['lastNonceTimestamp'] = currentTimestamp
self.options['lastNonce'] = 100000
self.options['lastNonce'] += 1
return self.options['lastNonce']
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + path
query = None
if api == 'public':
query = self.urlencode(params)
if len(query):
url += '?' + query
else:
self.check_required_credentials()
body = self.urlencode(self.keysort(self.extend({
'api_key': self.apiKey,
'timestamp': self.seconds(),
'nonce': self.nonce(),
}, params)))
body += '&sign=' + self.hash(self.encode(body + self.secret))
headers = {'Content-type': 'application/x-www-form-urlencoded'}
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
response = self.fetch2(path, api, method, params, headers, body)
code = self.safe_string(response, 'code')
if code != '0':
ErrorClass = self.safe_value({
'103': AuthenticationError,
'104': AuthenticationError,
'200': AuthenticationError,
'202': AuthenticationError,
'401': AuthenticationError,
'406': AuthenticationError,
'203': InvalidNonce,
'201': OrderNotFound,
'408': InsufficientFunds,
'106': DDoSProtection,
}, code, ExchangeError)
message = self.safe_string(response, 'msg', 'Error')
raise ErrorClass(message)
return response
| StarcoderdataPython |
3217518 | """
.. _tut-report:
Getting started with ``mne.Report``
===================================
This tutorial covers making interactive HTML summaries with
:class:`mne.Report`.
As usual we'll start by importing the modules we need and loading some
:ref:`example data <sample-dataset>`:
"""
import os
import matplotlib.pyplot as plt
import mne
###############################################################################
# Before getting started with :class:`mne.Report`, make sure the files you want
# to render follow the filename conventions defined by MNE:
#
# .. cssclass:: table-bordered
# .. rst-class:: midvalign
#
# ============== ==============================================================
# Data object Filename convention (ends with)
# ============== ==============================================================
# raw -raw.fif(.gz), -raw_sss.fif(.gz), -raw_tsss.fif(.gz),
# _meg.fif(.gz), _eeg.fif(.gz), _ieeg.fif(.gz)
# events -eve.fif(.gz)
# epochs -epo.fif(.gz)
# evoked -ave.fif(.gz)
# covariance -cov.fif(.gz)
# SSP projectors -proj.fif(.gz)
# trans -trans.fif(.gz)
# forward -fwd.fif(.gz)
# inverse -inv.fif(.gz)
# ============== ==============================================================
#
# Alternatively, the dash ``-`` in the filename may be replaced with an
# underscore ``_``.
#
# Basic reports
# ^^^^^^^^^^^^^
#
# The basic process for creating an HTML report is to instantiate the
# :class:`~mne.Report` class, then use the :meth:`~mne.Report.parse_folder`
# method to select particular files to include in the report. Which files are
# included depends on both the ``pattern`` parameter passed to
# :meth:`~mne.Report.parse_folder` and also the ``subject`` and
# ``subjects_dir`` parameters provided to the :class:`~mne.Report` constructor.
#
# .. sidebar: Viewing the report
#
# On successful creation of the report, the :meth:`~mne.Report.save` method
# will open the HTML in a new tab in the browser. To disable this, use the
# ``open_browser=False`` parameter of :meth:`~mne.Report.save`.
#
# For our first example, we'll generate a barebones report for all the
# :file:`.fif` files containing raw data in the sample dataset, by passing the
# pattern ``*raw.fif`` to :meth:`~mne.Report.parse_folder`. We'll omit the
# ``subject`` and ``subjects_dir`` parameters from the :class:`~mne.Report`
# constructor, but we'll also pass ``render_bem=False`` to the
# :meth:`~mne.Report.parse_folder` method — otherwise we would get a warning
# about not being able to render MRI and ``trans`` files without knowing the
# subject.
path = mne.datasets.sample.data_path(verbose=False)
report = mne.Report(verbose=True)
report.parse_folder(path, pattern='*raw.fif', render_bem=False)
report.save('report_basic.html', overwrite=True)
###############################################################################
# This report yields a textual summary of the :class:`~mne.io.Raw` files
# selected by the pattern. For a slightly more useful report, we'll ask for the
# power spectral density of the :class:`~mne.io.Raw` files, by passing
# ``raw_psd=True`` to the :class:`~mne.Report` constructor. We'll also
# visualize the SSP projectors stored in the raw data's `~mne.Info` dictionary
# by setting ``projs=True``. Lastly, let's also refine our pattern to select
# only the filtered raw recording (omitting the unfiltered data and the
# empty-room noise recordings):
pattern = 'sample_audvis_filt-0-40_raw.fif'
report = mne.Report(raw_psd=True, projs=True, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_raw_psd.html', overwrite=True)
###############################################################################
# The sample dataset also contains SSP projectors stored as *individual files*.
# To add them to a report, we also have to provide the path to a file
# containing an `~mne.Info` dictionary, from which the channel locations can be
# read.
info_fname = os.path.join(path, 'MEG', 'sample',
'sample_audvis_filt-0-40_raw.fif')
pattern = 'sample_audvis_*proj.fif'
report = mne.Report(info_fname=info_fname, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_proj.html', overwrite=True)
###############################################################################
# This time we'll pass a specific ``subject`` and ``subjects_dir`` (even though
# there's only one subject in the sample dataset) and remove our
# ``render_bem=False`` parameter so we can see the MRI slices, with BEM
# contours overlaid on top if available. Since this is computationally
# expensive, we'll also pass the ``mri_decim`` parameter for the benefit of our
# documentation servers, and skip processing the :file:`.fif` files:
subjects_dir = os.path.join(path, 'subjects')
report = mne.Report(subject='sample', subjects_dir=subjects_dir, verbose=True)
report.parse_folder(path, pattern='', mri_decim=25)
report.save('report_mri_bem.html', overwrite=True)
###############################################################################
# Now let's look at how :class:`~mne.Report` handles :class:`~mne.Evoked` data
# (we'll skip the MRIs to save computation time). The following code will
# produce butterfly plots, topomaps, and comparisons of the global field
# power (GFP) for different experimental conditions.
pattern = 'sample_audvis-no-filter-ave.fif'
report = mne.Report(verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked.html', overwrite=True)
###############################################################################
# You have probably noticed that the EEG recordings look particularly odd. This
# is because by default, `~mne.Report` does not apply baseline correction
# before rendering evoked data. So if the dataset you wish to add to the report
# has not been baseline-corrected already, you can request baseline correction
# here. The MNE sample dataset we're using in this example has **not** been
# baseline-corrected; so let's do this now for the report!
#
# To request baseline correction, pass a ``baseline`` argument to
# `~mne.Report`, which should be a tuple with the starting and ending time of
# the baseline period. For more details, see the documentation on
# `~mne.Evoked.apply_baseline`. Here, we will apply baseline correction for a
# baseline period from the beginning of the time interval to time point zero.
baseline = (None, 0)
pattern = 'sample_audvis-no-filter-ave.fif'
report = mne.Report(baseline=baseline, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked_baseline.html', overwrite=True)
###############################################################################
# To render whitened :class:`~mne.Evoked` files with baseline correction, pass
# the ``baseline`` argument we just used, and add the noise covariance file.
# This will display ERP/ERF plots for both the original and whitened
# :class:`~mne.Evoked` objects, but scalp topomaps only for the original.
cov_fname = os.path.join(path, 'MEG', 'sample', 'sample_audvis-cov.fif')
baseline = (None, 0)
report = mne.Report(cov_fname=cov_fname, baseline=baseline, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked_whitened.html', overwrite=True)
###############################################################################
# If you want to actually *view* the noise covariance in the report, make sure
# it is captured by the pattern passed to :meth:`~mne.Report.parse_folder`, and
# also include a source for an :class:`~mne.Info` object (any of the
# :class:`~mne.io.Raw`, :class:`~mne.Epochs` or :class:`~mne.Evoked`
# :file:`.fif` files that contain subject data also contain the measurement
# information and should work):
pattern = 'sample_audvis-cov.fif'
info_fname = os.path.join(path, 'MEG', 'sample', 'sample_audvis-ave.fif')
report = mne.Report(info_fname=info_fname, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_cov.html', overwrite=True)
###############################################################################
# Adding custom plots to a report
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# The Python interface has greater flexibility compared to the :ref:`command
# line interface <mne report>`. For example, custom plots can be added via
# the :meth:`~mne.Report.add_figs_to_section` method:
report = mne.Report(verbose=True)
fname_raw = os.path.join(path, 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname_raw, verbose=False).crop(tmax=60)
events = mne.find_events(raw, stim_channel='STI 014')
event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
'visual/right': 4, 'face': 5, 'buttonpress': 32}
# create some epochs and ensure we drop a few, so we can then plot the drop log
reject = dict(eeg=150e-6)
epochs = mne.Epochs(raw=raw, events=events, event_id=event_id,
tmin=-0.2, tmax=0.7, reject=reject, preload=True)
fig_drop_log = epochs.plot_drop_log(subject='sample', show=False)
# now also plot an evoked response
evoked_aud_left = epochs['auditory/left'].average()
fig_evoked = evoked_aud_left.plot(spatial_colors=True, show=False)
# add the custom plots to the report:
report.add_figs_to_section([fig_drop_log, fig_evoked],
captions=['Dropped Epochs',
'Evoked: Left Auditory'],
section='drop-and-evoked')
report.save('report_custom.html', overwrite=True)
###############################################################################
# Adding a slider
# ^^^^^^^^^^^^^^^
#
# Sliders provide an intuitive way for users to interactively browse a
# predefined set of images. You can add sliders via
# :meth:`~mne.Report.add_slider_to_section`:
report = mne.Report(verbose=True)
figs = list()
times = evoked_aud_left.times[::30]
for t in times:
figs.append(evoked_aud_left.plot_topomap(t, vmin=-300, vmax=300, res=100,
show=False))
plt.close(figs[-1])
report.add_slider_to_section(figs, times, 'Evoked Response',
image_format='png') # can also use 'svg'
report.save('report_slider.html', overwrite=True)
###############################################################################
# Adding ``SourceEstimate`` (STC) plot to a report
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Now we see how :class:`~mne.Report` handles :class:`~mne.SourceEstimate`
# data. The following will produce a source time course (STC) plot with vertex
# time courses. In this scenario, we also demonstrate how to use the
# :meth:`mne.viz.Brain.screenshot` method to save the figs in a slider.
report = mne.Report(verbose=True)
fname_stc = os.path.join(path, 'MEG', 'sample', 'sample_audvis-meg')
stc = mne.read_source_estimate(fname_stc, subject='sample')
figs = list()
kwargs = dict(subjects_dir=subjects_dir, initial_time=0.13,
clim=dict(kind='value', lims=[3, 6, 9]))
for hemi in ('lh', 'rh'):
brain = stc.plot(hemi=hemi, **kwargs)
brain.toggle_interface(False)
figs.append(brain.screenshot(time_viewer=True))
brain.close()
# add the stc plot to the report:
report.add_slider_to_section(figs)
report.save('report_stc.html', overwrite=True)
###############################################################################
# Managing report sections
# ^^^^^^^^^^^^^^^^^^^^^^^^
#
# The MNE report command internally manages the sections so that plots
# belonging to the same section are rendered consecutively. Within a section,
# the plots are ordered in the same order that they were added using the
# :meth:`~mne.Report.add_figs_to_section` command. Each section is identified
# by a toggle button in the top navigation bar of the report which can be used
# to show or hide the contents of the section. To toggle the show/hide state of
# all sections in the HTML report, press :kbd:`t`, or press the toggle-all
# button in the upper right.
#
# .. sidebar:: Structure
#
# Although we've been generating separate reports in each of these examples,
# you could easily create a single report for all :file:`.fif` files (raw,
# evoked, covariance, etc) by passing ``pattern='*.fif'``.
#
#
# Editing a saved report
# ^^^^^^^^^^^^^^^^^^^^^^
#
# Saving to HTML is a write-only operation, meaning that we cannot read an
# ``.html`` file back as a :class:`~mne.Report` object. In order to be able
# to edit a report once it's no longer in-memory in an active Python session,
# save it as an HDF5 file instead of HTML:
report.save('report.h5', overwrite=True)
report_from_disk = mne.open_report('report.h5')
print(report_from_disk)
###############################################################################
# This allows the possibility of multiple scripts adding figures to the same
# report. To make this even easier, :class:`mne.Report` can be used as a
# context manager:
with mne.open_report('report.h5') as report:
report.add_figs_to_section(fig_evoked,
captions='Left Auditory',
section='evoked',
replace=True)
report.save('report_final.html', overwrite=True)
###############################################################################
# With the context manager, the updated report is also automatically saved
# back to :file:`report.h5` upon leaving the block.
| StarcoderdataPython |
159709 | #!/usr/bin/env python
import time, sys
from Adafruit_LEDBackpack import LEDBackpack
from LEDLetterValues import *
from timeit import default_timer
grids = [LEDBackpack(address=i) for i in range(0x70, 0x74)]
wait_time = float(sys.argv[2] if len(sys.argv) > 2 else raw_input("Wait time: "))
text = sys.argv[1] if len(sys.argv) > 1 else raw_input("What should I scroll: ")
printcon = textTo2D(text)
print "Press CTRL+C to exit"
def main():
scrolled = 0
while True:
start = default_timer()
for y, v in enumerate(printcon):
buffers = [0x00, 0x00, 0x00, 0x00]
for x, i in enumerate(v):
if i:
a = x - scrolled
if a >= 0 and a < len(grids) * 16:
buffers[a // 16] = buffers[a // 16] | 1 << (a % 16)
for i, grid in enumerate(grids):
grid.setBufferRow(y, buffers[i], update=False)
for i in grids:
i.writeDisplay()
final = default_timer()-start
if final <= wait_time:
time.sleep(wait_time - final)
scrolled += 1
if scrolled >= len(printcon[0]) / 2 + 6:
scrolled = 0
if "--once" in sys.argv:
exit(0)
if __name__ == "__main__":
try:
main()
except BaseException:
for i in grids:
for y in range(8):
i.setBufferRow(y, 0x00, update=False)
i.writeDisplay()
| StarcoderdataPython |
3352918 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright (2018) Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import logging
from oneview_redfish_toolkit.api.computer_system import ComputerSystem
from oneview_redfish_toolkit.api.resource_block import ResourceBlock
from oneview_redfish_toolkit.api import status_mapping
from oneview_redfish_toolkit.api.zone_collection import ZoneCollection
from oneview_redfish_toolkit.services.zone_service import ZoneService
class StorageResourceBlock(ResourceBlock):
"""Creates a ResourceBlock Redfish dict for Storage Drive
Populates self.redfish with Drive data retrieved from OneView.
"""
def __init__(self, drive, drive_index_trees, zone_ids):
"""StorageResourceBlock constructor
Populates self.redfish with the contents of drive
Args:
drive: OneView Drive dict
drive_index_trees: Drives index trees dict
zone_ids: List of Zone Ids that this Resource Block belongs to
"""
uuid = drive["uri"].split("/")[-1]
super().__init__(uuid, drive)
self.redfish["ResourceBlockType"] = ["Storage"]
self.redfish["Status"] = status_mapping.STATUS_MAP.get(drive["status"])
if drive["attributes"]["available"] == "yes":
composit_state = "Unused"
else:
composit_state = "Composed"
self.redfish["CompositionStatus"]["CompositionState"] = composit_state
self.redfish["CompositionStatus"]["SharingCapable"] = False
self.redfish["Links"] = collections.OrderedDict()
self.redfish["Links"]["ComputerSystems"] = list()
self.redfish["Links"]["Zones"] = list()
self._fill_link_members(drive_index_trees, zone_ids)
self.redfish["Storage"] = [
{
"@odata.id": self.redfish["@odata.id"] + "/Storage/1"
}
]
self._validate()
def _fill_link_members(self, drive_index_trees, zone_ids):
sp_uuid = self._get_server_profile_uuid(drive_index_trees)
if sp_uuid:
system_dict = {
"@odata.id": ComputerSystem.BASE_URI + "/" + sp_uuid
}
self.redfish["Links"]["ComputerSystems"].append(system_dict)
current_encl_id = self._get_enclosure_uuid(drive_index_trees)
if current_encl_id:
for zone_id in zone_ids:
_, encl_id = ZoneService\
.split_zone_id_to_spt_uuid_and_enclosure_id(zone_id)
if encl_id == current_encl_id:
zone_dict = {
"@odata.id": ZoneCollection.BASE_URI + "/" + zone_id
}
self.redfish["Links"]["Zones"].append(zone_dict)
def _get_server_profile_uuid(self, drive_index_trees):
try:
bay = drive_index_trees["parents"]["DRIVE_BAY_TO_DRIVE_ASSOC"][0]
sas_jbod = \
bay["parents"]["SAS_LOGICAL_JBOD_TO_DRIVEBAYS_ASSOCIATION"][0]
server_profile = \
sas_jbod["parents"]["SERVERPROFILE_TO_SLJBOD_ASSOCIATION"][0]
server_profile_uuid = \
server_profile["resource"]["uri"].split("/")[-1]
except KeyError as e:
logging.debug("The key {} was not found inside "
"'drive index trees dict' from the Oneview when "
"trying get the server profile uuid"
.format(e.args[0]))
server_profile_uuid = None
return server_profile_uuid
def _get_enclosure_uuid(self, drive_index_trees):
try:
bay = drive_index_trees["parents"]["DRIVE_BAY_TO_DRIVE_ASSOC"][0]
drive_encl = \
bay["parents"]["DRIVE_ENCLOSURE_TO_DRIVE_BAY_ASSOC"][0]
enclosure = \
drive_encl["parents"]["ENCLOSURE_TO_BLADE"][0]
enclosure_id = \
enclosure["resource"]["attributes"]["uuid"]
except KeyError as e:
logging.debug("The key {} was not found inside "
"'drive index trees dict' from the Oneview when "
"trying get the enclosure uuid"
.format(e.args[0]))
enclosure_id = None
return enclosure_id
| StarcoderdataPython |
1661797 | class Code:
"""Translates Hack assembly language mnemonics into binary codes."""
@staticmethod
def dest(mnemonic):
"""Returns the binary code of the dest mnemonic."""
if 'A' not in mnemonic and 'M' not in mnemonic and 'D' not in mnemonic and mnemonic != "":
raise KeyError
if 'A' in mnemonic:
A = '1'
else:
A = '0'
if 'D' in mnemonic:
D = '1'
else:
D = '0'
if 'M' in mnemonic:
M = '1'
else:
M = '0'
return A + D + M
@staticmethod
def comp(mnemonic):
"""Returns the binary code of the comp mnemonic.
table{'typeOfOperations':'Binary Code'}"""
if "M" in mnemonic:
a='1'
else:
a='0'
table = {
'0': '101010',
'1': '111111',
'-1': '111010',
'D': '001100',
'A': '110000',
'M': '110000',
'!D': '001101',
'!A': '110001',
'!M': '110001',
'-D': '001111',
'-A': '110011',
'-M': '110011',
'D+1': '011111',
'A+1': '110111',
'M+1': '110111',
'D-1': '001110',
'A-1': '110010',
'M-1': '110010',
'D+A': '000010',
'D+M': '000010',
'D-A': '010011',
'D-M': '010011',
'A-D': '000111',
'M-D': '000111',
'D&A': '000000',
'D&M': '000000',
'D|A': '010101',
'D|M': '010101'
}
return a + table[mnemonic]
@staticmethod
def jump(mnemonic):
"""Returns the binary code of the jump mnemonic,
table{'typeOfJump':'Binary Code'}"""
table = {
'': '000',
'JGT': '001',
'JEQ': '010',
'JGE': '011',
'JLT': '100',
'JNE': '101',
'JLE': '110',
'JMP': '111'
}
return table[mnemonic]
| StarcoderdataPython |
3371120 | <filename>TOFD/dataloader.py
import torch
from torchvision import datasets,transforms
import numpy as np
from torch.utils.data.sampler import SubsetRandomSampler
import os
random_pad_size = 2
def get_train_valid_loader_cifars(batch_size,
augment=True,
cifar10_100= "cifar10",
data_dir = "./data/",
output_width=32,
output_height=32,
valid_size=0.1,
shuffle=True,
show_sample=False,
num_workers=16,
pin_memory=True,
test_as_valid =True):
error_msg = "[!] valid_size should be in the range [0, 1]."
assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
if cifar10_100 == "cifar10":
# Mean and STD for CIFAR10
normalize = transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))
elif cifar10_100 == "cifar100":
# Mean and STD for CIFAR100
normalize = transforms.Normalize(mean=[0.507, 0.487, 0.441], std=[0.267, 0.256, 0.276])
if augment:
train_transform = transforms.Compose([
transforms.Resize((output_width, output_height)),
transforms.RandomCrop(32, padding=4,padding_mode= "reflect"),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# define transforms
valid_transform = transforms.Compose([
transforms.Resize((output_width, output_height)),
transforms.ToTensor(),
normalize,
])
else:
train_transform = transforms.Compose([
transforms.ToTensor(),
normalize,
])
# define transforms
valid_transform = transforms.Compose([
transforms.ToTensor(),
normalize,
])
# load the dataset
if cifar10_100 == "cifar100":
train_dataset = datasets.CIFAR100(
root=data_dir, train=True,
download=True, transform=train_transform,
)
if test_as_valid:
valid_dataset = datasets.CIFAR100(
root=data_dir, train=False,
download=True, transform=valid_transform,
)
else:
valid_dataset = datasets.CIFAR100(
root=data_dir, train=True,
download=True, transform=valid_transform,
)
elif cifar10_100 == "cifar10":
train_dataset = datasets.CIFAR10(
root=data_dir, train=True,
download=True, transform=train_transform,
)
if test_as_valid:
valid_dataset = datasets.CIFAR10(
root=data_dir, train=False,
download=True, transform=valid_transform,
)
else:
valid_dataset = datasets.CIFAR10(
root=data_dir, train=True,
download=True, transform=valid_transform,
)
num_train = len(train_dataset)
indices = list(range(num_train))
split = int(np.floor(valid_size * num_train))
# print("spit ===> ",split,"num-train",num_train)
if shuffle:
# np.random.seed(0)
np.random.shuffle(indices)
# torch.manual_seed(0)
train_idx, valid_idx = indices[split:], indices[:split]
if test_as_valid:
train_sampler = SubsetRandomSampler(indices)
else:
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=batch_size, sampler=train_sampler,
num_workers=num_workers, pin_memory=pin_memory,
)
if test_as_valid:
if cifar10_100 == "cifar100":
valid_loader = get_test_loader_cifar(batch_size=batch_size,
dataset="cifar100",
output_width=output_width,
output_height=output_height)
elif cifar10_100 == "cifar10":
valid_loader = get_test_loader_cifar(batch_size=batch_size,
dataset="cifar10",
output_width=output_width,
output_height=output_height)
else:
valid_loader = torch.utils.data.DataLoader(
valid_dataset, batch_size=batch_size, sampler=valid_sampler,
num_workers=num_workers, pin_memory=pin_memory,
)
# TODO visualize some images
if show_sample:
sample_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=9, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory,
)
data_iter = iter(sample_loader)
images, labels = data_iter.next()
X = images.numpy().transpose([0, 2, 3, 1])
# plot_images(X, labels)
data_loader_dict = {
"train": train_loader,
"val": valid_loader
}
if test_as_valid:
dataset_sizes = {"train": len(train_sampler),
"val": len(valid_dataset)}
else:
dataset_sizes = {"train": len(train_sampler),
"val": len(valid_sampler)}
return data_loader_dict, dataset_sizes
def get_test_loader_cifar(
batch_size,
dataset="cifar10",
output_height = 32,
output_width = 32,
shuffle=True,
num_workers=16,
pin_memory=True,
data_dir = "./data/"):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR-100 dataset.
If using CUDA, num_workers should be set to 1 and pin_memory to True.
Params
------
- data_dir: path directory to the dataset.
- batch_size: how many samples per batch to load.
- shuffle: whether to shuffle the dataset after every epoch.
- num_workers: number of subprocesses to use when loading the dataset.
- pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
True if using GPU.
Returns
-------
- data_loader: test set iterator.
"""
if dataset =="cifar10":
normalize = transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))
# define transform
transform = transforms.Compose([
#transforms.Resize((output_width, output_height)),
transforms.ToTensor(),
normalize,
])
dataset = datasets.CIFAR10(
root=data_dir, train=False,
download=True, transform=transform,
)
elif dataset =="cifar100":
normalize = transforms.Normalize(mean=[0.507, 0.487, 0.441],
std=[0.267, 0.256, 0.276])
# define transform
transform = transforms.Compose([
transforms.ToTensor(),
normalize,
])
dataset = datasets.CIFAR100(
root=data_dir, train=False,
download=True, transform=transform,
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory,
)
return data_loader
def get_train_valid_loader_imagenet(batch_size,
augment=True,
data_dir = "./data/",
output_width=224,
output_height=224,
valid_size=0.1,
shuffle=True,
show_sample=False,
num_workers=16,
pin_memory=True,
test_as_valid =True):
error_msg = "[!] valid_size should be in the range [0, 1]."
assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
if augment:
train_transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# define transforms
valid_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])
# load the dataset
train_dataset = datasets.ImageNet(
root=data_dir, train=True,
download=True, transform=train_transform,
)
if test_as_valid:
valid_dataset = datasets.ImageNet(
root=data_dir, train=False,
download=True, transform=valid_transform,
)
else:
valid_dataset = datasets.ImageNet(
root=data_dir, train=True,
download=True, transform=valid_transform,
)
num_train = len(train_dataset)
indices = list(range(num_train))
split = int(np.floor(valid_size * num_train))
# print("spit ===> ",split,"num-train",num_train)
if shuffle:
# np.random.seed(0)
np.random.shuffle(indices)
# torch.manual_seed(0)
train_idx, valid_idx = indices[split:], indices[:split]
if test_as_valid:
train_sampler = SubsetRandomSampler(indices)
else:
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=batch_size, sampler=train_sampler,
num_workers=num_workers, pin_memory=pin_memory,
)
if test_as_valid:
valid_loader = get_test_loader_cifar(batch_size=batch_size,
dataset="cifar100",
output_width=output_width,
output_height=output_height)
else:
valid_loader = torch.utils.data.DataLoader(
valid_dataset, batch_size=batch_size, sampler=valid_sampler,
num_workers=num_workers, pin_memory=pin_memory,
)
# TODO visualize some images
if show_sample:
sample_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=9, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory,
)
data_iter = iter(sample_loader)
images, labels = data_iter.next()
X = images.numpy().transpose([0, 2, 3, 1])
# plot_images(X, labels)
data_loader_dict = {
"train": train_loader,
"val": valid_loader
}
if test_as_valid:
dataset_sizes = {"train": len(train_sampler),
"val": len(valid_dataset)}
else:
dataset_sizes = {"train": len(train_sampler),
"val": len(valid_sampler)}
return data_loader_dict, dataset_sizes
def get_test_loader_imagenet(
batch_size,
shuffle=True,
num_workers=16,
pin_memory=True,
data_dir = "./data/"):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR-100 dataset.
If using CUDA, num_workers should be set to 1 and pin_memory to True.
Params
------
- data_dir: path directory to the dataset.
- batch_size: how many samples per batch to load.
- shuffle: whether to shuffle the dataset after every epoch.
- num_workers: number of subprocesses to use when loading the dataset.
- pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
True if using GPU.
Returns
-------
- data_loader: test set iterator.
"""
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# define transform
transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
dataset = datasets.ImageNet(
root=data_dir, train=False,
download=True, transform=transform,
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory,
)
return data_loader
def get_train_valid_loader_svhn(batch_size,
data_dir = "./data/",
extra_training = True,
output_width=32,
output_height=32,
shuffle=True,
num_workers=16,
pin_memory=True,
):
#svhn_normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
#svhn_transform = transforms.Compose([
# transforms.ToTensor(),
# ])
svhn_normalize = transforms.Normalize((0.430, 0.430, 0.446),(0.196, 0.198, 0.199))
svhn_transform = transforms.Compose([
transforms.ToTensor,
svhn_normalize,
#transforms.Normalize(mean=[x / 255.0 for x in [109.9, 109.7, 113.8]],
#std=[x / 255.0 for x in [50.1, 50.6, 50.8]])
])
train_dataset = datasets.SVHN(
root=data_dir, split="train",
download=True, transform=svhn_transform,
)
if extra_training:
train_dataset += datasets.SVHN(
root=data_dir, split="extra",
download=True, transform=svhn_transform,
)
valid_dataset = datasets.SVHN(
root=data_dir, split="test",
download=True, transform=svhn_transform,)
num_train = len(train_dataset)
indices = list(range(num_train))
# print("spit ===> ",split,"num-train",num_train)
if shuffle:
# np.random.seed(0)
np.random.shuffle(indices)
# torch.manual_seed(0)
train_sampler = SubsetRandomSampler(indices)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=batch_size, sampler=train_sampler,
num_workers=num_workers, pin_memory=pin_memory,
)
valid_loader = get_test_loader_cifar(batch_size=batch_size,
output_width=output_width,
output_height=output_height)
data_loader_dict = {
"train": train_loader,
"val": valid_loader
}
dataset_sizes = {"train": len(train_sampler),
"val": len(valid_dataset)}
return data_loader_dict, dataset_sizes
def get_test_loader_svhn(
batch_size,
shuffle=True,
num_workers=16,
pin_memory=True,
data_dir = "./data/"):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR-100 dataset.
If using CUDA, num_workers should be set to 1 and pin_memory to True.
Params
------
- data_dir: path directory to the dataset.
- batch_size: how many samples per batch to load.
- shuffle: whether to shuffle the dataset after every epoch.
- num_workers: number of subprocesses to use when loading the dataset.
- pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
True if using GPU.
Returns
-------
- data_loader: test set iterator.
"""
svhn_normalize = transforms.Normalize((0.430, 0.430, 0.446),
(0.196, 0.198, 0.199))
transform = transforms.Compose([
transforms.ToTensor,
svhn_normalize,
#transforms.Normalize(mean=[x / 255.0 for x in [109.9, 109.7, 113.8]],
#std=[x / 255.0 for x in [50.1, 50.6, 50.8]])
])
#transform = transforms.Compose([
# transforms.ToTensor(),
# ])
dataset = datasets.SVHN(
root=data_dir, split="test",
download=True, transform=transform,
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory,
)
return data_loader
def load_tiny(data_folder="/home/aasadian/tiny_imagenet_200/", batch_size=64, phase='train',shuffle=True):
#MEAN == > tensor([0.4802, 0.4481, 0.3975])
#STD == > tensor([0.2770, 0.2691, 0.2821])
transform_dict = {
'train': transforms.Compose(
[#transforms.Resize(256),
#transforms.RandomCrop(224),
#transforms.RandomHorizontalFlip(),
#transforms.RandomHorizontalFlip(),
#transforms.RandomCrop(64, padding=4),
transforms.ToTensor(),
#transforms.Normalize(mean=[0.4802, 0.4481, 0.3975],
# std=[0.2770, 0.2691, 0.2821]),
]),
'test': transforms.Compose(
[#transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.4802, 0.4481, 0.3975],
std=[0.2770, 0.2691, 0.2821]),
])}
if phase == 'train':
data_train = datasets.ImageFolder(root=data_folder+"train/", transform=transform_dict[phase])
data_val = datasets.ImageFolder(root=data_folder+"val/", transform=transform_dict[phase])
train_loader = torch.utils.data.DataLoader(data_train, batch_size=batch_size, shuffle=shuffle, drop_last=True,
num_workers=4)
val_loader = torch.utils.data.DataLoader(data_val, batch_size=batch_size, shuffle=False, drop_last=False,
num_workers=4)
data_loader_dict = {
"train": train_loader,
"val": val_loader
}
dataset_sizes = {"train": len(train_loader),
"val": len(val_loader)}
return data_loader_dict,dataset_sizes
else:
data_test = datasets.ImageFolder(root=data_folder+"test/", transform=transform_dict[phase])
test_loader = torch.utils.data.DataLoader(data_test, batch_size=batch_size, shuffle=False, drop_last=False,
num_workers=4)
return test_loader
"""
data_loader_dict,dataset_sizes = load_tiny(batch_size=1,shuffle=False)
from general_utils import get_mean_std_ptr,get_mean_std
mean,std = get_mean_std(data_loader_dict["train"])
mean_prt,std_prt = get_mean_std_ptr(data_loader_dict["train"])
print("Mean ===> ",mean,"\t STD ==> ",std)
print("mean_prt ===> ",mean_prt,"\t std_prt ==> ",std_prt)
data_loader_dict,dataset_sizes = load_tiny(batch_size=4)
print("Train size ====> ", dataset_sizes["train"], "Test Size ===> ", dataset_sizes["val"])#from general_utils import get_mean_std
#mean,std = get_mean_std(train_loader)
#print("MEAN ==> ",mean)
#print("STD ==> ",std)
import torchvision
it = iter(data_loader_dict["train"])
image,label = it.next()
image,label = it.next()
print("Label ===> ",(label.data))
import matplotlib.pyplot as plt
#image_2,label_2 = it.next()
def imshow(img):
# img = img / 2 + 0.5 # unnormalize
npimg = img.numpy() # convert from tensor
plt.imshow(np.transpose(npimg, (1,2,0)))
plt.show()
imshow(torchvision.utils.make_grid(image))
#plt.imshow(image_2, interpolation='nearest')
#torchvision.utils.save_image(image_2,"/home/aasadian/ship.png")
#plt.savefig("/home/aasadian/plane.png")
#image,label = image.to("cuda:0"),label.to("cuda:0")
#print("Image type ",type(image))
#print("Label ===> ",load_label_names()[(int(label_2.data))])
"""
#get_train_valid_loader_cifars(batch_size=32)
| StarcoderdataPython |
102359 | import unittest
import os
import numpy as np
from platform import python_implementation
from sentinelhub import read_data, write_data, TestSentinelHub
class TestIO(TestSentinelHub):
class IOTestCase:
def __init__(self, filename, mean, shape=(2048, 2048, 3)):
self.filename = filename
self.mean = mean
self.shape = shape
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.test_cases = [
cls.IOTestCase('img.tif', 13577.494856),
cls.IOTestCase('img.jpg', 52.41194),
cls.IOTestCase('img.png', 52.33736),
cls.IOTestCase('img-8bit.jp2', 47.09060, (343, 343, 3)),
cls.IOTestCase('img-15bit.jp2', 0.3041897, (1830, 1830)),
cls.IOTestCase('img-16bit.jp2', 0.3041897, (1830, 1830)),
]
def test_img_read(self):
for test_case in self.test_cases:
with self.subTest(msg=test_case.filename):
file_path = os.path.join(self.INPUT_FOLDER, test_case.filename)
img = read_data(file_path)
self.assertEqual(img.shape, test_case.shape,
'Expected shape {}, got {}'.format(test_case.shape, img.shape))
if test_case.filename != 'img.jpg' or python_implementation() != 'PyPy':
self.assertAlmostEqual(np.mean(img), test_case.mean, delta=1e-4,
msg='Expected mean {}, got {}'.format(test_case.mean, np.mean(img)))
self.assertTrue(img.flags['WRITEABLE'], msg='Obtained numpy array is not writeable')
new_file_path = os.path.join(self.OUTPUT_FOLDER, test_case.filename)
write_data(new_file_path, img)
new_img = read_data(new_file_path)
if not test_case.filename.endswith('jpg'):
self.assertTrue(np.array_equal(img, new_img), msg="Original and new image are not the same")
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
38213 | from bs4 import BeautifulSoup
import time
from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement, XMPPResponse
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
class OutgoingAcknowledgement(XMPPElement):
"""
Represents an outgoing acknowledgement for a message ID
"""
def __init__(self, sender_jid, is_receipt, ack_id, group_jid):
super().__init__()
self.sender_jid = sender_jid
self.group_jid = group_jid
self.is_receipt = is_receipt
self.ack_id = ack_id
def serialize(self):
timestamp = str(int(round(time.time() * 1000)))
user_ack_data = (
'<sender jid="{}">'
'<ack-id receipt="{}">{}</ack-id>'
'</sender>'
).format(self.sender_jid, str(self.is_receipt).lower(), self.ack_id)
group_ack_data = (
'<sender jid="{}" g="{}">'
'<ack-id receipt="{}">{}</ack-id>'
'</sender>'
).format(self.sender_jid, self.group_jid, str(self.is_receipt).lower(), self.ack_id)
data = ('<iq type="set" id="{}" cts="{}">'
'<query xmlns="kik:iq:QoS">'
'<msg-acks>'
'{}'
'</msg-acks>'
'<history attach="false" />'
'</query>'
'</iq>'
).format(self.message_id, timestamp, user_ack_data if self.group_jid != None else group_ack_data)
return data.encode()
class OutgoingHistoryRequest(XMPPElement):
"""
Represents an outgoing request for the account's messaging history
"""
def __init__(self):
super().__init__()
def serialize(self):
timestamp = str(int(round(time.time() * 1000)))
data = ('<iq type="set" id="{}" cts="{}">'
'<query xmlns="kik:iq:QoS">'
'<msg-acks />'
'<history attach="true" />'
'</query>'
'</iq>'
).format(self.message_id, timestamp,)
return data.encode()
class HistoryResponse(XMPPResponse):
"""
Represents a Kik messaging history response.
"""
def __init__(self, data: BeautifulSoup):
super().__init__(data)
self.id = data["id"]
if data.query.history:
self.more = data.query.history.has_attr("more")
self.from_jid = data["from"]
self.messages = []
for message in data.query.history:
if message["type"] == "receipt":
args = {
'type':'receipt',
'from_jid': message["from"],
'receipt_type':message.receipt["type"],
'id':message.receipt.msgid["id"]
}
self.messages.append(Struct(**args))
elif message["type"] == "chat":
args = {
'type':'chat',
'id':message["id"],
'from_jid':message["from"],
'body': message.body.text if message.body else None,
'preview': message.preview.text if message.preview else None,
'timestamp': message.kik["timestamp"]
}
self.messages.append(Struct(**args))
elif message["type"] == "groupchat":
args = {
'type': 'groupchat',
'id': message["id"],
'from_jid': message["from"],
'body': message.body.text if message.body else None,
'preview': message.preview.text if message.preview else None,
'timestamp': message.kik["timestamp"],
'group_jid': message.g["jid"]
}
self.messages.append(Struct(**args))
| StarcoderdataPython |
1714810 | <reponame>foundation29org/F29.BioEntity
from flask import current_app, request, make_response, jsonify
from flask_restplus import Resource
from ._api import *
'''
Disease Successors/Predecessors
'''
@API.route('/disease/successors/<string:ids>')
@API.param('ids', 'Disease IDs')
class disease_successors(Resource):
def get(self, ids):
ids = [id.strip() for id in ids.split(',')]
depth = int(request.args.get('depth') or 1)
bio = get_bio_phens('en')
res = bio.Mondo.successors(ids, depth)
return jsonify(res)
@API.route('/disease/successors')
class disease_post(Resource):
def post(self):
ids = json.loads(request.data)
depth = int(request.args.get('depth') or 1)
bio = get_bio_phens('en')
res = bio.Mondo.predecessors(ids, depth)
return jsonify(res)
@API.route('/disease/predecessors/<string:ids>')
@API.param('ids', 'Disease IDs')
class disease_predecessors(Resource):
def get(self, ids):
ids = [id.strip() for id in ids.split(',')]
depth = int(request.args.get('depth') or 1)
bio = get_bio_phens('en')
res = bio.Mondo.predecessors(ids, depth)
return jsonify(res)
@API.route('/disease/predecessors')
class disease_predecessors_post(Resource):
def post(self):
ids = json.loads(request.data)
depth = int(request.args.get('depth') or 1)
bio = get_bio_phens('en')
res = bio.Mondo.predecessors(ids, depth)
return jsonify(res)
'''
Validation
'''
@API.route('/disease/validation/<string:ids>')
@API.param('ids', 'Disease IDs')
class disease_validation(Resource):
def get(self, ids):
ids = [id.strip() for id in ids.split(',')]
bio = get_bio_phens('en')
res = bio.Mondo.validate_terms(ids)
return jsonify(res)
@API.route('/disease/validation')
class disease_validation_post(Resource):
def post(self):
ids = json.loads(request.data)
bio = get_bio_phens('en')
res = bio.Mondo.validate_terms(ids)
return jsonify(res)
| StarcoderdataPython |
1742480 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import os
import re
import shutil
import codecs
import hashlib
import chardet
import json
import stat
import subprocess
from .Config import g_conf
from .Router import Router
from enum import Enum
class Color(Enum):
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
def print_color(text: str, fg: Color = Color.BLACK.value, end='\n'):
print('\033[%sm%s\033[0m' % (fg, text), end=end)
def run(command, cwd):
with subprocess.Popen(command, cwd=cwd, shell=True) as ret:
ret.wait()
if ret.returncode != 0:
ret.kill()
raise BaseException
def logged_func(delim='\n'):
def inner(func):
def wrapper(*args, **kwargs):
log_start(func.__name__, delim)
func(*args, **kwargs)
log_end()
return wrapper
return inner
def copytree(src, dst, syamlinks=False, ignore=None):
for item in os.listdir(src):
s = unify_joinpath(src, item)
d = unify_joinpath(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, syamlinks, ignore)
else:
shutil.copy2(s, d)
def force_rmtree(top):
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
filename = os.path.join(root, name)
os.chmod(filename, stat.S_IWUSR)
os.remove(filename)
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(top)
def log_start(message, delim):
print_color('Start ' + message, Color.YELLOW.value, end='...'+delim)
def log_end():
print_color('done.', Color.YELLOW.value)
def safe_write(path, content, codec="utf-8"):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with codecs.open(path, "w+", encoding=codec) as f:
f.write(content)
def safe_read(path):
if not os.path.exists(path):
return ""
# utf-8 is prefered
try:
with open(path, 'r', encoding='utf-8') as f:
return f.read()
except UnicodeDecodeError:
with open(path, 'rb') as f:
content = f.read()
encoding = chardet.detect(content)['encoding'] or 'utf-8'
return content.decode(encoding=encoding)
def gen_hash(str):
h1 = hashlib.md5()
h1.update(str.encode(encoding='utf-8'))
return h1.hexdigest()
def unify_joinpath(left, right):
path = os.path.join(left, right)
return path.replace('\\', '/')
def filterPlaceholders(content):
"""replace content like ${key} to corresponding value
1. search key in env
2. search key in config
"""
pattern = re.compile(r'[\s\S]*?\$\{([\s\S]*?)\}')
router = Router(g_conf)
def getKey(str):
m = pattern.match(str)
if not m is None:
return m.group(1)
else:
return None
while True:
key = getKey(content)
if key is None:
break
search_str = '${%s}' % key
value = ''
if key == "static_prefix":
value = router.gen_static_file_prefix()
else:
# find in os.env
value = os.getenv(key, None)
if value is None:
# find in config
try:
value = getattr(g_conf, key)
except AttributeError:
pass
# replace
content = content.replace(search_str, str(value), 1)
return content
| StarcoderdataPython |
1715906 | <gh_stars>0
import sys
import getopt
class Options(object):
def __init__(self, mandatory, optional=[], switches=[]):
self.opts = {}
self.__mand = mandatory
self.__optn = optional
self.__swtc = switches
def __getattr__(self, attribute):
if attribute in self.opts:
return self.opts[attribute]
return None
def usage(self, notes=''):
msg = 'usage: %s' %(sys.argv[0])
for option in self.__mand:
msg += ' --%s <%sname>' %(option, option)
for option in self.__optn:
msg += ' [--%s <%sname>]' %(option, option)
for option in self.__swtc:
msg += ' [--%s]' %(option)
if notes != '':
msg += '\nnotes: '
msg += notes
print msg
def parse(self):
opts = []
for option in self.__mand:
opts.append(option+'=')
for option in self.__optn:
opts.append(option+'=')
for option in self.__swtc:
opts.append(option)
results = getopt.getopt(sys.argv[1:], '', opts)
if len(results[1]) > 0:
raise RuntimeError, 'unknown argument(s) \'%s\'' %(results[1])
for opt in results[0]:
self.opts[opt[0][2:]] = opt[1]
for option in self.__mand:
if option not in self.opts:
raise RuntimeError, 'mandatory option \'--%s\' not found' %(option)
| StarcoderdataPython |
1613096 | #Faça um Algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preco = float(input('Qual o valor do seu produto? '))
desc = 0.05
precod = preco * (1-desc)
print(f'Olá, seu produto de R${preco:.2f} estará saindo por R${precod:.2f}' ) | StarcoderdataPython |
4835277 | """
https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/comparing-and-sorting-tuples
Which does the same thing as the following code?:
lst = []
for key, val in counts.items():
newtup = (val, key)
lst.append(newtup)
lst = sorted(lst, reverse=True)
print(lst)
Choices:
print( sorted( [ (v,k) for k,v in counts.items() ], reverse=True ) )
print( [ (k,v) for k,v in counts.items().sorted() ] )
print( sorted( [ (v,k) for k,v in counts.keys() ] ) )
print( [ (k,v) for k,v in counts.values().sort() ] )
"""
counts = {'May': 200, 'Mashima': 15, 'Hui': 215}
lst = []
for key, val in counts.items():
newtup = (val, key)
lst.append(newtup)
lst = sorted(lst, reverse=True)
print(lst)
print( sorted( [ (v,k) for k,v in counts.items() ], reverse=True ) )
| StarcoderdataPython |
4814290 | <reponame>0201shj/Python-OpenCV<filename>Chapter02/0211.py
# 0211.py
import cv2
import matplotlib.pyplot as plt
#1
def handle_key_press(event):
if event.key == 'escape':
cap.release()
plt.colse()
def handle_close(evt):
print('Close figure!')
cap.release()
#2 프로그램 시작
cap = cv2.VideoCapture(0) #0번카메라
plt.ion() #대화모드 설정
fig = plt.figure(figsize = (10, 6)) # fig.set_size_inches(10,6)
plt.axis('off')
#ax = fig.gca()
#ax.set_axis_off()
fig.canvas.set_window_title('Video Capture')
fig.canvas.mpl_connect('key_press_event', handle_key_press)
fig.canvas.mpl_connect('close_event', handle_close)
retval, frame = cap.read() #첫 프레임 캡처
im = plt.imshow(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
#3
while True:
retval, frame = cap.read()
if not retval:
break
# plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BRG2RGB))
# im.set_array(cv2.cvtColor(frame, cv2.COLOR_BRG2RGB))
fig.canvas.draw()
# fig.canvas.draw_idle()
fig.canvas.flush_events() # plt.pause(0.001)
if cap.isOpened():
cap.release() | StarcoderdataPython |
1655242 | <reponame>nachovazquez98/COVID-19_Paper<filename>covid_app.py<gh_stars>0
#https://blog.streamlit.io/uc-davis-tool-tracks-californias-covid-19-cases-by-region/
import streamlit as st
import os
import numpy as np
import pandas as pd
from PIL import Image
import joblib
import plotly.express as px
from covid_graficas import casos_nuevos_total
from covid_graficas import casos_acum_total
from covid_graficas import mort_porcentaje
#<<<<<<< HEAD
#eliminar otro caso
#corregir grafica hist de muertes y vent, comparar con notebook jalisco
#https://docs.streamlit.io/en/stable/caching.html
#=======
'''
eliminar otro caso
corregir grafica hist de muertes y vent, comparar con notebook jalisco
'''
#>>>>>>> 1906d1b29928dda1f159c3b148ab48488ab87b80
<EMAIL>(ttl=3600*24, show_spinner=False)
def load_data():
df = pd.read_csv("covid_data.zip",low_memory = True)
df_descrip = pd.read_excel("diccionario_datos_covid19/Descriptores.xlsx")
df_estados = pd.read_csv("diccionario_datos_covid19/diccionario_estados.csv")
return df, df_descrip,df_estados
genero_dict = {'Hombre':0,'Mujer':1}
feature_dict = {'No':0,'Si':1}
def get_value(val, my_dict):
for key,value in my_dict.items():
if val == key:
return value
def get_key(val, my_dict):
for key,value in my_dict.items():
if val == value:
return key
def get_fval(val):
feature_dict = {'No':0,'Si':1}
for key,value in feature_dict.items():
if val == key:
return value
#carga modelo de ml
def load_model(model_file):
loaded_model = joblib.load(open(os.path.join(model_file), 'rb'))
return loaded_model
def descriptores():
age = st.number_input("Edad",1,120)
emb = st.radio("Embarazo",tuple(feature_dict.keys()))
ren_cron = st.radio("¿Tiene diagnóstico de insuficiencia renal crónica?",tuple(feature_dict.keys()))
diab = st.radio("¿Tiene un diagnóstico de diabetes?",tuple(feature_dict.keys()))
inms = st.radio("¿Presenta inmunosupresión?",tuple(feature_dict.keys()))
epoc = st.radio("¿Tiene un diagnóstico la enfermedad pulmonar obstructiva crónica (EPOC)?",tuple(feature_dict.keys()))
obes = st.radio("¿Tiene diagnóstico de obesidad?",tuple(feature_dict.keys()))
#<<<<<<< HEAD
#=======
otro = st.radio("¿Tuvo contacto con algún otro caso diagnósticado con SARS CoV-2?",tuple(feature_dict.keys()))
#>>>>>>> 1906d1b29928dda1f159c3b148ab48488ab87b80
hiper = st.radio("¿Tiene diagnóstico de hipertensión?",tuple(feature_dict.keys()))
tab = st.radio("¿Tiene hábito de tabaquismo?",tuple(feature_dict.keys()))
cardio = st.radio("¿Tiene un diagnóstico de enfermedades cardiovasculares?",tuple(feature_dict.keys()))
asma = st.radio("¿Tiene un diagnóstico de asma?",tuple(feature_dict.keys()))
sex = st.radio("Sexo",tuple(genero_dict.keys()))
#<<<<<<< HEAD
return age, emb, ren_cron, diab, inms, epoc, obes, hiper, tab, cardio, asma, sex
#=======
return age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex
#>>>>>>> 1906d1b29928dda1f159c3b148ab48488ab87b80
def main():
df, df_descrip,df_estados = load_data()
df = df[df.RESULTADO == 1]
st.title("Análisis y diagnóstico de COVID-19 en México")
st.header("Una herramienta para visualizar y prevenir")
st.sidebar.title("Casos")
st.sidebar.markdown("Seleccione en el menu una opcion")
image = Image.open('covid.jpg')
st.image(image, use_column_width=True)
##
menu = ['README', 'Casos estatales','Hospitalización','Mortalidad antes de hopitalización','Mortalidad hopitalizado','ICU antes del diagnostico de neumonia','ICU despues del diagnostico de neumonia','Ventilador antes de un diagnostico de neumonia y de ICU','Ventilador despues de un diagnostico de neumonia y de ICU']
submenu = ['Plot', 'Prediction']
choice = st.sidebar.selectbox("Menu",menu)
if choice == 'README':
#st.header("Acerca de este proyecto")
st.subheader("Análisis y Predicción de Riesgos por COVID-19 en México")
st.write("Con este proyecto se pretende seguir la evolución y los patrones generados por el COVID-19 mediante gráficas y datos sencillos de visualizar para así generar conciencia de los riesgos que una persona dada pueda llegar a tener tomando en cuenta sus descriptores particulares.")
st.subheader("Motivación")
st.write("Proporcionar a la gente con un análisis que evita mostrar conclusiones ambiguas acerca del estado actual del país para asistir una toma de decisiones objetiva tanto por parte de autoridades como de ciudadanos. ")
st.subheader("Datos actuales")
st.write("Número de casos positivos de COVID: ", len(df))
st.write("Número de hospitalizados por COVID: ", df.TIPO_PACIENTE.value_counts()[1])
st.write("Número de intubados por COVID: ", df.INTUBADO.value_counts()[1])
st.write("Número de fallecidos por COVID: ", df.BOOL_DEF.value_counts()[1])
st.write("Número de UCI por COVID: ", df.UCI.value_counts()[1])
st.subheader("Muestra del dataset y su diccionario de fuentes oficiales")
st.dataframe(df.head())
st.dataframe(df_descrip)
st.image(Image.open('plots/barplot_casos_hos_def.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID en Mexico por sexo.png') , use_column_width=True)
st.image(Image.open('plots/corrmatrix_1.png') , use_column_width=True)
st.image(Image.open('plots/sector.png') , use_column_width=True)
st.write("<hr>", unsafe_allow_html=True)
st.write(
"Visita el repositorio en [Github](https://github.com/CT-6282/COVID-19_Paper), "
"descarga la [Bases de datos Covid-19 en México](https://www.gob.mx/salud/documentos/datos-abiertos-152127), "
"visita el [Tablero informativo de Covid-19 de México](https://coronavirus.gob.mx/datos/#DOView), "
"este proyecto fue basado principalmente en este [artículo](https://www.medrxiv.org/content/10.1101/2020.05.03.20089813v1.full.pdf)")
elif choice == 'Casos estatales':
st.write(df_estados.iloc[:,[1,2]])
st.image(Image.open('plots/entidades_casos_pos.png'), use_column_width=True)
st.image(Image.open('plots/entidades_def_pos.png'), use_column_width=True)
st.image(Image.open('plots/entidades_let.png'), use_column_width=True)
dict_estados = dict(zip(list(df_estados.iloc[:,0]),list(df_estados.iloc[:,1])))
#st.write(dict_estados)
#st.write(dict_estados.values())
selected_metrics = st.selectbox(label="Elije un estado...", options=list(dict_estados.values()))
#st.write(selected_metrics)
int_estado = get_key(selected_metrics,dict_estados)
#st.write(int_estado)
if int_estado == 36:
ult_sem=casos_nuevos_total(df,estado=False, estado_str='México',show=True)
st.pyplot()
casos_acum_total(df,estado=None, estado_str='México',show=True)
st.pyplot()
mort_porcentaje(df,estado=None, estado_str='México',show=True)
st.pyplot()
else:
ult_sem = casos_nuevos_total(df,estado=int_estado, estado_str=selected_metrics,show=True)
st.pyplot()
casos_acum_total(df,estado=int_estado, estado_str=selected_metrics,show=True)
st.pyplot()
mort_porcentaje(df,estado=int_estado, estado_str=selected_metrics,show=True)
st.pyplot()
st.write("Suma semanal de casos")
st.write(ult_sem)
elif choice == 'Hospitalización':
st.subheader("Se pretende predecir en base a los descriptores si el paciente contagiado de CoV-2 necesitará hospitalización")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.subheader("Data plot")
st.image(Image.open('plots/def_sin_boxplot.png'), use_column_width=True)
st.image(Image.open('plots/amb_hosp_casos_pos.png'), use_column_width=True)
st.image(Image.open('plots/barplot_hospitalizacion_edad.png'), use_column_width=True)
st.image(Image.open('plots/Tasa de casos de COVID en Mexico por rangos de edad.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/hosp_data_grid_report.csv", index_col=0))
#<<<<<<< HEAD
age, emb, ren_cron, diab, inms, epoc, obes, hiper, tab, cardio, asma, sex = descriptores()
feature_list = [get_value(sex,genero_dict),age,get_fval(emb),get_fval(diab),get_fval(epoc),get_fval(asma),get_fval(inms),get_fval(hiper),get_fval(cardio),get_fval(obes),get_fval(ren_cron),get_fval(tab)]
st.write(feature_list)
user_input_column_names = ['SEXO', 'EDAD', 'EMBARAZO', 'DIABETES', 'EPOC', 'ASMA', 'INMUSUPR', 'HIPERTENSION', 'CARDIOVASCULAR', 'OBESIDAD', 'RENAL_CRONICA','TABAQUISMO']
user_input = pd.DataFrame(np.array(feature_list).reshape(1,-1), columns= user_input_column_names)
#=======
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict)]
st.write(feature_list)
feature_model = np.array(feature_list).reshape(1,-1)
#>>>>>>> 1906d1b29928dda1f159c3b148ab48488ab87b80
#ML
# model_choice = st.selectbox("Seleccione un modelo:",['RF','SVM','LR'])
# if st.button('Predict'):
# if model_choice = 'SVM':-
model_load = load_model('models/hosp_data_grid.pkl')
#<<<<<<< HEAD
prediction = model_load.predict(user_input)
#=======
prediction = model_load.predict(feature_model)
#>>>>>>> 1906d1b29928dda1f159c3b148ab48488ab87b80
#
st.write(prediction)
if prediction == 1:
st.warning('Necesitara hospitalización')
else:
st.success("No necesitara hospitalización")
#<<<<<<< HEAD
pred_prob = model_load.predict_proba(user_input)
#=======
pred_prob = model_load.predict_proba(feature_model)
#>>>>>>> 1906d1b29928dda1f159c3b148ab48488ab87b80
st.write(pred_prob)
prob_score = {'Ambulante':pred_prob[0][0]*100,'Hospitalizado':pred_prob[0][1]*100}
st.json(prob_score)
####
elif choice == 'Mortalidad antes de hopitalización':
st.subheader("Se pretende predecir en base a los descriptores la mortalidad del paciente contagiado de CoV-2 antes de estar internado en el hospital")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.subheader("Data plot")
st.image(Image.open('plots/def_pos.png'), use_column_width=True)
st.image(Image.open('plots/def_edad_histograma.png'), use_column_width=True)
st.image(Image.open('plots/barplot_defuncion_edad.png'), use_column_width=True)
st.image(Image.open('plots/Tasa de casos de COVID en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Tasa de letalidad de COVID en México.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/def_data_grid_report.csv", index_col=0))
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict)]
st.write(feature_list)
feature_model = np.array(feature_list).reshape(1,-1)
#ML
# model_choice = st.selectbox("Seleccione un modelo:",['RF','SVM','LR'])
# if st.button('Predict'):
# if model_choice = 'SVM':
model_load = load_model('models/def_data_grid.pkl')
prediction = model_load.predict(feature_model)
#
st.write(prediction)
if prediction == 1:
st.warning('Es probable que fallezca si sus condiciones de salud permanecen igual')
else:
st.success("No es probable que fallezca")
elif choice == 'Mortalidad hopitalizado':
st.subheader("Se pretende predecir en base a los descriptores la mortalidad del paciente contagiado de CoV-2 al estar internado en el hospital")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.subheader("Data plot")
st.image(Image.open('plots/def_pos.png'), use_column_width=True)
st.image(Image.open('plots/def_edad_histograma.png'), use_column_width=True)
st.image(Image.open('plots/barplot_defuncion_edad.png'), use_column_width=True)
st.image(Image.open('plots/Tasa de casos de COVID en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Tasa de letalidad de COVID en México.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/def_hosp_data_grid_report.csv", index_col=0))
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
uci = st.radio("¿Requirió ingresar a una Unidad de Cuidados Intensivos?",tuple(feature_dict.keys()))
intub = st.radio("¿Requirió de intubación?",tuple(feature_dict.keys()))
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict),get_fval(intub),get_fval(uci)]
st.write(feature_list)
#ml
feature_model = np.array(feature_list).reshape(1,-1)
model_load = load_model('models/def_hosp_data_grid.pkl')
prediction = model_load.predict(feature_model)
st.write(prediction)
if prediction == 1:
st.warning('Es probable que fallezca si sus condiciones de salud permanecen igual')
else:
st.success("No es probable que fallezca")
elif choice == 'ICU antes del diagnostico de neumonia':
st.subheader("Se pretende predecir en base a los descriptores la necesidad de la Unidad de Cuidados Intensivos del paciente contagiado de CoV-2 al estar internado en el hospital sin tener un diagnostico de neumonia")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.subheader("Data plot")
st.image(Image.open('plots/barplot_casos_uci_int.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por sexo.png'), use_column_width=True)
st.image(Image.open('plots/Porcentaje de casos de hospitalizacion por COVID en Mexico por rangos de edad.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/icu_data_grid_report.csv", index_col=0))
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict)]
st.write(feature_list)
#ml
feature_model = np.array(feature_list).reshape(1,-1)
model_load = load_model('models/icu_data_grid.pkl')
prediction = model_load.predict(feature_model)
st.write(prediction)
if prediction == 1:
st.warning('Es probable que necesite ICU')
else:
st.success("No es probable que necesite ICU")
elif choice == 'ICU despues del diagnostico de neumonia':
st.subheader("Se pretende predecir en base a los descriptores la necesidad de la Unidad de Cuidados Intensivos del paciente contagiado de CoV-2 con un diagnostico de neumonia al estar internado en el hospital")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.image(Image.open('plots/barplot_casos_uci_int.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por sexo.png'), use_column_width=True)
st.image(Image.open('plots/Porcentaje de casos de hospitalizacion por COVID en Mexico por rangos de edad.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/icu_neum_data_grid_report.csv", index_col=0))
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
neum = st.radio("Resultado del diagnostico de neumonía",tuple(feature_dict.keys()))
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict),get_fval(neum)]
st.write(feature_list)
#ml
feature_model = np.array(feature_list).reshape(1,-1)
model_load = load_model('models/icu_neum_data_grid.pkl')
prediction = model_load.predict(feature_model)
st.write(prediction)
if prediction == 1:
st.warning('Es probable que necesite ICU')
else:
st.success("No es probable que necesite ICU")
elif choice == 'Ventilador antes de un diagnostico de neumonia y de ICU':
st.subheader("Se pretende predecir en base a los descriptores la necesidad de un ventilador invasivo del paciente contagiado de CoV-2 sin un diagnostico de neumonia y sin haber requerido de ICU al estar internado en el hospital")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.subheader("Data plot")
st.image(Image.open('plots/hosp_intubados_pos.png'), use_column_width=True)
st.image(Image.open('plots/barplot_casos_uci_int.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por sexo.png'), use_column_width=True)
st.image(Image.open('plots/Porcentaje de casos de hospitalizacion por COVID en Mexico por rangos de edad.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/vent_data_grid_report.csv", index_col=0))
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
#neum = st.radio("Resultado del diagnostico de neumonía",tuple(feature_dict.keys()))
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict)]#,get_fval(neum)]
st.write(feature_list)
#ml
feature_model = np.array(feature_list).reshape(1,-1)
model_load = load_model('models/vent_data_grid.pkl')
prediction = model_load.predict(feature_model)
st.write(prediction)
if prediction == 1:
st.warning('Es probable que necesite ventilador')
else:
st.success("No es probable que necesite ventilador")
elif choice == 'Ventilador despues de un diagnostico de neumonia y de ICU':
st.subheader("Se pretende predecir en base a los descriptores la necesidad de un ventilador invasivo del paciente contagiado de CoV-2 con un diagnostico de neumonia y haber requerido de ICU al estar internado en el hospital")
activity = st.selectbox("Activity", submenu)
if activity == "Plot":
st.subheader("Data plot")
st.image(Image.open('plots/hosp_intubados_pos.png'), use_column_width=True)
st.image(Image.open('plots/barplot_casos_uci_int.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por rangos de edad.png'), use_column_width=True)
st.image(Image.open('plots/Casos de COVID hospitalarios en Mexico por sexo.png'), use_column_width=True)
st.image(Image.open('plots/Porcentaje de casos de hospitalizacion por COVID en Mexico por rangos de edad.png'), use_column_width=True)
elif activity=='Prediction':
st.subheader("Análisis predictivo")
st.write(pd.read_csv("models/vent_ucineum_data_grid_report.csv", index_col=0))
age, emb, ren_cron, diab, inms, epoc, obes, otro, hiper, tab, cardio, asma, sex = descriptores()
neum = st.radio("Resultado del diagnostico de neumonía",tuple(feature_dict.keys()))
icu = st.radio("¿Requirió ingresar a una unidad de cuidados intensivos?",tuple(feature_dict.keys()))
feature_list = [age,get_fval(emb),get_fval(ren_cron),get_fval(diab),get_fval(inms),get_fval(epoc),get_fval(obes),get_fval(otro),get_fval(hiper),get_fval(tab),get_fval(cardio),get_fval(asma),get_value(sex,genero_dict),get_fval(icu),get_fval(neum)]
st.write(feature_list)
#ml
feature_model = np.array(feature_list).reshape(1,-1)
model_load = load_model('models/vent_ucineum_data_grid.pkl')
prediction = model_load.predict(feature_model)
st.write(prediction)
if prediction == 1:
st.warning('Es probable que necesite ventilador')
else:
st.success("No es probable que necesite ventilador")
if __name__ == '__main__':
main()
| StarcoderdataPython |
1681168 | # Copyright 2022 Tiernan8r
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from PySide6 import QtWidgets
from PySide6 import QtCore
from qcp.ui.components import AbstractComponent, \
ButtonComponent, GraphComponent
from qcp.ui.constants import LCD_CLASSICAL, LCD_GROVER
from qcp.matrices import Matrix
import qcp.algorithms as ga
import math
class SimulatorComponent(AbstractComponent):
"""
UI Component that handles the background task of running the Quantum
Computer Simulator code on a separate QThread.
"""
def __init__(self, main_window: QtWidgets.QMainWindow,
button_component: ButtonComponent,
graph_component: GraphComponent, *args, **kwargs):
"""
Initialise the SimulatorComponent object, referencing the main window
element, and the two UI components required for it to function.
:param QtWidgets.QMainWindow main_window: The main window element of
the UI.
:param ButtonComponent button_component: The search input box of the
UI
:param GraphComponent graph_component: The target input box of the UI
:param *args: variable length extra arguments to pass down
to QtCore.QObject
:param **kwargs: dictionary parameters to pass to QtCore.QObject
"""
self.button_component = button_component
self.graph_component = graph_component
super().__init__(main_window, *args, **kwargs)
def setup_signals(self):
"""
Initialise the QThread to run the simulation on and have it ready
to run when the input parameters are provided.
Setup signals to display the graph when the calculation completes,
and to hide the cancel button and progress bar.
"""
super().setup_signals()
self.qcp_thread = SimulateQuantumComputerThread()
self.qcp_thread.simulation_result_signal.connect(
self._simulation_results)
self.qcp_thread.finished.connect(self.update_lcd_displays)
# Hide the cancel button if the calculation finishes
self.qcp_thread.finished.connect(
self.button_component.cancel_button.hide)
self.qcp_thread.finished.connect(self.simulation_finished)
def _find_widgets(self):
lcds = self.main_window.ui_component.findChildren(QtWidgets.QLCDNumber)
for lcd in lcds:
if lcd.objectName() == LCD_CLASSICAL:
self.lcd_classical = lcd
elif lcd.objectName() == LCD_GROVER:
self.lcd_grover = lcd
def run_simulation(self, nqbits, target):
"""
Pass the input parameters to the QThread, and start up the
simulation
"""
# Code to initialise the qcp simulation on the qthread
# Pass the number of qbits and target bit over to the thread
self.nqbits = nqbits
self.qcp_thread.simulation_input_signal.emit(nqbits, target)
@QtCore.Slot(Matrix)
def _simulation_results(self, qregister):
"""
Signal catcher to read in the simulation results from the
QThread that it is calculated in.
"""
self.graph_component.display(qregister)
self.button_component.pb_thread.exiting = True
def simulation_finished(self):
"""
Function to handle behaviour when the QThread completes successfully
Shows the quantum state on the matplotlib graph
"""
self.graph_component.show()
def update_lcd_displays(self):
"""
Show the comparison between the number of iterations a classical
computer would have needed to run the search, versus the number
of iterations our quantum simulation took.
"""
if not self.nqbits:
return
# TODO: Don't know if this reasoning makes sense...
number_entries = math.log2(self.nqbits)
classical_average = math.ceil(number_entries / 2)
quantum_average = math.ceil(math.sqrt(number_entries))
self.lcd_classical.display(classical_average)
self.lcd_grover.display(quantum_average)
class SimulateQuantumComputerThread(QtCore.QThread):
"""
QThread object to handle the running of the Quantum Computer
Simulation, input/output is passed back to the main thread by pipes.
"""
simulation_result_signal = QtCore.Signal(Matrix)
simulation_input_signal = QtCore.Signal(int, int)
def __init__(self, parent=None):
"""
Setup the SimulateQuantumComputerThread QThread.
"""
super().__init__(parent)
self.simulation_input_signal.connect(self.input)
self.exiting = False
@QtCore.Slot(int, int)
def input(self, qbits, target):
if not self.isRunning():
self.nqbits = qbits
self.target = target
self.exiting = False
self.start()
else:
print("simulation already running!")
def run(self):
"""
Run the simulation
"""
# TODO: Actual calculated results would be passed back here...
grovers = ga.Grovers(self.nqbits, self.target)
qregister = None
try:
qregister = grovers.run()
except AssertionError as ae:
print(ae)
self.simulation_result_signal.emit(qregister)
self.quit()
| StarcoderdataPython |
5733 | <reponame>fabaff/spyse-python
import requests
from typing import List, Optional
from .models import AS, Domain, IP, CVE, Account, Certificate, Email, DNSHistoricalRecord, WHOISHistoricalRecord
from .response import Response
from .search_query import SearchQuery
from limiter import get_limiter, limit
class DomainsSearchResults:
def __init__(self, results: List[Domain], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[Domain] = results
class AutonomousSystemsSearchResults:
def __init__(self, results: List[AS], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[AS] = results
class IPSearchResults:
def __init__(self, results: List[IP], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[IP] = results
class CertificatesSearchResults:
def __init__(self, results: List[Certificate], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[Certificate] = results
class CVESearchResults:
def __init__(self, results: List[CVE], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[CVE] = results
class EmailsSearchResults:
def __init__(self, results: List[Email], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[Email] = results
class HistoricalDNSSearchResults:
def __init__(self, results: List[DNSHistoricalRecord], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[DNSHistoricalRecord] = results
class HistoricalWHOISSearchResults:
def __init__(self, results: List[WHOISHistoricalRecord], total_items: int = None, search_id: str = None):
self.total_items: Optional[int] = total_items
self.search_id: Optional[str] = search_id
self.results: List[WHOISHistoricalRecord] = results
class Client:
DEFAULT_BASE_URL = 'https://api.spyse.com/v4/data'
MAX_LIMIT = 100
SEARCH_RESULTS_LIMIT = 10000
RATE_LIMIT_FRAME_IN_SECONDS = 1
def __init__(self, api_token, base_url=DEFAULT_BASE_URL):
self.session = requests.Session()
self.session.headers.update({'Authorization': 'Bearer ' + api_token})
self.session.headers.update({'User-Agent': 'spyse-python'})
self.base_url = base_url
self.limiter = get_limiter(rate=self.RATE_LIMIT_FRAME_IN_SECONDS, capacity=1)
self.account = self.get_quotas()
self.limiter._capacity = self.account.requests_rate_limit
def __get(self, endpoint: str) -> Response:
with limit(self.limiter, consume=1):
return Response.from_dict(self.session.get(endpoint).json())
def __search(self, endpoint, query: SearchQuery, lim: int = MAX_LIMIT, offset: int = 0) -> Response:
with limit(self.limiter, consume=1):
return Response.from_dict(self.session.post(endpoint,
json={"search_params": query.get(), "limit": lim,
"offset": offset}).json())
def __scroll(self, endpoint, query: SearchQuery, search_id: Optional[str] = None) -> Response:
with limit(self.limiter, consume=1):
if search_id:
body = {"search_params": query.get(), "search_id": search_id}
else:
body = {"search_params": query.get()}
return Response.from_dict(self.session.post(endpoint, json=body).json())
def set_user_agent(self, s: str):
self.session.headers.update({'User-Agent': s})
def get_quotas(self) -> Optional[Account]:
"""Returns details about your account quotas."""
response = self.__get('{}/account/quota'.format(self.base_url))
response.check_errors()
return Account.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def get_autonomous_system_details(self, asn: int) -> Optional[AS]:
"""Returns details about an autonomous system by AS number."""
response = self.__get('{}/as/{}'.format(self.base_url, asn))
response.check_errors()
return AS.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def count_autonomous_systems(self, query: SearchQuery) -> int:
"""Returns the precise number of search results that matched the search query."""
response = self.__search('{}/as/search/count'.format(self.base_url), query)
response.check_errors()
return response.data.total_items
def search_autonomous_systems(self, query: SearchQuery, limit: int = MAX_LIMIT,
offset: int = 0) -> AutonomousSystemsSearchResults:
"""
Returns a list of autonomous systems that matched the search query.
Allows getting only the first 10,000 results.
"""
response = self.__search('{}/as/search'.format(self.base_url), query, limit, offset)
response.check_errors()
as_list = list()
for r in response.data.items:
as_list.append(AS.from_dict(r))
return AutonomousSystemsSearchResults(as_list, response.data.total_items)
def scroll_autonomous_systems(self, query: SearchQuery, scroll_id: str = None) -> AutonomousSystemsSearchResults:
"""
Returns a list of autonomous systems that matched the search query.
Allows getting all the results but requires a Spyse Pro subscription
"""
response = self.__scroll('{}/as/scroll/search'.format(self.base_url), query, scroll_id)
response.check_errors()
as_list = list()
for r in response.data.items:
as_list.append(AS.from_dict(r))
return AutonomousSystemsSearchResults(as_list, search_id=response.data.search_id)
def get_domain_details(self, domain_name: str) -> Optional[Domain]:
"""Returns details about domain"""
response = self.__get('{}/domain/{}'.format(self.base_url, domain_name))
response.check_errors()
return Domain.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def search_domains(self, query: SearchQuery, limit: int = MAX_LIMIT, offset: int = 0) -> DomainsSearchResults:
"""
Returns a list of domains that matched the search query.
Allows getting only the first 10,000 results.
"""
response = self.__search('{}/domain/search'.format(self.base_url), query, limit, offset)
response.check_errors()
domains = list()
for r in response.data.items:
domains.append(Domain.from_dict(r))
return DomainsSearchResults(domains, response.data.total_items)
def count_domains(self, query: SearchQuery):
"""Returns the precise number of search results that matched the search query."""
response = self.__search('{}/domain/search/count'.format(self.base_url), query)
response.check_errors()
return response.data.total_items
def scroll_domains(self, query: SearchQuery, scroll_id: str = None) -> DomainsSearchResults:
"""
Returns a list of domains that matched the search query.
Allows getting all the results but requires a Spyse Pro subscription
"""
response = self.__scroll('{}/domain/scroll/search'.format(self.base_url), query, scroll_id)
response.check_errors()
domains = list()
for r in response.data.items:
domains.append(Domain.from_dict(r))
return DomainsSearchResults(domains, search_id=response.data.search_id)
def get_ip_details(self, ip: str) -> Optional[IP]:
"""Returns details about IP"""
response = self.__get('{}/ip/{}'.format(self.base_url, ip))
response.check_errors()
return IP.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def search_ip(self, query: SearchQuery, limit: int = MAX_LIMIT, offset: int = 0) -> IPSearchResults:
"""
Returns a list of IPv4 hosts that matched the search query.
Allows getting only the first 10,000 results.
"""
response = self.__search('{}/ip/search'.format(self.base_url), query, limit, offset)
response.check_errors()
ips = list()
for r in response.data.items:
ips.append(IP.from_dict(r))
return IPSearchResults(ips, response.data.total_items)
def count_ip(self, query: SearchQuery) -> int:
"""Returns the precise number of search results that matched the search query."""
response = self.__search('{}/ip/search/count'.format(self.base_url), query)
response.check_errors()
return response.data.total_items
def scroll_ip(self, query: SearchQuery, scroll_id: str = None) -> IPSearchResults:
"""
Returns a list of IPv4 hosts that matched the search query.
Allows getting all the results but requires a Spyse Pro subscription
"""
response = self.__scroll('{}/ip/scroll/search'.format(self.base_url), query, scroll_id)
response.check_errors()
ips = list()
for r in response.data.items:
ips.append(IP.from_dict(r))
return IPSearchResults(ips, search_id=response.data.search_id)
def get_certificate_details(self, fingerprint_sha256: str) -> Optional[Certificate]:
"""Returns details about SSL/TLS certificate"""
response = self.__get('{}/certificate/{}'.format(self.base_url, fingerprint_sha256))
response.check_errors()
return Certificate.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def search_certificate(self, query: SearchQuery, limit: int = MAX_LIMIT,
offset: int = 0) -> CertificatesSearchResults:
"""
Returns a list of SSL/TLS certificate hosts that matched the search query.
Allows getting only the first 10,000 results.
"""
response = self.__search('{}/certificate/search'.format(self.base_url), query, limit, offset)
response.check_errors()
certs = list()
for r in response.data.items:
certs.append(Certificate.from_dict(r))
return CertificatesSearchResults(certs, response.data.total_items)
def count_certificate(self, query: SearchQuery) -> int:
"""Returns the precise number of search results that matched the search query."""
response = self.__search('{}/certificate/search/count'.format(self.base_url), query)
response.check_errors()
return response.data.total_items
def scroll_certificate(self, query: SearchQuery, scroll_id: str = None) -> CertificatesSearchResults:
"""
Returns a list of SSL/TLS certificates that matched the search query.
Allows getting all the results but requires a Spyse Pro subscription
"""
response = self.__scroll('{}/certificate/scroll/search'.format(self.base_url), query, scroll_id)
response.check_errors()
certs = list()
for r in response.data.items:
certs.append(Certificate.from_dict(r))
return CertificatesSearchResults(certs, search_id=response.data.search_id)
def get_cve_details(self, cve_id: str) -> Optional[CVE]:
"""Returns details about CVE"""
response = self.__get('{}/cve/{}'.format(self.base_url, cve_id))
response.check_errors()
return CVE.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def search_cve(self, query: SearchQuery, limit: int = MAX_LIMIT, offset: int = 0) -> CVESearchResults:
"""
Returns a list of CVE that matched the search query.
Allows getting only the first 10,000 results.
"""
response = self.__search('{}/cve/search'.format(self.base_url), query, limit, offset)
response.check_errors()
cve_list = list()
for r in response.data.items:
cve_list.append(CVE.from_dict(r))
return CVESearchResults(cve_list, response.data.total_items)
def count_cve(self, query: SearchQuery) -> int:
"""Returns the precise number of search results that matched the search query."""
response = self.__search('{}/cve/search/count'.format(self.base_url), query)
response.check_errors()
return response.data.total_items
def scroll_cve(self, query: SearchQuery, scroll_id: str = None) -> CVESearchResults:
"""
Returns a list of CVEs that matched the search query.
Allows getting all the results but requires a Spyse Pro subscription
"""
response = self.__scroll('{}/cve/scroll/search'.format(self.base_url), query, scroll_id)
response.check_errors()
cve_list = list()
for r in response.data.items:
cve_list.append(CVE.from_dict(r))
return CVESearchResults(cve_list, search_id=response.data.search_id)
def get_email_details(self, email: str) -> Optional[Email]:
"""Returns details about email"""
response = self.__get('{}/email/{}'.format(self.base_url, email))
response.check_errors()
return Email.from_dict(response.data.items[0]) if len(response.data.items) > 0 else None
def search_emails(self, query: SearchQuery, limit: int = MAX_LIMIT, offset: int = 0) -> EmailsSearchResults:
"""
Returns a list of emails that matched the search query.
Allows getting only the first 10,000 results.
"""
response = self.__search('{}/email/search'.format(self.base_url), query, limit, offset)
response.check_errors()
emails = list()
for r in response.data.items:
emails.append(Email.from_dict(r))
return EmailsSearchResults(emails, response.data.total_items)
def count_emails(self, query: SearchQuery) -> int:
"""Returns the precise number of search results that matched the search query."""
response = self.__search('{}/cve/email/count'.format(self.base_url), query)
response.check_errors()
return response.data.total_items
def scroll_emails(self, query: SearchQuery, scroll_id: str = None) -> EmailsSearchResults:
"""
Returns a list of emails that matched the search query.
Allows getting all the results but requires a Spyse Pro subscription
"""
response = self.__scroll('{}/email/scroll/search'.format(self.base_url), query, scroll_id)
response.check_errors()
emails = list()
for r in response.data.items:
emails.append(Email.from_dict(r))
return EmailsSearchResults(emails, search_id=response.data.search_id)
def search_historical_dns(self, dns_type, domain_name: str, limit: int = MAX_LIMIT, offset: int = 0) \
-> HistoricalDNSSearchResults:
"""
Returns the historical DNS records about the given domain name.
"""
response = self.__get(f'{self.base_url}/history/dns/{dns_type}/{domain_name}?limit={limit}&offset={offset}')
response.check_errors()
records = list()
for r in response.data.items:
records.append(DNSHistoricalRecord.from_dict(r))
return HistoricalDNSSearchResults(records, response.data.total_items)
def search_historical_whois(self, domain_name: str, limit: int = MAX_LIMIT, offset: int = 0) \
-> HistoricalWHOISSearchResults:
"""
Returns the historical WHOIS records for the given domain name.
"""
response = self.__get(f'{self.base_url}/history/domain-whois/{domain_name}?limit={limit}&offset={offset}')
response.check_errors()
records = list()
for r in response.data.items:
records.append(WHOISHistoricalRecord.from_dict(r))
return HistoricalWHOISSearchResults(records, response.data.total_items)
| StarcoderdataPython |
35655 | '''4. Write a Python program to check whether multiple variables have the same value.'''
var1, var2, var3 = 20, 20, 20
if var1 == var2== var3:
print("var1, var2, and var3 have the same value !") | StarcoderdataPython |
1648022 | <filename>paasta_tools/contrib/delete_old_marathon_deployments.py
#!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import datetime
import logging
import dateutil.parser
from dateutil import tz
from pytimeparse import timeparse
from paasta_tools import marathon_tools
log = logging.getLogger(__name__)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-a', '--age', dest='age', type=timedelta_type, default='1h',
help="Max age of a Marathon deployment before it is stopped."
"Any pytimeparse unit is supported",
)
parser.add_argument(
'-n', '--dry-run', action="store_true",
help="Don't actually stop any Marathon deployments",
)
parser.add_argument('-v', '--verbose', action='store_true')
options = parser.parse_args()
return options
def timedelta_type(value):
"""Return the :class:`datetime.datetime.DateTime` for a time in the past.
:param value: a string containing a time format supported by :mod:`pytimeparse`
"""
if value is None:
return None
return datetime_seconds_ago(timeparse.timeparse(value))
def datetime_seconds_ago(seconds):
return now() - datetime.timedelta(seconds=seconds)
def now():
return datetime.datetime.now(tz.tzutc())
def delete_deployment_if_too_old(client, deployment, max_date, dry_run):
started_at = dateutil.parser.parse(deployment.version)
age = now() - started_at
if started_at < max_date:
if dry_run is True:
log.warning("Would delete %s for %s as it is %s old" % (deployment.id, deployment.affected_apps[0], age))
else:
log.warning("Deleting %s for %s as it is %s old" % (deployment.id, deployment.affected_apps[0], age))
client.delete_deployment(deployment_id=deployment.id, force=False)
else:
if dry_run is True:
log.warning("NOT deleting %s for %s as it is %s old" % (deployment.id, deployment.affected_apps[0], age))
def main():
args = parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.WARNING)
clients = marathon_tools.get_list_of_marathon_clients()
for client in clients:
for deployment in client.list_deployments():
delete_deployment_if_too_old(
client=client,
deployment=deployment,
max_date=args.age,
dry_run=args.dry_run,
)
if __name__ == "__main__":
main()
| StarcoderdataPython |
1711303 | <reponame>tefra/xsdata-w3c-tests
from dataclasses import dataclass, field
@dataclass
class Iri3987:
class Meta:
name = "IRI-3987"
value: str = field(
default="",
metadata={
"required": True,
"pattern": r"",
}
)
@dataclass
class IriReference3987:
class Meta:
name = "IRI-reference-3987"
value: str = field(
default="",
metadata={
"pattern": r"",
}
)
@dataclass
class Uri3986:
class Meta:
name = "URI-3986"
value: str = field(
default="",
metadata={
"required": True,
"pattern": r"((([A-Za-z])[A-Za-z0-9+\-\.]*):((\?((([A-Za-z0-9\-\._~!$&'()*+,;=:@]|(%[0-9A-Fa-f][0-9A-Fa-f]))|/|\?))*))?((#((([A-Za-z0-9\-\._~!$&'()*+,;=:@]|(%[0-9A-Fa-f][0-9A-Fa-f]))|/|\?))*))?)",
}
)
@dataclass
class UriReference3986:
class Meta:
name = "URI-reference-3986"
value: str = field(
default="",
metadata={
"pattern": r"((([A-Za-z])[A-Za-z0-9+\-\.]*):((\?((([A-Za-z0-9\-\._~!$&'()*+,;=:@]|(%[0-9A-Fa-f][0-9A-Fa-f]))|/|\?))*))?((#((([A-Za-z0-9\-\._~!$&'()*+,;=:@]|(%[0-9A-Fa-f][0-9A-Fa-f]))|/|\?))*))?)",
}
)
@dataclass
class AbsoluteIri3987:
class Meta:
name = "absolute-IRI-3987"
value: str = field(
default="",
metadata={
"required": True,
"pattern": r"",
}
)
@dataclass
class AbsoluteUri3986:
class Meta:
name = "absolute-URI-3986"
value: str = field(
default="",
metadata={
"required": True,
"pattern": r"((([A-Za-z])[A-Za-z0-9+\-\.]*):((\?((([A-Za-z0-9\-\._~!$&'()*+,;=:@]|(%[0-9A-Fa-f][0-9A-Fa-f]))|/|\?))*))?)",
}
)
@dataclass
class RelativeReference3986:
class Meta:
name = "relative-reference-3986"
value: str = field(
default="",
metadata={
"required": True,
"pattern": r"",
}
)
@dataclass
class RelativeReference3987:
class Meta:
name = "relative-reference-3987"
value: str = field(
default="",
metadata={
"required": True,
"pattern": r"",
}
)
| StarcoderdataPython |
4815432 | import json
import sys
from pathlib import Path
TYPE_ENUM_ENTRY_TEMPLATE = "\
%(enum_id)s(%(enum_type)s),\n"
ID_ENUM_ENTRY_TEMPLATE = "\
%(enum_id)s = %(enum_value)#04x,\n"
ID_TRY_FROM_MATCH_ENTRY_TEMPLATE = "\
x if x == SEOutputDataId::%(enum_id)s as u16 => Ok(SEOutputDataId::%(enum_id)s),\n"
OUTPUT_TEMPLATE = """
// NOTE: this file is generated by generate_output_data.py
use super::types::*;
#[derive(Debug, PartialEq)]
pub enum SEOutputData {
%(type_enum_entries)s
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u16)]
pub enum SEOutputDataId {
%(id_enum_entries)s
}
impl std::convert::TryFrom<u16> for SEOutputDataId {
type Error = ();
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
%(try_from_match_entries)s
_ => unimplemented!("{:#x}", value),
}
}
}
"""
SEP_TO_RUST_DATA_TYPE = {
"SEType_u8": "SETypeU8",
"SEType_u16": "SETypeU16",
"SEType_u32": "SETypeU32",
"SEType_u64": "SETypeU64",
"SEType_float": "SETypeFloat",
"SEType_f64": "SETypeF64",
"SEType_Vector": "SETypeVector",
"SEType_Point2D": "SETypePoint2D",
"SEType_Point3D": "SETypePoint3D",
"SEType_Vect3D": "SETypeVect3D",
"SEType_String": "SETypeString",
"SEType_Quaternion": "SETypeQuaternion",
"SEType_UserMarker": "SETypeUserMarker",
"SEType_WorldIntersection": "SETypeWorldIntersection",
"SEType_WorldIntersections": "SETypeWorldIntersections",
}
def main():
data_output_json = Path(sys.argv[1])
out_file = Path(sys.argv[2])
assert (data_output_json.is_file())
with data_output_json.open() as f:
output_data_definitions = json.load(f)
type_enum_entries = ""
id_enum_entries = ""
id_try_from_match_entries = ""
for d in output_data_definitions:
enum_id = d["EnumID"]
enum_number = int(d["EnumNumber"], 16)
data_type = SEP_TO_RUST_DATA_TYPE[d["DataType"]]
required_module = d["RequiredModule"]
if required_module == "FacialFeatures":
# TODO: maybe support FacialFeatures module in the future..?
continue
type_enum_entries += TYPE_ENUM_ENTRY_TEMPLATE % {
'enum_id': enum_id, 'enum_type': data_type
}
id_enum_entries += ID_ENUM_ENTRY_TEMPLATE % {
'enum_id': enum_id,
'enum_value': enum_number
}
id_try_from_match_entries += ID_TRY_FROM_MATCH_ENTRY_TEMPLATE % {
'enum_id': enum_id
}
file_content = OUTPUT_TEMPLATE % {
'type_enum_entries': type_enum_entries,
'id_enum_entries': id_enum_entries,
'try_from_match_entries': id_try_from_match_entries
}
out_file.write_text(file_content)
if __name__ == "__main__":
main()
| StarcoderdataPython |
86423 | # Spider: A Spider in the game. The most basic unit.
# DO NOT MODIFY THIS FILE
# Never try to directly create an instance of this class, or modify its member variables.
# Instead, you should only be reading its variables and calling its functions.
from games.spiders.game_object import GameObject
# <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# you can add additional import(s) here
# <<-- /Creer-Merge: imports -->>
class Spider(GameObject):
"""The class representing the Spider in the Spiders game.
A Spider in the game. The most basic unit.
"""
def __init__(self):
"""Initializes a Spider with basic logic as provided by the Creer code generator."""
GameObject.__init__(self)
# private attributes to hold the properties so they appear read only
self._is_dead = False
self._nest = None
self._owner = None
@property
def is_dead(self):
"""If this Spider is dead and has been removed from the game.
:rtype: bool
"""
return self._is_dead
@property
def nest(self):
"""The Nest that this Spider is currently on. None when moving on a Web.
:rtype: Nest
"""
return self._nest
@property
def owner(self):
"""The Player that owns this Spider, and can command it.
:rtype: Player
"""
return self._owner
# <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# if you want to add any client side logic (such as state checking functions) this is where you can add them
# <<-- /Creer-Merge: functions -->>
| StarcoderdataPython |
3273466 | <reponame>simonmeoni/JRSTC-competition
from transformers import AutoConfig, AutoModel
def rm_dropout(model, remove_dropout):
if remove_dropout:
cfg = AutoConfig.from_pretrained(model)
cfg.hidden_dropout_prob = 0
cfg.attention_probs_dropout_prob = 0
return AutoModel.from_pretrained(model, config=cfg)
else:
return AutoModel.from_pretrained(model)
| StarcoderdataPython |
3383142 | import pytest
from autogoal.contrib import find_classes
classes = find_classes()
@pytest.mark.contrib
@pytest.mark.parametrize("clss", classes)
def test_create_grammar_for_generated_class(clss):
from autogoal.grammar import generate_cfg
generate_cfg(clss, registry=classes)
@pytest.mark.slow
@pytest.mark.contrib
@pytest.mark.parametrize("clss", classes)
def test_sample_generated_class(clss):
from autogoal.grammar import generate_cfg, Sampler
grammar = generate_cfg(clss, registry=classes)
sampler = Sampler(random_state=0)
for _ in range(1000):
grammar.sample(sampler=sampler)
| StarcoderdataPython |
1789931 | <reponame>mohammadbashiri/bashiri-et-al-2021<filename>neuraldistributions/trainers.py<gh_stars>1-10
from copy import deepcopy
from abc import ABC, abstractmethod
import numpy as np
import torch
from torch import optim, nn
from tqdm import tqdm, trange
from neuralpredictors.training import LongCycler
from .utility import (
EarlyStopping,
set_random_seed,
)
from .utility import Correlation
class Trainer:
def __init__(
self,
model,
dataloaders,
seed,
lr=0.005,
epochs=20,
use_avg_loss=False,
loss_accum_batch_n=None,
early_stopping=True,
device=torch.device("cuda"),
measure_for_scheduling="correlation",
switch_measure_for_scheduling=False,
compute_conditional_corr=False,
compute_correlation=True,
cb=None,
**kwargs,
):
self.model = model
self.seed = seed
self.train_loader, self.val_loader = (
dataloaders["train"],
dataloaders["validation"],
)
self.lr = lr
self.epochs = int(epochs)
self.use_avg_loss = use_avg_loss
self.device = device
self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr)
self.train_losses, self.val_losses = [], []
self.train_corrs_mean, self.val_corrs_mean = [], []
self.lrs = []
self.current_epoch = 0
self.optim_step_count = (
len(self.train_loader.keys())
if loss_accum_batch_n is None
else loss_accum_batch_n
)
self.compute_correlation = compute_correlation
self.measure_for_scheduling = (
measure_for_scheduling if compute_correlation else "loss"
)
self.switch_measure_for_scheduling = (
switch_measure_for_scheduling if compute_correlation else False
)
self.compute_conditional_corr = compute_conditional_corr
self.cb = cb
if measure_for_scheduling == "correlation":
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(
self.optimizer,
"max",
factor=0.3,
patience=10,
min_lr=1e-8,
verbose=True,
threshold_mode="abs",
)
self.early_stopping = (
EarlyStopping(mode="max", patience=20, verbose=True)
if early_stopping
else None
)
elif measure_for_scheduling == "loss":
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(
self.optimizer,
"min",
factor=0.3,
patience=10,
min_lr=1e-8,
verbose=True,
threshold_mode="abs",
)
self.early_stopping = (
EarlyStopping(mode="min", patience=20, verbose=True)
if early_stopping
else None
)
def train_step(self, batch, data_key):
x, y = batch[:2]
if self.use_avg_loss:
return self.model.loss(
*batch, data_key=data_key, use_avg=self.use_avg_loss
) + self.model.regularizer(data_key)
else:
dd = self.train_loader[data_key].dataset
m = dd.images.shape[0] if hasattr(dd, "images") else dd.tensors[0].shape[0]
k = x.shape[0]
return (
np.sqrt(m / k)
* self.model.loss(*batch, data_key=data_key, use_avg=self.use_avg_loss)
+ self.model.regularizer(data_key)
) / (y.shape[0] * y.shape[1])
def train_one_epoch(self):
"""Training function for a single epoch.
Returns:
float: Loss (of the first iteration).
"""
self.model.train()
losses = []
losses_ = 0.0
self.optimizer.zero_grad()
for batch_idx, (data_key, batch) in enumerate(
tqdm(LongCycler(self.train_loader))
):
loss = self.train_step(batch, data_key=data_key)
loss.backward()
losses_ += loss.item()
if (batch_idx + 1) % self.optim_step_count == 0:
self.optimizer.step()
self.optimizer.zero_grad()
losses.append(losses_ / self.optim_step_count)
losses_ = 0
return losses[0] # return the first computed loss in the epoch
def validation_step(self, batch, data_key):
x, y = batch[:2]
if self.use_avg_loss:
return self.model.loss(*batch, data_key=data_key, use_avg=self.use_avg_loss)
else:
dd = self.val_loader[data_key].dataset
m = dd.images.shape[0] if hasattr(dd, "images") else dd.tensors[0].shape[0]
k = x.shape[0]
return (
np.sqrt(m / k)
* self.model.loss(*batch, data_key=data_key, use_avg=self.use_avg_loss)
/ (y.shape[0] * y.shape[1])
)
@torch.no_grad()
def validate_one_epoch(self):
"""Validation performance.
Returns:
float: Loss (of the first iteration).
"""
self.model.eval()
losses = []
losses_ = 0
for batch_idx, (data_key, batch) in enumerate(LongCycler(self.val_loader)):
loss = self.validation_step(batch, data_key)
losses_ += loss.item()
if (batch_idx + 1) % self.optim_step_count == 0:
losses.append(losses_ / self.optim_step_count)
losses_ = 0
return losses[0]
def train(self):
# set the manual seed before running the epochs
set_random_seed(self.seed)
# establish a baseline via the validastion dataset
with torch.no_grad():
val_loss = self.validate_one_epoch()
if self.compute_correlation:
_, val_corrs = Correlation.single_trial(self.val_loader, self.model)
val_corr_mean = val_corrs.mean()
if self.early_stopping:
if self.measure_for_scheduling == "correlation":
self.early_stopping(val_corr_mean, self.model)
elif self.measure_for_scheduling == "loss":
self.early_stopping(val_loss, self.model)
old_lr = self.lr
lrs_counter = 0
for self.current_epoch in range(self.epochs):
if self.cb is not None:
self.cb()
# keep track of the learning rate
current_lr = self.optimizer.param_groups[0]["lr"]
if current_lr - old_lr:
self.retrive_best_model()
# switch the early stopping and lr scheduler to depend on loss (-loglikelihood)
if (lrs_counter == 0) and self.switch_measure_for_scheduling:
self.measure_for_scheduling = "loss"
print(
f"Changing the measure for early stopping and lr scheduler to {self.measure_for_scheduling}",
flush=True,
)
with torch.no_grad():
val_loss = self.validate_one_epoch()
self.early_stopping.mode = "min"
self.early_stopping.best_score = val_loss
self.early_stopping.last_best_score = val_loss
self.scheduler.mode = "min"
self.scheduler.best = val_loss
if hasattr(self.model, "apply_changes_while_training") and (
lrs_counter == 0
):
print("Applying changes..", flush=True)
self.model.apply_changes_while_training()
self.optimizer.param_groups[0]["lr"] = old_lr
# replace optimizer
if hasattr(self.model, "change_optimizer") and (lrs_counter == 0):
self.optimizer = self.model.change_optimizer(self.optimizer)
lrs_counter += 1
old_lr = current_lr
train_loss = self.train_one_epoch()
self.train_losses.append(train_loss)
val_loss = self.validate_one_epoch()
self.val_losses.append(val_loss)
if self.compute_correlation:
with torch.no_grad():
_, train_corrs = Correlation.single_trial(
self.train_loader, self.model
)
train_corr_mean = train_corrs.mean()
if self.compute_conditional_corr and (lrs_counter > 0):
_, val_corrs = Correlation.conditional_single_trial(
self.val_loader, self.model
)
else:
_, val_corrs = Correlation.single_trial(
self.val_loader, self.model
)
val_corr_mean = val_corrs.mean()
self.train_corrs_mean.append(train_corr_mean)
self.val_corrs_mean.append(val_corr_mean)
self.lrs.append(self.optimizer.state_dict()["param_groups"][0]["lr"])
if self.compute_correlation:
print_string = "Epoch {}/{} | train loss: {:.6f} | val loss: {:.6f} | train corr: {:.6f} | val corr: {:.6f}"
msg = print_string.format(
self.current_epoch + 1,
self.epochs,
train_loss,
val_loss,
train_corr_mean,
val_corr_mean,
)
else:
print_string = "Epoch {}/{} | train loss: {:.6f} | val loss: {:.6f}"
msg = print_string.format(
self.current_epoch + 1,
self.epochs,
train_loss,
val_loss,
)
print(msg, flush=True)
if self.early_stopping:
if self.measure_for_scheduling == "correlation":
self.early_stopping(val_corr_mean, self.model)
elif self.measure_for_scheduling == "loss":
self.early_stopping(val_loss, self.model)
if self.early_stopping.early_stop:
best_val = (
np.array(self.val_corrs_mean).max()
if self.measure_for_scheduling == "correlation"
else np.array(self.val_losses).min()
)
msg = "Early stopping at epoch {}. Best val {}: {:.3f}".format(
self.current_epoch,
self.measure_for_scheduling,
best_val,
)
print(msg, flush=True)
break
if self.measure_for_scheduling == "correlation":
self.scheduler.step(val_corr_mean)
elif self.measure_for_scheduling == "loss":
self.scheduler.step(val_loss)
if self.early_stopping:
self.retrive_best_model()
if self.compute_correlation:
return {
"model": self.model,
"train_losses": np.array(self.train_losses),
"val_losses": np.array(self.val_losses),
"train_corrs": np.array(self.train_corrs_mean),
"val_corrs": np.array(self.val_corrs_mean),
"lrs": np.array(self.lrs),
}
else:
return {
"model": self.model,
"train_losses": np.array(self.train_losses),
"val_losses": np.array(self.val_losses),
"lrs": np.array(self.lrs),
}
def retrive_best_model(self):
if self.early_stopping:
if self.early_stopping.best_model_state_dict is not None:
print("Retrieve best model..", flush=True)
self.model.load_state_dict(
deepcopy(self.early_stopping.best_model_state_dict)
)
else:
print("Keep existing model..", flush=True)
def base_trainer(
model,
dataloaders,
seed,
lr=0.005,
epochs=20,
use_avg_loss=False,
loss_accum_batch_n=None,
early_stopping=True,
device="cuda",
measure_for_scheduling="loss",
switch_measure_for_scheduling=False,
compute_conditional_corr=False,
compute_correlation=False,
**kwargs,
):
trainer = Trainer(
model,
dataloaders,
seed,
lr=lr,
epochs=epochs,
use_avg_loss=use_avg_loss,
loss_accum_batch_n=loss_accum_batch_n,
early_stopping=early_stopping,
device=device,
measure_for_scheduling=measure_for_scheduling,
switch_measure_for_scheduling=switch_measure_for_scheduling,
compute_conditional_corr=compute_conditional_corr,
compute_correlation=compute_correlation,
**kwargs,
)
out = trainer.train()
if compute_correlation:
score = np.max(out["val_corrs"])
other_outputs = (
out["train_losses"],
out["val_losses"],
out["train_corrs"],
out["val_corrs"],
out["lrs"],
)
model_state_dict = out["model"].state_dict()
else:
score = np.min(out["val_losses"])
other_outputs = (out["train_losses"], out["val_losses"], out["lrs"])
model_state_dict = out["model"].state_dict()
return score, other_outputs, model_state_dict
class DensityEstimatorTrainer:
def __init__(
self,
model,
dataloaders,
seed,
lr=0.005,
epochs=20,
device=torch.device("cuda"),
cb=None,
**kwargs,
):
self.model = model
self.trainloaders = dataloaders["train"]
self.seed = seed
self.lr = lr
self.epochs = int(epochs)
self.device = device
self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr)
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(
self.optimizer,
"min",
factor=0.3,
patience=10,
min_lr=1e-8,
verbose=True,
threshold_mode="abs",
)
self.early_stopping = EarlyStopping(mode="min", patience=20, verbose=False)
self.losses = []
self.lrs = []
self.current_epoch = 0
self.cb = cb
def train_one_epoch(self):
self.model.train()
losses = []
self.optimizer.zero_grad()
for batch in self.trainloaders:
loss = self.model.loss(*batch) + self.model.regularizer()
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
losses.append(loss.item())
return np.mean(losses)
def train(self):
set_random_seed(self.seed)
old_lr = self.lr
lrs_counter = 0
pbar = trange(self.epochs, desc="Loss: {}".format(np.nan), leave=True)
for self.current_epoch in pbar:
if self.cb is not None:
self.cb()
# keep track of the learning rate and change stuff when it drop for the first time
current_lr = self.optimizer.param_groups[0]["lr"]
if current_lr - old_lr:
self.retrive_best_model()
old_lr = current_lr
if hasattr(self.model, "apply_changes_while_training") and (
lrs_counter == 0
):
print("Applying changes..", flush=True)
self.model.apply_changes_while_training()
lrs_counter += 1
loss = self.train_one_epoch()
self.losses.append(loss)
self.lrs.append(self.optimizer.state_dict()["param_groups"][0]["lr"])
print_string = "Epoch {}/{} | loss: {:.2f}"
msg = print_string.format(
self.current_epoch + 1, self.epochs, self.losses[-1]
)
pbar.set_description(msg)
self.early_stopping(self.losses[-1], self.model)
if self.early_stopping.early_stop:
best_loss = np.array(self.losses).min()
msg = "Early stopping at epoch {}. Best loss: {:.3f}".format(
self.current_epoch, best_loss
)
print(msg, flush=True)
break
self.scheduler.step(self.losses[-1])
self.retrive_best_model()
return (self.model, np.array(self.losses), np.array(self.lrs))
def retrive_best_model(self):
if self.early_stopping.best_model_state_dict is not None:
print("Retrieve best model..", flush=True)
self.model.load_state_dict(
deepcopy(self.early_stopping.best_model_state_dict)
)
else:
print("Keep existing model..", flush=True)
def density_estimator_trainer(
model,
dataloaders,
seed,
lr=0.005,
epochs=20,
device=torch.device("cuda"),
cb=None,
**kwargs,
):
trainer = DensityEstimatorTrainer(
model, dataloaders, seed, lr=lr, epochs=epochs, device=device, cb=cb, **kwargs
)
out = trainer.train()
return out[1].min(), out[1:], out[0].state_dict() | StarcoderdataPython |
3345964 | import string
import talk
DEBUGGING = False
masterSchedule = []
talkPRE = '<h3 class="talkTitle">'
talkPOST = '</h3>'
dayTimeTrackPRE = '<p class="abstract">'
dayTimeTrackPOST = '</p>'
speakerPRE = '<h4 class="speaker">'
speakerPOST = '<span'
descriptionPRE = '<p class="abstract">'
descriptionPOST = '</p>'
def Parse(html):
htmlString = html.read()
idNum = 0
while len(htmlString) != 0 and string.find(htmlString, "day at") != -1: #crude, but that string existing means that there's another talk to parse
#Get Talk Title
start = string.find(htmlString, talkPRE) + len(talkPRE) # Establishes start index as first letter in title
htmlString = htmlString[start:] #Trims down the file
stop = string.find(htmlString, talkPOST) #Establishes stop index as last letter in title
title = htmlString[:stop] #Establishes talk title
htmlString = htmlString[stop:]
#Get talk day
start = string.find(htmlString, dayTimeTrackPRE) + len(dayTimeTrackPRE) #Establishes start as first letter in day / time / track string
htmlString = htmlString[start:] #Trims down the file
stop = string.find(htmlString, 'day') + 3 #Establishes stop as end of day
day = htmlString[:stop]
if len(day) > 8:
continue
htmlString = htmlString[stop:]
#Get talk time
start = string.find(htmlString, ':') - 2 #Set start index as 2 chars before ':' which will always work as earliest talk is at 10:00
if start - stop > 25: #ugly hack to fix annoying bug
continue
htmlString = htmlString[start:] #Trims string
time = htmlString[:5] #Establishes talk time
#Get talk track
if string.find(htmlString[:25], '101') != -1: #if '101' appears, making it the track
track = 101
else:
track = htmlString[15] #Probably shouldn't be hardcoded but it's more efficient that hunting for the next digit
if not str(track).isdigit(): #Special cases such as "20:00 - 22:00 in Modena Room" are rare and can be their own thing implemented later. They only come up ~4 times.
continue
#Get speaker
start = string.find(htmlString, speakerPRE) + len(speakerPRE)
stop = string.find(htmlString, speakerPOST)
speaker = htmlString[start:stop] #sets speaker value
htmlString = htmlString[stop:] #trims down file (I know I'm inconsistent with file vs string. Sorry.)
#Get description - KNOWN BUG - LINE BREAKS (<br>) ARE STILL IN TEXT
start = string.find(htmlString, descriptionPRE) + len(descriptionPRE)
htmlString = htmlString[start:]
stop = string.find(htmlString, descriptionPOST)
description = htmlString[:stop]
if DEBUGGING:
print "Title: " + title
print "Day: " + day
print "Time: " + time
print "Track: " + str(track)
print "Speaker(s): " + speaker
#print "Description: " + description
masterSchedule.append(talk.talk(day, time, track, title, speaker, description, idNum)) #Add the talk to the list
idNum += 1 #Increment identifier
return masterSchedule | StarcoderdataPython |
1703919 | <filename>tensorflow_/2zhang/14_tf_keras_regression-wide&deep-multi-input.py
# coding:utf-8
import matplotlib as mpl
import matplotlib.pyplot as plt
# %matplotlib inline
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras
# 打印name和版本
print(tf.__version__)
print(sys.version_info)
for module in mpl, np, pd, sklearn, tf, keras:
print(module.__name__, module.__version__)
"""
wide & deep模型 的 多输入
keras子类API
功能API(函数式API)
多输入与多输出
回归模型 适合wide & deep模型,有8个特征可以划分给 wide 和 deep, 而图像分类中分类价值都一样,在次没意义
房价预测 数据集 (加尼福利亚的房价的数据集)
下载数据集失败,浏览器下载:https://s3-eu-west-1.amazonaws.com/pfigshare-u-files/5976036/cal_housing.tgz
注释源码:urlretrieve(remote.url, file_path) 加载完成本地数据集后 取消注释
让一个分类模型变成回归模型:
keras.layers.Dense(1), # 输出一个数
model.compile(loss='mean_squared_error'
"""
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing() # 获取数据
# 了解数据集
# print(housing.DESCR)
# print(housing.data.shape) # 数据大小 ,相当于 x
# print(housing.target.shape) # target大小 ,相当于 y
# 查看数据集 数据
import pprint # 打印结果会好看 pprint
# pprint.pprint(housing.data[0:5]) # x
# pprint.pprint(housing.target[0:5]) # y
# 划分样本
from sklearn.model_selection import train_test_split
# 拆分训练集 / 测试集 , 默认情况train_test_split将数据以3:1 的方式划分,(后面的是4:1),默认就是test_size=0.25
x_train_all, x_test, y_train_all, y_test = train_test_split(housing.data, housing.target, random_state=7, test_size=0.25)
# 拆分训练集 / 验证集
x_train, x_valid, y_train, y_valid = train_test_split(x_train_all, y_train_all, random_state=11)
print(x_train.shape, y_train.shape) # 查看样本
print(x_valid.shape, y_valid.shape)
print(x_test.shape, y_test.shape)
# 归一化
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
x_train_scaler = scaler.fit_transform(x_train)
x_valid_scaled = scaler.transform(x_valid)
x_test_scaled = scaler.transform(x_test)
#############################wide&deep模型的多输入###########################################
# 搭建模型
# 多输入
input_wide = keras.layers.Input(shape=[5])
input_deep = keras.layers.Input(shape=[6])
hidden1 = keras.layers.Dense(30, activation='relu')(input_deep)
hidden2 = keras.layers.Dense(30, activation='relu')(hidden1)
concat = keras.layers.concatenate([input_wide, hidden2]) # 拼接起来
output = keras.layers.Dense(1)(concat) # 函数式调用
model = keras.models.Model(inputs=[input_wide, input_deep], outputs=[output])
# fit前需要拆分模型
print(model.summary())
# 编译模型 计算目标函数
model.compile(loss='mean_squared_error', optimizer=keras.optimizers.SGD(0.001)) # 编译model
# 会调
callbacks = [keras.callbacks.EarlyStopping(patience=5, min_delta=1e-3)]
# 因为有两个输入数据,需要拆分
x_train_scaled_wide= x_train_scaler[:, :5] # 取前5个
x_train_scaled_deep= x_train_scaler[:, 2:]
x_valid_scaled_wide = x_valid_scaled[:, :5]
x_valid_scaled_deep = x_valid_scaled[:, 2:]
x_test_scaled_wide = x_test_scaled[:, :5]
x_test_scaled_deep = x_test_scaled[:, 2:]
# 训练, 多输入x替换
history = model.fit([x_train_scaled_wide, x_train_scaled_deep], y_train,
validation_data=([x_valid_scaled_wide, x_valid_scaled_deep], y_valid),
epochs=100, callbacks=callbacks)
# 通过一张图打印出 训练值的变化过程
def polt_learning_curves(history):
pd.DataFrame(history.history).plot(figsize=(8, 5)) # DataFrame是pd中重要的数据结构, 图大小8和5
plt.grid(True) # 显示网格
plt.gca().set_ylim(0, 1)# 坐标轴范围, 如果图显示不全调整下x,y轴
plt.show()
polt_learning_curves(history) # 打印值训练值变化图
# 测试模型
test_result = model.evaluate([x_test_scaled_wide, x_test_scaled_deep], y_test)
print(test_result) | StarcoderdataPython |
3326239 | <filename>results-dissertation/cosine-sim/plot.py
import matplotlib.pyplot as plt
from scipy.spatial import distance
from scipy import spatial
a = [1, 2]
b = [2, 1]
c = distance.euclidean(a, b)
a = [1, 2, 3]
b = [3, 2, 1]
c = [2, 3, 1]
print(1 - spatial.distance.cosine(a, b))
print(1 - spatial.distance.cosine(a, c))
print(distance.euclidean(a, b))
print(distance.euclidean(a, c))
| StarcoderdataPython |
1635680 | <reponame>fbickfordsmith/attention-msc
"""
Define a set of 20 difficulty-based category sets. These are subsets of ImageNet
categories that we choose to have varying difficulty (average error rate of
VGG16) but equal size and approx equal visual similarity.
Method:
1. Sort categories by the base accuracy of VGG16.
2. Split into 20 disjoint sets of categories.
3. Sample 5 additional sets in order to get better coverage of category set
accuracies in the range [0.2, 0.4].
"""
version_wnids = input('Version number (WNIDs): ')
from ..utils_cat_set_properties import (average_distance, base_accuracy,
check_coverage, score_dist)
from ..utils.metadata import ind2wnid
from ..utils.paths import path_category_sets
df_baseline.sort_values(by='accuracy', ascending=True, inplace=True)
inds_split = np.array([list(inds) for inds in np.split(df_baseline.index, 20)])
thresholds = [0.35, 0.4, 0.45, 0.5, 0.55]
interval_ends = [0.2, 0.25, 0.3, 0.35, 0.4]
intervals_covered = False
dist_bestscore = np.inf
inds_best = None
for i in range(10000):
if i % 1000 == 0:
print(f'i = {i:05}')
inds_sampled = np.array([sample_below_acc(t) for t in thresholds])
acc = [base_accuracy(inds) for inds in inds_sampled]
dist = [score_dist(inds) for inds in inds_sampled]
intervals_covered = check_coverage(np.array(acc), interval_ends)
dist_score = np.max(np.abs(dist)) # similar results with dist_score = np.std(dist)
if intervals_covered and (dist_score < dist_bestscore):
inds_best = inds_sampled
dist_bestscore = dist_score
if inds_best is not None:
print('Accuracy:', [round(base_accuracy(inds), 2) for inds in inds_best])
print('Distance:',
[round(average_distance(distances(Z[inds])), 2) for inds in inds_best])
inds_all = np.concatenate((inds_split, inds_best), axis=0)
wnids_all = np.vectorize(ind2wnid.get)(inds_all)
pd.DataFrame(wnids_all).to_csv(
path_category_sets/f'diff_v{version_wnids}_wnids.csv',
header=False,
index=False)
else:
print('Suitable category sets not found')
| StarcoderdataPython |
3373648 | <gh_stars>0
import numpy as np
import pandas as pd
import time as time
import os
def go_fish(fname):
day_dir = os.path.realpath(__file__).split('/')[:-1]
fname = os.path.join('/',*day_dir, fname)
fish = np.array(pd.read_csv(fname).iloc[:,0].tolist())
# Initalize fish counts
fish_counts = np.zeros(9)
for n in fish:
fish_counts[n]+=1
return fish_counts
def evolve(fish_counts, days):
# Evolve
for i in range(days):
new = fish_counts[0]
fish_counts = np.roll(fish_counts,-1)
fish_counts[8] = new
fish_counts[6] += new
return int(fish_counts.sum())
# fname = 'test-input.csv'
fname = 'input.csv'
fish_dist = go_fish(fname)
# Part 1
t0 = time.time()
days=80
print(days,'days:',evolve(fish_dist, days))
dt = time.time()-t0
print("done in",dt/1E-6,"µs")
# Part 2
t0 = time.time()
days=256
print(days,'days:',evolve(fish_dist, days))
dt = time.time()-t0
print("done in",dt/1E-6,"µs")
| StarcoderdataPython |
4822147 | <reponame>Monia234/NCI-GwasQc
"""Test parsing of Illumina BPM files."""
import pytest
from cgr_gwas_qc.parsers.illumina import BeadPoolManifest
from cgr_gwas_qc.testing.data import FakeData
@pytest.fixture(scope="module")
def bpm():
return BeadPoolManifest(FakeData._data_path / FakeData._illumina_manifest_file)
################################################################################
# Most BPM attrributes have an entry for each loci. Check that these entries
# are equal to the number of loci.
################################################################################
bpm_list_attributes = [
"names",
"snps",
"chroms",
"map_infos",
"addresses",
"normalization_ids",
"assay_types",
"normalization_lookups",
"ref_strands",
"source_strands",
]
@pytest.mark.parametrize("attribute", bpm_list_attributes)
def test_bpm_attribute_lengths(bpm, attribute):
"""Check that the list element attributes all have the same length."""
# GIVEN: attributes of the Illumina BeadPoolManifest
# WHEN: these attributes are a list (i.e. a column of values from the file)
# THEN: the number of values is equal to the number of SNPs in the file (i.e., number of rows)
assert len(bpm.__dict__[attribute]) == bpm.num_loci
| StarcoderdataPython |
1733948 | """
``nn()`` is used to train an instance of ``globalemu`` on the preprocessed
data in ``base_dir``. All of the parameters for ``nn()`` are kwargs and
a number of them can be left at their default values however you will
need to set the ``base_dir`` and possibly ``epochs`` and ``xHI`` (see below and
the tutorial for details).
"""
import tensorflow as tf
from tensorflow import keras
import numpy as np
import time
import os
from globalemu.models import network_models
from globalemu.losses import loss_functions
class nn():
r"""
**kwargs:**
batch_size: **int / default: 100**
| The batch size used by ``tensorflow`` when performing training.
Corresponds to the number of samples propagated before the
networks hyperparameters are updated. Keep the value ~100 as
this will help with memory management and training speed.
epochs: **int / default: 10**
| The number of epochs to train the network on. An epoch
corresponds to training on x batches where x is sufficiently
large for every sample to have influenced an update of the
network hyperparameters.
activation: **string / default: 'tanh'**
| The type of activation function used in the neural networks
hidden layers. The activation function effects the way that the
network learns and updates its hyperparameters. The defualt
is a commonly used activation for regression neural networks.
lr: **float / default: 0.001**
| The learning rate acts as a "step size" in the optimization and
its value can effect the quality of the emulation. Typical
values fall in the range 0.001-0.1.
dropout: **float / default: 0**
| The dropout for the neural network training. ``globalemu`` is
designed so that you shouldn't need dropout to prevent
overfitting but we leave it as an option.
input_shape: **int / default: 8**
| The number of input parameters (astrophysical parameters
plus redshift) for the neural network. The default accounts
for 7 astrophysical
parameters and a single redshift input.
output_shape: **int / default: 1**
| The number of ouputs (temperature) from the neural network.
This shouldn't need changing.
layer_sizes: **list / default: [input_shape, input_shape]**
| The number of hidden layers and the number of nodes in each
layer. For example ``layer_sizes=[8, 8]`` will create
two hidden layers both with 8 nodes (this is the default).
base_dir: **string / default: 'model_dir/'**
| This should be the same as the ``base_dir`` used when
preprocessing. It contains the data that the network will
work with and is the directory in which the trained model will
be saved in.
early_stop: **Bool / default: False**
| If ``early_stop`` is set too ``True`` then the network will stop
learning if the loss has not changed up to an accuracy given
by ``early_stop_lim`` within the last ten epochs.
early_stop_lim: **float / default: 1e-4**
| The precision with which to assess the change in loss over the
last ten epochs when ``early_stop=True``. The value of this
parameter is strongly dependent on the magnitude of the
evaluated loss at each epoch and the default may be to high or
too low for the desired outcome. For example if our loss value
is initially 0.01 and decreases with each epoch then a
``epoch_stop_lim`` of 0.1 will cause training to stop after
10 epochs and give poor results.
xHI: **Bool / default: False**
| If True then ``globalemu`` will act as if it is training a
neutral fraction history emulator.
output_activation: **string / default: 'linear'**
| Determines the output activation function for the network.
Modifying this
is useful if the emulator output is required to be positive or
negative etc. If xHI is True then the output activation is
set to 'relu' else the function is 'linear'. See the tensorflow
documentation for more details on the types of activation
functions available.
loss_function: **Callable/ default: None**
| By default the code uses an MSE loss however users are able to
pass their own loss functions when training the neural
network. These should be functions that take in the true labels
(temperatures) and the predicted labels and return some measure
of loss. Care needs to be taken to ensure that the correct loss
function is supplied when resuming the training of
a previous run as ``globalemu`` will not check this. In order
for the loss function to work it must be built
using the tensorflow.keras backend. An example would be
.. code:: python
from tensorflow.keras import backend as K
def custom_loss(true_labels, predicted_labels,
netowrk_inputs):
return K.mean(K.abs(true_labels - predicted_labels))
The function must take in as arguments the `true_labels`,
the `predicted_labels` and the `network_inputs`.
resume: **Bool / default: False**
| If set to ``True`` then ``globalemu`` will look in the
``base_dir`` for a trained model and ``loss_history.txt``
file (which contains the loss recorded at each epoch) and
load these in to continue training. If ``resume`` is ``True``
then you need to make sure all of the kwargs are set the
with the same values that they had in the initial training
for a consistent run.
There will be a human readable file in ``base_dir`` called
"kwargs.txt" detailing
the values of the kwargs that were provided for the
initial training run. Anything missing from this file will
of had its default value. This file will not be overwritten
if ``resume=True``.
random_seed: **int or float / default: None**
| This kwarg sets the random seed used by tensorflow with the
function ``tf.random.set_seed(random_seed)``. It should
be used if you want to have reproducible results but note
that it may cause an 'out of memory' error if training on
large amounts of data
(see https://github.com/tensorflow/tensorflow/issues/37252).
"""
def __init__(self, **kwargs):
for key, values in kwargs.items():
if key not in set(
['batch_size', 'activation', 'epochs',
'lr', 'dropout', 'input_shape',
'output_shape', 'layer_sizes', 'base_dir',
'early_stop', 'early_stop_lim', 'xHI', 'resume',
'random_seed', 'output_activation',
'loss_function']):
raise KeyError("Unexpected keyword argument in nn()")
self.resume = kwargs.pop('resume', False)
self.base_dir = kwargs.pop('base_dir', 'model_dir/')
if type(self.base_dir) is not str:
raise TypeError("'base_dir' must be a sting.")
elif self.base_dir.endswith('/') is False:
raise KeyError("'base_dir' must end with '/'.")
if self.resume is not True:
with open(self.base_dir + 'kwargs.txt', 'w') as f:
for key, values in kwargs.items():
f.write(str(key) + ': ' + str(values) + '\n')
f.close()
self.batch_size = kwargs.pop('batch_size', 100)
self.activation = kwargs.pop('activation', 'tanh')
if type(self.activation) is not str:
raise TypeError("'activation' must be a string.")
self.epochs = kwargs.pop('epochs', 10)
self.lr = kwargs.pop('lr', 1e-3)
self.drop_val = kwargs.pop('dropout', 0)
self.input_shape = kwargs.pop('input_shape', 8)
self.output_shape = kwargs.pop('output_shape', 1)
self.layer_sizes = kwargs.pop(
'layer_sizes', [self.input_shape, self.input_shape])
if type(self.layer_sizes) is not list:
raise TypeError("'layer_sizes' must be a list.")
self.early_stop_lim = kwargs.pop('early_stop_lim', 1e-4)
self.early_stop = kwargs.pop('early_stop', False)
self.xHI = kwargs.pop('xHI', False)
self.random_seed = kwargs.pop('random_seed', None)
boolean_kwargs = [self.resume, self.early_stop, self.xHI]
boolean_strings = ['resume', 'early_stop', 'xHI']
for i in range(len(boolean_kwargs)):
if type(boolean_kwargs[i]) is not bool:
raise TypeError("'" + boolean_strings[i] + "' must be a bool.")
int_kwargs = [self.batch_size, self.epochs, self.input_shape,
self.output_shape]
int_strings = ['batch_size', 'epochs', 'input_shape',
'output_shape']
for i in range(len(int_kwargs)):
if type(int_kwargs[i]) is not int:
raise TypeError("'" + int_strings[i] + "' must be a int.")
float_kwargs = [self.lr, self.early_stop_lim, self.drop_val,
self.random_seed]
float_strings = ['lr', 'early_stop_lim', 'dropout', 'random_seed']
for i in range(len(float_kwargs)):
if float_kwargs[i] is not None:
if type(float_kwargs[i]) not in set([float, int]):
raise TypeError("'" + float_strings[i] +
"' must be a float.")
loss_function = kwargs.pop('loss_function', None)
if loss_function is not None:
if not callable(loss_function):
raise TypeError('loss_function should be a callable.')
if self.random_seed is not None:
tf.random.set_seed(self.random_seed)
if not os.path.exists(self.base_dir):
os.mkdir(self.base_dir)
pwd = os.getcwd()
train_dataset_fp = pwd + '/' + self.base_dir + 'train_dataset.csv'
column_names = [
'p' + str(i)
for i in range(self.input_shape + self.output_shape)]
label_names = column_names[-1]
train_dataset = tf.data.experimental.make_csv_dataset(
train_dataset_fp,
self.batch_size,
column_names=column_names,
label_name=label_names,
num_epochs=1)
def pack_features_vector(features, labels):
return tf.stack(list(features.values()), axis=1), labels
train_dataset = train_dataset.map(pack_features_vector)
self.output_activation = kwargs.pop('output_activation', 'linear')
if self.xHI is True:
self.output_activation = 'relu'
if self.resume is True:
model = keras.models.load_model(
self.base_dir + 'model.h5',
compile=False)
else:
model = network_models().basic_model(
self.input_shape, self.output_shape,
self.layer_sizes, self.activation, self.drop_val,
self.output_activation)
def loss(model, x, y, training):
y_ = tf.transpose(model(x, training=training))[0]
lf = loss_functions(y, y_)
if loss_function is None:
return lf.mse(), lf.rmse()
else:
return loss_function(y, y_, x), lf.rmse()
def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value, rmse = loss(model, inputs, targets, training=True)
return loss_value, rmse, tape.gradient(
loss_value, model.trainable_variables)
optimizer = keras.optimizers.Adam(learning_rate=self.lr)
if self.resume is True:
train_loss_results = list(
np.loadtxt(self.base_dir + 'loss_history.txt'))
else:
train_loss_results = []
train_rmse_results = []
num_epochs = self.epochs
for epoch in range(num_epochs):
s = time.time()
epoch_loss_avg = tf.keras.metrics.Mean()
epoch_rmse_avg = tf.keras.metrics.Mean()
for x, y in train_dataset:
loss_values, rmse, grads = grad(model, x, y)
optimizer.apply_gradients(
zip(grads, model.trainable_variables))
epoch_loss_avg.update_state(loss_values)
epoch_rmse_avg.update_state(rmse)
train_loss_results.append(epoch_loss_avg.result())
train_rmse_results.append(epoch_rmse_avg.result())
e = time.time()
print(
'Epoch: {:03d}, Loss: {:.5f}, RMSE: {:.5f}, Time: {:.3f}'
.format(
epoch, epoch_loss_avg.result(),
epoch_rmse_avg.result(), e-s))
if self.early_stop is True:
if len(train_loss_results) > 10:
if np.isclose(
train_loss_results[-10], train_loss_results[-1],
self.early_stop_lim, self.early_stop_lim):
print('Early Stop')
model.save(self.base_dir + 'model.h5')
break
if (epoch + 1) % 10 == 0:
model.save(self.base_dir + 'model.h5')
np.savetxt(
self.base_dir + 'loss_history.txt', train_loss_results)
model.save(self.base_dir + 'model.h5')
np.savetxt(self.base_dir + 'loss_history.txt', train_loss_results)
| StarcoderdataPython |
3333572 | import numpy as np
import cv2
def lambda_handler(event, context):
print(cv2.__version__) | StarcoderdataPython |
1698655 | <gh_stars>10-100
'''
file bird_model.py
@author <NAME>, <NAME>
@copyright Copyright © UCLouvain 2020
multiflap is a Python tool for finding periodic orbits and assess their stability via the Floquet multipliers.
Copyright <2020> <Université catholique de Louvain (UCLouvain), Belgique>
List of the contributors to the development of multiflap, Description and complete License: see LICENSE and NOTICE files.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import numpy as np
from .bird import Joint, Shoulder, Elbow, Wrist
from .line_functions import smooth_line, smooth_quarterline, quarterchord_naive, improveline_iteration
from .RotationMatrix import RotationMatrix
from .CompMatrix import CompMatrix
from .Plumes import plumes
from collections import namedtuple
from odes.bird_dynamics import dynamics, get_aeroforces, get_stability_matrix
WingState = namedtuple('WingState',[
'shoulder_x',
'shoulder_y',
'shoulder_z',
'elbow_x',
'elbow_y',
'wrist_y',
'wrist_z'] )
class BirdModel:
def __init__(self, shoulder=None, elbow=None, wrist=None):
#Parameters:
self.dimensions = 4
self.g = 9.81
self.mass = 1.2
self.frequency = 4
self.wingframe_position = np.array([0, -0.0, -0.05])
self.wingframe_position_tail = np.array([0, -0., .3])
self.tail_length = 0.25
self.tail_chord = 0.15
self.tail_opening = 0.
self.shoulder = Shoulder()
self.wrist = Wrist()
self.elbow = Elbow()
if isinstance(shoulder, Shoulder):
self.shoulder = shoulder
if isinstance(wrist, Wrist):
self.wrist = wrist
if isinstance(elbow, Elbow):
self.elbow = elbow
def get_wingstate(self, t):
# ws = WingState()
# Shoulder motion
#ws.shoulder_x = self.shoulder.axis_x.motion_joint(t)
#ws.shoulder_y = self.shoulder.axis_y.motion_joint(t)
#ws.shoulder_z = self.shoulder.axis_z.motion_joint(t)
## Elbow motion
#ws.elbow_x = self.elbow.axis_x.motion_joint(t)
#ws.elbow_y = self.elbow.axis_y.motion_joint(t)
## Wrist motion
#ws.wrist_y = self.wrist.axis_y.motion_joint(t)
#ws.wrist_z = self.wrist.axis_z.motion_joint(t)
state_shoulder_x = self.shoulder.axis_x.motion_joint(t)
state_shoulder_y = self.shoulder.axis_y.motion_joint(t)
state_shoulder_z = self.shoulder.axis_z.motion_joint(t)
# Elbow motion
state_elbow_x = self.elbow.axis_x.motion_joint(t)
state_elbow_y = self.elbow.axis_y.motion_joint(t)
# Wrist motion
state_wrist_y = self.wrist.axis_y.motion_joint(t)
state_wrist_z = self.wrist.axis_z.motion_joint(t)
wing_state = [state_shoulder_x, state_shoulder_z, state_shoulder_y, state_elbow_y, state_elbow_x, state_wrist_y, state_wrist_z]
#return ws
return wing_state
def get_wingenvelope(self, wing_state):
shoulder_x, shoulder_z, shoulder_y, elbow_y, elbow_x, wrist_y, wrist_z = wing_state
[plumesrot, plumesvec] = plumes()
dim_plumesrot0 = np.size(plumesrot[0])
"""
Assignment of the dimensions of the skeleton and the frame position
"""
# Versor along y axis
ey = [0, 1, 0]
# Lenght of the first part of the wing skeleton
l1 = .134
# Lenght of the second part of the wing skeleton
l2 = .162
# Lenght of the second third of the wing skeleton (l3 is used to connect l1 and l2)
l4 = .084
# Origin of the reference frame
origin = [0, 0, 0]
# Respective position of the end of the three parts of the skeleton
end1 = np.array([l1, 0, 0])
end2 = np.array([l2, 0, 0])
end4 = np.array([l4, 0, 0])
vec30 = np.array(end1) + np.array(end2) - np.array(origin) # Probably unused
"""
Assignment of the points over the three parts of the skeleton, arm, forearm, hand respoectively
"""
# Number of points over the arm
npoints_arm = 1
# Number of points over the forearm
npoints_forearm = 1
# Number of points over the hand
npoints_hand = 2
# Total number of point
nslice = npoints_arm + npoints_forearm + npoints_hand
# Distances from point to point for each part of the skeleton
delta_arm = l1/npoints_arm
delta_forearm = l2/npoints_forearm
delta_hand = l4/(npoints_hand-1)
# Routine for the xslice vector (values checked with Matlab code). Maybe write a function!
xslice = np.zeros(nslice)
for i in range(npoints_arm):
xslice[i] = 0 + (i*delta_arm)
for i in range(npoints_forearm):
xslice[i + npoints_arm] = l1 + (i*delta_forearm)
for i in range(npoints_hand):
xslice[i + npoints_arm + npoints_forearm] = l1 + l2 + (i*delta_hand)
# Index of feathers starting point (ask it for a more clear comment). CHECKED!
index = np.zeros(7)
index[0] = np.size(xslice)
index[1] = np.nonzero(xslice>=l1+l2+l4/2)[0][0]
index[2] = np.nonzero(xslice>=l1+l2)[0][0]
index[3] = np.nonzero(xslice>=l1+l2/2)[0][0]
index[4] = np.nonzero(xslice>=l1)[0][0]
index[5] = np.nonzero(xslice>=l1/2)[0][0]
index[6] = 1
# Ellipse thing (just double check to delete unnecessary things)
number_ellipses = 2
s = np.linspace(0,2*np.pi,number_ellipses + 1) # No idea but works
s = s[0:number_ellipses]
skz = .01
sky = .01
z = skz*np.cos(s)
y = sky*np.sin(s)
points = np.zeros((3 , nslice*number_ellipses))
# Weight thing, again ask to have a more clear comment
w1 = np.zeros(nslice*number_ellipses)
w2a = np.zeros(nslice*number_ellipses)
w2b = np.zeros(nslice*number_ellipses)
w3 = np.zeros(nslice*number_ellipses)
w4 = np.zeros(nslice*number_ellipses)
for j in range(nslice):
if xslice[j] < l1:
for k in range(number_ellipses):
points[:,(j)*number_ellipses+k] = [xslice[j], y[k], z[k]]
facb = (z/skz + 1)/2
lrefcd = min(l1,l2)
if xslice[j] < l1-lrefcd/2:
faccd1 = 1
else:
faccd1 = 0.5*(1-np.sin(np.pi*(xslice[j]-l1)/lrefcd))
faccd2 = 1-faccd1
fac2a = 1
fac2b = 0
w1[j*number_ellipses:(j+1)*number_ellipses] = facb*faccd1
w2a[j*number_ellipses:(j+1)*number_ellipses] = facb*faccd2*fac2a
w2b[j*number_ellipses:(j+1)*number_ellipses] = facb*faccd2*fac2b
w3[j*number_ellipses:(j+1)*number_ellipses] = (1-facb)
w4[j*number_ellipses:(j+1)*number_ellipses] = 0
elif xslice[j] < l1 + l2:
for k in range(number_ellipses):
points[:,(j)*number_ellipses+k] = [xslice[j], y[k], z[k]]
facb = (z/skz + 1)/2
lrefcd = min(l1,l2)
if xslice[j] < l1+lrefcd/2:
faccd2 = 0.5*(1+np.sin(np.pi*(xslice[j]-l1)/lrefcd))
else:
faccd2 = 1
faccd1 = 1-faccd2
fac2b = (xslice[j]-l1)/l2
fac2a = 1-fac2b
lrefpg = min(l2,l4)
if xslice[j] < l1+l2-lrefpg/2:
facpg2 = 1
else:
facpg2 = 0.5*(1-np.sin(np.pi*(xslice[j]-(l1+l2))/lrefpg))
facpg4 = 1-facpg2
w1[j*number_ellipses:(j+1)*number_ellipses] = facb*faccd1*facpg2
w2a[j*number_ellipses:(j+1)*number_ellipses] = facb*faccd2*fac2a*facpg2
w2b[j*number_ellipses:(j+1)*number_ellipses] = facb*faccd2*fac2b*facpg2
w3[j*number_ellipses:(j+1)*number_ellipses] = (1-facb)*facpg2
w4[j*number_ellipses:(j+1)*number_ellipses] = facpg4
else:
for k in range(number_ellipses):
points[:,(j)*number_ellipses+k] = [xslice[j], y[k], z[k]]
facb = (z/skz + 1)/2
fac2a = 0
fac2b = 1
lrefpg = min(l2,l4)
if xslice[j] < l1+l2+lrefpg/2:
facpg4 = 0.5*(1+np.sin(np.pi*(xslice[j]-(l1+l2))/lrefpg))
else:
facpg4 = 1
facpg2 = 1-facpg4
w1[j*number_ellipses:(j+1)*number_ellipses] = 0
w2a[j*number_ellipses:(j+1)*number_ellipses] = facb*facpg2*fac2a
w2b[j*number_ellipses:(j+1)*number_ellipses] = facb*facpg2*fac2b
w3[j*number_ellipses:(j+1)*number_ellipses] = (1-facb)*facpg2
w4[j*number_ellipses:(j+1)*number_ellipses] = facpg4
npts = nslice*number_ellipses
pts = points
"""
Rotation routine for the three parts of the skeleton (shoulder, elbow, hand)
"""
rot1X = RotationMatrix(shoulder_x,'x')
rot1Z = RotationMatrix(shoulder_z,'z')
rot1Y = RotationMatrix(shoulder_y,'y')
rot1 = np.array(rot1X).dot(np.array(rot1Z)).dot(np.array(rot1Y))
ey1 = np.array(rot1).dot(np.array(ey))
rot2relY = RotationMatrix(elbow_y,'y')
rot2relX = RotationMatrix(elbow_x,'x')
rot2b = np.array(rot1).dot(np.array(rot2relY)).dot(np.array(rot2relX))
rot2a = np.array(rot1).dot(np.array(rot2relY))
rot4relY = RotationMatrix(wrist_y,'y')
rot4relZ = RotationMatrix(wrist_z,'z')
rot4 = np.array(rot2b).dot(np.array(rot4relY)).dot(np.array(rot4relZ))
"""
Evaluation of the bones position
"""
endd1 = np.array(rot1).dot(np.array(end1))
endd2 = np.array(rot2a).dot(np.array(end2))+np.array(endd1)
endd4 = np.array(rot4).dot(np.array(end4))+np.array(endd2)
vec3 = np.array(endd2)-np.array(origin)
ex3 = vec3/np.linalg.norm(vec3)
ey3 = ey1
ez3 = np.array([ex3[1]*ey3[2]-ex3[2]*ey3[1], ex3[2]*ey3[0]-ex3[0]*ey3[2], ex3[0]*ey3[1]-ex3[1]*ey3[0]])
rot3 = np.array([ex3,ey3,ez3])
rot3 = rot3.transpose()
kx = np.linalg.norm(vec3)/np.linalg.norm(vec30)
comp3 = CompMatrix(kx,'x')
"""
Routine to find skin points
"""
for j in range(npts):
pt = np.array(points[:,j])
pt1 = rot1.dot(pt)
pt2a = rot2a.dot((pt-end1)) + endd1
pt2b = rot2b.dot((pt-end1)) + endd1
pt3 = rot3.dot(comp3).dot(pt)
pt4 = rot4.dot((pt-(end1+end2))) + endd2
pts[:,j] = pt1*w1[j] + pt2a*w2a[j] + pt2b*w2b[j] + pt3*w3[j] + pt4*w4[j]
"""
Routine to find main feathers
"""
vecpss = np.zeros((3,dim_plumesrot0))
startp = np.zeros((3,np.size(plumesrot[0])))
for i in range(np.size(plumesrot[0])):
if i == 0:
prerot = rot4
elif i == 1:
prerot = rot4.dot(RotationMatrix(wrist_z/4,'x'))
elif i == 2:
prerot = rot2b.dot(RotationMatrix(wrist_y/2,'y')).dot(RotationMatrix(-wrist_z/2,'x'))
elif i == 3:
prerot = rot2a.dot(RotationMatrix(elbow_x/2,'x')).dot(RotationMatrix(wrist_y/2,'y')).dot(RotationMatrix(-wrist_z/4,'x'))
elif i == 4:
prerot = rot1.dot(RotationMatrix(elbow_y/2,'y'))
elif i == 5:
prerot = rot1.dot(RotationMatrix(elbow_y/4,'y'))
elif i == 6:
prerot = rot1
rY = RotationMatrix(plumesrot[0,i],'y')
rX = RotationMatrix(plumesrot[1,i],'x')
rot = prerot.dot(rY).dot(rX)
vecpss[:,i] = np.dot(rot,plumesvec[:,i])
element = index[i]
column = int((index[i]-1)*(number_ellipses))
startp[0,i] = pts[0][column]
startp[1,i] = pts[1][column]
startp[2,i] = pts[2][column]
"""
Interpolation Routine
"""
main1 = ((xslice[xslice >= l1+l2+l4/2]-(l1+l2+l4/2))/(l4/2))
main1 = main1[:,np.newaxis].T
main2 = ((xslice[(xslice >= l1+l2) & (xslice < l1+l2+l4/2)]-(l1+l2))/(l4/2))
main2 = main2[:,np.newaxis].T
abras1 = ((xslice[(xslice >=l1+l2/2) & (xslice <l1+l2)]-(l1+l2/2))/(l2/2))
abras1 = abras1[:,np.newaxis].T
abras2 = ((xslice[(xslice >=l1) & (xslice <l1+l2/2)]-(l1))/(l2/2))
abras2 = abras2[:,np.newaxis].T
bras1 = ((xslice[(xslice >=l1/2) & (xslice <l1)]-(l1/2))/(l1/2))
bras1 = bras1[:,np.newaxis].T
bras2 = (xslice[xslice <l1/2]/(l1/2))
bras2 = bras2[:,np.newaxis].T
"""
Feathers Routine
"""
pm1 = vecpss[:,0][:,np.newaxis].dot(main1)+vecpss[:,1][:,np.newaxis].dot(1-main1)
pm2 = vecpss[:,1][:,np.newaxis].dot(main2)+vecpss[:,2][:,np.newaxis].dot(1-main2)
pa1 = vecpss[:,2][:,np.newaxis].dot(abras1)+vecpss[:,3][:,np.newaxis].dot(1-abras1)
pa2 = vecpss[:,3][:,np.newaxis].dot(abras2)+vecpss[:,4][:,np.newaxis].dot(1-abras2)
pb1 = vecpss[:,4][:,np.newaxis].dot(bras1)+vecpss[:,5][:,np.newaxis].dot(1-bras1)
pb2 = vecpss[:,5][:,np.newaxis].dot(bras2)+vecpss[:,6][:,np.newaxis].dot(1-bras2)
"""
Store the feathers in a single vector following the structure:
[pb2(0,0),..,pb2(0,n),pb1(0,0),..,pb1(0,n),pa2(0,0),..,pa2(0,k),pa1(0,0),..,pa1(0,k),pm2(0,0),..,pm2(0,j),pm1(0,0),..,pm1(0,j)]
vecps = [pb2(1,0),..,pb2(1,n),pb1(1,0),..,pb1(1,n),pa2(1,0),..,pa2(1,k),pa1(1,0),..,pa1(1,k),pm2(1,0),..,pm2(1,j),pm1(1,0),..,pm1(1,j)]
[pb2(2,0),..,pb2(2,n),pb1(2,0),..,pb1(2,n),pa2(2,0),..,pa2(2,k),pa1(2,0),..,pa1(2,k),pm2(2,0),..,pm2(2,j),pm1(2,0),..,pm1(2,j)]
Matrix concatenation
"""
vecps = np.c_[pb2, pb1, pa2, pa1, pm2, pm1]
trailingedge = np.zeros((3,nslice))
xpt = np.zeros(3)
ypt = np.zeros(3)
zpt = np.zeros(3)
for j in range(nslice):
xpt = np.array([pts[0,(j)*number_ellipses], pts[0,j*number_ellipses+1], pts[0,(j)*number_ellipses]])
ypt = np.array([pts[1,(j)*number_ellipses], pts[1,j*number_ellipses+1], pts[1,(j)*number_ellipses]])
zpt = np.array([pts[2,(j)*number_ellipses], pts[2,j*number_ellipses+1], pts[2,(j)*number_ellipses]])
vecp = np.array(vecps[:,j])
trailingedge[0,j] = xpt[0]+vecp[0]
trailingedge[1,j] = ypt[0]+vecp[1]
trailingedge[2,j] = zpt[0]+vecp[2]
leadingedge = np.c_[pts[:,int(number_ellipses/2)::int(number_ellipses)],trailingedge[:,-1]]
return leadingedge, trailingedge
def get_liftingline(self, leadingedge, trailingedge):
"""
=== Call of wing_envelope function. Given the kinematics, the wing shape is found ===
"""
nlete = 16
leadingedge = smooth_line(leadingedge, nlete)
trailingedge = smooth_line(trailingedge, nlete)
[line, chord_leadingedge, chord_trailingedge] = quarterchord_naive(leadingedge, trailingedge)
""""
============= PLOT ROUTINE =============
Here in the original code there is a function that prints out on the screen wing plots.
It is now omitted, and there will be implemented later in a second time
========================================
"""
tol = 0.1
nmax = 10
a = tol + 1
chg = tol + 1
it = 1
while a > tol and it < nmax:
[line, chord_leadingedge, chord_trailingedge, a] = improveline_iteration(line,chord_leadingedge,
chord_trailingedge,leadingedge,trailingedge,it)
chg = np.c_[chg, a]
it = it + 1
[lifting_line, chord_leadingedge, chord_trailingedge] = smooth_quarterline(line, chord_leadingedge, chord_trailingedge)
"""
Output lifting_line, chord_leadingedge, chord_trailingedge CHECKED
"""
line_dummy = np.copy(lifting_line)
nl = np.size(line[0])
chord_direction = np.zeros((3,nl))
updir = np.zeros((3,nl))
chord = np.zeros((nl))
# =============================================================================
# Evaluating the chord and its direction
# For every slice, it's calculated the distance btw Lead. edge and Trail.
# edge (chord_distance), and then the modulus, so that the versor is
# identified.
# =============================================================================
for i in range(nl):
chord_distance = (chord_trailingedge[:,i] - chord_leadingedge[:,i]) + 1e-20
chord[i] = np.linalg.norm(chord_distance)
#chord = chord[:,np.newaxis]
chord_direction[:,i] = chord_distance/chord[i]
if i == 0:
linevec = line[:,1] - line[:,0]
elif i == (nl - 1):
linevec = line[:,-1] - line[:,-2]
else:
linevec = line[:,i+1] - line[:,i-1]
linevec = linevec/np.linalg.norm(linevec)
updir[:,i] = np.cross(chord_direction[:,i], linevec) # Different value in the last iteration
updir_dummy = np.copy(updir)
chord_direction_dummy = np.copy(chord_direction)
chord_dummy = np.copy(chord)
# Left Wing
line_left = np.fliplr(line_dummy)
up_direction_left = np.fliplr(updir_dummy)
chord_direction_left = np.fliplr(chord_direction_dummy)
chord_left = chord_dummy[::-1]
line_left[0,:] = np.negative(line_left[0,:])
chord_direction_left[0,:] = np.negative(chord_direction_left[0,:])
up_direction_left[0,:] = np.negative(up_direction_left[0,:])
sumvector = np.zeros((1,nl))
for i in range(nl):
if i < nl-1:
sumvector[0,i] = np.sum((lifting_line[:,i+1] - lifting_line[:,i])**2)
else:
sumvector[0,i] = np.sum((lifting_line[:,-1] - lifting_line[:, -2])**2)
dx = np.mean(np.sqrt(sumvector))
return lifting_line, updir, chord_direction, chord, line_left, up_direction_left, chord_direction_left, chord_left, dx
def merge_lines(self, line_package):
line_r,updir_r,chordir_r,chord_r,line_l,updir_l,chordir_l,chord_l, dx = line_package
x_ep = 0.05
nmid = int(np.ceil(2*x_ep/dx))
line_r[0,:] = line_r[0,:] + x_ep
line_l[0,:] = line_l[0,:] - x_ep
xmid = np.linspace(line_l[0,-1],line_r[0,0],nmid)
length_xmid = np.size(xmid)
line_mid = np.array([xmid, line_r[1,0]*np.ones(np.size(xmid)), line_r[2,0]*np.ones(np.size(xmid))])
chordir_mid = np.array([chordir_r[:,0] for i in range(np.size(xmid))]).T
updir_mid = np.array([updir_r[:,0] for i in range(np.size(xmid))]).T
chord_mid = np.zeros(length_xmid)
chord_mid[:] = chord_r[0]*np.ones(length_xmid)
line = np.c_[line_l,line_mid[:,1:-1],line_r]
chordir = np.c_[chordir_l, chordir_mid[:,1:-1], chordir_r]
updir = np.c_[updir_l, updir_mid[:,1:-1], updir_r]
chord = np.concatenate([chord_l, chord_mid[1:-1]/1e4, chord_r])
return line, chordir, updir, chord
# calling methods of BirdModel that are defined in other files
get_aeroforces = get_aeroforces
dynamics = dynamics
get_stability_matrix = get_stability_matrix
#bird_shoulder = Shoulder(axis_x=Joint(0.2,0.014,-np.pi/2),
# axis_y=Joint(-np.deg2rad(19),np.pi/12,np.pi/2),
# axis_z=Joint(0,np.deg2rad(42),np.pi))
#bird_elbow = Elbow(axis_x=Joint(0.,np.pi/6,-np.pi/2),
# axis_y=Joint(np.pi/6,np.pi/6,-np.pi/2))
#
#bird_wrist = Wrist(axis_y=Joint(-np.pi/6,np.pi/6,np.pi/2),
# axis_z=Joint(0.,0.,0.))
#
#mybird = BirdModel(shoulder=bird_shoulder, elbow=bird_elbow, wrist=bird_wrist)
| StarcoderdataPython |
1793142 | #!/usr/bin/python
import sys
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def main():
fibonacci(40)
sys.exit(0)
if __name__ == '__main__':main() | StarcoderdataPython |
1626873 | # from .models import BlogPost
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
@receiver(post_save, sender=BlogPost)
def index_post(sender, instance, **kwargs):
# import ipdb; ipdb.set_trace()
instance.indexing()
# @receiver(pre_save, sender=BlogPost)
# def index_post(sender, instance, **kwargs):
# import ipdb; ipdb.set_trace()
# instance.indexing() | StarcoderdataPython |
45796 | <reponame>SWuchterl/cmssw<gh_stars>1-10
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True)
)
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(10000)
)
process.load("HLTrigger.special.hltDynamicPrescaler_cfi")
process.hltTrigReport = cms.EDAnalyzer( "HLTrigReport",
HLTriggerResults = cms.InputTag( 'TriggerResults' )
)
process.MessageLogger.categories.append('HLTrigReport')
process.path = cms.Path(process.hltDynamicPrescaler)
process.info = cms.EndPath(process.hltTrigReport)
| StarcoderdataPython |
3327892 | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, EqualTo, Email
class RegisterForm(FlaskForm):
email = EmailField("Email", validators=[DataRequired(), Email()])
password1 = PasswordField("Password", validators=[DataRequired()])
password2 = PasswordField("<PASSWORD>", validators=[DataRequired(), EqualTo("password1", message="Passwords must match!")])
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember Me')
| StarcoderdataPython |
1621414 | # Generated by Django 3.1.1 on 2020-10-03 15:19
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('quiz', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='favorite',
old_name='article',
new_name='quiz',
),
migrations.AlterUniqueTogether(
name='favorite',
unique_together={('owner', 'quiz')},
),
]
| StarcoderdataPython |
1691752 | <filename>Census_Checker.py
"""
Geo-referencing GTFS with Census geographies methods
by <NAME>
"""
import sys
from osgeo import ogr
from kdtree1 import *
from kdtree2a import *
from bst import *
from point import *
def getCensusTractsGDAL(long_lat_list, shapefile_name,MaxX,MaxY,MinX,MinY ):
"""
Geo referening using only GDAL
Input
long_lat_list: dictionary of stops
shapefile_name: Census Shpaefile
MaxX,MaxY,MinX,MinY : Extent of transit stops
*Assumes points and shapefil are in the same datum/projection
Output
A dictionary of stops_ID (key) and GEOID (value)
"""
driver = ogr.GetDriverByName("ESRI Shapefile")
vector = driver.Open(shapefile_name, 0)
layer = vector.GetLayer()
c = layer.GetFeatureCount()
results_dict = {}
i = 0
# Create ring
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(float(MaxX), float(MaxY))
ring.AddPoint(float(MinX), float(MaxY))
ring.AddPoint(float(MinX), float(MinY))
ring.AddPoint(float(MaxX), float(MinY))
ring.AddPoint(float(MaxX), float(MaxY))
# Create polygon
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
for feature in layer:
geom = feature.GetGeometryRef()
i += 1
print "{}/{}".format(i,c)
extent = geom.GetEnvelope()
if geom.Intersect(poly):
for pt in long_lat_list:
gid = pt['stop_id']
lon = float(pt['stop_lon'])
lat = float(pt['stop_lat'])
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat)
if point.Within(geom) == True:
feat_id = feature.GetField("GEOID")
results_dict[gid] = feat_id
for pt in long_lat_list:
gid = pt['stop_id']
lon = pt['stop_lon']
lat = pt['stop_lat']
if gid not in results_dict:
results_dict[gid] = 'NA'
return results_dict
def RangeQuerying(long_lat_list, shapefile_name,MaxX,MaxY,MinX,MinY ):
"""
Geo referening using range querying and GDAL
Input
long_lat_list: dictionary of stops
shapefile_name: Census Shpaefile
MaxX,MaxY,MinX,MinY : Extent of transit stops
Output
A dictionary of stops_ID (key) and GEOID (value)
"""
driver = ogr.GetDriverByName("ESRI Shapefile")
vector = driver.Open(shapefile_name, 0)
layer = vector.GetLayer()
c = layer.GetFeatureCount()
results_dict = {}
i = 0
# Create ring
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(float(MaxX), float(MaxY))
ring.AddPoint(float(MinX), float(MaxY))
ring.AddPoint(float(MinX), float(MinY))
ring.AddPoint(float(MaxX), float(MinY))
ring.AddPoint(float(MaxX), float(MaxY))
# Create polygon
poly = ogr.Geometry(ogr.wkbPolygon)
poly.AddGeometry(ring)
# Create Tree
points = [Point(float(d['stop_lon']), float(d['stop_lat']),d['stop_id']) for d in long_lat_list]
t1 = kdtree2(points)
for feature in layer:
geom = feature.GetGeometryRef()
i += 1
if i%200 == 0:
g = float("{0:.0f}".format((float(i)/c)*100))
print "{}% Complete, please wait...".format(g)
extent = geom.GetEnvelope()
rect = [[extent[0],extent[1]],[extent[2],extent[3]]]
if geom.Intersect(poly):
found = []
range_query_orthogonal(t1, rect, found)
for pt in found:
gid = pt.key
lon = float(pt.x)
lat = float(pt.y)
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat)
if point.Within(geom) == True:
feat_id = feature.GetField("GEOID")
results_dict[gid] = feat_id
for pt in long_lat_list:
gid = pt['stop_id']
lon = pt['stop_lon']
lat = pt['stop_lat']
if gid not in results_dict:
results_dict[gid] = 'NA'
return results_dict
def CheckStop(x,y):
"""
Geo referening using Census API
Input
x,y: Lon,Lat of point
shapefile_name: Census Shpaefile
MaxX,MaxY,MinX,MinY : Extent of transit stops
Output:
A GEOID value
"""
base = 'https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x={}&y={}&benchmark=Public_AR_Census2010&vintage=Census2010_Census2010&layers=14&format=json'.format(x,y)
full_url = base
js = urllib2.urlopen(base)
data = json.load(js)
GEOID = data['result']['geographies']['Census Blocks'][0]['GEOID']
print GEOID
| StarcoderdataPython |
1714267 | <reponame>JacobHilbert/week_schedule
from .schedule import schedule_figure | StarcoderdataPython |
29847 | #!/usr/bin/env python3
'''
==============================================================
Copyright © 2019 Intel Corporation
SPDX-License-Identifier: MIT
==============================================================
'''
import intel.tca as tca
target = tca.get_target(id="whl_u_cnp_lp")
components = [(c.component, tca.latest(c.steppings))
for c in target.components]
component_config = tca.ComponentWithSelectedSteppingList()
for comp in components:
config_tmp = tca.ComponentWithSelectedStepping()
config_tmp.component, config_tmp.stepping = comp
supported_connections = target.get_supported_connection_configurations(
component_config)
def conn_filter(conn: tca.ConnectionConfiguration) -> bool:
if conn.type != tca.ConnectionType_IPC:
return False
if "CCA" not in conn.ipc_configuration.selection:
return False
return True
connection_config = next(filter(conn_filter, supported_connections))
profile = tca.Profile()
profile.name = "My TCA profile"
profile.target = target
profile.component_configuration = component_config
profile.connection_configuration = connection_config
tca.load(profile)
tca.connect()
| StarcoderdataPython |
88583 | <reponame>Falldog/appengine-flask-template-light<gh_stars>0
from application import app
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
# app.jinja_env.filters['reverse'] = reverse_filte
| StarcoderdataPython |
3300991 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-01-31 06:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import lib.fields
class Migration(migrations.Migration):
dependencies = [
('fleet_management', '0019_auto_20180124_1409'),
]
operations = [
migrations.AlterField(
model_name='fuelcard',
name='card_type',
field=models.CharField(choices=[(b'fuel', b'Fuel Only'), (b'fuel oil', b'Fuel & Oil'), (b'fuel oil toll', b'Fuel, Oil & Toll'), (b'fuel oil etag', b'Fuel, Oil & eTag')], max_length=255, verbose_name=b'Card Type'),
),
migrations.AlterField(
model_name='historicalfuelcard',
name='card_type',
field=models.CharField(choices=[(b'fuel', b'Fuel Only'), (b'fuel oil', b'Fuel & Oil'), (b'fuel oil toll', b'Fuel, Oil & Toll'), (b'fuel oil etag', b'Fuel, Oil & eTag')], max_length=255, verbose_name=b'Card Type'),
),
migrations.AlterField(
model_name='historicalvehiclemaintenance',
name='service_interval',
field=models.IntegerField(blank=True, default=0, null=True, verbose_name=b'Service Interval'),
),
migrations.AlterField(
model_name='incident',
name='vehicle_driver',
field=lib.fields.ProtectedForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='incident', to='fleet_management.VehicleDriver'),
),
migrations.AlterField(
model_name='vehiclemaintenance',
name='service_interval',
field=models.IntegerField(blank=True, default=0, null=True, verbose_name=b'Service Interval'),
),
]
| StarcoderdataPython |
1659167 | from .v0 import V0
from .v1 import V1
from .v2 import V2
from .v3 import V3
| StarcoderdataPython |
192790 | from .variable import Variable
from .basis_vector import BasisVector
from .monomial_vector import MonomialVector
from .chebyshev_vector import ChebyshevVector
from .polynomial import Polynomial
| StarcoderdataPython |
82267 | import scadnano as sc
import modifications as mod
import dataclasses
def create_design():
stap_left_ss1 = sc.Domain(1, True, 0, 16)
stap_left_ss0 = sc.Domain(0, False, 0, 16)
stap_right_ss0 = sc.Domain(0, False, 16, 32)
stap_right_ss1 = sc.Domain(1, True, 16, 32)
scaf_ss1_left = sc.Domain(1, False, 0, 16)
scaf_ss0 = sc.Domain(0, True, 0, 32)
scaf_ss1_right = sc.Domain(1, False, 16, 32)
stap_left = sc.Strand([stap_left_ss1, stap_left_ss0])
stap_right = sc.Strand([stap_right_ss0, stap_right_ss1])
scaf = sc.Strand([scaf_ss1_left, scaf_ss0, scaf_ss1_right], color=sc.default_scaffold_color)
strands = [scaf, stap_left, stap_right]
design = sc.Design(strands=strands, grid=sc.square)
design.add_deletion(helix=0, offset=11)
design.add_deletion(helix=0, offset=12)
design.add_deletion(helix=0, offset=24)
design.add_deletion(helix=1, offset=12)
design.add_deletion(helix=1, offset=24)
design.add_insertion(helix=0, offset=29, length=1)
design.add_insertion(helix=1, offset=2, length=1)
design.assign_dna(scaf, 'AACT' * 16)
# biotin_mod_5p = dataclasses.replace(mod.biotin_5p, font_size=30)
# cy3_mod_3p = dataclasses.replace(mod.cy3_3p, font_size=30)
stap_left.set_modification_5p(mod.biotin_5p)
stap_left.set_modification_3p(mod.cy3_3p)
stap_left.set_modification_internal(9, mod.cy3_int)
stap_left.set_modification_internal(10, mod.biotin_int)
stap_left.set_modification_internal(11, mod.cy3_int)
stap_left.set_modification_internal(12, mod.cy5_int)
stap_left.set_modification_internal(4, mod.cy3_int)
stap_left.set_modification_internal(26, mod.cy5_int)
stap_right.set_modification_5p(mod.cy5_5p)
stap_right.set_modification_internal(5, mod.cy3_int)
stap_right.set_modification_3p(mod.biotin_3p)
scaf.set_modification_5p(mod.biotin_5p)
scaf.set_modification_3p(mod.cy3_3p)
scaf.set_modification_internal(5, mod.cy5_int)
scaf.set_modification_internal(32, mod.cy3_int)
return design
if __name__ == '__main__':
design = create_design()
design.write_scadnano_file(directory='output_designs')
| StarcoderdataPython |
1633002 | import numpy as np
import torch
from pgbar import progress_bar
class RayS(object):
def __init__(self, model, epsilon=0.031, order=np.inf):
self.model = model
self.ord = order
self.epsilon = epsilon
self.sgn_t = None
self.d_t = None
self.x_final = None
self.queries = None
def get_xadv(self, x, v, d, lb=0., ub=1.):
if isinstance(d, int):
d = torch.tensor(d).repeat(len(x)).cuda()
out = x + d.view(len(x), 1, 1, 1) * v
out = torch.clamp(out, lb, ub)
return out
def attack_hard_label(self, x, y, target=None, query_limit=10000, seed=None):
""" Attack the original image and return adversarial example
model: (pytorch model)
(x, y): original image
"""
shape = list(x.shape)
dim = np.prod(shape[1:])
if seed is not None:
np.random.seed(seed)
# init variables
self.queries = torch.zeros_like(y).cuda()
self.sgn_t = torch.sign(torch.ones(shape)).cuda()
self.d_t = torch.ones_like(y).float().fill_(float("Inf")).cuda()
working_ind = (self.d_t > self.epsilon).nonzero().flatten()
stop_queries = self.queries.clone()
dist = self.d_t.clone()
self.x_final = self.get_xadv(x, self.sgn_t, self.d_t)
block_level = 0
block_ind = 0
for i in range(query_limit):
block_num = 2 ** block_level
block_size = int(np.ceil(dim / block_num))
start, end = block_ind * block_size, min(dim, (block_ind + 1) * block_size)
valid_mask = (self.queries < query_limit)
attempt = self.sgn_t.clone().view(shape[0], dim)
attempt[valid_mask.nonzero().flatten(), start:end] *= -1.
attempt = attempt.view(shape)
self.binary_search(x, y, target, attempt, valid_mask)
block_ind += 1
if block_ind == 2 ** block_level or end == dim:
block_level += 1
block_ind = 0
dist = torch.norm((self.x_final - x).view(shape[0], -1), self.ord, 1)
stop_queries[working_ind] = self.queries[working_ind]
working_ind = (dist > self.epsilon).nonzero().flatten()
if torch.sum(self.queries >= query_limit) == shape[0]:
print('out of queries')
break
progress_bar(torch.min(self.queries.float()), query_limit,
'd_t: %.4f | adbd: %.4f | queries: %.4f | rob acc: %.4f | iter: %d'
% (torch.mean(self.d_t), torch.mean(dist), torch.mean(self.queries.float()),
len(working_ind) / len(x), i + 1))
stop_queries = torch.clamp(stop_queries, 0, query_limit)
return self.x_final, stop_queries, dist, (dist <= self.epsilon)
# check whether solution is found
def search_succ(self, x, y, target, mask):
self.queries[mask] += 1
if target:
return self.model.predict_label(x[mask]) == target[mask]
else:
return self.model.predict_label(x[mask]) != y[mask]
# binary search for decision boundary along sgn direction
def binary_search(self, x, y, target, sgn, valid_mask, tol=1e-3):
sgn_norm = torch.norm(sgn.view(len(x), -1), 2, 1)
sgn_unit = sgn / sgn_norm.view(len(x), 1, 1, 1)
d_start = torch.zeros_like(y).float().cuda()
d_end = self.d_t.clone()
initial_succ_mask = self.search_succ(self.get_xadv(x, sgn_unit, self.d_t), y, target, valid_mask)
to_search_ind = valid_mask.nonzero().flatten()[initial_succ_mask]
d_end[to_search_ind] = torch.min(self.d_t, sgn_norm)[to_search_ind]
while len(to_search_ind) > 0:
d_mid = (d_start + d_end) / 2.0
search_succ_mask = self.search_succ(self.get_xadv(x, sgn_unit, d_mid), y, target, to_search_ind)
d_end[to_search_ind[search_succ_mask]] = d_mid[to_search_ind[search_succ_mask]]
d_start[to_search_ind[~search_succ_mask]] = d_mid[to_search_ind[~search_succ_mask]]
to_search_ind = to_search_ind[((d_end - d_start)[to_search_ind] > tol)]
to_update_ind = (d_end < self.d_t).nonzero().flatten()
if len(to_update_ind) > 0:
self.d_t[to_update_ind] = d_end[to_update_ind]
self.x_final[to_update_ind] = self.get_xadv(x, sgn_unit, d_end)[to_update_ind]
self.sgn_t[to_update_ind] = sgn[to_update_ind]
def __call__(self, data, label, target=None, query_limit=10000):
return self.attack_hard_label(data, label, target=target, query_limit=query_limit)
| StarcoderdataPython |
1711338 | <reponame>shivamraval98/T5_AE<filename>src/eval_baseline.py
import torch
from models.bert_dataset_loader import *
from models.bert_model import *
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from sklearn.metrics import classification_report
'''
Function to test the trained model on a given dataset
Parameters
------------
model_name (str): pre-trained model name from the huggingface transformers library
model_path (str): the path to the trained model
task_name (str): task name (ex. smm4h_task1, cadec ..)
'''
def test_model(model_name, model_path, task):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_obj = BaselineBERT(model_name, task)
model = BertForSequenceClassification.from_pretrained(model_path)
_,_, test_dataset = model_obj.get_torch_dataset()
model.to(device)
model.eval()
preds_list = []
labels_list = []
for i in range(len(test_dataset)):
b1 = test_dataset[i]
outputs = model(b1['input_ids'].unsqueeze(0).to(device))
pred = outputs.logits.argmax(-1)
preds_list.append(pred.item())
labels_list.append(b1['labels'].item())
print("Test Results")
report = classification_report(labels_list, preds_list, output_dict = True)
print(report)
def main():
#choose any pre-trained BERT based models from huggingface's transformers library (ex: dmis-lab/biobert-v1.1, allenai/scibert_scivocab_uncased, ...)
model_name = "emilyalsentzer/Bio_ClinicalBERT"
#Path to the saved model
model_path = "./baseline"
#choose from the following assert_ade task to train the model (smm4h_task1, smm4h_task2, cadec, ade_corpus)
task = "smm4h_task1"
#Testing the model on the given pre-trained model and task
test_model(model_name, model_path, task)
if __name__ == "__main__":
main()
| StarcoderdataPython |
3303421 | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from ._shared import parse_key_vault_id, KeyVaultResourceId
def parse_key_vault_secret_id(source_id):
# type: (str) -> KeyVaultResourceId
"""Parses a secret's full ID into a class with parsed contents as attributes.
:param str source_id: the full original identifier of a secret
:returns: Returns a parsed secret ID as a :class:`KeyVaultResourceId`
:rtype: ~azure.keyvault.secrets.KeyVaultResourceId
:raises: ValueError
Example:
.. literalinclude:: ../tests/test_parse_id.py
:start-after: [START parse_key_vault_secret_id]
:end-before: [END parse_key_vault_secret_id]
:language: python
:caption: Parse a secret's ID
:dedent: 8
"""
parsed_id = parse_key_vault_id(source_id)
return KeyVaultResourceId(
name=parsed_id.name, source_id=parsed_id.source_id, vault_url=parsed_id.vault_url, version=parsed_id.version
)
| StarcoderdataPython |
1735310 | from distutils.core import setup
from Cython.Build import cythonize
import numpy as np
setup(
name = "On-the-Fly Gridder",
ext_modules = cythonize("src/*.pyx", include_path = [np.get_include()]),
include_dirs = [np.get_include()]
)
| StarcoderdataPython |
3320774 | from sqlite3 import connect
database_name = 'database.db'
class DataBase:
@staticmethod
def createTable(query):
try:
con = connect(database_name)
c = con.cursor()
c.execute(query)
except Exception as e:
print("error:", e)
@staticmethod
def insert(data):
try:
con = connect(database_name)
c = con.cursor()
c.execute(f"INSERT INTO information (name, value) VALUES (?, ?)", data)
con.commit()
con.close()
return True
except Exception as e:
print("error:", e)
@staticmethod
def select(name):
try:
con = connect(database_name)
c = con.cursor()
c.execute(f"SELECT * FROM information WHERE name='{name}'")
result = c.fetchone()
con.close()
return result[1]
except Exception as e:
print("error:", e)
@staticmethod
def update(name, value):
try:
con = connect(database_name)
c = con.cursor()
c.execute(f"UPDATE information SET value='{value}' WHERE name='{name}'")
con.commit()
con.close()
return True
except Exception as e:
print("error:", e)
#sql_create_table = "CREATE TABLE IF NOT EXISTS information (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255) NOT NULL, value VARCHAR(255) NOT NULL);"
#result = LocalDataBase.updateOne('system_id', '3')
#print(result)
#result = LocalDataBase.selectOne('item_camera_port')[2]
#print(result) | StarcoderdataPython |
1646527 | import os
def get_file_path(filename):
if not os.path.exists('config'):
os.makedirs('config')
return 'config/' + filename
| StarcoderdataPython |
3217391 | from pathlib import Path
from time import time
import tempfile
import pytest
from target_extraction.data_types import TargetTextCollection
from target_extraction.dataset_parsers import CACHE_DIRECTORY
from target_extraction.dataset_parsers import download_election_folder
from target_extraction.dataset_parsers import wang_2017_election_twitter_test, wang_2017_election_twitter_train
def test_download_election_folder():
def test_files_and_folders_downloaded(dir_path: Path):
annotation_folder = Path(dir_path, 'annotations')
assert annotation_folder.is_dir()
tweets_folder = Path(dir_path, 'tweets')
assert tweets_folder.is_dir()
train_id_fp = Path(dir_path, 'train_id.txt')
assert train_id_fp.exists()
test_id_fp = Path(dir_path, 'test_id.txt')
assert test_id_fp.exists()
# Test the normal case where it should successfully download the data
with tempfile.TemporaryDirectory() as temp_dir:
temp_dir_path = Path(temp_dir, 'data dir')
download_election_folder(temp_dir_path)
test_files_and_folders_downloaded(Path(temp_dir_path, 'Wang 2017 Election Twitter'))
# Test the case where you do not need to specify a directory it just uses
# the standard cache_dir = CACHE_DIRECTORY
download_election_folder()
test_files_and_folders_downloaded(Path(CACHE_DIRECTORY, 'Wang 2017 Election Twitter'))
# Test the case where it has already been downloaded
# Should take longer to download than to check
with tempfile.TemporaryDirectory() as temp_dir:
first_download_time = time()
temp_dir_path_1 = Path(temp_dir, 'first')
download_election_folder(temp_dir_path_1)
first_download_time = time() - first_download_time
test_files_and_folders_downloaded(Path(temp_dir_path_1, 'Wang 2017 Election Twitter'))
second_time = time()
download_election_folder(temp_dir_path_1)
second_time = time() - second_time
test_files_and_folders_downloaded(Path(temp_dir_path_1, 'Wang 2017 Election Twitter'))
assert second_time < first_download_time
assert second_time < 0.005
assert first_download_time > 0.1
# Test the case where only a certain number of the files have been downloaded.
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(FileNotFoundError):
temp_internal_dir = Path(temp_dir, 'Wang 2017 Election Twitter')
temp_internal_dir.mkdir(parents=True, exist_ok=True)
temp_internal_dir.touch('test_id.txt')
download_election_folder(Path(temp_dir))
def test_train_and_test_dataset():
with tempfile.TemporaryDirectory() as temp_dir:
# Test both the normal cahce_dir and the given cache dir
for data_dir in [None, Path(temp_dir, 'twitter data')]:
train_data = wang_2017_election_twitter_train(data_dir)
test_data = wang_2017_election_twitter_test(data_dir)
assert len(train_data) > len(test_data)
combined_data = TargetTextCollection.combine(train_data, test_data)
assert 11899 == combined_data.number_targets()
| StarcoderdataPython |
124871 | <reponame>Nelestya/baseapp<gh_stars>0
from django.db import models
#Abstract class
class Recently(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def update_recent(self):
"""
return True if is updated recently
"""
return (datetime.now() - self.updated).days < 30
def created_recent(self):
"""
return True if is created recently
"""
return (datetime.now() - self.created).days < 30
class Meta:
abstract = True
class Application(Recently):
name = models.CharField(max_length=30, primary_key=True)
priority = models.IntegerField()
working = models.BooleanField()
def __str__(self):
return self.name
class Image(Recently):
name = models.CharField(max_length=50)
description = models.CharField(max_length=70)
image = models.ImageField(upload_to='images/%Y/%m/%d', blank=True)
application = models.ForeignKey(
'Application',
on_delete=models.CASCADE,)
typeimage = models.ForeignKey(
'SectionImage',
on_delete=models.CASCADE,)
def __str__(self):
return self.name
class SectionImage(Recently):
name = models.CharField(max_length=50, primary_key=True)
def __str__(self):
return self.name
class BugReport(Recently):
STATUS_CHOICE = (
('published', 'Published'),
('resolved', 'Resolved'),
)
title = models.CharField(max_length=50)
mail = models.EmailField()
message = models.TextField()
status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='published')
def __str__(self):
return self.title
class ContactUs(Recently):
STATUS_CHOICE = (
('read', 'Read'),
('unread', 'Unread'),
)
title = models.CharField(max_length=50)
mail = models.EmailField()
message = models.TextField()
status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='unread')
def __str__(self):
return self.title
| StarcoderdataPython |
164043 | <gh_stars>10-100
import torch as th
from typing import Dict, Optional, Tuple
from tpp.models.encoders.base.variable_history import VariableHistoryEncoder
from tpp.utils.encoding import encoding_size
from tpp.utils.events import Events
class IdentityEncoder(VariableHistoryEncoder):
"""Variable encoder that passes the representations straight to the
decoder, i.e. r(t) = rep(l, t).
Args:
emb_dim: Size of the embeddings. Defaults to 1.
embedding_constraint: Constraint on the weights. Either `None`,
'nonneg' or 'softplus'. Defaults to `None`.
temporal_scaling: Scaling parameter for temporal encoding
padding_id: Id of the padding. Defaults to -1.
encoding: Way to encode the events: either times_only, marks_only,
concatenate or temporal_encoding. Defaults to times_only
marks: The distinct number of marks (classes) for the process. Defaults
to 1.
"""
def __init__(
self,
# Other args
emb_dim: Optional[int] = 1,
embedding_constraint: Optional[str] = None,
temporal_scaling: Optional[float] = 1.,
encoding: Optional[str] = "times_only",
time_encoding: Optional[str] = "relative",
marks: Optional[int] = 1,
**kwargs):
super(IdentityEncoder, self).__init__(
name="identity",
output_size=encoding_size(encoding=encoding, emb_dim=emb_dim),
emb_dim=emb_dim,
embedding_constraint=embedding_constraint,
temporal_scaling=temporal_scaling,
encoding=encoding,
time_encoding=time_encoding,
marks=marks,
**kwargs)
def forward(self, events: Events) -> Tuple[th.Tensor, th.Tensor, Dict]:
"""Compute the (query time independent) event representations.
Args:
events: [B,L] Times and labels of events.
Returns:
representations: [B,L+1,M+1] Representations of each event.
representations_mask: [B,L+1] Mask indicating which representations
are well-defined.
"""
histories, histories_mask = self.get_events_representations(
events=events) # [B,L+1,enc] [B,L+1]
return (histories, histories_mask,
dict()) # [B,L+1,D], [B,L+1], Dict
| StarcoderdataPython |
98828 | <reponame>Leonardo-Maciel/Truss_Maciel<filename>10truss/constrict.py
def constrict(maxc,minc,dell):
# Garante que as coordenadas de dell estão dentro dos limites
#
# next = constrict(maxc,minc,dell)
#
# next: vetor avaliado (com coordenadas dentro dos limites)
# maxc: valor máximo das coordenadas
# minc: valor mímimo das coordenadas
# dell: vetor a ser avaliado
for i in range(len(maxc)):
if dell[i]>maxc[i]:
dell[i]=maxc[i]
if dell[i]<minc[i]:
dell[i]=minc[i]
next = dell
return next | StarcoderdataPython |
1669950 | from unittest import TestCase
from yawast.scanner.plugins.dns import basic
class TestGetMx(TestCase):
def test_get_mx(self):
recs = basic.get_mx("adamcaudill.com")
self.assertTrue(len(recs) > 0)
for rec in recs:
if rec[0].startswith("aspmx4"):
self.assertEqual("aspmx4.googlemail.com.", rec[0])
| StarcoderdataPython |
1691350 | import requests, datetime
import json, os, os.path
from .gqlclient import GqlClient
from .constants import url, anime, manga
from collections import namedtuple
from .wrappers.media import Media, MediaTitle, AiringSchedule, MediaTrailer, MediaImage, MediaTag, MediaExternalLink, MediaStreamingEpisode
from .wrappers.character import Character, CharacterImage, CharacterName
from .query_builder import MediaQuery
from functools import singledispatch
from typing import List
class Client:
def __init__(self, client = None):
self.client = client or GqlClient(url)
# self.queries = {
# "mediaById": read("graphql\\media_by_id.gql"),
# "mediaListByIds": read("graphql\\media_list_by_ids.gql"),
# "mediaByName": read("graphql\\media_by_name.gql")
# }
# def getMediaById(self, id: int, type = anime) -> Media:
# return asMedia(self.request(self.queries["mediaById"], { "id": id, "type": type })["Media"])
# def getMediaListByIds(self, ids: list, type = anime) -> list:
# # "Queries are allowed to return a maximum of 50 items. If this is exceeded you just won't receive more entries.
# response = self.request(self.queries["mediaListByIds"], { "id_in": ids, "type": type })
# return [asMedia(media) for media in response["Page"]["media"]]
# def getMediaByName(self, name: str, type = anime) -> Media:
# return asMedia(self.request(self.queries["mediaByName"], { "name": name, "type": type })["Media"])
# def getMedia(self, args: list) -> Media:
# mq = MediaQuery()
# query, variables = mq.build(args)
# # TODO: Consider a better method to pass the args to MediaQuery.build()
# # TODO: Create a QueryBuilder class, that chooses the right query class itself. (?)
# return asMedia(self.request(query, variables)["Media"])
def request(self, query, variables):
response = self.client.request(query, variables)
return response["data"]
def read(relFilePath):
absPath = os.path.abspath(os.path.dirname(__file__))
absPath = os.path.join(absPath, relFilePath)
with open(absPath) as file:
contents = file.read()
return contents
def asCharacter(data):
return Character(
data.get("id", None),
asCharacterName(data.get("name", dict())),
asCharacterImage(data.get("image", dict())),
data.get("description", None),
data.get("isFavourite", None),
data.get("siteUrl", None),
data.get("media", None),
data.get("updatedAt", None),
data.get("favourites", None)
)
def asCharacterName(data):
return CharacterName(
data.get("first", None),
data.get("last", None),
data.get("full", None),
data.get("native", None)
)
def asCharacterImage(data):
return CharacterImage(
data.get("large",None),
data.get("medium",None)
)
def asMediaTrailer(data: dict):
return MediaTrailer(
data.get("id", None),
data.get("site", None),
data.get("thumbnail", None)
)
def asMediaTag(data):
return MediaTag(
data.get("id", None),
data.get("name", None),
data.get("description", None),
data.get("category", None),
data.get("rank", None),
data.get("isGeneralSpoiler", None),
data.get("isMediaSpoiler", None),
data.get("isAdult", None)
)
def asMediaExternalLink(data):
return MediaExternalLink(
data.get("id", None),
data.get("url", None),
data.get("site", None)
)
def asMediaStreamingEpisode(data):
return MediaStreamingEpisode(
data.get("title", None),
data.get("thumbnail", None),
data.get("url", None),
data.get("site", None)
)
def asMedia(data):
return Media(
[asAiringSchedule(airingScheduleDate) for airingScheduleDate in data.get("airingSchedule", dict()).get("edges", dict())],
data.get("id", None),
asMediaTitle(data.get("title", dict())),
asFuzzyDate(data.get("startDate", dict())),
asFuzzyDate(data.get("endDate", dict())),
data.get("type", None),
data.get("format", None),
data.get("status", None),
data.get("description", None),
data.get("season", None),
data.get("seasonInt", None),
data.get("episodes", None),
data.get("duration", None),
data.get("chapters", None),
data.get("volumes", None),
data.get("countryOfOrigin", None),
data.get("isLicensed", None),
data.get("source", None),
data.get("hashtag", None),
asMediaTrailer(data.get("trailer", dict())),
data.get("updatedAt", None),
asMediaImage(data.get("coverImage", dict())),
data.get("bannerImage", None),
data.get("genres", None),
data.get("synonyms", None),
data.get("averageScore", None),
data.get("meanScore", None),
data.get("popularity", None),
data.get("isLocked", None),
data.get("trending", None),
data.get("favourites", None),
[asMediaTag(tag) for tag in data.get("tags", dict())],
[relationId for relationId in data.get("relations", dict()).get("edges", dict())],
[charId for charId in data.get("characters", dict()).get("edges", dict())],
[staffId for staffId in data.get("staff", dict()).get("edges", dict())],
[studioId for studioId in data.get("studios", dict()).get("edges", dict())],
data.get("isFavourite", None),
data.get("isAdult", None),
asAiringSchedule(data.get("nextAiringEpisode", dict())),
data.get("trends", None), # TODO: Parse MediaTrends
[asMediaExternalLink(link) for link in data.get("externalLinks", dict())],
[asMediaStreamingEpisode(episode) for episode in data.get("streamingEpisodes", dict())],
data.get("rankings", None), # TODO: Parse MediaRankings
data.get("mediaListEntry", None), # TODO: Parse this, **if** the user is authenticated, TODO: Make it able so users are able to authenticate
data.get("reviews", None), # TODO: Parse Reviews. Maybe just keep these as ids and query them seperately
data.get("recommendations", None), # TODO: Parse Recommendations
data.get("siteUrl", None),
data.get("autoCreateForumThread", None),
data.get("isRecommendationBlocked", None))
def asMediaImage(data):
return MediaImage(
data.get("extraLarge", None),
data.get("large", None),
data.get("medium", None),
data.get("color", None)
)
def asAiringSchedule(dct: dict):
return AiringSchedule(dct.get("id", None), dct.get("airingAt", None), dct.get("tileUntilAiring", None), dct.get("episode", None), dct.get("mediaId", None))
def asFuzzyDate(dct: dict):
'''
Takes a dictionary and returns a date object using the values.
If either key has a None value, return None.
'''
if dct.get("year", None) == None or dct.get("month", None) == None or dct.get("day", None) == None:
return None
return datetime.date(dct["year"], dct["month"], dct["day"])
def asMediaTitle(dct: dict):
return MediaTitle(dct.get("romaji", None), dct.get("english", None), dct.get("native", None), dct.get("userPreferred", None)) | StarcoderdataPython |
152310 | <reponame>speer-kinjo/ro.py
"""
Grabs asset information.
"""
import asyncio
from roblox import Client
client = Client()
async def main():
asset = await client.get_asset(8100249026)
print("ID:", asset.id)
print("Name:", asset.name)
print(f"Description: {asset.description!r}")
print("Type:", asset.type.name)
print("Creator:")
print("\tType:", asset.creator_type.name)
print("\tName:", asset.creator.name)
print("\tID:", asset.creator.id)
print("Price:", asset.price)
print("Sales:", asset.sales)
print("Is Model:", asset.is_public_domain)
print("Is For Sale:", asset.is_for_sale)
print("Is Limited:", asset.is_limited)
print("Is Limited U:", asset.is_limited_unique)
print("\tRemaining:", asset.remaining)
print("Created:", asset.created.strftime("%m/%d/%Y, %H:%M:%S"))
print("Updated:", asset.updated.strftime("%m/%d/%Y, %H:%M:%S"))
asyncio.get_event_loop().run_until_complete(main())
| StarcoderdataPython |
1645497 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Django settings for server project.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their config, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
from django.utils.translation import ugettext_lazy as _
from project.settings import config, BASE_DIR, ENV
# To avoid cylic dependencies, the SECRET_KEY needs to be defined here so that
# it can be imported into other settings files. If it is defined in the
# environment files then it can be hard to access the value in settings files that
# are parsed before the environment files.
# Note that prod does not have a default value.
if ENV == "production":
SECRET_KEY = config("DJANGO_SECRET_KEY")
else:
SECRET_KEY = config(
"DJANGO_SECRET_KEY",
default="#(=6k@f2#%d%nkv21*%r=8r#%=edt^83lnlk5#yla8(i!!=i0w",
)
# Application title used in templates
SITE_NAME = "{{ cookiecutter.project_name }}"
# Application definition:
INSTALLED_APPS = [
# Local project apps:
"project.apps.main",
# Default django apps:
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# django-admin:
"django.contrib.admin",
"django.contrib.admindocs",
# HTML and CSS helper apps:
"bootstrap4",
"django_icons",
# 'django_filters',
# Security:
# 'axes',
"corsheaders",
# Other:
"django_extensions",
# TODO: Determine if Django FSM is required
# "django_fsm",
]
MIDDLEWARE = [
# Django:
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.contrib.admindocs.middleware.XViewMiddleware",
# Security:
"corsheaders.middleware.CorsMiddleware",
]
ROOT_URLCONF = "project.urls"
WSGI_APPLICATION = "project.wsgi.application"
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = False
USE_L10N = False
USE_TZ = True
LANGUAGES = (("en", _("English")),)
LOCALE_PATHS = ("locale/",)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = "/static/"
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
# Templates
# https://docs.djangoproject.com/en/3.0/ref/templates/api
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
"DIRS": [
# Contains plain text templates, like `robots.txt`:
BASE_DIR.joinpath("project", "templates").as_posix()
],
"OPTIONS": {
"context_processors": [
# Default template context processors:
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.request",
"django_settings_export.settings_export",
]
},
}
]
# Media files
# Media-root is commonly changed in production
# (see development.py and production.py).
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR.joinpath("media").as_posix()
| StarcoderdataPython |
3267984 | from share.transform.chain import * # noqa
from share.transform.chain.utils import format_address
def format_mendeley_address(ctx):
return format_address(
address1=ctx['name'],
city=ctx['city'],
state_or_province=ctx['state'],
country=ctx['country']
)
RELATION_MAP = {
'related_to': 'WorkRelation',
'derived_from': 'IsDerivedFrom',
'source_of': 'IsDerivedFrom',
'compiles': 'Compiles',
'compiled_by': 'Compiles',
'cites': 'Cites',
'cited_by': 'Cites',
}
INVERSE_RELATIONS = {
'cited_by',
'compiled_by',
'derived_from'
}
RELATIONS = {
'cites',
'compiles',
'source_of',
'related_to',
}
def get_related_works(options, inverse):
results = []
for option in options:
relation = option['rel']
if inverse and relation in INVERSE_RELATIONS:
results.append(option)
elif not inverse and relation in RELATIONS:
results.append(option)
return results
def get_relation_type(relation_type):
return RELATION_MAP.get(relation_type, 'WorkRelation')
def get_related_work_type(work_type):
if work_type == 'other':
return 'creativework'
return work_type
class WorkIdentifier(Parser):
uri = ctx
class Tag(Parser):
name = ctx.label
class Extra:
id = ctx.id
class ThroughTags(Parser):
tag = Delegate(Tag, ctx)
class Subject(Parser):
name = ctx
class ThroughSubjects(Parser):
subject = Delegate(Subject, ctx)
class RelatedWork(Parser):
schema = RunPython(get_related_work_type, ctx.type)
identifiers = Map(
Delegate(WorkIdentifier),
Try(
IRI(ctx.href),
exceptions=(InvalidIRI,)
)
)
class WorkRelation(Parser):
schema = RunPython(get_relation_type, ctx.rel)
related = Delegate(RelatedWork, ctx)
class InverseWorkRelation(Parser):
schema = RunPython(get_relation_type, ctx.rel)
subject = Delegate(RelatedWork, ctx)
class RelatedArticle(Parser):
schema = 'Article'
title = Try(ctx.title)
identifiers = Map(
Delegate(WorkIdentifier),
Try(
IRI(ctx.doi),
exceptions=(InvalidIRI,)
)
)
class Extra:
journal = Try(ctx.journal)
title = Try(ctx.title)
doi = Try(ctx.doi)
article_id = Try(ctx.id)
class UsesDataFrom(Parser):
subject = Delegate(RelatedArticle, ctx)
class AgentIdentifier(Parser):
uri = ctx
class AgentInstitution(Parser):
schema = GuessAgentType(ctx.name, default='organization')
name = Try(ctx.name)
location = Try(RunPython(format_mendeley_address, ctx))
identifiers = Map(
Delegate(AgentIdentifier),
Concat(
Try(
IRI(ctx.urls),
exceptions=(InvalidIRI,)
),
Try(
IRI(ctx.profile_url),
exceptions=(InvalidIRI,)
)
)
)
class Extra:
name = Try(ctx.name)
scival_id = Try(ctx.scival_id)
instituion_id = Try(ctx.id)
city = Try(ctx.city)
state = Try(ctx.state)
country = Try(ctx.country)
parent_id = Try(ctx.parent_id)
urls = Try(ctx.urls)
profile_url = Try(ctx.profile_url)
alt_names = Try(ctx.alt_names)
class AgentWorkRelation(Parser):
agent = Delegate(AgentInstitution, ctx)
class IsAffiliatedWith(Parser):
related = Delegate(AgentInstitution, ctx)
class Person(Parser):
"""
{
"id": "",
"first_name": "",
"last_name": "",
"display_name": "",
"link": "",
"folder": "",
"institution": "",
"institution_details": {
"scival_id": 0,
"id": "",
"name": "",
"city": "",
"state": "",
"country": "",
"parent_id": "",
"urls": [
""
],
"profile_url": "",
"alt_names": [
{
"name": ""
}
]
},
"location": {
"id": "",
"latitude": 0,
"longitude": 0,
"name": "",
"city": "",
"state": "",
"country": ""
},
"created": "",
"title": "",
"web_user_id": 0,
"scopus_author_ids": [
""
],
"orcid_id": "",
}
"""
given_name = ctx.first_name
family_name = ctx.last_name
location = RunPython(format_mendeley_address, Try(ctx.full_profile.location))
identifiers = Map(
Delegate(AgentIdentifier),
Concat(
Try(
IRI(ctx.full_profile.orcid_id),
exceptions=(InvalidIRI,)
),
Try(
IRI(ctx.full_profile.link),
exceptions=(InvalidIRI,)
)
)
)
related_agents = Concat(
Map(Delegate(IsAffiliatedWith), Try(ctx.full_profile.institution_details)),
Map(Delegate(IsAffiliatedWith), Try(ctx.institution)),
)
class Extra:
profile_id = Try(ctx.profile_id)
first_name = ctx.first_name
last_name = ctx.last_name
contribution = Try(ctx.contribution)
full_profile = Try(ctx.full_profile)
class Contributor(Parser):
agent = Delegate(Person, ctx)
class Creator(Contributor):
order_cited = ctx('index')
cited_as = RunPython('full_name', ctx)
def full_name(self, ctx):
return '{} {}'.format(ctx['first_name'], ctx['last_name'])
class DataSet(Parser):
"""
{
"id": "",
"doi": {
"id": "",
"status": ""
},
"name": "",
"description": "",
"contributors": [
{
"contribution": "",
"institution": {
"scival_id": 0,
"id": "",
"name": "",
"city": "",
"state": "",
"country": "",
"parent_id": "",
"urls": [""],
"profile_url": "",
"alt_names": [{"name": ""}]
},
"profile_id": "",
"first_name": "",
"last_name": ""
}
],
"articles": [
{
"journal": {
"url": "",
"issn": "",
"name": ""
},
"title": "",
"doi": "",
"id": ""
}
],
"institutions": [
{
"scival_id": 0,
"id": "",
"name": "",
"city": "",
"state": "",
"country": "",
"parent_id": "",
"urls": [],
"profile_url": "",
"alt_names": [{"name": ""}]
}
],
"related_links": [
{
"type": "",
"rel": "",
"href": ""
}
],
"publish_date": "",
"data_licence": {
"description": "",
"url": "",
"full_name": "",
"short_name": "",
"id": ""
},
"embargo_date": ""
}
"""
schema = 'DataSet'
title = Try(ctx.name)
description = Try(ctx.description)
# publish_date "reflects the published date of the most recent version of the dataset"
date_published = ParseDate(Try(ctx.publish_date))
date_updated = ParseDate(Try(ctx.publish_date))
tags = Map(
Delegate(ThroughTags),
Try(ctx.categories)
)
subjects = Map(
Delegate(ThroughSubjects),
Subjects(Try(ctx.categories.label))
)
rights = Try(ctx.data_licence.description)
free_to_read_type = Try(ctx.data_licence.url)
free_to_read_date = ParseDate(Try(ctx.embargo_date))
related_agents = Concat(
Map(
Delegate(Creator), RunPython('filter_contributors', Try(ctx.contributors), 'creator')
),
Map(
Delegate(Contributor), RunPython('filter_contributors', Try(ctx.contributors), 'contributor')
),
Map(
Delegate(AgentWorkRelation), Try(ctx.institutions)
)
)
related_works = Concat(
Map(
Delegate(UsesDataFrom),
Try(ctx.articles) # Journal articles associated with the dataset
),
Map(
Delegate(WorkRelation),
RunPython(
get_related_works,
Try(ctx.related_links),
False
)
),
Map(
Delegate(InverseWorkRelation),
RunPython(
get_related_works,
Try(ctx.related_links),
True
)
)
)
identifiers = Map(
Delegate(WorkIdentifier),
Concat(
RunPython(lambda mendeley_id: 'https://data.mendeley.com/datasets/{}'.format(mendeley_id) if mendeley_id else None, Try(ctx.id)),
Try(
IRI(ctx.doi.id),
exceptions=(InvalidIRI,)
)
)
)
def filter_contributors(self, contributor_list, contributor_type):
filtered = []
for contributor in contributor_list:
try:
if not contributor['contribution'] and contributor_type == 'creator':
filtered.append(contributor)
elif contributor['contribution'] and contributor_type == 'contributor':
filtered.append(contributor)
except KeyError:
if contributor_type == 'creator':
filtered.append(contributor)
return filtered
class Extra:
""" Documentation:
http://dev.mendeley.com/methods/#datasets
http://dev.mendeley.com/methods/#profile-attributes
"""
mendeley_id = Try(ctx.id)
doi = Try(ctx.doi)
name = Try(ctx.name)
description = Try(ctx.description)
version = Try(ctx.version)
contributors = Try(ctx.contributors)
versions = Try(ctx.versions)
files = Try(ctx.files)
articles = Try(ctx.articles)
categories = Try(ctx.categories)
institutions = Try(ctx.institutions)
metrics = Try(ctx.metrics)
available = Try(ctx.available)
method = Try(ctx.method)
related_links = Try(ctx.related_links)
publish_date = ctx.publish_date
data_licence = Try(ctx.data_licence)
owner_id = Try(ctx.owner_id)
embargo_date = Try(ctx.embargo_date)
class MendeleyTransformer(ChainTransformer):
VERSION = 1
root_parser = DataSet
| StarcoderdataPython |
115509 | <filename>benchmarks/sa.py
#!/usr/bin/env python3
import time, argparse
import numpy as np
import arkouda as ak
import random
import string
TYPES = ('int64', 'float64', 'bool', 'str')
def time_ak_sa( vsize,strlen, trials, dtype):
print(">>> arkouda suffix array")
cfg = ak.get_config()
Nv = vsize * cfg["numLocales"]
print("numLocales = {}, num of strings = {:,}".format(cfg["numLocales"], Nv))
if dtype == 'str':
v = ak.random_strings_uniform(1, strlen, Nv)
else:
print("Wrong data type")
c=ak.suffix_array(v)
# print("size of suffix array={}".format(c.bytes.size))
# print("offset/number of suffix array={}".format(c.offsets.size))
# print("itemsize of suffix array={}".format(c.offsets.itemsize))
print("All the random strings are as follows")
for k in range(vsize):
print("the {} th random tring ={}".format(k,v[k]))
print("the {} th suffix array ={}".format(k,c[k]))
print("")
timings = []
for _ in range(trials):
start = time.time()
c=ak.suffix_array(v)
end = time.time()
timings.append(end - start)
tavg = sum(timings) / trials
print("Average time = {:.4f} sec".format(tavg))
if dtype == 'str':
offsets_transferred = 0 * c.offsets.size * c.offsets.itemsize
bytes_transferred = (c.bytes.size * c.offsets.itemsize) + (0 * c.bytes.size)
bytes_per_sec = (offsets_transferred + bytes_transferred) / tavg
else:
print("Wrong data type")
print("Average rate = {:.2f} GiB/sec".format(bytes_per_sec/2**30))
def suffixArray(s):
suffixes = [(s[i:], i) for i in range(len(s))]
suffixes.sort(key=lambda x: x[0])
sa= [s[1] for s in suffixes]
#sa.insert(0,len(sa))
return sa
def time_np_sa(vsize, strlen, trials, dtype):
s=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(strlen))
timings = []
for _ in range(trials):
start = time.time()
sa=suffixArray(s)
end = time.time()
timings.append(end - start)
tavg = sum(timings) / trials
print("Average time = {:.4f} sec".format(tavg))
if dtype == 'str':
offsets_transferred = 0
bytes_transferred = len(s)
bytes_per_sec = (offsets_transferred + bytes_transferred) / tavg
else:
print("Wrong data type")
print("Average rate = {:.2f} GiB/sec".format(bytes_per_sec/2**30))
def check_correctness( vsize,strlen, trials, dtype):
Ni = strlen
Nv = vsize
v = ak.random_strings_uniform(1, Ni, Nv)
c=ak.suffix_array(v)
for k in range(Nv):
s=v[k]
sa=suffixArray(s)
aksa=c[k]
# _,tmp=c[k].split(maxsplit=1)
# aksa=tmp.split()
# intaksa = [int(numeric_string) for numeric_string in aksa]
# intaksa = aksa[1:-1]
# print(sa)
# print(intaksa)
assert (sa==aksa)
def create_parser():
parser = argparse.ArgumentParser(description="Measure the performance of suffix array building: C= suffix_array(V)")
parser.add_argument('hostname', help='Hostname of arkouda server')
parser.add_argument('port', type=int, help='Port of arkouda server')
parser.add_argument('-n', '--size', type=int, default=10**4, help='Problem size: length of strings')
parser.add_argument('-v', '--number', type=int, default=10,help='Number of strings')
parser.add_argument('-t', '--trials', type=int, default=6, help='Number of times to run the benchmark')
parser.add_argument('-d', '--dtype', default='str', help='Dtype of value array ({})'.format(', '.join(TYPES)))
parser.add_argument('--numpy', default=False, action='store_true', help='Run the same operation in NumPy to compare performance.')
parser.add_argument('-r', '--randomize', default=False, action='store_true', help='Use random values instead of ones')
parser.add_argument('--correctness-only', default=False, action='store_true', help='Only check correctness, not performance.')
return parser
if __name__ == "__main__":
import sys
parser = create_parser()
args = parser.parse_args()
if args.dtype not in TYPES:
raise ValueError("Dtype must be {}, not {}".format('/'.join(TYPES), args.dtype))
ak.verbose = False
ak.connect(args.hostname, args.port)
if args.correctness_only:
check_correctness(args.number, args.size, args.trials, args.dtype)
print("CORRECT")
sys.exit(0)
print("length of strings = {:,}".format(args.size))
print("number of strings = {:,}".format(args.number))
print("number of trials = ", args.trials)
time_ak_sa(args.number, args.size, args.trials, args.dtype)
if args.numpy:
time_np_sa(args.number, args.size, args.trials, args.dtype)
sys.exit(0)
| StarcoderdataPython |
3266952 | <filename>Identification-of-Paintings-and-Style-Transfer/Identification/util.py
import sys
import os
import numpy as np
import cv2
import re
def load_image():
filenames = list()
for filename in os.listdir(sys.path[0]):
filenames.append(filename)
X1, X1names = list(), list()
pat = re.compile(r'^(\d+\.)')
for filename in filenames:
if pat.search(filename):
X1.append(cv2.imread(filename, 0))
X1names.append(filename)
X, X_test = list(), list()
Xnames, Xnames_test = list(), list()
y = list() # labels
pat_test = re.compile(r'^((1|7|10|20|23|25|26)\.)')
pat_pos = re.compile(r'^((2|3|4|5|6|8|9|21|22|24|27|28)\.)')
for i in range(len(X1names)):
if pat_test.search(X1names[i]):
X_test.append(X1[i])
Xnames_test.append(X1names[i])
else:
X.append(X1[i])
Xnames.append(X1names[i])
if pat_pos.search(X1names[i]):
y.append(1)
else:
y.append(0)
return X, y, X_test, Xnames, Xnames_test
def distance(T0, C):
"""Compute the Euclidean distance."""
dist = np.sqrt(np.sum((T0 - C) ** 2, 1))
return dist
def resize(X, n=8):
"""
Return:
X: for x in X, x.shape == 2^n * 2^n.
"""
Xnew = list()
for x in X:
res = cv2.resize(x, (pow(2, n), pow(2, n)),
interpolation=cv2.INTER_CUBIC)
Xnew.append(res)
return Xnew
def sp(X, y):
Xnew = list()
for x in X:
a, b = x.shape
a = int(a / 2)
b = int(b / 2)
Xnew.append(x[:a, :b])
Xnew.append(x[:a, b:])
Xnew.append(x[a:, :b])
Xnew.append(x[a:, b:])
ynew = list()
for i in y:
for j in range(4):
ynew.append(i)
return Xnew, ynew
| StarcoderdataPython |
1696778 | <gh_stars>10-100
import shutil
import sqlite3
import subprocess
from os.path import dirname
from pathlib import Path
import regex # type: ignore
import context
from paroxython.cli_tag import main as tag_program
from paroxython.preprocess_source import Cleanup
import draw_flow
PATH = f"{Path(dirname(__file__)).parent}"
VERSION = regex.search(r'(?<=version = ").+?(?=")', Path("pyproject.toml").read_text())[0]
print(f"Release version: {VERSION}")
def update_readme_example():
source = Path("docs/resources/fibonacci.py").read_text().strip()
readme_path = Path("README.md")
readme_text = readme_path.read_text()
(readme_text, n) = regex.subn(
r"(?sm)^\| Taxon \| Lines \|.+?(?=\n\n)",
tag_program(f"# {source}"),
readme_text,
count=1,
)
assert n == 1
(readme_text, n) = regex.subn(r"(?<=paroxython )\S+(?= loaded)", VERSION, readme_text)
assert n == 1
readme_path.write_text(readme_text)
def generate_html():
temp = {
"user_manual": [
"foreword_user.md",
"preparing.md",
"taxonomy.md",
"pipeline_tutorial.md",
"pipeline_documentation.md",
"glossary.md",
],
"developer_manual": [
"bird_view.md",
"helpers.md",
"databases.md",
"implementation_notes.md",
],
}
package_path = Path("paroxython")
for (temp_folder, names) in temp.items():
path = package_path / temp_folder
if path.is_dir():
shutil.rmtree(path)
path.mkdir()
lines = "\n\n<br>\n\n".join(f".. include:: ../../docs/md/{name}" for name in names)
path = path / "__init__.py"
path.write_text(f'"""\n{lines}\n"""\n')
pdoc_options = " ".join(
[
"--force",
"--html",
"-c latex_math=True ",
"-c show_source_code=True",
"--template-dir=docs/pdoc_template",
"--output-dir docs",
]
)
base_path = Path("docs")
directory_names = ("cli", "user_manual", "developer_manual")
for directory_name in directory_names:
path = base_path / directory_name
if path.is_dir():
shutil.rmtree(path)
subprocess.run(f"pdoc {pdoc_options} paroxython", shell=True)
subprocess.run(f"mv -f docs/paroxython/* docs; rmdir docs/paroxython/", shell=True)
for temp_folder in temp:
path = package_path / temp_folder
if path.is_dir():
shutil.rmtree(path)
def resolve_new_types():
data = [
("user_types", "source", "Source"),
("assess_costs", "taxon", "TaxonName"),
("preprocess_source", "label_name", "LabelName"),
("derived_labels_db", "query", "Query"),
("filter_programs", "operation", "Operation"),
("map_taxonomy", "label_pattern", "LabelPattern"),
]
result = {}
for (filename, trigger, type_name) in data:
source = Path(f"docs/{filename}.html").read_text()
match = regex.search(
fr"{trigger}(?:</span> )?: (<function NewType\.<locals>\.new_type at 0x\w+?>)", source
)
result[type_name] = match[1]
print(f"{match[1]} -> {type_name}")
for path in Path("docs/").rglob("*.html"):
source = path.read_text()
initial_length = len(source)
for (type_name, bad_string) in result.items():
source = source.replace(bad_string, type_name)
if len(source) < initial_length:
path.write_text(source)
for path in Path("docs/").rglob("*.html"):
if path.name == "index.html":
continue
source = path.read_text()
source = regex.sub(
r'<a title="paroxython\.user_types\.(\w+?)" href="user_types\.html#paroxython\.user_types\.\1">\1</a>',
r"\1",
source,
)
source = source.replace("paroxython.user_types.", "")
source = source.replace("typing_extensions.", "")
source = source.replace("_regex.Pattern object", "regex")
source = source.replace(PATH, ".")
path.write_text(source)
path = Path("docs/index.html")
source = path.read_text()
source = regex.sub(r"(?m)^.+paroxython\.user_types.+\n", "", source)
path.write_text(source)
Path("docs/user_types.html").unlink()
def remove_blacklisted_sources():
filenames = ("index.html",)
base_path = Path("docs/")
for filename in filenames:
path = base_path / filename
source = path.read_text()
source = regex.sub(r'(?ms)^<details class="source">.+?^</details>\n', "", source)
path.write_text(source)
def strip_docstrings():
sub_code = regex.compile(r'(?ms)^(<pre><code class="python">)(.+?)(</code></pre>)').sub
sub_docstrings = regex.compile(r"(?ms)^\s*r?""".+?"""\n+").sub
for path in Path("docs/").rglob("*.html"):
source = path.read_text()
source = sub_code(lambda m: m[1] + sub_docstrings("", m[2]) + m[3], source)
source = source.replace('"git-link">Browse git</a>', '"git-link">Browse GitHub</a>')
path.write_text(source)
def cleanup_index():
for path in Path("docs/").rglob("index.html"):
source = path.read_text()
source = source.replace(" …", ".")
path.write_text(source)
def insert_line_breaks():
sub_args = regex.compile(
r'(?m)^(<span>def <span class="ident">\w+</span></span>\(<span>.+?)(,.+\) ‑>)'
).sub
sub_arg = regex.compile(r"(\w+:|\) ‑>|\*\*?\w+)").sub
for path in Path("docs/").rglob("*.html"):
source = path.read_text()
source = sub_args(lambda m: m[1] + sub_arg(r"<br>\1", m[2]), source)
path.write_text(source)
def compute_stats():
readme_path = Path("README.md")
readme_text = readme_path.read_text()
cleanup = Cleanup("full")
directories = ["paroxython", "tests", "helpers"]
for directory in directories:
total = 0
for program_path in Path(directory).glob("**/*.py"):
source = program_path.read_text()
# Work around a weird error:
# tokenize.TokenError: ('EOF in multi-line string', (12, 10))
source = source.replace('if __name__ == "__main__":\n bar = foo', "pass\npass")
source = cleanup.run(source)
total += source.count("\n")
print(f"{directory}: {total} SLOC")
total = 50 * round(total / 50)
(readme_text, n) = regex.subn(
fr"(?m)(!\[{directory} SLOC\].+?)~\d+(%20SLOC)",
fr"\1~{total}\2",
readme_text,
)
assert n > 0, f"Unable to create badge for '{directory}' SLOC."
total = Path("paroxython/resources/spec.md").read_text().count("#### Feature")
(readme_text, n) = regex.subn(
fr"(?m)(!\[spec features\].+?)-\d+(%20features)",
fr"\1-{total}\2",
readme_text,
)
assert n == 1
total = Path("paroxython/resources/taxonomy.tsv").read_text().partition("-- EOF")[0].count("\n")
(readme_text, n) = regex.subn(
fr"(?m)(!\[taxonomy mappings\].+)-\d+(%20mappings)",
fr"\1-{total}\2",
readme_text,
)
assert n == 1
readme_path.write_text(readme_text)
def patch_prose():
index_path = Path("docs/index.html")
index_text = index_path.read_text()
index_text = index_text.replace("<h1>Index</h1>\n", "")
for title in ("User manual", "Developer manual"):
slug = title.lower().replace(" ", "_")
path = Path("docs") / slug / "index.html"
text = path.read_text()
(text, n) = regex.subn(
f"""<h1 class="title">Module <code>paroxython.{slug}</code></h1>""",
f"""<h1 class="title">{title}</h1>""",
text,
)
assert n == 1, f"Unable to change the title of {slug}!"
(text, n) = regex.subn(
f"<h1>Index</h1>",
f"<h1>{title}</h1>",
text,
)
assert n == 1, f"Unable to change the title of {slug} in nav!"
(text, n) = regex.subn(fr"""(?s)</div>\n<ul id="index">.+</ul>\n""", "", text)
assert n == 1, f"Unable to suppress the index section in prose {slug}'s nav!"
(index_text, n) = regex.subn(
fr"""<li><code><a title="paroxython.{slug}".+\n""", "", index_text
)
assert n == 1, f"Unable to remove nav url for {slug}!"
(index_text, n) = regex.subn(
fr"""(?s)<dt><code class="name"><a title="paroxython\.{slug}".+?</dd>\n""",
"",
index_text,
)
assert n == 1, f"Unable to remove module section for {slug}!"
(text, n) = regex.subn(fr"""(?s)<details class="source">.+</details>\n""", "", text)
assert n == 1, f"Unable to suppress the source code in prose {slug}!"
(text, n) = regex.subn(
"""href="index.html">""",
"""href="../index.html">""",
text,
)
assert n == 1, f"Unable to patch the Home url in {slug}!"
path.write_text(text)
index_path.write_text(index_text)
def update_github_links():
count = 2
source = Path("tests/test_recommend_programs.py").read_text()
path = Path("docs/md/pipeline_documentation.md")
text = path.read_text()
(text, n) = regex.subn(
r"test_recommend_programs.py#L\d+-L\d+", f"test_recommend_programs.py#L-L", text
)
assert n == count
for i in range(1, count + 1):
start = source.partition(f"# extract_{i} (start)")[0].count("\n") + 2
stop = source.partition(f"# extract_{i} (stop)")[0].count("\n")
assert start < stop
(text, n) = regex.subn(
r"test_recommend_programs.py#L-L",
f"test_recommend_programs.py#L{start}-L{stop}",
text,
count=1,
)
assert n == 1
path.write_text(text)
def inject_flow_diagram_in_nav():
path = Path("docs/developer_manual/index.html")
text = path.read_text()
(text, n) = regex.subn(r"(</nav>)", r'<p><img alt="" src="../resources/flow.png"></p>\1', text)
assert n == 1
path.write_text(text)
def expand_repo_urls():
for path in Path("docs/").rglob("*.html"):
source = path.read_text()
source = source.replace(
"<code>spec.md</code>",
'<a href="https://repo/paroxython/resources/spec.md"><code>spec.md</code></a>',
)
source = source.replace(
"<code>taxonomy.tsv</code>",
'<a href="https://repo/paroxython/resources/taxonomy.tsv"><code>taxonomy.tsv</code></a>',
)
source = source.replace(
"https://repo/", "https://github.com/laowantong/paroxython/blob/master/"
)
path.write_text(source)
def update_version_number():
for path in ["paroxython/cli_tag.py", "paroxython/cli_collect.py"]:
path = Path(path)
source = path.read_text()
(source, n) = regex.subn(
r"(?<=https://github\.com/laowantong/paroxython/blob/)[^/]+", VERSION, source
)
assert n == 1, path
path.write_text(source)
def link_manuals():
index_path = Path("docs/index.html")
index_text = index_path.read_text()
(index_text, n) = regex.subn(
r'(<li><a href="#about">About</a><ul>)',
(
'<li><a href="user_manual/index.html">User manual</a></li>'
"<ul>"
'<li><a href="user_manual/index.html#how-to-read-this-manual">How to read this manual</a></li>'
'<li><a href="user_manual/index.html#preparing-your-program-collection">Preparing your program collection</a></li>'
'<li><a href="user_manual/index.html#taxonomy">Taxonomy</a></li>'
'<li><a href="user_manual/index.html#pipeline-tutorial">Pipeline tutorial</a></li>'
'<li><a href="user_manual/index.html#pipeline-documentation">Pipeline documentation</a></li>'
'<li><a href="user_manual/index.html#glossary">Glossary</a></li>'
"</ul>"
'<li><a href="developer_manual/index.html">Developer manual</a></li>'
"<ul>"
'<li><a href="developer_manual/index.html#bird-view">Bird view</a></li>'
'<li><a href="developer_manual/index.html#helper-programs">Helper programs</a></li>'
'<li><a href="developer_manual/index.html#tag-databases">Tag databases</a></li>'
'<li><a href="developer_manual/index.html#implementation-notes">Implementation notes</a></li>'
"</ul>"
r"\1"
),
index_text,
)
assert n == 1
(index_text, n) = regex.subn(r'\b(src|href)="docs/', r'\1="', index_text)
assert n == 2
index_path.write_text(index_text)
def inject_taxonomy():
index_path = Path("docs/user_manual/index.html")
text = index_path.read_text()
tree = Path("docs/resources/tree.js").read_text()
head = f"""
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">{tree}</script>
"""
(text, n) = regex.subn("</head>", fr"{head}</head>", text)
assert n == 1
index_path.write_text(text)
def disable_cli_code_syntax_hightlighting():
base_path = Path("docs")
for path in base_path.glob("cli*.html"):
print(path)
source = path.read_text()
source = regex.sub('(?s)<code class="plain">(.+?)</code>', r"\1", source)
path.write_text(source)
def main():
update_readme_example()
update_version_number()
update_github_links()
generate_html()
expand_repo_urls()
resolve_new_types()
remove_blacklisted_sources()
strip_docstrings()
cleanup_index()
insert_line_breaks()
patch_prose()
inject_flow_diagram_in_nav()
link_manuals()
inject_taxonomy()
disable_cli_code_syntax_hightlighting()
compute_stats()
if __name__ == "__main__":
main()
| StarcoderdataPython |
175370 | <filename>build_dataset.py<gh_stars>0
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split, KFold, StratifiedKFold
import matplotlib.pyplot as plt
OUTPUT = './data/'
NC = 2
NAMES = ['benign','malignant']
SEED = 0
def _count_class_samples(labels):
"""Count samples of each class names"""
names = np.unique(NAMES) #sort
return {names[i]:j for i, j in zip(*np.unique(labels, return_counts=True))}
def _process_csv(annotation_csv):
df = pd.read_csv(annotation_csv)
mask = df['SEVERITY'].str.lower().isin(NAMES)
masked_df = df[mask].copy()
filenames = masked_df['FILENAME'].values
severities = masked_df['SEVERITY'].values
lb = LabelEncoder()
labels = lb.fit_transform(severities)
labels_names = lb.classes_.tolist()
return filenames, labels
def _write_csv(csv_filename, image_filepaths, image_labels):
df = pd.DataFrame({'FILEPATHS':image_filepaths,'LABELS':image_labels})
df['FILEPATHS'] = df['FILEPATHS'].astype(str)
df['LABELS'] = df['LABELS'].astype(int)
dst = str(Path(OUTPUT).joinpath(csv_filename)) if csv_filename.endswith('.csv') else str(Path(OUTPUT).joinpath((csv_filename+'.csv')))
df.to_csv(dst,index=False)
def _plotter(ax,data,ax_title):
import matplotlib.patches as mpatches
names = list(data.keys())
values = list(data.values())
rects = ax.bar(names,values,color=['deepskyblue','orangered'],width=0.5)
ax.set_ylabel('Total')
ax.set_title(ax_title)
ymax = 1000
ymin = 0
ax.set_ylim([ymin,ymax])
total = sum([rect.get_height() for rect in rects])
black_patch = mpatches.Patch(color='black', label='Total = {}'.format(total))
ax.legend(handles=[black_patch])
def autolabel(rects):
for rect in rects:
height = rect.get_height()
cx = rect.get_x() + rect.get_width()/2
ax.annotate('{}'.format(height),
xy=(cx,height),
xytext=(0,2), #offset txt by 2 points
textcoords='offset points', #offset mode
ha='center',va='bottom')
autolabel(rects)
def visualize_stats(args_cbis,args_inbreast,fig_title='Dataset Statistic'):
cbis_csv = str(Path(args_cbis).joinpath('annotation/cbis-roi.csv'))
_ , cbis_labels = _process_csv(cbis_csv)
inbreas_csv = str(Path(args_inbreast).joinpath('annotation/inbreast-roi.csv'))
_ , inbreas_labels = _process_csv(inbreas_csv)
data1 = _count_class_samples(cbis_labels)
data2 = _count_class_samples(inbreas_labels)
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
_plotter(ax1,data1,'CBIS-DDSM')
_plotter(ax2,data2,'INbreast')
fig.suptitle(fig_title)
fig.tight_layout()
plt.show()
def split_train_val(image_directory,annotation_csv,train_ratio,stratify,name=''):
filenames, labels = _process_csv(annotation_csv)
image_filepaths = np.array([str(Path(image_directory).joinpath(f)) for f in filenames])
image_labels = labels.copy()
assert len(image_filepaths) == len(image_labels)
if stratify:
train_imgs, val_imgs, train_labels, val_labels = train_test_split(
image_filepaths,
image_labels,
train_size=train_ratio,
random_state = SEED,
stratify=image_labels)
else:
train_imgs, val_imgs, train_labels, val_labels = train_test_split(
image_filepaths,
image_labels,
train_size=train_ratio,
random_state = SEED)
_write_csv(f'{name}-train.csv',train_imgs,train_labels)
_write_csv(f'{name}-val.csv',val_imgs,val_labels)
def split_kfold(image_directory,annotation_csv,n_fold,stratify,name=''):
filenames, labels = _process_csv(annotation_csv)
image_filepaths = np.array([str(Path(image_directory).joinpath(f)) for f in filenames])
image_labels = labels.copy()
assert len(image_filepaths) == len(image_labels)
if stratify:
skf = StratifiedKFold(n_splits=n_fold,shuffle=True,random_state=SEED)
for fold, (train_index, val_index) in enumerate(skf.split(image_filepaths,image_labels),1):
train_imgs, val_imgs = image_filepaths[train_index], image_filepaths[val_index]
train_labels, val_labels = image_labels[train_index], image_labels[val_index]
_write_csv(f'{name}-fold{fold}-train.csv',train_imgs,train_labels)
_write_csv(f'{name}-fold{fold}-val.csv',val_imgs,val_labels)
else:
kf = KFold(n_splits=n_fold,shuffle=True,random_state=SEED)
for fold, (train_index, val_index) in enumerate(kf.split(image_filepaths),1):
train_imgs, val_imgs = image_filepaths[train_index], image_filepaths[val_index]
train_labels, val_labels = image_labels[train_index], image_labels[val_index]
_write_csv(f'{name}-fold{fold}-train.csv',train_imgs,train_labels)
_write_csv(f'{name}-fold{fold}-val.csv',val_imgs,val_labels)
def main(args):
print('[INFO] Build dataset')
if args.cbis:
print('[INFO] Processing CBIS')
image_directory = str(Path(args.cbis).joinpath('images'))
if not Path(image_directory).is_dir():
raise NotADirectoryError('image directory not found')
annotation_csv = str(Path(args.cbis).joinpath('annotation/cbis-roi.csv'))
if not Path(annotation_csv).is_file():
raise FileNotFoundError('csv file not found')
if args.command == 'split':
split_train_val(image_directory,annotation_csv,args.train_ratio,args.stratify,name='cbis')
elif args.command == 'kfold':
split_kfold(image_directory,annotation_csv,args.num_folds,args.stratify,name='cbis')
if args.inbreast:
print(('[INFO] Processing INbreast'))
image_directory = str(Path(args.inbreast).joinpath('images'))
if not Path(image_directory).is_dir():
raise NotADirectoryError('image directory not found')
annotation_csv = str(Path(args.inbreast).joinpath('annotation/inbreast-roi.csv'))
if not Path(annotation_csv).is_file():
raise FileNotFoundError('csv file not found')
filenames, labels = _process_csv(annotation_csv)
if args.command == 'split':
split_train_val(image_directory,annotation_csv,args.train_ratio,args.stratify,name='inbreast')
elif args.command == 'kfold':
split_kfold(image_directory,annotation_csv,args.num_folds,args.stratify,name='inbreast')
if args.visualize:
print('[INFO] Visualizing Dataset Statistic')
visualize_stats(args_cbis=args.cbis,args_inbreast=args.inbreast)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Build Mammogram Dataset for MMG Mass Classification')
parser.add_argument('--cbis',type=str,help='path to cbis-roi folder')
parser.add_argument('--inbreast',type=str,help='path to inbreast-roi folder')
parser.add_argument('--stratify',action='store_true',default=True,help='apply stratified splitting')
parser.add_argument('--visualize',action='store_true',help='visualize datasetstats')
subparser = parser.add_subparsers(dest='command')
split = subparser.add_parser('split')
split.add_argument('--train-ratio',type=float,help='split ratio for trainset',required=True)
kfold = subparser.add_parser('kfold')
kfold.add_argument('--num-folds',type=int,help='total fold split',required=True)
args = parser.parse_args()
main(args)
| StarcoderdataPython |
3354857 | import argparse
import tempfile
from flask import Flask
from flask_cors import CORS
from xplainer.backend.router import register_routes
from xplainer.backend.utils.model import load_and_analyze
def create_and_run_app(debug=False):
parser = argparse.ArgumentParser(description="xxx")
parser.add_argument("--model", type=str, help="your model file")
# parser.add_argument("--port", type=int, default=5005, help="port for running the backend")
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tmp_dir:
app = create_app(args, tmp_dir=tmp_dir, debug=debug)
app.run(host="127.0.0.1", port=5005)
def create_app(args, tmp_dir, debug=False):
app = Flask(__name__)
CORS(app, supports_credentials=True)
app.secret_key = <KEY>" # needed for session
app.config["model"] = args.model
print("----------------------------------------------------------")
print("Loading and analyzing model. This might take a while.")
print("----------------------------------------------------------")
model = load_and_analyze(args.model, tmp_dir)
print("----------------------------------------------------------")
print("Loading done. Application is stating.")
print("----------------------------------------------------------")
register_routes(app, tmp_dir, model, not debug)
return app
if __name__ == "__main__":
create_and_run_app(debug=True)
| StarcoderdataPython |
1644526 | <filename>tccli/services/billing/v20180709/help.py
# -*- coding: utf-8 -*-
DESC = "billing-2018-07-09"
INFO = {
"DescribeBillDetail": {
"params": [
{
"name": "Offset",
"desc": "Offset"
},
{
"name": "Limit",
"desc": "Quantity, maximum is 100"
},
{
"name": "PeriodType",
"desc": "The period type. byUsedTime: By usage period; byPayTime: By payment period. Must be the same as the period of the current monthly bill of the Billing Center. You can check your bill statistics period type at the top of the [Bill Overview](https://console.cloud.tencent.com/expense/bill/overview) page. "
},
{
"name": "Month",
"desc": "Month; format: yyyy-mm. You only have to enter either Month or BeginTime and EndTime. When you enter values for BeginTime and EndTime, Month becomes invalid. This value must be no earlier than the month when Bill 2.0 is activated; last 24 months data are available."
},
{
"name": "BeginTime",
"desc": "The start time of the period; format: Y-m-d H:i:s. You only have to enter either Month or BeginTime and EndTime. When you enter values for BeginTime and EndTime, Month becomes invalid. BeginTime and EndTime must be inputted as a pair. This value must be no earlier than the month when Bill 2.0 is activated; last 24 months data are available."
},
{
"name": "EndTime",
"desc": "The end time of the period; format: Y-m-d H:i:s. You only have to enter either Month or BeginTime and EndTime. When you enter values for BeginTime and EndTime, Month becomes invalid. BeginTime and EndTime must be inputted as a pair. This value must be no earlier than the month when Bill 2.0 is activated; last 24 months data are available."
},
{
"name": "NeedRecordNum",
"desc": "Indicates whether or not the total number of records of accessing the list is required, used for frontend pages.\n1 = yes, 0 = no"
},
{
"name": "ProductCode",
"desc": "Queries information on a specified product"
},
{
"name": "PayMode",
"desc": "Billing mode: prePay/postPay"
},
{
"name": "ResourceId",
"desc": "Queries information on a specified resource"
}
],
"desc": "This API is used to query bill details."
},
"DescribeBillSummaryByPayMode": {
"params": [
{
"name": "PayerUin",
"desc": "Query bill data user’s UIN"
},
{
"name": "BeginTime",
"desc": "Only beginning in the current month is supported, and it must be the same month as the EndTime. For example, 2018-09-01 00:00:00."
},
{
"name": "EndTime",
"desc": "Only ending in the current month is supported, and it must be the same month as the BeginTime. For example, 2018-09-30 23:59:59."
}
],
"desc": "Gets the bill summarized according to billing mode"
},
"DescribeBillResourceSummary": {
"params": [
{
"name": "Offset",
"desc": "Offset"
},
{
"name": "Limit",
"desc": "Quantity, maximum is 1000"
},
{
"name": "PeriodType",
"desc": "The period type. byUsedTime: By usage period; byPayTime: by payment period. Must be the same as the period of the current monthly bill of the Billing Center. You can check your bill statistics period type at the top of the [Bill Overview](https://console.cloud.tencent.com/expense/bill/overview) page."
},
{
"name": "Month",
"desc": "Month; format: yyyy-mm. This value cannot be earlier than the month when Bill 2.0 is enabled. Last 24 months data are available."
},
{
"name": "NeedRecordNum",
"desc": "Indicates whether or not the total number of records of accessing the list is required, used for frontend pages.\n1 = yes, 0 = no"
}
],
"desc": "This API is used to query bill resources summary. "
},
"DescribeBillSummaryByRegion": {
"params": [
{
"name": "PayerUin",
"desc": "Queries bill data user’s UIN"
},
{
"name": "BeginTime",
"desc": "Only beginning in the current month is supported, and it must be the same month as the EndTime. For example, 2018-09-01 00:00:00."
},
{
"name": "EndTime",
"desc": "Only ending in the current month is supported, and it must be the same month as the BeginTime. For example, 2018-09-30 23:59:59."
}
],
"desc": "Gets the bill summarized according to region"
},
"DescribeBillSummaryByProject": {
"params": [
{
"name": "PayerUin",
"desc": "Queries bill data user’s UIN"
},
{
"name": "BeginTime",
"desc": "Only beginning in the current month is supported, and it must be the same month as the EndTime. For example, 2018-09-01 00:00:00."
},
{
"name": "EndTime",
"desc": "Only ending in the current month is supported, and it must be the same month as the BeginTime. For example, 2018-09-30 23:59:59."
}
],
"desc": "Gets the bill summarized according to project"
},
"DescribeBillSummaryByProduct": {
"params": [
{
"name": "PayerUin",
"desc": "Queries bill data user’s UIN"
},
{
"name": "BeginTime",
"desc": "Only beginning in the current month is supported, and it must be the same month as the EndTime. For example, 2018-09-01 00:00:00."
},
{
"name": "EndTime",
"desc": "Only ending in the current month is supported, and it must be the same month as the BeginTime. For example, 2018-09-30 23:59:59."
}
],
"desc": "Gets the bill summarized according to product"
},
"DescribeBillSummaryByTag": {
"params": [
{
"name": "PayerUin",
"desc": "Payer UIN"
},
{
"name": "BeginTime",
"desc": "Currently the period to be queried must start from a time point in the current month, and the starting time and the end time must be in the same month. Example: 2018-09-01 00:00:00."
},
{
"name": "EndTime",
"desc": "Currently the period to be queried must end at a time point in the current month, and the starting time and the end time must be in the same month. Example: 2018-09-30 23:59:59."
},
{
"name": "TagKey",
"desc": "Cost allocation tag key"
}
],
"desc": "This API is used to get the cost distribution over different tags."
}
} | StarcoderdataPython |
52648 | <reponame>megatran/selflearning_openCV_ComputerVision
import cv2
import numpy as np
"""
Corner matching in images is tolerant of:
- Rotations
- Translation
- Slight photometric changes e.g brightness or affine intensity
It is INTOLERANT OF:
- large changes in intensity or photometric changes
- scaling
"""
#import image
source_input = "/Users/nhant/Google Drive/OnlineLearning/selflearning_CV_with_Python/practice_sources/images/chess.jpg"
image = cv2.imread(source_input)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# The cornerHarris function requires the array datatype to be float32
gray = np.float32(gray)
harris_corners = cv2.cornerHarris(gray, 3, 3, 0.05)
# We use dilation of the corner points to enlarge them
kernel = np.ones((7,7), np.uint8)
harris_corners = cv2.dilate(harris_corners, kernel, iterations=2)
# Threshold for an optimal value, it may vary depending on the image
image[harris_corners > 0.025*harris_corners.max()] = [255,127,127]
cv2.imshow('Harris Corners', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
#IMPROVE CORNER DETECTION USING - Good features to Track
img = cv2.imread(source_input)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Specify the top 50 corners
corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 150)
for corner in corners:
x, y = corner[0]
x = int(x)
y = int(y)
cv2.rectangle(img, (x-10, y-10), (x+10, y+10), (0,255,0), 2)
cv2.imshow("Corners Found", img)
cv2.waitKey()
cv2.destroyAllWindows()
| StarcoderdataPython |
3375218 | # -*- coding: utf-8 -*-
import importlib
from . import operators
from . import panels
importlib.reload(operators)
importlib.reload(panels)
def register():
operators.register()
panels.register()
def unregister():
operators.unregister()
panels.unregister()
| StarcoderdataPython |
27855 | <filename>medicalseg/utils/utils.py
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import contextlib
import filelock
import os
import tempfile
import numpy as np
import random
from urllib.parse import urlparse, unquote
import paddle
from medicalseg.utils import logger, seg_env
from medicalseg.utils.download import download_file_and_uncompress
@contextlib.contextmanager
def generate_tempdir(directory: str = None, **kwargs):
'''Generate a temporary directory'''
directory = seg_env.TMP_HOME if not directory else directory
with tempfile.TemporaryDirectory(dir=directory, **kwargs) as _dir:
yield _dir
def load_entire_model(model, pretrained):
if pretrained is not None:
load_pretrained_model(model, pretrained)
else:
logger.warning('Not all pretrained params of {} are loaded, ' \
'training from scratch or a pretrained backbone.'.format(model.__class__.__name__))
def download_pretrained_model(pretrained_model):
"""
Download pretrained model from url.
Args:
pretrained_model (str): the url of pretrained weight
Returns:
str: the path of pretrained weight
"""
assert urlparse(pretrained_model).netloc, "The url is not valid."
pretrained_model = unquote(pretrained_model)
savename = pretrained_model.split('/')[-1]
if not savename.endswith(('tgz', 'tar.gz', 'tar', 'zip')):
savename = pretrained_model.split('/')[-2]
else:
savename = savename.split('.')[0]
with generate_tempdir() as _dir:
with filelock.FileLock(os.path.join(seg_env.TMP_HOME, savename)):
pretrained_model = download_file_and_uncompress(
pretrained_model,
savepath=_dir,
extrapath=seg_env.PRETRAINED_MODEL_HOME,
extraname=savename)
pretrained_model = os.path.join(pretrained_model, 'model.pdparams')
return pretrained_model
def load_pretrained_model(model, pretrained_model):
if pretrained_model is not None:
logger.info(
'Loading pretrained model from {}'.format(pretrained_model))
if urlparse(pretrained_model).netloc:
pretrained_model = download_pretrained_model(pretrained_model)
if os.path.exists(pretrained_model):
para_state_dict = paddle.load(pretrained_model)
model_state_dict = model.state_dict()
keys = model_state_dict.keys()
num_params_loaded = 0
for k in keys:
if k not in para_state_dict:
logger.warning("{} is not in pretrained model".format(k))
elif list(para_state_dict[k].shape) != list(
model_state_dict[k].shape):
logger.warning(
"[SKIP] Shape of pretrained params {} doesn't match.(Pretrained: {}, Actual: {})"
.format(k, para_state_dict[k].shape,
model_state_dict[k].shape))
else:
model_state_dict[k] = para_state_dict[k]
num_params_loaded += 1
model.set_dict(model_state_dict)
logger.info("There are {}/{} variables loaded into {}.".format(
num_params_loaded, len(model_state_dict),
model.__class__.__name__))
else:
raise ValueError(
'The pretrained model directory is not Found: {}'.format(
pretrained_model))
else:
logger.info(
'No pretrained model to load, {} will be trained from scratch.'.
format(model.__class__.__name__))
def resume(model, optimizer, resume_model):
if resume_model is not None:
logger.info('Resume model from {}'.format(resume_model))
if os.path.exists(resume_model):
resume_model = os.path.normpath(resume_model)
ckpt_path = os.path.join(resume_model, 'model.pdparams')
para_state_dict = paddle.load(ckpt_path)
ckpt_path = os.path.join(resume_model, 'model.pdopt')
opti_state_dict = paddle.load(ckpt_path)
model.set_state_dict(para_state_dict)
optimizer.set_state_dict(opti_state_dict)
iter = resume_model.split('_')[-1]
iter = int(iter)
return iter
else:
raise ValueError(
'Directory of the model needed to resume is not Found: {}'.
format(resume_model))
else:
logger.info('No model needed to resume.')
def worker_init_fn(worker_id):
np.random.seed(random.randint(0, 100000))
def get_image_list(image_path, valid_suffix=None, filter_key=None):
"""Get image list from image name or image directory name with valid suffix.
if needed, filter_key can be used to whether 'include' the key word.
When filter_key is not None,it indicates whether filenames should include certain key.
Args:
image_path(str): the image or image folder where you want to get a image list from.
valid_suffix(tuple): Contain only the suffix you want to include.
filter_key(dict): the key and whether you want to include it. e.g.:{"segmentation": True} will futher filter the imagename with segmentation in it.
"""
if valid_suffix is None:
valid_suffix = [
'nii.gz', 'nii', 'dcm', 'nrrd', 'mhd', 'raw', 'npy', 'mha'
]
image_list = []
if os.path.isfile(image_path):
if image_path.split("/")[-1].split('.',
maxsplit=1)[-1] in valid_suffix:
if filter_key is not None:
f_name = image_path.split("/")[
-1] # TODO change to system invariant
for key, val in filter_key:
if (key in f_name) is not val:
break
else:
image_list.append(image_path)
else:
image_list.append(image_path)
else:
raise FileNotFoundError(
'{} is not a file end with supported suffix, the support suffixes are {}.'
.format(image_path, valid_suffix))
# load image in a directory
elif os.path.isdir(image_path):
for root, dirs, files in os.walk(image_path):
for f in files:
if '.ipynb_checkpoints' in root:
continue
if f.split(".", maxsplit=1)[-1] in valid_suffix:
image_list.append(os.path.join(root, f))
else:
raise FileNotFoundError(
'`--image_path` is not found. it should be a path of image, or a directory including images.'
)
if len(image_list) == 0:
raise RuntimeError(
'There are not image file in `--image_path`={}'.format(image_path))
return image_list
| StarcoderdataPython |
3305320 | <filename>tests/test_util.py
import unittest
from falcon_crossorigin.util import _match_sub_domain
class TestUtil(unittest.TestCase):
def test_match_sub_domain(self):
long_domain = "http://{}.com".format("a" * 254)
# schemes are empty or do not match
self.assertFalse(_match_sub_domain("", ""))
self.assertFalse(_match_sub_domain("http://example.com", "https://example.com"))
self.assertFalse(_match_sub_domain("https://example.com", "http://example.com"))
# domain is empty
self.assertFalse(_match_sub_domain("http://example.com", "http://"))
self.assertFalse(_match_sub_domain("http://", "http://example.com"))
# domain too long
self.assertFalse(_match_sub_domain(long_domain, "http://example.com"))
# domain does not match pattern
self.assertFalse(
_match_sub_domain("http://app.example.com", "http://app.test.example.com")
)
# invalid domain/pattern
self.assertFalse(_match_sub_domain("http://app.", "http://app"))
self.assertFalse(_match_sub_domain("http://app", "http://app."))
| StarcoderdataPython |
195814 | <reponame>juhapekka/apitrace
##########################################################################
#
# Copyright 2011 <NAME>
# Copyright 2008-2010 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/
"""GLX tracing generator."""
from gltrace import GlTracer
from specs.stdapi import Module, API
from specs.glapi import glapi
from specs.glxapi import glxapi
class GlxTracer(GlTracer):
def isFunctionPublic(self, function):
# The symbols visible in libGL.so can vary, so expose them all
return True
getProcAddressFunctionNames = [
"glXGetProcAddress",
"glXGetProcAddressARB",
]
createContextFunctionNames = [
'glXCreateContext',
'glXCreateContextAttribsARB',
'glXCreateContextWithConfigSGIX',
'glXCreateNewContext',
]
destroyContextFunctionNames = [
'glXDestroyContext',
]
makeCurrentFunctionNames = [
'glXMakeCurrent',
'glXMakeContextCurrent',
'glXMakeCurrentReadSGI',
]
def traceFunctionImplBody(self, function):
if function.name in self.destroyContextFunctionNames:
print ' gltrace::releaseContext((uintptr_t)ctx);'
GlTracer.traceFunctionImplBody(self, function)
if function.name in self.createContextFunctionNames:
print ' if (_result != NULL)'
print ' gltrace::createContext((uintptr_t)_result);'
if function.name in self.makeCurrentFunctionNames:
print ' if (_result) {'
print ' if (ctx != NULL)'
print ' gltrace::setContext((uintptr_t)ctx);'
print ' else'
print ' gltrace::clearContext();'
print ' }'
if __name__ == '__main__':
print
print '#include <stdlib.h>'
print '#include <string.h>'
print
print '#ifndef _GNU_SOURCE'
print '#define _GNU_SOURCE // for dladdr'
print '#endif'
print '#include <dlfcn.h>'
print
print '#include "trace_writer_local.hpp"'
print
print '// To validate our prototypes'
print '#define GL_GLEXT_PROTOTYPES'
print '#define GLX_GLXEXT_PROTOTYPES'
print
print '#include "glproc.hpp"'
print '#include "glsize.hpp"'
print
module = Module()
module.mergeModule(glxapi)
module.mergeModule(glapi)
api = API()
api.addModule(module)
tracer = GlxTracer()
tracer.traceApi(api)
print r'''
/*
* Invoke the true dlopen() function.
*/
static void *_dlopen(const char *filename, int flag)
{
typedef void * (*PFN_DLOPEN)(const char *, int);
static PFN_DLOPEN dlopen_ptr = NULL;
if (!dlopen_ptr) {
dlopen_ptr = (PFN_DLOPEN)dlsym(RTLD_NEXT, "dlopen");
if (!dlopen_ptr) {
os::log("apitrace: error: dlsym(RTLD_NEXT, \"dlopen\") failed\n");
return NULL;
}
}
return dlopen_ptr(filename, flag);
}
/*
* Several applications, such as Quake3, use dlopen("libGL.so.1"), but
* LD_PRELOAD does not intercept symbols obtained via dlopen/dlsym, therefore
* we need to intercept the dlopen() call here, and redirect to our wrapper
* shared object.
*/
extern "C" PUBLIC
void * dlopen(const char *filename, int flag)
{
void *handle;
handle = _dlopen(filename, flag);
const char * libgl_filename = getenv("TRACE_LIBGL");
if (filename && handle && !libgl_filename) {
if (0) {
os::log("apitrace: warning: dlopen(\"%s\", 0x%x)\n", filename, flag);
}
// FIXME: handle absolute paths and other versions
if (strcmp(filename, "libGL.so") == 0 ||
strcmp(filename, "libGL.so.1") == 0) {
// Use the true libGL.so handle instead of RTLD_NEXT from now on
_libGlHandle = handle;
// Get the file path for our shared object, and use it instead
static int dummy = 0xdeedbeef;
Dl_info info;
if (dladdr(&dummy, &info)) {
os::log("apitrace: redirecting dlopen(\"%s\", 0x%x)\n", filename, flag);
handle = _dlopen(info.dli_fname, flag);
} else {
os::log("apitrace: warning: dladdr() failed\n");
}
}
}
return handle;
}
'''
| StarcoderdataPython |
1796032 | <gh_stars>0
from requests import Session
QUERY_URL = "https://reware-production.yerdle.io/v4/graphql"
ITEM_URL_TEMPLATE = "https://wornwear.patagonia.com/shop/{slug}/{parentSKU}/{color}"
def fetch_titles(session, offset, limit):
query = """
{
partner(uuid: "7d32ad83-330e-4ccc-ba03-3bb32ac113ac") {
categories {
slug
inventoryItemsForSale(
facets: [{ tag:"size" name:"S" }]
""" + """
limit: {limit}
offset: {offset}
""".format(offset=offset, limit=limit) + """
sort: "pr"
) {
title
color
parentSKU
price
}
}
}
}
"""
resp = session.post(QUERY_URL, json=dict(query=query))
cats = resp.json()['data']['partner']['categories']
for cat in cats:
slug = cat['slug']
items = cat['inventoryItemsForSale']
for i in items:
i['slug'] = slug
yield i
def titles():
session = Session()
offset = 0
limit = 50
while True:
titles = list(fetch_titles(session, offset=offset, limit=limit))
if not titles:
break
offset += limit
for t in titles:
yield t
def main(*argv):
for t in titles():
t['price'] = int(t['price'] / 100)
t['url'] = ITEM_URL_TEMPLATE.format(**t)
print('{title}: ${price} {url}'.format(**t))
if __name__ == '__main__':
from sys import argv
main(*argv)
| StarcoderdataPython |
1743868 | <gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
import numpy as np
from runner import RunnerThread, process_rollout
from LSTM import LSTMPolicy
import tensorflow as tf
import six.moves.queue as queue
import gym
import sys
import os
from datetime import datetime, timedelta
from misc import timestamp, time_string
from envs import create_env
@ray.actor
class Runner(object):
"""Actor object to start running simulation on workers.
Gradient computation is also executed from this object."""
def __init__(self, env_name, actor_id, logdir="results/", start=True):
env = create_env(env_name)
self.id = actor_id
num_actions = env.action_space.n
self.policy = LSTMPolicy(env.observation_space.shape, num_actions, actor_id)
self.runner = RunnerThread(env, self.policy, 20)
self.env = env
self.logdir = logdir
if start:
self.start()
def pull_batch_from_queue(self):
""" self explanatory: take a rollout from the queue of the thread runner. """
rollout = self.runner.queue.get(timeout=600.0)
while not rollout.terminal:
try:
rollout.extend(self.runner.queue.get_nowait())
except queue.Empty:
break
return rollout
def start(self):
summary_writer = tf.summary.FileWriter(os.path.join(self.logdir, "agent_%d" % self.id))
self.summary_writer = summary_writer
self.runner.start_runner(self.policy.sess, summary_writer)
def compute_gradient(self, params):
self.policy.set_weights(params)
rollout = self.pull_batch_from_queue()
batch = process_rollout(rollout, gamma=0.99, lambda_=1.0)
gradient = self.policy.get_gradients(batch)
info = {"id": self.id,
"size": len(batch.a)}
return gradient, info
def train(num_workers, env_name="PongDeterministic-v3"):
env = create_env(env_name)
policy = LSTMPolicy(env.observation_space.shape, env.action_space.n, 0)
agents = [Runner(env_name, i) for i in range(num_workers)]
parameters = policy.get_weights()
gradient_list = [agent.compute_gradient(parameters) for agent in agents]
steps = 0
obs = 0
while True:
done_id, gradient_list = ray.wait(gradient_list)
gradient, info = ray.get(done_id)[0]
policy.model_update(gradient)
parameters = policy.get_weights()
steps += 1
obs += info["size"]
gradient_list.extend([agents[info["id"]].compute_gradient(parameters)])
return policy
if __name__ == '__main__':
num_workers = int(sys.argv[1])
ray.init(num_cpus=num_workers)
train(num_workers)
| StarcoderdataPython |
4830513 | import torch
from torch.utils.data import TensorDataset
import pickle
import numpy as np
import pandas as pd
from train_parameters import *
from src.normalization import Normalization
from src.voigt_rotation import *
from src.model_utils import CPU_Unpickler
def exportTensor(name,data,cols, header=True):
df=pd.DataFrame.from_records(data.detach().numpy())
if(header):
df.columns = cols
print(name)
df.to_csv(name+".csv", header=header, index=False)
def exportList(name,data):
arr=np.array(data)
np.savetxt(name+".csv", [arr], delimiter=',')
def getNormalization(save_normalization=False):
data = pd.read_csv(dataPath)
# check for NaNs
assert not data.isnull().values.any()
F1_features = torch.tensor(data[F1_features_names].values)
R2 = torch.tensor(data[R2_names].values)
V = torch.tensor(data[V_names].values)
C_ort = torch.tensor(data[C_ort_names].values)
C = torch.tensor(data[C_names].values)
a,b,c = torch.split(R2,[1,1,1],dim=1)
R2_transposed = torch.cat((-a,b,c),dim=1)
unrotatedlabelTensor = direct_rotate(C,R2_transposed)
F1_features_scaling = Normalization(F1_features,F1_features_types,F1_features_scaling_strategy)
V_scaling = Normalization(V,V_types,V_scaling_strategy)
C_ort_scaling = Normalization(C_ort, C_ort_types,C_ort_scaling_strategy)
C_scaling = Normalization(C,C_types,C_scaling_strategy)
C_hat_scaling = Normalization(unrotatedlabelTensor,C_types,C_hat_scaling_strategy)
# should only be activated if framework is retrained with different dataset
if save_normalization:
with open('src/normalization/F1_features_scaling.pickle', 'wb') as file_:
pickle.dump(F1_features_scaling, file_, -1)
with open('src/normalization/V_scaling.pickle', 'wb') as file_:
pickle.dump(V_scaling, file_, -1)
with open('src/normalization/C_ort_scaling.pickle', 'wb') as file_:
pickle.dump(C_ort_scaling, file_, -1)
with open('src/normalization/C_scaling.pickle', 'wb') as file_:
pickle.dump(C_scaling, file_, -1)
with open('src/normalization/C_hat_scaling.pickle', 'wb') as file_:
pickle.dump(C_hat_scaling, file_, -1)
return F1_features_scaling, C_ort_scaling, C_scaling, V_scaling, C_hat_scaling
def getSavedNormalization():
F1_features_scaling = CPU_Unpickler(open("src/normalization/F1_features_scaling.pickle", "rb", -1)).load()
V_scaling = CPU_Unpickler(open("src/normalization/V_scaling.pickle", "rb", -1)).load()
C_ort_scaling = CPU_Unpickler(open("src/normalization/C_ort_scaling.pickle", "rb", -1)).load()
C_scaling = CPU_Unpickler(open("src/normalization/C_scaling.pickle", "rb", -1)).load()
C_hat_scaling = CPU_Unpickler(open("src/normalization/C_hat_scaling.pickle", "rb", -1)).load()
return F1_features_scaling, C_ort_scaling, C_scaling, V_scaling, C_hat_scaling
def getDataset(F1_features_scaling, V_scaling, C_ort_scaling, C_scaling):
data = pd.read_csv(dataPath)
print('Data: ',data.shape)
# check for NaNs
assert not data.isnull().values.any()
F1_features = torch.tensor(data[F1_features_names].values)
R1 = torch.tensor(data[R1_names].values)
R2 = torch.tensor(data[R2_names].values)
V = torch.tensor(data[V_names].values)
C_ort = torch.tensor(data[C_ort_names].values)
C = torch.tensor(data[C_names].values)
F1_features = F1_features_scaling.normalize(F1_features)
V = V_scaling.normalize(V)
C_ort = C_ort_scaling.normalize(C_ort)
C = C_scaling.normalize(C)
dataset = TensorDataset(F1_features.float(), R1.float(), V.float(), R2.float(), C_ort.float(), C.float())
l1 = round(len(dataset)*traintest_split)
l2 = len(dataset) - l1
print('train/test: ',[l1,l2],'\n\n')
train_set, test_set = torch.utils.data.random_split(dataset, [l1,l2], generator=torch.Generator().manual_seed(42))
return train_set, test_set
def getDataset_pred(C_scaling,E,dataPath_pred):
data = pd.read_csv(dataPath_pred)
print('Data: ',data.shape)
# check for NaNs
assert not data.isnull().values.any()
C = torch.tensor(data[C_names].values)
# normalize stiffness by Young's modulus of base material
C = torch.div(C,E)
C = C_scaling.normalize(C)
dataset = C.float()
return dataset | StarcoderdataPython |
1725389 | <reponame>fernherrera/pylibrets
"""RETS search response parser classes."""
from xml.etree import ElementTree
from .exceptions import RetsException
class SearchResultSet(object):
def GetReplyCode(self):
pass
def GetReplyText(self):
pass
def GetCount(self):
pass
def GetColumns(self):
pass
def GetData(self):
pass
class CompactResultSetParser(SearchResultSet):
def __init__(self, xml_str):
self.xml_str = xml_str
self.result_xml = ElementTree.fromstring(xml_str)
self.delimiter = self._get_delimiter()
def _get_delimiter(self):
delimiter_node = self.result_xml.find('DELIMITER')
return int(delimiter_node.attrib['value'])
def _fix_compact_array(self, data_list):
if len(data_list) < 2:
raise RetsException('Unknown COMPACT format: ')
if not len(data_list[0]) == 0:
raise RetsException('nvalid COMPACT format, missing initial tab: ')
else:
del data_list[0]
if not len(data_list[-1]) == 0:
raise RetsException('Invalid COMPACT format, missing final tab: ')
else:
del data_list[-1]
return data_list
def GetReplyCode(self):
replyCode = self.result_xml.find('RETS').get('ReplyCode')
return int(replyCode)
def GetReplyText(self):
replyText = self.result_xml.find('RETS').get('ReplyText')
return replyText
def GetCount(self):
count = self.result_xml.find('COUNT').get('Records')
return int(count)
def GetColumns(self):
column_xml_list = self.result_xml.find('COLUMNS')
column_list = self._fix_compact_array(column_xml_list.text.split(chr(self.delimiter)))
return column_list
def GetData(self):
data_rows = []
column_list = self.GetColumns()
data_xml_list = self.result_xml.findall('DATA')
for item in data_xml_list:
row = dict(zip(column_list, self._fix_compact_array(item.text.split(chr(self.delimiter)))))
data_rows.append(row)
return data_rows
| StarcoderdataPython |
2776 | <reponame>by-liu/SegLossBia
import sys
import logging
from seglossbias.utils import mkdir, setup_logging
from seglossbias.engine import default_argument_parser, load_config, DefaultTester
logger = logging.getLogger(__name__)
def setup(args):
cfg = load_config(args)
mkdir(cfg.OUTPUT_DIR)
setup_logging(output_dir=cfg.OUTPUT_DIR)
return cfg
def main():
args = default_argument_parser().parse_args()
cfg = setup(args)
logger.info("Launch command : ")
logger.info(" ".join(sys.argv))
tester = DefaultTester(cfg)
tester.test()
if __name__ == "__main__":
main()
| StarcoderdataPython |
189198 | from carberretta import Config
from .bot import Bot
| StarcoderdataPython |
3274751 | <filename>feedzero/feeds/tests/test_models.py
from django.db.utils import IntegrityError
from model_mommy import mommy
import pytest
from feedzero.feeds.models import Entry, EntryState, Feed, FeedManager
@pytest.mark.django_db
class TestFeedModel:
def test_dunder_str(self, feed):
"""The model should render the name as the string."""
assert str(feed) == feed.title
def test_generated_slug(self, feed):
"""The model should generate an appropriate slug."""
assert feed.slug == "my-amazing-feed"
def test_handles_duplicated_slug(self):
"""The model should generate an appropriate slug if a duplicate is found."""
mommy.make(Feed, title="This is only a test")
feed_dup = mommy.make(Feed, title="This is only a test")
assert feed_dup.slug == "this-is-only-a-test-1"
def test_is_watched_by(self, feed, user):
"""If the user is watching the feed, return True."""
user.watch(feed)
assert feed.is_watched_by(user)
def test_is_watched_by_no_found(self, feed, user):
"""Feeds are not watched by default"""
assert not feed.is_watched_by(user)
def test_uses_custom_manager(self):
"""The feed model should use a custom manager, relied upon elsewhere in code."""
assert isinstance(Feed.objects, FeedManager)
def test_scraping_defaults_to_true(self):
"""The feed model should default to scraping."""
assert Feed._meta.get_field("scraping_enabled").default is True
@pytest.mark.django_db
class TestFeedManager:
def test_watched_by(self, feed_factory, user):
"""Should return only feeds watched by the user."""
feeds = [feed_factory() for i in range(5)]
unwatched = feeds.pop()
[user.watch(feed) for feed in feeds]
assert unwatched not in Feed.objects.watched_by(user).all()
@pytest.mark.django_db
class TestEntryStateModel:
def test_unique_together_constraint(self, entry, user):
"""The model should forbid state, user, entry combo duplicates."""
mommy.make(EntryState, entry=entry, state=EntryState.STATE_PINNED, user=user)
with pytest.raises(IntegrityError):
mommy.make(
EntryState, entry=entry, state=EntryState.STATE_PINNED, user=user
)
def test_pinned_and_read(self, entry, user):
"""The model should allow an entry to be both pinned and read."""
mommy.make(EntryState, entry=entry, state=EntryState.STATE_PINNED, user=user)
mommy.make(EntryState, entry=entry, state=EntryState.STATE_READ, user=user)
def test_saved_and_pinned(self, entry, user):
"""The model should allow an entry to be both pinned and saved."""
mommy.make(EntryState, entry=entry, state=EntryState.STATE_PINNED, user=user)
mommy.make(EntryState, entry=entry, state=EntryState.STATE_SAVED, user=user)
@pytest.mark.django_db
class TestEntryModel:
def test_dunder_str(self, entry):
"""The model should render the name as the string."""
assert str(entry) == entry.title
def test_clean_checks_duplicates(self, entry):
"""A duplicated entry within a feed should raise an IntegrityError."""
with pytest.raises(IntegrityError):
mommy.make(Entry, guid=entry.guid, feed=entry.feed)
def test_slug_handles_duplicates_per_feed(self):
"""A duplicated slug should not raise, should handle."""
entry = mommy.make(Entry, title="My Amazing Entry!")
entry_dup = mommy.make(Entry, feed=entry.feed, title=entry.title)
assert entry_dup.slug == "my-amazing-entry-1"
def test_feed_guid_unique_together_constraint(self, entry):
"""A duplicated guid for the same feed should raise IntegrityError."""
with pytest.raises(IntegrityError):
mommy.make(Entry, feed=entry.feed, guid=entry.guid)
def test_feed_guid_unique_together_allowed(self, entry):
"""Guid uniqueness should only be bound to the same feed."""
mommy.make(Entry, guid=entry.guid)
def test_feed_deletion_cascades_deletion(self, entry):
"""Entry should be deleted when an associated Feed is deleted."""
entry.feed.delete()
with pytest.raises(Entry.DoesNotExist):
entry.refresh_from_db()
def test_author_deletion_sets_null(self, entry_fill):
"""Entry should be preserved when an associated Author is deleted."""
entry_fill.author.delete()
entry_fill.refresh_from_db()
assert entry_fill.author is None
def test_mark_read_by_creates(self, entry, user):
"""Should create a read by state."""
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_READ
).exists()
entry.mark_read_by(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_READ
)
)
== 1
)
def test_mark_read_by_get(self, entry, user):
"""Should reuse existing state if exists."""
entry.mark_read_by(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_READ
)
)
== 1
)
entry.mark_read_by(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_READ
)
)
== 1
)
def test_mark_pinned_creates(self, entry, user):
"""Should create a pinned state."""
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
).exists()
entry.mark_pinned(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 1
)
def test_mark_pinned_get(self, entry, user):
"""Should reuse existing state if exists."""
entry.mark_pinned(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 1
)
entry.mark_pinned(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 1
)
def test_mark_unpinned_deletes(self, entry, user):
"""Should delete pinned state."""
entry.mark_pinned(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 1
)
entry.mark_unpinned(user)
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
).exists()
def test_mark_unpinned_allows_state_not_exists(self, entry, user):
"""If the state does not exist, should fail silently."""
entry.mark_unpinned(user)
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
).exists()
def test_mark_saved_creates(self, entry, user):
"""Should create a saved state."""
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
).exists()
entry.mark_saved(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
)
)
== 1
)
def test_mark_saved_get(self, entry, user):
"""Should reuse existing state if exists."""
entry.mark_saved(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
)
)
== 1
)
entry.mark_saved(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
)
)
== 1
)
def test_mark_unsaved_deletes(self, entry, user):
"""Should delete saved state."""
entry.mark_saved(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
)
)
== 1
)
entry.mark_unsaved(user)
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
).exists()
def test_mark_unsaved_allows_state_not_exists(self, entry, user):
"""If the state does not exist, should fail silently."""
entry.mark_unsaved(user)
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
).exists()
def test_mark_deleted_creates(self, entry, user):
"""Should create a deleted state."""
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
).exists()
entry.mark_deleted(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
)
)
== 1
)
def test_mark_deleted_get(self, entry, user):
"""Should reuse existing state if exists."""
entry.mark_deleted(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
)
)
== 1
)
entry.mark_deleted(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
)
)
== 1
)
def test_mark_undeleted_deletes(self, entry, user):
"""Should delete deleted state."""
entry.mark_deleted(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
)
)
== 1
)
entry.mark_undeleted(user)
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
).exists()
def test_mark_undeleted_allows_state_not_exists(self, entry, user):
"""If the state does not exist, should fail silently."""
entry.mark_undeleted(user)
assert not EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_DELETED
).exists()
def test_mark_deleted_removes_pinned_states(self, entry, user):
"""If the entry is also pinned, remove pinned state on deletion."""
entry.mark_pinned(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 1
)
entry.mark_deleted(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 0
)
def test_mark_deleted_removed_saved_states(self, entry, user):
"""If the entry is also saved, remove saved state on deletion."""
entry.mark_saved(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
)
)
== 1
)
entry.mark_deleted(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_SAVED
)
)
== 0
)
def test_mark_saved_deletes_pinned_states(self, entry, user):
"""If the entry is also pinned, remove pinned state on save."""
entry.mark_pinned(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 1
)
entry.mark_saved(user)
assert (
len(
EntryState.objects.filter(
entry=entry, user=user, state=EntryState.STATE_PINNED
)
)
== 0
)
def test_teaser_uses_summary_if_available(self, entry):
"""If the summary is available from the feed, use it instead."""
entry.summary = "Summary"
entry.content = "Content"
assert entry.teaser == "Summary"
def test_teaser_falls_back_to_content(self, entry):
"""If the summary is not available from the feed, use content."""
entry.summary = None
entry.content = "Content"
assert entry.teaser == "Content"
def test_teaser_truncates(self, entry):
"""Should truncate content longer than X characters."""
text = "Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it?" # noqa
entry.summary = text
assert (
entry.teaser
== "Do you see any Teletubbies in here? Do you see a slender plastic tag clipped…"
)
def test_teaser_short_copy_no_truncate(self, entry):
"""Short copy should return unmodified."""
entry.summary = "This is only a test"
assert entry.teaser == "This is only a test"
| StarcoderdataPython |
1741806 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
"""Helper functions for calculating optimal binary quantization."""
from typing import Tuple
import torch
import torch.nn.utils.rnn as rnn_utils
from quant.binary.ste import binary_sign
def cost_function(matrix: torch.Tensor, v1s: torch.Tensor, ternary: bool = False) -> torch.Tensor:
"""
Compute the cost function to find the optimal v1.
The cost function is equation (8) in the paper, for k=2.
It can be derived by expanding s1, s2 using the foldable quantization equation (9).
Args:
matrix: original 2D tensor
v1s: 2D tensor containing potential optimal solutions
ternary: compute cost for ternary function
Returns:
Norms as a 2D tensor
"""
matrix_view = matrix.view(matrix.shape[0], 1, -1)
v1s_view = v1s.view(v1s.shape[0], v1s.shape[1], 1)
s2_arg = matrix_view - v1s_view * binary_sign(matrix_view)
if ternary:
v2 = v1s_view
else:
v2 = s2_arg.abs().mean(dim=-1, keepdim=True)
return torch.norm(s2_arg - v2 * binary_sign(s2_arg), dim=-1) # type: ignore
def compute_mask(matrix: torch.Tensor, ternary: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Compute mask for a 2D tensor of absolute values.
The mask reveals potential optimal values.
Args:
matrix: A 2D tensor of absolute values.
ternary: whether we are computing mask for ternary algorithm
Returns:
A 2-tuple of tensors, where the first element is a mask
tensor and the second element are values selected
"""
values, _ = torch.sort(matrix, dim=1)
cum_sums = values.cumsum(dim=1)
# store counts of elements at the corresponding position
counts = torch.arange(1, matrix.shape[1] + 1, device=matrix.device)
counts_rev = torch.flip(counts, [0]) - 1
counts_rev[-1] = 1 # avoid division by 0, value at this pos. will not be used
m1s = None
if not ternary:
# m1s stores cumulative means from left to right (chopping left and right most values)
m1s = (cum_sums / counts)[:, 1:-1]
# m2s stores cumulative means from right to left (chopping left and right most values)
m2s = ((cum_sums[:, -1:] - cum_sums) / counts_rev)[:, 1:-1]
# re-using m1s and m2s to save memory
# using m1s and m2s values to find potential optimal solutions to v1 and v2
if not ternary:
m1s = 0.5 * (m1s + m2s)
m2s = 0.5 * m2s
# Find potential solutions in inner region and boundary
# Instead of finding equality, find index where m1s or m2s
# is >= than everything on the left and <= than everything on the right
mask = (values[:, 1:-1] <= m2s) * (m2s <= values[:, 2:])
if not ternary:
mask = mask + (values[:, 1:-1] <= m1s) * (m1s <= values[:, 2:])
masked_vs = torch.masked_select(values[:, 1:-1], mask)
return mask, masked_vs
def _handle_ternary_min_gt_half_avg(
matrix: torch.Tensor, masked_vs: torch.Tensor, split_sizes: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Handle edge case in ternary case when min value is less than half of average."""
# Suppose x is the absolute value of the tensor to be quantized
# For least squares, 2 bits, the optimal v will always be between min(x) and max(x)
# For the ternary case, the optimal v could be < min(x)
# This occurs when min(x) > 1/2 * avg(x)
# When this occurs, then we should append 1/2 * avg(x) as a solution
rows_mean = matrix.mean(dim=1)
rows_min, _ = matrix.min(dim=1)
row_min_gt_half_avg = rows_min > 0.5 * rows_mean
if not torch.any(row_min_gt_half_avg):
# This should almost always be the case
return masked_vs, split_sizes
# This should rarely happen if at all (e.g., when all elements are equal)
new_masked_vs = []
masked_vs_list = masked_vs.tolist()
current_pos = 0
for i, v in enumerate(row_min_gt_half_avg):
if split_sizes[i] > 0:
new_masked_vs.extend(
masked_vs_list[current_pos:current_pos + int(split_sizes[i].item())]
)
current_pos += int(split_sizes[i].item())
if v:
split_sizes[i] += 1
new_masked_vs.append(rows_mean[i].item() / 2)
return torch.tensor(new_masked_vs, device=matrix.device), split_sizes
def opt_v1(matrix: torch.Tensor, ternary: bool, skip: int = 1) -> torch.Tensor: # type: ignore
"""
Implement the algorithm to find v1 for least squares 2-bit and ternary algorithm.
Args:
matrix: A 2D tensor
ternary: whether to do ternary optimization
skip: increment in potential solution space to speed up computation
Returns:
Optimal v1
"""
with torch.no_grad():
matrix_skipped = matrix[..., ::skip].abs()
mask, masked_vs = compute_mask(matrix_skipped, ternary)
# masked_vs is a vector, we need to separate it into potential
# optimal solutions by row (dim 0)
split_sizes = mask.sum(dim=1)
if ternary:
# handle a special case for ternary that rarely occurs
masked_vs, split_sizes = _handle_ternary_min_gt_half_avg(
matrix_skipped, masked_vs, split_sizes
)
vs = torch.split(masked_vs, split_sizes.tolist()) # type: ignore
vs = rnn_utils.pad_sequence(vs, batch_first=True) # type: ignore
costs = cost_function(matrix_skipped, vs, ternary)
indices = torch.argmin(costs, dim=-1, keepdim=True)
v1 = torch.gather(vs, 1, indices)
return v1
| StarcoderdataPython |
3305407 | <gh_stars>0
import urllib
from IPython import embed
"""This module should contain functions to parse specific formats"""
def write_lsf_linetools_from_stscifile(stsci_file, output):
"""reads a stsci LSF file for COS, and writes the proper format that linetools
expects.
It currently works for the table versions at \
www.stsci.edu/hst/instrumentation/cos/performance/spectral-resolution
available on 16 april 2020... (they sometimes change the format)
"""
f = open(stsci_file, 'r')
fo = open(output, 'w')
lines = f.readlines()
# parse first line
l0 = lines[0]
l0_new = l0.replace(' ', 'A,')
l0_new = l0_new.replace('\n', 'A\n')
l0_new = 'pixel,'+l0_new
fo.write(l0_new)
for ii, line in enumerate(lines[1:]):
line_new = '{}\t'.format(ii+1) + line
fo.write(line_new)
fo.close()
f.close()
| StarcoderdataPython |
3342455 | # Generated by Django 2.2.9 on 2020-01-05 04:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('politicians', '0010_auto_20200105_0355'),
]
operations = [
migrations.AddField(
model_name='politicians',
name='email',
field=models.EmailField(blank=True, max_length=254, null=True),
),
migrations.AddField(
model_name='politicians',
name='first_name',
field=models.CharField(default='Aloizas', max_length=50, verbose_name='Vardas'),
preserve_default=False,
),
migrations.AddField(
model_name='politicians',
name='last_name',
field=models.CharField(default='Sakalas', max_length=150, verbose_name='Pavardė'),
preserve_default=False,
),
migrations.AddField(
model_name='politicians',
name='personal_website',
field=models.URLField(blank=True, null=True),
),
migrations.AddField(
model_name='politicians',
name='phone',
field=models.CharField(blank=True, max_length=12, null=True),
),
migrations.AddField(
model_name='politicians',
name='slug',
field=models.SlugField(default='aloizas-sakals', unique=True),
preserve_default=False,
),
]
| StarcoderdataPython |
3387742 | import yaml
# 文字列でYAMLを定義
yaml_str = """
# 定義
color_def:
- &color1 "#FF0000"
- &color2 "#00FF00"
- &color3 "#0000FF"
# エイリアスのテスト
color:
title: *color1
body: *color2
link: *color3
"""
# YAMLを解析
data = yaml.load(yaml_str)
# エイリアスが展開されているかテスト
print("title=", data["color"]["title"])
print("body=", data["color"]["body"])
print("link=", data["color"]["link"])
| StarcoderdataPython |
4838391 | <filename>reagent/training/ranking/seq2slate_dr_trainer.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
import reagent.core.types as rlt
import torch
import torch.nn as nn
import torch.nn.functional as F
from reagent.core.dataclasses import field
from reagent.core.parameters import Seq2SlateParameters
from reagent.model_utils.seq2slate_utils import (
Seq2SlateMode,
per_symbol_to_per_seq_log_probs,
)
from reagent.models.seq2slate import Seq2SlateTransformerModel, Seq2SlateTransformerNet
from reagent.optimizer.union import Optimizer__Union
from reagent.training.ranking.helper import ips_clamp
from reagent.training.trainer import Trainer
logger = logging.getLogger(__name__)
class Seq2SlateDifferentiableRewardTrainer(Trainer):
"""
Seq2Slate learned with differentiable reward (Section 3.2 in
https://arxiv.org/pdf/1810.02019.pdf )
"""
def __init__(
self,
seq2slate_net: Seq2SlateTransformerNet,
parameters: Seq2SlateParameters,
minibatch_size: int,
use_gpu: bool = False,
policy_optimizer: Optimizer__Union = field( # noqa: B008
default_factory=Optimizer__Union.default
),
print_interval: int = 100,
) -> None:
self.parameters = parameters
self.use_gpu = use_gpu
self.print_interval = print_interval
self.seq2slate_net = seq2slate_net
self.minibatch_size = minibatch_size
self.minibatch = 0
self.optimizer = policy_optimizer.make_optimizer_scheduler(
self.seq2slate_net.parameters()
)["optimizer"]
# TODO: T62269969 add baseline_net in training
self.kl_div_loss = nn.KLDivLoss(reduction="none")
def warm_start_components(self):
components = ["seq2slate_net"]
return components
def train(self, training_batch: rlt.PreprocessedRankingInput):
assert type(training_batch) is rlt.PreprocessedRankingInput
per_symbol_log_probs = self.seq2slate_net(
training_batch, mode=Seq2SlateMode.PER_SYMBOL_LOG_PROB_DIST_MODE
).log_probs
per_seq_log_probs = per_symbol_to_per_seq_log_probs(
per_symbol_log_probs, training_batch.tgt_out_idx
)
assert per_symbol_log_probs.requires_grad and per_seq_log_probs.requires_grad
# pyre-fixme[16]: `Optional` has no attribute `shape`.
assert per_seq_log_probs.shape == training_batch.tgt_out_probs.shape
if not self.parameters.on_policy:
importance_sampling = (
torch.exp(per_seq_log_probs) / training_batch.tgt_out_probs
)
importance_sampling = ips_clamp(
importance_sampling, self.parameters.ips_clamp
)
else:
importance_sampling = (
torch.exp(per_seq_log_probs) / torch.exp(per_seq_log_probs).detach()
)
assert importance_sampling.requires_grad
# pyre-fixme[6]: Expected `Tensor` for 1st param but got
# `Optional[torch.Tensor]`.
labels = self._transform_label(training_batch.tgt_out_idx)
assert not labels.requires_grad
batch_size, max_tgt_seq_len = training_batch.tgt_out_idx.shape
# batch_loss shape: batch_size x max_tgt_seq_len
batch_loss = (
torch.sum(self.kl_div_loss(per_symbol_log_probs, labels), dim=2)
* training_batch.position_reward
)
# weighted_batch_loss shape: batch_size, 1
weighted_batch_loss = torch.sum(
1.0
/ torch.log(
torch.arange(1, 1 + max_tgt_seq_len, device=batch_loss.device).float()
+ 1.0
)
* batch_loss,
dim=1,
keepdim=True,
)
loss = 1.0 / batch_size * torch.sum(importance_sampling * weighted_batch_loss)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
loss = loss.detach().cpu().numpy()
per_symbol_log_probs = per_symbol_log_probs.detach()
self.minibatch += 1
if self.minibatch % self.print_interval == 0:
logger.info(f"{self.minibatch} batch: loss={loss}")
return {"per_symbol_log_probs": per_symbol_log_probs, "sl": loss}
def _transform_label(self, tgt_out_idx: torch.Tensor):
label_size = self.seq2slate_net.max_src_seq_len + 2
label = F.one_hot(tgt_out_idx, label_size)
return label.float()
| StarcoderdataPython |
66530 | <gh_stars>0
from dataactcore.models.stagingModels import ObjectClassProgramActivity
from dataactcore.models.domainModels import SF133
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'b14_object_class_program_activity'
_TAS = 'b14_object_class_program_activity_tas'
def test_column_headers(database):
expected_subset = {'row_number', 'ussgl480100_undelivered_or_cpe_sum', 'ussgl480100_undelivered_or_fyb_sum',
'ussgl480200_undelivered_or_cpe_sum', 'ussgl480200_undelivered_or_fyb_sum',
'ussgl488100_upward_adjustm_cpe_sum', 'ussgl488200_upward_adjustm_cpe_sum',
'ussgl490100_delivered_orde_cpe_sum', 'ussgl490100_delivered_orde_fyb_sum',
'ussgl490200_delivered_orde_cpe_sum', 'ussgl490800_authority_outl_cpe_sum',
'ussgl490800_authority_outl_fyb_sum', 'ussgl498100_upward_adjustm_cpe_sum',
'ussgl498200_upward_adjustm_cpe_sum', 'expected_value_GTAS SF133 Line 2004',
'difference', 'uniqueid_TAS', 'uniqueid_DisasterEmergencyFundCode'}
actual = set(query_columns(_FILE, database))
assert (actual & expected_subset) == expected_subset
def test_success(database):
""" Tests that SF 133 amount sum for line 2004 matches the calculation from Appropriation based on the fields below
for the specified fiscal year and period and TAS/DEFC combination.
"""
tas = "".join([_TAS, "_success"])
# This uses the default submission created in utils for 10/2015 which is period 1 of FY 2016
sf = SF133(line=2004, tas=tas, period=1, fiscal_year=2016, amount=-15, agency_identifier="sys",
main_account_code="000", sub_account_code="000", disaster_emergency_fund_code='C')
op = ObjectClassProgramActivity(job_id=1, row_number=1, tas=tas, by_direct_reimbursable_fun='d',
ussgl480100_undelivered_or_cpe=1, ussgl480100_undelivered_or_fyb=1,
ussgl480200_undelivered_or_cpe=1, ussgl480200_undelivered_or_fyb=1,
ussgl488100_upward_adjustm_cpe=1, ussgl488200_upward_adjustm_cpe=1,
ussgl490100_delivered_orde_cpe=1, ussgl490100_delivered_orde_fyb=1,
ussgl490200_delivered_orde_cpe=1, ussgl490800_authority_outl_cpe=1,
ussgl490800_authority_outl_fyb=1, ussgl498100_upward_adjustm_cpe=1,
ussgl498200_upward_adjustm_cpe=1, disaster_emergency_fund_code='C')
op2 = ObjectClassProgramActivity(job_id=1, row_number=2, tas=tas, by_direct_reimbursable_fun='d',
ussgl480100_undelivered_or_cpe=2, ussgl480100_undelivered_or_fyb=2,
ussgl480200_undelivered_or_cpe=2, ussgl480200_undelivered_or_fyb=2,
ussgl488100_upward_adjustm_cpe=2, ussgl488200_upward_adjustm_cpe=2,
ussgl490100_delivered_orde_cpe=2, ussgl490100_delivered_orde_fyb=2,
ussgl490200_delivered_orde_cpe=2, ussgl490800_authority_outl_cpe=2,
ussgl490800_authority_outl_fyb=2, ussgl498100_upward_adjustm_cpe=2,
ussgl498200_upward_adjustm_cpe=2, disaster_emergency_fund_code='c')
assert number_of_errors(_FILE, database, models=[sf, op, op2]) == 0
def test_failure(database):
""" Tests that SF 133 amount sum for line 2004 does not match the calculation from Appropriation based on
the fields below for the specified fiscal year and period and TAS/DEFC combination.
"""
tas = "".join([_TAS, "_failure"])
sf = SF133(line=2004, tas=tas, period=1, fiscal_year=2016, amount=5, agency_identifier="sys",
main_account_code="000", sub_account_code="000", disaster_emergency_fund_code='D')
op = ObjectClassProgramActivity(job_id=1, row_number=1, tas=tas, by_direct_reimbursable_fun='d',
ussgl480100_undelivered_or_cpe=1, ussgl480100_undelivered_or_fyb=1,
ussgl480200_undelivered_or_cpe=1, ussgl480200_undelivered_or_fyb=1,
ussgl488100_upward_adjustm_cpe=1, ussgl488200_upward_adjustm_cpe=1,
ussgl490100_delivered_orde_cpe=1, ussgl490100_delivered_orde_fyb=1,
ussgl490200_delivered_orde_cpe=1, ussgl490800_authority_outl_cpe=1,
ussgl490800_authority_outl_fyb=1, ussgl498100_upward_adjustm_cpe=1,
ussgl498200_upward_adjustm_cpe=1, disaster_emergency_fund_code='D')
op2 = ObjectClassProgramActivity(job_id=1, row_number=2, tas=tas, by_direct_reimbursable_fun='d',
ussgl480100_undelivered_or_cpe=2, ussgl480100_undelivered_or_fyb=2,
ussgl480200_undelivered_or_cpe=2, ussgl480200_undelivered_or_fyb=2,
ussgl488100_upward_adjustm_cpe=2, ussgl488200_upward_adjustm_cpe=2,
ussgl490100_delivered_orde_cpe=2, ussgl490100_delivered_orde_fyb=2,
ussgl490200_delivered_orde_cpe=2, ussgl490800_authority_outl_cpe=2,
ussgl490800_authority_outl_fyb=2, ussgl498100_upward_adjustm_cpe=2,
ussgl498200_upward_adjustm_cpe=2, disaster_emergency_fund_code='D')
assert number_of_errors(_FILE, database, models=[sf, op, op2]) == 1
| StarcoderdataPython |
3246191 | <reponame>davidbrownell/Common_Environment
# ----------------------------------------------------------------------
# |
# | SetupEnvironment.py
# |
# | <NAME> <<EMAIL>>
# | 2018-02-11 12:59:02
# |
# ----------------------------------------------------------------------
# |
# | Copyright <NAME> 2018.
# | Distributed under the Boost Software License, Version 1.0.
# | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
# |
# ----------------------------------------------------------------------
import configparser
import json
import os
import shutil
import sys
import textwrap
from collections import OrderedDict
import six
import SourceRepositoryTools
from SourceRepositoryTools.Impl import CommonEnvironmentImports
from SourceRepositoryTools.Impl.Configuration import Configuration, Dependency
from SourceRepositoryTools.Impl import Constants
from SourceRepositoryTools.Impl.EnvironmentBootstrap import EnvironmentBootstrap
from SourceRepositoryTools.Impl import Utilities
# ----------------------------------------------------------------------
_script_fullpath = os.path.abspath(__file__) if "python" in sys.executable.lower() else sys.executable
_script_dir, _script_name = os.path.split(_script_fullpath)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
CODE_DIRECTORY_NAMES = [ "code",
"coding",
"source",
"src",
"development",
"develop",
"dev",
]
ENUMERATE_EXCLUDE_DIRS = [ "generated",
".hg",
".git",
]
# ----------------------------------------------------------------------
@CommonEnvironmentImports.CommandLine.EntryPoint( output_filename_or_stdout=CommonEnvironmentImports.CommandLine.EntryPoint.ArgumentInfo("Filename for generated content or standard output if the value is 'stdout'"),
repository_root=CommonEnvironmentImports.CommandLine.EntryPoint.ArgumentInfo("Root of the repository"),
debug=CommonEnvironmentImports.CommandLine.EntryPoint.ArgumentInfo("Display debug information"),
configuration=CommonEnvironmentImports.CommandLine.EntryPoint.ArgumentInfo("Configurations to setup; all will be setup if explicit values are not provided"),
)
@CommonEnvironmentImports.CommandLine.FunctionConstraints( output_filename_or_stdout=CommonEnvironmentImports.CommandLine.StringTypeInfo(),
repository_root=CommonEnvironmentImports.CommandLine.DirectoryTypeInfo(),
configuration=CommonEnvironmentImports.CommandLine.StringTypeInfo(arity='*'),
)
def EntryPoint( output_filename_or_stdout,
repository_root,
debug=False,
configuration=None,
):
configurations = configuration or []; del configuration
environment = CommonEnvironmentImports.Shell.GetEnvironment()
# Get the setup customization module
potential_customization_filename = os.path.join(repository_root, Constants.SETUP_ENVIRONMENT_CUSTOMIZATION_FILENAME)
if os.path.isfile(potential_customization_filename):
customization_name = os.path.splitext(Constants.SETUP_ENVIRONMENT_CUSTOMIZATION_FILENAME)[0]
sys.path.insert(0, repository_root)
customization_mod = __import__(customization_name)
del sys.path[0]
else:
customization_mod = None
# ----------------------------------------------------------------------
def Execute():
commands = []
for func in [ _SetupBootstrap,
_SetupCustom,
_SetupShortcuts,
_SetupGeneratedPermissions,
_SetupScmHooks,
]:
these_commands = func( environment,
repository_root,
customization_mod,
debug,
configurations,
)
if these_commands:
commands += these_commands
return commands
# ----------------------------------------------------------------------
result, commands = Utilities.GenerateCommands(Execute, environment, debug)
if output_filename_or_stdout == "stdout":
output_stream = sys.stdout
CloseStream = lambda: None
else:
output_stream = open(output_filename_or_stdout, 'w')
CloseStream = output_stream.close
output_stream.write(environment.GenerateCommands(commands))
CloseStream()
return result
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def _SetupBootstrap( environment,
repository_root,
customization_mod,
debug,
configurations_to_setup,
search_depth=5,
):
# Look for all dependencies by intelligently enumerating through the file system
search_depth += repository_root.count(os.path.sep)
if environment.CategoryName == "Windows":
# Remove the slash associated with the drive name
assert search_depth
search_depth -= 1
fundamental_repo = SourceRepositoryTools.GetFundamentalRepository()
repository_root_dirname = os.path.dirname(repository_root)
len_repository_root_dirname = len(repository_root_dirname)
# ----------------------------------------------------------------------
class LookupObject(object):
def __init__(self, name):
self.Name = name
self.repository_root = None
self.dependent_configurations = []
# ----------------------------------------------------------------------
def EnumerateDirectories():
search_items = []
searched_items = set()
# ----------------------------------------------------------------------
def FirstNonmatchingChar(s):
for index, c in enumerate(s):
if ( index == len_repository_root_dirname or
c != repository_root_dirname[index]
):
break
return index
# ----------------------------------------------------------------------
def PushSearchItem(item):
item = os.path.realpath(os.path.normpath(item))
parts = item.split(os.path.sep)
if len(parts) > search_depth:
return
parts_lower = set([ part.lower() for part in parts ])
priority = 1
for bump_name in CODE_DIRECTORY_NAMES:
if bump_name in parts_lower:
priority = 0
break
# Every item excpet the last is used for sorting
search_items.append(( -FirstNonmatchingChar(item), # Favor parents over other locations
priority, # Favor higer priorty items
len(parts), # Favor dirs closer to the root
item.lower(), # Case insensitive sort
item,
))
search_items.sort()
# ----------------------------------------------------------------------
def PopSearchItem():
return search_items.pop(0)[-1]
# ----------------------------------------------------------------------
def Impl( skip_root,
preprocess_item_func=None, # def Func(item) -> item
):
preprocess_item_func = preprocess_item_func or (lambda item: item)
while search_items:
search_item = PopSearchItem()
# Don't process if the dir has already been processed
if search_item in searched_items:
continue
searched_items.add(search_item)
# Don't process if the dir doesn't exist anymore (these searches can take
# ahwile and dirs come and go)
if not os.path.isdir(search_item):
continue
# Don't process if the dir has been explicitly ignored
if os.path.exists(os.path.join(search_item, Constants.IGNORE_DIRECTORY_AS_BOOTSTRAP_DEPENDENCY_SENTINEL_FILENAME)):
continue
yield search_item
try:
# Add the parent to the queue
potential_parent = os.path.dirname(search_item)
if potential_parent != search_item:
if not skip_root or os.path.dirname(potential_parent) != potential_parent:
PushSearchItem(preprocess_item_func(potential_parent))
# Add the children to the queue
for item in os.listdir(search_item):
fullpath = os.path.join(search_item, item)
if not os.path.isdir(fullpath):
continue
if item.lower() in ENUMERATE_EXCLUDE_DIRS:
continue
PushSearchItem(preprocess_item_func(fullpath))
except PermissionError:
# Most likely a permissions error raised when we attempted to
# access the dir. Unfortunately, there isn't a consistent exception
# type to catch across different platforms.
pass
# ----------------------------------------------------------------------
PushSearchItem(repository_root)
if environment.CategoryName == "Windows":
# ----------------------------------------------------------------------
def ItemPreprocessor(item):
drive, remainder = os.path.splitdrive(item)
if drive[-1] == ':':
drive = drive[:-1]
return "{}:{}".format(drive.upper(), remainder)
# ----------------------------------------------------------------------
for item in Impl(True, ItemPreprocessor):
yield item
# If here, look at other drive locations
import win32api
import win32file
for drive in [ drive for drive in win32api.GetLogicalDriveStrings().split('\000') if drive and win32file.GetDriveType(drive) == win32file.DRIVE_FIXED ]:
PushSearchItem(drive)
for item in Impl(False, ItemPreprocessor):
yield item
else:
for item in Impl(False):
yield item
# ----------------------------------------------------------------------
# Get the configurations from the script
configurations = None
is_tool_repository = False
if customization_mod:
dependencies_func = getattr(customization_mod, Constants.SETUP_ENVIRONMENT_DEPENDENCIES_METHOD_NAME, None)
if dependencies_func is not None:
# Get custom configurations
configurations = dependencies_func()
if configurations and not isinstance(configurations, dict):
configurations = { None : configurations }
# Is this a tool repo? Tool repos are specified via
# the ToolRepository wrapt decorator.
if ( hasattr(dependencies_func, "_self_wrapper") and
dependencies_func._self_wrapper.__name__ == "ToolRepository"
):
is_tool_repository = True
if not configurations:
configurations = { None : Configuration(),
}
has_configurations = len(configurations) > 1 or next(six.iterkeys(configurations)) is not None
# A tool repository cannot have configurations, dependencies, or version specs
if ( is_tool_repository and
( has_configurations or
next(six.itervalues(configurations)).Dependencies or
next(six.itervalues(configurations)).VersionSpecs.Tools or
next(six.itervalues(configurations)).VersionSpecs.Libraries
)
):
raise Exception("A tool repository cannot not have any configurations, dependencies, or version specs.")
# Calculate all of the repositories that we need to find
if configurations_to_setup:
for config_name in list(six.iterkeys(configurations)):
if config_name not in configurations_to_setup:
del configurations[config_name]
# Create a repo lookup list
fundamental_name, fundamental_guid = Utilities.GetRepositoryUniqueId(fundamental_repo)
id_lookup = OrderedDict([ ( fundamental_guid, LookupObject(fundamental_name) ),
])
for config_name, config_info in six.iteritems(configurations):
for dependency_info in config_info.Dependencies:
if dependency_info.Id not in id_lookup:
id_lookup[dependency_info.Id] = LookupObject(dependency_info.FriendlyName)
id_lookup[dependency_info.Id].dependent_configurations.append(config_name)
# Display status
col_sizes = [ 40, 32, 100, ]
display_template = "{{name:<{0}}} {{guid:<{1}}} {{data:<{2}}}".format(*col_sizes)
max_config_name_length = int(col_sizes[0] * 0.75)
config_display_info = []
for config_name, config_info in six.iteritems(configurations):
if config_name is None:
continue
max_config_name_length = max(max_config_name_length, len(config_name))
config_display_info.append(( config_name, config_info.Description ))
sys.stdout.write(textwrap.dedent(
"""\
Your system will be scanned for these repositories
{header}
{sep}
{values}
{configurations}
""").format( header=display_template.format( name="Repository Name",
guid="Id",
data="Dependent Configurations",
),
sep=display_template.format(**{ k : v for k, v in six.moves.zip( [ "name", "guid", "data", ],
[ '-' * col_size for col_size in col_sizes ],
) }),
values=CommonEnvironmentImports.StreamDecorator.LeftJustify( '\n'.join([ display_template.format( name=v.Name,
guid=k,
data=', '.join(sorted([ dc for dc in v.dependent_configurations if dc], key=str.lower)),
)
for k, v in six.iteritems(id_lookup)
]),
4,
),
configurations=CommonEnvironmentImports.StreamDecorator.LeftJustify( '' if not has_configurations else textwrap.dedent(
"""\
Based on these configurations:
{}
{}
""").format( CommonEnvironmentImports.StreamDecorator.LeftJustify( '\n'.join([ "- {0:<{1}}{2}".format( config_name,
max_config_name_length,
" : {}".format(description) if description else '',
)
for config_name, description in config_display_info
]),
4,
),
CommonEnvironmentImports.StreamDecorator.LeftJustify( '' if configurations_to_setup else textwrap.dedent(
"""\
To setup specific configurations, specify this argument one or more times on the command line:
/configuration=<configuration name>
"""),
4,
),
),
4,
),
))
# Find them all
remaining_repos = len(id_lookup)
for directory in EnumerateDirectories():
if debug:
sys.stdout.write("Searching in '{}'\n".format(directory))
result = Utilities.GetRepositoryUniqueId( directory,
find_by_scm=False,
throw_on_error=False,
)
if result is None:
continue
repo_name, repo_guid = result
if repo_guid in id_lookup:
# Note that we may already have a repository associated with this repo. This can
# happen when the repo was found near the originating repository and the search has
# continued into other directories.
if id_lookup[repo_guid].repository_root is None:
id_lookup[repo_guid].repository_root = directory
remaining_repos -= 1
if not remaining_repos:
break
if remaining_repos:
unknown_repos = []
for repo_guid, lookup_info in six.iteritems(id_lookup):
if lookup_info.repository_root is None:
unknown_repos.append(( lookup_info.name, repo_guid ))
assert unknown_repos
raise Exception(textwrap.dedent(
"""\
Unable to find the {repository}:
{repos}
""").format( repository="repository" if len(unknown_repos) == 1 else "repositories",
repos='\n'.join([ " - {} ({})".format(repo_name, repo_guid) for repo_name, repo_guid in unknown_repos ]),
))
sys.stdout.write(textwrap.dedent(
"""\
{num} {repository} {was} found at {this} {location}:
{header}
{sep}
{values}
""").format( num=len(id_lookup),
repository="repository" if len(id_lookup) == 1 else "repositories",
was="was" if len(id_lookup) == 1 else "were",
this="this" if len(id_lookup) == 1 else "these",
location="location" if len(id_lookup) == 1 else "locations",
header=display_template.format( name="Repository Name",
guid="Id",
data="Location",
),
sep=display_template.format(**{ k : v for k, v in six.moves.zip( [ "name", "guid", "data", ],
[ '-' * col_size for col_size in col_sizes ],
) }),
values=CommonEnvironmentImports.StreamDecorator.LeftJustify( '\n'.join([ display_template.format( name=lookup_info.Name,
guid=repo_guid,
data=lookup_info.repository_root,
)
for repo_guid, lookup_info in six.iteritems(id_lookup)
]),
4,
),
))
# Update the provided configuration info with information that we have discovered
for config_name, config_info in six.iteritems(configurations):
added_fundamental = False
for dependency in config_info.Dependencies:
dependency.RepositoryRoot = id_lookup[dependency.Id].repository_root
if dependency.Id == fundamental_guid:
added_fundamental = True
# We need to add the fundamental repo as a dependency unless one
# of the following conditions are met.
if ( not added_fundamental and
repository_root != id_lookup[fundamental_guid].repository_root and
not is_tool_repository
):
config_info.Dependencies.append(Dependency(fundamental_guid, fundamental_name))
config_info.Dependencies[-1].RepositoryRoot = fundamental_repo
config_info.Fingerprint = Utilities.CalculateFingerprint( [ repository_root, ] + [ dependency.RepositoryRoot for dependency in config_info.Dependencies ],
repository_root,
)
# Get the latest python binary, which may be different than the binary used to launch
# this process.
python_binary = Utilities.GetVersionedDirectory( [], # Always get the latest
fundamental_repo,
Constants.TOOLS_SUBDIR,
"Python",
)
potential_binary = os.path.join(python_binary, "bin")
if os.path.isdir(potential_binary):
python_binary = potential_binary
python_binary = os.path.join(python_binary, "python")
potential_binary = "{}{}".format(python_binary, environment.ExecutableExtension)
if os.path.isfile(potential_binary):
python_binary = potential_binary
assert os.path.isfile(python_binary), python_binary
# Write the bootstrap files
EnvironmentBootstrap( python_binary,
fundamental_repo,
is_tool_repository,
has_configurations,
configurations,
).Save( repository_root,
environment=environment,
)
# ----------------------------------------------------------------------
def _SetupCustom( environment,
repository_root,
customization_mod,
debug,
configurations,
):
if customization_mod is None or not hasattr(customization_mod, Constants.SETUP_ENVIRONMENT_ACTIONS_METHOD_NAME):
return
func = CommonEnvironmentImports.Interface.CreateCulledCallable(getattr(customization_mod, Constants.SETUP_ENVIRONMENT_ACTIONS_METHOD_NAME))
return func({ "debug" : debug,
"configurations" : configurations,
})
# ----------------------------------------------------------------------
def _SetupShortcuts( environment,
repository_root,
customization_mod,
debug,
configurations,
):
activate_script = environment.CreateScriptName(Constants.ACTIVATE_ENVIRONMENT_NAME)
shortcut_dest = os.path.join(SourceRepositoryTools.GetFundamentalRepository(), "SourceRepositoryTools", "Impl", activate_script)
assert os.path.isfile(shortcut_dest), shortcut_dest
return [ environment.SymbolicLink(os.path.join(repository_root, activate_script), shortcut_dest),
]
# ----------------------------------------------------------------------
def _SetupGeneratedPermissions( environment,
repository_root,
customization_mod,
debug,
configurations,
):
generated_dir = os.path.join(repository_root, Constants.GENERATED_DIRECTORY_NAME, environment.CategoryName)
assert os.path.isdir(generated_dir), generated_dir
os.chmod(generated_dir, 0x777)
# ----------------------------------------------------------------------
def _SetupScmHooks( environment,
repository_root,
customization_mod,
debug,
configurations,
):
# Mercurial
if os.path.isdir(os.path.join(repository_root, ".hg")):
hooks_filename = os.path.normpath(os.path.join(_script_dir, "Hooks", "Mercurial.py"))
assert os.path.isfile(hooks_filename), hooks_filename
config = configparser.ConfigParser( allow_no_value=True,
)
potential_hg_filename = os.path.join(repository_root, ".hg", "hgrc")
if os.path.isfile(potential_hg_filename):
with open(potential_hg_filename) as f:
config.read_file(f)
if not config.has_section("hooks"):
config.add_section("hooks")
config.set("hooks", "pretxncommit.CommonEnvironment", "python:{}:PreTxnCommit".format(hooks_filename))
config.set("hooks", "preoutgoing.CommonEnvironment", "python:{}:PreOutgoing".format(hooks_filename))
config.set("hooks", "pretxnchangegroup.CommonEnvironment", "python:{}:PreTxnChangeGroup".format(hooks_filename))
backup_hg_filename = "{}.bak".format(potential_hg_filename)
if os.path.isfile(potential_hg_filename) and not os.path.isfile(backup_hg_filename):
shutil.copyfile(potential_hg_filename, backup_hg_filename)
with open(potential_hg_filename, 'w') as f:
config.write(f)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
if __name__ == "__main__":
try: sys.exit(CommonEnvironmentImports.CommandLine.Main())
except KeyboardInterrupt: pass | StarcoderdataPython |
3362075 | <reponame>Sinap/mazes
# -*- coding: utf-8 -*-
import random
class BinaryTree(object):
"""
docstring for BinaryTree
"""
@staticmethod
def on(grid):
for cell in grid.each_cell():
neighbors = []
if cell.north:
neighbors.append(cell.north)
if cell.east:
neighbors.append(cell.east)
if neighbors:
neighbor = random.choice(neighbors)
cell.link(neighbor)
return grid
| StarcoderdataPython |
3303118 | <gh_stars>10-100
"""
Harvester for the ASU Digital Repository for the SHARE project
More information at https://github.com/CenterForOpenScience/SHARE/blob/master/providers/edu.asu.md
Example API call: http://repository.asu.edu/oai-pmh?verb=ListRecords&metadataPrefix=oai_dc&from=2014-10-05T00:00:00Z
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class ASUHarvester(OAIHarvester):
short_name = 'asu'
long_name = 'Arizona State University Digital Repository'
url = 'http://www.asu.edu/'
base_url = 'http://repository.asu.edu/oai-pmh'
approved_sets = ['research']
property_list = [
'type', 'format', 'date', 'description', 'relation',
'setSpec', 'rights', 'identifier'
]
| StarcoderdataPython |
1679341 | <filename>alembic/versions/07d1fdb1f9e0_foreign_key_to_post_table.py<gh_stars>0
"""foreign-key to post table
Revision ID: 07d1fdb1f9e0
Revises: <PASSWORD>
Create Date: 2022-01-08 23:55:39.058731
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '07d1fdb1f9e0'
down_revision = 'd<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('posts', sa.Column('owner_id', sa.Integer(), nullable=False))
op.create_foreign_key(
'posts_users_fk', source_table='posts', referent_table='users', local_cols=['owner_id'], remote_cols=['id'], ondelete="CASCADE")
pass
def downgrade():
op.drop_constraint('posts_users_fk', 'posts')
op.drop_column('posts', 'owner_id')
pass
| StarcoderdataPython |
172629 | import requests, sys
from PIL import Image
import time
def calc_perc(u):
tbpc = 0
img = Image.open(u)
pic = img.load()
total = img.height * img.width
for h in range(img.height):
for w in range(img.width):
if isinstance(pic[w,h], int):
if pic[w,h] == 0:
tbpc += 1
else:
try:
if isinstance(pic[w,h][2], int):
if pic[w,h][0] == 0 and pic[w,h][1] == 0 and pic[w,h][2] == 0:
tbpc += 1
except IndexError:
if pic[w,h][0] == 0 and pic[w,h][1] == 255:
tbpc += 1
percentage = tbpc / (total / 100)
return percentage, tbpc, total
def main():
image_file = sys.argv[1]
print("Calculating...")
perc = calc_perc(image_file)
print(f"\"{image_file}\" has a (true) black pixel percentage of {round(perc[0],2)}% with {perc[1]:,} black pixels of {perc[2]:,}.")
input("Press any key to close!")
if __name__ == "__main__":
main()
| StarcoderdataPython |
1765862 | import socket
import os
realpit = []
shadowpit = []
depth = []
def changeplayer():
if player == 1:
player = 2
elif:
player = 1
def choose(x, player, pit = []):
if pit[x] or x==13 or x=6:
pass
else:
hold = pit[x]
now = x
pit[x] = 0
while 1:
now += 1
now = now%14
if player == 1 and now==13:
pass
elif player == 2 and now == 6:
pass
elif pit[now]==0 or now==player*7-1:
if hold==1:
if now == player*7-1:
pit[now] = pit[now]+1
else:
if player==1 and now<6:
pit[player*7-1]+=pit[((player*7-1)+((player*7-1)-now))%14]
pit[((player*7-1)+((player*7-1)-now))%14]=0
elif player==2 and now>6:
pit[player*7-1]+=pit[((player*7-1)+((player*7-1)-now))%14]
pit[((player*7-1)+((player*7-1)-now))%14]=0
pit[now]=pit[now]+1;
changeplayer();
hold -= 1
break
elif hold==1 and pit[now]!=0:
hold+=pit[now]
pit[now]=0
else:
pit[now]+=1
hold--
print " "
for i in range(5,0):
print pit[i] + " "
print pit[6] + " " + pit[13]
print " "
for j in range(7,12):
print pit[j] + " "
print "hold = " + hold
print "Player"+player+"'s' turn"
sleep(1)
os.system('cls')
def test (x, player, pit = []):
if pit[x] or x==13 or x=6:
pass
else:
hold = pit[x]
now = x
pit[x] = 0
while 1:
now += 1
now = now%14
if player == 1 and now==13:
pass
elif player == 2 and now == 6:
pass
elif pit[now]==0 or now==player*7-1:
if hold==1:
if now == player*7-1:
pit[now] = pit[now]+1
else:
if player==1 and now<6:
pit[player*7-1]+=pit[((player*7-1)+((player*7-1)-now))%14]
pit[((player*7-1)+((player*7-1)-now))%14]=0
elif player==2 and now>6:
pit[player*7-1]+=pit[((player*7-1)+((player*7-1)-now))%14]
pit[((player*7-1)+((player*7-1)-now))%14]=0
pit[now]=pit[now]+1;
changeplayer();
hold -= 1
break
elif hold==1 and pit[now]!=0:
hold+=pit[now];
pit[now]=0;
else:
pit[now]+=1;
hold--
if __name__ == "__main__":
player = 1
for i in range(0,13):
if i==6 || i==13:
realpit[i] = 0
else:
realpit[i] =3
print " "
for j in range(5,0):
print realpit[j] + " "
print realpit[6] + " " + realpit[13]
print " "
for k in range(7,12):
print realpit[k] + " "
while 1:
play1 = 0
play2 = 0
print "Player"+player
if player == 1:
print "Pilih Player 1 : "
pilih = raw_input()
while pilih > 5:
print "Pilih Player 1 : "
pilih = raw_input()
else:
print "Pilih Player 1 : "
pilih = raw_input()
while pilih > 5:
print "Pilih Player 1 : "
pilih = raw_input()
sleep(1)
os.system(cls)
if realpit[pilih] == 0:
changeplayer()
else:
choose(pilih, player, realpit)
print " "
for y in range(5,0):
print realpit[y] + " "
if realpit[y] == 0:
play1+=1
print realpit[6] + " " + realpit[13]
print " "
for z in range(7,13):
print realpit[z] + " "
if realpit[z] == 0:
play2+=1
if play1 == 6 and play2 == 6:
if realpit[6] < realpit[13]:
print "Player 2 MENANG"
elif realpit[6] < realpit[13]:
print "Player 1 MENANG"
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.