hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
63d7f9a0fc8895b2908acd7758b7421d434e3c58 | 5,097 | py | Python | Chapter 12/ch12_r03.py | PacktPublishing/Modern-Python-Cookbook | 40ff656c64421ddf6c288e058bb99a929f6d4c39 | [
"MIT"
] | 107 | 2016-11-30T02:13:39.000Z | 2022-03-31T06:38:59.000Z | Chapter 12/ch12_r03.py | fengfanzhiwu/Modern-Python-Cookbook | 8eff962f6eae514d531beca9051aefa34941ef4d | [
"MIT"
] | 2 | 2017-04-19T04:08:21.000Z | 2019-03-09T16:18:33.000Z | Chapter 12/ch12_r03.py | fengfanzhiwu/Modern-Python-Cookbook | 8eff962f6eae514d531beca9051aefa34941ef4d | [
"MIT"
] | 71 | 2017-01-16T06:35:17.000Z | 2022-03-01T21:25:54.000Z | """
{
"swagger": "2.0",
"info": {
"title": "Python Cookbook\\nChapter 12, recipe 3.",
"version": "1.0"
},
"schemes": "http",
"host": "127.0.0.1:5000",
"basePath": "/dealer",
"consumes": "application/json",
"produces": "application/json",
"paths": {
"/hands": {
"get": {
"parameters": [
{"name": "cards",
"in": "query",
"description": "number of cards in each hand",
"type": "array", "items": {"type": "integer"},
"collectionFormat": "multi",
"default": [13, 13, 13, 13]
}
],
"responses": {
"200": {
"description": "one hand of cards for each `hand` value in the query string"
}
}
}
},
"/hand": {
"get": {
"parameters": [
{"name": "cards", "in": "query", "type": "integer", "default": 5}
],
"responses": {
"200": {
"description": "One hand of cards with a size given by the `hand` value in the query string"
}
}
}
}
}
}
"""
import random
from ch12_r01 import Card, Deck
from flask import Flask, jsonify, request, abort
from http import HTTPStatus
dealer = Flask('dealer')
specification = {
'swagger': '2.0',
'info': {
'title': '''Python Cookbook\nChapter 12, recipe 3.''',
'version': '1.0'
},
'schemes': ['http'],
'host': '127.0.0.1:5000',
'basePath': '/dealer',
'consumes': ['application/json'],
'produces': ['application/json'],
'paths': {
'/hands': {
'get': {
'parameters': [
{
'name': 'cards',
'in': 'query',
'description': 'number of cards in each hand',
'type': 'array',
'items': {'type': 'integer'},
'collectionFormat': 'multi',
'default': [13, 13, 13, 13]
}
],
'responses': {
'200': {
'description': '''One hand of cards for each `hand` value in the query string'''
}
}
}
},
'/hand': {
'get': {
'parameters': [
{
'name': 'cards',
'in': 'query',
'type': 'integer',
'default': 5
}
],
'responses': {
'200': {
'description': '''One hand of cards with a size given by the `hand` value in the query string'''
}
}
}
}
}
}
import os
random.seed(os.environ.get('DEAL_APP_SEED'))
deck = Deck()
@dealer.before_request
def check_json():
if request.path == '/dealer/swagger.json':
return
if 'json' in request.headers.get('Accept', '*/*'):
return
if 'json' == request.args.get('$format', 'html'):
return
return abort(HTTPStatus.BAD_REQUEST)
from flask import send_file
# @dealer.route('/dealer/swagger.json')
def swagger1():
response = send_file('swagger.json', mimetype='application/json')
return response
from flask import make_response
# @dealer.route('/dealer/swagger.json')
def swagger2():
response = make_response(__doc__.encode('utf-8'))
response.headers['Content-Type'] = 'application/json'
return response
from flask import make_response
import json
@dealer.route('/dealer/swagger.json')
def swagger3():
response = make_response(json.dumps(specification, indent=2).encode('utf-8'))
response.headers['Content-Type'] = 'application/json'
return response
@dealer.route('/dealer/hand/')
def deal():
try:
hand_size = int(request.args.get('cards', 5))
assert 1 <= hand_size < 53
except Exception as ex:
abort(HTTPStatus.BAD_REQUEST)
cards = deck.deal(hand_size)
response = jsonify([card.to_json() for card in cards])
return response
@dealer.route('/dealer/hands/')
def multi_hand():
try:
hand_sizes = request.args.getlist('cards', type=int)
if len(hand_sizes) == 0:
hand_sizes = [13,13,13,13]
assert all(1 <= hand_size < 53 for hand_size in hand_sizes)
assert sum(hand_sizes) < 53
except Exception as ex:
dealer.logger.exception(ex)
abort(HTTPStatus.BAD_REQUEST)
hands = [deck.deal(hand_size) for hand_size in hand_sizes]
response = jsonify(
[
{'hand':i, 'cards':[card.to_json() for card in hand]}
for i, hand in enumerate(hands)
]
)
return response
if __name__ == "__main__":
dealer.run(use_reloader=True, threaded=False)
| 29.125714 | 120 | 0.476947 | 0 | 0 | 0 | 0 | 1,454 | 0.285266 | 0 | 0 | 2,312 | 0.4536 |
63d8ff7291ec00834c06722d6f791ed6401a8d77 | 158 | py | Python | Desafios/desafio053.py | josivantarcio/Desafios-em-Python | c747eed785b9640e15c498262fc5f8f5afd4337e | [
"MIT"
] | null | null | null | Desafios/desafio053.py | josivantarcio/Desafios-em-Python | c747eed785b9640e15c498262fc5f8f5afd4337e | [
"MIT"
] | 1 | 2021-04-23T15:11:11.000Z | 2021-05-21T22:36:56.000Z | Desafios/desafio053.py | josivantarcio/Desafios-em-Python | c747eed785b9640e15c498262fc5f8f5afd4337e | [
"MIT"
] | null | null | null | frase = str(input('Digite a frase: ')).strip().upper()
palavras = frase.split()
juntarPalavras = ''.join(palavras)
trocar = juntarPalavras[::-1]
print(trocar) | 31.6 | 54 | 0.702532 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | 0.126582 |
63dc294f098bbd41379d16d4e24791b73958a2ea | 1,345 | py | Python | python/examples/test_tds.py | dmillard/autogen | c14790f01b7e6ff4c140331317ad981c33e9b40f | [
"MIT"
] | 33 | 2021-10-29T21:33:39.000Z | 2022-03-31T11:02:43.000Z | python/examples/test_tds.py | dmillard/autogen | c14790f01b7e6ff4c140331317ad981c33e9b40f | [
"MIT"
] | 8 | 2021-08-13T07:01:05.000Z | 2021-11-16T19:07:33.000Z | python/examples/test_tds.py | dmillard/autogen | c14790f01b7e6ff4c140331317ad981c33e9b40f | [
"MIT"
] | 4 | 2021-10-31T10:59:44.000Z | 2021-11-06T07:21:45.000Z | import pytinydiffsim_ad as dp
import autogen as ag
import numpy as np
import math
TIME_STEPS = 20
def func(input_tau):
world = dp.TinyWorld()
world.friction = dp.ADScalar(1.0)
urdf_parser = dp.TinyUrdfParser()
urdf_data = urdf_parser.load_urdf("/root/tiny-differentiable-simulator/data/cartpole.urdf")
print("robot_name=",urdf_data.robot_name)
# b2vis = meshcat_utils_dp.convert_visuals(urdf_data, "~/tiny-differentiable-simulator/data/laikago/laikago_tex.jpg", vis, "../../data/laikago/")
is_floating=False
mb = dp.TinyMultiBody(is_floating)
urdf2mb = dp.UrdfToMultiBody2()
res = urdf2mb.convert2(urdf_data, world, mb)
dt = dp.ADScalar(1./1000.)
cost_output = np.ones(TIME_STEPS, dtype=ag.ADScalar)
for i in range(TIME_STEPS):
# print(type(input_tau[0]))
# convert to tds type
mb.tau[0] = input_tau[i].value()
dp.forward_dynamics(mb, world.gravity)
dp.integrate_euler(mb, dt)
# convert to ag type
pole_cost = math.sin(mb.q[1].value()) ** 2
cart_cost = (mb.q[0].value() / 2.4) ** 2
total_cost = pole_cost + cart_cost
cost_output[i] = ag.ADScalar(total_cost)
print('cost arr=', cost_output)
return cost_output
f = ag.trace(func, [1.0] * TIME_STEPS)
gen = ag.GeneratedCppAD(f)
x = [2.0] * TIME_STEPS
y = f.forward(x)
print("y = ", y)
J = f.jacobian(x)
print("j = ", J) | 28.617021 | 147 | 0.692193 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 305 | 0.226766 |
63dec534870631fac5a7cfc546198847fb5658b4 | 5,923 | py | Python | tf_rl/examples/NerveNet/network/ggnn.py | Rowing0914/TF2_RL | c1b7f9b376cbecf01deb17f76f8e761035ed336a | [
"MIT"
] | 8 | 2020-01-13T03:29:50.000Z | 2021-11-19T00:59:42.000Z | tf_rl/examples/NerveNet/network/ggnn.py | Rowing0914/TF2_RL | c1b7f9b376cbecf01deb17f76f8e761035ed336a | [
"MIT"
] | 5 | 2020-11-13T17:40:40.000Z | 2022-03-12T00:11:33.000Z | tf_rl/examples/NerveNet/network/ggnn.py | Rowing0914/TF2_RL | c1b7f9b376cbecf01deb17f76f8e761035ed336a | [
"MIT"
] | 1 | 2021-04-02T13:42:39.000Z | 2021-04-02T13:42:39.000Z | import tensorflow as tf
import tensorflow_probability as tfp
XAVIER_INIT = tf.contrib.layers.xavier_initializer()
class GRU_cell(tf.keras.Model):
def __init__(self, hidden_unit, output_nodes):
super(GRU_cell, self).__init__()
self.i_to_r = tf.keras.layers.Dense(hidden_unit, activation="sigmoid", kernel_initializer=XAVIER_INIT)
self.i_to_z = tf.keras.layers.Dense(hidden_unit, activation="sigmoid", kernel_initializer=XAVIER_INIT)
self.i_to_h = tf.keras.layers.Dense(hidden_unit, activation="tanh", kernel_initializer=XAVIER_INIT)
self.h_to_h = tf.keras.layers.Dense(hidden_unit, activation="linear", kernel_initializer=XAVIER_INIT)
self.h_to_o = tf.keras.layers.Dense(output_nodes, activation="tanh", kernel_initializer=XAVIER_INIT)
def call(self, x, previous_hidden_state):
z = self.i_to_z(x)
r = self.i_to_r(x)
h = self.i_to_h(x) + self.h_to_h(previous_hidden_state) * r
current_hidden_state = tf.multiply((1 - z), h) + tf.multiply(previous_hidden_state, z)
output = self.h_to_o(current_hidden_state)
return output, current_hidden_state
class GGNN(tf.keras.Model):
"""
Gated Graph Sequence Neural Networks (GGNN)
Implementation based on https://arxiv.org/abs/1511.05493
"""
def __init__(self, state_dim, node_info, rec_hidden_unit=30, rec_output_unit=30, recurrent_step=3, batch_size=32):
super(GGNN, self).__init__()
self.batch_size = batch_size
self.recurrent_step = recurrent_step
self.state_dim = state_dim
self.node_info = node_info
# Each type of nodes has its own mapping func
# num_node x obs(for each node)-> num_node x node_state_dim
self.obs_to_node_embed = {
node_id: tf.keras.layers.Dense(state_dim, activation="tanh", kernel_initializer=XAVIER_INIT)
for node_id in self.node_info["input_dict"]
}
# Each type of nodes has its own propagation func
# num_node x node_params_dim -> num_node x node_state_dim
self.processed_node_params = {
node_type: tf.keras.layers.Dense(state_dim, activation="tanh", kernel_initializer=XAVIER_INIT)(
tf.cast(self.node_info["node_parameters"][node_type], dtype=tf.float32)
)
for node_type in self.node_info["node_type_dict"]
}
self.processed_node_params = self._dict_to_matrix(self.node_info["node_type_dict"], self.processed_node_params)
# Update the internal memory
# num_node x node_state_dim -> num_node x node_state_dim
# self.recurrent_unit = tf.keras.layers.CuDNNGRU(state_dim, return_state=True, stateful=True)
self.recurrent_unit = GRU_cell(hidden_unit=rec_hidden_unit, output_nodes=rec_output_unit)
# Output Model
# num_node x hidden_dim -> num_node x 1(used to construct the mu for each action)
self.hidden_to_output = tf.keras.layers.Dense(1, activation="tanh", kernel_initializer=XAVIER_INIT)
# STD for Action Distribution(Gaussian)
self.sigmas = tf.Variable([0.3] * len(self.node_info["output_list"]))
# self.sigmas = tf.keras.layers.Dense(len(self.node_info["output_list"]), activation='linear', kernel_initializer=XAVIER_INIT)
def call(self, obs):
# step 1: Mapping Observation to Node Embedding
node_embed = {
node_id: self.obs_to_node_embed[node_id](self._gather_obs_at_node(obs, node_id))
for node_id in self.node_info["input_dict"]
}
node_embed = self._dict_to_matrix(self.node_info["input_dict"], node_embed)
# Concat information
if len(node_embed.shape) == 3:
# (batch_size x num_node x node_state_dim), (batch_size x num_node x node_state_dim)
# => batch_size x num_node x node_state_dim*2
hidden_state = tf.concat([[self.processed_node_params]*self.batch_size, node_embed], axis=-1)
else:
# (num_node x node_state_dim), (num_node x node_state_dim) => num_node x node_state_dim*2
hidden_state = tf.concat([self.processed_node_params, node_embed], axis=-1)
prop_state = list()
for t in range(self.recurrent_step):
# step 2: Message Exchanging for each edge type
# (num_node x num_node) x (num_node x node_state_dim*2) -> num_node x node_state_dim*2
for edge in self.node_info["edge_type_list"]:
prop_state.append(tf.compat.v1.linalg.matmul(self.node_info["adjacency_matrix"][edge], hidden_state))
# step 4: Aggregate Exchanged Messages
# num_edge_type x (num_node x node_state_dim) -> num_node x node_state_dim*2
msgs = tf.math.reduce_sum(prop_state, axis=0)
# step 5: Recurrent Update
# num_node x node_state_dim*2 -> num_node x node_state_dim*2
output, hidden_state = self.recurrent_unit(msgs, hidden_state)
# step 6: Readout function
output = self.hidden_to_output(hidden_state)
# step 7: Construct the Gaussian distribution over the action
means = tf.gather(tf.reshape(output, output.shape[:-1]), self.node_info["output_list"], axis=-1)
actions = tfp.distributions.Normal(loc=means, scale=self.sigmas).sample(1)
return actions
def _gather_obs_at_node(self, state, node_id):
return tf.gather(state, self.node_info["input_dict"][node_id], axis=-1)
def _dict_to_matrix(self, loop_list, item):
for i, data in enumerate(loop_list):
if i == 0:
temp = item[data]
else:
if len(item[data].shape) == 3: # in the case of batch learning
temp = tf.concat([temp, item[data]], axis=1)
else:
temp = tf.concat([temp, item[data]], axis=0)
return tf.cast(temp, dtype=tf.float32)
| 48.950413 | 134 | 0.668749 | 5,802 | 0.979571 | 0 | 0 | 0 | 0 | 0 | 0 | 1,716 | 0.289718 |
63df36dd82f3b996a2b0bac96c47e201bb8f3bbf | 98 | py | Python | docsie_universal_importer/providers/google_drive/__init__.py | Zarif99/test-universal | 062972ed64d9f048de702ab1edf4025cffca2abb | [
"BSD-3-Clause"
] | null | null | null | docsie_universal_importer/providers/google_drive/__init__.py | Zarif99/test-universal | 062972ed64d9f048de702ab1edf4025cffca2abb | [
"BSD-3-Clause"
] | 16 | 2021-06-16T15:00:41.000Z | 2021-06-30T11:57:15.000Z | docsie_universal_importer/providers/google_drive/__init__.py | Zarif99/test-universal | 062972ed64d9f048de702ab1edf4025cffca2abb | [
"BSD-3-Clause"
] | 1 | 2021-11-17T19:24:45.000Z | 2021-11-17T19:24:45.000Z | default_app_config = 'docsie_universal_importer.providers.google_drive.apps.GoogleDriveAppConfig'
| 49 | 97 | 0.897959 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 76 | 0.77551 |
63e0394902396da9e64268bf1086a084ded28c6f | 3,312 | py | Python | agent/h42backup/h42backup/container.py | gilles67/h42-backup | 24dcc6dad784b7a8f3586824bba801fc3333cb58 | [
"MIT"
] | null | null | null | agent/h42backup/h42backup/container.py | gilles67/h42-backup | 24dcc6dad784b7a8f3586824bba801fc3333cb58 | [
"MIT"
] | null | null | null | agent/h42backup/h42backup/container.py | gilles67/h42-backup | 24dcc6dad784b7a8f3586824bba801fc3333cb58 | [
"MIT"
] | null | null | null | import docker, json
VALID_PROFILE = ['volume', 'mariadb']
def backup_list():
client = docker.DockerClient(base_url='unix://var/run/docker.sock')
bck = {}
for ct in client.containers.list(all=True):
is_backup = False
error = []
if 'one.h42.backup.enable' in ct.labels:
if ct.labels['one.h42.backup.enable'] == 'true':
is_backup = True
if is_backup:
ctb = bck[ct.name] = {}
ctb['profile'] = "volume"
if 'one.h42.backup.profile' in ct.labels:
if ct.labels['one.h42.backup.profile'] in VALID_PROFILE:
profile = ctb['profile'] = ct.labels['one.h42.backup.profile']
else:
profile = ctb['profile'] = 'invalid'
error.append("H42backup: invalid profile detected! one.h42.backup.profile=" + ct.labels['one.h42.backup.profile'] + ".")
if profile == 'volume':
vol_ignore = []
if 'one.h42.backup.volume.ignore' in ct.labels:
vol_ignore = ctb['volume_ignore'] = ct.labels['one.h42.backup.volume.ignore'].split(',')
include_bind = False
if 'one.h42.backup.volume.include_bind' in ct.labels:
if ct.labels['one.h42.backup.volume.include_bind'] == 'true':
include_bind = ctb['volume_include_bind'] = True
mounts = ctb['mounts'] = []
for vol in ct.attrs['Mounts']:
if vol['Type'] == 'bind' and include_bind:
mounts.append({'type': 'bind', 'dest': vol['Destination']})
if vol['Type'] == 'volume':
ignore = vol['Name'] in vol_ignore
mounts.append({'type': 'volume', 'dest': vol['Destination'], 'name': vol['Name'], 'ignore': ignore })
if profile == 'mariadb':
backup_volume = None
if 'one.h42.backup.mariadb.volume' in ct.labels:
backup_volume = ctb['mariadb_backup_volume'] = ct.labels['one.h42.backup.mariadb.volume']
else:
error.append('Mariadb: backup volume not define, "one.h42.backup.mariadb.volume" docker label not exists or is empty.')
if backup_volume:
mounts = ctb['mounts'] = []
for vol in ct.attrs['Mounts']:
if vol['Type'] == 'volume' and vol['Name'] == backup_volume:
mounts.append({'type': 'volume', 'dest': vol['Destination'], 'name': vol['Name'],'ignore': False })
if len(mounts) == 0:
error.append('Mariadb: backup volume ' + backup_volume + ' not found in docker mount list.')
if len(error):
ctb['error'] = error
return bck
def backup_run(bck):
client = docker.DockerClient(base_url='unix://var/run/docker.sock')
vols = bck.getDockerVolumes()
ctr = client.containers.run(
image='h42-backup/agent',
command='/h42backup/h42-backup-agent backup exec --name={}'.format(bck.name),
auto_remove=True,
network_mode='bridge',
volumes=vols
)
return ctr
| 43.578947 | 140 | 0.520833 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,078 | 0.325483 |
63e23b1440c3348f5642d4b2129b21ed8312660c | 7,309 | py | Python | testarch/unet/runs.py | weihao94/deepdyn | e8a1d6620f48094b76ea3d272c57d40c9ae6d949 | [
"MIT"
] | 42 | 2019-11-07T03:18:53.000Z | 2021-12-08T09:42:00.000Z | testarch/unet/runs.py | LucasLee-ff/deepdyn | 48018b62a245dd791e45d60b28068489a8c32742 | [
"MIT"
] | 17 | 2020-01-25T12:58:18.000Z | 2022-03-11T23:32:44.000Z | testarch/unet/runs.py | aksish/ature | 48018b62a245dd791e45d60b28068489a8c32742 | [
"MIT"
] | 21 | 2019-11-21T08:34:54.000Z | 2022-02-27T16:24:00.000Z | import copy
import os
import random
import numpy as np
sep = os.sep
####################### GLOBAL PARAMETERS ##################################################
############################################################################################
Params = {
'num_channels': 1,
'num_classes': 2,
'batch_size': 4,
'epochs': 251,
'learning_rate': 0.001,
'patch_shape': (388, 388),
'patch_offset': (150, 150),
'expand_patch_by': (184, 184),
'use_gpu': True,
'distribute': True,
'shuffle': True,
'log_frequency': 5,
'validation_frequency': 1,
'mode': 'train',
'parallel_trained': False,
}
dparm_1_100_1 = lambda x: np.random.choice(np.arange(1, 101, 1), 2)
dparm_1_1 = lambda x: [1, 1]
d_parm_weighted = lambda x: [x['Params']['cls_weights'][0], x['Params']['cls_weights'][1]]
##############################################################################################
DRIVE = {
'Params': Params,
'Dirs': {
'image': 'data' + sep + 'DRIVE' + sep + 'images',
'mask': 'data' + sep + 'DRIVE' + sep + 'mask',
'truth': 'data' + sep + 'DRIVE' + sep + 'manual',
'splits_json': 'data' + sep + 'DRIVE' + sep + 'splits'
},
'Funcs': {
'truth_getter': lambda file_name: file_name.split('_')[0] + '_manual1.gif',
'mask_getter': lambda file_name: file_name.split('_')[0] + '_mask.gif'
}
}
DRIVE_1_100_1 = copy.deepcopy(DRIVE)
DRIVE_1_100_1['Dirs']['logs'] = 'logs' + sep + 'DRIVE' + sep + 'UNET_1_100_1'
DRIVE_1_100_1['Funcs']['dparm'] = dparm_1_100_1
DRIVE_1_1 = copy.deepcopy(DRIVE)
DRIVE_1_1['Dirs']['logs'] = 'logs' + sep + 'DRIVE' + sep + 'UNET_1_1'
DRIVE_1_1['Funcs']['dparm'] = dparm_1_1
DRIVE_WEIGHTED = copy.deepcopy(DRIVE)
DRIVE_WEIGHTED['Dirs']['logs'] = 'logs' + sep + 'DRIVE' + sep + 'UNET_WEIGHTED'
DRIVE_WEIGHTED['Funcs']['dparm'] = d_parm_weighted
# --------------------------------------------------------------------------------------------
WIDE = {
'Params': Params,
'Dirs': {
'image': 'data' + sep + 'AV-WIDE' + sep + 'images',
'truth': 'data' + sep + 'AV-WIDE' + sep + 'manual',
'splits_json': 'data' + sep + 'AV-WIDE' + sep + 'splits'
},
'Funcs': {
'truth_getter': lambda file_name: file_name.split('.')[0] + '_vessels.png',
'mask_getter': None
}
}
WIDE_1_100_1 = copy.deepcopy(WIDE)
WIDE_1_100_1['Dirs']['logs'] = 'logs' + sep + 'AV_WIDE' + sep + 'UNET_1_100_1'
WIDE_1_100_1['Funcs']['dparm'] = dparm_1_100_1
WIDE_1_1 = copy.deepcopy(WIDE)
WIDE_1_1['Dirs']['logs'] = 'logs' + sep + 'AV_WIDE' + sep + 'UNET_1_1'
WIDE_1_1['Funcs']['dparm'] = dparm_1_1
WIDE_WEIGHTED = copy.deepcopy(WIDE)
WIDE_WEIGHTED['Dirs']['logs'] = 'logs' + sep + 'AV_WIDE' + sep + 'UNET_WEIGHTED'
WIDE_WEIGHTED['Funcs']['dparm'] = d_parm_weighted
# ---------------------------------------------------------------------------------------------
STARE = {
'Params': Params,
'Dirs': {
'image': 'data' + sep + 'STARE' + sep + 'stare-images',
'truth': 'data' + sep + 'STARE' + sep + 'labels-ah',
'splits_json': 'data' + sep + 'STARE' + sep + 'splits'
},
'Funcs': {
'truth_getter': lambda file_name: file_name.split('.')[0] + '.ah.pgm',
'mask_getter': None
}
}
STARE_1_100_1 = copy.deepcopy(STARE)
STARE_1_100_1['Dirs']['logs'] = 'logs' + sep + 'STARE' + sep + 'UNET_1_100_1'
STARE_1_100_1['Funcs']['dparm'] = dparm_1_100_1
STARE_1_1 = copy.deepcopy(STARE)
STARE_1_1['Dirs']['logs'] = 'logs' + sep + 'STARE' + sep + 'UNET_1_1'
STARE_1_1['Funcs']['dparm'] = dparm_1_1
STARE_WEIGHTED = copy.deepcopy(STARE)
STARE_WEIGHTED['Dirs']['logs'] = 'logs' + sep + 'STARE' + sep + 'UNET_WEIGHTED'
STARE_WEIGHTED['Funcs']['dparm'] = d_parm_weighted
# ------------------------------------------------------------------------------------------------
CHASEDB = {
'Params': Params,
'Dirs': {
'image': 'data' + sep + 'CHASEDB' + sep + 'images',
'truth': 'data' + sep + 'CHASEDB' + sep + 'manual',
'splits_json': 'data' + sep + 'CHASEDB' + sep + 'splits'
},
'Funcs': {
'truth_getter': lambda file_name: file_name.split('.')[0] + '_1stHO.png',
'mask_getter': None
}
}
CHASEDB_1_100_1 = copy.deepcopy(CHASEDB)
CHASEDB_1_100_1['Dirs']['logs'] = 'logs' + sep + 'CHASEDB' + sep + 'UNET_1_100_1'
CHASEDB_1_100_1['Funcs']['dparm'] = dparm_1_100_1
CHASEDB_1_1 = copy.deepcopy(CHASEDB)
CHASEDB_1_1['Dirs']['logs'] = 'logs' + sep + 'CHASEDB' + sep + 'UNET_1_1'
CHASEDB_1_1['Funcs']['dparm'] = dparm_1_1
CHASEDB_WEIGHTED = copy.deepcopy(CHASEDB)
CHASEDB_WEIGHTED['Dirs']['logs'] = 'logs' + sep + 'CHASEDB' + sep + 'UNET_WEIGHTED'
CHASEDB_WEIGHTED['Funcs']['dparm'] = d_parm_weighted
# -------------------------------------------------------------------------------------------------
VEVIO_MOSAICS = {
'Params': Params,
'Dirs': {
'image': 'data' + sep + 'VEVIO' + sep + 'mosaics',
'mask': 'data' + sep + 'VEVIO' + sep + 'mosaics_masks',
'truth': 'data' + sep + 'VEVIO' + sep + 'mosaics_manual_01_bw',
'splits_json': 'data' + sep + 'VEVIO' + sep + 'splits_mosaics'
},
'Funcs': {
'truth_getter': lambda file_name: 'bw_' + file_name.split('.')[0] + '_black.' + file_name.split('.')[1],
'mask_getter': lambda file_name: 'mask_' + file_name
}
}
VEVIO_MOSAICS_1_100_1 = copy.deepcopy(VEVIO_MOSAICS)
VEVIO_MOSAICS_1_100_1['Dirs']['logs'] = 'logs' + sep + 'VEVIO_MOSAICS' + sep + 'UNET_1_100_1'
VEVIO_MOSAICS_1_100_1['Funcs']['dparm'] = dparm_1_100_1
VEVIO_MOSAICS_1_1 = copy.deepcopy(VEVIO_MOSAICS)
VEVIO_MOSAICS_1_1['Dirs']['logs'] = 'logs' + sep + 'VEVIO_MOSAICS' + sep + 'UNET_1_1'
VEVIO_MOSAICS_1_1['Funcs']['dparm'] = dparm_1_1
VEVIO_MOSAICS_WEIGHTED = copy.deepcopy(VEVIO_MOSAICS)
VEVIO_MOSAICS_WEIGHTED['Dirs']['logs'] = 'logs' + sep + 'VEVIO_MOSAICS' + sep + 'UNET_WEIGHTED'
VEVIO_MOSAICS_WEIGHTED['Funcs']['dparm'] = d_parm_weighted
# ---------------------------------------------------------------------------------------------------------
VEVIO_FRAMES = {
'Params': Params,
'Dirs': {
'image': 'data' + sep + 'VEVIO' + sep + 'frames',
'mask': 'data' + sep + 'VEVIO' + sep + 'frames_masks',
'truth': 'data' + sep + 'VEVIO' + sep + 'frames_manual_01_bw',
'splits_json': 'data' + sep + 'VEVIO' + sep + 'splits_frames'
},
'Funcs': {
'truth_getter': lambda file_name: 'bw_' + file_name.split('.')[0] + '_black.' + file_name.split('.')[1],
'mask_getter': lambda file_name: 'mask_' + file_name
}
}
VEVIO_FRAMES_1_100_1 = copy.deepcopy(VEVIO_FRAMES)
VEVIO_FRAMES_1_100_1['Dirs']['logs'] = 'logs' + sep + 'VEVIO_FRAMES' + sep + 'UNET_1_100_1'
VEVIO_FRAMES_1_100_1['Funcs']['dparm'] = dparm_1_100_1
VEVIO_FRAMES_1_1 = copy.deepcopy(VEVIO_FRAMES)
VEVIO_FRAMES_1_1['Dirs']['logs'] = 'logs' + sep + 'VEVIO_FRAMES' + sep + 'UNET_1_1'
VEVIO_FRAMES_1_1['Funcs']['dparm'] = dparm_1_1
VEVIO_FRAMES_WEIGHTED = copy.deepcopy(VEVIO_FRAMES)
VEVIO_FRAMES_WEIGHTED['Dirs']['logs'] = 'logs' + sep + 'VEVIO_FRAMES' + sep + 'UNET_WEIGHTED'
VEVIO_FRAMES_WEIGHTED['Funcs']['dparm'] = d_parm_weighted
# -------------------------------------------------------------------------------------------------------------
| 36.914141 | 112 | 0.543166 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,234 | 0.442468 |
63e27f210990b9b90b5a11bf73d8896f5729b462 | 3,673 | py | Python | mysql_table_generator.py | zed31/mongo_vs_mysql | 53c84c40a5f316b05445b1d9baf329c4ea85aa97 | [
"MIT"
] | null | null | null | mysql_table_generator.py | zed31/mongo_vs_mysql | 53c84c40a5f316b05445b1d9baf329c4ea85aa97 | [
"MIT"
] | null | null | null | mysql_table_generator.py | zed31/mongo_vs_mysql | 53c84c40a5f316b05445b1d9baf329c4ea85aa97 | [
"MIT"
] | null | null | null | #!/usr/bin/python3
import MySQLdb
from sys import argv, exit
from random import choice
arr_prefix = [
"sit",
"eiusmod",
"nulla",
"tempor",
"exercitation",
"Lorem",
"consectetur",
"qui",
"aute",
"laborum",
"culpa",
"sunt",
"sunt",
"enim",
"cupidatat",
"ipsum",
"nulla",
"consectetur",
"minim",
"ipsum",
"sunt",
"ut",
"qui",
"fugiat",
"culpa",
"et",
"aliqua",
"veniam",
"ipsum",
"in",
"occaecat",
"excepteur",
"eu",
"est",
"excepteur",
"magna",
"nisi",
"duis",
"cillum",
"culpa",
"et"
]
arr_suffix = [
"sunt",
"labore",
"id",
"sint",
"aliqua",
"commodo",
"veniam",
"nostrud",
"voluptate",
"dolore",
"laborum",
"est",
"est",
"in",
"elit",
"eu",
"pariatur",
"nulla",
"laboris",
"sunt",
"nostrud",
"reprehenderit",
"commodo",
"occaecat",
"et",
"ex",
"in",
"irure",
"adipisicing",
"reprehenderit",
"excepteur",
"duis",
"in",
"pariatur",
"labore",
"qui",
"cillum",
"eu",
"laborum",
"anim",
"et",
"officia",
"velit",
"irure",
"ipsum",
"ad",
"labore"
]
arr_end = [
"sint",
"officia",
"veniam",
"veniam",
"labore",
"est",
"pariatur",
"non",
"nulla",
"consectetur",
"officia",
"exercitation",
"mollit",
"reprehenderit",
"Lorem",
"nulla",
"aliqua",
"aute",
"incididunt",
"Lorem",
"veniam",
"in",
"consequat",
"cupidatat",
"culpa",
"eiusmod",
"sit",
"amet",
"ad",
"fugiat",
"ipsum",
"labore",
"anim",
"magna",
"enim",
"non",
"ea",
"labore",
"in",
"duis",
"qui",
"ullamco",
"Lorem",
"cillum",
"laborum",
"consectetur",
"esse",
"excepteur",
"eu"
]
company_table = "DROP TABLE IF EXISTS offer;\n\
DROP TABLE IF EXISTS company;\n\
CREATE TABLE company (\n\
id int not null primary key,\n\
name varchar(255),\n\
address varchar(255),\n\
about varchar(255),\n\
financial varchar(255),\n\
ceo varchar(255)\n\
);\n\
INSERT INTO company(id, name, address, about, financial, ceo) VALUES"
offer_table = "\
CREATE TABLE offer (\n\
id int not null primary key,\n\
name varchar(255),\n\
address varchar(255),\n\
about varchar(255),\n\
email varchar(255),\n\
company_fk_id int not null,\n\
foreign key (company_fk_id) references company(id)\n\
);\n\
INSERT INTO offer(id, name, address, about, email, company_fk_id) VALUES"
def generate_offer(id, name, address, about, email, company_id):
return "( " + str(id) + ", \"" + str(name) + "\", \"" + str(address) + "\", \"" + str(about) + "\", \"" + str(email) + "\", \"" + str(company_id) + "\" )"
def generate_company(id, name, address, about, financial, ceo):
return "( " + str(id) + ", \"" + str(name) + "\", \"" + str(address) + "\", \"" + str(about) + "\", \"" + str(financial) + "\", \"" + str(ceo) + "\" )"
def compose():
return choice(arr_prefix) + choice(arr_prefix) + choice(arr_end)
def main(nbr_entries, output):
final_table = company_table + ''.join([generate_company(x, compose(), compose(), compose(), compose(), compose()) + ',' for x in range(0, nbr_entries + 1)])
final_table = final_table[:-1] + ';\n'
final_table += offer_table
final_table = final_table + ''.join([generate_offer(x, compose(), compose(), compose(), compose(), x) + ',' for x in range(0, nbr_entries + 1)])
final_table = final_table[:-1] + ';\n'
print(final_table)
with open(output, 'w') as ofs:
ofs.write(final_table)
if __name__=='__main__':
if len(argv) != 3:
print("Usage:", argv[0], "<NB_ENTRIES> <OUTPUT_FILE>")
exit(0)
main(int(argv[1]), argv[2])
| 18.183168 | 160 | 0.553771 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,893 | 0.515383 |
63e3b897fe069846ad271c86ccffde7cfa2ad187 | 1,964 | py | Python | tests/test_database.py | rahulg/mongorm | 511611dc68b444317e8e3fe4a9e07cfe5d5032a2 | [
"BSD-2-Clause"
] | 4 | 2015-06-22T05:16:39.000Z | 2018-10-10T15:33:08.000Z | tests/test_database.py | rahulg/mongorm | 511611dc68b444317e8e3fe4a9e07cfe5d5032a2 | [
"BSD-2-Clause"
] | null | null | null | tests/test_database.py | rahulg/mongorm | 511611dc68b444317e8e3fe4a9e07cfe5d5032a2 | [
"BSD-2-Clause"
] | null | null | null | import unittest
from mongorm import Database
class DatabaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db = Database(uri='mongodb://localhost:27017/orm_test')
cls.db2 = Database(host='localhost', port=27017, db='orm_test2')
@classmethod
def tearDownClass(cls):
cls.db.drop()
cls.db2.drop()
def test_init_with_uri(self):
self.assertEquals(self.db.host, 'localhost')
self.assertEquals(self.db.port, 27017)
def test_init_with_hostport(self):
self.assertEquals(self.db2.host, 'localhost')
self.assertEquals(self.db2.port, 27017)
def test_default_db(self):
self.assertEquals(self.db.name, 'orm_test')
self.assertEquals(self.db2.name, 'orm_test2')
def test_default_connection(self):
db = Database()
self.assertEquals(db.host, 'localhost')
self.assertEquals(db.port, 27017)
self.assertEquals(db.name, 'test')
def test_drop_collection_from_str(self):
class SomeTestClass(self.db.Document):
pass
t = SomeTestClass()
t.test_val = 44
t.save()
colls = self.db.get_collections()
self.assertIn('some_test_class', colls)
self.db.drop_collection('some_test_class')
colls = self.db.get_collections()
self.assertNotIn('some_test_class', colls)
def test_drop_collection_from_obj(self):
class SomeTestClass(self.db.Document):
pass
t = SomeTestClass()
t.test_val = 44
t.save()
colls = self.db.get_collections()
self.assertIn('some_test_class', colls)
self.db.drop_collection(SomeTestClass)
colls = self.db.get_collections()
self.assertNotIn('some_test_class', colls)
def test_drop_collection_typeerror(self):
self.assertRaises(
TypeError,
self.db.drop_collection,
5
)
| 27.277778 | 72 | 0.63391 | 1,915 | 0.975051 | 0 | 0 | 263 | 0.13391 | 0 | 0 | 203 | 0.10336 |
63e423f755852b992268e18edda0f5773e6503d3 | 760 | py | Python | heap/binary_heap_test.py | dyc-it/algorithm | 68b866c9bf5ee2b479be124d70d2362144d568bb | [
"Apache-2.0"
] | null | null | null | heap/binary_heap_test.py | dyc-it/algorithm | 68b866c9bf5ee2b479be124d70d2362144d568bb | [
"Apache-2.0"
] | null | null | null | heap/binary_heap_test.py | dyc-it/algorithm | 68b866c9bf5ee2b479be124d70d2362144d568bb | [
"Apache-2.0"
] | null | null | null | import unittest
import random
from binary_heap import BinaryHeap
class TestBinaryHeap(unittest.TestCase):
def setUp(self):
size = 8
self.random_list = random.sample(range(0, size), size)
print "random list generated: " + str(self.random_list)
self.heap = BinaryHeap(size)
for key in self.random_list:
if not self.heap.is_full():
self.heap.insert(key)
def tearDown(self):
pass
def test_delete_min(self):
order_list = sorted(self.random_list)
index = 0
while not self.heap.is_empty():
min_value = self.heap.delete_min()
print min_value
self.assertEqual(min_value, order_list[index])
index += 1
| 24.516129 | 63 | 0.607895 | 689 | 0.906579 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0.032895 |
63e5242ca320b82cfe9f818b9dabb8b7721af332 | 22,418 | py | Python | src/alfred3/element/action.py | mate-code/alfred | e687e9318ecefe3a49565027841ca8d910647978 | [
"MIT"
] | 9 | 2020-05-11T08:13:12.000Z | 2022-01-20T11:35:14.000Z | src/alfred3/element/action.py | mate-code/alfred | e687e9318ecefe3a49565027841ca8d910647978 | [
"MIT"
] | 77 | 2019-02-22T07:34:58.000Z | 2022-02-23T15:32:34.000Z | src/alfred3/element/action.py | mate-code/alfred | e687e9318ecefe3a49565027841ca8d910647978 | [
"MIT"
] | 6 | 2020-11-11T16:51:04.000Z | 2022-02-21T10:29:02.000Z | """
Provides elements that make stuff happen.
.. moduleauthor: Johannes Brachem <jbrachem@posteo.de>
"""
from typing import Union
from typing import List
from uuid import uuid4
import cmarkgfm
from cmarkgfm.cmark import Options as cmarkgfmOptions
from emoji import emojize
from ..exceptions import AlfredError
from .._helper import inherit_kwargs
from .core import jinja_env
from .core import _Choice
from .core import Row
from .core import Element
from .misc import JavaScript
from .input import SingleChoiceButtons
from .input import SingleChoiceBar
from .input import SingleChoiceList
from .input import SelectPageList
@inherit_kwargs
class SubmittingButtons(SingleChoiceButtons):
"""
SingleChoiceButtons that trigger submission of the current page
on click.
Args:
*choice_labels: Variable numbers of choice labels. See
:class:`.ChoiceElement` for details.
{kwargs}
Examples:
Using submitting buttons together with the
:class:`.HideNavigation` element::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
name = "demo"
def on_exp_access(self):
self += al.HideNavigation()
self += al.SubmittingButtons("choice1", "choice2", name="b1")
"""
js_template = jinja_env.get_template("js/submittingbuttons.js.j2")
def __init__(self, *choice_labels, **kwargs):
super().__init__(*choice_labels, **kwargs)
def prepare_web_widget(self):
super().prepare_web_widget()
self._js_code = []
js = self.js_template.render(choices=self.choices)
self.add_js(js)
@inherit_kwargs
class SubmittingBar(SingleChoiceBar):
"""
SingleChoiceButtons that trigger submission of the current page
on click.
Args:
*choice_labels: Variable numbers of choice labels. See
:class:`.ChoiceElement` for details.
{kwargs}
Examples:
Using submitting buttons together with the
:class:`.HideNavigation` element::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
name = "demo"
def on_exp_access(self):
self += al.HideNavigation()
self += al.SubmittingButtons("choice1", "choice2", name="b1")
"""
js_template = jinja_env.get_template("js/submittingbuttons.js.j2")
def __init__(self, *choice_labels, **kwargs):
super().__init__(*choice_labels, **kwargs)
def prepare_web_widget(self):
super().prepare_web_widget()
self._js_code = []
js = self.js_template.render(choices=self.choices)
self.add_js(js)
@inherit_kwargs
class JumpButtons(SingleChoiceButtons):
"""
SingleChoiceButtons that trigger jumps to specific pages on click.
Each button can target a different page.
Args:
*choice_labels: Tuples of the form ``("label", "target_name")``,
where "label" is the text that will be displayed and
"target_name" is the name of the page that the experiment
will jump to on click of the button.
{kwargs}
Attributes:
targets (str): List of target page names.
Examples:
Simple jump buttons::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo1(al.Page):
name = "demo1"
def on_exp_access(self):
self += al.JumpButtons(
("jump to demo2", "demo2"),
("jump to demo3", "demo3"),
name="jump1"
)
@exp.member
class Demo2(al.Page):
name = "demo2"
@exp.member
class Demo3(al.Page):
name = "demo3"
Jump buttons with target page taken from the input on a previous
page, using the :meth:`.Page.on_first_show` hook::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo1(al.Page):
name = "demo1"
def on_exp_access(self):
self += al.TextEntry(toplab="Enter target page name", name="text1")
@exp.member
class Demo2(al.Page):
name = "demo2"
def on_first_show(self):
target = self.exp.values.get("text1")
self += al.JumpButtons(("jump to target", target), name="jump1")
@exp.member
class Demo3(al.Page):
name = "demo3"
"""
#: JavaScript template for the code that submits the form on click
js_template = jinja_env.get_template("js/jumpbuttons.js.j2")
def __init__(self, *choice_labels, button_style: Union[str, list] = "btn-primary", **kwargs):
super().__init__(*choice_labels, button_style=button_style, **kwargs)
self.choice_labels, self.targets = map(list, zip(*choice_labels))
def prepare_web_widget(self):
super().prepare_web_widget()
if self.page.prefix_element_names and not self.page.has_been_shown:
self.targets = [self.page.name + "_" + target for target in self.targets]
self._js_code = []
for choice, target in zip(self.choices, self.targets):
js = self.js_template.render(id=choice.id, target=target)
self.add_js(js)
def validate_data(self):
if not self.should_be_shown:
return True
cond1 = bool(self.input) if self.force_input else True
return cond1
@inherit_kwargs
class DynamicJumpButtons(JumpButtons):
"""
JumpButtons, where the target pages depend on the input to
other elements on the same page.
Args:
*choice_labels: Tuples of the form ``("label", "element_name")``,
where "label" is the text that will be displayed and
"element_name" is the name of the element on the *same page*,
whose input value will be inserted as the name of the target
page.
{kwargs}
Attributes:
targets (str): List of target page names.
Examples:
::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo1(al.Page):
name = "demo1"
def on_exp_access(self):
self += al.TextEntry(toplab="Enter a target page", name="text1")
self += al.DynamicJumpButtons(("Jump", "text1"), name="jump1")
@exp.member
class Demo2(al.Page):
name = "demo2"
@exp.member
class Demo3(al.Page):
name = "demo3"
"""
# Documented at :class:`.JumpButtons`
js_template = jinja_env.get_template("js/dynamic_jumpbuttons.js.j2")
def validate_data(self):
return True
# cond1 = bool(self.data) if self.force_input else True
# cond2 = True
# for target in self.targets:
# value = self.experiment.data.get(target, None)
# cond2 = value in self.experiment.root_section.all_pages
# if not cond2:
# break
# cond2 = all([target in self.experiment.root_section.all_pages for target in self.targets])
# return cond1 and cond2
@inherit_kwargs
class JumpList(Row):
"""
Allows participants to select a page from a dropdown menu and jump
to it.
Args:
scope: Can be 'exp', or a section name. If *scope* is 'exp', all
pages in the experiment are listed as choices. If *scope* is
a section name, all pages in that section are listed.
include_self: Whether to include the current page in the list,
if it is in scope.
check_jumpto: If *True* (default), pages that cannot be jumped
to will be marked as disabled options. The evaluation is
based on the :attr:`.Section.allow_jumpto` attribute of
each page's direct parent section (and only that section).
check_jumpfrom: If *True*, the element will check, if the
current page can be left via jump. If not, all pages in the
list will be marked as disabled options.
show_all_in_scope: If *True* (default), all pages in the scope
will be shown, including those that cannot be jumped to.
display_page_name: If *True*, the page name will be displayed
in the select list. Defaults to *True*.
label: Label to display on the jump button.
button_style: Style of the jump button. See
:class:`.SingleChoiceButtons` for more details on this
argument.
button_round_corners: Boolean, determining whether the button
should have rounded corners.
debugmode: Boolean switch, telling the JumpList whether it
should operate in debug mode. In debugmode, *save_data*
defaults to *False*, i.e. the JumpList will not save any
data.
{kwargs}
Notes:
Different from other input-type elements, the JumpList does not
have to be named.
Examples:
Minimal example::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo1(al.Page):
name = "demo2"
def on_exp_access(self):
self += al.JumpList()
@exp.member
class Demo2(al.Page):
name = "demo2"
"""
def __init__(
self,
scope: str = "exp",
include_self: bool = False,
check_jumpto: bool = True,
check_jumpfrom: bool = True,
show_all_in_scope: bool = True,
label: str = "Jump",
button_style: Union[str, list] = "btn-dark",
button_round_corners: bool = False,
debugmode: bool = False,
display_page_name: bool = True,
**kwargs,
):
random_name = "jumplist_" + uuid4().hex
name = kwargs.get("name", random_name)
select_name = name + "_select"
btn_name = name + "_btn"
save_data = kwargs.pop("save_data", not debugmode)
select = SelectPageList(
scope=scope,
include_self=include_self,
name=select_name,
check_jumpto=check_jumpto,
check_jumpfrom=check_jumpfrom,
show_all_in_scope=show_all_in_scope,
display_page_name=display_page_name,
save_data=save_data
)
btn = DynamicJumpButtons(
(label, select.name),
name=btn_name,
button_style=button_style,
button_round_corners=button_round_corners,
save_data=save_data
)
super().__init__(select, btn, **kwargs)
self.layout.width_sm = [10, 2]
self.debugmode = debugmode
def prepare_web_widget(self):
super().prepare_web_widget()
if not self.page.section.allow_jumpfrom:
# disable button (disabling the list is controlled via init arguments of the list)
self.elements[1].disabled = True
if self.debugmode:
for el in self.elements:
el.disabled = False
@inherit_kwargs
class Button(Element):
"""
A button that triggers execution of a python function on click.
Args:
text (str): Button text
func (callable): Python function to be called on button click.
The function must take zero arguments, but it can be a
method of a class or instance.
followup (str): What to do after the python function was called.
Can take the following values:
- ``refresh`` submits and reloads the current page (default),
- ``none`` does nothing,
- ``forward`` submits the current page and moves forward,
- ``backward`` submits the current page and moves backward,
- ``jump>page_name`` submits the current page and triggers
a jump to a page with the name 'page_name'
- ``custom`` executes custom JavaScript. If you choose this
option, you must supply your custom JavaScript through the
argument *custom_js*.
submit_first (bool): If True, the current values of all input
elements on the current page will be saved on button click,
before *func* is called. This way, these values will be
available in *func* through :attr:`.ExperimentSession.values`,
if func has access to the ExperimentSession object.
See Example 3. Defaults to True.
button_style (str): Can be used for quick color-styling, using
Bootstraps default color keywords: btn-primary, btn-secondary,
btn-success, btn-info, btn-warning, btn-danger, btn-light,
btn-dark. You can also use the "outline" variant to get
outlined buttons (eg. "btn-outline-secondary"). Advanced users can
supply their own CSS classes for button-styling. Defaults
to "btn-primary".
button_round_corners (bool): A boolean switch to toggle whether
the button should be displayed with rounded corners. Defaults
to False.
button_block (bool): A boolean switch to toggle whether the button
should take up all horizontal space that is available. Can be
quite useful when arranging buttons in :class:`.Row`.
Defaults to False.
custom_js (str): Custom JavaScript to execute after the python
function specified in *func* was called. Only takes effect,
if *followup* is set to 'custom'.
{kwargs}
Notes:
Note that by default, the Button will not save data itself. If
you wish to save information about button clicks, you can utilize
the :attr:`.ExperimentSession.adata` dictionary in the button's
callable. See Example 4.
.. warning:: This element is very powerful. Remember that with great
power comes great responsibility. Be aware that the callable
*func* will be executed *every time* the button is clicked.
Examples:
Example 1: A minimal example that will print some text to your terminal
window on button click::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.Button("Demo Button", func=self.demo_function)
def demo_function(self):
print("\\nThis is a demonstration")
print(self.exp.exp_id)
print("\\n")
Example 2: An example with a jump after the function call::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.Button("Demo Button", func=self.demo_function, followup="jump>page3")
def demo_function(self):
print("\\nThis is a demonstration")
print(self.exp.exp_id)
print("\\n")
exp += al.Page(title="Page 2", name="page2")
exp += al.Page(title="Page 3", name="page3")
Example 3: An example that uses values entered on the current page::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.TextEntry(leftlab="Enter", name="entry1")
self += al.Button("Demo Button", func=self.demo_function)
def demo_function(self):
print("\\nThis is a demonstration")
print(self.exp.exp_id)
print(self.exp.values["entry1"])
print("\\n")
Example 4: An example that saves a count of how often the button
was clicked::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.Button("Demo Button", func=self.demo_function)
def demo_function(self):
print("\\nThis is a demonstration")
if "demo_button" in self.exp.adata:
self.exp.adata["demo_button"] += 1
else:
self.exp.adata["demo_button"] = 1
print("\\n")
"""
element_template = jinja_env.get_template("html/ActionButtonElement.html.j2")
js_template = jinja_env.get_template("js/actionbutton.js.j2")
def __init__(
self,
text: str,
func: callable,
followup: str = "refresh",
submit_first: bool = True,
button_style: str = "btn-primary",
button_round_corners: bool = False,
button_block: bool = False,
custom_js: str = "",
**kwargs):
super().__init__(**kwargs)
self.func = func
self.submit_first = submit_first
self.followup = followup
self.url = None
self.text = text
self.custom_js = custom_js
if not followup in {"refresh", "forward", "backward", "none", "custom"} and not followup.startswith("jump>"):
raise ValueError(f"{followup} is an inappropriate value for 'followup'.")
if self.followup == "custom" and not self.custom_js:
raise ValueError("If you set 'followup' to 'custom', you must specify custom Javascript to run.")
self.button_style = button_style
self.button_round_corners = button_round_corners
self.button_block = button_block
@property
def template_data(self):
d = super().template_data
text = emojize(self.text, use_aliases=True)
text = cmarkgfm.github_flavored_markdown_to_html(text, options=cmarkgfmOptions.CMARK_OPT_UNSAFE)
d["text"] = text
d["button_block"] = "btn-block" if self.button_block else ""
d["button_style"] = self.button_style
return d
def added_to_experiment(self, experiment):
super().added_to_experiment(experiment)
self.url = self.exp.ui.add_callable(self.func)
def prepare_web_widget(self):
self._js_code = []
d = {}
d["url"] = self.url
d["expurl"] = f"{self.exp.ui.basepath}/experiment"
d["followup"] = self.followup
d["custom_js"] = self.custom_js
d["name"] = self.name
d["submit_first"] = self.submit_first
d["set_data_url"] = self.exp.ui.set_page_data_url
js = self.js_template.render(d)
self.add_js(js)
# Round corners part
if self.button_round_corners:
self._css_code = []
css = f"#{ self.name } {{border-radius: 1rem;}}"
self.add_css(css)
@inherit_kwargs(exclude=["func", "submit_first", "custom_js"])
class BackButton(Button):
"""
A backward button.
Args:
text (str, optional): Button text. If *None* (default), alfred3
uses the default text for backward buttons from config.conf.
{kwargs}
Examples:
Simple usage::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.BackButton()
"""
def __init__(self,
text: str = None,
button_style: str = "btn-dark",
button_round_corners: bool = False,
button_block: bool = False,
**kwargs):
for arg in ["func", "submit_first", "custom_js"]:
val = kwargs.pop(arg, None)
if val is not None:
raise TypeError(f"{type(self).__name__} got an unexpected keyword argument '{arg}'")
super().__init__(text=text, button_style=button_style, button_round_corners=button_round_corners, button_block=button_block, followup= "backward", func=lambda: None, **kwargs)
def added_to_experiment(self, experiment):
super().added_to_experiment(experiment)
if self.text is None:
self.text = self.exp.config.get("navigation", "backward")
@inherit_kwargs(exclude=["func", "submit_first", "custom_js"])
class ForwardButton(Button):
"""
A forward button.
Args:
text (str, optional): Button text. If *None* (default), alfred3
uses the default text for forward buttons from config.conf.
{kwargs}
Examples:
Simple usage::
import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.ForwardButton()
"""
def __init__(self,
text: str = None,
button_style: str = "btn-dark",
button_round_corners: bool = False,
button_block: bool = False,
**kwargs):
for arg in ["func", "submit_first", "custom_js"]:
val = kwargs.pop(arg, None)
if val is not None:
raise TypeError(f"{type(self).__name__} got an unexpected keyword argument '{arg}'")
super().__init__(text=text, button_style=button_style, button_round_corners=button_round_corners, button_block=button_block, followup= "forward", func=lambda: None, **kwargs)
def added_to_experiment(self, experiment):
super().added_to_experiment(experiment)
if self.text is None:
self.text = self.exp.config.get("navigation", "forward")
| 32.442836 | 183 | 0.576724 | 21,539 | 0.96079 | 0 | 0 | 21,761 | 0.970693 | 0 | 0 | 14,784 | 0.65947 |
63e546527b43b6cd0426995d284ee250d0346d96 | 598 | py | Python | models/loss/vae_loss.py | PeterJaq/optical_film_toolbox | 0e2d2bfa5f1f93d405a2f25ee50e51771be777a5 | [
"Apache-2.0"
] | 4 | 2020-07-05T12:35:45.000Z | 2022-03-17T18:43:04.000Z | models/loss/vae_loss.py | PeterJaq/optical_film_toolbox | 0e2d2bfa5f1f93d405a2f25ee50e51771be777a5 | [
"Apache-2.0"
] | null | null | null | models/loss/vae_loss.py | PeterJaq/optical_film_toolbox | 0e2d2bfa5f1f93d405a2f25ee50e51771be777a5 | [
"Apache-2.0"
] | null | null | null | def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2. * np.pi)
return tf.reduce_sum(
-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),
axis=raxis)
def compute_loss(model, x):
mean, logvar = model.encode(x)
z = model.reparameterize(mean, logvar)
x_logit = model.decode(z)
cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logit, labels=x)
logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2, 3])
logpz = log_normal_pdf(z, 0., 0.)
logqz_x = log_normal_pdf(z, mean, logvar)
return -tf.reduce_mean(logpx_z + logpz - logqz_x) | 37.375 | 79 | 0.67893 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
63e5fd80b31040b98f86d3e9a1070894b979bab4 | 6,147 | py | Python | agent/main_runner.py | velteyn/agent57 | b0dd7b54fd4c3560b529fe196f62e9d51bfed82e | [
"MIT"
] | 48 | 2020-07-13T03:19:27.000Z | 2022-03-05T12:05:40.000Z | agent/main_runner.py | andreanvictor6374/agent57 | 175c8367254107d3f7e7ff12d40f01708b7ee75b | [
"MIT"
] | 10 | 2020-07-14T08:09:54.000Z | 2021-11-20T00:40:05.000Z | agent/main_runner.py | andreanvictor6374/agent57 | 175c8367254107d3f7e7ff12d40f01708b7ee75b | [
"MIT"
] | 14 | 2020-07-21T14:35:02.000Z | 2022-02-10T10:32:17.000Z | import gym
from keras.optimizers import Adam
import traceback
import os
from .dqn import DQN
from .agent57 import Agent57
from .model import InputType, DQNImageModel, LstmType
from .policy import AnnealingEpsilonGreedy
from .memory import PERRankBaseMemory, PERProportionalMemory
from .env_play import EpisodeSave, EpisodeReplay
from .callbacks import ConvLayerView, MovieLogger
from .callbacks import LoggerType, TimeStop, TrainLogger, ModelIntervalCheckpoint
from .callbacks import DisTrainLogger, DisSaveManager
def run_gym_dqn(
enable_train,
env,
env_name,
kwargs,
nb_steps=999_999_999,
nb_time=999_999_999,
logger_type=LoggerType.STEP,
log_interval=0,
test_env=None,
test_episodes=10,
load_weights="",
checkpoint_interval=0,
movie_save=False,
base_dir="tmp",
):
os.makedirs(base_dir, exist_ok=True)
weight_file = os.path.join(base_dir, "{}_weight.h5".format(env_name))
print("nb_steps: {}".format(nb_steps))
print("nb_time : {:.2f}m".format(nb_time/60))
agent = DQN(**kwargs)
print(agent.actor.actval_ext_model.summary())
if test_env is None:
test_agent = None
else:
test_agent = DQN(**kwargs)
log = TrainLogger(
logger_type,
interval=log_interval,
savefile=os.path.join(base_dir, "{}_log.json".format(env_name)),
test_agent=test_agent,
test_env=test_env,
test_episodes=test_episodes,
test_save_max_reward_file=weight_file+'_max_{step:02d}_{reward}.h5'
)
if enable_train:
print("--- start ---")
print("'Ctrl + C' is stop.")
try:
callbacks = [log]
if load_weights != "":
agent.load_weights(load_weights, load_memory=True)
if checkpoint_interval > 0:
callbacks.append(
ModelIntervalCheckpoint(
filepath = weight_file + '_{step:02d}.h5',
interval=checkpoint_interval,
save_memory=False,
)
)
callbacks.append(TimeStop(nb_time))
agent.fit(env, nb_steps=nb_steps, visualize=False, verbose=0, callbacks=callbacks)
except Exception:
print(traceback.print_exc())
raise
# save
print("weight save: " + weight_file)
agent.save_weights(weight_file, overwrite=True, save_memory=False)
# plt
log.drawGraph("step")
# 訓練結果を見る
if log.max_reward_file == "":
print("weight load: " + weight_file)
agent.load_weights(weight_file)
else:
print("weight load: " + log.max_reward_file)
agent.load_weights(log.max_reward_file)
agent.test(env, nb_episodes=5, visualize=True)
# 動画保存用
if movie_save:
movie = MovieLogger()
callbacks = [movie]
if kwargs["input_type"] != InputType.VALUES:
conv = ConvLayerView(agent)
callbacks.append(conv)
agent.test(env, nb_episodes=1, visualize=False, callbacks=callbacks)
movie.save(gifname="tmp/{}_1.gif".format(env_name), fps=30)
if kwargs["input_type"] != InputType.VALUES:
conv.save(grad_cam_layers=["c3"], add_adv_layer=True, add_val_layer=True,
end_frame=200, gifname="tmp/{}_2.gif".format(env_name), fps=10)
env.close()
def run_gym_agent57(
enable_train,
env,
env_name,
kwargs,
nb_trains=999_999_999,
nb_time=999_999_999,
logger_type=LoggerType.TIME,
log_interval=0,
test_env=None,
test_episodes=10,
is_load_weights=False,
checkpoint_interval=0,
movie_save=False,
):
base_dir = os.path.join("tmp_{}".format(env_name))
os.makedirs(base_dir, exist_ok=True)
print("nb_time : {:.2f}m".format(nb_time/60))
print("nb_trains: {}".format(nb_trains))
weight_file = os.path.join(base_dir, "{}_weight.h5".format(env_name))
manager = Agent57(**kwargs)
if test_env is None:
test_actor = None
else:
test_actor = kwargs["actors"][0]
log = DisTrainLogger(
logger_type,
interval=log_interval,
savedir=base_dir,
test_actor=test_actor,
test_env=test_env,
test_episodes=test_episodes,
test_save_max_reward_file=os.path.join(base_dir, 'max_{step:02d}_{reward}.h5')
)
if enable_train:
print("--- start ---")
print("'Ctrl + C' is stop.")
save_manager = DisSaveManager(
save_dirpath=base_dir,
is_load=is_load_weights,
save_memory=False,
checkpoint=(checkpoint_interval>0),
checkpoint_interval=checkpoint_interval,
verbose=0
)
manager.train(nb_trains, nb_time, callbacks=[save_manager, log])
# plt
log.drawGraph("train")
# 訓練結果を見る
agent = manager.createTestAgent(kwargs["actors"][0], "tmp_{}/last/learner.dat".format(env_name))
if agent is None:
return
agent.test(env, nb_episodes=5, visualize=True)
# 動画保存用
if movie_save:
movie = MovieLogger()
callbacks = [movie]
if kwargs["input_type"] != InputType.VALUES:
conv = ConvLayerView(agent)
callbacks.append(conv)
agent.test(env, nb_episodes=1, visualize=False, callbacks=callbacks)
movie.save(gifname="tmp/{}_1.gif".format(env_name), fps=30)
if kwargs["input_type"] != InputType.VALUES:
conv.save(grad_cam_layers=[], add_adv_layer=True, add_val_layer=True,
end_frame=200, gifname="tmp/{}_2.gif".format(env_name), fps=10)
env.close()
def run_play(env, episode_save_dir, processor, **kwargs):
es = EpisodeSave(env,
episode_save_dir=episode_save_dir,
processor=processor,
font="arial")
es.play(**kwargs)
env.close()
def run_replay(episode_save_dir, **kwargs):
r = EpisodeReplay(episode_save_dir, font="arial")
r.play(**kwargs)
| 29.271429 | 100 | 0.616561 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 590 | 0.095238 |
63e72dba0fb4b89d7e9e4db6bf070ba06e155aae | 1,473 | py | Python | Fred/7_Gestures/Reactions.py | ProjectHewitt/Fred_Inmoov | 179be5ba18c89fe6b2c64efc0b88c9db8e40b75b | [
"Apache-2.0"
] | 6 | 2021-02-25T02:14:56.000Z | 2021-06-13T16:13:00.000Z | Fred/7_Gestures/Reactions.py | ProjectHewitt/Fred_Inmoov | 179be5ba18c89fe6b2c64efc0b88c9db8e40b75b | [
"Apache-2.0"
] | null | null | null | Fred/7_Gestures/Reactions.py | ProjectHewitt/Fred_Inmoov | 179be5ba18c89fe6b2c64efc0b88c9db8e40b75b | [
"Apache-2.0"
] | 4 | 2021-02-07T00:14:32.000Z | 2021-10-02T03:32:44.000Z | ##############################################################
# Program Code for Fred Inmoov #
# Of the Cyber_One YouTube Channel #
# https://www.youtube.com/cyber_one #
# #
# This is version 5 #
# Divided up into sub programs #
# #
# Running on MyRobotLab (MRL) http://myrobotlab.org/ #
# Fred in a modified Inmmov robot, you can find all the #
# origonal files on the Inmoov web site. http://inmoov.fr/ #
# #
# 7_Gestures/Reactions.py #
# This file perform standard actions such as nodding Yes #
# or shaking the head No #
# #
##############################################################
import time
print "Creating the various gestures to make the robot appear alive"
def Yes():
PanTilt(0, -40, 0)
time.sleep(0.3)
PanTilt(0, 30, 0)
time.sleep(0.3)
PanTilt(0, -20, 0)
time.sleep(0.4)
PanTilt(0, 0, 0)
def No():
PanTilt(40, 0, 0)
time.sleep(0.3)
PanTilt(-40, 0, 0)
time.sleep(0.3)
PanTilt(40, 0, 0)
time.sleep(0.3)
PanTilt(0, 0, 0)
| 37.769231 | 68 | 0.376782 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,116 | 0.757637 |
63e79a57d87beb222b4d338e8505178a6b213db0 | 7,019 | py | Python | StormPyTwitter/src/main/multilang/resources/python/twitter_storm/twitter_components.py | juanrh/data42 | b42006917bfaf6bdf5aabf88f9b2714e879bf8f3 | [
"Apache-2.0"
] | 1 | 2016-04-06T09:21:42.000Z | 2016-04-06T09:21:42.000Z | StormPyTwitter/src/main/multilang/resources/python/twitter_storm/twitter_components.py | juanrh/data42 | b42006917bfaf6bdf5aabf88f9b2714e879bf8f3 | [
"Apache-2.0"
] | null | null | null | StormPyTwitter/src/main/multilang/resources/python/twitter_storm/twitter_components.py | juanrh/data42 | b42006917bfaf6bdf5aabf88f9b2714e879bf8f3 | [
"Apache-2.0"
] | 3 | 2015-12-14T00:16:31.000Z | 2019-03-24T13:35:55.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Based on storm.py module from https://github.com/nathanmarz/storm/blob/master/storm-core/src/multilang/py/storm.py, and the examples from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/multilang/resources/splitsentence.py and http://storm.incubator.apache.org/documentation/Tutorial.html
Packaging: To run a shell component on a cluster, the scripts that are shelled out to must be in the resources/ directory within the jar submitted to the master (https://github.com/nathanmarz/storm/wiki/Multilang-protocol). By default, Maven will look for your project's resources under src/main/resources (https://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html).
Tested in Python2.7 and Apache Storm 0.9.0.1
'''
import storm, tweepy
import json, time
from operator import itemgetter
import get_tweets
def log_tweeter_error(tweep_error, sleep_time=2):
'''
:param tweep_error: Exception dealing with twitter to log to the parent process
:type api: tweepy.TweepError
:param sleep_time: time in seconds to sleep before continuing the execution
'''
# We have hit the REST API Rate limit for Twitter https://dev.twitter.com/docs/rate-limiting/1.1, no more tweets for some time
storm.log("Tweepy error {error}, sleeping for {secs} seconds in case Twitter rate limit has been hit".format(error=str(tweep_error), secs=sleep_time))
time.sleep(sleep_time)
class PlacesSpout(storm.Spout):
'''
Emit a tuple with a single field for a place as encoded in the module get_tweets,
with the frequency specified in the storm configuration passed at initialize()
'''
# Field in the configuration map where the emision frequency is
# configured
_frequency_conf_key = "PlacesSpoutFrequency"
def initialize(self, conf, context):
# self._conf = conf
# self._context = context
self._places = get_tweets.available_places()
self._tick_frequency = conf[self.__class__._frequency_conf_key]
def nextTuple(self):
'''
Should adhere to the following contract expressed in the wrapping Java spout
declarer.declare(new Fields(TopologyFields.PLACE));
'''
# storm.log(json.dumps({ "conf" : self._conf}))
# storm.log(json.dumps({ "context" : self._context}))
for place in self._places:
storm.emit([place])
time.sleep(self._tick_frequency)
class TwitterBolt(storm.Bolt):
'''
This class extends storm.Bolt as no ack is handled because we are using a non reliable source with no defined id for the messages.
As additional functionality, a tweepy.api.API object ready to used is stored at self._twitter_api during initialization.
NOTE: don't forget to setup authentication calling "python2.7 get_tweets.py" __before__ compiling the topology: the auth file has to be included in the jar and copied to the cluster
'''
def initialize(self, stormconf, context):
# Init connection to twitter API
auth = get_tweets.authenticate(rebuild=False)
# Better fail here if we cannot even authenticate
self._twitter_api = tweepy.API(auth)
class TrendsBolt(TwitterBolt):
'''
Assumes each input tuple has a single field for the name of a place as encoded in get_tweets. This bolt emits tuples (place, trend name, query) for the trending topics at the coordinates corresponding to that place.
In case the Twitter REST API Rate limit is hit, this bolt sleeps for some seconds.
'''
_rate_limit_sleep_time = 1
def process(self, tuple):
place = tuple.values[0]
try:
trends = get_tweets.get_trending_topics_text(self._twitter_api, place)
except tweepy.TweepError as te:
# We have hit the REST API Rate limit for Twitter https://dev.twitter.com/docs/rate-limiting/1.1, no more tweets for some time
log_tweeter_error(te, sleep_time=self._rate_limit_sleep_time)
return
for trend in trends:
storm.emit([place, trend['name'], trend['query']])
class GetTweetsBolt(TwitterBolt):
'''
Assumes each input tuple is of the shape (place, topic_name, query) where query is a twitter query string for the trending topic topic_name. For each input tuple Twitter is queried for the most popular tweets, and some fields are projected from each resulting tweets and then emitted, see process() for details about the fields.
In case the Twitter REST API Rate limit is hit, this bolt sleeps for some seconds.
'''
@staticmethod
def _storm_tweet_processor(status):
shallow_fields = ['text', 'favorite_count', 'retweeted', 'in_reply_to_screen_name',
'retweet_count', 'possibly_sensitive', 'lang', 'created_at', 'source']
ret = {k : status.__dict__.get(k, None) for k in shallow_fields}
ret['created_at'] = ret['created_at'].strftime('%Y-%m-%d %H:%M:%S')
ret['author_screen_name'] = status.author.screen_name
ret['hashtags_texts'] = "|".join(sorted([hashtag['text'] for hashtag in status.entities['hashtags']]))
ret['place_full_name'] = status.place.full_name if not status.place is None else None
return ret
_rate_limit_sleep_time = 1
def process(self, tuple):
'''
Must fulfil the following contract expressed in the Java wrapper:
declarer.declare(new Fields(TopologyFields.AUTHOR_SCREEN_NAME, TopologyFields.CREATED_AT,
TopologyFields.FAV_COUNT, TopologyFields.HASHTAGS_TEXTS, TopologyFields.IN_REPLY_TO_SCREEN_NAME,
TopologyFields.LANG, TopologyFields.RETWEET_COUNT, TopologyFields.RETWEETED,
TopologyFields.SOURCE, TopologyFields.PLACE, TopologyFields.POSSIBLY_SENSITIVE,
TopologyFields.TEXT, TopologyFields.TOPIC_NAME));
'''
place, topic_name, query = tuple.values
try:
tweets = list(get_tweets.get_tweets_for_trends(self._twitter_api, [{"query" : query}], popular = True, tweet_processor = self._storm_tweet_processor))[0]["tweets"]
except tweepy.TweepError as te:
# We have hit the REST API Rate limit for Twitter https://dev.twitter.com/docs/rate-limiting/1.1, no more tweets for some time
log_tweeter_error(te, sleep_time=self._rate_limit_sleep_time)
return
for pt in tweets:
# Here we add the trending topic name, and take the place name from those
# used internally by get_tweets, instead of the from place names returned by twitter
tup = [pt['author_screen_name'], pt['created_at'],
pt['favorite_count'], pt['hashtags_texts'], pt['in_reply_to_screen_name'],
pt['lang'], pt['retweet_count'], pt['retweeted'],
pt['source'], place, pt['possibly_sensitive'],
pt['text'], topic_name]
storm.emit(tup) | 54.410853 | 397 | 0.695541 | 5,527 | 0.787434 | 0 | 0 | 677 | 0.096452 | 0 | 0 | 4,501 | 0.641259 |
63e7de70cee4c80bf1a84446fed435049d34cefe | 1,329 | py | Python | nuremberg/core/urls.py | emmalemma/nuremberg | 10a5f789f5668aa4e7902e1765737c2c764ff2b2 | [
"MIT"
] | null | null | null | nuremberg/core/urls.py | emmalemma/nuremberg | 10a5f789f5668aa4e7902e1765737c2c764ff2b2 | [
"MIT"
] | null | null | null | nuremberg/core/urls.py | emmalemma/nuremberg | 10a5f789f5668aa4e7902e1765737c2c764ff2b2 | [
"MIT"
] | null | null | null | from django.conf.urls import include, url
from django.contrib import admin
from httpproxy.views import HttpProxy
from django.views.generic.base import RedirectView
from django.http import HttpResponse
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^transcripts/', include('nuremberg.transcripts.urls')),
url(r'^documents/', include('nuremberg.documents.urls')),
url(r'^photographs/', include('nuremberg.photographs.urls')),
url(r'^search/', include('nuremberg.search.urls')),
url(r'^', include('nuremberg.content.urls')),
url(r'^proxy_image/printing/(?P<url>.*)$',
# RedirectView.as_view(url='http://nuremberg.law.harvard.edu/imagedir/HLSL_NUR_printing/%(url)s')),
HttpProxy.as_view(base_url='http://nuremberg.law.harvard.edu/imagedir/HLSL_NUR_printing')),
url(r'^proxy_image/(?P<url>.*)$',
# RedirectView.as_view(url='http://s3.amazonaws.com/nuremberg-documents/%(url)s'))
HttpProxy.as_view(base_url='http://s3.amazonaws.com/nuremberg-documents')),
url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /search/", content_type="text/plain")),
]
handler400 = 'nuremberg.core.views.handler400'
handler403 = 'nuremberg.core.views.handler403'
handler404 = 'nuremberg.core.views.handler404'
handler500 = 'nuremberg.core.views.handler500'
| 49.222222 | 113 | 0.717833 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 746 | 0.561324 |
63e9684d10afbc91d9cdbd324d7a08494f2c12d6 | 5,125 | py | Python | signin/jd_job/common.py | nujabse/simpleSignin | e818f9880d97d39beddcadccb53dc23e18fe6d8e | [
"MIT"
] | 11 | 2018-03-07T04:13:05.000Z | 2019-11-28T04:43:55.000Z | signin/jd_job/common.py | nujabse/simpleSignin | e818f9880d97d39beddcadccb53dc23e18fe6d8e | [
"MIT"
] | 2 | 2018-03-04T15:08:01.000Z | 2018-05-28T07:42:47.000Z | signin/jd_job/common.py | nujabse/simpleSignin | e818f9880d97d39beddcadccb53dc23e18fe6d8e | [
"MIT"
] | 15 | 2018-01-25T10:54:06.000Z | 2019-11-05T07:09:20.000Z | #!/usr/bin/env python
# encoding: utf-8
# author: Vincent
# refer: https://github.com/vc5
import re
import time
from requests import Response
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.touch_actions import TouchActions
from ..chrome import mobile_emulation
from lib.settings import MOBILE_UA
class RequestError(Exception):
def __init__(self, message, code: str = None, response: Response = None):
self.message = message
self.code = code
self.response = response
def find_value(pattern, string, default=None, flags=0):
"""
根据正则表达式在字符串中搜索值,若未找到,返回 default
"""
m = re.search(pattern, string, flags)
if m:
return m.group(1)
else:
return default
class Job:
job_name = '签到任务名称demo'
index_url = 'https://bk.jd.com/m/channel/login/daka.html'
login_url = 'https://home.m.jd.com'
sign_url = 'https://bk.jd.com/m/channel/login/clock.html'
test_url = index_url
job_gb_url = 'https://bk.jd.com/m/channel/login/recDakaGb.html'
is_mobile = True # 默认为True,模拟移动动设备登陆
ua = MOBILE_UA
# sess = requestium.Session()
# sess.get(index_url)
# sess.driver.close()
# #重新初始化session的driver
# sess._driver = sess._driver_initializer() 或
# sess._driver = None后,可以重新使用sess.driver.get
# 重新指定driver path
# sess.webdriver_path="bin/chromedriver_linux64"
def __init__(self, bot):
self.bot = bot
self.session = bot.session
self.job_success = False
self.logger = bot.user.logger
self.session.headers.update({'User-Agent': self.ua})
self.session.webdriver_options.add_argument('user-agent={0}'.format(self.ua))
def run(self):
self.logger.info('Job Start: {}'.format(self.job_name))
is_login = self.is_login()
self.logger.info('登录状态: {}'.format(is_login))
if not is_login:
self.logger.info('进行登录...')
try:
self.login(url=self.login_url)
is_login = True
self.logger.info('登录成功')
except Exception as e:
self.logger.error('登录失败: {}'.format(repr(e)))
if is_login:
if self.is_signed():
self.job_success = True
else:
self.job_success = self.sign()
self.logger.info('Job End.')
def is_login(self):
r = self.session.get(self.test_url, allow_redirects=False)
if r.is_redirect and 'passport' in r.headers['Location']:
return False
else:
return True
def login(self, url):
# cookies = browser.get_cookies(url=self.login_url, signbot=self.bot)
# self.session.cookies.update(cookies)
self.session._driver = None
if self.is_mobile:
self.session.webdriver_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = self.session.driver
# 模拟触控操作
# https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.touch_actions.html
tap_loginbtn = TouchActions(driver)
driver.get(url)
user_input = driver.find_element_by_id('username')
password_input = driver.find_element_by_id('password')
login_btn = driver.find_element_by_id('loginBtn')
user_input.send_keys(self.bot.user.username)
password_input.send_keys(self.bot.user.password)
tap_loginbtn.tap(login_btn).perform()
time.sleep(6)
nickname = driver.find_element_by_css_selector('#myHeader span[class$="name_text"]')
nickname = nickname.text
self.logger.info('登陆成功,欢迎{}'.format(nickname))
print('登陆成功')
else:
self.login_pc(url)
self.session.transfer_driver_cookies_to_session()
self.session.driver.close()
def login_pc(self, url):
driver = self.session.driver
driver.get(url)
nickname = ''
switcher = driver.find_element_by_link_text('账户登录')
switcher.click()
user_input = driver.find_element_by_id('loginname')
password_input = driver.find_element_by_id('nloginpwd')
login_btn = driver.find_element_by_id('loginsubmit')
user_input.send_keys(self.bot.user.username)
password_input.send_keys(self.bot.user.password)
login_btn.click()
time.sleep(6)
try:
nickname = driver.find_element_by_css_selector('#shortcut-2014 a[class=nickname]')
nickname = nickname.text
self.logger.info('登陆成功,欢迎{}'.format(nickname))
except NoSuchElementException:
self.logger.warn('登陆异常,请检查是否需要验证码')
return nickname
def is_signed(self):
'''
验证是否签到
:return: 已经签到则返回True,否则返回False
'''
return False
def sign(self):
'''
用来签到的方法
:return:
'''
pass
def report(self):
'''
用来报告签到结果的方法
:return:返回需要通知用户的签到结果str
'''
return ''
| 31.441718 | 118 | 0.617756 | 4,841 | 0.886792 | 0 | 0 | 0 | 0 | 0 | 0 | 1,630 | 0.298589 |
63e9b0dfa031eb19f53844081f610705e8c0629f | 3,046 | py | Python | tests/test_parse.py | adamrp/emperor | ee12881953cdd65e13325c09d5adf87db7e63afd | [
"MIT"
] | null | null | null | tests/test_parse.py | adamrp/emperor | ee12881953cdd65e13325c09d5adf87db7e63afd | [
"MIT"
] | null | null | null | tests/test_parse.py | adamrp/emperor | ee12881953cdd65e13325c09d5adf87db7e63afd | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from __future__ import division
__author__ = "Jose Antonio Navas Molina"
__copyright__ = "Copyright 2013, The Emperor Project"
__credits__ = ["Jose Antonio Navas Molina"]
__license__ = "BSD"
__version__ = "0.9.3-dev"
__maintainer__ = "Jose Antonio Navas Molina"
__email__ = "josenavasmolina@gmail.com"
__status__ = "Development"
from unittest import TestCase, main
from tempfile import mkstemp
from os import close
import numpy as np
import numpy.testing as npt
from emperor.parse import parse_coords
class ParseTests(TestCase):
def test_parse_coords_ordination_results(self):
"""parse_coords should handle skbio's OrdinationResults file"""
coords = ordination_results_file.splitlines()
obs = parse_coords(coords)
exp = (['A', 'B', 'C'],
np.array([[.11, .09, .23], [.03, .07, -.26], [.12, .06, -.32]]),
np.array([4.94, 1.79, 1.50]),
np.array([14.3, 5.2, 4.3]))
# test the header and the values apart from each other
self.assertEqual(obs[0], exp[0])
npt.assert_almost_equal(obs[1], exp[1])
npt.assert_almost_equal(obs[2], exp[2])
npt.assert_almost_equal(obs[3], exp[3])
def test_parse_coords_qiime(self):
"""parse_coords should handle old qiime PCoA coords format"""
coords = qiime_pcoa_file.splitlines()
obs = parse_coords(coords)
exp = (['A', 'B', 'C'],
np.array([[.11, .09, .23], [.03, .07, -.26], [.12, .06, -.32]]),
np.array([4.94, 1.79, 1.50]),
np.array([14.3, 5.2, 4.3]))
# test the header and the values apart from each other
self.assertEqual(obs[0], exp[0])
npt.assert_almost_equal(obs[1], exp[1])
npt.assert_almost_equal(obs[2], exp[2])
npt.assert_almost_equal(obs[3], exp[3])
def test_parse_coords_qiime_file(self):
"""parse_coords should handle old qiime PCoA coords file"""
fd, fp = mkstemp()
close(fd)
with open(fp, 'w') as f:
f.write(qiime_pcoa_file)
with open(fp, 'U') as f:
obs = parse_coords(f)
exp = (['A', 'B', 'C'],
np.array([[.11, .09, .23], [.03, .07, -.26], [.12, .06, -.32]]),
np.array([4.94, 1.79, 1.50]),
np.array([14.3, 5.2, 4.3]))
# test the header and the values apart from each other
self.assertEqual(obs[0], exp[0])
npt.assert_almost_equal(obs[1], exp[1])
npt.assert_almost_equal(obs[2], exp[2])
npt.assert_almost_equal(obs[3], exp[3])
ordination_results_file = """Eigvals\t3
4.94\t1.79\t1.50
Proportion explained\t3
14.3\t5.2\t4.3
Species\t0\t0
Site\t3\t3
A\t.11\t.09\t.23
B\t.03\t.07\t-.26
C\t.12\t.06\t-.32
Biplot\t0\t0
Site constraints\t0\t0"""
qiime_pcoa_file = """pc vector number\t1\t2\t3
A\t0.11\t0.09\t0.23
B\t0.03\t0.07\t-0.26
C\t0.12\t0.06\t-0.32
eigvals\t4.94\t1.79\t1.50
% variation explained\t14.3\t5.2\t4.3
"""
if __name__ == '__main__':
main()
| 28.46729 | 79 | 0.601116 | 2,075 | 0.681221 | 0 | 0 | 0 | 0 | 0 | 0 | 936 | 0.307288 |
63eb09455a488d9193ff41ee088a0eccb9993357 | 998 | py | Python | Nmapscript.py | WhiteRedTHT/port-scann | bb4a6731f3c4ae484d1978fa7527f55520cb7e99 | [
"MIT"
] | null | null | null | Nmapscript.py | WhiteRedTHT/port-scann | bb4a6731f3c4ae484d1978fa7527f55520cb7e99 | [
"MIT"
] | null | null | null | Nmapscript.py | WhiteRedTHT/port-scann | bb4a6731f3c4ae484d1978fa7527f55520cb7e99 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import os
import vulners
print("---------------------------------------------------------------")
print(""" P4RS Script Hoş Geldiniz
Programı kullanmak için sadece IP adresini yazmanız yeterlidir.
Programı çalıştırmak için; Medusa araçları, searcsploit ve brutespray uygulamaları gerekmektedir. BruteSpray uygulamasını ben sizlere verdim. Diğerlerini kendiniz indirmelisiniz.
""")
print("---------------------------------------------------------------")
hedef_ip = raw_input("Lütfen IP adresi giriniz: ")
b = os.system("nmap " + hedef_ip + " -oX output.xml -v ")
c = os.system("searchsploit " "-v output.xml")
def vulners():
api = input("Api key'i giriniz: ")
servis = input("Tarama yapmak istediğiniz servisi yazınız: ")
vulners_api = vulners.Vulners(api_key="api")
tarama = vulners_api.search("servis", limit=3)
print(tarama)
d = os.system("./brutespray.py " "--file output.xml -U user.txt -P wordlist.txt --threads 5 --hosts 5")
| 26.263158 | 179 | 0.61022 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 705 | 0.692534 |
63ee6c3b647155df5b389065b12bf3169080b2cc | 1,276 | py | Python | portal/migrations/versions/a031e26dc1bd_.py | ivan-c/truenth-portal | 0b9d39ae43f42ea3413ed9634f295f5d856cbc77 | [
"BSD-3-Clause"
] | 3 | 2017-01-15T10:11:57.000Z | 2018-10-02T23:46:44.000Z | portal/migrations/versions/a031e26dc1bd_.py | uwcirg/true_nth_usa_portal | e2434731aed86f1c43f15d428dde8ffc28ac7e5f | [
"BSD-3-Clause"
] | 876 | 2016-04-04T20:45:11.000Z | 2019-02-28T00:10:36.000Z | portal/migrations/versions/a031e26dc1bd_.py | uwcirg/truenth-portal | 459a0d157982f010175c50b9cccd860a61790370 | [
"BSD-3-Clause"
] | 9 | 2016-04-13T01:18:55.000Z | 2018-09-19T20:44:23.000Z | from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
"""empty message
Revision ID: a031e26dc1bd
Revises: 8efa45d83a3b
Create Date: 2018-08-06 16:03:36.820890
"""
# revision identifiers, used by Alembic.
revision = 'a031e26dc1bd'
down_revision = '8efa45d83a3b'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('auth_providers',
sa.Column('created_at',
sa.DateTime(),
nullable=True))
op.add_column('auth_providers',
sa.Column('token',
sqlalchemy_utils.types.json.JSONType(),
nullable=True))
op.create_unique_constraint('auth_providers_by_provider',
'auth_providers',
['provider', 'provider_id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('auth_providers_by_provider',
'auth_providers',
type_='unique')
op.drop_column('auth_providers', 'token')
op.drop_column('auth_providers', 'created_at')
# ### end Alembic commands ###
| 28.355556 | 67 | 0.576019 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 581 | 0.455329 |
63f048c44468cdaab3bbd671bedb7f73b50abad5 | 7,048 | py | Python | gui/main_window/reservations/add_reservations/gui.py | Just-Moh-it/HotinGo | 13f3d0d9ed7991336dfbb4f50c2b87a7d9d19810 | [
"MIT"
] | 14 | 2022-02-08T02:40:34.000Z | 2022-03-24T19:17:57.000Z | gui/main_window/reservations/add_reservations/gui.py | Just-Moh-it/HotinGo | 13f3d0d9ed7991336dfbb4f50c2b87a7d9d19810 | [
"MIT"
] | 2 | 2022-02-03T13:22:04.000Z | 2022-02-08T06:16:57.000Z | gui/main_window/reservations/add_reservations/gui.py | SnazzyCoder/HotinGo | 13f3d0d9ed7991336dfbb4f50c2b87a7d9d19810 | [
"MIT"
] | 1 | 2022-03-21T00:05:47.000Z | 2022-03-21T00:05:47.000Z | from pathlib import Path
from tkinter import Frame, Canvas, Entry, Text, Button, PhotoImage, messagebox
import controller as db_controller
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def add_reservations():
AddReservations()
class AddReservations(Frame):
def __init__(self, parent, controller=None, *args, **kwargs):
Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.data = {"g_id": "", "check_in": "", "meal": "", "r_id": ""}
self.configure(bg="#FFFFFF")
self.canvas = Canvas(
self,
bg="#FFFFFF",
height=432,
width=797,
bd=0,
highlightthickness=0,
relief="ridge",
)
self.canvas.place(x=0, y=0)
self.entry_image_1 = PhotoImage(file=relative_to_assets("entry_1.png"))
entry_bg_1 = self.canvas.create_image(137.5, 153.0, image=self.entry_image_1)
self.canvas.create_text(
52.0,
128.0,
anchor="nw",
text="Guest Id",
fill="#5E95FF",
font=("Montserrat Bold", 14 * -1),
)
self.entry_image_2 = PhotoImage(file=relative_to_assets("entry_2.png"))
entry_bg_2 = self.canvas.create_image(141.5, 165.0, image=self.entry_image_2)
entry_2 = Entry(
self,
bd=0,
bg="#EFEFEF",
highlightthickness=0,
font=("Montserrat Bold", 18 * -1),
foreground="#777777",
)
entry_2.place(x=52.0, y=153.0, width=179.0, height=22.0)
self.data["g_id"] = entry_2
self.entry_image_3 = PhotoImage(file=relative_to_assets("entry_3.png"))
entry_bg_3 = self.canvas.create_image(137.5, 259.0, image=self.entry_image_3)
self.canvas.create_text(
52.0,
234.0,
anchor="nw",
text="Is Taking Meal",
fill="#5E95FF",
font=("Montserrat Bold", 14 * -1),
)
self.entry_image_4 = PhotoImage(file=relative_to_assets("entry_4.png"))
entry_bg_4 = self.canvas.create_image(141.5, 271.0, image=self.entry_image_4)
entry_4 = Entry(
self,
bd=0,
bg="#EFEFEF",
highlightthickness=0,
font=("Montserrat Bold", 18 * -1),
foreground="#777777",
)
entry_4.place(x=52.0, y=259.0, width=179.0, height=22.0)
self.data["r_id"] = entry_4
self.entry_image_5 = PhotoImage(file=relative_to_assets("entry_5.png"))
entry_bg_5 = self.canvas.create_image(378.5, 153.0, image=self.entry_image_5)
self.canvas.create_text(
293.0,
128.0,
anchor="nw",
text="Room Id",
fill="#5E95FF",
font=("Montserrat Bold", 14 * -1),
)
self.entry_image_6 = PhotoImage(file=relative_to_assets("entry_6.png"))
entry_bg_6 = self.canvas.create_image(382.5, 165.0, image=self.entry_image_6)
entry_6 = Entry(
self,
bd=0,
bg="#EFEFEF",
highlightthickness=0,
foreground="#777777",
font=("Montserrat Bold", 18 * -1),
)
entry_6.place(x=293.0, y=153.0, width=179.0, height=22.0)
self.data["meal"] = entry_6
self.entry_image_7 = PhotoImage(file=relative_to_assets("entry_7.png"))
entry_bg_7 = self.canvas.create_image(378.5, 259.0, image=self.entry_image_7)
self.canvas.create_text(
293.0,
234.0,
anchor="nw",
text="Check-in Time",
fill="#5E95FF",
font=("Montserrat Bold", 14 * -1),
)
self.entry_image_8 = PhotoImage(file=relative_to_assets("entry_8.png"))
entry_bg_8 = self.canvas.create_image(382.5, 271.0, image=self.entry_image_8)
entry_8 = Entry(
self,
bd=0,
bg="#EFEFEF",
highlightthickness=0,
foreground="#777777",
font=("Montserrat Bold", 18 * -1),
)
entry_8.place(x=293.0, y=259.0, width=179.0, height=22.0)
self.data["check_in"] = entry_8
self.button_image_1 = PhotoImage(file=relative_to_assets("button_1.png"))
button_1 = Button(
self,
image=self.button_image_1,
borderwidth=0,
highlightthickness=0,
command=self.save,
relief="flat",
)
button_1.place(x=164.0, y=322.0, width=190.0, height=48.0)
self.canvas.create_text(
139.0,
59.0,
anchor="nw",
text="Add a Reservation",
fill="#5E95FF",
font=("Montserrat Bold", 26 * -1),
)
self.canvas.create_text(
549.0,
59.0,
anchor="nw",
text="Operations",
fill="#5E95FF",
font=("Montserrat Bold", 26 * -1),
)
self.canvas.create_rectangle(
515.0, 59.0, 517.0, 370.0, fill="#EFEFEF", outline=""
)
self.button_image_2 = PhotoImage(file=relative_to_assets("button_2.png"))
button_2 = Button(
self,
image=self.button_image_2,
borderwidth=0,
highlightthickness=0,
command=lambda: self.parent.navigate("view"),
relief="flat",
)
button_2.place(x=547.0, y=116.0, width=209.0, height=74.0)
self.button_image_3 = PhotoImage(file=relative_to_assets("button_3.png"))
button_3 = Button(
self,
image=self.button_image_3,
borderwidth=0,
highlightthickness=0,
command=lambda: self.parent.navigate("edit"),
relief="flat",
)
button_3.place(x=547.0, y=210.0, width=209.0, height=74.0)
# Set default value for entry
self.data["check_in"].insert(0, "now")
# Save the data to the database
def save(self):
# check if any fields are empty
for label in self.data.keys():
if self.data[label].get() == "":
messagebox.showinfo("Error", "Please fill in all the fields")
return
# Save the reservation
result = db_controller.add_reservation(
*[self.data[label].get() for label in ("g_id", "meal", "r_id", "check_in")]
)
if result:
messagebox.showinfo("Success", "Reservation added successfully")
self.parent.navigate("view")
self.parent.refresh_entries()
# clear all fields
for label in self.data.keys():
self.data[label].delete(0, "end")
else:
messagebox.showerror(
"Error",
"Unable to add reservation. Please make sure the data is validated",
)
| 32.036364 | 87 | 0.539444 | 6,694 | 0.949773 | 0 | 0 | 0 | 0 | 0 | 0 | 1,027 | 0.145715 |
63f0dcedfc927c0b523f3a53c332513bb2498eb2 | 8,977 | py | Python | lib/util/ImageProcessing/homopgrahy.py | Thukor/MazeSolver | c953e193ce27a7348e8ec9c5592144426dfce193 | [
"MIT"
] | 5 | 2018-02-06T22:48:34.000Z | 2020-01-07T20:19:05.000Z | lib/util/ImageProcessing/homopgrahy.py | Thukor/MazeSolver | c953e193ce27a7348e8ec9c5592144426dfce193 | [
"MIT"
] | 11 | 2018-01-31T21:47:49.000Z | 2018-04-21T16:42:52.000Z | lib/util/ImageProcessing/homopgrahy.py | Thukor/MazeSolver | c953e193ce27a7348e8ec9c5592144426dfce193 | [
"MIT"
] | 2 | 2020-06-18T05:40:03.000Z | 2022-02-02T03:46:30.000Z | import cv2
import numpy as np
import imutils
from collections import defaultdict
# mouse callback function
def define_points(target_img):
corners = []
refPt = []
def draw_circle(event,x,y,flags,param):
global refPt
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(param,(x,y),5,(255,0,0),-1)
refPt = [x,y]
print(type(refPt))
corners.append(refPt)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle, target_img)
while(1):
cv2.imshow('image',target_img)
k = cv2.waitKey(20) & 0xFF
# corners.append(refPt)
if k == 27:
break
cv2.destroyAllWindows()
print (corners)
new_corners = np.array(corners)
return new_corners
def order_points(pts):
# initialzie a list of coordinates that will be ordered
# such that the first entry in the list is the top-left,
# the second entry is the top-right, the third is the
# bottom-right, and the fourth is the bottom-left
rect = np.zeros((4, 2), dtype = "float32")
# the top-left point will have the smallest sum, whereas
# the bottom-right point will have the largest sum
s = pts.sum(axis = 1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
# now, compute the difference between the points, the
# top-right point will have the smallest difference,
# whereas the bottom-left will have the largest difference
diff = np.diff(pts, axis = 1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
# return the ordered coordinates
return rect
def segment_by_angle_kmeans(lines,k=2, **kwargs):
"""Groups lines based on angle with k-means.
Uses k-means on the coordinates of the angle on the unit circle
to segment `k` angles inside `lines`.
"""
# Define criteria = (type, max_iter, epsilon)
default_criteria_type = cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER
criteria = kwargs.get('criteria', (default_criteria_type, 10, 1.0))
flags = kwargs.get('flags', cv2.KMEANS_RANDOM_CENTERS)
attempts = kwargs.get('attempts', 10)
# returns angles in [0, pi] in radians
angles = np.array([line[0][1] for line in lines])
# multiply the angles by two and find coordinates of that angle
pts = np.array([[np.cos(2*angle), np.sin(2*angle)]
for angle in angles], dtype=np.float32)
# run kmeans on the coords
labels, centers = cv2.kmeans(pts, k, None, criteria, attempts, flags)[1:]
labels = labels.reshape(-1) # transpose to row vec
# segment lines based on their kmeans label
segmented = defaultdict(list)
for i, line in zip(range(len(lines)), lines):
segmented[labels[i]].append(line)
segmented = list(segmented.values())
return segmented
def intersection(line1, line2):
"""Finds the intersection of two lines given in Hesse normal form.
Returns closest integer pixel locations.
See https://stackoverflow.com/a/383527/5087436
"""
rho1, theta1 = line1[0]
rho2, theta2 = line2[0]
A = np.array([
[np.cos(theta1), np.sin(theta1)],
[np.cos(theta2), np.sin(theta2)]
])
b = np.array([[rho1], [rho2]])
x0, y0 = np.linalg.solve(A, b)
x0, y0 = int(np.round(x0)), int(np.round(y0))
return [[x0, y0]]
def segmented_intersections(lines):
"""Finds the intersections between groups of lines."""
intersections = []
for i, group in enumerate(lines[:-1]):
for next_group in lines[i+1:]:
for line1 in group:
for line2 in next_group:
intersections.append(intersection(line1, line2))
return intersections
def isEqual(l1, l2):
length1 = sqrtf((l1[2] - l1[0])*(l1[2] - l1[0]) + (l1[3] - l1[1])*(l1[3] - l1[1]))
length2 = sqrtf((l2[2] - l2[0])*(l2[2] - l2[0]) + (l2[3] - l2[1])*(l2[3] - l2[1]))
product = (l1[2] - l1[0])*(l2[2] - l2[0]) + (l1[3] - l1[1])*(l2[3] - l2[1])
if (fabs(product / (length1 * length2)) < cos(CV_PI / 30)):
return false
mx1 = (l1[0] + l1[2]) * 0.5
mx2 = (l2[0] + l2[2]) * 0.5
my1 = (l1[1] + l1[3]) * 0.5
my2 = (l2[1] + l2[3]) * 0.5
dist = sqrtf((mx1 - mx2)*(mx1 - mx2) + (my1 - my2)*(my1 - my2))
if (dist > max(length1, length2) * 0.5):
return false
return true
def birdseye_correction(img = "angled.jpg"):
img = cv2.imread(img,0)
resized = imutils.resize(img, height = 1000)
copy = resized.copy()
rect = order_points(define_points(copy))
print (rect)
(tl, tr, br, bl) = rect
# compute the width of the new image, which will be the
# maximum distance between bottom-right and bottom-left
# x-coordiates or the top-right and top-left x-coordinates
widthA = np.sqrt(((br[0]-bl[0])**2)+((br[1]-bl[1])**2))
widthB = np.sqrt(((tr[0]-tl[0])**2)+((tr[1]-tl[1])**2))
maxWidth = max(int(widthA), int(widthB))
# compute the height of the new image, which will be the
# maximum distance between the top-right and bottom-right
# y-coordinates or the top-left and bottom-left y-coordinates
heightA = np.sqrt(((tr[0]-br[0])**2)+((tr[1]-br[1])**2))
heightB = np.sqrt(((tl[0]-bl[0])**2)+((tl[1]-bl[1])**2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([[0, 0], \
[maxWidth - 1, 0], \
[maxWidth - 1, maxHeight - 1], \
[0, maxHeight - 1]], dtype = "float32")
# compute the perspective transform matrix and then apply it
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(resized, M, (maxWidth, maxHeight))
cv2.imshow("warped", warped)
cv2.waitKey(0)
cv2.destroyAllWindows()
# gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
blurred_img = cv2.GaussianBlur(warped,(3,3),0)
binary = cv2.adaptiveThreshold(blurred_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,31,2)
# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(binary,cv2.MORPH_OPEN,kernel, iterations = 2)
# Apply edge detection method on the image
edges = cv2.Canny(warped,50,150,apertureSize = 3)
#
cv2.imshow("edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
# This returns an array of r and theta values
lines = cv2.HoughLines(edges,1,np.pi/180, 140)
# The below for loop runs till r and theta values
# are in the range of the 2d array
for line in lines:
for r,theta in line:
# Stores the value of cos(theta) in a
a = np.cos(theta)
# Stores the value of sin(theta) in b
b = np.sin(theta)
# x0 stores the value rcos(theta)
x0 = a*r
# y0 stores the value rsin(theta)
y0 = b*r
# x1 stores the rounded off value of (rcos(theta)-1000sin(theta))
x1 = int(x0 + 1000*(-b))
# y1 stores the rounded off value of (rsin(theta)+1000cos(theta))
y1 = int(y0 + 1000*(a))
# x2 stores the rounded off value of (rcos(theta)+1000sin(theta))
x2 = int(x0 - 1000*(-b))
# y2 stores the rounded off value of (rsin(theta)-1000cos(theta))
y2 = int(y0 - 1000*(a))
# cv2.line draws a line in img from the point(x1,y1) to (x2,y2).
# (0,0,255) denotes the colour of the line to be
# In this case, it is red.
cv2.line(warped,(x1,y1), (x2,y2), (0,0,255),2)
# labels = []
# num_lines = partition(lines, labels, isEqual)
# define criteria, number of clusters(K) and apply kmeans()
# criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 54, 1.0)
# K = 54
# ret,label,center=cv2.kmeans(lines,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
#
# # Now convert back into uint8, and make original image
# center = np.uint8(center)
# res = center[label.flatten()]
# print(res.shape, img.shape)
# # res2 = res.reshape((img.shape))
# cv2.imshow('res',res)
# res2 = cv2.resize(res, warped.shape);
# cv2.imshow('img', img)
# cv2.imshow('res2',res2)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
cv2.imwrite("unclustered_lines.jpg", warped)
#
cv2.imshow("lines", warped)
cv2.waitKey(0)
cv2.destroyAllWindows()
# segmented = segment_by_angle_kmeans(lines)
# intersections = segmented_intersections(segmented)
# print(intersections)
# draw the intersection points
# intersectsimg = img.copy()
# for cx, cy in zip(intersections):
# cx = np.round(cx).astype(int)
# cy = np.round(cy).astype(int)
# color = np.random.randint(0,255,3).tolist() # random colors
# cv2.circle(intersectsimg, (cx, cy), radius=2, color=color, thickness=-1) # -1: filled circle
#
#
# cv2.imshow("intersections", intersectionimg)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
def main():
birdseye_correction()
if __name__ == "__main__":
main()
| 33.003676 | 102 | 0.614236 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,643 | 0.405815 |
63f426a7b9bb1a0814ac7f14e6b624d2906c52be | 8,729 | py | Python | chime.py | alexklapheke/chime | 2a0ed71310488cfc5cf5daeacd3dcb62558d44dc | [
"MIT"
] | null | null | null | chime.py | alexklapheke/chime | 2a0ed71310488cfc5cf5daeacd3dcb62558d44dc | [
"MIT"
] | null | null | null | chime.py | alexklapheke/chime | 2a0ed71310488cfc5cf5daeacd3dcb62558d44dc | [
"MIT"
] | null | null | null | import argparse
import configparser
import os
import pathlib
import platform
import random
import subprocess as sp
import sys
import typing
import warnings
if platform.system() == 'Windows':
import winsound
try:
from IPython.core import magic
IPYTHON_INSTALLED = True
except ImportError:
IPYTHON_INSTALLED = False
def _get_config_path(system: str) -> pathlib.Path:
"""Return the path of the config file.
Parameters:
system: The OS being used.
"""
home_dir = pathlib.Path.home()
if system == 'Windows':
config_path = (
pathlib.Path(
os.getenv('APPDATA',
home_dir / pathlib.Path('AppData', 'Roaming')))
/ pathlib.Path('chime', 'chime.ini')
)
else:
config_path = home_dir / pathlib.Path('.config', 'chime', 'chime.conf')
return config_path.resolve().absolute()
def _get_default_theme(path: pathlib.Path, fallback_theme: str) -> str:
"""Check for the existence of a theme in a config file.
Parameters:
path: Path of the config file.
fallback_theme: The theme to fallback to if a config file is not found or contains no
theme.
"""
if path.exists():
config = configparser.ConfigParser()
config.read(path)
if 'chime' in config:
default_theme = config['chime'].get('theme', fallback_theme)
else:
default_theme = fallback_theme
else:
default_theme = fallback_theme
return default_theme
config_path = _get_config_path(platform.system())
THEME = _get_default_theme(config_path, fallback_theme='chime')
__all__ = [
'error',
'info',
'notify_exceptions',
'success'
'theme',
'themes',
'warning'
]
def run(command: str, sync: bool, raise_error: bool):
if sync:
try:
sp.run(command, shell=True, check=True, stdout=sp.PIPE, stderr=sp.PIPE)
except sp.CalledProcessError as e:
msg = f'{e} stderr: {e.stderr.decode().strip()}'
if raise_error:
raise RuntimeError(msg)
else:
warnings.warn(msg)
else:
sp.Popen(command, shell=True, stderr=sp.DEVNULL)
def play_wav(path: pathlib.Path, sync=True, raise_error=True):
"""Play a .wav file.
This function is platform agnostic, meaning that it will determine what to do based on
the `sys.platform` variable.
Parameters:
path: Path to a .wav file.
sync: The sound file will be played synchronously if this is `True`. If not, then the sound
will be played asynchronously in a separate process. In such a case, the process will
fail silently if an error occurs.
raise_error: Whether to raise an exception when an occurs, or instead to just send a
warning.
Raises:
RuntimeError: If the platform is not supported.
"""
system = platform.system()
if system == 'Darwin':
run(f'afplay {path}', sync, raise_error)
elif system == 'Linux':
run(f'aplay {path}', sync, raise_error)
elif system == 'OpenBSD':
run(f'aucat -i {path}', sync, raise_error)
elif system == 'Windows':
flags = winsound.SND_FILENAME
if not sync:
flags |= winsound.SND_ASYNC
try:
winsound.PlaySound(str(path), flags)
except RuntimeError as e:
if raise_error:
raise e
else:
warnings.warn(e)
else:
raise RuntimeError(f'Unsupported platform ({sys.platform})')
def themes_dir() -> pathlib.Path:
"""Return the directory where the themes are located."""
here = pathlib.Path(__file__).parent
return here.joinpath('themes')
def current_theme_dir() -> pathlib.Path:
"""Return the current theme's sound directory."""
if THEME == 'random':
return themes_dir().joinpath(random.choice(themes()))
return themes_dir().joinpath(THEME)
def themes() -> typing.List[str]:
"""Return the available themes to choose from."""
return sorted(
theme.name
for theme in themes_dir().iterdir()
if not theme.name.startswith('.') # ignores .DS_Store on MacOS
)
def theme(name: str = None):
"""Set the current theme.
Parameters:
name: The change will be switched if a valid name is provided. The current theme is
returned if `None`.
Raises:
ValueError: If the theme is unknown.
"""
global THEME
if name is None:
return THEME
if name != 'random' and name not in themes():
raise ValueError(f'Unknown theme ({name})')
THEME = name
def notify(event: str, sync: bool, raise_error: bool):
wav_path = current_theme_dir().joinpath(f'{event}.wav')
if not wav_path.exists():
raise ValueError(f"{wav_path} is doesn't exist")
play_wav(wav_path, sync, raise_error)
def success(sync=False, raise_error=False):
"""Make a success sound.
Parameters:
sync: The sound file will be played synchronously if this is `True`. If not, then the sound
will be played in a separate process. In such a case, the process will fail silently if
an error occurs.
raise_error: Whether to raise an exception when an occurs, or instead to just send a
warning.
"""
return notify('success', sync, raise_error)
def warning(sync=False, raise_error=False):
"""Make a warning sound.
Parameters:
sync: The sound file will be played synchronously if this is `True`. If not, then the sound
will be played in a separate process. In such a case, the process will fail silently if
an error occurs.
raise_error: Whether to raise an exception when an occurs, or instead to just send a
warning.
"""
return notify('warning', sync, raise_error)
def error(sync=False, raise_error=False):
"""Make an error sound.
Parameters:
sync: The sound file will be played synchronously if this is `True`. If not, then the sound
will be played in a separate process. In such a case, the process will fail silently if
an error occurs.
raise_error: Whether to raise an exception when an occurs, or instead to just send a
warning.
"""
return notify('error', sync, raise_error)
def info(sync=False, raise_error=False):
"""Make a generic information sound.
Parameters:
sync: The sound file will be played synchronously if this is `True`. If not, then the sound
will be played in a separate process. In such a case, the process will fail silently if
an error occurs.
raise_error: Whether to raise an exception when an occurs, or instead to just send a
warning.
"""
return notify('info', sync, raise_error)
def notify_exceptions():
"""Will call error() whenever an exception occurs."""
def except_hook(exctype, value, traceback):
error()
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = except_hook
if IPYTHON_INSTALLED:
class Watcher:
def __init__(self, ipython):
self.shell = ipython
def post_run_cell(self, result):
if result.error_in_exec:
error()
try:
ipython = get_ipython()
except NameError:
return
watcher = Watcher(ipython)
ipython.events.register('post_run_cell', watcher.post_run_cell)
if IPYTHON_INSTALLED:
@magic.magics_class
class ChimeMagics(magic.Magics):
@magic.needs_local_scope
@magic.line_cell_magic
def chime(self, line, cell=None, local_ns=None):
def run(code):
try:
exec(code, local_ns)
success()
except Exception as e:
error()
raise e
if cell is None:
run(line)
else:
run(cell)
def load_ipython_extension(ipython):
ipython.register_magics(ChimeMagics)
def main():
"""Command-line interface."""
parser = argparse.ArgumentParser()
parser.add_argument('event', nargs='?', default='success',
help='either one of {success, warning, error, info}')
parser.add_argument('--theme', help=f'either one of {{{", ".join(themes())}}}')
args = parser.parse_args()
if args.theme:
theme(args.theme)
notify(args.event, sync=False, raise_error=False)
if __name__ == '__main__':
main()
| 27.799363 | 99 | 0.613701 | 677 | 0.077558 | 0 | 0 | 493 | 0.056478 | 0 | 0 | 3,661 | 0.419407 |
63f4fd4ae3791d5d16a0a77ceadc4495ca195f7c | 7,733 | py | Python | tests/Omega/test_Omega_ligand_preparation.py | niladell/DockStream | 75f06d24a95699cdc06fe1ea021e213e1d9fa5b3 | [
"Apache-2.0"
] | 34 | 2021-08-05T06:28:30.000Z | 2022-03-17T02:42:49.000Z | tests/Omega/test_Omega_ligand_preparation.py | niladell/DockStream | 75f06d24a95699cdc06fe1ea021e213e1d9fa5b3 | [
"Apache-2.0"
] | 9 | 2021-08-31T10:35:51.000Z | 2022-02-03T08:57:58.000Z | tests/Omega/test_Omega_ligand_preparation.py | niladell/DockStream | 75f06d24a95699cdc06fe1ea021e213e1d9fa5b3 | [
"Apache-2.0"
] | 10 | 2021-08-12T02:32:11.000Z | 2022-01-19T11:51:33.000Z | import unittest
import os
from dockstream.core.OpenEyeHybrid.Omega_ligand_preparator import OmegaLigandPreparator
from dockstream.core.ligand.ligand_input_parser import LigandInputParser
from dockstream.utils.enums.docking_enum import DockingConfigurationEnum
from dockstream.utils.enums.Omega_enums import OmegaExecutablesEnum
from tests.tests_paths import PATHS_1UYD
from dockstream.utils.files_paths import attach_root_path
from dockstream.utils.smiles import read_smiles_file
_DE = DockingConfigurationEnum()
_OE = OmegaExecutablesEnum()
# TODO: move "prefix_execution" to "config/tests_config/config.json"
# TODO: add macrocycle mode unit test
class Test_Omega_ligand_preparation(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
def setUp(self):
self.smiles = list(read_smiles_file(attach_root_path(PATHS_1UYD.LIGANDS_SMILES_TXT), standardize=False))
@classmethod
def tearDownClass(cls):
pass
def test_classic_coordinate_generation(self):
conf = {_OE.POOLID: "testPool",
_OE.INPUT: {_OE.INPUT_TYPE: _OE.INPUT_TYPE_LIST},
_OE.PARAMS: {_OE.PREFIX_EXECUTION: "module load omega",
_OE.MODE: _OE.CLASSIC}}
lig_parser = LigandInputParser(smiles=self.smiles, **conf)
prep = OmegaLigandPreparator(ligands=lig_parser.get_ligands(), **conf)
# check 3D coordinate generation
prep.generate3Dcoordinates()
self.assertEqual(prep.get_number_ligands(), 15)
self.assertEqual(prep.get_ligands()[0].get_molecule().GetNumAtoms(), 51)
self.assertListEqual(list(prep.get_ligands()[0].get_molecule().GetConformer(0).GetPositions()[0]),
[-5.9481, 1.231, -6.7269])
# test write-out
out_path = attach_root_path("tests/junk/omega_classic_ligands.sdf")
prep.write_ligands(path=out_path, format=_OE.OUTPUT_FORMAT_SDF)
stat_inf = os.stat(out_path)
self.assertEqual(stat_inf.st_size, 63824)
def test_classic_coordinate_generation_fails(self):
conf = {_OE.POOLID: "testPool",
_OE.INPUT: {_OE.INPUT_TYPE: _OE.INPUT_TYPE_LIST},
_OE.PARAMS: {_OE.PREFIX_EXECUTION: "module load omega",
_OE.MODE: _OE.CLASSIC}}
test = self.smiles + ["abc"]
lig_parser = LigandInputParser(smiles=test, **conf)
prep = OmegaLigandPreparator(ligands=lig_parser.get_ligands(), **conf)
self.assertEqual(prep.get_number_ligands(), 16)
# check 3D coordinate generation
prep.generate3Dcoordinates()
self.assertEqual(prep.get_number_ligands(), 16)
self.assertEqual(len([True for lig in prep.get_ligands() if lig.get_molecule() is not None]),
15)
self.assertEqual(prep.get_ligands()[0].get_molecule().GetNumAtoms(), 51)
self.assertListEqual(list(prep.get_ligands()[0].get_molecule().GetConformer(0).GetPositions()[0]),
[-5.9481, 1.231, -6.7269])
# test write-out
out_path = attach_root_path("tests/junk/omega_classic_ligands.sdf")
prep.write_ligands(path=out_path, format=_OE.OUTPUT_FORMAT_SDF)
stat_inf = os.stat(out_path)
self.assertEqual(stat_inf.st_size, 63824)
def test_classic_coordinate_generation_parallelized(self):
conf = {_OE.POOLID: "testPool",
_OE.INPUT: {_OE.INPUT_TYPE: _OE.INPUT_TYPE_LIST},
_OE.PARAMS: {
_OE.PARALLELIZATION: {
_OE.PARALLELIZATION_NUMBER_CORES: 4
},
_OE.PREFIX_EXECUTION: "module load omega",
_OE.MODE: _OE.CLASSIC}}
lig_parser = LigandInputParser(smiles=self.smiles, **conf)
prep = OmegaLigandPreparator(ligands=lig_parser.get_ligands(), **conf)
# check 3D coordinate generation
prep.generate3Dcoordinates()
self.assertEqual(prep.get_number_ligands(), 15)
self.assertEqual(prep.get_ligands()[0].get_molecule().GetNumAtoms(), 51)
self.assertListEqual(list(prep.get_ligands()[0].get_molecule().GetConformer(0).GetPositions()[0]),
[-5.9481, 1.231, -6.7269])
# test write-out
out_path = attach_root_path("tests/junk/omega_classic_parallelized_ligands.sdf")
prep.write_ligands(path=out_path, format=_OE.OUTPUT_FORMAT_SDF)
stat_inf = os.stat(out_path)
self.assertEqual(stat_inf.st_size, 63824)
def test_rocs_coordinate_generation(self):
conf = {_OE.POOLID: "testPool",
_OE.INPUT: {_OE.INPUT_TYPE: _OE.INPUT_TYPE_LIST},
_OE.PARAMS: {_OE.PREFIX_EXECUTION: "module load omega",
_OE.MODE: _OE.ROCS}}
lig_parser = LigandInputParser(smiles=self.smiles, **conf)
prep = OmegaLigandPreparator(ligands=lig_parser.get_ligands(), **conf)
# check 3D coordinate generation
prep.generate3Dcoordinates()
self.assertEqual(prep.get_number_ligands(), 15)
self.assertEqual(prep.get_ligands()[0].get_molecule().GetNumAtoms(), 51)
self.assertListEqual(list(prep.get_ligands()[0].get_molecule().GetConformer(0).GetPositions()[0]),
[-5.9481, 1.231, -6.7269])
# test write-out
out_path = attach_root_path("tests/junk/omega_rocs_ligands.sdf")
prep.write_ligands(path=out_path, format=_OE.OUTPUT_FORMAT_SDF)
stat_inf = os.stat(out_path)
self.assertEqual(stat_inf.st_size, 63824)
def test_pose_coordinate_generation(self):
conf = {_OE.POOLID: "testPool",
_OE.INPUT: {_OE.INPUT_TYPE: _OE.INPUT_TYPE_LIST},
_OE.PARAMS: {_OE.PREFIX_EXECUTION: "module load omega",
_OE.MODE: _OE.POSE}}
lig_parser = LigandInputParser(smiles=self.smiles, **conf)
prep = OmegaLigandPreparator(ligands=lig_parser.get_ligands(), **conf)
# check 3D coordinate generation
prep.generate3Dcoordinates()
self.assertEqual(prep.get_number_ligands(), 15)
self.assertEqual(prep.get_ligands()[0].get_molecule().GetNumAtoms(), 51)
self.assertListEqual(list(prep.get_ligands()[0].get_molecule().GetConformer(0).GetPositions()[0]),
[-5.9481, 1.231, -6.7269])
# test write-out
out_path = attach_root_path("tests/junk/omega_pose_ligands.sdf")
prep.write_ligands(path=out_path, format=_OE.OUTPUT_FORMAT_SDF)
stat_inf = os.stat(out_path)
self.assertEqual(stat_inf.st_size, 63824)
def test_dense_coordinate_generation(self):
conf = {_OE.POOLID: "testPool",
_OE.INPUT: {_OE.INPUT_TYPE: _OE.INPUT_TYPE_LIST},
_OE.PARAMS: {_OE.PREFIX_EXECUTION: "module load omega",
_OE.MODE: _OE.DENSE}}
lig_parser = LigandInputParser(smiles=self.smiles, **conf)
prep = OmegaLigandPreparator(ligands=lig_parser.get_ligands(), **conf)
# check 3D coordinate generation
prep.generate3Dcoordinates()
self.assertEqual(prep.get_number_ligands(), 15)
self.assertEqual(prep.get_ligands()[0].get_molecule().GetNumAtoms(), 51)
self.assertListEqual(list(prep.get_ligands()[0].get_molecule().GetConformer(0).GetPositions()[0]),
[-5.9481, 1.231, -6.7269])
# test write-out
out_path = attach_root_path("tests/junk/omega_dense_ligands.sdf")
prep.write_ligands(path=out_path, format=_OE.OUTPUT_FORMAT_SDF)
stat_inf = os.stat(out_path)
self.assertEqual(stat_inf.st_size, 63824)
| 46.305389 | 112 | 0.655114 | 7,076 | 0.915039 | 0 | 0 | 103 | 0.01332 | 0 | 0 | 805 | 0.104099 |
63f58c76597e10765889d7945f69878a414cf4fc | 1,989 | py | Python | tests/test_blog/test_post_search.py | florimondmanca/personal-api | 6300f965d3f51d1bf5f10cf1eb15d673bd627631 | [
"MIT"
] | 4 | 2018-08-17T08:06:06.000Z | 2020-02-20T15:15:56.000Z | tests/test_blog/test_post_search.py | florimondmanca/personal-api | 6300f965d3f51d1bf5f10cf1eb15d673bd627631 | [
"MIT"
] | 2 | 2018-10-08T15:59:58.000Z | 2018-10-20T16:50:13.000Z | tests/test_blog/test_post_search.py | florimondmanca/personal-api | 6300f965d3f51d1bf5f10cf1eb15d673bd627631 | [
"MIT"
] | 1 | 2019-09-14T23:15:10.000Z | 2019-09-14T23:15:10.000Z | """Test searching the list of blog posts."""
from typing import List
from rest_framework.test import APITestCase
from blog.factories import PostFactory
from tests.decorators import authenticated
@authenticated
class PostSearchListTest(APITestCase):
"""Test searching on the post list endpoint."""
def setUp(self):
self.post1 = PostFactory.create(title="Getting Started With Python")
self.post2 = PostFactory.create(description="Ruby: From Zero To Hero")
self.post3 = PostFactory.create(tags=["docker"])
def search(self, term: str):
url = "/api/posts/"
response = self.client.get(url, {"search": term})
self.assertEqual(response.status_code, 200)
return response.data["results"]
def test_returns_posts_matching_title(self):
results = self.search("Python")
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["id"], self.post1.pk)
def test_returns_posts_matching_description(self):
results = self.search("Ruby")
self.assertEqual(len(results), 1)
self.assertEqual(results[0]["id"], self.post2.pk)
def test_does_not_return_posts_matching_tags(self):
results = self.search("docker")
self.assertEqual(len(results), 0)
@authenticated
class SearchByTagTest(APITestCase):
"""Test the filtering of the blog post list for a given tag."""
def perform(self) -> List[dict]:
url = "/api/posts/"
response = self.client.get(url, data={"tag": "python"})
self.assertEqual(response.status_code, 200)
return response.data["results"]
def test_if_post_has_tag_then_included(self):
PostFactory.create(tags=["python", "webdev"])
posts = self.perform()
self.assertEqual(len(posts), 1)
def test_if_post_does_not_have_tag_then_not_included(self):
PostFactory.create(tags=["javascript", "webdev"])
posts = self.perform()
self.assertEqual(len(posts), 0)
| 33.15 | 78 | 0.676219 | 1,755 | 0.882353 | 0 | 0 | 1,785 | 0.897436 | 0 | 0 | 347 | 0.17446 |
63f6b54840467413595924d2498a90042e914026 | 10,641 | py | Python | yo/schema.py | RailCoin/yo | c5384cedd30771b36d4603d7a28b30d7a1273433 | [
"MIT"
] | 10 | 2017-10-22T20:07:40.000Z | 2018-08-01T21:48:49.000Z | client-libs/yo/yo/schema.py | Blurt-Blockchain/steem | fbffd373cdb0f6192aa8806d07e8671e219c3767 | [
"MIT"
] | 81 | 2017-08-19T15:38:32.000Z | 2020-05-12T09:56:14.000Z | client-libs/yo/yo/schema.py | Blurt-Blockchain/steem | fbffd373cdb0f6192aa8806d07e8671e219c3767 | [
"MIT"
] | 9 | 2017-09-19T07:12:20.000Z | 2021-05-25T17:09:27.000Z | # coding=utf-8
from enum import IntEnum
class NotificationType(IntEnum):
power_down = 1
power_up = 2
resteem = 3
feed = 4
reward = 5
send = 6
mention = 7
follow = 8
vote = 9
comment_reply = 10
post_reply = 11
account_update = 12
message = 13
receive = 14
class TransportType(IntEnum):
desktop = 1
email = 2
sms = 3
class Priority(IntEnum):
low = 1
normal = 2
high = 3
always = 4
class ActionStatus(IntEnum):
sent = 1
rate_limited = 2
failed = 3
perm_failed = 4
class EventOrigin(IntEnum):
blockchain = 1
steemit = 2
class EventPriority(IntEnum):
blockchain = 1
steemit = 2
NOTIFICATION_TYPES = [i.name for i in NotificationType]
TRANSPORT_TYPES = [i.name for i in TransportType]
EVENT_ORIGINS = [i.name for i in EventOrigin]
EVENT_PRIORITIES = [i.name for i in EventPriority]
'''
Example Notification
-------
{
"notify_id": 39,
"notify_type": "power_down",
"created": "2017-10-27T01:31:29.382749",
"updated": "2017-10-27T15:16:06.178975",
"read": true,
"shown": false,
"username": "test_user",
"data": {
"author": "roadscape",
"amount": 10000.2
}
}
'''
'''
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose
'''
'''
flow
bf detects operation
op's handlers are run to generate event
begin transaction
event is stored
potential notification accounts are determined
account notification prefs are loaded
events are filtered against notification prefs
filtered events are added to transport queues
end transaction
transport queue item read
if not rate-limited
load user info from conveyor
attempt send
if success:
delete queue item
record result
if rate-limited:
delete queue item
record result
'''
yo_schema = {
'$schema': 'http://json-schema.org/draft-06/schema#',
'id': 'https://schema.steemit.com/yo/objects.json',
'title': 'notification transport schema',
'definitions': {
'transport': {
'title': 'transport',
'type': 'object',
'properties':{
'transport': {
'$ref': '#/definitions/transport_type'
},
'notification_types': {
"type": "array",
"uniqueItems": True,
'items': {
'$ref': '#/definitions/notification_type'
}
},
'data': 'object'
},
'required': ['transport','notification_types'],
'additionalProperties': False,
},
'notification': {
'title': 'notification schema',
'type':'object',
'properties': {
'nid': 'number',
'notify_type': {
'$ref': '#/definitions/notification_type'
},
'created': 'string',
'to_username': 'string',
'from_username': 'string',
'json_data': {
'type':'object'
},
'priority': {
'$ref': '#/definitions/priority'
}
},
'required': ['notify_id','notify_type','created','updated','read','shown','username','data'],
'additionalProperties': False
},
'priority': {
'type': 'string',
'enum': EVENT_PRIORITIES
},
'notification_type': {
'type': 'string',
'enum': NOTIFICATION_TYPES
},
'transport_type': {
'type':'string',
'enum': TRANSPORT_TYPES
},
'event_origin': {
'type': 'string',
'enum': EVENT_ORIGINS
},
'event_urn': {
'type': 'string'
},
'event': {
'title': 'event schema',
'type': 'object',
'properties': {
'priority': {
'$ref': '#/definitions/priority'
},
'urn': {
'$ref': '#/definitions/event_urn'
},
'origin': {
'$ref': '#/definitions/event_origin'
},
'data': {
'type':'object',
}
},
'required': ['priority','urn','origin','data'],
'additionalProperties': False
}
}
}
EVENTS = {
'account_update': {
'priority': 'HIGH',
'source_event': {
'type': 'blockchain',
'filter': {
'operation_type': ['account_update']
},
'example': {
"json_metadata": "",
"account": "theoretical",
"memo_key": "STM6FATHLohxTN8RWWkU9ZZwVywXo6MEDjHHui1jEBYkG2tTdvMYo",
"posting": {
"key_auths": [
[
"STM6FATHLohxTN8RWWkU9ZZwVywXo6MEDjHHui1jEBYkG2tTdvMYo",
1
],
[
"STM76EQNV2RTA6yF9TnBvGSV71mW7eW36MM7XQp24JxdoArTfKA76",
1
]
],
"account_auths": [],
"weight_threshold": 1
}
}
}
},
'comment_reply': {
'priority': 'LOW',
'source_event': {
'type': 'blockchain',
'filter': {
'operation_type': ['comment'],
'parent_permlink': [{"anything-but":""}]
},
'example': {
"title": "Welcome to Steem!",
"parent_permlink": "meta",
"permlink": "firstpost",
"parent_author": "steemit",
"body": "Steemit is a social media platform where anyone can earn STEEM points by posting. The more people who like a post, the more STEEM the poster earns. Anyone can sell their STEEM for cash or vest it to boost their voting power.",
"json_metadata": "",
"author": "steemit"
}
}
},
'feed': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': [],
},
'example':{}
}
},
'follow': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['custom_json'],
},
'example':{
"required_auths": [],
"id": "follow",
"json": "{\"follower\":\"steemit\",\"following\":\"steem\",\"what\":[\"posts\"]}",
"required_posting_auths": [
"steemit"
]
}
}
},
'mention': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['comment'],
},
'example':{
"title": "Welcome to Steem!",
"parent_permlink": "meta",
"permlink": "firstpost",
"parent_author": "steemit",
"body": "Steemit is a social media platform where anyone can earn STEEM points by posting. The more people who like a post, the more STEEM the poster earns. Anyone can sell their STEEM for cash or vest it to boost their voting power.",
"json_metadata": "",
"author": "steemit"
}
}
},
'post_reply': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['comment'],
},
'example':{}
}
},
'power_down': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['withdraw_vesting'],
},
'example':{
"vesting_shares": "200000.000000 VESTS",
"account": "steemit"
}
}
},
'send': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['transfer'],
},
'example':{
"amount": "833.000 STEEM",
"from": "admin",
"to": "steemit",
"memo": ""
}
}
},
'receive': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['transfer'],
},
'example':{
"amount": "833.000 STEEM",
"from": "admin",
"to": "steemit",
"memo": ""
}
}
},
'resteem': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['custom_json'],
},
'example':{}
}
},
'reward': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': [],
},
'example': {
"author": "ivelina89",
"permlink": "friends-forever",
"sbd_payout": "2.865 SBD",
"steem_payout": "0.000 STEEM",
"vesting_payout": "1365.457442 VESTS"
}
}
},
'vote': {
'priority': 'LOW',
'source_event': {
'type':'blockchain',
'filter': {
'operation_type': ['vote'],
},
'example':{
"voter": "steemit78",
"permlink": "firstpost",
"author": "steemit",
"weight": 10000
}
}
}
}
| 26.871212 | 253 | 0.423926 | 643 | 0.060427 | 0 | 0 | 0 | 0 | 0 | 0 | 5,209 | 0.489522 |
63f6c1a6e6d4382fdea90513c54f2d68c07f76d8 | 2,491 | py | Python | iu_mongo/session.py | intelligenceunion/mongo-driver | 02bbc6839c8264d4b06b053e8cc83d42147ede17 | [
"MIT"
] | null | null | null | iu_mongo/session.py | intelligenceunion/mongo-driver | 02bbc6839c8264d4b06b053e8cc83d42147ede17 | [
"MIT"
] | null | null | null | iu_mongo/session.py | intelligenceunion/mongo-driver | 02bbc6839c8264d4b06b053e8cc83d42147ede17 | [
"MIT"
] | 1 | 2019-06-21T17:49:08.000Z | 2019-06-21T17:49:08.000Z | from pymongo.read_concern import ReadConcern
from pymongo.read_preferences import ReadPreference
from pymongo.write_concern import WriteConcern
from pymongo.errors import InvalidOperation
from iu_mongo.errors import TransactionError
__all__ = ['Session', 'TransactionContext']
DEFAULT_READ_CONCERN = ReadConcern('majority')
DEFAULT_WRITE_CONCERN = WriteConcern(w='majority', wtimeout=5000)
DEFAULT_READ_PREFERENCE = ReadPreference.PRIMARY
class TransactionContext(object):
def __init__(self, pymongo_transaction_context, pymongo_session):
self._pymongo_transaction_context = pymongo_transaction_context
self._pymongo_session = pymongo_session
def __enter__(self):
self._pymongo_transaction_context.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._pymongo_transaction_context.__exit__(exc_type, exc_val, exc_tb)
@property
def _transaction(self):
return self._pymongo_session._transaction
@property
def transaction_id(self):
return self._transaction.transaction_id
class Session(object):
def __init__(self, pymongo_client_session):
self._pymongo_client_session = pymongo_client_session
@property
def pymongo_session(self):
return self._pymongo_client_session
@property
def pymongo_client(self):
return self._pymongo_client_session.client
@property
def session_id(self):
return self._pymongo_client_session.session_id
def start_transaction(self):
try:
pymongo_transaction_context = self._pymongo_client_session.start_transaction(
read_concern=DEFAULT_READ_CONCERN,
write_concern=DEFAULT_WRITE_CONCERN,
read_preference=DEFAULT_READ_PREFERENCE
)
return TransactionContext(pymongo_transaction_context, self._pymongo_client_session)
except InvalidOperation as e:
raise TransactionError(str(e))
def abort_transaction(self):
try:
self._pymongo_client_session.abort_transaction()
except InvalidOperation as e:
raise TransactionError(str(e))
def commit_transaction(self):
self._pymongo_client_session.commit_transaction()
def __enter__(self):
self._pymongo_client_session.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._pymongo_client_session.__exit__(exc_type, exc_val, exc_tb)
| 32.350649 | 96 | 0.734243 | 2,044 | 0.820554 | 0 | 0 | 438 | 0.175833 | 0 | 0 | 49 | 0.019671 |
63f8d4f926db9084fff0778f781e3d35e9ba0d24 | 5,009 | py | Python | bin/ingredient_phrase_tagger/training/cli.py | Deekshith1994/Recipes | 5dfc98b249f6caf90571c037eb35560417b6818e | [
"Apache-2.0"
] | null | null | null | bin/ingredient_phrase_tagger/training/cli.py | Deekshith1994/Recipes | 5dfc98b249f6caf90571c037eb35560417b6818e | [
"Apache-2.0"
] | null | null | null | bin/ingredient_phrase_tagger/training/cli.py | Deekshith1994/Recipes | 5dfc98b249f6caf90571c037eb35560417b6818e | [
"Apache-2.0"
] | null | null | null | import re
import decimal
import optparse
import pandas as pd
from ingredient_phrase_tagger.training import utils
class Cli(object):
def __init__(self, argv):
self.opts = self._parse_args(argv)
self._upstream_cursor = None
def run(self):
self.generate_data(self.opts.count, self.opts.offset)
def generate_data(self, count, offset):
"""
Generates training data in the CRF++ format for the ingredient
tagging task
"""
df = pd.read_csv(self.opts.data_path)
df = df.fillna("")
start = int(offset)
end = int(offset) + int(count)
df_slice = df.iloc[start: end]
for index, row in df_slice.iterrows():
try:
# extract the display name
display_input = utils.cleanUnicodeFractions(row["input"])
tokens = utils.tokenize(display_input)
del(row["input"])
rowData = self.addPrefixes([(t, self.matchUp(t, row)) for t in tokens])
for i, (token, tags) in enumerate(rowData):
features = utils.getFeatures(token, i+1, tokens)
print utils.joinLine([token] + features + [self.bestTag(tags)])
# ToDo: deal with this
except UnicodeDecodeError:
pass
print
def parseNumbers(self, s):
"""
Parses a string that represents a number into a decimal data type so that
we can match the quantity field in the db with the quantity that appears
in the display name. Rounds the result to 2 places.
"""
ss = utils.unclump(s)
m3 = re.match('^\d+$', ss)
if m3 is not None:
return decimal.Decimal(round(float(ss), 2))
m1 = re.match(r'(\d+)\s+(\d)/(\d)', ss)
if m1 is not None:
num = int(m1.group(1)) + (float(m1.group(2)) / float(m1.group(3)))
return decimal.Decimal(str(round(num,2)))
m2 = re.match(r'^(\d)/(\d)$', ss)
if m2 is not None:
num = float(m2.group(1)) / float(m2.group(2))
return decimal.Decimal(str(round(num,2)))
return None
def matchUp(self, token, ingredientRow):
"""
Returns our best guess of the match between the tags and the
words from the display text.
This problem is difficult for the following reasons:
* not all the words in the display name have associated tags
* the quantity field is stored as a number, but it appears
as a string in the display name
* the comment is often a compilation of different comments in
the display name
"""
ret = []
# strip parens from the token, since they often appear in the
# display_name, but are removed from the comment.
token = utils.normalizeToken(token)
decimalToken = self.parseNumbers(token)
for key, val in ingredientRow.iteritems():
if isinstance(val, basestring):
for n, vt in enumerate(utils.tokenize(val)):
if utils.normalizeToken(vt) == token:
ret.append(key.upper())
elif decimalToken is not None:
try:
if val == decimalToken:
ret.append(key.upper())
except:
pass
return ret
def addPrefixes(self, data):
"""
We use BIO tagging/chunking to differentiate between tags
at the start of a tag sequence and those in the middle. This
is a common technique in entity recognition.
Reference: http://www.kdd.cis.ksu.edu/Courses/Spring-2013/CIS798/Handouts/04-ramshaw95text.pdf
"""
prevTags = None
newData = []
for n, (token, tags) in enumerate(data):
newTags = []
for t in tags:
p = "B" if ((prevTags is None) or (t not in prevTags)) else "I"
newTags.append("%s-%s" % (p, t))
newData.append((token, newTags))
prevTags = tags
return newData
def bestTag(self, tags):
if len(tags) == 1:
return tags[0]
# if there are multiple tags, pick the first which isn't COMMENT
else:
for t in tags:
if (t != "B-COMMENT") and (t != "I-COMMENT"):
return t
# we have no idea what to guess
return "OTHER"
def _parse_args(self, argv):
"""
Parse the command-line arguments into a dict.
"""
opts = optparse.OptionParser()
opts.add_option("--count", default="100", help="(%default)")
opts.add_option("--offset", default="0", help="(%default)")
opts.add_option("--data-path", default="nyt-ingredients-snapshot-2015.csv", help="(%default)")
(options, args) = opts.parse_args(argv)
return options
| 30.730061 | 102 | 0.553404 | 4,892 | 0.976642 | 0 | 0 | 0 | 0 | 0 | 0 | 1,663 | 0.332002 |
63f969d5f629381bf59ef7c423c9e80ade88f17b | 726 | py | Python | snowballs.py | GYosifov88/Python-Fundamentals | b46ba2822bd2dac6ff46830c6a520e559b448442 | [
"MIT"
] | null | null | null | snowballs.py | GYosifov88/Python-Fundamentals | b46ba2822bd2dac6ff46830c6a520e559b448442 | [
"MIT"
] | null | null | null | snowballs.py | GYosifov88/Python-Fundamentals | b46ba2822bd2dac6ff46830c6a520e559b448442 | [
"MIT"
] | null | null | null | import sys
number_of_snowballs = int(input())
highest_value = -sys.maxsize
highest_quality = -sys.maxsize
highest_weight = -sys.maxsize
highest_time = -sys.maxsize
for i in range (number_of_snowballs):
weight_of_snowball = int(input())
time_of_reaching = int(input())
quality_of_snowball = int(input())
current_snowball_value = (weight_of_snowball / time_of_reaching) ** quality_of_snowball
if current_snowball_value > highest_value:
highest_value = current_snowball_value
highest_weight = weight_of_snowball
highest_quality = quality_of_snowball
highest_time = time_of_reaching
print(f"{highest_weight} : {highest_time} = {highest_value:.0f} ({highest_quality:.0f})")
| 31.565217 | 91 | 0.746556 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 82 | 0.112948 |
63f9f32e4e0b138503ce2018f80b9a8c535cec3c | 1,871 | py | Python | altperf-server/apps/start-api.py | ynakaoku/altperf | eb4e9e8e76820ddf0325a047eed20a64accb9cf8 | [
"MIT"
] | null | null | null | altperf-server/apps/start-api.py | ynakaoku/altperf | eb4e9e8e76820ddf0325a047eed20a64accb9cf8 | [
"MIT"
] | null | null | null | altperf-server/apps/start-api.py | ynakaoku/altperf | eb4e9e8e76820ddf0325a047eed20a64accb9cf8 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, Markup, abort, make_response
# import peewee
# import json
api = Flask(__name__)
@api.route('/')
def index():
html = '''
<form action="/iperf3test">
<p><label>iperf3 test: </label></p>
Test Name: <input type="text" name="TestName"></p>
Config File: <input type="text" name="ConfigFile"></p>
Interval: <input type="text" name="Interval" value="1"></p>
Bandwidth: <input type="text" name="Bandwidth" value="1G"></p>
MSS: <input type="text" name="MSS" value="1460"></p>
Parallel: <input type="text" name="Parallel" value="1"></p>
Time: <input type="text" name="Time" value="10"></p>
Protocol is UDP? : <input type="checkbox" name="UDP?"></p>
Use Server Output? : <input type="checkbox" name="Get Server Output?"></p>
Use ESXTOP Output? : <input type="checkbox" name="Get ESXTOP Output?"></p>
<button type="submit" formmethod="get">GET</button></p>
<button type="submit" formmethod="post">POST</button></p>
</form>
'''
return Markup(html)
@api.route('/iperf3test', methods=['GET', 'POST'])
def iperf3test():
try:
if request.method == 'POST':
return request.form['TestName']
else:
return request.args.get('TestName', '')
except Exception as e:
return str(e)
@api.route('/sayHello', methods=['GET'])
def say_hello():
result = {
"result":True,
"data": "Hello, world!"
}
return make_response(jsonify(result))
# if you do not want to use Unicode:
# return make_response(json.dumps(result, ensure_ascii=False))
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
api.run(host='0.0.0.0', port=8000)
| 32.824561 | 82 | 0.597007 | 0 | 0 | 0 | 0 | 1,647 | 0.880278 | 0 | 0 | 1,200 | 0.641368 |
63fa568f646d17018a9b9b6a0c301f61efae8ec9 | 4,212 | py | Python | ESAN.py | wnxbwyc/ESAN | 9f97c4cf0d323e893ac2205ec945b6c37320aaf3 | [
"MIT"
] | null | null | null | ESAN.py | wnxbwyc/ESAN | 9f97c4cf0d323e893ac2205ec945b6c37320aaf3 | [
"MIT"
] | null | null | null | ESAN.py | wnxbwyc/ESAN | 9f97c4cf0d323e893ac2205ec945b6c37320aaf3 | [
"MIT"
] | null | null | null | import functools
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def make_model(level):
return ESAN(level = level)
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
m.weight.data *= scale # for residual block
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
init.kaiming_normal_(m.weight, a=0, mode='fan_in')
m.weight.data *= scale
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias.data, 0.0)
def make_layer(block, n_layers):
layers = []
for _ in range(n_layers):
layers.append(block())
return nn.Sequential(*layers)
class ESA(nn.Module):
def __init__(self, n_feats, conv):
super(ESA, self).__init__()
f = n_feats // 4
self.conv1 = conv(n_feats, f, kernel_size=1)
self.conv2 = conv(f, f, kernel_size=3, stride=2, padding=0)
self.conv3_1 = conv(f, f, kernel_size=3, padding=1)
self.conv3_2 = conv(f, f, kernel_size=3, padding=1)
self.conv3_3 = conv(f, f, kernel_size=3, padding=1)
self.conv4 = conv(f, n_feats, kernel_size=1)
self.sigmoid = nn.Sigmoid()
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
c1_ = (self.conv1(x))
c1 = self.conv2(c1_)
c1 = F.max_pool2d(c1, kernel_size=7, stride=3)
c3 = self.relu(self.conv3_1(c1))
c3 = self.relu(self.conv3_2(c3))
c3 = self.conv3_3(c3)
c3 = F.interpolate(c3, (x.size(2), x.size(3)), mode='bilinear', align_corners=False)
c4 = self.conv4(c3 + c1_)
m = self.sigmoid(c4)
return x * m
class ResidualBlock_ESA(nn.Module):
'''
---Conv-ReLU-Conv-ESA +-
'''
def __init__(self, nf=32):
super(ResidualBlock_ESA, self).__init__()
self.conv1 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.conv2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.ESA = ESA(nf, nn.Conv2d)
# initialize_weights([self.conv1, self.conv2, self.ESA], 0.1)
def forward(self, x):
identity = x
out = F.relu(self.conv1(x), inplace=True)
out = self.conv2(out)
out = self.ESA(out)
return identity + out
class ESAN(nn.Module):
''' ELECTRIC'''
def __init__(self, in_nc=3, out_nc=3, nf = 32, level = 0, upscale=4):
super(ESAN, self).__init__()
self.upscale = upscale
self.level = level
conv_first = []
recon_trunk = []
upconv = []
self.upconv0 = nn.Conv2d(in_nc, out_nc * 4 * 4, 3, 1, 1, bias=True)
basic_block = functools.partial(ResidualBlock_ESA, nf=nf)
power = 16 #18
for i in range(level):
recon_trunk.append(make_layer(basic_block, power))
# power *= 2
conv_first.append(nn.Conv2d(in_nc, nf, 3, 1, 1, bias=True))
# upsampling
upconv.append(nn.Conv2d(nf, out_nc * 4 * 4, 3, 1, 1, bias=True))
self.pixel_shuffle = nn.PixelShuffle(4)
self.recon_trunk = nn.ModuleList()
for i in range(self.level):
self.recon_trunk.append(
nn.Sequential(*recon_trunk[i])
)
self.conv_first = nn.ModuleList()
for i in range(self.level):
self.conv_first.append(
conv_first[i]
)
self.upconv = nn.ModuleList()
for i in range(self.level):
self.upconv.append(
upconv[i]
)
def forward(self, x):
result = self.pixel_shuffle(self.upconv0(x))
for i in range(self.level):
fea = self.conv_first[i](x)
out = self.recon_trunk[i](fea)
out = self.pixel_shuffle(self.upconv[i](out))
result += out
return result
| 33.428571 | 92 | 0.555793 | 3,132 | 0.74359 | 0 | 0 | 0 | 0 | 0 | 0 | 189 | 0.044872 |
63fb8b0b09023645d9ad10a5e8feb048ac8c77ad | 3,478 | py | Python | problems/tsptw/problem_tsptw.py | cem0963/dpdp | 86f91a1e425826a3f31bcc175724c26a349fdb96 | [
"MIT"
] | null | null | null | problems/tsptw/problem_tsptw.py | cem0963/dpdp | 86f91a1e425826a3f31bcc175724c26a349fdb96 | [
"MIT"
] | null | null | null | problems/tsptw/problem_tsptw.py | cem0963/dpdp | 86f91a1e425826a3f31bcc175724c26a349fdb96 | [
"MIT"
] | null | null | null | import math
import numpy as np
from scipy.spatial.distance import cdist
from torch.utils.data import Dataset
import torch
import os
import pickle
from problems.tsptw.state_tsptw import StateTSPTWInt
from utils.functions import accurate_cdist
class TSPTW(object):
NAME = 'tsptw' # TSP with Time Windows
@staticmethod
def get_costs(dataset, pi):
"""
:param dataset: (batch_size, graph_size, 2) coordinates
:param pi: (batch_size, graph_size) permutations representing tours
:return: (batch_size) lengths of tours
"""
# Check that tours are valid, i.e. contain 1 to n (0 is depot and should not be included)
if (pi[:, 0] == 0).all():
pi = pi[:, 1:] # Strip of depot
assert (
torch.arange(pi.size(1), out=pi.data.new()).view(1, -1).expand_as(pi) + 1 ==
pi.data.sort(1)[0]
).all(), "Invalid tour"
# Distance must be provided in dataset since way of rounding can vary
if 'dist' in dataset:
dist = dataset['dist']
else:
coords = torch.cat((dataset['depot'][:, None, :], dataset['loc']), 1)
dist = accurate_cdist(coords, coords).round().int()
batch_size, graph_size, _ = dataset['loc'].size()
# Check the time windows
t = dist.new_zeros((batch_size, ))
#assert (pi[:, 0] == 0).all() # Tours must start at depot
batch_zeros = pi.new_zeros((batch_size, ))
cur = batch_zeros
batch_ind = torch.arange(batch_size).long()
lb, ub = torch.unbind(dataset['timew'], -1)
for i in range(graph_size - 1):
next = pi[:, i]
t = torch.max(t + dist[batch_ind, cur, next], lb[batch_ind, next])
assert (t <= ub[batch_ind, next]).all()
cur = next
length = dist[batch_ind, 0, pi[:, 0]] + dist[batch_ind[:, None], pi[:, :-1], pi[:, 1:]].sum(-1) + dist[batch_ind, pi[:, -1], 0]
# We want to maximize total prize but code minimizes so return negative
return length, None
# @staticmethod
def make_dataset(*args, **kwargs):
return TSPTWDataset(*args, **kwargs)
@staticmethod
def make_state(*args, **kwargs):
return StateTSPTWInt.initialize(*args, **kwargs)
def get_rounded_distance_matrix(coord):
return cdist(coord, coord).round().astype(np.int)
def generate_instance(size):
raise NotImplementedError()
class TSPTWDataset(Dataset):
def __init__(self, filename=None, size=100, num_samples=1000000, offset=0, distribution=None, normalize=False):
super(TSPTWDataset, self).__init__()
self.data_set = []
assert filename is not None
assert not normalize
assert os.path.splitext(filename)[1] == '.pkl'
with open(filename, 'rb') as f:
data = pickle.load(f)
self.data = [
{
'loc': torch.tensor(loc, dtype=torch.float),
'depot': torch.tensor(depot, dtype=torch.float),
'timew': torch.tensor(timew, dtype=torch.int64),
'max_coord': torch.tensor(max_coord, dtype=torch.int64), # Scalar
}
for depot, loc, timew, max_coord in (data[offset:offset+num_samples])
]
self.size = len(self.data)
def __len__(self):
return self.size
def __getitem__(self, idx):
return self.data[idx]
| 33.76699 | 135 | 0.587407 | 3,071 | 0.882979 | 0 | 0 | 1,872 | 0.53824 | 0 | 0 | 672 | 0.193214 |
63fc18b2a0a8c8afa137abd0e9e8f89ed4b67b71 | 11,089 | py | Python | thespian/test/__init__.py | dendron2000/Thespian | 0acbc5a0803f6d2be3421ea6eb08c6beecbf3802 | [
"MIT"
] | 210 | 2015-08-31T19:39:34.000Z | 2020-01-10T08:07:48.000Z | thespian/test/__init__.py | dendron2000/Thespian | 0acbc5a0803f6d2be3421ea6eb08c6beecbf3802 | [
"MIT"
] | 85 | 2017-04-08T19:28:42.000Z | 2022-03-23T15:25:49.000Z | thespian/test/__init__.py | dendron2000/Thespian | 0acbc5a0803f6d2be3421ea6eb08c6beecbf3802 | [
"MIT"
] | 47 | 2015-09-01T19:24:20.000Z | 2020-01-02T20:03:05.000Z | """Defines various classes and definitions that provide assistance for
unit testing Actors in an ActorSystem."""
import unittest
import pytest
import logging
import time
from thespian.actors import ActorSystem
def simpleActorTestLogging():
"""This function returns a logging dictionary that can be passed as
the logDefs argument for ActorSystem() initialization to get
simple stdout logging configuration. This is not necessary for
typical unit testing that uses the simpleActorSystemBase, but
it can be useful for multiproc.. ActorSystems where the
separate processes created should have a very simple logging
configuration.
"""
import sys
if sys.platform == 'win32':
# Windows will not allow sys.stdout to be passed to a child
# process, which breaks the startup/config for some of the
# tests.
handler = { 'class': 'logging.handlers.RotatingFileHandler',
'filename': 'nosetests.log',
'maxBytes': 256*1024,
'backupCount':3,
}
else:
handler = { 'class': 'logging.StreamHandler',
'stream': sys.stdout,
}
return {
'version' : 1,
'handlers': { #'discarder': {'class': 'logging.NullHandler' },
'testStream' : handler,
},
'root': { 'handlers': ['testStream'] },
'disable_existing_loggers': False,
}
class LocallyManagedActorSystem(object):
def setSystemBase(self, newBase='simpleSystemBase', systemCapabilities=None, logDefs='BestForBase'):
newBaseStr = str(newBase)
if not hasattr(self, 'currentBase') or self.currentBase != newBaseStr:
ldefs = logDefs if logDefs != 'BestForBase' else (simpleActorTestLogging() if newBase.startswith('multiproc') else False)
# In case the ActorSystem was *already* setup, break the singleton aspect and re-init
ActorSystem(logDefs = ldefs).shutdown()
ActorSystem(newBase, systemCapabilities, logDefs = ldefs)
self.currentBase = newBaseStr
class ActorSystemTestCase(unittest.TestCase, LocallyManagedActorSystem):
"""The ActorSystemTestCase is a wrapper for the unittest TestCase
class that will startup a default ActorSystem in the provided
setUp() and tearDown() any active ActorSystem after testing.
If a non-default ActorSystem is to be used, the setSystemBase()
method should be called with that system base.
It also provides some additional methods for assistance in testing Actors.
"""
def setUp(self):
if not hasattr(self, 'currentBase'):
self.setSystemBase()
def tearDown(self):
if hasattr(self, 'currentBase'):
ActorSystem().shutdown()
delattr(self, 'currentBase')
import time
time.sleep(0.02)
@staticmethod
def actualActorObject(actorClass):
"""Normally an Actor is only instantiated in the context of an
ActorSystem, and then only responds to messages delivered
via that system. For testing purposes *only*, it may be
desireable to have the actual Actor instance to test
methods on that Actor directly. This method will return
that actual Actor instance after instantiating the actor in
an ActorSystem.
This method can ONLY be used with an ActorSystem that will
instantiate the Actor in the context of the current process
(e.g. simpleSystemBase) and the methods tested on the
resulting Actor CANNOT perform any Actor-related actions
(e.g. self.createActor(), self.send()).
This method is for TESTING only under very special
circumstances; if you're not sure you need this, then you
probably don't.
"""
# Create the Actor within the system.
aAddr = ActorSystem().createActor(actorClass)
# This depends on the internals of the systemBase
return ActorSystem()._systemBase.actorRegistry[aAddr.actorAddressString].instance
###
### pytest fixtures and helpers
###
testAdminPort = None
def get_free_admin_port_random():
global testAdminPort
if testAdminPort is None:
import random
# Reserved system ports are typically below 1024. Ephemeral
# ports typically start at either 32768 (Linux) or 49152
# (IANA), or range from 1024-5000 (older Windows). Pick
# something unused outside those ranges for the admin.
testAdminPort = random.randint(10000, 30000)
#testAdminPort = random.randint(5,60) * 1000
else:
testAdminPort = testAdminPort + 1
return testAdminPort
def get_free_admin_port():
import socket
import random
for tries in range(100):
port = random.randint(5000, 30000)
try:
for m,p in [ (socket.SOCK_STREAM, socket.IPPROTO_TCP),
(socket.SOCK_DGRAM, socket.IPPROTO_UDP),
]:
s = socket.socket(socket.AF_INET, m, p)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('',port))
s.close()
return port
except Exception:
pass
return get_free_admin_port_random()
@pytest.fixture(params=['simpleSystemBase',
'multiprocQueueBase',
'multiprocUDPBase',
'multiprocTCPBase',
'multiprocTCPBase-AdminRouting',
'multiprocTCPBase-AdminRoutingTXOnly',
])
def asys(request):
caps = {'Foo Allowed': True,
'Cows Allowed': True,
'Dogs Allowed': True,
'dog': 'food'}
if request.param.startswith('multiprocTCP') or \
request.param.startswith('multiprocUDP'):
caps['Admin Port'] = get_free_admin_port()
caps['Convention Address.IPv4'] = '', caps['Admin Port']
if request.param.endswith('-AdminRouting'):
caps['Admin Routing'] = True
if request.param.endswith('-AdminRoutingTXOnly'):
caps['Admin Routing'] = True
caps['Outbound Only'] = True
asys = ActorSystem(systemBase=request.param.partition('-')[0],
capabilities=caps,
logDefs=(simpleActorTestLogging()
if request.param.startswith('multiproc')
else False),
transientUnique=True)
asys.base_name = request.param
asys.port_num = caps.get('Admin Port', None)
asys.txonly = request.param.endswith('-AdminRoutingTXOnly')
request.addfinalizer(lambda asys=asys: asys.shutdown())
return asys
def similar_asys(asys, in_convention=True, start_wait=True, capabilities=None):
caps = capabilities or {}
if asys.base_name.startswith('multiprocTCP') or \
asys.base_name.startswith('multiprocUDP'):
caps['Admin Port'] = get_free_admin_port()
if in_convention:
caps['Convention Address.IPv4'] = '', asys.port_num
if asys.base_name.endswith('-AdminRouting'):
caps['Admin Routing'] = True
asys2 = ActorSystem(systemBase=asys.base_name.partition('-')[0],
capabilities=caps,
logDefs=(simpleActorTestLogging()
if asys.base_name.startswith('multiproc')
else False),
transientUnique=True)
asys2.base_name = asys.base_name
asys2.port_num = caps.get('Admin Port', None)
if in_convention and start_wait:
time.sleep(0.25) # Wait for Actor Systems to start and connect together
return asys2
@pytest.fixture
def asys2(request, asys):
asys2 = similar_asys(asys, in_convention=False)
# n.b. shutdown the second actor system first:
# 1. Some tests ask asys1 to create an actor
# 2. That actor is actually supported by asys2
# 3. There is an external port the tester uses for each asys
# 4. When asys2 is shutdown, it will attempt to notify the
# parent of the actor that the actor is dead
# 5. This parent is the external port for asys1.
# 6. If asys1 is shutdown first, then asys2 must time out
# on the transmit attempt (usually 5 minutes) before
# it can exit.
# 7. If the test is re-run within this 5 minute period, it will fail
# because the old asys2 is still existing but in shutdown state
# (and will therefore rightfully refuse new actions).
# By shutting down asys2 first, the parent notification can be
# performed and subsequent runs don't encounter the lingering
# asys2.
request.addfinalizer(lambda asys=asys2: asys2.shutdown())
return asys2
@pytest.fixture
def asys_pair(request, asys):
asys2 = similar_asys(asys, in_convention=True)
# n.b. shutdown the second actor system first:
# 1. Some tests ask asys1 to create an actor
# 2. That actor is actually supported by asys2
# 3. There is an external port the tester uses for each asys
# 4. When asys2 is shutdown, it will attempt to notify the
# parent of the actor that the actor is dead
# 5. This parent is the external port for asys1.
# 6. If asys1 is shutdown first, then asys2 must time out
# on the transmit attempt (usually 5 minutes) before
# it can exit.
# 7. If the test is re-run within this 5 minute period, it will fail
# because the old asys2 is still existing but in shutdown state
# (and will therefore rightfully refuse new actions).
# By shutting down asys2 first, the parent notification can be
# performed and subsequent runs don't encounter the lingering
# asys2.
request.addfinalizer(lambda asys=asys2: asys2.shutdown())
return (asys, asys2)
@pytest.fixture
def run_unstable_tests(request):
return request.config.getoption('unstable', default=False)
def unstable_test(run_unstable_tests, asys, *unstable_bases):
if asys.base_name in unstable_bases and not run_unstable_tests:
pytest.skip("Test unstable for %s system base"%asys.base_name)
def actor_system_unsupported(asys, *unsupported_bases):
if asys.base_name in unsupported_bases:
pytest.skip("Functionality not supported for %s system base"%asys.base_name)
from thespian.system.timing import timePeriodSeconds
import time
inTestDelay = lambda period: time.sleep(timePeriodSeconds(period))
def delay_for_next_of_kin_notification(system):
if system.base_name == 'multiprocQueueBase':
# The multiprocQueueBase signal processor cannot interrupt a
# sleeping Queue.get(), so for this base it is necessary to
# wait for the timeout on the Queue.get() to allow it time to
# notice and process the child exit.
time.sleep(2.5)
elif system.base_name == 'multiprocUDPBase':
time.sleep(0.6)
else:
time.sleep(0.1)
| 39.74552 | 133 | 0.646497 | 2,692 | 0.242763 | 0 | 0 | 4,939 | 0.445396 | 0 | 0 | 5,446 | 0.491117 |
63fc46927ba7027c56b95c5435a784c8f5cc9d72 | 2,454 | py | Python | main.py | JeffSpies/nonwordlist | 3f4e3c3c4d81d36f28ce03baf10f2a29b1272722 | [
"Apache-2.0"
] | null | null | null | main.py | JeffSpies/nonwordlist | 3f4e3c3c4d81d36f28ce03baf10f2a29b1272722 | [
"Apache-2.0"
] | null | null | null | main.py | JeffSpies/nonwordlist | 3f4e3c3c4d81d36f28ce03baf10f2a29b1272722 | [
"Apache-2.0"
] | 2 | 2016-05-19T07:14:25.000Z | 2019-05-09T03:14:50.000Z | from process import wordlist
import itertools
import time
import os
import re
ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz'
def main():
blacklist_all = wordlist.dict_by_length()
blacklist = blacklist_all[3].union(blacklist_all[4]).union(blacklist_all[5])
combinations = get_combinations(3)
tick = time.time()
bad_guids = generate_guids(blacklist, combinations=combinations)
print('Time: {}, Length: {}'.format(time.time()-tick, len(bad_guids)))
bad_guids.union(generate_69s(combinations))
with open('guid_blacklist.txt', 'w') as writer:
for item in bad_guids:
writer.write(item + os.linesep)
def get_combinations(length, alphabet=ALPHABET):
combinations = {}
for x in range(length):
combinations[x + 1] = list(itertools.product(alphabet, repeat=(x+1)))
return combinations
def generate_guids(words, combinations=None, length=5, alphabet=ALPHABET):
guids = set()
if not combinations:
combinations = get_combinations(2, alphabet)
n = 0
for word in words:
if n % 1000 == 0:
print(str(n))
if len(word) > length:
raise Exception
if len(word) == length:
guids.add(word)
else:
positions = n_positions(word, length)
n_random = length - len(word)
for c in combinations[n_random]:
for i in range(0, positions):
word_list = create_word_list(word, i)
available_indices = [i for i, x in enumerate(word_list) if not x]
for idx in available_indices:
index = available_indices.index(idx)
word_list[idx] = c[index]
result = ''.join(word_list)
guids.add(result)
n += 1
return guids
def generate_69s(combinations):
found = []
guids_with_69 = generate_guids(['69'], combinations=combinations)
for word in guids_with_69:
if re.search('[a-z]69[a-z]', word) or \
re.search('^69[a-z]', word) or \
re.search('[a-z]69$', word):
found.append(word)
return found
def create_word_list(word, index):
word_list = [None] * 5
for letter in word:
word_list[index] = letter
index += 1
return word_list
def n_positions(word, length):
return length - len(word) + 1
if __name__ == '__main__':
main()
| 27.266667 | 85 | 0.5978 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 128 | 0.05216 |
63fd18d9cde24eebf1bd28cfec8a2e3f2f9d0dd4 | 10,400 | py | Python | src/PPO.py | thurbridi/mo436-project-1 | 6d29bb4536d684a79b1a271e4d8505aca40db03b | [
"MIT"
] | null | null | null | src/PPO.py | thurbridi/mo436-project-1 | 6d29bb4536d684a79b1a271e4d8505aca40db03b | [
"MIT"
] | null | null | null | src/PPO.py | thurbridi/mo436-project-1 | 6d29bb4536d684a79b1a271e4d8505aca40db03b | [
"MIT"
] | null | null | null | import numpy as np
import random
import gym
import time
import itertools
from numpy.random.mtrand import gamma
import torch
from torch import nn
from torch._C import dtype
from torch.optim import Adam
from torch.distributions import Categorical
class ExperienceBuffer:
def __init__(self, buffer_size, gamma, lambd):
self.obs_buffer = np.zeros((buffer_size, 1), dtype=np.float32)
self.action_buffer = np.zeros((buffer_size, 1), dtype=np.float32)
self.reward_buffer = np.zeros(buffer_size, dtype=np.float32)
self.value_buffer = np.zeros(buffer_size, dtype=np.float32)
self.logp_buffer = np.zeros(buffer_size, dtype=np.float32)
self.adv_buffer = np.zeros(buffer_size, dtype=np.float32)
self.return_buffer = np.zeros(buffer_size, dtype=np.float32)
self.gamma, self.lambd = gamma, lambd
self.max_size = buffer_size
self.pointer, self.traj_start = 0, 0
def push(self, obs, action, reward, value, logp):
assert self.pointer < self.max_size
self.obs_buffer[self.pointer] = obs
self.action_buffer[self.pointer] = action
self.reward_buffer[self.pointer] = reward
self.value_buffer[self.pointer] = value
self.logp_buffer[self.pointer] = logp
self.pointer += 1
def get_data(self):
assert self.pointer == self.max_size
self.pointer, self.traj_start = 0, 0
self.adv_buffer = (self.adv_buffer -
self.adv_buffer.mean()) / (self.adv_buffer.std() + 1e-8)
data = dict(
obs=self.obs_buffer,
action=self.action_buffer,
reward=self.reward_buffer,
value=self.value_buffer,
logp=self.logp_buffer,
adv=self.adv_buffer,
returns=self.return_buffer,
)
return {k: torch.as_tensor(v, dtype=torch.float32) for k, v in data.items()}
def compute_trajectory_values(self, last_value=0):
trajectory = slice(self.traj_start, self.pointer)
rewards = np.append(self.reward_buffer[trajectory], last_value)
values = np.append(self.value_buffer[trajectory], last_value)
# GAE-Lambda
deltas = - values[:-1] + rewards[:-1] + values[1:] * self.gamma
weights = (
self.gamma * self.lambd) ** np.array(range(len(deltas)), dtype=np.float32)
self.adv_buffer[trajectory] = np.array([np.sum(
deltas[i:] * weights[:len(deltas)-i]) for i, _ in enumerate(deltas)], dtype=np.float32)[::-1]
# Rewards-to-go
weights = self.gamma ** np.array(range(len(rewards)), dtype=np.float32)
self.return_buffer[trajectory] = np.array(
[np.sum(rewards[i:] * weights[:len(rewards)-i]) for i, _ in enumerate(rewards)], dtype=np.float32)[::-1][:-1]
self.traj_start = self.pointer
def mlp(layer_sizes, activation, output_activation=nn.Identity):
layers = []
for i in range(len(layer_sizes) - 1):
layers.append(nn.Linear(layer_sizes[i], layer_sizes[i+1]))
if i < len(layer_sizes) - 2:
layers.append(activation())
else:
layers.append(output_activation())
return nn.Sequential(*layers)
class ActorNet(nn.Module):
def __init__(self, input_dim, n_actions, layer_sizes, activation=nn.Tanh):
super(ActorNet, self).__init__()
self.actor = mlp([input_dim] + list(layer_sizes) +
[n_actions], activation)
def forward(self, obs, action=None):
logits = self.actor(obs)
pi = Categorical(logits=logits)
logp_a = pi.log_prob(action) if (action is not None) else None
return pi, logp_a
def step(self, obs):
with torch.no_grad():
pi = Categorical(logits=self.actor(obs))
action = pi.sample()
logp_a = pi.log_prob(action)
return action.cpu().numpy(), logp_a.cpu().numpy()
class CriticNet(nn.Module):
def __init__(self, input_dim, layer_sizes, activation=nn.Tanh):
super(CriticNet, self).__init__()
self.critic = mlp([input_dim] + list(layer_sizes) +
[1], activation)
def forward(self, obs):
value = torch.squeeze(self.critic(obs), -1)
return value
def step(self, obs):
with torch.no_grad():
value = torch.squeeze(self.critic(obs), -1)
return value.cpu().numpy()
def PPO_clip(env: gym.Env, actor, critic, actor_lr, critic_lr, epochs, steps_per_epoch, gamma, lambd, clip_ratio):
ep_returns = []
ep_lens = []
buffer = ExperienceBuffer(
steps_per_epoch,
gamma,
lambd
)
policy_optimizer = Adam(actor.actor.parameters(), lr=actor_lr)
value_optimizer = Adam(critic.critic.parameters(), lr=critic_lr)
def compute_loss_actor(data):
obs, action, adv, logp_old = data['obs'].cuda(), data['action'].cuda(), data['adv'].cuda(
), data['logp'].cuda()
_, logp = actor(obs, action)
ratio = torch.exp(logp - logp_old)
clip_adv = torch.clamp(ratio, 1-clip_ratio, 1+clip_ratio) * adv
return -(torch.min(ratio * adv, clip_adv)).mean()
def compute_loss_critic(data):
obs, ret = data['obs'].cuda(), data['returns'].cuda()
value = critic(obs)
return ((value - ret)**2).mean()
def update():
data = buffer.get_data()
loss_actor_old = compute_loss_actor(data).item()
loss_critic_old = compute_loss_critic(data).item()
for i in range(5):
policy_optimizer.zero_grad()
loss_actor = compute_loss_actor(data)
loss_actor.backward()
policy_optimizer.step()
for i in range(5):
value_optimizer.zero_grad()
loss_critic = compute_loss_critic(data)
loss_critic.backward()
value_optimizer.step()
print(f'Delta loss actor: {loss_actor.item() - loss_actor_old:.4f}')
print(f'Delta loss critic: {loss_critic.item() - loss_critic_old:.4f}')
obs = env.reset()
ep_ret, ep_len = 0, 0
for epoch in range(epochs):
print(f'Epoch {epoch}')
for t in range(steps_per_epoch):
# env.render()
action, logp = actor.step(
torch.as_tensor([obs], dtype=torch.float32).cuda())
value = critic.step(torch.as_tensor(
[obs], dtype=torch.float32).cuda())
next_obs, reward, done, _ = env.step(action.item())
ep_ret += reward
ep_len += 1
buffer.push(obs, action, reward, value, logp)
obs = next_obs
epoch_ended = t == steps_per_epoch - 1
if done or epoch_ended:
if epoch_ended and not done:
print('Trajectory cut off by epoch')
if epoch_ended:
value = critic.step(
torch.as_tensor([obs], dtype=torch.float32).cuda())
else:
value = 0
buffer.compute_trajectory_values(value)
if done:
ep_returns.append(ep_ret)
ep_lens.append(ep_len)
obs = env.reset()
ep_ret, ep_len = 0, 0
update()
return ep_returns, ep_lens
def print_policy(actor, size=8):
actions_names = ['←', '↓', '→', '↑']
s = 0
print("\n\t\t Policy/Actions")
for _ in range(size):
print("------------------------------------------------")
for _ in range(size):
# Get the best action
action, _ = actor.step(
torch.tensor([s], dtype=torch.float).cuda())
s += 1
print(" %s |" % actions_names[action], end="")
print("")
print("------------------------------------------------")
def plot_episode_returns(ep_returns, title=''):
import plotly.express as px
fig = px.line(ep_returns, title='')
fig.update_layout(xaxis_title='Episode', yaxis_title='Return', title=title)
fig.show()
def plot_action_value_plotly(critic, title=''):
import plotly.graph_objects as go
fig = go.Figure()
# Generate data
grid = np.arange(0, 64, 1)
x = grid // 8
y = grid % 8
# adding surfaces to subplots.
z = np.array([critic.step(torch.tensor([s], dtype=torch.float).cuda())
for s in grid])
fig.add_trace(
go.Mesh3d(x=x, y=y, z=z, opacity=1.0, showlegend=True))
fig.update_layout(
scene_camera=dict(
up=dict(x=0, y=0, z=1),
center=dict(x=0, y=0, z=0),
eye=dict(x=1.5, y=-1.5, z=1.25)
),
scene=dict(
xaxis_title='Row',
yaxis_title='Col',
zaxis_title='V(s)'
),
title_text=title,
height=800,
width=800
)
fig.show()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--gamma', type=float, default=0.99)
parser.add_argument('--clip_ratio', type=float, default=0.3)
parser.add_argument('--actor_lr', type=float, default=3e-4)
parser.add_argument('--critic_lr', type=float, default=1e-3)
parser.add_argument('--lambd', type=float, default=0.97)
parser.add_argument('--seed', type=int, default=777)
parser.add_argument('--steps', type=int, default=4000)
parser.add_argument('--epochs', type=int, default=50)
args = parser.parse_args()
np.random.seed(args.seed)
torch.manual_seed(args.seed)
env = gym.make('FrozenLake8x8-v1', is_slippery=False)
obs_dim = env.observation_space.shape
obs_dim = 1
actions_dim = env.action_space.n
hidden_layers = [64, 64]
actor = ActorNet(obs_dim, actions_dim, hidden_layers).cuda()
critic = CriticNet(obs_dim, hidden_layers).cuda()
start = time.time()
ep_returns, ep_lens = PPO_clip(
env,
actor, critic,
actor_lr=args.actor_lr,
critic_lr=args.critic_lr,
epochs=args.epochs,
steps_per_epoch=args.steps,
gamma=args.gamma,
lambd=args.lambd,
clip_ratio=args.clip_ratio,
)
end = time.time()
print(f'Algorithm took: {end-start:.2f} seconds')
print_policy(actor)
plot_episode_returns(ep_returns)
plot_action_value_plotly(critic)
| 30.3207 | 121 | 0.590096 | 3,813 | 0.366353 | 0 | 0 | 0 | 0 | 0 | 0 | 664 | 0.063797 |
63fe55bbd1c58b24c66f67e3ef0288edddb3e0ab | 4,052 | pyw | Python | python/macRC.pyw | drs251/MacRC | 35bcf8d8b7c64d48d90fcde3aa83786f820e5b0c | [
"MIT"
] | null | null | null | python/macRC.pyw | drs251/MacRC | 35bcf8d8b7c64d48d90fcde3aa83786f820e5b0c | [
"MIT"
] | null | null | null | python/macRC.pyw | drs251/MacRC | 35bcf8d8b7c64d48d90fcde3aa83786f820e5b0c | [
"MIT"
] | null | null | null | from subprocess import Popen, PIPE
from distutils.util import strtobool
import serial
import sys
import time
import glob
import serial.tools.list_ports_posix
def run_applescript(scpt, args=()):
p = Popen(['osascript', '-'] + list(args), stdin=PIPE, stdout=PIPE)
stdout, stderr = p.communicate(scpt)
return stdout
def toggle_mute():
set_mute_script = b'''
on run {x}
set volume output muted x
end run'''
get_mute_script = b'''output muted of (get volume settings)'''
mute_status = strtobool(run_applescript(get_mute_script).strip().decode())
run_applescript(set_mute_script, [str(not mute_status)])
get_volume_script = b'''output volume of (get volume settings)'''
set_volume_script = b'''
on run {x}
set volume output volume x
end run'''
volume_increment = 6
def increase_volume():
volume = int(run_applescript(get_volume_script))
volume += 6
run_applescript(set_volume_script, [str(volume)])
def decrease_volume():
volume = int(run_applescript(get_volume_script))
volume -= 6
run_applescript(set_volume_script, [str(volume)])
def pause_itunes():
pause_itunes_script = b'''
tell application "iTunes"
pause
end tell'''
run_applescript(pause_itunes_script)
def play_itunes():
play_itunes_script = b'''
tell application "iTunes"
play
end tell'''
run_applescript(play_itunes_script)
def next_track_itunes():
next_track_itunes_script = b'''
tell application "iTunes"
next track
end tell'''
run_applescript(next_track_itunes_script)
def previous_track_itunes():
next_track_itunes_script = b'''
tell application "iTunes"
previous track
end tell'''
run_applescript(next_track_itunes_script)
def connect_arduino():
# find the arduino:
portlist = glob.glob('/dev/tty.usbmodem*')
for port in portlist:
try:
ser = serial.Serial(port=port, baudrate=9600, timeout=1)
except Exception:
continue
else:
break
else:
raise IOError("Arduino not found")
return ser
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "-v":
# print some extra information (useful for troubleshooting)
verbose = True
else:
verbose = False
error = False
try:
ser = connect_arduino()
if verbose:
print("Connected to Arduino.")
except Exception as err:
error = True
if verbose:
print("Encountered Exception while connecting: {0}".format(err))
while True:
if not error:
try:
res = ser.readline().strip().decode()
if verbose and res != '':
print("Got command " + str(res))
if res == 'L':
increase_volume()
elif res == 'S':
decrease_volume()
elif res == 'M':
toggle_mute()
elif res == 'N':
next_track_itunes()
elif res == 'B':
previous_track_itunes()
elif res == 'P':
play_itunes()
elif res == 'H':
pause_itunes()
elif verbose and res != '':
print("Unknown command: ", res)
except Exception as err:
error = True
if verbose:
print("Encountered {0} in main loop: {1}".format(err.__class__.__name__, err))
# try to reconnect to Arduino if connection is lost
if error:
time.sleep(5)
try:
ser = connect_arduino()
error = False
if verbose:
print("Reconnected to Arduino.")
except Exception as err:
error = True
if verbose:
print("Reconnect failed.")
| 26.834437 | 98 | 0.55849 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 940 | 0.231984 |
63ffa1929e247b6219607c1f68157af18847d3fb | 4,275 | py | Python | tryopenapi.py | fakegit/eave | 3b4e5183a3f6df952685d63cf983d03c2157dff6 | [
"MIT"
] | null | null | null | tryopenapi.py | fakegit/eave | 3b4e5183a3f6df952685d63cf983d03c2157dff6 | [
"MIT"
] | null | null | null | tryopenapi.py | fakegit/eave | 3b4e5183a3f6df952685d63cf983d03c2157dff6 | [
"MIT"
] | null | null | null |
import json
import yaml
import dnode
from eave import *
openapi_yaml = open('openapi.yaml').read()
openapi_json = open('openapi.json').read()
yaml_data = yaml.safe_load(openapi_yaml)
json_data = json.loads(openapi_json)
assert yaml_data == json_data
class DNode(dnode.DNode):
def __getattr__(self, item):
if item not in self.fields:
return None
return super().__getattr__(item)
root = DNode(json_data)
doc = Doc()
info = root.info
if info:
doc.title = info.title or ''
doc.version = info.version or doc.version
doc.description = info.description or ''
servers = root.servers
if servers:
hosts = []
for server in servers:
h = server.url
description = server.description
if description:
h += f'({description})'
hosts.append(h)
doc.host = ', '.join(hosts)
paths = root.paths
for path, operations in root.paths.items():
# print(path)
for method, operation in operations.items():
operation = DNode(operation)
# print(method)
# print(operation)
api = Api()
api.url = path
api.title = operation.summary or operation.description or operation.operationId
api.description = operation.description
api.method = method.upper()
api.params = []
api.content_types = []
parameters = operation.parameters or []
requestBody = operation.requestBody
responses = operation.responses or []
for parameter in parameters:
category = parameter.get('in')
name = parameter.name
required = parameter.required or False
description = parameter.description or ''
# todo: support deprecated and allowEmptyValue
deprecated = parameter.deprecated
allowEmptyValue = parameter.allowEmptyValue
type = 'string'
example = ''
schema = parameter.schema
if schema:
type = schema.type or type
example = schema.example or example
# in: "path", "query", "cookie", "header"
p = None
if category == 'path':
p = PathParam()
elif category == 'query':
p = QueryParam()
p.required = required
elif category == 'cookie':
# todo: support cookie parameters
pass
elif category == 'header':
# todo: support header parameters
pass
if p:
p.name = name
p.description = description
p.type = type
p.example = example
p.default = ''
api.params.append(p)
if requestBody and requestBody.content:
param_names = []
for content_type, value in requestBody.content.items():
content = DNode(value)
api.content_types.append(content_type)
properties = content.schema and content.schema.properties or {}
required_names = content.schema and content.schema.required or []
for param_name, value in properties.items():
if param_name in param_names:
continue
param = DNode(value)
p = BodyParam()
p.name = param_name
p.type = param.type
p.description = param.description or ''
p.required = param_name in required_names
api.params.append(p)
param_names.append(param_name)
api.make_body_example()
# todo: support response
response_description = ''
response_example = ''
doc.add_api(api)
doc.build('openapi.html', 'zh')
# todo: support more
# root.security
# root.externalDocs
# root.components
# root.components.schemas
# root.components.responses
# root.components.parameters
# root.components.examples
# root.components.requestBodies
# root.components.headers
# root.components.securitySchemes
# root.components.links
# root.components.callbacks
| 28.311258 | 87 | 0.564211 | 164 | 0.038363 | 0 | 0 | 0 | 0 | 0 | 0 | 664 | 0.155322 |
63fffacd17d14f9d91e78c33cd2cb358957bdfb0 | 12,939 | py | Python | memory.py | Matioz/World-Models | e0eb98b78b4fa6b8828fef8098f867a4ccf06a36 | [
"MIT"
] | 9 | 2018-08-21T14:25:50.000Z | 2021-12-15T12:10:51.000Z | memory.py | Matioz/World-Models | e0eb98b78b4fa6b8828fef8098f867a4ccf06a36 | [
"MIT"
] | 5 | 2018-08-25T10:29:05.000Z | 2018-09-19T15:18:40.000Z | memory.py | Matioz/World-Models | e0eb98b78b4fa6b8828fef8098f867a4ccf06a36 | [
"MIT"
] | 3 | 2018-10-01T00:55:12.000Z | 2019-05-09T07:33:31.000Z | import logging as log
import numpy as np
import h5py
import humblerl as hrl
from humblerl import Callback, Interpreter
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
from torch.utils.data import Dataset
from common_utils import get_model_path_if_exists
from third_party.torchtrainer import TorchTrainer, evaluate
class MDNInterpreter(Interpreter, Callback):
"""Performs state preprocessing with VAE module and concatenates it with hidden state of MDN module.
Args:
vae_model (keras.Model): Keras VAE encoder.
mdn_model (torch.nn.Module): PyTorch MDN-RNN memory.
latent_dim (int): Latent space dimensionality.
Note:
In order to work, this Interpreter system must be also passed as callback to 'hrl.loop(...)'!
"""
def __init__(self, vae_model, mdn_model, latent_dim):
self.vae_model = vae_model
self.mdn_model = mdn_model
self.latent_dim = latent_dim
def __call__(self, state, reward=0.):
return self.process_state(state), reward
def process_state(self, state):
# NOTE: [0][0] <- it gets first in the batch latent space mean (mu)
latent = self.vae_model.predict(state[np.newaxis, :])[0][0]
memory = self.mdn_model.hidden[0].cpu().detach().numpy()
# NOTE: See HRL `ply`, `on_step_taken` that would update hidden state is called AFTER
# Interpreter is used to preprocess next_state. So next_state has out-dated hidden state!
# What saves us is the fact, that `state` in next `ply` call will have it updated so,
# Transitions.state has up-to-date latent and hidden state and in all the other places
# exactly it is used, not next state.
return np.concatenate((latent, memory.flatten()))
def on_episode_start(self, episode, train_mode):
self.mdn_model.init_hidden(1)
def on_step_taken(self, step, transition, info):
state = torch.from_numpy(transition.state[:self.latent_dim]).view(1, 1, -1)
action = torch.from_numpy(np.array([transition.action])).view(1, 1, -1)
if torch.cuda.is_available():
state = state.cuda()
action = action.cuda()
with torch.no_grad(), evaluate(self.mdn_model) as net:
net(state, action)
class MDNDataset(Dataset):
"""Dataset of sequential data to train MDN-RNN.
Args:
dataset_path (string): Path to HDF5 dataset file.
sequence_len (int): Desired output sequence len.
terminal_prob (float): Probability of sampling sequence that finishes with
terminal state. (Default: 0.5)
Note:
Arrays should have the same size of the first dimension and their type should be the
same as desired Tensor type.
"""
def __init__(self, dataset_path, sequence_len, terminal_prob=0.5, dataset_fraction=1.):
assert 0 < terminal_prob and terminal_prob <= 1.0, "0 < terminal_prob <= 1.0"
assert 0 < dataset_fraction and dataset_fraction <= 1.0, "0 < dataset_fraction <= 1.0"
self.dataset = h5py.File(dataset_path, "r")
self.sequence_len = sequence_len
self.terminal_prob = terminal_prob
self.dataset_fraction = dataset_fraction
self.latent_dim = self.dataset.attrs["LATENT_DIM"]
self.action_dim = self.dataset.attrs["ACTION_DIM"]
def __getitem__(self, idx):
"""Get sequence at random starting position of given sequence length from episode `idx`."""
offset = 1
t_start, t_end = self.dataset['episodes'][idx:idx + 2]
episode_length = t_end - t_start
if self.sequence_len <= episode_length - offset:
sequence_len = self.sequence_len
else:
sequence_len = episode_length - offset
log.warning(
"Episode %d is too short to form full sequence, data will be zero-padded.", idx)
# Sample where to start sequence of length `self.sequence_len` in episode `idx`
# '- offset' because "next states" are offset by 'offset'
if np.random.rand() < self.terminal_prob:
# Take sequence ending with terminal state
start = t_start + episode_length - sequence_len - offset
else:
# NOTE: np.random.randint takes EXCLUSIVE upper bound of range to sample from
start = t_start + np.random.randint(max(1, episode_length - sequence_len - offset))
states_ = torch.from_numpy(self.dataset['states'][start:start + sequence_len + offset])
actions_ = torch.from_numpy(self.dataset['actions'][start:start + sequence_len])
states = torch.zeros(self.sequence_len, self.latent_dim, dtype=states_.dtype)
next_states = torch.zeros(self.sequence_len, self.latent_dim, dtype=states_.dtype)
actions = torch.zeros(self.sequence_len, self.action_dim, dtype=actions_.dtype)
# Sample latent states (this is done to prevent overfitting MDN-RNN to a specific 'z'.)
mu = states_[:, 0]
sigma = torch.exp(states_[:, 1] / 2)
latent = Normal(loc=mu, scale=sigma)
z_samples = latent.sample()
states[:sequence_len] = z_samples[:-offset]
next_states[:sequence_len] = z_samples[offset:]
actions[:sequence_len] = actions_
return [states, actions], [next_states]
def __len__(self):
return int(self.dataset.attrs["N_GAMES"] * self.dataset_fraction)
def close(self):
self.dataset.close()
class MDN(nn.Module):
def __init__(self, hidden_units, latent_dim, action_space, temperature, n_gaussians, num_layers=1):
super(MDN, self).__init__()
self.hidden_units = hidden_units
self.latent_dim = latent_dim
self.temperature = temperature
self.n_gaussians = n_gaussians
self.num_layers = num_layers
self.embedding = nn.Embedding.from_pretrained(torch.eye(action_space.num)) \
if isinstance(action_space, hrl.environments.Discrete) else None
self.lstm = nn.LSTM(input_size=(latent_dim + action_space.num),
hidden_size=hidden_units,
num_layers=num_layers,
batch_first=True)
self.pi = nn.Linear(hidden_units, n_gaussians * latent_dim)
self.mu = nn.Linear(hidden_units, n_gaussians * latent_dim)
self.logsigma = nn.Linear(hidden_units, n_gaussians * latent_dim)
# NOTE: This is here only for backward compatibility with trained checkpoint
self.reward = nn.Linear(hidden_units, 1)
def forward(self, latent, action, hidden=None):
self.lstm.flatten_parameters()
sequence_len = latent.size(1)
if self.embedding:
# Use one-hot representation for discrete actions
x = torch.cat((latent, self.embedding(action).squeeze(dim=2)), dim=2)
else:
# Pass raw action vector for continuous actions
x = torch.cat((latent, action.float()), dim=2)
h, self.hidden = self.lstm(x, hidden if hidden else self.hidden)
pi = self.pi(h).view(-1, sequence_len, self.n_gaussians, self.latent_dim) / self.temperature
pi = torch.softmax(pi, dim=2)
logsigma = self.logsigma(h).view(-1, sequence_len, self.n_gaussians, self.latent_dim)
sigma = torch.exp(logsigma)
mu = self.mu(h).view(-1, sequence_len, self.n_gaussians, self.latent_dim)
return mu, sigma, pi
def sample(self, latent, action, hidden=None):
"""Sample (simulate) next state from Mixture Density Network a.k.a. Gaussian Mixture Model.
Args:
latent (torch.Tensor): Latent vectors to start from.
Shape of tensor: batch x sequence x latent dim.
action (torch.Tensor): Actions to simulate.
Shape of tensor: batch x sequence x action dim.
hidden (tuple): Memory module (torch.nn.LSTM) hidden state.
Return:
numpy.ndarray: Latent vector of next state.
Shape of array: batch x sequence x latent dim.
Note:
You can find next hidden state in this module `hidden` member.
"""
# Simulate transition
with torch.no_grad(), evaluate(self) as net:
mu, sigma, pi = net(latent, action, hidden)
# Transform tensors to numpy arrays and move "gaussians mixture" dim to the end
# NOTE: Arrays will have shape (batch x sequence x latent dim. x num. gaussians)
mu = np.transpose(mu.cpu().detach().numpy(), axes=[0, 1, 3, 2])
sigma = np.transpose(sigma.cpu().detach().numpy(), axes=[0, 1, 3, 2])
pi = np.transpose(pi.cpu().detach().numpy(), axes=[0, 1, 3, 2])
# Sample parameters of Gaussian distribution(s) from mixture
c = pi.cumsum(axis=-1)
u = np.random.rand(*c.shape[:-1], 1)
choices = np.expand_dims((u < c).argmax(axis=-1), axis=-1)
# Sample latent vector from Gaussian distribution with mean and std. dev. from above
mean = np.take_along_axis(mu, choices, axis=-1)
stddev = np.take_along_axis(sigma, choices, axis=-1)
samples = mean + stddev * np.random.randn(*mean.shape)
return np.squeeze(samples, axis=-1)
def simulate(self, latent, actions):
"""Simulate environment trajectory.
Args:
latent (torch.Tensor): Latent vector with state(s) to start from.
Shape of tensor: batch x 1 (sequence dim.) x latent dim.
actions (torch.Tensor): Tensor with actions to take in simulated trajectory.
Shape of tensor: batch x sequence x action dim.
Return:
np.ndarray: Array of latent vectors of simulated trajectory.
Shape of array: batch x sequence x latent dim.
Note:
You can find next hidden state in this module `hidden` member.
"""
states = []
for a in range(actions.shape[1]):
# NOTE: We use np.newaxis to preserve shape of tensor.
states.append(self.sample(latent, actions[:, a, np.newaxis, :]))
# NOTE: This is a bit arbitrary to set it to float32 which happens to be type of torch
# tensors. It can blow up further in code if we'll choose to change tensors types.
latent = torch.from_numpy(states[-1]).float().to(next(self.parameters()).device)
# NOTE: Squeeze former sequence dim. (which is 1 because we inferred next latent state
# action by action) and reorder batch dim. and list sequence dim. to finally get:
# batch x len(states) (sequence dim.) x latent dim.
return np.transpose(np.squeeze(np.array(states), axis=2), axes=[1, 0, 2])
def init_hidden(self, batch_size):
device = next(self.parameters()).device
self.hidden = (
torch.zeros(self.num_layers, batch_size, self.hidden_units, device=device),
torch.zeros(self.num_layers, batch_size, self.hidden_units, device=device)
)
def build_rnn_model(rnn_params, latent_dim, action_space, model_path=None):
"""Builds MDN-RNN memory module, which model time dependencies.
Args:
rnn_params (dict): MDN-RNN parameters from .json config.
latent_dim (int): Latent space dimensionality.
action_space (hrl.environments.ActionSpace): Action space, discrete or continuous.
model_path (str): Path to VAE ckpt. Taken from .json config if `None` (Default: None)
Returns:
TorchTrainer: Compiled MDN-RNN model wrapped in TorchTrainer, ready for training.
"""
use_cuda = torch.cuda.is_available()
def mdn_loss_function(pred, target):
"""Mixed Density Network loss function, see:
https://mikedusenberry.com/mixture-density-networks"""
mu, sigma, pi = pred
sequence_len = mu.size(1)
latent_dim = mu.size(3)
target = target.view(-1, sequence_len, 1, latent_dim)
loss = Normal(loc=mu, scale=sigma)
loss = torch.exp(loss.log_prob(target)) # TODO: Is this stable?! Check that.
loss = torch.sum(loss * pi, dim=2)
loss = -torch.log(loss + 1e-9)
return torch.mean(loss)
mdn = TorchTrainer(MDN(rnn_params['hidden_units'], latent_dim, action_space,
rnn_params['temperature'], rnn_params['n_gaussians']),
device_name='cuda' if use_cuda else 'cpu')
mdn.compile(
optimizer=optim.Adam(mdn.model.parameters(), lr=rnn_params['learning_rate']),
loss=mdn_loss_function
)
model_path = get_model_path_if_exists(
path=model_path, default_path=rnn_params['ckpt_path'], model_name="MDN-RNN")
if model_path is not None:
mdn.load_ckpt(model_path)
log.info("Loaded MDN-RNN model weights from: %s", model_path)
return mdn
| 42.00974 | 104 | 0.64464 | 10,730 | 0.829276 | 0 | 0 | 0 | 0 | 0 | 0 | 4,933 | 0.38125 |
12004752447a3c322e24283675f1768106bc32b5 | 761 | py | Python | wagtailrelated/utils.py | torchbox/wagtail-related | b0e811e5093d6d5c1554cab66f3c5097d6d474ad | [
"BSD-3-Clause"
] | 2 | 2018-09-03T15:09:30.000Z | 2020-11-29T02:23:01.000Z | wagtailrelated/utils.py | torchbox/wagtail-related | b0e811e5093d6d5c1554cab66f3c5097d6d474ad | [
"BSD-3-Clause"
] | null | null | null | wagtailrelated/utils.py | torchbox/wagtail-related | b0e811e5093d6d5c1554cab66f3c5097d6d474ad | [
"BSD-3-Clause"
] | null | null | null | from bs4 import BeautifulSoup
from wagtail.core.fields import StreamField
def extract_text(obj):
"""Extracts data, concatenates and removes html tags
from fields listed in a obj.related_source_fields list.
"""
related_source_fields = getattr(obj._meta.model, 'related_source_fields', None)
if not related_source_fields:
return
html_pieces = []
for source_field in related_source_fields:
field = source_field.get_field(obj.__class__)
field_value = source_field.get_value(obj)
if isinstance(field, StreamField):
field_value = ' '.join(field_value)
html_pieces.append(field_value)
text = ' '.join(html_pieces)
text = BeautifulSoup(text, 'html5lib').text
return text
| 29.269231 | 83 | 0.703022 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 159 | 0.208936 |
12012366643f4f22b21641dcce1d6d36c1aaaf3a | 1,233 | py | Python | codes/globo_videos_cuts/core/tests/models/programs_model_test_case.py | lariodiniz/teste_meta | 3bf043df3ee76871d68a3f8aea7c3ecd53765fec | [
"MIT"
] | null | null | null | codes/globo_videos_cuts/core/tests/models/programs_model_test_case.py | lariodiniz/teste_meta | 3bf043df3ee76871d68a3f8aea7c3ecd53765fec | [
"MIT"
] | null | null | null | codes/globo_videos_cuts/core/tests/models/programs_model_test_case.py | lariodiniz/teste_meta | 3bf043df3ee76871d68a3f8aea7c3ecd53765fec | [
"MIT"
] | null | null | null | # coding: utf-8
__author__ = "Lário dos Santos Diniz"
from django.test import TestCase
from model_mommy import mommy
from core.models import Programs
class ProgramsModelTestCase(TestCase):
"""Class Testing Model Pogramas """
def setUp(self):
"""
Initial Test Settings
"""
self.program = mommy.make(Programs)
def tearDown(self):
"""Final method"""
self.program.delete()
def test_there_are_fields(self):
"""test the fields the model"""
self.assertTrue('title' in dir(Programs), 'Class Program does not have the field title')
self.assertTrue('start_time' in dir(Programs), 'Class Program does not have the field start_time')
self.assertTrue('end_time' in dir(Programs), 'Class Program does not have the field end_time')
def test_there_is_a_program(self):
"""test if you are creating a Program correctly"""
self.assertEquals(Programs.objects.count(), 1)
self.assertEquals(Programs.objects.all()[0].title, self.program.title)
self.assertEquals(Programs.objects.all()[0].start_time, self.program.start_time)
self.assertEquals(Programs.objects.all()[0].end_time, self.program.end_time)
| 33.324324 | 106 | 0.680454 | 1,079 | 0.874392 | 0 | 0 | 0 | 0 | 0 | 0 | 391 | 0.316856 |
1201648d14db637a8c539982bbb05d716a282c19 | 8,002 | py | Python | figures/plot_occurrence.py | wdlynch/symbolic_experiments | 8c0c9bf93edc8f58ed1e027cf5704dadd57e853a | [
"MIT"
] | null | null | null | figures/plot_occurrence.py | wdlynch/symbolic_experiments | 8c0c9bf93edc8f58ed1e027cf5704dadd57e853a | [
"MIT"
] | null | null | null | figures/plot_occurrence.py | wdlynch/symbolic_experiments | 8c0c9bf93edc8f58ed1e027cf5704dadd57e853a | [
"MIT"
] | 1 | 2022-01-25T18:35:44.000Z | 2022-01-25T18:35:44.000Z |
import os
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import rcParams
params = {
# 'text.latex.preamble': ['\\usepackage{gensymb}'],
# 'text.usetex': True,
'font.family': 'Helvetica',
'lines.solid_capstyle':'butt',
'lines.markeredgewidth': 1,
}
rcParams.update(params)
sns.set_context("paper", font_scale=1.6, rc={"lines.linewidth": 2})
sns.set_style('white')
sns.set_palette("cividis")
dir_path = os.path.dirname(os.path.realpath(__file__))
def main():
sens = pd.read_csv('model_sensitivities.csv',header=0,index_col=0) # ,low_memory=False)
occu = pd.read_csv('sc_occurrence_data.csv',header=0,index_col=0)
occu.index = [val if val[6] is not '_' else val[:6] + val[7:] for val in occu.index.values] # oops, used two naming conventions
occu['cluster'] = [sens.loc[((sens['model_id']==i) & (sens['experiment']=='classification')),'cluster'].values[0] for i in occu.index.values]
clust_list = ['Dominated Cluster','Overfit Cluster','Parsimonious Cluster',]
occu = occu[[True if i in [1,2,3] else False for i in occu['cluster'].values]]
occu['Cluster'] = [clust_list[i-1] for i in occu['cluster']]
occu = occu.drop(['training_error', 'complexity', 'test_error','cluster'],axis=1)
occu[occu.columns[:-1]] = occu[occu.columns[:-1]] > 0
occu = occu.groupby(['Cluster']).sum()
inpu = occu[occu.columns[:-9]].stack()
inputs = pd.DataFrame()
inputs['Cluster'] = inpu.index.get_level_values(0)
inputs['Input'] = inpu.index.get_level_values(1)
inputs['category'] = [categorize(i) for i in inputs['Input'].values]
inputs['Category'] = [translate(i) for i in inputs['category'].values]
inputs['Lag'] = [lag(i) for i in inputs['Input'].values]
inputs['Neighbor'] = [neighbor(i) for i in inputs['Input'].values]
inputs['Occurrence'] = inpu.values
func = occu[occu.columns[-9:]].stack()
functions = pd.DataFrame()
functions['Cluster'] = func.index.get_level_values(0)
functions['Function'] = [func_trans(i) for i in func.index.get_level_values(1)]
functions['Occurrence'] = func.values
plots = {'category':'Category',
'neighborhood':'Neighborhood',
'lag':'Lag'
} # three in total
orders = {'category':['land_tree','land_non','water_pump','water_deliv','econ_tree','econ_non'],
'neighborhood':['home','neighbor_1','neighbor_2','neighbor_3','neighbor_4','neighbor_5'],
'lag':['present','lag1','lag2','lag3','lag4','lag5','lag6'],
'function':['Addition','Subtraction','Multiplication','Division','Negative','Sine','Cosine','Less Than','If-Then-Else'],
'Category':['Tree Acreage','Non-Tree Acreage','Tree Prices/Values','Non-Tree Prices/Values','Water Deliveries','Water Pumping'],
'Cluster':['Parsimonious Cluster','Dominated Cluster','Overfit Cluster'],
# 'color':['midnightblue','Red']
}
colors = ['midnightblue','Red','Blue'] #,'c','m','y','b']
fig, axes = plt.subplots(1,2,figsize=(8,6))
g2 = sns.boxplot(x='Occurrence',
y='Category',
order=orders['Category'],
hue='Cluster',
hue_order=orders['Cluster'],
data=inputs,
whis='range',
dodge=True,
# width=0.8,
linewidth=2,
palette=colors,
ax=axes[0],
)
g1 = sns.scatterplot(x='Occurrence',
y='Function',
marker='o',
palette=colors,
s=100,
alpha=0.9,
hue='Cluster',
hue_order=orders['Cluster'],
data=functions,
ax=axes[1]
)
adjust_box_widths(fig, 0.8)
for i,artist in enumerate(axes[0].artists):
# Set the linecolor on the artist to the facecolor, and set the facecolor to None
col = artist.get_facecolor()
artist.set_edgecolor(col)
artist.set_facecolor('None')
# Each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.)
# Loop over them here, and use the same colour as above
for j in range(i*6,i*6+6):
line = axes[0].lines[j]
line.set_color(col)
line.set_mfc(col)
line.set_mec(col)
line.set_solid_capstyle('butt')
med_line = axes[0].lines[i*6+4].set_ydata(axes[0].lines[i*6+2].get_ydata())
axes[0].set_xscale('log')
axes[0].legend_.remove()
axes[1].legend_.remove()
axes[1].legend(frameon=False,markerscale=2,bbox_to_anchor=(1, 1),ncol=4,bbox_transform=plt.gcf().transFigure)
axes[1].yaxis.set_label_position("right")
axes[1].yaxis.tick_right()
axes[0].text(x= 0.95,y=0.8,s='(A)',ha='right',va='top',transform=axes[0].transAxes)
axes[1].text(x= 0.05,y=0.8,s='(B)',ha='left',va='top',transform=axes[1].transAxes)
# for patch in axes[0].artists:
# r, g, b, a = patch.get_facecolor()
# patch.set_facecolor((r, g, b, .9))
# plt.tight_layout()
plt.subplots_adjust(wspace=0.05)
fig.savefig('plot_occurrence.pdf',format='pdf',bbox_inches='tight',dpi=600,transparent=True)
from matplotlib.patches import PathPatch
def adjust_box_widths(g, fac):
"""
Adjust the withs of a seaborn-generated boxplot.
"""
# iterating through Axes instances
for ax in g.axes:
# iterating through axes artists:
for i,c in enumerate(ax.get_children()):
# searching for PathPatches
if isinstance(c, PathPatch):
# getting current width of box:
p = c.get_path()
verts = p.vertices
# print(verts)
verts_sub = verts[:-1]
xmin = np.min(verts_sub[:, 1])
xmax = np.max(verts_sub[:, 1])
xmid = 0.5*(xmin+xmax)
xhalf = 0.5*(xmax - xmin)
# setting new width of box
xmin_new = xmid-fac*xhalf
xmax_new = xmid+fac*xhalf
verts_sub[verts_sub[:, 1] == xmin, 1] = xmin_new
verts_sub[verts_sub[:, 1] == xmax, 1] = xmax_new
# setting new width of median line
for l in ax.lines:
if np.all(l.get_xdata() == [xmin, xmax]):
l.set_xdata([xmin_new, xmax_new])
def categorize(term):
trees = ['ALMOND','ALMONDHULLS','APRICOT','NECTARINES','PISTACHIO','PLUMS','WALNUT']
if ('ppu' in term) or ('value' in term):
if any(tree in term for tree in trees):
category = 'econ_tree'
else:
category = 'econ_non'
elif 'Pump' in term or 'Deliv' in term:
if 'Pump' in term:
category = 'water_pump'
else:
category = 'water_deliv'
elif 'tree' in term:
category = 'land_tree'
elif 'non_' in term:
category = 'land_non'
else:
category = 'none'
return category
def lag(term):
lags = ['lag1','lag2','lag3','lag4','lag5','lag6']
if any(lag_ in term for lag_ in lags):
lag = lags[np.argmax([lag_ in term for lag_ in lags])]
else:
lag = 'present'
return lag
def neighbor(term):
if 'neighbor' in term:
neighbor = term[:10]
else:
neighbor = 'home'
return neighbor
def func_trans(term):
if term == 'lt':
return 'Less Than'
elif term == 'ite':
return 'If-Then-Else'
elif term == 'vadd':
return 'Addition'
elif term == 'vsub':
return 'Subtraction'
elif term == 'vmul':
return 'Multiplication'
elif term == 'vdiv':
return 'Division'
elif term == 'vneg':
return 'Negative'
elif term == 'vsin':
return 'Sine'
elif term == 'vcos':
return 'Cosine'
def translate(item):
if item == 'land_tree':
return 'Tree Acreage'
if item == 'land_non':
return 'Non-Tree Acreage'
if item == 'water_pump':
return 'Water Pumping'
if item == 'water_deliv':
return 'Water Deliveries'
if item == 'econ_tree':
return 'Tree Prices/Values'
if item == 'econ_non':
return 'Non-Tree Prices/Values'
if item == 'home':
return 'Current Plot Data'
if item == 'neighbor_1':
return 'Neighbor 1 Data'
if item == 'neighbor_2':
return 'Neighbor 2 Data'
if item == 'neighbor_3':
return 'Neighbor 3 Data'
if item == 'neighbor_4':
return 'Neighbor 4 Data'
if item == 'neighbor_5':
return 'Neighbor 5 Data'
if item == 'present':
return 'Present Data'
if item == 'lag1':
return "Previous Year's Data"
if item == 'lag2':
return 'Two Years Previous'
if item == 'lag3':
return 'Three Years Previous'
if item == 'lag4':
return 'Four Years Previous'
if item == 'lag5':
return 'Five Years Previous'
if item == 'lag6':
return 'Six Years Previous'
if __name__ == "__main__":
main()
| 29.970037 | 142 | 0.661335 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,009 | 0.376031 |
1201b7d36d1bc8f3a1d15295c1c59670a006d89d | 1,164 | py | Python | Chapter04/apriori.py | PacktPublishing/Mastering-Machine-Learning-Algorithms-Second-Edition | 706d76fdb91b8c59223879cb236ce2bb6cc7e768 | [
"MIT"
] | 40 | 2019-08-23T13:33:12.000Z | 2022-02-24T12:48:41.000Z | Chapter04/apriori.py | PacktPublishing/Mastering-Machine-Learning-Algorithms-Second-Edition | 706d76fdb91b8c59223879cb236ce2bb6cc7e768 | [
"MIT"
] | null | null | null | Chapter04/apriori.py | PacktPublishing/Mastering-Machine-Learning-Algorithms-Second-Edition | 706d76fdb91b8c59223879cb236ce2bb6cc7e768 | [
"MIT"
] | 33 | 2019-10-21T09:47:51.000Z | 2022-01-14T17:21:54.000Z | import numpy as np
# Install the library using: pip install -U efficient-apriori
from efficient_apriori import apriori
# Set random seed for reproducibility
np.random.seed(1000)
nb_users = 100
nb_products = 100
if __name__ == "__main__":
# Create the dataset
items = [i for i in range(nb_products)]
transactions = []
ratings = np.zeros(shape=(nb_users, nb_products),
dtype=np.int)
for i in range(nb_users):
n_items = np.random.randint(2, 60)
transaction = tuple(
np.random.choice(items,
replace=False,
size=n_items))
transactions.append(
list(map(lambda x: "P{}".format(x + 1),
transaction)))
for t in transaction:
rating = np.random.randint(1, 11)
ratings[i, t] = rating
_, rules = apriori(transactions,
min_support=0.15,
min_confidence=0.75,
max_length=3,
verbosity=1)
print("No. rules: {}".format(len(rules)))
for r in rules:
print(r) | 25.304348 | 61 | 0.534364 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 148 | 0.127148 |
12027780d9f17722cbac1d89fef4396c4df419ca | 1,202 | py | Python | graph_nn-master/utils.py | allisontam/graph_coattention | 5edc98615d5526269452b519bb13512ec5e952da | [
"MIT"
] | null | null | null | graph_nn-master/utils.py | allisontam/graph_coattention | 5edc98615d5526269452b519bb13512ec5e952da | [
"MIT"
] | null | null | null | graph_nn-master/utils.py | allisontam/graph_coattention | 5edc98615d5526269452b519bb13512ec5e952da | [
"MIT"
] | null | null | null | import numpy as np
def split_ids(args, ids, folds=10):
if args.dataset == 'COLORS-3':
assert folds == 1, 'this dataset has train, val and test splits'
train_ids = [np.arange(500)]
val_ids = [np.arange(500, 3000)]
test_ids = [np.arange(3000, 10500)]
elif args.dataset == 'TRIANGLES':
assert folds == 1, 'this dataset has train, val and test splits'
train_ids = [np.arange(30000)]
val_ids = [np.arange(30000, 35000)]
test_ids = [np.arange(35000, 45000)]
else:
n = len(ids)
stride = int(np.ceil(n / float(folds)))
test_ids = [ids[i: i + stride] for i in range(0, n, stride)]
assert np.all(
np.unique(np.concatenate(test_ids)) == sorted(ids)), 'some graphs are missing in the test sets'
assert len(test_ids) == folds, 'invalid test sets'
train_ids = []
for fold in range(folds):
train_ids.append(np.array([e for e in ids if e not in test_ids[fold]]))
assert len(train_ids[fold]) + len(test_ids[fold]) == len(
np.unique(list(train_ids[fold]) + list(test_ids[fold]))) == n, 'invalid splits'
return train_ids, test_ids | 42.928571 | 107 | 0.591514 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 188 | 0.156406 |
1203c3903ddc96149a5651577ae2b0829fdbb6b4 | 498 | py | Python | dingus/block.py | ricott1/dingus | ef0edd9fff164f54171b354714e600f410a3bbe9 | [
"MIT"
] | null | null | null | dingus/block.py | ricott1/dingus | ef0edd9fff164f54171b354714e600f410a3bbe9 | [
"MIT"
] | null | null | null | dingus/block.py | ricott1/dingus | ef0edd9fff164f54171b354714e600f410a3bbe9 | [
"MIT"
] | null | null | null | import dingus.codec
import utils
import transaction
class BlockHeader(object):
VERSION = 0
def __init__(
self,
) -> None:
raise NotImplementedError
class Block(object):
VERSION = 0
def __init__(
self,
header: BlockHeader,
payload: list[transaction.Transaction],
fee: int,
asset_schema: GeneratedProtocolMessageType,
asset_params: dict,
strict: bool,
) -> None:
raise NotImplementedError
| 17.172414 | 51 | 0.616466 | 439 | 0.881526 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
120470c227d9ba2b49eaf7b4e99557346482221f | 34,609 | py | Python | sigpy/block.py | EfratShimron/sigpy | d140abf0fe7268851aec3be74d238a5ba8d2dd28 | [
"BSD-3-Clause"
] | null | null | null | sigpy/block.py | EfratShimron/sigpy | d140abf0fe7268851aec3be74d238a5ba8d2dd28 | [
"BSD-3-Clause"
] | null | null | null | sigpy/block.py | EfratShimron/sigpy | d140abf0fe7268851aec3be74d238a5ba8d2dd28 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""Block reshape functions.
"""
import numpy as np
import numba as nb
from sigpy import backend, config, util
__all__ = ['array_to_blocks', 'blocks_to_array']
def array_to_blocks(input, blk_shape, blk_strides):
"""Extract blocks from an array in a sliding window manner.
Args:
input (array): input array of shape [..., N_1, ..., N_D]
blk_shape (tuple): block shape of length D, with D <= 4.
blk_strides (tuple): block strides of length D.
Returns:
array: array of shape [...] + num_blks + blk_shape, where
num_blks = (N - blk_shape + blk_strides) // blk_strides.
Example:
>>> input = np.array([0, 1, 2, 3, 4, 5])
>>> print(array_to_blocks(input, [2], [2]))
[[0, 1],
[2, 3],
[4, 5]]
"""
if len(blk_shape) != len(blk_strides):
raise ValueError('blk_shape must have the same length as blk_strides.')
D = len(blk_shape)
num_blks = [(i - b + s) // s for i, b,
s in zip(input.shape[-D:], blk_shape, blk_strides)]
batch_shape = list(input.shape[:-D])
batch_size = util.prod(batch_shape)
device = backend.get_device(input)
xp = device.xp
with device:
output = xp.zeros([batch_size] + num_blks + blk_shape,
dtype=input.dtype)
input = input.reshape([batch_size] + list(input.shape[-D:]))
if D == 1:
if device == backend.cpu_device:
_array_to_blocks1(output, input,
batch_size,
blk_shape[-1],
blk_strides[-1],
num_blks[-1])
else: # pragma: no cover
_array_to_blocks1_cuda(input,
batch_size,
blk_shape[-1],
blk_strides[-1],
num_blks[-1],
output,
size=batch_size *
num_blks[-1] * blk_shape[-1])
elif D == 2:
if device == backend.cpu_device:
_array_to_blocks2(output, input,
batch_size, blk_shape[-1], blk_shape[-2],
blk_strides[-1], blk_strides[-2],
num_blks[-1], num_blks[-2])
else: # pragma: no cover
_array_to_blocks2_cuda(input,
batch_size,
blk_shape[-1], blk_shape[-2],
blk_strides[-1], blk_strides[-2],
num_blks[-1], num_blks[-2],
output,
size=batch_size *
num_blks[-1] * num_blks[-2] *
blk_shape[-1] * blk_shape[-2])
elif D == 3:
if device == backend.cpu_device:
_array_to_blocks3(output,
input,
batch_size,
blk_shape[-1],
blk_shape[-2],
blk_shape[-3],
blk_strides[-1],
blk_strides[-2],
blk_strides[-3],
num_blks[-1],
num_blks[-2],
num_blks[-3])
else: # pragma: no cover
_array_to_blocks3_cuda(input,
batch_size,
blk_shape[-1], blk_shape[-2],
blk_shape[-3],
blk_strides[-1], blk_strides[-2],
blk_strides[-3],
num_blks[-1], num_blks[-2],
num_blks[-3],
output,
size=batch_size *
num_blks[-1] * num_blks[-2] *
num_blks[-3] *
blk_shape[-1] * blk_shape[-2] *
blk_shape[-3])
elif D == 4:
if device == backend.cpu_device:
_array_to_blocks4(output,
input,
batch_size,
blk_shape[-1],
blk_shape[-2],
blk_shape[-3],
blk_shape[-4],
blk_strides[-1],
blk_strides[-2],
blk_strides[-3],
blk_strides[-4],
num_blks[-1],
num_blks[-2],
num_blks[-3],
num_blks[-4])
else: # pragma: no cover
_array_to_blocks4_cuda(input,
batch_size,
blk_shape[-1], blk_shape[-2],
blk_shape[-3], blk_shape[-4],
blk_strides[-1], blk_strides[-2],
blk_strides[-3], blk_strides[-4],
num_blks[-1], num_blks[-2],
num_blks[-3], num_blks[-4],
output,
size=batch_size *
num_blks[-1] * num_blks[-2] *
num_blks[-3] * num_blks[-4] *
blk_shape[-1] * blk_shape[-2] *
blk_shape[-3] * blk_shape[-4])
else:
raise ValueError('Only support D <= 4, got {}'.format(D))
return output.reshape(batch_shape + num_blks + blk_shape)
def blocks_to_array(input, oshape, blk_shape, blk_strides):
"""Accumulate blocks into an array in a sliding window manner.
Args:
input (array): input array of shape [...] + num_blks + blk_shape
oshape (tuple): output shape.
blk_shape (tuple): block shape of length D.
blk_strides (tuple): block strides of length D.
Returns:
array: array of shape oshape.
"""
if len(blk_shape) != len(blk_strides):
raise ValueError('blk_shape must have the same length as blk_strides.')
D = len(blk_shape)
num_blks = input.shape[-(2 * D):-D]
batch_shape = list(oshape[:-D])
batch_size = util.prod(batch_shape)
device = backend.get_device(input)
xp = device.xp
with device:
output = xp.zeros([batch_size] + list(oshape[-D:]),
dtype=input.dtype)
input = input.reshape([batch_size] + list(input.shape[-2 * D:]))
if D == 1:
if device == backend.cpu_device:
_blocks_to_array1(output, input,
batch_size, blk_shape[-1],
blk_strides[-1],
num_blks[-1])
else: # pragma: no cover
if np.issubdtype(input.dtype, np.floating):
_blocks_to_array1_cuda(input,
batch_size, blk_shape[-1],
blk_strides[-1],
num_blks[-1],
output,
size=batch_size *
num_blks[-1] * blk_shape[-1])
else:
_blocks_to_array1_cuda_complex(input,
batch_size, blk_shape[-1],
blk_strides[-1],
num_blks[-1],
output,
size=batch_size
* num_blks[-1] *
blk_shape[-1])
elif D == 2:
if device == backend.cpu_device:
_blocks_to_array2(output, input,
batch_size, blk_shape[-1], blk_shape[-2],
blk_strides[-1], blk_strides[-2],
num_blks[-1], num_blks[-2])
else: # pragma: no cover
if np.issubdtype(input.dtype, np.floating):
_blocks_to_array2_cuda(input,
batch_size,
blk_shape[-1], blk_shape[-2],
blk_strides[-1], blk_strides[-2],
num_blks[-1], num_blks[-2],
output,
size=batch_size *
num_blks[-1] * num_blks[-2] *
blk_shape[-1] * blk_shape[-2])
else: # pragma: no cover
_blocks_to_array2_cuda_complex(
input,
batch_size, blk_shape[-1], blk_shape[-2],
blk_strides[-1], blk_strides[-2],
num_blks[-1], num_blks[-2],
output,
size=batch_size * num_blks[-1] * num_blks[-2] *
blk_shape[-1] * blk_shape[-2])
elif D == 3:
if device == backend.cpu_device:
_blocks_to_array3(output,
input,
batch_size, blk_shape[-1],
blk_shape[-2],
blk_shape[-3],
blk_strides[-1],
blk_strides[-2],
blk_strides[-3],
num_blks[-1],
num_blks[-2],
num_blks[-3])
else: # pragma: no cover
if np.issubdtype(input.dtype, np.floating):
_blocks_to_array3_cuda(
input,
batch_size,
blk_shape[-1], blk_shape[-2], blk_shape[-3],
blk_strides[-1], blk_strides[-2], blk_strides[-3],
num_blks[-1], num_blks[-2], num_blks[-3],
output,
size=batch_size * num_blks[-1] * num_blks[-2] *
num_blks[-3] * blk_shape[-1] * blk_shape[-2] *
blk_shape[-3])
else:
_blocks_to_array3_cuda_complex(
input,
batch_size,
blk_shape[-1], blk_shape[-2], blk_shape[-3],
blk_strides[-1], blk_strides[-2], blk_strides[-3],
num_blks[-1], num_blks[-2], num_blks[-3],
output,
size=batch_size *
num_blks[-1] * num_blks[-2] * num_blks[-3] *
blk_shape[-1] * blk_shape[-2] * blk_shape[-3])
elif D == 4:
if device == backend.cpu_device:
_blocks_to_array4(output,
input,
batch_size, blk_shape[-1],
blk_shape[-2],
blk_shape[-3],
blk_shape[-4],
blk_strides[-1],
blk_strides[-2],
blk_strides[-3],
blk_strides[-4],
num_blks[-1],
num_blks[-2],
num_blks[-3],
num_blks[-4])
else: # pragma: no cover
if np.issubdtype(input.dtype, np.floating):
_blocks_to_array4_cuda(
input,
batch_size, blk_shape[-1], blk_shape[-2],
blk_shape[-3], blk_shape[-4],
blk_strides[-1], blk_strides[-2],
blk_strides[-3], blk_strides[-4],
num_blks[-1], num_blks[-2],
num_blks[-3], num_blks[-4],
output,
size=batch_size *
num_blks[-1] * num_blks[-2] *
num_blks[-3] * num_blks[-4] *
blk_shape[-1] * blk_shape[-2] *
blk_shape[-3] * blk_shape[-4])
else:
_blocks_to_array4_cuda_complex(
input,
batch_size, blk_shape[-1], blk_shape[-2],
blk_shape[-3], blk_shape[-4],
blk_strides[-1], blk_strides[-2],
blk_strides[-3], blk_strides[-4],
num_blks[-1], num_blks[-2],
num_blks[-3], num_blks[-4],
output,
size=batch_size * num_blks[-1] * num_blks[-2] *
num_blks[-3] * num_blks[-4] *
blk_shape[-1] * blk_shape[-2] *
blk_shape[-3] * blk_shape[-4])
else:
raise ValueError('Only support D <= 4, got {}'.format(D))
return output.reshape(oshape)
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _array_to_blocks1(output, input, batch_size, Bx, Sx, Nx):
for b in range(batch_size):
for nx in range(Nx):
for bx in range(Bx):
ix = nx * Sx + bx
if ix < input.shape[-1]:
output[b, nx, bx] = input[b, ix]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _array_to_blocks2(output, input, batch_size, Bx, By, Sx, Sy, Nx, Ny):
for b in range(batch_size):
for ny in range(Ny):
for nx in range(Nx):
for by in range(By):
for bx in range(Bx):
iy = ny * Sy + by
ix = nx * Sx + bx
if ix < input.shape[-1] and iy < input.shape[-2]:
output[b, ny, nx, by, bx] = input[b, iy, ix]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _array_to_blocks3(output, input, batch_size, Bx, By, Bz,
Sx, Sy, Sz, Nx, Ny, Nz):
for b in range(batch_size):
for nz in range(Nz):
for ny in range(Ny):
for nx in range(Nx):
for bz in range(Bz):
for by in range(By):
for bx in range(Bx):
iz = nz * Sz + bz
iy = ny * Sy + by
ix = nx * Sx + bx
if (ix < input.shape[-1] and
iy < input.shape[-2] and
iz < input.shape[-3]):
output[b, nz, ny, nx, bz, by,
bx] = input[b, iz, iy, ix]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _array_to_blocks4(output, input, batch_size, Bx, By, Bz, Bt,
Sx, Sy, Sz, St,
Nx, Ny, Nz, Nt):
for b in range(batch_size):
for nt in range(Nt):
for nz in range(Nz):
for ny in range(Ny):
for nx in range(Nx):
for bt in range(Bt):
for bz in range(Bz):
for by in range(By):
for bx in range(Bx):
it = nt * St + bt
iz = nz * Sz + bz
iy = ny * Sy + by
ix = nx * Sx + bx
if (ix < input.shape[-1] and
iy < input.shape[-2] and
iz < input.shape[-3] and
it < input.shape[-4]):
output[b, nt, nz, ny, nx,
bt, bz, by,
bx] = input[b, it,
iz, iy, ix]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _blocks_to_array1(output, input, batch_size, Bx, Sx, Nx):
for b in range(batch_size):
for nx in range(Nx):
for bx in range(Bx):
ix = nx * Sx + bx
if ix < output.shape[-1]:
output[b, ix] += input[b, nx, bx]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _blocks_to_array2(output, input, batch_size, Bx, By, Sx, Sy, Nx, Ny):
for b in range(batch_size):
for ny in range(Ny):
for nx in range(Nx):
for by in range(By):
for bx in range(Bx):
iy = ny * Sy + by
ix = nx * Sx + bx
if ix < output.shape[-1] and iy < output.shape[-2]:
output[b, iy, ix] += input[b, ny, nx, by, bx]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _blocks_to_array3(output, input, batch_size, Bx, By, Bz, Sx, Sy, Sz,
Nx, Ny, Nz):
for b in range(batch_size):
for nz in range(Nz):
for ny in range(Ny):
for nx in range(Nx):
for bz in range(Bz):
for by in range(By):
for bx in range(Bx):
iz = nz * Sz + bz
iy = ny * Sy + by
ix = nx * Sx + bx
if (ix < output.shape[-1]
and iy < output.shape[-2]
and iz < output.shape[-3]):
output[b, iz, iy, ix] += input[b, nz,
ny, nx,
bz, by, bx]
@nb.jit(nopython=True, cache=True) # pragma: no cover
def _blocks_to_array4(output, input, batch_size, Bx, By, Bz, Bt,
Sx, Sy, Sz, St, Nx, Ny, Nz, Nt):
for b in range(batch_size):
for nt in range(Nt):
for nz in range(Nz):
for ny in range(Ny):
for nx in range(Nx):
for bt in range(Bt):
for bz in range(Bz):
for by in range(By):
for bx in range(Bx):
it = nt * St + bt
iz = nz * Sz + bz
iy = ny * Sy + by
ix = nx * Sx + bx
if (ix < output.shape[-1]
and iy < output.shape[-2]
and iz < output.shape[-3]
and it < output.shape[-4]):
output[b, it,
iz,
iy,
ix] += input[b, nt,
nz,
ny,
nx,
bt,
bz,
by,
bx]
if config.cupy_enabled: # pragma: no cover
import cupy as cp
_array_to_blocks1_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 Sx, int32 Nx',
'raw T output',
"""
const int ndim = input.ndim;
int b = i / Bx / Nx;
i -= b * Bx * Nx;
int nx = i / Bx;
i -= nx * Bx;
int bx = i;
int ix = nx * Sx + bx;
if (ix < input.shape()[ndim - 1]) {
int input_idx[] = {b, ix};
int output_idx[] = {b, nx, bx};
output[output_idx] = input[input_idx];
}
""",
name='_array_to_blocks1_cuda')
_array_to_blocks2_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 By, '
'int32 Sx, int32 Sy, int32 Nx, int32 Ny',
'raw T output',
"""
const int ndim = input.ndim;
int b = i / Bx / By / Nx / Ny;
i -= b * Bx * By * Nx * Ny;
int ny = i / Bx / By / Nx;
i -= ny * Bx * By * Nx;
int nx = i / Bx / By;
i -= nx * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < input.shape()[ndim - 1] && iy < input.shape()[ndim - 2]) {
int input_idx[] = {b, iy, ix};
int output_idx[] = {b, ny, nx, by, bx};
output[output_idx] = input[input_idx];
}
""",
name='_array_to_blocks2_cuda')
_array_to_blocks3_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 By, int32 Bz, '
'int32 Sx, int32 Sy, int32 Sz, int32 Nx, int32 Ny, int32 Nz',
'raw T output',
"""
const int ndim = input.ndim;
int b = i / Bx / By / Bz / Nx / Ny / Nz;
i -= b * Bx * By * Bz * Nx * Ny * Nz;
int nz = i / Bx / By / Bz / Nx / Ny;
i -= nz * Bx * By * Bz * Nx * Ny;
int ny = i / Bx / By / Bz / Nx;
i -= ny * Bx * By * Bz * Nx;
int nx = i / Bx / By / Bz;
i -= nx * Bx * By * Bz;
int bz = i / Bx / By;
i -= bz * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int iz = nz * Sz + bz;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < input.shape()[ndim - 1] && iy < input.shape()[ndim - 2]
&& iz < input.shape()[ndim - 3]) {
int input_idx[] = {b, iz, iy, ix};
int output_idx[] = {b, nz, ny, nx, bz, by, bx};
output[output_idx] = input[input_idx];
}
""",
name='_array_to_blocks3_cuda')
_array_to_blocks4_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, '
'int32 Bx, int32 By, int32 Bz, int32 Bt, '
'int32 Sx, int32 Sy, int32 Sz, int32 St, '
'int32 Nx, int32 Ny, int32 Nz, int32 Nt',
'raw T output',
"""
const int ndim = input.ndim;
int b = i / Bx / By / Bz / Bt / Nx / Ny / Nz / Nt;
i -= b * Bx * By * Bz * Bt * Nx * Ny * Nz * Nt;
int nt = i / Bx / By / Bz / Bt / Nx / Ny / Nz;
i -= nt * Bx * By * Bz * Bt * Nx * Ny * Nz;
int nz = i / Bx / By / Bz / Bt / Nx / Ny;
i -= nz * Bx * By * Bz * Bt * Nx * Ny;
int ny = i / Bx / By / Bz / Bt / Nx;
i -= ny * Bx * By * Bz * Bt * Nx;
int nx = i / Bx / By / Bz / Bt;
i -= nx * Bx * By * Bz * Bt;
int bt = i / Bx / By / Bz;
i -= bt * Bx * By * Bz;
int bz = i / Bx / By;
i -= bz * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int it = nt * St + bt;
int iz = nz * Sz + bz;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < input.shape()[ndim - 1] && iy < input.shape()[ndim - 2]
&& iz < input.shape()[ndim - 3] && it < input.shape()[ndim - 4]) {
int input_idx[] = {b, it, iz, iy, ix};
int output_idx[] = {b, nt, nz, ny, nx, bt, bz, by, bx};
output[output_idx] = input[input_idx];
}
""",
name='_array_to_blocks4_cuda')
_blocks_to_array1_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 Sx, int32 Nx',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / Nx;
i -= b * Bx * Nx;
int nx = i / Bx;
i -= nx * Bx;
int bx = i;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1]) {
int input_idx[] = {b, nx, bx};
int output_idx[] = {b, ix};
atomicAdd(&output[output_idx], input[input_idx]);
}
""",
name='_blocks_to_array1_cuda')
_blocks_to_array1_cuda_complex = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 Sx, int32 Nx',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / Nx;
i -= b * Bx * Nx;
int nx = i / Bx;
i -= nx * Bx;
int bx = i;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1]) {
int input_idx[] = {b, nx, bx};
int output_idx[] = {b, ix};
atomicAdd(reinterpret_cast<T::value_type*>(&(output[output_idx])),
input[input_idx].real());
atomicAdd(
reinterpret_cast<T::value_type*>(&(output[output_idx])) + 1,
input[input_idx].imag());
}
""",
name='_blocks_to_array1_cuda_complex')
_blocks_to_array2_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, '
'int32 Bx, int32 By, int32 Sx, int32 Sy, '
'int32 Nx, int32 Ny',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / By / Nx / Ny;
i -= b * Bx * By * Nx * Ny;
int ny = i / Bx / By / Nx;
i -= ny * Bx * By * Nx;
int nx = i / Bx / By;
i -= nx * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1] && iy < output.shape()[ndim - 2]) {
int input_idx[] = {b, ny, nx, by, bx};
int output_idx[] = {b, iy, ix};
atomicAdd(&output[output_idx], input[input_idx]);
}
""",
name='_blocks_to_array2_cuda')
_blocks_to_array2_cuda_complex = cp.ElementwiseKernel(
'raw T input, int32 batch_size, '
'int32 Bx, int32 By, int32 Sx, int32 Sy, '
'int32 Nx, int32 Ny',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / By / Nx / Ny;
i -= b * Bx * By * Nx * Ny;
int ny = i / Bx / By / Nx;
i -= ny * Bx * By * Nx;
int nx = i / Bx / By;
i -= nx * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1] && iy < output.shape()[ndim - 2]) {
int input_idx[] = {b, ny, nx, by, bx};
int output_idx[] = {b, iy, ix};
atomicAdd(reinterpret_cast<T::value_type*>(&(output[output_idx])),
input[input_idx].real());
atomicAdd(
reinterpret_cast<T::value_type*>(&(output[output_idx])) + 1,
input[input_idx].imag());
}
""",
name='_blocks_to_array2_cuda_complex')
_blocks_to_array3_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 By, int32 Bz, '
'int32 Sx, int32 Sy, int32 Sz, int32 Nx, int32 Ny, int32 Nz',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / By / Bz / Nx / Ny / Nz;
i -= b * Bx * By * Bz * Nx * Ny * Nz;
int nz = i / Bx / By / Bz / Nx / Ny;
i -= nz * Bx * By * Bz * Nx * Ny;
int ny = i / Bx / By / Bz / Nx;
i -= ny * Bx * By * Bz * Nx;
int nx = i / Bx / By / Bz;
i -= nx * Bx * By * Bz;
int bz = i / Bx / By;
i -= bz * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int iz = nz * Sz + bz;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1] &&
iy < output.shape()[ndim - 2] &&
iz < output.shape()[ndim - 3]) {
int input_idx[] = {b, nz, ny, nx, bz, by, bx};
int output_idx[] = {b, iz, iy, ix};
atomicAdd(&output[output_idx], input[input_idx]);
}
""",
name='_blocks_to_array3_cuda')
_blocks_to_array3_cuda_complex = cp.ElementwiseKernel(
'raw T input, int32 batch_size, int32 Bx, int32 By, int32 Bz, '
'int32 Sx, int32 Sy, int32 Sz, int32 Nx, int32 Ny, int32 Nz',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / By / Bz / Nx / Ny / Nz;
i -= b * Bx * By * Bz * Nx * Ny * Nz;
int nz = i / Bx / By / Bz / Nx / Ny;
i -= nz * Bx * By * Bz * Nx * Ny;
int ny = i / Bx / By / Bz / Nx;
i -= ny * Bx * By * Bz * Nx;
int nx = i / Bx / By / Bz;
i -= nx * Bx * By * Bz;
int bz = i / Bx / By;
i -= bz * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int iz = nz * Sz + bz;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1] &&
iy < output.shape()[ndim - 2] &&
iz < output.shape()[ndim - 3]) {
int input_idx[] = {b, nz, ny, nx, bz, by, bx};
int output_idx[] = {b, iz, iy, ix};
atomicAdd(reinterpret_cast<T::value_type*>(&(output[output_idx])),
input[input_idx].real());
atomicAdd(reinterpret_cast<T::value_type*>(
&(output[output_idx])) + 1, input[input_idx].imag());
}
""",
name='_blocks_to_array3_cuda_complex')
_blocks_to_array4_cuda = cp.ElementwiseKernel(
'raw T input, int32 batch_size, '
'int32 Bx, int32 By, int32 Bz, int32 Bt, '
'int32 Sx, int32 Sy, int32 Sz, int32 St, '
'int32 Nx, int32 Ny, int32 Nz, int32 Nt',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / By / Bz / Bt / Nx / Ny / Nz / Nt;
i -= b * Bx * By * Bz * Bt * Nx * Ny * Nz * Nt;
int nt = i / Bx / By / Bz / Bt / Nx / Ny / Nz;
i -= nt * Bx * By * Bz * Bt * Nx * Ny * Nz;
int nz = i / Bx / By / Bz / Bt / Nx / Ny;
i -= nz * Bx * By * Bz * Bt * Nx * Ny;
int ny = i / Bx / By / Bz / Bt / Nx;
i -= ny * Bx * By * Bz * Bt * Nx;
int nx = i / Bx / By / Bz / Bt;
i -= nx * Bx * By * Bz * Bt;
int bt = i / Bx / By / Bz;
i -= bt * Bx * By * Bz;
int bz = i / Bx / By;
i -= bz * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int it = nt * St + bt;
int iz = nz * Sz + bz;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1] &&
iy < output.shape()[ndim - 2] &&
iz < output.shape()[ndim - 3] &&
it < output.shape()[ndim - 4]) {
int input_idx[] = {b, nt, nz, ny, nx, bt, bz, by, bx};
int output_idx[] = {b, it, iz, iy, ix};
atomicAdd(&output[output_idx], input[input_idx]);
}
""",
name='_blocks_to_array4_cuda')
_blocks_to_array4_cuda_complex = cp.ElementwiseKernel(
'raw T input, int32 batch_size, '
'int32 Bx, int32 By, int32 Bz, int32 Bt, '
'int32 Sx, int32 Sy, int32 Sz, int32 St, '
'int32 Nx, int32 Ny, int32 Nz, int32 Nt',
'raw T output',
"""
const int ndim = output.ndim;
int b = i / Bx / By / Bz / Bt / Nx / Ny / Nz / Nt;
i -= b * Bx * By * Bz * Bt * Nx * Ny * Nz * Nt;
int nt = i / Bx / By / Bz / Bt / Nx / Ny / Nz;
i -= nt * Bx * By * Bz * Bt * Nx * Ny * Nz;
int nz = i / Bx / By / Bz / Bt / Nx / Ny;
i -= nz * Bx * By * Bz * Bt * Nx * Ny;
int ny = i / Bx / By / Bz / Bt / Nx;
i -= ny * Bx * By * Bz * Bt * Nx;
int nx = i / Bx / By / Bz / Bt;
i -= nx * Bx * By * Bz * Bt;
int bt = i / Bx / By / Bz;
i -= bt * Bx * By * Bz;
int bz = i / Bx / By;
i -= bz * Bx * By;
int by = i / Bx;
i -= by * Bx;
int bx = i;
int it = nt * St + bt;
int iz = nz * Sz + bz;
int iy = ny * Sy + by;
int ix = nx * Sx + bx;
if (ix < output.shape()[ndim - 1] &&
iy < output.shape()[ndim - 2] &&
iz < output.shape()[ndim - 3] &&
it < output.shape()[ndim - 4]) {
int input_idx[] = {b, nt, nz, ny, nx, bt, bz, by, bx};
int output_idx[] = {b, it, iz, iy, ix};
atomicAdd(reinterpret_cast<T::value_type*>(&(output[output_idx])),
input[input_idx].real());
atomicAdd(reinterpret_cast<T::value_type*>(
&(output[output_idx])) + 1, input[input_idx].imag());
}
""",
name='_blocks_to_array4_cuda_complex')
| 40.8125 | 79 | 0.38464 | 0 | 0 | 0 | 0 | 6,759 | 0.195296 | 0 | 0 | 13,499 | 0.390043 |
12047d5e2a741823096dbc33bf5afe683749bd26 | 1,531 | py | Python | awscdk/app.py | jaliste/mi_coop | 66be4328117c39026d85a3d6cc9b8635bde49077 | [
"MIT"
] | 54 | 2019-08-11T03:39:22.000Z | 2022-01-06T02:16:33.000Z | awscdk/app.py | jaliste/mi_coop | 66be4328117c39026d85a3d6cc9b8635bde49077 | [
"MIT"
] | 11 | 2020-02-12T01:17:38.000Z | 2021-05-10T06:22:22.000Z | awscdk/app.py | jaliste/mi_coop | 66be4328117c39026d85a3d6cc9b8635bde49077 | [
"MIT"
] | 20 | 2019-09-07T20:04:08.000Z | 2021-12-05T04:43:20.000Z | #!/usr/bin/env python3
import os
from aws_cdk import core
from awscdk.app_stack import ApplicationStack
# naming conventions, also used for ACM certs, DNS Records, resource naming
# Dynamically generated resource names created in CDK are used in GitLab CI
# such as cluster name, task definitions, etc.
environment_name = f"{os.environ.get('ENVIRONMENT', 'dev')}"
base_domain_name = os.environ.get("DOMAIN_NAME", "mysite.com")
# if the the production environent subdomain should nott be included in the URL
# redefine `full_domain_name` to `base_domain_name` for that environment
full_domain_name = f"{environment_name}.{base_domain_name}" # dev.mysite.com
if environment_name == "app":
full_domain_name = base_domain_name
base_app_name = os.environ.get("APP_NAME", "mysite-com")
full_app_name = f"{environment_name}-{base_app_name}" # dev-mysite-com
aws_region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
app = core.App()
stack = ApplicationStack(
app,
f"{full_app_name}-stack",
environment_name=environment_name,
base_domain_name=base_domain_name,
full_domain_name=full_domain_name,
base_app_name=base_app_name,
full_app_name=full_app_name,
env={"region": aws_region},
)
# in order to be able to tag ECS resources, you need to go to
# the ECS Console > Account Settings > Amazon ECS ARN and resource ID settings
# and enable at least Service and Task. Optionally enable
# CloudWatch Container Insights
stack.node.apply_aspect(core.Tag("StackName", full_app_name))
app.synth()
| 36.452381 | 79 | 0.766819 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 872 | 0.569562 |
1204c9abc6db283ce3d3831f239b7fd8af24dbea | 4,563 | py | Python | test_phase_equilibrium.py | khuston/interfacial_transport | dfca4288e2876de81683fb46704c14393afdf422 | [
"MIT"
] | 1 | 2020-05-07T09:25:24.000Z | 2020-05-07T09:25:24.000Z | test_phase_equilibrium.py | khuston/interfacial_transport | dfca4288e2876de81683fb46704c14393afdf422 | [
"MIT"
] | null | null | null | test_phase_equilibrium.py | khuston/interfacial_transport | dfca4288e2876de81683fb46704c14393afdf422 | [
"MIT"
] | null | null | null | import numpy as np
import logging
from interfacial_transport import compute_one_phase_equilibrium, compute_mass_balance_one_phase
from interfacial_transport import compute_two_phase_equilibrium, compute_mass_balance_two_phase
from numpy.testing import assert_almost_equal
logger = logging.getLogger(__name__)
# Check one-phase equilibrium for errors
def test_no_errors_one_phase_equilibrium_interface():
alpha = 6.86e-6 # 1/s
beta = 22.1 # m**3/mol/s
n = 0.460 #
kappa = 10.3 #
D = 3.8e-10 # m**2/s
Gamma_infty = 2.25e-6 # mol/m**2
R = 1.9e-3
a = alpha/beta
c0 = 0.0006
times_to_save = np.logspace(-3., 4.)
r, c_save, Gamma_save = compute_one_phase_equilibrium(D, c0, R, a, Gamma_infty, kappa, n, times_to_save)
assert(c_save.ndim == 2)
assert(Gamma_save.ndim == 1)
assert(r.ndim == 1)
assert(len(Gamma_save) == len(times_to_save))
assert(len(c_save) == len(times_to_save))
assert(len(r) == c_save.shape[1])
def test_no_errors_two_phase_equilibrium_interface():
alpha = 6.86e-6 # 1/s
beta = 22.1 # m**3/mol/s
n = 0.460 #
kappa = 10.3 #
DA = 3.8e-10/48. # m**2/s
DB = 3.8e-10 # m**2/s
Gamma_infty = 2.25e-6 # mol/m**2
R = 1.9e-3
aB = alpha/beta
aA = alpha/beta*1.45
c0A = 0.
c0B = 0.0006
times_to_save = np.logspace(-3., 4.)
rA, rB, cA_save, cB_save, Gamma_save = compute_two_phase_equilibrium(DA, DB, c0A, c0B, R, aA, aB, Gamma_infty, kappa, n, times_to_save)
assert(cA_save.ndim == 2)
assert(cB_save.ndim == 2)
assert(Gamma_save.ndim == 1)
assert(rA.ndim == 1)
assert(rB.ndim == 1)
assert(len(Gamma_save) == len(times_to_save))
assert(len(cA_save) == len(times_to_save))
assert(len(cB_save) == len(times_to_save))
assert(len(rA) == cA_save.shape[1])
assert(len(rB) == cB_save.shape[1])
def test_no_errors_compute_mass_balance_one_phase():
Gamma = 1.
c = np.ones(5)
r = np.linspace(1., 2., 5)
compute_mass_balance_one_phase(Gamma, c, r, r[0])
Gamma = np.ones(10)
c = np.ones((10, 20))
r = np.linspace(1., 2., 20)
compute_mass_balance_one_phase(Gamma, c, r, r[0])
def test_no_errors_compute_mass_balance_two_phase():
Gamma = 1.
cA = np.ones(5)
rA = np.linspace(0., 1., 5)
cB = np.ones(5)
rB = np.linspace(1., 2., 5)
compute_mass_balance_two_phase(Gamma, cA, rA, cA, rB, rB[0])
Gamma = np.ones(10)
cA = np.ones((10, 20))
rA = np.linspace(0., 1., 20)
cB = np.ones((10, 20))
rB = np.linspace(1., 2., 20)
compute_mass_balance_two_phase(Gamma, cA, rA, cB, rB, rB[0])
def test_one_phase_mass_balance_accuracy():
alpha = 6.86e-6 # 1/s
beta = 22.1 # m**3/mol/s
n = 0.460 #
kappa = 10.3 #
D = 3.8e-10 # m**2/s
Gamma_infty = 2.25e-6 # mol/m**2
R = 1.9e-3
a = alpha/beta
c0 = 0.0006
times_to_save = np.logspace(-3., 4.)
r, c_save, Gamma_save = compute_one_phase_equilibrium(D, c0, R, a, Gamma_infty, kappa, n, times_to_save)
compute_mass_balance_one_phase(Gamma_save, c_save, r, R)
error = (compute_mass_balance_one_phase(Gamma_save, c_save, r, R) - compute_mass_balance_one_phase(0., np.array([0.]+[c0]*(len(r)-1)), r, R))
assert_almost_equal(error[-1]/Gamma_save[-1], 0., decimal=2)
def test_two_phase_mass_balance_accuracy():
alpha = 6.86e-6 # 1/s
beta = 22.1 # m**3/mol/s
n = 0.460 #
kappa = 10.3 #
DA = 3.8e-10/48. # m**2/s
DB = 3.8e-10 # m**2/s
Gamma_infty = 2.25e-6 # mol/m**2
R = 1.9e-3
aB = alpha/beta
aA = alpha/beta*1.45
c0A = 0.
c0B = 0.0006
times_to_save = np.logspace(-3., 4.)
rA, rB, cA_save, cB_save, Gamma_save = compute_two_phase_equilibrium(DA, DB, c0A, c0B, R, aA, aB, Gamma_infty, kappa, n, times_to_save)
compute_mass_balance_two_phase(Gamma_save, cA_save, rA, cB_save, rB, R)
logger.info('rA={}'.format(rA))
logger.info('rB={}'.format(rB))
logger.info('cA={}'.format(cA_save))
logger.info('cB={}'.format(cB_save))
error = (compute_mass_balance_two_phase(Gamma_save, cA_save, rA, cB_save, rB, R) - compute_mass_balance_two_phase(0., np.array([c0A]*(len(rA)-1)+[0.]), rA, np.array([0.]+[c0B]*(len(rB)-1)), rB, R))
assert_almost_equal(error[-1]/Gamma_save[-1], 0., decimal=2)
def test_validate_one_phase_equilibrium_interface():
pass
| 31.909091 | 201 | 0.60881 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 232 | 0.050844 |
1205020ea522f7b1fd7bb580cbb7689312826db5 | 3,914 | py | Python | testbed1/scratchnet_single_switch_test.py | Benny93/SDNMininetScripts | 16844ac1cecfdf27e25ca0f758029c81030b9ba1 | [
"MIT"
] | null | null | null | testbed1/scratchnet_single_switch_test.py | Benny93/SDNMininetScripts | 16844ac1cecfdf27e25ca0f758029c81030b9ba1 | [
"MIT"
] | null | null | null | testbed1/scratchnet_single_switch_test.py | Benny93/SDNMininetScripts | 16844ac1cecfdf27e25ca0f758029c81030b9ba1 | [
"MIT"
] | null | null | null | #!/usr/bin/python
"""
Build a simple network from scratch, using mininet primitives.
This is more complicated than using the higher-level classes,
but it exposes the configuration details and allows customization.
For most tasks, the higher-level API will be preferable.
"""
import csv
import sys
import time
from mininet.net import Mininet
from mininet.node import Node
from mininet.link import Link
from mininet.log import setLogLevel, info
from mininet.util import quietRun
import pingparser
CTLR_IP = '2017:db8::ffaa'
CTLR_PRT = '6653'
# 0: Step wise testing, 1: Continues Testing
mode = 1
def stop_net(controller, cname, switch):
info("*** Stopping network\n")
controller.cmd('kill %' + cname)
switch.cmd('ovs-vsctl del-br dp0')
switch.deleteIntfs()
info('Net was removed\n')
def scratchNet(cname='controller', cargs='-v ptcp:'):
"Create network from scratch using Open vSwitch."
info("*** Creating nodes\n")
controller = Node('c0', inNamespace=False)
switch = Node('s0', inNamespace=False)
h0 = Node('h0')
h1 = Node('h1')
info("*** Creating links\n")
Link(h0, switch)
Link(h1, switch)
info("*** Configuring hosts\n")
h0.setIP('192.168.123.1/24')
h1.setIP('192.168.123.2/24')
info(str(h0) + '\n')
info(str(h1) + '\n')
info("*** Starting network using Open vSwitch\n")
controller.cmd(cname + ' ' + cargs + '&')
switch.cmd('ovs-vsctl del-br dp0')
switch.cmd('ovs-vsctl add-br dp0')
for intf in switch.intfs.values():
print switch.cmd('ovs-vsctl add-port dp0 %s' % intf)
# Note: controller and switch are in root namespace, and we
# can connect via loopback interface
s_cmd = 'ovs-vsctl set-controller dp0 tcp:[{}]:{}'.format(CTLR_IP, CTLR_PRT)
print s_cmd
switch.cmd(s_cmd)
ping_results = ['received,host,jitter,packet_loss,avgping,minping,time,sent,maxping\n']
try:
h0.cmd('echo "" > pings.txt')
if mode == 0:
step_wise_testing(h0, h1, ping_results)
else:
continuous_testing(h0, h1, ping_results)
except KeyboardInterrupt:
print "Warning: Caught KeyboardInterrupt, stopping network"
tm_local = time.localtime()
dt = time.gmtime()
file_name = 'pings_{}_{}_{}-{}_{}_{}.csv'.format(dt.tm_year, dt.tm_mon, dt.tm_mday, tm_local.tm_hour, tm_local.tm_min, tm_local.tm_sec)
f = open(file_name, 'w+')
for item in ping_results:
f.write(item)
stop_net(controller, cname, switch)
def step_wise_testing(h0, h1, ping_results):
while True:
if 'is_connected' not in quietRun('ovs-vsctl show'):
wait_for_controller_connection()
print "Press ENTER to execute Test\n"
line = sys.stdin.readline()
if line:
info("Key Input Accepted\n")
ping_test(h0, h1, ping_results)
def continuous_testing(h0, h1, ping_results):
while True:
if 'is_connected' not in quietRun('ovs-vsctl show'):
wait_for_controller_connection()
ping_test(h0, h1, ping_results)
time.sleep(1)
def ping_test(h0, h1, ping_results):
info("*** Running test\n")
ping_res = h0.cmdPrint('ping -c1 ' + h1.IP())
ping_res = pingparser.parse(ping_res)
tm_local = time.localtime()
ping_res['time'] = '{}:{}:{}'.format(tm_local.tm_hour, tm_local.tm_min, tm_local.tm_sec)
val_string = ','.join(ping_res.itervalues())
ping_results.append(val_string + "\n")
print ping_res
info("*** Sleep\n")
def wait_for_controller_connection():
info('*** Waiting for switch to connect to controller')
while 'is_connected' not in quietRun('ovs-vsctl show'):
time.sleep(1)
info('.')
info('Connected \n')
if __name__ == '__main__':
setLogLevel('info')
info('*** Scratch network demo (kernel datapath)\n')
Mininet.init()
scratchNet()
| 29.877863 | 143 | 0.648441 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,385 | 0.353858 |
1207575defc5d03469e62a79d6627247fbf73ef2 | 108 | py | Python | teampy/__init__.py | arcward/teampy | 34097dfca2cf6eb2a405ff0346b46e7ab9520444 | [
"MIT"
] | null | null | null | teampy/__init__.py | arcward/teampy | 34097dfca2cf6eb2a405ff0346b46e7ab9520444 | [
"MIT"
] | null | null | null | teampy/__init__.py | arcward/teampy | 34097dfca2cf6eb2a405ff0346b46e7ab9520444 | [
"MIT"
] | null | null | null | from teampy.client import APIClient
__version__ = '0.1'
__author__ = 'Edward Wells'
__all__ = ['APIClient'] | 21.6 | 35 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 30 | 0.277778 |
120789fe010c8cdb8e79c4be3739e15f479811eb | 1,032 | py | Python | app/housekeeping.py | openpeoria/covid-19-il-data-scraper | f1978f08f4451398ef6d892593d6259745237073 | [
"MIT"
] | 2 | 2020-06-16T16:36:21.000Z | 2020-06-28T16:38:15.000Z | app/housekeeping.py | openpeoria/covid-19-il-data-scraper | f1978f08f4451398ef6d892593d6259745237073 | [
"MIT"
] | 15 | 2020-05-09T20:42:02.000Z | 2020-08-06T17:12:06.000Z | app/housekeeping.py | openpeoria/covid-19-il-data-scraper | f1978f08f4451398ef6d892593d6259745237073 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
app.housekeeping
~~~~~~~~~~~~~~~~
Provides additional housekeeping endpoints
"""
from flask import Blueprint, redirect, request
from werkzeug.exceptions import HTTPException
from app.helpers import exception_hook
from app.utils import jsonify
blueprint = Blueprint("Housekeeping", __name__)
@blueprint.before_app_request
def clear_trailing():
request_path = request.path
is_root = request_path == "/"
is_admin = request_path.startswith("/admin")
has_trailing = request_path.endswith("/")
if not (is_root or is_admin) and has_trailing:
return redirect(request_path[:-1])
@blueprint.app_errorhandler(Exception)
def handle_exception(error):
if isinstance(error, HTTPException):
status_code = error.code
use_tb = False
else:
status_code = 500
use_tb = True
etype = error.__class__.__name__
exception_hook(etype, use_tb=use_tb)
json = {"status_code": status_code, "result": etype}
return jsonify(**json)
| 25.170732 | 56 | 0.694767 | 0 | 0 | 0 | 0 | 692 | 0.670543 | 0 | 0 | 169 | 0.16376 |
12097bfd1d23d0ffaac136238da16dcbf5b48204 | 10,463 | py | Python | game.py | MisterL2/WarzoneAI | eeae8975f58d11bcce5acf2556e5c47b7e6e4c7c | [
"MIT"
] | null | null | null | game.py | MisterL2/WarzoneAI | eeae8975f58d11bcce5acf2556e5c47b7e6e4c7c | [
"MIT"
] | null | null | null | game.py | MisterL2/WarzoneAI | eeae8975f58d11bcce5acf2556e5c47b7e6e4c7c | [
"MIT"
] | null | null | null | from aiplayer import *
from player import *
from gameclasses import *
def setup(countries, countryMap):
print("Setup started!")
#Initialise boni
NA.countries = countries[0:9]
SA.countries = countries[9:13]
AF.countries = countries[13:19]
EU.countries = countries[19:26]
AU.countries = countries[26:30]
AS.countries = countries[30:42] #41 countries; this is a valid list slice and detects error with the list more easily than simply saying "30:"
neutral = Player("Neutral",[],[])
for country in countries:
#Convert the country name strings to the actual countries
country.adjacent = [countryMap[countryName] for countryName in country.adjacent]
#Set base amount of armies for all neutral fields
country.armies = 2
#Set country owner to Neutral player
country.owner = neutral
print("Setup completed!")
def attackCountry(countryFrom, attackingArmies, countryTo):
print(f"Attack from {countryFrom.name} ({countryFrom.owner}) with {attackingArmies} armies on {countryTo} ({countryTo.owner}) with {countryTo.armies} armies")
defendingArmies = countryTo.armies
defenderDeaths = round(attackingArmies*0.6)
attackerDeaths = round(defendingArmies*0.7)
attacker = countryFrom.owner
defender = countryTo.owner
if defenderDeaths >= countryTo.armies and (attackingArmies - attackerDeaths) >= 1: #All units killed and at least one attacking army remaining
#Inform players so they can calculate a score
attacker.armiesLost(attackerDeaths)
attacker.armiesKilled(countryTo.armies) #All defending armies are killed
defender.armiesLost(countryTo.armies)
defender.armiesKilled(attackerDeaths)
attacker.countryCaptured(countryTo)
countryFrom.armies -= attackingArmies #Remove all armies involved in the successful attack from the original country
countryTo.armies = (attackingArmies - attackerDeaths)
countryTo.owner = countryFrom.owner
else: #Successful defense or tie
#Inform players so they can calculate a score
attacker.armiesLost(attackerDeaths)
attacker.armiesKilled(defenderDeaths)
defender.armiesLost(defenderDeaths)
attacker.armiesKilled(attackerDeaths)
countryFrom.armies -= attackerDeaths
countryTo.armies -= defenderDeaths
#The core game logic.
#This processes the actions after both players have finalised them
def gameTurn(players):
#Process deployments
deploymentMap = {player: player.decideDeployments() for player in players}
#The tricky part here is, that the players need to be aware of their own deployments *before* making decisions, but they must NOT know the deployments of other players
#So first, each player deploys their units, makes their decisions, then un-deploys them
#Then, each player deploys their units
playerMovementLists = []
for player in deploymentMap.keys():
deployments = deploymentMap[player]
#Temporarily deploy own units
for deploymentCountry in deployments.keys():
deploymentCountry.armies += deployments[deploymentCountry]
#Make decision
playerMovementLists.append(player.decideMovements())
#Un-deploy own units
for deploymentCountry in deployments.keys():
deploymentCountry.armies += deployments[deploymentCountry]
#Now actually deploy the units
for deployment in deploymentMap.values():
for deploymentCountry in deployments.keys():
deploymentCountry.armies += deployments[deploymentCountry]
#Schedule player attacks/movements
#THIS IS VERY SIMPLIFIED FROM THE ACTUAL (more random) game logic!
mostMoves = max([len(lst) for lst in playerMovementLists])
movementsInOrder = []
for i in range(mostMoves):
for movementList in playerMovementLists:
if i < len(movementList):
movementsInOrder.add(movementList[i])
#Perform player attacks movements
countriesConqueredThisTurn = []
for movement in movementsInOrder:
if movement.countryFrom.owner != movement.player:
continue #The player no longer has that field and the armies on it are not his
if movement.countryFrom in countriesConqueredThisTurn:
continue #No attacks can come from a country that has been freshly conquered (or re-conquered), as that would allow armies to move 2+ steps in one turn, which is not consistent with the real game.
#If some armies were killed etc then we can't send i.e. 10 units across, if there are only 6 left on the field.
#So send as many units as possible (in this case all 6) up to the max of the 10 units specified.
actualAmount = min(movement.countryFrom.armies, movement.armies)
if actualAmount == 0:
continue #Cannot make a movement if there are 0 units on this field
if movement.countryFrom.owner == movement.countryTo.owner: #Transfer
movement.countryTo.armies += actualAmount
movement.countryFrom.armies -= actualAmount
if movement.countryTo.armies < 0:
print("ERROR (negative armies)! Country: " + movement.countryTo.name)
else: #Attack
#This function deals with all necessary processing related to attacking a country
attackCountry(movement.countryFrom, actualAmount, movement.countryTo)
#Update players
for player in players:
turnScore = player.update()
#Check win condition
for player in players:
if len(player.getControlledTerritories()) == 0:
print(f"Player {player.name} has no more territories and is eliminated!")
return False #End game loop
return True
NA = Bonus("North America",5)
EU = Bonus("Europe",5)
SA = Bonus("South America",2)
AF = Bonus("Afrika",3)
AS = Bonus("Asia",7)
AU = Bonus("Australia",2)
boni = [
NA,
EU,
SA,
AF,
AS,
AU
]
countries = [
#NA (9)
Country("Alaska", ["Northwest Territory","Alberta","Kanchatka"]),
Country("Alberta", ["Northwest Territory","Alaska", "Ontario", "Western United States"]),
Country("Northwest Territory", ["Alaska","Alberta","Ontario","Greenland"]),
Country("Ontario", ["Northwest Territory","Alberta", "Greenland", "Western United States", "Eastern United States", "Quebec"]),
Country("Quebec", ["Ontario", "Greenland", "Eastern United States"]),
Country("Greenland", ["Northwest Territory", "Ontario", "Quebec", "Iceland"]),
Country("Western United States",["Alberta", "Ontario", "Eastern United States", "Mexico"]),
Country("Eastern United States",["Western United States", "Mexico", "Ontario", "Quebec"]),
Country("Mexico",["Western United States","Eastern United States","Venezuela"]),
#SA (4)
Country("Venezuela",["Mexico", "Peru", "Brazil"]),
Country("Peru",["Venezuela", "Brazil", "Argentina"]),
Country("Argentina",["Peru","Brazil"]),
Country("Brazil",["Venezuela", "Peru", "Argentina", "North Africa"]),
#AF (6)
Country("North Africa",["Brazil","W. Europe", "S. Europe", "Egypt", "East Africa", "Congo"]),
Country("Congo",["North Africa", "East Africa", "South Africa"]),
Country("South Africa",["Congo", "East Africa", "Madagascar"]),
Country("Madagascar",["South Africa", "East Africa"]),
Country("East Africa",["North Africa", "Egypt", "Middle East", "Madagascar", "South Africa", "Congo"]),
Country("Egypt",["North Africa", "East Africa", "S. Europe", "Middle East"]),
#EU (7)
Country("W. Europe",["North Africa", "S. Europe", "N. Europe", "Great Britain"]),
Country("S. Europe",["W. Europe", "North Africa", "Egypt", "Middle East", "Ukraine", "N. Europe"]),
Country("N. Europe",["W. Europe", "S. Europe", "Great Britain", "Ukraine"]),
Country("Great Britain",["Iceland", "W. Europe", "N. Europe", "Scandinavia"]),
Country("Iceland",["Greenland", "Great Britain", "Scandinavia"]),
Country("Scandinavia",["Iceland", "Great Britain", "Ukraine"]),
Country("Ukraine",["Scandinavia", "N. Europe", "S. Europe", "Middle East", "Kazakhstan", "Ural"]),
#AU (4)
Country("Eastern Australia",["New Guinea", "Western Australia"]),
Country("Western Australia",["New Guinea", "Eastern Australia", "Indonesia"]),
Country("New Guinea",["Western Australia", "Eastern Australia", "Indonesia"]),
Country("Indonesia",["New Guinea", "Western Australia", "Siam"]),
#AS (12)
Country("Siam",["India", "China", "Indonesia"]),
Country("India",["Siam", "China", "Kazakhstan", "Middle East"]),
Country("Middle East",["East Africa", "Egypt", "S. Europe", "Ukraine", "India", "Kazakhstan"]),
Country("Kazakhstan",["Middle East", "Ukraine", "Ural", "China", "India"]),
Country("Ural",["Ukraine", "Kazakhstan", "China", "Siberia"]),
Country("China",["Siam", "India", "Kazakhstan", "Ural", "Siberia", "Mongolia"]),
Country("Siberia",["Ural", "China", "Mongolia", "Irkutsk", "Yakutsk"]),
Country("Mongolia",["China", "Siberia", "Irkutsk", "Japan", "Kanchatka"]),
Country("Japan",["Mongolia", "Kanchatka"]),
Country("Irkutsk",["Siberia", "Mongolia", "Yakutsk", "Kanchatka"]),
Country("Yakutsk",["Siberia", "Irkutsk", "Kanchatka"]),
Country("Kanchatka",["Irkutsk", "Mongolia", "Japan", "Yakutsk", "Alaska"]),
]
countryMap = {country.name : country for country in countries}
#Setup and connect all countries
setup(countries, countryMap)
alpha = AIPlayer("alpha",countries,boni)
beta = AIPlayer("beta",countries,boni)
players = [
alpha,
beta
]
#Give player spawns (hard-coded for initial simplicity).
#Each player always starts with 2 territories of 4 armies each
#Territories are distributed so that there is either 0 or 1 territory given out (in total) per bonus
#It is equally likely to get a territory from each bonus, and within that bonus each territory is also equally likely
countryMap["Eastern Australia"].owner = alpha
countryMap["Eastern Australia"].armies = 4
countryMap["Northwest Territory"].owner = alpha
countryMap["Northwest Territory"].armies = 4
countryMap["Peru"].owner = beta
countryMap["Peru"].armies = 4
countryMap["W. Europe"].owner = beta
countryMap["W. Europe"].armies = 4
gameRunning = True
while gameRunning:
gameRunning = gameTurn(players)
break
| 42.706122 | 208 | 0.67409 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5,041 | 0.481793 |
1209c55c292fdc6dbe7e74d85cb44c48a7a0980f | 1,678 | py | Python | src/pretix/plugins/stripe/views.py | abrock/pretix | cd9c048458afce1198276e5936bf583578855a4f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-06-23T07:44:54.000Z | 2021-06-23T07:44:54.000Z | src/pretix/plugins/stripe/views.py | awg24/pretix | b1d67a48601838bac0d4e498cbe8bdcd16013d60 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/pretix/plugins/stripe/views.py | awg24/pretix | b1d67a48601838bac0d4e498cbe8bdcd16013d60 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | import json
import logging
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from pretix.base.models import Event, Order
from pretix.plugins.stripe.payment import Stripe
logger = logging.getLogger('pretix.plugins.stripe')
@csrf_exempt
@require_POST
def webhook(request):
event_json = json.loads(request.body.decode('utf-8'))
event_type = event_json['type']
if event_type != 'charge.refunded':
# Not interested
return HttpResponse('Event is not a refund', status=200)
charge = event_json['data']['object']
if charge['object'] != 'charge':
return HttpResponse('Object is not a charge', status=200)
metadata = charge['metadata']
if 'event' not in metadata:
return HttpResponse('Event not given', status=200)
try:
event = Event.objects.current.get(identity=metadata['event'])
except Event.DoesNotExist:
return HttpResponse('Event not found', status=200)
try:
order = Order.objects.current.get(identity=metadata['order'])
except Order.DoesNotExist:
return HttpResponse('Order not found', status=200)
prov = Stripe(event)
prov._init_api()
try:
charge = stripe.Charge.retrieve(charge['id'])
except stripe.error.StripeError as err:
logger.error('Stripe error on webhook: %s Event data: %s' % (str(err), str(event_json)))
return HttpResponse('StripeError', status=500)
if charge['refunds']['total_count'] > 0 and order.status == Order.STATUS_PAID:
order.mark_refunded()
return HttpResponse(status=200)
| 30.509091 | 96 | 0.694875 | 0 | 0 | 0 | 0 | 1,342 | 0.799762 | 0 | 0 | 311 | 0.18534 |
120b31cd9b8d0a2588dcab759b2ad94681f0fd60 | 389 | py | Python | meerkat_backend_interface/logger.py | rubyvanrooyen/meerkat-backend-interface | 3e4e6e6dfe99edb5998c08987ab50f6e0a014bc2 | [
"MIT"
] | null | null | null | meerkat_backend_interface/logger.py | rubyvanrooyen/meerkat-backend-interface | 3e4e6e6dfe99edb5998c08987ab50f6e0a014bc2 | [
"MIT"
] | 7 | 2019-03-20T23:36:11.000Z | 2021-12-13T19:49:02.000Z | meerkat_backend_interface/logger.py | rubyvanrooyen/meerkat-backend-interface | 3e4e6e6dfe99edb5998c08987ab50f6e0a014bc2 | [
"MIT"
] | 3 | 2019-03-20T23:35:10.000Z | 2019-04-17T23:27:54.000Z | import logging
def get_logger():
"""Get the logger."""
return logging.getLogger("BLUSE.interface")
log = get_logger()
def set_logger(log_level=logging.DEBUG):
"""Set up logging."""
FORMAT = "[ %(levelname)s - %(asctime)s - %(filename)s:%(lineno)s] %(message)s"
logging.basicConfig(format=FORMAT)
log = get_logger()
log.setLevel(log_level)
return log
| 19.45 | 83 | 0.650386 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 129 | 0.33162 |
120c2eff5a8ca3795d5975762849b5022164abd8 | 4,749 | py | Python | alipay/aop/api/domain/AlipayUserApplepayMerchantauthtokenGetModel.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 213 | 2018-08-27T16:49:32.000Z | 2021-12-29T04:34:12.000Z | alipay/aop/api/domain/AlipayUserApplepayMerchantauthtokenGetModel.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 29 | 2018-09-29T06:43:00.000Z | 2021-09-02T03:27:32.000Z | alipay/aop/api/domain/AlipayUserApplepayMerchantauthtokenGetModel.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 59 | 2018-08-27T16:59:26.000Z | 2022-03-25T10:08:15.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.OpenApiAppleRequestHeader import OpenApiAppleRequestHeader
class AlipayUserApplepayMerchantauthtokenGetModel(object):
def __init__(self):
self._amount = None
self._currency_code = None
self._partner_owned_merchant_identifier = None
self._provisioning_bundle_identifier = None
self._request_header = None
self._transaction_notification_identifier = None
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
self._amount = value
@property
def currency_code(self):
return self._currency_code
@currency_code.setter
def currency_code(self, value):
self._currency_code = value
@property
def partner_owned_merchant_identifier(self):
return self._partner_owned_merchant_identifier
@partner_owned_merchant_identifier.setter
def partner_owned_merchant_identifier(self, value):
self._partner_owned_merchant_identifier = value
@property
def provisioning_bundle_identifier(self):
return self._provisioning_bundle_identifier
@provisioning_bundle_identifier.setter
def provisioning_bundle_identifier(self, value):
self._provisioning_bundle_identifier = value
@property
def request_header(self):
return self._request_header
@request_header.setter
def request_header(self, value):
if isinstance(value, OpenApiAppleRequestHeader):
self._request_header = value
else:
self._request_header = OpenApiAppleRequestHeader.from_alipay_dict(value)
@property
def transaction_notification_identifier(self):
return self._transaction_notification_identifier
@transaction_notification_identifier.setter
def transaction_notification_identifier(self, value):
self._transaction_notification_identifier = value
def to_alipay_dict(self):
params = dict()
if self.amount:
if hasattr(self.amount, 'to_alipay_dict'):
params['amount'] = self.amount.to_alipay_dict()
else:
params['amount'] = self.amount
if self.currency_code:
if hasattr(self.currency_code, 'to_alipay_dict'):
params['currency_code'] = self.currency_code.to_alipay_dict()
else:
params['currency_code'] = self.currency_code
if self.partner_owned_merchant_identifier:
if hasattr(self.partner_owned_merchant_identifier, 'to_alipay_dict'):
params['partner_owned_merchant_identifier'] = self.partner_owned_merchant_identifier.to_alipay_dict()
else:
params['partner_owned_merchant_identifier'] = self.partner_owned_merchant_identifier
if self.provisioning_bundle_identifier:
if hasattr(self.provisioning_bundle_identifier, 'to_alipay_dict'):
params['provisioning_bundle_identifier'] = self.provisioning_bundle_identifier.to_alipay_dict()
else:
params['provisioning_bundle_identifier'] = self.provisioning_bundle_identifier
if self.request_header:
if hasattr(self.request_header, 'to_alipay_dict'):
params['request_header'] = self.request_header.to_alipay_dict()
else:
params['request_header'] = self.request_header
if self.transaction_notification_identifier:
if hasattr(self.transaction_notification_identifier, 'to_alipay_dict'):
params['transaction_notification_identifier'] = self.transaction_notification_identifier.to_alipay_dict()
else:
params['transaction_notification_identifier'] = self.transaction_notification_identifier
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayUserApplepayMerchantauthtokenGetModel()
if 'amount' in d:
o.amount = d['amount']
if 'currency_code' in d:
o.currency_code = d['currency_code']
if 'partner_owned_merchant_identifier' in d:
o.partner_owned_merchant_identifier = d['partner_owned_merchant_identifier']
if 'provisioning_bundle_identifier' in d:
o.provisioning_bundle_identifier = d['provisioning_bundle_identifier']
if 'request_header' in d:
o.request_header = d['request_header']
if 'transaction_notification_identifier' in d:
o.transaction_notification_identifier = d['transaction_notification_identifier']
return o
| 39.575 | 121 | 0.692777 | 4,546 | 0.957254 | 0 | 0 | 2,231 | 0.469783 | 0 | 0 | 712 | 0.149926 |
120fe27f1b5e75a52f5b34455fea3d4051d4c84c | 2,239 | py | Python | sloth/lexer.py | TueHaulund/SLOTH | bd6ce343b22719f58d746768eda36a7164ec0446 | [
"MIT"
] | null | null | null | sloth/lexer.py | TueHaulund/SLOTH | bd6ce343b22719f58d746768eda36a7164ec0446 | [
"MIT"
] | null | null | null | sloth/lexer.py | TueHaulund/SLOTH | bd6ce343b22719f58d746768eda36a7164ec0446 | [
"MIT"
] | null | null | null | import re
from sloth.grammar import LexicalGrammar
from sloth.token import Token
class LexerError(Exception):
def __init__(self, pos):
self.pos = pos
self.description = 'LexerError at Line {}, Column {}'.format(
self.pos[0], self.pos[1]
)
def __str__(self):
return self.description
def __repr__(self):
return 'LexerError {}'.format(self.pos)
class Lexer(object):
def __init__(self, buf):
# Initialise position state
self.pos = 0
self.line = 1
self.column = 1
# Remove trailing whitespace from buffer
self.buffer = buf.rstrip()
# Remove leading whitespace from buffer
# But advance lexer position accordingly
# Ensures subsequent token positions are accurate
if self.buffer:
self.skip_whitespace([' ', '\t', '\n'])
# Compile regex for lexing
grouped_rules = ['(?P<{}>{})'.format(t.name, t.value) for t in LexicalGrammar]
self.regex = re.compile('|'.join(grouped_rules))
def advance(self):
if self.buffer[self.pos] == '\n':
self.line += 1
self.column = 1
else:
self.column += 1
self.pos += 1
def skip_whitespace(self, whitespace):
while self.buffer[self.pos] in whitespace:
self.advance()
def next_token(self):
while self.pos < len(self.buffer):
# Advance past whitespace
self.skip_whitespace([' ', '\t'])
# Apply lexing regex at current positon
match = self.regex.match(self.buffer[self.pos :])
# Store current position
position = (self.line, self.column)
if not match:
raise LexerError(position)
token_name = match.lastgroup
# Extract lexeme
lexeme = match.group(token_name)
# Advance lexer position past current lexeme
for _ in lexeme:
self.advance()
# Produce token, skip comments
if token_name != 'COMMENT':
yield Token(token_name, lexeme, position)
def all_tokens(self):
return list(self.next_token())
| 27.304878 | 86 | 0.567664 | 2,151 | 0.960697 | 796 | 0.355516 | 0 | 0 | 0 | 0 | 494 | 0.220634 |
12103e0a24c1302957392f23e845952a37e61e1d | 577 | py | Python | test/hlt/pytest/python/com/huawei/iotplatform/client/dto/QueryDeviceCmdCancelTaskOutDTO.py | yuanyi-thu/AIOT- | 27f67d98324593c4c6c66bbd5e2a4aa7b9a4ac1e | [
"BSD-3-Clause"
] | 128 | 2018-10-29T04:11:47.000Z | 2022-03-07T02:19:14.000Z | test/hlt/pytest/python/com/huawei/iotplatform/client/dto/QueryDeviceCmdCancelTaskOutDTO.py | yuanyi-thu/AIOT- | 27f67d98324593c4c6c66bbd5e2a4aa7b9a4ac1e | [
"BSD-3-Clause"
] | 40 | 2018-11-02T00:40:48.000Z | 2021-12-07T09:33:56.000Z | test/hlt/pytest/python/com/huawei/iotplatform/client/dto/QueryDeviceCmdCancelTaskOutDTO.py | yuanyi-thu/AIOT- | 27f67d98324593c4c6c66bbd5e2a4aa7b9a4ac1e | [
"BSD-3-Clause"
] | 118 | 2018-10-29T08:43:57.000Z | 2022-01-07T06:49:25.000Z | from com.huawei.iotplatform.client.dto.DeviceCommandCancelTaskRespV4 import DeviceCommandCancelTaskRespV4
from com.huawei.iotplatform.client.dto.Pagination import Pagination
class QueryDeviceCmdCancelTaskOutDTO(object):
pagination = Pagination()
data = DeviceCommandCancelTaskRespV4()
def __init__(self):
pass
def getPagination(self):
return self.pagination
def setPagination(self, pagination):
self.pagination = pagination
def getData(self):
return self.data
def setData(self, data):
self.data = data
| 25.086957 | 105 | 0.729636 | 400 | 0.693241 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
1213c2cda4d18aa24aaef90a3765df3d511ac853 | 4,872 | py | Python | utils/file_utils.py | hardore007/FeedSDK-Python | c94795f75c0654d160e77301bb15ce055fe81e96 | [
"Apache-2.0"
] | 27 | 2019-04-18T18:56:11.000Z | 2022-03-27T14:33:05.000Z | utils/file_utils.py | hardore007/FeedSDK-Python | c94795f75c0654d160e77301bb15ce055fe81e96 | [
"Apache-2.0"
] | 1 | 2021-12-12T10:50:19.000Z | 2021-12-12T10:50:19.000Z | utils/file_utils.py | hardore007/FeedSDK-Python | c94795f75c0654d160e77301bb15ce055fe81e96 | [
"Apache-2.0"
] | 14 | 2019-06-13T17:56:28.000Z | 2022-01-11T22:32:13.000Z | # **************************************************************************
# Copyright 2018-2019 eBay Inc.
# Author/Developers: --
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# **************************************************************************/
import json
from os import makedirs
from os.path import isdir, basename, splitext, exists, dirname
from errors import custom_exceptions
import constants.feed_constants as const
def append_response_to_file(file_handler, data):
"""
Appends the given data to the existing file
:param file_handler: the existing and open file object
:param data: the data to be appended to the file
:raise if there are any IO errors a FileCreationError exception is raised
"""
try:
file_handler.write(data)
except (IOError, AttributeError) as exp:
if file_handler:
file_handler.close()
raise custom_exceptions.FileCreationError('Error while writing in the file: %s' % repr(exp), data)
def create_and_replace_binary_file(file_path):
"""
Creates a binary file in the given path including the file name and extension
If the file exists, it will be replaced
:param file_path: The path to the file including the file name and extension
:raise: if the file is not created successfully an FileCreationError exception is raised
"""
try:
if not exists(dirname(file_path)):
makedirs(dirname(file_path))
with open(file_path, 'wb'):
pass
except (IOError, OSError, AttributeError) as exp:
raise custom_exceptions.FileCreationError('IO error in creating file %s: %s' % (file_path, repr(exp)),
file_path)
def find_next_range(content_range_header, chunk_size=const.SANDBOX_CHUNK_SIZE):
"""
Finds the next value of the Range header
:param content_range_header: The content-range header value returned in the response, ex. 0-1000/7181823761
If None, the default Range header that is bytes=0-CHUNK_SIZE is returned
:param chunk_size: The chunk size in bytes. If not provided, the default chunk size is used
:return: The next value of the Range header in the format of bytes=lower-upper or empty string if no data is left
:raise: If the input content-range value is not correct an InputDataError exception is raised
"""
chunk = chunk_size if chunk_size else const.SANDBOX_CHUNK_SIZE
if content_range_header is None:
return const.RANGE_PREFIX + '0-' + str(chunk)
else:
try:
# ex. content-range : 0-1000/7181823761
range_components = content_range_header.split('/')
total_size = long(range_components[1])
bounds = range_components[0].split('-')
upper_bound = long(bounds[1]) + 1
if upper_bound > total_size:
return ''
return const.RANGE_PREFIX + str(upper_bound) + '-' + str(upper_bound + chunk)
except Exception:
raise custom_exceptions.InputDataError('Bad content-range header format: %s' % content_range_header,
content_range_header)
def get_extension(file_type):
"""
Returns file extension including '.' according to the given file type
:param file_type: format of the file such as gzip
:return: extension of the file such as '.gz'
"""
if not file_type:
return ''
if file_type.lower() == 'gz' or file_type.lower() == 'gzip':
return '.gz'
def get_file_name(name_or_path):
"""
Finds name of the file from the given file path or name
:param name_or_path: name or path to the file
:return: file name
"""
if not name_or_path:
raise custom_exceptions.InputDataError('Bad file name or directory %s' % name_or_path, name_or_path)
if isdir(name_or_path):
base = basename(name_or_path)
return splitext(base)
elif '/' in name_or_path:
return name_or_path[name_or_path.rfind('/') + 1:]
else:
return name_or_path
def read_json(file_path):
"""
Reads json from a file and returns a json object
:param file_path: the path to the file
:return: a json object
"""
with open(file_path) as config_file:
json_obj = json.load(config_file)
return json_obj
| 39.934426 | 117 | 0.654557 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,568 | 0.527094 |
1214ad1ddf30b9d8eafe82e3eadd72d6db36b769 | 1,040 | py | Python | tests/licenses/test_tasks.py | GitKlip/python-common | b44d1aaba5db3e1aa571b189999a8edea54c96bb | [
"MIT"
] | null | null | null | tests/licenses/test_tasks.py | GitKlip/python-common | b44d1aaba5db3e1aa571b189999a8edea54c96bb | [
"MIT"
] | null | null | null | tests/licenses/test_tasks.py | GitKlip/python-common | b44d1aaba5db3e1aa571b189999a8edea54c96bb | [
"MIT"
] | null | null | null | import os
import subprocess
class TestTasks:
""" Test that the tasks work with invoke. """
CMD_KWARGS = dict(
capture_output=True,
encoding="utf-8",
shell=True,
env=os.environ.copy(),
)
def test_unapproved_licenses(self):
""" Should emit table of unapproved licenses. """
reply = subprocess.run("poetry run invoke license.unapproved-licenses", **self.CMD_KWARGS)
output = reply.stdout
# assumes we require pylint and pylint is GPL and that's on our unapproved list
assert "pylint" in output
assert "GNU General Public License" in output
def test_write_table(self):
""" Should emit a table of licenses used. """
reply = subprocess.run("poetry run invoke license.write-table --outfile='-'", **self.CMD_KWARGS)
output = reply.stdout
# assumes we require coverage and at least one package we depend on is Apache licensed
assert 'coverage' in output
assert 'Apache Software License' in output
| 35.862069 | 104 | 0.653846 | 1,009 | 0.970192 | 0 | 0 | 0 | 0 | 0 | 0 | 482 | 0.463462 |
12181341c970163cc0fc0af88683d0ae2d3ab386 | 959 | py | Python | src/config.py | raywu60kg/credit-card-fraud-detection | 83d8e4ce6afeb9f74cccbd98286103a5ee874308 | [
"MIT"
] | 4 | 2021-04-16T08:16:38.000Z | 2021-12-24T14:21:38.000Z | src/config.py | raywu60kg/credit-card-fraud-detection | 83d8e4ce6afeb9f74cccbd98286103a5ee874308 | [
"MIT"
] | 3 | 2021-03-31T19:56:04.000Z | 2021-12-13T21:00:30.000Z | src/config.py | raywu60kg/lightgbm-project-demo | 83d8e4ce6afeb9f74cccbd98286103a5ee874308 | [
"MIT"
] | null | null | null | import os
from ray import tune
package_dir = os.path.dirname(os.path.abspath(__file__))
identity_dir = os.path.join(package_dir, "..", "data/train_identity.csv")
transaction_dir = os.path.join(package_dir, "..", "data/train_transaction.csv")
data_primary_key = "TransactionID"
label_name = ["isFraud"]
feature_names = [
'TransactionAmt',
'ProductCD',
'card1',
'C1',
'C2',
'C3',
'C4',
'C5',
'C6',
'C7',
'C8',
'C9',
'C10',
'C11',
'C12',
'C13',
'C14']
productCD_categories = ['C', 'H', 'R', 'S', 'W']
categorical_feature_names = ["card1", "ProductCD"]
num_samples = 3
hyperparams_space = {
"objective": "binary",
"metric": ["binary_logloss", "auc"],
"verbose": 1,
"num_threads": 1,
"num_iterations": 100,
"num_leaves": tune.randint(10, 1000),
"learning_rate": tune.loguniform(1e-8, 1e-1),
"identity_dir": identity_dir,
"transaction_dir": transaction_dir
}
| 22.833333 | 79 | 0.611053 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 357 | 0.372263 |
121852da41e3319cf6adc7aeb0809f6d3f289225 | 64 | py | Python | app/chat/__init__.py | B-T-S/Build | c6fae1fc44ec6a1ec3c2f01784ac2a1e67017ccc | [
"MIT"
] | 1 | 2020-09-06T11:21:43.000Z | 2020-09-06T11:21:43.000Z | app/chat/__init__.py | B-T-S/Build | c6fae1fc44ec6a1ec3c2f01784ac2a1e67017ccc | [
"MIT"
] | null | null | null | app/chat/__init__.py | B-T-S/Build | c6fae1fc44ec6a1ec3c2f01784ac2a1e67017ccc | [
"MIT"
] | null | null | null | from . import guest
from . import pusherauth
from . import admin | 21.333333 | 24 | 0.78125 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
121859643d9d38314cf2b4f7dd98311a26fc6f87 | 22,481 | py | Python | dataloader/statetransformer_Guidance.py | proroklab/magat_pathplanning | a2cab3b11abc46904bc45be1762a780becb1e8c7 | [
"MIT"
] | 40 | 2021-07-01T03:14:20.000Z | 2022-03-23T23:45:22.000Z | dataloader/statetransformer_Guidance.py | QingbiaoLi/magat_pathplanning | f28429b1a2ab7866c3001b82e6ae9ca3f072c106 | [
"MIT"
] | null | null | null | dataloader/statetransformer_Guidance.py | QingbiaoLi/magat_pathplanning | f28429b1a2ab7866c3001b82e6ae9ca3f072c106 | [
"MIT"
] | 13 | 2021-07-14T07:57:16.000Z | 2022-03-03T10:43:25.000Z | import numpy as np
import torch
from offlineExpert.a_star import PathPlanner
class AgentState:
def __init__(self, config):
# self.config = config
# self.num_agents = self.config.num_agents
self.config = config
self.num_agents = self.config.num_agents
# self.FOV = 5
self.FOV = self.config.FOV
self.FOV_width = int(self.FOV/2)
self.border = 1
self.W = self.FOV + 2
self.H = self.FOV + 2
self.dist = int(np.floor(self.W/2))
self.border_down = 0
self.border_left = 0
self.centerX = self.dist #+ 1
self.centerY = self.dist #+ 1
self.map_pad = None
self.Path_Planner = PathPlanner(False)
# a fuction to merge all different guidance
self.mode_Guidance = self.config.guidance.split('_')[0]
self.mode_Obstacle = self.config.guidance.split('_')[1]
if self.mode_Guidance == 'LocalG':
# print('#################### use local G')
self.agentStateToTensor = self.agentStateToTensor_LocalG
elif self.mode_Guidance == 'SemiLG':
# print('#################### use SemiLG G')
self.agentStateToTensor = self.agentStateToTensor_SemiLG
elif self.mode_Guidance == 'GlobalG':
# print('#################### use GlobalG G')
self.agentStateToTensor = self.agentStateToTensor_globalG
if self.config.guidance == 'Project_G':
# print('#################### use Project_G G')
# print("hello project")
self.agentStateToTensor = self.agentStateToTensor_projectG
# self.consider_DObs = True
if self.mode_Obstacle =='S':
self.consider_DObs = False
elif self.mode_Obstacle =='SD':
self.consider_DObs = True
def pad_with(self, vector, pad_width, iaxis, kwargs):
pad_value = kwargs.get('padder', 10)
vector[:pad_width[0]] = pad_value
vector[-pad_width[1]:] = pad_value
def setmap(self, map_channel):
self.map_global = np.array(map_channel,dtype=np.int64)
self.map_pad = np.pad(map_channel, self.FOV_width, self.pad_with, padder=1).astype(np.int64)
# print(self.map_pad.shape)
if self.mode_Guidance == 'Project_G':
self.max_localPath = 2
elif self.mode_Guidance == 'LocalG':
self.max_localPath = self.W * 4
else:
self.max_localPath = self.map_pad.shape[0] + self.map_pad.shape[1]
if self.mode_Guidance == 'SemiLG':
# store map know the border
# self.map_global_empty = np.zeros_like(self.map_pad,dtype=np.int64)
# self.map_global_empty_pad = np.pad(self.map_global_empty, self.FOV_width, self.pad_with, padder=1).astype(np.int64)
# self.store_map_agentView = np.tile(self.map_global_empty_pad,[self.num_agents,1,1]).astype(np.int64)
# store map don't know border
self.store_map_agentView = np.tile(np.zeros_like(self.map_pad),[self.num_agents,1,1]).astype(np.int64)
def setPosAgents(self, state_allagents):
# the second channel represent position of local agent and agents within FOV
# channel_allstate = np.zeros([self.W, self.H], dtype=np.int64)
channel_allstate = np.zeros_like(self.map_global, dtype=np.int64)
for id_agent in range(self.num_agents):
currentX = int(state_allagents[id_agent][0])
currentY = int(state_allagents[id_agent][1])
channel_allstate[currentX][currentY] = 1
channel_allstate_pad = np.pad(channel_allstate, self.FOV_width, self.pad_with, padder=0)
return channel_allstate_pad
def projectedgoal(self, goal_FOV, state_agent, goal_agent):
channel_goal = np.pad(goal_FOV, self.border, self.pad_with, padder=0)
dy = float(goal_agent[1]-state_agent[1])
dx = float(goal_agent[0]-state_agent[0])
y_sign = np.sign(dy)
x_sign = np.sign(dx)
# angle between position of agent an goal
angle = np.arctan2(dy,dx)
if (angle >= np.pi / 4 and angle <= np.pi * 3 / 4) or (angle >= -np.pi * (3 / 4) and angle <= -np.pi / 4):
goalY_FOV = int(self.dist * (y_sign + 1))
goalX_FOV = int(self.centerX + np.round(self.dist * dx / np.abs(dy)))
else:
goalX_FOV = int(self.dist * (x_sign + 1))
goalY_FOV = int(self.centerX + np.round(self.dist * dy / np.abs(dx)))
channel_goal[goalX_FOV][goalY_FOV] = 1
return channel_goal
def stackinfo_(self, goal_allagents, state_allagents):
input_step = np.stack((goal_allagents, state_allagents),axis=1)
input_tensor = torch.FloatTensor(input_step)
return input_tensor
def stackinfo(self, goal_allagents, state_allagents):
input_tensor = np.stack((goal_allagents, state_allagents))
input_tensor = torch.FloatTensor(input_tensor)
return input_tensor
def toInputTensor(self, goal_allagents, state_allagents):
# print("run on semilocal")
channel_allstate_pad = self.setPosAgents(state_allagents)
self.record_localPath = np.zeros([self.num_agents, self.max_localPath, 2])
input_step = []
select_agent = 5
for id_agent in range(self.num_agents): #range(3,6):#
load_state = (goal_allagents, state_allagents, channel_allstate_pad, id_agent)
mode = (id_agent == select_agent)
# mode = False
input_step_currentAgent, record_localPath = self.agentStateToTensor(load_state, mode)
input_step.append(input_step_currentAgent)
self.record_localPath[id_agent, :, :] = record_localPath
# if mode:
# print("\n", self.record_localPath[id_agent, :, :])
input_tensor = torch.FloatTensor(input_step)
return input_tensor
def get_localPath(self):
return self.record_localPath
def toSeqInputTensor(self, goal_allagents, state_AgentsSeq, makespan):
list_input = []
select_agent = 2
for step in range(makespan):
state_allagents = state_AgentsSeq[step][:]
channel_allstate_pad = self.setPosAgents(state_allagents)
input_step = []
for id_agent in range(self.num_agents): #range(3,6):#
load_state = (goal_allagents, state_allagents, channel_allstate_pad, id_agent)
mode = (id_agent == select_agent)
# mode = False
input_step_currentAgent, record_localPath = self.agentStateToTensor(load_state, mode)
input_step.append(input_step_currentAgent)
list_input.append(input_step)
input_tensor = torch.FloatTensor(list_input)
return input_tensor
def agentStateToTensor_projectG(self, load_state, mode):
goal_allagents, state_allagents, channel_allstate_pad, id_agent = load_state
input_step_currentAgent = []
currentX_global = int(state_allagents[id_agent][0])
currentY_global = int(state_allagents[id_agent][1])
currentPos = np.array([[currentX_global, currentY_global]])
record_localPath = np.repeat(currentPos, [self.max_localPath], axis=0)
goalX_global = int(goal_allagents[id_agent][0])
goalY_global = int(goal_allagents[id_agent][1])
# check position
FOV_X = [currentX_global, currentX_global + 2 * self.FOV_width + 1]
FOV_Y = [currentY_global, currentY_global + 2 * self.FOV_width + 1]
channel_map_FOV = self.map_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
channel_map = np.pad(channel_map_FOV, self.border, self.pad_with, padder=0)
channel_state_FOV = channel_allstate_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
channel_state = np.pad(channel_state_FOV, self.border, self.pad_with, padder=0)
channel_goal_global = np.zeros_like(self.map_global, dtype=np.int64)
channel_goal_global[goalX_global][goalY_global] = 1
channel_goal_pad = np.pad(channel_goal_global, self.FOV_width, self.pad_with, padder=0)
channel_goal_FOV = channel_goal_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
if (channel_goal_FOV > 0).any():
channel_goal = np.pad(channel_goal_FOV, self.border, self.pad_with, padder=0)
else:
channel_goal = self.projectedgoal(channel_goal_FOV, [currentX_global, currentY_global],
[goalX_global, goalY_global])
goalX_FOV, goalY_FOV = np.nonzero(channel_goal)
if goalX_FOV.shape[0] == 1:
for id_path in range(goalX_FOV.shape[0]):
posX_goalFOV = goalX_FOV[0]
posY_goalFOV = goalY_FOV[0]
record_localPath[id_path][0] = posX_goalFOV + (currentX_global - self.FOV_width) - 1
record_localPath[id_path][1] = posY_goalFOV + (currentY_global - self.FOV_width) - 1
# if mode:
# print("\n-----------{} - Goal -----------\n{}".format(id_agent, channel_goal_globalmap_pad))
# print("\n", channel_goal)
# print("\n", goalX_global, goalY_global)
input_step_currentAgent.append(channel_map)
input_step_currentAgent.append(channel_goal)
input_step_currentAgent.append(channel_state)
return input_step_currentAgent, record_localPath
def agentStateToTensor_LocalG(self, load_state, mode):
goal_allagents, state_allagents, channel_allstate_pad, id_agent = load_state
input_step_currentAgent = []
currentX_global = int(state_allagents[id_agent][0])
currentY_global = int(state_allagents[id_agent][1])
currentPos = np.array([[currentX_global, currentY_global]])
record_localPath = np.repeat(currentPos, [self.max_localPath], axis=0)
goalX_global = int(goal_allagents[id_agent][0])
goalY_global = int(goal_allagents[id_agent][1])
# check position
FOV_X = [currentX_global, currentX_global + 2 * self.FOV_width + 1]
FOV_Y = [currentY_global, currentY_global + 2 * self.FOV_width + 1]
channel_map_FOV = self.map_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
channel_map = np.pad(channel_map_FOV, self.border, self.pad_with, padder=0)
if self.consider_DObs:
channel_state_FOV = channel_allstate_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
channel_state = np.pad(channel_state_FOV, self.border, self.pad_with, padder=0)
else:
channel_state = np.zeros_like(channel_map, dtype=np.int64)
channel_goal_global = np.zeros_like(self.map_global, dtype=np.int64)
channel_goal_global[goalX_global][goalY_global] = 1
channel_goal_pad = np.pad(channel_goal_global, self.FOV_width, self.pad_with, padder=0)
channel_goal_FOV = channel_goal_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
if (channel_goal_FOV > 0).any():
channel_goal = np.pad(channel_goal_FOV, self.border, self.pad_with, padder=0)
else:
channel_goal = self.projectedgoal(channel_goal_FOV, [currentX_global, currentY_global],
[goalX_global, goalY_global])
goalX_FOV, goalY_FOV = np.nonzero(channel_goal)
if goalX_FOV.shape[0] == 1:
channel_combine = np.add(channel_map, channel_state)
channel_combine[self.centerX][self.centerY] = 0
check_collidedWithGoal = np.add(channel_state, channel_goal)
collided_goalX_FOV, collided_goalY_FOV = np.where(check_collidedWithGoal == 2)
if collided_goalX_FOV.shape[0] >= 1:
channel_combine[int(collided_goalX_FOV[0])][int(collided_goalY_FOV[0])] = 0
full_path, full_path_length = self.Path_Planner.a_star(channel_combine,
[self.centerX, self.centerY],
[goalX_FOV[0], goalY_FOV[0]])
for id_path in range(full_path_length):
posX_goalFOV = full_path[id_path][0]
posY_goalFOV = full_path[id_path][1]
channel_goal[posX_goalFOV][posY_goalFOV] = 1
record_localPath[id_path][0] = posX_goalFOV + (currentX_global - self.FOV_width) - 1
record_localPath[id_path][1] = posY_goalFOV + (currentY_global - self.FOV_width) - 1
# if mode:
# print("\n-----------{} - Goal -----------\n{}".format(id_agent, channel_goal_globalmap_pad))
# print("\n", channel_goal)
# print("\n", goalX_global, goalY_global)
input_step_currentAgent.append(channel_map)
input_step_currentAgent.append(channel_goal)
input_step_currentAgent.append(channel_state)
return input_step_currentAgent, record_localPath
def agentStateToTensor_SemiLG(self, load_state, mode):
goal_allagents, state_allagents, channel_allstate_pad, id_agent = load_state
input_step_currentAgent = []
currentX_global = int(state_allagents[id_agent][0])
currentY_global = int(state_allagents[id_agent][1])
currentPos = np.array([[currentX_global,currentY_global]])
record_localPath = np.repeat(currentPos, [self.max_localPath], axis=0)
goalX_global = int(goal_allagents[id_agent][0])
goalY_global = int(goal_allagents[id_agent][1])
# check position
FOV_X = [currentX_global, currentX_global + 2*self.FOV_width + 1]
FOV_Y = [currentY_global, currentY_global + 2*self.FOV_width + 1]
# crop the state within FOV from global map
channel_state_FOV = channel_allstate_pad[FOV_X[0]:FOV_X[1],FOV_Y[0]:FOV_Y[1]]
# (input tensor-ready) pad the state within FOV with border 1
channel_state = np.pad(channel_state_FOV, self.border, self.pad_with, padder=0, dtype=np.int64)
# array to store robot state (within FOV) and goal
channel_state_globalmap = np.zeros_like(self.map_pad, dtype=np.int64)
channel_goal_globalmap = np.zeros_like(self.map_pad, dtype=np.int64)
channel_goal_globalmap_pad = np.pad(channel_goal_globalmap, self.border, self.pad_with, padder=0, dtype=np.int64)
FOV_X = [currentX_global, currentX_global + 2 * self.FOV_width + 1]
FOV_Y = [currentY_global, currentY_global + 2 * self.FOV_width + 1]
channel_state_globalmap[FOV_X[0]:FOV_X[1],FOV_Y[0]:FOV_Y[1]] = channel_state_FOV
# the map that current robot observe
# if mode:
# print(channel_fullmap_FOV)
channel_fullmap_FOV = self.map_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
channel_map = np.pad(channel_fullmap_FOV, self.border, self.pad_with, padder=0, dtype=np.int64)
# use to update the data of the map in the memory of current robot
self.store_map_agentView[id_agent,FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]] = channel_fullmap_FOV
channel_agentmap = self.store_map_agentView[id_agent,:,:]
channel_combine = np.add(channel_agentmap, channel_state_globalmap)
channel_combine_pad = np.pad(channel_combine, self.border, self.pad_with, padder=0, dtype=np.int64)
currentX_global_pad = currentX_global + self.FOV_width + self.border
currentY_global_pad = currentY_global + self.FOV_width + self.border
goalX_global_pad = goalX_global + self.FOV_width + self.border
goalY_global_pad = goalY_global + self.FOV_width + self.border
FOV_X_pad = [currentX_global, currentX_global + 2 * self.FOV_width + 1 + 2 * self.border]
FOV_Y_pad = [currentY_global, currentY_global + 2 * self.FOV_width + 1 + 2 * self.border]
# check if the agents standing at current agent's goal
if channel_combine_pad[goalX_global_pad][goalY_global_pad] == 1:
channel_combine_pad[goalX_global_pad][goalY_global_pad] = 0
# if mode:
# print("-------------------------\n------------ {} ------------\n------------------------\n".format(id_agent))
# print("------------{} World Map -----------\n{}".format(id_agent,self.map_pad))
# print("------------ Agent{} storedMap-----------\n{} \n".format(id_agent,self.store_map_agentView[id_agent, :, :]))
# print("------------{} A* Map -----------\n{}\n".format(id_agent,channel_combine_pad))
full_path, full_path_length = self.Path_Planner.a_star(channel_combine_pad,
[currentX_global_pad, currentY_global_pad],
[goalX_global_pad, goalY_global_pad])
# print(full_path)
for id_path in range(full_path_length):
posX_goalFOV = full_path[id_path][0]
posY_goalFOV = full_path[id_path][1]
channel_goal_globalmap_pad[posX_goalFOV][posY_goalFOV] = 1
record_localPath[id_path][0] = posX_goalFOV - 1 - self.FOV_width
record_localPath[id_path][1] = posY_goalFOV - 1 - self.FOV_width
channel_goal = np.zeros_like(channel_map, dtype=np.int64)
# print(channel_goal_globalmap_pad.shape, FOV_X_pad[0], FOV_X_pad[1], FOV_Y_pad[0],FOV_Y_pad[1])
channel_goal[:, :] = channel_goal_globalmap_pad[FOV_X_pad[0]:FOV_X_pad[1], FOV_Y_pad[0]:FOV_Y_pad[1]]
# if mode:
# print("\n-----------{} - Goal -----------\n{}".format(id_agent, channel_goal_globalmap_pad))
# print("\n", channel_goal)
# print("\n", goalX_global, goalY_global)
input_step_currentAgent.append(channel_map.astype(np.float64))
input_step_currentAgent.append(channel_goal.astype(np.float64))
input_step_currentAgent.append(channel_state.astype(np.float64))
return input_step_currentAgent, record_localPath
def agentStateToTensor_globalG(self, load_state, mode):
goal_allagents, state_allagents, channel_allstate_pad, id_agent = load_state
input_step_currentAgent = []
currentX_global = int(state_allagents[id_agent][0])
currentY_global = int(state_allagents[id_agent][1])
currentPos = np.array([[currentX_global, currentY_global]], dtype=np.int64)
record_localPath = np.repeat(currentPos, [self.max_localPath], axis=0)
goalX_global = int(goal_allagents[id_agent][0])
goalY_global = int(goal_allagents[id_agent][1])
# define the region of FOV
FOV_X = [currentX_global, currentX_global + 2 * self.FOV_width + 1]
FOV_Y = [currentY_global, currentY_global + 2 * self.FOV_width + 1]
# crop the state within FOV from global map
channel_state_FOV = channel_allstate_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
# (input tensor-ready) pad the state within FOV with border 1
channel_state = np.pad(channel_state_FOV, self.border, self.pad_with, padder=0, dtype=np.int64)
# crop the map within FOV from global map
# if mode:
# print(channel_fullmap_FOV)
channel_fullmap_FOV = self.map_pad[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]]
# (input map-ready) pad the map within FOV with border 1
channel_map = np.pad(channel_fullmap_FOV, self.border, self.pad_with, padder=0, dtype=np.int64)
# array to store robot state (within FOV) and goal into map size array
channel_state_globalmap = np.zeros_like(self.map_pad, dtype=np.int64)
channel_goal_globalmap = np.zeros_like(self.map_pad, dtype=np.int64)
channel_goal_globalmap_pad = np.pad(channel_goal_globalmap, self.border, self.pad_with, padder=0,
dtype=np.int64)
if self.consider_DObs:
channel_state_globalmap[FOV_X[0]:FOV_X[1], FOV_Y[0]:FOV_Y[1]] = channel_state_FOV
channel_combine = np.add(self.map_pad, channel_state_globalmap)
channel_combine_pad = np.pad(channel_combine, self.border, self.pad_with, padder=0, dtype=np.int64)
currentX_global_pad = currentX_global + self.FOV_width + self.border
currentY_global_pad = currentY_global + self.FOV_width + self.border
goalX_global_pad = goalX_global + self.FOV_width + self.border
goalY_global_pad = goalY_global + self.FOV_width + self.border
FOV_X_pad = [currentX_global, currentX_global + 2 * self.FOV_width + 1 + 2 * self.border]
FOV_Y_pad = [currentY_global, currentY_global + 2 * self.FOV_width + 1 + 2 * self.border]
# check if the agents standing at current agent's goal
if channel_combine_pad[goalX_global_pad][goalY_global_pad] == 1:
channel_combine_pad[goalX_global_pad][goalY_global_pad] = 0
# if mode:
# print("-------------------------\n------------ {} ------------\n------------------------\n".format(id_agent))
# print("------------{} World Map -----------\n{}".format(id_agent,self.map_pad))
# print("------------{} A* Map -----------\n{}\n".format(id_agent,channel_combine_pad))
full_path, full_path_length = self.Path_Planner.a_star(channel_combine_pad,
[currentX_global_pad, currentY_global_pad],
[goalX_global_pad, goalY_global_pad])
for id_path in range(full_path_length):
posX_goalFOV = full_path[id_path][0]
posY_goalFOV = full_path[id_path][1]
# print(posX_goalFOV,posY_goalFOV)
channel_goal_globalmap_pad[posX_goalFOV][posY_goalFOV] = 1
record_localPath[id_path][0] = posX_goalFOV - 1 - self.FOV_width
record_localPath[id_path][1] = posY_goalFOV - 1 - self.FOV_width
channel_goal = np.zeros_like(channel_map, dtype=np.int64)
channel_goal[:, :] = channel_goal_globalmap_pad[FOV_X_pad[0]:FOV_X_pad[1], FOV_Y_pad[0]:FOV_Y_pad[1]]
# if mode:
# print("\n-----------{} - Goal -----------\n{}".format(id_agent, channel_goal_globalmap_pad))
# print("\n", channel_goal)
# print("\n", goalX_global, goalY_global)
input_step_currentAgent.append(channel_map.astype(np.float64))
input_step_currentAgent.append(channel_goal.astype(np.float64))
input_step_currentAgent.append(channel_state.astype(np.float64))
return input_step_currentAgent, record_localPath
| 45.2334 | 129 | 0.637294 | 22,400 | 0.996397 | 0 | 0 | 0 | 0 | 0 | 0 | 3,464 | 0.154086 |
121923d1e8491eca43f62c50b434300d0afbbc05 | 1,713 | py | Python | Algorithms/0212_Word_Search_II/Python/Word_Search_II_Solution_1.py | lht19900714/Leetcode_Python | 645211f0ec71de579f1b091453db9eea80de9816 | [
"MIT"
] | null | null | null | Algorithms/0212_Word_Search_II/Python/Word_Search_II_Solution_1.py | lht19900714/Leetcode_Python | 645211f0ec71de579f1b091453db9eea80de9816 | [
"MIT"
] | null | null | null | Algorithms/0212_Word_Search_II/Python/Word_Search_II_Solution_1.py | lht19900714/Leetcode_Python | 645211f0ec71de579f1b091453db9eea80de9816 | [
"MIT"
] | null | null | null |
# Space: O(n)
# Time: O(n)
import collections
class Solution():
def findWords(self, board, words):
column = len(board)
if column == 0: return []
row = len(board[0])
if row == 0: return []
target_word = set()
res = set()
# build a trie, this will be used in DFS search
trie = collections.defaultdict(set)
trie[''] = {word[0] for word in words}
for each_word in words:
string = ''
for index in range(len(each_word)):
string += each_word[index]
if index != len(each_word) - 1:
trie[string].add(each_word[index + 1])
else:
target_word.add(each_word)
def search(word_list, cur_sub_string, x, y):
if cur_sub_string in target_word:
res.add(cur_sub_string)
target_word.remove(cur_sub_string)
if (not 0 <= x < row) or (not 0 <= y < column) or board[y][x] == 0 or board[y][x] not in trie[cur_sub_string] or len(res) == len(word_list): return
cur_sub_string += board[y][x]
temp = board[y][x]
board[y][x] = 0
search(word_list, cur_sub_string, x - 1, y)
search(word_list, cur_sub_string, x + 1, y)
search(word_list, cur_sub_string, x, y - 1)
search(word_list, cur_sub_string, x, y + 1)
board[y][x] = temp
cur_sub_string = cur_sub_string[:-1]
for y in range(column):
for x in range(row):
if len(words) == len(res):
return res
search(words, '', x, y)
return res
| 28.081967 | 159 | 0.50613 | 1,657 | 0.967309 | 0 | 0 | 0 | 0 | 0 | 0 | 78 | 0.045534 |
12192a5c4a0869098ef5a2f6114fc9d572aaa5ab | 2,101 | py | Python | training/pl_logger.py | stdiff/emo-classifier | 211731a44022408c750b611383216ce0578f2d41 | [
"MIT"
] | null | null | null | training/pl_logger.py | stdiff/emo-classifier | 211731a44022408c750b611383216ce0578f2d41 | [
"MIT"
] | null | null | null | training/pl_logger.py | stdiff/emo-classifier | 211731a44022408c750b611383216ce0578f2d41 | [
"MIT"
] | null | null | null | from typing import Dict, Any, Optional
import pandas as pd
from pytorch_lightning.loggers import LightningLoggerBase
from pytorch_lightning.loggers.base import rank_zero_experiment
from pytorch_lightning.utilities import rank_zero_only
class SimpleLogger(LightningLoggerBase):
def __init__(self):
super().__init__()
self.metrics = []
self.params: Optional[Dict[str, Any]] = None
@property
def name(self):
return "simple_logger"
def flush(self):
self.metrics = []
self.params = None
@property
@rank_zero_experiment
def experiment(self):
# Return the experiment object associated with this logger.
pass
@property
def version(self):
# Return the experiment version, int or str.
return "0.1"
@rank_zero_only
def log_hyperparams(self, params):
self.params = params
@rank_zero_only
def log_metrics(self, metrics: Dict[str, Any], step):
## metrics = {"metric_name": 0.123, "epoch": 9}
## step will not be cleared at the end of an epoch. It is just increasing
# print(metrics)
metrics["step"] = step
self.metrics.append(metrics)
@rank_zero_only
def save(self):
# Optional. Any code necessary to save logger data goes here
# If you implement this, remember to call `super().save()`
# at the start of the method (important for aggregation of metrics)
super().save()
@rank_zero_only
def finalize(self, status):
# Optional. Any code that needs to be run after training
# finishes goes here
pass
def get_history(self) -> pd.DataFrame:
rows = []
for metric in self.metrics:
metric_name = [key for key in metric.keys() if key not in ("epoch", "step")][0]
row = {
"epoch": metric["epoch"],
"step": metric["step"],
"metric": metric_name,
"value": metric[metric_name],
}
rows.append(row)
return pd.DataFrame(rows)
| 29.180556 | 91 | 0.611614 | 1,861 | 0.885769 | 0 | 0 | 1,119 | 0.532604 | 0 | 0 | 580 | 0.276059 |
121a371d11810daf15b49cd12a5b51615558c5c2 | 13,225 | py | Python | exec/tests/unit/runners/test_evaluators.py | AndersonReyes/klio | 758c80daa2c537a42a72e5ba061e8686b68de111 | [
"Apache-2.0"
] | 705 | 2020-10-02T17:25:31.000Z | 2022-03-24T15:26:53.000Z | exec/tests/unit/runners/test_evaluators.py | AndersonReyes/klio | 758c80daa2c537a42a72e5ba061e8686b68de111 | [
"Apache-2.0"
] | 63 | 2020-10-02T17:53:47.000Z | 2022-03-23T21:36:40.000Z | exec/tests/unit/runners/test_evaluators.py | isabella232/klio | 4b8b96b03948235c0b28af96fc85de17cb679e8c | [
"Apache-2.0"
] | 49 | 2020-10-13T18:44:34.000Z | 2022-03-18T08:38:15.000Z | # Copyright 2021 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Tests for KlioPubSubReadEvaluator
These were adapted from
apache_beam/io/gcp/pubsub_test.py::TestReadFromPubSub.
These validate that the original expected behavior from _PubSubReadEvaluator
was kept, as well checking that:
* Responses are not auto-acked
* MessageManager daemon threads started
* Messages added to MessageManager
* Messages handled one at a time, instead of 10 at a time
"""
import pytest
from apache_beam import transforms as beam_transforms
from apache_beam import utils as beam_utils
from apache_beam.io.gcp import pubsub as b_pubsub
from apache_beam.options import pipeline_options
from apache_beam.runners.direct import direct_runner
from apache_beam.runners.direct import transform_evaluator
from apache_beam.testing import test_pipeline as beam_test_pipeline
from apache_beam.testing import test_utils as beam_test_utils
from apache_beam.testing import util as beam_testing_util
from klio.message import pubsub_message_manager as pmm
from klio_core.proto import klio_pb2
from klio_exec.runners import evaluators
@pytest.fixture
def patch_msg_manager(mocker, monkeypatch):
p = mocker.Mock(name="patch_msg_manager")
monkeypatch.setattr(pmm, "MessageManager", p)
return p
@pytest.fixture
def patch_sub_client(mocker, monkeypatch):
# patch out network calls in SubscriberClient instantiation
c = mocker.Mock(name="patch_sub_client")
monkeypatch.setattr(evaluators.g_pubsub, "SubscriberClient", c)
return c.return_value
class KlioTestPubSubReadEvaluator(object):
"""Wrapper of _PubSubReadEvaluator that makes it bounded."""
_pubsub_read_evaluator = evaluators.KlioPubSubReadEvaluator
def __init__(self, *args, **kwargs):
self._evaluator = self._pubsub_read_evaluator(*args, **kwargs)
def start_bundle(self):
return self._evaluator.start_bundle()
def process_element(self, element):
return self._evaluator.process_element(element)
def finish_bundle(self):
result = self._evaluator.finish_bundle()
result.unprocessed_bundles = []
result.keyed_watermark_holds = {None: None}
return result
transform_evaluator.TransformEvaluatorRegistry._test_evaluators_overrides = {
direct_runner._DirectReadFromPubSub: KlioTestPubSubReadEvaluator,
}
def test_klio_pubsub_read_eval_read_messages_success(
mocker, patch_sub_client, patch_msg_manager,
):
exp_entity_id = "entity_id"
kmsg = klio_pb2.KlioMessage()
kmsg.data.element = bytes(exp_entity_id, "utf-8")
data = kmsg.SerializeToString()
publish_time_secs = 1520861821
publish_time_nanos = 234567000
attributes = {"key": "value"}
ack_id = "ack_id"
pull_response = beam_test_utils.create_pull_response(
[
beam_test_utils.PullResponseMessage(
data, attributes, publish_time_secs, publish_time_nanos, ack_id
)
]
)
pmsg = b_pubsub.PubsubMessage(data, attributes)
expected_elements = [
beam_testing_util.TestWindowedValue(
pmsg,
beam_utils.timestamp.Timestamp(1520861821.234567),
[beam_transforms.window.GlobalWindow()],
)
]
patch_sub_client.pull.return_value = pull_response
options = pipeline_options.PipelineOptions([])
options.view_as(pipeline_options.StandardOptions).streaming = True
with beam_test_pipeline.TestPipeline(options=options) as p:
pcoll = p | b_pubsub.ReadFromPubSub(
"projects/fakeprj/topics/a_topic", None, None, with_attributes=True
)
beam_testing_util.assert_that(
pcoll,
beam_testing_util.equal_to(expected_elements),
reify_windows=True,
)
# Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()
# 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(
patch_sub_client.subscription_path()
)
# 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id, pmsg)
# 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(
mocker.ANY, max_messages=1, return_immediately=True
)
patch_sub_client.api.transport.channel.close.assert_called_once_with()
def test_read_messages_timestamp_attribute_milli_success(
mocker, patch_sub_client, patch_msg_manager,
):
exp_entity_id = "entity_id"
kmsg = klio_pb2.KlioMessage()
kmsg.data.element = bytes(exp_entity_id, "utf-8")
data = kmsg.SerializeToString()
attributes = {"time": "1337"}
publish_time_secs = 1520861821
publish_time_nanos = 234567000
ack_id = "ack_id"
pull_response = beam_test_utils.create_pull_response(
[
beam_test_utils.PullResponseMessage(
data, attributes, publish_time_secs, publish_time_nanos, ack_id
)
]
)
pmsg = b_pubsub.PubsubMessage(data, attributes)
expected_elements = [
beam_testing_util.TestWindowedValue(
pmsg,
beam_utils.timestamp.Timestamp(
micros=int(attributes["time"]) * 1000
),
[beam_transforms.window.GlobalWindow()],
),
]
patch_sub_client.pull.return_value = pull_response
options = pipeline_options.PipelineOptions([])
options.view_as(pipeline_options.StandardOptions).streaming = True
with beam_test_pipeline.TestPipeline(options=options) as p:
pcoll = p | b_pubsub.ReadFromPubSub(
"projects/fakeprj/topics/a_topic",
None,
None,
with_attributes=True,
timestamp_attribute="time",
)
# Check original functionality that was kept the same
beam_testing_util.assert_that(
pcoll,
beam_testing_util.equal_to(expected_elements),
reify_windows=True,
)
# Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()
# 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(
patch_sub_client.subscription_path()
)
# 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id, pmsg)
# 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(
mocker.ANY, max_messages=1, return_immediately=True
)
patch_sub_client.api.transport.channel.close.assert_called_once_with()
def test_read_messages_timestamp_attribute_rfc3339_success(
mocker, patch_sub_client, patch_msg_manager,
):
exp_entity_id = "entity_id"
kmsg = klio_pb2.KlioMessage()
kmsg.data.element = bytes(exp_entity_id, "utf-8")
data = kmsg.SerializeToString()
attributes = {"time": "2018-03-12T13:37:01.234567Z"}
publish_time_secs = 1337000000
publish_time_nanos = 133700000
ack_id = "ack_id"
pull_response = beam_test_utils.create_pull_response(
[
beam_test_utils.PullResponseMessage(
data, attributes, publish_time_secs, publish_time_nanos, ack_id
)
]
)
pmsg = b_pubsub.PubsubMessage(data, attributes)
expected_elements = [
beam_testing_util.TestWindowedValue(
pmsg,
beam_utils.timestamp.Timestamp.from_rfc3339(attributes["time"]),
[beam_transforms.window.GlobalWindow()],
),
]
patch_sub_client.pull.return_value = pull_response
options = pipeline_options.PipelineOptions([])
options.view_as(pipeline_options.StandardOptions).streaming = True
with beam_test_pipeline.TestPipeline(options=options) as p:
pcoll = p | b_pubsub.ReadFromPubSub(
"projects/fakeprj/topics/a_topic",
None,
None,
with_attributes=True,
timestamp_attribute="time",
)
# Check original functionality that was kept the same
beam_testing_util.assert_that(
pcoll,
beam_testing_util.equal_to(expected_elements),
reify_windows=True,
)
# Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()
# 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(
patch_sub_client.subscription_path()
)
# 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id, pmsg)
# 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(
mocker.ANY, max_messages=1, return_immediately=True
)
patch_sub_client.api.transport.channel.close.assert_called_once_with()
def test_read_messages_timestamp_attribute_missing(
mocker, patch_sub_client, patch_msg_manager,
):
exp_entity_id = "entity_id"
kmsg = klio_pb2.KlioMessage()
kmsg.data.element = bytes(exp_entity_id, "utf-8")
data = kmsg.SerializeToString()
attributes = {}
publish_time_secs = 1520861821
publish_time_nanos = 234567000
publish_time = "2018-03-12T13:37:01.234567Z"
ack_id = "ack_id"
pull_response = beam_test_utils.create_pull_response(
[
beam_test_utils.PullResponseMessage(
data, attributes, publish_time_secs, publish_time_nanos, ack_id
)
]
)
pmsg = b_pubsub.PubsubMessage(data, attributes)
expected_elements = [
beam_testing_util.TestWindowedValue(
pmsg,
beam_utils.timestamp.Timestamp.from_rfc3339(publish_time),
[beam_transforms.window.GlobalWindow()],
),
]
patch_sub_client.pull.return_value = pull_response
options = pipeline_options.PipelineOptions([])
options.view_as(pipeline_options.StandardOptions).streaming = True
with beam_test_pipeline.TestPipeline(options=options) as p:
pcoll = p | b_pubsub.ReadFromPubSub(
"projects/fakeprj/topics/a_topic",
None,
None,
with_attributes=True,
timestamp_attribute="nonexistent",
)
# Check original functionality that was kept the same
beam_testing_util.assert_that(
pcoll,
beam_testing_util.equal_to(expected_elements),
reify_windows=True,
)
# Check overridden functionality:
# 1. Check that auto-acking is skipped
patch_sub_client.acknowledge.assert_not_called()
# 2. Check that MessageManager daemon threads were started
patch_msg_manager.assert_called_once_with(
patch_sub_client.subscription_path()
)
# 3. Check that messages were added to the MessageManager
patch_msg_manager.return_value.add.assert_called_once_with(ack_id, pmsg)
# 4. Check that one message is handled at a time, instead of the
# original 10
patch_sub_client.pull.assert_called_once_with(
mocker.ANY, max_messages=1, return_immediately=True
)
patch_sub_client.api.transport.channel.close.assert_called_once_with()
def test_read_messages_timestamp_attribute_fail_parse(patch_sub_client):
exp_entity_id = "entity_id"
kmsg = klio_pb2.KlioMessage()
kmsg.data.element = bytes(exp_entity_id, "utf-8")
data = kmsg.SerializeToString()
attributes = {"time": "1337 unparseable"}
publish_time_secs = 1520861821
publish_time_nanos = 234567000
ack_id = "ack_id"
pull_response = beam_test_utils.create_pull_response(
[
beam_test_utils.PullResponseMessage(
data, attributes, publish_time_secs, publish_time_nanos, ack_id
)
]
)
patch_sub_client.pull.return_value = pull_response
options = pipeline_options.PipelineOptions([])
options.view_as(pipeline_options.StandardOptions).streaming = True
p = beam_test_pipeline.TestPipeline(options=options)
_ = p | b_pubsub.ReadFromPubSub(
"projects/fakeprj/topics/a_topic",
None,
None,
with_attributes=True,
timestamp_attribute="time",
)
with pytest.raises(ValueError, match=r"parse"):
p.run()
patch_sub_client.acknowledge.assert_not_called()
patch_sub_client.api.transport.channel.close.assert_called_with()
| 35.172872 | 79 | 0.707977 | 650 | 0.049149 | 0 | 0 | 429 | 0.032439 | 0 | 0 | 2,843 | 0.214972 |
121b43822422f72f27023efc96df9a7d9e66a9dd | 218 | py | Python | tests/test_test.py | pthomson88/drug_design | d92ed4c06cd036c83fe60ada05b493f4581d24d6 | [
"MIT"
] | 1 | 2020-07-06T10:50:17.000Z | 2020-07-06T10:50:17.000Z | tests/test_test.py | pthomson88/drug_design | d92ed4c06cd036c83fe60ada05b493f4581d24d6 | [
"MIT"
] | 3 | 2020-04-06T22:06:07.000Z | 2020-04-23T23:07:43.000Z | tests/test_test.py | pthomson88/drug_design | d92ed4c06cd036c83fe60ada05b493f4581d24d6 | [
"MIT"
] | null | null | null | import pytest
def test_test():
hello_world = "Hello World"
assert hello_world == "Hello World"
def test_always_passes():
assert True
#This test will always fail
def test_always_fails():
assert False
| 16.769231 | 39 | 0.715596 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 53 | 0.243119 |
121c0a3df995d20450310ecffb8591aaab406cd8 | 3,812 | py | Python | tic-tac-toe.py | aaditkapoor/tic-tac-toe-ml-project | 21071af048486198bedcf4c775c3e44136b1a62f | [
"MIT"
] | 4 | 2020-09-27T15:15:07.000Z | 2022-02-02T22:07:18.000Z | tic-tac-toe.py | aaditkapoor/tic-tac-toe-ml-project | 21071af048486198bedcf4c775c3e44136b1a62f | [
"MIT"
] | null | null | null | tic-tac-toe.py | aaditkapoor/tic-tac-toe-ml-project | 21071af048486198bedcf4c775c3e44136b1a62f | [
"MIT"
] | 2 | 2020-10-01T04:06:04.000Z | 2021-12-12T15:07:23.000Z |
# coding: utf-8
# - We are creating a very simple machine learning model.<br>
# - Using dataset: tic-tac-toe.data.txt with user-defined columns.<br>
# - We are treating this problem as a supervised learning problem.<br>
# In[74]:
# This the rough sketch of the processing that happened in my brain while creating the program.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Imputer
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
# In[52]:
# Loading data
data = pd.read_csv("../tic-tac-toe.data.txt", sep = ",")
data_copy = pd.read_csv("../tic-tac-toe.data.txt", sep = ",")
# Setting cols.
data.columns = ["first_row_left", "first_row_middle", "first_row_right", "center_row_left", "center_row_middle", "center_row_right", "bottom_row_left", "bottom_row_middle", "bottom_row_right", "is_win"]
data_copy.columns = ["first_row_left", "first_row_middle", "first_row_right", "center_row_left", "center_row_middle", "center_row_right", "bottom_row_left", "bottom_row_middle", "bottom_row_right", "is_win"]
# In[53]:
# Viewing data
data.head()
# In[54]:
# As we can see the the different move options, we perform label encoding.
mapping_for_moves = {'x':1, "o":0} # For b, we put mean of the data.
mapping_for_wins = {"positive":1, "negative":0} # Positive is win, negative is lose
data.is_win = data.is_win.map(mapping_for_wins)
data_copy.is_win = data_copy.is_win.map(mapping_for_wins)
data = data.drop(columns=["is_win"], axis=1)
# In[55]:
data.head()
# In[56]:
for i in data.columns: # Applying map to all the columns except is_win.
data[i] = data[i].map(mapping_for_moves)
# In[57]:
data.head() # Viewing data
# In[58]:
# Extracting features and labels
features = data.values
labels = data_copy.is_win.values
# In[63]:
# Filling missing values aka "b"
features = (Imputer().fit_transform(features))
# In[48]:
len(features)
# In[49]:
len(labels)
# In[65]:
# Changing type to int
features = features.astype(np.int)
labels = labels.astype(np.int)
# In[66]:
features
# In[67]:
labels
# - Preprocessing is done.
# In[68]:
features_train, features_test, labels_train, labels_test = train_test_split(features, labels, random_state=3, shuffle=True)
# In[73]:
data.corr()
# - Clearly it is a classification problem, we can use DecisionTree or SVC
# In[84]:
# Trying different classifiers.
clf = DecisionTreeClassifier()
clf.fit(features_train, labels_train)
d_tree_score = clf.score(features_test, labels_test) # Good result!
# In[78]:
clf2 = SVC() # Clearly the data is non linear.
clf2.fit(features_train, labels_train)
clf2.score(features_test, labels_test) # Not good!
# In[85]:
clf3 = KNeighborsClassifier(n_neighbors=1)
clf3.fit(features_train, labels_train)
k_score = clf3.score(features_test, labels_test)
# In[86]:
d_tree_score > k_score
# In[87]:
predictions = clf3.predict(features_test)
# In[89]:
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test, predictions)
# In[90]:
cm
# In[91]:
np.where(labels_test!=predictions)
# In[95]:
d_tree_score
# In[94]:
k_score
# In[97]:
from sklearn.metrics import classification_report
c = classification_report(labels_test, predictions)
# In[98]:
c
# In[115]:
from sklearn.ensemble import RandomForestClassifier
r = RandomForestClassifier(n_estimators=100) # With 100 decision tree
r.fit(features_train, labels_train)
r_forest = r.score(features_test, labels_test)
p = r.predict(features_test)
np.where(labels_test!=features_test) # Only one misclassified
# In[116]:
cm = confusion_matrix(labels_test, p)
# In[117]:
cm
| 15.883333 | 207 | 0.726653 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,587 | 0.416317 |
12205785847781fdf91f2f5c239b4afc1705b168 | 566 | py | Python | murel/models/networks/control.py | gokcengokceoglu/murel.bootstrap.pytorch | e3f1cfde377969a872a8f930fbaedf3f814f8fe0 | [
"BSD-3-Clause"
] | 1 | 2019-05-13T17:28:36.000Z | 2019-05-13T17:28:36.000Z | murel/models/networks/control.py | gokcengokceoglu/murel.bootstrap.pytorch | e3f1cfde377969a872a8f930fbaedf3f814f8fe0 | [
"BSD-3-Clause"
] | null | null | null | murel/models/networks/control.py | gokcengokceoglu/murel.bootstrap.pytorch | e3f1cfde377969a872a8f930fbaedf3f814f8fe0 | [
"BSD-3-Clause"
] | null | null | null | import torch.nn as nn
import torch
class ControlModule(nn.Module):
def __init__(self, input_size, hidden_size):
super(ControlModule, self).__init__()
self.rnncell = nn.RNNCell(input_size=input_size, hidden_size=hidden_size, nonlinearity='tanh')
def forward(self, input, hidden):
hidden_next = self.rnncell(input, hidden)
hidden_next_check = torch.isnan(hidden_next)
if hidden_next_check.sum() > 0 :
print("This actually corresponds to c. I don't know why I put this. ")
return hidden_next
| 25.727273 | 102 | 0.680212 | 525 | 0.927562 | 0 | 0 | 0 | 0 | 0 | 0 | 69 | 0.121908 |
1220d274182a0990223702c61d3c21c277645d4a | 452 | py | Python | uim/model/helpers/__init__.py | Wacom-Developer/universal-ink-library | 689ed90e09e912b8fc9ac249984df43a7b59aa59 | [
"Apache-2.0"
] | 5 | 2021-09-06T11:45:37.000Z | 2022-03-24T15:56:06.000Z | uim/model/helpers/__init__.py | Wacom-Developer/universal-ink-library | 689ed90e09e912b8fc9ac249984df43a7b59aa59 | [
"Apache-2.0"
] | null | null | null | uim/model/helpers/__init__.py | Wacom-Developer/universal-ink-library | 689ed90e09e912b8fc9ac249984df43a7b59aa59 | [
"Apache-2.0"
] | 2 | 2021-09-03T09:08:45.000Z | 2021-12-15T14:03:16.000Z | # -*- coding: utf-8 -*-
"""
Helpers
=======
The helpers are simple functions to support with:
- Catmull-Rom splines
- Extracting text and named entities from Ink Model
- Iterate over the Ink Tree
"""
__all__ = ['spline', 'text_extractor', 'treeiterator', 'policy']
from uim.model.helpers import spline
from uim.model.helpers import text_extractor
from uim.model.helpers import treeiterator
from uim.model.helpers import policy
| 25.111111 | 64 | 0.710177 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 267 | 0.590708 |
1221a67d2afbaeaa06f032e92f261758edc08659 | 1,544 | py | Python | matrix_traversal/get_matrix.py | SiberiaMan/Avitotech | 0f17bedd157973ad3f5a3fa748a4892eb1a42204 | [
"MIT"
] | null | null | null | matrix_traversal/get_matrix.py | SiberiaMan/Avitotech | 0f17bedd157973ad3f5a3fa748a4892eb1a42204 | [
"MIT"
] | null | null | null | matrix_traversal/get_matrix.py | SiberiaMan/Avitotech | 0f17bedd157973ad3f5a3fa748a4892eb1a42204 | [
"MIT"
] | null | null | null | import aiohttp
from matrix_traversal.utils import (
traverse_matrix_counterclockwise,
get_formatted_matrix,
check_url)
from typing import List
from aiohttp import ClientError
from asyncio.exceptions import TimeoutError
async def send_request(url: str) -> List[List[int]]:
"""
This function sends a request to URL and processes the response, if any
:param url: URL
:return: formatted matrix if response exists
"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if 400 <= resp.status < 500:
print(f'Client error - {resp.status}')
elif resp.status >= 500:
print(f'Server error - {resp.status}')
else:
matrix = await get_formatted_matrix(resp)
return matrix
except TimeoutError:
print("Timeout error!")
except ClientError:
print("Some problems with connection or URL")
except Exception as e:
print(e)
async def get_matrix(url: str) -> List[int]:
"""
This function gets URL address, sends a request to server
and returns a list obtained by traversing the matrix counterclockwise
:param url: URL
:return: list obtained by traversing the matrix
"""
if check_url(url):
matrix = await send_request(url)
if matrix:
lst = traverse_matrix_counterclockwise(matrix)
return lst
else:
print("Invalid URL address")
| 31.510204 | 75 | 0.626943 | 0 | 0 | 0 | 0 | 0 | 0 | 1,307 | 0.846503 | 512 | 0.331606 |
1222227113bac1587e2d7de9daa11d0c8149596e | 366 | py | Python | wildlifecompliance/migrations/0431_merge_20200218_1801.py | preranaandure/wildlifecompliance | bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5 | [
"Apache-2.0"
] | 1 | 2020-12-07T17:12:40.000Z | 2020-12-07T17:12:40.000Z | wildlifecompliance/migrations/0431_merge_20200218_1801.py | preranaandure/wildlifecompliance | bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5 | [
"Apache-2.0"
] | 14 | 2020-01-08T08:08:26.000Z | 2021-03-19T22:59:46.000Z | wildlifecompliance/migrations/0431_merge_20200218_1801.py | preranaandure/wildlifecompliance | bc19575f7bccf7e19adadbbaf5d3eda1d1aee4b5 | [
"Apache-2.0"
] | 15 | 2020-01-08T08:02:28.000Z | 2021-11-03T06:48:32.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-02-18 10:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0430_briefofevidencedocument'),
('wildlifecompliance', '0427_merge_20200214_1614'),
]
operations = [
]
| 21.529412 | 63 | 0.688525 | 216 | 0.590164 | 0 | 0 | 0 | 0 | 0 | 0 | 167 | 0.456284 |
12228e3b63d5800fdd397f990213ba8df82669bd | 23 | py | Python | python/testData/copyPaste/LineToPrev.after.py | jnthn/intellij-community | 8fa7c8a3ace62400c838e0d5926a7be106aa8557 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | python/testData/copyPaste/LineToPrev.after.py | Cyril-lamirand/intellij-community | 60ab6c61b82fc761dd68363eca7d9d69663cfa39 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | python/testData/copyPaste/LineToPrev.after.py | Cyril-lamirand/intellij-community | 60ab6c61b82fc761dd68363eca7d9d69663cfa39 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | print
print 21
print 3
| 5.75 | 8 | 0.782609 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
12229d09733f5a8668d4db1077a04761f8c6c6e6 | 1,234 | py | Python | pdfencrypter.py | kamimura/pdfendecrypter | 0fc93b8234d7e94cd42267eb05f97ba398f08e1e | [
"MIT"
] | null | null | null | pdfencrypter.py | kamimura/pdfendecrypter | 0fc93b8234d7e94cd42267eb05f97ba398f08e1e | [
"MIT"
] | null | null | null | pdfencrypter.py | kamimura/pdfendecrypter | 0fc93b8234d7e94cd42267eb05f97ba398f08e1e | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import PyPDF2
length = len(sys.argv)
if length >= 2:
PASSWORD = sys.argv[1]
else:
print('usage: cmd password [path]')
sys.exit(1)
if length == 3:
PATH = sys.argv[2]
else:
PATH = os.curdir
for folder_name, _, filenames in os.walk(PATH):
for filename in filenames:
if filename.endswith('.pdf'):
filename = folder_name + os.sep + filename
with open(filename, 'rb') as pdf_file:
try:
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
if not pdf_reader.isEncrypted:
pdf_writer = PyPDF2.PdfFileWriter()
pdf_writer.encrypt(PASSWORD)
for page_num in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
pdf_writer.addPage(page)
with open(filename + '_encrypted.pdf', 'wb') as f:
pdf_writer.write(f)
os.rename(filename + '_encrypted.pdf', filename)
except Exception as err:
print('{0}: {1}'.format(filename, err))
| 32.473684 | 74 | 0.523501 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 129 | 0.104538 |
1223017e27fe3759d3dd4b76699ecf7642b1cb0c | 112 | py | Python | Term2/15-5-square-for-input.py | theseana/apondaone | 7cbf3572a86c73220329804fee1f3d03842ae902 | [
"MIT"
] | null | null | null | Term2/15-5-square-for-input.py | theseana/apondaone | 7cbf3572a86c73220329804fee1f3d03842ae902 | [
"MIT"
] | null | null | null | Term2/15-5-square-for-input.py | theseana/apondaone | 7cbf3572a86c73220329804fee1f3d03842ae902 | [
"MIT"
] | null | null | null | import turtle as t
zel = float(input("What is your Zel: "))
for i in range(4):
t.fd(zel)
t.lt(90)
t.done()
| 14 | 40 | 0.616071 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | 0.178571 |
12233f2f13fb8938280813abd35f4446b1be890a | 691 | py | Python | src/ashley/urls.py | openfun/ashley | 33af6a46bc22c86417c200fdd84876c2c46b02ce | [
"MIT"
] | 6 | 2020-05-05T11:50:29.000Z | 2021-09-19T06:01:39.000Z | src/ashley/urls.py | openfun/ashley | 33af6a46bc22c86417c200fdd84876c2c46b02ce | [
"MIT"
] | 93 | 2020-02-17T16:28:57.000Z | 2022-03-18T14:06:45.000Z | src/ashley/urls.py | openfun/ashley | 33af6a46bc22c86417c200fdd84876c2c46b02ce | [
"MIT"
] | 1 | 2020-03-02T04:36:12.000Z | 2020-03-02T04:36:12.000Z | """
Ashley URLs (that includes django machina urls)
"""
from django.urls import include, path, re_path
from machina import urls as machina_urls
from ashley.api import urls as api_urls
from ashley.views import ChangeUsernameView, ForumLTIView, ManageModeratorsView
API_PREFIX = "v1.0"
urlpatterns = [
path("lti/forum/<uuid:uuid>", ForumLTIView.as_view(), name="forum.lti.view"),
path(
"profile/username",
ChangeUsernameView.as_view(),
name="forum.username.change",
),
path("moderators/", ManageModeratorsView.as_view(), name="moderators"),
re_path(r"api/{}/".format(API_PREFIX), include(api_urls)),
path("forum/", include(machina_urls)),
]
| 28.791667 | 81 | 0.704776 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 184 | 0.266281 |
1225b42f1a8d25d36977830638476dfe2a802c62 | 11,992 | py | Python | schemes/mkcap.py | gold2718/ccpp-framework | 66f1a069b6b15748e08adbe940b8ceb9b39619ab | [
"Apache-2.0"
] | null | null | null | schemes/mkcap.py | gold2718/ccpp-framework | 66f1a069b6b15748e08adbe940b8ceb9b39619ab | [
"Apache-2.0"
] | 39 | 2019-01-25T21:50:33.000Z | 2021-09-03T16:57:43.000Z | schemes/mkcap.py | gold2718/ccpp-framework | 66f1a069b6b15748e08adbe940b8ceb9b39619ab | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#
# Script to generate a cap module and subroutines
# from a scheme xml file.
#
from __future__ import print_function
import os
import sys
import getopt
import xml.etree.ElementTree as ET
#################### Main program routine
def main():
args = parse_args()
data = parse_scheme(args['scheme'])
cap = Cap()
cap.filename = args['output']
cap.write(data)
#################### Parse the command line arguments
def parse_args():
args = {}
opts, rem = getopt.getopt(sys.argv[1:],
'hvo:',
['help',
'verbose',
'output=',
])
for opt, arg in opts:
if opt in ('-h', '--help'):
lusage()
elif opt in ('-v', '--verbose'):
args['verbose'] = True
elif opt in ('-o', '--output'):
args['output'] = arg
else:
usage()
if (not rem):
eprint("Must specify an input scheme file")
usage()
if (os.path.isfile(rem[0])):
args['scheme'] = rem[0]
else:
eprint("Unable to read input scheme file: {0}".format(rem[0]))
usage()
if (not 'output' in args):
args['output'] = sys.stdout
return args
#################### Parse the scheme xml file into a data dictionary
def parse_scheme(filename):
data = {}
tree = ET.parse(filename)
root = tree.getroot()
data['module'] = root.attrib.get('module')
data['subs'] = {}
for sub in root.findall('subroutine'):
name = sub.attrib.get('name')
data['subs'][name] = {}
data['subs'][name]['vars'] = []
for var in sub.findall('var'):
v = Var()
v.standard_name = var.find('standard_name').text
#v.long_name = var.find('long_name').text
v.units = var.find('units').text
v.local_name = var.find('local_name').text
v.type = var.find('type').text
v.rank = int(var.find('rank').text)
data['subs'][name]['vars'].append(v)
return data
#################### Print a usage statement
def usage():
name = os.path.basename(__file__)
eprint("Usage {0}: [-h] [-v] [-o output.f90] scheme.xml".format(name))
sys.exit(1)
#################### Print a long usage statement
def lusage():
pass
#################### Print a message to STDERR
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
###############################################################################
class Var(object):
def __init__(self, **kwargs):
self._standard_name = None
self._long_name = None
self._units = None
self._local_name = None
self._type = None
self._rank = None
self._container = None
for key, value in kwargs.items():
setattr(self, "_"+key, value)
@property
def standard_name(self):
'''Get the name of the variable.'''
return self._standard_name
@standard_name.setter
def standard_name(self, value):
self._standard_name = value
@property
def long_name(self):
'''Get the name of the variable.'''
return self._long_name
@long_name.setter
def long_name(self, value):
self._long_name = value
@property
def units(self):
'''Get the units of the variable.'''
return self._units
@units.setter
def units(self, value):
self._units = value
@property
def local_name(self):
'''Get the local variable name of the variable.'''
return self._local_name
@local_name.setter
def local_name(self, value):
self._local_name = value
@property
def type(self):
'''Get the type of the variable.'''
return self._type
@type.setter
def type(self, value):
self._type = value
@property
def rank(self):
'''Get the rank of the variable.'''
return self._rank
@rank.setter
def rank(self, value):
if not isinstance(value, int):
raise TypeError('Invalid type for variable property rank, must be integer')
if (value == 0):
self._rank = ''
else:
self._rank = '('+ ','.join([':'] * value) +')'
@property
def intent(self):
'''Get the intent of the variable.'''
return self._intent
@intent.setter
def intent(self, value):
if not value in ['none', 'in', 'out', 'inout']:
raise ValueError('Invalid value {0} for variable property intent'.format(value))
self._intent = value
@property
def optional(self):
'''Get the optional of the variable.'''
return self._optional
@optional.setter
def optional(self, value):
if not value in ['T', 'F']:
raise ValueError('Invalid value {0} for variable property optional'.format(value))
self._optional = value
@property
def container(self):
'''Get the container of the variable.'''
return self._container
@container.setter
def container(self, value):
self._container = value
def compatible(self, other):
return self.standard_name == other.standard_name \
and self.long_name == other.long_name \
and self.units == other.units \
and self.type == other.type \
and self.rank == other.rank
def print_def(self):
'''Print the definition line for the variable.'''
str = "{s.type}, pointer :: {s.local_name}{s.rank}"
return str.format(s=self)
def print_get(self):
'''Print the data retrieval line for the variable.'''
str='''
call ccpp_field_get(cdata, '{s.standard_name}', {s.local_name}, ierr)
if (ierr /= 0) then
call ccpp_error('Unable to retrieve {s.standard_name}')
return
end if'''
return str.format(s=self)
def print_debug(self):
'''Print the data retrieval line for the variable.'''
str='''Contents of {s} (* = mandatory for compatibility):
standard_name = {s.standard_name} *
long_name = {s.long_name} *
units = {s.units} *
local_name = {s.local_name}
type = {s.type} *
rank = {s.rank} *
intent = {s.intent}
optional = {s.optional}
container = {s.container}'''
return str.format(s=self)
@classmethod
def from_table(cls, columns, data):
# DH* - workaround to use the existing table headers
standard_name = data[columns.index('longname')]
#standard_name = data[columns.index('standard_name')]
long_name = data[columns.index('description')]
#long_name = data[columns.index('long_name')]
units = data[columns.index('units')]
local_name = data[columns.index('local var name')]
#local_name = data[columns.index('local_name')]
type = data[columns.index('type')]
rank = data[columns.index('rank')]
intent = data[columns.index('intent')]
optional = data[columns.index('optional')]
# *DH
return cls(standard_name = standard_name,
long_name = long_name,
units = units,
local_name = local_name,
type = type,
rank = rank,
intent = intent,
optional = optional,
)
def to_xml(self, element):
element.set('name', self._standard_name)
sub_element = ET.SubElement(element, 'standard_name')
sub_element.text = self._standard_name
sub_element = ET.SubElement(element, 'long_name')
sub_element.text = self._long_name
sub_element = ET.SubElement(element, 'units')
sub_element.text = self._units
sub_element = ET.SubElement(element, 'local_name')
sub_element.text = self._local_name
sub_element = ET.SubElement(element, 'type')
sub_element.text = self._type
sub_element = ET.SubElement(element, 'rank')
sub_element.text = self._rank
sub_element = ET.SubElement(element, 'intent')
sub_element.text = self._intent
sub_element = ET.SubElement(element, 'optional')
sub_element.text = self._optional
sub_element = ET.SubElement(element, 'container')
sub_element.text = self._container
return element
###############################################################################
class Cap(object):
header='''
!
! This work (Common Community Physics Package), identified by NOAA, NCAR,
! CU/CIRES, is free of known copyright restrictions and is placed in the
! public domain.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
! THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
! IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
! CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!
!>
!! @brief Auto-generated cap module for the {module} scheme
!!
!
module {module}_cap
use, intrinsic :: iso_c_binding, &
only: c_f_pointer, c_ptr
use :: ccpp_types, &
only: ccpp_t
use :: ccpp_fields, &
only: ccpp_field_get
use :: ccpp_errors, &
only: ccpp_error
use :: {module}, &
only: {subroutines}
implicit none
private
public :: {subroutine_caps}
contains
'''
sub='''
subroutine {subroutine}_cap(ptr) bind(c)
type(c_ptr), intent(inout) :: ptr
type(ccpp_t), pointer :: cdata
integer :: ierr
{var_defs}
call c_f_pointer(ptr, cdata)
{var_gets}
call {subroutine}({args})
end subroutine {subroutine}_cap
'''
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, "_"+key, value)
def write(self, data):
if (self.filename is not sys.stdout):
f = open(self.filename, 'w')
else:
f = sys.stdout
subs = ','.join(["{0}".format(s) for s in data['subs']])
sub_caps = ','.join(["{0}_cap".format(s) for s in data['subs']])
f.write(Cap.header.format(module = data['module'],
subroutines = subs,
subroutine_caps = sub_caps))
for (k, v) in data['subs'].items():
var_defs = "\n".join([" "*8 + x.print_def() for x in v['vars']])
var_gets = "\n".join([x.print_get() for x in v['vars']])
args = ','.join(["{0}={0}".format(x.local_name) for x in v['vars']])
f.write(Cap.sub.format(subroutine=k,
var_defs=var_defs,
var_gets=var_gets,
args=args))
f.write("end module {module}_cap\n".format(module = data['module']))
if (f is not sys.stdout):
f.close()
@property
def filename(self):
'''Get the filename of write the output to.'''
return self._filename
@filename.setter
def filename(self, value):
self._filename = value
###############################################################################
if __name__ == "__main__":
main()
| 30.827763 | 94 | 0.532688 | 9,136 | 0.761841 | 0 | 0 | 3,403 | 0.283773 | 0 | 0 | 4,615 | 0.38484 |
122659abc409041390c5c76b00e76f1745c0df5d | 2,457 | py | Python | setup.py | CertiFire/certifire | 722da20bade41b8cc8553177e70e1f56015fe335 | [
"MIT"
] | null | null | null | setup.py | CertiFire/certifire | 722da20bade41b8cc8553177e70e1f56015fe335 | [
"MIT"
] | null | null | null | setup.py | CertiFire/certifire | 722da20bade41b8cc8553177e70e1f56015fe335 | [
"MIT"
] | 1 | 2021-02-06T03:29:56.000Z | 2021-02-06T03:29:56.000Z | #!/usr/bin/env python
import certifire
import certifire.plugins.acme
import certifire.plugins.dns_providers
from codecs import open
from setuptools import setup, find_packages
import sys
try:
# for pip >= 10
from pip._internal.req import parse_requirements
except ImportError:
# for pip <= 9.0.3
print("error: Upgrade to a pip version newer than 10. Run \"pip install "
"--upgrade pip\".")
sys.exit(1)
with open("README.md", "r") as fh:
long_description = fh.read()
# Solution from http://bit.ly/29Yl8VN
def resolve_requires(requirements_file):
try:
requirements = parse_requirements("./%s" % requirements_file,
session=False)
return [str(ir.req) for ir in requirements]
except AttributeError:
# for pip >= 20.1.x
# Need to run again as the first run was ruined by the exception
requirements = parse_requirements("./%s" % requirements_file,
session=False)
# pr stands for parsed_requirement
return [str(pr.requirement) for pr in requirements]
setup(
name="certifire",
version=certifire.get_version(),
license=certifire.__licence__,
description=("Certifire Minimal - Automate Certificates from let'sencrypt"),
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/certi-fire/certifire",
author=certifire.get_author(),
author_email=certifire.get_author_email(),
classifiers=[
"Development Status :: 1 - Alpha",
"License :: OSI Approved :: Apache Software License",
"Environment :: Console",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
packages=find_packages(),
install_requires=resolve_requires("requirements.txt"),
entry_points={
'console_scripts': [
"certifire = certifire.cli:certifire_main",
"certifire-manager = certifire.manage:main",
],
},
)
| 34.125 | 80 | 0.635328 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,062 | 0.432234 |
12274afee7b6bda951b1ffa4cfd48248c01b1033 | 2,687 | py | Python | kanka/utils.py | rbtnx/python-kanka | 74e75243094816a5d0ddc33575951749a090c673 | [
"MIT"
] | 3 | 2020-07-26T22:05:06.000Z | 2021-09-14T12:58:45.000Z | kanka/utils.py | rbtnx/python-kanka | 74e75243094816a5d0ddc33575951749a090c673 | [
"MIT"
] | 3 | 2021-09-13T21:08:12.000Z | 2021-09-18T15:00:58.000Z | kanka/utils.py | rbtnx/python-kanka | 74e75243094816a5d0ddc33575951749a090c673 | [
"MIT"
] | 2 | 2021-09-14T22:27:21.000Z | 2022-01-07T01:35:45.000Z | """
:mod: `kanka.utils` - Helper functions
"""
from datetime import datetime
from requests_toolbelt.sessions import BaseUrlSession
from dacite import from_dict, Config
from .exceptions import KankaAPIError
API_BASE_ENDPOINT = 'https://kanka.io/api/1.0/'
class KankaSession(BaseUrlSession):
""" Store session data.
For every API request a header with the API token has to be provided.
This object stores the token and the header and provides methods for
GET, POST and UPDATE requests with the needed header. Also this object
can be handed down from the KankaClient object to entitiy objects in case
they need to make API requests.
:param api_endpoint: Base endpoint to the kanka API. Default: API_BASE_ENDPOINT
:param api_token: kanka API token. Default: empty string
:type api_endpoint: string
:type api_token: string
"""
def __init__(self, api_endpoint=API_BASE_ENDPOINT, api_token=''):
self.base_url = api_endpoint
self.token = api_token
auth_header = {
'Authorization': f'Bearer {self.token}',
'Accept': 'application/json'}
super().__init__()
self.headers.update(auth_header)
def api_request(self, endpoint=''):
"""
Requests data from given API endpoint.
:return: json data from given endpoint
:rtype: dict
"""
r = self.get(endpoint)
if r.status_code == 401:
raise KankaAPIError("Authentication error. Wrong token or no token given.")
if r.status_code == 404:
raise KankaAPIError(
"Page not found. Request from a non-existent endpoint: {}.".format(r.url))
return r.json()
def __repr__(self):
return "Kanka Session to {}".format(self.base_url)
def to_datetime(dict_date):
""" Convert json date entry to datetime.
:param dict_date: Date as retrieved from kanka in the format "YYYY-mm-dd HH:MM:SS.000000"
:type dict_date: string
:return: Date converted to python datetime object
:rtype: datetime.datetime
"""
t = dict_date.split(".")[0]
return datetime.strptime(t, "%Y-%m-%dT%H:%M:%S")
def append_from(session, data, page):
""" Collect paginated data."""
r = session.api_request(page)
url_next = r["links"]["next"]
if url_next:
append_from(session, data, url_next[len(session.base_url):])
data.extend(r["data"])
return data
def create_entity(Entity_object, data):
""" Creates entitiy objects from dictionary. """
entity = from_dict(
data_class=Entity_object,
data=data,
config=Config(type_hooks={datetime: to_datetime}))
return entity
| 33.5875 | 93 | 0.66431 | 1,537 | 0.572013 | 0 | 0 | 0 | 0 | 0 | 0 | 1,349 | 0.502047 |
12276b102b462739e46f7a9646d34ec66d31bbd9 | 3,599 | py | Python | day2/exercises/Jamila/pi_estimate/plots.py | lavjams/BI-Demo | 2ff4aeb9dc71eeb1aa9e1f6510a79994c6c20ef1 | [
"MIT"
] | null | null | null | day2/exercises/Jamila/pi_estimate/plots.py | lavjams/BI-Demo | 2ff4aeb9dc71eeb1aa9e1f6510a79994c6c20ef1 | [
"MIT"
] | null | null | null | day2/exercises/Jamila/pi_estimate/plots.py | lavjams/BI-Demo | 2ff4aeb9dc71eeb1aa9e1f6510a79994c6c20ef1 | [
"MIT"
] | null | null | null | ######
###BACKGROUND
#Below Section: Imports necessary functions
import numpy as np
import matplotlib.pyplot as graph
import random as rand
import time as watch
import sims
pi = np.pi
######
###PLOTS
#FUNCTION: drawdarts
#PURPOSE: This function is meant to draw the darts for a given simulation within the unit square.
#INPUTS: X- and Y- locations of the simulated darts
def drawdarts(x, y):
#Below Section: Scatters the simulated darts
graph.scatter(x, y, color='blue', alpha=.4)
#Below Section: Plots a circle as a guideline to show boundaries of unit circle
xcircle = np.linspace(0, 1, 1000)
ycircle = np.sqrt(1 - xcircle**2)
graph.plot(xcircle, ycircle, color='purple', alpha=.6, linestyle='--', linewidth=3)
graph.title('Visual Dart Simulation: '+str(len(x))+' Darts')
graph.xlabel('(Darts Depicted in Blue, Target Outline in Purple)')
graph.xlim([0,1])
graph.ylim([0,1])
#graph.savefig('EstPiDraw-'+str(len(x))+'Darts')
graph.show()
graph.close()
#FUNCTION: histdarts
#PURPOSE: This function is meant to plot a histogram of the estimated pi value of several dart simulations.
#INPUTS: Number of histogram points; number of darts per simulation
def histdarts(numdarts, numsims):
#Below Section: Generates several simulations of given number of darts each
estpis = np.zeros(numsims)
for c in range(0, numsims):
estpis[c] = sims.simdarts(num=numdarts)['estpi']
#Below Section: Graphs results in histogram
meanstring = 'Mean: {:.4f}, '.format(np.mean(estpis))
stdstring = 'St. Dev: {:.4f}'.format(np.std(estpis))
graph.hist(estpis, histtype='step', alpha=.6, bins=50)
graph.title('Histogram of Pi Estimations: '+str(numdarts)+' Darts Each')
graph.suptitle(meanstring+stdstring)
graph.xlabel('Estimated Pi Values')
graph.ylabel('Frequencies')
#graph.savefig('EstPiHist-'+numdarts'Darts-'+numsims+'Sims')
graph.show()
graph.close()
#FUNCTION: plottime
#PURPOSE: This function is meant to plot the dependence of time upon the number of darts.
#INPUTS: An array containing the number of darts for each simulation
def plottime(numdartsarray):
#Below Section: Times the dart simulation for each number of darts given
simtimes = np.zeros(len(numdartsarray))
for d in range(0, len(numdartsarray)):
starthere = watch.time() #Start time
simhere = sims.simdarts(num=numdartsarray[d]) #Simulation
endhere = watch.time() #End time
#Below records time taken for current simulation
simtimes[d] = endhere - starthere
#Below Section: Plots the time taken
graph.plot(numdartsarray, simtimes, alpha=.8, color='purple', linewidth=3)
graph.title('Time Dependence of the Number of Darts (s)')
graph.xlabel('Number of Darts')
graph.ylabel('Time Taken by Simulation (s)')
graph.show()
graph.close()
#FUNCTION: plotacc
#PURPOSE: This function is meant to plot the dependence of accuracy upon the number of darts.
#INPUT: An array containing number of darts for each simulation
def plotacc(numdartsarray):
#Below Section: Determines accuracy for each number of darts given
simacc = np.zeros(len(numdartsarray))
for e in range(0, len(numdartsarray)):
esthere = sims.simdarts(num=numdartsarray[e])['estpi']
#Below calculates and records current accuracy
simacc[e] = abs(esthere - pi)
#Below Section: Graphs the accuracy of pi estimations
graph.plot(numdartsarray, np.log10(simacc), alpha=.8, color='orange', linewidth=3)
graph.title('Log10(Estimation Accuracy) by the Number of Darts')
graph.xlabel('Number of Darts')
graph.ylabel('Log10(Distance of Pi Estimation from Actual Value)')
graph.show()
graph.close()
| 33.635514 | 107 | 0.734371 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,951 | 0.542095 |
122a8bcfb8def21ca6542908e7ec0138c02aea09 | 1,803 | py | Python | scripts/animate_demo.py | wjchen84/rapprentice | 9232a6a21e2c80f00854912f07dcdc725b0be95a | [
"BSD-2-Clause"
] | 23 | 2015-08-25T19:40:18.000Z | 2020-12-27T09:23:06.000Z | scripts/animate_demo.py | wjchen84/rapprentice | 9232a6a21e2c80f00854912f07dcdc725b0be95a | [
"BSD-2-Clause"
] | null | null | null | scripts/animate_demo.py | wjchen84/rapprentice | 9232a6a21e2c80f00854912f07dcdc725b0be95a | [
"BSD-2-Clause"
] | 8 | 2016-05-18T20:13:06.000Z | 2020-11-03T16:09:50.000Z | #!/usr/bin/env python
"""
Animate demonstration trajectory
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("h5file")
parser.add_argument("--seg")
parser.add_argument("--nopause", action="store_true")
args = parser.parse_args()
import h5py, openravepy,trajoptpy
from rapprentice import animate_traj, ros2rave,clouds
from numpy import asarray
import numpy as np
hdf = h5py.File(args.h5file)
segnames = [args.seg] if args.seg else hdf.keys()
env = openravepy.Environment()
env.StopSimulation()
env.Load("robots/pr2-beta-static.zae")
robot = env.GetRobots()[0]
viewer = trajoptpy.GetViewer(env)
for segname in segnames:
seg_info = hdf[segname]
from rapprentice import berkeley_pr2
r2r = ros2rave.RosToRave(robot, seg_info["joint_states"]["name"])
rave_traj = [r2r.convert(row) for row in asarray(seg_info["joint_states"]["position"])]
robot.SetActiveDOFs(r2r.rave_inds)
robot.SetActiveDOFValues(rave_traj[0])
handles = []
T_w_k = berkeley_pr2.get_kinect_transform(robot)
o = T_w_k[:3,3]
x = T_w_k[:3,0]
y = T_w_k[:3,1]
z = T_w_k[:3,2]
handles.append(env.drawarrow(o, o+.3*x, .005,(1,0,0,1)))
handles.append(env.drawarrow(o, o+.3*y, .005,(0,1,0,1)))
handles.append(env.drawarrow(o, o+.3*z, .005,(0,0,1,1)))
XYZ_k = clouds.depth_to_xyz(np.asarray(seg_info["depth"]), berkeley_pr2.f)
Twk = asarray(seg_info["T_w_k"])
XYZ_w = XYZ_k.dot(Twk[:3,:3].T) + Twk[:3,3][None,None,:]
RGB = np.asarray(seg_info["rgb"])
handles.append(env.plot3(XYZ_w.reshape(-1,3), 2, RGB.reshape(-1,3)[:,::-1]/255.))
animate_traj.animate_traj(rave_traj, robot, pause = not args.nopause)
print "DONE"
trajoptpy.GetViewer(env).Idle()
| 24.04 | 91 | 0.661675 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 196 | 0.108708 |
122ae92db8c0fba7f33754fcbab35f9e25571cce | 1,032 | py | Python | rsp2/src/python/rsp2/io/structure_dir.py | colin-daniels/agnr-ml | fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8 | [
"MIT"
] | null | null | null | rsp2/src/python/rsp2/io/structure_dir.py | colin-daniels/agnr-ml | fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8 | [
"MIT"
] | null | null | null | rsp2/src/python/rsp2/io/structure_dir.py | colin-daniels/agnr-ml | fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8 | [
"MIT"
] | null | null | null | import json
import os
from pymatgen.io.vasp import Poscar
def from_path(path):
# TODO: should maybe support .tar.gz or .tar.xz
return StructureDir.from_dir(path)
class StructureDir:
def __init__(self, *, layers, masses, layer_sc_matrices, structure):
self.layers = layers
self.masses = masses
self.layer_sc_matrices = layer_sc_matrices
self.structure = structure
@classmethod
def from_dir(cls, path):
structure = Poscar.from_file(os.path.join(path, 'POSCAR')).structure
with open(os.path.join(path, 'meta.json')) as f:
meta = json.load(f)
layer_sc_matrices = meta.pop('layer_sc_matrices', None) or meta.pop('layer-sc-matrices', None)
if layer_sc_matrices:
layer_sc_matrices = [x['matrix'] for x in layer_sc_matrices]
return cls(
layers=meta.pop('layers', None),
masses=meta.pop('masses', None),
layer_sc_matrices=layer_sc_matrices,
structure=structure,
)
| 32.25 | 102 | 0.643411 | 859 | 0.832364 | 0 | 0 | 617 | 0.597868 | 0 | 0 | 128 | 0.124031 |
122bf0e224108c95adcbb96cb64e305c57af3a8b | 891 | py | Python | scripts/generate_mapping_summary.py | BleekerLab/snakemake_rnaseq | 1b9db81ca82a3f3df5978c87f8ef76bfea00f584 | [
"MIT"
] | 4 | 2020-06-26T08:59:07.000Z | 2022-02-02T15:24:25.000Z | scripts/generate_mapping_summary.py | BleekerLab/snakemake_rnaseq | 1b9db81ca82a3f3df5978c87f8ef76bfea00f584 | [
"MIT"
] | 11 | 2020-07-28T07:40:26.000Z | 2021-08-05T07:52:00.000Z | scripts/generate_mapping_summary.py | BleekerLab/snakemake_rnaseq | 1b9db81ca82a3f3df5978c87f8ef76bfea00f584 | [
"MIT"
] | 3 | 2020-10-30T14:09:19.000Z | 2022-02-02T15:16:41.000Z | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import os
from functools import reduce
import sys
directory_with_mapping_reports = sys.argv[1]
mapping_summary = sys.argv[2]
############################################################
# Reads each file. Add sample name in the column with values
############################################################
list_of_logs = [directory_with_mapping_reports + f for f in os.listdir(directory_with_mapping_reports) if f.endswith("Log.final.out")]
list_of_logs.sort()
sample_names = [log.replace("_Log.final.out","") for log in list_of_logs]
list_of_dfs = [pd.read_csv(log, sep = "\t", names=["attribute", str(sample)])
for log,sample in zip(list_of_logs, sample_names)
]
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['attribute'], how='outer'), list_of_dfs)
df_merged.to_csv(mapping_summary, sep=",")
| 24.75 | 134 | 0.641975 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 285 | 0.319865 |
122e92d89d689afb07f2870e5616b184ec228c74 | 74 | py | Python | Chapter2_Python/fStrings.py | dependencyInversion/UdemyML | 9e1a0a01688a82c61ef006a592a58c12fb186552 | [
"MIT"
] | null | null | null | Chapter2_Python/fStrings.py | dependencyInversion/UdemyML | 9e1a0a01688a82c61ef006a592a58c12fb186552 | [
"MIT"
] | null | null | null | Chapter2_Python/fStrings.py | dependencyInversion/UdemyML | 9e1a0a01688a82c61ef006a592a58c12fb186552 | [
"MIT"
] | null | null | null | my_name = "Jan"
my_age = 23
print(f"Age: { my_age }, Name: { my_name }")
| 14.8 | 44 | 0.594595 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 42 | 0.567568 |
122f641d2932f57d9055b11d54666d81eb9d402f | 1,140 | py | Python | src/models/predict_text_model.py | eyosyaswd/disaster-response | 836f40119e0795d35747c0fd3f975e7a13e46258 | [
"RSA-MD"
] | null | null | null | src/models/predict_text_model.py | eyosyaswd/disaster-response | 836f40119e0795d35747c0fd3f975e7a13e46258 | [
"RSA-MD"
] | null | null | null | src/models/predict_text_model.py | eyosyaswd/disaster-response | 836f40119e0795d35747c0fd3f975e7a13e46258 | [
"RSA-MD"
] | null | null | null | from ast import literal_eval
from performance_metrics import get_performance_metrics
from tensorflow.keras.models import load_model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # Ignore tf info messages
import pandas as pd
if __name__ == "__main__":
TASK = "humanitarian"
print("\nLoading in testing data...")
# Read in testing data
test_filepath = f"../../data/interim/task_{TASK}_test_preprocessed_text.csv"
test_df = pd.read_csv(test_filepath)
# Extract data and labels from dataset
test_X = list(test_df["padded_sequence"].apply(literal_eval))
test_y = list(test_df["onehot_label"].apply(literal_eval))
print("\nLoading in trained model...")
# Load in trained model
trained_model = load_model(f"../../models/text/{TASK}/{TASK}.hdf5")
print(trained_model.summary())
print("\nPredicting testing data...")
# Predict testing data using trained model
pred_y = trained_model.predict(test_X, batch_size=128)
print("\nGetting performance metrics...")
# Get performance metrics
get_performance_metrics(test_y, pred_y, test_df, TASK, "text")
| 29.230769 | 80 | 0.710526 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 486 | 0.426316 |
122fc0c14857deefada9ab37db5cbbaade40f9f1 | 9,795 | py | Python | pygsti/tools/lindbladtools.py | pyGSTi-Developers/pyGSTi | bfedc1de4d604f14b0f958615776fb80ddb59e33 | [
"Apache-2.0"
] | null | null | null | pygsti/tools/lindbladtools.py | pyGSTi-Developers/pyGSTi | bfedc1de4d604f14b0f958615776fb80ddb59e33 | [
"Apache-2.0"
] | null | null | null | pygsti/tools/lindbladtools.py | pyGSTi-Developers/pyGSTi | bfedc1de4d604f14b0f958615776fb80ddb59e33 | [
"Apache-2.0"
] | null | null | null | """
Utility functions relevant to Lindblad forms and projections
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import numpy as _np
import scipy.sparse as _sps
from pygsti.tools import matrixtools as _mt
from pygsti.tools.basistools import basis_matrices
def create_elementary_errorgen_dual(typ, p, q=None, sparse=False, normalization_factor='auto'):
"""
Construct a "dual" elementary error generator matrix in the "standard" (matrix-unit) basis.
The elementary error generator that is dual to the one computed by calling
:function:`create_elementary_errorgen` with the same argument. This dual element
can be used to find the coefficient of the original, or "primal" elementary generator.
For example, if `A = sum(c_i * E_i)`, where `E_i` are the elementary error generators given
by :function:`create_elementary_errorgen`), then `c_i = dot(D_i.conj(), A)` where `D_i`
is the dual to `E_i`.
There are four different types of dual elementary error generators: 'H' (Hamiltonian),
'S' (stochastic), 'C' (correlation), and 'A' (active). See arxiv:2103.01928.
Each type transforms an input density matrix differently. The action of an elementary
error generator `L` on an input density matrix `rho` is given by:
Hamiltonian: `L(rho) = -1j/(2d^2) * [ p, rho ]`
Stochastic: `L(rho) = 1/(d^2) p * rho * p
Correlation: `L(rho) = 1/(2d^2) ( p * rho * q + q * rho * p)
Active: `L(rho) = 1j/(2d^2) ( p * rho * q - q * rho * p)
where `d` is the dimension of the Hilbert space, e.g. 2 for a single qubit. Square
brackets denotes the commutator and curly brackets the anticommutator.
`L` is returned as a superoperator matrix that acts on vectorized density matrices.
Parameters
----------
typ : {'H','S','C','A'}
The type of dual error generator to construct.
p : numpy.ndarray
d-dimensional basis matrix.
q : numpy.ndarray, optional
d-dimensional basis matrix; must be non-None if and only if `typ` is `'C'` or `'A'`.
sparse : bool, optional
Whether to construct a sparse or dense (the default) matrix.
Returns
-------
ndarray or Scipy CSR matrix
"""
d = p.shape[0]; d2 = d**2
pdag = p.T.conjugate()
qdag = q.T.conjugate() if (q is not None) else None
if sparse:
elem_errgen = _sps.lil_matrix((d2, d2), dtype=p.dtype)
else:
elem_errgen = _np.empty((d2, d2), dtype=p.dtype)
assert(typ in ('H', 'S', 'C', 'A')), "`typ` must be one of 'H', 'S', 'C', or 'A'"
assert((typ in 'HS' and q is None) or (typ in 'CA' and q is not None)), \
"Wrong number of basis elements provided for %s-type elementary errorgen!" % typ
# Loop through the standard basis as all possible input density matrices
for i, rho0 in enumerate(basis_matrices('std', d2)): # rho0 == input density mx
# Only difference between H/S/C/A is how they transform input density matrices
if typ == 'H':
rho1 = -1j * (p @ rho0 - rho0 @ p) # -1j / (2 * d2) *
elif typ == 'S':
rho1 = (p @ rho0 @ pdag) # 1 / d2 *
elif typ == 'C':
rho1 = (p @ rho0 @ qdag + q @ rho0 @ pdag) # 1 / (2 * d2) *
elif typ == 'A':
rho1 = 1j * (p @ rho0 @ qdag - q @ rho0 @ pdag) # 1j / (2 * d2)
elem_errgen[:, i] = rho1.flatten()[:, None] if sparse else rho1.flatten()
return_normalization = bool(normalization_factor == 'auto_return')
if normalization_factor in ('auto', 'auto_return'):
primal = create_elementary_errorgen(typ, p, q, sparse)
if sparse:
normalization_factor = _np.vdot(elem_errgen.toarray().flatten(), primal.toarray().flatten())
else:
normalization_factor = _np.vdot(elem_errgen.flatten(), primal.flatten())
elem_errgen *= _np.asscalar(_np.real_if_close(1 / normalization_factor))
if sparse: elem_errgen = elem_errgen.tocsr()
return (elem_errgen, normalization_factor) if return_normalization else elem_errgen
def create_elementary_errorgen(typ, p, q=None, sparse=False):
"""
Construct an elementary error generator as a matrix in the "standard" (matrix-unit) basis.
There are four different types of elementary error generators: 'H' (Hamiltonian),
'S' (stochastic), 'C' (correlation), and 'A' (active). See arxiv:2103.01928.
Each type transforms an input density matrix differently. The action of an elementary
error generator `L` on an input density matrix `rho` is given by:
Hamiltonian: `L(rho) = -1j * [ p, rho ]`
Stochastic: `L(rho) = p * rho * p - rho
Correlation: `L(rho) = p * rho * q + q * rho * p - 0.5 {{p,q}, rho}
Active: `L(rho) = 1j( p * rho * q - q * rho * p + 0.5 {[p,q], rho} )
Square brackets denotes the commutator and curly brackets the anticommutator.
`L` is returned as a superoperator matrix that acts on vectorized density matrices.
Parameters
----------
typ : {'H','S','C','A'}
The type of error generator to construct.
p : numpy.ndarray
d-dimensional basis matrix.
q : numpy.ndarray, optional
d-dimensional basis matrix; must be non-None if and only if `typ` is `'C'` or `'A'`.
sparse : bool, optional
Whether to construct a sparse or dense (the default) matrix.
Returns
-------
ndarray or Scipy CSR matrix
"""
d = p.shape[0]; d2 = d**2
if sparse:
elem_errgen = _sps.lil_matrix((d2, d2), dtype=p.dtype)
else:
elem_errgen = _np.empty((d2, d2), dtype=p.dtype)
assert(typ in ('H', 'S', 'C', 'A')), "`typ` must be one of 'H', 'S', 'C', or 'A'"
assert((typ in 'HS' and q is None) or (typ in 'CA' and q is not None)), \
"Wrong number of basis elements provided for %s-type elementary errorgen!" % typ
pdag = p.T.conjugate()
qdag = q.T.conjugate() if (q is not None) else None
if typ in 'CA':
pq_plus_qp = pdag @ q + qdag @ p
pq_minus_qp = pdag @ q - qdag @ p
# Loop through the standard basis as all possible input density matrices
for i, rho0 in enumerate(basis_matrices('std', d2)): # rho0 == input density mx
# Only difference between H/S/C/A is how they transform input density matrices
if typ == 'H':
rho1 = -1j * (p @ rho0 - rho0 @ p) # Add "/2" to have PP ham gens match previous versions of pyGSTi
elif typ == 'S':
pdag_p = (pdag @ p)
rho1 = p @ rho0 @ pdag - 0.5 * (pdag_p @ rho0 + rho0 @ pdag_p)
elif typ == 'C':
rho1 = p @ rho0 @ qdag + q @ rho0 @ pdag - 0.5 * (pq_plus_qp @ rho0 + rho0 @ pq_plus_qp)
elif typ == 'A':
rho1 = 1j * (p @ rho0 @ qdag - q @ rho0 @ pdag + 0.5 * (pq_minus_qp @ rho0 + rho0 @ pq_minus_qp))
elem_errgen[:, i] = rho1.flatten()[:, None] if sparse else rho1.flatten()
if sparse: elem_errgen = elem_errgen.tocsr()
return elem_errgen
def create_lindbladian_term_errorgen(typ, Lm, Ln=None, sparse=False): # noqa N803
"""
Construct the superoperator for a term in the common Lindbladian expansion of an error generator.
Mathematically, for d-dimensional matrices Lm and Ln, this routine
constructs the d^2-dimension Lindbladian matrix L whose action is
given by:
L(rho) = -i [Lm, rho] (when `typ == 'H'`)
or
L(rho) = Ln*rho*Lm^dag - 1/2(rho*Lm^dag*Ln + Lm^dag*Ln*rho) (`typ == 'O'`)
where rho is a density matrix. L is returned as a superoperator
matrix that acts on a vectorized density matrices.
Parameters
----------
typ : {'H', 'O'}
The type of error generator to construct.
Lm : numpy.ndarray
d-dimensional basis matrix.
Ln : numpy.ndarray, optional
d-dimensional basis matrix.
sparse : bool, optional
Whether to construct a sparse or dense (the default) matrix.
Returns
-------
ndarray or Scipy CSR matrix
"""
d = Lm.shape[0]; d2 = d**2
if sparse:
lind_errgen = _sps.lil_matrix((d2, d2), dtype=Lm.dtype)
else:
lind_errgen = _np.empty((d2, d2), dtype=Lm.dtype)
assert(typ in ('H', 'O')), "`typ` must be one of 'H' or 'O'"
assert((typ in 'H' and Ln is None) or (typ in 'O' and Ln is not None)), \
"Wrong number of basis elements provided for %s-type lindblad term errorgen!" % typ
if typ in 'O':
Lm_dag = _np.conjugate(_np.transpose(Lm))
Lmdag_Ln = Lm_dag @ Ln
# Loop through the standard basis as all possible input density matrices
for i, rho0 in enumerate(basis_matrices('std', d2)): # rho0 == input density mx
# Only difference between H/S/C/A is how they transform input density matrices
if typ == 'H':
rho1 = -1j * (Lm @ rho0 - rho0 @ Lm)
elif typ == 'O':
rho1 = Ln @ rho0 @ Lm_dag - 0.5 * (Lmdag_Ln @ rho0 + rho0 @ Lmdag_Ln)
else: raise ValueError("Invalid lindblad term errogen type!")
lind_errgen[:, i] = rho1.flatten()[:, None] if sparse else rho1.flatten()
if sparse: lind_errgen = lind_errgen.tocsr()
return lind_errgen
| 42.038627 | 112 | 0.611434 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6,008 | 0.613374 |
1230448ffec588d42b768d0919ac0104f451a382 | 1,490 | py | Python | quality_dataset.py | Phoenix-Chen/butterflies | 06abf393c69f7a7c54d4e8a8775de81de7908285 | [
"MIT"
] | 45 | 2019-12-26T10:36:47.000Z | 2022-03-30T12:17:45.000Z | quality_dataset.py | Phoenix-Chen/butterflies | 06abf393c69f7a7c54d4e8a8775de81de7908285 | [
"MIT"
] | 1 | 2022-02-04T02:54:05.000Z | 2022-02-04T02:54:05.000Z | quality_dataset.py | Phoenix-Chen/butterflies | 06abf393c69f7a7c54d4e8a8775de81de7908285 | [
"MIT"
] | 8 | 2019-12-27T08:51:40.000Z | 2022-02-04T01:29:23.000Z | import torch
from torch.utils.data import Dataset
import numpy as np
import csv
import random
from config import *
import itertools
import torch
from skimage import io
import os
class QualityDataset(Dataset):
def __init__(self, return_hashes=False):
self.label_count = 3
file = open(QUALITY_DATA_FILENAME, 'r')
reader = csv.reader(file)
self.ids_by_label = [[] for i in range(self.label_count)]
for row in reader:
label = int(row[1])
id = row[0]
if os.path.isfile('data/images_rotated_128/{:s}.jpg'.format(id)):
self.ids_by_label[label].append(id)
print('Items in quality ground truth dataset:', [len(x) for x in self.ids_by_label])
self.shuffle()
def shuffle(self):
size = min(len(i) for i in self.ids_by_label)
ids = list(itertools.chain(*[random.sample(population, size) for population in self.ids_by_label]))
indices = list(range(size * self.label_count))
random.shuffle(indices)
self.ids = [ids[i] for i in indices]
self.labels = [i // size for i in indices]
def __len__(self):
return len(self.ids)
def __getitem__(self, index):
image = io.imread('data/images_rotated_128/{:s}.jpg'.format(self.ids[index]))
image = image.transpose((2, 0, 1)).astype(np.float32) / 255
image = torch.from_numpy(image)
return image, self.labels[index], self.ids[index] | 32.391304 | 107 | 0.631544 | 1,311 | 0.879866 | 0 | 0 | 0 | 0 | 0 | 0 | 111 | 0.074497 |
12313e062dbc6cb84fe76bc3653621f0ba161998 | 40 | py | Python | tests/components/geofency/__init__.py | domwillcode/home-assistant | f170c80bea70c939c098b5c88320a1c789858958 | [
"Apache-2.0"
] | 30,023 | 2016-04-13T10:17:53.000Z | 2020-03-02T12:56:31.000Z | tests/components/geofency/__init__.py | jagadeeshvenkatesh/core | 1bd982668449815fee2105478569f8e4b5670add | [
"Apache-2.0"
] | 31,101 | 2020-03-02T13:00:16.000Z | 2022-03-31T23:57:36.000Z | tests/components/geofency/__init__.py | jagadeeshvenkatesh/core | 1bd982668449815fee2105478569f8e4b5670add | [
"Apache-2.0"
] | 11,956 | 2016-04-13T18:42:31.000Z | 2020-03-02T09:32:12.000Z | """Tests for the Geofency component."""
| 20 | 39 | 0.7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 39 | 0.975 |
12329373ceaaf62c2595b60a93477f6c3c56faed | 5,564 | py | Python | examples/nn_opt.py | jjakimoto/BBoptimizer | fcc58393905ee72184ad3759ea444bc52b9a3a2d | [
"MIT"
] | 1 | 2019-01-28T00:16:55.000Z | 2019-01-28T00:16:55.000Z | examples/nn_opt.py | jjakimoto/BBoptimizer | fcc58393905ee72184ad3759ea444bc52b9a3a2d | [
"MIT"
] | null | null | null | examples/nn_opt.py | jjakimoto/BBoptimizer | fcc58393905ee72184ad3759ea444bc52b9a3a2d | [
"MIT"
] | 1 | 2019-11-05T00:56:12.000Z | 2019-11-05T00:56:12.000Z | from sklearn.preprocessing import OneHotEncoder
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, BatchNormalization, Dropout
from keras.layers import Activation, Reshape
from keras.optimizers import Adam, Adadelta, SGD, RMSprop
from keras.regularizers import l2
import matplotlib.pyplot as plt
from bboptimizer import Optimizer
# Fetch MNIST dataset
mnist = tf.contrib.learn.datasets.load_dataset("mnist")
train = mnist.train
X = train.images
train_X = X
train_y = np.expand_dims(train.labels, -1)
train_y = OneHotEncoder().fit_transform(train_y)
valid = mnist.validation
X = valid.images
valid_X = X
valid_y = np.expand_dims(valid.labels, -1)
valid_y = OneHotEncoder().fit_transform(valid_y)
def get_optimzier(name, **kwargs):
if name == "rmsprop":
return RMSprop(**kwargs)
elif name == "adam":
return Adam(**kwargs)
elif name == "sgd":
return SGD(**kwargs)
elif name == "adadelta":
return Adadelta(**kwargs)
else:
raise ValueError(name)
def construct_NN(params):
model = Sequential()
model.add(Reshape((784,), input_shape=(784,)))
def update_model(_model, _params, name):
_model.add(Dropout(_params[name + "_drop_rate"]))
_model.add(Dense(units=_params[name + "_num_units"],
activation=None,
kernel_regularizer=l2(_params[name + "_w_reg"])))
if _params[name + "_is_batch"]:
_model.add(BatchNormalization())
if _params[name + "_activation"] is not None:
_model.add(Activation(_params[name + "_activation"]))
return _model
# Add input layer
model = update_model(model, params, "input")
# Add hidden layer
for i in range(params["num_hidden_layers"]):
model = update_model(model, params, "hidden")
# Add output layer
model = update_model(model, params, "output")
optimizer = get_optimzier(params["optimizer"],
lr=params["learning_rate"])
model.compile(optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
return model
def score_func(params):
# print("parameters", params)
model = construct_NN(params)
model.fit(train_X, train_y,
epochs=params["epochs"],
batch_size=params["batch_size"], verbose=1)
# print("###################", model.metrics_names)
score = model.evaluate(valid_X, valid_y,
batch_size=params["batch_size"])
idx = model.metrics_names.index("acc")
score = score[idx]
print(params, score)
return score
params_conf = [
{"name": "num_hidden_layers", "type": "integer",
"domain": (0, 5)},
{"name": "batch_size", "type": "integer",
"domain": (16, 128), "scale": "log"},
{"name": "learning_rate", "type": "continuous",
"domain": (1e-5, 1e-1), "scale": "log"},
{"name": "epochs", "type": "integer",
"domain": (10, 250), "scale": "log"},
{"name": "optimizer", "type": "categorical",
"domain": ("rmsprop", "sgd", "adam", "adadelta")},
{"name": "input_drop_rate", "type": "continuous",
"domain": (0, 0.5)},
{"name": "input_num_units", "type": "integer",
"domain": (32, 512), "scale": "log"},
{"name": "input_w_reg", "type": "continuous",
"domain": (1e-10, 1e-1), "scale": "log"},
{"name": "input_is_batch", "type": "categorical",
"domain": (True, False)},
{"name": "input_activation", "type": "categorical",
"domain": ("relu", "sigmoid", "tanh")},
{"name": "hidden_drop_rate", "type": "continuous",
"domain": (0, 0.75)},
{"name": "hidden_num_units", "type": "integer",
"domain": (32, 512), "scale": "log"},
{"name": "hidden_w_reg", "type": "continuous",
"domain": (1e-10, 1e-1), "scale": "log"},
{"name": "hidden_is_batch", "type": "categorical",
"domain": (True, False)},
{"name": "hidden_activation", "type": "categorical",
"domain": ("relu", "sigmoid", "tanh")},
{"name": "output_drop_rate", "type": "continuous",
"domain": (0, 0.5)},
{"name": "output_num_units", "type": "fixed",
"domain": 10},
{"name": "output_w_reg", "type": "continuous",
"domain": (1e-10, 1e-1), "scale": "log"},
{"name": "output_is_batch", "type": "categorical",
"domain": (True, False)},
{"name": "output_activation", "type": "fixed",
"domain": "softmax"},
]
if __name__ == "__main__":
np.random.seed(0)
random.seed(0)
bayes_opt = Optimizer(score_func, params_conf, sampler="bayes", r_min=10, maximize=True)
print("****************************")
print("bayes")
print(bayes_opt.search(num_iter=50))
print("****************************")
print("random")
np.random.seed(0)
random.seed(0)
random_opt = Optimizer(score_func, params_conf, sampler="random", maximize=True)
random_opt.search(num_iter=50)
# Plot results
plt.figure(figsize=(20, 10))
X = np.arange(1, len(bayes_opt.results[1]) + 1)
plt.plot(X, bayes_opt.results[1], color="b", label="bayes")
plt.plot(X, random_opt.results[1], color="g", label="random")
plt.scatter(X, bayes_opt.results[1], color="b")
plt.scatter(X, random_opt.results[1], color="g")
plt.xlabel("the number of trials", fontsize=30)
plt.ylabel("score", fontsize=30)
plt.title("Neural Network Hyperparameter Optimization", fontsize=50)
plt.ylim(0.96, 1.0)
plt.legend(fontsize=20)
plt.savefig("hyper_nn_opt.jpg")
| 33.518072 | 92 | 0.608735 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,749 | 0.314342 |
1234396a6bb8250f31699a3c56eb0bb2cef11b8c | 1,070 | py | Python | tests/library/register_expansion_test.py | Walon1998/dace | 95ddfd3e9a5c654f0f0d66d026e0b64ec0f028a0 | [
"BSD-3-Clause"
] | 1 | 2022-03-11T13:36:34.000Z | 2022-03-11T13:36:34.000Z | tests/library/register_expansion_test.py | Walon1998/dace | 95ddfd3e9a5c654f0f0d66d026e0b64ec0f028a0 | [
"BSD-3-Clause"
] | null | null | null | tests/library/register_expansion_test.py | Walon1998/dace | 95ddfd3e9a5c654f0f0d66d026e0b64ec0f028a0 | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
import dace.library
from dace.transformation import transformation as xf
import pytest
@dace.library.node
class MyLibNode(dace.nodes.LibraryNode):
implementations = {}
default_implementation = 'pure'
def __init__(self, name='MyLibNode', **kwargs):
super().__init__(name=name, **kwargs)
def test_register_expansion():
sdfg = dace.SDFG('libtest')
state = sdfg.add_state()
n = state.add_node(MyLibNode())
# Expect KeyError as pure expansion not given
with pytest.raises(KeyError):
sdfg()
@dace.library.register_expansion(MyLibNode, 'pure')
class ExpandMyLibNode(xf.ExpandTransformation):
environments = []
@staticmethod
def expansion(node: MyLibNode, state: dace.SDFGState, sdfg: dace.SDFG, **kwargs):
return dace.nodes.Tasklet('donothing', code='pass')
# After registering the expansion, the code should work
sdfg()
if __name__ == '__main__':
test_register_expansion()
| 26.75 | 89 | 0.696262 | 450 | 0.420561 | 0 | 0 | 525 | 0.490654 | 0 | 0 | 234 | 0.218692 |
1234bf219e24ad436242f38b48011626c907f01c | 2,390 | py | Python | utils/db_manipulate.py | DSSG-EUROPE/wef_oceans | 53121808b0191015f6808ac5d57c2bf433f55b57 | [
"MIT"
] | 3 | 2018-11-09T16:18:04.000Z | 2019-04-08T06:43:49.000Z | utils/db_manipulate.py | DSSG-EUROPE/wef_oceans | 53121808b0191015f6808ac5d57c2bf433f55b57 | [
"MIT"
] | null | null | null | utils/db_manipulate.py | DSSG-EUROPE/wef_oceans | 53121808b0191015f6808ac5d57c2bf433f55b57 | [
"MIT"
] | 1 | 2020-06-20T12:28:45.000Z | 2020-06-20T12:28:45.000Z | """
Functions to manipulate data from PostgreSQL database includes a
parallelise dataframe that runs a function on a pandas data frame
in parallel, as well as a loop_chunks function. This reads a chunk
from the database performs an operation and uploads to a new
table in the database.
"""
import numpy as np
import pandas as pd
import time
from multiprocessing import Pool, cpu_count
from utils import db_connect
def parallelise_dataframe(df, func, num_cores=None):
'''
Perform function in parallel on pandas data frame where if the
num_cores is not specified then use the number of available
cores -1.
Arguments:
df (dataframe to manipulate)
func (function to apply)
num_cores (number of cores to parallelise)
Returns:
The data frame processed by function in parallel.
'''
if num_cores==None:
num_cores = cpu_count() - 1
df_split = np.array_split(df, num_cores)
pool = Pool(num_cores)
df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df
def loop_chunks(table_read, chunk_function, output_schema, output_table,
size_chunk=1000000, parallel=True):
'''
Perform function on PostgreSQL database chunk. Read from the db
perform operation either threaded or on a single core, then
upload to the database.
Arguments:
table_read (a PSQL query that alchemy uses to read the table)
chunk_function (the function to apply to that chunk)
output_schema (schema for table output)
output_table (table name to output data into, will create if not exists)
size_chunk (the number of rows to process in 1 chunk)
parallel (use the parallelise_dataframe function on chunk)
'''
conn_input, conn_output = db_connect.alchemy_input_output_open()
start = round(time.time())
j = 0
for chunk in pd.read_sql_query(table_read, conn_input, chunksize=size_chunk):
if parallel==True:
chunk = parallelise_dataframe(chunk, chunk_function)
else:
chunk = chunk_function(chunk)
chunk.to_sql(output_table, conn_output, schema=output_schema,
if_exists='append', index=False)
j+=1
print('{} seconds: completed {} rows'.format(
(round(time.time()) - start), j*size_chunk))
db_connect.alchemy_input_output_close(conn_input, conn_output)
| 33.194444 | 81 | 0.702929 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,229 | 0.514226 |
123588ad730aafa13b29dfb9d8148d8bd7ecbc3e | 4,633 | py | Python | dialogue-engine/test/programytest/mappings/test_properties.py | cotobadesign/cotoba-agent-oss | 3833d56e79dcd7529c3e8b3a3a8a782d513d9b12 | [
"MIT"
] | 104 | 2020-03-30T09:40:00.000Z | 2022-03-06T22:34:25.000Z | dialogue-engine/test/programytest/mappings/test_properties.py | cotobadesign/cotoba-agent-oss | 3833d56e79dcd7529c3e8b3a3a8a782d513d9b12 | [
"MIT"
] | 25 | 2020-06-12T01:36:35.000Z | 2022-02-19T07:30:44.000Z | dialogue-engine/test/programytest/mappings/test_properties.py | cotobadesign/cotoba-agent-oss | 3833d56e79dcd7529c3e8b3a3a8a782d513d9b12 | [
"MIT"
] | 10 | 2020-04-02T23:43:56.000Z | 2021-05-14T13:47:01.000Z | """
Copyright (c) 2020 COTOBA DESIGN, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import unittest
import os
from programy.mappings.properties import PropertiesCollection
from programy.storage.factory import StorageFactory
from programy.storage.stores.file.config import FileStorageConfiguration
from programy.storage.stores.file.engine import FileStorageEngine
from programy.storage.stores.file.config import FileStoreConfiguration
class PropertysTests(unittest.TestCase):
def test_initialise_collection(self):
collection = PropertiesCollection()
self.assertIsNotNone(collection)
def test_properties_operations(self):
collection = PropertiesCollection()
self.assertIsNotNone(collection)
collection.add_property("name", "KeiffBot 1.0")
collection.add_property("firstname", "Keiff")
collection.add_property("middlename", "AIML")
collection.add_property("lastname", "BoT")
collection.add_property("fullname", "KeiffBot")
self.assertTrue(collection.has_property("name"))
self.assertFalse(collection.has_property("age"))
self.assertEqual("KeiffBot 1.0", collection.property("name"))
self.assertIsNone(collection.property("age"))
def test_load_from_file(self):
storage_factory = StorageFactory()
file_store_config = FileStorageConfiguration()
file_store_config._properties_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "test_files" + os.sep + "properties.txt",
format="text", extension="txt", encoding="utf-8", delete_on_start=False)
storage_engine = FileStorageEngine(file_store_config)
storage_factory._storage_engines[StorageFactory.PROPERTIES] = storage_engine
storage_factory._store_to_engine_map[StorageFactory.PROPERTIES] = storage_engine
collection = PropertiesCollection()
self.assertIsNotNone(collection)
collection.load(storage_factory)
self.assertTrue(collection.has_property("name"))
self.assertFalse(collection.has_property("age"))
self.assertEqual("KeiffBot 1.0", collection.property("name"))
self.assertIsNone(collection.property("age"))
def test_reload_from_file(self):
storage_factory = StorageFactory()
file_store_config = FileStorageConfiguration()
file_store_config._properties_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "test_files" + os.sep + "properties.txt",
format="text", extension="txt", encoding="utf-8", delete_on_start=False)
storage_engine = FileStorageEngine(file_store_config)
storage_factory._storage_engines[StorageFactory.PROPERTIES] = storage_engine
storage_factory._store_to_engine_map[StorageFactory.PROPERTIES] = storage_engine
collection = PropertiesCollection()
self.assertIsNotNone(collection)
collection.load(storage_factory)
self.assertTrue(collection.has_property("name"))
self.assertFalse(collection.has_property("age"))
self.assertEqual("KeiffBot 1.0", collection.property("name"))
self.assertIsNone(collection.property("age"))
collection.remove()
collection.reload_file(storage_factory)
self.assertTrue(collection.has_property("name"))
self.assertFalse(collection.has_property("age"))
self.assertEqual("KeiffBot 1.0", collection.property("name"))
self.assertIsNone(collection.property("age"))
| 44.980583 | 154 | 0.725448 | 3,208 | 0.692424 | 0 | 0 | 0 | 0 | 0 | 0 | 1,397 | 0.301532 |
1235cfb823eaf0316261db4734ea4c699278e3e7 | 2,006 | py | Python | arango/mixins.py | joymax/arango-python | 7bdb8a1a0fa0a4bd00a71e27a5b48e0b9dd7b465 | [
"ISC"
] | 6 | 2015-07-26T20:25:04.000Z | 2020-05-04T17:43:01.000Z | arango/mixins.py | appscluster/arango-python | 280a6e18ebeff22e4e991acd8957d9372fffe4b5 | [
"0BSD"
] | 1 | 2015-03-18T10:40:52.000Z | 2015-03-18T10:40:52.000Z | arango/mixins.py | appscluster/arango-python | 280a6e18ebeff22e4e991acd8957d9372fffe4b5 | [
"0BSD"
] | 6 | 2015-02-11T18:27:47.000Z | 2020-08-04T07:30:08.000Z |
__all__ = ("ComparsionMixin", "LazyLoadMixin")
class ComparsionMixin(object):
"""
Mixin to help compare two instances
"""
def __eq__(self, other):
"""
Compare two items
"""
if not issubclass(type(other), self.__class__):
return False
if (self.body == other.body and self._id == other._id and
self._rev == other._rev):
return True
keys = lambda o: [key for key in o.body.keys()
if key not in self.IGNORE_KEYS]
# compare keys only
if keys(self) != keys(other):
return False
# compare bodies but ignore sys keys
if (self.body is not None and other.body is not None):
for key in keys(other):
if self.body.get(key, None) != other.body.get(key, None):
return False
if (self._id is not None and self._rev is not None and
(self._id != other._id or str(self._rev) != str(other._rev))):
return False
return True
class LazyLoadMixin(object):
"""
Mixin to lazily load some objects
before processing some of methods.
Required attributes:
* LAZY_LOAD_HANDLERS - list of methods which should be handled
* lazy_loader - method which should check status of loading
and make decision about loading something
or simply process next method in chain
* _lazy_loaded - property which provide status of the lazy loading,
should be False by default
"""
def __getattribute__(self, name):
"""Fetching lazy document"""
if name in object.__getattribute__(self, "LAZY_LOAD_HANDLERS"):
object.__getattribute__(self, "_handle_lazy")()
return object.__getattribute__(self, name)
def _handle_lazy(self):
if self._lazy_loaded is False:
self._lazy_loaded = True
self.lazy_loader()
| 29.5 | 78 | 0.584247 | 1,951 | 0.972582 | 0 | 0 | 0 | 0 | 0 | 0 | 736 | 0.366899 |
12363f66dfb844f667ebb8ec1017ade26b9cd03a | 237 | py | Python | gherkin_to_markdown/expressions/second_header_expression.py | LeandreArseneault/gherkin_to_markdown | 157a6a7ba5b7f1f3a159bc163bf1b1187401243a | [
"MIT"
] | 6 | 2022-02-14T22:10:50.000Z | 2022-03-10T20:42:29.000Z | gherkin_to_markdown/expressions/second_header_expression.py | LeandreArseneault/gherkin_to_markdown | 157a6a7ba5b7f1f3a159bc163bf1b1187401243a | [
"MIT"
] | null | null | null | gherkin_to_markdown/expressions/second_header_expression.py | LeandreArseneault/gherkin_to_markdown | 157a6a7ba5b7f1f3a159bc163bf1b1187401243a | [
"MIT"
] | null | null | null | from gherkin_to_markdown.expressions.expression import Expression
class SecondHeaderExpression(Expression):
def to_markdown(self, statement: str):
return f"##{statement.strip().replace(':', '', 1)[len(self.keyword):]}\n\n"
| 33.857143 | 83 | 0.725738 | 168 | 0.708861 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 0.28692 |
123715b12a5b1cf1e72dca351d0afec4057e4c1c | 1,965 | py | Python | deephub/resources/__init__.py | deeplab-ai/deephub | b1d271436fab69cdfad14f19fa2e29c5338f18d6 | [
"Apache-2.0"
] | 8 | 2019-10-17T12:46:13.000Z | 2020-03-12T08:09:40.000Z | deephub/resources/__init__.py | deeplab-ai/deephub | b1d271436fab69cdfad14f19fa2e29c5338f18d6 | [
"Apache-2.0"
] | 12 | 2019-10-22T13:11:56.000Z | 2022-02-10T00:23:30.000Z | deephub/resources/__init__.py | deeplab-ai/deephub | b1d271436fab69cdfad14f19fa2e29c5338f18d6 | [
"Apache-2.0"
] | 1 | 2019-10-17T13:21:27.000Z | 2019-10-17T13:21:27.000Z | from __future__ import unicode_literals
from __future__ import absolute_import
import os
from pathlib import Path
class ResourceNotFound(OSError):
pass
DEFAULT_USER_RESOURCES_DIRECTORY = 'runtime_resources'
_default_package_dir = Path(__file__).resolve().parent / 'blobs'
_user_resources_dir = Path(os.getcwd()).resolve() / DEFAULT_USER_RESOURCES_DIRECTORY
def set_user_resources_directory(new_path):
"""
Change the path where to read for user specific resources
:param Union[str, Path] new_path: The new path to search for user resources
"""
global _user_resources_dir
_user_resources_dir = Path(new_path)
def get_resource_path(*subpaths):
"""
Get the absolute path of a resource file. Resources are first searched in the local working directory
and then on the application package.
:param str subpaths: The relative path inside the resources folder
:rtype: Path
"""
subpaths = [
path.strip('/')
for path in subpaths
]
relative_path = os.path.join(*subpaths)
if (_user_resources_dir / relative_path).exists():
return _user_resources_dir / relative_path
elif (_default_package_dir / relative_path).exists():
return _default_package_dir / relative_path
else:
raise ResourceNotFound("Cannot find resource \"{}\"".format(relative_path))
def get_resources_writable_directory(*subpaths):
"""
Get the absolute path to a writable directory in runtime path. Any intermediate directory will be first created.
:param str|Path subpaths:
:return: The absolute path in local storage
:rtype: Path
"""
subpaths = [
str(path).strip('/')
for path in subpaths
]
relative_path = os.path.join(*subpaths)
full_path = _user_resources_dir / relative_path
# Assure that the directory exists
if not os.path.exists(str(full_path)):
os.makedirs(str(full_path))
return full_path
| 26.554054 | 116 | 0.711959 | 41 | 0.020865 | 0 | 0 | 0 | 0 | 0 | 0 | 719 | 0.365903 |
12376f57cbbdd06f4b31de54e8c71b1b3af17063 | 7,334 | py | Python | kaggle-lung-cancer-approach2/modules/ImagePreprocessing3d.py | flaviostutz/datascience-snippets | 768083c4eda972bc1f6548baa86751e0405bda9b | [
"MIT"
] | 2 | 2017-06-05T17:25:55.000Z | 2018-02-04T04:01:13.000Z | kaggle-lung-cancer-approach2/modules/ImagePreprocessing3d.py | flaviostutz/datascience-snippets | 768083c4eda972bc1f6548baa86751e0405bda9b | [
"MIT"
] | null | null | null | kaggle-lung-cancer-approach2/modules/ImagePreprocessing3d.py | flaviostutz/datascience-snippets | 768083c4eda972bc1f6548baa86751e0405bda9b | [
"MIT"
] | null | null | null | from tflearn.data_preprocessing import DataPreprocessing
import numpy as np
import random
class ImagePreprocessing3d(DataPreprocessing):
""" Image Preprocessing.
Base class for applying real-time image related pre-processing.
This class is meant to be used as an argument of `input_data`. When training
a model, the defined pre-processing methods will be applied at both
training and testing time. Note that ImageAugmentation is similar to
ImagePreprocessing, but only applies at training time.
"""
def __init__(self):
super(ImagePreprocessing3d, self).__init__()
self.global_mean_pc = False
self.global_std_pc = False
# -----------------------
# Preprocessing Methods
# -----------------------
def add_image_normalization(self):
""" add_image_normalization.
Normalize a picture pixel to 0-1 float (instead of 0-255 int).
Returns:
Nothing.
"""
self.methods.append(self._normalize_image)
self.args.append(None)
def add_crop_center(self, shape):
""" add_crop_center.
Crop the center of an image.
Arguments:
shape: `tuple` of `int`. The croping shape (height, width).
Returns:
Nothing.
"""
self.methods.append(self._crop_center)
self.args.append([shape])
def resize(self, height, width):
raise NotImplementedError
def blur(self):
raise NotImplementedError
# -----------------------
# Preprocessing Methods
# -----------------------
def _normalize_image(self, batch):
return np.array(batch) / 255.
def _crop_center(self, batch, shape):
oshape = np.shape(batch[0])
nd = int((oshape[0] - shape[0]) * 0.5)
nh = int((oshape[0] - shape[1]) * 0.5)
nw = int((oshape[1] - shape[2]) * 0.5)
new_batch = []
for i in range(len(batch)):
new_batch.append(batch[i][nd: nd + shape[0], nh: nh + shape[1], nw: nw + shape[2]])
return new_batch
# ----------------------------------------------
# Preprocessing Methods (Overwritten from Base)
# ----------------------------------------------
def add_samplewise_zero_center(self, per_channel=False):
""" add_samplewise_zero_center.
Zero center each sample by subtracting it by its mean.
Arguments:
per_channel: `bool`. If True, apply per channel mean.
Returns:
Nothing.
"""
self.methods.append(self._samplewise_zero_center)
self.args.append([per_channel])
def add_samplewise_stdnorm(self, per_channel=False):
""" add_samplewise_stdnorm.
Scale each sample with its standard deviation.
Arguments:
per_channel: `bool`. If True, apply per channel std.
Returns:
Nothing.
"""
self.methods.append(self._samplewise_stdnorm)
self.args.append([per_channel])
def add_featurewise_zero_center(self, mean=None, per_channel=False):
""" add_samplewise_zero_center.
Zero center every sample with specified mean. If not specified,
the mean is evaluated over all samples.
Arguments:
mean: `float` (optional). Provides a custom mean. If none
provided, it will be automatically caluclated based on
the training dataset. Default: None.
per_channel: `bool`. If True, compute mean per color channel.
Returns:
Nothing.
"""
self.global_mean.is_required = True
self.global_mean.value = mean
if per_channel:
self.global_mean_pc = True
self.methods.append(self._featurewise_zero_center)
self.args.append(None)
def add_featurewise_stdnorm(self, std=None, per_channel=False):
""" add_featurewise_stdnorm.
Scale each sample by the specified standard deviation. If no std
specified, std is evaluated over all samples data.
Arguments:
std: `float` (optional). Provides a custom standard derivation.
If none provided, it will be automatically caluclated based on
the training dataset. Default: None.
per_channel: `bool`. If True, compute std per color channel.
Returns:
Nothing.
"""
self.global_std.is_required = True
self.global_std.value = std
if per_channel:
self.global_std_pc = True
self.methods.append(self._featurewise_stdnorm)
self.args.append(None)
# --------------------------------------------------
# Preprocessing Calculation (Overwritten from Base)
# --------------------------------------------------
def _samplewise_zero_center(self, batch, per_channel=False):
for i in range(len(batch)):
if not per_channel:
batch[i] -= np.mean(batch[i])
else:
batch[i] -= np.mean(batch[i], axis=(0, 1, 2), keepdims=True)
return batch
def _samplewise_stdnorm(self, batch, per_channel=False):
for i in range(len(batch)):
if not per_channel:
batch[i] /= (np.std(batch[i]) + _EPSILON)
else:
batch[i] /= (np.std(batch[i], axis=(0, 1, 2),
keepdims=True) + _EPSILON)
return batch
# --------------------------------------------------------------
# Calulation with Persistent Parameters (Overwritten from Base)
# --------------------------------------------------------------
def _compute_global_mean(self, dataset, session, limit=None):
""" Compute mean of a dataset. A limit can be specified for faster
computation, considering only 'limit' first elements. """
_dataset = dataset
mean = 0.
if isinstance(limit, int):
_dataset = _dataset[:limit]
if isinstance(_dataset, np.ndarray) and not self.global_mean_pc:
mean = np.mean(_dataset)
else:
# Iterate in case of non numpy data
for i in range(len(dataset)):
if not self.global_mean_pc:
mean += np.mean(dataset[i]) / len(dataset)
else:
mean += (np.mean(dataset[i], axis=(0, 1, 2),
keepdims=True) / len(dataset))[0][0][0]
self.global_mean.assign(mean, session)
return mean
def _compute_global_std(self, dataset, session, limit=None):
""" Compute std of a dataset. A limit can be specified for faster
computation, considering only 'limit' first elements. """
_dataset = dataset
std = 0.
if isinstance(limit, int):
_dataset = _dataset[:limit]
if isinstance(_dataset, np.ndarray) and not self.global_std_pc:
std = np.std(_dataset)
else:
for i in range(len(dataset)):
if not self.global_std_pc:
std += np.std(dataset[i]) / len(dataset)
else:
std += (np.std(dataset[i], axis=(0, 1, 2),
keepdims=True) / len(dataset))[0][0][0]
self.global_std.assign(std, session)
return std | 38.197917 | 95 | 0.559176 | 7,243 | 0.987592 | 0 | 0 | 0 | 0 | 0 | 0 | 3,113 | 0.424461 |
1238f5782c007b0342cf7631189d532a4f5471d2 | 640 | py | Python | rpicamera/usepygame.py | terasakisatoshi/pythonCodes | baee095ecee96f6b5ec6431267cdc6c40512a542 | [
"MIT"
] | null | null | null | rpicamera/usepygame.py | terasakisatoshi/pythonCodes | baee095ecee96f6b5ec6431267cdc6c40512a542 | [
"MIT"
] | null | null | null | rpicamera/usepygame.py | terasakisatoshi/pythonCodes | baee095ecee96f6b5ec6431267cdc6c40512a542 | [
"MIT"
] | null | null | null | import pygame
import pygame.camera
#from pygame.locals import *
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640, 480), 0)
def main():
camlist = pygame.camera.list_cameras()
if camlist:
print('camera {} is detected'.format(camlist[0]))
cam = pygame.camera.Camera(camlist[0], (640, 480))
cam.start()
image = cam.get_image()
print(image)
screen.blit(
image,
(0, 0),
)
pygame.display.update()
else:
raise ValueError('Sorry no cameras detected')
print('end program')
if __name__ == '__main__':
main()
| 22.857143 | 58 | 0.590625 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 101 | 0.157813 |
123bccff69a049fadbfe73510677148e9ddcb731 | 1,210 | py | Python | AI502/ScAI/lstm.py | sungnyun/AI-assignments | 6451fd6db33fd8671ca362b4ad4c190979a98c22 | [
"MIT"
] | null | null | null | AI502/ScAI/lstm.py | sungnyun/AI-assignments | 6451fd6db33fd8671ca362b4ad4c190979a98c22 | [
"MIT"
] | null | null | null | AI502/ScAI/lstm.py | sungnyun/AI-assignments | 6451fd6db33fd8671ca362b4ad4c190979a98c22 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch.nn as nn
class SimpleRNN(nn.Module):
def __init__(self, num_features, name='LSTM', seq_length=100, hidden_size=128):
super(SimpleRNN, self).__init__()
self.num_features = num_features
self.seq_length = seq_length
self.hidden_size = hidden_size
self.name = name
if self.name == 'RNN':
self.rnn = nn.RNN(input_size=self.num_features, hidden_size=self.hidden_size, num_layers=2, dropout=0.1, batch_first=True)
elif self.name == 'LSTM':
self.rnn = nn.LSTM(input_size=self.num_features, hidden_size=self.hidden_size, batch_first=True)
#self.linear = nn.Linear(self.hidden_size*2, 1)
#self.sigmoid = nn.Sigmoid()
def forward(self, x):
if self.name == 'LSTM':
output, (h_n, c_n) = self.rnn(x)
else:
output, h_n = self.rnn(x)
# h_n = h_n.reshape(h_n.size(1), 1, -1).squeeze()
# output = self.sigmoid(self.linear(h_n))
#output = output.reshape(output.size(0), output.size(1), -1)
#output = self.linear(output)
return output
# In[ ]:
| 28.139535 | 134 | 0.591736 | 1,120 | 0.92562 | 0 | 0 | 0 | 0 | 0 | 0 | 329 | 0.271901 |
123cdad2272e052e427dddd3ee2cb08bee5b4d82 | 573 | py | Python | dracoon/public_models.py | Quirinwierer/dracoon-python-api | 7fad8cdb95069fb80069e76c740547f3ad02b910 | [
"Apache-2.0"
] | 3 | 2020-10-05T14:34:46.000Z | 2020-11-27T07:44:57.000Z | dracoon/public_models.py | Quirinwierer/dracoon-python-api | 7fad8cdb95069fb80069e76c740547f3ad02b910 | [
"Apache-2.0"
] | 1 | 2022-02-15T16:01:12.000Z | 2022-02-15T16:01:12.000Z | dracoon/public_models.py | Quirinwierer/dracoon-python-api | 7fad8cdb95069fb80069e76c740547f3ad02b910 | [
"Apache-2.0"
] | 1 | 2021-03-04T08:16:07.000Z | 2021-03-04T08:16:07.000Z | from dataclasses import dataclass
from typing import List
@dataclass
class SystemInfo:
languageDefault: str
hideLoginPinputFields: bool
s3Hosts: List[str]
s3EnforceDirectUpload: bool
useS3Storage: bool
@dataclass
class ActiveDirectoryInfoItem:
id: int
alias: str
isGlobalAvailable: bool
@dataclass
class ActiveDirectoryInfo:
items: List[ActiveDirectoryInfoItem]
@dataclass
class OpenIdInfoItem:
id: int
issuer: str
alias: str
isGlobalAvailable: bool
@dataclass
class OpenIdInfo:
items: List[OpenIdInfoItem]
| 17.363636 | 40 | 0.743455 | 445 | 0.776614 | 0 | 0 | 504 | 0.879581 | 0 | 0 | 0 | 0 |
123e85539b0232e897726505c073ee908b36655f | 3,315 | py | Python | col_validation.py | scouvreur/pyspark-rdd-csv-parser | 59fa9ee5202ebb10c05b14d638234036e5139332 | [
"Apache-2.0"
] | null | null | null | col_validation.py | scouvreur/pyspark-rdd-csv-parser | 59fa9ee5202ebb10c05b14d638234036e5139332 | [
"Apache-2.0"
] | null | null | null | col_validation.py | scouvreur/pyspark-rdd-csv-parser | 59fa9ee5202ebb10c05b14d638234036e5139332 | [
"Apache-2.0"
] | null | null | null | import csv
import codecs
import StringIO
import cStringIO
import sys
import time
import argparse
from pyspark import SparkContext
parser = argparse.ArgumentParser(description='Count columns and lines existing in file')
parser.add_argument('-df','--DATAFILE', dest="DATAFILE", type=str,
help='the path for the file to be analyzed (a csv one)')
parser.add_argument('-orep','--SAVE_TO_REP', dest="SAVE_TO_REP", type=str,
help='the path for the repartitioned file to be analyzed')
class UnicodeWriter:
"""
A csv writer which will write rows to CSV file "f",
which is encoded in the given encoding
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
def unicode_csv_reader(unicode_csv_data, **kwargs):
csv.field_size_limit(sys.maxsize)
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), delimiter='|', **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
def toCSVLine(row):
# Given a list of strings, returns a properly csv formatted string
output = StringIO.StringIO("")
UnicodeWriter(output,quoting=csv.QUOTE_ALL).writerow(row)
return output.getvalue().strip()
def get_fields_index(header):
# Identify field positions from header and populate dictionary.
return dict(zip(header, range(len(header))))
def add_header(unicode_csv_data, new_header):
final_iterator = [",".join(new_header)]
for row in unicode_csv_data:
final_iterator.append(row)
return iter(final_iterator)
args = parser.parse_args()
params = vars(args)
sc = SparkContext()
file_path_full=params['DATAFILE']
kwargs = {'escapechar': '\\', 'doublequote':False}
rdd =sc.textFile(file_path_full).map(lambda x: x.replace("\x00","")).mapPartitions(lambda x: unicode_csv_reader(x))
sample = rdd.take(2)
header = sample[0]
line = sample[1]
print(header)
print(line)
# Get field positions from header.
fields_index = get_fields_index(data_header)
a = rdd.map(lambda x: (len(x),1)).reduceByKey(lambda a,b: a+b).collect()
if params['SAVE_TO_REP']:
rdd.map(toCSVLine).mapPartitions(lambda x: add_header(x,data_header)).saveAsTextFile(params['SAVE_TO_REP']);
| 33.15 | 115 | 0.634389 | 1,130 | 0.340875 | 394 | 0.118854 | 0 | 0 | 0 | 0 | 761 | 0.229563 |
123fd7b7b9f4d286bd20d4bce4dab814f4d0a36c | 254 | py | Python | Fibonacci.py | Eziowrf/project555 | a8c883b55186f59d7fe1d953c404522a17985f98 | [
"MIT"
] | 1 | 2019-07-21T06:05:09.000Z | 2019-07-21T06:05:09.000Z | Fibonacci.py | Eziowrf/project555 | a8c883b55186f59d7fe1d953c404522a17985f98 | [
"MIT"
] | 5 | 2018-09-21T01:15:26.000Z | 2018-09-26T18:37:32.000Z | Fibonacci.py | Eziowrf/project555 | a8c883b55186f59d7fe1d953c404522a17985f98 | [
"MIT"
] | 1 | 2018-09-23T15:57:26.000Z | 2018-09-23T15:57:26.000Z | # Yunfan Ye 10423172
def Fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
# arr = [1,2,3,4,5,6,7,8,9,10]
# for i in arr:
# print(Fibonacci(i))
| 19.538462 | 51 | 0.484252 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 96 | 0.377953 |
1242151ef65549586db3bf65bc0bd27cfd616b7b | 9,415 | py | Python | seek/dbtable_content_blobs.py | BMCBCC/NExtSEEK | 7aca407bbc74efc5beb4a98227c6864444b11f61 | [
"MIT"
] | null | null | null | seek/dbtable_content_blobs.py | BMCBCC/NExtSEEK | 7aca407bbc74efc5beb4a98227c6864444b11f61 | [
"MIT"
] | null | null | null | seek/dbtable_content_blobs.py | BMCBCC/NExtSEEK | 7aca407bbc74efc5beb4a98227c6864444b11f61 | [
"MIT"
] | null | null | null | '''
Created on July 12, 2016
@author: Huiming Ding
Email: huiming@mit.edu
Description:
This script is implemented for the Content_blobs database/table.
Input: No typical input to define.
Output: No typical output to define.
Example command line:
Log of changes:
'''
#!/usr/bin/env python
import os
import sys
import time
import datetime
import simplejson
import json
import logging
logger = logging.getLogger(__name__)
from .models import Content_blobs
from dmac.dbtable import DBtable
# This is the mapping between the field name used in DataGrid table
# and the field name used in the SQL query for DB retrieval
CONTENT_BLOBS_FILTER_MAPPING = {
}
# Default values for Sample table
CONTENT_BLOBS_DEFAULT = {
#'id':'',
'md5sum':'',
'url':None,
'uuid':'',
'original_filename':'',
'content_type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'asset_id':0,
'asset_type':'DataFile',
'asset_version':1,
'is_webpage':0,
'external_link':0,
'sha1sum':'',
'file_size':0,
'created_at':'',
'updated_at':''
}
class DBtable_content_blobs(DBtable):
''' The class stores all the information about the table [Sample].[dbo].[Sample]
Typical usage of the class
content_blobs = DBtable_content_blobs("DEFAULT")
return content_blobs.retrieveTableList(request)
'''
def __init__(self, whichServer='default'):
print "DBtable_content_blobs"
DBtable.__init__(self, 'SEEK', 'seek_development')
self.tablename = 'content_blobs'
self.tablemodel = Content_blobs
self.fulltablename = self.tablemodel
# this is the table for retrieving the list and shown in a dataGrid
#self.viewtablename = self.dbname + '.' + self.tablename
self.viewtablename = self.tablemodel
self.fields = [
'id',
'md5sum',
'url',
'uuid',
'original_filename',
'content_type',
'asset_id',
'asset_type',
'asset_version',
'is_webpage',
'external_link',
'sha1sum',
'file_size',
'created_at',
'updated_at'
]
# the unique constraint to find the primary key
self.uniqueFields = ['original_filename']
# The primary key name
self.primaryField = "id"
self.fieldMapping = CONTENT_BLOBS_FILTER_MAPPING
self.excludeFields = []
def storeDataFile(self, username, sampleType, record, attributeInfo, uploadEnforced=False):
''' Store one record from input excel file for batch uploading.
Input
record, a dictionary from sample sheet for uploading.
attributeInfo, the list of sample attributes defined in Seek system for this sample type.
uploadEnforced, if False, only run test; if True, forcefully upload the rcord into DB.
Output
msg, any message
status, whether or nor the test passes.
'''
if not self.__notEmptyLine(record):
#msg = 'Error: record for uploading empty in ' + sampleType
print(msg)
return msg, 0, None
# prepare requuired fields for the sample
headers_required = attributeInfo['headers_required']
# Verify whether the record for uploading has all required fields
msg_required, meetRequired = self.__verifyRequiredFields(record, headers_required)
if not meetRequired:
msg = 'Error: ' + msg_required
print(msg)
return msg, 0, None
#keysup = [x.upper() for x in record.keys()]
if 'UID' not in record.keys():
msg = 'Error: Sample record does not have a UID field.'
print(msg)
return msg, 0, None
record_new = self.__getRecord(username, record, attributeInfo)
uid = record_new['title']
#print(record_new)
if not uploadEnforced:
msg = 'Warning: Upload not enforced, test okay.'
#print(msg)
return 'Upload not enforced', 1, uid
#print(record_new)
#return 'Upload to be enforced', 1, uid
msg, status, sample_id = self.storeOneRecord(username, record_new)
if status:
self.__updateProject(username, sample_id)
#print(msg, status, uid)
return msg, status, uid
def searchFile(self, infilename, asset_typeIn=None):
''' Search Seek whether a data file has been uploaded previously.
Input
infilename: = original file name from the client side.
Output
diclist, a list of dictionaries/records from content_blobs table.
asset_id, latest asset id
asset_type, asset type
asset_version, asset version, default 1.
nassets, how many assets with the same original name and asset type.
Criteria
Only the following first two criteria are applied in the implementation of the script.
1. same file name, applied;
2. same login user, applied;
3. file checksum, not applied;
4. file time stamp, not applied;
5. file size, not applied.
'''
# Step 1. Query content_blobs table whether the data file is already uploaded.
constraint = {}
constraint['original_filename'] = infilename
if asset_typeIn is not None:
constraint['asset_type'] = asset_typeIn
diclist_cb = self.queryRecordsByConstraint(constraint)
asset_id = None
asset_type = None
asset_version = None
nassets = len(diclist_cb)
if nassets==1:
print("unqiue record found in content_blobs table")
dici = diclist_cb[0]
asset_id = dici['asset_id']
asset_type = dici['asset_type']
asset_version = dici['asset_version']
elif nassets>1:
print("multiple records found, choose the one with the highest version")
version_max = -1
for dici in diclist_cb:
version_i = dici['asset_version']
if version_i is None:
version_i = 0
else:
version_i = int(version_i)
if version_i > version_max:
asset_id = dici['asset_id']
asset_type = dici['asset_type']
asset_version = version_i
else:
print("file not found in content blob")
asset_id = None
asset_type = None
asset_version = None
print "asset info: ", asset_id, asset_type, asset_version, nassets
return asset_id, asset_type, asset_version, nassets
def retrieveFileList(self, username, asset_type):
''' Retrieve a list of records.
Input:
user_seek,
asset_type, such as "Document", "SampleType", "DataFile" or, "Sop"
'''
#filtersdic = dg.getDatagridFilters(ret)
filtersdic = {}
filtersdic['orderby'] = ''
filtersdic['limit'] = ''
filtersdic['suffix'] = ''
filtersdic['startNo'] = 0
filtersdic['endNo'] = 0
#sqlquery_filter, filterRules = self.__getFilteringParameters(ret)
filterRules = [{"field":"asset_type","op":"contains","value":asset_type}]
if asset_type in ["Document", "SampleType", "DataFile", "Sop"]:
sqlquery_filter = " asset_type='" + asset_type + "';"
else:
sqlquery_filter = " "
filtersdic['sqlquery_filter'] = sqlquery_filter
filtersdic['filterRules'] = filterRules
data = self.retrieveRecords(username, filtersdic)
return data
def getRecord(self, asset_id, asset_typeIn):
''' Search Seek whether a data file has been uploaded previously.
Input
asset_id: = primary key for the asset type, such as Sample, data file or SOP
asset_typeIn, one of 'DataFile', 'Sop', 'SampleType', and 'Document'
Output
diclist, a list of dictionaries/records from content_blobs table.
asset_id, latest asset id
asset_type, asset type
asset_version, asset version, default 1.
nassets, how many assets with the same original name and asset type.
content_type
Criteria
Only the following first two criteria are applied in the implementation of the script.
1. same file name, applied;
2. same login user, applied;
3. file checksum, not applied;
4. file time stamp, not applied;
5. file size, not applied.
'''
# Step 1. Query content_blobs table whether the data file is already uploaded.
constraint = {}
constraint['asset_id'] = asset_id
constraint['asset_type'] = asset_typeIn
diclist_cb = self.queryRecordsByConstraint(constraint)
return diclist_cb | 34.613971 | 101 | 0.585024 | 8,295 | 0.881041 | 0 | 0 | 0 | 0 | 0 | 0 | 5,085 | 0.540096 |