repo_name
stringlengths 7
111
| __id__
int64 16.6k
19,705B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
151
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_url
stringlengths 26
130
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 14.6k
687M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 12
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
10.2M
⌀ | gha_stargazers_count
int32 0
178k
⌀ | gha_forks_count
int32 0
88.9k
⌀ | gha_open_issues_count
int32 0
2.72k
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 10
2.95M
| src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 10
2.95M
| extension
stringclasses 19
values | num_repo_files
int64 1
202k
| filename
stringlengths 4
112
| num_lang_files
int64 1
202k
| alphanum_fraction
float64 0.26
0.89
| alpha_fraction
float64 0.2
0.89
| hex_fraction
float64 0
0.09
| num_lines
int32 1
93.6k
| avg_line_length
float64 4.57
103
| max_line_length
int64 7
931
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lyzustc/Reinforcement_Learning | 15,710,990,387,286 | 144ad2bdfd395dd0974e120a64b79049371f8d2a | b5c6f2ee3630b346d5e582305d9a1414765d364f | /Morvan_tutorial/rl/dqn/DDQN.py | ced319d7fdb7b974d4dfa993ef1c6f9fd4fcd815 | [] | no_license | https://github.com/lyzustc/Reinforcement_Learning | e2997d21f63692efda6dc91865fe54f95c4534e8 | 2951a23557b25e3559019dcfb2f4a34a284f739d | refs/heads/master | 2022-02-12T12:01:46.677732 | 2019-10-24T20:51:34 | 2019-10-24T20:51:34 | 208,156,390 | 0 | 0 | null | false | 2022-05-26T20:33:43 | 2019-09-12T22:26:48 | 2019-10-24T20:51:37 | 2022-05-26T20:33:42 | 7,451 | 0 | 0 | 3 | C | false | false | import tensorflow as tf
import numpy as np
from DQN import DQN
class DoubleDQN(DQN):
def __init__(
self,
n_actions,
n_features,
sess,
learning_rate=0.01,
reward_decay=0.9,
e_greedy=0.9,
replace_target_iter=300,
memory_size=500,
batch_size=32,
e_greedy_increment=None,
store_q = False
):
super(DoubleDQN, self). __init__(
n_actions,
n_features,
sess,
learning_rate,
reward_decay,
e_greedy,
replace_target_iter,
memory_size,
batch_size,
e_greedy_increment,
store_q
)
def learn(self):
s, a, r, s_ = self.sample()
if self.learn_step_counter % self.replace_target_iter == 0:
self.sess.run(self.replace_target_op)
print('\ntarget_params_replaced\n')
q_next, q_eval = self.sess.run(
[self.q_next, self.q_eval],
feed_dict={self.s_: s_, self.s: s}
)
q_target = q_eval.copy()
batch_index = np.arange(self.batch_size)
q_next_new = self.sess.run(self.q_eval, feed_dict={self.s: s_})
max_actions = np.argmax(q_next_new, axis=1)
q_target[batch_index, a] = r + self.gamma * q_next[batch_index, max_actions]
_, self.cost = self.sess.run([self._train_op, self.loss], feed_dict={self.s: s, self.q_target: q_target})
self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max
self.learn_step_counter += 1
if __name__ == '__main__':
import gym
import matplotlib.pyplot as plt
env = gym.make("Pendulum-v0")
env.seed(1)
MEMORY_SIZE = 3000
ACTION_SPACE = 11
sess = tf.Session()
with tf.variable_scope("Natural_DQN"):
natural_DQN = DQN(
n_actions=ACTION_SPACE,
n_features=env.observation_space.shape[0],
memory_size=MEMORY_SIZE,
e_greedy_increment=0.001,
sess=sess,
store_q = True
)
with tf.variable_scope("Double_DQN"):
double_DQN = DoubleDQN(
n_actions=ACTION_SPACE,
n_features=env.observation_space.shape[0],
memory_size=MEMORY_SIZE,
e_greedy_increment=0.001,
sess=sess,
store_q=True
)
sess.run(tf.global_variables_initializer())
def train(learner):
total_steps = 0
s = env.reset()
while True:
# env.render()
a = learner.choose_action(s)
f_action = (a - (ACTION_SPACE - 1) / 2) / ((ACTION_SPACE - 1) / 4)
s_new, reward, done, info = env.step(np.array([f_action]))
reward /= 10
learner.store_transition(s, a, reward, s_new)
if total_steps > MEMORY_SIZE:
learner.learn()
if total_steps - MEMORY_SIZE > 20000:
break
s = s_new
total_steps += 1
return learner.q
q_natural = train(natural_DQN)
q_double = train(double_DQN)
plt.plot(np.array(q_natural), c='r', label='natural')
plt.plot(np.array(q_double), c='b', label='double')
plt.legend(loc='best')
plt.ylabel('Q eval')
plt.xlabel('training steps')
plt.grid()
plt.show() | UTF-8 | Python | false | false | 3,426 | py | 18 | DDQN.py | 16 | 0.526562 | 0.512259 | 0 | 124 | 26.637097 | 117 |
north-jewel/data_analysis | 15,556,371,588,841 | 0713453768df046ae31c7e6afca4b6a7514c6c7b | a886d4a2fc8febfff2686cb829b9cfaba2945f43 | /homework/谷晓宇-SnrsGu/1210/salary_site_analyze.py | 459d67cb45e00ec53471f7f8f3ec113638fad6a5 | [] | no_license | https://github.com/north-jewel/data_analysis | 017f4eedd6c1f00f187f9736d1b9afd980e97e0b | 6e077a6d777d9a339095fb133b7d9a6f9d408743 | refs/heads/master | 2020-04-03T20:32:39.514601 | 2019-01-06T12:52:16 | 2019-01-06T12:52:16 | 155,548,428 | 8 | 6 | null | false | 2018-11-20T09:13:38 | 2018-10-31T11:46:17 | 2018-11-20T09:11:40 | 2018-11-20T09:13:37 | 1,467 | 4 | 3 | 0 | Jupyter Notebook | false | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/12/10/9:24
# @Author : SnrsGu
# @Email : SnrsGu@qq.com & SnrsGu@gmail.com
# @File : salary_site_analyze.py
# @Software: PyCharm
from functools import reduce
import pandas as pd
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def alter(list):
a = str(list)
w_rex = '([\d+\.\d]*)-([\d+\.\d]*)万/月'
k_rex = '([\d+\.\d]*)-([\d+\.\d]*)千/月'
w_x = re.findall(w_rex, a) # 获得待处理的万元每月的数据
k_x = re.findall(k_rex, a) # 获得待处理的千元每月的数据
w_xx = eval(str(w_x).replace('(', '').replace(')', ''))
k_xx = eval(str(k_x).replace('(', '').replace(')', ''))
w = []
k = []
for w_ in w_xx:
w.append(int(eval(w_) * 10))
for k_ in k_xx:
w.append(eval(k_))
zong = w + k
return reduce(lambda x, y: x + y, zong) / len(zong)
def salary_site(df):
area = ['北京-东城区', '北京-丰台区', '北京-大兴区', '北京-延庆区', '北京-房山区',
'北京-昌平区', '北京-朝阳区', '北京-海淀区', '北京-石景山区', '北京-西城区',
'北京-通州区', '北京-门头沟区','北京-顺义区']
salary_mean = []
for i in area:
a = int(alter(list(df[df['company_site'].isin([i])].dropna(how='any').salary.values)))
salary_mean.append(a)
print(salary_mean)
plt.barh(area, salary_mean, color='lime')
ax = plt.gca()
for i in ax.spines:
ax.spines[i].set_color('none')
ax.xaxis.grid(True)
plt.title('前程无忧Python招聘地区与工资关系')
plt.xlabel('薪资区间(千/月)')
plt.show()
if __name__ == '__main__':
df = pd.read_csv('51job.csv', encoding='gbk')
salary_site(df) | UTF-8 | Python | false | false | 1,908 | py | 488 | salary_site_analyze.py | 202 | 0.514354 | 0.504785 | 0 | 55 | 28.436364 | 94 |
vietnamican/Deep-Image-Matting-PyTorch | 3,264,175,160,308 | 06890bbde11978f7a686c251a4044ee182f822fa | a40cb085a50b3ced518074a6ec312fced3523cbd | /utils.py | 968b539ed7f30af107c3244f6e174d576c8a51a0 | [
"MIT"
] | permissive | https://github.com/vietnamican/Deep-Image-Matting-PyTorch | 3992992ad0e9f6b0389ac5811168367bc5647f20 | 3e5cbd5c1038e2bc864010b647522024a5ae4c8b | refs/heads/master | 2022-11-23T10:05:49.676284 | 2020-07-05T13:17:36 | 2020-07-05T13:17:36 | 263,933,260 | 1 | 0 | null | true | 2020-05-14T14:10:10 | 2020-05-14T14:10:10 | 2020-05-14T12:42:14 | 2020-01-09T06:21:22 | 527,563 | 0 | 0 | 0 | null | false | false | import argparse
import logging
import os
import math
import random
import cv2 as cv
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import Sampler
from skimage.measure import label
import scipy.ndimage
import scipy.ndimage.morphology
from torchvision import transforms
from config import im_size, epsilon, epsilon_sqr, device
def clip_gradient(optimizer, grad_clip):
"""
Clips gradients computed during backpropagation to avoid explosion of gradients.
:param optimizer: optimizer with the gradients to be clipped
:param grad_clip: clip value
"""
for group in optimizer.param_groups:
for param in group['params']:
if param.grad is not None:
param.grad.data.clamp_(-grad_clip, grad_clip)
def save_checkpoint(epoch, epochs_since_improvement, model, optimizer, loss, is_best, logdir):
state = {'epoch': epoch,
'epochs_since_improvement': epochs_since_improvement,
'loss': loss,
'model': model,
'optimizer': optimizer,
'torch_seed': torch.get_rng_state(),
'torch_cuda_seed': torch.cuda.get_rng_state(),
'np_seed': np.random.get_state(),
'python_seed': random.getstate()}
filename = logdir + '/checkpoint_' + str(epoch) + '_' + str(loss) + '.tar'
# filename = 'checkpoint.tar'
torch.save(state, filename)
# If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint
if is_best:
torch.save(state, logdir + '/BEST_checkpoint.tar')
def save_checkpoint_2(epoch, epochs_since_improvement, model, optimizer, loss, is_best):
state = {'epoch': epoch,
'epochs_since_improvement': epochs_since_improvement,
'loss': loss,
'model': model,
'optimizer': optimizer}
filename = 'checkpoints_2/checkpoint_' + str(epoch) + '_' + str(loss) + '.tar'
# filename = 'checkpoint.tar'
torch.save(state, filename)
# If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint
if is_best:
torch.save(state, 'checkpoints_2/BEST_checkpoint.tar')
def save_checkpoint_4(epoch, epochs_since_improvement, model, optimizer, loss, is_best):
state = {'epoch': epoch,
'epochs_since_improvement': epochs_since_improvement,
'loss': loss,
'model': model,
'optimizer': optimizer}
filename = 'checkpoints_4/checkpoint_' + str(epoch) + '_' + str(loss) + '.tar'
# filename = 'checkpoint.tar'
torch.save(state, filename)
# If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint
if is_best:
torch.save(state, 'checkpoints_4/BEST_checkpoint.tar')
def save_checkpoint_5(epoch, epochs_since_improvement, model, optimizer, loss, is_best):
state = {'epoch': epoch,
'epochs_since_improvement': epochs_since_improvement,
'loss': loss,
'model': model,
'optimizer': optimizer}
filename = 'checkpoints_5/checkpoint_' + str(epoch) + '_' + str(loss) + '.tar'
# filename = 'checkpoint.tar'
torch.save(state, filename)
# If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint
if is_best:
torch.save(state, 'checkpoints_5/BEST_checkpoint.tar')
class AverageMeter(object):
"""
Keeps track of most recent, average, sum, and count of a metric.
"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate(optimizer, shrink_factor):
"""
Shrinks learning rate by a specified factor.
:param optimizer: optimizer whose learning rate must be shrunk.
:param shrink_factor: factor in interval (0, 1) to multiply learning rate with.
"""
print("\nDECAYING learning rate.")
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr'] * shrink_factor
print("The new learning rate is %f\n" % (optimizer.param_groups[0]['lr'],))
def get_learning_rate(optimizer):
return optimizer.param_groups[0]['lr']
def accuracy(scores, targets, k=1):
batch_size = targets.size(0)
_, ind = scores.topk(k, 1, True, True)
correct = ind.eq(targets.view(-1, 1).expand_as(ind))
correct_total = correct.view(-1).float().sum() # 0D tensor
return correct_total.item() * (100.0 / batch_size)
def parse_args():
parser = argparse.ArgumentParser(description='Train face network')
# general
parser.add_argument('--checkpointdir', type=str)
parser.add_argument('--print-freq', type=int, default=100)
parser.add_argument('--logdir', type=str)
parser.add_argument('--random-interp', type=bool, default=True, help='randomly choose interpolation')
parser.add_argument('--start-epoch', type=int, default=0, help='start epoch.')
parser.add_argument('--end-epoch', type=int, default=1000, help='training epoch size.')
parser.add_argument('--lr', type=float, default=0.001, help='start learning rate')
parser.add_argument('--lr-step', type=int, default=10, help='period of learning rate decay')
parser.add_argument('--optimizer', default='adam', help='optimizer')
parser.add_argument('--weight-decay', type=float, default=0.0, help='weight decay')
parser.add_argument('--mom', type=float, default=0.9, help='momentum')
parser.add_argument('--batch-size', type=int, default=32, help='batch size in each context')
parser.add_argument('--checkpoint', type=str, default=None, help='checkpoint')
parser.add_argument('--pretrained', type=bool, default=False, help='pretrained model')
parser.add_argument('--data-augumentation', type=bool, default=False, help='is augument data or not')
parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam.')
parser.add_argument('--beta2', type=float, default=0.999, help='beta2 for adam.')
args = parser.parse_args()
return args
def get_logger():
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s %(levelname)s \t%(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
def safe_crop(mat, x, y, crop_size=(im_size, im_size)):
crop_height, crop_width = crop_size
if len(mat.shape) == 2:
ret = np.zeros((crop_height, crop_width), np.uint8)
else:
ret = np.zeros((crop_height, crop_width, 3), np.uint8)
crop = mat[y:y + crop_height, x:x + crop_width]
h, w = crop.shape[:2]
ret[0:h, 0:w] = crop
if crop_size != (im_size, im_size):
ret = cv.resize(ret, dsize=(im_size, im_size), interpolation=cv.INTER_NEAREST)
return ret
def gauss(x, sigma):
y = np.exp(-x ** 2 / (2 * sigma ** 2)) / (sigma * np.sqrt(2 * np.pi))
return y
def dgauss(x, sigma):
y = -x * gauss(x, sigma) / (sigma ** 2)
return y
def gaussgradient(im, sigma):
epsilon = 1e-2
halfsize = np.ceil(sigma * np.sqrt(-2 * np.log(np.sqrt(2 * np.pi) * sigma * epsilon))).astype(np.int32)
size = 2 * halfsize + 1
hx = np.zeros((size, size))
for i in range(0, size):
for j in range(0, size):
u = [i - halfsize, j - halfsize]
hx[i, j] = gauss(u[0], sigma) * dgauss(u[1], sigma)
hx = hx / np.sqrt(np.sum(np.abs(hx) * np.abs(hx)))
hy = hx.transpose()
gx = scipy.ndimage.convolve(im, hx, mode='nearest')
gy = scipy.ndimage.convolve(im, hy, mode='nearest')
return gx, gy
def compute_gradient_loss(pred, target, trimap):
pred_x, pred_y = gaussgradient(pred, 1.4)
target_x, target_y = gaussgradient(target, 1.4)
pred_amp = np.sqrt(pred_x ** 2 + pred_y ** 2)
target_amp = np.sqrt(target_x ** 2 + target_y ** 2)
error_map = (pred_amp - target_amp) ** 2
loss = np.sum(error_map[trimap == 128])
return loss / 1000.
def getLargestCC(segmentation):
labels = label(segmentation, connectivity=1)
largestCC = labels == np.argmax(np.bincount(labels.flat))
return largestCC
def compute_connectivity_error(pred, target, trimap, step=0.1):
# pred = pred / 255.0
# target = target / 255.0
h, w = pred.shape
thresh_steps = list(np.arange(0, 1 + step, step))
l_map = np.ones_like(pred, dtype=np.float) * -1
for i in range(1, len(thresh_steps)):
pred_alpha_thresh = (pred >= thresh_steps[i]).astype(np.int)
target_alpha_thresh = (target >= thresh_steps[i]).astype(np.int)
omega = getLargestCC(pred_alpha_thresh * target_alpha_thresh).astype(np.int)
flag = ((l_map == -1) & (omega == 0)).astype(np.int)
l_map[flag == 1] = thresh_steps[i - 1]
l_map[l_map == -1] = 1
pred_d = pred - l_map
target_d = target - l_map
pred_phi = 1 - pred_d * (pred_d >= 0.15).astype(np.int)
target_phi = 1 - target_d * (target_d >= 0.15).astype(np.int)
loss = np.sum(np.abs(pred_phi - target_phi)[trimap == 128])
return loss / 1000.
# alpha prediction loss: the abosolute difference between the ground truth alpha values and the
# predicted alpha values at each pixel. However, due to the non-differentiable property of
# absolute values, we use the following loss function to approximate it.
def mse_core(pred, true, mask):
return F.mse_loss(pred * mask, true * mask, reduction='sum') / (torch.sum(mask) + epsilon)
def alpha_prediction_loss(y_pred, y_true):
mask = y_true[:, 1, :]
pred = y_pred[:, 0, :]
true = y_true[:, 0, :]
return mse_core(pred, true, mask)
def composition_loss(y_pred, y_true, image, fg, bg):
mask = y_true[:, 1:2, :, :]
mask = torch.cat((mask, mask, mask), dim=1)
pred = y_pred[:, :, :]
pred = pred.reshape((-1, 1, pred.shape[1], pred.shape[2]))
pred = torch.cat((pred, pred, pred), dim=1)
true = y_true[:, 0, :, :]
merged = pred * fg + (1 - pred) * bg
return mse_core(merged, image, mask) / 3.
# compute the MSE error given a prediction, a ground truth and a trimap.
# pred: the predicted alpha matte
# target: the ground truth alpha matte
# trimap: the given trimap
#
def compute_mse(pred, alpha, trimap):
num_pixels = float((trimap == 128).sum())
return ((pred - alpha) ** 2).sum() / num_pixels
# compute the SAD error given a prediction and a ground truth.
#
def compute_sad(pred, alpha):
diff = np.abs(pred - alpha)
return np.sum(diff) / 1000
def draw_str(dst, target, s):
x, y = target
cv.putText(dst, s, (x + 1, y + 1), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness=2, lineType=cv.LINE_AA)
cv.putText(dst, s, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv.LINE_AA)
def ensure_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
interp_list = [cv.INTER_NEAREST, cv.INTER_LINEAR, cv.INTER_CUBIC, cv.INTER_LANCZOS4]
def maybe_random_interp(cv2_interp):
if np.random.rand() < 0.5:
return np.random.choice(interp_list)
return cv2_interp
num_fgs = 431
num_bgs_per_fg = 100
num_bgs = num_fgs * num_bgs_per_fg
split_ratio = 0.2
out_names_train = 0
out_names_valid = 0
def split_name(split, num, split_index):
if(split == 'train'):
names = np.arange(num)
np.random.shuffle(names)
names_train = names[:split_index]
names_valid = names[split_index:]
global out_names_train
out_names_train = names_train
global out_names_valid
out_names_valid = names_valid
return out_names_train, out_names_valid
class InvariantSampler(Sampler):
def __init__(self, data_source, split, batch_size):
super().__init__(data_source)
self.data_source = data_source
self.split = split
self.batch_size = batch_size
def generate(self):
names_train, names_valid = split_name(self.split, num_fgs * 8, math.ceil(num_fgs * (1-split_ratio)) * 8)
if self.split == 'train':
names = names_train
else:
names = names_valid
np.random.shuffle(names)
names = names * self.batch_size
names = np.expand_dims(names, 1)
reduces = np.copy(names)
for i in np.arange(1, self.batch_size):
temp = names + i
reduces = np.concatenate([reduces, temp], axis=1)
reduces = reduces.reshape(-1)
return np.asarray(reduces)
def __iter__(self):
self.names = self.generate()
return iter(self.names)
def __len__(self):
return len(self.names)
class RandomSampler(Sampler):
def __init__(self, data_source, replacement=False, num_samples=None):
super().__init__(data_source)
self.data_source = data_source
self.replacement = replacement
self._num_samples = num_samples
def num_samples(self):
# dataset size might change at runtime
if self._num_samples is None:
return len(self.data_source)
return self._num_samples
def __iter__(self):
n = self.__len__()
if self.replacement:
return iter(torch.randint(high=n, size=(self.num_samples,), dtype=torch.int64).tolist())
return iter(torch.randperm(n).tolist())
def __len__(self):
return self.num_samples() | UTF-8 | Python | false | false | 13,600 | py | 20 | utils.py | 17 | 0.626691 | 0.611912 | 0 | 382 | 34.604712 | 112 |
Gattocrucco/lab4mpr | 2,018,634,653,928 | 0d2581093653a201e44a2c5f0a41b6ce4696099a | fd2908f80e6a20d1a2c9e7f39bc18ce53e625e9f | /esp-0-preliminare/petrillo/integral.py | d904a8fe2028927f55080195e822a2ce6f278afc | [] | no_license | https://github.com/Gattocrucco/lab4mpr | a79ecdcb293923188fcef637c7566bbb3904af05 | c613bb8e57c2943123697789f5b600483a2b4ff6 | refs/heads/master | 2021-09-15T08:15:19.129544 | 2018-05-28T23:20:47 | 2018-05-28T23:20:47 | 111,024,426 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from cmath import sin, cos, sqrt, log, tan
from pylab import arctan2, pi
def csc(x):
return 1/sin(x)
def cot(x):
return 1/tan(x)
def integ1(x, a):
return -(csc(x) * sqrt(-2 * a**2 + cos(2 * x) - 1) * log(sqrt(-2 * a**2 + cos(2 * x) - 1) + sqrt(2) * cos(x)))/sqrt(2 * a**2 * csc(x)**2 + 2)
def integ(x, a):
return 4/pi * (csc(x)**2 * (sqrt(2) * csc(x) * (-2 * a**2 + cos(2 * x) - 1)**(3/2) * log(sqrt(-2 * a**2 + cos(2 * x) - 1) + sqrt(2) * cos(x)) - (2 * a**2 * cot(x) * (-2 * a**2 + cos(2 * x) - 1))/(a**2 + 1)))/(12 * (a**2 * csc(x)**2 + 1)**(3/2))
H1 = 20
H2 = 24
h = 20
s12 = integ(arctan2(H2, -H1), h/H2) - integ(arctan2(H2, H1), h/H2)
s21 = integ(arctan2(H1, -H2), h/H1) - integ(arctan2(H1, H2), h/H1)
I = 2 * (s12 + s21)
print(I/(2*pi), ' frazione dei muoni totali')
| UTF-8 | Python | false | false | 805 | py | 738 | integral.py | 141 | 0.490683 | 0.391304 | 0 | 24 | 32.375 | 248 |
udhayprakash/PythonMaterial | 5,488,968,253,088 | d85262260f5fcfc72b9d23bb046cc460d51bc8e3 | 0fd5793e78e39adbfe9dcd733ef5e42390b8cc9a | /python3/14_Code_Quality/01_static_typing/k_Union_type.py | 7cb6191172607e458c2ef7ba4024f2f628d5f8c7 | [] | no_license | https://github.com/udhayprakash/PythonMaterial | 3ea282ceb4492d94d401e3bc8bad9bf6e9cfa156 | e72f44e147141ebc9bf9ec126b70a5fcdbfbd076 | refs/heads/develop | 2023-07-08T21:07:33.154577 | 2023-07-03T10:53:25 | 2023-07-03T10:53:25 | 73,196,374 | 8 | 5 | null | false | 2023-05-26T09:59:17 | 2016-11-08T14:55:51 | 2023-03-06T13:38:50 | 2023-05-26T09:59:16 | 293,344 | 7 | 5 | 2 | Jupyter Notebook | false | false | """
Purpose: Union type
"""
from typing import Union
def is_even_whole(num) -> Union[bool, str]:
if num < 0:
return "Not a whole number"
return True if num % 2 == 0 else False
assert is_even_whole(10) is True
assert is_even_whole(19) is False
assert is_even_whole(-2) == "Not a whole number"
def is_even_whole2(num) -> Union[bool, Exception]:
if num < 0:
return Exception("Not a whole number")
return True if num % 2 == 0 else False
assert is_even_whole2(10) is True
assert is_even_whole2(19) is False
res = is_even_whole2(-2)
assert res.args[0] == "Not a whole number"
| UTF-8 | Python | false | false | 610 | py | 1,490 | k_Union_type.py | 1,269 | 0.654098 | 0.619672 | 0 | 27 | 21.592593 | 50 |
NickSwainston/blindsearch_scripts | 16,853,451,673,555 | 311119d712055088faedb087d3ab5343758ce292 | 1c6cd2efc16e93b4a74e2eb0d62aaafbed9dac8e | /blindsearch_database.py | 8dac5afecf58341741eb4064c4724d7f953cad69 | [] | no_license | https://github.com/NickSwainston/blindsearch_scripts | 83f9bf0c0ba12a07975e8f827b1f00df6483a25f | 53c83d3f566db6ff9953b719ec16cac1f345de20 | refs/heads/master | 2018-10-16T10:04:24.547627 | 2018-10-16T08:59:15 | 2018-10-16T08:59:15 | 129,832,220 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
import os, datetime, logging
import sqlite3 as lite
from optparse import OptionParser #NB zeus does not have argparse!
DB_FILE = os.environ['CMD_BS_DB_DEF_FILE']
#how many seconds the sqlite database conection takes until it times out
TIMEOUT=120
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def database_blindsearch_start(obsid, pointing, comment):
con = lite.connect(DB_FILE, timeout = TIMEOUT)
with con:
cur = con.cursor()
cur.execute("""INSERT INTO Blindsearch(Started, Obsid, Pointing, Comment,
TotalProc, TotalErrors, TotalDS, TotalDE, TotalJobComp,
BeamformProc, BeamformErrors, BeamformDS, BeamformDE, BeamformJobComp,
PrepdataProc, PrepdataErrors, PrepdataDS, PrepdataDE, PrepdataJobComp,
FFTProc, FFTErrors, FFTDS, FFTDE, FFTJobComp,
AccelProc, AccelErrors, AccelDS, AccelDE, AccelJobComp,
FoldProc, FoldErrors, FoldDS, FoldDE, FoldJobComp,
CandTotal, CandOverNoise, CandDect) VALUES(?,?,?,?,
?,?,?,?,?,
?,?,?,?,?,
?,?,?,?,?,
?,?,?,?,?,
?,?,?,?,?,
?,?,?,?,?,
?,?,?)""",
(datetime.datetime.now(), obsid, pointing, comment,
0.0, 0, 0, 0, 0,
0.0, 0, 0, 0, 0,
0.0, 0, 0, 0, 0,
0.0, 0, 0, 0, 0,
0.0, 0, 0, 0, 0,
0.0, 0, 0, 0, 0,
0, 0, 0))
vcs_command_id = cur.lastrowid
return vcs_command_id
def database_script_list(bs_id, command, arguments_list, threads, expe_proc_time,
attempt=1):
"""
Will create all the rows in the database for each job
"""
#works out the table from the command
if command == 'prepsubband':
table = 'Prepdata'
elif command == 'realfft':
table = 'FFT'
elif command == 'accelsearch':
table = 'Accel'
elif command == 'prepfold':
table = 'Fold'
print "attempt: "+str(attempt)
con = lite.connect(DB_FILE, timeout = TIMEOUT)
with con:
cur = con.cursor()
row_id_list = []
for ai, arguments in enumerate(arguments_list):
cur.execute("INSERT OR IGNORE INTO "+table+" (Rownum, AttemptNum, BSID, Command, Arguments, CPUs, ExpProc) VALUES(?, ?, ?, ?, ?, ?, ?)", (ai, attempt, bs_id, command, arguments, threads, expe_proc_time))
row_id_list.append(cur.lastrowid)
return row_id_list
def database_script_start(table, bs_id, rownum, attempt_num, time=datetime.datetime.now()):
con = lite.connect(DB_FILE, timeout = TIMEOUT)
with con:
cur = con.cursor()
cur.execute("UPDATE "+table+" SET Started=? WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(time, rownum, attempt_num, bs_id))
row_id = cur.lastrowid
return row_id
def database_script_stop(table, bs_id, rownum, attempt_num, errorcode,
end_time=datetime.datetime.now()):
con = lite.connect(DB_FILE, timeout = TIMEOUT)
con.row_factory = lite.Row
with con:
cur = con.cursor()
#get script data
cur.execute("SELECT * FROM "+table+" WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(rownum, attempt_num, bs_id))
columns = cur.fetchone()
#get blindsearch data
cur.execute("SELECT * FROM Blindsearch WHERE Rownum="+str(bs_id))
bs_columns = cur.fetchone()
if int(errorcode) == 0:
#add processing times and job completion count
end_s = date_to_sec(str(end_time))
start_s = date_to_sec(columns['Started'])
processing = (end_s - start_s)
cur.execute("UPDATE "+table+\
" SET Proc=?, Ended=?, Exit=? WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(processing, end_time, errorcode, rownum, attempt_num, bs_id))
tot_proc = float(bs_columns['TotalProc']) + processing
job_proc = float(bs_columns[table+'Proc']) + processing
tot_jc = int(bs_columns['TotalJobComp']) + 1
job_jc = int(bs_columns[table+'JobComp']) + 1
cur.execute("UPDATE Blindsearch SET TotalProc=?, "+table+\
"Proc=?, TotalJobComp=?, "+table+\
"JobComp=? WHERE Rownum=?",
(str(tot_proc)[:9], str(job_proc)[:9], str(tot_jc)[:9],
str(job_jc)[:9], bs_id))
else:
tot_er = int(bs_columns['TotalErrors']) + 1
job_er = int(bs_columns[table+'Errors']) + 1
cur.execute("UPDATE "+table+\
" SET Ended=?, Exit=? WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(end_time, errorcode, rownum, attempt_num, bs_id))
cur.execute("UPDATE Blindsearch SET TotalErrors=?, "+table+\
"Errors=? WHERE Rownum=?",
(tot_er,job_er, bs_id))
return
def database_script_check(table, bs_id, attempt_num):
"""
Searches for any jobs that didn't work and return the data needed to send
them off again
"""
con = lite.connect(DB_FILE, timeout = TIMEOUT)
con.row_factory = lite.Row
with con:
cur = con.cursor()
#get script data
cur.execute("SELECT * FROM "+table+" WHERE AttemptNum=? AND BSID=?",
(attempt_num, bs_id))
rows = cur.fetchall()
error_data = []
for row in rows:
if row['Started'] == None or row['Ended'] == None or row['Exit'] != 0:
error_data.append([row['Command'], row['Arguments'], row['ExpProc']])
return error_data
def database_mass_process(table, bs_id, dm_file_int=None):
#goes through jobs of that id and command type and counts errors and processing time
query = "SELECT * FROM " + table + " WHERE BSID=" + str(bs_id)
if dm_file_int is not None:
query += " AND DMFileInt=" + str(dm_file_int)
print query
con = lite.connect(DB_FILE, timeout = TIMEOUT)
con.row_factory = dict_factory
cur = con.cursor()
cur.execute(query)
rows = cur.fetchall()
processing = 0.
errors = 0
for row in rows:
#print row['Ended'], row['Started']
#processsing +=
if not row['Ended'] == None and not row['Started'] == None:
end_s = date_to_sec(row['Ended'])
start_s = date_to_sec(row['Started'])
if (end_s - start_s) >= 0.:
processing += (end_s - start_s)
else:
print "error in processing calc"
print "row num: " + str(row)
print "End secs: " + str(end_s)
print "Strat secs: " + str(start_s)
exit()
if str(row['Exit']).endswith("\n"):
if not str(row['Exit'])[:-1] == "0":
errors += 1
else:
if not row['Exit'] == 0:
errors += 1
#TODO make a better fix
try:
nodes = float(rows[0]['CPUs'])
except:
nodes =1
print "Processing time (s): " + str(processing)
print "Errors number: " + str(errors)
print "Nodes: " + str(nodes)
print "Database Table name: " + str(table)
query = "SELECT * FROM Blindsearch WHERE Rownum='" + str(bs_id) + "'"
cur.execute(query)
row = cur.fetchall()
tot_proc = row[0]['TotalProc']
if tot_proc:
new_total_proc = tot_proc + processing/3600.*nodes
else:
new_total_proc = 0. + processing/3600.*nodes
tot_er = row[0]['TotalErrors']
if tot_er:
new_total_er = tot_er + errors
else:
new_total_er = 0 + errors
job_proc = row[0][table+'Proc']
if job_proc:
new_job_proc = job_proc + processing/3600.*nodes
else:
new_job_proc = 0. + processing/3600.*nodes
job_er = row[0][table+'Errors']
if job_er:
new_job_er = job_er + errors
else:
new_job_er = 0 + errors
print new_total_proc, new_total_er, new_job_proc, new_job_er
con = lite.connect(DB_FILE, timeout = TIMEOUT)
with con:
cur = con.cursor()
cur.execute("UPDATE Blindsearch SET TotalProc=?, TotalErrors=?, "+table+"Proc=?, "+table+"Errors=? WHERE Rownum=?", (str(new_total_proc)[:9], new_total_er, str(new_job_proc)[:9], new_job_er, bs_id))
def database_mass_update(table,file_location):
print table
with open(file_location,'r') as csv:
con = lite.connect(DB_FILE, timeout = TIMEOUT)
con.row_factory = lite.Row
with con:
cur = con.cursor()
lines = csv.readlines()
for i,l in enumerate(lines):
l = l.split(',')
if i % 2 == 0:
rownum = l[2]
attempt_num = l[3]
bs_id = l[1]
cur.execute("UPDATE "+table+\
" SET Started=? WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(l[0], rownum, attempt_num, bs_id))
else:
end_time = l[0]
errorcode = l[1]
cur.execute("SELECT * FROM "+table+" WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(rownum, attempt_num, bs_id))
columns = cur.fetchone()
#get blindsearch data
cur.execute("SELECT * FROM Blindsearch WHERE Rownum="+str(bs_id))
bs_columns = cur.fetchone()
if int(errorcode) == 0:
#add processing times and job completion count
end_s = date_to_sec(str(end_time))
start_s = date_to_sec(columns['Started'])
processing = (end_s - start_s)
cur.execute("UPDATE "+table+\
" SET Proc=?, Ended=?, Exit=? WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(processing, end_time, errorcode, rownum, attempt_num, bs_id))
tot_proc = float(bs_columns['TotalProc']) + processing
job_proc = float(bs_columns[table+'Proc']) + processing
tot_jc = int(bs_columns['TotalJobComp']) + 1
job_jc = int(bs_columns[table+'JobComp']) + 1
cur.execute("UPDATE Blindsearch SET TotalProc=?, "+table+\
"Proc=?, TotalJobComp=?, "+table+\
"JobComp=? WHERE Rownum=?",
(str(tot_proc)[:9], str(job_proc)[:9], str(tot_jc)[:9],
str(job_jc)[:9], bs_id))
else:
tot_er = int(bs_columns['TotalErrors']) + 1
job_er = int(bs_columns[table+'Errors']) + 1
cur.execute("UPDATE "+table+\
" SET Ended=?, Exit=? WHERE Rownum=? AND AttemptNum=? AND BSID=?",
(end_time, errorcode, rownum, attempt_num, bs_id))
cur.execute("UPDATE Blindsearch SET TotalErrors=?, "+table+\
"Errors=? WHERE Rownum=?",
(tot_er,job_er, bs_id))
return
def database_beamform_find(table,file_location, bs_id):
time_now = datetime.datetime.now()
#go through the batch file for info
with open("{0}.batch".format(file_location),'r') as batch:
lines = batch.readlines()
for l in lines:
if l.startswith("export OMP_NUM_THREADS"):
nodes = l.split("=")[1]
if l.startswith("srun"):
command = "make_beam" #I don't think these needs to be more robust
arguments = l.split(command)[1]
with open("{0}.out".format(file_location),'r') as output:
lines = output.readlines()
find_check = False
for l in lines:
if "**FINISHED BEAMFORMING**" in l:
find_check = True
time_seconds = float(l[1:10])
#So this may be inaccurate because now isn't when the job
#finished but should get the right delta
time_then = datetime.datetime.now() - datetime.timedelta(seconds=time_seconds)
row_num = database_script_start(table, bs_id, command, arguments, nodes, None,\
time_then)
database_script_stop(table, row_num, 0, end_time=time_now)
if not find_check:
#no finshed string so likely it failed:
#TODO make this more robust to work out how long it ran before it died
row_num = database_script_start(table, bs_id, command, arguments, nodes, None, time_now)
database_script_stop(table, bs_id, rownum, attempt_num, end_time=time_now)
def date_to_sec(string):
#just an approximation (doesn't even use year and month
date, time = string.split(' ')
y,m,d = date.split('-')
h,mi,s = time.split(':')
s_out = ((float(d)*24. + float(h))*60. + float(mi))*60. + float(s)
#print "hours " + str(float(d)*24. + float(h))
#print "Minutes " + str((float(d)*24. + float(h))*60. + float(mi))
#print "secounds " + str(s_out)
return s_out
if __name__ == '__main__':
from optparse import OptionParser, OptionGroup, SUPPRESS_HELP
parser = OptionParser(usage = "usage: %prog <options>" +
"""
Script used to manage the VCS database by recording the scripts process_vcs.py uses and prints the database.
Common commands:
blindsearch_database.py -m vc
blindsearch_database.py -m vs -c <presto command>
""")
parser.add_option("-m", "--mode", dest="mode", metavar="mode", default='v', type=str, help='This script has three modes: "vc" used to view the database commands, "vs" used to view the database scripts, "vp" view processing and error statistics, "s" used to start a record of a script on the database, "e" used to record the end time and error code of a script on the database, "p" counts errors and processing time for one id and "b" is a special mode for receiving the total time of beamforming jobs. Default mode is v')
parser.add_option("-f", "--file_location", dest="file_location", metavar="file_location", type=str, help='mass update csv file location.')
view_options = OptionGroup(parser, 'View Options')
view_options.add_option("--recent", dest="recent", metavar="HOURS", default=None, type=float, help="print only jobs started in the last N hours")
view_options.add_option("--number", dest="n", metavar="N", default=20, type=int, help="number of jobs to print [default=%default]")
view_options.add_option("--all", dest="all", action="store_true", help="print all lines of the database")
view_options.add_option("-s", "--startrow", dest="startrow", default=0, type=int, help="ignore any row earlier than this one")
view_options.add_option("-e", "--endrow", dest="endrow", default=None, type=int, help="ignore any row later than this one")
view_options.add_option("-o", "--obsid", dest="obsid", default=None, type=str, help="Only prints one obsid's jobs.")
start_options = OptionGroup(parser, 'Script Start Options')
start_options.add_option("-b", "--bs_id", dest="bs_id", default=None, type=str, help="The row number of the blindsearch command of the databse")
start_options.add_option("-c", "--command", dest="command", default=None, type=str, help="The script name being run. eg volt_download.py.")
start_options.add_option("-a", "--attempt_num", dest="attempt_num", default=None, type=str, help="The attempt number of a script.")
start_options.add_option("-n", "--nodes", dest="nodes", default=None, type=int, help="The number of cpu nodes used.")
start_options.add_option("-d", "--dm_file_int", dest="dm_file_int", default=None, type=int, help="The DM file reference eg 1 = DM_002_004.")
end_options = OptionGroup(parser, 'Script End Options')
end_options.add_option("--errorcode", dest="errorcode", default=None, type=str, help="Error code of scripts.")
end_options.add_option("-r", "--rownum", dest="rownum", default=None, type=str, help="The row number of the script.")
parser.add_option_group(view_options)
parser.add_option_group(start_options)
parser.add_option_group(end_options)
(opts, args) = parser.parse_args()
#work out table
if opts.command == 'rfifind':
table = 'RFI'
elif opts.command == 'prepsubband':
table = 'Prepdata'
elif opts.command == 'realfft':
table = 'FFT'
elif opts.command == 'accelsearch':
table = 'Accel'
elif opts.command == 'prepfold':
table = 'Fold'
elif opts.mode == 'vc' or opts.mode == 'vp':
table = 'Blindsearch'
elif opts.mode == 'b' or opts.command == 'make_beam':
table = 'Beamform'
if opts.mode == "s":
vcs_row = database_script_start(table, opts.bs_id, opts.rownum, opts.attempt_num)
elif opts.mode == "e":
database_script_stop(table, opts.bs_id, opts.rownum, opts.attempt_num, opts.errorcode)
elif opts.mode == 'p':
database_mass_process(table, opts.bs_id, dm_file_int=opts.dm_file_int)
elif opts.mode == 'm':
if opts.file_location:
file_loc = opts.file_location
else:
file_loc = opts.command + '_temp_database_file.csv'
database_mass_update(table,file_loc)
elif opts.mode == 'b':
database_beamform_find(table,opts.file_location, opts.bs_id)
elif opts.mode.startswith("v"):
con = lite.connect(DB_FILE, timeout = TIMEOUT)
con.row_factory = dict_factory
query = "SELECT * FROM " + table
if opts.obsid:
query += " WHERE Arguments LIKE '%" + str(opts.obsid) + "%'"
if opts.recent is not None:
query += ''' WHERE Started > "%s"''' % str(datetime.datetime.now() - relativedelta(hours=opts.recent))
logging.debug(query)
if opts.bs_id and not opts.mode == 'vp':
query += " WHERE BSID='" + str(opts.bs_id) + "'"
elif opts.mode == 'vp' and opts.bs_id:
query += " WHERE Rownum='" + str(opts.bs_id) + "'"
if opts.dm_file_int:
query += " WHERE DMFileInt='" + str(opts.dm_file_int) + "'"
if opts.attempt_num:
if "WHERE" in query:
query += " AND AttemptNum='" + str(opts.attempt_num) + "'"
else:
query += " WHERE AttemptNum='" + str(opts.attempt_num) + "'"
if opts.errorcode:
if "WHERE" in query:
query += " AND Exit='" + str(opts.errorcode) + "'"
else:
query += " WHERE Exit='" + str(opts.errorcode) + "'"
with con:
cur = con.cursor()
cur.execute(query)
rows = cur.fetchall()
if opts.startrow and opts.endrow is None:
rows = rows[opts.startrow:]
elif opts.endrow is not None:
rows = rows[opts.startrow:opts.endrow+1]
elif not (opts.all or opts.recent):
rows = rows[-opts.n:]
if opts.mode == "vc":
print 'Row# ','Obsid ','Pointing ','Started ','Comments'
print '--------------------------------------------------------------------------------------------------'
for row in rows:
print '%-5s' % (str(row['Rownum']).rjust(4)),
print '%-12s' % (row['Obsid']),
print '%-30s' % (row['Pointing']),
print '%-22s' % (row['Started'][:19]),
print row['Comment']
#print "\n"
if opts.mode == "vs":
if (table =='RFI' or table == 'Prepdata'):
print 'BDIS ','Row# ','Atm#','Started ','Ended ','Exit_Code','ProcTime ','ExpecTime ','Arguments'
else:
print 'BDIS ','Row# ','DM_i ','Atm#','Started ','Ended ','Err_Code','ProcTime ','ExpecTime ','CPUs','Arguments'
print '--------------------------------------------------------------------------------------------------'
for row in rows:
#BSID INT, Command TEXT, Arguments TEXT, Started date, Ended date, Exit
print '%-5s' % (row['BSID']),
print '%-5s' % (str(row['Rownum']).rjust(4)),
if not (table =='RFI' or table == 'Prepdata' or table == 'Beamform'):
if str(row['DMFileInt']).endswith('\n'):
print '%-5s' % str((row['DMFileInt']))[:-1],
else:
print '%-5s' % (row['DMFileInt']),
print '%-5s' % (row['AttemptNum']),
if row['Started'] is None:
print '%-22s' % (row['Started']),
else:
print '%-22s' % (row['Started'][:19]),
if row['Ended'] is None:
print '%-22s' % (row['Ended']),
else:
print '%-22s' % (row['Ended'][:19]),
print '%-7s' % (row['Proc']),
print '%-7s' % (row['ExpProc']),
if str(row['Exit']).endswith('\n'):
print '%-5s' % str(row['Exit'])[:-1],
else:
print '%-5s' % (row['Exit']),
print '%-5s' % (row['CPUs']),
print row['Arguments'],
print "\n"
if opts.mode == "vp":
for ri, row in enumerate(rows):
if ri%20 == 0:
print 'Row# | Total proc | err# | Beamform proc | err# | Prep proc | err# | FFT proc | err# | Accel proc | err# | Fold proc | err# |'
print '-----|------------|------|---------------|------|-----------|------|----------|------|------------|------|-----------|------|'
#TotalProc FLOAT, TotalErrors INT, RFIProc FLOAT, RFIErrors INT, PrepdataProc FLOAT, PrepdataErrors INT, FFTProc FLOAT, FFTErrors INT, AccelProc FLOAT, AccelErrors INT, FoldProc FLOAT, FoldErrors INT,
print '{:4s} |{:11.2f} |{:5d} | {:13.2f} |{:5d} | {:9.2f} |{:5d} | {:8.2f} |{:5d} | {:10.2f} |{:5d} | {:9.2f} |{:5d} |'.format(str(row['Rownum']).rjust(4),row['TotalProc'],row['TotalErrors'],row['BeamformProc'],row['BeamformErrors'],row['PrepdataProc'],row['PrepdataErrors'],row['FFTProc'],row['FFTErrors'],row['AccelProc'],row['AccelErrors'],row['FoldProc'],row['FoldErrors'])
| UTF-8 | Python | false | false | 23,612 | py | 10 | blindsearch_database.py | 9 | 0.509233 | 0.500762 | 0 | 512 | 45.068359 | 525 |
mayrazan/exercicios-python-unoesc | 4,561,255,304,696 | 45aea735a9423eaf194ca9d2a1d6dc7db4340889 | 264aa1cde73eafbe7c640658c435a9d7d288754e | /funcoes/2.py | 21a216a4e4ecf133f62e49c54f716d0f3ff98f9f | [] | no_license | https://github.com/mayrazan/exercicios-python-unoesc | bb64f7aa495c66c4c1d53569ec5c674df39f956c | e05137663587fa2ba7a636a688b4696989f895b1 | refs/heads/master | 2022-12-18T03:23:31.019903 | 2020-09-26T13:55:35 | 2020-09-26T13:55:35 | 293,115,733 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def imprime(numero):
i = 1
lista = []
while i <= numero:
lista.append(i)
for e in lista:
print(e, end = ' ')
print('\n')
i+=1
| UTF-8 | Python | false | false | 146 | py | 39 | 2.py | 38 | 0.513699 | 0.5 | 0 | 9 | 15.222222 | 24 |
bunnyblanco/vendrest | 4,870,492,948,253 | 9ca20c93b9e4fcbb88fe688d2ab0a40d72c63416 | 25b7a4dcaa10d781ceac6e4d957dea5cd340bf46 | /scripts/accountability.py | 339672632d9e5c75d5ec805e427d1326a96316d1 | [
"MIT",
"BSD-3-Clause",
"Python-2.0",
"BSD-2-Clause"
] | permissive | https://github.com/bunnyblanco/vendrest | 241b293a2db7b9e6bfc6aba6b19341b0a17e117d | f922cb9bc504216673e02896c258ff270fedaee4 | refs/heads/master | 2020-12-31T06:22:24.167172 | 2019-04-17T14:04:02 | 2019-04-17T14:04:02 | 58,963,213 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import configparser
from flask_script import Manager, Command
from vendcli import (
app,
views,
)
from vendcli.models.meta import (
engine,
Session
)
from vendcli.models import Transaction, Source
manager = Manager(app)
session = Session()
source_list = session.query(Source)
@manager.command
def cash_pull():
denom = {1:'Single',5:'Five',10:'Ten',20:'Twenty',50:'Fifty',100:'Hundred'}
value = [1,5,10,20,50,100]
for i in range(0,6):
amount = cli.prompt('Please enter the total for '+denom[value[i]]+'s')
@manager.command
def coin_pull():
denom = {100:'Dollar',50:'Fifty-cent',25:'Quarter',10:'Dime',5:'Nickle',1:'Penny'}
value = [100,50,25,10,5,1]
for d in value:
amount = cli.prompt('Please enter the total for '+denom[d]+'s')
@manager.command
def add_expense():
new_purv = cli.prompt_choice('Is this for an existing purveyor?',default='y')
if(new_purv):
ptypecli.prompt_choices('Purveyor type:')
acct=cli.prompt('Account Number')
pnum=cli.prompt('Phone Number')
addr=cli.prompt('Street Address')
addr2=cli.prompt('Street Address 2')
city=cli.prompt('City')
state=cli.prompt('State Code')
postal=cli.prompt('Postal Code')
# purv_num=generate_purveyor(pname=name,pacct=acct,pnum=pnum,saddr=addr,saddr2=addr2,city=city,postal=postal)
else:
purv_num = cli.prompt('Purveyor Number')
exp_date=cli.prompt('Date of Expense')
amount=cli.prompt('Total Expense')
supply=cli.prompt('Cost of Supplies')
other=cli.prompt('Other Expenses')
if(__name__=='__main__'):
manager.run()
| UTF-8 | Python | false | false | 1,685 | py | 13 | accountability.py | 12 | 0.637389 | 0.607715 | 0 | 55 | 29.618182 | 116 |
rohidev001/databricks_adf_repo | 15,530,601,766,650 | 37587709c56613ff227a3140b382b6d33726d60f | 7112ebabcbab081b92dd2d31001b66291b208273 | /notebooks/Users/r.rahul.deshmukh@sapphireondemand.com/mynotebook.py | a7b086c63c58a2932debc25c5ae0640aa447e7a6 | [] | no_license | https://github.com/rohidev001/databricks_adf_repo | 582d401e503e7788cdacfe83b0977667f47fbccd | df0c9ab24eca3ee64cc2989077cd07bb7072fe86 | refs/heads/master | 2020-03-26T16:04:59.425323 | 2018-08-20T08:25:57 | 2018-08-20T08:25:57 | 145,081,736 | 0 | 0 | null | false | 2018-08-17T07:26:34 | 2018-08-17T06:35:25 | 2018-08-17T06:46:28 | 2018-08-17T07:26:34 | 0 | 0 | 0 | 0 | Python | false | null | # Databricks notebook source
# COMMAND ----------
# rest1.py
# This script should demo databricks REST API.
# ref:
# goog: With python how to authenticate to REST API?
# http://docs.python-requests.org/en/latest/
import requests
usr='r.rahul.deshmukh@sapphireondemand.com'
pas='dapi748a8e2e3d9113f3e74463038cef972d'
hhost = 'https://abc-12345-911.cloud.databricks.com/api/1.2'
clusters_list = hhost+'/clusters/list'
rq1 = requests.get(clusters_list, auth=(usr,pas))
print(rq1.status_code)
print(rq1.json())
print("hello") | UTF-8 | Python | false | false | 532 | py | 2 | mynotebook.py | 2 | 0.731203 | 0.663534 | 0 | 19 | 27.052632 | 68 |
mich326/scored | 13,486,197,327,230 | 7ff70680bf20834d2169f0517848b57ee90e1f85 | 7af634b9162dae00d13c6a85382a60e221ad3591 | /scored.py | 8394e9d12ba748a7fb7d53d7cfaf6c6f8073337b | [] | no_license | https://github.com/mich326/scored | d7e820de69ab239b473794f89cacacfc890b0a00 | 3634faff00cd6406928a05b81e7fc50ff2380085 | refs/heads/master | 2021-01-15T15:54:51.631049 | 2016-03-10T02:34:03 | 2016-03-10T02:34:03 | 50,685,317 | 0 | 0 | null | true | 2016-01-29T19:17:52 | 2016-01-29T19:17:52 | 2016-01-20T19:01:10 | 2016-01-22T19:47:49 | 14 | 0 | 0 | 0 | null | null | null | from selenium import webdriver
from bs4 import BeautifulSoup, SoupStrainer
import time, sys, os, difflib, fileinput, re, urllib2, cookielib, json, multiprocessing
if os.path.exists(os.getcwd()+'/scored.log'):
os.remove(os.getcwd()+'/scored.log')
if os.path.exists(os.getcwd()+'/journals.txt'):
os.remove(os.getcwd()+'/journals.txt')
if os.path.exists(os.getcwd()+'/issuelist.txt'):
os.remove(os.getcwd()+'/issuelist.txt')
if os.path.exists(os.getcwd()+'/seedlist.txt'):
os.remove(os.getcwd()+'/seedlist.txt')
'''Purpose: To create seedlist of journal issues and extract article page metadata from journal sites
Inputs: URL of website
num - 0, 1, 2 (indicating file with xpaths, classtag or xpath)
input1 - location of file of xpaths if num ==0; class tag string if num == 1; xpath tag string
if num ==2
'''
class scored(object):
def __init__(self, url, num, input1):
self.driver = webdriver.PhantomJS()
self.driver.set_window_size(1024, 768)
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
self.xpages = 10
self.url = url
self.log = os.getcwd() + '/scored.log'
self.f = open(self.log,'ab+')
self.num = num
self.input1 = input1
def tear_down(self):
self.driver.quit()
return True
def get_journal_list(self):
self.driver.get(self.url)
fname = 'journals.txt'
with open(fname, 'ab+') as f:
if self.num == 0:
try:
self.f.write('Name of file: %s\n' %self.input1 )
xpathList = [line.strip() for line in open(self.input1)]
for xpath in xpathList:
xpathElement = self.driver.find_element_by_xpath(xpath)
self.f.write('xpath: %s\n' %xpathElement.get_attribute('href'))
f.write('%s\n' %xpathElement.get_attribute('href'))
except:
print 'The file ' + self.input1 + ' does not exist'
elif self.num == 1:
try:
classTagArray = self.driver.find_elements_by_class_name(self.input1)
self.f.write('Using %s as class tag \n' %self.input1)
for classTag in classTagArray:
self.f.write('class: %s\n' %classTag.find_element_by_tag_name('a').get_attribute('href'))
f.write('%s\n' %classTag.find_element_by_tag_name('a').get_attribute('href'))
except:
print 'The class_name '+ self.input1 + 'is not valid on the input site provided'
elif self.num == 2:
try:
allXpaths = self.driver.find_elements_by_xpath(self.input1)
for i in allXpaths:
if 'journal' in i.find_element_by_tag_name('a').get_attribute('href'):
if self.url in i.find_element_by_tag_name('a').get_attribute('href'):
currLink = (i.find_element_by_tag_name('a').get_attribute('href'))+'issues'
else:
currLink = i.find_element_by_tag_name('a').get_attribute('href')
f.write('%s\n' %currLink)
except:
print 'The xpath provided, ' + self.input1 + 'is not valid for the input site provided'
else:
print 'Please enter a legal input'
self.tear_down()
def get_issues_list(self):
''' get all issues '''
fname = 'issuelist.txt'
jfname = 'journals.txt'
try:
journals = [line.rstrip() for line in open(jfname)]
except:
self.f.write('No journals.txt\n')
sys.exit()
for j in journals:
soup = self.get_page_soup(j)
self.get_list(soup, j, fname)
def get_articles_list(self):
''' generate the journals lists from the issues list '''
fname = 'seedlist.txt'
iname = 'issuelist.txt'
issues = []
again = True
try:
issues = [line.rstrip() for line in open(iname)]
except:
self.f.write('No issuelist.txt\n')
sys.exit()
for page in issues:
soup = self.get_page_soup(page)
self.get_list(soup, page, fname)
def get_html(self, link, selenium=None):
''' reach html using urllib2 & cookies '''
if selenium:
self.driver.get(link)
time.sleep(5)
self.tear_down()
return self.driver.page_source
else:
try:
request = urllib2.Request(link)
response = self.opener.open(request)
time.sleep(5)
self.cj.clear()
return response.read()
except:
print 'unable to reach link'
return False
def get_page_soup(self, link, selenium = None, strain=None):
''' return html using BS for a page '''
print 'in get_page_soup ', link
if selenium:
html = self.get_html(link, selenium=True)
else:
html = self.get_html(link)
if html:
if strain:
strainer = SoupStrainer(id=strain)
try:
return BeautifulSoup(html, parse_only=strainer)
except:
return False
else:
try:
return BeautifulSoup(html)
except:
return False
def get_list(self, soup, soupURL, filename, pubHouse=None):
''' generate issuelist from all issues on a given page'''
stopwords = ['facebook', 'twitter', 'youtube', 'linkedin', 'membership', 'subscribe', 'subscription', 'blog',\
'submit', 'contact', 'listserve', 'login', 'disclaim', 'editor', 'section', 'librarian', 'alert',\
'#', 'email', '?', 'copyright', 'license', 'charges', 'terms', 'mailto:', 'submission', 'author',\
'media', 'news', 'rss', 'mobile', 'help', 'award', 'meetings','job', 'access', 'privacy', 'features'\
'information', 'search', 'book', 'aim']
currLink = ''
issues = []
issuelist = []
links = []
seeds = []
eachlink = ''
try:
journals = [line.rstrip() for line in open('journals.txt')]
except:
journals = []
self.f.write('No journals.txt to compare urls against. \n')
if 'seedlist.txt' in filename:
try:
issues = [line.rstrip() for line in open('issuelist.txt')]
except:
issues = []
self.f.write('No issuelist.txt to compare urls against. \n')
for link in soup.find_all('a', href=True):
if not pubHouse:
pubHouse = 'http://'+self.url.split('http://')[1].split('/')[0]
doi = self.link_has_doi(link.get('href'))
try:
allLines = [line.rstrip() for line in open(filename)]
except:
allLines = []
try:
issuesTmp = [line.rstrip() for line in open('issuelistTmp.txt')]
except:
issuesTmp = []
allLines += journals + issues + issuesTmp
allLines.append(soupURL)
with open(filename,'ab+') as f:
currLink = self.get_link(link.get('href'), pubHouse)
textDiff = self.compare_text(currLink.rstrip(), allLines)
if pubHouse in currLink:
if 'issuelist.txt' in filename:
if currLink.lower().startswith('http') or doi:
if not(any(word in currLink.lower() for word in stopwords)):
if textDiff == True:
if re.findall('issue', link.get('href').lower()):
if re.findall('issue', link.getText().lower()):
f.write('%s\n' %currLink)
else:
issuelist.append(currLink)
else:
links.append(currLink)
elif 'seedlist.txt' in filename:
if currLink.lower().startswith('http') or doi:
if not(any(word in currLink.lower() for word in stopwords)):
if 'abs' in currLink.lower():
f.write('%s\n' %currLink)
seeds.append(currLink)
elif 'full' in currLink.lower():
if textDiff == True:
f.write('%s\n' %currLink)
seeds.append(currLink)
else:
if not(any(word in currLink.lower() for word in stopwords)):
if textDiff == True:
f.write('%s\n' %currLink)
# recursion for finding issuelist if necessary
if 'issuelist.txt' in filename:
with open(filename,'ab+') as f:
if len(issuelist) == 0:
for i in links:
f.write('%s\n' %i)
links = []
return
else:
with open('issuelistTmp.txt', 'ab+') as t:
t.write('%s\n' %issuelist[0])
soup = self.get_page_soup(issuelist[0])
self.get_list(soup, issuelist[0].rstrip(), filename, pubHouse)
#try selenium to access the page
if 'seedlist.txt' in filename:
if len(seeds) == 0:
soup = self.get_page_soup(soupURL, selenium=True)
for link in soup.find_all('a', href=True):
doi = self.link_has_doi(link.get('href'))
currLink = self.get_link(link.get('href'), pubHouse)
textDiff = self.compare_text(currLink.strip(), allLines)
with open(filename,'ab+') as f:
if currLink.lower().startswith('http') or doi:
if not(any(word in currLink.lower() for word in stopwords)):
if textDiff == True:
if 'abs' in currLink.lower():
f.write('%s\n' %currLink)
allLines.append(currLink)
elif 'full' in currLink.lower():
if textDiff == True:
f.write('%s\n' %currLink)
allLines.append(currLink)
def get_link (self, link, pubHouse):
''' utility function for generating an absolute link if necessary '''
if not link.lower().startswith('http'):
if pubHouse:
return pubHouse+link
else:
return link
def link_has_doi (self, link):
''' utility function to check if a link is a doi link '''
if not link.lower().startswith('http'):
if 'doi/' in link:
return True
elif any([self.is_number(i) for i in link.split('/')]):
return True
else:
return False
def is_number(self,s):
''' utility function to check if a string is a decimal number'''
try:
float(s)
if '.' in s:
return True
else:
return False
except ValueError:
return False
def compare_text(self, url, urlList):
''' check for link in a urlList '''
textDiff = ''
diffList = []
if self.url == url or self.url+'/' == url:
return False
elif urlList == [] or len(urlList) < 2:
return True
elif filter(lambda x: url in x, urlList):
return False
else:
for i in urlList:
textDiff = ''
for _,s in enumerate(difflib.ndiff(url, i)):
if s[0] == ' ': continue
elif s[0] == '+': textDiff += s[2]
diffList.append(textDiff)
for diff in diffList:
if diff == None or ('abs' in diff.lower() and len(diff) <= 9):
return False
return True
def get_meta_data(self, soup):
''' get page metadata using BS'''
metaDict = {}
authors = []
pubdate = []
subject = []
keywords = []
format = ''
fileType = ''
doiidentifier = ''
pubidentifier = ''
source = ''
title = ''
rights = ''
contentType = ''
try:
allMeta = soup.findAll('meta')
except:
print 'no metaData'
return False
for tag in allMeta:
if tag.get('name'):
if 'creator' in tag.get('name').lower() or 'author' in tag.get('name').lower():
authors.append(tag.get('content'))
if 'type' in tag.get('name').lower():
fileType = tag.get('content')
if 'subject' in tag.get('name').lower():
subjet.append(tag.get('content'))
if 'keyword' in tag.get('name').lower():
keywords.append(tag.get('content'))
if 'format' in tag.get('name').lower():
format = tag.get('content')
if 'title' in tag.get('name').lower():
title = tag.get('content')
if 'source' in tag.get('name').lower():
source = tag.get('content')
if 'rights' in tag.get('name').lower():
rights = tag.get('content')
if 'date' in tag.get('name').lower():
pubdate.append(tag.get('content'))
try:
pubdate.append(tag.get('scheme'))
except:
continue
if 'identifier' in tag.get('name').lower():
try:
if 'doi' in tag.get('scheme').lower():
doiidentifier = tag.get('content')
except:
continue
try:
if 'publisher' in tag.get('scheme').lower():
pubidentifier = tag.get('content')
except:
continue
return {'metaAuthors':authors,
'date':pubdate,
'subject':subject,
'keywords':keywords,
'format':format,
'fileType':fileType,
'doi':doiidentifier,
'pubid':pubidentifier,
'source':source,
'metaTitle':title,
'rights':rights,
'contentType':contentType}
def get_full_text(self, page):
''' Extract the data from a page '''
metaDict = {}
contentDict = {}
abstract = ''
authors = []
affilations = []
soup = self.get_page_soup(page)
metaDict = self.get_meta_data(soup)
print 'text from: ', page
if not os.path.exists(os.getcwd()+'/jsonFilesAMS'):
os.makedirs(os.getcwd()+'/jsonFilesAMS')
contentDict['id'] = page
try:
for i in soup.find_all(class_=re.compile("^abstr")):
abstract += i.find('p').text.encode('utf-8')
except:
print 'Abstract was not found on this page'
try:
title = soup.find_all(class_=re.compile("itle"))
contentDict['title'] = title.text.encode('utf-8')
except:
print 'Title was not found on this page'
contentDict['title'] = 'Null'
try:
ack = soup.find_all(class_=re.compile("cknowledgement"))
contentDict['acknowledgement'] = ack.text.encode('utf-8')
except:
print 'Acknowledgements not found on this page'
contentDict['acknowledgement'] = 'Null'
try:
for x in soup.find_all(class_=re.compile("uthor")):
try:
for k in x.find_all('strong'):
authors.append(k.text.encode('utf-8'))
except:
continue
try:
y = x.find_all('p')
if not authors:
for z in y:
authors.append(z.text.encode('utf-8'))
else:
for z in y:
affilations.append(z.text.encode('utf-8'))
except:
continue
except:
print 'Citation Authors info not found on this page'
contentDict['citation_authors'] = 'Null'
contentDict['abstract'] = abstract
contentDict['citation_authors'] = authors
contentDict['citation_affilations'] = affilations
if metaDict:
contentDict.update(metaDict)
if abstract:
filenameJSON = os.getcwd()+ '/jsonFiles/'+ page.split('://')[1].replace('/','-').replace('.','-') +'.json'
with open(filenameJSON, 'w+') as f:
json.dump(contentDict, f)
def main():
print 'Extracting Data from Journals...'
journals.get_journal_list()
journals.get_issues_list()
journals.get_articles_list()
if __name__ == '__main__':
main() | UTF-8 | Python | false | false | 13,793 | py | 1 | scored.py | 1 | 0.61669 | 0.612557 | 0 | 503 | 26.423459 | 112 |
tbobm/99problems | 12,592,844,115,553 | 3cb71a2b56972f44c874c1a856efe8cb69b2166e | d70b4d184cb80ee14e306755f7ef4bab5ee94f7b | /python/lists/P10.py | e2ba57602b7ca2d09d19a7219640857f05f612be | [] | no_license | https://github.com/tbobm/99problems | e29f65a59aa93f3ddca45ff114e24b1e3661f774 | 492146625bbe173fb31658a552d1c353eb11600f | refs/heads/master | 2021-06-01T05:42:13.412190 | 2016-07-16T14:43:07 | 2016-07-16T14:43:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # encoding: utf-8
# 1.10 (*) Run-length encoding of a list.
# Use the result of problem 1.09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as terms [N,E] where N is the number of duplicates of the element E.
#
# Example:
# ?- encode([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
# X = [[4,a],[1,b],[2,c],[2,a],[1,d][4,e]]
def func(data):
last_elem = data[:1][0]
res = []
counter = 1
for elem in data[1:]:
if elem == last_elem:
counter += 1
if elem != last_elem:
res.append([counter, last_elem])
counter = 1
last_elem = elem
res.append([counter, last_elem])
return res | UTF-8 | Python | false | false | 731 | py | 29 | P10.py | 27 | 0.573187 | 0.547196 | 0 | 23 | 30.826087 | 224 |
xiewjsir/learns | 5,360,119,233,352 | 4d91365563e554b79b5f6c008515bc63beef00cd | 5ca045803301e62caa7bb0946933621344161848 | /python/learnspider/dzdp/dzdp/spiders/spider.py | 770d5f15003eb80c4ff01ce01d40e9dbed7bd4c2 | [] | no_license | https://github.com/xiewjsir/learns | 9d5b1f85fff29b97027fefe1376f8088e0fc6f4e | 23808c34f294faf73055e5d4262fd5738a3ef214 | refs/heads/master | 2021-11-24T02:08:52.191540 | 2021-11-09T09:11:59 | 2021-11-09T09:11:59 | 163,933,868 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from scrapy import Spider, Request
import re
from lxml import etree
import json
from urllib.parse import quote
from dzdp.items import StoreItem, StorePictureItem
from copy import deepcopy
class Dzdp_spider(Spider):
name = 'dzdp'
allowed_domains = ['dianping.com']
classifys = {
'c21151': '购宠',
# 'c21150': '宠物食品',
# 'c20692': '宠物店'
}
def start_requests(self):
for classify in list(self.classifys.keys()):
for i in range(100):
url = "http://www.dianping.com/shenzhen/ch95/g25147p{}".format(str(i+1))
yield Request(url=url, callback=self.parse)
def parse(self, response):
selector = etree.HTML(response.text)
stores = selector.xpath("//div[@class='shop-list J_shop-list shop-all-list']/ul/li")
for store in stores:
print(store)
name = store.xpath(".//div[@class='tit']/a/@title")
print(name)
| UTF-8 | Python | false | false | 978 | py | 51 | spider.py | 37 | 0.6 | 0.572917 | 0 | 30 | 30.766667 | 92 |
kevincrane/kevcrablog | 16,484,084,520,333 | 9b5209731bf512f68380a4a85385a06e0e1d40eb | 21fce83c2ebf4651cff8afe7191cf247b2c3969e | /app/kevcrablog/forms.py | c6afd9df59ab17e9c254eea682b9bf1b1f8ff886 | [] | no_license | https://github.com/kevincrane/kevcrablog | 51a211877d45de3bf5ce5f72769f769258b68924 | 1522fb5b718d67228626d5cf2910e004f4ce4db4 | refs/heads/master | 2021-01-10T20:13:17.619042 | 2018-06-28T00:04:39 | 2018-06-28T00:04:39 | 17,099,676 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from flask_wtf import Form
from wtforms import TextField, TextAreaField
from wtforms import validators
from wtforms.widgets import TextArea, HTMLString
class MarkdownWidget(TextArea):
""" Replacement TextArea for blog Markdown
- When typing, text is converted to markdown and displayed in
HTML div 'markdown-preview'
"""
def __call__(self, field, **kwargs):
html = super(MarkdownWidget, self).__call__(field, id='markdown-input', **kwargs)
return HTMLString(html)
class PostForm(Form):
""" Form for new blog Post object
"""
title = TextField(u'Post Title', validators=[validators.InputRequired("Please enter a good title.")])
body = TextAreaField(u'Content', validators=[validators.InputRequired("This would be the worst blog post.")],
widget=MarkdownWidget())
class CommentForm(Form):
""" Form for a Comment on a blog Post
"""
body = TextAreaField(u'Comment', validators=[validators.InputRequired("Say something at least.")])
author = TextField(u'Name', validators=[validators.InputRequired("Don't be scared, what's your name?")]) | UTF-8 | Python | false | false | 1,141 | py | 57 | forms.py | 23 | 0.688869 | 0.688869 | 0 | 30 | 37.066667 | 113 |
ZhengkunTian/OpenTransformer | 13,907,104,139,548 | a2ebead905608bc05551bf324c0ca555f03da730 | b7f3d206f25221770fd707209f4343886e9639a9 | /otrans/encoder/base.py | 5109de6cf7530ad7b64c4fdbfa451b7c3a334c8f | [
"MIT"
] | permissive | https://github.com/ZhengkunTian/OpenTransformer | cfd4a9b41ae99d7246f202c8a565568a75261d00 | 802750a2bba2b5db5a61869a0819bce977bcd7d8 | refs/heads/master | 2022-07-26T19:40:11.824668 | 2022-07-21T01:25:09 | 2022-07-21T01:25:09 | 226,343,764 | 385 | 81 | MIT | false | 2021-11-08T04:27:05 | 2019-12-06T14:12:00 | 2021-11-05T01:39:19 | 2021-11-08T04:27:04 | 185 | 262 | 53 | 2 | Python | false | false | # File : base.py
# Author : Zhengkun Tian
# Email : zhengkun.tian@outlook.com
import torch
import torch.nn as nn
class BaseEncoder(nn.Module):
def __init__(self):
super(BaseEncoder, self).__init__()
def forward(self, inputs, inputs_mask, **kargs):
raise NotImplementedError
def inference(self, inputs, inputs_mask, cache=None, **kargs):
raise NotImplementedError | UTF-8 | Python | false | false | 406 | py | 57 | base.py | 53 | 0.667488 | 0.667488 | 0 | 17 | 22.941176 | 66 |
akiitr/python0 | 10,015,863,736,992 | 9c30e1e26df8598fa44a8e6582fbe5957dd20288 | ef59676cee1fc4c523dac85db2d6bdb5454d7658 | /coursera_automation_google_python/c2/week6.py | 102f9b8f2c4bd813966a8e6e854b9d822a15786b | [] | no_license | https://github.com/akiitr/python0 | 549bdc9c31b63ffa3101c7dbaff2f75e7a733a26 | 8e4be64c4b6017cfdbe1b87ae3eac779a169acb8 | refs/heads/master | 2021-08-18T08:19:36.177206 | 2021-06-02T07:15:31 | 2021-06-02T07:15:31 | 210,405,972 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #Python script for the reanming the old username to new username
#!/usr/bin/env python3
import sys,subprocess
f = open(sys.argv[1])
lines = f.readlines()
f.close()
for line in lines:
line_new = line.strip().replace('jane','jdoe')
sub_inputs = ["mv",line.strip(),line_new]
subprocess.run(sub_inputs)
#Bash file for the finding the files to be ranamed
#!/bin/bash
touch oldFiles.txt
files=$(grep 'jane_' ~/data/list.txt | cut -d ' ' -f3)
for i in $files; do
if test -e "/home/student-00-242fe9494c70$i"; then
echo "file $i exists"
echo "/home/student-00-242fe9494c70$i" >> oldFiles.txt
else
echo "file $i does not exist"
fi
done
| UTF-8 | Python | false | false | 719 | py | 21 | week6.py | 14 | 0.620306 | 0.585535 | 0 | 30 | 22.966667 | 70 |
aphp/edspdf | 1,503,238,575,094 | a7293d0cd54a1ff4ae7e5841e84fa857efa93177 | 465e9aeab1466708f2ee8f74075739c7c8f0cbd6 | /edspdf/pipes/classifiers/mask.py | 4be5450b0eca598f3bfce3bfb6a2897029c3f743 | [
"BSD-3-Clause",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later"
] | permissive | https://github.com/aphp/edspdf | e87187dd7b2f47e2715b3074b4288b8e5eafbbb0 | 492db043ee0bb0d3a3fd42979c8ea6e70065e9f5 | refs/heads/main | 2023-08-17T03:25:57.713447 | 2023-08-04T13:05:53 | 2023-08-04T13:05:53 | 517,726,737 | 21 | 2 | BSD-3-Clause | false | 2023-09-07T14:46:23 | 2022-07-25T15:47:09 | 2023-08-23T09:37:37 | 2023-09-07T14:46:21 | 7,454 | 22 | 4 | 0 | Python | false | false | from typing import Sequence
from edspdf import Box, PDFDoc, Pipeline, registry
from edspdf.utils.alignment import align_box_labels
@registry.factory.register("mask-classifier")
def simple_mask_classifier_factory(
x0: float,
y0: float,
x1: float,
y1: float,
pipeline: Pipeline = None,
name: str = "mask-classifier",
threshold: float = 1.0,
):
"""
The simplest form of mask classification. You define the mask, everything else
is tagged as pollution.
Parameters
----------
pipeline: Pipeline
The pipeline object
name: str
The name of the component
x0: float
The x0 coordinate of the mask
y0: float
The y0 coordinate of the mask
x1: float
The x1 coordinate of the mask
y1: float
The y1 coordinate of the mask
threshold: float
The threshold for the alignment
Examples
--------
=== "API-based"
```python
pipeline.add_pipe(
"mask-classifier",
name="classifier",
config={
"threshold": 0.9,
"x0": 0.1,
"y0": 0.1,
"x1": 0.9,
"y1": 0.9,
},
)
```
=== "Configuration-based"
```toml
[components.classifier]
@classifiers = "mask-classifier"
x0 = 0.1
y0 = 0.1
x1 = 0.9
y1 = 0.9
threshold = 0.9
```
"""
return MaskClassifier(
pipeline=pipeline,
name=name,
masks=[
Box(
label="body",
x0=x0,
y0=y0,
x1=x1,
y1=y1,
)
],
threshold=threshold,
)
@registry.factory.register("multi-mask-classifier")
def mask_classifier_factory(
pipeline: Pipeline = None,
name: str = "multi-mask-classifier",
threshold: float = 1.0,
**masks: Box,
):
"""
A generalisation, wherein the user defines a number of regions.
The following configuration produces _exactly_ the same classifier as `mask.v1`
example above.
Any bloc that is not part of a mask is tagged as `pollution`.
Parameters
----------
pipeline: Pipeline
The pipeline object
name: str
threshold: float
The threshold for the alignment
masks: Dict[str, Box]
The masks
Examples
--------
=== "API-based"
```python
pipeline.add_pipe(
"multi-mask-classifier",
name="classifier",
config={
"threshold": 0.9,
"mymask": {"x0": 0.1, "y0": 0.1, "x1": 0.9, "y1": 0.3, "label": "body"},
},
)
```
=== "Configuration-based"
```toml
[components.classifier]
@factory = "multi-mask-classifier"
threshold = 0.9
[components.classifier.mymask]
label = "body"
x0 = 0.1
y0 = 0.1
x1 = 0.9
y1 = 0.9
```
The following configuration defines a `header` region.
=== "API-based"
```python
pipeline.add_pipe(
"multi-mask-classifier",
name="classifier",
config={
"threshold": 0.9,
"body": {"x0": 0.1, "y0": 0.1, "x1": 0.9, "y1": 0.3, "label": "header"},
"header": {"x0": 0.1, "y0": 0.3, "x1": 0.9, "y1": 0.9, "label": "body"},
},
)
```
=== "Configuration-based"
```toml
[components.classifier]
@factory = "multi-mask-classifier"
threshold = 0.9
[components.classifier.header]
label = "header"
x0 = 0.1
y0 = 0.1
x1 = 0.9
y1 = 0.3
[components.classifier.body]
label = "body"
x0 = 0.1
y0 = 0.3
x1 = 0.9
y1 = 0.9
```
"""
return MaskClassifier(
pipeline=pipeline,
name=name,
masks=list(masks.values()),
threshold=threshold,
)
class MaskClassifier:
"""
Simple mask classifier, that labels every box inside one of the masks
with its label.
"""
def __init__(
self,
pipeline: Pipeline = None,
name: str = "multi-mask-classifier",
masks: Sequence[Box] = (),
threshold: float = 1.0,
):
self.name = name
masks = list(masks)
masks.append(
Box(
label="pollution",
x0=-10000,
x1=10000,
y0=-10000,
y1=10000,
)
)
self.masks = masks
self.threshold = threshold
def __call__(self, doc: PDFDoc) -> PDFDoc:
doc.content_boxes = align_box_labels(
src_boxes=self.masks,
dst_boxes=doc.content_boxes,
threshold=self.threshold,
)
return doc
| UTF-8 | Python | false | false | 4,971 | py | 97 | mask.py | 53 | 0.485013 | 0.453028 | 0 | 224 | 21.191964 | 88 |
liammaloney/roman_study_tool | 455,266,555,258 | f2f83ffaba34d2593bdb1b64f9f4f92d583db439 | ee67ca2e97062d81d1ec11d3ce9011d1af3e639d | /data.py | 79aa29c3b859a4811f2272b8aa8d8fc4097021ce | [] | no_license | https://github.com/liammaloney/roman_study_tool | 00d72c7fa8e089692995f2cd23d7f2b86805d12b | 24db85e974c8331f904a743c01db144cce2ecebf | refs/heads/master | 2021-03-10T04:51:31.207714 | 2020-03-11T00:45:22 | 2020-03-11T00:45:22 | 246,420,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | PROVINCES = {
'Britannia':'2',
'Germania inferior':'3',
'Belgica':'4',
'Lugdunensis':'5',
'Germania superior':'6',
'Aquitania':'7',
'Alpes poeninae':'8',
'Alpes cottiae':'9',
'Alpes maritimae':'10',
'Narbonensis':'11',
'Tarraconensis':'12',
'Lusitania':'13',
'Baetica':'14',
'Italia (Italy)':'15',
'Corsica':'16',
'Sardinia':'17',
'Raetia':'18',
'Noricum':'19',
'Pannonia superior':'20',
'Pannonia inferior':'21',
'Dalmatia (=Illyricum)':'22',
'Dacia':'23',
'Moesia superior':'24',
'Moesia inferior':'25',
'Thracia (Thrace)':'26',
'Macedonia':'27',
'Epirus':'28',
'Achaea':'29',
'Creta (Crete)':'30',
'Bithynia et Pontus':'31',
'Asia':'32',
'Galatia':'33',
'Lycia et Pamphylia':'34',
'Cappadocia':'35',
'Cilicia':'36',
'Armenia':'37',
'Assyria':'38',
'Mesopotamia':'39',
'Syria':'40',
'Cyprus':'41',
'Iudaea (Judea)':'42',
'Arabia':'43',
'Aegyptus (Egypt)':'44',
'Cyrenaica':'45',
'Africa Proconsularis':'46',
'Numidia':'47',
'Mauretania Caesariensis':'48',
'Mauretania Tingitana':'49',
'Sicilia (Sicily)':'50'
}
CITIES = {
'London': 'A',
'Trier': 'B',
'Paris': 'C',
'Marseilles': 'D',
'Saguntum': 'E',
'New Carthage': 'F',
'Ravenna': 'G',
'Roma (Rome)': 'H',
'Syracuse': 'I',
'Philippi': 'J',
'Pharsalus': 'K',
'Actium': 'L',
'Athens': 'M',
'Byzantium/Constantinople': 'N',
'Nicomedia': 'O',
'Pergamum/Pergamon': 'P',
'Edessa': 'Q',
'Antioch': 'R',
'Seleucia-Ctesiphon': 'S',
'Sidon': 'T',
'Jerusalem': 'U',
'Alexandria': 'V',
'Memphis': 'W',
'Carthage': 'X',
'Cirta': 'Y',
'Cadiz': 'Z'
}
DATES = {
'RANGE Second Punic War': '218-201',
'Battles of Ticinum and Trebia': '218',
'Battle of Lake Trasimene': '217',
'Battle of Cannae' : '216',
'Hannibal takes Capua and is supported by Philip V of Macedon': '215',
'defeat of Syracuse; death of Archimedes': '212',
'defeat of Hasdrubal at Metaurus River': '215',
'Romans conquer Spain': '206',
'end of First Macedonia War': '205',
'Scipio invades Africa': '204',
'Hannibal recalled': '203',
'Battle of Zama': '202',
'treaty signed after second punic war': '201',
'Spain made into two provinces': '197',
'Philip V defeated at Cynoscephalae (Second Macedonian War)': '197',
'Antiochus III of Syria defeated at Magnesia': '190',
'Third Macedonian War ends at Pydna': '168',
'Illyricum made a province': '167',
'RANGE Third Punic War; destruction of Carthage; Africa made a province': '149-146',
'Fourth Macedonian War ends': '148',
'revolt of Achaean League; Achaea and Macedonia made a province': '146',
'Tiberius Gracchus, tribune of the plebs': '133',
'RANGE Gaius Gracchus, tribune of the plebs': '123-122',
'RANGE Gaius Marius, consul six times, five times in a row (104-100)': '107-100',
'RANGE Social War': '91-87',
'siege of Rome': '82',
'RANGE Sulla dictator': '81-80',
'RANGE revolt of Spartacus in Italy': '73-71',
'Pompey and Crassus consuls': '70',
'Gaius Julius Caesar consul': '59',
'Caesar begins first five-year command in Gaul': '58',
'RANGE Caesar’s conquest of Britain': '55-54',
'Crassus killed at Carrhae against Parthians': '53',
'Gaul made a province': '51',
'DAY (# month year) senate declares martial law against Caesar': '7 january 49',
'DAY (# month year) Caesar crosses the Rubicon River, thereby declaring civil war': '11 january 49',
'Pompey defeated at Pharsalus by Caesar': '48',
'DAY (# month year) Caesar assassinated': '15 march 44'
} | UTF-8 | Python | false | false | 3,769 | py | 3 | data.py | 2 | 0.576852 | 0.518184 | 0 | 121 | 30.140496 | 104 |
Jimmy-INL/google-research | 3,719,441,708,105 | 041a9e41d48120aa56807d47f6a440a8a9459035 | e10a6d844a286db26ef56469e31dc8488a8c6f0e | /On_Combining_Bags_to_Better_Learn_from_Label_Proportions/Code/TrainTestCreation/twostraddlebags.py | 3db9ffa864a6a918f2a10bb4678c460eb9b35eec | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | https://github.com/Jimmy-INL/google-research | 54ad5551f97977f01297abddbfc8a99a7900b791 | 5573d9c5822f4e866b6692769963ae819cb3f10d | refs/heads/master | 2023-04-07T19:43:54.483068 | 2023-03-24T16:27:28 | 2023-03-24T16:32:17 | 282,682,170 | 1 | 0 | Apache-2.0 | true | 2020-07-26T15:50:32 | 2020-07-26T15:50:31 | 2020-07-26T13:45:43 | 2020-07-24T10:45:03 | 239,465 | 0 | 0 | 0 | null | false | false | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.
#!/usr/bin/python
#
# Copyright 2021 The On Combining Bags to Better Learn from
# Label Proportions Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generating Training Bags for two straddle bags."""
import pickle
import random
import numpy as np
import pandas as pd
def makeonlybagswithtwostraddle(n_clusters,
straddle_inclusion_first,
straddle_inclusion_second,
tail_inclusion,
p_law_param,
n_straddle,
n_tail,
trainfile,
cluster_dir,
option,
directory_to_read,
random_seed=None,
numpy_seed=None):
# pylint: disable=unused-argument
"""Generating Training Bags for two straddle bags."""
random.seed(random_seed)
np.random.seed(numpy_seed)
train_df = pd.read_csv(trainfile)
train_df.reset_index(drop=True, inplace=True)
# ###Reading instead of creating
cluster_to_indices_list = pickle.load(
open(directory_to_read + "cluster_indices", "rb"))
for cluster_label in range(n_clusters):
print("size of cluster ", cluster_label, " is ",
len(cluster_to_indices_list[cluster_label]))
# All Bags
all_bags_list = []
# #create the first straddle bags
straddle_bags_first = []
for _ in range(n_straddle):
this_bag = []
for cluster_label in range(n_clusters - 1):
no_of_indices = len(cluster_to_indices_list[cluster_label])
no_of_sampled_indices = np.random.binomial(
n=no_of_indices, p=straddle_inclusion_first[cluster_label])
this_bag = this_bag + random.sample(
cluster_to_indices_list[cluster_label], no_of_sampled_indices)
straddle_bags_first.append(this_bag)
print("A straddle bag created")
all_bags_list.append(this_bag)
straddle_bags_file = cluster_dir + "straddle_bags_first"
with open(straddle_bags_file, "wb") as writing_to_straddle_bags_file:
pickle.dump(straddle_bags_first, writing_to_straddle_bags_file)
# #create the second straddle bags
straddle_bags_second = []
for _ in range(n_straddle):
this_bag = []
for cluster_label in range(1, n_clusters):
no_of_indices = len(cluster_to_indices_list[cluster_label])
no_of_sampled_indices = np.random.binomial(
n=no_of_indices, p=straddle_inclusion_second[cluster_label - 1])
this_bag = this_bag + random.sample(
cluster_to_indices_list[cluster_label], no_of_sampled_indices)
straddle_bags_second.append(this_bag)
print("A straddle bag created")
all_bags_list.append(this_bag)
straddle_bags_file = cluster_dir + "straddle_bags_second"
with open(straddle_bags_file, "wb") as writing_to_straddle_bags_file:
pickle.dump(straddle_bags_second, writing_to_straddle_bags_file)
# create the tail bags
cluster_label_to_tail_bags_list = []
for cluster_label in range(n_clusters):
this_cluster_tail_bags = []
no_of_indices = len(cluster_to_indices_list[cluster_label])
for _ in range(n_tail):
no_of_sampled_indices = np.random.binomial(
n=no_of_indices, p=tail_inclusion[cluster_label])
this_bag = random.sample(cluster_to_indices_list[cluster_label],
no_of_sampled_indices)
this_bag.sort()
this_cluster_tail_bags.append(this_bag)
all_bags_list.append(this_bag)
cluster_label_to_tail_bags_list.append(this_cluster_tail_bags)
tail_bags_file = cluster_dir + "tail_bags_" + str(cluster_label)
with open(tail_bags_file, "wb") as writing_to_tail_bags_file:
pickle.dump(this_cluster_tail_bags, writing_to_tail_bags_file)
# write all bags
all_bags_file = cluster_dir + "all_bags"
with open(all_bags_file, "wb") as writing_to_all_bags_file:
pickle.dump(all_bags_list, writing_to_all_bags_file)
# create the raw training set using all bags
new_train_df = pd.DataFrame()
bag_no = 1
for bag_list in all_bags_list:
if not bag_list:
continue
this_bag_df = train_df.iloc[bag_list].copy()
this_bag_df["bag"] = bag_no
new_train_df = new_train_df.append(this_bag_df, ignore_index=True)
bag_no = bag_no + 1
new_train_df = new_train_df.sample(frac=1)
new_train_df.to_csv(cluster_dir + "full_train.csv", index=False)
| UTF-8 | Python | false | false | 5,624 | py | 6,251 | twostraddlebags.py | 4,585 | 0.652738 | 0.648649 | 0 | 156 | 35.051282 | 74 |
vaishnavishetty19/Classification-of-Credit-Card-Transactions | 6,992,206,800,527 | 22862e7d622ae99c5625694007df70c1de8e196e | d0e506ec74bcea629b46139b9332bfaa146f2ec0 | /code for classification of credit card/app.py | 2f6bcedbcddafce3356711a8723ab927c42c566b | [] | no_license | https://github.com/vaishnavishetty19/Classification-of-Credit-Card-Transactions | c3a5ea97f17826a4df401ab6cc2d40c49217d1c4 | d1d3454be54f5788af01a9abe054c883f0bfe406 | refs/heads/main | 2023-06-01T08:04:56.643023 | 2021-06-23T20:04:47 | 2021-06-23T20:04:47 | 347,320,104 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from flask import Flask, render_template, request
import pickle
import numpy as np
with open('rf_pickle_model.pkl','rb') as file:
model = pickle.load(file)
app = Flask(__name__)
@app.route('/')
def man():
return render_template('home.html')
@app.route('/predict', methods=['POST','GET'])
def home():
V1 = 0.000010
V2 = -0.000021
V3 = -0.000015
V4 = -0.000020
V5 = -0.000006
V6 = -0.000028
V7 = 0.000005
V8 = -0.000004
V9 = -0.000004
V10= 0.000005
V11= -0.000004
V12= -0.000022
V13= 0.000008
V14= -0.000003
V15= 0.000013
V16= 0.000026
V17= -0.000016
V18= 0.000029
V19= 0.000009
V20= 0.000007
V21= -0.000010
V22= 8.675109e-07
V23= 0.000001
V24= 0.000019
V25= -0.000007
V26= 0.000008
V27= 9.956689e-07
V28= -0.000001
average= sum([V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V18,V19,V20,V21,V22,V23,V24,V25,V26,V27,V28])/28
time= request.form['D']
time_difference= request.form['E']
Amount= request.form['F']
cond= request.form['G']
min= request.form['H']
import pandas as pd
import pickle
df = pd.read_pickle('C:/Users/Vaishnavi M Shetty/Desktop/code for classification of credit card/dfmod.pickle')
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
f1 = ['V1','V2','V3','V4','V5','V6','V7','V8','V9','V10','V11','V12','V13','V14','V15','V16','V17','V18','V19','V20','V21','V22','V23','V24','V25','V26','V27','V28','Amount','cond','time_difference','average']
std_x = StandardScaler()
X = df.drop('Class', axis=1)
y = df['Class']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train[f1] = std_x.fit_transform(X_train[f1])
arr = [V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V18,V19,V20,V21,V22,V23,V24,V25,V26,V27,V28,Amount,cond,time_difference,average]
arr1 = std_x.transform([arr])
import json
# arr1 = np.array([['arr']])
arr2 = np.array([[time, min]])
arr = np.concatenate((arr1, arr2), axis=1)
output = model.predict(arr)
return render_template('after.html', pred=min)
if __name__ == "__main__":
app.run(debug=True)
| UTF-8 | Python | false | false | 2,427 | py | 9 | app.py | 1 | 0.574372 | 0.407911 | 0 | 77 | 29.181818 | 213 |
conjure-up/conjure-up | 15,341,623,196,211 | 32acdb9e55daa1d0e234f936e2725f2ff5c65334 | 8b57ca58722bdd3b9335b10ead2ce578d67a636f | /conjureup/telemetry.py | 038e3efef7970b9f99c9904c7c6b90326dfd86b9 | [
"MIT"
] | permissive | https://github.com/conjure-up/conjure-up | 5257d1937961c13babb83cdb396701ff69aabcc4 | d2bf8ab8e71ff01321d0e691a8d3e3833a047678 | refs/heads/master | 2023-09-03T11:56:43.476146 | 2021-04-12T14:27:43 | 2021-04-12T14:27:43 | 45,847,491 | 473 | 78 | MIT | false | 2021-04-12T14:27:43 | 2015-11-09T15:36:18 | 2021-04-12T14:24:34 | 2021-04-12T14:27:43 | 2,677 | 456 | 74 | 103 | Python | false | false |
import asyncio
from functools import partial
import requests
from conjureup import __version__ as VERSION
from conjureup.app_config import app
GA_ID = "UA-1018242-61"
SENTRY_DSN = ('https://27ee3b60dbb8412e8acf6bc159979165:'
'b3828e6bfc05432bb35fb12f6f97fdf6@sentry.io/180147')
TELEMETRY_ASYNC_QUEUE = "telemetry-async-queue"
def track_screen(screen_name):
app.log.debug('Showing screen: {}'.format(screen_name))
if app.no_track:
return
args = dict(cd=screen_name,
t="screenview")
if 'spell' in app.config:
args['cd1'] = app.config['spell']
if not app.loop:
app.loop = asyncio.get_event_loop()
app.loop.run_in_executor(None, partial(_post_track, args))
def track_event(category, action, label):
""
app.log.debug('{}: {} {}'.format(category, action, label))
if app.no_track:
return
args = dict(ec=category,
ea=action,
el=label,
t='event')
if 'spell' in app.config:
args['cd1'] = app.config['spell']
if not app.loop:
app.loop = asyncio.get_event_loop()
app.loop.run_in_executor(None, partial(_post_track, args))
def track_exception(description, is_fatal=True):
""
if app.no_track:
return
exf = 1 if is_fatal else 0
args = dict(t='exception',
exd=description,
exf=exf)
if 'spell' in app.config:
args['cd1'] = app.config['spell']
if not app.loop:
app.loop = asyncio.get_event_loop()
app.loop.run_in_executor(None, partial(_post_track, args))
def _post_track(arg_dict):
params = dict(tid=GA_ID, v=1, aip=1, ds='app', cid=app.session_id,
av=VERSION, an="Conjure-Up")
params.update(arg_dict)
try:
requests.post("http://www.google-analytics.com/collect",
data=params)
except Exception:
pass # ignore failures to submit telemetry
| UTF-8 | Python | false | false | 1,970 | py | 164 | telemetry.py | 141 | 0.60203 | 0.571574 | 0 | 69 | 27.536232 | 70 |
gjbex/Python-software-engineering | 15,058,155,354,265 | d304e5a7d550c81486416c72d70e0b90dd8d69fe | 06ebacb64cace791f8257fb6942a0bc3a40a8447 | /source-code/decorators/decorator.py | add3f0902c884297a267cf7515a01eb0e4eec655 | [
"CC-BY-4.0"
] | permissive | https://github.com/gjbex/Python-software-engineering | 07a2e22fa1d662e882fffe6a2c4b97326beba41b | 369045946ccd6fa8fc9638de1ad6b150126de76b | refs/heads/master | 2023-08-10T09:48:27.565554 | 2023-04-18T12:56:59 | 2023-04-18T12:56:59 | 221,865,259 | 23 | 19 | CC-BY-4.0 | false | 2023-04-18T12:56:53 | 2019-11-15T07:08:52 | 2023-04-18T11:21:33 | 2023-04-18T12:56:52 | 3,809 | 21 | 15 | 1 | Jupyter Notebook | false | false | #!/usr/bin/env python
from functools import wraps
class NegArgError(Exception):
def __init__(self, name, n):
super().__init__()
self.message = 'argument {0} for {1} negative'.format(n, name)
class TooLargeArgError(Exception):
def __init__(self, name, n):
super().__init__()
self.message = 'argument {0} for {1} too large'.format(n, name)
def check_min(f):
@wraps(f)
def wrapped(n):
if n < 0:
raise NegArgError(f.__name__, n)
return f(n)
return wrapped
def check_max(f):
@wraps(f)
def wrapped(n):
if n > 12:
raise TooLargeArgError(f.__name__, n)
return f(n)
return wrapped
@check_max
@check_min
def fact(n):
'''compute factorial of given number'''
if n == 0:
return 1
else:
return n*fact(n - 1)
if __name__ == '__main__':
import sys
for n in [3, 7, 22, -1]:
try:
print(f'{n}! = {fact(n)}')
except Exception as error:
print(f'### error: {error.message}', file=sys.stderr)
print(f'function name: {fact.__name__}')
print(f'function docs: {fact.__doc__}')
| UTF-8 | Python | false | false | 1,167 | py | 57 | decorator.py | 13 | 0.533847 | 0.520994 | 0 | 53 | 21.018868 | 71 |
AvaneeshKolluri/Agile_Methods_Project | 16,844,861,774,585 | 6b6a7a3520f116075d9219624d7caad5f80e54d8 | 39accf0a2ecff0bd0e16c912a6c7d3e353769b07 | /test_userStory13.py | 721494ea52914aba1033edd0a4504a593ca5bc73 | [] | no_license | https://github.com/AvaneeshKolluri/Agile_Methods_Project | 4b7529d735ad8b3b4edae6aa81fd6acc28da17f0 | 00959adc3e103ce3f67778d667f77054068c674d | refs/heads/master | 2023-01-21T05:20:43.937680 | 2020-11-30T00:17:39 | 2020-11-30T00:17:39 | 296,751,189 | 0 | 1 | null | false | 2020-10-26T22:47:09 | 2020-09-18T23:43:40 | 2020-10-26T21:12:22 | 2020-10-26T22:46:49 | 1,145 | 0 | 1 | 0 | HTML | false | false | import unittest
from userStories import userStory13
import HtmlTestRunner
class TestUserStory13Class(unittest.TestCase):
def test_UserStory13_1(self):
resultsList = userStory13("InputGedFiles/UserStory13_GED/testUserStory13-1.ged")
self.assertEqual(resultsList, [])
def test_UserStory13_2(self):
resultsList = userStory13("InputGedFiles/UserStory13_GED/testUserStory13-2.ged")
self.maxDiff = None
#print(resultsList)
self.assertEqual(resultsList, ['ERROR: INDIVIDUAL: US13: 122: Family F2 has two children (I10, I12) with implausible birth dates (1000-01-01, 0999-11-01)',
'ERROR: INDIVIDUAL: US13: 58: Family F1 has two children (I3, I5) with implausible birth dates (1000-01-01, 1000-05-01)',
'ERROR: INDIVIDUAL: US13: 58: Family F1 has two children (I4, I5) with implausible birth dates (1000-01-02, 1000-05-01)',
'ERROR: INDIVIDUAL: US13: 76: Family F1 has two children (I3, I7) with implausible birth dates (1000-01-01, 0999-10-01)',
'ERROR: INDIVIDUAL: US13: 76: Family F1 has two children (I4, I7) with implausible birth dates (1000-01-02, 0999-10-01)',
'ERROR: INDIVIDUAL: US13: 76: Family F1 has two children (I5, I7) with implausible birth dates (1000-05-01, 0999-10-01)',
'ERROR: INDIVIDUAL: US13: 95: Family F2 has two children (I12, I9) with implausible birth dates (0999-11-01, 1000-01-01)'])
if __name__ == '__main__':
#warnings.filterwarnings("ignore")
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='./reports'))
| UTF-8 | Python | false | false | 1,750 | py | 80 | test_userStory13.py | 45 | 0.624571 | 0.516571 | 0 | 25 | 69 | 163 |
neuroradiology/Gooey | 17,497,696,777,048 | 2991a58d585d642149ac9148bfdf8b7819c0023a | dd3ca62ee1dab07eaf84ebbc0535d8e5627e1f62 | /gooey/tests/test_processor.py | 0fd866687200b777c10008e65e54508eb8b6582f | [
"MIT"
] | permissive | https://github.com/neuroradiology/Gooey | f03b51677be1fb280485b689434afdb725da0e29 | 59684fc507c118b683f22f968d733b71afde4ee1 | refs/heads/master | 2021-08-15T22:15:13.252224 | 2021-01-24T17:23:24 | 2021-01-24T17:23:24 | 23,333,982 | 5 | 3 | MIT | true | 2021-01-24T17:23:24 | 2014-08-26T01:04:20 | 2018-04-24T19:37:02 | 2021-01-24T17:23:24 | 2,148 | 4 | 2 | 0 | null | false | false | import re
import unittest
from gooey.gui.processor import ProcessController
class TestProcessor(unittest.TestCase):
def test_extract_progress(self):
# should pull out a number based on the supplied
# regex and expression
processor = ProcessController(r"^progress: (\d+)%$", None, False, 'utf-8')
self.assertEqual(processor._extract_progress(b'progress: 50%'), 50)
processor = ProcessController(r"total: (\d+)%$", None, False, 'utf-8')
self.assertEqual(processor._extract_progress(b'my cool total: 100%'), 100)
def test_extract_progress_returns_none_if_no_regex_supplied(self):
processor = ProcessController(None, None, False, 'utf-8')
self.assertIsNone(processor._extract_progress(b'Total progress: 100%'))
def test_extract_progress_returns_none_if_no_match_found(self):
processor = ProcessController(r'(\d+)%$', None, False, 'utf-8')
self.assertIsNone(processor._extract_progress(b'No match in dis string'))
def test_eval_progress(self):
# given a match in the string, should eval the result
regex = r'(\d+)/(\d+)$'
processor = ProcessController(regex, r'x[0] / x[1]', False,False, 'utf-8')
match = re.search(regex, '50/50')
self.assertEqual(processor._eval_progress(match), 1.0)
def test_eval_progress_returns_none_on_failure(self):
# given a match in the string, should eval the result
regex = r'(\d+)/(\d+)$'
processor = ProcessController(regex, r'x[0] *^/* x[1]', False, False,'utf-8')
match = re.search(regex, '50/50')
self.assertIsNone(processor._eval_progress(match))
| UTF-8 | Python | false | false | 1,705 | py | 135 | test_processor.py | 109 | 0.635777 | 0.616422 | 0 | 39 | 41.717949 | 85 |
lucyemmel/speedwagon-foundation-shop | 5,360,119,232,226 | a2550f4a7f4e7d574584d7a2ef5db74376595e1b | de5d7bab4e35b3f2a6426ce09e0d9726443c3737 | /simple_ecommerce/simple_ecommerce/middleware.py | ec466cee584dc3e13ae19a081d1c7cd23816016e | [] | no_license | https://github.com/lucyemmel/speedwagon-foundation-shop | 595135643e7ac325d356c46c68b6ab02221b4882 | e62bc4593dfafb74e260e46339f55c0d4d0345f8 | refs/heads/main | 2022-12-30T20:22:16.477284 | 2020-10-21T15:08:57 | 2020-10-21T15:08:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class FramingControlMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response['Content-Security-Policy'] = 'frame-ancestors http://localhost:3000 http://127.0.0.1:3000'
return response
| UTF-8 | Python | false | false | 324 | py | 27 | middleware.py | 13 | 0.657407 | 0.614198 | 0 | 9 | 35 | 107 |
Nauendorf/fizzbuzz_python | 16,698,832,876,359 | 2f9bcec26fd4fdc51b52dc6dea5bc598d9e6571a | 969adb984423cbc4e7e8716dbf84519ff03cde1f | /notes.py | 51ead3e3b65a89f8cab57c2b934c1074aeebda84 | [] | no_license | https://github.com/Nauendorf/fizzbuzz_python | b08d534c0d7b4201548d405c05a3e99436c89833 | 935be824d0238c14c78d5d1937fefd68a6455124 | refs/heads/master | 2020-12-27T01:09:07.645030 | 2020-02-15T11:32:36 | 2020-02-15T11:32:36 | 237,714,334 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # import sys
#
#
# test = sys
#
#
# print([a for a in dir(test)])
# print([a for a in dir(test) if not a.startswith('__')])
# print(', '.join(i for i in dir(sys) if not i.startswith('__')))
import sys
import platform
def getsysinfo():
return [a for a in dir(platform) if not a.startswith('__')
and print(getattr(platform, a)
and print(a))]
print(getsysinfo())
| UTF-8 | Python | false | false | 402 | py | 3 | notes.py | 3 | 0.577114 | 0.577114 | 0 | 20 | 19.1 | 65 |
pecata83/soft-uni-python-solutions | 2,070,174,273,475 | eec18a869c8b9e7e71740088826b767c8bd49d1d | f95e0c64792ff7c00b997bd645181f74b3aa3add | /Python Advanced/01. Stacks and Queues Exercise/04.01.py | 7a7b2eea4a29b0820443893ada929ebd4ad18edb | [] | no_license | https://github.com/pecata83/soft-uni-python-solutions | 6f28fde73ff261c8294c1dd5ea0ad72b6bb4e342 | e9746b4b60e803376e475c1e6638964ca4013849 | refs/heads/main | 2023-02-25T18:01:11.933019 | 2021-02-02T20:49:28 | 2021-02-02T20:49:28 | 329,273,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | clothes_stack = [int(x) for x in input().split()]
rack_capacity = int(input())
current_rack_capacity = rack_capacity
racks_used = 1
while clothes_stack:
cloth = clothes_stack.pop()
if current_rack_capacity >= cloth:
current_rack_capacity -= cloth
else:
racks_used += 1
current_rack_capacity = rack_capacity - cloth
print(racks_used)
| UTF-8 | Python | false | false | 375 | py | 191 | 04.01.py | 190 | 0.650667 | 0.645333 | 0 | 18 | 19.833333 | 53 |
NicolasBerveglieri/STAGEM2 | 1,752,346,688,366 | 2ade4d4346ebd66c6eea1cb589abd69eb6fbcf4b | 537f91bc0a6d0b33550c8378a416c3856e876f9f | /moead_ego.py | e9b30608d3fa9bdf59caad11abf6a45ed71666a0 | [] | no_license | https://github.com/NicolasBerveglieri/STAGEM2 | 69ce502ba52b5e8729e4c969d3a1f08258fe553d | 8119f5e4973b1b2023233bdb0ea5228d50437b00 | refs/heads/master | 2020-03-18T12:24:39.457129 | 2018-10-02T17:09:26 | 2018-10-02T17:09:26 | 134,724,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Wed May 2 15:49:04 2018
@author: nicol
"""
import numpy.linalg as np
from scipy.spatial import distance
import heapq
from random import randint
import random
from random import *
import sys
import sklearn
from sklearn.svm import SVR
import numpy as np
from meoadubqp import *
from expected_improvement import *
from ZDT1_problem import *
from evo_op import *
from Aggreg import *
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import (RBF, Matern, RationalQuadratic,
ExpSineSquared, DotProduct,
ConstantKernel)
import itertools
def moead_EGO(problem,filename,weight_size=24,init_pop=30,update_pop=24,saves=[10,30,70,100,-1]):
current_save=0
save = []
#creation des vecteurs de poids
weights = weight_vectors(weight_size)
solution_size=problem.number_of_variables
#solutions initiales
current_solutions = [[uniform(-100,100) for x in range(0,solution_size)] for y in range(len(weights))]
# leurs valeurs
current_solutionsV = [problem(current_solutions[x]) for x in range(len(current_solutions))]
gp_kernel = 1.0 * RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0))
#debut de la boucle
total_eval = 0 #len(current_solutions)
while(total_eval < 20):
print(total_eval)
total_eval+= 1
if total_eval == saves[current_save]:
save.append(offline_filter([x.tolist() for x in current_solutionsV]))
save[current_save].sort()
save[current_save] = list(save[current_save] for save[current_save],_ in itertools.groupby(save[current_save]))
current_save+=1
gp1 = GaussianProcessRegressor(kernel =gp_kernel)
gp2 = GaussianProcessRegressor(kernel =gp_kernel)
# Fit to data using Maximum Likelihood Estimation of the parameters
if len(current_solutions) < 231:
gp1.fit(current_solutions,[current_solutionsV[x][0] for x in range(len(current_solutions))])
gp2.fit(current_solutions,[current_solutionsV[x][1] for x in range(len(current_solutions))])
else:
print("MAX SOLUTION")
sol_fit = current_solutions[-200:]
solV_fit = current_solutionsV[-200:]
gp1.fit(sol_fit,[solV_fit[x][0] for x in range(len(sol_fit))])
gp2.fit(sol_fit,[solV_fit[x][1] for x in range(len(sol_fit))])
#création des gaussians process
valuesS = []
for i in range(len(weights)):
values = [weighted_sum(weights[i],current_solutionsV[x]) for x in range(len(current_solutionsV))]
# Instanciate a Gaussian Process model
# kernel = C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2))
valuesS += [values]
newsol = moead_EI([gp1,gp2] , valuesS ,problem.number_of_variables,weights)
newsolV = [problem(newsol[x]) for x in range(len(newsol))]
current_solutions += newsol
current_solutionsV += newsolV
big_save(filename,save,current_solutions,current_solutionsV)
return current_solutions, current_solutionsV
| UTF-8 | Python | false | false | 3,424 | py | 96 | moead_ego.py | 13 | 0.605317 | 0.580777 | 0 | 92 | 34.98913 | 123 |
andrewschreiber/agent | 1,915,555,443,579 | 5bee984bf94786b07bae012b1f55c7f5369eda8d | a011e4096ce9635419cd2d19883ccbd979bbb9a3 | /tensorboard/plugins/debugger/debugger_server_test.py | b95f90ff2d6a930ac4222b32f918c1a3ebab250c | [
"Apache-2.0"
] | permissive | https://github.com/andrewschreiber/agent | d9cdd480cb7d7d596095256e223b7b6773ababf5 | 7ad0b37e8ce3ea1f5ff0eac02c23195736ed6f68 | refs/heads/master | 2020-03-31T08:31:13.695921 | 2019-05-07T02:21:50 | 2019-05-07T02:21:50 | 152,060,727 | 16 | 2 | Apache-2.0 | true | 2019-04-29T05:57:49 | 2018-10-08T10:21:50 | 2019-04-02T21:36:16 | 2019-04-29T05:57:48 | 78,607 | 12 | 0 | 1 | Python | false | false | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests the debugger data server, which receives and writes debugger events."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import tensorflow as tf
# pylint: disable=ungrouped-imports, wrong-import-order
from google.protobuf import json_format
from tensorflow.core.debug import debugger_event_metadata_pb2
from tensorboard.compat.proto import event_pb2
from tensorboard.plugins.debugger import constants
from tensorboard.plugins.debugger import debugger_server_lib
from tensorboard.plugins.debugger import numerics_alert
from tensorboard.util import tensor_util
# pylint: enable=ungrouped-imports, wrong-import-order
class FakeEventsWriterManager(object):
"""An events writer manager that tracks events that would be written.
During normal usage, the debugger data server would write events to disk.
Unfortunately, this test cannot depend on TensorFlow's record reader due to
GRPC library conflicts (b/35006065). Hence, we use a fake EventsWriter that
keeps track of events that would be written to disk.
"""
def __init__(self, events_output_list):
"""Constructs a fake events writer, which appends events to a list.
Args:
events_output_list: The list to append events that would be written to
disk.
"""
self.events_written = events_output_list
def dispose(self):
"""Does nothing. This implementation creates no file."""
def write_event(self, event):
"""Pretends to write an event to disk.
Args:
event: The event proto.
"""
self.events_written.append(event)
class DebuggerDataServerTest(tf.test.TestCase):
def setUp(self):
self.events_written = []
events_writer_manager = FakeEventsWriterManager(self.events_written)
self.stream_handler = debugger_server_lib.DebuggerDataStreamHandler(
events_writer_manager=events_writer_manager)
self.stream_handler.on_core_metadata_event(event_pb2.Event())
def tearDown(self):
tf.compat.v1.test.mock.patch.stopall()
def _create_event_with_float_tensor(self, node_name, output_slot, debug_op,
list_of_values):
"""Creates event with float64 (double) tensors.
Args:
node_name: The string name of the op. This lacks both the output slot as
well as the name of the debug op.
output_slot: The number that is the output slot.
debug_op: The name of the debug op to use.
list_of_values: A python list of values within the tensor.
Returns:
A `Event` with a summary containing that node name and a float64
tensor with those values.
"""
event = event_pb2.Event()
value = event.summary.value.add(
tag=node_name,
node_name="%s:%d:%s" % (node_name, output_slot, debug_op),
tensor=tensor_util.make_tensor_proto(
list_of_values, dtype=tf.float64, shape=[len(list_of_values)]))
plugin_content = debugger_event_metadata_pb2.DebuggerEventMetadata(
device="/job:localhost/replica:0/task:0/cpu:0", output_slot=output_slot)
value.metadata.plugin_data.plugin_name = constants.DEBUGGER_PLUGIN_NAME
value.metadata.plugin_data.content = tf.compat.as_bytes(
json_format.MessageToJson(
plugin_content, including_default_value_fields=True))
return event
def _verify_event_lists_have_same_tensor_values(self, expected, gotten):
"""Checks that two lists of events have the same tensor values.
Args:
expected: The expected list of events.
gotten: The list of events we actually got.
"""
self.assertEqual(len(expected), len(gotten))
# Compare the events one at a time.
for expected_event, gotten_event in zip(expected, gotten):
self.assertEqual(expected_event.summary.value[0].node_name,
gotten_event.summary.value[0].node_name)
self.assertAllClose(
tensor_util.make_ndarray(expected_event.summary.value[0].tensor),
tensor_util.make_ndarray(gotten_event.summary.value[0].tensor))
self.assertEqual(expected_event.summary.value[0].tag,
gotten_event.summary.value[0].tag)
def testOnValueEventWritesHealthPill(self):
"""Tests that the stream handler writes health pills in order."""
# The debugger stream handler receives 2 health pill events.
received_events = [
self._create_event_with_float_tensor(
"MatMul", 0, "DebugNumericSummary", list(range(1, 15))),
self._create_event_with_float_tensor(
"add", 0, "DebugNumericSummary", [x * x for x in range(1, 15)]),
self._create_event_with_float_tensor(
"MatMul", 0, "DebugNumericSummary", [x + 42 for x in range(1, 15)]),
]
for event in received_events:
self.stream_handler.on_value_event(event)
# Verify that the stream handler wrote them to disk in order.
self._verify_event_lists_have_same_tensor_values(received_events,
self.events_written)
def testOnValueEventIgnoresIrrelevantOps(self):
"""Tests that non-DebugNumericSummary ops are ignored."""
# Receive a DebugNumericSummary event.
numeric_summary_event = self._create_event_with_float_tensor(
"MatMul", 42, "DebugNumericSummary", list(range(1, 15)))
self.stream_handler.on_value_event(numeric_summary_event)
# Receive a non-DebugNumericSummary event.
self.stream_handler.on_value_event(
self._create_event_with_float_tensor("add", 0, "DebugIdentity",
list(range(1, 15))))
# The stream handler should have only written the DebugNumericSummary event
# to disk.
self._verify_event_lists_have_same_tensor_values([numeric_summary_event],
self.events_written)
def testCorrectStepIsWritten(self):
events_written = []
metadata_event = event_pb2.Event()
metadata_event.log_message.message = json.dumps({"session_run_index": 42})
stream_handler = debugger_server_lib.DebuggerDataStreamHandler(
events_writer_manager=FakeEventsWriterManager(events_written))
stream_handler.on_core_metadata_event(metadata_event)
# The server receives 2 events. It should assign both the correct step.
stream_handler.on_value_event(
self._create_event_with_float_tensor("MatMul", 0, "DebugNumericSummary",
list(range(1, 15))))
stream_handler.on_value_event(
self._create_event_with_float_tensor("Add", 0, "DebugNumericSummary",
list(range(2, 16))))
self.assertEqual(42, events_written[0].step)
self.assertEqual(42, events_written[1].step)
def testSentinelStepValueAssignedWhenExecutorStepCountKeyIsMissing(self):
events_written = []
metadata_event = event_pb2.Event()
metadata_event.log_message.message = json.dumps({})
stream_handler = debugger_server_lib.DebuggerDataStreamHandler(
events_writer_manager=FakeEventsWriterManager(events_written))
stream_handler.on_core_metadata_event(metadata_event)
health_pill_event = self._create_event_with_float_tensor(
"MatMul", 0, "DebugNumericSummary", list(range(1, 15)))
stream_handler.on_value_event(health_pill_event)
self.assertGreater(events_written[0].step, 0)
def testSentinelStepValueAssignedWhenMetadataJsonIsInvalid(self):
events_written = []
metadata_event = event_pb2.Event()
metadata_event.log_message.message = "some invalid JSON string"
stream_handler = debugger_server_lib.DebuggerDataStreamHandler(
events_writer_manager=FakeEventsWriterManager(events_written))
stream_handler.on_core_metadata_event(metadata_event)
health_pill_event = self._create_event_with_float_tensor(
"MatMul", 0, "DebugNumericSummary", list(range(1, 15)))
stream_handler.on_value_event(health_pill_event)
self.assertGreater(events_written[0].step, 0)
def testAlertingEventCallback(self):
numerics_alert_callback = tf.compat.v1.test.mock.Mock()
stream_handler = debugger_server_lib.DebuggerDataStreamHandler(
events_writer_manager=FakeEventsWriterManager(
self.events_written),
numerics_alert_callback=numerics_alert_callback)
stream_handler.on_core_metadata_event(event_pb2.Event())
# The stream handler receives 1 good event and 1 with an NaN value.
stream_handler.on_value_event(
self._create_event_with_float_tensor("Add", 0, "DebugNumericSummary",
[0] * 14))
stream_handler.on_value_event(
self._create_event_with_float_tensor("Add", 0, "DebugNumericSummary", [
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]))
# The second event should have triggered the callback.
numerics_alert_callback.assert_called_once_with(
numerics_alert.NumericsAlert("/job:localhost/replica:0/task:0/cpu:0",
"Add:0", 0, 1, 0, 0))
# The stream handler receives an event with a -Inf value.
numerics_alert_callback.reset_mock()
stream_handler.on_value_event(
self._create_event_with_float_tensor("Add", 0, "DebugNumericSummary", [
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]))
numerics_alert_callback.assert_called_once_with(
numerics_alert.NumericsAlert("/job:localhost/replica:0/task:0/cpu:0",
"Add:0", 0, 0, 1, 0))
# The stream handler receives an event with a +Inf value.
numerics_alert_callback.reset_mock()
stream_handler.on_value_event(
self._create_event_with_float_tensor("Add", 0, "DebugNumericSummary", [
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0
]))
numerics_alert_callback.assert_called_once_with(
numerics_alert.NumericsAlert("/job:localhost/replica:0/task:0/cpu:0",
"Add:0", 0, 0, 0, 1))
# The stream handler receives an event without any pathetic values.
numerics_alert_callback.reset_mock()
stream_handler.on_value_event(
self._create_event_with_float_tensor("Add", 0, "DebugNumericSummary", [
0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0
]))
# assert_not_called is not available in Python 3.4.
self.assertFalse(numerics_alert_callback.called)
if __name__ == "__main__":
tf.test.main()
| UTF-8 | Python | false | false | 11,177 | py | 316 | debugger_server_test.py | 114 | 0.666995 | 0.650264 | 0 | 258 | 42.321705 | 80 |
yb8350/OnrestChatbot | 2,645,699,889,464 | b547bae6649cd987615096fcc12e30ab383830e5 | 17e4570eadefa3fc31a6ff2d9fac113c1f72ece8 | /mrp.py | 673ec84834729d1e66e43b90f981068c7681c87e | [] | no_license | https://github.com/yb8350/OnrestChatbot | 5b12bcff7be25dec4cab928573605bc7327f1d25 | 9d2e85d2fd9bff088e90177b527c8253cf9a8f72 | refs/heads/master | 2023-07-24T18:17:19.940698 | 2021-08-30T16:41:02 | 2021-08-30T16:41:02 | 401,236,264 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | import re
import math
import datetime
import pandas as pd
from konlpy.tag import Komoran
kom = Komoran(userdic='./UserDictionaryData.txt')
SongLocation = pd.read_csv ('./SongLocation.csv')
EmoDic = pd.read_csv ('./EmotionalDictionary.csv')
negative = [('않', 'VX'), ('못하', 'VX'), ('말', 'VX'), ('아니', 'MAG'), ('아니', 'VCN'), ('안', 'MAG'), ('못', 'MAG'), ('지 않', 'EP'),('지 말', 'EP'),('지 못', 'EP'),('지 마', 'EC'),('지 마라', 'EC'),('진 않', 'EP'),('진 말', 'EP'),('진 못', 'EP'),('진 마', 'EC'),('진 마라', 'EC'),('질 않', 'EP'),('질 못', 'EP'),('질 말', 'EP'),('질 마', 'EC'),('질 마라', 'EC')]
emotion = ['XR', 'VA', 'VV', 'VX', 'NNG', 'MAG', 'NNP', 'MM', 'NA']
angle = [75, 45, 15, 345, 315, 285, 255, 225, 195, 165, 135, 105]
ed = {}
for i in range(len(EmoDic)):
ed[(EmoDic.abbr[i], EmoDic.wc[i])] = EmoDic.num[i]
#사용자 감정 분석 함수
def emotionAnalysis(diary):
vector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#1. 영어 제거
diary = re.sub('[^ㄱ-ㅣ 가-힣 \n]+', '', diary)
#2. 형태소 분석
try:
res = kom.pos(diary, flatten=False)
except:
return 0, 0
#3. 부정어 처리
NegSentences = []
d_index = []
for i in range(len(res)):
for j in range(len(res[i])):
if res[i][j] in negative :
NegSentences.append(res[i])
d_index.append(i)
break
d_index.reverse()
if len(d_index) > 0:
for i in d_index:
del res[i]
emo = []
neg = False
for ng in NegSentences :
for i in range(len(ng)):
if ng[i] in negative:
neg = True
if ng[i][1] == 'EC' or ng[i][1] == 'EF':
if len(emo) > 0 and neg == True :
for i in emo:
if i < 6 :
vector[i+6] += 1;
else:
vector[i-6] += 1;
else:
if len(emo) > 0:
for i in emo:
vector[i] += 1;
emo = []
neg = False
elif ng[i] in ed.keys():
emo.append(ed[ng[i]]-1)
#4. 필요없는 품사 제거 + BoW
word = {}
bow = []
for voca in res:
for i in range(len(voca)):
if voca[i][1] in emotion:
if voca[i] not in word.keys():
word[voca[i]] = len(word)
bow.insert(len(word)-1,1)
else:
index = word.get(voca[i])
bow[index] += 1
#5. 감성사전 탐색
for w in word:
if w in ed.keys():
vector[ed[w]-1] += bow[word.get(w)]
#6. 정규화, 좌표값 계산
sum = 0
x = 0
y = 0
for i in vector:
sum += i
if sum == 0 :
return 0, 0
for i in range(12):
vector[i] /= sum
x += vector[i] * math.cos((angle[i]/180) * math.pi)
y += vector[i] * math.sin((angle[i]/180) * math.pi)
x /= 12
y /= 12
return x, y
# 좌표를 통해 감정 카테고리 판단하는 함수
def SelectCategory(x, y):
if x == 0 and y == 0:
return 0
myradians = math.atan2(y, x)
mydegrees = math.degrees(myradians)
if mydegrees >= 60 and mydegrees < 90:
return 1
elif mydegrees >= 30 and mydegrees < 60:
return 2
elif mydegrees >= 0 and mydegrees < 30:
return 3
elif mydegrees >= -30 and mydegrees < 0:
return 4
elif mydegrees >= -60 and mydegrees < -30:
return 5
elif mydegrees >= -90 and mydegrees < -60:
return 6
elif mydegrees >= -120 and mydegrees < -90:
return 7
elif mydegrees >= -150 and mydegrees < -120:
return 8
elif mydegrees >= -180 and mydegrees < -150:
return 9
elif mydegrees >= 150 and mydegrees < 180:
return 10
elif mydegrees >= 120 and mydegrees < 150:
return 11
elif mydegrees >= 90 and mydegrees < 120:
return 12
#감정 분석 결과를 통해 음악 추천 방식을 결정하는 함수
def resultCheck(feelX, feelY, diaryX, diaryY):
check = -1
if diaryX == 0 and diaryY == 0:
if feelX == 0 and feelY == 0:
return check
else:
check = 1
return check
elif feelX == 0 and feelY == 0:
check = 0
return check
feelCateNum = SelectCategory(feelX, feelY)
diaryCateNum = SelectCategory(diaryX, diaryY)
absCateNum = abs(diaryCateNum - feelCateNum)
#1번 카테고리는 2번 카테고리까지만 허용
if diaryCateNum == 1:
if absCateNum == 0 or feelCateNum == 2:
check = 0
# 카테고리가 같거나 양옆까지만 허용
elif absCateNum == 0 or absCateNum == 1:
check = 0
else:
check = 1
return check
#사용자 감정에 가장 근접한 음악 추천 함수
def musicRecommend(diaryX, diaryY):
leng = len(SongLocation)
userCategory = SelectCategory(diaryX, diaryY)
distance = []
for i in range(leng):
songCategory = SongLocation.CategoryNum[i]
dis = round(math.sqrt( math.pow(SongLocation.x[i] - diaryX , 2) + math.pow(SongLocation.y[i] - diaryY , 2)), 5)
distance.append(dis)
SongLocation['distance'] = distance
resultSort = SongLocation.sort_values(by='distance')
resultSort = resultSort.reset_index(drop=True)
result = []
for i in range(leng):
songData = []
if userCategory-1 <= resultSort.CategoryNum[i] and userCategory+1 >= resultSort.CategoryNum[i]:
songData.append(resultSort.SongName[i])
songData.append(resultSort.Singer[i])
songData.append(resultSort.Image[i])
songData.append(resultSort.SongNum[i])
result.append(songData)
if len(result) == 3:
break
return result
#랜덤 음악 추천 함수
def randomMusic(cateNum):
bitMask = SongLocation['CategoryNum'] == cateNum
randomList = SongLocation[bitMask]
playList = randomList.sample(n=3)
# result 추천할 곡의 데이터 리스트 형태
result = []
for i in range(len(playList)):
songList = []
songList.append(playList['SongName'].iloc[i])
songList.append(playList['Singer'].iloc[i])
songList.append(playList['Image'].iloc[i])
songList.append(playList['SongNum'].iloc[i])
result.append(songList)
return result | UTF-8 | Python | false | false | 6,653 | py | 5 | mrp.py | 4 | 0.507916 | 0.477691 | 0 | 216 | 27.953704 | 323 |
wangyum/Anaconda | 6,433,861,015,599 | 468141573796b0dec768be5d8acd772180538fcf | 1dacbf90eeb384455ab84a8cf63d16e2c9680a90 | /lib/python2.7/site-packages/openopt/solvers/CoinOr/ipopt_oo.py | ea4fde06ede58745943b5e9a8817cc2168202fdd | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | permissive | https://github.com/wangyum/Anaconda | ac7229b21815dd92b0bd1c8b7ec4e85c013b8994 | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | refs/heads/master | 2022-10-21T15:14:23.464126 | 2022-10-05T12:10:31 | 2022-10-05T12:10:31 | 76,526,728 | 11 | 10 | Apache-2.0 | false | 2022-10-05T12:10:32 | 2016-12-15T05:26:12 | 2018-10-20T18:15:17 | 2022-10-05T12:10:31 | 935,904 | 10 | 7 | 1 | Python | false | false | from numpy import *
import re
from openopt.kernel.baseSolver import baseSolver
from openopt.kernel.nonOptMisc import Vstack, Find, isspmatrix
#import os
try:
import pyipopt
pyipoptInstalled = True
except:
pyipoptInstalled = False
class ipopt(baseSolver):
__name__ = 'ipopt'
__license__ = "CPL"
__authors__ = 'Carl Laird (Carnegie Mellon University) and Andreas Wachter'
__alg__ = "A. Wachter and L. T. Biegler, On the Implementation of a Primal-Dual Interior Point Filter Line Search Algorithm for Large-Scale Nonlinear Programming, Mathematical Programming 106(1), pp. 25-57, 2006 "
__homepage__ = 'http://www.coin-or.org/'
__info__ = "requires pyipopt made by Eric Xu You"
__optionalDataThatCanBeHandled__ = ['A', 'Aeq', 'b', 'beq', 'lb', 'ub', 'c', 'h']
_canHandleScipySparse = True
# CHECK ME!
#__isIterPointAlwaysFeasible__ = lambda self, p: p.__isNoMoreThanBoxBounded__()
optFile = 'auto'
options = ''
def __init__(self): pass
def __solver__(self, p):
if not pyipoptInstalled:
p.err('you should have pyipopt installed')
# try:
# os.close(1); os.close(2) # may not work for non-Unix OS
# except:
# pass
nvar = p.n
x_L = p.lb
x_U = p.ub
ncon = p.nc + p.nh + p.b.size + p.beq.size
g_L, g_U = zeros(ncon), zeros(ncon)
g_L[:p.nc] = -inf
g_L[p.nc+p.nh:p.nc+p.nh+p.b.size] = -inf
# IPOPT non-linear constraints, both eq and ineq
if p.isFDmodel:
r = []
if p.nc != 0: r.append(p._getPattern(p.user.c))
if p.nh != 0: r.append(p._getPattern(p.user.h))
if p.nb != 0: r.append(p.A)
if p.nbeq != 0: r.append(p.Aeq)
if len(r)>0:
if all([isinstance(elem, ndarray) for elem in r]):
r = vstack(r)
else:
r = Vstack(r)
if isspmatrix(r):
from scipy import __version__
if __version__.startswith('0.7.3') or __version__.startswith('0.7.2') or __version__.startswith('0.7.1') or __version__.startswith('0.7.0'):
p.pWarn('updating scipy to version >= 0.7.4 is very recommended for the problem with the solver IPOPT')
else:
r = array([])
if isspmatrix(r):
I, J, _ = Find(r)
# DON'T remove it!
I, J = array(I, int64), array(J, int64)
elif isinstance(r, ndarray):
if r.size == 0:
I, J= array([], dtype=int64),array([], dtype=int64)
else:
I, J = where(r)
else:
p.disp('unimplemented type:%s' % str(type(r))) # dense matrix?
nnzj = len(I)
else:
I, J = where(ones((ncon, p.n)))
#I, J = None, None
nnzj = ncon * p.n #TODO: reduce it
def eval_g(x):
r = array(())
if p.userProvided.c: r = p.c(x)
if p.userProvided.h: r = hstack((r, p.h(x)))
r = hstack((r, p._get_AX_Less_B_residuals(x), p._get_AeqX_eq_Beq_residuals(x)))
return r
def eval_jac_g(x, flag, userdata = (I, J)):
(I, J) = userdata
if flag and p.isFDmodel:
return (I, J)
r = []
if p.userProvided.c: r.append(p.dc(x))
if p.userProvided.h: r.append(p.dh(x))
if p.nb != 0: r.append(p.A)
if p.nbeq != 0: r.append(p.Aeq)
# TODO: fix it!
if any([isspmatrix(elem) for elem in r]):
r = Vstack([(atleast_2d(elem) if elem.ndim < 2 else elem) for elem in r])
elif len(r)!=0:
r = vstack(r)
if p.isFDmodel:
# TODO: make it more properly
R = (r.tocsr() if isspmatrix(r) else r)[I, J]
if isspmatrix(R):
return R.A
elif isinstance(R, ndarray):
return R
else: p.err('bug in OpenOpt-ipopt connection, inform OpenOpt developers, type(R) = %s' % type(R))
if flag:
return (I, J)
else:
if isspmatrix(r): r = r.A
return r.flatten()
""" This function might be buggy, """ # // comment by Eric
nnzh = 0
def eval_h(lagrange, obj_factor, flag):
return None
# def apply_new(x):
# return True
nlp = pyipopt.create(nvar, x_L, x_U, ncon, g_L, g_U, nnzj, nnzh, p.f, p.df, eval_g, eval_jac_g)
if self.optFile == 'auto':
lines = ['# generated automatically by OpenOpt\n','print_level 0\n']
lines.append('tol ' + str(p.ftol)+ '\n')
lines.append('constr_viol_tol ' + str(p.contol)+ '\n')
lines.append('max_iter ' + str(min(15000, p.maxIter))+ '\n')
if self.options != '' :
for s in re.split(',|;', self.options):
lines.append(s.strip().replace('=', ' ', 1) + '\n')
if p.nc == 0:
lines.append('jac_d_constant yes\n')
if p.nh == 0:
lines.append('jac_c_constant yes\n')
if p.castFrom.lower() in ('lp', 'qp', 'llsp'):
lines.append('hessian_constant yes\n')
ipopt_opt_file = open('ipopt.opt', 'w')
ipopt_opt_file.writelines(lines)
ipopt_opt_file.close()
try:
x, zl, zu, obj = nlp.solve(p.x0)[:4]
if p.point(p.xk).betterThan(p.point(x)):
obj = p.fk
p.xk = p.xk.copy() # for more safety
else:
p.xk, p.fk = x.copy(), obj
if p.istop == 0: p.istop = 1000
finally:
nlp.close()
| UTF-8 | Python | false | false | 6,072 | py | 4,623 | ipopt_oo.py | 3,931 | 0.470191 | 0.459486 | 0 | 169 | 34.91716 | 217 |
devin300team/booking-django | 6,081,673,694,748 | 268d0a32673c22bc062a971934d9ec0954210fc3 | 866acfd3218483c647f1798b9ee386e6c58b8fb8 | /listings/views.py | b50a2282d3a92fbd9e6e13625c9f293cb6790338 | [] | no_license | https://github.com/devin300team/booking-django | 987fe05a5d579084bfcf7122316d38823fa6a301 | 274c5d3edd1783bc4890761c8cc8dc6b38af0d22 | refs/heads/main | 2023-05-01T20:20:54.067353 | 2021-05-25T03:36:00 | 2021-05-25T03:36:00 | 370,549,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import json
from django.core.serializers import serialize
from rest_framework.response import Response
from .serializers import ListingSerializer, BookingInfoSerializer
from .models import Listing, BookingInfo
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from django.http import JsonResponse
from datetime import datetime
class ListingView(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Listing.objects.all()
serializer_class = ListingSerializer
def get(self, request, *args, **kwargs):
Listings = Listing.objects.all()
BookingInfos = BookingInfo.objects.all()
JsonListings = json.loads(serialize("json", Listings))
data = []
check_in = request.GET['check_in']
check_out = request.GET['check_out']
max_price = request.GET['max_price']
for each in BookingInfos:
for obj in JsonListings:
if each.id == obj["fields"]["blocksday"]:
# datetime.strptime(obj["fields"]["blockdays_start"], "%Y-%m-%d").strftime("%d-%m-%Y")
if int(max_price) >= int(each.price):
data.append({"listing_type": obj["fields"]["listing_type"],
"title": obj["fields"]["title"],
"country": obj["fields"]["country"],
"city": obj["fields"]["city"],
"price": each.price })
data = sorted(data, key=lambda k: int(k['price']), reverse=False)
return JsonResponse({"items": data}, content_type='application/json')
# return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class ListingDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Listing.objects.all()
serializer_class = ListingSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs) | UTF-8 | Python | false | false | 2,556 | py | 9 | views.py | 9 | 0.606025 | 0.606025 | 0 | 60 | 41.616667 | 106 |
Ganna05/Python-algorithms-and-structures | 13,082,470,418,990 | 81500c1173c89af0749960c4d0143b221ca2b55f | adff07e71383be3f2549f40822c1fc6adfad6742 | /Lesson 3. Task 2.py | a4290b615209a5f469561df57f5f66be990ebec6 | [] | no_license | https://github.com/Ganna05/Python-algorithms-and-structures | 193c8ea2d77c8760014c3d735d254736a8e2fc9c | dfe60aef61b9e41c90c2afb1b0e2f9751709f8bd | refs/heads/master | 2020-04-15T02:33:23.198706 | 2019-01-27T14:40:19 | 2019-01-27T14:40:19 | 164,318,872 | 0 | 0 | null | false | 2019-02-10T10:32:38 | 2019-01-06T15:14:41 | 2019-01-27T14:40:22 | 2019-02-10T10:29:18 | 12 | 0 | 0 | 2 | Python | false | null | # 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями 8, 3, 15, 6, 4, 2,
# то во второй массив надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация начинается с нуля),
# т.к. именно в этих позициях первого массива стоят четные числа.
import random
SIZE = 10
min_item = 2
max_item = 100
array_1 = [random.randint(min_item, max_item) for _ in range(SIZE)]
ar_index = []
for i in range(len(array_1)):
if array_1[i] % 2 == 0:
ar_index.append(i)
# Вывод на экран результата
print(f'Дан массив чисел {array_1}')
print('Необходимо вывести индексы четных чисел в массиве.')
print(f'В данном массиве четные числа расположены под индексами {ar_index}')
| UTF-8 | Python | false | false | 1,080 | py | 9 | Lesson 3. Task 2.py | 8 | 0.708672 | 0.670732 | 0 | 20 | 35.9 | 133 |
openstack/horizon | 9,534,827,445,672 | 8c8cab23f9bb0be4f2fc04d750ff723a0421104d | 69d8d91954f6623f3674d52d734d589f72383628 | /openstack_dashboard/dashboards/project/floating_ips/tests.py | ecaff90481d0709f90302a86cf2a22d002584c3e | [
"Apache-2.0"
] | permissive | https://github.com/openstack/horizon | d031cebe126c06ad9717bbc52790b3d890e8661e | 7896fd8c77a6766a1156a520946efaf792b76ca5 | refs/heads/master | 2023-09-04T06:57:58.069907 | 2023-09-01T20:17:10 | 2023-09-01T20:17:10 | 2,665,166 | 1,060 | 1,175 | Apache-2.0 | false | 2023-08-07T02:33:44 | 2011-10-28T13:12:05 | 2023-07-28T08:39:05 | 2023-08-06T07:39:56 | 354,181 | 1,303 | 1,250 | 0 | Python | false | false | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from django.urls import reverse
from django.utils.http import urlencode
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
from openstack_dashboard.usage import quotas
from horizon.workflows import views
INDEX_URL = reverse('horizon:project:floating_ips:index')
NAMESPACE = "horizon:project:floating_ips"
class FloatingIpViewTests(test.TestCase):
def setUp(self):
super().setUp()
api_mock = mock.patch.object(
api.neutron,
'is_extension_floating_ip_port_forwarding_supported').start()
api_mock.return_value = True
@test.create_mocks({api.neutron: ('floating_ip_target_list',
'tenant_floating_ip_list')})
def test_associate(self):
self.mock_floating_ip_target_list.return_value = \
self._get_fip_targets()
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
url = reverse('%s:associate' % NAMESPACE)
res = self.client.get(url)
self.assertTemplateUsed(res, views.WorkflowView.template_name)
workflow = res.context['workflow']
choices = dict(workflow.steps[0].action.fields['ip_id'].choices)
# Verify that our "associated" floating IP isn't in the choices list.
self.assertNotIn(self.floating_ips.first(), choices)
self.mock_floating_ip_target_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
@test.create_mocks({api.neutron: ('floating_ip_target_list_by_instance',
'tenant_floating_ip_list')})
def test_associate_with_instance_id(self):
targets = self._get_fip_targets()
target = targets[0]
self.mock_floating_ip_target_list_by_instance.return_value = [target]
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
base_url = reverse('%s:associate' % NAMESPACE)
params = urlencode({'instance_id': target.instance_id})
url = '?'.join([base_url, params])
res = self.client.get(url)
self.assertTemplateUsed(res, views.WorkflowView.template_name)
workflow = res.context['workflow']
choices = dict(workflow.steps[0].action.fields['ip_id'].choices)
# Verify that our "associated" floating IP isn't in the choices list.
self.assertNotIn(self.floating_ips.first(), choices)
self.mock_floating_ip_target_list_by_instance.assert_called_once_with(
test.IsHttpRequest(), target.instance_id)
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
def _get_compute_ports(self):
return [p for p in self.ports.list()
if not p.device_owner.startswith('network:')]
def _get_fip_targets(self):
server_dict = dict((s.id, s.name) for s in self.servers.list())
targets = []
for p in self._get_compute_ports():
for ip in p.fixed_ips:
targets.append(api.neutron.FloatingIpTarget(
p, ip['ip_address'], server_dict.get(p.device_id)))
targets[-1].port_forwardings = []
return targets
@staticmethod
def _get_target_id(port):
return '%s_%s' % (port.id, port.fixed_ips[0]['ip_address'])
@test.create_mocks({api.neutron: ('floating_ip_target_list',
'tenant_floating_ip_list')})
def test_associate_with_port_id(self):
compute_port = self._get_compute_ports()[0]
associated_fips = [fip.id for fip in self.floating_ips.list()
if fip.port_id]
self.mock_floating_ip_target_list.return_value = \
self._get_fip_targets()
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
base_url = reverse('%s:associate' % NAMESPACE)
params = urlencode({'port_id': compute_port.id})
url = '?'.join([base_url, params])
res = self.client.get(url)
self.assertTemplateUsed(res, views.WorkflowView.template_name)
workflow = res.context['workflow']
choices = dict(workflow.steps[0].action.fields['ip_id'].choices)
# Verify that our "associated" floating IP isn't in the choices list.
self.assertFalse(set(associated_fips) & set(choices.keys()))
self.mock_floating_ip_target_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
@test.create_mocks({api.neutron: ('floating_ip_associate',
'floating_ip_target_list',
'tenant_floating_ip_list')})
def test_associate_post(self):
floating_ip = [fip for fip in self.floating_ips.list()
if not fip.port_id][0]
compute_port = self._get_compute_ports()[0]
port_target_id = self._get_target_id(compute_port)
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
self.mock_floating_ip_target_list.return_value = \
self._get_fip_targets()
self.mock_floating_ip_associate.return_value = None
form_data = {'port_id': port_target_id,
'ip_id': floating_ip.id}
url = reverse('%s:associate' % NAMESPACE)
res = self.client.post(url, form_data)
self.assertRedirectsNoFollow(res, INDEX_URL)
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_target_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_associate.assert_called_once_with(
test.IsHttpRequest(), floating_ip.id, port_target_id)
@test.create_mocks({api.neutron: ('floating_ip_associate',
'floating_ip_target_list',
'tenant_floating_ip_list')})
def test_associate_post_with_redirect(self):
floating_ip = [fip for fip in self.floating_ips.list()
if not fip.port_id][0]
compute_port = self._get_compute_ports()[0]
port_target_id = self._get_target_id(compute_port)
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
self.mock_floating_ip_target_list.return_value = \
self._get_fip_targets()
self.mock_floating_ip_associate.return_value = None
next = reverse("horizon:project:instances:index")
form_data = {'port_id': port_target_id,
'next': next,
'ip_id': floating_ip.id}
url = reverse('%s:associate' % NAMESPACE)
res = self.client.post(url, form_data)
self.assertRedirectsNoFollow(res, next)
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_target_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_associate.assert_called_once_with(
test.IsHttpRequest(), floating_ip.id, port_target_id)
@test.create_mocks({api.neutron: ('floating_ip_associate',
'floating_ip_target_list',
'tenant_floating_ip_list')})
def test_associate_post_with_exception(self):
floating_ip = [fip for fip in self.floating_ips.list()
if not fip.port_id][0]
compute_port = self._get_compute_ports()[0]
port_target_id = self._get_target_id(compute_port)
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
self.mock_floating_ip_target_list.return_value = \
self._get_fip_targets()
self.mock_floating_ip_associate.side_effect = self.exceptions.nova
form_data = {'port_id': port_target_id,
'ip_id': floating_ip.id}
url = reverse('%s:associate' % NAMESPACE)
res = self.client.post(url, form_data)
self.assertRedirectsNoFollow(res, INDEX_URL)
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_target_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_associate.assert_called_once_with(
test.IsHttpRequest(), floating_ip.id, port_target_id)
@test.create_mocks({api.nova: ('server_list',),
api.neutron: ('floating_ip_disassociate',
'floating_ip_pools_list',
'floating_ip_port_forwarding_list',
'is_extension_supported',
'tenant_floating_ip_list')})
def test_disassociate_post(self):
floating_ip = self.floating_ips.first()
self.mock_is_extension_supported.return_value = False
self.mock_floating_ip_port_forwarding_list.return_value = []
self.mock_server_list.return_value = [self.servers.list(), False]
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
self.mock_floating_ip_pools_list.return_value = self.pools.list()
self.mock_floating_ip_disassociate.return_value = None
action = "floating_ips__disassociate__%s" % floating_ip.id
res = self.client.post(INDEX_URL, {"action": action})
self.assertMessageCount(success=1)
self.assertRedirectsNoFollow(res, INDEX_URL)
self.mock_server_list.assert_called_once_with(test.IsHttpRequest(),
detailed=False)
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_pools_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_disassociate.assert_called_once_with(
test.IsHttpRequest(), floating_ip.id)
self.mock_is_extension_supported.assert_called_once_with(
test.IsHttpRequest(), 'dns-integration')
@test.create_mocks({api.nova: ('server_list',),
api.neutron: ('floating_ip_disassociate',
'floating_ip_port_forwarding_list',
'floating_ip_pools_list',
'is_extension_supported',
'tenant_floating_ip_list')})
def test_disassociate_post_with_exception(self):
floating_ip = self.floating_ips.first()
self.mock_is_extension_supported.return_value = False
self.mock_floating_ip_port_forwarding_list.return_value = []
self.mock_server_list.return_value = [self.servers.list(), False]
self.mock_tenant_floating_ip_list.return_value = \
self.floating_ips.list()
self.mock_floating_ip_pools_list.return_value = self.pools.list()
self.mock_floating_ip_disassociate.side_effect = self.exceptions.nova
action = "floating_ips__disassociate__%s" % floating_ip.id
res = self.client.post(INDEX_URL, {"action": action})
self.assertRedirectsNoFollow(res, INDEX_URL)
self.mock_server_list.assert_called_once_with(test.IsHttpRequest(),
detailed=False)
self.mock_tenant_floating_ip_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_pools_list.assert_called_once_with(
test.IsHttpRequest())
self.mock_floating_ip_disassociate.assert_called_once_with(
test.IsHttpRequest(), floating_ip.id)
self.mock_is_extension_supported.assert_called_once_with(
test.IsHttpRequest(), 'dns-integration')
@test.create_mocks({api.neutron: ('tenant_floating_ip_list',
'is_extension_supported',
'floating_ip_port_forwarding_list',
'floating_ip_pools_list'),
api.nova: ('server_list',),
quotas: ('tenant_quota_usages',)})
def test_allocate_button_attributes(self):
floating_ips = self.floating_ips.list()
floating_pools = self.pools.list()
quota_data = self.neutron_quota_usages.first()
self.mock_is_extension_supported.return_value = False
self.mock_tenant_floating_ip_list.return_value = floating_ips
self.mock_floating_ip_port_forwarding_list.return_value = []
self.mock_floating_ip_pools_list.return_value = floating_pools
self.mock_server_list.return_value = [self.servers.list(), False]
self.mock_tenant_quota_usages.return_value = quota_data
res = self.client.get(INDEX_URL)
allocate_action = self.getAndAssertTableAction(res, 'floating_ips',
'allocate')
self.assertEqual(set(['ajax-modal']), set(allocate_action.classes))
self.assertEqual('Allocate IP To Project', allocate_action.verbose_name)
self.assertIsNone(allocate_action.policy_rules)
url = 'horizon:project:floating_ips:allocate'
self.assertEqual(url, allocate_action.url)
self.mock_tenant_floating_ip_list.assert_called_with(
test.IsHttpRequest())
self.mock_floating_ip_pools_list.assert_called_with(
test.IsHttpRequest())
self.mock_server_list.assert_called_once_with(test.IsHttpRequest(),
detailed=False)
self.assert_mock_multiple_calls_with_same_arguments(
self.mock_tenant_quota_usages, 3,
mock.call(test.IsHttpRequest(), targets=('floatingip', )))
self.mock_is_extension_supported.assert_called_once_with(
test.IsHttpRequest(), 'dns-integration',
)
@test.create_mocks({api.neutron: ('tenant_floating_ip_list',
'is_extension_supported',
'floating_ip_port_forwarding_list',
'floating_ip_pools_list'),
api.nova: ('server_list',),
quotas: ('tenant_quota_usages',)})
def test_allocate_button_disabled_when_quota_exceeded(self):
floating_ips = self.floating_ips.list()
floating_pools = self.pools.list()
quota_data = self.neutron_quota_usages.first()
quota_data['floatingip']['available'] = 0
self.mock_is_extension_supported.return_value = False
self.mock_tenant_floating_ip_list.return_value = floating_ips
self.mock_floating_ip_port_forwarding_list.return_value = []
self.mock_floating_ip_pools_list.return_value = floating_pools
self.mock_server_list.return_value = [self.servers.list(), False]
self.mock_tenant_quota_usages.return_value = quota_data
res = self.client.get(INDEX_URL)
allocate_action = self.getAndAssertTableAction(res, 'floating_ips',
'allocate')
self.assertIn('disabled', allocate_action.classes,
'The create button should be disabled')
self.assertEqual('Allocate IP To Project (Quota exceeded)',
allocate_action.verbose_name)
self.mock_tenant_floating_ip_list.assert_called_with(
test.IsHttpRequest())
self.mock_floating_ip_pools_list.assert_called_with(
test.IsHttpRequest())
self.mock_server_list.assert_called_once_with(test.IsHttpRequest(),
detailed=False)
self.assert_mock_multiple_calls_with_same_arguments(
self.mock_tenant_quota_usages, 3,
mock.call(test.IsHttpRequest(), targets=('floatingip', )))
self.mock_is_extension_supported.assert_called_once_with(
test.IsHttpRequest(), 'dns-integration',
)
@test.create_mocks({api.neutron: ('floating_ip_pools_list',
'is_extension_supported'),
quotas: ('tenant_quota_usages',)})
@test.update_settings(OPENSTACK_NEUTRON_NETWORK={'enable_quotas': True})
def test_correct_quotas_displayed(self):
self.mock_is_extension_supported.side_effect = [False, True, False]
self.mock_tenant_quota_usages.return_value = \
self.neutron_quota_usages.first()
self.mock_floating_ip_pools_list.return_value = self.pools.list()
url = reverse('%s:allocate' % NAMESPACE)
res = self.client.get(url)
self.assertEqual(res.context['usages']['floatingip']['quota'],
self.neutron_quotas.first().get('floatingip').limit)
self.mock_is_extension_supported.assert_called_once_with(
test.IsHttpRequest(), 'dns-integration')
self.mock_tenant_quota_usages.assert_called_once_with(
test.IsHttpRequest(), targets=('floatingip',))
self.mock_floating_ip_pools_list.assert_called_once_with(
test.IsHttpRequest())
| UTF-8 | Python | false | false | 18,370 | py | 2,064 | tests.py | 1,011 | 0.601361 | 0.599565 | 0 | 388 | 46.345361 | 80 |
seer-group/Robokit_TCP_API_py | 10,256,381,914,790 | 3de4c836ce118267b15478ec09a3bd78d52ce990 | c0151d01bdedd17484b4f3d83bfc77ca7b39f2c9 | /rbkApiCopyFile.py | 49bedbab4d75e38204ae1325ccd45707a800ba03 | [] | no_license | https://github.com/seer-group/Robokit_TCP_API_py | 5e9f369fcabd6ab262da26e52af0e3f8bfb0eef7 | a407ea56767ec50cfea4ed301a6c2c9894de3845 | refs/heads/master | 2022-12-13T02:42:52.794738 | 2018-03-21T06:08:47 | 2018-03-21T06:08:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from rbkNetProtoEnums import *
import rbkNetProtoEnums
import json
import socket
import os
so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
so.settimeout(2)
#so.connect(('192.168.4.109', API_PORT_STATE))
so.connect(('192.168.192.5', API_PORT_ROBOD))
so.send(packMsg(1, robot_daemon_scp_req, {
"path": '/log', "filename": 'robokit_2018 - 01 - 29_12 - 49 - 01.109.log'}))
data = so.recv(16)
jsonDataLen = 0
if(len(data) < 16):
print('pack head error')
os.system('pause')
so.close()
quit()
else:
jsonDataLen = unpackHead(data)
data = so.recv(1024)
logfile = open('log.zip', 'wb')
logfile.write(data)
logfile.close()
os.system('pause')
so.close()
| UTF-8 | Python | false | false | 683 | py | 15 | rbkApiCopyFile.py | 14 | 0.666179 | 0.5959 | 0 | 32 | 20.34375 | 84 |
tireub/Chromaffin | 14,491,219,659,008 | 60fe9696164535111da5ca0eadaaa7487ea51763 | 79f1eafcfa8089615bdcc0cc2048e10826a9c2f3 | /Models.py | c5d9ea609d7e5cbaee1e392c65014f492b89eb4d | [] | no_license | https://github.com/tireub/Chromaffin | b35a1890c603aeff523f33afa235dc52eec68ca9 | 56ddec1cc988a4a8361a46c8da7d4ce6d95f2d54 | refs/heads/master | 2020-04-05T05:11:11.352452 | 2018-12-27T11:23:45 | 2018-12-27T11:23:45 | 156,584,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from sqlalchemy import Column, Integer, String, Date, ForeignKey, DECIMAL
from sqlalchemy.orm import relationship
from Base import Base
class Cell(Base):
__tablename__ = 'cell'
id = Column(Integer, primary_key=True)
name = Column(String(100))
date = Column(Date)
stimulation_time = Column(Integer)
stimulation_type_id = Column(Integer, ForeignKey("stimulation_type.id"))
stimulation_type = relationship("StimulationType")
vesicles = relationship("Vesicle", back_populates="cell")
membranes = relationship("MembranePoint", back_populates="cell")
def __init__(self, name, date):
self.name = name
self.date = date
class StimulationType(Base):
__tablename__ = "stimulation_type"
id = Column(Integer, primary_key=True)
chemical = Column(String(100))
def __init__(self, chemical):
self.chemical = chemical
class MembranePoint(Base):
__tablename__ = "membrane_point"
id = Column(Integer, primary_key=True)
cell_id = Column(Integer, ForeignKey("cell.id"))
cell = relationship("Cell", back_populates="membranes")
x = Column(DECIMAL(6,4))
y = Column(DECIMAL(6,4))
def __init__(self, cell_id, x, y):
self.cell_id = cell_id
self.x = x
self.y = y
class Vesicle(Base):
__tablename__ = "vesicle"
id = Column(Integer, primary_key=True)
track_duration = Column(Integer)
cell_id = Column(Integer, ForeignKey("cell.id"))
cell = relationship("Cell", back_populates="vesicles")
behaviour = relationship("VesicleBehaviour", back_populates="vesicle")
positions = relationship("Position", back_populates="vesicle")
def __init__(self, duration, cell):
self.track_duration = duration
self.cell = cell
class BehaviourType(Base):
__tablename__ = "behaviour_type"
id = Column(Integer, primary_key=True)
type = Column(String(20))
def __init__(self, type):
self.type = type
class VesicleBehaviour(Base):
__tablename__ = "vesicle_behaviour"
vesicle_id = Column(Integer, ForeignKey("vesicle.id"), primary_key=True)
vesicle = relationship("Vesicle", back_populates="behaviour")
time_status = Column(Integer, primary_key=True)
behaviour_type_id = Column(Integer, ForeignKey("behaviour_type.id"))
behaviour_type = relationship("BehaviourType")
def __init__(self, vesicle, time):
self.vesicle = vesicle
self.time_status = time
class MSD(Base):
__tablename__ = "msd"
vesicle_id = Column(Integer, ForeignKey("vesicle.id"), primary_key=True)
vesicle = relationship("Vesicle")
deltat = Column(Integer, primary_key=True)
before_after_stimu = Column(Integer, primary_key=True)
value = Column(DECIMAL(8,6))
def __init__(self, vesicle, deltat, value, beforeafter):
self.vesicle = vesicle
self.before_after_stimu = beforeafter
self.deltat = deltat
self.value = value
class Position(Base):
__tablename__ = "position"
id = Column(Integer, primary_key=True)
x = Column(DECIMAL(6,4))
y = Column(DECIMAL(6,4))
z = Column(DECIMAL(6,4))
t = Column(Integer)
vesicle_id = Column(Integer, ForeignKey("vesicle.id"))
vesicle = relationship("Vesicle", back_populates="positions")
membrane_point_id = Column(Integer, ForeignKey("membrane_point.id"))
membrane_point = relationship("MembranePoint")
distance = Column(DECIMAL(6,4))
def __init__(self, vesicle, x, y, z, t):
self.vesicle = vesicle
self.x = x
self.y = y
self.z = z
self.t = t
| UTF-8 | Python | false | false | 3,608 | py | 24 | Models.py | 21 | 0.646341 | 0.640244 | 0 | 123 | 28.317073 | 76 |
Prorok1015/Summary | 9,131,100,475,899 | 00dfc66e2341af153ea28d0c28607ad2bd024fb2 | 99ab6f0e9efcd67be68125f04f4229c0f5b698be | /script/PageAlgoritm.py | da8014e6cc6f47c2c9f3d475f90d17ebd3e91355 | [] | no_license | https://github.com/Prorok1015/Summary | 516c7c0d55b9cd4a2c4de4f5dc1d98aa794f9d3c | 51ac376f5aa7f8de545a648e60c5be3bf2cb0c39 | refs/heads/master | 2022-11-07T06:57:56.166778 | 2020-06-22T12:20:50 | 2020-06-22T12:20:50 | 251,022,376 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from wiki.models import settingUser, Page, PageStatmant, randomUnicalPage
class Algoritm():
hour = 0
def do(self):
self.hour += 1
settings = settingUser.objects.all()
for setting in settings:
if settingUser.One_hour == setting.Time_to_new_page:
PageStatmant.objects.create(User = setting.User, Pages = randomUnicalPage(User=setting.User))
if settingUser.Two_hour == setting.Time_to_new_page:
if self.hour%2 == 0:
PageStatmant.objects.create(User = setting.User, Pages = randomUnicalPage(User=setting.User))
if settingUser.Six_hour == setting.Time_to_new_page:
if self.hour%6 == 0:
PageStatmant.objects.create(User = setting.User, Pages = randomUnicalPage(User=setting.User))
if settingUser.One_day == setting.Time_to_new_page:
if self.hour == 24:
PageStatmant.objects.create(User = setting.User, Pages = randomUnicalPage(User=setting.User))
if self.hour == 24:
self.hour = 0
| UTF-8 | Python | false | false | 1,146 | py | 31 | PageAlgoritm.py | 18 | 0.582897 | 0.573298 | 0 | 29 | 38.310345 | 113 |
QCAPI-DRIP/DRIP | 15,238,544,011,700 | e39729ad81dc1edc71e74bd4051bdb3dcafb0577 | 5836cc43cd4ee1bcf22e168eba6a7539d0876b3b | /drip_parser/src/rpc_server.py | eb44724b1f77e7753bba605fab21932191fbe488 | [
"Apache-2.0"
] | permissive | https://github.com/QCAPI-DRIP/DRIP | d2ce1816a6b0aeda0cac44d7763cadf0c5999941 | 57a8fd69327f38805597a3c040938206b9728048 | refs/heads/master | 2020-04-06T14:46:01.628824 | 2018-11-14T13:30:41 | 2018-11-14T13:30:41 | 157,553,634 | 0 | 0 | Apache-2.0 | true | 2018-11-14T13:34:08 | 2018-11-14T13:34:08 | 2018-11-14T13:33:53 | 2018-11-14T13:30:42 | 134,680 | 0 | 0 | 0 | null | false | null | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
import os
import os.path
import pika
import sys
import tempfile
import time
import json
import yaml
from transformer.docker_compose_transformer import *
from os.path import expanduser
def init_chanel(args):
if len(args) > 1:
rabbitmq_host = args[1]
queue_name = args[2] #tosca_2_docker_compose_queue
else:
rabbitmq_host = '127.0.0.1'
connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host))
channel = connection.channel()
channel.queue_declare(queue=queue_name)
return channel
def start(channel):
channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue=queue_name)
print(" [x] Awaiting RPC requests")
channel.start_consuming()
def on_request(ch, method, props, body):
response = handle_delivery(body)
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id=\
props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag=method.delivery_tag)
def handle_delivery(message):
parsed_json_message = json.loads(message)
params = parsed_json_message["parameters"]
param = params[0]
value = yaml.load(param['value'])
tosca_file_name = param["name"]
current_milli_time = lambda: int(round(time.time() * 1000))
try:
tosca_file_path = tempfile.gettempdir() + "/transformer_files/" + str(current_milli_time()) + "/"
except NameError:
import sys
tosca_file_path = os.path.dirname(os.path.abspath(sys.argv[0])) + "/transformer_files/" + str(current_milli_time()) + "/"
if not os.path.exists(tosca_file_path):
os.makedirs(tosca_file_path)
with open(tosca_file_path + "/" + tosca_file_name + ".yml", 'w') as outfile:
outfile.write(str(value))
if queue_name == "tosca_2_docker_compose_queue":
transformer = DockerComposeTransformer(tosca_file_path + "/" + tosca_file_name + ".yml");
compose = transformer.getnerate_compose('3.3')
response = {}
current_milli_time = lambda: int(round(time.time() * 1000))
response["creationDate"] = current_milli_time()
response["parameters"] = []
parameter = {}
parameter['value'] = str(yaml.dump(compose))
parameter['name'] = 'docker-compose.yml'
parameter['encoding'] = 'UTF-8'
response["parameters"].append(parameter)
print ("Output message: %s" % json.dumps(response))
return response
def test_local():
home = expanduser("~")
transformer = DockerComposeTransformer(home+"/Downloads/tosca.yml")
vresion = '2';
compose = transformer.getnerate_compose(vresion)
print yaml.dump(compose)
with open(home+'/Downloads/docker-compose.yml', 'w') as outfile:
yaml.dump(compose, outfile, default_flow_style=False)
# response = {}
# current_milli_time = lambda: int(round(time.time() * 1000))
# response["creationDate"] = current_milli_time()
# response["parameters"] = []
#
# parameter = {}
# parameter['value'] = str(yaml.dump(compose))
# parameter['name'] = 'docker-compose.yml'
# parameter['encoding'] = 'UTF-8'
# response["parameters"].append(parameter)
# print response
if __name__ == "__main__":
if(sys.argv[1] == "test_local"):
test_local()
else:
print sys.argv
channel = init_chanel(sys.argv)
global queue_name
queue_name = sys.argv[2]
start(channel)
# try:
## for node in tosca.nodetemplates:
## print "Name %s Type: %s " %(node.name,node.type)
##
## for input in tosca.inputs:
## print input.name
#
## for node in tosca.nodetemplates:
## for relationship, trgt in node.relationships.items():
## rel_template = trgt.get_relationship_template()
## for rel in rel_template:
## print "source %s Relationship: %s target: %s" %(rel.source.type,rel.type,rel.target.type)
## print dir(rel)
# response = {}
# current_milli_time = lambda: int(round(time.time() * 1000))
# response["creationDate"] = current_milli_time()
# response["parameters"] = []
# vm_nodes = []
#
# for node in tosca.nodetemplates:
# if not node.relationships.items() and 'docker' in node.type.lower():
# print "1Adding: %s , %s" %(node.name,node.type)
# vm_nodes.append(node)
## else:
# for relationship, trgt in node.relationships.items():
# if relationship.type == EntityType.HOSTEDON:
# rel_template = trgt.get_relationship_template()
# for rel in rel_template:
# print "2Adding: %s , %s" %(rel.target.name,rel.target.type)
## print "Name: %s Type: %s " %(node.name, node.type)
# vm_nodes.append(rel.target)
#
#
## if not compute_nodes:
## for node in tosca.nodetemplates:
### print dir(node)
## print "Name: %s Type: %s props: %s"%(node.name,node.type,node.get_properties().keys())
#
# for vm in vm_nodes:
# result = {}
# parameter = {}
# result['name'] = vm.name
# result['size'] = 'Medium'
# if 'dockers' in vm.get_properties():
# result['docker'] = vm.get_properties()['dockers'].value
# elif 'artifacts' in vm.templates[next(iter(vm.templates))]:
# artifacts = vm.templates[next(iter(vm.templates))]['artifacts']
# result['docker'] = artifacts['docker_image']['file']
## print "1st Key: %s" %next(iter(vm.templates))
## print vm.templates[next(iter(vm.templates))]
#
## print dir(compute_node.get_properties()['dockers'] )
## print "dockers. Name: %s Type: %s Value: %s" % (compute_node.get_properties()['dockers'].name, compute_node.get_properties()['dockers'].type, compute_node.get_properties()['dockers'].value )
# parameter['value'] = str(json.dumps(result))
# parameter['attributes'] = 'null'
# parameter["url"] = "null"
# parameter["encoding"] = "UTF-8"
# response["parameters"].append(parameter)
## print "Name: %s Type: %s properties: %s" %(vm.name,vm.type,vm.get_properties().keys())
##
# print ("Output message: %s" % json.dumps(response))
#
# except AttributeError as e:
# z = e
# print z
| UTF-8 | Python | false | false | 7,015 | py | 199 | rpc_server.py | 128 | 0.571205 | 0.56536 | 0 | 180 | 37.811111 | 204 |
jfangwpi/Interactive_planning_and_sensing | 9,294,309,255,955 | 729484341a57bc2f5da26f57d3b33f04c3363824 | 881067724ddcf277c21854f647eaa56054944e15 | /src/lcmtypes/python/graph_data/map_data.py | 03d8d3f576c3f61116955b7b8dfafda67634be9c | [
"MIT"
] | permissive | https://github.com/jfangwpi/Interactive_planning_and_sensing | 004d58ccdcaa1178e24a1186119e862e86afbf3f | 00042c51c2fdc020b7b1c184286cf2b513ed9096 | refs/heads/master | 2023-02-13T03:13:46.496128 | 2020-05-29T18:24:49 | 2020-05-29T18:24:49 | 267,086,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """LCM type definitions
This file automatically generated by lcm.
DO NOT MODIFY BY HAND!!!!
"""
try:
import cStringIO.StringIO as BytesIO
except ImportError:
from io import BytesIO
import struct
import graph_data.vertex_data
class map_data(object):
__slots__ = ["num_v_", "vertex_"]
__typenames__ = ["int64_t", "graph_data.vertex_data"]
__dimensions__ = [None, ["num_v_"]]
def __init__(self):
self.num_v_ = 0
self.vertex_ = []
def encode(self):
buf = BytesIO()
buf.write(map_data._get_packed_fingerprint())
self._encode_one(buf)
return buf.getvalue()
def _encode_one(self, buf):
buf.write(struct.pack(">q", self.num_v_))
for i0 in range(self.num_v_):
assert self.vertex_[i0]._get_packed_fingerprint() == graph_data.vertex_data._get_packed_fingerprint()
self.vertex_[i0]._encode_one(buf)
def decode(data):
if hasattr(data, 'read'):
buf = data
else:
buf = BytesIO(data)
if buf.read(8) != map_data._get_packed_fingerprint():
raise ValueError("Decode error")
return map_data._decode_one(buf)
decode = staticmethod(decode)
def _decode_one(buf):
self = map_data()
self.num_v_ = struct.unpack(">q", buf.read(8))[0]
self.vertex_ = []
for i0 in range(self.num_v_):
self.vertex_.append(graph_data.vertex_data._decode_one(buf))
return self
_decode_one = staticmethod(_decode_one)
_hash = None
def _get_hash_recursive(parents):
if map_data in parents: return 0
newparents = parents + [map_data]
tmphash = (0x1b4d686d48fd87f0+ graph_data.vertex_data._get_hash_recursive(newparents)) & 0xffffffffffffffff
tmphash = (((tmphash<<1)&0xffffffffffffffff) + (tmphash>>63)) & 0xffffffffffffffff
return tmphash
_get_hash_recursive = staticmethod(_get_hash_recursive)
_packed_fingerprint = None
def _get_packed_fingerprint():
if map_data._packed_fingerprint is None:
map_data._packed_fingerprint = struct.pack(">Q", map_data._get_hash_recursive([]))
return map_data._packed_fingerprint
_get_packed_fingerprint = staticmethod(_get_packed_fingerprint)
| UTF-8 | Python | false | false | 2,289 | py | 181 | map_data.py | 109 | 0.609436 | 0.597204 | 0 | 70 | 31.685714 | 115 |
pratik-iiitkalyani/Python | 4,398,046,547,850 | 985bfa7d6dec4eddc1595d3bb9f22e74dbf87b71 | a4653fb6c5a7a9e6db0457480e9e860c5304b2b8 | /OOPs/operator_overloading_polymorphism.py | 896d16f3dad5ca64e1cdc90af473147c7c904b36 | [] | no_license | https://github.com/pratik-iiitkalyani/Python | c315ca1f3a2446ccb871b74026edae97daec3773 | 082ae6d833f151054567d737de543898ebfe1d87 | refs/heads/master | 2020-08-07T05:59:21.930089 | 2020-01-04T17:05:27 | 2020-01-04T17:05:27 | 213,324,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # operator overloading
# polymorphism - many forms
# method overriding is also a example of polymorphism
class Phone:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
def phone_name(self):
return f"{self.brand} {self.model}"
def __add__(self, other): # overload + operator in our class
return self.price + other.price
def __mul__(self, other): # overload * operator in our class
return self.price * other.price
class Smartphone(Phone):
def __init__(self, brand, model, price, camera):
super().__init__(brand, model, price)
self.camera = camera
def phone_name(self):
return f"{self.brand} {self.model} and price is {self.price}"
# polymorphism - + having two different form(one is adding int and another is adding string)
# 2 + 3 = 5
# 'pratik' + ' kumar' = 'pratik kumar'
# l = [1,2,3]
# s = 'pratik
# len(l), len(s) different form of len function
my_phone = Phone('Nokia', '1100', 1000)
my_phone2 = Phone('Nokia', '1600', 1200)
my_smartphone = Smartphone('oneplus', '5t', 33000, '26 MP')
# polymorphism because here we use two diffirent form of phone_name method
print(my_smartphone.phone_name())
print(my_phone.phone_name())
# overload +, * operator in our class
print(my_phone + my_phone2)
print(my_phone * my_phone2)
| UTF-8 | Python | false | false | 1,421 | py | 172 | operator_overloading_polymorphism.py | 168 | 0.629134 | 0.605911 | 0 | 48 | 28.458333 | 92 |
PreciadoAlex/PreciadoAlex.github.io | 7,876,970,057,386 | 73a4a90c6ee8d45111ea1436135712c640ef4365 | 3da1fbc9e7b826bbe7d4b92574b882896786d5b2 | /Projects/Python_start/Preciado_StepOneWhile.py | e540603e9fc37ae87be1b0b7b740b014c934e04f | [] | no_license | https://github.com/PreciadoAlex/PreciadoAlex.github.io | 0b451dc7f082b49f909b9d90cdac43cc4ddd6892 | fc2163d4534de3fa7d73397377a7afd6ef07b225 | refs/heads/master | 2021-09-24T08:45:04.761435 | 2018-10-06T08:11:15 | 2018-10-06T08:11:15 | 110,735,773 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | acc = 1
while acc < 11:
print (acc)
acc = acc + 1
| UTF-8 | Python | false | false | 64 | py | 23 | Preciado_StepOneWhile.py | 16 | 0.453125 | 0.390625 | 0 | 5 | 10.8 | 17 |
stompingBubble/PythonBootcamp | 16,655,883,190,545 | 5c9917d3961d6dc7d74119f9705e8f632946b1c3 | a2735476958c0315e43d3b6ffe8b22701b9a469e | /TicTacToe1.py | 89a29c7e48c8c560c9ee150787030f8a256ef96d | [] | no_license | https://github.com/stompingBubble/PythonBootcamp | ad67fd32fcf01ccaabd0eb0d183ef1496ff22423 | fcb51b6ecda0f0812d46ba3dd0b1d15660e334e7 | refs/heads/master | 2021-07-17T22:40:41.887419 | 2017-10-24T17:37:39 | 2017-10-24T17:37:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Spyder Editor
"""
# In[1]:
import os
# global variables
board = [" "] * 10
game_state = True
position = 0
player = {"Player one": [True, "X"], "Player two": [False, "O"]}
number_of_tries = 0
invalid_input = True
not_empty_position = True
# In[2]:
def clear_game():
global board, game_state, position, number_of_tries, invalid_input
board = [" "] * 10
game_state = True
position = 0
number_of_tries = 0
invalid_input = True
# In[3]:
def print_board():
global board
print("|" + board[0] + "|" + board[1] + "|" + board[2] + "|")
print("|" + board[3] + "|" + board[4] + "|" + board[5] + "|")
print("|" + board[6] + "|" + board[7] + "|" + board[8] + "|")
# In[]
def print_currently_playing():
global player
for key in player.items():
if key[1][0]:
print("Playing right now: ", key[0])
# In[]
def check_input():
global position, invalid_input
if position > 10 or position < 0:
print("Invalid position, input number between 1-9")
invalid_input = True
else:
if check_if_position_is_empty():
print("Position is not empty, try again:")
invalid_input = True
else:
invalid_input = False
return invalid_input
# In[25]:
def take_input():
global position, invalid_input, number_of_tries, player
invalid_input = True
while (invalid_input):
print_currently_playing()
position = int(input("Input player position: "))
check_input()
# In[9]:
def place_player():
global board, position, player
if player["Player one"][0]:
board[position - 1] = player["Player one"][1]
elif player["Player two"][0]:
board[position - 1] = player["Player two"][1]
# In[10]:
def switch_player():
global player
if player["Player one"][0]:
player["Player one"][0] = False
player["Player two"][0] = True
else:
player["Player one"][0] = True
player["Player two"][0] = False
# In[11]:
def ask_to_play_again():
global game_state
ans = input("Want to play again (y/n)? ")
if ans == "Y" or ans == "y":
game_state = True
clear_game()
else:
game_state = False
return game_state
# In[12]:
def check_if_position_is_empty():
global board, position, not_empty_position
not_empty_position = True
if board[position - 1] == " ":
not_empty_position = False
else:
not_empty_position = True
return not_empty_position
# In[16]:
def check_if_winner():
global board, player
for key in player.items():
if (board[0] == key[1][1] and board[1] == key[1][1] and board[2] == key[1][1]) or (
board[3] == key[1][1] and board[4] == key[1][1] and board[5] == key[1][1]) or (
board[6] == key[1][1] and board[7] == key[1][1] and board[8] == key[1][1]) or (
board[0] == key[1][1] and board[3] == key[1][1] and board[6] == key[1][1]) or (
board[1] == key[1][1] and board[4] == key[1][1] and board[7] == key[1][1]) or (
board[2] == key[1][1] and board[5] == key[1][1] and board[8] == key[1][1]) or (
board[0] == key[1][1] and board[4] == key[1][1] and board[8] == key[1][1]) or (
board[2] == key[1][1] and board[4] == key[1][1] and board[6] == key[1][1]):
clear()
print_board()
print("***", key[0], " is the winner***")
ask_to_play_again()
# In[]
clear = lambda: os.system('cls')
# In[ ]:
clear_game()
while (game_state):
print_board()
take_input()
place_player()
check_if_winner()
switch_player()
number_of_tries += 1
if number_of_tries == 9:
ask_to_play_again()
clear()
| UTF-8 | Python | false | false | 3,869 | py | 12 | TicTacToe1.py | 11 | 0.522874 | 0.490049 | 0 | 156 | 23.769231 | 99 |
gyang274/leetcode | 1,537,598,340,098 | a0a33e104deed965366b17861cbb5d1079ae3a15 | 242f1dafae18d3c597b51067e2a8622c600d6df2 | /src/1500-1599/1545.kth.bit.in.nth.binary.str.py | 640b92fde1db7a7e99d812700ada70b960178614 | [] | no_license | https://github.com/gyang274/leetcode | a873adaa083270eb05ddcdd3db225025533e0dfe | 6043134736452a6f4704b62857d0aed2e9571164 | refs/heads/master | 2021-08-07T15:15:01.885679 | 2020-12-22T20:57:19 | 2020-12-22T20:57:19 | 233,179,192 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution:
def findKthBit(self, n: int, k: int) -> str:
f, k = 0, k
while n > 1:
m = 1 << (n - 1)
if k == m:
return str(1 ^ f)
elif k > m:
k = (1 << n) - k
f = f ^ 1
n -= 1
return str(0 ^ f)
if __name__ == '__main__':
solver = Solution()
cases = [
(1, 0),
(2, 0),
(2, 3),
]
rslts = [solver.findKthBit(n, k) for n, k in cases]
for cs, rs in zip(cases, rslts):
print(f"case: {cs} | solution: {rs}")
| UTF-8 | Python | false | false | 491 | py | 1,461 | 1545.kth.bit.in.nth.binary.str.py | 1,456 | 0.429735 | 0.399185 | 0 | 23 | 20.347826 | 53 |
ascorblack/library | 14,860,586,850,374 | 36bdce419df8a22dad050aadd34ad62939d5e20e | 1d3d3a645662a40674ef3748882f3bccc464001e | /gui.py | 7bb6146ad32123915223a7b0163ca52b2658247d | [] | no_license | https://github.com/ascorblack/library | 88e280b5a8d20f39c73038a82874fe61a9417599 | 46616bb730f422b25d7454917d0dfc6a43f9dbb6 | refs/heads/main | 2023-07-28T15:15:08.538299 | 2021-09-08T06:54:03 | 2021-09-08T06:54:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import eel
from eel import expose
import os
import json
import numpy as np
from PIL import Image
from io import BytesIO
import base64
from mainElastic import Book, show_warn, get_all_categories
from recommendation_ai.ai_rec import get_similarity, get_cosine_book
from sys import exit
db = Book()
def add_stat(name_stat, item):
with open("stats_log.json", "r", encoding="utf8") as f:
data = json.load(f)
with open("stats_log.json", "w", encoding="utf8") as f:
if type(data[name_stat]) == list:
data[name_stat].append(item)
elif type(data[name_stat]) == dict:
data[name_stat][item[0]] = data[name_stat].get(item[0], [])
if name_stat == "viewed":
try:
check_exist = np.where(np.array(data[name_stat][item[0]]) == item[1])[0][0]
data[name_stat][item[0]].pop(check_exist)
except:
pass
data[name_stat][item[0]].append(item[1])
json.dump(data, f, ensure_ascii=False, indent=4)
@expose
def del_stat(name_stat, item):
data = json.load(open("stats_log.json", "r", encoding="utf8"))
with open("stats_log.json", "w", encoding="utf8") as f:
if type(data[name_stat]) == list:
data[name_stat].pop(np.where(np.array(data[name_stat]) == item)[0][0])
elif type(data[name_stat]) == dict:
data[name_stat][item[0]] = data[name_stat].get(item[0], [])
data[name_stat][item[0]].pop(np.where(np.array(data[name_stat][item[0]]) == item[1])[0][0])
json.dump(data, f, ensure_ascii=False, indent=4)
@expose
def get_stat(what="all"):
data = json.load(open("stats_log.json", "r", encoding="utf8"))
if what == "all":
return data
else:
return data[what]
@expose
def check_favorite(author, title):
data = get_stat("favorite")
try:
check = np.where(np.array(data) == [author, title])[0][0]
return True
except:
return False
@expose
def stat_add(name_stat, item): add_stat(name_stat, item)
@expose
def get_viewed_books():
with open("stats_log.json", "r", encoding="utf8") as f:
data = json.load(f)
books = data["viewed"]["All"]
clear_all = []
for x in books:
if not x in clear_all:
clear_all.append(x)
return clear_all[-5:][::-1]
@expose
def all_categories(): return get_all_categories()
@expose
def random_book_category(category): return db.get_random_book_category(category)
@expose
def search_book(query):
books_author = db.author_books(query)
books_title = db.find_book(query)
if books_author != [] or books_title != []:
add_stat("search", query)
return [books_author, books_title]
@expose
def info_book(author, title): return db.info_book(author, title)
@expose
def get_book_id(id_): return db.get_book_id(id_)
@expose
def get_text(author, title): return db.get_book(author, title)
@expose
def open_pdf(author, title, category):
if not os.path.isfile(f"web/books_pdf/{author} [[]] {title.replace('?', '')}.pdf"):
open(f"web/books_pdf/{author} [[]] {title.replace('?', '')}.pdf", "wb").write(
db.get_pdf_bytes_book(author, title)
)
add_stat("viewed", (category, (author, title)))
add_stat("viewed", ("All", (author, title)))
cosine_stat = get_stat("books_viewed_cosine")
if len(cosine_stat) >= 11:
mean_cosines = np.mean(cosine_stat)
set_stat("books_viewed_cosine", [mean_cosines])
try:
add_stat("books_viewed_cosine", get_cosine_book(author, title))
except:
print("Книги нет в векторизированных")
return os.path.abspath(f"web/books_pdf/{author} [[]] {title.replace('?', '')}.pdf")
@expose
def add_book(author, title, text, category, cover=None):
text = text.encode("utf-8").decode("utf-8")
try:
if cover != None:
image = Image.open(BytesIO(base64.b64decode(cover.replace("data:image/jpeg;base64,", ""))))
image.thumbnail((190, 288), Image.ANTIALIAS)
image = db.get_cover_bytes(image)
else:
image = None
res = db.add_book(author=author, title=title, category=category, text=text, cover_book=image)
if not np.where(np.array(get_stat("user_books")) == [author, title])[0] and not res:
add_stat("user_books", [author, title])
return res
except:
import traceback
print(traceback.format_exc())
return "ERROR ADD BOOK"
@expose
def del_book(author, title, category):
try:
del_stat("user_books", [author, title])
del_stat("viewed", (category, (author, title)))
del_stat("viewed", ("All", (author, title)))
if check_favorite(author, title):
del_stat("favorite", (author, title))
db.del_book(author, title)
return True
except:
import traceback
print(traceback.format_exc())
return False
@expose
def books_category_paginated(category, page):
return db.get_category_book(category, page, 25)
@expose
def get_count_category(category):
return db.count_category(category)
@expose
def get_recommendation(author, title, count=5):
result = []
try:
for author, title in get_similarity(author, title, count):
result.append(info_book(author, title))
return result
except:
return None
@expose
def average_cosine_rec(count=10):
books_cosine = get_stat("books_viewed_cosine")
if len(books_cosine) < 1:
return []
result = []
for author, title in get_similarity(cosine=np.mean(books_cosine), count=count):
result.append(info_book(author, title))
return result
@expose
def set_stat(stat_name, new_data):
data = get_stat("all")
with open("stats_log.json", "w", encoding="utf8") as f:
if type(stat_name) == str:
data[stat_name] = new_data
elif type(stat_name) == list:
way_str = "data"
for stat in stat_name:
way_str += f"['{stat}']"
way_str += " = new_data"
exec(way_str, globals(), locals())
json.dump(data, f, ensure_ascii=False, indent=4)
@expose
def fast_search(query):
search_result = db.similarity_search(query)
return {"authors": search_result[0][:5], "titles": search_result[1][:5]}
@expose
def get_user_book_info():
books = list(set([(x[0], x[1]) for x in get_stat("user_books")]))
books_info = []
for book in books:
books_info.append(db.info_book(book[0], book[1]))
return books_info
def create_stats():
if not os.path.isfile("stats_log.json"):
with open("stats_log.json", "w", encoding="utf8") as f:
data = {
"viewed": {"All": []},
"favorite": [],
"search": [],
"books_viewed_cosine": [],
"user_books": []
}
json.dump(data, f, ensure_ascii=False, indent=4)
try:
check = json.load(open("stats_log.json", "r", encoding="utf8"))
except json.decoder.JSONDecodeError:
with open("stats_log.json", "w", encoding="utf8") as f:
data = {
"viewed": {"All": []},
"favorite": [],
"search": [],
"books_viewed_cosine": [],
"user_books": []
}
json.dump(data, f, ensure_ascii=False, indent=4)
create_stats()
def clear_books():
if not os.path.isdir("web/books_pdf"):
os.mkdir("web/books_pdf")
favorites = [f"{book[0]} [[]] {book[1]}.pdf".replace('?', '') for book in get_stat("favorite")]
for book in os.listdir("web/books_pdf/"):
if book not in favorites:
os.remove(f"web/books_pdf/{book}")
clear_books()
options = {
'mode': "chrome",
'host': "localhost",
'port': 7521,
'size': (1600, 1000)
}
if __name__ == '__main__':
eel.init('web')
eel.browsers.set_path("chrome", os.path.abspath("chrome-win\\chrome.exe"))
eel.start("index.html", options=options, suppress_error=True, cmdline_args=['--no-experiments', '--incognito'],
disable_cache=True, close_callback=None)
| UTF-8 | Python | false | false | 8,290 | py | 13 | gui.py | 5 | 0.577323 | 0.567159 | 0 | 279 | 28.616487 | 115 |
fzhcary/TCEF_Python_2020 | 14,199,161,920,535 | 6bd7c67c30fee5165412d87413c7bdb69ae3aca5 | cf0dfc31213c0a8cd0c6c0b5837fff07c2501991 | /selection_sort.py | 11a6181b2b255cce6ef616c4f1a25b7234047b95 | [] | no_license | https://github.com/fzhcary/TCEF_Python_2020 | 1c26103e2c1b65b50631ad4a728523c9ff1f118e | b753ca65b33a21d9094954ebb4193bfc97b8c056 | refs/heads/master | 2023-02-27T16:25:28.340662 | 2021-02-06T21:38:41 | 2021-02-06T21:38:41 | 282,457,824 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Selection Sort
def selection_sort(nums):
size = len(nums)
for j in range(1, size):
# on the last run, j: size -1
max_number = nums[size - j]
max_i = size - j
for i in range(0, size - j):
if nums[i] > max_number:
max_i = i
max_number = nums[i]
# swap max_i and size-1
nums[max_i], nums[size - j] = nums[size - j], nums[max_i]
return nums
if __name__ == "__main__":
import random
print(selection_sort([]))
print(selection_sort([1]))
print(selection_sort([26, 54, 93, 17, 77, 31, 44, 55, 20]))
n = 20
a = list(range(n))
random.shuffle(a)
print(a)
assert(selection_sort(a) == list(range(n)))
| UTF-8 | Python | false | false | 740 | py | 36 | selection_sort.py | 5 | 0.508108 | 0.474324 | 0 | 31 | 22.774194 | 65 |
saif409/Construction_management_system | 11,227,044,541,160 | debd80ab07d1f495f9972aa823ffdb6ab8123853 | 900780eedf00e1fbeab43d229e0b83acf76d668d | /sadmin/urls.py | f038b6c39eb44f637104d64c2524747d8ffbaa4a | [] | no_license | https://github.com/saif409/Construction_management_system | 126318a04112b8457da35ca78164b3eddeac00a8 | 6a0b5ffaabf22fea4c41ac5bd38a90f7e947f1cd | refs/heads/main | 2023-04-10T19:25:23.975509 | 2021-05-01T15:04:30 | 2021-05-01T15:04:30 | 352,547,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.urls import path
from.import views
urlpatterns = [
path('', views.user_login, name="login"),
path('home/', views.home, name="home"),
path('user_logout/', views.user_logout, name="user_logout")
]
| UTF-8 | Python | false | false | 221 | py | 36 | urls.py | 8 | 0.656109 | 0.656109 | 0 | 9 | 23.555556 | 63 |
DTUWindEnergy/PyWake | 16,166,256,903,451 | 5d734a02cc2cf3826cb028f498c4e678687671e7 | 42e0f154e0f18be3d5a6532b796036bead7ff996 | /py_wake/examples/data/ParqueFicticio/_parque_ficticio.py | 9da436c2d3ee3490dee1855664c0f6c648731cc7 | [
"MIT"
] | permissive | https://github.com/DTUWindEnergy/PyWake | 75d7dd5cedae68761958389b15d585191b200a90 | 36da70b2335321e435194d277511c17d8f012571 | refs/heads/master | 2023-08-20T09:00:30.946594 | 2023-08-10T12:07:55 | 2023-08-10T12:07:55 | 164,115,313 | 53 | 29 | MIT | false | 2022-11-07T08:47:06 | 2019-01-04T14:10:20 | 2022-11-04T02:27:01 | 2022-11-07T07:30:13 | 118,718 | 36 | 18 | 3 | Python | false | false | from py_wake.site.wasp_grid_site import WaspGridSite, load_wasp_grd
from py_wake.examples.data.ParqueFicticio import ParqueFicticio_path
from py_wake import np
from py_wake.site.distance import TerrainFollowingDistance
"""
min x: 262878
min y: 6504214
max x: 265078
max y: 6507414.0
Resolution: 100
columns: 23
rows: 33
30 and 200 m
"""
class ParqueFicticioSite(WaspGridSite):
def __init__(self, distance=TerrainFollowingDistance(distance_resolution=2000), mode='valid'):
ds = load_wasp_grd(ParqueFicticio_path, speedup_using_pickle=True)
WaspGridSite.__init__(self, ds, distance, mode)
self.initial_position = np.array([
[263655.0, 6506601.0],
[263891.1, 6506394.0],
[264022.2, 6506124.0],
[264058.9, 6505891.0],
[264095.6, 6505585.0],
[264022.2, 6505365.0],
[264022.2, 6505145.0],
[263936.5, 6504802.0],
])
| UTF-8 | Python | false | false | 946 | py | 250 | _parque_ficticio.py | 172 | 0.641649 | 0.469345 | 0 | 33 | 27.666667 | 98 |
0x913/python-practice-projects | 6,047,313,984,715 | eec58f4410fcd7adc04f44846b67e1a98c205413 | 4f67ac7517ea46b733f80a27d181374666131d6e | /python practice projects/Exceptions & Files/finally.py | 979cc498b947bf7ccd5dae1c388638015de2b35b | [] | no_license | https://github.com/0x913/python-practice-projects | 42af39ad6eed5ef82ff18a66523beecb4739805f | d3aea4a2b2bba4e1dabd56633be47e19c13ede16 | refs/heads/master | 2021-02-05T20:33:27.197069 | 2020-02-28T18:41:44 | 2020-02-28T18:41:44 | 243,828,924 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | try:
print(1)
print(10 / 0)
except ZeroDivisionError:
print(unknown_var)
finally:
print("This is executed last") | UTF-8 | Python | false | false | 148 | py | 46 | finally.py | 45 | 0.574324 | 0.547297 | 0 | 13 | 9.538462 | 33 |
paris3200/AdventOfCode | 4,801,773,475,163 | a713bb09bf0101e408db788c5e84d86a0a7a5996 | 0a70a9873bf09d56fd72faf0a00174660aaf07e6 | /code/2021/10/tests.py | f92b17b003a0cd23858007f465a5bc809ec74e4c | [] | no_license | https://github.com/paris3200/AdventOfCode | 40ef0828e70ed6736212a3cfe0574c6a26fe94bd | 8cd9dcbd946026d69b1f19a1495480f3ac6a41a0 | refs/heads/master | 2022-12-22T23:36:12.727295 | 2022-12-12T11:52:14 | 2022-12-12T11:52:14 | 226,195,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pytest
from aoc_10 import is_valid, part_one, complete_lines, score_autocomplete, part_two
@pytest.mark.parametrize(
("line", "expected"),
(
("{([(<{}[<>[]}>{[]{[(<()>", "}"),
("[({(<(())[]>[[{[]{<()<>>", True),
),
)
def test_is_valid(line, expected) -> None:
assert is_valid(line) == expected
def test_part_one() -> None:
assert part_one("data/test_input") == 26397
@pytest.mark.parametrize(
("line", "expected"),
(
("[({(<(())[]>[[{[]{<()<>>", "}}]])})]"),
("[(()[<>])]({[<{<<[]>>(", ")}>]})"),
),
)
def test_complete_lines(line, expected) -> None:
assert complete_lines(line) == expected
@pytest.mark.parametrize(
("completion", "expected"),
(
("}}]])})]", 288957),
(")}>]})", 5566),
),
)
def test_complete_lines(completion, expected) -> None:
assert score_autocomplete(completion) == expected
def test_part_two() -> None:
assert part_two("data/test_input") == 288957
| UTF-8 | Python | false | false | 993 | py | 83 | tests.py | 82 | 0.504532 | 0.48137 | 0 | 44 | 21.568182 | 83 |
lim0606/likelion | 17,763,984,754,472 | 87bc40f3b6dcd4dd88aa5af262374569cfb0f34b | aac3b8e8c01d93f71bb1bab05dbc9588ba3b765a | /w5_flaskr_upgrade/apps/flaskr_mvc.py | 6615cac11f724a85ba80389deef813be37bfe462 | [] | no_license | https://github.com/lim0606/likelion | 4f4a505e8e1cf1ce92e0c091d188f67fda5c3e26 | ec2fefae45897afd09d7f78dca1f979a28932e4b | refs/heads/master | 2021-01-22T04:43:56.803627 | 2014-09-06T08:11:22 | 2014-09-06T08:11:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
# all the imports
from flask import request, redirect, url_for,\
render_template
from apps import app
from database import Database
from datetime import datetime
dataStorage = Database()
@app.route('/', methods=['GET', 'POST'])
def show_entries():
entries = dataStorage.out()
return render_template('show_entries.html', entries=entries)
@app.route('/add', methods=['POST'])
def add_entry():
entry = {}
entry['id'] = dataStorage.newid()
entry['title'] = request.form['title']
entry['contents'] = request.form['contents']
entry['datetime'] = datetime.now()
entry['likecount'] = 0
dataStorage.put(entry)
return redirect(url_for('show_entries'))
@app.route('/del/<key>', methods=['GET'])
def del_entry(key):
dataStorage.delete(key)
return redirect(url_for('show_entries'))
@app.route('/like/<key>', methods=['GET'])
def like_entry(key):
entry = dataStorage.select(key)
entry['likecount'] += 1
dataStorage.update(key, entry)
return redirect(url_for('show_entries'))
@app.route('/dislike/<key>', methods=['GET'])
def dislike_entry(key):
entry = dataStorage.select(key)
if entry['likecount'] > 0:
entry['likecount'] -= 1
dataStorage.update(key, entry)
return redirect(url_for('show_entries'))
@app.route('/edit/<key>', methods=['GET'])
def edit_entry(key):
entry = dataStorage.select(key)
return render_template('edit_entry.html', entry=entry)
@app.route('/apply_edited/<key>', methods=['POST'])
def apply_edited_entry(key):
entry = dataStorage.select(key)
entry['id'] = int(key)
entry['title'] = request.form['title']
entry['contents'] = request.form['contents']
entry['datetime'] = datetime.now()
entry['likecount'] = entry['likecount']
dataStorage.update(key, entry)
return redirect(url_for('show_entries'))
from operator import itemgetter
@app.route('/top_entries')
def top_entries():
entries = dataStorage.out() # get all entries
entries = sorted(entries, key=itemgetter('likecount'), reverse=True)
# the same with the above statement
# entries = sorted(entries, key=lambda item: item['likecount'], reverse=True)
# if len(entries) > 3:
# return render_template('top_entries.html', entries=entries[1:3])
# else:
# return render_template('top_entries.html', entries=entries)
return render_template('top_entries.html', entries=entries)
| UTF-8 | Python | false | false | 2,459 | py | 31 | flaskr_mvc.py | 20 | 0.658804 | 0.655551 | 0 | 88 | 26.943182 | 81 |
ElTapia/computacion-grafica | 17,085,379,905,875 | 83c523604f4028d288a3769e92be85f12c76c032 | 77e31a5c86c78ce2e4967532417435275dc07b58 | /Ejercicios/Ejercicio_3/Version Windows/Ejercicio_3_Windows.py | 2555458a754a74e1bb13f2720a1e2275fa5f2fb1 | [
"MIT"
] | permissive | https://github.com/ElTapia/computacion-grafica | 742f90d40adf3bf9b43c49e34d7b91182b1bb233 | 8d6ec5e1bd2426093f253da9a197a7b74bb656a9 | refs/heads/main | 2023-08-23T14:10:21.792322 | 2021-11-01T15:42:21 | 2021-11-01T15:42:21 | 348,476,472 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # coding=utf-8
"""Ejercicio 3: Planeta tierra orbitando alrededor del sol y luna alrededor de la tierra
Extra: La tierra y la luna también tienen movimiento de rotación.
"""
import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import sys
import os.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import planet_shape as ps
import easy_shaders_Mac as es
import transformations as tr
import math
__author__ = "Daniel Calderon"
__license__ = "MIT"
# We will use 32 bits data, so an integer has 4 bytes
# 1 byte = 8 bits
SIZE_IN_BYTES = 4
# A class to store the application control
class Controller:
fillPolygon = True
# we will use the global controller as communication with the callback function
controller = Controller()
def on_key(window, key, scancode, action, mods):
if action != glfw.PRESS:
return
global controller
if key == glfw.KEY_SPACE:
controller.fillPolygon = not controller.fillPolygon
elif key == glfw.KEY_ESCAPE:
glfw.set_window_should_close(window, True)
else:
print('Unknown key')
if __name__ == "__main__":
# Initialize glfw
if not glfw.init():
glfw.set_window_should_close(window, True)
width = 600
height = 600
window = glfw.create_window(width, height, "Ejercicio 3: Movimiento órbitas Tierra y luna", None, None)
if not window:
glfw.terminate()
glfw.set_window_should_close(window, True)
glfw.make_context_current(window)
# Connecting the callback function 'on_key' to handle keyboard events
glfw.set_key_callback(window, on_key)
# Creating our shader program and telling OpenGL to use it
pipeline = es.SimpleTransformShaderProgram()
glUseProgram(pipeline.shaderProgram)
# Setting up the clear screen color
glClearColor(0.15, 0.15, 0.15, 1.0)
# Creating shapes on GPU memory
# * Crea contorno de la tierra
contourTierra = ps.createContorno(100)
gpuContourTierra = es.GPUShape().initBuffers()
gpuContourTierra.fillBuffers(contourTierra.vertices, contourTierra.indices, GL_STATIC_DRAW)
# * Crea shape de la tierra
shapeTierra = ps.createPlanet(100, [0, 0, 1])
gpuTierra = es.GPUShape().initBuffers()
gpuTierra.fillBuffers(shapeTierra.vertices, shapeTierra.indices, GL_STATIC_DRAW)
# * Crea trayectoria de la tierra
trayectoriaTierra = ps.createTrayectoria(200)
gpuTrayectoriaTierra = es.GPUShape().initBuffers()
gpuTrayectoriaTierra.fillBuffers(trayectoriaTierra.vertices, trayectoriaTierra.indices, GL_STATIC_DRAW)
# * Crea contorno del sol
contourSol = ps.createContorno(100)
gpuContourSol = es.GPUShape().initBuffers()
gpuContourSol.fillBuffers(contourSol.vertices, contourSol.indices, GL_STATIC_DRAW)
# * Crea shape del sol
shapeSol = ps.createPlanet(100, [1, 1, 0])
gpuSol = es.GPUShape().initBuffers()
gpuSol.fillBuffers(shapeSol.vertices, shapeSol.indices, GL_STATIC_DRAW)
# * Crea trayectoria de la luna
trayectoriaLuna = ps.createTrayectoria(100)
gpuTrayectoriaLuna = es.GPUShape().initBuffers()
gpuTrayectoriaLuna.fillBuffers(trayectoriaLuna.vertices, trayectoriaLuna.indices, GL_STATIC_DRAW)
# * Crea shape de la luna
shapeLuna = ps.createPlanet(100, [0.5, 0.5, 0.5])
gpuLuna = es.GPUShape().initBuffers()
gpuLuna.fillBuffers(shapeLuna.vertices, shapeLuna.indices, GL_STATIC_DRAW)
glBindVertexArray(gpuSol.vao)
# Creating our shader program and telling OpenGL to use it
pipeline = es.SimpleTransformShaderProgram()
glUseProgram(pipeline.shaderProgram)
pipeline.setupVAO(gpuContourTierra)
pipeline.setupVAO(gpuTierra)
pipeline.setupVAO(gpuTrayectoriaTierra)
pipeline.setupVAO(gpuContourSol)
pipeline.setupVAO(gpuSol)
pipeline.setupVAO(gpuTrayectoriaLuna)
pipeline.setupVAO(gpuLuna)
while not glfw.window_should_close(window):
# Using GLFW to check for input events
glfw.poll_events()
# Filling or not the shapes depending on the controller state
if (controller.fillPolygon):
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
# Clearing the screen in both, color and depth
glClear(GL_COLOR_BUFFER_BIT)
# Using the time as the theta parameter
theta = glfw.get_time()
# * Tamaño trayectoria tierra
trayectoriaTierraTransform = tr.matmul([
tr.translate(0, 0, 0),
tr.uniformScale(1.4)
])
# updating the transform attribute
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, trayectoriaTierraTransform)
# drawing function
pipeline.drawCall(gpuTrayectoriaTierra, mode=GL_LINES)
# * Tamaño contorno tierra
contourTierraTransform = tr.matmul([
tr.rotationZ(-theta),
tr.translate(math.sin(theta/10)*0.7, math.cos(theta/10)*0.7, 0),
tr.uniformScale(0.307)
])
# updating the transform attribute
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, contourTierraTransform)
# drawing function
pipeline.drawCall(gpuContourTierra, mode=GL_TRIANGLES)
# * Movimiento tierra
tierraTransform = tr.matmul([
tr.rotationZ(-theta),
tr.translate(math.sin(theta/10)*0.7, math.cos(theta/10)*0.7, 0),
tr.uniformScale(0.3)
])
# updating the transform attribute
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, tierraTransform)
# drawing function
pipeline.drawCall(gpuTierra)
# * Tamaño contorno sol
contourSolTransform = tr.matmul([
tr.translate(0, 0, 0),
tr.uniformScale(0.507)
])
# updating the transform attribute
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, contourSolTransform)
# drawing function
pipeline.drawCall(gpuContourSol, mode=GL_TRIANGLES)
# * Posición sol
solTransform = tr.matmul([
tr.translate(0, 0, 0),
tr.uniformScale(0.5)
])
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, solTransform)
pipeline.drawCall(gpuSol)
# * Tamaño trayectoria luna
trayectoriaLunaTransform = tr.matmul([
#tr.rotationZ(-theta),
tr.translate(math.sin(theta*1.1)*0.7, math.cos(theta*1.1)*0.7, 0),
tr.uniformScale(0.6)
])
# updating the transform attribute
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, trayectoriaLunaTransform)
# drawing function
pipeline.drawCall(gpuTrayectoriaLuna, mode=GL_LINES)
# * Movimiento luna
lunaTransform = tr.matmul([
tr.translate(math.sin(theta*1.1)*0.7, math.cos(theta*1.1)*0.7, 0),
tr.rotationZ(-theta),
tr.translate(math.sin(theta*2)*0.3, math.cos(theta*2)*0.3, 0),
tr.uniformScale(0.1)
])
glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, lunaTransform)
pipeline.drawCall(gpuLuna)
# Once the drawing is rendered, buffers are swap so an uncomplete drawing is never seen.
glfw.swap_buffers(window)
# freeing GPU memory
gpuTierra.clear()
gpuContourTierra.clear()
gpuTrayectoriaTierra.clear()
gpuTrayectoriaLuna.clear()
gpuSol.clear()
gpuContourSol.clear()
gpuLuna.clear()
glfw.terminate()
| UTF-8 | Python | false | false | 7,815 | py | 39 | Ejercicio_3_Windows.py | 26 | 0.673242 | 0.654925 | 0 | 240 | 31.529167 | 125 |
urudaro/data-ue | 8,761,733,294,684 | 76b9cf3fc17c394cc798c25943178ce75acc89e4 | b39d9ef9175077ac6f03b66d97b073d85b6bc4d0 | /Sorbisterit_powder_for_oral_or_rectal_suspension_SmPC.py | 6554d2305f3901c13418c3c670de3619ee50e9ae | [] | no_license | https://github.com/urudaro/data-ue | 2d840fdce8ba7e759b5551cb3ee277d046464fe0 | 176c57533b66754ee05a96a7429c3e610188e4aa | refs/heads/master | 2021-01-22T12:02:16.931087 | 2013-07-16T14:05:41 | 2013-07-16T14:05:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | {'_data': [['Common',
[['Metabolism', u'hyperkalcemi, hypokalemi, hypomagnesemi'],
['GI', u'illam\xe5ende, kr\xe4kningar']]],
['Uncommon',
[['GI',
u'f\xf6rstoppning, diarr\xe9, tarmobstruktion, ulceration, kolonnekros som kan ge perforation, anorexi']]],
['Rare',
[['GI',
u'i sv\xe5ra fall ileus ocklusion (beroende p\xe5 sammanklumpning av pulvret i tarmen), fekal klumpbildning efter rektal administrering till barn, gastrointestinal konkretion efter oral administrering till nyf\xf6dda. Hematochezi har observerats hos prematura barn och nyf\xf6dda med l\xe5g f\xf6delsevikt som f\xe5tt lavemang inneh\xe5llande polystyrensulfonatharts. Vid oral administrering kan patienter f\xe5 sv\xe5rt att sv\xe4lja den ganska stora m\xe4ngden utr\xf6rt pulver. Omfattningen av dessa besv\xe4r \xe4r beroende av individuell disposition, sjukdom, administrering och behandlingstidens l\xe4ngd.']]],
['Very rare',
[['Respiratory',
u'akut bronkit och/eller bronkopneumoni vid inhalation av kalciumpolystyrensulfonat']]]],
'_pages': [4, 4],
u'_rank': 5,
u'_type': u'LSFU'} | UTF-8 | Python | false | false | 1,198 | py | 3,177 | Sorbisterit_powder_for_oral_or_rectal_suspension_SmPC.py | 3,177 | 0.679466 | 0.660267 | 0.016694 | 15 | 78.933333 | 630 |
noh-hyeonseong/python3-algorithm-level1 | 4,037,269,290,431 | c2dd1be41120c2c01716a3f9db7a579ff46b99ce | 8f5e4e2aa50a629c93ad7be317d7139f7394e699 | /행렬의덧셈.py | de18616f213d7beb321d6caf468a217abc79197e | [] | no_license | https://github.com/noh-hyeonseong/python3-algorithm-level1 | d0c9b76d539e6cab5c68bb6c5a7ba12e87073640 | 5aec6c24fb3c3fb2833bdc80e4af7c0bd9e8fddd | refs/heads/master | 2023-06-06T02:34:02.882296 | 2021-06-29T06:16:05 | 2021-06-29T06:16:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
def solution(arr1, arr2):
"""
행렬은 numpy 모듈을 활용하면 더 쉽게 풀 수 있음
import numpy as np
"""
#numpy 사용 코드
A = np.array(arr1)
B = np.array(arr2)
answer = (A + B).tolist()
print(answer)
return answer
#기존 코드
# answer = []
# for i, j in zip(arr1, arr2):
# tempArr = []
# for k, p in zip(i, j):
# tempArr.append(k+p)
# answer.append(tempArr)
# return answer | UTF-8 | Python | false | false | 507 | py | 24 | 행렬의덧셈.py | 24 | 0.512035 | 0.498906 | 0 | 23 | 18.913043 | 34 |
Green-Project/Green | 6,768,868,465,423 | 14579c9cf1a109d063bbb61aa549a955b59c7e7b | 82459da507886101871a750241b1b108baccbb9f | /IA/api/config.py | f8cbf33520fe19a799a294258131aa153b32be0e | [] | no_license | https://github.com/Green-Project/Green | e5be745a31a1623eb6336dae3a5aec1a72f90b1c | da491f7278cc3acaf24c7441ae14d0922a266b58 | refs/heads/main | 2023-06-19T11:06:10.401324 | 2021-07-04T11:22:23 | 2021-07-04T11:22:23 | 317,233,527 | 2 | 0 | null | false | 2020-12-10T17:30:29 | 2020-11-30T13:32:46 | 2020-12-10T15:22:17 | 2020-12-10T17:30:28 | 2,482 | 3 | 0 | 3 | JavaScript | false | false | env = {
"SERVER_PORT": 8000,
"TOKEN_SECRET": "hsf7ClN471QKJ6DPgreI"
} | UTF-8 | Python | false | false | 77 | py | 52 | config.py | 23 | 0.623377 | 0.506494 | 0 | 4 | 18.5 | 42 |
AdamR77/Palindrom | 13,675,175,881,382 | 61a8a1817c62bf2c138232bf2c48e8814b25073f | 358cb092e7c15884f81b7269640f730bfcb69422 | /palindrom.py | be2ab1ae954b6070b09416f1a79b4605adca618d | [] | no_license | https://github.com/AdamR77/Palindrom | 18ba7ffb48070377e0bba3b7f4d4205a2ca74f0a | 5b1c714662385a7a8849690f517b1b144998217a | refs/heads/main | 2023-08-23T11:31:49.206317 | 2021-10-13T20:03:25 | 2021-10-13T20:03:25 | 416,882,078 | 0 | 0 | null | false | 2021-10-17T15:56:09 | 2021-10-13T20:02:33 | 2021-10-13T20:03:27 | 2021-10-17T15:56:09 | 1 | 0 | 0 | 2 | Python | false | false |
def check_palindrom (string):
reversed_string = string[::-1]
if string == reversed_string:
return True
else:
return False
#spr
string = "madam"
if check_palindrom(string) == True:
print(string," is palnindrom")
| UTF-8 | Python | false | false | 244 | py | 1 | palindrom.py | 1 | 0.631148 | 0.627049 | 0 | 11 | 20.909091 | 35 |
neuracr/privacyAggretationTSPOC | 17,806,934,433,482 | cd7e723648ea1413b399b313ec8715d357d8df1f | 99bf30df817ee022e7e4ac43b26bbac5a58a2a5f | /main.py | 496259fe198ae8ea89b4cb560cc3b72e197c4797 | [] | no_license | https://github.com/neuracr/privacyAggretationTSPOC | 8f6b4dc42f584cfebbdbfff1a90a7dc8642957fb | c878bf4ba89b3011fa2eb701f83768c31064b9e4 | refs/heads/master | 2021-02-05T21:01:13.269003 | 2020-09-22T09:38:21 | 2020-09-22T09:38:21 | 243,832,133 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import logging
from poc.aggregator import Aggregator
from poc.participant import Participant
from poc.ttp import TTPBasic
import matplotlib.pyplot as plt
big_delta = 2000 # delta
eps = 0.5
small_delta = 0.001
n = 120
gamma = 0.5
logger = logging.getLogger(__name__)
def experiment_basic(n, t, eps, small_delta, big_delta, gamma):
"""Simulate an aggregation of n participants at time t."""
# We create the different parties of the experiment
aggregator = Aggregator()
participants = [Participant(big_delta) for _ in range(n)]
# The TTP chooses a g, p, P
ttp = TTPBasic()
# initialization
# The TTP generates the sk for each participant and
# the aggregator
ttp.init_generator(n)
# The TTP distributes the parameter and sk to the participants
# The aggregator gets sk0
aggregator.g, aggregator.P, aggregator.p = ttp.g, ttp.P, ttp.p
aggregator.sk = ttp.generate_sk()
aggregator.init_cipher_basic()
# The participants receive the parameter and their key
for p in participants:
p.small_delta = small_delta
p.eps = eps
p.gamma = gamma
p.n = n
p.g, p.P, p.p = ttp.g, ttp.P, ttp.p
p.sk = ttp.generate_sk()
p.init_cipher_basic()
# Now the participants share their private value x to the aggregator
for p in participants:
aggregator.append_contribution(p.noisy_enc(t))
# Once all participants have sent their contribution, the aggretator
# ... aggregates
res = aggregator.aggregate_basic(t)
logger.info("modulo for the experiment: %d" % (ttp.p))
logger.info("result of the aggregation: %d." % (res))
real_res = 0
for p in participants:
real_res += p.x
real_res %= ttp.p
logger.info("real sum: %d." % (real_res))
logger.info("error: %d" % (modular_abs(res, real_res, ttp.p)))
return(res, real_res, ttp.p)
def modular_abs(x, y, p):
return(min((x-y) % p, (y-x) % p))
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
# L = []
# for i in range(1000):
# res, real_res, p = experiment_basic(n, 1337, eps, small_delta,
# big_delta, gamma)
# L.append((abs(res-real_res)/real_res)*100)
# plt.hist(L, bins=10)
# plt.show()
res, real_res, p = experiment_basic(n, 1337, eps, small_delta,
big_delta, gamma)
| UTF-8 | Python | false | false | 2,439 | py | 12 | main.py | 11 | 0.614596 | 0.600656 | 0 | 81 | 29.111111 | 72 |
Ilfarro/live_code_django | 506,806,186,717 | 2a6ddc7c82d8068aeeff17eabbf63bbced4ecf8b | 4d2d0f1b51ddfccb2f3aaec0e97025f94d3c0c95 | /home/migrations/0006_home_barang_deskripsi.py | 8dcbea8c0e8c7a3dea0ca4c98565129b2d4a20b8 | [] | no_license | https://github.com/Ilfarro/live_code_django | ea446dc7efc930e4f04293bde020a909bf7a5288 | 5ababb51fe583b1d907dffd50cb43672805f31fd | refs/heads/master | 2020-04-22T19:22:15.097587 | 2019-02-14T03:55:51 | 2019-02-14T03:55:51 | 170,605,321 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.1.7 on 2019-02-14 03:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0005_remove_home_barang_deksripsi'),
]
operations = [
migrations.AddField(
model_name='home_barang',
name='deskripsi',
field=models.TextField(default=None),
preserve_default=False,
),
]
| UTF-8 | Python | false | false | 434 | py | 12 | 0006_home_barang_deskripsi.py | 8 | 0.592166 | 0.548387 | 0 | 19 | 21.842105 | 54 |
Anri-Lombard/PythonBootcamp | 6,347,961,682,829 | 6b54921fd7019587f2bdd9eebb1cb63ab2d057d8 | 5e0a08cd66692443f477245a2ec45ff4e672bcba | /day2/18.py | c0fb375b51155f5bced7d7558be17df01fa74f44 | [] | no_license | https://github.com/Anri-Lombard/PythonBootcamp | 30b224294de7878cf65066943285c788b2ab9505 | 8504d1fd15b47a9cbe187f4e99e598265dec0b5d | refs/heads/main | 2023-04-14T18:10:43.997879 | 2021-04-25T04:17:09 | 2021-04-25T04:17:09 | 341,822,181 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # num_char = len(input("What is your name? "))
#
# print("Your name has " + str(num_char) + " characters.")
a = 123
# use type() function to investigate types
print(type(a)) | UTF-8 | Python | false | false | 174 | py | 78 | 18.py | 67 | 0.643678 | 0.626437 | 0 | 7 | 24 | 58 |
nathaliatvrs/checagem_precos | 6,038,724,047,262 | 17603d3c594b144ddd8beb7214c71c0a78ffdd91 | 8a833ffd5a0d65e3a954982e6ff35061dfb6968c | /pdleo/leo.py | ce0b4950ba89b03dbcc04dd1a91f6fc7c55658b2 | [
"MIT"
] | permissive | https://github.com/nathaliatvrs/checagem_precos | 4ab7c62d3ac9feddc3d1c0d8b0299cec33acbc5c | 025c143f8ab921c54d4283ca34335597989e4666 | refs/heads/master | 2020-11-25T01:51:20.945006 | 2019-12-16T21:35:53 | 2019-12-16T21:35:53 | 228,437,873 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# coding: utf-8
# ## Importando bibliotecas
# In[3]:
import pandas as pd
import re
from io import BytesIO
from os import listdir
from os.path import join
from unicodedata import normalize
import platform
# In[8]:
if platform.system() == 'Linux':
from IPython.core.magic import register_line_cell_magic
from concurrent.futures import ProcessPoolExecutor, as_completed
# ## Funções
# #### bmldev.loads
# In[9]:
def __char_validation(char):
invalid = ['', '\n', '\t']
if char in invalid:
return False
return True
def __line_validation(line, qtd_columns, delimiter):
line_data = line.split(delimiter)
line_data = list(map(str.strip, line_data))
len_line = len(line_data)
if (len_line == qtd_columns):
return line_data.copy()
if (len_line == qtd_columns+2):
if (not __char_validation(line_data[0]) and not __char_validation(line_data[-1])):
return line_data[1:-1]
raise ValueError('Quantidade inválida de colunas na linha')
def __str_to_float(text, ind_cut, negative=False):
pref = text[:ind_cut].replace('.', '').replace(',', '')
suf = text[ind_cut:].replace(',', '.')
if (negative):
return float(pref + suf) * -1
else:
return float(pref + suf)
def __to_numeric(val):
if (re.search(r'^(\d\d)?\d\d\.\d\d?\.\d\d(\d\d)?$', val)): # verificação de padrão de data (xx.xx.xxxx)
return val
found_re = re.search(r'[\.]\d{3}$', val) # verfica *.xxx (positivo)
if (found_re):
try:
val.replace('.', '')
return int(val.replace('.', ''))
except:
return val
found_re = re.search(r'[\.]\d{3}-$', val) # verfica *.xxx (negativo)
if (found_re):
try:
val.replace('.', '')
return int(val[:-1].replace('.', '')) * -1
except:
return val
found_re = re.search(r'[\.\,]\d+$', val) # verfica *.xx ou *,xx (positivo)
if (found_re):
try:
return __str_to_float(val, found_re.span()[0])
except:
return val
found_re = re.search(r'[\.\,]\d+-$', val) # verfica *.xx ou *,xx (negativo)
if (found_re):
try:
return __str_to_float(val[:-1], found_re.span()[0], True)
except:
return val
if (re.search(r'^\d+-$', val)):
return (int(val[:-1])*-1)
if (re.search(r'^\d+$', val)):
return (int(val))
return val
def __back_to_blank(text, begin):
for ind in range(begin,-1,-1):
if (text[ind-1] == ' '): return(ind)
return 0
def __end_column(text, begin):
ind = text[begin:].find(' ')
if (ind < 0): return ind
ind = ind + 3
for i in range(ind + begin, len(text)):
if (text[i] != ' '): return i
return None
def __get_begin_end(text, column):
begin = text.find(column)
if (begin < 0): return None # retorno caso nao encontre a coluna
end = __end_column(text, begin)
if not(end): return None # retorno caso encontre algum erro no end
return (begin, end)
def __conditions(header, line):
if (len(line) < len(header)): return False
if (re.search(r'^-+$', line)): return False
if (line == header): return False
return True
def txts_to_pd(arquivos, qtd_columns, has_header=True, encoding='latin-1', delimiter='|', cols_names=None):
header_names = []
dic = {i:[] for i in range(qtd_columns)}
for arquivo in arquivos:
arq = arquivo.readlines() if type(arquivo) == BytesIO else open(arquivo, "r", encoding=encoding)
for line in arq:
line = line.decode(encoding) if type(arquivo) == BytesIO else line
done = False
try:
data = __line_validation(line, qtd_columns, delimiter)
done = True
except:
done = False
if (done):
for i in range(len(data)):
data[i] = __to_numeric(data[i])
if (not header_names):
if (has_header):
# print(data)
header_names = data
else:
if (data != header_names):
for i in range(qtd_columns):
if (isinstance(data[i], str)):
dic[i].append(data[i].strip())
else:
dic[i].append(data[i])
df = pd.DataFrame.from_dict(dic)
# print(header_names)
if (len(header_names) == qtd_columns) & (cols_names == None):
df.columns = header_names
elif (cols_names != None):
df.columns = cols_names
return df
def zvlike_to_df(columns, file, skip=6, encoding="latin-1"):
coord = {}
df = dict([(col, []) for col in columns])
header = ''
cont = 0 # force break
with open(file, "r", encoding=encoding) as slar:
for line in slar.readlines()[skip:]:
if not (header):
header = line
for col in columns:
coord[col] = __get_begin_end(header, col)
else:
if (__conditions(header, line)):
for col in columns:
value = line[__back_to_blank(line, coord[col][0]):coord[col][1]].strip()
df[col].append(__to_numeric(value))
cont += 1 # force break
if (cont > 75): break # force break
return pd.DataFrame.from_dict(df)
def get_lineData(line, n_cols, delimiter):
line_data = line[1:-2].split(delimiter)
line_data = list(map(str.strip, line_data))
len_line = len(line_data)
if (len_line == n_cols):
# if (not __char_validation(line_data[0]) and not __char_validation(line_data[-1])):
return line_data
return None
def line_to_dict(lines, n_cols, delimiter):
dic = {i:[] for i in range(n_cols)}
if type(lines) != list:
lines = [lines]
for line in lines:
# print(line)
data = get_lineData(line, n_cols, delimiter)
if data:
for i in range(n_cols):
data[i] = __to_numeric(data[i])
if (isinstance(data[i], str)):
dic[i].append(data[i].strip())
else:
dic[i].append(data[i])
return dic
def file_to_df(path, n_cols, delimiter, encoding, slice_size=10):
lines = path.readlines() if type(path) == BytesIO else open(path, "r", encoding=encoding)
dic_all = {i:[] for i in range(n_cols)}
header_names = None
for line in lines:
line = line.decode(encoding) if type(path) == BytesIO else line
data = get_lineData(line, n_cols, delimiter)
if data:
if not header_names:
header_names = data.copy()
elif data != header_names:
ret = line_to_dict(line, n_cols, delimiter)
for key, vals in ret.items():
for val in vals:
dic_all[key].append(val)
df = pd.DataFrame.from_dict(dic_all)
df.columns = header_names
return df
def read_files(files, n_cols, delimiter, encoding):
futures = []
result = pd.DataFrame()
with ProcessPoolExecutor(max_workers=4) as executor:
for path in files:
# futures.append(executor.submit(txts_to_pd, [path], n_cols))
futures.append(executor.submit(file_to_df, path, n_cols, delimiter, encoding))
for future in as_completed(futures):
ret = future.result()
result = pd.concat([result, ret]).reset_index(drop=True)
return result
if platform.system() == 'Linux':
def sap_to_df(paths, n_cols, has_header=True, encoding='latin-1', delimiter='|', cols_names=None):
if type(paths) != list:
paths = [paths]
df = read_files(paths, n_cols, delimiter=delimiter, encoding=encoding)
if cols_names:
df.columns = cols_names
return df
# #### Funções utilitárias
# In[10]:
def arquivo_valido(file):
return not '~lock' in file or not '~$' in file
def remover_acentos(txt):
return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')
def normaliza(txt):
return str(txt).lower().replace(' ','_').replace('.','')
def buscar_bases(path, nome=None):
for file in listdir(path):
if (re.search(nome, remover_acentos(file), flags=re.IGNORECASE)) and arquivo_valido(file):
caminho = join(path, file)
try:
return caminho
except:
print('Palavra chave não encontrada:', nome)
def renomeia_colunas(colunas):
return [(str(col)[0].upper() + str(col)[1:]).replace('_',' ') for col in colunas]
def normaliza_colunas(cols):
colunas = []
try:
cols=cols.tolist()
except:
return cols
for col in cols:
try:
colunas.append(remover_acentos(normaliza(col)))
except:
colunas.append(col)
return colunas
def leitura_dic_bases(bases, normaliza=True, Linux=False):
dfs={}
for base in bases:
if bases[base]['tipo'] == 'txt':
print ("Lendo base {}...".format(base), end='')
try:
if Linux:
dfs[base] = sap_to_df(bases[base]['path'],bases[base]['columns'])
else:
dfs[base] = txts_to_pd([bases[base]['path']],bases[base]['columns'])
if normaliza:
dfs[base].columns = normaliza_colunas(dfs[base].columns)
print('ok')
except Exception as e:
print('erro ao ler base:')
print(e)
else:
print ("Lendo base {}...".format(base), end='')
try:
if 'sheet' in bases[base]:
dfs[base] = pd.read_excel(bases[base]['path'],bases[base]['sheet'])
else:
dfs[base] = pd.read_excel(bases[base]['path'])
if normaliza:
dfs[base].columns = normaliza_colunas(dfs[base].columns)
print('ok')
except Exception as e:
print('erro ao ler base:')
print(e)
return dfs
def close_program(msg=''):
print('{}'.format(msg), flush=True)
input('Press any key to exit.')
exit()
# In[7]:
if platform.system() == 'Linux':
@register_line_cell_magic
def handle(line, cell):
try:
exec(cell)
except Exception as e:
print(e)
print('Em:')
print(cell)
input('Pressione enter para sair')
# #### Funções de criação
# In[5]:
def cria_elemento(tipo, palavra_chave, diretorio='bases', col=0, sheet_name=None):
dic = {}
dic['tipo'] = tipo
dic['path'] = buscar_bases(diretorio, nome=palavra_chave)
if tipo == 'txt':
dic['columns'] = col
if tipo == 'excel' and sheet_name != None:
dic['sheet'] = sheet_name
return dic
def cria_dfs(tipos=[], nomes_bases=[], palavras_chave=[], cols=[], sheet_names=[], diretorio='bases', normaliza_colunas=True):
#Informa o S.O.
if platform.system() == 'Linux':
linux = True
else:
linux=False
bases={}
cont_col=0 #contador para atribuir o n° de colunas aos arquvios .txt
names=False #boleano para atribuir sheets caso existam
if len(sheet_names) > 0:
cont_sheet=0
names=True
if len(tipos) == len(nomes_bases) == len(palavras_chave):
for i in range(len(tipos)):
#Arquivos .txt
if tipos[i] == 'txt':
if cont_col < len(cols):
aux = cria_elemento(tipo=tipos[i], palavra_chave = palavras_chave[i], col = cols[cont_col], diretorio = diretorio)
cont_col+=1
else:
print('Erro em informações de colunas')
#Arquivos .xlsx
if tipos[i] == 'excel':
if not(names):
aux = cria_elemento(tipo=tipos[i], palavra_chave = palavras_chave[i], diretorio = diretorio)
if names:
aux = cria_elemento(tipo=tipos[i], palavra_chave = palavras_chave[i], sheet_name = sheet_names[cont_sheet], diretorio = diretorio)
cont_sheet+=1
names = False if not(cont_sheet<len(sheet_names)) else names
bases[nomes_bases[i]] = aux
else: print('Erro, dados de entrada incorretos')
return leitura_dic_bases(bases, normaliza=normaliza_colunas, Linux=linux)
| UTF-8 | Python | false | false | 13,029 | py | 2 | leo.py | 1 | 0.520981 | 0.516754 | 0 | 422 | 29.829384 | 150 |
mawunyodm/PointOfSale | 11,501,922,439,663 | 6d711285ceab7c7592a2cc48d5dd808772035bbd | 459797c1ed60c9899f882710418555dd7261257d | /Authentication.py | 404ddcbd77df400f5cea7903f56930f3b5709150 | [] | no_license | https://github.com/mawunyodm/PointOfSale | 2f3f286974b0475767eb3a72bb6ce7c14eb567c3 | 894b705bd47ad415d21b4ee8fe8cbf6c3cb7c6d0 | refs/heads/master | 2023-03-01T00:10:39.685128 | 2021-02-11T05:55:10 | 2021-02-11T05:55:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from tkinter import *
from tkinter import messagebox
import sqlite3
authScreen = Tk()
authScreen.title("POS START")
authScreen.geometry("500x300")
spacingFrame = Frame(authScreen)
frame = Frame(bg="green",padx=10)
welcomeLabel = Label(frame,text="STOP & SHOP",font=("roboto",10,"bold"),pady=10)
# CREATING AND/OR CONNECTING TO LOGIN DATABASE
conn = sqlite3.connect("db/userAuthentication.db")
c = conn.cursor()
# c.execute("""CREATE TABLE Users(
# firstName text,
# lastName text,
# password varchar
# )""")
# c.execute("INSERT INTO users (firstName,lastName,password) VALUES('Emmanuel','Mukombero','Manue4578')")
# creating all necessary functions of system modules
def back():
oplogin.destroy()
def operatorlogin():
conn = sqlite3.connect("db/userAuthentication.db")
c = conn.cursor()
c.execute("SELECT * FROM Users")
records = c.fetchall()
for record in records:
if usernameEntry.get() == record[0] and passwordEntry.get() == record[2]:
response = messagebox.showinfo("LOGIN SUCCESS","You have successfully logged in.")
if response == "ok":
oplogin.destroy()
import pointOfSale
elif len(usernameEntry.get()) == 0 or len(passwordEntry.get()) == 0:
messagebox.showerror("FILL IN","Fill in all fields")
else:
messagebox.showerror("LOGIN FAIL","Incorrect username or password")
conn.commit()
conn.close()
# CREATING OPERATOR LOGIN SCREEN
def operatorLogin():
global oplogin
oplogin = Tk()
oplogin.title("OPERATOR LOGIN")
oplogin.geometry("500x300")
# create labels for logins
usernameLabel = Label(oplogin,text="Username",font=("roboto",10))
passwordLabel = Label(oplogin,text="Password",font=("roboto",10))
# create entry widgets for login
global usernameEntry
global passwordEntry
usernameEntry = Entry(oplogin,width=35)
passwordEntry = Entry(oplogin,width=35,show="-")
# create login and back button
loginBtn = Button(oplogin,text="Login",font=("roboto",10),command=operatorlogin)
backBtn = Button(oplogin,text="Back",font=("roboto",10),command=back)
# displaying widgets on screen
usernameLabel.grid(row=0,column=0,pady=(100,20),padx=(100,10))
passwordLabel.grid(row=1,column=0,padx=(100,10))
usernameEntry.grid(row=0,column=1,pady=(100,20))
passwordEntry.grid(row=1,column=1)
loginBtn.grid(row=2,column=0,columnspan=2,pady=20,padx=(150,0),ipadx=50)
backBtn.grid(row=3,column=0,columnspan=2,padx=(150,0),ipadx=50)
def adminlogin():
conn = sqlite3.connect("db/userAuthentication.db")
c = conn.cursor()
c.execute("SELECT * FROM Users")
records = c.fetchall()
for record in records:
if usernameEntry.get() == record[0] and passwordEntry.get() == record[2]:
response = messagebox.showinfo("LOGIN SUCCESS","You have successfully logged in.")
if response == "ok":
adlogin.destroy()
import adminView
elif len(usernameEntry.get()) == 0 or len(passwordEntry.get()) == 0:
messagebox.showerror("FILL IN","Fill in all fields")
else:
messagebox.showerror("LOGIN FAIL","Incorrect username or password")
conn.commit()
conn.close()
# if str(usernameEntry.get()) == "Emmanuel" and str(passwordEntry.get()) == "Mukombero":
# response = messagebox.showinfo("LOGIN SUCCESS","You have successfully logged in.")
# if response == "ok":
# adlogin.destroy()
# # import adminView
# else:
# messagebox.showerror("LOGIN FAIL","Incorrect username or password, try again.")
# CREATING ADMIN LOGIN SCREEN
def adminLogin():
global adlogin
adlogin = Tk()
adlogin.title("ADMIN LOGIN")
adlogin.geometry("500x300")
def adback():
adlogin.destroy()
# create labels for logins
usernameLabel = Label(adlogin,text="Username",font=("roboto",10))
passwordLabel = Label(adlogin,text="Password",font=("roboto",10))
global usernameEntry
global passwordEntry
# create entry widgets for login
usernameEntry = Entry(adlogin,width=35)
passwordEntry = Entry(adlogin,width=35,show="-")
# create login and back button
loginBtn = Button(adlogin,text="Login",font=("roboto",10),command=adminlogin)
backBtn = Button(adlogin,text="Back",font=("roboto",10),command=adback)
# displaying widgets on screen
usernameLabel.grid(row=0,column=0,pady=(100,20),padx=(100,10))
passwordLabel.grid(row=1,column=0,padx=(100,10))
usernameEntry.grid(row=0,column=1,pady=(100,20))
passwordEntry.grid(row=1,column=1)
loginBtn.grid(row=2,column=0,columnspan=2,pady=20,padx=(150,0),ipadx=50)
backBtn.grid(row=3,column=0,columnspan=2,padx=(150,0),ipadx=50)
# Creating Login Options Buttons
AdminloginOptionBtn = Button(authScreen,text="LOGIN \n AS ADMIN",font=("roboto",10,"bold"),command=adminLogin)
OperatorloginOptionBtn = Button(authScreen,text="LOGIN \n AS OPERATOR",font=("roboto",10,"bold"),command=operatorLogin)
# Displaying Widgets to screen
spacingFrame.grid(row=0,column=0,columnspan=2,pady=10)
frame.grid(row=1,column=0,columnspan=2,ipadx=130)
welcomeLabel.grid(row=1,column=0,columnspan=2,ipadx=100)
# Displaying Buttons on the screen
AdminloginOptionBtn.grid(row=2,column=0,pady=(50,10),ipady=5,ipadx=35,padx=(0,70),columnspan=2)
OperatorloginOptionBtn.grid(row=3,column=0,pady=10,ipady=5,padx=(0,70),ipadx=20,columnspan=2)
conn.commit()
conn.close()
authScreen.mainloop() | UTF-8 | Python | false | false | 5,693 | py | 6 | Authentication.py | 5 | 0.663973 | 0.627964 | 0 | 168 | 32.892857 | 119 |
Genza999/readme_cli | 18,391,049,962,858 | 8ad74ab861702762f76c7c858451d832b81abedd | fea9d83430fe4ba6bfc858d155ca92fcc5dfbe9a | /setup.py | b1442f681f6a3e98c05bf6d4d9e373a4bf2bd44c | [
"MIT"
] | permissive | https://github.com/Genza999/readme_cli | 3f9c5699889dfc8d3e7ed86f52df3158bd12123b | 66c059ee253cac4727788426e7ca3f65f2c1e035 | refs/heads/main | 2023-01-01T12:07:59.815321 | 2020-10-21T13:48:11 | 2020-10-21T13:48:11 | 304,986,941 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import io
import os
import re
import sys
from setuptools import find_packages
from setuptools import setup
if sys.version_info[:3] < (3, 0, 0):
print("Requires Python 3 to run.")
sys.exit(1)
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding='utf-8') as fd:
return re.sub(text_type(r':[a-z]+:`~?(.*?)`'), text_type(r'``\1``'), fd.read())
setup(
name="read_me_cli",
version="0.2.1",
url="https://github.com/Genza999/readme_cli",
license='MIT',
author="Kisekka David",
author_email="cartpix@gmail.com",
description="Command line tool that displays github README.md content for github repositories",
long_description=read("README.rst"),
install_requires=[
'beautifulsoup4==4.9.3',
'certifi==2020.6.20',
'chardet==3.0.4',
'idna==2.10',
'requests==2.24.0',
'soupsieve==2.0.1',
'urllib3==1.25.10',
'urwid==2.1.2'
],
keywords='readme cli readme.md github repository',
include_package_data=True,
packages=["readme_cli"],
entry_points={"console_scripts": ["readme_cli = readme_cli.main:main"]},
python_requires=">=3",
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
| UTF-8 | Python | false | false | 1,769 | py | 7 | setup.py | 5 | 0.590729 | 0.556246 | 0 | 60 | 28.483333 | 99 |
s3593810/IoT-Based-Automation | 5,093,831,228,413 | cc0a4b6149a49997e89381e1078ee6082a7fb21a | f2c6a0fbbc1728ab409975157dfdf00826b23e74 | /App_Logging.py | 45a6d26fff2c1fbd450ce99daaba05bddcede9cf | [] | no_license | https://github.com/s3593810/IoT-Based-Automation | 9f140ba3492f59a49680e66a673402cacd20fd42 | ecbd24282789748710ce7d3043361fb4347dbebd | refs/heads/master | 2021-04-16T07:24:07.926742 | 2019-04-07T11:04:55 | 2019-04-07T11:04:55 | 249,337,462 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import logging
class SenseHatApp_logging:
logger = logging.getLogger(name='AppLogger')
def __init__(self):
self.logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'[%(asctime)s:%(module)s:%(lineno)s:%(levelname)s] %(message)s'
)
filehandler = logging.FileHandler('SenseHatApp.log')
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(formatter)
self.logger.addHandler(filehandler)
| UTF-8 | Python | false | false | 480 | py | 12 | App_Logging.py | 10 | 0.654167 | 0.654167 | 0 | 15 | 31 | 75 |
dcollins4096/p19_newscripts | 13,511,967,151,120 | 50ce160e378f898ab8c85548b12e722775ef0e48 | 04a643a77927bc56ab58c7df91d4733321e61e51 | /tools_data/annotate_hair.py | ad6584f0d03d804fdd70e93a6ad8734a3a100c30 | [] | no_license | https://github.com/dcollins4096/p19_newscripts | d2fae1807170a4d70cf4c87222a6258211f993ff | 23c780dd15b60944ed354406706de85282d0bee6 | refs/heads/master | 2023-07-21T11:53:55.188383 | 2023-07-18T17:38:21 | 2023-07-18T17:38:21 | 215,159,839 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import yt
import matplotlib.pyplot as plt
from yt.visualization.plot_modifications import *
import pyximport; pyximport.install()
import particle_ops
import particle_grid_mask
from scipy.spatial import ConvexHull
import h5py
import time
import numpy as na
import os
import pdb
import copy
class HairCallback(PlotCallback):
"""
Add streamlines to any plot, using the *field_x* and *field_y*
from the associated data, skipping every *factor* datapoints like
'quiver'. *density* is the index of the amount of the streamlines.
*field_color* is a field to be used to colormap the streamlines.
If *display_threshold* is supplied, any streamline segments where
*field_color* is less than the threshold will be removed by having
their line width set to 0.
"""
_type_name = "hair"
_supported_geometries = ("cartesian", "spectral_cube", "polar", "cylindrical")
def __init__(
self,
field_x,
field_y,
factor=16,
density=1,
field_color=None,
display_threshold=None,
plot_args=None,
this_looper=None,
frame=None,
core_id=None
):
PlotCallback.__init__(self)
def_plot_args = {}
self.this_looper=this_looper
self.frame=frame
self.core_id=core_id
self.field_x = field_x
self.field_y = field_y
self.field_color = field_color
self.factor = factor
self.dens = density
self.display_threshold = display_threshold
if plot_args is None:
plot_args = def_plot_args
self.plot_args = plot_args
def __call__(self, plot):
import pdb
bounds = self._physical_bounds(plot)
xx0, xx1, yy0, yy1 = self._plot_bounds(plot)
# We are feeding this size into the pixelizer, where it will properly
# set it in reverse order
nx = plot.image._A.shape[1] // self.factor
ny = plot.image._A.shape[0] // self.factor
pixX = plot.data.ds.coordinates.pixelize(
plot.data.axis, plot.data, self.field_x, bounds, (nx, ny)
)
pixY = plot.data.ds.coordinates.pixelize(
plot.data.axis, plot.data, self.field_y, bounds, (nx, ny)
)
if self.field_color:
field_colors = plot.data.ds.coordinates.pixelize(
plot.data.axis, plot.data, self.field_color, bounds, (nx, ny)
)
if self.display_threshold:
mask = field_colors > self.display_threshold
lwdefault = matplotlib.rcParams["lines.linewidth"]
if "linewidth" in self.plot_args:
linewidth = self.plot_args["linewidth"]
else:
linewidth = lwdefault
try:
linewidth *= mask
self.plot_args["linewidth"] = linewidth
except ValueError as e:
err_msg = (
"Error applying display threshold: linewidth"
+ "must have shape ({}, {}) or be scalar"
)
err_msg = err_msg.format(nx, ny)
raise ValueError(err_msg) from e
else:
field_colors = None
X, Y = (
np.linspace(xx0, xx1, nx, endpoint=True),
np.linspace(yy0, yy1, ny, endpoint=True),
)
streamplot_args = {
"x": X,
"y": Y,
"u": pixX,
"v": pixY,
"density": self.dens,
"color": field_colors,
}
streamplot_args.update(self.plot_args)
plot._axes.streamplot(**streamplot_args)
plot._axes.set_xlim(xx0, xx1)
plot._axes.set_ylim(yy0, yy1)
#new stuff
import trackage
obnoxious_counter=0
try:
xax =plot.data.ds.coordinates.x_axis[plot.data.axis]
yax =plot.data.ds.coordinates.y_axis[plot.data.axis]
xaf = 'xyz'[xax]
yaf = 'xyz'[yax]
obnoxious_counter=1
core_id = self.core_id
this_looper=self.this_looper
thtr=this_looper.tr
ms = trackage.mini_scrubber(thtr,core_id)
ms.particle_pos(core_id)
frame_ind = np.where(this_looper.tr.frames ==self.frame)[0][0]
obnoxious_counter=2
all_x,all_y,all_z=ms.particle_x,ms.particle_y, ms.particle_z
all_p = [all_x,all_y,all_z]
all_p_s = np.stack(all_p)
max_max = all_p_s.max(axis=1).max(axis=1)
min_min = all_p_s.min(axis=1).min(axis=1)
cen = 0.5*(min_min+max_max)
XX,YY= all_p[xax].transpose(), all_p[yax].transpose()
plot._axes.scatter(XX[0,:],YY[0,:], c='k')
plot._axes.plot(XX[:frame_ind+1,:],YY[:frame_ind+1,:], c=[0.5]*4, zorder=7, linewidth=0.1)
plot._axes.scatter(XX[frame_ind,:],YY[frame_ind,:], c='r', s=1,zorder=1)
except:
print("Failed by ",obnoxious_counter)
pdb.set_trace()
#plot._axes.set_xlim(xx0, xx1)
#plot._axes.set_ylim(yy0, yy1)
| UTF-8 | Python | false | false | 5,177 | py | 530 | annotate_hair.py | 500 | 0.546455 | 0.53757 | 0 | 151 | 33.251656 | 102 |
justincurl/prior-time | 19,155,554,177,324 | 472787400978210e38254cdc15c865d5f15b34d7 | 8227e890fc6e222c600342024a2cac1838f97d97 | /otime/config.py | 8b2b8bb1f1b8d66ef21c678b40ceb6941b5881ed | [
"MIT"
] | permissive | https://github.com/justincurl/prior-time | aa95070e36bc2e52681a66e6580cff015426c540 | af74ca50272560a37f1ef9dd29816b9c58a58ac4 | refs/heads/master | 2021-04-24T13:32:56.437632 | 2020-12-27T02:09:47 | 2020-12-27T02:09:47 | 250,124,168 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
This file includes all available configuration options for the otime app.
Modify this file to set all your preferences - also modify `templates/otime/Results.html` to your liking
which will be displayed after all questions of all blocks have been answered.
It's not recommended to edit any of the other files.
Be sure to also check the README.md file!
"""
import random
from .block import Block
#: The total budget available for each choice
TOTAL_BUDGET = 5
NUM_BLOCKS = 4
#: Set to True if you want blocks to be randomized in order
RANDOMIZE_BLOCKS = False
#: Set to True if the choices per question in a block should be visualized as a slider
#: as opposed to single radio buttons
VISUALIZE_CHOICES_AS_SLIDER = False
#: The configuration for all blocks to be displayed to the user
#: Note:
#: - The given delays are treated as WEEKS where an initial delay of 0 means today.
#: - The order of interest_rates given is the order in which they will be display, i.e.
#: to change the order of display just change the order of values here
""" Edit the number of choices and values to put in the blocks here """
block_order = [i for i in range(NUM_BLOCKS)]
if RANDOMIZE_BLOCKS:
random.shuffle(block_order)
BLOCKS = [
Block(
values=[5, 4, 3, 2],
initial_payout_delay=0,
initial_to_last_payout_delay=1,
number_of_choices=6,
decrease_rate=0.8,
block_index= int(block_order[0])
),
Block(
values=[5, 4, 3, 2],
initial_payout_delay=0,
initial_to_last_payout_delay=2,
number_of_choices=6,
decrease_rate=0.8,
block_index= int(block_order[1])
),
Block(
values=[5, 4, 3, 2],
initial_payout_delay=1,
initial_to_last_payout_delay=1,
number_of_choices=6,
decrease_rate=0.8,
block_index= int(block_order[2])
),
Block(
values=[5, 4, 3, 2],
initial_payout_delay=1,
initial_to_last_payout_delay=2,
number_of_choices=6,
decrease_rate=0.8,
block_index= int(block_order[3])
)
]
| UTF-8 | Python | false | false | 2,099 | py | 51 | config.py | 17 | 0.65698 | 0.636494 | 0 | 69 | 29.42029 | 104 |
AndrewGYork/msim | 8,478,265,488,337 | 7205dbe00cc852d02a809b710677d29f035ac0d7 | cc6886ef475eebfa2f0e126a04041f5ec5427ff8 | /data_processing/convolve_sparse.py | 4ed41e647be0d42461f48ea3e2a11027343f9ba1 | [] | no_license | https://github.com/AndrewGYork/msim | 5d88784b21235f124d0c21ef835b69bdfe672039 | 5eb8370eb0979cf564b956a7e1adb3038d8f505e | refs/heads/master | 2021-01-13T00:52:25.160450 | 2015-10-15T17:14:28 | 2015-10-15T17:14:28 | 44,332,737 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import time
import numpy
def convolve_sparse(a, locations_list, amplitude_list=None):
if amplitude_list == None:
amplitude_list = [1 for l in locations_list]
assert len(locations_list) == len(amplitude_list)
output = numpy.zeros_like(a)
for j, location in enumerate(locations_list):
assert len(location) == len(a.shape)
input_slices = [
slice(
max(0, location[i]),
min(a.shape[i], a.shape[i] + location[i]))
for i in range(len(a.shape))]
output_slices = [
slice(
max(0, -location[i]),
min(a.shape[i], a.shape[i] - location[i]))
for i in range(len(a.shape))]
output[output_slices] += amplitude_list[j] * a[input_slices]
return output
a = numpy.zeros((50, 500, 500))
a[3, 10, 10] = 1
location_list = [
(-3, 0, 0),
(1, 1, -1)
]
print "Convolving with list..."
start = time.time()
b = convolve_sparse(a, location_list)
end = time.time()
print "Done convolving."
print "Time:", end-start
import pylab
fig = pylab.figure()
pylab.imshow(b.max(axis=0), cmap=pylab.cm.gray, interpolation='nearest')
fig.show()
| UTF-8 | Python | false | false | 1,242 | py | 41 | convolve_sparse.py | 40 | 0.556361 | 0.537037 | 0 | 43 | 26.883721 | 72 |
LibreChou/Data-Finance-Cup | 1,047,972,039,537 | 620a9e1e83f66c5ffda6142acf8ddeb268f8856f | 76e7a508d6a4fb07f2ee3a596ecb84e20a717041 | /xm_80.py | afead151f42e8b8271100da22ee4f9ba59760a70 | [] | no_license | https://github.com/LibreChou/Data-Finance-Cup | 986b31c228ea5dec340ffff838b9d3101249b8d3 | 55efd7c6438c697bb4d1ddcd30b12c2c6e9fe0e0 | refs/heads/master | 2022-04-20T20:17:07.342575 | 2019-12-21T02:00:08 | 2019-12-21T02:00:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # !pip install xgboost --user
# !pip install tqdm --user
# !pip install seaborn --user
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def load_xgb_data():
train = pd.read_csv("new_data/train.csv")
train_target = pd.read_csv('new_data/train_target.csv')
train = train.merge(train_target, on='id')
test = pd.read_csv("new_data/test.csv")
test['target'] = -1
df = pd.concat([train, test], sort=False, axis=0)
# 删除重复列
duplicated_features = ['x_0', 'x_1', 'x_2', 'x_3', 'x_4', 'x_5', 'x_6',
'x_7', 'x_8', 'x_9', 'x_10', 'x_11', 'x_13',
'x_15', 'x_17', 'x_18', 'x_19', 'x_21',
'x_23', 'x_24', 'x_36', 'x_37', 'x_38', 'x_57', 'x_58',
'x_59', 'x_60', 'x_77', 'x_78'] + \
['x_22', 'x_40', 'x_70'] + \
['x_41'] + \
['x_43'] + \
['x_45'] + \
['x_61']
# df = df.drop(columns=duplicated_features)
###############
###############
x_feature = []
for i in range(79):
x_feature.append('x_{}'.format(i))
no_features = ['id', 'target', 'isNew']
features = []
numerical_features = ['lmt', 'certValidBegin', 'certValidStop']
categorical_features = [fea for fea in df.columns if fea not in numerical_features + no_features]
###########
import time
df['certValidPeriod'] = df['certValidStop'] - df['certValidBegin']
df['begin'] = df['certValidBegin'].apply(lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
df['end'] = df['certValidStop'].apply(lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
df['begin'] = df['begin'].apply(lambda x: int(x.split('-')[0]))
df['end'] = df['end'].apply(lambda x: int(x.split('-')[0]))
df['val_period'] = df['end'] - df['begin']
###########
# 0.76新加
###########
cols = []
df['certId12'] = df['certId'].apply(lambda x: int(str(x)[:2]) if x != -999 else -999)
df['certId34'] = df['certId'].apply(lambda x: int(str(x)[2:4]) if x != -999 else -999)
df['certId56'] = df['certId'].apply(lambda x: int(str(x)[4:]) if x != -999 else -999)
from sklearn.preprocessing import LabelEncoder
df['certId12_basicLevel'] = df['certId12'].astype(str) + df['basicLevel'].astype(str)
df['certId34_basicLevel'] = df['certId34'].astype(str) + df['basicLevel'].astype(str)
df['certId56_basicLevel'] = df['certId56'].astype(str) + df['basicLevel'].astype(str)
df['certId12_loanProduct'] = df['certId12'].astype(str) + df['loanProduct'].astype(str)
df['certId34_loanProduct'] = df['certId34'].astype(str) + df['loanProduct'].astype(str)
df['certId56_loanProduct'] = df['certId56'].astype(str) + df['loanProduct'].astype(str)
# cols += ['certId12_loanProduct', 'certId34_loanProduct','certId56_loanProduct']
cols += ['certId12_basicLevel', 'certId34_basicLevel', 'certId56_basicLevel',
'certId12_loanProduct', 'certId34_loanProduct', 'certId56_loanProduct']
df['dist56'] = df['dist'].apply(lambda x: int(str(x)[4:]) if x != -999 else -999)
df['dist56_basicLevel'] = df['dist56'].astype(str) + df['basicLevel'].astype(str)
df['dist56_loanProduct'] = df['dist56'].astype(str) + df['loanProduct'].astype(str)
# cols += ['dist56_loanProduct']
cols += ['dist56_basicLevel', 'dist56_loanProduct']
# 估计有用
# df['residentAddr56'] = df['residentAddr'].apply(lambda x: int(str(x)[4:]) if x != -999 else -999)
# df['residentAddr56_basicLevel'] = df['residentAddr56'].astype(str) + df['basicLevel'].astype(str)
# df['residentAddr56_loanProduct'] = df['residentAddr56'].astype(str) + df['loanProduct'].astype(str)
# cols += ['residentAddr56_loanProduct']
# cols += ['residentAddr56_basicLevel', 'residentAddr56_loanProduct']
####
# df['certId12_lmt'] = df.groupby('certId12')['lmt'].transform('mean')
# df['certId12_lmt'] = df.groupby('certId12')['lmt'].transform('median')
# df['certId34_lmt'] = df.groupby('certId34')['lmt'].transform('mean')
# df['certId34_lmt'] = df.groupby('certId34')['lmt'].transform('median')
# df['certId56_lmt'] = df.groupby('certId56')['lmt'].transform('mean')
# df['certId56_lmt'] = df.groupby('certId56')['lmt'].transform('median')
################
# things not work
# df['certId12_edu'] = df['certId12'].astype(str) + df['edu'].astype(str)
# df['certId34_edu'] = df['certId34'].astype(str) + df['edu'].astype(str)
# df['certId56_edu'] = df['certId56'].astype(str) + df['edu'].astype(str)
# 'certId12_edu', 'certId34_edu','certId56_edu'
# useless = ['x_59','x_22','x_23','x_24','x_30','x_31','x_32','x_35','x_36','x_37','x_38','x_39','x_40','x_42',
# 'x_57','x_58','x_60','x_69','x_70','x_77','x_78','ncloseCreditCard','unpayIndvLoan','unpayOtherLoan',
# 'unpayNormalLoan','5yearBadloan','x_21','x_19','is_edu_equal','x_9','x_7','x_8','x_4','x_10','x_11',
# 'x_1','x_6','x_13','x_3','x_18','x_15','x_17','x_2','x_5']
################
# 待尝试
# 四个一起降分
# df['certId12_job'] = df['certId12'].astype(str) + df['job'].astype(str)
# df['certId12_ethnic'] = df['certId12'].astype(str) + df['ethnic'].astype(str)
# cols += ['certId12_job', 'certId12_ethnic']
# df['certId12_edu'] = df['certId12'].astype(str) + df['edu'].astype(str)
# df['certId12_highestEdu'] = df['certId12'].astype(str) + df['highestEdu'].astype(str)
# cols += ['certId12_edu', 'certId12_highestEdu']
# df['edu_basicLevel'] = df['edu'].astype(str) + df['basicLevel'].astype(str)
# df['edu_loanProduct'] = df['edu'].astype(str) + df['loanProduct'].astype(str)
# df['edu_lmt'] = df.groupby('edu')['lmt'].transform('mean')
# df['edu_lmt'] = df.groupby('edu')['lmt'].transform('median')
# cols += ['edu_basicLevel', 'edu_loanProduct']
# df['highestEdu_basicLevel'] = df['highestEdu'].astype(str) + df['basicLevel'].astype(str)
# df['highestEdu_loanProduct'] = df['highestEdu'].astype(str) + df['loanProduct'].astype(str)
# df['highestEdu_lmt'] = df.groupby('highestEdu')['lmt'].transform('mean')
# df['highestEdu_lmt'] = df.groupby('highestEdu')['lmt'].transform('median')
# cols += ['highestEdu_basicLevel', 'highestEdu_loanProduct']
for col in cols:
lab = LabelEncoder()
df[col] = lab.fit_transform(df[col])
cols += ['certId12', 'certId34', 'certId56', 'dist56']
cols += ['bankCard', 'residentAddr', 'certId', 'dist', 'age', 'job', 'basicLevel', 'loanProduct', 'val_period']
# count
for col in cols:
df['{}_count'.format(col)] = df.groupby(col)['id'].transform('count')
df['is_edu_equal'] = (df['edu'] == df['highestEdu']).astype(int)
print(df.shape)
feature = [fea for fea in df.columns if fea not in no_features + ['begin', 'end']]
train, test = df[:len(train)], df[len(train):]
return train,test,feature
train,test,feature=load_xgb_data()
import numpy as np
import xgboost as xgb
from sklearn.model_selection import StratifiedKFold, KFold
n_fold = 5
y_scores = 0
y_pred_l1 = np.zeros([n_fold, test.shape[0]])
y_pred_all_l1 = np.zeros(test.shape[0])
fea_importances = np.zeros(len(feature))
label = ['target']
# [1314, 4590]
kfold = StratifiedKFold(n_splits=n_fold, shuffle=True, random_state=1314)
for i, (train_index, valid_index) in enumerate(kfold.split(train[feature], train[label])):
if i != 1:
print(i)
X_train, y_train, X_valid, y_valid = train.loc[train_index][feature], train[label].loc[train_index], \
train.loc[valid_index][feature], train[label].loc[valid_index]
bst = xgb.XGBClassifier(max_depth=3, n_estimators=10000,verbosity=1, learning_rate=0.01)
bst.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], eval_metric='auc', verbose=500,
early_stopping_rounds=500)
y_pred_l1[i] = bst.predict_proba(test[feature])[:, 1]
y_pred_all_l1 += y_pred_l1[i]
y_scores += bst.best_score
fea_importances += bst.feature_importances_
test['target'] = y_pred_all_l1 / 4
print('average score is {}'.format(y_scores / 4)) | UTF-8 | Python | false | false | 8,317 | py | 51 | xm_80.py | 30 | 0.577866 | 0.533043 | 0 | 184 | 43.98913 | 115 |
jakebyford/web-scraping-challenge | 17,497,696,791,287 | 9a351f42e96e1a18208cf2c37f20b700c16508f5 | 0a54454a452e91d2c4b53c6cd01fecb1c6bd2e6f | /Mission to Mars/app.py | c9db3cd5a35986212db77d000aa657a9ab5b3acc | [] | no_license | https://github.com/jakebyford/web-scraping-challenge | c8f28d6502d7e956d220b8c717eb0c61a1dcee1f | a8e0f764c2a5c4122d361f54aa0b4ad69e9c0be8 | refs/heads/master | 2022-12-13T03:11:23.310368 | 2020-09-02T21:26:45 | 2020-09-02T21:26:45 | 290,950,206 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
import scrape_mars
app = Flask(__name__)
#Allowing mongo to be used in flask - use mars_app - is the identical code in mongodb
mongo = PyMongo(app, uri = "mongodb://localhost:27017/mars_app")
@app.route("/")
def init_browser():
#
mars_data_db = mongo.db.mars_collection.find_one()
return render_template("index.html", mars = mars_data_db)
@app.route("/scrape")
def scrape():
mars_data = scrape_mars.scrape_info()
mongo.db.mars_collection.update({}, mars_data, upsert = True)
return redirect("/")
if __name__ == "__main__":
app.run(debug = True)
| UTF-8 | Python | false | false | 671 | py | 2 | app.py | 2 | 0.66766 | 0.660209 | 0 | 31 | 20.645161 | 85 |
ztl2004/recover | 5,385,889,017,475 | aa0efed1aff12d8032b96c27d9cdd568bae84c67 | d783ce5216bafe180f6d63986e7754a1df490139 | /models.py | 031b86e776d57fa9d4d5bfb8472486bee983ba9d | [] | no_license | https://github.com/ztl2004/recover | 4e91dcb1020bd12d3577e11bf0e1cd1bc5d6cda2 | 0367af4145488fb487293e09a81a229d9b103377 | refs/heads/master | 2021-01-19T00:16:33.427391 | 2013-07-06T11:52:53 | 2013-07-06T11:52:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, BigInteger, Text
Base = declarative_base()
class Rat(Base):
__tablename__ = 'rats'
id = Column(Integer, primary_key=True)
name = Column(String(100))
title = Column(String(100))
def __init__(self, name, title):
self.name = name
self.title = title
def __repr__(self):
return "<Rat('%s','%s')>" % (self.name, self.title)
class Event(Base):
__tablename__ = 'event'
id = Column(Integer, primary_key=True)
title = Column(String(500))
location = Column(String(500))
content = Column(Text)
def __init__(self, name):
self.title = title
self.location = location
self.content = content
def __repr__(self):
return "<Event('%s')>" % (self.title)
| UTF-8 | Python | false | false | 887 | py | 1 | models.py | 1 | 0.600902 | 0.587373 | 0 | 34 | 25.058824 | 86 |
adambaranec/math | 11,287,174,079,024 | d56bf712fd061d9cf0b937b7364cbd09cf9f577e | 7780dc31dc58ce153409b3f043543bbff1a3c707 | /count.py | 454d309b08a1c6753c3a46ab8a1f3b7bd7424c34 | [] | no_license | https://github.com/adambaranec/math | 828c087fc2516d0f783493b1219b9f685773cc1e | 1294428f79a27d85c1d85a9ed378bc01587c1b9e | refs/heads/main | 2023-08-22T05:17:53.160958 | 2021-10-19T18:27:43 | 2021-10-19T18:27:43 | 408,085,582 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import ui, math, texts as tx
from tkinter import messagebox
def prvy():
if ui.shape.get() == 1:
try:
getside = ui.dlzka.get()
side = float(getside)
obsah = side * side
zapis = str(obsah)
stav = tx.writesqarea + zapis
ui.l_obsahstvorca.pack_forget()
ui.l_obsahstvorca.pack()
ui.l_obsahstvorca.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
if ui.shape.get() == 2:
try:
geta = ui.a.get()
getb = ui.b.get()
sidea = float(geta)
sideb = float(getb)
obsah = sidea * sideb
zapis = str(obsah)
stav = tx.writerectarea + zapis
ui.l_obsahobdlznika.pack_forget()
ui.l_obsahobdlznika.pack()
ui.l_obsahobdlznika.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
if ui.shape.get() == 3:
try:
getr = ui.r.get()
radius = float(getr)
obsah = math.pi * radius*radius
zapis = str(obsah)
stav = tx.writecirclea + zapis
ui.l_obsahkruhu.pack_forget()
ui.l_obsahkruhu.pack()
ui.l_obsahkruhu.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
if ui.shape.get() == 4:
try:
geta = ui.a.get()
getb = ui.b.get()
sidea = float(geta)
sideb = float(getb)
vysledok = sidea*sidea + sideb*sideb
zapis = str(vysledok)
stav = tx.writepytres + zapis
ui.l_vysledokvety.pack_forget()
ui.l_vysledokvety.pack()
ui.l_vysledokvety.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
def druhy():
if ui.shape.get() == 1:
try:
getside = ui.dlzka.get()
side = float(getside)
obvod = side * 4
zapis = str(obvod)
stav = tx.writesqper + zapis
ui.l_obvodstvorca.pack_forget()
ui.l_obvodstvorca.pack()
ui.l_obvodstvorca.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
if ui.shape.get() == 2:
try:
geta = ui.a.get()
getb = ui.b.get()
sidea = int(geta)
sideb = int(getb)
obvod = 2 * (sidea + sideb)
zapis = str(obvod)
stav = tx.writerectper + zapis
ui.l_obvodobdlznika.pack_forget()
ui.l_obvodobdlznika.pack()
ui.l_obvodobdlznika.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
if ui.shape.get() == 3:
try:
getr = ui.r.get()
radius = int(getr)
obvod = 2 * math.pi * radius
zapis = str(obvod)
stav = tx.writecirclep + zapis
ui.l_obvodkruhu.pack_forget()
ui.l_obvodkruhu.pack()
ui.l_obvodkruhu.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
if ui.shape.get() == 4:
try:
geta = ui.a.get()
getb = ui.b.get()
sidea = int(geta)
sideb = int(getb)
vypocet = sidea*sidea + sideb*sideb
vysledok = math.sqrt(vypocet)
zapis = str(vysledok)
stav = tx.writepytlen + zapis
ui.l_dlzkaodvesny.pack_forget()
ui.l_dlzkaodvesny.pack()
ui.l_dlzkaodvesny.config(text=stav)
except ValueError:
messagebox.showerror(tx.attention, tx.accept)
ui.obsah.config(command=prvy)
ui.obvod.config(command=druhy)
ui.vysledok.config(command=prvy)
ui.realna_dlzka.config(command=druhy) | UTF-8 | Python | false | false | 3,877 | py | 8 | count.py | 7 | 0.535208 | 0.53237 | 0 | 115 | 32.721739 | 56 |
ZZhangsyx/RE01_NOAA_GPM | 5,815,385,725,879 | 33a96e8037b81b040a923baf2246f655d44ad74e | 73982949ace4ef0dfc0df98accabaf45de8fc20c | /Code/Train_class.py | bf5be2e17635bf9057240cc3e79fd78ffdcac453 | [] | no_license | https://github.com/ZZhangsyx/RE01_NOAA_GPM | 5c959efb7c734046f3c8ee1942081defb20194f2 | fbba1ce5f90fb8953cbde8813b0956f5ddf6c0f5 | refs/heads/master | 2023-07-14T06:34:16.194060 | 2021-08-25T01:38:40 | 2021-08-25T01:38:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # coding=utf-8
"""
Author: Zhang Zhi
Email: zhangzh49@mail2.sysu.edu.cn
Date: 2021/1/5
"""
import numpy as np
import pandas as pd
import tensorflow as tf
import os
from imblearn.over_sampling import SMOTE
import joblib
from sklearn.model_selection import RandomizedSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from scipy.stats import randint
import xgboost as xgb
def calculate_acc(A, B, isShow=True):
"""
:param A: Label
:param B: Predict value
:param isShow: Whether to plot
:return: Evaluation indicators: POD, FAR, accuracy, F1-score
"""
A[A != 0] = 1
B[B != 0] = 1
A, B = np.array(A), np.array(B)
num_A = len(A)
TP = np.sum(np.multiply(A, B))
TN = np.sum((A + B) == 0)
FP = np.sum((A - B) == -1)
FN = np.sum((A - B) == 1)
POD = TP / np.sum(A)
FAR = FP / np.sum(B)
accuracy = (TP + TN) / num_A
precision = TP / (TP + FP)
recall = TP / (TP + FN)
F = precision * recall * 2 / (precision + recall)
if isShow:
print('****** Evaluation Score ******')
print("POD: ", '%.3f' % POD)
print("FAR: ", '%.3f' % FAR)
print("ACC: ", '%.3f' % accuracy)
print("F: ", '%.3f' % F, '\n')
return POD, FAR, accuracy, F
class Model(object):
def __init__(self, model_name, basin_name):
"""
:param model_name: Model name
:param basin_name: Basin name
"""
self.name = model_name
self.basin = basin_name
self.path = '../Model/' + self.name + '_C_' + self.basin + '.pkl'
def load(self):
"""
:return: Load model
"""
if os.path.isfile(self.path):
self.model = joblib.load(self.path)
return self.model
else:
print('Model didnt exsit!')
def predict(self, x_train, x_test, y_train, y_test):
"""
:param x_train: Input feature in training step
:param x_test: Input feature in testing step
:param y_train: Output feature in training step
:param y_test: Output feature in testing step
:return: Predicting class value (Rain/No rain)
"""
print('Predicting ' + self.name + ':')
train_class_pre = self.model.predict(x_train)
calculate_acc(train_class_pre, y_train)
test_class_pre = self.model.predict(x_test)
calculate_acc(test_class_pre, y_test)
return train_class_pre, test_class_pre
def SVM(x_train, x_test, y_train, y_test, BN):
"""
:param BN: Basin name's abbreviation [str]
:param x_train: Input feature in training step
:param x_test: Input feature in testing step
:param y_train: Output feature in training step
:param y_test: Output feature in testing step
"""
Model_SVM = Model(model_name='SVM', basin_name=BN)
if os.path.isfile(Model_SVM.path):
model = Model_SVM.load()
else:
model = SVC(C=1, kernel='rbf', shrinking=True, max_iter=-1)
model.fit(x_train, y_train)
joblib.dump(model, Model_SVM.path)
model = Model_SVM.load()
train_class_pre, test_class_pre = Model_SVM.predict(
x_train, x_test, y_train, y_test)
return train_class_pre, test_class_pre
def RF(x_train, x_test, y_train, y_test, BN):
Model_RF = Model(model_name='RF', basin_name=BN)
if os.path.isfile(Model_RF.path):
model = Model_RF.load()
else:
model = RandomForestClassifier(random_state=2020)
param_distribs = {'n_estimators': randint(low=1, high=200),
'max_features': randint(low=1, high=10),
}
rnd_search = RandomizedSearchCV(
model,
param_distributions=param_distribs,
n_iter=10,
cv=5,
random_state=2020)
rnd_search.fit(x_train, y_train)
model = rnd_search.best_estimator_
print('Model RFC Fitted!')
joblib.dump(model, Model_RF.path)
model = Model_RF.load()
train_class_pre, test_class_pre = Model_RF.predict(
x_train, x_test, y_train, y_test)
return train_class_pre, test_class_pre
def ANN(x_train, x_test, y_train, y_test, BN):
checkpoint_ANN = '../model/ANN_C_' + BN + '.ckpt'
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(2, activation='softmax')
])
model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=False),
metrics=['sparse_categorical_accuracy'])
if os.path.exists(checkpoint_ANN + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_ANN)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_ANN,
save_weights_only=True,
save_best_only=True)
if not os.path.isfile(checkpoint_ANN):
model.fit(
np.array(x_train),
np.array(y_train),
batch_size=128,
epochs=100,
validation_data=[
np.array(x_test),
np.array(y_test)],
validation_freq=1,
callbacks=[cp_callback])
print('Predicting ANN:')
train_class_pre = model.predict(x_train).argmax(axis=1)
calculate_acc(train_class_pre, y_train)
test_class_pre = model.predict(x_test).argmax(axis=1)
calculate_acc(test_class_pre, y_test)
return train_class_pre, test_class_pre
def XGB(x_train, x_test, y_train, y_test, BN):
Model_XGB = Model(model_name='XGB', basin_name=BN)
if os.path.isfile(Model_XGB.path):
model = Model_XGB.load()
else:
model = xgb.XGBClassifier(
max_depth=5,
n_estimators=1000,
colsample_bytree=0.8,
subsample=0.8,
nthread=10,
learning_rate=0.1,
min_child_weight=2)
model.fit(x_train, y_train)
print('Model XGBC Fitted!')
joblib.dump(model, Model_XGB.path)
model = Model_XGB.load()
train_class_pre, test_class_pre = Model_XGB.predict(
x_train, x_test, y_train, y_test)
return train_class_pre, test_class_pre
def Train_class(in_path, out_path, BN, BS, isBalance):
"""
:param in_path: Csv path
:param out_path: Save path
:param BN: Basin name's abbreviation [str]
:param BS: One word to express basin [str]
:param isBalance: Whether the data is balance in class distribution
:return: Predicting class value to csv file
"""
print('Loading data...')
csv_name = os.path.join(in_path, 'data_DEA1.csv')
data_pro = pd.read_csv(csv_name)
data_pro['Time'] = pd.to_datetime(data_pro['Time'])
data_pro = data_pro.set_index('Time')
print('Data processing...')
Train = data_pro['2015':'2017']
Test = data_pro['2018']
y_train, y_test = Train['isRain_CMPA'], Test['isRain_CMPA']
x_train = Train.drop(['isRain_CMPA', 'CMPA_' + BS], axis=1)
x_test = Test.drop(['isRain_CMPA', 'CMPA_' + BS], axis=1)
if not isBalance:
smo = SMOTE(random_state=42)
x_train, y_train = smo.fit_sample(x_train, y_train)
print('Execute modeling..')
nonsen, Test['ANN_class'] = ANN(x_train, x_test, y_train, y_test, BN)
nonsen, Test['SVM_class'] = SVM(x_train, x_test, y_train, y_test, BN)
nonsen, Test['RF_class'] = RF(x_train, x_test, y_train, y_test, BN)
nonsen, Test['XGB_class'] = XGB(x_train, x_test, y_train, y_test, BN)
# Compare with GPM
isRain_GPM = np.array(Test['GPM_' + BS])
isRain_GPM[isRain_GPM > 0] = 1
Test['GPM_class'] = isRain_GPM
calculate_acc(isRain_GPM, y_test)
# Save
Test.to_csv(os.path.join(out_path, 'Test_class' + BN + '.csv'), index=True)
else:
print('Execute modeling..')
Train['SVM_class'], Test['SVM_class'] = SVM(x_train, x_test, y_train, y_test)
Train['RF_class'], Test['RF_class'] = RF(x_train, x_test, y_train, y_test)
Train['ANN_class'], Test['ANN_class'] = ANN(x_train, x_test, y_train, y_test)
Train['XGB_class'], Test['XGB_class'] = XGB(x_train, x_test, y_train, y_test)
# Compare with GPM
isRain_GPM = np.array(Train['GPM_' + BS])
isRain_GPM[isRain_GPM > 0] = 1
Train['GPM_class'] = isRain_GPM
calculate_acc(isRain_GPM, y_train)
isRain_GPM = np.array(Test['GPM_' + BS])
isRain_GPM[isRain_GPM > 0] = 1
Test['GPM_class'] = isRain_GPM
calculate_acc(isRain_GPM, y_test)
# Save
Train.to_csv(os.path.join(out_path, 'Train_class' + BN + '.csv'), index=True)
Test.to_csv(os.path.join(out_path, 'Test_class' + BN + '.csv'), index=True)
print('Code deal!')
def main():
BN = 'DJ'
BS = 'DongJ'
processed_path = '../data/processed_' + BN +'2'
DEA_path = processed_path + '/DEA'
isBalance = False
Train_class(DEA_path, processed_path, BN, BS, isBalance)
if __name__ == '__main__':
main()
| UTF-8 | Python | false | false | 9,676 | py | 10 | Train_class.py | 5 | 0.555854 | 0.545408 | 0 | 279 | 32.65233 | 85 |
colbyjantzen/my-first-blog | 4,904,852,672,752 | 45fae0d654257f7dbb34f9cb1bd7155bc7a65dd5 | 2f54353bcb535093560f3a0e63c62859d6055846 | /blog/migrations/0007_auto_20180226_2126.py | 1cc8c59e0d5930866914a9076cd195b941e044a4 | [] | no_license | https://github.com/colbyjantzen/my-first-blog | 4f3f7034559e700118da81256d3d749209848d10 | e0228208ab6c917eead518f3ec3dfbb3d12f17ac | refs/heads/master | 2021-04-27T02:27:14.656091 | 2018-03-23T00:08:52 | 2018-03-23T00:08:52 | 122,695,051 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-27 02:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_post_date'),
]
operations = [
migrations.AlterField(
model_name='temperature',
name='date',
field=models.DateField(),
),
]
| UTF-8 | Python | false | false | 429 | py | 7 | 0007_auto_20180226_2126.py | 5 | 0.58042 | 0.531469 | 0 | 20 | 20.45 | 48 |
PINTO0309/PINTO_model_zoo | 17,566,416,260,342 | 6fd166fc37fce37fa8ae4d62e4d858d79a9bc60d | 4e2117a4381f65e7f2bb2b06da800f40dc98fa12 | /158_HR-Depth/onnx_merge.py | 4de8daa29ba205aebcc0a0960cb6db63b98afac9 | [
"MIT",
"AGPL-3.0-only",
"LicenseRef-scancode-proprietary-license"
] | permissive | https://github.com/PINTO0309/PINTO_model_zoo | 84f995247afbeda2543b5424d5e0a14a70b8d1f1 | ff08e6e8ab095d98e96fc4a136ad5cbccc75fcf9 | refs/heads/main | 2023-09-04T05:27:31.040946 | 2023-08-31T23:24:30 | 2023-08-31T23:24:30 | 227,367,327 | 2,849 | 520 | MIT | false | 2023-08-31T23:24:31 | 2019-12-11T13:02:40 | 2023-08-31T20:36:11 | 2023-08-31T23:24:30 | 186,868 | 2,861 | 508 | 8 | Python | false | false | import onnx
import onnx_graphsurgeon as gs
import sclblonnx as so
H=192
W=640
MODEL1=f'lite_hr_depth_k_t_encoder_{H}x{W}.onnx'
MODEL2=f'lite_hr_depth_k_t_depth_{H}x{W}.onnx'
MODEL3=f'lite_hr_depth_k_t_encoder_depth_{H}x{W}.onnx'
graph1 = gs.import_onnx(onnx.load(MODEL1))
for n in graph1.nodes:
for cn in n.inputs:
if cn.name[-1:] != 'a':
cn.name = f'{cn.name}a'
else:
pass
for cn in n.outputs:
if cn.name[-1:] != 'a':
cn.name = f'{cn.name}a'
else:
pass
graph1_outputs = [o.name for o in graph1.outputs]
print(f'graph1 outputs: {graph1_outputs}')
onnx.save(gs.export_onnx(graph1), "graph1.onnx")
graph2 = gs.import_onnx(onnx.load(MODEL2))
graph2_inputs = []
for n in graph2.nodes:
for cn in n.inputs:
if cn.name[-1:] != 'b':
cn.name = f'{cn.name}b'
else:
pass
for cn in n.outputs:
if cn.name[-1:] != 'b':
cn.name = f'{cn.name}b'
else:
pass
graph2_inputs = [i.name for i in graph2.inputs]
print(f'graph2 inputs: {graph2_inputs}')
onnx.save(gs.export_onnx(graph2), "graph2.onnx")
"""
graph1 outputs: [
'317a',
'852a',
'870a',
'897a',
'836a'
]
graph2 inputs: [
'0b',
'input.1b',
'input.13b',
'input.25b',
'input.37b'
]
"""
sg1 = so.graph_from_file('graph1.onnx')
sg2 = so.graph_from_file('graph2.onnx')
sg3 = so.merge(
sg1,
sg2,
outputs=graph1_outputs,
inputs=graph2_inputs
)
so.graph_to_file(sg3, MODEL3)
| UTF-8 | Python | false | false | 1,540 | py | 1,252 | onnx_merge.py | 301 | 0.571429 | 0.527273 | 0 | 69 | 21.318841 | 54 |
2923mark/Python_learn | 16,784,732,228,228 | ef6edffa5739159ce79c62b1b314465c017e7217 | 3f4789c1479f7c6b34ebda4e0a0cdb7277adc65d | /in.py | 71b6d8d92a266a3b630491400f16a10935b42439 | [] | no_license | https://github.com/2923mark/Python_learn | a8932f80fe12ccc5d7d0e55b1608e801987ed4f7 | 405bcb70deb1c9ac6477de37e6e05b55e9ef2e3a | refs/heads/master | 2021-01-01T06:27:15.917088 | 2013-08-13T18:59:45 | 2013-08-13T18:59:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python
Users = ['mlh', 'foo', 'bar']
raw_input ('Enter your user name:') in Users
| UTF-8 | Python | false | false | 93 | py | 2 | in.py | 1 | 0.623656 | 0.623656 | 0 | 3 | 30 | 44 |
shu004/calculator-2 | 3,839,700,795,289 | 5c5bef3660b16c6af7d382a64ab0e8e30cc495f5 | bc215d2187944bd0cd98329efda339716e7282b5 | /calculator.py | 98c6d0be5b4a15714d307b1c26c88281160c4aac | [] | no_license | https://github.com/shu004/calculator-2 | 909db9100c52247f0fa57c3d3174e34fb1f4c51b | fc65b0e773e88cfff6d56437ad2e6a3aebfcb2a6 | refs/heads/main | 2023-09-06T02:17:43.818712 | 2021-11-04T00:15:08 | 2021-11-04T00:15:08 | 424,419,930 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | """CLI application for a prefix-notation calculator."""
from functools import reduce
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
while True:
command = input("> ").split(" ")
operator = command[0]
if operator == "q":
break
else:
if len(command) == 3:
try:
num1 = float(command[1])
num2 = float(command[2])
if operator == '+':
print(add(num1, num2))
elif operator == '-':
print(subtract(num1, num2))
elif operator == '*':
print(multiply(num1, num2))
elif operator == '/':
print(divide(num1, num2))
elif operator == 'pow':
print(power(num1, num2))
elif operator == 'mod':
print(mod(num1, num2))
else:
print("Not a valid command")
except ValueError:
print("Please enter a number after the operator")
elif len(command) == 2:
try:
num1 = float(command[1])
if operator == 'square':
print(square(num1))
elif operator == 'cube':
print(cube(num1))
else:
print("Not a valid command")
except ValueError:
print("Please enter a number after the operator")
elif len(command) > 3:
numbers = []
for num in command[1:]:
try:
num = float(num)
numbers.append(num)
except ValueError:
print('Please enter numbers after the operator')
if operator == '+':
print(reduce(add, numbers))
elif operator == '-':
print(reduce(subtract, numbers))
elif operator == '*':
print(reduce(multiply, numbers))
elif operator == '/':
print(reduce(divide, numbers))
else:
print("Not a valid command")
else:
print("Not a valid command")
| UTF-8 | Python | false | false | 2,283 | py | 1 | calculator.py | 1 | 0.43802 | 0.42707 | 0 | 68 | 32.485294 | 70 |
yl54/interview-problems | 8,718,783,653,844 | 9e8b068d089e1cf23d5af1755a433a9aac428ad5 | b8254aa9d1b6efeaba35d72b79548c8db6c53628 | /python/tree/contacts.py | 810e95429cd2b017f7a2c2a39a3b0ecdea3c7ab2 | [] | no_license | https://github.com/yl54/interview-problems | eefbd79f538ce7b8e41fffd39b3c53938f91dcc1 | 357bb35c7bc78c1df8c240d423e3727ca1a73abd | refs/heads/master | 2023-08-23T20:59:24.728841 | 2023-08-21T19:23:25 | 2023-08-21T19:23:25 | 115,690,385 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #
# Complete the 'contacts' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_STRING_ARRAY queries as parameter.
#
"""
given a set of queries to add a string to the state and find a string
implement these queries
"""
"""
test cases
different starting characters
a single string
multiple strings with the same prefixes
multiple strings with the partially same prefixes
multiple strings with the different prefixes
"""
"""
ways to do this
use a trie to store all of the combinations
while building the trie, you can store the number of strings that the prefix is a substring of. this makes it so you don't have to recurse further once you get to the query prefix
"""
def contacts(queries):
return optimizeTrie(queries)
# -- trie node implementation --
# trie node class
class Node:
# init function
def __init__(self):
# dict to next trie node
# keys: alphabet characters
# values: next trie node
self.children = {}
# count of words it is a prefix of
self.count = 0
# is word
self.is_word = False
# -- trie with no optimization --
# function for this
def noOptimizeTrie(queries):
# check if the input is illegal
# hold results
result = []
# create a root trie node that is empty
root = Node()
# for each query
for q in queries:
# if the command is add
if q[0] == "add":
# run the add function
root = noOptimizeAdd(root, q[1])
# else if the command is find
elif q[0] == "find":
# run the find function
result.append(noOptimizeFind(root, q[1]))
# else:
# illegal
# return results
return result
# function to add to the trie node
# input:
# - root of trie
# - string
def noOptimizeAdd(root, input):
# hold onto current pointer of trie
# start at the root
current = root
# loop over characters of string in order
for i in range(0, len(input)):
# get the character of the character to the prefix array
ch = input[i]
# if the children array has no child there
if ch not in current.children:
# create a new trie node
node = Node()
# assign it to that array index
current.children[ch] = node
# traverse to the child at the index
current = current.children[ch]
# set is_word to true for the current pointer's trie node
current.is_word = True
# return trie root
return root
# function to find the number of matches in the trie
# - root of trie
# - string
def noOptimizeFind(root, input):
# hold onto current pointer of trie
# start at the root
current = root
# hold onto matches of words found
result = 0
# track if we need to keep continuing
cont = True
i = 0
# for i in range 0 to length of string
while i < len(input):
# get the character at the index
ch = input[i]
# if the children array does not have a trie node at the index
if ch not in current.children:
cont = False
# break
break
# traverse to the child node
current = current.children[ch]
i += 1
if cont:
# go through the rest of the children
result += findAllChildren(current)
# return number of matches
return result
# function for recursive traversal
def findAllChildren(node):
# -- illegal case --
# -- base case --
# hold onto result
result = 0
# for all children
for ch in node.children:
# result +=
result += findAllChildren(node.children[ch])
# check if current one is a word
if node.is_word:
result += 1
# return number
return result
# -- trie with substring with count optimization --
def optimizeTrie(queries):
# check if the input is illegal
# hold results
result = []
# create a root trie node that is empty
root = Node()
# for each query
for q in queries:
# if the command is add
if q[0] == "add":
# run the add function
_, root = optimizeAdd(root, q[1], 0)
# else if the command is find
elif q[0] == "find":
# run the find function
result.append(optimizeFind(root, q[1]))
# else:
# illegal
# return results
return result
# function to add to the trie node
# this will need to be a recursive function to return results up the trie
# input:
# - root of trie
# - string
# - index of string currently evaluated
#
# return:
# - number of subwords
def optimizeAdd(node, input, index):
# -- illegal case --
# check if index is out of bounds for string
if index >= len(input):
# return 0
return 0, node
# -- current case --
#print(index)
# get the index of the character to the prefix array
ch = input[index]
# hold onto whether a new child was created
new_child = False
next_node = None
# if the children array has no child there
if ch not in node.children:
# create a new trie node
next_node = Node()
# assign it to that array index
node.children[ch] = next_node
else:
next_node = node.children[ch]
# result = recurse to child array and index + 1
result, next_node = optimizeAdd(next_node, input, index + 1)
# check if the current node is the last index
if index == len(input) - 1:
# set the trie node is word to true
next_node.is_word = True
result += 1
# set the current trie node word count to result
next_node.count += result
# -- return result --
# return result
return result, node
# function to find the number of matches in the trie
# - root of trie
# - string
def optimizeFind(root, input):
# hold onto current pointer of trie
# start at the root
current = root
# hold onto index of string
i = 0
# while the index is less than the string length
while i < len(input):
# get the character at the index
ch = input[i]
# if the children array does not have a trie node at the index
if ch not in current.children:
# break
break
# traverse to the child node
current = current.children[ch]
i += 1
# check if it reached the end of the input string
if i == len(input):
# return trie number of subwords
return current.count
# return 0
return 0
| UTF-8 | Python | false | false | 6,665 | py | 175 | contacts.py | 131 | 0.605401 | 0.6012 | 0 | 291 | 21.90378 | 179 |
adamLange/freecadutil | 2,250,562,912,270 | ec077940b5d46992986d760a7fade6bf650e3734 | bc10663c7b51710a20a5c2c5ae8b04f15ab35b8c | /PyOCCLevelUtils.py | fb69d9e05b5de319ca97e7f13fc4675f040b5724 | [] | no_license | https://github.com/adamLange/freecadutil | 0eddddf541a20fe37263c6dd28c0e35fc7bee7fb | 12884709e16e2d52c9cfede9d8cc278f5e788a39 | refs/heads/master | 2021-01-17T16:14:31.000327 | 2018-02-23T04:41:33 | 2018-02-23T04:41:33 | 71,716,603 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from OCC.Geom import Geom_BSplineSurface, Handle_Geom_BSplineSurface
from OCC.TColgp import TColgp_Array2OfPnt
from OCC.TColStd import TColStd_Array1OfReal, TColStd_Array2OfReal, TColStd_Array1OfInteger
from OCC.gp import gp_Vec, gp_Trsf, gp_Pnt
from OCC.BRepBuilderAPI import BRepBuilderAPI_MakeFace
import numpy as np
from OCCUtils.edge import Edge
import OCCUtils
class NurbsSurfaceBase:
def __init__(self,**kwargs):
self.uDegree = 2
self.vDegree = 2
self.uPeriodic = False
self.vPeriodic = False
self.uStartMultiplicity = 3
self.vStartMultiplicity = 3
self.uEndMultiplicity = 3
self.vEndMultiplicity = 3
def getPoles(self):
poles = []
poleSequence = []
for sketch in self.sketchList:
points = []
geo = []
for G in sketch.Geometry:
if not G.Construction:
geo.append(G)
vec = sketch.Placement.multVec(geo[0].StartPoint)
vec = gp_Pnt(vec.x,vec.y,vec.z)
points.append(vec)
poleSequence.append(vec)
for line in geo:
vec = sketch.Placement.multVec(line.EndPoint)
vec = gp_Pnt(vec.x,vec.y,vec.z)
points.append(vec)
poleSequence.append(vec)
poles.append(points)
n_u = len(poles[0])
n_v = len(poles)
return (poleSequence,n_u,n_v)
def toPyOCC(self,dbg=False):
poles,n_u,n_v = self.getPoles()
Poles = TColgp_Array2OfPnt(1,n_u,1,n_v)
for n,i in enumerate(poles):
iu = n%n_u
iv = n/n_u
Poles.SetValue(iu+1,iv+1,i)
weights = [1]*(n_u*n_v)
Weights = TColStd_Array2OfReal(1,n_u,1,n_v)
for n,i in enumerate(weights):
iu = n%n_u
iv = n/n_u
Weights.SetValue(iu+1,iv+1,i)
if not self.uPeriodic:
n_increasing = (n_u + self.uDegree + 1) - (self.uStartMultiplicity-1) - (self.uEndMultiplicity-1)
else:
n_increasing = n_u + 1
uknots = []
uknots.extend(np.linspace(0,1.0,n_increasing).tolist())
UKnots = TColStd_Array1OfReal(1,len(uknots))
for n,i in enumerate(uknots):
UKnots.SetValue(n+1,i)
l = [self.uStartMultiplicity]
m = [1]*(len(uknots)-2)
r = [self.uEndMultiplicity]
m.extend(r)
l.extend(m)
uMults = l
UMults = TColStd_Array1OfInteger(1,len(uMults))
for n,i in enumerate(uMults):
UMults.SetValue(n+1,i)
if not self.vPeriodic:
n_increasing = (n_v + self.vDegree + 1) - (self.vStartMultiplicity-1) - (self.vEndMultiplicity-1)
else:
n_increasing = n_v + 1
vknots = []
vknots.extend(np.linspace(0,1.0,n_increasing).tolist())
VKnots = TColStd_Array1OfReal(1,len(vknots))
for n,i in enumerate(vknots):
VKnots.SetValue(n+1,i)
l = [self.vStartMultiplicity]
m = [1]*(len(vknots)-2)
r = [self.vEndMultiplicity]
m.extend(r)
l.extend(m)
vMults = l
VMults = TColStd_Array1OfInteger(1,len(vMults))
for n,i in enumerate(vMults):
VMults.SetValue(n+1,i)
if dbg:
return {'poles':poles,'weights':weights,'uknots':uknots,'vknots':vknots,'umults':uMults,'vmults':vMults,'udegree':self.uDegree,'vdegree':self.vDegree}
#return (Poles,Weights,UKnots,VKnots,UMults,VMults,self.UDegree,self.vDegree,UPeriodic,VPeriodic)
return Geom_BSplineSurface(Poles,Weights,UKnots,VKnots,UMults,VMults,self.uDegree,self.vDegree,self.uPeriodic,self.vPeriodic)
def TopoDS_Face(self):
surf = self.toPyOCC()
hsurf = Handle_Geom_BSplineSurface(surf)
facemaker = BRepBuilderAPI_MakeFace()
facemaker.Init(hsurf,True,0.001)
return facemaker.Face()
class RibMaker(NurbsSurfaceBase):
def __init__(self,pointsList,l0,l1,l2,**kwargs):
"""
pointsList is a list of gp_pnt
l0, l1, and l2 are TopoDS_Edge
"""
NurbsSurfaceBase.__init__(self,**kwargs)
self.pts = pointsList
self.l0 = Edge(l0)
self.l1 = Edge(l1)
self.l2 = Edge(l2)
self.a = (self.l0.curve.Value(0)).as_vec()
r1, r2, r3 = self.getRVecs(0)
A = np.matrix([[r1.X(),r1.Y(),r1.Z()],
[r2.X(),r2.Y(),r2.Z()],
[r3.X(),r3.Y(),r3.Z()]
],dtype='float64')
self.AI = A.I
def getRVecs(self,t):
l0t = (self.l0.curve.Value(t)).as_vec()
l1t = (self.l1.curve.Value(t)).as_vec()
l2t = (self.l2.curve.Value(t)).as_vec()
r1 = l1t - l0t
r2 = l2t - l0t
r3 = gp_Vec(r1.XYZ())
r3.Cross(r2)
r3 = r3/r3.Magnitude()
r4 = gp_Vec(r1.XYZ())
r4.Cross(r3)
r4 = r4/r4.Magnitude() # unit vector in plane and perpenducular
# to r1
r2 = r4*(r4.Dot(r2)) # This is the r2 you are looking for
return r1, r2, r3
def T(self,t):
"""
Get the transformation matrix, T at parameter t.
"""
r1,r2,r3 = self.getRVecs(t)
B = np.matrix([[r1.X(),r1.Y(),r1.Z()],
[r2.X(),r2.Y(),r2.Z()],
[r3.X(),r3.Y(),r3.Z()]
],dtype='float64')
return self.AI*B
def getSection(self,t):
M = self.T(t)
trsf_pts = []
b = (self.l0.curve.Value(t)).as_vec()
for pnt in self.pts:
pnt = pnt.as_vec() - self.a
pnt = np.matrix([pnt.X(),pnt.Y(),pnt.Z()],dtype='float64').T
trsf_pt = (pnt.T * M).T
p = gp_Pnt((gp_Vec(trsf_pt[0,0],trsf_pt[1,0],trsf_pt[2,0]) + b).XYZ())
trsf_pts.append(p)
return trsf_pts
def getSections(self,tMin,tMax,numSections):
sections = []
for t in np.linspace(tMin,tMax,numSections):
sections.append(self.getSection(t))
return sections
def getPoles(self):
poles = []
sections = self.getSections(0,1.0,10)
n_u = len(sections[0])
n_v = len(sections)
for row in sections:
poles.extend(row)
return (poles,n_u,n_v)
from OCC.Geom import Geom_Plane
from OCC.GeomAPI import GeomAPI_IntCS
class RibMakerL0Normal(RibMaker):
def getRVecs(self,t):
p0 = gp_Pnt()
vec = gp_Vec()
self.l0.curve.D1(t,p0,vec)
plane = Geom_Plane( p0, vec.as_dir() )
intcs1 = GeomAPI_IntCS(self.l1.curve.GetHandle(),plane.GetHandle())
intcs2 = GeomAPI_IntCS(self.l2.curve.GetHandle(),plane.GetHandle())
u1, v1, w1 = intcs1.Parameters(1)
u2, v2, w2 = intcs2.Parameters(1)
p1 = self.l1.curve.Value(w1)
p2 = self.l2.curve.Value(w2)
r1 = p1.as_vec() - p0.as_vec()
r2 = p2.as_vec() - p0.as_vec()
r3 = gp_Vec(r1.XYZ())
r3.Cross(r2)
r3 = r3/r3.Magnitude()
r4 = gp_Vec(r1.XYZ())
r4.Cross(r3)
r4 = r4/r4.Magnitude()
r2 = r4*(r4.Dot(r2))
return r1, r2 ,r3
class RibMakerTranslatePlane(RibMaker):
def __init__(self,pointsList,l0,l1,l2,**kwargs):
NurbsSurfaceBase.__init__(self,**kwargs)
self.pts = pointsList
self.l0 = Edge(l0)
self.l1 = Edge(l1)
self.l2 = Edge(l2)
self.a = (self.l0.curve.Value(0)).as_vec()
p0 = self.l0.curve.Value(0).as_vec()
p1 = self.l1.curve.Value(0).as_vec()
p2 = self.l2.curve.Value(0).as_vec()
r1 = p1 - p0
r2 = p2 - p0
r3 = gp_Vec(r2.XYZ())
r3.Cross(r1)
r3 = r3/r3.Magnitude()
r4 = gp_Vec(r1.XYZ())
r4.Cross(r3)
r4 = r4/r4.Magnitude()
r2 = r4*(r4.Dot(r2))
self.planeNormal = r3.as_dir()
A = np.matrix([[r1.X(),r1.Y(),r1.Z()],
[r2.X(),r2.Y(),r2.Z()],
[r3.X(),r3.Y(),r3.Z()]
],dtype='float64')
self.AI = A.I
def getRVecs(self,t):
p0 = self.l0.curve.Value(t)
plane = Geom_Plane(p0, self.planeNormal)
intcs1 = GeomAPI_IntCS(self.l1.curve.GetHandle(),plane.GetHandle())
intcs2 = GeomAPI_IntCS(self.l2.curve.GetHandle(),plane.GetHandle())
u1, v1, w1 = intcs1.Parameters(1)
u2, v2, w2 = intcs2.Parameters(1)
p1 = self.l1.curve.Value(w1)
p2 = self.l2.curve.Value(w2)
r1 = p1.as_vec() - p0.as_vec()
r2 = p2.as_vec() - p0.as_vec()
r3 = gp_Vec(r2.XYZ())
r3.Cross(r1)
r3 = r3/r3.Magnitude()
r4 = gp_Vec(r1.XYZ())
r4.Cross(r3)
r4 = r4/r4.Magnitude()
r2 = r4*(r4.Dot(r2))
return r1, r2 ,r3
class SectionProjectionSurface(NurbsSurfaceBase):
from OCC.BRepProj import BRepProj_Projection
from OCC.BRepIntCurveSurface import BRepIntCurveSurface_Inter
from OCC.gp import gp_Lin,gp_Dir,gp_Vec
import pdb
def __init__(self,point,rootWire,face1,face2,**kwargs):
"""
@param point gp_Pnt
@param rootWire TopoDS_Wire
@param face1 TopoDS_Face
@param face2 TopoDS_Face
"""
#NurbsSurfaceBase.__init__(self)
self.basePoint = point
self.rootWire = rootWire
self.face1 = face1
self.face2 = face2
self.uDegree = 2
self.vDegree = 1
self.uPeriodic = True
self.vPeriodic = False
self.uStartMultiplicity = 1
self.vStartMultiplicity = 2
self.uEndMultiplicity = 1
self.vEndMultiplicity = 2
def getPoles(self):
poles = []
poleSequence = []
rootPoleSequence = []
tipPoleSequence = []
rootBSpline = OCCUtils.edge.Edge(OCCUtils.Topo(self.rootWire).edges().next()).adaptor.BSpline().GetObject()
inter = self.BRepIntCurveSurface_Inter()
for i in range(rootBSpline.NbPoles()):
currentRootPole = rootBSpline.Pole(i+1)
vec = self.gp_Vec(self.basePoint,currentRootPole)
direction = self.gp_Dir(vec)
line = self.gp_Lin(self.basePoint,direction)
inter.Init(self.face1,line,1e-6)
rootPoleSequence.append(inter.Pnt())
inter.Init(self.face2,line,1e-6)
tipPoleSequence.append(inter.Pnt())
poleSequence.extend(rootPoleSequence)
poleSequence.extend(tipPoleSequence)
n_u = rootBSpline.NbPoles()
n_v = 2
return (poleSequence,n_u,n_v)
"""
TODO make classes inhereting from RibMaker that
A. has a plane which is always parallel to the plane defined by l0(0) l1(0) l2(0)
B. has a plane which is always perpendicular to l0(t)
C. has a plane which revolves around l0
- For A B and C, a handy oce class will be GeomAPI_IntCS
"""
| UTF-8 | Python | false | false | 11,035 | py | 16 | PyOCCLevelUtils.py | 15 | 0.54599 | 0.51527 | 0 | 384 | 27.736979 | 162 |
dsr373/phase-locked-loops | 3,504,693,336,795 | 12301e239c0ce1a52eef9fda7b5beb95097bac87 | 40b46d370ec4c4763627566df36f6d723b7a33be | /python/analysis/vco_freqs.py | d2b8122faa6a4d2020ac83f186f53111a4b6a721 | [] | no_license | https://github.com/dsr373/phase-locked-loops | fdb6e14e9f5711e8e33c3a510f07073dff69f581 | 3e89b8c84de6f9af1f3b6b3d7fac8d5e950342c2 | refs/heads/master | 2021-02-07T11:46:07.742683 | 2018-10-22T20:26:13 | 2018-10-22T20:26:13 | 244,021,483 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import csv
from ..measurement.utils.gui_utils import def_input
FONTSIZE = 20
# the measurements are dictionaries from the expected_v to arrays of the measured values
v_in = {}
f_out = {}
results = {}
with open('data/vco/vco_R1M.tsv') as fin:
reader = csv.reader(fin, delimiter='\t')
reader.next() # skip first row - those are the headings
for row in reader:
# construct the measurements dict
exp_v = float(row[0])
v_A = float(row[2])
f_B = float(row[4])
if exp_v in v_in.keys():
v_in[exp_v].append(v_A)
f_out[exp_v].append(f_B)
else:
v_in[exp_v] = [v_A]
f_out[exp_v] = [f_B]
xs, ys, sigX, sigY = [], [], [], []
for exp_v in v_in.keys():
xs.append(np.mean(v_in[exp_v]))
ys.append(np.mean(f_out[exp_v]))
sigX.append(np.std(v_in[exp_v]))
sigY.append(np.std(f_out[exp_v]))
fig, ax = plt.subplots(figsize=(12, 8))
matplotlib.rcParams.update({'errorbar.capsize': 5})
ax.errorbar(xs, ys, yerr=sigY, xerr=sigX, fmt='+', markersize=8)
ax.set_title('Output of VCO', fontsize=FONTSIZE)
ax.set_xlabel('Input Voltage (V)', fontsize=FONTSIZE)
ax.set_ylabel('Output Frequency (Hz)', fontsize=FONTSIZE)
ax.tick_params(labelsize=FONTSIZE-4)
ax.set_xlim(left=-0.1, right=5.1)
plt.show()
saveopt = def_input('Save figure? (y/n)', default='n')
if saveopt == 'y':
figname = raw_input('file name: ')
fig.savefig('docs/%s.pdf' % figname, bbox_inches='tight')
| UTF-8 | Python | false | false | 1,549 | py | 32 | vco_freqs.py | 30 | 0.622337 | 0.612008 | 0 | 53 | 28.226415 | 88 |
humabilgin/2048-Game-With-Expectimax-Algorithm | 17,162,689,326,044 | 8363c21ac5db695171ee372f6962a4ed9b777368 | 7cb3ae5a61bef09ccd6308a4b2cae422a7455943 | /2048-expectimax-ai-master/expectimax.py | b5031d73c916b0764c0017d358bae3b93e061463 | [] | no_license | https://github.com/humabilgin/2048-Game-With-Expectimax-Algorithm | 4f0419bc6c44a0ee31b1cc3a492089cd38a5685e | f79f71b3910f0102c4fd6eca0688a88efeb0b8b8 | refs/heads/main | 2023-06-29T19:08:35.527415 | 2021-07-30T09:32:13 | 2021-07-30T09:32:13 | 391,004,572 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import math
import time
import numpy as np
UP, DOWN, LEFT, RIGHT = range(4)
class Expectimax():
def get_move(self, board):
best_move, _ = self.maximize(board)
return best_move
#degerlendirme fonksiyonu
def evaluationFunction(self, board, n_empty):
grid = board.grid
empty_w = 50000 # bos karelerin saglayacagi fayda degeri
loss_w = 2 # kareler arasindaki farkin verecegi zarar degerinin alıncagi üstel deger
utility = 0 #fayda
loss = 0 #zarar
p_grid = np.sum(np.power(grid, 2)) # grid 4*4luk bir matrix. Hepsinin ikinci kuvveti alınıp toplanıyor.
s_grid = np.sqrt(grid) # gridin kök alınmış hali
# kök alınmış matrisin yan yana olan satır ve sütunlarının farklarının mutlak değerleri toplanıyor
loss = -np.sum(np.abs(s_grid[::,0] - s_grid[::,1])) -np.sum(np.abs(s_grid[::,1] - s_grid[::,2])) - np.sum(np.abs(s_grid[::,2] - s_grid[::,3]))
loss += -np.sum(np.abs(s_grid[0,::] - s_grid[1,::])) -np.sum(np.abs(s_grid[1,::] - s_grid[2,::])) -np.sum(np.abs(s_grid[2,::] - s_grid[3,::]))
#negatif bir sayı oluşur
loss_u = loss ** loss_w # kareler arasindaki farkin verecegi toplam zarar degeri
empty_u = n_empty * empty_w # bos karelerin verecegi toplam utility degeri
p_grid_u = p_grid
utility += (p_grid + empty_u + loss_u)
#utility toplami icin bos karelerin faydasi, smoothness degerlerinin verdigi zarar ve matrixin
#değerlerinin buyuklugu toplanir.
return (utility, empty_u, loss_u, p_grid_u)
# subtreelerden gelen degerlerin en buyugunun secildiği fonksiyon
def maximize(self, board, depth = 0):
moves = board.get_available_moves() #yapilabilecek hamleler alinir
moves_boards = []
for m in moves:
m_board = board.clone() # o anki hamle uygulanırsa olusacak boardu olusturacagiz
m_board.move(m) # move fonksiyonu ile olusturuyoruz
moves_boards.append((m, m_board)) # tüm hamlelerin boardlarının tutuldugu listeye ekliyoruz
best_utility = (float('-inf'),0,0,0) # tüm utilityler arasında en iyi olani tutulacak
best_direction = None
for mb in moves_boards:
utility = self.chance(mb[1], depth + 1) # her hamlenin tahtasinin chance degeri hesaplanir
if utility[0] >= best_utility[0]: # bu degerlerin en buyugu secilir
best_utility = utility
best_direction = mb[0]
return best_direction, best_utility # en iyi hamle donulur
# bir sonraki elde yapılabilecek hamlelerin optimal olmadigi kabul edilir ve her subtreenin ortalamasi alinir.
def chance(self, board, depth = 0):
empty_cells = board.get_available_cells() # bos hucreler listesi
noOfEmpty = len(empty_cells) # bos hucre sayisi
#if n_empty >= 7 and depth >= 5:
# return self.eval_board(board, n_empty)
if noOfEmpty >= 6 and depth >= 3: # bos hucre sayisi 6dan buyukse ve derinlik 3ten buyukse
return self.evaluationFunction(board, noOfEmpty) # utility degerlerini dondur
if 6 > noOfEmpty >= 0 and depth >= 5: # bos hucre sayisi 6-0 arasindaysa ve derinlik 5ten buyukse
return self.evaluationFunction(board, noOfEmpty) # utility degerlerini dondur
# bos hucre sayisi arttıkca derinlik artıyor. Bunun sebebi oyunun zorlasmasıdır. Bir diger sebebi ise
# oyun kolayken buyuk bir derinlik vermenin sureyi uzatacak olmasidir. Bu yüzden zorlastikca derinlik artıyor.
if noOfEmpty == 0:
_, utility = self.maximize(board, depth + 1) #yon ignore edilir
return utility
possible_tiles = []
# her el yeni bir sayi tahtaya eklenir
chanceOf2 = (.95 * (1 / noOfEmpty)) # random olarak 2 gelme olasiligi daha cok
chanceOf4 = (.05 * (1 / noOfEmpty)) # random olarak 4 gelme olasiligi daha az
for empty_cell in empty_cells:
possible_tiles.append((empty_cell, 2, chanceOf2))
possible_tiles.append((empty_cell, 4, chanceOf4))
totalUtility = [0, 0, 0, 0]
for t in possible_tiles:
t_board = board.clone()
t_board.insert_tile(t[0], t[1]) # 4 ya da 2 eklenir
_, utility = self.maximize(t_board, depth + 1)
for i in range(4):
totalUtility[i] += utility[i] * t[2]
return tuple(totalUtility)
| UTF-8 | Python | false | false | 4,516 | py | 2 | expectimax.py | 1 | 0.628406 | 0.612104 | 0 | 102 | 42.892157 | 151 |
bruecksen/pumpwerk | 16,750,372,463,222 | a707df1e0c691e9a5e4648cc6f294690602e2191 | 491bd7a305859b380d777f3420b099d4790ca807 | /pumpwerk/food/migrations/0001_initial.py | bcad2f3a3228d1e92fd0424890e124214bb8d120 | [
"MIT"
] | permissive | https://github.com/bruecksen/pumpwerk | 65103eb741c49691b203b419e9752dad996fd089 | e76df6bedee3e338b10106565f0f6139fa63994c | refs/heads/master | 2023-05-31T20:59:24.721234 | 2022-11-16T15:20:36 | 2022-11-16T15:20:36 | 251,088,621 | 0 | 0 | MIT | false | 2023-05-10T01:56:30 | 2020-03-29T17:17:49 | 2022-10-21T13:01:27 | 2023-05-10T01:56:29 | 2,076 | 0 | 0 | 14 | Python | false | false | # Generated by Django 2.2.6 on 2020-02-25 20:23
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Bill',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('month', models.PositiveSmallIntegerField(choices=[(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')])),
('year', models.PositiveIntegerField()),
('days_in_month', models.PositiveIntegerField(editable=False)),
('terra_daily_rate', models.DecimalField(decimal_places=2, max_digits=8)),
('users', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('month', 'year')},
},
),
migrations.CreateModel(
name='UserBill',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('attendance_days', models.PositiveIntegerField()),
('total', models.DecimalField(decimal_places=2, max_digits=8)),
('has_payed', models.BooleanField(default=False)),
('is_notified', models.BooleanField(default=False)),
('bill', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='food.Bill')),
],
),
]
| UTF-8 | Python | false | false | 1,827 | py | 70 | 0001_initial.py | 64 | 0.568692 | 0.550082 | 0 | 42 | 42.5 | 255 |
JasonOwenss/pyforum | 7,670,811,592,752 | 9cdb94bd59321d3cc221f1d617c3f79da0d30656 | e42052c97a2026f51a129079780f4ad1c3d50e31 | /pyforum/Forum_project/admin.py | 2ff1f603ee64a4d3c1871fdc27bcd930e6db1f43 | [] | no_license | https://github.com/JasonOwenss/pyforum | 20c79041d6a2d2280b1283d74031bacbf9b26aca | bec7b483eb1b76caaea8651a384d6983e23cf9e1 | refs/heads/master | 2020-04-11T06:42:17.957727 | 2018-12-15T05:54:20 | 2018-12-15T05:54:20 | 161,588,835 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.contrib import admin
from .models import Forum,Comment
admin.site.register(Forum)
admin.site.register(Comment)
# Register your models here.
| UTF-8 | Python | false | false | 161 | py | 11 | admin.py | 6 | 0.770186 | 0.770186 | 0 | 7 | 21 | 33 |
eggplantisme/NetworkEvolution | 18,571,438,608,043 | 9662915257f1029593beea63d9d297e7a319f2f7 | dfbbd8bbf0d364475ab3eee67ba858c9604af4ff | /_EdgeSort_.py | ca4a5c8b7357f1997ed36c647ddf6c48fdf0d2cb | [] | no_license | https://github.com/eggplantisme/NetworkEvolution | 3dfaffa8a4c2558235084e7dab350caaef2a58b8 | fcb01afd52f8f0726af9cca2f260da0e571f723f | refs/heads/master | 2020-11-27T11:25:11.592186 | 2019-12-21T12:04:17 | 2019-12-21T12:04:17 | 221,919,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import random
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import time
import pickle
import os
from scipy import optimize
from getEdgeTime import get_all_edge_time
from getFeatureJudge import get_feature_dict
from getNet import get_mat
import _EnsembleJudge_
import getEdgePair
from __Configuration import *
class EdgeSort:
# 排序 + Δk-k图验证BA理论
def __init__(self, net_name):
global TRAIN_EDGE_RATIO
TRAIN_EDGE_RATIO = 0.4
self.net_name = net_name
self.all_days = dict() # {'real':[0, 0, ...], 'random ':[], ' } 三个时间列表 + 边列表
file_name = ".\\sort\\" + net_name + "_" + str(TRAIN_EDGE_RATIO) + ".pkl"
if os.path.exists(file_name) is False:
self.base_train_edges = None
self.ensemble_train_edges = None
self.test_edges = None
self.edges, self.real_days = self.get_sort_edges()
self.shuffle_edges = list(self.edges)
random.shuffle(self.shuffle_edges)
self.random_days = self.random_sort() # edges 对应的随机排序后的时间
self.sort_days = self.vote_sort() # edges 对应的使用ensemble方法排序后的时间
with open(file_name, 'wb') as file:
self.all_days['real'] = self.real_days # [1, 1, 1, 1, 2, 2, 3]
self.all_days['random'] = self.random_days # [..., 0, ..., 1, ...]
self.all_days['ensemble'] = self.sort_days # [..., 0, ..., 1, ...]
self.all_days['edges'] = self.edges
pickle.dump(self.all_days, file)
else:
with open(file_name, 'rb') as file:
self.all_days = pickle.load(file)
self.real_days = self.all_days['real']
self.random_days = self.all_days['random']
self.sort_days = self.all_days['ensemble']
self.edges = self.all_days['edges']
def get_sort_edges(self):
"""
获取两个训练边集以及要排序的测试边集,并找到测试边集的真实顺序
:return:
"""
self.base_train_edges, self.ensemble_train_edges, self.test_edges = getEdgePair.ensemble_get_train_test_edges(
TRAIN_EDGE_RATIO,
self.net_name)
edge_days = get_all_edge_time(self.net_name)
edges = []
days = []
sorted_edge_days = sorted(set(edge_days.values()))
for i in sorted_edge_days:
i_day_edges = [edge for edge in edge_days.keys() if edge_days[edge] == i]
print("i_day_edges:", i_day_edges.__len__())
edges.extend(i_day_edges)
days.extend([sorted_edge_days.index(i)] * i_day_edges.__len__())
return edges, days
def random_sort(self):
shuffle_edges_copy = list(self.shuffle_edges) # 深拷贝
edges_l = shuffle_edges_copy.__len__()
# 冒泡排序
for i in range(edges_l):
for j in range(i):
x = random.random()
if x < 0.5:
new_edge_judge = 1
else:
new_edge_judge = -1
if new_edge_judge > 0:
temp = shuffle_edges_copy[i]
shuffle_edges_copy[j + 1:i + 1] = shuffle_edges_copy[j:i]
shuffle_edges_copy[j] = temp
break
else:
pass
days = [0] * edges_l
for edge in shuffle_edges_copy:
sort_day = shuffle_edges_copy.index(edge)
real_index = self.edges.index(edge)
days[real_index] = sort_day
print("random sort finished!")
return days
def vote_sort(self):
shuffle_edges_copy = list(self.shuffle_edges) # 深拷贝
edge_score = dict(zip(shuffle_edges_copy, [0] * len(shuffle_edges_copy))) # 每条边的投票分数
# ensemble 判断 获取模型
judge_methods = [BEST_SINGLE, NODE2VEC_PAIR_NN, UNION_PAIR_NN]
ensemble = _EnsembleJudge_.EnsembleJudge(self.net_name, self.base_train_edges, self.test_edges, judge_methods,
self.ensemble_train_edges)
model = ensemble
for edge1 in shuffle_edges_copy:
_edge2s = shuffle_edges_copy[shuffle_edges_copy.index(edge1):]
for edge2 in _edge2s:
# 根据rule指标判断新旧
judge = model.get_ep_judge((edge1, edge2))
if judge == 1:
edge_score[edge1] += 1
else:
edge_score[edge2] += 1
# 按value排序
sorted_edge_score_list = sorted(edge_score.items(), key=lambda item: item[1])
sorted_edge_score = dict()
for tuple_score in sorted_edge_score_list:
sorted_edge_score[tuple_score[0]] = tuple_score[1]
# 构造每条边的位置列表
sorted_edge = list(sorted_edge_score.keys())
days = [0] * sorted_edge.__len__()
for edge in sorted_edge:
sort_day = sorted_edge.index(edge)
real_index = self.edges.index(edge)
days[real_index] = sort_day
print("vote sort finished!")
return days
def plot_sort(self):
random_days = np.array(self.random_days)
real_days = np.array(self.real_days)
sort_days = np.array(self.sort_days)
# 真实情况
plt.figure(figsize=(10, 5))
plt.subplot(3, 1, 1)
plt.yticks([])
plt.title(self.net_name + ' real times')
plt.imshow(real_days[np.newaxis, :], aspect='auto', cmap=mpl.cm.cool)
cb = plt.colorbar()
cb.set_label("time")
# 随机判定排序
rn_auc = self.auc_after_sort(random_days, real_days)
# 统一排序后和排序前的时间粒度(即真实某时刻有多少条边,排序后也如此)
for i in range(real_days.size):
pos = np.where(random_days == i)
random_days[pos] = real_days[i]
rn_corr = round(np.corrcoef(random_days, real_days)[0, 1], 3)
plt.subplot(3, 1, 2)
plt.yticks([])
plt.title('random sort, correlation coefficient:' + str(rn_corr) + " Accuracy:" + str(rn_auc))
plt.imshow(random_days[np.newaxis, :], aspect='auto', cmap=mpl.cm.cool)
cb = plt.colorbar()
cb.set_label("time")
# ensemble判断 vote排序
vote_auc = self.auc_after_sort(sort_days, real_days)
# 统一排序后和排序前的时间粒度(即真实某时刻有多少条边,排序后也如此)
for i in range(real_days.size):
pos = np.where(sort_days == i)
sort_days[pos] = real_days[i]
vote_corr = round(np.corrcoef(sort_days, real_days)[0, 1], 3)
plt.subplot(3, 1, 3)
plt.yticks([])
plt.title(
'vote sort by ensemble, correlation coefficient:' + str(vote_corr) + " Accuracy:" + str(vote_auc))
plt.imshow(sort_days[np.newaxis, :], aspect='auto', cmap=mpl.cm.cool)
cb = plt.colorbar()
cb.set_label("time")
plt.tight_layout()
plt.savefig("./Result/sort/" + self.net_name + "_sort.png", dpi=600)
plt.show()
@staticmethod
def auc_after_sort(_sorted, _real):
diff_time_ep_num = 0
right_ep_num = 0
for edge1 in range(len(_real)):
for edge2 in range(edge1, len(_real)):
if _real[edge1] != _real[edge2]:
diff_time_ep_num += 1
if (_real[edge2] > _real[edge1]) == (_sorted[edge2] > _sorted[edge1]):
right_ep_num += 1
return round(right_ep_num / diff_time_ep_num, 3)
def ba_validation(self):
plt.figure(figsize=(30, 10))
# 按第一个真实时间点来分before_edges和after_edges
first_real_day = min(self.real_days)
real_before_edges = []
for edge in self.edges:
i = self.edges.index(edge)
if self.real_days[i] <= first_real_day:
real_before_edges.append(edge)
before_nodes_degree = self.get_node_degree_from_edges(real_before_edges)
after_nodes_degree = self.get_node_degree_from_edges(self.edges)
plt.subplot(1, 3, 1)
self.plot_deltak_k(before_nodes_degree, after_nodes_degree, "real")
# 按第一个真实时间点来分的before_edges数量来分vote_sort_edges
vote_sort_before_edges = []
for edge in self.edges:
i = self.edges.index(edge)
if self.sort_days[i] < len(real_before_edges):
vote_sort_before_edges.append(edge)
vote_sort_before_node_degree = self.get_node_degree_from_edges(vote_sort_before_edges)
plt.subplot(1, 3, 2)
self.plot_deltak_k(vote_sort_before_node_degree, after_nodes_degree, "sort")
# vote_sort_edges 一半一半来分
half_vote_sort_before_edges = []
for edge in self.edges:
i = self.edges.index(edge)
if self.sort_days[i] < (len(self.edges) / 2):
half_vote_sort_before_edges.append(edge)
half_vote_sort_before_node_degree = self.get_node_degree_from_edges(half_vote_sort_before_edges)
plt.subplot(1, 3, 3)
self.plot_deltak_k(half_vote_sort_before_node_degree, after_nodes_degree, "half_sort")
plt.savefig("./Result/BA_validation/" + self.net_name + "_scatter.png", dpi=600)
plt.show()
@staticmethod
def line(x, a, b):
return a * x + b
def plot_deltak_k(self, before_nodes_degree, after_nodes_degree, mode):
# TODO 散点图拟合直线
k_list = []
delta_k_list = []
for node in before_nodes_degree:
k = before_nodes_degree[node]
delta_k = after_nodes_degree[node] - before_nodes_degree[node]
if k > 50 or delta_k > 50:
pass
else:
k_list.append(k)
delta_k_list.append(delta_k)
# 拟合
a, b = optimize.curve_fit(self.line, k_list, delta_k_list)[0]
x1 = np.arange(0, max(k_list), 0.01)
y1 = a * x1 + b
print("A is", a)
# 绘图
plt.title("Average Δk - k for net " + self.net_name + ": " + mode + ". a is " + str(round(a, 3)), fontsize=25, fontweight='bold')
plt.xlabel("k", fontsize=15, fontweight='bold')
plt.ylabel("Δk", fontsize=15, fontweight='bold')
plt.scatter(k_list, delta_k_list)
plt.plot(x1, y1, "r")
plt.tight_layout()
# # 获取k_Δk数据
# k_delta_k = dict()
# k_node_num = dict()
# for node in before_nodes_degree:
# k = before_nodes_degree[node]
# delta_k = after_nodes_degree[node] - before_nodes_degree[node]
# if k in k_delta_k.keys():
# k_delta_k[k] += delta_k
# k_node_num[k] += 1
# else:
# k_delta_k[k] = delta_k
# k_node_num[k] = 1
# for k in k_delta_k.keys():
# k_delta_k[k] = k_delta_k[k] / k_node_num[k] # 取均值
# # 绘图
# sorted_k_delta_k = dict()
# for k in sorted(k_delta_k):
# sorted_k_delta_k[k] = k_delta_k[k]
# plt.title("Average Δk - k for net " + self.net_name + ": " + mode, fontsize=25, fontweight='bold')
# plt.xlabel("k", fontsize=15, fontweight='bold')
# plt.ylabel("Δk", fontsize=15, fontweight='bold')
# plt.plot(list(sorted_k_delta_k.keys()), list(sorted_k_delta_k.values()), "-*")
# plt.tight_layout()
@staticmethod
def get_node_degree_from_edges(edges):
"""
根据 [边对列表] 获取 {节点度的词典}
:param edges:
:return:
"""
node_degree = dict()
for edge in edges:
if edge[0] not in node_degree.keys():
node_degree[edge[0]] = 1
else:
node_degree[edge[0]] += 1
if edge[1] not in node_degree.keys():
node_degree[edge[1]] = 1
else:
node_degree[edge[1]] += 1
return node_degree
def main():
net_names = protein_net_names
for net_name in net_names:
edge_sort = EdgeSort(net_name)
# edge_sort.plot_sort()
edge_sort.ba_validation()
if __name__ == '__main__':
main()
| UTF-8 | Python | false | false | 12,506 | py | 211 | _EdgeSort_.py | 27 | 0.537684 | 0.526654 | 0 | 302 | 38.629139 | 137 |
info9117/BlueGarden_Project | 6,322,191,881,208 | caac4e35dc18f93a9f34d425689041e76aef90c2 | 91754e5c7252806a723e7e060a7a8b2beb0e72ad | /models/unit.py | bb62845953b54bb5e2af553d5c7d4e3fa996f315 | [] | no_license | https://github.com/info9117/BlueGarden_Project | e0ce7f0ff0b68eed6297abc25c7405d383665579 | b85f0a7ba610e580f9c2da3d25b69421cd9373fe | refs/heads/master | 2020-12-11T03:34:19.589083 | 2016-06-02T03:55:49 | 2016-06-02T03:55:49 | 56,494,085 | 2 | 6 | null | true | 2016-05-30T10:35:45 | 2016-04-18T09:19:07 | 2016-05-16T06:26:17 | 2016-05-30T10:35:44 | 16,044 | 2 | 4 | 16 | JavaScript | null | null | from shared import db
class Unit(db.Model):
__tablename__ = 'units'
id = db.Column('id', db.Integer, primary_key=True)
name = db.Column('name', db.String(10), unique=True, nullable=False)
def __init__(self, name):
self.name = name
| UTF-8 | Python | false | false | 258 | py | 60 | unit.py | 29 | 0.616279 | 0.608527 | 0 | 10 | 24.8 | 72 |
KristianHolsheimer/blog | 10,617,159,156,342 | c719dc06839b997e5a64a411b8e5137ab6047e53 | 0df842d52ff3c51da3ac641ecca50bfe85543ee8 | /posts/views.py | cbefd69c0c9841f0d1946e3f24361e80ac64bda3 | [] | no_license | https://github.com/KristianHolsheimer/blog | aa8712b0dac4073cb2a49447d43b76a7069254d7 | f9b932e07018a65dc85759d15d1dff83a5f0d903 | refs/heads/master | 2021-07-09T12:20:33.594136 | 2020-07-07T01:35:53 | 2020-07-07T01:35:53 | 155,557,569 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import logging
from django.shortcuts import render, get_object_or_404
from .models import Post, Tag
logger = logging.getLogger(__name__)
def log_request(view):
def view_that_also_logs(request, *args, **kwargs):
logger.debug('request.__dict__', extra={'request': request.__dict__})
return view(request, *args, **kwargs)
return view_that_also_logs
@log_request
def index(request):
posts_ds = Post.objects.filter(is_live=True, category=Post.CATEGORY_DS).order_by('-pub_date')[:5]
posts_eng = Post.objects.filter(is_live=True, category=Post.CATEGORY_ENG).order_by('-pub_date')[:5]
tags = Post.all_live_tags()
context = {'posts_ds': posts_ds, 'posts_eng': posts_eng, 'tags': tags}
return render(request, 'posts/index.html', context)
@log_request
def post(request, post_name):
logger.debug(dict(request))
post_obj = get_object_or_404(Post, name=post_name, is_live=True)
return render(request, 'posts/post_site.html', {'post': post_obj})
@log_request
def tag(request, tag_name):
logger.debug(dict(request))
tag_obj = get_object_or_404(Tag, name=tag_name)
return render(request, 'posts/tag_site.html', {'tag': tag_obj})
| UTF-8 | Python | false | false | 1,190 | py | 44 | views.py | 22 | 0.676471 | 0.667227 | 0 | 36 | 32.055556 | 103 |
kojicz983/talkabout | 18,537,078,884,271 | 630dfca405f5a799ef79a94f175df3f48b54c471 | 051fcc3bc7e8acaeb48d9111b91d73152bf2aac2 | /talkabout/apps/cruises/ports/apps.py | 18c4d4c458da0af9cba4fe4bb2dbbb42a3accece | [] | no_license | https://github.com/kojicz983/talkabout | 901174af9dbe1e9f9ad050b5aa21a4700d482d21 | 2dfec7df6f7d1bdec9f7d16cc77f489b34784786 | refs/heads/master | 2018-12-31T03:43:54.728735 | 2018-12-23T21:19:03 | 2018-12-23T21:19:03 | 84,946,971 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.apps import AppConfig
class PortsConfig(AppConfig):
name = 'talkabout.apps.cruises.ports'
| UTF-8 | Python | false | false | 108 | py | 137 | apps.py | 106 | 0.768519 | 0.768519 | 0 | 5 | 20.6 | 41 |
wfeng1991/learnpy | 8,263,517,119,961 | 12bd3a7623119dece020e20903a68f7e259071d9 | e2ae5c6d1d3ff9c512d526b1b4d7d7b64d50e87d | /py/leetcode/67.py | 31e8057c7b137a496a027163d4d65652fad090ea | [] | no_license | https://github.com/wfeng1991/learnpy | 59ed66d0abc2947c2f73c0bfe3901ef45ba5eb56 | e5b018493bbd12edcdcd0434f35d9c358106d391 | refs/heads/master | 2021-01-23T07:35:08.376547 | 2018-09-28T02:16:31 | 2018-09-28T02:16:31 | 86,430,476 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la=len(a)
lb=len(b)
if la<lb:
return self.addBinary(b,a)
a=a[::-1]
b=b[::-1]
i = 0
carry=0
r=''
while i<la:
ia=ord(a[i])-48
ib=0
if i<lb:
ib=ord(b[i])-48
if ia+ib+carry==3:
r='1'+r
carry=1
elif ia+ib+carry==2:
r='0'+r
carry=1
else:
r=str(ia+ib+carry)+r
carry=0
i+=1
if carry==1:
r='1'+r
return r
print(Solution().addBinary('1010','1011'))
| UTF-8 | Python | false | false | 814 | py | 301 | 67.py | 300 | 0.32801 | 0.29484 | 0 | 36 | 20.916667 | 42 |
barlettacarmen/Smile | 18,227,841,214,243 | 617440d59c5855b8ed8b2c6de55ae9dae991e4ab | 0418fae22897f0015b92b58069a33b275b60c73a | /Smile/files/server.py | 87652f11bd0ee27771929afc3abc520528e7cfeb | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | https://github.com/barlettacarmen/Smile | c8ed255ec96582a7853038c479bf82b1bbff58e2 | 1b5618d61ca272cf3f26ba19a7098d1e3a8a2db6 | refs/heads/master | 2021-01-11T20:08:01.523628 | 2017-12-19T14:48:01 | 2017-12-19T14:48:01 | 79,045,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # ___
# / /\
# /___/ \
# \___\ /_ \_\_\_
# / /\\/ /| \_
# /___/ \_/ | \_\_\_ \_ \_ \_ \_ \_\_\_
# \ \ / \ | \_ \_\_\_ \_ \_ \_\_
# \___\//\_\| \_\_\_ \_ \_ \_ \_\_\_ \_\_\_
# /___/ \
# \ \ /
# \___\/
#
# Copyright 2017 Fabiola Casasopra, Carmen Barletta, Gabriele Iannone, Guido Lanfranchi, Francesco Maio
#
# 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.
get_ipython().magic('matplotlib inline')
from pynq import Overlay
Overlay("base.bit").download()
from pynq.iop import Arduino_Analog
from pynq.iop import ARDUINO
from pynq.iop import ARDUINO_GROVE_A1, ARDUINO_GROVE_A2, ARDUINO_GROVE_A3, ARDUINO_GROVE_A4
from pynq.board import LED, RGBLED
import time
import socket
import numpy as np
import matplotlib.pyplot as plt
TEMP_BEFORE_SENDING = 20
#frequency with which sensors will take input from outside
FREQUENCY = 0.05
TIME_OF_EVENT = 60 # fixed as 60sec for the demo
# In final implementation it must be set with respect to the duration of the event
MAX_LEDS = 4
MAX_RGB_LEDS = 2
MAX_RGB_VALUE = 8
global flag_crowded
global ss
def Main():
host = "10.79.3.204"
port = 5001
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
flag_crowded = 0
data = conn.recv(1024).decode()
while data !="ciao":
time.sleep(0.1)
while True:
readSensorsInput()
conn.send ("gente".encode())
while not data:
time.sleep(1)
data = conn.recv(1024).decode()
getNotice(str(data))
flag_crowded = 0
conn.close()
def readSensorsInput():
#inizialize readers pins
proximityPresence1= Arduino_Analog(ARDUINO,ARDUINO_GROVE_A4)
proximityPresence2= Arduino_Analog(ARDUINO,ARDUINO_GROVE_A3)
proximitySound= Arduino_Analog(ARDUINO,ARDUINO_GROVE_A2)
proximityLight= Arduino_Analog(ARDUINO,ARDUINO_GROVE_A1)
crowdLevel = 0
ss = 0 #start state
valuesPresence1 = np.zeros(TEMP_BEFORE_SENDING)
valuesPresence2 = np.zeros(TEMP_BEFORE_SENDING)
valuesSound = np.zeros(TEMP_BEFORE_SENDING)
valuesLight = np.zeros(TEMP_BEFORE_SENDING)
#calibration
for i in range(0,TEMP_BEFORE_SENDING):
valuesPresence1[i] = proximityPresence1.read()[1]
valuesPresence2[i] = proximityPresence2.read()[1]
#valuesSound.append(proximitySound.read()[1])
#valuesLight.append(proximityLight.read()[1])
time.sleep(FREQUENCY)
cal1 = np.mean(valuesPresence1)
cal2 = np.mean(valuesPresence2)
while True:
#inizialize lists for values
valuesPresence1 = np.zeros(TEMP_BEFORE_SENDING)
valuesPresence2 = np.zeros(TEMP_BEFORE_SENDING)
#valuesSound = list()
#valuesLight = list()
valuesSound = np.zeros(TEMP_BEFORE_SENDING)
valuesLight = np.zeros(TEMP_BEFORE_SENDING)
#plt.axis([0,TEMP_BEFORE_SENDING,0,3])
#plt.ion()
#read input from sensors
for i in range(0,TEMP_BEFORE_SENDING):
valuesPresence1[i] = proximityPresence1.read()[1]
valuesPresence2[i] = proximityPresence2.read()[1]
valuesSound[i] = proximitySound.read()[0]
valuesLight[i] = proximityLight.read()[0]
#valueSound.append(proximitySound.read()[1])
#valueLight.append(proximityLight.read()[1])
time.sleep(FREQUENCY)
#y = valuesSound[i]
#plt.plot(i,y)
#plt.show()
#debug
#print (len(valuesPresence1))
#print (valuesPresence1)
#print (valuesPresence2)
#print (valueSound)
#print (valueLight)
#processInput (valuesPresence1, valuesPresence2, valueSound)
avg1 = np.mean(valuesPresence1)
avg2 = np.mean(valuesPresence2)
#implemento una macchina a stati.
# 0 ENTRAMBI SENSORI BASSI
# 1 PRIMO ALTO SECONDO BASSO MA CI ARRIVO DA 0
# 2 PRIMO BASSO SECONDO ALTO MA CI ARRIVO DA 0
# 3 ENTRAMBI ALTI
# 4 PRIMO BASSO SECONDO ALTO MA CI ARRIVO DA 1
# 5 PRIMO ALTO SECONDO BASSO MA CI ARRIVO DA 2
if ss == 0:
print("sono nello stato 0")
if avg1 > 1.2*cal1 and avg2 < 1.2*cal2:
ss = 1
elif avg1 < 1.2*cal1 and avg2 > 1.2*cal2:
ss = 2
elif avg1 > 1.2*cal1 and avg2 > 1.2*cal2:
ss = 3
elif avg1 < 1.2*cal1 and avg2 < 1.2*cal2:
ss = 0
elif ss == 1:
print("sono nello stato 1")
if avg1 > 1.2*cal1 and avg2 < 1.2*cal2:
ss = 1
elif avg1 < 1.2*cal1 and avg2 > 1.2*cal2:
ss = 4
elif avg1 > 1.2*cal1 and avg2 > 1.2*cal2:
ss = 3
elif avg1 < 1.2*cal1 and avg2 < 1.2*cal2:
ss = 0
elif ss == 2:
print("sono nello stato 2")
if avg1 > 1.2*cal1 and avg2 < 1.2*cal2:
ss = 5
elif avg1 < 1.2*cal1 and avg2 > 1.2*cal2:
ss = 2
elif avg1 > 1.2*cal1 and avg2 > 1.2*cal2:
ss = 3
elif avg1 < 1.2*cal1 and avg2 < 1.2*cal2:
ss = 0
elif ss == 3:
print("sono nello stato 3")
print("c e qualcuno fermo")
ss = 0
elif ss == 4:
print("sono nello stato 4")
flag_crowded = 1
ss = 0
break
elif ss == 5:
print("sono nello stato 5")
flag_crowded = 0
print("uscito qualcuno")
ss = 0
def getNotice(s):
proximityLight= Arduino_Analog(ARDUINO,ARDUINO_GROVE_A1)
valuesLight = np.zeros(TEMP_BEFORE_SENDING)
#read input from sensors
for i in range(0,TEMP_BEFORE_SENDING):
valuesLight[i] = proximityLight.read()[0]
time.sleep(FREQUENCY)
avgLight = sum(valuesLight)/TEMP_BEFORE_SENDING
print(avgLight)
threshold = 1
accesi = 0
if avgLight > threshold:
accesi = 2
else:
accesi = 1
rgb_leds = [RGBLED(i+MAX_LEDS) for i in range (MAX_RGB_LEDS)]
for i in range(MAX_RGB_LEDS):
rgb_leds[i].off()
if s == "focus":
for i in range (accesi):
rgb_leds[i].on(3) #light blue
elif s == "party":
for i in range (accesi):
rgb_leds[i].on(4) #red
elif s == "dinner":
rgb_leds[0].on(4) #red
rgb_leds[1].on(6) #yellow
elif s == "sleep":
for i in range (accesi):
rgb_leds[i].on(5) #purple
elif s == "workout":
for i in range (accesi):
rgb_leds[i].on(2) #green
elif s == "chill":
for i in range (accesi):
rgb_leds[i].on(1) #blue
elif s == "travel":
for i in range (accesi):
rgb_leds[i].on(6) #yellow
elif s == "nomatch":
for i in range (accesi):
rgb_leds[i].on(7) #white
elif s == "noevent":
for i in range (accesi):
rgb_leds[i].off() # shut down everything
else:
print("Error in data transmission from Calendar!")
time.sleep(TIME_OF_EVENT)
for i in range (MAX_RGB_LEDS):
rgb_leds[i].off() # shut down everything
if __name__ == '__main__':
Main()
| UTF-8 | Python | false | false | 8,410 | py | 5 | server.py | 2 | 0.531034 | 0.501189 | 0 | 294 | 27.581633 | 104 |
cashila/block-exploder | 19,207,093,768,461 | 3bf9cc1d3d49b7885ccd40e2288ee48620917b5e | 0918cc441ad199a86ed9879ff6dace165de3b40e | /syncer/serializers.py | e83c5ade38add54d45758031f9ceba171811379d | [] | no_license | https://github.com/cashila/block-exploder | b97c47b147f6463f0966e9d8c4ebf06c510b57e8 | 1ac611a4adc1c114b7ab09f81d3f9aaf27e39490 | refs/heads/master | 2021-01-23T09:38:20.025755 | 2017-08-21T16:13:45 | 2017-08-21T16:13:45 | 102,586,814 | 0 | 1 | null | true | 2017-09-06T09:00:01 | 2017-09-06T09:00:01 | 2017-06-17T03:17:14 | 2017-08-23T19:31:12 | 2,271 | 0 | 0 | 0 | null | null | null | class VoutSerializer(object):
@staticmethod
def to_database(vout):
return {
"value": vout.value,
"asm": vout.asm,
"addresses": vout.addresses,
"type": vout.type,
"reqSigs": vout.reqSigs,
"spent": vout.spent
}
class VinSerializer(object):
@staticmethod
def to_database(vin):
return {
"prev_txid": vin.prev_txid,
"vout_index": vin.vout_index,
"hex": vin.hex,
"sequence": vin.sequence,
"coinbase": vin.coinbase
}
class TransactionSerializer(object):
@staticmethod
def to_database(tr):
formatted = {
"version": tr.version,
"locktime": tr.locktime,
"txid": tr.txid,
"vin": [],
"vout": [],
"total": tr.total,
"blockhash": tr.blockhash,
"blocktime": tr.blocktime
}
for v in tr.vin:
formatted['vin'].append(VinSerializer.to_database(v))
for v in tr.vout:
formatted['vout'].append(VoutSerializer.to_database(v))
return formatted
class BlockSerializer(object):
@staticmethod
def to_database(block):
if not type(block.tx[0]) == unicode:
tx = [tr.txid for tr in block.tx]
else:
tx = block.tx
return {
"hash": block.hash,
"size": block.size,
"height": block.height,
"version": block.version,
"merkleroot": block.merkleroot,
"tx": tx,
"time": block.time,
"nonce": block.nonce,
"bits": block.bits,
"difficulty": str(block.difficulty),
"chainwork": hex(block.chainwork),
"previousblockhash": block.previousblockhash,
"nextblockhash": block.nextblockhash,
"target": hex(block.target),
"dat": block.dat,
"total": str(block.total),
"work": block.work,
"chain": block.chain
}
class HashrateSerializer(object):
@staticmethod
def to_database(rate, timestamp):
return {
"hashrate": rate,
"timestamp": timestamp
}
class SyncHistorySerializer(object):
@staticmethod
def to_database(start_time, end_time, start_block_height, end_block_height):
return {
"start_time": start_time,
"end_time": end_time,
"start_block_height": start_block_height,
"end_block_height": end_block_height
}
class NetworkStatsSerializer(object):
@staticmethod
def to_database(supply, blockchain_size):
return {
"supply": supply,
"blockchain_size": blockchain_size
}
class PriceSerializer(object):
@staticmethod
def to_database(price):
return {
"usd_price": price
}
class ClientInfoSerializer(object):
@staticmethod
def to_database(version, ip, peer_info):
# If ipify api stops working don't update ip field
if ip:
return {
"version": version,
"ip": ip,
"peer_info": peer_info
}
else:
return {
"version": version,
"peer_info": peer_info
}
class ClientSyncProgressSerializer(object):
@staticmethod
def to_database(progress):
return {
"sync_progress": progress
}
| UTF-8 | Python | false | false | 3,558 | py | 37 | serializers.py | 18 | 0.517426 | 0.517144 | 0 | 138 | 24.782609 | 80 |
bellancal/CAN_Invader | 7,782,480,751,348 | d77df5bffa552c2f0ae8e6757dbfc5cfd67c927c | 80d7b43447fea4755987124c1a7cd4993d1840f5 | /bg.py | 489745faca45b1f1c32587748507dc597157929a | [] | no_license | https://github.com/bellancal/CAN_Invader | 686e2bdf0b136c781adad8d4a340033e6f86360f | c2892e3ab1e906e289459faa221620f1624c8652 | refs/heads/master | 2020-04-05T23:08:45.960723 | 2018-02-23T22:56:59 | 2018-02-23T22:56:59 | 58,976,285 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | from tkinter import *
import tkinter.messagebox
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as font
import subprocess
from subprocess import Popen, CREATE_NEW_CONSOLE, PIPE
import os
import ConfigFile
import configparser
import socket
import sys
import threading
import traceback
"""
Purpose: Main file that creates the gui using TK widgets for the CAN INVADER control.
This program will launch the BT server and initiate message using server. This program will also monitor for server status
and CAN responses for the diagnostic requests and present these to user.
Author: Louis V Bellanca / LBELLAN1@FORD.COM
Date: April 2016 first release
ver2.0 | May 14 2016 major updates:
-added a new socket server for gui in new thread to monitor for incoming request for button controls - to be used with Klippel tool
"""
#TODO:determine supplier of AHU from CAN bus.
#TODO: get input from buld sheet to decode configuration
#TODO:If connect is pressed with no server?
# Define global variables here
cfg = configparser.ConfigParser()
engineering_mode = False
command_error = False
CREATE_NO_WINDOW = 0x08000000
# set defaults for the size
default_sizex = "662"
default_sizey = "478"
fileOK = ""
MasterVol1 = 1
MasterVol2 = 16
def ConfigSelect(selection=None):
print("Configuration selected = " + str(selection))
if selection is not None:
LoadConfig(ConfigFile.config_list2[selection]["filename"])
def LoadConfig(filetoload):
# sub to check the config file and load data
global sizex, sizey, fileOK, config_file, loaded_freq
# refer to the file to see if a config is defined
fileOK = cfg.read(filetoload)
if fileOK:
print("ini file read in bg = " + str(fileOK))
loaded_config.set("Config file = " + filetoload)
# ConfigFile.CFT = filetoload
print("Attempting to load config = " + filetoload)
config_file = filetoload
# CheckTP()
CheckAMP()
CheckAHU()
CheckSpeaker()
CheckVIN()
CheckBassTreb()
CheckCAN(bus_type=cfg['CAN']['busType'].lower(), speed=cfg['CAN']['speed'].lower())
# Note if already connected and CAN changes then settings will not take effect since a disconnect is needed.
# if the config file does not have the section 'SIZE', then add it to the config-file
if not cfg.has_section('SIZE'):
cfg.add_section('SIZE')
# set default size
sizex = default_sizex
sizey = default_sizey
print("cfg section SIZE not found - to be added!!")
# else just return the the value of globle->settings
else:
sizex = cfg['SIZE']['X']
sizey = cfg['SIZE']['Y']
print ("Size x =" + sizex + " Size y =" + sizey)
# change the window to the defined size
root.geometry("%sx%s" % (sizex, sizey))
loaded_freq.set('Default Freq = ' + cfg['DUT']['FM_FREQ'])
#set bass and trebel to defaults
# bass_scale.set(7)
# treb_scale.set(0)
#clear frequency to restore default
fin.delete(0, END)
else:
print("Missing Config File!!" + str(fileOK))
tkinter.messagebox.showinfo("Config File Error", "The specified configuration file could not be found:" + filetoload )
loaded_config.set("Config file not found!")
def CheckBassTreb():
print("Check bass and treble values")
if cfg.has_section('BASS'):
bass_default = int(cfg['BASS']['VALUE'])
else:
bass_default = 7
if cfg.has_section('TREBLE'):
treb_default = int(cfg['TREBLE']['VALUE'])
else:
treb_default = 0
print("Bass default = " + str(bass_default))
print("Treb default = " + str(treb_default))
bass_scale.set(bass_default)
treb_scale.set(treb_default)
def CheckCAN(bus_type=None, speed=None):
# set gui to match default setting
global CONNECTED_BUS_SPEED, CONNECTED_BUS_TYPE, User_Connect
print("bus=" + bus_type + " speed=" + speed, " connected type=" + CONNECTED_BUS_TYPE)
if User_Connect and ((CONNECTED_BUS_SPEED != "None" and CONNECTED_BUS_SPEED != speed) or (CONNECTED_BUS_TYPE != "None" and CONNECTED_BUS_TYPE != bus_type)):
tkinter.messagebox.showinfo("CAN Config Not Implemented", "CAN speed or type change detected. You must disconnect and reconnect to make this effective!")
return
if bus_type == 'hs' and speed == '500':
sp_500_HS.set(True)
CONNECTED_BUS_SPEED = speed
CONNECTED_BUS_TYPE = bus_type
CAN_setup0()
elif bus_type == 'hs' and speed == '125':
sp_125_HS.set(True)
CONNECTED_BUS_SPEED = speed
CONNECTED_BUS_TYPE = bus_type
CAN_setup1()
elif bus_type == 'ms' and speed == '125':
sp_125_MS.set(True)
CONNECTED_BUS_SPEED = speed
CONNECTED_BUS_TYPE = bus_type
CAN_setup3()
elif bus_type == 'ms' and speed == '500':
sp_500_MS.set(True)
CONNECTED_BUS_SPEED = speed
CONNECTED_BUS_TYPE = bus_type
CAN_setup2()
else:
print("Invalid CAN settings in ini file!")
def CheckSpeaker():
# checks for speaker type in the ini file and sets program accordingly
# Enter in config file as:
# [SPEAKER]
# type = Panasonic | Clarion | Visteon
if cfg.has_section('SPEAKER'):
sptype = cfg['SPEAKER']['TYPE']
sptype = sptype.lower()
if sptype == '1': #no tweeter
Speaker1.set(True)
Sp1_change()
print("Speaker type 1")
elif sptype == '2': #with tweeter
Speaker2.set(True)
Sp2_change()
print("Speaker type 2")
elif sptype == '3': #undefined
Speaker3.set(True)
print("Speaker type 3")
Sp3_change()
else:
print("Invalid Speaker type defined - check config")
else:
print("No Speaker type found")
def CheckAMP():
"""
Run as part of load config only. checks for AMP in the ini file and sets program accordingly - also determines the default volume setting
Enter in config file as:
[AMP]
If volume is missing then last loaded volume will persists
"""
global default_volume_front, default_volume_rear
print("Checking for AMP in config file only...")
if cfg.has_section('AMP'):
amptype = cfg['AMP']['TYPE']
amptype = amptype.lower()
if amptype == '1': # THX
Amp_THX_Present.set(True)
Amp_SONY_Present.set(False)
Amp_HARMAN_Present.set(False)
print("THX AMP is present")
default_volume_front= cfg['AMP']['VOLUME_FRONT']
default_volume_rear = cfg['AMP']['VOLUME_REAR']
elif amptype == '2': # SONY
Amp_SONY_Present.set(True)
Amp_THX_Present.set(False)
Amp_HARMAN_Present.set(False)
print("THX AMP is present")
default_volume_front= cfg['AMP']['VOLUME_FRONT']
default_volume_rear = cfg['AMP']['VOLUME_REAR']
elif amptype == '3': # HARMNA
Amp_SONY_Present.set(False)
Amp_THX_Present.set(False)
Amp_HARMAN_Present.set(True)
print("HARMAN AMP is present")
default_volume_front= cfg['AMP']['VOLUME_FRONT']
default_volume_rear = cfg['AMP']['VOLUME_REAR']
elif amptype == '0': # NO AMP
Amp_THX_Present.set(False)
Amp_SONY_Present.set(False)
Amp_HARMAN_Present.set(False)
print("No AMP present")
default_volume_front= cfg['DUT']['VOLUME_FRONT']
default_volume_rear = cfg['DUT']['VOLUME_REAR']
else:
print("Invalid AMP type defined - check config")
Amp_THX_Present.set(False)
Amp_SONY_Present.set(False)
else:
print("No AMP type found during autocheck")
default_volume_front= cfg['DUT']['VOLUME_FRONT']
default_volume_rear = cfg['DUT']['VOLUME_REAR']
loaded_volume.set('Default Front Volume Setting = ' + default_volume_front)
loaded_Rvolume.set('Default Rear Volume Setting = ' + default_volume_rear)
print('Default Front Volume Setting = ' + default_volume_front)
print('Default Rear Volume Setting = ' + default_volume_rear)
def AMP_autocheck():
"""
Run each time a BT connection is made and will force the AMP setting based on results and is independent of the
config.ini file.
"""
global default_volume_front, default_volume_rear
print("Auto check for AMP")
# do auto check for AMP THX and HARMAN use same messages so need to decide which to run based on config
if Amp_HARMAN_Present.get():
if speaker_All(False):
print("HARMAN AMP FOUND in AutoCHECK!!")
default_volume_front = cfg['AMP']['VOLUME_FRONT']
default_volume_rear = cfg['AMP']['VOLUME_REAR']
return
else: # check for THX AMP
Amp_THX_Present.set(True) # source to send messsage to AMP
Amp_HARMAN_Present.set(False) # source to send messsage to AMP
Amp_SONY_Present.set(False) # source to send messsage to AMP
if speaker_All(False):
print("THX AMP FOUND in AutoCHECK!!")
default_volume_front = cfg['AMP']['VOLUME_FRONT']
default_volume_rear = cfg['AMP']['VOLUME_REAR']
return
# if none found then check for SONY ano
Amp_THX_Present.set(False) # source to send messsage to AMP
Amp_SONY_Present.set(True) # source to send messsage to AMP
Amp_HARMAN_Present.set(False) # source to send messsage to AMP
if speaker_All(False):
print("SONY AMP FOUND in AutoCHECK!!")
default_volume_front = cfg['AMP']['VOLUME_FRONT']
default_volume_rear = cfg['AMP']['VOLUME_REAR']
return
else:
print("NO AMP FOUND in AutoCHECK!!")
Amp_THX_Present.set(False)
Amp_SONY_Present.set(False)
Amp_HARMAN_Present.set(False) # source to send messsage to AMP
default_volume_front= cfg['DUT']['VOLUME_FRONT']
default_volume_rear = cfg['DUT']['VOLUME_REAR']
loaded_volume.set('Default Front Volume Setting = ' + default_volume_front)
loaded_Rvolume.set('Default Rear Volume Setting = ' + default_volume_rear)
print('Default Front Volume Setting = ' + default_volume_front)
print('Default Rear Volume Setting = ' + default_volume_rear)
def CheckAHU():
"""
checks for AHU type in the ini file and sets program accordingly
Enter in config file as:
[AHU]
type = Panasonic | Clarion | Visteon
"""
if cfg.has_section('AHU'):
ahutype = cfg['AHU']['TYPE']
ahutype = ahutype.lower()
if ahutype == 'panasonic':
AHU_Pana.set(True)
AHU_changeP()
elif ahutype == 'clarion':
AHU_Clar.set(True)
AHU_changeC()
elif ahutype == 'visteon':
AHU_Vist.set(True)
AHU_changeV()
elif ahutype == 'visteon-gap':
AHU_VistGap.set(True)
AHU_changeVGap()
elif ahutype == 'pana-gap':
AHU_PanaGap.set(True)
AHU_changePGap()
else:
print("Invalid AHU type defined - check config")
else:
print("No AHU type found")
def CheckTP():
"""
checks for additional tester present ID and sends the TP On command
Enter in config file as:
[TESTERPRESENT]
idlist = 7DF, 777, 711
"""
if cfg.has_section('TESTERPRESENT'):
canid = cfg['TESTERPRESENT']['IDLIST'].split(',')
for id in canid:
id = id.replace(" ", "") # remove whitespacec if present
id = id.upper()
print ("Enable TP for :" + id)
testerPon(forceid=id)
else:
print("No additional TP")
def CheckVIN():
""""
checks for presence of the VIN ECU to query and displays the correct button
Enter in config file as:
[VIN]
ecu = bcm sync, ahu, ipc, bcm, abs - only list 1!!!
"""
global VIN_ecu, vin_y, vin_x
if cfg.has_section('VIN'):
VIN_ecu = cfg['VIN']['ECU'].upper()
print("VIN ecu = " + VIN_ecu)
# hide all and show the ones used
HideVINbuttons()
if VIN_ecu == "SYNC":
print("Show VIN-SYNC")
app.getVINsync_b.pack()
app.getVINsync_b.place(rely=vin_y, relx=.40)
elif VIN_ecu == "AHU":
print("Show VIN-AHU")
app.getVINahu_b.pack()
app.getVINahu_b.place(rely=vin_y, relx=vin_x)
elif VIN_ecu == "ABS":
print("Show VIN-ABS")
app.getVINabs_b.pack()
app.getVINabs_b.place(rely=vin_y, relx=0)
elif VIN_ecu == "BCM":
print("Show VIN-BCM")
app.getVINbcm_b.pack()
app.getVINbcm_b.place(rely=vin_y, relx=vin_x * 2)
elif VIN_ecu == "IPC":
print("Show VIN-IPC")
app.getVINipc_b.pack()
app.getVINipc_b.place(rely=vin_y, relx=vin_x * 3)
elif VIN_ecu == "RCM":
print("Show VIN-RCM")
app.getVINrcm_b.pack()
app.getVINrcm_b.place(rely=vin_y, relx=vin_x * 4)
else:
print("No VIN ecu in config")
def HideVINbuttons():
app.getVINahu_b.place_forget()
app.getVINabs_b.place_forget()
app.getVINsync_b.place_forget()
app.getVINbcm_b.place_forget()
app.getVINipc_b.place_forget()
app.getVINrcm_b.place_forget()
def ReadVIN():
""""
query the vehicle for the VIN data
"""
global VIN_ecu
if VIN_ecu == "SYNC":
print("get VIN-SYNC")
get_VIN_SYNC()
elif VIN_ecu == "AHU":
print("get VIN-AHU")
get_VIN_AHU()
elif VIN_ecu == "ABS":
print("get VIN-ABS")
get_VIN_ABS()
elif VIN_ecu == "BCM":
print("get VIN-BCM")
get_VIN_BCM()
elif VIN_ecu == "IPC":
print("get VIN-IPC")
get_VIN_IPC()
elif VIN_ecu == "RCM":
print("get VIN-RCM")
get_VIN_RCM()
elif VIN_ecu == "PCM":
print("get VIN-PCM")
get_VIN_PCM()
else:
print("No VIN ecu in config")
def Hide(action):
print("hiding =" + str(action))
if action:
app.startserver_b.place_forget()
app.connect_b.place_forget()
# app.setBass_b.place_forget()
# app.setTreb_b.place_forget()
# bass_in.place_forget()
# treb_in.place_forget()
app.radioOn_b.place_forget()
app.Testerp_b.place_forget()
app.TesterpOff_b.place_forget()
app.Test_b.place_forget()
tpid.place_forget()
tpid_off.place_forget()
HideVINbuttons()
else:
app.onepress_b.place_forget()
app.startserver_b.pack(in_=app.frame)
app.startserver_b.place(rely=.12, relx=.2)
app.onepress_b.pack(in_=app.frame)
app.onepress_b.place(rely=.12, relx=0)
app.connect_b.pack(in_=app.frame)
app.connect_b.place(rely=.12, relx=.3)
# app.setBass_b.pack(in_=app.frame)
# app.setBass_b.place(rely=.2, relx=0)
# app.setTreb_b.pack(in_=app.frame)
# app.setTreb_b.place(rely=.2, relx=.34)
# bass_in.pack(in_=app.frame)
# bass_in.place(rely=.21, relx=.18)
# treb_in.pack(in_=app.frame)
# treb_in.place(rely=.21, relx=.52)
app.radioOn_b.pack(in_=app.frame)
app.radioOn_b.place(rely=.12, relx=.4)
app.Testerp_b.pack(in_=app.frame)
app.Testerp_b.place(rely=.95, relx=0)
app.TesterpOff_b.pack(in_=app.frame)
app.TesterpOff_b.place(rely=.9, relx=0)
app.Test_b.pack(in_=app.frame)
app.Test_b.place(rely=.9, relx=.2)
tpid.pack(in_=app.frame)
tpid.place(rely=.96, relx=.1)
tpid_off.pack(in_=app.frame)
tpid_off.place(rely=.91, relx=.1)
app.getVINahu_b.pack()
app.getVINahu_b.place(rely=vin_y, relx=vin_x)
app.getVINabs_b.pack()
app.getVINabs_b.place(rely=vin_y, relx=0)
app.getVINsync_b.pack()
app.getVINsync_b.place(rely=vin_y, relx=vin_x * 5)
app.getVINbcm_b.pack()
app.getVINbcm_b.place(rely=vin_y, relx=vin_x * 2)
app.getVINipc_b.pack()
app.getVINipc_b.place(rely=vin_y, relx=vin_x * 3)
app.getVINrcm_b.pack()
app.getVINrcm_b.place(rely=vin_y, relx=vin_x * 4)
def quitme():
# write the window size to the ini file for next startup
global fileOK, servercmd, config_file
if fileOK:
cfg.set('SIZE', 'X', str(root.winfo_width()))
cfg.set('SIZE', 'Y', str(root.winfo_height()))
print("Saving Configuration data...")
cfg.write(open(config_file, "w"))
disconnect()
try:
s.close()
servercmd.kill()
except:
pass
sys.exit()
def left_mouse(event):
print("Left Mouse @ {},{}".format(event.x, event.y))
def right_mouse(event):
print("Right Mouse @ {},{}".format(event.x, event.y))
def a_key(event):
global engineering_mode
global MasterVol1, MasterVol2
print("{},{}".format(event.x, event.y), event.char)
if event.char == 'E':
engineering_mode = not engineering_mode
Hide(not engineering_mode)
print("toggle engineering mode = " + str(engineering_mode))
elif event.char == 'T':
CheckVIN()
elif event.char == '+':
# create a popup menu self.setVol1_b = Button(master, text="Vol=1", command=set_vol1, fg="white", bg="green")
if MasterVol1 < 30:
MasterVol1 += 1
app.setVol1_b.configure(text="Vol=" + str(MasterVol1))
elif event.char == '-':
# create a popup menu self.setVol1_b = Button(master, text="Vol=1", command=set_vol1, fg="white", bg="green")
if MasterVol1 > 0 :
MasterVol1 -= 1
app.setVol1_b.configure(text="Vol=" + str(MasterVol1))
elif event.char == '>':
# create a popup menu self.setVol1_b = Button(master, text="Vol=1", command=set_vol1, fg="white", bg="green")
if MasterVol2 < 30:
MasterVol2 += 1
app.setVol16_b.configure(text="Vol=" + str(MasterVol2))
elif event.char == '<':
# create a popup menu self.setVol1_b = Button(master, text="Vol=1", command=set_vol1, fg="white", bg="green")
if MasterVol2 > 0 :
MasterVol2 -= 1
app.setVol16_b.configure(text="Vol=" + str(MasterVol2))
# popupw = Menu(root, tearoff=0)
# popupw.add_command(label="Display the label")
# popupw.add_command(input("hi"))
# # display the popup menu
# try:
# popupw.tk_popup(event.x_root, event.y_root, 0)
# finally:
# # make sure to release the grab (Tk 8.0a1 only)
# popupw.grab_release()
def about():
tkinter.messagebox.showinfo("CAN Invader BT Controller", "Ver 3.0 - June 17, 2016 \r\n Ford Motor Company \r\n Contact:LbeLLan1@Ford.com\r\n")
print("width =" + str(root.winfo_width()))
print("height =" + str(root.winfo_height()))
# print (root.winfo_geometry())
def show_instructions():
# show pdf instruction guide
subprocess.Popen("instructions.pdf",shell=True)
def start_server():
global command_error, servercmd
# see if already connected
if User_Connect:
print("server already connected")
tkinter.messagebox.showinfo("Server Started", "Server already started and connected!")
return
# see if server already running but not connected
try:
server_status = servercmd.poll()
print ("Check server status = " + str(server_status) + "(None = running)")
if server_status is None:
tkinter.messagebox.showinfo("Server Started", "Server already started but not connected!")
return
except:
print("server status run check failed (means not running yet).")
command_error = False
print("starting server")
# global servercmd
servercmd = subprocess.Popen([sys.executable, "tcp_server.py", "--CONFIG", config_file], creationflags=CREATE_NEW_CONSOLE)
def onepress():
global command_error, default_volume_front, servercmd
if User_Connect:
print("already connected")
tkinter.messagebox.showinfo("Server Running", "Server already started and connected!")
return
print("onepress started")
command_error = False
# see if server already running but not connected
try:
server_status = servercmd.poll()
print ("Check server status = " + str(server_status) + "(None = running)")
if server_status is None:
print( "Server already started but not connected!")
else: # number means tereminated and need to start again
start_server()
except: # can occur first time server_status is checked since servercmd not defined
print("server not running - starting now")
start_server()
# if connect not successful then do not perform other commands!
a = connect()
if a:
AMP_autocheck() # another check to make sure of AMP presence
radio_on()
set_bass()
set_treble()
set_freq()
set_vol_default(default_volume_front)
ReadVIN()
else:
# close active server
disconnect()
def testerPon(forceid=None):
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("tester present on")
id1 = tpid.get()
if id1 != "":
id1 = "," + id1
if forceid is not None: # forceid takes precedence
id1 = "," + str(forceid)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'testerPresentOn' + id1], creationflags=CREATE_NO_WINDOW)
def testerPoff():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("tester present off")
id1 = tpid_off.get()
if id1 != "":
id1 = "," + id1
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'testerPresentOff' + id1], creationflags=CREATE_NO_WINDOW)
def connect():
global command_error, CONNECTED_BUS_SPEED, CONNECTED_BUS_TYPE
command_error = False
print("BT connect")
# see if server already running but not connected
try:
server_status = servercmd.poll()
print ("Check server status = " + str(server_status) + "(None = running)")
if server_status is None:
print( "Server already started..will attemp to connect!")
else: # number means tereminated and need to start again
tkinter.messagebox.showinfo("No Server","No server running - please start this first!" )
return
except: # can occur first time server_status is checked since servercmd not defined
tkinter.messagebox.showinfo("No Server","No server running - please start this first!" )
return
os.system("start /wait cmd /c bt_connect_only.bat")
if sp_125_HS.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'configureCAN,125,hs'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
print("Set CAN 125 HS")
#todo: set connect status flags
CONNECTED_BUS_SPEED = "125"
CONNECTED_BUS_TYPE = "hs"
elif sp_125_MS.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'configureCAN,125,ms'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
print("Set CAN 125 MS")
CONNECTED_BUS_SPEED = "125"
CONNECTED_BUS_TYPE = "ms"
elif sp_500_MS.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'configureCAN,500,ms'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
print("Set CAN 500 MS")
CONNECTED_BUS_SPEED = "500"
CONNECTED_BUS_TYPE = "ms"
elif sp_500_HS.get():
print("Set CAN 500 HS")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'configureCAN,500,hs'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
CONNECTED_BUS_SPEED = "500"
CONNECTED_BUS_TYPE = "hs"
else:
print("Set CAN from ini")
# no configuration chosen so use default in ini file
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'configureCAN'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
# CheckCAN(bus_type = cfg['CAN']['busType'].lower(), speed = cfg['CAN']['speed'].lower())
stdout, stderr = p.communicate()
print(stdout + stderr)
if stdout.find(b'ConfigOK') > 0:
global User_Connect
User_Connect = True
os.system("start /wait cmd /c TP_on.bat")
CheckTP() # keep this here
print("Connected OK!")
# CheckAHU()
# CheckSpeaker()
# CheckVIN()
ReadVIN()
AMP_autocheck()
return True
else:
User_Connect = False
print("Failed to connect via BT!")
tkinter.messagebox.showinfo("Connection Error", "No BT connection made! Please check setup. Make sure BlueTooth dongle is attached to PC. Check that CAN Invader is in range and attached to vehicle diagnostic port. Make sure BT MAC address is correect in setup file. Try unplugging and reconnecting CAN INVADER to vehicle." )
return False
def radio_on():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Radio On")
# os.system("start /wait cmd /c radio_on_AHU.bat")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','radioOnahu'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
print(stdout + stderr)
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_bass():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
b = bass_scale.get()
if b == "":
b = '0E' # max
else:
b = format(int(b) + 7, '02X')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set BASS =" + b)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetBassX,' + b], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get():
#Convert b to signed integer'
#convert to decimal
ivalue= bass_scale.get()
if ivalue == "":
ivalue = '07' # max
else:
ivalue = (tohex(ivalue,8)) #converts to signed integer - local function here
ivalue = ivalue.replace('x', '')
ivalue = ivalue[-2:]
print("Set BassV=" + ivalue)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setBassVisteon,' + ivalue], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_PanaGap.get(): #new add for DS-JK2T-18D15-CA
#Convert b to signed integer'
#convert to decimal
ivalue= bass_scale.get()
if ivalue == "":
ivalue = '07' # max
else:
ivalue = (tohex(ivalue,8)) #converts to signed integer - local function here
ivalue = ivalue.replace('x', '')
ivalue = ivalue[-2:]
print("Set BassV=" + ivalue)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setBassX,' + ivalue], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Bass=" + b)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setBassX,' + b], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def tohex(val, nbits):
return hex((val + (1 << nbits)) % (1 << nbits))
def set_treble():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Set Treble")
# os.system("start /wait cmd /c setTrebX.bat")
t = treb_scale.get()
if t == "":
t = '07' # nominal
else:
t = format(int(t) + 7,'02X')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Treble =" + t)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetTrebX,' + t], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get():
ivalue= treb_scale.get()
if ivalue == "":
ivalue = '07' # max
else:
ivalue = (tohex(ivalue,8)) #converts to signed integer - local function here
ivalue = ivalue.replace('x', '')
ivalue = ivalue[-2:]
print("Set TrebleV=" + ivalue)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setTrebVisteon,' + ivalue], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_PanaGap.get(): #new add for the Pana DS-JK2T-18D15-CA
ivalue= treb_scale.get()
if ivalue == "":
ivalue = '07' # max
else:
ivalue = (tohex(ivalue,8)) #converts to signed integer - local function here
ivalue = ivalue.replace('x', '')
ivalue = ivalue[-2:]
print("Set TrebleV=" + ivalue)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setTrebX,' + ivalue], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Treble=" + t)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setTrebX,' + t], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_freq():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
f = fin.get()
if f != "":
f_float = max(float(f), 87.5) # needs to be at least 87.5
f_float = min(f_float, 108) # limit to 108
fint = int(f_float * 10)
print("Set Frequency " + f + " " + str(fint))
p=Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setFreqX,' + str(fint)], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Frequency to default")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setFreq'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_vol1():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
v = format(MasterVol1, '02x')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol " + str(MasterVol1))
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get(): # setvolfront command uses the vol lookup table to adjust the volume steps
print("Set Vol GAP " + str(MasterVol1))
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol " + str(MasterVol1))
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_vol5():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol 5")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetVolumeX,05'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get(): # setvolfront command uses the vol lookup table to adjust the volume steps
print("Set Vol GAP 5" )
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,05'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol 5")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeX,05'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c setVolumeX5.bat")
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_vol19():
"""
This was changed from a static 19 setting to the FRONT DEFAULT volume setting
"""
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
vf = format(int(default_volume_front), '02x')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol Front = " + default_volume_front)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetVolumeX,' + vf], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get(): # setvolfront command uses the vol lookup table to adjust the volume steps
print("Set Vol GAP Front = " + default_volume_front)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,' + vf], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol Front = " + default_volume_front)
# os.system("start /wait cmd /c setVolumeX13.bat")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeX,' + vf], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_vol16():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
v = format(MasterVol2, '02x')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol" + str(MasterVol2))
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get(): # setvolfront command uses the vol lookup table to adjust the volume steps
print("Set Vol GAP " + str(MasterVol2))
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol " + str(MasterVol2))
v = format(MasterVol2, '02x')
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_vol22():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
vr = format(int(default_volume_rear), '02x')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol Rear = " + default_volume_rear)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPsetVolumeX,' + vr], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get(): # setvolfront command uses the vol lookup table to adjust the volume steps
print("Set Vol GAP Rear = " + default_volume_rear)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,' + vr], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol Rear = " + default_volume_rear)
# os.system("start /wait cmd /c setVolumeX13.bat")
p=Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeX,' + vr], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
return False
else:
command_error = False
return True
def set_volX():
"""
Take input form gui and send in volume - needs to be sent in HEX format!!
"""
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
v = v_scale.get()
if v != "":
v = format(int(v), '02x')
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol X =" + v)
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','AMPsetVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get(): # setvolfront command uses the vol lookup table to adjust the volume steps
print("Set Vol GAP " + v)
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol X =" + v)
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','setVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else: # no data entered so assume default defined in setVolumeX command that is 0
if Amp_THX_Present.get() or Amp_SONY_Present.get():
print("AMP Set Vol X = 0")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','AMPsetVolumeX'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get():
print("Set Vol GAP = 0")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol X = 0")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','setVolumeX'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
# check responses
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def set_vol_default(v_dec):
global command_error
# convert to hex for command as ini file is NOT in hex format!!
v = format(int(v_dec), '02x')
if v != "":
if Amp_THX_Present.get() or Amp_SONY_Present.get() or Amp_HARMAN_Present.get():
print("AMP Set Vol Default =" + v)
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','AMPsetVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
elif AHU_VistGap.get():
print("Set Vol GAP default")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'setVolumeFront,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
else:
print("Set Vol Default =" + v)
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','setVolumeX,' + v], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
return False
else:
command_error = False
loaded_volume.set('Default Front Volume Setting = ' + str(v_dec))
return True
else:
print("Default volume missing")
command_error = True
return False
def get_VIN_AHU():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN ahu")
# os.system("start /wait cmd /c log_VIN_AHU.bat")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVIN'], creationflags=CREATE_NO_WINDOW, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
def get_VIN_ABS():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN abs")
# os.system("start /wait cmd /c log_VIN_ABS.bat")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVINabs'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
def get_VIN_SYNC():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN sync")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVINsync'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c log_VIN_SYNC.bat")
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
def get_VIN_BCM():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN bcm")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVINbcm'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
# TODO-test PCM get VIN and add button
def get_VIN_PCM():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN pcm")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVINpcm'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
def get_VIN_RCM():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN rcm")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVINrcm'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
def get_VIN_IPC():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
command_error = False
print("Get VIN ipc")
p = Popen([sys.executable, "pynetcat.py",'localhost','50000','readVINipc'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c log_VIN_SYNC.bat")
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
fv = stdout.find(b'vin=')
VIN_read = str(stdout)
VIN_read = VIN_read[fv + 6:fv + 23]
print("VIN = " + VIN_read)
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = " + VIN_read)
info_l4.config(state=DISABLED)
def disconnect():
global User_Connect, CONNECTED_BUS_TYPE, CONNECTED_BUS_SPEED
global command_error, servercmd
print("BT Disconnect")
os.system("start /wait cmd /c bt_disconnect.bat")
global User_Connect
User_Connect = False
command_error = False
info_l4.config(state=NORMAL)
info_l4.delete(1.0, END)
info_l4.insert(1.0, "VIN = <no connection>")
info_l4.config(state=DISABLED)
CONNECTED_BUS_SPEED = "None"
CONNECTED_BUS_TYPE = "None"
try:
servercmd.kill()
except:
pass
def speaker_LF():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
# take into account the speaker config, AHU type, and AMP presence
print("Speaker LF")
# Check for AMP first
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableLFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableLFtwt8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableLFtwt4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
if Speaker1.get(): # no tweeters
print("AHU=Clar, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLF4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else: # with tweeters
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Pana.get() or AHU_PanaGap.get():
print("Panasonic")
if Speaker1.get(): # no tweeters
print("AHU=Pana, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLF4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else: # with tweeters
print("AHU=Pana, Speaker=2/3")
# os.system("start /wait cmd /c speakerEnableLFtwt_Clarion.bat")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Vist.get() or AHU_VistGap.get():
# print("Visteon")
if Speaker1.get():
print("AHU=Visteon, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLF'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLFtwt'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_RF():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Speaker RF")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRFtwt8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRFtwt4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
if Speaker1.get():
print("AHU=Clar, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRF4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Pana.get() or AHU_PanaGap.get():
# os.system("start /wait cmd /c speakerEnableRFtwt_Panasonic.bat")
if Speaker1.get():
print("AHU=Pana, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRF4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
print("AHU=Pana, Speaker=2")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Vist.get() or AHU_VistGap.get():
if Speaker1.get():
print("AHU=Visteon, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRF'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRFtwt'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_LR():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Speaker LR")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableLRtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableLRtwt8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableLRtwt4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
if Speaker1.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Pana.get()or AHU_PanaGap.get():
if Speaker1.get():
print("AHU=Pana, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
print("AHU=Pana, Speaker=2")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Vist.get() or AHU_VistGap.get():
if Speaker1.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLR'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableLR'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_RR():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Speaker RR")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRRtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRRtwt8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRRtwt4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
if Speaker1.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Pana.get()or AHU_PanaGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableRR_Panasonic.bat")
elif AHU_Vist.get() or AHU_VistGap.get():
if Speaker1.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRR'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRR'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_All(check=True): # check used to supress waring when used as AMP Detector
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Speaker All")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableAllOn4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableAllOn8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableAllOn4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get(): # works on P552
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableAllOn4Clarion'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Clarion.bat")
elif AHU_Pana.get()or AHU_PanaGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableAllOn4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Panasonic.bat")
elif AHU_Vist.get() or AHU_VistGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableAllOn'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Visteon.bat")
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
if check:
command_error = True
return False
else:
command_error = False
return True
def speaker_Center():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
# os.system("start /wait cmd /c speakerEnableCntr_Clarion.bat")
global command_error
print("Speaker Center")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableCntr'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableCntr8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableCntrH'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableCntrtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Clarion.bat")
elif AHU_Pana.get()or AHU_PanaGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableCntrtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Panasonic.bat")
elif AHU_Vist.get() or AHU_VistGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableCntrtwt'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Visteon.bat")
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_Sub():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
print("Speaker Sub")
# os.system("start /wait cmd /c speakerEnableSub_Clarion.bat")
global command_error
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableSub4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableSub8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableSub4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableSub4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Clarion.bat")
elif AHU_Pana.get()or AHU_PanaGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableSub4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Panasonic.bat")
elif AHU_Vist.get() or AHU_VistGap.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableSub'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# os.system("start /wait cmd /c speakerEnableAllOn_Visteon.bat")
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_FrontOnly():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Speaker Front Only")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableFtwt8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableFtwt4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
if Speaker1.get():
print("AHU=Clar, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableF4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Pana.get()or AHU_PanaGap.get():
if Speaker1.get():
print("AHU=Pana, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableF4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
print("AHU=Pana, Speaker=2")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableFtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Vist.get() or AHU_VistGap.get():
if Speaker1.get():
print("AHU=Visteon, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableF'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableFtwt'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def speaker_RearOnly():
if not User_Connect:
tkinter.messagebox.showinfo("No Connection", "Please connect to a CAN device")
return
global command_error
print("Speaker Rear Only")
if Amp_THX_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_SONY_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRtwt8'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif Amp_HARMAN_Present.get():
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'AMPspeakerEnableRtwt4H'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
# then check by AHU and speaker type
elif AHU_Clar.get():
if Speaker1.get():
print("AHU=Clar, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Pana.get()or AHU_PanaGap.get():
if Speaker1.get():
print("AHU=Pana, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableR4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
print("AHU=Pana, Speaker=2")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRtwt4'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
elif AHU_Vist.get() or AHU_VistGap.get():
if Speaker1.get():
print("AHU=Visteon, Speaker=1")
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableR'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
else:
p = Popen([sys.executable, "pynetcat.py", 'localhost', '50000', 'speakerEnableRtwt'], creationflags=CREATE_NEW_CONSOLE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stdout.find(b'Error') > 0:
print("Error sending last command!")
command_error = True
else:
command_error = False
def CAN_setup0(): #500 HS
if User_Connect:
if (CONNECTED_BUS_SPEED == "500") and (CONNECTED_BUS_TYPE == "hs"):
sp_500_HS.set(True)
else:
sp_500_HS.set(False)
tkinter.messagebox.showinfo("CAN Config 500 HS Not Implemented", "CAN speed or type change detected. You must disconnect and reconnect to make this effective!")
return
if sp_500_HS.get:
sp_125_HS.set(False)
sp_125_MS.set(False)
sp_500_MS.set(False)
sp_500_HS.set(True)
# print("sp_500=" + str(sp_500_HS.get()))
print("CAN setup 0")
def CAN_setup1(): #125 HS
if User_Connect: #and ((CONNECTED_BUS_SPEED != "None") or (CONNECTED_BUS_TYPE != "None"))
if (CONNECTED_BUS_SPEED == "125") and (CONNECTED_BUS_TYPE == "hs"):
sp_125_HS.set(True)
else:
sp_125_HS.set(False)
tkinter.messagebox.showinfo("CAN Config 125 HS Not Implemented", "CAN speed or type change detected. You must disconnect and reconnect to make this effective!")
return
if sp_125_HS.get:
sp_125_HS.set(True)
sp_125_MS.set(False)
sp_500_MS.set(False)
sp_500_HS.set(False)
print("CAN setup 1")
def CAN_setup2(): #500 MS
if User_Connect:
if (CONNECTED_BUS_SPEED == "500") and (CONNECTED_BUS_TYPE == "ms"):
sp_500_MS.set(True)
else:
sp_500_MS.set(False)
tkinter.messagebox.showinfo("CAN Config 500 MS Not Implemented", "CAN speed or type change detected. You must disconnect and reconnect to make this effective!")
return
if sp_500_MS.get:
sp_125_HS.set(False)
sp_125_MS.set(False)
sp_500_MS.set(True)
sp_500_HS.set(False)
print("CAN setup 2")
def CAN_setup3(): # 125 MS
if User_Connect:
if (CONNECTED_BUS_SPEED == "125") and (CONNECTED_BUS_TYPE == "ms"):
sp_125_MS.set(True)
else:
sp_125_MS.set(False)
tkinter.messagebox.showinfo("CAN Config 125 MS Not Implemented", "CAN speed or type change detected. You must disconnect and reconnect to make this effective!")
return
if sp_125_MS.get:
sp_125_HS.set(False)
sp_125_MS.set(True)
sp_500_MS.set(False)
sp_500_HS.set(False)
print("CAN setup 3")
def AHU_changeP():
print("AHU Change")
if AHU_Pana.get():
print("Panasonic")
AHU_Pana.set(True)
AHU_Clar.set(False)
AHU_Vist.set(False)
AHU_VistGap.set(False)
AHU_PanaGap.set(False)
def AHU_changeC():
print("AHU Change")
if AHU_Clar.get():
print("Clarion")
AHU_Pana.set(False)
AHU_Clar.set(True)
AHU_Vist.set(False)
AHU_VistGap.set(False)
AHU_PanaGap.set(False)
def AHU_changeV():
print("AHU Change")
if AHU_Vist.get():
print("Visteon")
AHU_Pana.set(False)
AHU_Clar.set(False)
AHU_Vist.set(True)
AHU_VistGap.set(False)
AHU_PanaGap.set(False)
def AHU_changeVGap():
print("AHU Change")
if AHU_VistGap.get():
print("Visteon Gap")
AHU_Pana.set(False)
AHU_Clar.set(False)
AHU_Vist.set(False)
AHU_VistGap.set(True)
AHU_PanaGap.set(False)
def AHU_changePGap(): #added on Dec 12 2017
print("AHU Change")
if AHU_PanaGap.get():
print("Pana Gap")
AHU_Pana.set(False)
AHU_Clar.set(False)
AHU_Vist.set(False)
AHU_VistGap.set(False)
AHU_PanaGap.set(True)
def Amp_SONY_Change():
print("AMP Change")
if Amp_SONY_Present.get():
print("SONY AMP")
Amp_THX_Present.set(False)
Amp_SONY_Present.set(True)
Amp_HARMAN_Present.set(False)
def Amp_THX_Change():
print("AMP Change")
if Amp_THX_Present.get():
print("THX AMP")
Amp_THX_Present.set(True)
Amp_SONY_Present.set(False)
Amp_HARMAN_Present.set(False)
def Amp_HARMAN_Change():
print("AMP Change")
if Amp_HARMAN_Present.get():
print("HARMAN AMP")
Amp_THX_Present.set(False)
Amp_SONY_Present.set(False)
Amp_HARMAN_Present.set(True)
def Sp1_change():
if Speaker1.get():
Speaker2.set(False)
Speaker1.set(True)
Speaker3.set(False)
def Sp2_change():
if Speaker2.get():
Speaker1.set(False)
Speaker2.set(True)
Speaker3.set(False)
def Sp3_change():
if Speaker3.get():
Speaker1.set(False)
Speaker2.set(False)
Speaker3.set(True)
def on_closing():
# handle the close x press
if tkinter.messagebox.askokcancel("Quit", "Do you want to quit?"):
# root.destroy()
quitme()
def listenloop(s):
# creates thread that monitors for incoming data to the gui port 50001
# to use run this in command line: python pynetcat.py localhost 50001 data
global default_volume_front
size = 1024
while True:
try:
client, address = s.accept()
print("Client " + str(address) + " connected!")
data = client.recv(size)
if data:
try:
data = str(data)
print("command recd = " + data)
if data.find("about")>0:
about()
elif data.find("speakerlf")>0:
speaker_LF()
elif data.find("speakerrf")>0:
speaker_RF()
elif data.find("speakerlr")>0:
speaker_LR()
elif data.find("speakerrr")>0:
speaker_RR()
elif data.find("startBT")>0:
onepress()
elif data.find("speakerAll")>0:
speaker_All()
elif data.find("speakerCenter")>0:
speaker_Center()
elif data.find("speakerSub")>0:
speaker_Sub()
elif data.find("disconnect")>0:
disconnect()
elif data.find("config")>0:
filename = data[data.find('=') + 1:]
filename = str(filename).replace("'","") # remove quotes
print("Klippel config :" + filename)
LoadConfig(filename)
elif data.find("volDownF")>0:
default_volume_int = int(default_volume_front) - 1
default_volume_int = max(0, default_volume_int)
print("Klippel Vol Down Front = " + str(default_volume_int))
default_volume_front= str(default_volume_int)
set_vol_default(default_volume_front)
elif data.find("volUpF")>0:
default_volume_int = int(default_volume_front) + 1
default_volume_int = min(30, default_volume_int)
print("Klippel Vol Up Front = " + str(default_volume_int))
default_volume_front= str(default_volume_int)
set_vol_default(default_volume_front)
except:
print(traceback.format_exc())
print('Command Execution failed!')
client.send(b'OK')
client.close()
except (KeyboardInterrupt, SystemExit):
s.close()
exit()
except socket.timeout:
print("Waiting for incoming connection" )
class App:
def __init__(self, master):
# reference global variables for button position - makes organizing easier
global speaker_y, speaker_x, volume_y, vin_y
self.frame = Frame(master, relief=SUNKEN)
# master.geometry("320x400")
master.geometry("%sx%s" % (default_sizex, default_sizey))
master.title("CAN Invader Script Controller")
master.bind("<Button-1>", left_mouse)
master.bind("<Button-3>", right_mouse)
master.bind("<Key>", a_key)
self.frame.pack()
# info_l1 = Label(master, text="Config... ")# + ConfigFile.config_file)
# info_l1.pack(side=TOP)
# info_l2 = Label(master, text="Connection Status = NOT CONNECTED")
# info_l2.pack(side=TOP)
self.disconnect_b = Button(master, text="Disconnect", command=disconnect, fg="red", bg="white", height=1, width=10, font=font1)
self.disconnect_b.pack(side=BOTTOM)
disconnect_b_ttp = CreateToolTip(self.disconnect_b, "Disconnects BT and stops server - use if changing config")
self.startserver_b = Button(master, text="Start Serv", command=start_server, fg="white", bg="blue")
self.startserver_b.pack(in_=self.frame)
self.startserver_b.place(rely=.12, relx=0)
startserver_b_ttp = CreateToolTip(self.startserver_b, "Press First - This needs to be running for other commands to work!")
self.connect_b = Button(master, text="Connect", command=connect, fg="blue", bg="white")
self.connect_b.pack()
self.connect_b.place(rely=.12, relx=.3)
Connect_b_ttp = CreateToolTip(self.connect_b, "Connects BT, initializes CAN and starts default TP message.")
self.radioOn_b = Button(master, text="Radio On", command=radio_on, fg="white", bg="purple")
self.radioOn_b.pack()
self.radioOn_b.place(rely=.12, relx=.4)
setradioOn__ttp = CreateToolTip(self.radioOn_b, "Enables audio system and sets mode to FM.")
self.setBass_b = Button(master, text="Set Bass", command=set_bass, fg="blue", bg="yellow")
self.setBass_b.pack()
self.setBass_b.place(rely=.2, relx=.2)
setBass_b_ttp = CreateToolTip(self.setBass_b, "Set Bass. Select value using slider on right.")
self.setTreb_b = Button(master, text="Set Treb", command=set_treble, fg="blue", bg="yellow")
self.setTreb_b.pack()
self.setTreb_b.place(rely=.2, relx=.34)
setTreb_b_ttp = CreateToolTip(self.setTreb_b, "Set Treble. Select value using slider on right.")
self.getVINahu_b = Button(master, text="VIN AHU", command=get_VIN_AHU, fg="white", bg="brown", height=2, width=7, font=font1)
self.getVINahu_b.pack()
self.getVINahu_b.place(rely=vin_y, relx=vin_x)
getVINahu_b_ttp = CreateToolTip(self.getVINahu_b, "Read VIN from AHU in F190.")
self.getVINabs_b = Button(master, text="VIN ABS", command=get_VIN_ABS, fg="white", bg="brown", height=2, width=7, font=font1)
self.getVINabs_b.pack()
self.getVINabs_b.place(rely=vin_y, relx=0)
getVINabs_b_ttp = CreateToolTip(self.getVINabs_b, "Read VIN from ABS module in F190.")
self.getVINsync_b = Button(master, text="VIN SYNC", command=get_VIN_SYNC, fg="white", bg="brown", height=2, width=8, font=font1)
self.getVINsync_b.pack()
self.getVINsync_b.place(rely=vin_y, relx=vin_x * 5)
getVINsync_b_ttp = CreateToolTip(self.getVINsync_b, "Read VIN from SYNC in F190.")
self.getVINbcm_b = Button(master, text="VIN BCM", command=get_VIN_BCM, fg="white", bg="brown", height=2, width=7, font=font1)
self.getVINbcm_b.pack()
self.getVINbcm_b.place(rely=vin_y, relx=vin_x * 2)
getVINbcm_b_ttp = CreateToolTip(self.getVINbcm_b, "Read VIN from BCM in F190.")
self.getVINipc_b = Button(master, text="VIN IPC", command=get_VIN_IPC, fg="white", bg="brown", height=2, width=7, font=font1)
self.getVINipc_b.pack()
self.getVINipc_b.place(rely=vin_y, relx=vin_x * 3)
getVINipc_b_ttp = CreateToolTip(self.getVINipc_b, "Read VIN from IPC in F190.")
self.getVINrcm_b = Button(master, text="VIN RCM", command=get_VIN_RCM, fg="white", bg="brown", height=2, width=7, font=font1)
self.getVINrcm_b.pack()
self.getVINrcm_b.place(rely=vin_y, relx=vin_x * 4)
getVINrcm_b_ttp = CreateToolTip(self.getVINrcm_b, "Read VIN from RCM in F190.")
self.setFreq_b = Button(master, text="Set Freq", command=set_freq, fg="blue", bg="orange", height=2, width=7, font=font1)
self.setFreq_b.pack()
self.setFreq_b.place(rely=.12, relx=.64)
# creat tool tips here
setFreq_b_ttp = CreateToolTip(self.setFreq_b, "Use box to enter optional frequency. If blank default used.")
self.setVol1_b = Button(master, text="Vol=1", command=set_vol1, fg="white", bg="green", height=2, width=6, font=font1)
self.setVol1_b.pack()
self.setVol1_b.place(rely=volume_y, relx=0)
setVol1_b_ttp = CreateToolTip(self.setVol1_b, "Use + and - to adjust the value of this button.")
self.setVol5_b = Button(master, text="Vol=5", command=set_vol5, fg="white", bg="green", height=2, width=6, font=font1)
self.setVol5_b.pack()
self.setVol5_b.place(rely=volume_y, relx=.16)
self.setVol16_b = Button(master, text="Vol=16", command=set_vol16, fg="white", bg="green", height=2, width=6, font=font1)
self.setVol16_b.pack()
self.setVol16_b.place(rely=volume_y, relx=.32)
setVol16_b_ttp = CreateToolTip(self.setVol16_b, "Use < and > to adjust the value of this button.")
self.setVol19_b = Button(master, text="Vol Front", command=set_vol19, fg="white", bg="lime", height=2, width=6, font=font1, wraplength=60)
self.setVol19_b.pack()
self.setVol19_b.place(rely=volume_y, relx=.48)
setVol19_b_ttp = CreateToolTip(self.setVol19_b, "Press to set the volume to FRONT default setting")
# self.setVol19_b = Button(master, text="Vol=19", command=set_vol19, fg="white", bg="green", height=2, width=6, font=font1)
# self.setVol19_b.pack()
# self.setVol19_b.place(rely=volume_y, relx=.48)
self.setVol22_b = Button(master, text="Vol Rear", command=set_vol22, fg="white", bg="lime", height=2, width=6, font=font1, wraplength=60)
self.setVol22_b.pack()
self.setVol22_b.place(rely=volume_y, relx=.64)
setVol22_b_ttp = CreateToolTip(self.setVol22_b, "Press to set the volume to REAR default setting")
# self.setVol22_b = Button(master, text="Vol=22", command=set_vol22, fg="white", bg="green", height=2, width=6, font=font1)
# self.setVol22_b.pack()
# self.setVol22_b.place(rely=volume_y, relx=.64)
self.setVolX_b = Button(master, text="Set VolX", command=set_volX, fg="white", bg="green", height=2, width=7, font=font1)
self.setVolX_b.pack()
self.setVolX_b.place(rely=volume_y, relx=.8)
setVolX_b_ttp = CreateToolTip(self.setVolX_b, "Use slider on right to select desired value")
self.speakerLF_b = Button(master, text="Speaker LF", command=speaker_LF, fg="white", bg="black", height=2, width=10, font=font1)
self.speakerLF_b.pack()
self.speakerLF_b.place(rely=speaker_y + .12, relx=speaker_x)
speakerLF_b_ttp = CreateToolTip(self.speakerLF_b, "Enable LEFT FRONT speaker only")
self.speakerCenter_b = Button(master, text="Speaker Center", command=speaker_Center, fg="white", bg="black", height=2, width=12, font=font1)
self.speakerCenter_b.pack()
self.speakerCenter_b.place(rely=speaker_y + .12, relx=speaker_x + .2)
speakerCenter_b_ttp = CreateToolTip(self.speakerCenter_b, "Enable Center Speaker only")
self.speakerRF_b = Button(master, text="Speaker RF", command=speaker_RF, fg="white", bg="black", height=2, width=10, font=font1)
self.speakerRF_b.pack()
self.speakerRF_b.place(rely=speaker_y + .12, relx=speaker_x + .43)
speakerRF_b_ttp = CreateToolTip(self.speakerRF_b, "Enable RIGHT FRONT speaker only")
self.speakerF_b = Button(master, text="Spk. Front", command=speaker_FrontOnly, fg="white", bg="gray", height=2, width=10, font=font1)
self.speakerF_b.pack()
self.speakerF_b.place(rely=speaker_y + .12, relx=speaker_x + .63)
speakerF_b_ttp = CreateToolTip(self.speakerF_b, "Enable ALL FRONT speakers only")
self.speakerRR_b = Button(master, text="Speaker RR", command=speaker_RR, fg="white", bg="black", height=2, width=10, font=font1)
self.speakerRR_b.pack()
self.speakerRR_b.place(rely=speaker_y + .28, relx=speaker_x + .43)
speakerRR_b_ttp = CreateToolTip(self.speakerRR_b, "Enable RIGHT REAR speaker only")
self.speakerR_b = Button(master, text="Spk. Rear", command=speaker_RearOnly, fg="white", bg="gray", height=2, width=10, font=font1)
self.speakerR_b.pack()
self.speakerR_b.place(rely=speaker_y + .28, relx=speaker_x + .63)
speakerR_b_ttp = CreateToolTip(self.speakerR_b, "Enable ALL REAR speakers only")
self.speakerSub_b = Button(master, text="Speaker Sub", command=speaker_Sub, fg="white", bg="black", height=2, width=10, font=font1)
self.speakerSub_b.pack()
self.speakerSub_b.place(rely=speaker_y + .28, relx=speaker_x + .2)
speakerSub_b_ttp = CreateToolTip(self.speakerSub_b, "Enable Subwoofer only")
self.speakerLR_b = Button(master, text="Speaker LR", command=speaker_LR, fg="white", bg="black", height=2, width=10, font=font1)
self.speakerLR_b.pack()
self.speakerLR_b.place(rely=speaker_y + .28, relx=speaker_x)
speakerLR_b_ttp = CreateToolTip(self.speakerLR_b, "Enable LEFT REAR speaker only")
self.speakerAll_b = Button(master, text="Speaker ALL", command=speaker_All, fg="white", bg="black", height=6, width=7, font=font1, wraplength=80)
self.speakerAll_b.pack()
self.speakerAll_b.place(rely=speaker_y + .12, relx=speaker_x + .82)
speakerAll_b_ttp = CreateToolTip(self.speakerAll_b, "Turn all speakers on to original setting")
self.Testerp_b = Button(master, text="TesterP On", command=testerPon, fg="blue", bg="pink")
self.Testerp_b.pack()
self.Testerp_b.place(rely=1, relx=0)
self.TesterpOff_b = Button(master, text="TesterP Off", command=testerPoff, fg="blue", bg="pink")
self.TesterpOff_b.pack()
self.TesterpOff_b.place(rely=.84, relx=.80)
self.onepress_b = Button(master, text="Start Here!", command=onepress, fg="white", bg="blue", height=2, width=10, font=font1)
self.onepress_b.pack()
self.onepress_b.place(rely=.12, relx=0)
onepress_b_ttp = CreateToolTip(self.onepress_b, "Starts server, configures CAN, TP on, radio on, sets treb bass vol and freq to default")
self.Test_b = Button(master, text="Test", command=NONE, fg="blue", bg="pink")
self.Test_b.pack()
self.Test_b.place(rely=.9, relx=0)
class CreateToolTip(object):
# create a tooltip for a given widget
def __init__(self, widget, text='widget info'):
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.close)
def enter(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.tw = tk.Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(self.tw, text=self.text, justify='left', background='yellow', relief='solid', borderwidth=1, font=("times", "10", "normal"))
label.pack(ipadx=1)
def close(self, event=None):
if self.tw:
self.tw.destroy()
# ==================================================================================================================
# ==================================================================================================================
# create global variable for the configuration file
User_Connect = False
root = Tk()
CONNECTED_BUS_TYPE = "None"
CONNECTED_BUS_SPEED = "None"
loaded_config = StringVar()
loaded_config.set('Config file not loaded!!')
e_popup = False
VIN_ecu = ""
ocolor = root.cget('bg')
info_l1 = Label(root, textvariable=loaded_config, font ="12")
info_l1.pack(side=TOP)
info_l1.place(relx=0)
default_volume_front = 0
default_volume_rear = 0
# global positioning variables to make life easier
speaker_y = .47
speaker_x = 0
volume_y = .42
vin_y = .27
vin_x = .16
# FRONT volume label
loaded_volume = StringVar()
loaded_volume.set('Front Volume Setting = tbd')
info_l3 = Label(root, textvariable=loaded_volume, font="12")
info_l3.pack(side=TOP)
info_l3.place(relx=.65)
# REAR volume label
loaded_Rvolume = StringVar()
loaded_Rvolume.set('Rear Volume Setting = tbd')
info_l13 = Label(root, textvariable=loaded_Rvolume, font="12")
info_l13.pack()
info_l13.place(rely=.05, relx=.65)
# VIN label
info_l4 = Text(root, height=1)
info_l4.insert(1.0,'VIN = <no connection>')
info_l4.pack()
info_l4.place(relx=.65, rely=.94)
info_l4.configure(bg=root.cget('bg'), relief=FLAT, font="12")
# Freq label
loaded_freq = StringVar()
loaded_freq.set('Default Freq = ')
info_l5 = Label(root, textvariable=loaded_freq, font="12")
info_l5.pack()
info_l5.place(relx=.78, rely=.19)
# Define fonts to use
font1 = font.Font(family='Helvetica', size='14')
tpid = Entry(root, bd =2, width=3)
tpid.pack()
tpid.place(rely=.76, relx=.82)
tpid_ttp = CreateToolTip(tpid, "Enter optional ECU ID for tester present on message. ex: 7DF")
fin = Entry(root, bd =2, width=5)
fin.pack()
fin.place(rely=.13, relx=.8)
fin_ttp = CreateToolTip(fin, "Enter valid FM freq from 87.50 to 108.00")
v_scale = Scale(root, from_=30, to=0)
v_scale.pack()
v_scale.place(rely=speaker_y - .12, relx=.935)
tpid_off = Entry(root, bd=2, width=3)
tpid_off.pack()
tpid_off.place(rely=.92, relx=.82)
tpid_off_ttp = CreateToolTip(tpid_off, "Enter ECU ID to disable tester present message. ex: 7DF")
# bass_in = Entry(root, bd=2, width=2)
# bass_in.pack()
# bass_in.place(rely=.21, relx=.285)
# bass_in_ttp = CreateToolTip(bass_in, "Enter bass -7 to 7. Defaults to 7(max)")
bass_scale = Scale(root, from_=7, to=-7, showvalue=7, width=10, length=50, sliderlength=20)
bass_scale.pack()
bass_scale.place(rely=.17, relx=.275)
#bass_scale.set(7)
# treb_in = Entry(root, bd=2, width=2)
# treb_in.pack()
# treb_in.place(rely=.21, relx=.427)
# treb_in_ttp = CreateToolTip(treb_in, "Enter treble -7 to 7. Defaults to 0(nom)")
treb_scale = Scale(root, from_=7, to=-7, showvalue=7, width=10, length=50, sliderlength=20)
treb_scale.pack()
treb_scale.place(rely=.17, relx=.427)
#treb_scale.set(0)
# create a top level menu
menubar = Menu(root)
menubar.add_command(label="Quit!", command=on_closing)
# add CAN setup selection to menu bar
sp_500_HS = tk.BooleanVar()
sp_500_HS.set(False)
sp_125_HS = tk.BooleanVar()
sp_125_HS.set(False)
sp_500_MS = tk.BooleanVar()
sp_500_MS.set(False)
sp_125_MS = tk.BooleanVar()
sp_125_MS.set(False)
cansp_menu = tk.Menu(menubar, background='white')
cansp_menu.add_checkbutton(label="500K on HS", onvalue=True, offvalue=False, variable=sp_500_HS, command=CAN_setup0)
cansp_menu.add_checkbutton(label="125K on HS", onvalue=True, offvalue=False, variable=sp_125_HS, command=CAN_setup1)
cansp_menu.add_checkbutton(label="500K on MS", onvalue=True, offvalue=False, variable=sp_500_MS, command=CAN_setup2)
cansp_menu.add_checkbutton(label="125K on MS", onvalue=True, offvalue=False, variable=sp_125_MS, command=CAN_setup3)
menubar.add_cascade(label='CAN Setup', menu=cansp_menu)
# add AMP setup selection to menu bar
# ECU Diagnostic Reception ID 0x0783 CAN ID for physically addressed diagnostic requests.This parameter is only relevant, if a 11 bit identifier (=> normal addressing) is used.
# ECU Diagnostic Transmission ID 0x078B CAN ID for physically addressed diagnostic responses.This parameter is only relevant, if a 11 bit identifier (=> normal addressing) is used.
Amp_THX_Present = tk.BooleanVar()
Amp_THX_Present.set(False)
Amp_SONY_Present = tk.BooleanVar()
Amp_SONY_Present.set(False)
Amp_HARMAN_Present = tk.BooleanVar()
Amp_HARMAN_Present.set(False)
Amp_menu = tk.Menu(menubar, background='white')
Amp_menu.add_checkbutton(label="THX AMP", onvalue=True, offvalue=False, variable=Amp_THX_Present, command=Amp_THX_Change)
Amp_menu.add_checkbutton(label="SONY AMP", onvalue=True, offvalue=False, variable=Amp_SONY_Present, command=Amp_SONY_Change)
Amp_menu.add_checkbutton(label="HARMAN AMP", onvalue=True, offvalue=False, variable=Amp_HARMAN_Present, command=Amp_HARMAN_Change)
menubar.add_cascade(label='AMP', menu=Amp_menu)
# add AHU selection to menu bar
AHU_Pana = tk.BooleanVar()
AHU_Clar = tk.BooleanVar()
AHU_Vist = tk.BooleanVar()
AHU_VistGap = tk.BooleanVar()
AHU_PanaGap = tk.BooleanVar()
AHU_Pana.set(True)
AHU_Clar.set(False)
AHU_Vist.set(False)
AHU_VistGap.set(False)
AHU_PanaGap.set(False)
AHU_menu = tk.Menu(menubar, background='white')
AHU_menu.add_checkbutton(label="Panasonic", onvalue=True, offvalue=False, variable=AHU_Pana, command=AHU_changeP)
AHU_menu.add_checkbutton(label="Clarion", onvalue=True, offvalue=False, variable=AHU_Clar, command=AHU_changeC)
AHU_menu.add_checkbutton(label="Visteon", onvalue=True, offvalue=False, variable=AHU_Vist, command=AHU_changeV)
AHU_menu.add_checkbutton(label="Visteon-GAP", onvalue=True, offvalue=False, variable=AHU_VistGap, command=AHU_changeVGap)
AHU_menu.add_checkbutton(label="Pana-1DIN", onvalue=True, offvalue=False, variable=AHU_PanaGap, command=AHU_changePGap)
menubar.add_cascade(label='AHU', menu=AHU_menu)
# add Speaker Setup selection to menu bar
Speaker1 = tk.BooleanVar()
Speaker2 = tk.BooleanVar()
Speaker3 = tk.BooleanVar()
Speaker1.set(True)
Speaker2.set(False)
Speaker3.set(False)
speaker_menu = tk.Menu(menubar,background='white')
speaker_menu.add_checkbutton(label="No Tweeters", onvalue=True, offvalue=False, variable=Speaker1, command=Sp1_change)
speaker_menu.add_checkbutton(label="With Tweeters", onvalue=True, offvalue=False, variable=Speaker2, command=Sp2_change)
speaker_menu.add_checkbutton(label="Config 3", onvalue=True, offvalue=False, variable=Speaker3, command=Sp3_change)
menubar.add_cascade(label='Speakers', menu=speaker_menu)
info_l2 = Label(root, text="Connection Status = NOT CONNECTED", font="12")
info_l2.pack(side=TOP)
info_l2.place(relx=0, rely=.05)
# Check Connection Status in periodic update loop
def task():
global e_popup, servercmd
ConfigFile.User_AMP_Selection = Amp_THX_Present.get()
# print("AMP present = " + str(User_AMP_Selection))
print("User Connect = " + str(User_Connect))
# print("OOBD Connect = " + str(OOBDControl.ConnectTest))
if not User_Connect:
info_l2.configure(text="Connection Status = NOT CONNECTED", fg='red')
else:
info_l2.configure(text="Connection Status = CONNECTED!", fg='green')
if command_error:
root.configure(background='red')
if not e_popup:
tkinter.messagebox.showinfo("CAN Error", "No response, Late response or Negative response (7F) from last message request!")
e_popup = True # show only 1 popup - no need to over do it!
else:
root.configure(background=ocolor)
e_popup = False
# check the servercmd status if showing connected - someone may have closed it then nothing will work!!
if User_Connect:
server_status = servercmd.poll()
print ("Server status = " + str(server_status) + "(None = running)")
if server_status is not None:
# server was terminated and needs to restart
print("Server was terminated unexpectedly!! Forcing disconnect...")
tkinter.messagebox.showinfo("Error", "Server process was terminated unexpectedly!! Forcing disconnect...")
disconnect()
root.after(4000, task) # reschedule event every 4 seconds after first call
# start the periodic check loop for first time - need this here!!
root.after(1000, task)
# add Configuration
Config_menu = tk.Menu(menubar, background='white')
for i in range(len(ConfigFile.config_list2)):
# submenu.add_command(label=ConfigFile.config_list[i], command=lambda : ConfigSelect(selection=i))
Config_menu.add_command(label=ConfigFile.config_list2[i]["displayname"], command=lambda s=i: ConfigSelect(selection=s))
menubar.add_cascade(label='Configuration', menu=Config_menu)
# add about item to menu bar
Help_menu = tk.Menu(menubar, background='white')
Help_menu.add_command(label="About", command=about)
Help_menu.add_command(label="Instructions", command=show_instructions)
# Help_menu.add_separator()
#submenu = Menu(Help_menu)
# automatically scroll thru the list and add to the menu the displayname
#for i in range(len(ConfigFile.config_list2)):
# submenu.add_command(label=ConfigFile.config_list[i], command=lambda : ConfigSelect(selection=i))
# submenu.add_command(label=ConfigFile.config_list2[i]["displayname"], command=lambda s=i: ConfigSelect(selection=s))
#Help_menu.add_cascade(label='Configuration', menu=submenu, underline=0)
menubar.add_cascade(label='Help', menu=Help_menu)
# display the menu
root.config(menu=menubar)
# Calls the app class above
app = App(root)
# hide engineering mode things
Hide(True)
# Load the configuration file if present - needs to be done after to App(root) and Hide(True) to allow hiding/showing for the buttons
LoadConfig(ConfigFile.config_file_default)
config_file = ConfigFile.config_file_default
# add handler for the exit
root.protocol("WM_DELETE_WINDOW", on_closing)
# set up listening socket
HOST = 'localhost' # Symbolic name same as the tcp_server name
PORT = 50001 # equal to tcpserver port + 1 - needs to be unique to avoid confusion
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
# Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
#sys.exit()
print ('Socket bind complete')
# Start listening on socket
s.listen(5) # set backlog
s.settimeout(2)
print('Socket now listening')
# start new thread for incoming server
#threading.Thread(target=listenloop, args=(s,)).start()
listen_thread = threading.Thread(target=listenloop, args=(s,))
listen_thread.daemon = True
listen_thread.start()
root.mainloop()
| UTF-8 | Python | false | false | 98,249 | py | 31 | bg.py | 6 | 0.626276 | 0.606988 | 0 | 2,395 | 40.022547 | 332 |
twcannon/MSDataSci | 16,844,861,757,753 | 7d7bb2f0bff956a4cd9ba2cc8040f5419fdb53d9 | d11fefd843ba5f3909871c8ec64e36b4bd2f37c3 | /DATA505/projects/P1_cannon.py | 2d0bc5a049dd49c78c8120b0cae4a61c843599ce | [] | no_license | https://github.com/twcannon/MSDataSci | d7065ff16537c23c2a29a95e2f79565cd15df4b0 | 443ef45cf6594f61ae35ad16c62b040c9386e2c2 | refs/heads/master | 2023-07-19T02:14:09.665138 | 2020-05-22T14:10:48 | 2020-05-22T14:10:48 | 195,902,104 | 0 | 0 | null | false | 2023-07-06T21:42:00 | 2019-07-09T00:06:58 | 2020-05-22T14:11:08 | 2023-07-06T21:41:59 | 163,298 | 0 | 0 | 6 | Python | false | false | import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
debug = False
sample_data = np.genfromtxt('501/data/project_one/TABLE2.csv', delimiter = ',')
print('Sample Data: \n'+sample_data) if debug else next
doc_labels = ['cl','c2','c3','c4','c5','m1','m2','m3','m4']
terms = ['human','interface','computer','user','system','response','time','EPS','survey','trees','graph','minors']
T,S,D = np.linalg.svd(sample_data, full_matrices = False)
print('Calculated T Data: \n'+T) if debug else next
print('Calculated S Data: \n'+S) if debug else next
print('Calculated D Data: \n'+D) if debug else next
Si = 1/S
Si = Si*np.identity(9)
print('S Inverse: \n'+Si) if debug else next
Dt = np.transpose(D)
print('Transposed D: \n'+Dt) if debug else next
def plot_labels(data,labels,offset):
for i in range(len(labels)):
plt.text(data[i,0]+offset, data[i,1]-offset, labels[i], fontsize=8)
plt.scatter(T[:,0], T[:,1], color='red', marker='.', label='Terms')
plt.scatter(Dt[:,0], Dt[:,1], color='blue', marker='s', label='Documents')
plot_labels(T,terms,0.015)
plot_labels(Dt,doc_labels,0.015)
plt.title('2-D plot of Terms and Documents with Queries')
plt.xlabel('Dimension-1')
plt.ylabel('Dimension-2')
plt.legend()
plt.show()
q_labels = ['q1','q2','q3','q4','q5']
X = [[0,0,0,1,0],
[1,0,1,0,0],
[1,1,0,0,0],
[1,1,1,0,1],
[0,0,1,2,0],
[0,1,0,1,1],
[0,1,0,0,0],
[0,0,1,1,0],
[0,1,1,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
Q = np.matmul(np.matmul(np.transpose(X),T),Si)
print('Calculated Query Data: \n'+Q) if debug else next
plt.scatter(T[:,0], T[:,1], color='red', marker='.', label='Terms')
plt.scatter(Dt[:,0], Dt[:,1], color='blue', marker='s', label='Documents')
plt.scatter(Q[:,0], Q[:,1], color='green', marker='x', label='Queries')
plot_labels(T,terms,0.015)
plot_labels(Dt,doc_labels,0.015)
plot_labels(Q,q_labels,0.015)
plt.title('2-D plot of Terms and Documents with Queries')
plt.xlabel('Dimension-1')
plt.ylabel('Dimension-2')
plt.legend()
plt.show()
T_dist_list = []
T_dist_index = []
Dt_dist_list = []
Dt_dist_index = []
for i in range(len(Q)):
T_dist_list.append([np.inf,np.inf,np.inf])
T_dist_index.append([np.inf,np.inf,np.inf])
Dt_dist_list.append([np.inf,np.inf,np.inf])
Dt_dist_index.append([np.inf,np.inf,np.inf])
q=Q[i,0:2]
for j in range(len(T)):
t=T[j,0:2]
list_max = np.amax(T_dist_list[i])
min_index = np.where(T_dist_list[i] == np.amax(list_max))[0][0]
d = spatial.distance.cosine(q, t)
if d < list_max:
T_dist_list[i][min_index] = d
T_dist_index[i][min_index] = j
print(T_dist_list) if debug else next
print(T_dist_index) if debug else next
for k in range(len(Dt)):
dt=Dt[k,0:2]
list_max = np.amax(Dt_dist_list[i])
min_index = np.where(Dt_dist_list[i] == np.amax(list_max))[0][0]
d = spatial.distance.cosine(q, t)
if d < list_max:
Dt_dist_list[i][min_index] = d
Dt_dist_index[i][min_index] = k
print(Dt_dist_list) if debug else next
print(Dt_dist_index) if debug else next
for i in range(len(Q)):
print('\nThe three closest Terms by cosine distance to Query {} are:'.format(q_labels[i]))
for j in range(len(T_dist_list[i])):
print(' Term: {}, by a distance of: {}'.format(terms[T_dist_index[i][j]],T_dist_list[i][j]))
for i in range(len(Q)):
print('\nThe three closest Documents by cosine distance to Query {} are:'.format(q_labels[i]))
for j in range(len(T_dist_list[i])):
print(' Document: {}, by a distance of: {}'.format(doc_labels[T_dist_index[i][j]],T_dist_list[i][j]))
| UTF-8 | Python | false | false | 3,776 | py | 119 | P1_cannon.py | 56 | 0.594809 | 0.560911 | 0 | 155 | 23.329032 | 114 |
ai-how/inputpipeline | 16,621,523,476,876 | 88aefd88adf40c1e5fbcb1167b8e783fd0437f6f | 6cae1cf0fe184febfd6cea2ced593108bc65c30a | /input.py | 3cd930e1086223d3851e194385cbeb2adb9fb123 | [] | no_license | https://github.com/ai-how/inputpipeline | 348e75610a3a28b7e4799f122b67243b95c4617e | c2c7cce16b9d5c1dfb27265184ab706b9b1ec584 | refs/heads/master | 2021-05-10T21:18:59.341871 | 2018-01-20T09:44:48 | 2018-01-20T09:44:48 | 118,225,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import tensorflow as tf
import threading
##================================================##
## good practice to limit data processing to CPU ##
##================================================##
def return_batch(train, list_of_columns):
with tf.device("/cpu:0"):
train = train.sample(frac=1).reset_index(drop=True) # ensure the train data is shuffled at each epoch
X_train = train[[list_of_columns]] # list_of_columns indicating the set of features to be used for training
Y_train = train['labels'] # labels corresponds to target variable
return X_train, Y_train
queue_capacity = 2000 # indicates how much a queue can hold at any time
queue = tf.RandomShuffleQueue(shapes = [[no_of_features],[]],
dtypes = [tf.float32, tf.int32
capacity=queue_capacity
min_after_dequeue=1000)
##================================================##
## placeholder to hold features and labels data ##
##================================================##
X = tf.placeholder(dtype=tf.float32, shape = [None,no_of_features])
Y = tf.placeholder(dtype=tf.int32, shape = [None,])
##================================================##
## operation to fill and close the queue ##
##================================================##
enqueue_op = queue.enqueue_many([X,Y])
close_op = queue.close()
##================================================##
## operation to fetch mini-batches in training ##
##================================================##
X_batch, Y_batch = queue.dequeue_many(128) # 128 is the size of mini-batch, ususally a hyperparameter
def enqueue(sess, train,list_of_columns):
for i in range(no_epochs): # run the loop for no. of epochs used for model training
X_train, Y_train = return_batch(train, list_of_columns)
start_pos =0
##================================================##
## ensures the queue is filled all the time ##
##================================================##
while start_pos < X_train.shape[0]:
end_pos = start_pos+queue_capacity
feed_X = X_train[start_pos:end_pos]
feed_Y = Y_train[start_pos:end_pos]
sess.run(enqueue_op, feed_dict = {X: feed_X, Y: feed_Y})
start_pos + = queue_capacity
sess.run(close_op)
##================================================##
## operation to start the queue and fetch data ##
##================================================##
with tf.Session as sess:
tf.train.start_queue_runners(sess=sess)
enqueue_thread = threading.Thread(target=enqueue, args=(sess,train,list_of_columns))
enqueue_thread.start()
##================================================##
## fetch minibatches in each iteration ##
##================================================##
for i in range(no_epochs):
for in range(no_of_iter):
batch_X, batch_Y = sess.run([X_batch, Y_batch])
# batch_X and batch_y shapes are (128,no_of_features), (1,128)
# use these mini-batches to train your AI models
| UTF-8 | Python | false | false | 3,141 | py | 2 | input.py | 1 | 0.484559 | 0.474053 | 0 | 68 | 45.191176 | 111 |
mohnish-gobo/ifog_light_hue | 1,554,778,176,644 | 5fff5c58814f2d301871addd5f98f419a4dfeccf | 6e2344a342577b51faefcc30f762be675d4209ab | /app.py | 70b67450392c888d1f6e8baabb67c4d44e12c799 | [
"Apache-2.0"
] | permissive | https://github.com/mohnish-gobo/ifog_light_hue | 99bb82955b136117a0ad2a3b0ec99df37912e2e1 | 03a21fe05193b958c0a68b8d5e72c14a9a6abd15 | refs/heads/master | 2020-06-20T10:21:25.512204 | 2016-11-28T18:32:51 | 2016-11-28T18:32:51 | 74,871,122 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
import urllib
import json
import os
import requests
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
#print("Request:")
#print(json.dumps(req, indent=4))
res = makeWebhookResult(req)
res = json.dumps(res, indent=4)
print(res)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def makeWebhookResult(req):
#if req.get("result").get("action") != "light":
#return {}
result = req.get("result")
parameters = result.get("parameters")
state = parameters.get("light1")
brightness = parameters.get("number")
if state == "":
state = 'on'
if brightness == "":
brightness = 250
elif int(brightness) > 250:
brightness = 250
else:
brightness = int(brightness)
#print(json.dumps(item, indent=4))
url = "http://ac9baf93.ngrok.io/api/PwZ5n9cSlbRssx0bMipb69lNIj4Sn7m8vTLwS2bR/lights/6/state"
body = {"on": True,"bri": brightness}
print("State:")
print(state)
print("URL:")
print(url)
print("BODY:")
print(body)
if state == 'on':
body = {"on": True,"bri": brightness}
else:
body = {"on": False, "bri": 0 }
response = requests.put(url, data=json.dumps(body))
if response.status_code == 200:
if state == 'on':
speech = "The light is now switched " + state + " with brightness of " + str(brightness)
if state == 'off':
speech = "The light is now switched " + state
else:
speech = "The light was not switched " + state + " due to an error. Please try again."
print("Response:")
print(speech)
return {
"speech": speech,
"displayText": speech,
# "data": data,
# "contextOut": [],
"source": "ifog_light_hue"
}
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print('Starting app on port %d' % port)
app.run(debug=True, port=port, host='0.0.0.0')
| UTF-8 | Python | false | false | 2,248 | py | 2 | app.py | 1 | 0.578292 | 0.561388 | 0 | 100 | 21.48 | 100 |
snaiperx8/pizza | 4,217,657,892,271 | 7e3e6e6caafd376f2949cf50338d17de94799dd8 | 437f47b9420c9dbdcb519e8f2187a0ba2c8bf52f | /pizza/urls.py | fc84cbba56f50e647bc0ad84b4296bae968ba9c0 | [] | no_license | https://github.com/snaiperx8/pizza | e38d4b2f8c117ade62d70591db2394b4393ac723 | cc84b724126b202962f3e72d4ad802dcd015018c | refs/heads/master | 2020-03-31T18:43:23.841093 | 2018-10-18T06:30:34 | 2018-10-18T06:30:34 | 152,470,036 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from authenticate_app.views import login_view, logout_view, signup_view, home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name = 'home-url'),
path('accounts/login/', login_view, name = 'login-url'),
path('accounts/logout/', logout_view, name = 'logout-url'),
path('accounts/signup/', signup_view, name = 'signup-url'),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| UTF-8 | Python | false | false | 571 | py | 10 | urls.py | 7 | 0.704028 | 0.704028 | 0 | 16 | 34.6875 | 77 |
chenxuhl/Nestnet | 8,349,416,426,807 | 14d43eca9c8436281455149947c43a56e8973027 | aa1621bae671a34b5ec4ad3ece918301bd9ba276 | /main.py | 31d408936d0532ad515d38b02f37befbf8c4f323 | [] | no_license | https://github.com/chenxuhl/Nestnet | 982abc0c56e702d22870641f8c318459492462e3 | 848a834cca3556cafb5578123fdb1017be7d4467 | refs/heads/master | 2020-09-01T11:23:36.610791 | 2020-07-25T14:07:41 | 2020-07-25T14:07:41 | 218,949,081 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding:utf-8 -*-
# Author : Ray
# Data : 2019/7/25 2:15 PM
from data import *
from model import *
import warnings
warnings.filterwarnings('ignore')
# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
aug_args = dict(
rotation_range = 0.2,
width_shift_range = 0.05,
height_shift_range = 0.05,
shear_range = 0.05,
zoom_range = 0.05,
horizontal_flip = True,
vertical_flip = True,
fill_mode = 'nearest'
)
#生成训练数据,返回迭代器
train_gene = trainGenerator(batch_size=2,aug_dict=aug_args,train_path='data/train/',
image_folder='train_img',label_folder='train_label',
image_color_mode='rgb',label_color_mode='rgb',
image_save_prefix='image',label_save_prefix='label',
flag_multi_class=True,num_class=4,save_to_dir=None
)
val_gene = valGenerator(batch_size=2,aug_dict=aug_args,val_path='data/train/',
image_folder='val_img',label_folder='val_label',
image_color_mode='rgb',label_color_mode='rgb',
image_save_prefix='image',label_save_prefix='label',
flag_multi_class=True,num_class=4,save_to_dir=None
)
tensorboard = TensorBoard(log_dir='./log')
# model, loss_function = unet(num_class=4)
model, loss_function = nestnet(num_class=4,dropout_rate = 0.5)
model.compile(optimizer=Adam(lr = 8e-4),loss=loss_function,metrics=['accuracy'])
model.summary()
model_checkpoint = ModelCheckpoint('welding_nestnet_v1_4.hdf5',monitor='val_loss',verbose=1,save_best_only=True)
history = model.fit_generator(train_gene,
steps_per_epoch=63,
epochs=10,
verbose=1,
callbacks=[model_checkpoint,tensorboard],
validation_data=val_gene,
validation_steps=1 #validation/batchsize
)
| UTF-8 | Python | false | false | 2,059 | py | 5 | main.py | 4 | 0.557248 | 0.534644 | 0 | 61 | 32.327869 | 112 |
CesarAcjotaMerma/Ecommerce_Django | 12,309,376,312,897 | 316f9f3373c6fc275801353d9cb1b4ef818c38fd | 389ea3bca435e9599d078e532ec5a18cf3a84f7a | /myvenv/Scripts/django-admin.py | 66101ab997c60d6779d3c0fe618c96c03f89d48a | [] | no_license | https://github.com/CesarAcjotaMerma/Ecommerce_Django | 7d086925d4a7d75fd3fb4d3c9f22bdf21c1f5c30 | 2b7df2dc861952bb04d369f5b3e5df83a13aa98c | refs/heads/master | 2023-07-11T18:06:54.514752 | 2021-08-03T04:28:55 | 2021-08-03T04:28:55 | 392,185,181 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!c:\users\usuario\documents\4to semestre\pasantia\pasantia_proyecto\myvenv\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| UTF-8 | Python | false | false | 201 | py | 7 | django-admin.py | 4 | 0.751244 | 0.746269 | 0 | 5 | 39.2 | 94 |
rahasayantan/Work-For-Reference | 2,001,454,774,352 | a78b357ebbe4fcce09c9b793c13cab222a193f6f | 9c094456139fe0fb55621a6a230a37a03024800c | /others/stepwiseResults.py | 5bb7c9b3a91bd8aeb1e1db2afa00d8b23520104a | [
"MIT"
] | permissive | https://github.com/rahasayantan/Work-For-Reference | 3989169935b1f6d246717eab800112d1dccf329d | e052da538df84034ec5a0fe3b19c4287de307286 | refs/heads/master | 2022-01-15T05:48:17.226826 | 2019-07-03T11:31:36 | 2019-07-03T11:31:36 | 155,310,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pandas as pd
import numpy as np
import datetime as dt
import gc
from sklearn.preprocessing import MinMaxScaler
from encoding import cat2MeanShiftEncode
from sklearn.externals import joblib
from stepwiseSelectionRegression import stepwiseOLS
'''
dftrainStat = joblib.load("../input2/trainStat33.pkl")
dftrainStat2 = joblib.load("../input2/trainStat06.pkl")
dftrainStat3 = joblib.load("../input2/trainStat39.pkl")
'''
trainparcel = joblib.load("../input2/trainparcel.pkl")
train1 = joblib.load("../input/trainnum9Impute.pkl")
train2 = joblib.load("../input/trainlblcat.pkl")
#trainparcel = pd.DataFrame(trainparcel)
#trainparcel.columns = ['parcelid']
train = train#pd.concat((trainparcel,train1,train2), axis = 1)
train_y = joblib.load("../input2/y.pkl")
train['train_y'] = train_y
'''
train.set_index('parcelid', inplace = True)
dftrainStat.set_index('parcelid', inplace = True)
dftrainStat2.set_index('parcelid', inplace = True)
dftrainStat3.set_index('parcelid', inplace = True)
train = train.join(dftrainStat)
train = train.join(dftrainStat2, rsuffix='1')
train = train.join(dftrainStat3, rsuffix='2')
'''
stepwiseOLS(train, train_y)
#'taxdelinquencyyear_countenc0', 'poolcnt_countenc0', 'hashottuborspa_countenc0','bedroomcnt_countenc0',
#'regionidzip_meanshftenc0', 'assessmentyear_meanshftenc0', 'buildingclasstypeid_meanshftenc0', 'propertycountylandusecode_meanshftenc0', 'rawcensustractandblock_meanshftenc0', 'taxdelinquencyflag_meanshftenc0', 'propertyzoningdesc_meanshftenc0', 'poolcnt_meanshftenc0'
#'regionidzip_medianenc0', 'assessmentyear_medianenc0', 'buildingclasstypeid_medianenc0','propertycountylandusecode_medianenc0', 'rawcensustractandblock_medianenc0', 'taxdelinquencyflag_medianenc0', 'propertyzoningdesc_medianenc0', 'poolcnt_medianenc0'
#'regionidzip_meanenc0', 'assessmentyear_meanenc0', 'buildingclasstypeid_meanenc0','propertycountylandusecode_meanenc0', 'rawcensustractandblock_meanenc0', 'taxdelinquencyflag_meanenc0', 'propertyzoningdesc_meanenc0', 'poolcnt_meanenc0'
| UTF-8 | Python | false | false | 2,017 | py | 102 | stepwiseResults.py | 47 | 0.790283 | 0.76351 | 0 | 39 | 50.615385 | 269 |
ictsc/prep-pstate | 12,687,333,404,592 | 30a857664fcefce102181a9ce286bdfd059b8b13 | 310509a07e7c30cf60e82d20f06acb35088c70a3 | /ictsc_prep_school/pstate/migrations/0019_auto_20190801_1405.py | 7a62601b2b3a853babdc70e3fb741e54276260f7 | [] | no_license | https://github.com/ictsc/prep-pstate | 69ce346ec5c63f9e86a79c44c700f6365877ee50 | afcd3c53a292b9a20ae2e2c9e480197b0bc11255 | refs/heads/master | 2023-03-09T08:36:09.768824 | 2020-10-14T15:52:50 | 2020-10-14T15:53:06 | 154,928,737 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.0.4 on 2019-08-01 05:05
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('pstate', '0018_auto_20190801_1314'),
]
operations = [
migrations.AddField(
model_name='github',
name='name',
field=models.CharField(default='ictsc-problems', max_length=100),
),
migrations.AlterField(
model_name='problem',
name='end_date',
field=models.DateTimeField(blank=True, default=datetime.datetime(2019, 8, 1, 5, 5, 44, 184187, tzinfo=utc), null=True, verbose_name='問題公開終了日時'),
),
migrations.AlterField(
model_name='problem',
name='start_date',
field=models.DateTimeField(blank=True, default=datetime.datetime(2019, 8, 1, 5, 5, 44, 184147, tzinfo=utc), null=True, verbose_name='問題公開日時'),
),
]
| UTF-8 | Python | false | false | 1,014 | py | 138 | 0019_auto_20190801_1405.py | 76 | 0.606491 | 0.539554 | 0 | 30 | 31.866667 | 156 |
sdpython/mlstatpy | 8,186,207,704,607 | c5d98b42fb158c841886e1cc75bf29e36bf88aa1 | ac768a35cc145185aa940bbb8255c40ec38a7c6f | /mlstatpy/ml/_neural_tree_node.py | 2d4828028b353ed99c658afdc60292a6fdd9fc88 | [
"MIT"
] | permissive | https://github.com/sdpython/mlstatpy | 3dcb2629773c25bb5256b0568932b6753b3c4068 | 572e0de91bfe02857fc8594ba0ad8ee3ecf9f6e2 | refs/heads/main | 2023-08-17T11:06:14.258773 | 2023-08-05T22:35:27 | 2023-08-05T22:35:27 | 61,439,492 | 10 | 10 | MIT | false | 2023-08-05T22:35:29 | 2016-06-18T15:21:42 | 2023-07-19T20:41:36 | 2023-08-05T22:35:28 | 37,030 | 9 | 8 | 12 | Jupyter Notebook | false | false | # coding: utf-8
import numpy
import numpy.random as rnd
from scipy.special import expit, softmax, kl_div as kl_fct # pylint: disable=E0611
from ._neural_tree_api import _TrainingAPI
class NeuralTreeNode(_TrainingAPI):
"""
One node in a neural network.
:param weights: weights
:param bias: bias, if None, draws a random number
:param activation: activation function
:param nodeid: node id
:param tag: unused but to add information on how this node was created
"""
@staticmethod
def _relu(x):
"Relu function."
return numpy.maximum(x, 0)
@staticmethod
def _leakyrelu(x):
"Leaky Relu function."
return numpy.maximum(x, 0) + numpy.minimum(x, 0) * 0.01
@staticmethod
def _drelu(x):
"Derivative of the Relu function."
res = numpy.ones(x.shape, dtype=x.dtype)
res[x < 0] = 0.0
return res
@staticmethod
def _dleakyrelu(x):
"Derivative of the Leaky Relu function."
res = numpy.ones(x.shape, dtype=x.dtype)
res[x < 0] = 0.01
return res
@staticmethod
def _dsigmoid(x):
"Derivativ of the sigmoid function."
y = expit(x)
return y * (1 - y)
@staticmethod
def _softmax(x):
"Derivative of the softmax function."
if len(x.shape) == 2:
return softmax(x, axis=1)
return softmax(x)
@staticmethod
def _dsoftmax(x):
"Derivative of the softmax function."
soft = softmax(x)
grad = -soft @ soft.T
diag = numpy.diag(soft)
return diag + grad
@staticmethod
def get_activation_function(activation):
"""
Returns the activation function.
It returns a function *y=f(x)*.
"""
if activation == "softmax":
return NeuralTreeNode._softmax
if activation == "softmax4":
return lambda x: NeuralTreeNode._softmax(x * 4)
if activation in {"logistic", "expit", "sigmoid"}:
return expit
if activation == "sigmoid4":
return lambda x: expit(x * 4)
if activation == "relu":
return NeuralTreeNode._relu
if activation == "leakyrelu":
return NeuralTreeNode._leakyrelu
if activation == "identity":
return lambda x: x
raise ValueError( # pragma: no cover
f"Unknown activation function '{activation}'."
)
@staticmethod
def get_activation_gradient_function(activation):
"""
Returns the activation function.
It returns a function *y=f'(x)*.
About the sigmoid:
.. math::
\\begin{array}{rcl}
f(x) &=& \\frac{1}{1 + e^{-x}} \\\\
f'(x) &=& \\frac{e^{-x}}{(1 + e^{-x})^2} = f(x)(1-f(x))
\\end{array}
"""
if activation == "softmax":
return NeuralTreeNode._dsoftmax
if activation == "softmax4":
return lambda x: NeuralTreeNode._dsoftmax(x) * 4
if activation in {"logistic", "expit", "sigmoid"}:
return NeuralTreeNode._dsigmoid
if activation == "sigmoid4":
return lambda x: NeuralTreeNode._dsigmoid(x) * 4
if activation == "relu":
return NeuralTreeNode._drelu
if activation == "leakyrelu":
return NeuralTreeNode._dleakyrelu
if activation == "identity":
return lambda x: numpy.ones(x.shape, dtype=x.dtype)
raise ValueError( # pragma: no cover
f"Unknown activation gradient function '{activation}'."
)
@staticmethod
def get_activation_loss_function(activation):
"""
Returns a default loss function based on the activation
function. It returns two functions *g=loss(x,y)*.
"""
if activation in {"logistic", "expit", "sigmoid", "sigmoid4"}:
# regression + regularization
return lambda x, y: (x - y) ** 2
if activation in {"softmax", "softmax4"}:
cst = numpy.finfo(numpy.float32).eps
# classification
def kl_fct2(x, y):
return kl_fct(x + cst, y + cst)
return kl_fct2
if activation in {"identity", "relu", "leakyrelu"}:
# regression
return lambda x, y: (x - y) ** 2
raise ValueError(f"Unknown activation function '{activation}'.")
@staticmethod
def get_activation_dloss_function(activation):
"""
Returns the derivative of the default loss function based
on the activation function. It returns a function
*df(x,y)/dw, df(w)/dw* where *w* are the weights.
"""
if activation in {"logistic", "expit", "sigmoid", "sigmoid4"}:
# regression + regularization
def dregrdx(x, y):
return (x - y) * 2
return dregrdx
if activation in {"softmax", "softmax4"}:
# classification
cst = numpy.finfo(numpy.float32).eps
def dclsdx(x, y):
return numpy.log(x + cst) - numpy.log(y + cst)
return dclsdx
if activation in {"identity", "relu", "leakyrelu"}:
# regression
def dregdx(x, y):
return (x - y) * 2
return dregdx
raise ValueError( # pragma: no cover
f"Unknown activation function '{activation}'."
)
def __init__(self, weights, bias=None, activation="sigmoid", nodeid=-1, tag=None):
self.tag = tag
if isinstance(weights, int):
if activation.startswith("softmax"):
weights = rnd.randn(2, weights)
else:
weights = rnd.randn(weights)
if isinstance(weights, list):
weights = numpy.array(weights)
if len(weights.shape) == 1:
self.n_outputs = 1
if bias is None:
bias = rnd.randn()
self.coef = numpy.empty(len(weights) + 1)
self.coef[1:] = weights
self.coef[0] = bias
elif len(weights.shape) == 2:
self.n_outputs = weights.shape[0]
if bias is None:
bias = rnd.randn(self.n_outputs)
shape = list(weights.shape)
shape[1] += 1
self.coef = numpy.empty(shape)
self.coef[:, 1:] = weights
self.coef[:, 0] = bias
else:
raise RuntimeError( # pragma: no cover
f"Unexpected weights shape: {weights.shape}"
)
self.activation = activation
self.nodeid = nodeid
self._set_fcts()
def _set_fcts(self):
self.activation_ = NeuralTreeNode.get_activation_function(self.activation)
self.gradient_ = NeuralTreeNode.get_activation_gradient_function(
self.activation
)
self.losss_ = NeuralTreeNode.get_activation_loss_function(self.activation)
self.dlossds_ = NeuralTreeNode.get_activation_dloss_function(self.activation)
@property
def input_weights(self):
"Returns the weights."
if self.n_outputs == 1:
return self.coef[1:]
return self.coef[:, 1:]
@property
def bias(self):
"Returns the weights."
if self.n_outputs == 1:
return self.coef[0]
return self.coef[:, 0]
def __getstate__(self):
"usual"
return {
"coef": self.coef,
"activation": self.activation,
"nodeid": self.nodeid,
"n_outputs": self.n_outputs,
"tag": self.tag,
}
def __setstate__(self, state):
"usual"
self.coef = state["coef"]
self.activation = state["activation"]
self.nodeid = state["nodeid"]
self.n_outputs = state["n_outputs"]
self.tag = state["tag"]
self._set_fcts()
def __eq__(self, obj):
if self.coef.shape != obj.coef.shape:
return False
if any(
map(lambda xy: xy[0] != xy[1], zip(self.coef.ravel(), obj.coef.ravel()))
):
return False
if self.activation != obj.activation:
return False
return True
def __repr__(self):
"usual"
if len(self.coef.shape) == 1:
return "%s(weights=%r, bias=%r, activation=%r)" % (
self.__class__.__name__,
self.coef[1:],
self.coef[0],
self.activation,
)
return "%s(weights=%r, bias=%r, activation=%r)" % (
self.__class__.__name__,
self.coef[:, 1:],
self.coef[:, 0],
self.activation,
)
def _predict(self, X):
"Computes inputs of the activation function."
if self.n_outputs == 1:
return X @ self.coef[1:] + self.coef[0]
if len(X.shape) == 2:
return X @ self.coef[:, 1:].T + self.coef[:, 0]
res = X.reshape((1, -1)) @ self.coef[:, 1:].T + self.coef[:, 0]
return res.ravel()
def predict(self, X):
"Computes neuron outputs."
y = self._predict(X)
return self.activation_(y)
@property
def ndim(self):
"Returns the input dimension."
if len(self.coef.shape) == 1:
return self.coef.shape[0] - 1
return self.coef.shape[1] - 1
@property
def ndim_out(self):
"Returns the output dimension."
if len(self.coef.shape) == 1:
return 1
return self.coef.shape[0]
@property
def training_weights(self):
"Returns the weights stored in the neuron."
return self.coef.ravel()
def update_training_weights(self, X, add=True): # pylint: disable=W0237
"""
Updates weights.
:param X: training datasets
:param add: addition or replace
"""
if add:
self.coef += X.reshape(self.coef.shape)
else:
numpy.copyto(self.coef, X.reshape(self.coef.shape))
def fill_cache(self, X):
"""
Creates a cache with intermediate results.
``lX`` is the results before the activation function,
``aX`` is the results after the activation function, the prediction.
"""
cache = dict(lX=self._predict(X))
cache["aX"] = self.activation_(cache["lX"])
return cache
def _common_loss_dloss(self, X, y, cache=None):
"""
Common beginning to methods *loss*, *dlossds*,
*dlossdw*.
"""
if cache is not None and "aX" in cache:
act = cache["aX"]
else:
act = self.predict(X)
return act
def loss(self, X, y, cache=None):
"""
Computes the loss. Returns a float.
"""
act = self._common_loss_dloss(X, y, cache=cache)
if len(X.shape) == 1:
return self.losss_(act, y) # pylint: disable=E1120
return self.losss_(act, y) # pylint: disable=E1120
def dlossds(self, X, y, cache=None):
"""
Computes the loss derivative due to prediction error.
"""
act = self._common_loss_dloss(X, y, cache=cache)
return self.dlossds_(act, y)
def gradient_backward(self, graddx, X, inputs=False, cache=None):
"""
Computes the gradients at point *X*.
:param graddx: existing gradient against the inputs
:param X: computes the gradient in X
:param inputs: if False, derivative against the coefficients,
otherwise against the inputs.
:param cache: cache intermediate results
:return: gradient
"""
if cache is None:
cache = self.fill_cache(X)
pred = cache["aX"]
ga = self.gradient_(pred)
if len(ga.shape) == 2:
f = graddx @ ga
else:
f = graddx * ga
if inputs:
if len(self.coef.shape) == 1:
rgrad = numpy.empty(X.shape)
rgrad[:] = self.coef[1:]
rgrad *= f
else:
rgrad = numpy.sum(self.coef[:, 1:] * f.reshape((-1, 1)), axis=0)
return rgrad
rgrad = numpy.empty(self.coef.shape)
if len(self.coef.shape) == 1:
rgrad[0] = 1
rgrad[1:] = X
rgrad *= f
else:
rgrad[:, 0] = 1
rgrad[:, 1:] = X
rgrad *= f.reshape((-1, 1))
return rgrad
| UTF-8 | Python | false | false | 12,509 | py | 213 | _neural_tree_node.py | 62 | 0.530658 | 0.520985 | 0 | 401 | 30.194514 | 86 |
Street-King/python_primer | 6,227,702,582,196 | b4e1a33a26129103a70a79e2f7da181a010e2b55 | 24557755f44c18b36f10f81b6341cf1edfc2ede8 | /ch_3/L3_flexible.py | 22b5f262abeadb44dcd463596d18336873d8d88f | [
"MIT"
] | permissive | https://github.com/Street-King/python_primer | 5e81472bed340812a38619a50d555bb545c29ef1 | 211e37c1f2fd169269fc4f3c08e8b7e5225f2ad0 | refs/heads/master | 2020-03-30T15:49:30.349229 | 2017-01-03T12:42:23 | 2017-01-03T12:42:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Exercise 3.31
# Author: Noah Waterfield Price
def L3(x, n=None, epsilon=None, return_n=False):
if (n is None and epsilon is None) or \
(n is not None and epsilon is not None):
print 'Error: Either n or epsilon must be given (not both)'
term = x / (1. + x)
s = term
if n is not None:
for i in range(2, n + 1):
# recursive relation between ci and c(i-1)
term *= (i - 1.) / i * x / (1. + x)
s += term
return (s, n) if return_n is True else s
elif epsilon is not None:
i = 1
while abs(term) > epsilon:
i += 1
# recursive relation between ci and c(i-1)
term *= (i - 1.) / i * x / (1. + x)
s += term
return (s, i) if return_n is True else s
print L3(10, n=100)
print L3(10, n=1000, return_n=True)
print L3(10, epsilon=1e-10)
print L3(10, epsilon=1e-10, return_n=True)
"""
Sample run:
python L3_flexible.py
2.39788868474
(2.397895272798365, 1000)
2.39789527188
(2.397895271877886, 187
"""
| UTF-8 | Python | false | false | 1,051 | py | 95 | L3_flexible.py | 84 | 0.551855 | 0.452902 | 0 | 37 | 27.405405 | 67 |
logithr/djangocms-widgetbox | 7,430,293,457,167 | d1d6d4e222522348147e1e89c8dfa827cdded6f6 | 988c07ae1de971b877a5250ac7dc821c0e96a972 | /widgetbox/migrations/0005_rename_model_button.py | f9a93dcb16d388fee59b9ec27d675529c6673f80 | [
"MIT"
] | permissive | https://github.com/logithr/djangocms-widgetbox | 31c7a52bf6628dffde7868dfc2d7f0da3937f079 | dbafb9b70f7795de5eb94447b7703cba3bd73f84 | refs/heads/master | 2020-12-24T14:10:44.469017 | 2016-03-08T09:53:57 | 2016-03-08T09:53:57 | 35,680,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('widgetbox', '0003_auto_20150522_0959'),
]
operations = [
migrations.RenameModel('ButtonPlugin', 'Button'),
migrations.RenameModel('QuotePlugin', 'Quote'),
migrations.RenameModel('GalleryPlugin', 'Gallery'),
migrations.RenameModel('GalleryImagePlugin', 'GalleryImage'),
]
| UTF-8 | Python | false | false | 495 | py | 35 | 0005_rename_model_button.py | 21 | 0.660606 | 0.626263 | 0 | 18 | 26.5 | 69 |
n8felton/AoC2020 | 10,411,000,768,425 | 868f54f35221d4789f65a07ff1f013108aa6dc01 | 5a1a876c76edbc5189793285f2c6e6fd970091d0 | /day04/0401.py | 9e01b1eae324770369697045768c4546ad430514 | [] | no_license | https://github.com/n8felton/AoC2020 | d0a5ca1c9c03a78149dbf0806b1ba5eb2812d4f5 | 1c46df2b4099ea2786e5626cf986dea026e6025f | refs/heads/main | 2023-01-28T15:27:43.498117 | 2020-12-05T05:39:58 | 2020-12-05T05:39:58 | 318,567,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
required_fields = sorted(["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"])
temp_required_fields = sorted(["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"])
passports = []
valid_passports = []
with open("input_0401") as input:
passport = []
for line in input:
if not line.strip():
passports.append(passport)
passport = []
else:
_line = line.replace("\n", " ").split()
passport.extend(_line)
else:
passports.append(passport)
for passport in passports:
fields = []
for field in passport:
fields.append(field.split(":")[0])
fields.sort()
if fields == temp_required_fields or fields == required_fields:
valid_passports.append(passport)
print(len(valid_passports)) | UTF-8 | Python | false | false | 811 | py | 4 | 0401.py | 4 | 0.574599 | 0.567201 | 0 | 30 | 26.066667 | 82 |
lwoloszy/personal_website | 6,150,393,195,128 | f3fc5905fe6ff72d8c94a417fa3332ebe7a1e181 | 23664e1ab68292a2604b549f60feb7bf5c4d5ae6 | /pelicanconf.py | 18e8f4c1d147e0c2ecdcf3b2fd3b90011a94a3ed | [] | no_license | https://github.com/lwoloszy/personal_website | 9e88dfd08a736df16417ef2a7fddbbec0f1ecc53 | 6021ab888d583418943689250f4cc38f6cfb764b | refs/heads/master | 2020-12-24T05:12:47.176650 | 2016-10-22T00:10:27 | 2016-10-24T16:51:41 | 61,959,055 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Luke Woloszyn'
SITEURL = u'http://lukewoloszyn.com'
SITENAME = u'Luke Woloszyn'
SITESUBTITLE = u'data scientist, outdoor enthusiast, music lover, sports fan'
ARTICLE_URL = '{date:%Y}/{date:%m}/{date:%d}/{slug}.html'
ARTICLE_SAVE_AS = '{date:%Y}/{date:%m}/{date:%d}/{slug}.html'
RELATIVE_URLS = True
TYPOGRIFY = True
THEME = '../crowsfoot'
# PATH = 'content'
ARTICLE_PATHS = ['blog']
# MENUITEMS = [('blog', '/'), ('cv', '/misc/cv.pdf')]
MENUITEMS = [('Blog', '/'), ]
PROFILE_IMAGE_URL = '/images/personal.jpg'
STATIC_PATHS = ['images', 'extra/robots.txt', 'extra/favicon.ico', 'misc']
EXTRA_PATH_METADATA = {
'extra/robots.txt': {'path': 'robots.txt'},
'extra/favicon.ico': {'path': 'favicon.ico'},
}
PLUGIN_PATHS = ['../pelican-plugins']
PLUGINS = ['render_math']
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = u'en'
DEFAULT_PAGINATION = None
# addresses
EMAIL_ADDRESS = 'luke.woloszyn@gmail.com'
GITHUB_ADDRESS = 'https://github.com/lwoloszy'
LINKEDIN_ADDRESS = 'https://www.linkedin.com/in/lukewoloszyn'
TWITTER_ADDRESS = 'https://www.twitter.com/lukewoloszyn'
# feed
FEED_RSS = 'feeds/rss.xml'
FEED_MAX_ITEMS = 10
SHOW_ARTICLE_AUTHOR = False
LICENSE_NAME = "CC BY-SA"
LICENSE_URL = "https://creativecommons.org/licenses/by-sa/3.0/"
LOAD_CONTENT_CACHE = False
| UTF-8 | Python | false | false | 1,388 | py | 6 | pelicanconf.py | 1 | 0.669308 | 0.665706 | 0 | 56 | 23.785714 | 77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.