content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def xmatch_arguments():
""" Obtain information about the xmatch service
"""
return jsonify({'args': args_xmatch})
| 7,400 |
def rosenbrock_func(x):
"""Rosenbrock objective function.
Also known as the Rosenbrock's valley or Rosenbrock's banana
function. Has a global minimum of :code:`np.ones(dimensions)` where
:code:`dimensions` is :code:`x.shape[1]`. The search domain is
:code:`[-inf, inf]`.
Parameters
----------
x : numpy.ndarray
set of inputs of shape :code:`(n_particles, dimensions)`
Returns
-------
numpy.ndarray
computed cost of size :code:`(n_particles, )`
"""
r = np.sum(100*(x.T[1:] - x.T[:-1]**2.0)**2 + (1-x.T[:-1])**2.0, axis=0)
return r
| 7,401 |
def isHdf5Dataset(obj):
"""Is `obj` an HDF5 Dataset?"""
return isinstance(obj, h5py.Dataset)
| 7,402 |
async def on_message(message):
"""
メッセージ書き込みイベント
:param message: 書き込まれたメッセージ
:type message: Message
:return: None
:rtype: None
"""
try:
if message.channel.name.upper() == consts.CMD_CHANNEL_NAME and not message.author.bot:
await cmd_manager.execute(message)
except Exception as e:
print("【エラー】on_message. 処理継続.")
with open(consts.LOG_FILE, 'a') as f:
traceback.print_exc(file=f)
client.send_message(message.channel, "【エラー】複数回発生したら再起動か管理者に報告よろ.")
| 7,403 |
def writing_height(sample_wrapper, in_air):
"""
Returns writing height.
:param sample_wrapper: sample wrapper object
:type sample_wrapper: HandwritingSampleWrapper
:param in_air: in-air flag
:type in_air: bool
:return: writing height
:rtype: float
"""
# Get the on-surface/in-air sample data
sample = sample_wrapper.on_surface_data \
if not in_air \
else sample_wrapper.in_air_data
# Check the presence of sample data
if not sample:
return numpy.nan
# Return the writing height
return float(numpy.max(sample.y) - numpy.min(sample.y))
| 7,404 |
def simplify_index_permutations(expr, permutation_operators):
"""
Performs simplification by introducing PermutationOperators where appropriate.
Schematically:
[abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij]
permutation_operators is a list of PermutationOperators to consider.
If permutation_operators=[P(ab),P(ij)] we will try to introduce the
permutation operators P(ij) and P(ab) in the expression. If there are other
possible simplifications, we ignore them.
>>> from sympy import symbols, Function
>>> from sympy.physics.secondquant import simplify_index_permutations
>>> from sympy.physics.secondquant import PermutationOperator
>>> p,q,r,s = symbols('p,q,r,s')
>>> f = Function('f')
>>> g = Function('g')
>>> expr = f(p)*g(q) - f(q)*g(p); expr
f(p)*g(q) - f(q)*g(p)
>>> simplify_index_permutations(expr,[PermutationOperator(p,q)])
f(p)*g(q)*PermutationOperator(p, q)
>>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)]
>>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r)
>>> simplify_index_permutations(expr,PermutList)
f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s)
"""
def _get_indices(expr, ind):
"""
Collects indices recursively in predictable order.
"""
result = []
for arg in expr.args:
if arg in ind:
result.append(arg)
else:
if arg.args:
result.extend(_get_indices(arg,ind))
return result
def _choose_one_to_keep(a,b,ind):
# we keep the one where indices in ind are in order ind[0] < ind[1]
if _get_indices(a,ind) < _get_indices(b,ind):
return a
else:
return b
expr = expr.expand()
if isinstance(expr,Add):
terms = set(expr.args)
for P in permutation_operators:
new_terms = set([])
on_hold = set([])
while terms:
term = terms.pop()
permuted = P.get_permuted(term)
if permuted in terms | on_hold:
try:
terms.remove(permuted)
except KeyError:
on_hold.remove(permuted)
keep = _choose_one_to_keep(term, permuted, P.args)
new_terms.add(P*keep)
else:
# Some terms must get a second chance because the permuted
# term may already have canonical dummy ordering. Then
# substitute_dummies() does nothing. However, the other
# term, if it exists, will be able to match with us.
permuted1 = permuted
permuted = substitute_dummies(permuted)
if permuted1 == permuted:
on_hold.add(term)
elif permuted in terms | on_hold:
try:
terms.remove(permuted)
except KeyError:
on_hold.remove(permuted)
keep = _choose_one_to_keep(term, permuted, P.args)
new_terms.add(P*keep)
else:
new_terms.add(term)
terms = new_terms | on_hold
return Add(*terms)
return expr
| 7,405 |
def get_classification_outcomes(
confusion_matrix: pd.DataFrame,
classes: Set[Any],
class_name: str,
) -> Tuple[int, int, int, int]:
"""
Given a confusion matrix, this function counts the cases of:
- **True Positives** : classifications that accurately labeled a class
- **True Negatives** : classifications that accurately labeled an example as
not belonging to a class.
- **False Positives** : classifications that attributed the wrong label to an
example.
- **False Negatives** : classifications that falsely claimed that an example
does not belong to a class.
Args:
confusion_matrix: The result of calling [generate_confusion_matrix]
[toolbox.algorithms.learning.evaluation.generate_confusion_matrix]
classes: The set of all class labels
class_name: The name (label) of the class being evaluated.
Returns:
- `tp`: Count of True Positives
- `tn`: Count of True Negatives
- `fp`: Count of False Positives
- `fn`: Count of False Negatives
"""
excl_idx = classes.difference(set((class_name,)))
tp = confusion_matrix.loc[class_name, class_name]
tn = confusion_matrix.loc[excl_idx, excl_idx].sum().sum()
fp = confusion_matrix.loc[class_name, excl_idx].sum()
fn = confusion_matrix.loc[excl_idx, class_name].sum()
return (tp, tn, fp, fn)
| 7,406 |
def update_dbt_id(
table_name: str,
id_where: sqlalchemy.Integer,
columns: typing.Dict[str, str],
) -> None:
"""Update a database row based on its id column.
Args:
table_name (str): sqlalchemy.Table name.
id_where (sqlalchemy.Integer): Content of column id.
columns (Columns): Pairs of column name and value.
"""
dbt = sqlalchemy.Table(table_name, cfg.glob.db_orm_metadata, autoload_with=cfg.glob.db_orm_engine)
with cfg.glob.db_orm_engine.connect().execution_options(autocommit=True) as conn:
conn.execute(sqlalchemy.update(dbt).where(dbt.c.id == id_where).values(columns))
conn.close()
| 7,407 |
def save_ply(filename, points, colors=None, normals=None, binary=True):
"""
save 3D/2D points to ply file
Args:
points (numpy array): (N,2or3)
colors (numpy uint8 array): (N, 3or4)
"""
assert(points.ndim == 2)
if points.shape[-1] == 2:
points = np.concatenate([points, np.zeros_like(points)[:, :1]], axis=-1)
vertex = np.core.records.fromarrays(points.transpose(
1, 0), names='x, y, z', formats='f4, f4, f4')
num_vertex = len(vertex)
desc = vertex.dtype.descr
if normals is not None:
assert(normals.ndim == 2)
if normals.shape[-1] == 2:
normals = np.concatenate([normals, np.zeros_like(normals)[:, :1]], axis=-1)
vertex_normal = np.core.records.fromarrays(
normals.transpose(1, 0), names='nx, ny, nz', formats='f4, f4, f4')
assert len(vertex_normal) == num_vertex
desc = desc + vertex_normal.dtype.descr
if colors is not None:
assert len(colors) == num_vertex
if colors.max() <= 1:
colors = colors * 255
if colors.shape[1] == 4:
vertex_color = np.core.records.fromarrays(colors.transpose(
1, 0), names='red, green, blue, alpha', formats='u1, u1, u1, u1')
else:
vertex_color = np.core.records.fromarrays(colors.transpose(
1, 0), names='red, green, blue', formats='u1, u1, u1')
desc = desc + vertex_color.dtype.descr
vertex_all = np.empty(num_vertex, dtype=desc)
for prop in vertex.dtype.names:
vertex_all[prop] = vertex[prop]
if normals is not None:
for prop in vertex_normal.dtype.names:
vertex_all[prop] = vertex_normal[prop]
if colors is not None:
for prop in vertex_color.dtype.names:
vertex_all[prop] = vertex_color[prop]
ply = plyfile.PlyData(
[plyfile.PlyElement.describe(vertex_all, 'vertex')], text=(not binary))
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
ply.write(filename)
| 7,408 |
def points_in_convex_polygon_3d_jit(points,
polygon_surfaces,
):
"""check points is in 3d convex polygons.
Args:
points: [num_points, 3] array.
polygon_surfaces: [num_polygon, max_num_surfaces,
max_num_points_of_surface, 3]
array. all surfaces' normal vector must direct to internal.
max_num_points_of_surface must at least 3.
num_surfaces: [num_polygon] array. indicate how many surfaces
a polygon contain
Returns:
[num_points, num_polygon] bool array.
"""
max_num_surfaces, max_num_points_of_surface = polygon_surfaces.shape[1:3]
num_points = points.shape[0]
num_polygons = polygon_surfaces.shape[0]
num_surfaces = np.full((num_polygons,), 9999999, dtype=np.int64)
normal_vec, d = surface_equ_3d_jit(polygon_surfaces[:, :, :3, :])
# normal_vec: [num_polygon, max_num_surfaces, 3]
# d: [num_polygon, max_num_surfaces]
ret = np.ones((num_points, num_polygons), dtype=np.bool_)
sign = 0.0
for i in range(num_points):
for j in range(num_polygons):
for k in range(max_num_surfaces):
if k > num_surfaces[j]:
break
sign = points[i, 0] * normal_vec[j, k, 0] \
+ points[i, 1] * normal_vec[j, k, 1] \
+ points[i, 2] * normal_vec[j, k, 2] + d[j, k]
if sign >= 0:
ret[i, j] = False
break
return ret
| 7,409 |
def classify(data, target_class, model_type, best_model, data_path):
"""
Classify the data using the best model.
GIVEN:
data (ist) list of events to be classified
target_class (str) one of ["tactics", "techniques"]
model_type (str) one of ["nb", "lsvc"]
best_model (model) the best model
data_path (str) relative path for data being classified
"""
# Classify new data using best model
model_map = {"nb": "MultinomalNB", "lsvc": "LinearSVC"}
print("Classifying {} for new data with best {} model.".format(
target_class, model_map[model_type]))
predictions = best_model.predict(data)
# Write predictions to disk
data_name = data_path.split("/")[-1].rstrip(".csv")
print(data_name)
outfile = "predictions_{}_{}_{}.csv".format(
model_map[model_type], target_class, data_name)
with open(outfile, "w") as f:
for pred in predictions:
f.write(pred + "\n")
| 7,410 |
def _get_spamassassin_flag_path(domain_or_user):
"""
Get the full path of the file who's existence is used as a flag to turn
SpamAssassin on.
Args:
domain_or_user - A full email address or a domain name
"""
domain = domain_or_user.lower()
user = False
if '@' in domain:
user, domain = domain.split('@')
sys_user = get_account_from_domain(domain)
if user:
return '/home/' + sys_user + '/etc/' + domain + '/' + user + '/enable_spamassassin'
else:
return '/home/' + sys_user + '/etc/' + domain + '/enable_spamassassin'
| 7,411 |
def list_api_keys(ctx):
"""List all api keys in db."""
show_fields = ["valid_key", "allow_fallback", "allow_locate", "allow_region"]
db = configure_db("rw")
with db_worker_session(db) as session:
columns = ApiKey.__table__.columns
fields = [getattr(columns, f) for f in show_fields]
rows = session.execute(select(fields)).fetchall()
click.echo("%d api keys." % len(rows))
if rows:
# Add header row
table = [show_fields]
# Add rest of the rows; the columns are in the order of show_fields so we
# don't have to do any re-ordering
table.extend(rows)
print_table(table, stream_write=click_echo_no_nl)
| 7,412 |
def format(number):
"""Reformat the passed number to the standard format."""
number = compact(number)
return '-'.join((number[:3], number[3:-1], number[-1]))
| 7,413 |
def get_terms(request):
"""Returns list of terms matching given query"""
if TEST_MODE:
thesaurus_name = request.params.get('thesaurus_name')
extract_name = request.params.get('extract_name')
query = request.params.get('term')
else:
thesaurus_name = request.validated.get('thesaurus_name')
extract_name = request.validated.get('extract_name')
query = request.validated.get('term')
if not (thesaurus_name or query):
return {}
thesaurus = query_utility(IThesaurus, name=thesaurus_name)
if thesaurus is None:
return {}
try:
return {
'results': [
{
'id': term.label,
'text': term.label
}
for term in unique(thesaurus.find_terms(query, extract_name,
exact=True, stemmed=True))
if term.status != STATUS_ARCHIVED
]
}
except ParseError:
return []
| 7,414 |
def createExportNeuroML2(netParams=None, simConfig=None, output=False, reference=None, connections=True, stimulations=True, format='xml'):
"""
Wrapper function create and export a NeuroML2 simulation
Parameters
----------
netParams : ``netParams object``
NetPyNE netParams object specifying network parameters.
**Default:** *required*.
simConfig : ``simConfig object``
NetPyNE simConfig object specifying simulation configuration.
**Default:** *required*.
output : bool
Whether or not to return output from the simulation.
**Default:** ``False`` does not return anything.
**Options:** ``True`` returns output.
reference : <``None``?>
<Short description of reference>
**Default:** ``None``
**Options:** ``<option>`` <description of option>
connections : bool
<Short description of connections>
**Default:** ``True``
**Options:** ``<option>`` <description of option>
stimulations : bool
<Short description of stimulations>
**Default:** ``True``
**Options:** ``<option>`` <description of option>
format : str
<Short description of format>
**Default:** ``'xml'``
**Options:** ``<option>`` <description of option>
Returns
-------
data : tuple
If ``output`` is ``True``, returns (pops, cells, conns, stims, rxd, simData)
"""
from .. import sim
import __main__ as top
if not netParams: netParams = top.netParams
if not simConfig: simConfig = top.simConfig
sim.initialize(netParams, simConfig) # create network object and set cfg and net params
pops = sim.net.createPops() # instantiate network populations
cells = sim.net.createCells() # instantiate network cells based on defined populations
conns = sim.net.connectCells() # create connections between cells based on params
stims = sim.net.addStims() # add external stimulation to cells (IClamps etc)
rxd = sim.net.addRxD() # add reaction-diffusion (RxD)
simData = sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc)
sim.exportNeuroML2(reference, connections, stimulations,format) # export cells and connectivity to NeuroML 2 format
if output:
return (pops, cells, conns, stims, rxd, simData)
| 7,415 |
def i18n_pull():
"""pull the updated translation from transifex"""
with lcd('readthedocs'):
local('rm -rf rtd_tests/tests/builds/')
local('tx pull -f ')
local('django-admin makemessages --all')
local('django-admin compilemessages')
| 7,416 |
def run_2(gosubdag):
"""Test GO colors at high and low levels of hierarchy."""
goids = [
'GO:0002682', # GO:0002682 1,127 D03 A regulation of immune system process
'GO:0002726'] # GO:0002726 2 D09 A +reg of T cell cytokine production
gosubdag.prt_goids(goids)
go2color = {
'GO:0002682': '#b1fc99', # pale light green
'GO:0002726': '#f6cefc'} # very light purple
plt_goids(gosubdag, "test_get_parents2.png", goids, go2color=go2color, mark_alt_id=True)
assert 'GO:0002682' in gosubdag.rcntobj.go2parents
| 7,417 |
def load(file: str) -> pd.DataFrame:
"""Load custom file into dataframe. Currently will work with csv
Parameters
----------
file: str
Path to file
Returns
-------
pd.DataFrame:
Dataframe with custom data
"""
if not Path(file).exists():
return pd.DataFrame()
file_type = Path(file).suffix
# TODO More data types
if file_type != ".csv":
return pd.DataFrame()
return pd.read_csv(file)
| 7,418 |
def better_get_first_model_each_manufacturer(car_db):
"""Uses map function and lambda to avoid code with side effects."""
result = map(lambda x: x[0], car_db.values())
# convert map to list
return list(result)
| 7,419 |
def configurable_testcase(default_config_function):
"""Decorator to make a test case configurable."""
def internal_configurable_testcase(testcase):
_log_testcase_header(testcase.__name__, testcase.__doc__)
def wrapper_function(func, name, config, generate_default_func):
@wraps(func)
def _func(*a):
if generate_default_func:
generate_default_func(*a)
_releaseAllPorts()
_log_testcase_header(name, func.__doc__)
return func(*a, config_filename=config)
_func.__name__ = name
return _func
def generate_default(func, default_filename):
@wraps(func)
def _func(*a):
return func(*a, filename=default_filename)
return _func
# Create config directory for this function if it doesn't already exist.
harness_dir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
config_dir = os.path.join(harness_dir, 'testcases', 'configs',
testcase.__name__)
config_names = os.listdir(config_dir) if os.path.exists(config_dir) else []
# No existing configs => generate default config.
generate_default_func = None
if not config_names:
default_config_filename = os.path.join(config_dir, 'default.config')
logging.info("%s: Creating default config at '%s'", testcase.__name__,
default_config_filename)
generate_default_func = generate_default(default_config_function,
default_config_filename)
config_names.append('default.config')
# Run once for each config.
stack = inspect.stack()
frame = stack[1] # Picks the 'testcase' frame.
frame_locals = frame[0].f_locals
for i, config_name in enumerate(config_names):
base_config_name = os.path.splitext(config_name)[0]
name = '%s_%d_%s' % (testcase.__name__, i, base_config_name)
config_filename = os.path.join(config_dir, config_name)
frame_locals[name] = wrapper_function(testcase, name, config_filename,
generate_default_func)
return internal_configurable_testcase
| 7,420 |
def _is_scalar(value):
"""Whether to treat a value as a scalar.
Any non-iterable, string, or 0-D array
"""
from collections import Iterable
return (getattr(value, 'ndim', None) == 0
or isinstance(value, (str, bytes))
or not isinstance(value, (Iterable,)))
| 7,421 |
def start(ctx):
"""
Start Teamplify
"""
_start(ctx.obj['env'])
| 7,422 |
def copy_random(x, y):
""" from 2 randInt calls """
seed = find_seed(x, y)
rand = JavaRandom(seed)
rand.next() # this will be y so we discard it
return rand
| 7,423 |
def build_tree(train, max_depth, min_size, n_features):
"""build_tree(创建一个决策树)
Args:
train 训练数据集
max_depth 决策树深度不能太深,不然容易导致过拟合
min_size 叶子节点的大小
n_features 选取的特征的个数
Returns:
root 返回决策树
"""
# 返回最优列和相关的信息
root = get_split(train, n_features)
# 对左右2边的数据 进行递归的调用,由于最优特征使用过,所以在后面进行使用的时候,就没有意义了
# 例如: 性别-男女,对男使用这一特征就没任何意义了
split(root, max_depth, min_size, n_features, 1)
return root
| 7,424 |
def test_image_download(mock_s3):
""" test running image download"""
runner = CliRunner()
result = runner.invoke(
voithos.cli.openstack.download_image, ["--image", "windows2019"], catch_exceptions=False,
)
assert result.exit_code == 0, result.output
assert mock_s3.download.called
| 7,425 |
def delete_bucket(bucket_name: str, location: str, verbose: bool) -> bool:
"""Delete the specified S3 bucket
Args:
bucket_name (str): name of the S3 bucket
location (str): the location (region) the S3 bucket resides in
verbose (bool): enable verbose output
Returns:
bool: True if the specified S3 bucket was successfully deleted,
False otherwise
"""
try:
print(f'Deleting S3 bucket {bucket_name} in location {location} ...')
start = timer()
s3_client = boto3.client('s3', region_name=location)
response = s3_client.delete_bucket(Bucket=bucket_name)
end = timer()
elapsed_time = round(end - start, 3)
print(f'Deleted bucket in {elapsed_time} seconds')
if verbose:
print('delete_bucket() response:')
pprint.pprint(response)
print()
if response['ResponseMetadata']['HTTPStatusCode'] == 204:
print(f'S3 bucket {bucket_name} successfully deleted')
return True
except ClientError as e:
print(f'S3 ClientError occurred while trying to delete bucket:')
print(f"\t{e.response['Error']['Code']}: {e.response['Error']['Message']}")
return False
| 7,426 |
def generate_ordered_match_str_from_subseqs(r1,
subseqs_to_track,
rc_component_dict,
allow_overlaps=False):
"""Generates an ordered subsequences match string for the input sequence.
Args:
r1: (str) R1 sequence to scan for subsequence matches.
subseqs_to_track: (list) Subsequences to look for in R1.
rc_component_dict: (dict) Dict mapping DNA sequence to label.
allow_overlaps: (boolean) Whether to allow matches that overlap on R1. If
False, then it will identify a maximal non-overlapping set of matches.
Returns:
(str) labeled components for r1 in the form: 'label_1;label_2;...;label_n'
"""
# Generate ordered set of subseq matches to r1 sequence.
match_tups = []
for mer_label in subseqs_to_track:
mer = rc_component_dict[mer_label]
for match in re.finditer(mer, r1):
xstart = match.start()
xend = xstart + len(mer)
match_tups.append((xstart, xend, mer_label))
match_tups.sort(reverse=True)
# Create a maximal independent set that does not allow overlapping subseqs.
if not allow_overlaps and len(match_tups) > 0:
mer_graph = nx.Graph()
mer_graph.add_nodes_from(match_tups)
for i in range(len(match_tups)):
for j in range(i + 1, len(match_tups)):
# Check if the end of match_tups[j] overlaps the start of match_tups[i].
if match_tups[i][0] < match_tups[j][1]:
mer_graph.add_edge(match_tups[i], match_tups[j])
# Generate a non-overlapping list of subseqs.
match_tups = nx.maximal_independent_set(mer_graph)
match_tups.sort(reverse=True)
match_str = BCS_SEP.join([match_tup[-1] for match_tup in match_tups])
return match_str
| 7,427 |
def combination(n: int, r: int) -> int:
""":return nCr = nPr / r!"""
return permutation(n, r) // factorial(r)
| 7,428 |
def _extract_operator_data(fwd, inv_prep, labels, method='dSPM'):
"""Function for extracting forward and inverse operator matrices from
the MNE-Python forward and inverse data structures, and assembling the
source identity map.
Input arguments:
================
fwd : ForwardOperator
The fixed_orientation forward operator.
Instance of the MNE-Python class Forward.
inv_prep : Inverse
The prepared inverse operator.
Instance of the MNE-Python class InverseOperator.
labels : list
List of labels belonging to the used parcellation, e.g. the
Desikan-Killiany, Destrieux, or Schaefer parcellation.
May not contain 'trash' labels/parcels (unknown or medial wall), those
should be deleted from the labels array!
method : str
The inversion method. Default 'dSPM'.
Other methods ('MNE', 'sLORETA', 'eLORETA') have not been tested.
Output arguments:
=================
source_identities : ndarray
Vector mapping sources to parcels or labels.
fwd_mat : ndarray [sensors x sources]
The forward operator matrix.
inv_mat : ndarray [sources x sensors]
The prepared inverse operator matrix.
"""
# counterpart to forwardOperator, [sources x sensors]. ### pick_ori None for free, 'normal' for fixed orientation.
K, noise_norm, vertno, source_nn = _assemble_kernel(
inv=inv_prep, label=None, method=method, pick_ori='normal')
# get source space
src = inv_prep.get('src')
vert_lh, vert_rh = src[0].get('vertno'), src[1].get('vertno')
# get labels, vertices and src-identities
src_ident_lh = np.full(len(vert_lh), -1, dtype='int')
src_ident_rh = np.full(len(vert_rh), -1, dtype='int')
# find sources that belong to the left hemisphere labels
n_labels = len(labels)
for la, label in enumerate(labels[:n_labels//2]):
for v in label.vertices:
src_ident_lh[np.where(vert_lh == v)] = la
# find sources that belong to the right hemisphere labels. Add by n left.
for la, label in enumerate(labels[n_labels//2:n_labels]):
for v in label.vertices:
src_ident_rh[np.where(vert_rh == v)] = la
src_ident_rh[np.where(src_ident_rh<0)] = src_ident_rh[np.where(
src_ident_rh<0)] -n_labels/2
src_ident_rh = src_ident_rh + (n_labels // 2)
source_identities = np.concatenate((src_ident_lh,src_ident_rh))
# extract fwd and inv matrices
fwd_mat = fwd['sol']['data'] # sensors x sources
"""If there are bad channels the corresponding rows can be missing
from the forward matrix. Not sure if the same can occur for the
inverse. This is not a problem if bad channels are interpolated.""" ### MOVED from weight_inverse_operator, just before """Compute the weighted operator."""
ind = np.asarray([i for i, ch in enumerate(fwd['info']['ch_names'])
if ch not in fwd['info']['bads']])
fwd_mat = fwd_mat[ind, :]
# noise_norm is used with dSPM and sLORETA. Other methods return null.
if method != 'dSPM' or method != 'sLORETA':
noise_norm = 1.
inv_mat = K * noise_norm # sources x sensors
return source_identities, fwd_mat, inv_mat
| 7,429 |
def create_new_containers(module, intended, facts):
"""
Create missing container to CVP Topology.
Parameters
----------
module : AnsibleModule
Object representing Ansible module structure with a CvpClient connection
intended : list
List of expected containers based on following structure:
facts : dict
Facts from CVP collected by cv_facts module
"""
count_container_creation = 0
# Get root container of topology
topology_root = tools_tree.get_root_container(containers_fact=facts['containers'])
# Build ordered list of containers to create: from Tenant to leaves.
container_intended_tree = tools_tree.tree_build_from_dict(containers=intended, root=topology_root)
MODULE_LOGGER.debug("The ordered dict is: %s", str(container_intended_tree))
container_intended_ordered_list = tools_tree.tree_to_list(json_data=container_intended_tree, myList=list())
MODULE_LOGGER.debug("The ordered list is: %s", str(container_intended_ordered_list))
# Parse ordered list of container and check if they are configured on CVP.
# If not, then call container creation process.
for container_name in container_intended_ordered_list:
found = False
# Check if container name is found in CVP Facts.
for fact_container in facts['containers']:
if container_name == fact_container['name']:
found = True
break
# If container has not been found, we create it
if not found:
# module.fail_json(msg='** Create container'+container_name+' attached to '+intended[container_name]['parent_container'])
MODULE_LOGGER.debug('sent process_container request with %s / %s', str(
container_name), str(intended[container_name]['parent_container']))
response = process_container(module=module,
container=container_name,
parent=intended[container_name]['parent_container'],
action='add')
MODULE_LOGGER.debug('sent process_container request with %s / %s and response is : %s', str(
container_name), str(intended[container_name]['parent_container']), str(response))
# If a container has been created, increment creation counter
if response[0]:
count_container_creation += 1
# Build module message to return for creation.
if count_container_creation > 0:
return [True, {'containers_created': "" + str(count_container_creation) + ""}]
return [False, {'containers_created': "0"}]
| 7,430 |
def main(test_only=False):
"""
Main function
"""
if not os.path.exists('adjectives.txt') or not os.path.exists('animals.txt'):
LOGGER.critical('You need both adjectives.txt and animals.txt')
sys.exit(1)
current_threats_group_id, archived_threats_group_id = get_group_ids()
base_assets = get_assets(settings.PAT_GROUP_ID)
if current_threats_group_id is None or archived_threats_group_id is None:
LOGGER.critical('run Patrowl Asset Lifecycle first')
sys.exit(1)
ct_assets = get_assets(current_threats_group_id)
at_assets = get_assets(archived_threats_group_id)
if not base_assets and not ct_assets and not at_assets:
LOGGER.warning('no assets')
else:
ct_findings = get_findings(ct_assets)
for ct_asset in ct_assets:
ct_findings = update_for_sale_finding(ct_asset, ct_findings, test_only=test_only)
ct_findings = update_ip_finding(ct_asset, ct_findings, test_only=test_only)
for ct_asset in ct_assets:
ct_findings = update_current_threat(ct_asset, ct_findings, test_only=test_only)
base_findings = get_findings(base_assets)
for base_asset in base_assets:
update_for_sale_finding(base_asset, base_findings, test_only=test_only)
update_ip_finding(base_asset, base_findings, test_only=test_only)
update_threat(base_asset, base_findings[base_asset['id']], ct_findings, test_only=test_only)
at_findings = get_findings(at_assets)
for at_asset in at_assets:
update_for_sale_finding(at_asset, at_findings, test_only=test_only)
update_ip_finding(at_asset, at_findings, test_only=test_only)
update_threat(at_asset, at_findings[at_asset['id']], ct_findings, test_only=test_only)
| 7,431 |
def find_window_for_buffer_name(cli, buffer_name):
"""
Look for a :class:`~prompt_toolkit.layout.containers.Window` in the Layout
that contains the :class:`~prompt_toolkit.layout.controls.BufferControl`
for the given buffer and return it. If no such Window is found, return None.
"""
from prompt_toolkit.interface import CommandLineInterface
assert isinstance(cli, CommandLineInterface)
from .containers import Window
from .controls import BufferControl
for l in cli.layout.walk(cli):
if isinstance(l, Window) and isinstance(l.content, BufferControl):
if l.content.buffer_name == buffer_name:
return l
| 7,432 |
def convert_transpose(params, w_name, scope_name, inputs, layers, weights, short_names):
"""
Convert transpose layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
short_names: use short names for keras layers
"""
print('Converting transpose ...')
if params['perm'][0] != 0:
# raise AssertionError('Cannot permute batch dimension')
print('!!! Cannot permute batch dimension. Result may be wrong !!!')
layers[scope_name] = layers[inputs[0]]
else:
if short_names:
tf_name = 'PERM' + random_string(4)
else:
tf_name = w_name + str(random.random())
permute = keras.layers.Permute(params['perm'][1:], name=tf_name)
layers[scope_name] = permute(layers[inputs[0]])
| 7,433 |
def main(mytimer: func.TimerRequest, outputblob: func.Out[bytes]):
# pylint: disable=E1136
"""Serverless scraping function."""
utc_timestamp = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
if mytimer.past_due:
logging.info("The timer is past due!")
url = "https://fantasy.premierleague.com/api/fixtures/"
fixtures = requests.get(url).json()
download_time = str(datetime.datetime.now())
data = {}
data["download_time"] = download_time
data["fixtures"] = fixtures
logging.info("Python timer trigger function ran at %s", utc_timestamp)
outputblob.set(json.dumps(data, ensure_ascii=False))
| 7,434 |
def create_pilot(username='kimpilot', first_name='Kim', last_name='Pilot', email='kim@example.com', password='secret'):
"""Returns a new Pilot (User) with the given properties."""
pilot_group, _ = Group.objects.get_or_create(name='Pilots')
pilot = User.objects.create_user(username, email, password, first_name=first_name, last_name=last_name)
pilot.groups.add(pilot_group)
return pilot
| 7,435 |
def set_default_role():
"""Set custom default role.
By default::
`text` -> :title:`text`
we override with our role::
`text` -> `text`
See Also:
:attr:`roles.DEFAULT_INTERPRETED_ROLE`.
"""
if roles._roles.get('') != default_role:
roles._roles[''] = default_role
| 7,436 |
def dict_to_datasets(data_list, components):
"""add models and backgrounds to datasets
Parameters
----------
datasets : `~gammapy.modeling.Datasets`
Datasets
components : dict
dict describing model components
"""
models = dict_to_models(components)
datasets = []
for data in data_list["datasets"]:
dataset = DATASETS.get_cls(data["type"]).from_dict(data, components, models)
datasets.append(dataset)
return datasets
| 7,437 |
def of(*args: _TSource) -> Seq[_TSource]:
"""Create sequence from iterable.
Enables fluent dot chaining on the created sequence object.
"""
return Seq(args)
| 7,438 |
async def test_create_stop_action(
decoy: Decoy,
mock_engine_store: EngineStore,
mock_run_store: RunStore,
mock_task_runner: TaskRunner,
run_id: str,
subject: RunController,
) -> None:
"""It should resume a run."""
result = subject.create_action(
action_id="some-action-id",
action_type=RunActionType.STOP,
created_at=datetime(year=2021, month=1, day=1),
)
assert result == RunAction(
id="some-action-id",
actionType=RunActionType.STOP,
createdAt=datetime(year=2021, month=1, day=1),
)
decoy.verify(mock_run_store.insert_action(run_id, result), times=1)
decoy.verify(mock_task_runner.run(mock_engine_store.runner.stop), times=1)
| 7,439 |
def find_anagrams(word_list: list) -> dict:
"""Finds all anagrams in a word list and returns it in a dictionary
with the letters as a key.
"""
d = dict()
for word in word_list:
unique_key = single(word)
if unique_key in d:
d[unique_key].append(word)
else:
d[unique_key] = [word]
return d
| 7,440 |
def check_aggregator(aggregator, source, expression_type, group_by):
"""Check aggregator fields."""
if aggregator["source"] != source:
raise ValueError(
"All expressions must be annotated by the same genome database (NCBI, UCSC, ENSEMBLE,...)."
)
if aggregator["expression_type"] != expression_type:
raise ValueError("All expressions must be of the same type.")
if aggregator["group_by"] != group_by:
raise ValueError("Group by field must be the same.")
| 7,441 |
def acr_helm_install_cli(client_version='2.16.3', install_location=None, yes=False):
"""Install Helm command-line tool."""
if client_version >= '3':
logger.warning('Please note that "az acr helm" commands do not work with Helm 3, '
'but you can still push Helm chart to ACR using a different command flow. '
'For more information, please check out '
'https://docs.microsoft.com/azure/container-registry/container-registry-helm-repos')
install_location, install_dir, cli = _process_helm_install_location_info(install_location)
client_version = "v%s" % client_version
source_url = 'https://get.helm.sh/{}'
package, folder = _get_helm_package_name(client_version)
download_path = ''
if not package:
raise CLIError('No prebuilt binary for current system.')
try:
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
download_path = os.path.join(tmp_dir, package)
_urlretrieve(source_url.format(package), download_path)
_unzip(download_path, tmp_dir)
sub_dir = os.path.join(tmp_dir, folder)
# Ask user to check license
if not yes:
with open(os.path.join(sub_dir, 'LICENSE')) as f:
text = f.read()
logger.warning(text)
user_confirmation('Before proceeding with the installation, '
'please confirm that you have read and agreed the above license.')
# Move files from temporary location to specified location
import shutil
import stat
for f in os.scandir(sub_dir):
# Rename helm to specified name
target_path = install_location if os.path.splitext(f.name)[0] == 'helm' \
else os.path.join(install_dir, f.name)
logger.debug('Moving %s to %s', f.path, target_path)
shutil.move(f.path, target_path)
if os.path.splitext(f.name)[0] in ('helm', 'tiller'):
os.chmod(target_path, os.stat(target_path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except IOError as e:
import traceback
logger.debug(traceback.format_exc())
raise CLIError('Error while installing {} to {}: {}'.format(cli, install_dir, e))
logger.warning('Successfully installed %s to %s.', cli, install_dir)
# Remind user to add to path
system = platform.system()
if system == 'Windows': # be verbose, as the install_location likely not in Windows's search PATHs
env_paths = os.environ['PATH'].split(';')
found = next((x for x in env_paths if x.lower().rstrip('\\') == install_dir.lower()), None)
if not found:
# pylint: disable=logging-format-interpolation
logger.warning('Please add "{0}" to your search PATH so the `{1}` can be found. 2 options: \n'
' 1. Run "set PATH=%PATH%;{0}" or "$env:path += \'{0}\'" for PowerShell. '
'This is good for the current command session.\n'
' 2. Update system PATH environment variable by following '
'"Control Panel->System->Advanced->Environment Variables", and re-open the command window. '
'You only need to do it once'.format(install_dir, cli))
else:
logger.warning('Please ensure that %s is in your search PATH, so the `%s` command can be found.',
install_dir, cli)
| 7,442 |
def resolver(state_sets, event_map):
"""Given a set of state return the resolved state.
Args:
state_sets(list[dict[tuple[str, str], str]]): A list of dicts from
type/state_key tuples to event_id
event_map(dict[str, FrozenEvent]): Map from event_id to event
Returns:
dict[tuple[str, str], str]: The resolved state map.
"""
# First split up the un/conflicted state
unconflicted_state, conflicted_state = _seperate(state_sets)
# Also fetch all auth events that appear in only some of the state sets'
# auth chains.
auth_diff = _get_auth_chain_difference(state_sets, event_map)
# Now order the conflicted state and auth_diff by power level (falling
# back to event_id to tie break consistently).
event_id_to_level = [
(_get_power_level_for_sender(event_id, event_map), event_id)
for event_id in set(itertools.chain(
itertools.chain.from_iterable(conflicted_state.values()),
auth_diff,
))
]
event_id_to_level.sort()
events_sorted_by_power = [eid for _, eid in event_id_to_level]
# Now we reorder the list to ensure that auth dependencies of an event
# appear before the event in the list
sorted_events = []
def add_to_list(event_id):
event = event_map[event_id]
for aid, _ in event.auth_events:
if aid in events_sorted_by_power:
events_sorted_by_power.remove(aid)
add_to_list(aid)
sorted_events.append(event_id)
# First, lets pick out all the events that (probably) require power
leftover_events = []
while events_sorted_by_power:
event_id = events_sorted_by_power.pop()
if _is_power_event(event_map[event_id]):
add_to_list(event_id)
else:
leftover_events.append(event_id)
# Now we go through the sorted events and auth each one in turn, using any
# previously successfully auth'ed events (falling back to their auth events
# if they don't exist)
overridden_state = {}
event_id_to_auth = {}
for event_id in sorted_events:
event = event_map[event_id]
auth_events = {}
for aid, _ in event.auth_events:
aev = event_map[aid]
auth_events[(aev.type, aev.state_key)] = aev
for key, eid in overridden_state.items():
auth_events[key] = event_map[eid]
try:
event_auth.check(
event, auth_events,
do_sig_check=False,
do_size_check=False
)
allowed = True
overridden_state[(event.type, event.state_key)] = event_id
except AuthError:
allowed = False
event_id_to_auth[event_id] = allowed
resolved_state = {}
# Now for each conflicted state type/state_key, pick the latest event that
# has passed auth above, falling back to the first one if none passed auth.
for key, conflicted_ids in conflicted_state.items():
sorted_conflicts = []
for eid in sorted_events:
if eid in conflicted_ids:
sorted_conflicts.append(eid)
sorted_conflicts.reverse()
for eid in sorted_conflicts:
if event_id_to_auth[eid]:
resolved_eid = eid
resolved_state[key] = resolved_eid
break
resolved_state.update(unconflicted_state)
# OK, so we've now resolved the power events. Now mainline them.
sorted_power_resolved = sorted(resolved_state.values())
mainline = []
def add_to_list_two(event_id):
ev = event_map[event_id]
for aid, _ in ev.auth_events:
if aid not in mainline and event_id_to_auth.get(aid, True):
add_to_list_two(aid)
if event_id not in mainline:
mainline.append(event_id)
while sorted_power_resolved:
ev_id = sorted_power_resolved.pop()
ev = event_map[ev_id]
if _is_power_event(ev):
add_to_list_two(ev_id)
mainline_map = {ev_id: i + 1 for i, ev_id in enumerate(mainline)}
def get_mainline_depth(event_id):
if event_id in mainline_map:
return mainline_map[event_id]
ev = event_map[event_id]
if not ev.auth_events:
return 0
depth = max(
get_mainline_depth(aid)
for aid, _ in ev.auth_events
)
return depth
leftover_events_map = {
ev_id: get_mainline_depth(ev_id)
for ev_id in leftover_events
}
leftover_events.sort(key=lambda ev_id: (leftover_events_map[ev_id], ev_id))
for event_id in leftover_events:
event = event_map[event_id]
auth_events = {}
for aid, _ in event.auth_events:
aev = event_map[aid]
auth_events[(aev.type, aev.state_key)] = aev
for key, eid in overridden_state.items():
auth_events[key] = event_map[eid]
try:
event_auth.check(
event, auth_events,
do_sig_check=False,
do_size_check=False
)
allowed = True
overridden_state[(event.type, event.state_key)] = event_id
except AuthError:
allowed = False
event_id_to_auth[event_id] = allowed
for key, conflicted_ids in conflicted_state.items():
sorted_conflicts = []
for eid in leftover_events:
if eid in conflicted_ids:
sorted_conflicts.append(eid)
sorted_conflicts.reverse()
for eid in sorted_conflicts:
if event_id_to_auth[eid]:
resolved_eid = eid
resolved_state[key] = resolved_eid
break
resolved_state.update(unconflicted_state)
return resolved_state
| 7,443 |
def parse_study(study):
"""Parse study
Args:
study (object): object from DICOMDIR level 1 object (children of patient_record)
Returns:
children_object
appending_keys
"""
#study_id = study.StudyID
study_date = study.StudyDate
study_time = study.StudyTime
study_des = study.StudyDescription
return study.children, study_date, study_time, study_des
| 7,444 |
def list_organizational_units_for_parent_single_page(self, **kwargs):
"""
This will continue to call list_organizational_units_for_parent until there are no more pages left to retrieve.
It will return the aggregated response in the same structure as list_organizational_units_for_parent does.
:param self: organizations client
:param kwargs: these are passed onto the list_organizational_units_for_parent method call
:return: organizations_client.list_organizational_units_for_parent.response
"""
return slurp(
'list_organizational_units_for_parent',
self.list_organizational_units_for_parent,
'OrganizationalUnits',
'NextToken', 'NextToken',
**kwargs
)
| 7,445 |
def daemon(target, name=None, args=None, kwargs=None, after=None):
"""
Create and start a daemon thread.
It is same as `start()` except that it sets argument `daemon=True`.
"""
return start(target, name=name, args=args, kwargs=kwargs,
daemon=True, after=after)
| 7,446 |
def mkdirs(dpath):
"""
Create directory path (including the path of the parent directory if it
doesn't already exist)
:param dpath: string - path to directory to be created
"""
if os.path.isdir(dpath):
return
try:
os.makedirs(dpath)
except OSError as exc:
fstr = "cannot create directory: {}".format(dpath)
raise GlobeIndexerError(fstr, details=str(exc))
| 7,447 |
def convert_pc2plyandweaklabels(anno_path, save_path, sub_pc_folder,
weak_label_folder, weak_label_ratio, sub_grid_size,
gt_class, gt_class2label):
"""
Convert original dataset files (consiting of rooms) to ply file and weak labels. Physically, each room will generate several files, including raw_pc.ply, sub_pc.ply, sub_pc.pkl (for the kdtree), proj_idx.pkl (for each raw point's nearest neighbor in the sub_pc) and weak labels for raw and sub_pc, respectively )
:param anno_path: path to annotations. e.g. Area_1/office_2/Annotations/
:param save_path: path to save original point clouds (each line is XYZRGBL), e.g., xx.ply
:return: None
"""
num_raw_points = 0 # number of raw points for current room
num_sub_points = 0 # number of sub-sampled points for current room
# save raw_cloud
if not os.path.exists(save_path):
data_list = []
# aggregate a room's instances into 1 pc
for f in glob.glob(join(anno_path, '*.txt')):
class_name = os.path.basename(f).split('_')[0]
if class_name not in gt_class: # note: in some room there is 'staris' class..
class_name = 'clutter'
pc = pd.read_csv(f, header=None, delim_whitespace=True).values
labels = np.ones((pc.shape[0], 1)) * gt_class2label[class_name]
data_list.append(np.concatenate([pc, labels], 1)) # Nx7
# translate the data by xyz_min--yc
pc_label = np.concatenate(data_list, 0) # Nx7 as a np object
xyz_min = np.amin(pc_label, axis=0)[0:3]
pc_label[:, 0:3] -= xyz_min
# manage data types and save in PLY format--yc
xyz = pc_label[:, :3].astype(np.float32)
num_raw_points = xyz.shape[0]
colors = pc_label[:, 3:6].astype(np.uint8)
labels = pc_label[:, 6].astype(np.uint8)
write_ply(save_path, (xyz, colors, labels), ['x', 'y', 'z', 'red', 'green', 'blue', 'class'])
else:
# if existed then read this ply file to fill the data/xyz/colors/labels
data = read_ply(save_path) # ply format: x,y,z,red,gree,blue,class
xyz = np.vstack((data['x'], data['y'], data['z'])).T # (N',3), note the transpose symbol
num_raw_points = xyz.shape[0]
colors = np.vstack((data['red'], data['green'], data['blue'])).T # (N',3), note the transpose symbol
labels = data['class']
pc_label = np.concatenate((xyz, colors, np.expand_dims(labels, axis=1)),axis=1) # (N,7)
# save sub_cloud
sub_ply_file = join(sub_pc_folder, save_path.split('/')[-1][:-4] + '.ply')
if not os.path.exists(sub_ply_file):
sub_xyz, sub_colors, sub_labels = DP.grid_sub_sampling(xyz, colors, labels, sub_grid_size)
sub_colors = sub_colors / 255.0
num_sub_points = sub_xyz.shape[0]
write_ply(sub_ply_file, [sub_xyz, sub_colors, sub_labels], ['x', 'y', 'z', 'red', 'green', 'blue', 'class'])
else:
data = read_ply(sub_ply_file) # ply format: x,y,z,red,gree,blue,class
sub_xyz = np.vstack((data['x'], data['y'], data['z'])).T # (N',3), note the transpose symbol
num_sub_points = sub_xyz.shape[0]
sub_colors = np.vstack((data['red'], data['green'], data['blue'])).T # (N',3), note the transpose symbol
sub_labels = data['class']
# save KDTree for sub_pc
kd_tree_file = join(sub_pc_folder, str(save_path.split('/')[-1][:-4]) + '_KDTree.pkl')
if not os.path.exists(kd_tree_file):
search_tree = KDTree(sub_xyz)
with open(kd_tree_file, 'wb') as f:
pickle.dump(search_tree, f)
# save projection indcies for all raw points over the corresponding sub_pc
proj_save = join(sub_pc_folder, str(save_path.split('/')[-1][:-4]) + '_proj.pkl')
if not os.path.exists(proj_save):
proj_idx = np.squeeze(search_tree.query(xyz, return_distance=False))
proj_idx = proj_idx.astype(np.int32)
with open(proj_save, 'wb') as f:
pickle.dump([proj_idx, labels], f)
# USED for weakly semantic segmentation, save sub pc's weak labels
# KEY: Randomly select some points to own labels, give them a mask (no need to save weak label mask for raw pc)
weak_label_sub_file = join(weak_label_folder, save_path.split('/')[-1][:-4] + '_sub_weak_label.ply')
if not os.path.exists(weak_label_sub_file):
# compute weak ratio of weak points w.r.t. #sub_pc
print(f'Current sub-sampled ratio(#sub_points/#raw_points) is {(num_sub_points/num_raw_points)*100:.2f}%')
print(f'Current weak_ratio(#weak_points/#raw_points) is {(weak_label_ratio):.4f}')
# set weak points by randomly selecting weak_label_ratio*N points(i.e., the number of raw_pc) and denote them w. a mask
weak_label_sub_mask = np.zeros((num_sub_points, 1), dtype=np.uint8)
# BUG FIXED: fixed already; here, should set replace = True, otherwise a bug will be resulted
# KEY: weak_label_ratio should be multiplied by number of raw points rather sub-sampled points
selected_idx = np.random.choice(num_sub_points, int(num_raw_points*weak_label_ratio),replace=False)
weak_label_sub_mask[selected_idx,:]=1
write_ply(weak_label_sub_file, (weak_label_sub_mask,), ['weak_mask'])
else:
data = read_ply(weak_label_sub_file)
weak_label_mask = data['weak_mask']
| 7,448 |
def add_image_to_obj(obj, img, *args, **kwargs):
"""
"""
# skip everything if there is no image
if img == None:
return None
# find out of the object is an artist or an album
# then add the artist or the album to the objects
objs = {}
if isinstance(obj, Artist):
objs['artist'] = obj
t = 'artist'
elif isinstance(obj, Album):
objs['album'] = obj
t = 'album'
# delete old objects in S3 if editing:
reprocess = kwargs.pop('reprocess', False)
editing = kwargs.pop('edit', False)
if editing:
prefix = f"images/{obj.__class__.__name__}/{str(obj.uri)}/"
# delete the old objects from the database and S3
if settings.USE_S3:
s3 = boto3.resource('s3')
image_mngr = getattr(obj, f"{t}_image")
images = image_mngr.all()
for item in images:
if item.file:
if settings.USE_S3:
s3.Object(settings.AWS_STORAGE_BUCKET_NAME, item.file.name)#.delete()
# else: # delete file locally... who cares...
if reprocess:
if not item.is_original:
item.delete()
else:
item.delete()
def process_image(image_obj):
width, height = get_image_dimensions(image_obj.file.file)
image_obj.width = width
image_obj.height = height
image_obj.save()
# post processing, creating duplicates, etc...
# create new thread...
t = threading.Thread(target=resize_image_async, args=[image_obj])
t.setDaemon(True)
t.start()
return image_obj
# create the object
if type(img) == str:
image_obj = Image.objects.create(reference=img, is_original=True, height=1, width=1, **objs)
elif type(img) == dict:
image_obj = Image.objects.create(reference=img['image'], is_original=True, height=image['height'], width=image['width'], **objs)
else: # image is the file
if reprocess:
image_obj = Image.objects.filter(**{f"{t}": obj, 'is_original': True}).first()
else:
image_obj = Image.objects.create(file=img, is_original=True, height=1, width=1, **objs) # image is stored in S3
image_obj = process_image(image_obj)
return image_obj
| 7,449 |
def test_zco_x_y_invariant():
"""Make sure all vertical columns are identical"""
# Generate 2x2 flat bathymetry dataset
ds_bathy = Bathymetry(10.0e3, 1.2e3, 2, 2).flat(5.0e3)
ds_bathy.domcfg.jpk = 10
ds = ds_bathy.domcfg.zco(ppdzmin=10, pphmax=5.0e3)
# Check z3 and e3
for varname in ["z3T", "z3W", "e3T", "e3W"]:
expected = ds[varname].isel(x=0, y=0)
actual = ds[varname]
assert (expected == actual).all()
| 7,450 |
def rr_category_ad(context, ad_zone, ad_category, index=0):
"""
Returns a rr advert from the specified category based on index.
Usage:
{% load adzone_tags %}
{% rr_category_ad 'zone_slug' 'my_category_slug' 1 %}
"""
to_return = {'random_int': randint(1000000, 10000000)}
# Retrieve a rr ad for the category and zone
ad = AdBase.objects.get_rr_ad(ad_zone, ad_category, index)
to_return['ad'] = ad
# Record a impression for the ad
if settings.ADZONE_LOG_AD_IMPRESSIONS and 'from_ip' in context and ad:
from_ip = context.get('from_ip')
try:
AdImpression.objects.create(
ad=ad, impression_date=datetime.now(), source_ip=from_ip)
except Exception:
pass
return to_return
| 7,451 |
def test_config_unset_backreferences(config_app):
"""Testing Deprecation warning message against unset backreference config
In this case the user is notified to update the set the
backreferences_dir config variable if such feature is to be enabled or
otherwise to deactivate the feature. Sphinx-Gallery should notify the
user and also silently setup the old default config value into the new
config style. """
cfg = config_app.config
assert cfg.project == "Sphinx-Gallery <Tests>"
assert cfg.sphinx_gallery_conf['backreferences_dir'] == os.path.join(
'modules', 'generated')
build_warn = config_app._warning.getvalue()
assert "Gallery now requires" in build_warn
assert "'backreferences_dir': False" in build_warn
assert "WARNING:" in build_warn
assert "mod_example_dir" not in build_warn
| 7,452 |
def decoderCNN(x, layers):
""" Construct the Decoder
x : input to decoder
layers : the number of filters per layer (in encoder)
"""
# Feature unpooling by 2H x 2W
for _ in range(len(layers) - 1, 0, -1):
n_filters = layers[_]
x = Conv2DTranspose(n_filters, (3, 3), strides=(2, 2), padding='same', use_bias=False,
kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = ReLU()(x)
# Last unpooling, restore number of channels
x = Conv2DTranspose(1, (3, 3), strides=(2, 2), padding='same', use_bias=False, kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = ReLU()(x)
return x
| 7,453 |
def main(tempdir):
"""
Create a Flask app, and using the updated security config file get a new
REST token. Then write the new token to a file under the snapshot`s
tmp dir.
:param tempdir: The temp dir used by `restore snapshot` wf.
"""
setup_flask_app()
sm = get_storage_manager()
admin_user = sm.get(models.User, 0)
token = admin_user.get_auth_token()
_write_token_to_file(tempdir, token)
| 7,454 |
def centroid_imzml(input_filename, output_filename, step=[], apodization=False, w_size=10, min_intensity=1e-5, prevent_duplicate_pixels=False):
# write a file to imzml format (centroided)
"""
:type input_filename string - source file path (must be .imzml)
:type output_filename string - output file path (must be .imzml)
:type step tuple grid spacing of pixels (if [] the script will try and guess it)
:type apodization boolean whether to try and remove FT wiglet artefacts
:type w_size window side (m/z bins) for apodization
:type min_intensity: float minimum intensity peaks to return during centroiding
:type prevent_duplicate_pixels bool if True will only return the first spectrum for pixels with the same coodinates
"""
from pyimzml.ImzMLParser import ImzMLParser
from pyimzml.ImzMLWriter import ImzMLWriter
from pyMSpec.centroid_detection import gradient
imzml_in = ImzMLParser(input_filename)
precisionDict = {'f':("32-bit float", np.float32), 'd': ("64-bit float", np.float64), 'i': ("32-bit integer", np.int32), 'l': ("64-bit integer", np.int64)}
mz_dtype = precisionDict[imzml_in.mzPrecision][1]
int_dtype = precisionDict[imzml_in.intensityPrecision][1]
# Convert coords to index -> kinda hacky
coords = np.asarray(imzml_in.coordinates).round(5)
coords -= np.amin(coords, axis=0)
if step == []: # have a guesss
step = np.array([np.median(np.diff(np.unique(coords[:, i]))) for i in range(coords.shape[1])])
step[np.isnan(step)] = 1
print 'estimated pixel size: {} x {}'.format(step[0], step[1])
coords = coords / np.reshape(step, (3,)).T
coords = coords.round().astype(int)
ncol, nrow, _ = np.amax(coords, axis=0) + 1
print 'new image size: {} x {}'.format(nrow, ncol)
if prevent_duplicate_pixels:
b = np.ascontiguousarray(coords).view(np.dtype((np.void, coords.dtype.itemsize * coords.shape[1])))
_, coord_idx = np.unique(b, return_index=True)
print np.shape(imzml_in.coordinates), np.shape(coord_idx)
print "original number of spectra: {}".format(len(coords))
else:
coord_idx = range(len(coords))
n_total = len(coord_idx)
print 'spectra to write: {}'.format(n_total)
with ImzMLWriter(output_filename, mz_dtype=mz_dtype, intensity_dtype=int_dtype) as imzml_out:
done = 0
for key in range(np.shape(imzml_in.coordinates)[0]):
print key
if all((prevent_duplicate_pixels, key not in coord_idx)): # skip duplicate pixels
continue
mzs, intensities = imzml_in.getspectrum(key)
if apodization:
from pyMSpec import smoothing
# todo - add to processing list in imzml
mzs, intensities = smoothing.apodization(mzs, intensities, {'w_size':w_size})
mzs_c, intensities_c, _ = gradient(mzs, intensities, min_intensity=min_intensity)
pos = coords[key]
if len(pos)==2:
pos.append(0)
pos = (pos[0], nrow - 1 - pos[1], pos[2])
imzml_out.addSpectrum(mzs_c, intensities_c, pos)
done += 1
if done % 1000 == 0:
print "[%s] progress: %.1f%%" % (input_filename, float(done) * 100.0 / n_total)
print "finished!"
| 7,455 |
def binary_dice_iou_score(
y_pred: torch.Tensor,
y_true: torch.Tensor,
mode="dice",
threshold=None,
nan_score_on_empty=False,
eps=1e-7,
ignore_index=None,
) -> float:
"""
Compute IoU score between two image tensors
:param y_pred: Input image tensor of any shape
:param y_true: Target image of any shape (must match size of y_pred)
:param mode: Metric to compute (dice, iou)
:param threshold: Optional binarization threshold to apply on @y_pred
:param nan_score_on_empty: If true, return np.nan if target has no positive pixels;
If false, return 1. if both target and input are empty, and 0 otherwise.
:param eps: Small value to add to denominator for numerical stability
:param ignore_index:
:return: Float scalar
"""
assert mode in {"dice", "iou"}
# Make binary predictions
if threshold is not None:
y_pred = (y_pred > threshold).to(y_true.dtype)
if ignore_index is not None:
mask = (y_true != ignore_index).to(y_true.dtype)
y_true = y_true * mask
y_pred = y_pred * mask
intersection = torch.sum(y_pred * y_true).item()
cardinality = (torch.sum(y_pred) + torch.sum(y_true)).item()
if mode == "dice":
score = (2.0 * intersection) / (cardinality + eps)
else:
score = intersection / (cardinality - intersection + eps)
has_targets = torch.sum(y_true) > 0
has_predicted = torch.sum(y_pred) > 0
if not has_targets:
if nan_score_on_empty:
score = np.nan
else:
score = float(not has_predicted)
return score
| 7,456 |
def test_glob_files_single_pattern(root_directory: str) -> None:
"""Test pattern matching while listing notebooks in a directory."""
data_directory = os.path.join(root_directory, "tests", "data")
nb_pattern = os.path.join("replace_images_in_markdown", "*.ipynb")
files = glob_files(data_directory, nb_pattern)
assert files == {
os.path.join(data_directory, nb_pattern).replace("*", nb_name) for nb_name in (
"html_and_markdown_images", "html_image", "image_and_code", "markdown_image")}
| 7,457 |
def get_uname_arch():
"""
Returns arch of the current host as the kernel would interpret it
"""
global _uname_arch # pylint: disable=global-statement
if not _uname_arch:
_uname_arch = detect_uname_arch()
return _uname_arch
| 7,458 |
def _getSTSToken() -> Tuple[str, BosClient, str]:
"""
Get the token to upload the file
:return:
"""
if not Define.hubToken:
raise Error.ArgumentError('Please provide a valid token', ModuleErrorCode, FileErrorCode, 4)
config = _invokeBackend("circuit/genSTS", {"token": Define.hubToken})
bosClient = BosClient(
BceClientConfiguration(
credentials=BceCredentials(
str(
config['accessKeyId']),
str(
config['secretAccessKey'])),
endpoint='http://bd.bcebos.com',
security_token=str(
config['sessionToken'])))
return Define.hubToken, bosClient, config['dest']
| 7,459 |
async def get_thumb_file(mass: MusicAssistant, url, size: int = 150):
"""Get path to (resized) thumbnail image for given image url."""
assert url
cache_folder = os.path.join(mass.config.data_path, ".thumbs")
cache_id = await mass.database.get_thumbnail_id(url, size)
cache_file = os.path.join(cache_folder, f"{cache_id}.png")
if os.path.isfile(cache_file):
# return file from cache
return cache_file
# no file in cache so we should get it
os.makedirs(cache_folder, exist_ok=True)
# download base image
async with mass.http_session.get(url, verify_ssl=False) as response:
assert response.status == 200
img_data = BytesIO(await response.read())
# save resized image
if size:
basewidth = size
img = Image.open(img_data)
wpercent = basewidth / float(img.size[0])
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save(cache_file, format="png")
else:
with open(cache_file, "wb") as _file:
_file.write(img_data.getvalue())
# return file from cache
return cache_file
| 7,460 |
def load_pickle(filename):
"""Load Pickfle file"""
filehandler = open(filename, 'rb')
return pickle.load(filehandler)
| 7,461 |
def columnize(s, header=None, width=40):
"""Dump an object and make each line the given width
The input data will run though `json.loads` in case it is a JSON object
Args:
s (str): Data to format
header (optional[str]): Header to prepend to formatted results
width (optional[int]): Max width of the resulting lines
Returns:
list[str]: List of formatted lines
"""
try:
j = json.loads(s)
except: # Assume that the value is a string
j = s
s = pformat(j, width=40)
ls = [l.ljust(width) for l in s.splitlines()]
if header is not None:
ls.insert(0, header.ljust(width))
ls.insert(1, '-' * width)
return ls
| 7,462 |
def create_eeg_epochs(config):
"""Create the data with each subject data in a dictionary.
Parameter
----------
subject : string of subject ID e.g. 7707
trial : HighFine, HighGross, LowFine, LowGross
Returns
----------
eeg_epoch_dataset : dataset of all the subjects with different conditions
"""
eeg_epoch_dataset = {}
for subject in config['subjects']:
data = nested_dict()
for trial in config['trials']:
epochs = eeg_epochs_dataset(subject, trial, config)
data['eeg'][trial] = epochs
eeg_epoch_dataset[subject] = data
return eeg_epoch_dataset
| 7,463 |
def restart():
"""Terminate the currently running instance of the script and start a new
one.
:command: `Reload <https://www.autohotkey.com/docs/commands/Reload.htm>`_
"""
# TODO: If the new script has an error, AHK will show it and quit. Instead,
# keep the old script running.
from . import launcher
sys.exit(launcher.EXIT_CODE_RESTART)
| 7,464 |
def to_newick(phylo):
"""
Returns a string representing the simplified Newick code of the input.
:param: `PhyloTree` instance.
:return: `str` instance.
"""
return phylo_to_newick_node(phylo).newick
| 7,465 |
def pipe(*functions):
"""
pipes functions one by one in the provided order
i.e. applies arg1, then arg2, then arg3, and so on
if any arg is None, just skips it
"""
return functools.reduce(
lambda f, g: lambda x: f(g(x)) if g else f(x),
functions[::-1],
lambda x: x) if functions else None
| 7,466 |
def remove_news_update(removed_update_name: str, expired: bool) -> None:
"""Removes any expired news articles or any articles that have been
manuallyremoved by the user.
If an update has expired, a loop is used to find the update and remove it
from the global list of updates. Otherwise, updates need to be removed
manually, this is done by searching for the removed udpate in the list
of updates and removing it from the scheduler queue (the event id is
assigned to a variable and then used to remove the update) and global list.
A try accept is used to catch any repeat upates that have already expired
(not in the update queue) but are still manually removed.
Args:
removed_update_name (str): The name of the update to be removed, given
as a string. This enables the update to be removed from the
scheduler queue (Allows for the event ID to be found) and is used
to ensure the correct update is removed, regardless of whether it
had expired or was manually removed.
expired (bool): A boolean value indicating whether or not a scheduled
update currently being displayed has already expired. Consequently
, this is used to help remove any expired updates.
Returns:
None: Global variables are the only thing altered during the execution
of the function, so nothing needs to be returned.
"""
logging.debug("Entering the remove_news_update function.")
# Expired updates are removed from the global list of articles.
if expired is True:
for update in news_queue_info:
if update['event_name'] == removed_update_name:
logging.info("Expired update removed from global list.")
news_queue_info.remove(update)
# Iterates through the global list of events, if the removed event.
# Is in the global list, it is removed from the queue and the list.
for update in news_queue_info:
if update["event_name"] == removed_update_name:
event_to_remove = update['event_id']
# Events must be in (and removed from) both the global list
# And the queue if the event has not expired.
news_queue_info.remove(update)
try:
news_scheduler.cancel(event_to_remove)
logging.info("Update removed from queue and list.")
except ValueError:
logging.warning("Repeat update removed from list.")
logging.debug("Exiting the remove_news_update function.")
return None
| 7,467 |
def initialize_graph_batch(batch_size):
""" Initialize a batch of empty graphs to begin the generation process.
Args:
batch_size (int) : Batch size.
Returns:
generated_nodes (torch.Tensor) : Empty node features tensor (batch).
generated_edges (torch.Tensor) : Empty edge features tensor (batch).
generated_n_nodes (torch.Tensor) : Number of nodes per graph in `nodes` and `edges`
(batch), currently all 0.
"""
# define tensor shapes
node_shape = ([batch_size + 1] + C.dim_nodes)
edge_shape = ([batch_size + 1] + C.dim_edges)
# initialize tensors
nodes = torch.zeros(node_shape, dtype=torch.float32, device="cuda")
edges = torch.zeros(edge_shape, dtype=torch.float32, device="cuda")
n_nodes = torch.zeros(batch_size + 1, dtype=torch.int64, device="cuda")
# add a dummy non-empty graph at top, since models cannot receive as input
# purely empty graphs
nodes[0] = torch.ones(([1] + C.dim_nodes), device="cuda")
edges[0, 0, 0, 0] = 1
n_nodes[0] = 1
return nodes, edges, n_nodes
| 7,468 |
def TimestampFromTicks(ticks):
"""Construct an object holding a timestamp value from the given ticks value
(number of seconds since the epoch).
This function is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
:rtype: :class:`datetime.datetime`
"""
return Timestamp(*localtime(ticks)[:6])
| 7,469 |
def extract_object_token(data, num_tokens, obj_list=[], verbose=True):
""" Builds a set that contains the object names. Filters infrequent tokens. """
token_counter = Counter()
for img in data:
for region in img['objects']:
for name in region['names']:
if not obj_list or name in obj_list:
token_counter.update([name])
tokens = set()
# pick top N tokens
token_counter_return = {}
for token, count in token_counter.most_common():
tokens.add(token)
token_counter_return[token] = count
if len(tokens) == num_tokens:
break
if verbose:
print(('Keeping %d / %d objects'
% (len(tokens), len(token_counter))))
return tokens, token_counter_return
| 7,470 |
def test_lambda_expressions():
"""Lambda 表达式"""
# 这个函数返回两个参数的和:lambda a, b: a+b
# 与嵌套函数定义一样,lambda函数可以引用包含范围内的变量。
def make_increment_function(delta):
"""本例使用 lambda 表达式返回函数"""
return lambda number: number + delta
increment_function = make_increment_function(42)
assert increment_function(0) == 42
assert increment_function(1) == 43
assert increment_function(2) == 44
# lambda 的另一种用法是将一个小函数作为参数传递。
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
# 按文本键对排序。
pairs.sort(key=lambda pair: pair[1])
assert pairs == [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
| 7,471 |
def test_dont_merge():
"""
Configuration support disabling recursive merging
"""
config = Configuration(
nested=dict(
__merge__=False,
nested_key="nested_value",
other_key="initial_value",
)
)
config.merge(
key="value",
nested=dict(
other_key="new_value",
),
)
assert_that(config.key, is_(equal_to("value")))
assert_that(
calling(getattr).with_args(config.nested, "nested_key"),
raises(AttributeError),
)
assert_that(config.nested.other_key, is_(equal_to("new_value")))
| 7,472 |
def _generate_with_relative_time(initial_state, condition, iterate, time_mapper) -> Observable:
"""Generates an observable sequence by iterating a state from an
initial state until the condition fails.
Example:
res = source.generate_with_relative_time(0, lambda x: True, lambda x: x + 1, lambda x: 0.5)
Args:
initial_state: Initial state.
condition: Condition to terminate generation (upon returning
false).
iterate: Iteration step function.
time_mapper: Time mapper function to control the speed of
values being produced each iteration, returning relative times, i.e.
either floats denoting seconds or instances of timedelta.
Returns:
The generated sequence.
"""
def subscribe(observer, scheduler=None):
scheduler = scheduler or timeout_scheduler
mad = MultipleAssignmentDisposable()
state = [initial_state]
has_result = [False]
result = [None]
first = [True]
time = [None]
def action(scheduler, _):
if has_result[0]:
observer.on_next(result[0])
try:
if first[0]:
first[0] = False
else:
state[0] = iterate(state[0])
has_result[0] = condition(state[0])
if has_result[0]:
result[0] = state[0]
time[0] = time_mapper(state[0])
except Exception as e:
observer.on_error(e)
return
if has_result[0]:
mad.disposable = scheduler.schedule_relative(time[0], action)
else:
observer.on_completed()
mad.disposable = scheduler.schedule_relative(0, action)
return mad
return Observable(subscribe)
| 7,473 |
def test_cache_model(app, authed_client):
"""Test that caching a model works."""
user = User.from_pk(1)
cache.cache_model(user, timeout=60)
user_data = cache.get('users_1')
assert user_data['id'] == 1
assert user_data['username'] == 'user_one'
assert user_data['enabled'] is True
assert user_data['inviter_id'] is None
| 7,474 |
def setup(bot: commands.Bot) -> None:
"""Starts owner cog."""
bot.add_cog(owner(bot))
| 7,475 |
def is_prime(num):
"""判断一个数是不是素数"""
for factor in range(2, int(num ** 0.5) + 1):
if num % factor == 0:
return False
return True if num != 1 else False
| 7,476 |
def ptcorr(y1, y2, dim=-1, eps=1e-8, **kwargs):
"""
Compute the correlation between two PyTorch tensors along the specified dimension(s).
Args:
y1: first PyTorch tensor
y2: second PyTorch tensor
dim: dimension(s) along which the correlation is computed. Any valid PyTorch dim spec works here
eps: offset to the standard deviation to avoid exploding the correlation due to small division (default 1e-8)
**kwargs: passed to final numpy.mean operatoin over standardized y1 * y2
Returns: correlation tensor
"""
y1 = (y1 - y1.mean(dim=dim, keepdim=True)) / (y1.std(dim=dim, keepdim=True) + eps)
y2 = (y2 - y2.mean(dim=dim, keepdim=True)) / (y2.std(dim=dim, keepdim=True) + eps)
return (y1 * y2).mean(dim=dim, **kwargs)
| 7,477 |
def discretize_time_difference(
times, initial_time, frequency, integer_timestamps=False
) -> typing.Sequence[int]:
"""method that discretizes sequence of datetimes (for prediction slices)
Arguments:
times {Sequence[datetime] or Sequence[float]} -- sequence of datetime objects
initial_time {datetime or float} -- last datetime instance from training set
(to offset test datetimes)
frequency {str} -- string alias representing granularity of pd.datetime object
Keyword Arguments:
integer_timestamps {bool} -- whether timestamps are integers or datetime values
Returns:
typing.Sequence[int] -- prediction intervals expressed at specific time granularity
"""
# take differences to convert to deltas
time_differences = times - initial_time
# edge case for integer timestamps
if integer_timestamps:
return time_differences.values.astype(int)
# convert to seconds representation
if type(time_differences.iloc[0]) is pd._libs.tslibs.timedeltas.Timedelta:
time_differences = time_differences.apply(lambda t: t.total_seconds())
if frequency == "YS":
return [round(x / S_PER_YEAR_0) for x in time_differences]
elif frequency == "MS" or frequency == 'M':
return [round(x / S_PER_MONTH_31) for x in time_differences]
elif frequency == "W":
return [round(x / S_PER_WEEK) for x in time_differences]
elif frequency == "D":
return [round(x / S_PER_DAY) for x in time_differences]
elif frequency == "H":
return [round(x / S_PER_HR) for x in time_differences]
else:
return [round(x / SECONDS_PER_MINUTE) for x in time_differences]
| 7,478 |
def pathlines(u_netcdf_filename,v_netcdf_filename,w_netcdf_filename,
startx,starty,startz,startt,
t,
grid_object,
t_max,delta_t,
u_netcdf_variable='UVEL',
v_netcdf_variable='VVEL',
w_netcdf_variable='WVEL',
u_grid_loc='U',v_grid_loc='V',w_grid_loc='W',
u_bias_field=None,
v_bias_field=None,
w_bias_field=None):
"""!A three-dimensional lagrangian particle tracker. The velocity fields must be four dimensional (three spatial, one temporal) and have units of m/s.
It should work to track particles forwards or backwards in time (set delta_t <0 for backwards in time). But, be warned, backwards in time hasn't been thoroughly tested yet.
Because this is a very large amount of data, the fields are passed as netcdffile handles.
The variables are:
* ?_netcdf_filename = name of the netcdf file with ?'s data in it.
* start? = intial value for x, y, z, or t.
* t = vector of time levels that are contained in the velocity data.
* grid_object is m.grid if you followed the standard naming conventions.
* ?_netcdf_variable = name of the "?" variable field in the netcdf file.
* t_max = length of time to track particles for, in seconds. This is always positive
* delta_t = timestep for particle tracking algorithm, in seconds. This can be positive or negative.
* ?_grid_loc = where the field "?" is located on the C-grid. Possibles options are, U, V, W, T and Zeta.
* ?_bias_field = bias to add to that velocity field omponent. If set to -mean(velocity component), then only the time varying portion of that field will be used.
"""
if u_grid_loc == 'U':
x_u = grid_object['Xp1'][:]
y_u = grid_object['Y'][:]
z_u = grid_object['Z'][:]
elif u_grid_loc == 'V':
x_u = grid_object['X'][:]
y_u = grid_object['Yp1'][:]
z_u = grid_object['Z'][:]
elif u_grid_loc == 'W':
x_u = grid_object['X'][:]
y_u = grid_object['Y'][:]
z_u = grid_object['Zl'][:]
elif u_grid_loc == 'T':
x_u = grid_object['X'][:]
y_u = grid_object['Y'][:]
z_u = grid_object['Z'][:]
elif u_grid_loc == 'Zeta':
x_u = grid_object['Xp1'][:]
y_u = grid_object['Yp1'][:]
z_u = grid_object['Z'][:]
else:
print 'u_grid_loc not set correctly. Possible options are: U,V,W,T, and Zeta'
return
if v_grid_loc == 'U':
x_v = grid_object['Xp1'][:]
y_v = grid_object['Y'][:]
z_v = grid_object['Z'][:]
elif v_grid_loc == 'V':
x_v = grid_object['X'][:]
y_v = grid_object['Yp1'][:]
z_v = grid_object['Z'][:]
elif v_grid_loc == 'W':
x_v = grid_object['X'][:]
y_v = grid_object['Y'][:]
z_v = grid_object['Zl'][:]
elif v_grid_loc == 'T':
x_v = grid_object['X'][:]
y_v = grid_object['Y'][:]
z_v = grid_object['Z'][:]
elif v_grid_loc == 'Zeta':
x_v = grid_object['Xp1'][:]
y_v = grid_object['Yp1'][:]
z_v = grid_object['Z'][:]
else:
print 'v_grid_loc not set correctly. Possible options are: U,V,W,T, and Zeta'
return
if w_grid_loc == 'U':
x_w = grid_object['Xp1'][:]
y_w = grid_object['Y'][:]
z_w = grid_object['Z'][:]
elif w_grid_loc == 'V':
x_w = grid_object['X'][:]
y_w = grid_object['Yp1'][:]
z_w = grid_object['Z'][:]
elif w_grid_loc == 'W':
x_w = grid_object['X'][:]
y_w = grid_object['Y'][:]
z_w = grid_object['Zl'][:]
elif w_grid_loc == 'T':
x_w = grid_object['X'][:]
y_w = grid_object['Y'][:]
z_w = grid_object['Z'][:]
elif w_grid_loc == 'Zeta':
x_w = grid_object['Xp1'][:]
y_w = grid_object['Yp1'][:]
z_w = grid_object['Z'][:]
else:
print 'w_grid_loc not set correctly. Possible options are: U,V,W,T, and Zeta'
return
len_x_u = len(x_u)
len_y_u = len(y_u)
len_z_u = len(z_u)
len_x_v = len(x_v)
len_y_v = len(y_v)
len_z_v = len(z_v)
len_x_w = len(x_w)
len_y_w = len(y_w)
len_z_w = len(z_w)
len_t = len(t)
if u_bias_field is None:
u_bias_field = np.zeros_like(grid_object['wet_mask_U'][:])
if v_bias_field is None:
v_bias_field = np.zeros_like(grid_object['wet_mask_V'][:])
if w_bias_field is None:
w_bias_field = np.zeros_like(grid_object['wet_mask_W'][:])
x_stream = np.ones((int(np.fabs(t_max/delta_t))+2))*startx
y_stream = np.ones((int(np.fabs(t_max/delta_t))+2))*starty
z_stream = np.ones((int(np.fabs(t_max/delta_t))+2))*startz
t_stream = np.ones((int(np.fabs(t_max/delta_t))+2))*startt
t_RK = startt #set the initial time to be the given start time
z_RK = startz
y_RK = starty
x_RK = startx
i=0
u_netcdf_filehandle = netCDF4.Dataset(u_netcdf_filename)
v_netcdf_filehandle = netCDF4.Dataset(v_netcdf_filename)
w_netcdf_filehandle = netCDF4.Dataset(w_netcdf_filename)
t_index = np.searchsorted(t,t_RK)
t_index_new = np.searchsorted(t,t_RK) # this is later used to test if new data needs to be read in.
if t_index == 0:
raise ValueError('Given time value is outside the given velocity fields - too small')
elif t_index == len_t:
raise ValueError('Given time value is outside the given velocity fields - too big')
# load fields in ready for the first run through the loop
# u
u_field,x_index_u,y_index_u,z_index_u = indices_and_field(x_u,y_u,z_u,
x_RK,y_RK,z_RK,t_index,
len_x_u,len_y_u,len_z_u,len_t,
u_netcdf_filehandle,u_netcdf_variable,u_bias_field)
u_field,x_index_u_new,y_index_u_new,z_index_u_new = indices_and_field(x_u,y_u,z_u,
x_RK,y_RK,z_RK,t_index,
len_x_u,len_y_u,len_z_u,len_t,
u_netcdf_filehandle,u_netcdf_variable,u_bias_field)
# v
v_field,x_index_v,y_index_v,z_index_v = indices_and_field(x_v,y_v,z_v,
x_RK,y_RK,z_RK,t_index,
len_x_v,len_y_v,len_z_v,len_t,
v_netcdf_filehandle,v_netcdf_variable,v_bias_field)
v_field,x_index_v_new,y_index_v_new,z_index_v_new = indices_and_field(x_v,y_v,z_v,
x_RK,y_RK,z_RK,t_index,
len_x_v,len_y_v,len_z_v,len_t,
v_netcdf_filehandle,v_netcdf_variable,v_bias_field)
# w
w_field,x_index_w,y_index_w,z_index_w = indices_and_field(x_w,y_w,z_w,
x_RK,y_RK,z_RK,t_index,
len_x_w,len_y_w,len_z_w,len_t,
w_netcdf_filehandle,w_netcdf_variable,w_bias_field)
w_field,x_index_w_new,y_index_w_new,z_index_w_new = indices_and_field(x_w,y_w,z_w,
x_RK,y_RK,z_RK,t_index,
len_x_w,len_y_w,len_z_w,len_t,
w_netcdf_filehandle,w_netcdf_variable,w_bias_field)
# Prepare for spherical polar grids
deg_per_m = np.array([1,1])
# Runge-Kutta fourth order method to estimate next position.
while i < np.fabs(t_max/delta_t):
#t_RK < t_max + startt:
if grid_object['grid_type']=='polar':
# use degrees per metre and convert all the velocities to degrees / second# calculate degrees per metre at current location - used to convert the m/s velocities in to degrees/s
deg_per_m = np.array([1./(1852.*60.),np.cos(starty*np.pi/180.)/(1852.*60.)])
# Compute indices at location given
if (y_index_u_new==y_index_u and
x_index_u_new==x_index_u and
z_index_u_new==z_index_u and
y_index_v_new==y_index_v and
x_index_v_new==x_index_v and
z_index_v_new==z_index_v and
y_index_w_new==y_index_w and
x_index_w_new==x_index_w and
z_index_w_new==z_index_w and
t_index_new == t_index):
# the particle hasn't moved out of the grid cell it was in.
# So the loaded field is fine; there's no need to reload it.
pass
else:
t_index = np.searchsorted(t,t_RK)
if t_index == 0:
raise ValueError('Given time value is outside the given velocity fields - too small')
elif t_index == len_t:
raise ValueError('Given time value is outside the given velocity fields - too big')
# for u
u_field,x_index_u,y_index_u,z_index_u = indices_and_field(x_u,y_u,z_u,
x_RK,y_RK,z_RK,t_index,
len_x_u,len_y_u,len_z_u,len_t,
u_netcdf_filehandle,u_netcdf_variable,u_bias_field)
# for v
v_field,x_index_v,y_index_v,z_index_v = indices_and_field(x_v,y_v,z_v,
x_RK,y_RK,z_RK,t_index,
len_x_v,len_y_v,len_z_v,len_t,
v_netcdf_filehandle,v_netcdf_variable,v_bias_field)
# for w
w_field,x_index_w,y_index_w,z_index_w = indices_and_field(x_w,y_w,z_w,
x_RK,y_RK,z_RK,t_index,
len_x_w,len_y_w,len_z_w,len_t,
w_netcdf_filehandle,w_netcdf_variable,w_bias_field)
# Interpolate velocities to initial location
u_loc = quadralinear_interp(x_RK,y_RK,z_RK,t_RK,
u_field,
x_u,y_u,z_u,t,
len_x_u,len_y_u,len_z_u,len_t,
x_index_u,y_index_u,z_index_u,t_index)
v_loc = quadralinear_interp(x_RK,y_RK,z_RK,t_RK,
v_field,
x_v,y_v,z_v,t,len_x_v,len_y_v,len_z_v,len_t,
x_index_v,y_index_v,z_index_v,t_index)
w_loc = quadralinear_interp(x_RK,y_RK,z_RK,t_RK,
w_field,
x_w,y_w,z_w,t,len_x_w,len_y_w,len_z_w,len_t,
x_index_w,y_index_w,z_index_w,t_index)
u_loc = u_loc*deg_per_m[1]
v_loc = v_loc*deg_per_m[0]
dx1 = delta_t*u_loc
dy1 = delta_t*v_loc
dz1 = delta_t*w_loc
u_loc1 = quadralinear_interp(x_RK + 0.5*dx1,y_RK + 0.5*dy1,z_RK + 0.5*dz1,t_RK + 0.5*delta_t,
u_field,
x_u,y_u,z_u,t,len_x_u,len_y_u,len_z_u,len_t,
x_index_u,y_index_u,z_index_u,t_index)
v_loc1 = quadralinear_interp(x_RK + 0.5*dx1,y_RK + 0.5*dy1,z_RK + 0.5*dz1,t_RK + 0.5*delta_t,
v_field,
x_v,y_v,z_v,t,len_x_v,len_y_v,len_z_v,len_t,
x_index_v,y_index_v,z_index_v,t_index)
w_loc1 = quadralinear_interp(x_RK + 0.5*dx1,y_RK + 0.5*dy1,z_RK + 0.5*dz1,t_RK + 0.5*delta_t,
w_field,
x_w,y_w,z_w,t,len_x_w,len_y_w,len_z_w,len_t,
x_index_w,y_index_w,z_index_w,t_index)
u_loc1 = u_loc1*deg_per_m[1]
v_loc1 = v_loc1*deg_per_m[0]
dx2 = delta_t*u_loc1
dy2 = delta_t*v_loc1
dz2 = delta_t*w_loc1
u_loc2 = quadralinear_interp(x_RK + 0.5*dx2,y_RK + 0.5*dy2,z_RK + 0.5*dz2,t_RK + 0.5*delta_t,
u_field,
x_u,y_u,z_u,t,len_x_u,len_y_u,len_z_u,len_t,
x_index_u,y_index_u,z_index_u,t_index)
v_loc2 = quadralinear_interp(x_RK + 0.5*dx2,y_RK + 0.5*dy2,z_RK + 0.5*dz2,t_RK + 0.5*delta_t,
v_field,
x_v,y_v,z_v,t,len_x_v,len_y_v,len_z_v,len_t,
x_index_v,y_index_v,z_index_v,t_index)
w_loc2 = quadralinear_interp(x_RK + 0.5*dx2,y_RK + 0.5*dy2,z_RK + 0.5*dz2,t_RK + 0.5*delta_t,
w_field,
x_w,y_w,z_w,t,len_x_w,len_y_w,len_z_w,len_t,
x_index_w,y_index_w,z_index_w,t_index)
u_loc2 = u_loc2*deg_per_m[1]
v_loc2 = v_loc2*deg_per_m[0]
dx3 = delta_t*u_loc2
dy3 = delta_t*v_loc2
dz3 = delta_t*w_loc2
u_loc3 = quadralinear_interp(x_RK + dx3,y_RK + dy3,z_RK + dz3,t_RK + delta_t,
u_field,
x_u,y_u,z_u,t,len_x_u,len_y_u,len_z_u,len_t,
x_index_u,y_index_u,z_index_u,t_index)
v_loc3 = quadralinear_interp(x_RK + dx3,y_RK + dy3,z_RK + dz3,t_RK + delta_t,
v_field,
x_v,y_v,z_v,t,len_x_v,len_y_v,len_z_v,len_t,
x_index_v,y_index_v,z_index_v,t_index)
w_loc3 = quadralinear_interp(x_RK + dx3,y_RK + dy3,z_RK + dz3,t_RK + delta_t,
w_field,
x_w,y_w,z_w,t,len_x_w,len_y_w,len_z_w,len_t,
x_index_w,y_index_w,z_index_w,t_index)
u_loc3 = u_loc3*deg_per_m[1]
v_loc3 = v_loc3*deg_per_m[0]
dx4 = delta_t*u_loc3
dy4 = delta_t*v_loc3
dz4 = delta_t*w_loc3
#recycle the variables to keep the code clean
x_RK = x_RK + (dx1 + 2*dx2 + 2*dx3 + dx4)/6
y_RK = y_RK + (dy1 + 2*dy2 + 2*dy3 + dy4)/6
z_RK = z_RK + (dz1 + 2*dz2 + 2*dz3 + dz4)/6
t_RK += delta_t
i += 1
x_stream[i] = x_RK
y_stream[i] = y_RK
z_stream[i] = z_RK
t_stream[i] = t_RK
t_index_new = np.searchsorted(t,t_RK)
x_index_w_new = np.searchsorted(x_w,x_RK)
y_index_w_new = np.searchsorted(y_w,y_RK)
if z_RK < 0:
z_index_w_new = np.searchsorted(-z_w,-z_RK)
else:
z_index_w_new = np.searchsorted(z_w,z_RK)
x_index_v_new = np.searchsorted(x_v,x_RK)
y_index_v_new = np.searchsorted(y_v,y_RK)
if z_RK < 0:
z_index_v_new = np.searchsorted(-z_v,-z_RK)
else:
z_index_v_new = np.searchsorted(z_v,z_RK)
x_index_u_new = np.searchsorted(x_u,x_RK)
y_index_u_new = np.searchsorted(y_u,y_RK)
if z_RK < 0:
z_index_u_new = np.searchsorted(-z_u,-z_RK)
else:
z_index_u_new = np.searchsorted(z_u,z_RK)
u_netcdf_filehandle.close()
v_netcdf_filehandle.close()
w_netcdf_filehandle.close()
return x_stream,y_stream,z_stream,t_stream
| 7,479 |
def firing_rate(x, theta=0.5, alpha=0.12):
""" Sigmoidal firing rate function
Parameters
----------
x : float
Mean membrane potential.
theta : float
Inflection point (mean firing activity) of sigmoidal curve (default
value 0.12)
alpha : float
Steepness of sigmoidal curve (default value 0.12)
Returns
-------
f : float
Firing rate of x.
"""
expo = np.exp((theta - x) / alpha)
f = 1 / (1 + expo)
return f
| 7,480 |
def plot_nn_pred_2D_extra_std(x, y_pred, y_target):
"""
x np.array(n_samples, n_tgrid, n_xgrid, dim_in)
y_pred np.array(n_samples, n_tgrid, n_xgrid, 1)
y_target np.array(n_samples, n_tgrid, n_xgrid, 1)
"""
n_samples = x.shape[0]
n_tgrid = x.shape[1]
n_xgrid = x.shape[2]
x_sample_id = 0
# Plot
fig, axs = plt.subplots(nrows=2, ncols=2, dpi=300)
colors = cm.get_cmap('tab20')
for idx, t in enumerate([0, int(n_tgrid/2), n_tgrid-1]):
# Pred
axs[0,0].plot(x[x_sample_id,t,:,1], np.mean(y_pred[:,t,:,0], axis=0),
color=colors.colors[2*idx], label=r'$\hat y(t_{'+str(t)+'})$')
axs[1,0].plot(x[x_sample_id,t,:,1], np.std(y_pred[:,t,:,0], axis=0),
color=colors.colors[2*idx], label=r'$\hat y(t_{'+str(t)+'})$')
# Target
axs[0,0].plot(x[x_sample_id,t,:,1], np.mean(y_target[:,t,:,0], axis=0),
color=colors.colors[2*idx+1], linewidth=4, linestyle=':', label=r'$y(t_{'+str(t)+'})$')
axs[1,0].plot(x[x_sample_id,t,:,1], np.std(y_target[:,t,:,0], axis=0),
color=colors.colors[2*idx+1], linewidth=4, linestyle=':', label=r'$y(t_{'+str(t)+'})$')
axs[1,0].set_xlabel(r'location, $x$')
axs[0,0].set_ylabel(r'$y$')
axs[1,0].set_ylabel(r'$\sigma(y)$')
#axs[0].set_ylim(-1, 1)
#axs[0,0].legend()
axs[1,0].legend()
for idx, xi in enumerate([0, int(n_xgrid/2), n_xgrid-1]):
# Plot predicted
axs[0,1].plot(x[x_sample_id,:,xi,0], np.mean(y_pred[:,:,xi,0], axis=0),
color=colors.colors[2*idx], label=r'$\hat y(x_{'+str(xi)+'})$')
axs[1,1].plot(x[x_sample_id,:,xi,0], np.std(y_pred[:,:,xi,0], axis=0),
color=colors.colors[2*idx], label=r'$\hat y(x_{'+str(xi)+'})$')
# Plot Target
axs[0,1].plot(x[x_sample_id,:,xi,0], np.mean(y_target[:,:,xi,0], axis=0),
color=colors.colors[2*idx+1], linewidth=4, linestyle=':', label=r'$y(x_{'+str(xi)+'})$')
axs[1,1].plot(x[x_sample_id,:,xi,0], np.mean(y_target[:,:,xi,0], axis=0),
color=colors.colors[2*idx+1], linewidth=4, linestyle=':', label=r'$y(x_{'+str(xi)+'})$')
axs[1,1].set_xlabel(r'time, $t$')
#axs[1].set_ylabel(r'$y$')
#axs[1].set_ylim(-1, 1)
#axs[0,1].legend()
axs[1,1].legend()
import pdb;pdb.set_trace()
fig.tight_layout()
fig.savefig('doc/figures/localAdvDiff/nn_pred_2D_extra_std.png')
plt.close(fig)
| 7,481 |
def generator2(Trainval_GT, Trainval_N, Pos_augment, Neg_select, augment_type, pattern_type, zero_shot_type, isalign,
epoch=0):
"""
:param Trainval_GT:
:param Trainval_N:
:param Pos_augment:
:param Neg_select:
:param augment_type:
:param pattern_type:
:return:
"""
# import skimage
# assert skimage.__version__ == '0.14.2', "The version of skimage might affect the speed largely. I use 0.14.2"
Neg_select1, Pos_augment1, inters_per_img = get_aug_params(Neg_select, Pos_augment, augment_type)
unseen_idx = get_unseen_index(zero_shot_type)
Trainval_N = get_new_Trainval_N(Trainval_N, zero_shot_type, unseen_idx)
print("generator2", inters_per_img, Pos_augment1, 'Neg_select:', Neg_select1, augment_type, 'zero shot:',
zero_shot_type)
import math
img_id_index_map = {}
for i, gt in enumerate(Trainval_GT):
img_id = gt[0]
if img_id in img_id_index_map:
img_id_index_map[img_id].append(i)
else:
img_id_index_map[img_id] = [i]
img_id_list = list(img_id_index_map.keys())
for k, v in img_id_index_map.items():
for i in range(math.ceil(len(v) * 1.0 / inters_per_img) - 1):
img_id_list.append(k)
import copy
import time
st = time.time()
count_time = 0
avg_time = 0
while True:
running_map = copy.deepcopy(img_id_index_map)
# print('Step: ', i)
np.random.shuffle(img_id_list)
for k in running_map.keys():
np.random.shuffle(running_map[k])
for img_id_tmp in img_id_list:
gt_ids = running_map[img_id_tmp][:inters_per_img]
running_map[img_id_tmp] = running_map[img_id_tmp][inters_per_img:]
Pattern_list = []
Human_augmented_list = []
Object_augmented_list = []
action_HO_list = []
num_pos_list = 0
mask_all_list = []
image_id = img_id_tmp
if image_id in [528, 791, 1453, 2783, 3489, 3946, 3946, 11747, 11978, 12677, 16946, 17833, 19218, 19218,
22347, 27293, 27584, 28514, 33683, 35399]:
# This is a list contain multiple objects within the same object box. It seems like wrong annotations.
# We remove those images. This do not affect the performance in our experiment.
continue
im_file = cfg.DATA_DIR + '/' + 'hico_20160224_det/images/train2015/HICO_train2015_' + (
str(image_id)).zfill(
8) + '.jpg'
# id, gt, h, o
# print(gt_ids, gt_ids[0], Trainval_GT[gt_ids[0]])
import cv2
import os
if not os.path.exists(im_file):
print('not exist', im_file)
continue
im = cv2.imread(im_file)
if im is None:
print('node', im_file)
continue
im_orig = im.astype(np.float32, copy=True)
im_orig -= cfg.PIXEL_MEANS
im_shape = im.shape
import os
# print('generate batch read image:', time.time() - st, "average;", avg_time)
for i in gt_ids:
GT = Trainval_GT[i]
# rare data
if zero_shot_type > 0:
has_rare = False
for label in GT[1]:
if label in unseen_idx:
has_rare = True
if has_rare:
continue
assert GT[0] == image_id
# im_orig = im_orig.reshape(1, im_shape[0], im_shape[1], 3)
cur_pos_augment = Pos_augment1
if augment_type > 1:
if i == gt_ids[-1]: # This must be -1
cur_neg_select = Neg_select1 * len(gt_ids)
else:
cur_neg_select = 0
else:
cur_neg_select = Neg_select1
# st1 = time.time()
Pattern, Human_augmented, Object_augmented, action_HO, num_pos = Augmented_HO_Neg_HICO(
GT,
Trainval_N,
im_shape,
Pos_augment=cur_pos_augment,
Neg_select=cur_neg_select,
pattern_type=pattern_type,
isalign=isalign)
# maintain same number of augmentation,
# print('generate batch read image:', i, time.time() - st1, cur_neg_select, len(Trainval_N[image_id]) if image_id in Trainval_N else 0)
Pattern_list.append(Pattern)
Human_augmented_list.append(Human_augmented)
Object_augmented_list.append(Object_augmented)
action_HO_list.append(action_HO)
num_pos_list += num_pos
# print('item:', Pattern.shape, num_pos)
if len(Pattern_list) <= 0:
continue
Pattern = np.concatenate(Pattern_list, axis=0)
Human_augmented = np.concatenate(Human_augmented_list, axis=0)
Object_augmented = np.concatenate(Object_augmented_list, axis=0)
action_HO = np.concatenate(action_HO_list, axis=0)
num_pos = num_pos_list
im_orig = np.expand_dims(im_orig, axis=0)
yield (im_orig, image_id, num_pos, Human_augmented, Object_augmented, action_HO, Pattern)
if augment_type < 0:
break
| 7,482 |
def map_points(pois, sample_size=-1, kwd=None, show_bbox=False, tiles='OpenStreetMap', width='100%', height='100%'):
"""Returns a Folium Map displaying the provided points. Map center and zoom level are set automatically.
Args:
pois (GeoDataFrame): A GeoDataFrame containing the POIs to be displayed.
sample_size (int): Sample size (default: -1; show all).
kwd (string): A keyword to filter by (optional).
show_bbox (bool): Whether to show the bounding box of the GeoDataFrame (default: False).
tiles (string): The tiles to use for the map (default: `OpenStreetMap`).
width (integer or percentage): Width of the map in pixels or percentage (default: 100%).
height (integer or percentage): Height of the map in pixels or percentage (default: 100%).
Returns:
A Folium Map object displaying the given POIs.
"""
# Set the crs to WGS84
pois = to_wgs84(pois)
# Filter by keyword
if kwd is None:
pois_filtered = pois
else:
pois_filtered = filter_by_kwd(pois, kwd)
# Pick a sample
if sample_size > 0 and sample_size < len(pois_filtered.index):
pois_filtered = pois_filtered.sample(sample_size)
# Automatically center the map at the center of the bounding box enclosing the POIs.
bb = bbox(pois_filtered)
map_center = [bb.centroid.y, bb.centroid.x]
# Initialize the map
m = folium.Map(location=map_center, tiles=tiles, width=width, height=height)
# Automatically set the zoom level
m.fit_bounds(([bb.bounds[1], bb.bounds[0]], [bb.bounds[3], bb.bounds[2]]))
# Create the marker cluster
locations = list(zip(pois_filtered.geometry.y.tolist(),
pois_filtered.geometry.x.tolist(),
pois_filtered.id.tolist(),
pois_filtered.name.tolist(),
pois_filtered.kwds.tolist()))
callback = """\
function (row) {
var icon, marker;
icon = L.AwesomeMarkers.icon({
icon: 'map-marker', markerColor: 'blue'});
marker = L.marker(new L.LatLng(row[0], row[1]));
marker.setIcon(icon);
var popup = L.popup({height: '300'});
popup.setContent(row[2] + '<br/>' + row[3] + '<br/>' + row[4]);
marker.bindPopup(popup);
return marker;
};
"""
m.add_child(folium.plugins.FastMarkerCluster(locations, callback=callback))
# Add pois to a marker cluster
#coords, popups = [], []
#for idx, poi in pois.iterrows():
# coords.append([poi.geometry.y, poi.geometry.x)]
# label = str(poi['id']) + '<br>' + str(poi['name']) + '<br>' + ' '.join(poi['kwds'])
# popups.append(folium.IFrame(label, width=300, height=100))
#poi_layer = folium.FeatureGroup(name='pois')
#poi_layer.add_child(MarkerCluster(locations=coords, popups=popups))
#m.add_child(poi_layer)
# folium.GeoJson(pois, tooltip=folium.features.GeoJsonTooltip(fields=['id', 'name', 'kwds'],
# aliases=['ID:', 'Name:', 'Keywords:'])).add_to(m)
if show_bbox:
folium.GeoJson(bb).add_to(m)
folium.LatLngPopup().add_to(m)
return m
| 7,483 |
def read_data_file():
"""
Reads Data file from datafilename given name
"""
datafile = open(datafilename, 'r')
old = datafile.read()
datafile.close()
return old
| 7,484 |
def squared_loss(y_hat, y):
"""均方损失。"""
return (y_hat - y.reshape(y_hat.shape))**2 / 2
| 7,485 |
def normalize_string(string, lowercase=True, convert_arabic_numerals=True):
"""
Normalize the given string for matching.
Example::
>>> normalize_string("tétéà 14ème-XIV, foobar")
'tetea XIVeme xiv, foobar'
>>> normalize_string("tétéà 14ème-XIV, foobar", False)
'tetea 14eme xiv, foobar'
:param string: The string to normalize.
:param lowercase: Whether to convert string to lowercase or not. Defaults
to ``True``.
:param convert_arabic_numerals: Whether to convert arabic numerals to roman
ones. Defaults to ``True``.
:return: The normalized string.
"""
# ASCIIfy the string
string = unidecode.unidecode(string)
# Replace any non-alphanumeric character by space
# Keep some basic punctuation to keep syntaxic units
string = re.sub(r"[^a-zA-Z0-9,;:]", " ", string)
# Convert to lowercase
if lowercase:
string = string.lower()
# Convert arabic numbers to roman numbers
if convert_arabic_numerals:
string = convert_arabic_to_roman_in_text(string)
# Collapse multiple spaces, replace tabulations and newlines by space
string = re.sub(r"\s+", " ", string)
# Trim whitespaces
string = string.strip()
return string
| 7,486 |
def find_sub_expression(
expression: Sequence[SnailfishElement],
) -> Sequence[SnailfishElement]:
"""Finds the outermost closed sub-expression in a subsequence."""
num_open_braces = 1
pos = 0
while num_open_braces > 0:
pos += 1
if expression[pos] == "[":
num_open_braces += 1
elif expression[pos] == "]":
num_open_braces -= 1
return expression[: pos + 1]
| 7,487 |
def printDebug(s, style=None):
"""
=> http://click.pocoo.org/5/utils/
EG
click.secho('Hello World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)
"""
msg = ">>[%s]debug>>: %s" % (strftime("%H:%M:%S"), s)
try:
if style == "comment":
click.secho(msg, fg='white')
elif style == "important":
click.secho(msg, bold=True)
else:
click.secho(msg)
except:
try:
print >> sys.stderr, msg
except:
pass
| 7,488 |
def set_secondary(typedef, fileobj, discovered):
"""
Pull over missing secondaryFiles to the job object entry.
Adapted from:
https://github.com/curoverse/arvados/blob/2b0b06579199967eca3d44d955ad64195d2db3c3/sdk/cwl/arvados_cwl/runner.py#L67
"""
if isinstance(fileobj, MutableMapping) and fileobj.get("class") == "File":
if "secondaryFiles" not in fileobj:
fileobj["secondaryFiles"] = cmap(
[{"location": substitute(fileobj["location"], sf),
"class": "File"} for sf in typedef["secondaryFiles"]])
if discovered is not None:
discovered[fileobj["location"]] = fileobj["secondaryFiles"]
elif isinstance(fileobj, MutableSequence):
for entry in fileobj:
set_secondary(typedef, entry, discovered)
| 7,489 |
def run_tha_test(manifest, cache_dir, remote, max_cache_size, min_free_space):
"""Downloads the dependencies in the cache, hardlinks them into a temporary
directory and runs the executable.
"""
cache = Cache(cache_dir, remote, max_cache_size, min_free_space)
outdir = tempfile.mkdtemp(prefix='run_tha_test')
try:
for filepath, properties in manifest['files'].iteritems():
infile = properties['sha-1']
outfile = os.path.join(outdir, filepath)
cache.retrieve(infile)
outfiledir = os.path.dirname(outfile)
if not os.path.isdir(outfiledir):
os.makedirs(outfiledir)
link_file(outfile, cache.path(infile), HARDLINK)
os.chmod(outfile, properties['mode'])
cwd = os.path.join(outdir, manifest['relative_cwd'])
if not os.path.isdir(cwd):
os.makedirs(cwd)
if manifest.get('read_only'):
make_writable(outdir, True)
cmd = manifest['command']
logging.info('Running %s, cwd=%s' % (cmd, cwd))
return subprocess.call(cmd, cwd=cwd)
finally:
# Save first, in case an exception occur in the following lines, then clean
# up.
cache.save()
rmtree(outdir)
cache.trim()
| 7,490 |
def _add_baseline(baseline_results, counts, doc, correct_ents, kb):
"""
Measure 3 performance baselines: random selection, prior probabilities, and 'oracle' prediction for upper bound.
Only evaluate entities that overlap between gold and NER, to isolate the performance of the NEL.
"""
for ent in doc.ents:
ent_label = ent.label_
start = ent.start_char
end = ent.end_char
offset = _offset(start, end)
gold_entity = correct_ents.get(offset, None)
# the gold annotations are not complete so we can't evaluate missing annotations as 'wrong'
if gold_entity is not None:
candidates = kb.get_candidates(ent.text)
oracle_candidate = ""
prior_candidate = ""
random_candidate = ""
if candidates:
scores = []
for c in candidates:
scores.append(c.prior_prob)
if c.entity_ == gold_entity:
oracle_candidate = c.entity_
best_index = scores.index(max(scores))
prior_candidate = candidates[best_index].entity_
random_candidate = random.choice(candidates).entity_
current_count = counts.get(ent_label, 0)
counts[ent_label] = current_count+1
baseline_results.update_baselines(
gold_entity,
ent_label,
random_candidate,
prior_candidate,
oracle_candidate,
)
| 7,491 |
def get_rec_attr(obj, attrstr):
"""Get attributes and do so recursively if needed"""
if attrstr is None:
return None
if "." in attrstr:
attrs = attrstr.split('.', maxsplit=1)
if hasattr(obj, attrs[0]):
obj = get_rec_attr(getattr(obj, attrs[0]), attrs[1])
else:
try:
obj = get_rec_attr(importlib.import_module(obj.__name__ + "." + attrs[0]), attrs[1])
except ImportError:
raise
else:
if hasattr(obj, attrstr):
obj = getattr(obj, attrstr)
return obj
| 7,492 |
def _get_message_mapping(types: dict) -> dict:
"""
Return a mapping with the type as key, and the index number.
:param types: a dictionary of types with the type name, and the message type
:type types: dict
:return: message mapping
:rtype: dict
"""
message_mapping = {}
entry_index = 2 # based on the links found, they normally start with 2?
for _type, message in types.items():
message_mapping[_type] = entry_index
entry_index += 1
return message_mapping
| 7,493 |
def _get_default_config_files_location():
"""Get the locations of the standard configuration files. These are
Unix/Linux:
1. `/etc/pywps.cfg`
2. `$HOME/.pywps.cfg`
Windows:
1. `pywps\\etc\\default.cfg`
Both:
1. `$PYWPS_CFG environment variable`
:returns: configuration files
:rtype: list of strings
"""
is_win32 = sys.platform == 'win32'
if is_win32:
LOGGER.debug('Windows based environment')
else:
LOGGER.debug('UNIX based environment')
if os.getenv("PYWPS_CFG"):
LOGGER.debug('using PYWPS_CFG environment variable')
# Windows or Unix
if is_win32:
PYWPS_INSTALL_DIR = os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))
cfgfiles = (os.getenv("PYWPS_CFG"))
else:
cfgfiles = (os.getenv("PYWPS_CFG"))
else:
LOGGER.debug('trying to estimate the default location')
# Windows or Unix
if is_win32:
PYWPS_INSTALL_DIR = os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))
cfgfiles = (os.path.join(PYWPS_INSTALL_DIR, "pywps", "etc", "pywps.cfg"))
else:
homePath = os.getenv("HOME")
if homePath:
cfgfiles = (os.path.join(pywps.__path__[0], "etc", "pywps.cfg"), "/etc/pywps.cfg",
os.path.join(os.getenv("HOME"), ".pywps.cfg"))
else:
cfgfiles = (os.path.join(pywps.__path__[0], "etc",
"pywps.cfg"), "/etc/pywps.cfg")
return cfgfiles
| 7,494 |
def cd(path):
"""
Change location to the provided path.
:param path: wlst directory to which to change location
:return: cmo object reference of the new location
:raises: PyWLSTException: if a WLST error occurs
"""
_method_name = 'cd'
_logger.finest('WLSDPLY-00001', path, class_name=_class_name, method_name=_method_name)
try:
result = wlst.cd(path)
except (wlst.WLSTException, offlineWLSTException), e:
raise exception_helper.create_pywlst_exception('WLSDPLY-00002', path, _get_exception_mode(e),
_format_exception(e), error=e)
_logger.finest('WLSDPLY-00003', path, result, class_name=_class_name, method_name=_method_name)
return result
| 7,495 |
def plt_roc_curve(y_true, y_pred, classes, writer, total_iters):
"""
:param y_true:[[1,0,0,0,0], [0,1,0,0], [1,0,0,0,0],...]
:param y_pred: [0.34,0.2,0.1] , 0.2,...]
:param classes:5
:return:
"""
fpr = {}
tpr = {}
roc_auc = {}
roc_auc_res = []
n_classes = len(classes)
for i in range(n_classes):
fpr[classes[i]], tpr[classes[i]], _ = roc_curve(y_true[:, i], y_pred[:, i])
roc_auc[classes[i]] = auc(fpr[classes[i]], tpr[classes[i]])
roc_auc_res.append(roc_auc[classes[i]])
fig = plt.figure()
lw = 2
plt.plot(fpr[classes[i]], tpr[classes[i]], color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[classes[i]])
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic beat {}'.format(classes[i]))
plt.legend(loc="lower right")
writer.add_figure('test/roc_curve_beat_{}'.format(classes[i]), fig, total_iters)
plt.close()
fig.clf()
fig.clear()
return roc_auc_res
| 7,496 |
def get_deps(sentence_idx: int, graph: DependencyGraph):
"""Get the indices of the dependants of the word at index sentence_idx
from the provided DependencyGraph"""
return list(chain(*graph.nodes[sentence_idx]['deps'].values()))
| 7,497 |
def incr(func):
"""
Increment counter
"""
@functools.wraps(func)
def wrapper(self):
# Strip off the "test_" from the function name
name = func.__name__[5:]
def _incr(counter, num):
salt.utils.process.appendproctitle("test_{}".format(name))
for _ in range(0, num):
counter.value += 1
attrname = "incr_" + name
setattr(self, attrname, _incr)
self.addCleanup(delattr, self, attrname)
return wrapper
| 7,498 |
def IgnoreSigint():
"""Ignores any future SIGINTs."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
| 7,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.