blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
70f76bc9b439c416383973f9088f2be3a89488ca | cb9b861f5f3c0a36acfa2d0e1664216587b91f07 | /svr_surrogate.py | df181b6f63917221a1b40cfcb1ae7a7835fb5914 | [] | no_license | rubinxin/SoTL | feae052dba5506b3750126b9f7180a02a01bd998 | 16e24371972aab2a5fa36f8febbe83ae4dacf352 | refs/heads/master | 2023-01-20T14:35:37.027939 | 2020-11-30T16:51:29 | 2020-11-30T16:51:29 | 307,888,874 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,080 | py | # Our implementation of SVR-based learning curve extrapolation surrogate
# based on the description in B. Baker, O. Gupta, R. Raskar, and N. Naik,
# “Accelerating neural architecture search using performance prediction,” arXiv preprint arXiv:1705.10823, 2017.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import BayesianRidge
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.svm import NuSVR
import time
from scipy import stats
def loguniform(low=0, high=1, size=None):
return np.exp(np.random.uniform(np.log(low), np.log(high), size))
class LcSVR(object):
def __init__(self, VC_all_archs_list, HP_all_archs_list, AP_all_archs_list, test_acc_all_archs_list,
n_hypers=1000, n_train=200, seed=0, all_curve=True, model_name='svr'):
self.n_hypers = n_hypers
self.all_curve = all_curve
self.n_train = n_train
self.seed = seed
self.model_name = model_name
self.VC = np.vstack(VC_all_archs_list)
self.HP = np.vstack(HP_all_archs_list)
self.AP = np.vstack(AP_all_archs_list)
self.DVC = np.diff(self.VC, n=1, axis=1)
self.DDVC = np.diff(self.DVC, n=1, axis=1)
self.max_epoch = self.VC.shape[1]
self.test_acc_seed_all_arch = test_acc_all_archs_list
def learn_hyper(self, epoch):
n_epoch = int(epoch)
VC_sub = self.VC[:, :n_epoch]
DVC_sub = self.DVC[:, :n_epoch]
DDVC_sub = self.DDVC[:, :n_epoch]
mVC_sub = np.mean(VC_sub, axis=1)[:, None]
stdVC_sub = np.std(VC_sub, axis=1)[:, None]
mDVC_sub = np.mean(DVC_sub, axis=1)[:, None]
stdDVC_sub = np.std(DVC_sub, axis=1)[:, None]
mDDVC_sub = np.mean(DDVC_sub, axis=1)[:, None]
stdDDVC_sub = np.std(DDVC_sub, axis=1)[:, None]
if self.all_curve:
TS = np.hstack([VC_sub, DVC_sub, DDVC_sub, mVC_sub, stdVC_sub])
else:
TS = np.hstack([mVC_sub, stdVC_sub, mDVC_sub, stdDVC_sub, mDDVC_sub, stdDDVC_sub])
X = np.hstack([self.AP, self.HP, TS])
y_val_acc = self.VC[:, -1]
y_test_acc = np.array(self.test_acc_seed_all_arch)
y = np.vstack([y_val_acc, y_test_acc]).T
# split into train/test data sets
split = (X.shape[0] - self.n_train) / X.shape[0]
X_train, X_test, y_both_train, y_both_test = train_test_split(
X, y, test_size=split, random_state=self.seed)
y_train = y_both_train[:, 0] # all final validation acc
y_test = y_both_test[:, 1] # all final test acc
np.random.seed(self.seed)
# specify model parameters
if self.model_name == 'svr':
C = loguniform(1e-5, 10, self.n_hypers)
nu = np.random.uniform(0, 1, self.n_hypers)
gamma = loguniform(1e-5, 10, self.n_hypers)
hyper = np.vstack([C, nu, gamma]).T
else:
print('Not implemented')
print(f'start CV on {self.model_name}')
mean_score_list = []
t_start = time.time()
for i in range(self.n_hypers):
# define model
if self.model_name == 'svr':
model = NuSVR(C=hyper[i, 0], nu=hyper[i, 1], gamma=hyper[i, 2], kernel='rbf')
# model = SVR(C=hyper[i, 0], nu=hyper[i, 1], gamma= ,kernel='linear')
elif self.model_name == 'blr':
model = BayesianRidge(alpha_1=hyper[i, 0], alpha_2=hyper[i, 1],
lambda_1=hyper[i, 2], lambda_2=hyper[i, 3])
elif self.model_name == 'rf':
model = RandomForestRegressor(n_estimators=int(hyper[i, 0]), max_features=hyper[i, 1])
# perform cross validation to learn the best hyper value
scores = cross_val_score(model, X_train, y_train, cv=3)
mean_scores = np.mean(scores)
mean_score_list.append(mean_scores)
t_end = time.time()
best_hyper_idx = np.argmax(mean_score_list)
best_hyper = hyper[best_hyper_idx]
max_score = np.max(mean_score_list)
time_taken = t_end - t_start
print(f'{self.model_name} on {self.seed} n_train={self.n_train}: '
f'best_hyper={best_hyper}, score={max_score}, time={time_taken}')
self.epoch = epoch
self.best_hyper = best_hyper
self.X_train, self.X_test = X_train, X_test
self.y_train, self.y_test = y_train, y_test
return best_hyper, time_taken
def extrapolate(self):
if self.model_name == 'svr':
best_model = NuSVR(C=self.best_hyper[0], nu=self.best_hyper[1], gamma=self.best_hyper[2], kernel='rbf')
else:
print('Not implemented')
# train and fit model
best_model.fit(self.X_train, self.y_train)
y_pred = best_model.predict(self.X_test)
rank_corr, p = stats.spearmanr(self.y_test, y_pred)
print(f'{self.model_name} on n_train={self.n_train} e={self.epoch}: rank_corr={rank_corr}')
return rank_corr
| [
"[email protected]"
] | |
810b042622acc9d9cedfba2b326adb4433c28b73 | fe4f2aeb889f939ea6caf4a34371a3558064abcd | /vqa/model_vlmap_finetune.py | 5915643c18747587a1c77fb0bddde770a3e5516d | [
"MIT"
] | permissive | HyeonwooNoh/VQA-Transfer-ExternalData | cf9c1b82dd55389dfe5f52d8fd196780dd3d4629 | d21b700bcdc3ba3c392ff793b3f5efe23eb68ed6 | refs/heads/master | 2021-10-25T22:58:00.318492 | 2019-04-08T04:52:46 | 2019-04-08T04:52:46 | 122,662,354 | 21 | 3 | null | null | null | null | UTF-8 | Python | false | false | 9,938 | py | import cPickle
import h5py
import os
import numpy as np
import tensorflow as tf
from util import log
from vlmap import modules
W_DIM = 300 # Word dimension
L_DIM = 1024 # Language dimension
V_DIM = 1024
class Model(object):
def __init__(self, batch, config, is_train=True):
self.batch = batch
self.config = config
self.image_dir = config.image_dir
self.is_train = is_train
self.pretrained_param_path = config.pretrained_param_path
if self.pretrained_param_path is None:
raise ValueError('pretrained_param_path is mendatory')
self.word_weight_dir = config.vlmap_word_weight_dir
if self.word_weight_dir is None:
raise ValueError('word_weight_dir is mendatory')
self.losses = {}
self.report = {}
self.mid_result = {}
self.vis_image = {}
self.vocab = cPickle.load(open(config.vocab_path, 'rb'))
self.answer_dict = cPickle.load(open(
os.path.join(config.tf_record_dir, 'answer_dict.pkl'), 'rb'))
self.num_answer = len(self.answer_dict['vocab'])
self.num_train_answer = self.answer_dict['num_train_answer']
self.train_answer_mask = tf.expand_dims(tf.sequence_mask(
self.num_train_answer, maxlen=self.num_answer, dtype=tf.float32),
axis=0)
self.glove_map = modules.LearnGloVe(self.vocab)
self.v_word_map = modules.WordWeightEmbed(
self.vocab, self.word_weight_dir, 'v_word', scope='V_WordMap')
log.infov('loading image features...')
with h5py.File(config.vfeat_path, 'r') as f:
self.features = np.array(f.get('image_features'))
log.infov('feature done')
self.spatials = np.array(f.get('spatial_features'))
log.infov('spatials done')
self.normal_boxes = np.array(f.get('normal_boxes'))
log.infov('normal_boxes done')
self.num_boxes = np.array(f.get('num_boxes'))
log.infov('num_boxes done')
self.max_box_num = int(f['data_info']['max_box_num'].value)
self.vfeat_dim = int(f['data_info']['vfeat_dim'].value)
log.infov('done')
self.build()
def filter_train_vars(self, trainable_vars):
train_vars = []
for var in trainable_vars:
train_vars.append(var)
return train_vars
def filter_transfer_vars(self, all_vars):
transfer_vars = []
for var in all_vars:
if var.name.split('/')[0] == 'v_word_fc':
transfer_vars.append(var)
elif var.name.split('/')[0] == 'q_linear_v':
transfer_vars.append(var)
elif var.name.split('/')[0] == 'v_linear_v':
transfer_vars.append(var)
elif var.name.split('/')[0] == 'hadamard_attention':
transfer_vars.append(var)
elif var.name.split('/')[0] == 'q_linear_l':
transfer_vars.append(var)
elif var.name.split('/')[0] == 'pooled_linear_l':
transfer_vars.append(var)
elif var.name.split('/')[0] == 'joint_fc':
transfer_vars.append(var)
return transfer_vars
def build(self):
"""
build network architecture and loss
"""
"""
Visual features
"""
with tf.device('/cpu:0'):
def load_feature(image_idx):
selected_features = np.take(self.features, image_idx, axis=0)
return selected_features
V_ft = tf.py_func(
load_feature, inp=[self.batch['image_idx']], Tout=tf.float32,
name='sample_features')
V_ft.set_shape([None, self.max_box_num, self.vfeat_dim])
num_V_ft = tf.gather(self.num_boxes, self.batch['image_idx'],
name='gather_num_V_ft', axis=0)
self.mid_result['num_V_ft'] = num_V_ft
normal_boxes = tf.gather(self.normal_boxes, self.batch['image_idx'],
name='gather_normal_boxes', axis=0)
self.mid_result['normal_boxes'] = normal_boxes
log.warning('v_linear_v')
v_linear_v = modules.fc_layer(
V_ft, V_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='v_linear_v')
"""
Encode question
"""
q_token, q_len = self.batch['q_intseq'], self.batch['q_intseq_len']
q_embed = tf.nn.embedding_lookup(self.glove_map, q_token)
q_L_map, q_L_ft = modules.encode_L_bidirection(
q_embed, q_len, L_DIM, scope='encode_L_bi', cell_type='GRU')
q_att_key = modules.fc_layer( # [bs, len, L_DIM]
q_L_map, L_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='q_att_key')
q_att_query = modules.fc_layer( # [bs, L_DIM]
q_L_ft, L_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='q_att_query')
w_att_score = modules.hadamard_attention(
q_att_key, q_len, q_att_query, use_ln=False, is_train=self.is_train,
scope='word_attention')
q_v_embed = tf.nn.embedding_lookup(self.v_word_map, q_token)
q_v_ft = modules.fc_layer( # [bs, len, L_DIM]
q_v_embed, L_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='v_word_fc')
pooled_q_v = modules.attention_pooling(q_v_ft, w_att_score)
# [bs, V_DIM}
log.warning('q_linear_v')
q_linear_v = modules.fc_layer(
pooled_q_v, V_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='q_linear_v')
"""
Perform attention
"""
att_score = modules.hadamard_attention(v_linear_v, num_V_ft, q_linear_v,
use_ln=False, is_train=self.is_train,
scope='hadamard_attention')
self.mid_result['att_score'] = att_score
pooled_V_ft = modules.attention_pooling(V_ft, att_score)
"""
Answer classification
"""
log.warning('pooled_linear_l')
pooled_linear_l = modules.fc_layer(
pooled_V_ft, L_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='pooled_linear_l')
log.warning('q_linear_l')
l_linear_l = modules.fc_layer(
q_L_ft, L_DIM, use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train,
scope='q_linear_l')
joint = modules.fc_layer(
pooled_linear_l * l_linear_l, L_DIM * 2,
use_bias=True, use_bn=False, use_ln=True,
activation_fn=tf.nn.relu, is_training=self.is_train, scope='joint_fc')
joint = tf.nn.dropout(joint, 0.5)
logit = modules.WordWeightAnswer(
joint, self.answer_dict, self.word_weight_dir,
use_bias=True, is_training=self.is_train, scope='WordWeightAnswer')
"""
Compute loss and accuracy
"""
with tf.name_scope('loss'):
answer_target = self.batch['answer_target']
loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=answer_target, logits=logit)
train_loss = tf.reduce_mean(tf.reduce_sum(
loss * self.train_answer_mask, axis=-1))
report_loss = tf.reduce_mean(tf.reduce_sum(loss, axis=-1))
pred = tf.cast(tf.argmax(logit, axis=-1), dtype=tf.int32)
one_hot_pred = tf.one_hot(pred, depth=self.num_answer,
dtype=tf.float32)
acc = tf.reduce_mean(
tf.reduce_sum(one_hot_pred * answer_target, axis=-1))
self.mid_result['pred'] = pred
self.losses['answer'] = train_loss
self.report['answer_train_loss'] = train_loss
self.report['answer_report_loss'] = report_loss
self.report['answer_accuracy'] = acc
"""
Prepare image summary
"""
"""
with tf.name_scope('prepare_summary'):
self.vis_image['image_attention_qa'] = self.visualize_vqa_result(
self.batch['image_id'],
self.mid_result['normal_boxes'], self.mid_result['num_V_ft'],
self.mid_result['att_score'],
self.batch['q_intseq'], self.batch['q_intseq_len'],
self.batch['answer_target'], self.mid_result['pred'],
max_batch_num=20, line_width=2)
"""
self.loss = self.losses['answer']
# scalar summary
for key, val in self.report.items():
tf.summary.scalar('train/{}'.format(key), val,
collections=['heavy_train', 'train'])
tf.summary.scalar('val/{}'.format(key), val,
collections=['heavy_val', 'val'])
tf.summary.scalar('testval/{}'.format(key), val,
collections=['heavy_testval', 'testval'])
# image summary
for key, val in self.vis_image.items():
tf.summary.image('train-{}'.format(key), val, max_outputs=10,
collections=['heavy_train'])
tf.summary.image('val-{}'.format(key), val, max_outputs=10,
collections=['heavy_val'])
tf.summary.image('testval-{}'.format(key), val, max_outputs=10,
collections=['heavy_testval'])
return self.loss
| [
"[email protected]"
] | |
69fffa27f3895ac0ec76dfa70d08f3e0ab8e62f2 | e76c8b127ae58c5d3b5d22c069719a0343ea8302 | /tf_ex_5_linear_reg_with_eager_api.py | 31dc0013a8602daf6ff29927b818a2c4785c48cd | [] | no_license | janFrancoo/TensorFlow-Tutorials | 18f3479fc647db3cbdb9fb9d5c0b9a67be804642 | b34dbf903d2f5ff7bde6fb279fef6d7e2004a3bf | refs/heads/master | 2020-07-23T02:01:14.940932 | 2019-10-26T08:41:23 | 2019-10-26T08:41:23 | 207,410,175 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,490 | py | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Set Eager API
tf.enable_eager_execution()
tfe = tf.contrib.eager
# Parameters
num_steps = 1000
learning_rate = .01
# Training data
x_train = np.array([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167, 7.042, 10.791, 5.313,
7.997, 5.654, 9.27, 3.1])
y_train = np.array([1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221, 2.827, 3.465, 1.65,
2.904, 2.42, 2.94, 1.3])
# Weights
w = tfe.Variable(np.random.randn())
b = tfe.Variable(np.random.randn())
# Construct a linear model
def linear_regression(inputs):
return (inputs * w) + b
# Define loss function
def mean_square_fn(model_fn, inputs, labels):
return tf.reduce_sum(((model_fn(inputs) - labels) ** 2) / (2 * len(x_train)))
# Define optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
# Compute gradients
grad = tfe.implicit_gradients(mean_square_fn)
# Start training
for step in range(num_steps):
optimizer.apply_gradients(grad(linear_regression, x_train, y_train))
if (step + 1) % 50 == 0:
print("Epoch: {}, Loss: {}, W: {}, b: {}".format(step + 1, mean_square_fn(linear_regression, x_train, y_train),
w.numpy(), b.numpy()))
# Display
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, np.array(w * x_train + b), label='Fitted line')
plt.legend()
plt.show()
| [
"[email protected]"
] | |
c094ca768a09f90b5ff71b83649c758e5347b11a | dbf34d933a288e6ebca568eaebaa53e5b98ba7c1 | /src/rebecca/index/splitter.py | 34d4aa005a6bca3c5d5273b7acd574142148f30d | [] | no_license | rebeccaframework/rebecca.index | dc68dfa2c1b77fc273a12b3f934074722fb8300c | ab452c9b375227e84fab42496633dc026421a283 | refs/heads/master | 2021-01-10T21:11:53.567186 | 2013-05-05T18:53:58 | 2013-05-05T18:53:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 759 | py | from zope.interface import implementer
from zope.index.text.interfaces import ISplitter
from persistent import Persistent
from igo.Tagger import Tagger
@implementer(ISplitter)
class IgoSplitter(Persistent):
def __init__(self, dictionary):
self.dictionary = dictionary
@property
def tagger(self):
if not hasattr(self, '_v_tagger'):
self._v_tagger = Tagger(self.dictionary)
return self._v_tagger
def process(self, terms):
results = []
for term in terms:
results.extend(self.tagger.wakati(term))
return results
def processGlob(self, terms):
results = []
for term in terms:
results.extend(self.tagger.wakati(term))
return results
| [
"[email protected]"
] | |
c361eca7aae2a04817c28fe837c042af887c9567 | 411e5de8629d6449ff9aad2eeb8bb1dbd5977768 | /AlgoExpert/greedy/minimumWaitingTime.py | 654f08d249d968d38d7b072c4abfa1fdfa5e8e37 | [
"MIT"
] | permissive | Muzque/Leetcode | cd22a8f5a17d9bdad48f8e2e4dba84051e2fb92b | 2c37b4426b7e8bfc1cd2a807240b0afab2051d03 | refs/heads/master | 2022-06-01T20:40:28.019107 | 2022-04-01T15:38:16 | 2022-04-01T15:39:24 | 129,880,002 | 1 | 1 | MIT | 2022-04-01T15:39:25 | 2018-04-17T09:28:02 | Python | UTF-8 | Python | false | false | 486 | py | """
"""
testcases = [
{
'input': [3, 2, 1, 2, 6],
'output': 17,
},
{
'input': [2],
'output': 0,
},
]
def minimumWaitingTime(queries):
queries.sort()
ret = 0
for i in range(len(queries)-1):
if i > 0:
queries[i] += queries[i-1]
ret += queries[i]
return ret
if __name__ == '__main__':
for tc in testcases:
ret = minimumWaitingTime(tc['input'])
assert(ret == tc['output'])
| [
"[email protected]"
] | |
3d90e1a3792eaec38062f7ea1dbe0cfdf9455b06 | 3fa4a77e75738d00835dcca1c47d4b99d371b2d8 | /backend/pyrogram/raw/base/server_dh_inner_data.py | 6813099ac6c9cffd446ad983b6da40d37ae93590 | [
"Apache-2.0"
] | permissive | appheap/social-media-analyzer | 1711f415fcd094bff94ac4f009a7a8546f53196f | 0f9da098bfb0b4f9eb38e0244aa3a168cf97d51c | refs/heads/master | 2023-06-24T02:13:45.150791 | 2021-07-22T07:32:40 | 2021-07-22T07:32:40 | 287,000,778 | 5 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,903 | py | # Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
# # # # # # # # # # # # # # # # # # # # # # # #
# !!! WARNING !!! #
# This is a generated file! #
# All changes made in this file will be lost! #
# # # # # # # # # # # # # # # # # # # # # # # #
from typing import Union
from pyrogram import raw
from pyrogram.raw.core import TLObject
ServerDHInnerData = Union[raw.types.ServerDHInnerData]
# noinspection PyRedeclaration
class ServerDHInnerData: # type: ignore
"""This base type has 1 constructor available.
Constructors:
.. hlist::
:columns: 2
- :obj:`ServerDHInnerData <pyrogram.raw.types.ServerDHInnerData>`
"""
QUALNAME = "pyrogram.raw.base.ServerDHInnerData"
def __init__(self):
raise TypeError("Base types can only be used for type checking purposes: "
"you tried to use a base type instance as argument, "
"but you need to instantiate one of its constructors instead. "
"More info: https://docs.pyrogram.org/telegram/base/server-dh-inner-data")
| [
"[email protected]"
] | |
6927adb2877ed18131676f2f35fb65189fcc17a5 | ca617409a3a992a2014eab34bf45ea5cd22021d7 | /event_management/serializers/venue.py | c595ecb61bac9e3ec3a25c229f8cb80dabf5c790 | [] | no_license | Imam-Hossain-45/ticketing | 89463b048db3c7b1bc92a4efc39b83c4f17d967f | 65a124d579162a687b20dfbdba7fd85c110006c6 | refs/heads/master | 2022-04-14T22:36:23.152185 | 2020-03-07T11:52:38 | 2020-03-07T11:52:38 | 230,717,468 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 495 | py | from rest_framework import serializers
from event_management.models import Venue
from settings.models import Address
class AddressCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = '__all__'
class VenueCreateSerializer(serializers.ModelSerializer):
venue_address = AddressCreateSerializer()
class Meta:
model = Venue
fields = ('name', 'amenities', 'capacity', 'contact_person', 'contact_mobile', 'venue_address')
| [
"[email protected]"
] | |
8985c156f126ecc79db188ed97f0e9294a25d6d3 | b048abb5f35b5c69b59387dda86ef0ed62a5b378 | /elias.py | c0500cbf67226b4feaa64037b1e26cba1ccc0539 | [] | no_license | vam-sin/DoctorElias | e7cc362417ad33bb0b43b354be3c65b7b38aa5fc | a3c543de17a3ab2f33e9d2c54159c0d378164084 | refs/heads/master | 2022-09-02T02:52:53.616775 | 2020-05-30T11:04:03 | 2020-05-30T11:04:03 | 257,921,467 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 10,899 | py | # tasks
# Consider all symptoms.
# Build engine
# Take severity symptoms: 0-5 scale, 0 being not at all, 5 meaning extremely severe.
# Libraries
from experta import *
symptoms_list = ['headache', 'back pain', 'chest pain', 'cough', 'fainting', 'fatigue', 'sunken eyes', 'low body temperature',
'restlesness', 'sore throat', 'fever', 'nausea', 'blurred vision']
# Diseases: [0,0,0,0,0,0,0,0,0,0,0,0,0]
diseases_dict = ["Alzheimers", "Arthritis", "Asthma", "Diabetes", "Epilepsy", "Glaucoma", "Heart Disease", "Heat Stroke",
"Hyperthyroidism", "Hypothermia", "Jaundice", "Sinusitis", "Tuberculosis"]
symptoms_disease_map = [
[0,0,0,0,0,0,0,1,0,0,0,0,0]
,[0,1,0,0,0,0,1,0,0,0,0,0,0]
,[0,0,1,1,0,0,0,1,0,0,0,0,0]
,[0,0,0,0,0,0,1,0,0,0,0,1,1]
,[0,0,0,0,0,0,1,0,0,0,0,0,0]
,[1,0,0,0,0,0,0,0,0,0,0,1,1]
,[0,0,1,0,0,0,0,0,0,0,0,1,0]
,[1,0,0,0,0,0,0,0,0,1,0,1,0]
,[0,0,0,0,0,0,1,0,0,0,0,1,0]
,[0,0,0,0,1,0,0,0,1,0,0,0,0]
,[0,0,0,0,0,0,1,0,0,1,0,1,0]
,[1,0,0,1,0,1,0,0,0,1,0,0,0]
,[0,0,1,1,0,0,0,0,0,1,0,0,0]]
def get_symptoms(disease):
return symptoms_disease_map[diseases_dict.index(disease)]
# Doctor Class
class DoctorElias(KnowledgeEngine):
@DefFacts()
def start(self):
print("Hey! Welcome to the Olive Wellness Centre, I am Elias! I believe you are here for a checkup. In order to do that, I will need you to ask some questions for me.\n For all these questions, answer with a number between 0 to 5. With 0 meaning that symptom is not present and 5 meaning a severe case of that symptom.\n")
yield Fact(action = "diagnose")
@Rule(Fact(action = "diagnose"), NOT(Fact(headache = W())), salience = 1)
def symptom1(self):
self.declare(Fact(headache = input("Do you have a headache? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(back_pain = W())), salience = 1)
def symptom2(self):
self.declare(Fact(back_pain = input("Do you have back pain? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(chest_pain = W())), salience = 1)
def symptom3(self):
self.declare(Fact(chest_pain = input("Do you have chest pain? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(cough = W())), salience = 1)
def symptom4(self):
self.declare(Fact(cough = input("Do you have a cough? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(fainting = W())), salience = 1)
def symptom5(self):
self.declare(Fact(fainting = input("Do you experience fainting? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(fatigue = W())), salience = 1)
def symptom6(self):
self.declare(Fact(fatigue = input("Do you experience fatigue? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(sunken_eyes = W())), salience = 1)
def symptom7(self):
self.declare(Fact(sunken_eyes = input("Do you have sunken eyes? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(low_body_temp = W())), salience = 1)
def symptom8(self):
self.declare(Fact(low_body_temp = input("Do you have a low body temperature? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(restlessness = W())), salience = 1)
def symptom9(self):
self.declare(Fact(restlessness = input("Do you feel restless? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(sore_throat = W())), salience = 1)
def symptom10(self):
self.declare(Fact(sore_throat = input("Do you have a sore throat? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(fever = W())), salience = 1)
def symptom11(self):
self.declare(Fact(fever = input("Do you have a fever? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(nausea = W())), salience = 1)
def symptom12(self):
self.declare(Fact(nausea = input("Do you feel nauseous? ")))
@Rule(Fact(action = "diagnose"), NOT(Fact(blurred_vision = W())), salience = 1)
def symptom13(self):
self.declare(Fact(blurred_vision = input("Do you experience blurred vision? ")))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),NOT(Fact(fatigue="0")),Fact(restlessness="0"),Fact(low_body_temp="0"),NOT(Fact(fever="0")),Fact(sunken_eyes="0"),NOT(Fact(nausea="0")),Fact(blurred_vision="0"))
def disease_0(self):
self.declare(Fact(disease="Jaundice"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),Fact(fatigue="0"),NOT(Fact(restlessness="0")),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_1(self):
self.declare(Fact(disease="Alzheimers"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),NOT(Fact(back_pain="0")),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),NOT(Fact(fatigue="0")),Fact(restlessness="0"),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_2(self):
self.declare(Fact(disease="Arthritis"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),NOT(Fact(chest_pain="0")),NOT(Fact(cough="0")),Fact(fainting="0"),Fact(sore_throat="0"),Fact(fatigue="0"),Fact(restlessness="0"),Fact(low_body_temp="0"),NOT(Fact(fever="1")),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_3(self):
self.declare(Fact(disease="Tuberculosis"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),NOT(Fact(chest_pain="0")),NOT(Fact(cough="0")),Fact(fainting="0"),Fact(sore_throat="0"),Fact(fatigue="0"),NOT(Fact(restlessness="0")),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_4(self):
self.declare(Fact(disease="Asthma"))
@Rule(Fact(action='diagnose'),NOT(Fact(headache="0")),Fact(back_pain="0"),Fact(chest_pain="0"),NOT(Fact(cough="0")),Fact(fainting="0"),NOT(Fact(sore_throat="0")),Fact(fatigue="0"),Fact(restlessness="0"),Fact(low_body_temp="0"),NOT(Fact(fever="0")),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_5(self):
self.declare(Fact(disease="Sinusitis"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),NOT(Fact(fatigue="0")),Fact(restlessness="0"),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_6(self):
self.declare(Fact(disease="Epilepsy"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),NOT(Fact(chest_pain="0")),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),Fact(fatigue="0"),Fact(restlessness="0"),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),NOT(Fact(nausea="0")),Fact(blurred_vision="0"))
def disease_7(self):
self.declare(Fact(disease="Heart Disease"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),NOT(Fact(fatigue="0")),Fact(restlessness="0"),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),NOT(Fact(nausea="0")),NOT(Fact(blurred_vision="0")))
def disease_8(self):
self.declare(Fact(disease="Diabetes"))
@Rule(Fact(action='diagnose'),NOT(Fact(headache="0")),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),Fact(fatigue="0"),Fact(restlessness="0"),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),NOT(Fact(nausea="0")),NOT(Fact(blurred_vision="0")))
def disease_9(self):
self.declare(Fact(disease="Glaucoma"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),NOT(Fact(fatigue="0")),Fact(restlessness="0"),Fact(low_body_temp="0"),Fact(fever="0"),Fact(sunken_eyes="0"),NOT(Fact(nausea="0")),Fact(blurred_vision="0"))
def disease_10(self):
self.declare(Fact(disease="Hyperthyroidism"))
@Rule(Fact(action='diagnose'),Fact(headache="1"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),Fact(fainting="0"),Fact(sore_throat="0"),Fact(fatigue="0"),Fact(restlessness="0"),Fact(low_body_temp="0"),NOT(Fact(fever="0")),Fact(sunken_eyes="0"),NOT(Fact(nausea="0")),Fact(blurred_vision="0"))
def disease_11(self):
self.declare(Fact(disease="Heat Stroke"))
@Rule(Fact(action='diagnose'),Fact(headache="0"),Fact(back_pain="0"),Fact(chest_pain="0"),Fact(cough="0"),NOT(Fact(fainting="0")),Fact(sore_throat="0"),Fact(fatigue="0"),Fact(restlessness="0"),NOT(Fact(low_body_temp="0")),Fact(fever="0"),Fact(sunken_eyes="0"),Fact(nausea="0"),Fact(blurred_vision="0"))
def disease_12(self):
self.declare(Fact(disease="Hypothermia"))
@Rule(Fact(action='diagnose'),Fact(disease=MATCH.disease),salience = -998)
def disease(self, disease):
id_disease = disease
disease_details = get_symptoms(id_disease)
print("\nThe disease could mostly be " + str(id_disease))
print("The rule taken into account was: ")
for i in range(len(disease_details)):
if disease_details[i] != 0:
print("<" + symptoms_list[i] + "> yes.")
else:
print("<" + symptoms_list[i] + "> no.")
print(" --> " + str(id_disease))
@Rule(Fact(action='diagnose'),
Fact(headache=MATCH.headache),
Fact(back_pain=MATCH.back_pain),
Fact(chest_pain=MATCH.chest_pain),
Fact(cough=MATCH.cough),
Fact(fainting=MATCH.fainting),
Fact(sore_throat=MATCH.sore_throat),
Fact(fatigue=MATCH.fatigue),
Fact(low_body_temp=MATCH.low_body_temp),
Fact(restlessness=MATCH.restlessness),
Fact(fever=MATCH.fever),
Fact(sunken_eyes=MATCH.sunken_eyes),
Fact(nausea=MATCH.nausea),
Fact(blurred_vision=MATCH.blurred_vision),NOT(Fact(disease=MATCH.disease)),salience = -999)
def unmatched(self,headache, back_pain, chest_pain, cough, fainting, sore_throat, fatigue, restlessness,low_body_temp ,fever ,sunken_eyes ,nausea ,blurred_vision):
print("\nCould not exactly diagnose what the disease is, but let me try maximum symptom match!")
dis_lis = [headache, back_pain, chest_pain, cough, fainting, sore_throat, fatigue, restlessness,low_body_temp ,fever ,sunken_eyes ,nausea ,blurred_vision]
max_val = 0
max_dis = ""
for i in range(len(symptoms_disease_map)):
temp_val = 0
for j in range(len(symptoms_disease_map[i])):
if dis_lis[j] == str(symptoms_disease_map[i][j]):
temp_val += 1
if temp_val > max_val:
max_val = temp_val
max_dis = diseases_dict[i]
id_disease = max_dis
disease_details = get_symptoms(id_disease)
print("\nThe disease could mostly be " + str(id_disease))
print("The rule taken into account was: ")
for i in range(len(disease_details)):
if disease_details[i] != 0:
print("<" + symptoms_list[i] + "> yes.")
else:
print("<" + symptoms_list[i] + "> no.")
print(" --> " + str(id_disease))
if __name__ == "__main__":
elias = DoctorElias()
while 1:
elias.reset()
elias.run()
print("Would you like to diagnose some other symptoms?")
if input() == "no":
exit()
| [
"[email protected]"
] | |
c9826cc909c6ccaa1d56df36acffaefce9861555 | 4a2f3369620add7a72de4f8c50ed208442e024ba | /my_admin/service/sites.py | 690c970485c84f936cf79d39885be357d65086f3 | [] | no_license | YangQian1992/CRM | a7292a48bbaf221baffdfdc80b04270f9d7a2398 | 7cd026f99a4bf46ed896517fbd1141d92a1072f3 | refs/heads/master | 2020-03-28T01:01:32.674293 | 2018-10-10T07:25:38 | 2018-10-10T07:25:38 | 147,470,027 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,420 | py | from django.conf.urls import url
from django.shortcuts import render, HttpResponse, redirect
from django.db.models.fields.related import ManyToManyField,ForeignKey,OneToOneField
from django.utils.safestring import mark_safe
from django.urls import reverse
from django import forms
from my_admin.utils.mypage import MyPage
from django.db.models import Q
import copy
class Showlist(object):
"""
展示类:只服务于listview视图函数
"""
def __init__(self, config_obj, data_list, request):
self.config_obj = config_obj
self.data_list = data_list
self.request = request
# 分页
current_page = request.GET.get("page", 1) # 获取当前页面
all_data_amount = self.data_list.count() # 获取当前模型表中的总数据量
self.myPage_obj = MyPage(current_page, all_data_amount, request) # 实例化对象
self.current_show_data = data_list[self.myPage_obj.start:self.myPage_obj.end]
# 获取一个新式actions格式:[{"text":"xxx","name":"patch_delete"},]
def get_new_actions(self):
add_actions = []
add_actions.extend(self.config_obj.actions)
add_actions.append(self.config_obj.patch_delete)
new_actions = [] # 新式actions
for func in add_actions:
new_actions.append({
"text":func.short_description,
"name":func.__name__,
})
return new_actions
# 获取一个新式list_filter格式:{"publish":[xx,xx,],"authors":[xx,xx,]}
def get_new_list_filter(self):
new_list_filter = {}
for str_field in self.config_obj.list_filter:
get_url_params = copy.deepcopy(self.request.GET)
current_field_pk = get_url_params.get(str_field,0)
field_obj = self.config_obj.model._meta.get_field(str_field)
# 新建存放表中数据的列表
model_list = []
if current_field_pk == 0:
a_tag = '<a style="color:purple" href="?{}">{}</a>'.format(get_url_params.urlencode(), "全部")
else:
get_url_params.pop(str_field)
a_tag = '<a style="color:purple" href="?{}">{}</a>'.format(get_url_params.urlencode(), "全部")
model_list.append(a_tag)
# 判断是否是关联字段
if isinstance(field_obj,ManyToManyField) or isinstance(field_obj,ForeignKey) or isinstance(field_obj,OneToOneField):
rel_model = field_obj.rel.to
rel_model_queryset = rel_model.objects.all()
for rel_model_obj in rel_model_queryset:
get_url_params[str_field] = rel_model_obj.pk
if rel_model_obj.pk == int(current_field_pk):
a_tag = '<a class="active" href="?{}">{}</a>'.format(get_url_params.urlencode(), rel_model_obj)
else:
a_tag = '<a href="?{}">{}</a>'.format(get_url_params.urlencode(), rel_model_obj)
model_list.append(a_tag)
else:
current_model_queryset = self.config_obj.model.objects.values(str_field)
for current_model_dict in current_model_queryset:
get_url_params[str_field] = current_model_dict[str_field]
if current_model_dict[str_field] == current_field_pk:
a_tag = '<a class="active" href="?{}">{}</a>'.format(get_url_params.urlencode(), current_model_dict[str_field])
else:
a_tag = '<a href="?{}">{}</a>'.format(get_url_params.urlencode(),current_model_dict[str_field])
model_list.append(a_tag)
new_list_filter[str_field] = model_list
return new_list_filter
def get_header(self):
# 创建数据表格头部分
header_list = []
for field_or_func in self.config_obj.get_new_list_display():
# 判断 field_or_func 是否可以被调用
if callable(field_or_func):
add_header = field_or_func(self.config_obj, is_header=True)
else:
# 判断 field_or_func 是否为"__str__"
if field_or_func == "__str__":
# 继承默认配置类,就默认展示当前访问模型表的表名
add_header = self.config_obj.model._meta.model_name.upper()
else:
# 自定制配置类,就获取字段对象
field_obj = self.config_obj.model._meta.get_field(field_or_func)
add_header = field_obj.verbose_name
header_list.append(add_header)
return header_list
def get_body(self):
# 创建数据表格体部分
new_data_list = []
for data_obj in self.current_show_data:
inner_data_list = []
for field_or_func in self.config_obj.get_new_list_display():
# 判断 field_or_func 是否可以被调用
if callable(field_or_func):
field_value = field_or_func(self.config_obj, data_obj=data_obj)
else:
# 针对继承默认配置类的模型表的list_display的值是"__str__".进行异常处理
try:
# 判断field_or_func 所对应的字段对象的类型是否为ManyToManyField
field_obj = self.config_obj.model._meta.get_field(field_or_func)
if isinstance(field_obj, ManyToManyField):
# 多对多关系的字段需要调用all()
rel_obj_list = getattr(data_obj, field_or_func).all()
rel_data_list = [str(item) for item in rel_obj_list]
field_value = ",".join(rel_data_list)
else:
# 除了多对多关系以外的字段都可以直接添加,无需调用all()
field_value = getattr(data_obj, field_or_func)
if field_or_func in self.config_obj.list_display_links:
# 若在当前访问模型表的配置类对象的list_display_links中能找到此field_or_func,则给此field_or_func对应的字段值添加a标签,可以跳转到编辑页面,再将构建好的a标签赋值给field_value
change_url = self.config_obj.get_change_url(data_obj)
field_value = mark_safe('<a href="{}">{}</a>'.format(change_url, field_value))
except Exception as e:
# field_or_func 为"__str__"
field_value = getattr(data_obj, field_or_func)
inner_data_list.append(field_value)
new_data_list.append(inner_data_list)
return new_data_list
class ModelMyAdmin():
model_form_class = []
list_display = ["__str__", ]
list_display_links = []
search_fields = []
actions = []
list_filter = []
def __init__(self, model):
self.model = model
self.model_name = self.model._meta.model_name
self.app_label = self.model._meta.app_label
# 批量删除函数
def patch_delete(self,request,queryset):
queryset.delete()
# 定义汉语描述
patch_delete.short_description = "批量删除"
# 获取增删改查的url
def get_list_url(self):
list_url = "{}_{}_list".format(self.app_label, self.model_name)
return reverse(list_url)
def get_add_url(self):
list_url = "{}_{}_add".format(self.app_label, self.model_name)
return reverse(list_url)
def get_delete_url(self, data_obj):
list_url = "{}_{}_delete".format(self.app_label, self.model_name)
return reverse(list_url, args=(data_obj.pk,))
def get_change_url(self, data_obj):
list_url = "{}_{}_change".format(self.app_label, self.model_name)
return reverse(list_url, args=(data_obj.pk,))
# 默认操作函数
def delete(self, data_obj=None, is_header=False):
if is_header:
return "操作"
else:
return mark_safe('<a href="{}">删除</a>'.format(self.get_delete_url(data_obj)))
def change(self, data_obj=None, is_header=False):
if is_header:
return "操作"
else:
return mark_safe('<a href="{}">编辑</a>'.format(self.get_change_url(data_obj)))
def checkbox(self, data_obj=None, is_header=False):
if is_header:
return "选择"
else:
return mark_safe('<input type="checkbox" name="pk_list" value={}>'.format(data_obj.pk))
# 获取新的list_display
def get_new_list_display(self):
new_list_display = []
new_list_display.extend(self.list_display)
new_list_display.insert(0, ModelMyAdmin.checkbox)
new_list_display.append(ModelMyAdmin.delete)
if not self.list_display_links:
# 若继承默认配置类的list_display_links,则需要默认添加编辑列
new_list_display.append(ModelMyAdmin.change)
return new_list_display
# 获取默认配置类或者自定制配置类中的model_form
def get_model_form(self):
if self.model_form_class:
return self.model_form_class
else:
class ModelFormClass(forms.ModelForm):
class Meta:
model = self.model
fields = '__all__'
return ModelFormClass
# 获取新的model_form(添加pop功能)
def get_new_model_form(self,form):
from django.forms.models import ModelChoiceField
for bfield in form:
if isinstance(bfield.field, ModelChoiceField):
bfield.is_pop = True
# 获取字段的字符串格式
str_field = bfield.name
# 获取关联字段所对应的表(类)
rel_model = self.model._meta.get_field(str_field).rel.to
# 获取关联字段所对应的表名
str_model_name = rel_model._meta.model_name
# 获取关联字段所对应的app名
str_app_label = rel_model._meta.app_label
# 通过反射获取到url
_url = reverse("{}_{}_add".format(str_app_label,str_model_name))
bfield.url = _url
bfield.pop_back_id = "id_" + str_field
return form
# 获取定位搜索条件
def get_search_condition(self, request):
# 从url上获取填入的搜索值,没有就默认为空
search_value = request.GET.get("query", "")
# 实例化出一个搜索对象
search_condition = Q()
if search_value:
# 将搜索联合条件更改为或,默认为且
search_condition.connector = "or"
for field in self.search_fields:
search_condition.children.append((field + '__icontains', search_value))
# 若不走if条件,则返回的是空搜索条件,即会显示所有信息
return search_condition
# 获取筛选搜索条件
def get_filter_condition(self,request):
filter_condition = Q()
for key,val in request.GET.items():
if key in ["page","query"]:
continue
filter_condition.children.append((key,val))
return filter_condition
# 视图函数(增删改查)
def listview(self, request):
if request.method == "POST":
func_name = request.POST.get("actions","")
pk_list = request.POST.getlist("pk_list")
print("actions-->",func_name) # food: --> patch_init
print("pk_list-->",pk_list) # pk_list--> ['5061', '5062', '5063']
queryset = self.model.objects.filter(pk__in = pk_list)
if func_name:
# func_name-->str 故需要通过反射来找到函数名
action = getattr(self,func_name)
# 执行函数
action(request,queryset)
# 获取添加数据的url
add_url = self.get_add_url()
# 获取展示数据的url
list_url = self.get_list_url()
# 获取当前模型表的所有数据
data_list = self.model.objects.all()
# 获取定位搜索条件对象
search_condition = self.get_search_condition(request)
# 获取筛选搜索条件对象
filter_condition = self.get_filter_condition(request)
# 数据过滤
data_list = data_list.filter(search_condition).filter(filter_condition)
# 需求:要用到Showlist类中的两个方法,故需要先实例化对象
show_list = Showlist(self, data_list, request)
# 调用类中的方法或属性
header_list = show_list.get_header()
current_show_data = show_list.get_body()
page_html = show_list.myPage_obj.ret_html()
new_actions = show_list.get_new_actions()
new_list_filter = show_list.get_new_list_filter()
return render(request, "my-admin/listview.html", {
"current_show_data": current_show_data,
"header_list": header_list,
"current_model": self.model_name,
"add_url": add_url,
"page_html": page_html,
"search_fields": self.search_fields,
"new_actions": new_actions,
"list_filter":self.list_filter,
"list_url":list_url,
"new_list_filter":new_list_filter,
})
def addview(self, request):
ModelFormClass = self.get_model_form()
if request.method == "POST":
form = ModelFormClass(request.POST)
form_obj = self.get_new_model_form(form)
if form_obj.is_valid():
obj = form_obj.save()
pop = request.GET.get("pop","")
if pop:
form_data = str(obj)
pk = obj.pk
return render(request,"my-admin/pop.html",{"form_data":form_data,"pk":pk})
else:
list_url = self.get_list_url()
return redirect(list_url)
return render(request, "my-admin/addview.html", {
"form_obj": form_obj,
"model_name": self.model_name,
})
form = ModelFormClass()
form_obj = self.get_new_model_form(form)
return render(request, "my-admin/addview.html", {
"form_obj": form_obj,
"model_name": self.model_name,
})
def changeview(self, request, id):
ModelFormClass = self.get_model_form()
change_obj = self.model.objects.get(pk=id)
if request.method == "POST":
form = ModelFormClass(data=request.POST, instance=change_obj)
form_obj = self.get_new_model_form(form)
if form_obj.is_valid():
form_obj.save()
list_url = self.get_list_url()
return redirect(list_url)
return render(request, "my-admin/changeview.html", {
"form_obj": form_obj,
"model_name": self.model_name,
})
form = ModelFormClass(instance=change_obj)
form_obj = self.get_new_model_form(form)
return render(request, "my-admin/changeview.html", {
"form_obj": form_obj,
"model_name": self.model_name,
})
def deleteview(self, request, id):
delete_obj = self.model.objects.get(pk=id)
list_url = self.get_list_url()
if request.method == "POST":
delete_obj.delete()
return redirect(list_url)
form_obj = self.get_model_form()(instance=delete_obj)
return render(request, "my-admin/delete.html", {
"model_name": self.model_name,
"form_obj": form_obj,
"list_url": list_url,
})
def extra_url(self):
res = []
return res
def get_urls_02(self):
res = [
url(r'^$', self.listview, name="{}_{}_list".format(self.app_label, self.model_name)),
url(r'^add/$', self.addview, name="{}_{}_add".format(self.app_label, self.model_name)),
url(r'^(\d+)/change/$', self.changeview, name="{}_{}_change".format(self.app_label, self.model_name)),
url(r'^(\d+)/delete/$', self.deleteview, name="{}_{}_delete".format(self.app_label, self.model_name)),
]
res.extend(self.extra_url())
return res
@property
def urls(self):
return self.get_urls_02(), None, None
class MyAdminSite():
def __init__(self):
self._registry = {}
def register(self, model, my_admin_class=None):
if not my_admin_class:
my_admin_class = ModelMyAdmin
self._registry[model] = my_admin_class(model)
def get_urls_01(self):
res = []
for model, config_obj in self._registry.items():
model_name = model._meta.model_name
app_label = model._meta.app_label
add_url = url(r'^{}/{}/'.format(app_label, model_name), config_obj.urls)
res.append(add_url)
return res
@property
def urls(self):
return self.get_urls_01(), None, None
site = MyAdminSite()
| [
"[email protected]"
] | |
1e77c71e14d2df705175577ba95acfce83d220cc | e64db6fced156ea26497958dd3a9265db177ba2b | /manage.py | abb96d18b3314fdce50aae2b041b57e426611e36 | [] | no_license | skyride/reve-flairs | 9c2fe782db8f74696d4eea42c83abf1ceb55e72e | 6f84d571f5756964b8bcb822147ce9b144036c76 | refs/heads/master | 2022-12-16T22:25:45.671614 | 2020-06-12T20:58:58 | 2020-06-12T20:58:58 | 110,861,354 | 2 | 1 | null | 2022-11-22T02:01:52 | 2017-11-15T16:55:30 | Python | UTF-8 | Python | false | false | 804 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "flairs.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| [
"[email protected]"
] | |
2ea30df6db951105fb4bc2b8f1eb8fdd7e346f4d | cbd60a20e88adb174b40832adc093d848c9ca240 | /solutions/busnumbers/busnumbers.py | 690a0be7996a788721974b7b20150d4091bcf299 | [] | no_license | maxoja/kattis-solution | 377e05d468ba979a50697b62ce8efab5dcdddc63 | b762bfa9bbf6ef691d3831c628d9d16255ec5e33 | refs/heads/master | 2018-10-09T04:53:31.579686 | 2018-07-19T12:39:09 | 2018-07-19T12:39:09 | 111,871,691 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 579 | py | n = int(input())
seq = sorted(list(map(int, input().split())))
prevs = []
for i in range(len(seq)):
current = seq[i]
nxt = -1 if i == len(seq)-1 else seq[i+1]
if nxt == current+1:
prevs.append(current)
continue
else:
if prevs:
## print('enter' , prevs)
if len(prevs) >= 2:
print(str(prevs[0]) + '-' + str(current), end=' ')
else:
print(prevs[0], current, end=' ')
prevs = []
else:
print(current, end=' ')
| [
"-"
] | - |
3bd03fe4d769ba382d80392cf0c083c66cb30acb | 71501709864eff17c873abbb97ffabbeba4cb5e3 | /llvm13.0.0/lldb/test/API/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointThreads.py | 1f6832d9ecdb1b993193adf3655ceba218a19e06 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | LEA0317/LLVM-VideoCore4 | d08ba6e6f26f7893709d3285bdbd67442b3e1651 | 7ae2304339760685e8b5556aacc7e9eee91de05c | refs/heads/master | 2022-06-22T15:15:52.112867 | 2022-06-09T08:45:24 | 2022-06-09T08:45:24 | 189,765,789 | 1 | 0 | NOASSERTION | 2019-06-01T18:31:29 | 2019-06-01T18:31:29 | null | UTF-8 | Python | false | false | 700 | py |
import unittest2
from lldbsuite.test.decorators import *
from lldbsuite.test.concurrent_base import ConcurrentEventsBase
from lldbsuite.test.lldbtest import TestBase
@skipIfWindows
class ConcurrentTwoBreakpointThreads(ConcurrentEventsBase):
mydir = ConcurrentEventsBase.compute_mydir(__file__)
# Atomic sequences are not supported yet for MIPS in LLDB.
@skipIf(triple='^mips')
@expectedFailureAll(archs=["aarch64"], oslist=["freebsd"],
bugnumber="llvm.org/pr49433")
def test(self):
"""Test two threads that trigger a breakpoint. """
self.build(dictionary=self.getBuildFlags())
self.do_thread_actions(num_breakpoint_threads=2)
| [
"[email protected]"
] | |
433be8a7d7781edf3a6c0b6fd7ea8ce7d790b2f2 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02803/s436740421.py | e18ddeaa284997e7a2fa19641dcbbc710be7f0af | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,057 | py | from collections import deque
H, W = map(int, input().split())
field = ['#' * (W+2)] * (H+2)
for i in range(1, H+1):
field[i] = '#' + input() + '#'
di = [1, 0, -1, 0]
dj = [0, 1, 0, -1]
ans = 0
q = deque()
for si in range(1, H+1):
for sj in range(1, W+1):
if field[si][sj] == '#':
continue
q.clear()
q.append([si, sj])
dist = [[-1 for _ in range(W+2)] for _ in range(H+2)]
dist[si][sj] = 0
dist_max = 0
while len(q) != 0:
current = q.popleft()
ci = current[0]
cj = current[1]
for d in range(4):
next_i = ci + di[d]
next_j = cj + dj[d]
if field[next_i][next_j] == '#':
continue
if dist[next_i][next_j] != -1:
continue
q.append([next_i, next_j])
dist[next_i][next_j] = dist[ci][cj] + 1
dist_max = max(dist_max, dist[next_i][next_j])
ans = max(ans, dist_max)
print(ans)
| [
"[email protected]"
] | |
76f9cf3c70feb1745228287e760e543e56e9ce1d | 900f3e5e0a5f9bbc28aa8673153046e725d66791 | /less15/chat_v3/chat/chat/settings.py | e6a04b5f17f725ceee6cdb1c8879e9c0dbd6a011 | [] | no_license | atadm/python_oop | c234437faebe5d387503c2c7f930ae72c2ee8107 | 2ffbadab28a18c28c14d36ccb008c5b36a426bde | refs/heads/master | 2021-01-23T04:40:10.092048 | 2017-05-30T12:22:53 | 2017-05-30T12:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,427 | py | """
Django settings for chat project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '692yjr^yr4$)m_4ud6j7^^!*gd%r+jcp!vn+nr@a4iuzy=m1js'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chatApp.apps.ChatappConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'chat.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'chat.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'chatdb',
'USER': 'postgres',
'PASSWORD': 'Univer123',
'HOST': '', # Set to empty string for localhost.
'PORT': '5433', # Set to empty string for default.
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
| [
"[email protected]"
] | |
6b09c02200e9cd1e184bdbbc08dba0c6c89f9b8e | e8f6a0d45cc5b98747967169cea652f90d4d6489 | /week2/day2/taco_project/taco_project/settings.py | 0d5bc4a9d6be4b8a4afe7e0834b1445e8f8b528f | [] | no_license | prowrestler215/python-2020-09-28 | 1371695c3b48bbd89a1c42d25aa8a5b626db1d19 | d250ebd72e7f2a76f40ebbeb7fbb31ac36afd75f | refs/heads/master | 2022-12-28T22:24:52.356588 | 2020-10-06T18:50:12 | 2020-10-06T18:50:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,128 | py | """
Django settings for taco_project project.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'kkc*+j-s50vfg_6s%p!rc^#5$pc2=okw94a6=r17z+lz1s&y@a'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'taco_stand_app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'taco_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'taco_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
| [
"[email protected]"
] | |
d45bbc2ebc3e163699e0e18d6bf32523bccae91f | 978248bf0f275ae688f194593aa32c267832b2b6 | /xlsxwriter/test/worksheet/test_write_sheet_views8.py | 16dd94be70b03ae21d672a359c7baa4a50a33d46 | [
"BSD-2-Clause-Views"
] | permissive | satish1337/XlsxWriter | b0c216b91be1b74d6cac017a152023aa1d581de2 | 0ab9bdded4f750246c41a439f6a6cecaf9179030 | refs/heads/master | 2021-01-22T02:35:13.158752 | 2015-03-31T20:32:28 | 2015-03-31T20:32:28 | 33,300,989 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,068 | py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, [email protected]
#
import unittest
from ...compatibility import StringIO
from ...worksheet import Worksheet
class TestWriteSheetViews(unittest.TestCase):
"""
Test the Worksheet _write_sheet_views() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_sheet_views1(self):
"""Test the _write_sheet_views() method with split panes + selection"""
self.worksheet.select()
self.worksheet.set_selection('A2')
self.worksheet.split_panes(15, 0)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane ySplit="600" topLeftCell="A2" activePane="bottomLeft"/><selection pane="bottomLeft" activeCell="A2" sqref="A2"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_sheet_views2(self):
"""Test the _write_sheet_views() method with split panes + selection"""
self.worksheet.select()
self.worksheet.set_selection('B1')
self.worksheet.split_panes(0, 8.43)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1350" topLeftCell="B1" activePane="topRight"/><selection pane="topRight" activeCell="B1" sqref="B1"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_sheet_views3(self):
"""Test the _write_sheet_views() method with split panes + selection"""
self.worksheet.select()
self.worksheet.set_selection('G4')
self.worksheet.split_panes(45, 54.14)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6150" ySplit="1200" topLeftCell="G4" activePane="bottomRight"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight" activeCell="G4" sqref="G4"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_sheet_views4(self):
"""Test the _write_sheet_views() method with split panes + selection"""
self.worksheet.select()
self.worksheet.set_selection('I5')
self.worksheet.split_panes(45, 54.14)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6150" ySplit="1200" topLeftCell="G4" activePane="bottomRight"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight" activeCell="I5" sqref="I5"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(got, exp)
| [
"[email protected]"
] | |
bd1244422c562b95b4abe609a6ecc9151d8cc0f3 | 2c5edd9a3c76f2a14c01c1bd879406850a12d96e | /config/default.py | 37e61c16709d86117c0fa3d63970296d5b8742d2 | [
"MIT"
] | permissive | by46/coffee | e13f5e22a8ff50158b603f5115d127e07c2e322b | f12e1e95f12da7e322a432a6386a1147c5549c3b | refs/heads/master | 2020-08-14T04:42:05.248138 | 2017-10-23T13:39:05 | 2017-10-23T13:39:05 | 73,526,501 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | HTTP_HOST = '0.0.0.0'
HTTP_PORT = 8080
DEBUG = False
SECRET_KEY = "\x02|\x86.\\\xea\xba\x89\xa3\xfc\r%s\x9e\x06\x9d\x01\x9c\x84\xa1b+uC"
# Flask-NegLog Settings
LOG_LEVEL = 'debug'
LOG_FILENAME = "logs/error.log"
LOG_BACKUP_COUNT = 10
LOG_MAX_BYTE = 1024 * 1024 * 10
LOG_FORMATTER = '%(asctime)s - %(levelname)s - %(message)s'
LOG_ENABLE_CONSOLE = True
# Flask-CORS Settings
CORS_ORIGINS = "*"
CORS_METHODS = "GET,POST,PUT"
CORS_ALLOW_HEADERS = "Content-Type,Host"
| [
"[email protected]"
] | |
e53bee84de0b19c27956646ed221e41449d3e3ae | 0818a9020adc6e25b86060a8e84171d0b4958625 | /tensorflow-piece/file_gene_scripts.py | 840928b309ae60acdab8f757ab590e178999874f | [] | no_license | wgwangang/mycodes | 2107becb6c457ed88b46426974a8f1fa07ed37dd | 9fa48ca071eacf480034d1f69d3c05171d8a97d2 | refs/heads/master | 2020-03-28T07:58:45.017910 | 2018-03-14T07:21:14 | 2018-03-14T07:21:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,196 | py | import os
def generate_train_test_txt(data_root_dir, save_dir, rate=.1):
train_txt_file_path = os.path.join(save_dir, "train.txt")
test_txt_file_path = os.path.join(save_dir, "test.txt")
dirs = os.listdir(data_root_dir)
train_txt_file = open(train_txt_file_path, mode="w")
test_txt_file = open(test_txt_file_path, mode="w")
for i,level1 in enumerate(dirs):
path_to_level1 = os.path.join(data_root_dir, level1)
img_names = os.listdir(path_to_level1)
test_num = rate*len(img_names)
if test_num < 1:
test_num = 1
test_num = int(test_num)
for img in img_names[:-test_num]:
abs_path = os.path.join(level1, img)
item = abs_path+" "+str(i)+"\n"
train_txt_file.write(item)
for img in img_names[-test_num:]:
abs_path = os.path.join(level1, img)
item = abs_path + " " + str(i) + "\n"
test_txt_file.write(item)
print("people ", i, " Done!")
train_txt_file.close()
test_txt_file.close()
def main():
generate_train_test_txt("/home/dafu/PycharmProjects/data", save_dir="../data")
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
8e0277e0fae0c9499d3837975223b854aed5431e | 6ba406a7c13d5c76934e36494c32c927bbda7ae7 | /tests/trails_fhn.py | 8ff814c29523973081000a55dda715750cf1dacf | [
"MIT"
] | permissive | sowmyamanojna/neuronmd | 50e5e4bd9a4340fda73e363133314118ea815360 | 3994d02214c3cc4996261324cfe9238e34e29f1c | refs/heads/main | 2023-07-09T01:31:32.597268 | 2021-08-23T14:33:38 | 2021-08-23T14:33:38 | 398,491,112 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 315 | py | import numpy as np
import matplotlib.pyplot as plt
from fitzhugh_nagumo import FHNNeuron
neuron = FHNNeuron()
tmax = 100
dt = 0.01
I = 1.75
t = np.arange(0, tmax, dt)
neuron.simulate(0.6, 0, t, 0.6)
neuron.plot(name="0.1")
current_list = np.arange(0.01, I, 0.01)
neuron.animate(t, current_list, ylim=[-0.45,1.5]) | [
"[email protected]"
] | |
f82263b8d652c912b1df45704b5f390611d3dfd2 | 3b60e6f4bbc011003ac4929f01eb7409918deb79 | /Analysis_v1/PlotterVariants/MultiSets/plotsHelper.py | ffa6f171c59e9cad382935e878e872b6eb9872c4 | [] | no_license | uzzielperez/Analyses | d1a64a4e8730325c94e2bc8461544837be8a179d | 1d66fa94763d7847011ea551ee872936c4c401be | refs/heads/master | 2023-02-09T04:54:01.854209 | 2020-09-07T14:57:54 | 2020-09-07T14:57:54 | 120,850,137 | 0 | 0 | null | 2020-06-17T16:48:16 | 2018-02-09T03:14:04 | C++ | UTF-8 | Python | false | false | 8,671 | py | import ROOT
from ROOT import TMath, TClass,TKey, TIter,TCanvas, TPad, TFile, TPaveText, TColor, TGaxis, TH1F, TPad, TH1D, TLegend
from ROOT import kBlack, kBlue, kRed
from ROOT import gBenchmark, gStyle, gROOT, gDirectory
import re
import sys
CMSlumiPath = '/uscms_data/d3/cuperez/CMSSW_8_0_25/src/scripts/pyroot'
sys.path.append(CMSlumiPath)
from CMSlumi import CMS_lumi
import argparse
def createRatio(h1, h2):
h3 = h1.Clone("h3")
h3.SetLineColor(kBlack)
h3.SetMarkerStyle(21)
h3.SetTitle("RATIO")
#h3.SetMinimum(0.8)
#h3.SetMaximum(2.5)
# Set up plot for markers and errors
h3.Sumw2()
h3.SetStats(0)
h3.Divide(h2)
# Adjust y-axis settings
y = h3.GetYaxis()
y.SetTitle("ratio %s/%s" %(h1, h2))
#y.SetTitleOffset(4.55)
#y = h3.GetYaxis()
#y.SetTitle("ratio h1/h2 ")
y.SetNdivisions(505)
y.SetTitleSize(20)
y.SetTitleFont(43)
y.SetTitleOffset(1.55)
y.SetLabelFont(43)
y.SetLabelSize(15)
# Adjust x-axis settings
x = h3.GetXaxis()
x.SetTitleSize(40)
x.SetTitleFont(43)
x.SetTitleOffset(10.0)
x.SetLabelFont(43)
x.SetLabelSize(15)
return h3
def createCanvasPads():
c = TCanvas("c", "canvas", 800, 800)
# Upper histogram plot is pad1
pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
pad1.SetBottomMargin(0) # joins upper and lower plot
#pad1.SetGridx()
pad1.SetLogy()
pad1.Draw()
# Lower ratio plot is pad2
c.cd() # returns to main canvas before defining pad2
pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
pad2.SetTopMargin(0) # joins upper and lower plot
pad2.SetBottomMargin(0.2)
pad2.SetGridy()
#pad2.SetGridx()
pad2.Draw()
return c, pad1, pad2
#-----------------------------------------
# Plotting functions
def createHist(file_typ, color, objtype):
hist = file_typ.Get(objtype) # e.g. DiphotonMinv
hist.SetLineColor(color) # kOrange + 7 for MC
hist.SetLineWidth(2)
hist.GetYaxis().SetTitleSize(20)
hist.GetYaxis().SetTitleFont(43)
hist.GetYaxis().SetTitleOffset(1.55)
hist.SetStats(0)
#hist.SetAxisRange(450, 1050)
return hist
#----------------------------------------
# This part taken from andy buckley
# https://root-forum.cern.ch/t/loop-over-all-objects-in-a-root-file/10807/4
def getall(d, basepath="/"):
"Generator function to recurse into a ROOT file/dir and yield (path, obj) pairs"
for key in d.GetListOfKeys():
kname = key.GetName()
if key.IsFolder():
# TODO: -> "yield from" in Py3
for i in getall(d.Get(kname), basepath+kname+"/"):
yield i
else:
yield basepath+kname, d.Get(kname)
def makeList(ListName):
ListName = []
return ListName
def LoopObjKeys(fileAssign, obj_i, canvas_i, hist_i, index):
for k, o in getall(fileAssign):
#print "h_%s" %(k[1:])
obj_i.append(k[1:])
canvas_i.append("c_%s"%(k[1:]))
histFi = createHist(fileAssign, index+1 , k[1:])
hist_i.append(histFi)
#print "obj: %s" %(String(index)), obj_i[index]
#def regexHelper(expTarget, WholeExpression, sec):
# regex = (r'%s\s+(.*)'%(expTarget))
# match = re.findall(regex, WholeExpression)
#
# #match = match[0].split(" ")
# #print regex, WholeExpression
#def diphotonAnalysisStringFinder(objEL):
def objSettings(obj):
if obj.find("Minv") != -1:
xtitle = r"m_{#gamma#gamma}#scale[1.0]{(GeV)}" # r"#scale[0.8]{m_{#gamma#gamma}(GeV)}"
xmin = 0
xmax = 8000
SetLogy = True
xpos1, ypos1, xpos2, ypos2 = .60, 0.63, 1.0, .85
elif obj.find("Pt") != -1:
xtitle = "#scale[1.0]{p_{T}(GeV)}"
xmin = 75
xmax = 8000
SetLogy = True
xpos1, ypos1, xpos2, ypos2 = .60, 0.70, 1.0, .85
#xpos1, ypos1, xpos2, ypos2 = .40, 0.75, 1.0, .85
elif obj.find("Eta") != -1:
xtitle = r"#eta"
if obj.find("sc") != -1:
xtitle = r"#scale[0.7]{sc} " + xtitle
if obj.find("det") != -1:
xtitle = r"#scale[0.7]{det} " + xtitle
xmin = -3.0
xmax = 3.0
SetLogy = False
xpos1, ypos1, xpos2, ypos2 = .32, 0.20, .85, .38
elif obj.find("Phi") != -1:
xtitle = r"#phi"
if obj.find("sc") != -1:
xtitle = r"#scale[0.7]{sc} " + xtitle
if obj.find("det") != -1:
xtitle = r"#scale[0.7]{det} " + xtitle
xmin = -3.5
xmax = 3.5
SetLogy = False
xpos1, ypos1, xpos2, ypos2 = .32, 0.20, .85, .38
else:
xtitle, xmin, xmax, SetLogy, xpos1, ypos1, xpos2, ypos2
return xtitle, xmin, xmax, SetLogy, xpos1, ypos1, xpos2, ypos2
def histDrawSettings(h, i, drawstyle):
if i < 5:
h.SetLineColor(1)
#h.SetLineColor(i)
h.SetFillColor(40+i)
#h.SetLineStyle(i)
h.Draw("hist same")
else:
h.SetLineColor(i+1)
#h.SetLineColor(i)
#h.SetFillColor(40+i)
#h.SetLineStyle(i)
h.Draw("same")
# For same set of files Same parameters except one
def LoopOverHistogramsPerFile(study, obj_f1, h, listofFiles, canv, outName):
print "LOOP OVER HISTOGRAMS PER FILE"
i = 0
#print len(obj_f1)
while i<len(obj_f1):
print obj_f1[i]
ytitle = "Events"
canv[i] = ROOT.TCanvas()
#c, pad1, pad2 = createCanvasPads()
scale = 1.00
#c.cd()
o = obj_f1[i]
xtitle, xmin, xmax, SetLogy, xpos1, ypos1, xpos2, ypos2 = objSettings(o)
print xmin, xmax
if obj_f1[i].find("diphoton") != -1:
#ocount = ocount + 1
legentry = r"SM #gamma#gamma"
elif (obj_f1[i].find("photon1")) != -1:
legentry = r"#gamma_{1}"
elif (obj_f1[i].find("photon2")) != -1:
legentry = r"#gamma_{2}"
else:
legentry = obj_f1[i]
# EBEE or EBEB
if obj_f1[i].find("EBEE") != -1:
xtitle = xtitle + r" #scale[0.45]{(EBEE)}"
if obj_f1[i].find("EBEB") != -1:
xtitle = xtitle + r" #scale[0.45]{(EBEB)}"
# Photon1 or Photon2
if obj_f1[i].find("photon1") != -1:
xtitle = r"#scale[1.0]{#gamma_{1}: }" + xtitle
if obj_f1[i].find("photon2") != -1:
xtitle = r"#scale[1.0]{#gamma_{2}: }" + xtitle
# Draw All the Histograms in the List of Files
FileNum = 0
hi = h[FileNum][i]
#h[FileNum][i].Scale(scale)
#h[FileNum][i].SetTitle(obj_f1[i])
h[FileNum][i].GetYaxis().SetTitle("Events")
h[FileNum][i].GetXaxis().SetTitle(xtitle)
h[FileNum][i].GetYaxis().SetTitleOffset(0.7)
h[FileNum][i].GetXaxis().SetTitleOffset(1.1)
#h[FileNum][i].GetXaxis().SetRangeUser(xmin, xmax)
#h[FileNum][i].GetXaxis().SetLimits(xmin, xmax)
leg = TLegend(xpos1, ypos1, xpos2, ypos2)
leg.SetBorderSize(0)
leg.SetFillStyle(0)
leg.SetTextFont(42)
leg.SetTextSize(0.035)
#leg.SetEntrySeparation(3)
#leg.SetEntrySeparation(0.3)
while FileNum < len(listofFiles):
canv[i].cd()
if SetLogy:
canv[i].SetLogy()
####### DRAW
#hi.Draw("same")
#hi.GetXaxis().SetLimits(xmin, xmax)
lower_lim = hi.GetBinCenter(hi.FindFirstBinAbove(0,1))
upper_lim = hi.GetBinCenter(hi.FindLastBinAbove(0,1))
# hi.GetXaxis().SetLimits(xmin, xmax)
#hi.GetXaxis().SetRangeUser(xmin, xmax)
#print lower_lim, upper_lim
#ymin = hi.GetMinimum()
#ymax = hi.GetMaximum()
#print ymax, ymin
if "Minv" in o or "Pt" in o:
ymin = 10**-3
ymax = 10**2
hi.GetYaxis().SetRangeUser(ymin, ymax)
#hi.GetYaxis().SetLimits(ymin, ymax)
#h[FileNum][i].GetXaxis().SetLimits(xmin, xmax)
h[FileNum][i].GetXaxis().SetRangeUser(xmin, xmax)
histDrawSettings(h[FileNum][i], FileNum+1, "hist same")
#Labelling and Legends
if FileNum < 4:
pattern = r'Ms-([^(]*)\_M'
match = re.findall(pattern, listofFiles[FileNum])
leg.AddEntry(h[FileNum][i], "MS-%s" %(match[0]), "f")
else:
pattern = r'LambdaT-([^(]*)\_M'
match = re.findall(pattern, listofFiles[FileNum])
leg.AddEntry(h[FileNum][i], "LambdaT-%s" %(match[0]), "l")
leg.Draw()
leg.SetEntrySeparation(1.3)
canv[i].Update()
FileNum = FileNum + 1
print "filenum: ", FileNum
CMS_lumi(canv[i], 4, 11, True)
#leg.SetEntrySeparation(0.6)
#leg.Draw()
canv[i].Print("%s%s%s.png" %(outName, study, obj_f1[i]))
# move to next object in root file
i = i + 1
| [
"[email protected]"
] | |
8fe76f727f44429df1fc0876ce238e15960bc6ec | 549d11c89ce5a361de51f1e1c862a69880079e3c | /python高级语法/线程/都任务版的UDP聊天器.py | 9d751967f4b2eaba2e1846ea3f723ae9a52eca1e | [] | no_license | BaldSuperman/workspace | f304845164b813b2088d565fe067d5cb1b7cc120 | 4835757937b700963fdbb37f75a5e6b09db97535 | refs/heads/master | 2020-08-01T15:32:02.593251 | 2019-09-26T08:04:50 | 2019-09-26T08:04:50 | 211,034,750 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 953 | py |
import socket
import threading
def recv_msg( udp_socket):
while True:
recv_data = udp_socket.recvfrom(1024)
print("收到的数据:{0}".format(recv_data))
def send_msg(udp_socket, dest_port,dest_ip):
'''发送数据'''
while True :
send_data = input("输入发送的数据: ")
udp_socket.sendto(send_data.encode('utf-8'), (dest_ip,dest_port))
def main():
#创建套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#绑定本地信息
udp_socket.bind(("", 7890))
#获取对方ip
dest_ip = input("请输入对方IP: ")
dest_port = int(input("请输入对方port: "))
#接受数据
#创建线程执行接受发送功能
t_recv = threading.Thread(target=recv_msg, args=(udp_socket, ))
t_send = threading.Thread(target=send_msg, args=(udp_socket, dest_port,dest_ip))
t_recv.start()
t_send.start()
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
f2c68ec335f6a55681c06b381e461d9c65326cee | a316a0018bd1cb42c477423916669ed32e2c5d7c | /homie/node/property/property_boolean.py | 49d8eb14cd18735035fe6c9f1f25173d63f9b69c | [
"MIT"
] | permissive | mjcumming/HomieV3 | a8b60ee9119059d546b69b31280cf15a7978e6fc | 62278ec6e5f72071b2aaebe8e9f66b2071774ef7 | refs/heads/master | 2020-04-28T06:49:22.193682 | 2020-04-04T12:36:08 | 2020-04-04T12:36:08 | 175,072,550 | 5 | 7 | MIT | 2020-01-15T03:41:38 | 2019-03-11T19:44:17 | Python | UTF-8 | Python | false | false | 624 | py | from .property_base import Property_Base
class Property_Boolean(Property_Base):
def __init__(self, node, id, name, settable=True, retained=True, qos=1, unit=None, data_type='boolean', data_format=None, value=None, set_value=None):
super().__init__(node,id,name,settable,retained,qos,unit,'boolean',data_format,value,set_value)
def validate_value(self, value):
return True # tests below validate
def get_value_from_payload(self,payload):
if payload == 'true':
return True
elif payload == 'false':
return False
else:
return None
| [
"[email protected]"
] | |
2b2ae4e3e90b1b98750f66a053a03514118123d6 | e88f2f590e9b58c294ea34f9277748b6bbabeac7 | /sandbox/finetuning/algos/concurrent_continuous_ppo.py | d4cd314bd47d95820381415300f80a6c264fbc93 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | jesbu1/rllab-finetuning | 4aade730f0401f46675e5a7588ca59968272a41d | ccfbc9a612dc9c85238183209814e98666825d01 | refs/heads/master | 2022-12-04T10:42:37.442485 | 2020-08-18T00:07:39 | 2020-08-18T00:07:39 | 282,724,263 | 0 | 0 | null | 2020-07-26T20:03:48 | 2020-07-26T20:03:48 | null | UTF-8 | Python | false | false | 10,264 | py | import theano
import theano.tensor as TT
from rllab.misc import ext
import numpy as np
import copy
import rllab.misc.logger as logger
from rllab.spaces.box import Box
from rllab.envs.env_spec import EnvSpec
from sandbox.finetuning.policies.concurrent_hier_policy2 import HierarchicalPolicy
from sandbox.finetuning.algos.hier_batch_polopt import BatchPolopt, \
BatchSampler # note that I use my own BatchPolopt class here
from sandbox.finetuning.algos.hier_batch_sampler import HierBatchSampler
from rllab.optimizers.first_order_optimizer import FirstOrderOptimizer
from rllab.distributions.diagonal_gaussian import DiagonalGaussian
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.baselines.gaussian_mlp_baseline import GaussianMLPBaseline
class ConcurrentContinuousPPO(BatchPolopt):
"""
Designed to enable concurrent training of a SNN that parameterizes skills
and also train the manager at the same time
Note that, if I'm not trying to do the sample approximation of the weird log of sum term,
I don't need to know which skill was picked, just need to know the action
"""
# double check this constructor later
def __init__(self,
optimizer=None,
optimizer_args=None,
step_size=0.003,
num_latents=6,
latents=None, # some sort of iterable of the actual latent vectors
period=10, # how often I choose a latent
truncate_local_is_ratio=None,
epsilon=0.1,
train_pi_iters=10,
use_skill_dependent_baseline=False,
mlp_skill_dependent_baseline=False,
freeze_manager=False,
freeze_skills=False,
**kwargs):
if optimizer is None:
if optimizer_args is None:
# optimizer_args = dict()
optimizer_args = dict(batch_size=None)
self.optimizer = FirstOrderOptimizer(learning_rate=step_size, max_epochs=train_pi_iters, **optimizer_args)
self.step_size = step_size
self.truncate_local_is_ratio = truncate_local_is_ratio
self.epsilon = epsilon
super(ConcurrentContinuousPPO, self).__init__(**kwargs) # not sure if this line is correct
self.num_latents = kwargs['policy'].latent_dim
self.latents = latents
self.period = period
self.freeze_manager = freeze_manager
self.freeze_skills = freeze_skills
assert (not freeze_manager) or (not freeze_skills)
# todo: fix this sampler stuff
# import pdb; pdb.set_trace()
self.sampler = HierBatchSampler(self, self.period)
# self.sampler = BatchSampler(self)
# i hope this is right
self.diagonal = DiagonalGaussian(self.policy.low_policy.action_space.flat_dim)
self.debug_fns = []
assert isinstance(self.policy, HierarchicalPolicy)
self.period = self.policy.period
assert self.policy.period == self.period
self.continuous_latent = self.policy.continuous_latent
assert self.continuous_latent
# self.old_policy = copy.deepcopy(self.policy)
# skill dependent baseline
self.use_skill_dependent_baseline = use_skill_dependent_baseline
self.mlp_skill_dependent_baseline = mlp_skill_dependent_baseline
if use_skill_dependent_baseline:
curr_env = kwargs['env']
skill_dependent_action_space = curr_env.action_space
new_obs_space_no_bi = curr_env.observation_space.shape[0] + 1 # 1 for the t_remaining
skill_dependent_obs_space_dim = (new_obs_space_no_bi * (self.num_latents + 1) + self.num_latents,)
skill_dependent_obs_space = Box(-1.0, 1.0, shape=skill_dependent_obs_space_dim)
skill_dependent_env_spec = EnvSpec(skill_dependent_obs_space, skill_dependent_action_space)
if self.mlp_skill_dependent_baseline:
self.skill_dependent_baseline = GaussianMLPBaseline(env_spec=skill_dependent_env_spec)
else:
self.skill_dependent_baseline = LinearFeatureBaseline(env_spec=skill_dependent_env_spec)
# initialize the computation graph
# optimize is run on >= 1 trajectory at a time
# assumptions: 1 trajectory, which is a multiple of p; that the obs_var_probs is valid
def init_opt(self):
assert isinstance(self.policy, HierarchicalPolicy)
assert not self.freeze_manager and not self.freeze_skills
manager_surr_loss = 0
# skill_surr_loss = 0
obs_var_sparse = ext.new_tensor('sparse_obs', ndim=2, dtype=theano.config.floatX)
obs_var_raw = ext.new_tensor('obs', ndim=3, dtype=theano.config.floatX) # todo: check the dtype
action_var = self.env.action_space.new_tensor_variable('action', extra_dims=1, )
advantage_var = ext.new_tensor('advantage', ndim=1, dtype=theano.config.floatX)
# latent_var = ext.new_tensor('latents', ndim=2, dtype=theano.config.floatX)
mean_var = ext.new_tensor('mean', ndim=2, dtype=theano.config.floatX)
log_std_var = ext.new_tensor('log_std', ndim=2, dtype=theano.config.floatX)
# undoing the reshape, so that batch sampling is ok
obs_var = TT.reshape(obs_var_raw, [obs_var_raw.shape[0] * obs_var_raw.shape[1], obs_var_raw.shape[2]])
############################################################
### calculating the skills portion of the surrogate loss ###
############################################################
latent_var_sparse = self.policy.manager.dist_info_sym(obs_var_sparse)['mean']
latent_var = TT.extra_ops.repeat(latent_var_sparse, self.period, axis=0) #.dimshuffle(0, 'x')
dist_info_var = self.policy.low_policy.dist_info_sym(obs_var, state_info_var=latent_var)
old_dist_info_var = dict(mean=mean_var, log_std=log_std_var)
skill_lr = self.diagonal.likelihood_ratio_sym(action_var, old_dist_info_var, dist_info_var)
skill_surr_loss_vector = TT.minimum(skill_lr * advantage_var,
TT.clip(skill_lr, 1 - self.epsilon, 1 + self.epsilon) * advantage_var)
skill_surr_loss = -TT.mean(skill_surr_loss_vector)
surr_loss = skill_surr_loss # so that the relative magnitudes are correct
if self.freeze_skills and not self.freeze_manager:
raise NotImplementedError
elif self.freeze_manager and not self.freeze_skills:
raise NotImplementedError
else:
assert (not self.freeze_manager) or (not self.freeze_skills)
input_list = [obs_var_raw, obs_var_sparse, action_var, advantage_var, mean_var, log_std_var]
self.optimizer.update_opt(
loss=surr_loss,
target=self.policy,
inputs=input_list
)
return dict()
# do the optimization
def optimize_policy(self, itr, samples_data):
print(len(samples_data['observations']), self.period)
assert len(samples_data['observations']) % self.period == 0
# note that I have to do extra preprocessing to the advantages, and also create obs_var_sparse
if self.use_skill_dependent_baseline:
input_values = tuple(ext.extract(
samples_data, "observations", "actions", "advantages", "agent_infos", "skill_advantages"))
else:
input_values = tuple(ext.extract(
samples_data, "observations", "actions", "advantages", "agent_infos"))
obs_raw = input_values[0].reshape(input_values[0].shape[0] // self.period, self.period,
input_values[0].shape[1])
obs_sparse = input_values[0].take([i for i in range(0, input_values[0].shape[0], self.period)], axis=0)
if not self.continuous_latent:
advantage_sparse = input_values[2].reshape([input_values[2].shape[0] // self.period, self.period])[:, 0]
latents = input_values[3]['latents']
latents_sparse = latents.take([i for i in range(0, latents.shape[0], self.period)], axis=0)
prob = np.array(
list(input_values[3]['prob'].take([i for i in range(0, latents.shape[0], self.period)], axis=0)),
dtype=np.float32)
mean = input_values[3]['mean']
log_std = input_values[3]['log_std']
if self.use_skill_dependent_baseline:
advantage_var = input_values[4]
else:
advantage_var = input_values[2]
# import ipdb; ipdb.set_trace()
if self.freeze_skills and not self.freeze_manager:
raise NotImplementedError
elif self.freeze_manager and not self.freeze_skills:
raise NotImplementedError
else:
assert (not self.freeze_manager) or (not self.freeze_skills)
all_input_values = (obs_raw, obs_sparse, input_values[1], advantage_var, mean, log_std)
# todo: assign current parameters to old policy; does this work?
# old_param_values = self.policy.get_param_values(trainable=True)
# self.old_policy.set_param_values(old_param_values, trainable=True)
# old_param_values = self.policy.get_param_values()
# self.old_policy.set_param_values(old_param_values)
loss_before = self.optimizer.loss(all_input_values)
self.optimizer.optimize(all_input_values)
loss_after = self.optimizer.loss(all_input_values)
logger.record_tabular('LossBefore', loss_before)
logger.record_tabular('LossAfter', loss_after)
logger.record_tabular('dLoss', loss_before - loss_after)
return dict()
def get_itr_snapshot(self, itr, samples_data):
return dict(
itr=itr,
policy=self.policy,
baseline=self.baseline,
env=self.env
)
def log_diagnostics(self, paths):
# paths obtained by self.sampler.obtain_samples
BatchPolopt.log_diagnostics(self, paths)
# self.sampler.log_diagnostics(paths) # wasn't doing anything anyways
# want to log the standard deviations
# want to log the max and min of the actions
| [
"[email protected]"
] | |
6ee0b28d5d47fef3766ee9a9567b845b290892dd | 3298ad5f82b30e855637e9351fe908665e5a681e | /Regression/Polynomial Regression/polynomial_regression.py | 07f16298a93575a5156ff3fe4ef8b1102a78ad42 | [] | no_license | Pratyaksh7/Machine-learning | 8ab5281aecd059405a86df4a3ade7bcb308f8120 | 74b7b045f17fe52bd02e99c0e25b8e0b4ac3f3a6 | refs/heads/master | 2022-12-21T14:05:28.882803 | 2020-09-28T17:03:55 | 2020-09-28T17:03:55 | 292,274,874 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,924 | py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[: , 1:-1].values
y = dataset.iloc[: , -1].values
# training the linear regression model on the whole dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
# training the polynomial regression model on the whole dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly,y)
# visualising the linear regression results
plt.scatter(X,y, color='red')
plt.plot(X, lin_reg.predict(X), color= 'blue') # plotting the linear regression line for the X values and the predicted Salary i.e., lin_reg
plt.title('Truth or Bluff (Linear Regression )')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
# visualising the polynomial regression results
plt.scatter(X,y, color='red')
plt.plot(X, lin_reg_2.predict(X_poly), color= 'blue') # plotting the linear regression line for the X values and the predicted Salary i.e., lin_reg
plt.title('Truth or Bluff (Polynomial Regression )')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
# visualising the polynomial regression results(for higher resolution and smoother curve)
X_grid = np.arange(min(X), max(X), 0.1) # choosing each point with a diff of 0.1
X_grid = X_grid.reshape((len(X_grid),1))
plt.scatter(X,y,color= 'red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)),color='blue')
plt.title('Truth or Bluff (Polynomial Regression Smooth)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
# predicting a new result with linear regression
print(lin_reg.predict([[6.5]]))
# predicting a new result with polynomial regression
print(lin_reg_2.predict(poly_reg.fit_transform([[6.5]])))
| [
"[email protected]"
] | |
079ded3be59ad28e3f6743e307ba309423d27dcd | 87cfb3d137853d91faf4c1c5f6e34a4e4a5206d9 | /src/zojax/cssregistry/tests.py | 41aa3e1e8e541b96a69a0706d39bde5e7b101372 | [
"ZPL-2.1"
] | permissive | Zojax/zojax.cssregistry | cea24579ef73f7ea2cec9c8b95671a5eeec0ce8f | 688f4ecb7556935997bbe4c09713bf57ef7be617 | refs/heads/master | 2021-01-10T21:06:12.664527 | 2011-12-16T07:15:04 | 2011-12-16T07:15:04 | 2,034,954 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,368 | py | ##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" zojax.cssregistry tests
$Id$
"""
__docformat__ = "reStructuredText"
import unittest, doctest
from zope import interface, schema
from zope.component import provideAdapter
from zope.app.testing import setup
from zope.traversing.namespace import view
from zope.traversing.interfaces import ITraversable
def setUp(test):
setup.placelessSetUp()
setup.setUpTraversal()
provideAdapter(view, (None, None), ITraversable, name="view")
def tearDown(test):
setup.placelessTearDown()
def test_suite():
return unittest.TestSuite((
doctest.DocFileSuite(
'README.txt',
setUp=setUp, tearDown=tearDown,
optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),
))
| [
"[email protected]"
] | |
2a330c17396ee6d12bfa8513bad002fed30eb3aa | d7016f69993570a1c55974582cda899ff70907ec | /sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2021_06_01_preview/aio/operations/_configuration_operations.py | 983de8a70ad7b726dd2c34712f7c3a4f291083eb | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | kurtzeborn/azure-sdk-for-python | 51ca636ad26ca51bc0c9e6865332781787e6f882 | b23e71b289c71f179b9cf9b8c75b1922833a542a | refs/heads/main | 2023-03-21T14:19:50.299852 | 2023-02-15T13:30:47 | 2023-02-15T13:30:47 | 157,927,277 | 0 | 0 | MIT | 2022-07-19T08:05:23 | 2018-11-16T22:15:30 | Python | UTF-8 | Python | false | false | 12,584 | py | # pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import sys
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._configuration_operations import build_get_request, build_patch_request
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ConfigurationOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.eventhub.v2021_06_01_preview.aio.EventHubManagementClient`'s
:attr:`configuration` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@overload
async def patch(
self,
resource_group_name: str,
cluster_name: str,
parameters: _models.ClusterQuotaConfigurationProperties,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.ClusterQuotaConfigurationProperties]:
"""Replace all specified Event Hubs Cluster settings with those contained in the request body.
Leaves the settings not specified in the request body unmodified.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param cluster_name: The name of the Event Hubs Cluster. Required.
:type cluster_name: str
:param parameters: Parameters for creating an Event Hubs Cluster resource. Required.
:type parameters:
~azure.mgmt.eventhub.v2021_06_01_preview.models.ClusterQuotaConfigurationProperties
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ClusterQuotaConfigurationProperties or None or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2021_06_01_preview.models.ClusterQuotaConfigurationProperties or
None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def patch(
self,
resource_group_name: str,
cluster_name: str,
parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> Optional[_models.ClusterQuotaConfigurationProperties]:
"""Replace all specified Event Hubs Cluster settings with those contained in the request body.
Leaves the settings not specified in the request body unmodified.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param cluster_name: The name of the Event Hubs Cluster. Required.
:type cluster_name: str
:param parameters: Parameters for creating an Event Hubs Cluster resource. Required.
:type parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ClusterQuotaConfigurationProperties or None or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2021_06_01_preview.models.ClusterQuotaConfigurationProperties or
None
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def patch(
self,
resource_group_name: str,
cluster_name: str,
parameters: Union[_models.ClusterQuotaConfigurationProperties, IO],
**kwargs: Any
) -> Optional[_models.ClusterQuotaConfigurationProperties]:
"""Replace all specified Event Hubs Cluster settings with those contained in the request body.
Leaves the settings not specified in the request body unmodified.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param cluster_name: The name of the Event Hubs Cluster. Required.
:type cluster_name: str
:param parameters: Parameters for creating an Event Hubs Cluster resource. Is either a
ClusterQuotaConfigurationProperties type or a IO type. Required.
:type parameters:
~azure.mgmt.eventhub.v2021_06_01_preview.models.ClusterQuotaConfigurationProperties or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ClusterQuotaConfigurationProperties or None or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2021_06_01_preview.models.ClusterQuotaConfigurationProperties or
None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2021-06-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2021-06-01-preview")
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.ClusterQuotaConfigurationProperties]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(parameters, (IO, bytes)):
_content = parameters
else:
_json = self._serialize.body(parameters, "ClusterQuotaConfigurationProperties")
request = build_patch_request(
resource_group_name=resource_group_name,
cluster_name=cluster_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.patch.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("ClusterQuotaConfigurationProperties", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("ClusterQuotaConfigurationProperties", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
patch.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}/quotaConfiguration/default"
}
@distributed_trace_async
async def get(
self, resource_group_name: str, cluster_name: str, **kwargs: Any
) -> _models.ClusterQuotaConfigurationProperties:
"""Get all Event Hubs Cluster settings - a collection of key/value pairs which represent the
quotas and settings imposed on the cluster.
:param resource_group_name: Name of the resource group within the azure subscription. Required.
:type resource_group_name: str
:param cluster_name: The name of the Event Hubs Cluster. Required.
:type cluster_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ClusterQuotaConfigurationProperties or the result of cls(response)
:rtype: ~azure.mgmt.eventhub.v2021_06_01_preview.models.ClusterQuotaConfigurationProperties
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2021-06-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2021-06-01-preview")
)
cls: ClsType[_models.ClusterQuotaConfigurationProperties] = kwargs.pop("cls", None)
request = build_get_request(
resource_group_name=resource_group_name,
cluster_name=cluster_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize("ClusterQuotaConfigurationProperties", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/clusters/{clusterName}/quotaConfiguration/default"
}
| [
"[email protected]"
] | |
07f515eae1a86622a522fa62d427c819d880730d | c8efab9c9f5cc7d6a16d319f839e14b6e5d40c34 | /source/All_Solutions/1116.打印零与奇偶数/1116-打印零与奇偶数.py | 6ba403369346dcd95a2fdfe939a07dc70c003e60 | [
"MIT"
] | permissive | zhangwang0537/LeetCode-Notebook | 73e4a4f2c90738dea4a8b77883b6f2c59e02e9c1 | 1dbd18114ed688ddeaa3ee83181d373dcc1429e5 | refs/heads/master | 2022-11-13T21:08:20.343562 | 2020-04-09T03:11:51 | 2020-04-09T03:11:51 | 277,572,643 | 0 | 0 | MIT | 2020-07-06T14:59:57 | 2020-07-06T14:59:56 | null | UTF-8 | Python | false | false | 1,103 | py | import threading
class ZeroEvenOdd:
def __init__(self, n):
self.n = n+1
self.Zero=threading.Semaphore(1)
self.Even=threading.Semaphore(0)
self.Odd=threading.Semaphore(0)
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1,self.n):
self.Zero.acquire()
printNumber(0)
if i%2==1:
self.Odd.release()
else:
self.Even.release()
def even(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1,self.n):
if i%2==0:
self.Even.acquire()
printNumber(i)
self.Zero.release()
def odd(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1,self.n):
if i%2==1:
self.Odd.acquire()
printNumber(i)
self.Zero.release()
| [
"[email protected]"
] | |
c8813dfc6bcc9f3e14517bbb631dad71176f78d9 | 32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd | /benchmark/wikipedia/testcase/interestallcases/testcase6_011_1.py | f8d2461ccd955bd20d8bbd39508574f42faae36b | [] | no_license | Prefest2018/Prefest | c374d0441d714fb90fca40226fe2875b41cf37fc | ac236987512889e822ea6686c5d2e5b66b295648 | refs/heads/master | 2021-12-09T19:36:24.554864 | 2021-12-06T12:46:14 | 2021-12-06T12:46:14 | 173,225,161 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,155 | py | #coding=utf-8
import os
import subprocess
import time
import traceback
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import NoSuchElementException, WebDriverException
desired_caps = {
'platformName' : 'Android',
'deviceName' : 'Android Emulator',
'platformVersion' : '4.4',
'appPackage' : 'org.wikipedia',
'appActivity' : 'org.wikipedia.main.MainActivity',
'resetKeyboard' : True,
'androidCoverage' : 'org.wikipedia/org.wikipedia.JacocoInstrumentation',
'noReset' : True
}
def command(cmd, timeout=5):
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
time.sleep(timeout)
p.terminate()
return
def getElememt(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str)
return element
def getElememtBack(driver, str1, str2) :
for i in range(0, 2, 1):
try:
element = driver.find_element_by_android_uiautomator(str1)
except NoSuchElementException:
time.sleep(1)
else:
return element
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str2)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str2)
return element
def swipe(driver, startxper, startyper, endxper, endyper) :
size = driver.get_window_size()
width = size["width"]
height = size["height"]
try:
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
except WebDriverException:
time.sleep(1)
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
return
def scrollToFindElement(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
swipe(driver, 0.5, 0.6, 0.5, 0.2)
else:
return element
return
def clickoncheckable(driver, str, value = "true") :
parents = driver.find_elements_by_class_name("android.widget.LinearLayout")
for parent in parents:
try :
parent.find_element_by_android_uiautomator(str)
lists = parent.find_elements_by_class_name("android.widget.LinearLayout")
if (len(lists) == 1) :
innere = parent.find_element_by_android_uiautomator("new UiSelector().checkable(true)")
nowvalue = innere.get_attribute("checked")
if (nowvalue != value) :
innere.click()
break
except NoSuchElementException:
continue
# preference setting and exit
try :
os.popen("adb shell svc data diable")
time.sleep(5)
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
os.popen("adb shell am start -n org.wikipedia/org.wikipedia.settings.DeveloperSettingsActivity")
scrollToFindElement(driver, "new UiSelector().text(\"useRestbase_setManually\")").click()
clickoncheckable(driver, "new UiSelector().text(\"useRestbase_setManually\")", "false")
scrollToFindElement(driver, "new UiSelector().text(\"mediaWikiBaseUriSupportsLangCode\")").click()
clickoncheckable(driver, "new UiSelector().text(\"mediaWikiBaseUriSupportsLangCode\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"suppressNotificationPolling\")").click()
clickoncheckable(driver, "new UiSelector().text(\"suppressNotificationPolling\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"memoryLeakTest\")").click()
clickoncheckable(driver, "new UiSelector().text(\"memoryLeakTest\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"readingListsFirstTimeSync\")").click()
clickoncheckable(driver, "new UiSelector().text(\"readingListsFirstTimeSync\")", "false")
driver.press_keycode(4)
time.sleep(2)
os.popen("adb shell am start -n org.wikipedia/org.wikipedia.settings.SettingsActivity")
scrollToFindElement(driver, "new UiSelector().text(\"Download only over Wi-Fi\")").click()
clickoncheckable(driver, "new UiSelector().text(\"Download only over Wi-Fi\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"Show images\")").click()
clickoncheckable(driver, "new UiSelector().text(\"Show images\")", "false")
driver.press_keycode(4)
time.sleep(2)
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
finally :
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"6_011_pre\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
# testcase011
try :
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
element = getElememtBack(driver, "new UiSelector().text(\"Search Wikipedia\")", "new UiSelector().className(\"android.widget.TextView\")")
TouchAction(driver).tap(element).perform()
driver.press_keycode(82)
driver.press_keycode(82)
driver.press_keycode(82)
driver.press_keycode(82)
driver.press_keycode(82)
driver.press_keycode(82)
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageButton\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/menu_overflow_button\").className(\"android.widget.TextView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/menu_overflow_button\").className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
swipe(driver, 0.5, 0.8, 0.5, 0.2)
element = getElememtBack(driver, "new UiSelector().text(\"Explore\")", "new UiSelector().className(\"android.widget.TextView\").instance(4)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/menu_overflow_button\").className(\"android.widget.TextView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/voice_search_button\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Got it\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
else:
print 'OK'
finally:
cpackage = driver.current_package
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"6_011\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
if (cpackage != 'org.wikipedia'):
cpackage = "adb shell am force-stop " + cpackage
os.popen(cpackage)
os.popen("adb shell svc data enable")
| [
"[email protected]"
] | |
9cbf5b6cf37fb49f49e1452747be65c5d74a5e7b | 05887f0f20f3a57c11370021b996d76a56596e5f | /cats/articles/urls.py | ec12a3e5441c566e5a600233b109c2dba9bbd2ea | [] | no_license | kate-ka/cats_backend | 11b5102f0e324713a30747d095291dbc9e194c3a | df19f7bfa4d94bf8effdd6f4866012a0a5302b71 | refs/heads/master | 2020-12-06T16:59:02.713830 | 2017-10-27T09:51:23 | 2017-10-27T09:51:23 | 73,502,091 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 340 | py | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from . views import ArticleList, ArticleDetail
urlpatterns = [
url(r'^api-v1/articles/$', ArticleList.as_view()),
url(r'^api-v1/articles/(?P<pk>[0-9]+)/$', ArticleDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
| [
"[email protected]"
] | |
ea1bcc55cfd8b75317e22e14dd2204cfadba8760 | 413f7768f98f72cef8423c473424d67642f1228f | /examples/10_useful_functions/ex06_enumerate.py | 909474c54cfdc5aacf3c864d87b7e09cc6e3b343 | [] | no_license | easypythoncode/PyNEng | a7bbf09c5424dcd81796f8836509be90c3b1a752 | daaed1777cf5449d5494e5a8471396bbcb027de6 | refs/heads/master | 2023-03-22T01:21:47.250346 | 2022-08-29T18:25:13 | 2022-08-29T18:25:13 | 228,477,021 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 176 | py | from pprint import pprint
with open("config_r1.txt") as f:
for num, line in enumerate(f, 1):
if line.startswith("interface"):
print(num, line, end="")
| [
"[email protected]"
] | |
7391bab13b498877c272f00e6690ce87243867f1 | c85d43dc50c26ea0fa4f81b54fb37460ef6cca8d | /rms/urls.py | e59bd4b9b1b0e2b3f232d4b3be1bab71db14aab9 | [] | no_license | yorong/buzzz-web-dev | c48dbc165d0aa3abce07971a2dee0280f9bf1e92 | 0b74bd1b7cfc7a6a7d61672f930d0bde635b4398 | refs/heads/master | 2021-08-23T02:38:00.544503 | 2017-12-02T16:01:31 | 2017-12-02T16:01:31 | 112,854,877 | 0 | 0 | null | 2017-12-02T15:50:40 | 2017-12-02T15:50:39 | null | UTF-8 | Python | false | false | 281 | py | from django.conf.urls import url
# from django.views.generic.base import RedirectView
from rms.views import (
RMSHomeView,
RMSStartView,
)
urlpatterns = [
url(r'^$', RMSHomeView.as_view(), name='home'),
url(r'^start/$', RMSStartView.as_view(), name='start'),
]
| [
"[email protected]"
] | |
af673f23ff715e728cc51363efba47a00d25983a | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /MxNcFpABB68JCxSwA_21.py | c723eb2ea66a70cd882829dbe3acdcb56347c6b0 | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 109 | py |
def legendre(p, n):
sum = 0
i = 1
while n // p**i >= 1:
sum += n // p**i
i += 1
return sum
| [
"[email protected]"
] | |
f2f5bb2c58b64f25edc908f54fe3891a4afcd5f3 | ec65636f2f0183c43b1ec2eac343b9aa1fc7c459 | /train/abnormal_detection_new/10.8.160.17/sga_shared_pool.py | 8a737bdd656b80792eacc2ff1661d95aec78865d | [] | no_license | tyroarchitect/AIOPs | db5441e5180fcace77b2d1022adb53bbd0b11f23 | 46fe93329a1847efa70e5b73bcbfd54469645cdd | refs/heads/master | 2020-04-16T13:45:02.963404 | 2018-11-15T06:50:57 | 2018-11-15T06:51:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,202 | py | import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# settings of lstm model
timesteps = 20
batch_size = 64
epochs = 5
lstm_size = 30
lstm_layers = 2
filename = "../../../datasets/1-10.8.160.17_20181027_20181109.csv"
model = "../../../model/abnormal_detection_model_new/10.8.160.17/sga_shared_pool_model/SGA_SHARED_POOL_MODEL"
column = "SGA_SHARED_POOL"
start = 207313
end = 224584
class NewData(object):
def __init__(self, filename, column, timesteps, start, end):
self.timesteps = timesteps
self.filename = filename
self.column = column
self.start = start
self.end = end
self.train_x, self.train_y, self.test_x, self.test_y = self.preprocess()
def MaxMinNormalization(self, x, max_value, min_value):
"""
:param x: data
:param max_value: max value in the data
:param min_value: min value in the data
:return: normalization data
"""
x = (x - min_value) / (max_value - min_value)
return x
def generateGroupDataList(self, seq):
"""
:param seq: continuous sequence of value in data
:return: input data array and label data array in the format of numpy
"""
x = []
y = []
for i in range(len(seq) - self.timesteps):
x.append(seq[i: i + self.timesteps])
y.append(seq[i + self.timesteps])
return np.array(x, dtype=np.float32), np.array(y, dtype=np.float32)
def preprocess(self):
"""
:return: training data and testing data of given filename and column
"""
data = pd.read_csv(self.filename)
data = data["VALUE"].values.tolist()
data = data[self.start - 1:self.end]
data = self.MaxMinNormalization(data,
np.max(data, axis=0),
np.min(data, axis=0))
train_x, train_y = self.generateGroupDataList(data)
test_x, test_y = self.generateGroupDataList(data)
return train_x, train_y, test_x, test_y
def getBatches(self, x, y, batch_size):
for i in range(0, len(x), batch_size):
begin_i = i
end_i = i + batch_size if (i + batch_size) < len(x) else len(x)
yield x[begin_i:end_i], y[begin_i:end_i]
def initPlaceholder(timesteps):
x = tf.placeholder(tf.float32, [None, timesteps, 1], name='input_x')
y_ = tf.placeholder(tf.float32, [None, 1], name='input_y')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
return x, y_, keep_prob
def lstm_model(x, lstm_size, lstm_layers, keep_prob):
# define basis structure LSTM cell
def lstm_cell():
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
return drop
# multi layer LSTM cell
cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(lstm_layers)])
# dynamic rnn
outputs, final_state = tf.nn.dynamic_rnn(cell, x, dtype=tf.float32)
# reverse
outputs = outputs[:, -1]
# fully connected
predictions = tf.contrib.layers.fully_connected(outputs, 1, activation_fn=tf.sigmoid)
return predictions
def train_model():
# prepare data
data = NewData(filename=filename, column=column, timesteps=timesteps, start=start, end=end)
# init placeholder
x, y, keep_prob = initPlaceholder(timesteps)
predictions = lstm_model(x,
lstm_size=lstm_size,
lstm_layers=lstm_layers,
keep_prob=keep_prob)
# mse loss function
cost = tf.losses.mean_squared_error(y, predictions)
# optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
tf.add_to_collection("predictions", predictions)
saver = tf.train.Saver()
# define session
gpu_options = tf.GPUOptions(allow_growth=True)
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
tf.global_variables_initializer().run()
# batches counter
iteration = 1
# loop for training
for epoch in range(epochs):
for xs, ys in data.getBatches(data.train_x, data.train_y, batch_size):
feed_dict = {x: xs[:, :, None], y: ys[:, None], keep_prob: .5}
loss, train_step = sess.run([cost, optimizer], feed_dict=feed_dict)
if iteration % 100 == 0:
print('Epochs:{}/{}'.format(epoch, epochs),
'Iteration:{}'.format(iteration),
'Train loss: {}'.format(loss))
iteration += 1
# save model as checkpoint format to optional folder
saver.save(sess, model)
# test model
feed_dict = {x: data.test_x[:, :, None], keep_prob: 1.0}
results = sess.run(predictions, feed_dict=feed_dict)
plt.plot(results, 'r', label='predicted')
plt.plot(data.test_y, 'g--', label='real')
plt.legend()
plt.show()
if __name__ == "__main__":
train_model()
| [
"[email protected]"
] | |
a0b89519a21414737b9664285aa3073dcc619318 | 9ab48ad4a8daf4cab1cdf592bac722b096edd004 | /genutility/fingerprinting.py | b20ca97a8ec9dc1a95e9d6192a517f13f01cf58d | [
"ISC"
] | permissive | Dobatymo/genutility | c902c9b2df8ca615b7b67681f505779a2667b794 | 857fad80f4235bda645e29abbc14f6e94072403b | refs/heads/master | 2023-08-16T18:07:23.651000 | 2023-08-15T19:05:46 | 2023-08-15T19:05:46 | 202,296,877 | 4 | 1 | ISC | 2022-06-14T01:39:53 | 2019-08-14T07:22:23 | Python | UTF-8 | Python | false | false | 4,528 | py | import logging
import numpy as np
from PIL import Image, ImageFilter
# from .numba import opjit
from .numpy import rgb_to_hsi, rgb_to_ycbcr, unblock
# fingerprinting aka perceptual hashing
def phash_antijpeg(image: Image.Image) -> np.ndarray:
"""Source: An Anti-JPEG Compression Image Perceptual Hashing Algorithm
`image` is a RGB pillow image.
"""
raise NotImplementedError
def hu_moments(channels: np.ndarray) -> np.ndarray:
"""Calculates all Hu invariant image moments for all channels separately.
Input array must be of shape [width, height, channels]
Returns shape [moments, channels]
"""
# pre-calculate matrices
n, m, _ = channels.shape
coords_x, coords_y = np.meshgrid(np.arange(m), np.arange(n))
coords_x = np.expand_dims(coords_x, axis=-1) # for batch input, some change is needed here
coords_y = np.expand_dims(coords_y, axis=-1) # for batch input, some change is needed here
def M(p, q):
return np.sum(coords_x**p * coords_y**q * channels, axis=(-2, -3))
def mu(p, q, xb, yb):
return np.sum((coords_x - xb) ** p * (coords_y - yb) ** q * channels, axis=(-2, -3))
def eta(p, q, xb, yb, mu00):
gamma = (p + q) / 2 + 1
return mu(p, q, xb, yb) / mu00**gamma
def loop():
M00 = M(0, 0)
if not np.all(M00 > 0.0):
logging.error("M00: %s", M00)
raise ValueError("Failed to calculate moments. Single color pictures are not supported yet.")
M10 = M(1, 0)
M01 = M(0, 1)
xb = M10 / M00
yb = M01 / M00
mu00 = mu(0, 0, xb, yb)
eta20 = eta(2, 0, xb, yb, mu00)
eta02 = eta(0, 2, xb, yb, mu00)
eta11 = eta(1, 1, xb, yb, mu00)
eta30 = eta(3, 0, xb, yb, mu00)
eta12 = eta(1, 2, xb, yb, mu00)
eta21 = eta(2, 1, xb, yb, mu00)
eta03 = eta(0, 3, xb, yb, mu00)
phi1 = eta20 + eta02
phi2 = (eta20 - eta02) ** 2 + 4 * eta11**2
phi3 = (eta30 - 3 * eta12) ** 2 + (3 * eta21 - eta03) ** 2
phi4 = (eta30 + eta12) ** 2 + (eta21 + eta03) ** 2
phi5 = (eta30 - 3 * eta12) * (eta30 + eta12) * ((eta30 + eta12) ** 2 - 3 * (eta21 + eta03) ** 2) + (
3 * eta21 - eta03
) * (eta21 + eta03) * (3 * (eta30 + eta12) ** 2 - (eta21 + eta03) ** 2)
phi6 = (eta20 - eta02) * ((eta30 + eta12) ** 2 - (eta21 + eta03) ** 2) + 4 * eta11 * (eta30 + eta12) * (
eta21 + eta03
)
phi7 = (3 * eta21 - eta03) * (eta30 + eta12) * ((eta30 + eta12) ** 2 - 3 * (eta21 + eta03) ** 2) - (
eta30 - 3 * eta12
) * (eta21 + eta03) * (3 * (eta30 + eta12) ** 2 - (eta21 + eta03) ** 2)
return np.array([phi1, phi2, phi3, phi4, phi5, phi6, phi7])
return loop()
# @opjit() rgb_to_hsi and rgb_to_ycbcr not supported by numba
def phash_moments_array(arr: np.ndarray) -> np.ndarray:
arr = arr / 255.0
# convert colorspaces
hsi = rgb_to_hsi(arr)
ycbcr = rgb_to_ycbcr(arr) # .astype(np.uint8)
channels = np.concatenate([hsi, ycbcr], axis=-1)
return np.concatenate(hu_moments(channels).T)
def phash_moments(image: Image.Image) -> np.ndarray:
"""Source: Perceptual Hashing for Color Images Using Invariant Moments
`image` is a RGB pillow image. Results should be compared with L^2-Norm of difference vector.
"""
if image.mode != "RGB":
raise ValueError("Only RGB images are supported")
# preprocessing
image = image.resize((512, 512), Image.BICUBIC)
image = image.filter(ImageFilter.GaussianBlur(3))
image = np.array(image)
return phash_moments_array(image)
def phash_blockmean_array(arr: np.ndarray, bits: int = 256) -> np.ndarray:
"""If bits is not a multiple of 8,
the result will be zero padded from the right.
"""
if len(arr.shape) != 2:
raise ValueError("arr must be 2-dimensional")
n = int(np.sqrt(bits))
if n**2 != bits:
raise ValueError("bits must be a square number")
blocks = unblock(arr, n, n)
means = np.mean(blocks, axis=-1)
median = np.median(means)
bools = means >= median
return np.packbits(bools)
def phash_blockmean(image: Image.Image, bits: int = 256, x: int = 256) -> bytes:
"""Source: Block Mean Value Based Image Perceptual Hashing
Method: 1
Metric: 'Bit error rate' (normalized hamming distance)
"""
image = image.convert("L").resize((x, x))
image = np.array(image)
return phash_blockmean_array(image, bits).tobytes()
| [
"[email protected]"
] | |
df66074ddd9a427cb855cccb45608dba94bd3f97 | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_3294.py | 5e9ea46918a4f4b675a7c226efb96d67ef2616ba | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 88 | py | # Piecewise list comprehensions in python
[50 if hasProperty(x) else 10 for x in alist]
| [
"[email protected]"
] | |
b7ed771c6a32261aa34a41a784151e1f35e36ea8 | 01ede4fc2497943cdf64211457338838cca97997 | /DatasetManager/DatasetManager/arrangement/arrangement_statistics.py | f18a60997a7ab7ca3a83dee4b298d13b2924e591 | [] | no_license | qsdfo/orchestration_aws | e317cb55a39789ad270410ba886a42f67e5ce81b | 10ebb1752680b03e88fd08ca0a80e55b1269e8a1 | refs/heads/master | 2021-05-18T03:19:49.562863 | 2020-07-10T10:06:24 | 2020-07-10T10:06:24 | 251,080,622 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,588 | py | import copy
import csv
import os
import shutil
from DatasetManager.arrangement.instrument_grouping import get_instrument_grouping
from DatasetManager.config import get_config
from DatasetManager.arrangement.arrangement_helper import ArrangementIteratorGenerator, note_to_midiPitch, \
separate_instruments_names, OrchestraIteratorGenerator, score_to_pianoroll
import music21
import numpy as np
import json
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
class ComputeStatistics:
def __init__(self, score_iterator, subdivision, savefolder_name, sounding_pitch_boolean=False):
config = get_config()
# Dump folder
self.dump_folder = config['dump_folder']
self.savefolder_name = f'{self.dump_folder}/{savefolder_name}/statistics'
if os.path.isdir(self.savefolder_name):
shutil.rmtree(self.savefolder_name)
os.makedirs(self.savefolder_name)
self.num_bins = 30
# Simplify instrumentation
simplify_instrumentation_path = config['simplify_instrumentation_path']
with open(simplify_instrumentation_path, 'r') as ff:
self.simplify_instrumentation = json.load(ff)
self.instrument_grouping = get_instrument_grouping()
# Histogram with range of notes per instrument
self.tessitura = dict()
# Histogram with number of simultaneous notes
self.simultaneous_notes = dict()
# Histogram with the number of simultaneous notes per instrument
self.stat_dict = dict()
# Other stuffs used for parsing
self.score_iterator = score_iterator
self.subdivision = subdivision
self.sounding_pitch_boolean = sounding_pitch_boolean
# Write out paths here
self.simultaneous_notes_details_path = f'{self.savefolder_name}/simultaneous_notes_details.txt'
open(self.simultaneous_notes_details_path, 'w').close()
if self.sounding_pitch_boolean:
self.tessitura_path = f'{self.savefolder_name}/tessitura_sounding'
else:
self.tessitura_path = f'{self.savefolder_name}/tessitura'
if os.path.isdir(self.tessitura_path):
shutil.rmtree(self.tessitura_path)
os.makedirs(self.tessitura_path)
return
def get_statistics(self):
for arrangement_pair in self.score_iterator():
if arrangement_pair is None:
continue
# Orchestra scores
self.histogram_tessitura(arrangement_pair['Orchestra'])
self.counting_simultaneous_notes(arrangement_pair['Orchestra'], True)
self.counting_simultaneous_notes(arrangement_pair['Piano'], False)
# Get reference tessitura for comparing when plotting
with open('reference_tessitura.json') as ff:
reference_tessitura = json.load(ff)
reference_tessitura = {
k: (note_to_midiPitch(music21.note.Note(v[0])), note_to_midiPitch(music21.note.Note(v[1]))) for
k, v in reference_tessitura.items()}
stats = []
this_stats = {}
for instrument_name, histogram in self.tessitura.items():
# Plot histogram for each instrument
x = range(128)
y = list(histogram.astype(int))
plt.clf()
plt.bar(x, y)
plt.xlabel('Notes', fontsize=8)
plt.ylabel('Frequency', fontsize=8)
plt.title(instrument_name, fontsize=10)
plt.xticks(np.arange(0, 128, 1))
# Add reference tessitura
if instrument_name != "Remove":
min_ref, max_ref = reference_tessitura[instrument_name]
else:
min_ref = 0
max_ref = 128
x = range(min_ref, max_ref)
y = [0 for _ in range(len(x))]
plt.plot(x, y, 'ro')
plt.savefig(f'{self.tessitura_path}/{instrument_name}_tessitura.pdf')
# Write stats in txt file
total_num_notes = histogram.sum()
non_zero_indices = np.nonzero(histogram)[0]
lowest_pitch = non_zero_indices.min()
highest_pitch = non_zero_indices.max()
this_stats = {
'instrument_name': instrument_name,
'total_num_notes': total_num_notes,
'lowest_pitch': lowest_pitch,
'highest_pitch': highest_pitch
}
stats.append(this_stats)
# Write number of co-occuring notes
with open(f'{self.savefolder_name}/simultaneous_notes.txt', 'w') as ff:
for instrument_name, simultaneous_counter in self.simultaneous_notes.items():
ff.write(f"## {instrument_name}\n")
for ind, simultaneous_occurences in enumerate(list(simultaneous_counter)):
ff.write(' {:d} : {:d}\n'.format(ind, int(simultaneous_occurences)))
with open(f'{self.savefolder_name}/statistics.csv', 'w') as ff:
fieldnames = this_stats.keys()
writer = csv.DictWriter(ff, fieldnames=fieldnames, delimiter=";")
writer.writeheader()
for this_stats in stats:
writer.writerow(this_stats)
def histogram_tessitura(self, score):
# Transpose to sounding pitch ?
if self.sounding_pitch_boolean:
if score.atSoundingPitch != 'unknown':
score_processed = score.toSoundingPitch()
else:
score_processed = score
for part in score_processed.parts:
instrument_names = [self.instrument_grouping[e] for e in
separate_instruments_names(self.simplify_instrumentation[part.partName])]
for instrument_name in instrument_names:
part_flat = part.flat
histogram = music21.graph.plot.HistogramPitchSpace(part_flat)
histogram.extractData()
histogram_data = histogram.data
for (pitch, frequency, _) in histogram_data:
if instrument_name not in self.tessitura:
self.tessitura[instrument_name] = np.zeros((128,))
self.tessitura[instrument_name][int(pitch)] += frequency
return
def counting_simultaneous_notes(self, score, orchestra_flag):
if orchestra_flag:
pr, onsets, _ = score_to_pianoroll(
score,
self.subdivision,
self.simplify_instrumentation,
self.instrument_grouping,
self.sounding_pitch_boolean)
else:
pr, onsets, _ = score_to_pianoroll(
score,
self.subdivision,
None,
self.instrument_grouping,
self.sounding_pitch_boolean)
with open(self.simultaneous_notes_details_path, 'a') as ff:
ff.write(f'##### {score.filePath}\n')
for instrument_name, this_pr in pr.items():
# binarize
this_pr_bin = np.where(this_pr > 0, 1, 0)
# flatten
this_pr_flat = this_pr_bin.sum(1)
# Update simultaneous notes counter
if instrument_name not in self.simultaneous_notes.keys():
self.simultaneous_notes[instrument_name] = np.zeros((self.num_bins,))
histo, _ = np.histogram(this_pr_flat, bins=range(self.num_bins+1), range=range(self.num_bins+1))
self.simultaneous_notes[instrument_name] = self.simultaneous_notes[instrument_name] + histo
return
if __name__ == '__main__':
database_path = '/home/leo/Recherche/Databases/Orchestration/arrangement/'
subsets = [
# 'bouliane',
# 'hand_picked_Spotify',
# 'imslp',
'liszt_classical_archives'
]
score_iterator = ArrangementIteratorGenerator(
arrangement_path=database_path,
subsets=subsets
)
savefolder_name = 'liszt_beethov'
# database_path = '/home/leo/Recherche/Databases/Orchestration/orchestral/'
# subsets = [
# 'kunstderfuge'
# ]
# score_iterator = OrchestraIteratorGenerator(
# folder_path=database_path,
# subsets=subsets,
# process_file=True
# )
# savefolder_name = 'kunst_orchestral'
simplify_instrumentation_path = 'simplify_instrumentation.json'
sounding_pitch_boolean = True
subdivision = 4
computeStatistics = ComputeStatistics(score_iterator, subdivision, savefolder_name, sounding_pitch_boolean)
computeStatistics.get_statistics()
| [
"[email protected]"
] | |
550b55101c715dd350fa5cd27249306a0f72db95 | aea7bbe854591f493f4a37919eb75dde7f2eb2ca | /startCamp/03_day/flask/intro/function.py | f11de57476cf04f3c28b5c8018c3382bdd7abb9c | [] | no_license | GaYoung87/StartCamp | 6e31a50d3037174b08a17114e467989520bb9a86 | 231b1fd0e245acb5d4570778aa41de79d6ad4b17 | refs/heads/master | 2020-06-17T11:52:38.256085 | 2019-07-12T01:14:47 | 2019-07-12T01:14:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 167 | py | # sum이라는 함수를 정의
def sum(num1, num2): # 숫자 num1, num2라는 인자를 받는 함수
return num1 + num2
result = sum(5, 6)
print(result)
| [
"[email protected]"
] | |
5a2524a0bd81ae136a6c230538fb8c7985d95562 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/p3BR/R2/benchmark/startCirq330.py | 74d7d9238c53332a3cb7ad0438bb8c452fc6d169 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,271 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=3
# total number=66
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for the rotation angles in the QAOA circuit.
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[2])) # number=38
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=39
c.append(cirq.H.on(input_qubit[2])) # number=40
c.append(cirq.H.on(input_qubit[2])) # number=59
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=60
c.append(cirq.H.on(input_qubit[2])) # number=61
c.append(cirq.H.on(input_qubit[2])) # number=42
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=43
c.append(cirq.H.on(input_qubit[2])) # number=44
c.append(cirq.H.on(input_qubit[2])) # number=48
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=49
c.append(cirq.H.on(input_qubit[2])) # number=50
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=54
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=63
c.append(cirq.X.on(input_qubit[2])) # number=64
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=65
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=56
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=47
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=37
c.append(cirq.H.on(input_qubit[2])) # number=51
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=52
c.append(cirq.H.on(input_qubit[2])) # number=53
c.append(cirq.H.on(input_qubit[2])) # number=25
c.append(cirq.CZ.on(input_qubit[0],input_qubit[2])) # number=26
c.append(cirq.H.on(input_qubit[2])) # number=27
c.append(cirq.H.on(input_qubit[1])) # number=7
c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=8
c.append(cirq.rx(0.17592918860102857).on(input_qubit[2])) # number=34
c.append(cirq.rx(-0.3989822670059037).on(input_qubit[1])) # number=30
c.append(cirq.H.on(input_qubit[1])) # number=9
c.append(cirq.H.on(input_qubit[1])) # number=18
c.append(cirq.rx(2.3310617489636263).on(input_qubit[2])) # number=58
c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=19
c.append(cirq.H.on(input_qubit[1])) # number=20
c.append(cirq.X.on(input_qubit[1])) # number=62
c.append(cirq.Y.on(input_qubit[1])) # number=14
c.append(cirq.H.on(input_qubit[1])) # number=22
c.append(cirq.CZ.on(input_qubit[2],input_qubit[1])) # number=23
c.append(cirq.rx(-0.9173450548482197).on(input_qubit[1])) # number=57
c.append(cirq.H.on(input_qubit[1])) # number=24
c.append(cirq.Z.on(input_qubit[2])) # number=3
c.append(cirq.Z.on(input_qubit[1])) # number=41
c.append(cirq.X.on(input_qubit[1])) # number=17
c.append(cirq.Y.on(input_qubit[2])) # number=5
c.append(cirq.X.on(input_qubit[2])) # number=21
c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=15
c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=16
c.append(cirq.X.on(input_qubit[2])) # number=28
c.append(cirq.X.on(input_qubit[2])) # number=29
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq330.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"[email protected]"
] | |
7354bef465760c7821f2382d875c71a979be9fd7 | 332cceb4210ff9a5d99d2f3a65a704147edd01a2 | /justext/utils.py | 42e5074ec56396d742d4234e9106a0655e9de958 | [] | permissive | miso-belica/jusText | 16e5befcb449d3939ce62dc3460afbc768bd07cc | 22a59079ea691d67e2383039cf5b40d490420115 | refs/heads/main | 2023-08-30T03:48:27.225553 | 2023-01-24T08:45:58 | 2023-01-24T08:45:58 | 8,121,947 | 527 | 70 | BSD-2-Clause | 2022-05-04T06:11:47 | 2013-02-10T11:42:20 | Python | UTF-8 | Python | false | false | 1,965 | py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import re
import os
import sys
import pkgutil
MULTIPLE_WHITESPACE_PATTERN = re.compile(r"\s+", re.UNICODE)
def normalize_whitespace(text):
"""
Translates multiple whitespace into single space character.
If there is at least one new line character chunk is replaced
by single LF (Unix new line) character.
"""
return MULTIPLE_WHITESPACE_PATTERN.sub(_replace_whitespace, text)
def _replace_whitespace(match):
"""Normalize all spacing characters that aren't a newline to a space."""
text = match.group()
return "\n" if "\n" in text or "\r" in text else " "
def is_blank(string):
"""
Returns `True` if string contains only white-space characters
or is empty. Otherwise `False` is returned.
"""
return not string or string.isspace()
def get_stoplists():
"""Returns a collection of built-in stop-lists."""
path_to_stoplists = os.path.dirname(sys.modules["justext"].__file__)
path_to_stoplists = os.path.join(path_to_stoplists, "stoplists")
stoplist_names = []
for filename in os.listdir(path_to_stoplists):
name, extension = os.path.splitext(filename)
if extension == ".txt":
stoplist_names.append(name)
return frozenset(stoplist_names)
def get_stoplist(language):
"""Returns an built-in stop-list for the language as a set of words."""
file_path = os.path.join("stoplists", "%s.txt" % language)
try:
stopwords = pkgutil.get_data("justext", file_path)
except IOError:
raise ValueError(
"Stoplist for language '%s' is missing. "
"Please use function 'get_stoplists' for complete list of stoplists "
"and feel free to contribute by your own stoplist." % language
)
return frozenset(w.decode("utf8").lower() for w in stopwords.splitlines())
| [
"[email protected]"
] | |
8e17f0a7737a188114983caa8fd0c1b8ec4af73e | ad6c519f356c0c49eb004084b12b5f08e3cd2e9e | /contrib/compile_po_files.py | 1456bab6925d5b04a85ff3269ef94c187c334a03 | [
"MIT"
] | permissive | csilvers/kake | 1a773e7c2232ea243be256bb5e6bd92e0189db9d | 51465b12d267a629dd61778918d83a2a134ec3b2 | refs/heads/master | 2021-05-05T23:07:40.425063 | 2019-01-23T23:35:48 | 2019-01-23T23:35:48 | 116,594,798 | 0 | 0 | MIT | 2019-01-23T23:19:17 | 2018-01-07T19:59:09 | Python | UTF-8 | Python | false | false | 17,080 | py | # TODO(colin): fix these lint errors (http://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes)
# pep8-disable:E128
"""Converts translation (.po) files to the format we use internally.
Most people convert .po files to .mo files and use the standard
library gettext module to use the translation data. But not us. For
reasons of efficiency -- both time and space -- we use our own file
format which is basically a pickled dict. This converts the .po files
to our new file format.
"""
from __future__ import absolute_import
import md5
import os
import shutil
import sys
import shared.util.thread
import ka_globals
from kake.lib import compile_rule
from kake.lib import computed_inputs
from kake.lib import log
class NoSuchLocaleCompileFailure(compile_rule.BadRequestFailure):
"""Raised when GCS does not contain translations for the requested locale.
When Google Cloud Storage (GCS) does not contain translations for a
requested locale, this failure should be negatively cached to avoid
re-requesting the same index over and over again.
This failure is only raised on the dev-appserver, NOT on Jenkins.
"""
def __init__(self, locale):
super(NoSuchLocaleCompileFailure, self).__init__(
"The index for the '%s' locale is not present on "
"Google Cloud Storage." % (locale))
class FetchFileFromS3(compile_rule.CompileBase):
"""If the po-file is stored on S3, retrieve it from there.
PO files have traditionally been checked into source control
(github.com:Khan/webapp-i18n). But a more modern approach has
been to store those files remotely on S3, and only store the
s3-file name in source control. We use the 'git bigfile'
extension to control this. This compile rule deals with both
cases: just copying the file in the first case and downloading
from S3 in the second.
"""
def version(self):
"""Update every time build() changes in a way that affects output."""
return 1
@staticmethod
def _munge_sys_path():
"""Modify sys.path so we can load the git-bigfile library."""
# First, find out where git-bigfile lives. It lives on the
# path, so we can just look for that.
for pathdir in os.environ['PATH'].split(':'):
if os.path.exists(os.path.join(pathdir, 'git-bigfile')):
sys.path.append(os.path.dirname(pathdir))
return
raise compile_rule.CompileFailure(
"Can't find git-bigfile in %s" % os.environ['PATH'])
@staticmethod
def _download_from_s3(gitbigfile_module, outfile_abspath, sha):
s3_fetcher = gitbigfile_module.GitBigfile().transport()
log.v2('Downloading s3://%s/%s to %s' % (
s3_fetcher.bucket.name, sha, outfile_abspath + '.tmp'))
s3_fetcher.get(sha, outfile_abspath + '.tmp')
# Make sure we don't create the 'real' file until it's fully
# downloaded.
try:
os.unlink(outfile_abspath)
except (IOError, OSError):
pass # probably "file not found"
try:
os.rename(outfile_abspath + '.tmp', outfile_abspath)
except OSError:
log.v1('Error fetching %s' % outfile_abspath)
raise
def build_many(self, outfile_infiles_changed_context):
from shared.testutil import fake_datetime
sha_to_files = {} # for the files we need to get from S3
for (outfile, infiles, _, context) in outfile_infiles_changed_context:
assert len(infiles) == 1, infiles
assert infiles[0].startswith('intl/translations/')
with open(self.abspath(infiles[0])) as f:
head = f.read(64).strip()
# Does the head look like a sha1? (sha1's are only 40 bytes.)
# If so, store it for later. If not, take care of it now.
if head.strip('0123456789abcdefABCDEF') == '':
sha_to_files.setdefault(head, []).append(outfile)
else:
# Nope, not a sha1. NOTE: We could also use a hard-link,
# but that could fail if genfiles is on a different
# filesystem from the source. Copying is more expensive
# but safer. Symlinks are right out.
shutil.copyfile(self.abspath(infiles[0]),
self.abspath(outfile))
if not sha_to_files:
return
# We could just call 'git bigfile pull' but we purposefully
# don't so as to leave untouched the file-contents in
# intl/translations. This works better with kake, which
# doesn't like it when input contents change as part of a kake
# rule.
self._munge_sys_path() # so the following import succeeds
import gitbigfile.command
# Download all our files from S3 in parallel. We store these
# files under a 'permanent' name based on the sha1. (Later
# we'll copy these files to outfile_name.) That way even if
# you check out a different branch and come back to this one
# again, you can get the old contents without needing to
# revisit S3.
# GitBigfile() (in _download_from_s3) runs 'git' commands in a
# subprocess, so we need to be in the right repository for that.
old_cwd = os.getcwd()
os.chdir(self.abspath('intl/translations'))
try:
# This will actually try to download translation files via
# bigfile. This requires a real datetime for making the
# api requests to S3 (S3 complains about weird dates).
with fake_datetime.suspend_fake_datetime():
arglists = []
for (sha, outfiles) in sha_to_files.iteritems():
# Typically a given sha will have only one outfile,
# but for some shas (an empty po-file, e.g.), many
# outfiles may share the same sha!
log.v1('Fetching %s from S3' % ' '.join(outfiles))
# We just need to put this in a directory we know we
# can write to: take one of the outfile dirs arbitrarily.
sha_name = os.path.join(os.path.dirname(outfiles[0]), sha)
arglists.append(
(gitbigfile.command, self.abspath(sha_name), sha))
shared.util.thread.run_many_threads(
self._download_from_s3, arglists)
except RuntimeError as why:
log.error(why) # probably misleading, but maybe helpful
# TODO(csilvers): check whether git-bigfile *is* set up
# correctly, and give a more precise failure message if so.
raise compile_rule.CompileFailure(
"Failed to download translation file for %s from S3. "
"Make sure you have git-bigfile set up as per the "
"configs in the khan-dotfiles repo: namely, the "
"'bigfile' section in .gitconfig.khan, and the "
"update_credentials() section in setup.sh." % outfile)
finally:
os.chdir(old_cwd)
# Now copy from the sha-name to the actual output filename.
for (sha, outfiles) in sha_to_files.iteritems():
sha_name = os.path.join(os.path.dirname(outfiles[0]), sha)
for outfile in outfiles:
log.v2('Copying from %s to %s' % (sha_name, outfile))
try:
os.unlink(self.abspath(outfile))
except OSError:
pass # probably file not found
os.link(self.abspath(sha_name), self.abspath(outfile))
def num_outputs(self):
"""We limit how many parallel fetches we do so we don't overload S3."""
return 50
# This is only used on the dev-appserver, NOT on Jenkins (or else we'd never
# update the indices!)
class DownloadIndex(compile_rule.CompileBase):
def __init__(self):
super(DownloadIndex, self).__init__()
self._locale_paths = None
def version(self):
"""Update every time build() changes in a way that affects output."""
import datetime
# Force redownloading once a month.
return datetime.datetime.now().strftime("%Y-%m")
def build(self, outfile_name, infile_names, changed, context):
"""Download .index and .chunk files from prod.
CompilePOFile takes a long time to compute. So when not on jenkins we
call this rule instead to fetch from prod what is there.
"""
if self._locale_paths is None:
self._init_locale_paths()
log.v2("Determining latest prod translation files for %s" %
context['{lang}'])
locale = context['{lang}']
locale_path = 'gs://ka_translations/%s/' % locale
if locale_path not in self.locale_paths:
raise NoSuchLocaleCompileFailure(locale)
try:
stdout = self.call_with_output(['gsutil', 'ls', locale_path])
except compile_rule.CompileFailure, e:
# TODO(james): make sure we download gcloud and gsutil as part
# of the khan-dotfiles setup.
raise compile_rule.CompileFailure(
"%s.\nFailed to download translations from gcs. Make sure "
"that you have gsutil installed via gcloud." % e)
dirs = stdout.split()
if dirs:
most_recent_dir = dirs[-1]
log.v2("Downloading latest prod files from %s" %
most_recent_dir)
self.call(
['gsutil', '-m', 'cp', '-r', "%s*" % most_recent_dir,
os.path.dirname(outfile_name)])
return
# No translation files found on gcs ... lets complain
raise compile_rule.CompileFailure(
"Failed to find translation files for %s on gcs" %
context['{lang}'])
def _init_locale_paths(self):
try:
self.locale_paths = self.call_with_output(
['gsutil', 'ls', 'gs://ka_translations']).split()
except compile_rule.CompileFailure, e:
raise compile_rule.CompileFailure(
"%s.\nFailed to download translations from gcs. Make sure "
"that you have gsutil installed via gcloud." % e)
class CompilePOFile(compile_rule.CompileBase):
def version(self):
"""Update every time build() changes in a way that affects output."""
return 9
def build(self, outfile_name, infile_names, changed, context):
"""Merge the pofiles and approved pofiles & build pickle and chunks.
We export from crowdin twice for each language. One time to get all the
translated strings which winds up in
intl/translation/pofile/{lang}.(rest|datastore).po files and another
time to get just the approved translations which winds up in the
intl/translation/approved_pofile/{lang}.(rest|datastore).po files. This
merges them all together, preferring an entry in the approved pofile
over the unapproved one, and adding a flag to the approved entries. We
then create our own specially formatted files that use less space.
There is the genfiles/translations/{lang}/index.pickle that gets
created, and a bunch of genfiles/translations/{lang}/chunk.# files that
the index file points to and holds the actual translations.
"""
# We import here so the kake system doesn't require these
# imports unless they're actually used.
import intl.translate
from intl import polib_util
full_content = ''
for infile in sorted([n for n in infile_names
if "approved_pofiles" not in n]):
with open(self.abspath(infile)) as f:
log.v3("Reading %s" % infile)
full_content += f.read()
approved_full_content = ''
for infile in sorted([n for n in infile_names
if "approved_pofiles" in n]):
with open(self.abspath(infile)) as f:
log.v3("Reading %s" % infile)
approved_full_content += f.read()
log.v3("Calculating md5 to get translation file version for %s" %
context['{lang}'])
# The output files need a version string. We'll use an
# md5sum of the input files.
version_md5sum = md5.new(
full_content + approved_full_content).hexdigest()
version = 'compile_po_%s' % version_md5sum
translate_writer = intl.translate.TranslateWriter(
os.path.dirname(outfile_name), context['{lang}'], version)
# Now lets combine the two po files and add a flag to the approved
# pofile entries.
log.v3("Creating .index and .chunk translation files for %s" %
context['{lang}'])
approved_msgids = set()
def add_approved_entry(po_entry):
po_entry.flags.append('approved')
approved_msgids.add(po_entry.msgid)
translate_writer.add_poentry(po_entry)
def add_unapproved_entry(po_entry):
if po_entry.msgid not in approved_msgids:
translate_writer.add_poentry(po_entry)
_ = polib_util.streaming_pofile(
approved_full_content.decode('utf-8'),
callback=add_approved_entry) # called on each input POEntry.
unapproved_pofile = polib_util.streaming_pofile(
full_content.decode('utf-8'),
callback=add_unapproved_entry)
# This adds in the metadata (and only the metadata).
translate_writer.add_pofile(unapproved_pofile)
translate_writer.commit()
class IntlToGenfiles(computed_inputs.ComputedInputsBase):
"""Replace intl/translations/pofile/glob with genfiles/translations...
This is because we want to read files from the
genfiles/translations/pofiles/ directory, but can't do a glob in
that directory because it holds generated files. Luckily there's
a 1-to-1 correspondence between files in the intl/ directory and
in the genfiles/ directory, so we can say what the list of files
in genfiles/translations/pofiles will be.
"""
def version(self):
"""Update if input_patterns() changes in a way that affects output."""
return 1
def input_patterns(self, outfile_name, context, triggers, changed):
return [x.replace('intl/', 'genfiles/') for x in triggers]
# "Expand" the intl/translations file if it's being stored as a sha1
# for use by 'git bigfile'.
# NOTE: Changing git branches can cause intl/translations timestamps
# to change. Since a changed .po file causes every single file in
# that language to get recompiled -- expensive! -- it's worth it to
# depend on crc's rather than just timestamps for these files.
compile_rule.register_compile(
'EXPAND PO-FILE',
'genfiles/translations/pofiles/{{path}}',
['intl/translations/pofiles/{{path}}'],
FetchFileFromS3(),
compute_crc=True)
# Also "expand" approved_pofiles with git bigfile.
compile_rule.register_compile(
'EXPAND APPROVED PO-FILES',
'genfiles/translations/approved_pofiles/{{path}}',
['intl/translations/approved_pofiles/{{path}}'],
FetchFileFromS3(),
compute_crc=True)
# (This isn't really po-file-related, but it's about expanding: these
# are the other types of translation files that are stored in S3.)
compile_rule.register_compile(
'EXPAND PICKLE-FILE',
'genfiles/translations/{{path}}.pickle',
['intl/translations/{{path}}.pickle'],
FetchFileFromS3(),
compute_crc=True)
# In addition to index.pickle, this will also create all the chunk.# files.
if ka_globals.is_on_jenkins:
compile_rule.register_compile(
'DEPLOYED TRANSLATIONS',
'genfiles/translations/{lang}/index.pickle',
# This allows for .po files being split up (to get under github
# filesize limits: foo.po, foo.po.2, foo.po.3, etc.)
# We fetch the actual files from
# genfiles/translations/combined_pofiles,
# but there's a 1-to-1 relationship between those files and the
# ones in intl/translations/pofiles.
IntlToGenfiles(['intl/translations/pofiles/{lang}.*',
'intl/translations/approved_pofiles/{lang}.*']),
CompilePOFile())
else:
# If not on jenkins (ie. dev server) we do not build this file
# ourselves as it is very expensive to compute and instead download
# it from prod. It's most likely fine to use out of date data, so we
# don't rebuild on any inputs at all, but instead increase the version once
# a month. If a dev wanted a newer datastore sooner, they need to run:
# make sync_prod_translations LANGS=<lang>
compile_rule.register_compile(
'DOWNLOAD PROD TRANSLATIONS',
'genfiles/translations/{lang}/index.pickle',
[],
DownloadIndex())
| [
"[email protected]"
] | |
e42abe3c8e78b1c9969be47b78657894ae274870 | 351fa4edb6e904ff1ac83c6a790deaa7676be452 | /graphs/graphUtil/graphAdjMat.py | a8211d8ac10c6c16d87eb91ba14de7aa24570e2a | [
"MIT"
] | permissive | shahbagdadi/py-algo-n-ds | 42981a61631e1a9af7d5ac73bdc894ac0c2a1586 | f3026631cd9f3c543250ef1e2cfdf2726e0526b8 | refs/heads/master | 2022-11-27T19:13:47.348893 | 2022-11-14T21:58:51 | 2022-11-14T21:58:51 | 246,944,662 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,664 | py | from typing import List
from collections import deque
from collections import defaultdict
# A class to represent a graph. A graph
# is the list of the adjacency Matrix.
# Size of the array will be the no. of the
# vertices "V"
class Graph:
def __init__(self, vertices, directed=True):
self.V = vertices
self.adjMatrix = []
self.directed = directed
for i in range(self.V):
self.adjMatrix.append([0 for i in range(self.V)])
# Function to add an edge in an undirected graph
def add_edge(self, src, dest):
if src == dest:
print(f"Same vertex {src} and {dest}")
self.adjMatrix[src][dest] = 1
if not self.directed:
self.adjMatrix[dest][src] = 1
# Function to print the graph adj list
def print_adj_list(self):
for k in self.graph.keys():
print(f"Adjacency list of vertex {k}\n {k}", end="")
for n in self.graph[k]:
print(f" -> {n}", end="")
print(" \n")
def print_adj_mat(self):
print(self.adjMatrix)
# Breadth First Traversal of graph
def BFS(self, root):
q = deque([root])
visited = set([root])
while q:
node = q.pop()
print(f'{node} => ', end="")
for i, child in enumerate(self.adjMatrix[node]):
if child == 1 and i not in visited:
visited.add(i)
q.appendleft(i)
g = Graph(5, True)
g.add_edge(0, 1)
g.add_edge(0, 4)
g.add_edge(1, 4)
g.add_edge(1, 3)
g.add_edge(1, 2)
g.add_edge(2, 3)
g.print_adj_mat()
print('====== BFS =====')
g.BFS(0)
print('\n')
| [
"[email protected]"
] | |
1326a2e287de4aba98c8281869940dc914c7ec24 | 7db575150995965b0578f3b7c68567e07f5317b7 | /tr2/models/transformer.py | f3799d94287770125fd19476f059cc6c49ce70a5 | [] | no_license | anhdhbn/thesis-tr2 | b14049cc3de517cdd9205239e4cf3d225d168e85 | 7a74bb1228f5493b37934f38a8d3e1ab5328fc3c | refs/heads/master | 2023-03-27T21:51:57.763495 | 2021-02-26T12:51:20 | 2021-02-26T12:51:20 | 338,924,981 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,876 | py | import torch
import torch.nn as nn
from torch import Tensor
from tr2.models.encoder import TransformerEncoder, TransformerEncoderLayer
from tr2.models.decoder import TransformerDecoder, TransformerDecoderLayer
class Transformer(nn.Module):
def __init__(self,
hidden_dims=512,
num_heads = 8,
num_encoder_layer=6,
num_decoder_layer=6,
dim_feed_forward=2048,
dropout=.1
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
hidden_dims=hidden_dims,
num_heads=num_heads,
dropout=dropout,
dim_feedforward=dim_feed_forward
)
self.encoder = TransformerEncoder(
encoder_layer=encoder_layer,
num_layers=num_encoder_layer
)
decoder_layer = TransformerDecoderLayer(
hidden_dims=hidden_dims,
num_heads=num_heads,
dropout=dropout,
dim_feedforward=dim_feed_forward
)
decoder_layer2 = TransformerDecoderLayer(
hidden_dims=hidden_dims,
num_heads=num_heads,
dropout=dropout,
dim_feedforward=dim_feed_forward
)
self.decoder = TransformerDecoder(decoder_layer=decoder_layer, num_layers=num_decoder_layer)
self.decoder2 = TransformerDecoder(decoder_layer=decoder_layer2, num_layers=num_decoder_layer)
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def forward(self, template: Tensor, mask_template: Tensor, pos_template: Tensor,
search: Tensor, mask_search: Tensor, pos_search:Tensor) -> Tensor:
"""
:param src: tensor of shape [batchSize, hiddenDims, imageHeight // 32, imageWidth // 32]
:param mask: tensor of shape [batchSize, imageHeight // 32, imageWidth // 32]
Please refer to detr.py for more detailed description.
:param query: object queries, tensor of shape [numQuery, hiddenDims].
:param pos: positional encoding, the same shape as src.
:return: tensor of shape [batchSize, num_decoder_layer * WH, hiddenDims]
"""
# flatten NxCxHxW to HWxNxC
bs, c, h, w = search.shape
template = template.flatten(2).permute(2, 0, 1) # HWxNxC
search = search.flatten(2).permute(2, 0, 1) # HWxNxC
mask_template = mask_template.flatten(1) # NxHW
mask_search = mask_search.flatten(1) # NxHW
pos_template = pos_template.flatten(2).permute(2, 0, 1) # HWxNxC
pos_search = pos_search.flatten(2).permute(2, 0, 1) # HWxNxC
memory = self.encoder(template, src_key_padding_mask=mask_template, pos=pos_template)
out = self.decoder(search, memory, memory_key_padding_mask=mask_template, pos_template=pos_template, pos_search=pos_search, tgt_key_padding_mask=mask_search) # num_decoder_layer x WH x N x C
out2 = self.decoder2(search, memory, memory_key_padding_mask=mask_template, pos_template=pos_template, pos_search=pos_search, tgt_key_padding_mask=mask_search) # num_decoder_layer x WH x N x C
return out.transpose(1, 2), out2.transpose(1, 2)
def init(self, template, mask_template, pos_template):
template = template.flatten(2).permute(2, 0, 1) # HWxNxC
mask_template = mask_template.flatten(1) # NxHW
pos_template = pos_template.flatten(2).permute(2, 0, 1) # HWxNxC
return self.encoder(template, src_key_padding_mask=mask_template, pos=pos_template)
def track(self, memory, mask_template, pos_template, search, mask_search, pos_search):
search = search.flatten(2).permute(2, 0, 1) # HWxNxC
mask_template = mask_template.flatten(1) # NxHW
mask_search = mask_search.flatten(1) # NxHW
pos_template = pos_template.flatten(2).permute(2, 0, 1) # HWxNxC
pos_search = pos_search.flatten(2).permute(2, 0, 1) # HWxNxC
out = self.decoder(search, memory, memory_key_padding_mask=mask_template, pos_template=pos_template, pos_search=pos_search, tgt_key_padding_mask=mask_search)
out2 = self.decoder2(search, memory, memory_key_padding_mask=mask_template, pos_template=pos_template, pos_search=pos_search, tgt_key_padding_mask=mask_search)
return out.transpose(1, 2), out2.transpose(1, 2)
def build_transformer(
hidden_dims=512,
num_heads = 8,
num_encoder_layer=6,
num_decoder_layer=6,
dim_feed_forward=2048,
dropout=.1
):
return Transformer(hidden_dims=hidden_dims,
num_heads = num_heads,
num_encoder_layer = num_encoder_layer,
num_decoder_layer = num_decoder_layer,
dim_feed_forward = dim_feed_forward,
dropout=dropout
) | [
"[email protected]"
] | |
70b347db5fcd769831550b3fecad4822d3c19ea2 | fe9573bad2f6452ad3e2e64539361b8bc92c1030 | /Socket_programming/TLS_server.py | 846eac13cb9e9873d922eb3e035275be919fb72a | [] | no_license | OceanicSix/Python_program | e74c593e2e360ae22a52371af6514fcad0e8f41f | 2716646ce02db00306b475bad97105b260b6cd75 | refs/heads/master | 2022-01-25T16:59:31.212507 | 2022-01-09T02:01:58 | 2022-01-09T02:01:58 | 149,686,276 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,090 | py | #!/usr/bin/python3
import socket, ssl, pprint
html = """
HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n
<!DOCTYPE html><html><body><h1>This is Bank32.com!</h1></body></html>
"""
SERVER_CERT = './certs/mycert.crt'
SERVER_PRIVATE = './certs/mycert.key'
# context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) # For Ubuntu 20.04 VM
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) # For Ubuntu 16.04 VM
context.load_cert_chain(SERVER_CERT, SERVER_PRIVATE)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.bind(('0.0.0.0', 4433))
sock.listen(5)
while True:
newsock, fromaddr = sock.accept()
try:
ssock = context.wrap_socket(newsock, server_side=True)
print("TLS connection established")
data = ssock.recv(1024) # Read data over TLS
pprint.pprint("Request: {}".format(data))
ssock.sendall(html.encode('utf-8')) # Send data over TLS
ssock.shutdown(socket.SHUT_RDWR) # Close the TLS connection
ssock.close()
except Exception as e:
print("TLS connection fails")
print(e)
continue
| [
"[email protected]"
] | |
8f5307ec6a941ac8d84d56f251ad4dbd6cccadd2 | d362a983e055984c588ee81c66ba17d536bae2f5 | /backend/agent/migrations/0003_beautician.py | 50fc77458670228cbb0dd38577ad9635cf06145d | [] | no_license | prrraveen/Big-Stylist-CRM | 1d770b5ad28f342dfc5d40002ddc3ee7cc6f840a | 6cd84ce7b01a49a09b844c27ecc4575dcca54393 | refs/heads/master | 2021-01-10T04:37:43.414844 | 2015-12-15T10:47:21 | 2015-12-15T10:47:21 | 49,239,402 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,057 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agent', '0002_service'),
]
operations = [
migrations.CreateModel(
name='Beautician',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=100)),
('gender', models.CharField(max_length=1, choices=[(b'M', b'Male'), (b'F', b'Female')])),
('marital_status', models.CharField(max_length=1, choices=[(b'M', b'married'), (b'S', b'Single')])),
('family_members', models.CharField(max_length=80, blank=True)),
('age', models.IntegerField(null=True, blank=True)),
('customer_rating', models.IntegerField(null=True, blank=True)),
('bs_rating', models.IntegerField(null=True, blank=True)),
('rating_by_service', models.IntegerField(null=True, blank=True)),
('phone_number', models.CharField(max_length=11)),
('alternate_number', models.CharField(max_length=11, blank=True)),
('address', models.CharField(max_length=1000, blank=True)),
('locality', models.CharField(max_length=100)),
('employment_status', models.CharField(blank=True, max_length=1, choices=[(b'0', b'Employed'), (b'1', b'Unemployed')])),
('availability', models.CharField(blank=True, max_length=2, choices=[(b'A', b'Available'), (b'NA', b'Single')])),
('Services', models.ManyToManyField(to='agent.Service', null=True, blank=True)),
('pincode', models.ForeignKey(related_name='beautician_pincode', blank=True, to='agent.Pincode', null=True)),
('serving_in', models.ManyToManyField(related_name='beautician_pincode_server_in', null=True, to='agent.Pincode', blank=True)),
],
),
]
| [
"[email protected]"
] | |
5c1167fe99ba3fb29255afa69fa05a2a94c03178 | 6c2d219dec81b75ac1aef7f96f4e072ed7562f81 | /scenes/siteVogov.py | 2501bf763ea4538e32f964cf4d904cf6f7aeb93f | [] | no_license | SFTEAM/scrapers | 7e2b0a159cb19907017216c16a976d630d883ba5 | 778f282bf1b6954aa06d265fdb6f2ecc2e3c8e47 | refs/heads/main | 2023-08-15T18:21:41.922378 | 2021-09-24T22:24:29 | 2021-09-24T22:24:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,781 | py | import re
import scrapy
from tpdb.BaseSceneScraper import BaseSceneScraper
class VogovSpider(BaseSceneScraper):
name = 'Vogov'
network = 'Vogov'
parent = 'Vogov'
site = 'Vogov'
start_urls = [
'https://vogov.com'
]
selector_map = {
'title': '//meta[@property="og:title"]/@content',
'description': '//div[contains(@class,"info-video-description")]/p/text()',
'performers': '//div[contains(@class,"info-video-models")]/a/text()',
'date': '//li[contains(text(),"Release")]/span/text()',
'image': '//meta[@property="og:image"]/@content',
'tags': '//div[contains(@class,"info-video-category")]/a/text()',
'external_id': r'videos\/(.*)\/?',
'trailer': '//script[contains(text(),"video_url")]/text()',
'pagination': '/latest-videos/%s/'
}
def get_scenes(self, response):
scenes = response.xpath('//div[@class="video-post"]/div/a/@href').getall()
for scene in scenes:
yield scrapy.Request(url=self.format_link(response, scene), callback=self.parse_scene, meta={'site': 'Vogov'})
def get_trailer(self, response):
if 'trailer' in self.get_selector_map() and self.get_selector_map('trailer'):
trailer = self.process_xpath(
response, self.get_selector_map('trailer')).get()
trailer = re.search(r'video_url:\ .*?(https:\/\/.*?\.mp4)\/', trailer).group(1)
if trailer:
return trailer
return ''
def get_tags(self, response):
if self.get_selector_map('tags'):
tags = self.process_xpath(
response, self.get_selector_map('tags')).getall()
return list(map(lambda x: x.strip().title(), tags))
return []
| [
"[email protected]"
] | |
5e7f226554ea2fb5c3ea365c54d0f77bb1955e6d | 180dc578d12fff056fce1ef8bd1ba5c227f82afc | /tensorflow_models/__init__.py | 18eea8c6304e418deeb1b34e45a57fd437c81079 | [
"Apache-2.0"
] | permissive | jianzhnie/models | 6cb96c873d7d251db17afac7144c4dbb84d4f1d6 | d3507b550a3ade40cade60a79eb5b8978b56c7ae | refs/heads/master | 2023-07-12T05:08:23.314636 | 2023-06-27T07:54:20 | 2023-06-27T07:54:20 | 281,858,258 | 2 | 0 | Apache-2.0 | 2022-03-27T12:53:44 | 2020-07-23T05:22:33 | Python | UTF-8 | Python | false | false | 909 | py | # Copyright 2023 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.
"""TensorFlow Models Libraries."""
# pylint: disable=wildcard-import
from tensorflow_models import nlp
from tensorflow_models import vision
from official import core
from official.modeling import hyperparams
from official.modeling import optimization
from official.modeling import tf_utils as utils
| [
"[email protected]"
] | |
14bc7b551cf26a394151530e590ccdb32e250759 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /benchmark/startPyquil2701.py | b7aa787a468a8dbc6e74cfb46597078a617fc507 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,864 | py | # qubit number=4
# total number=41
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(3) # number=32
prog += CZ(0,3) # number=33
prog += H(3) # number=34
prog += H(3) # number=26
prog += CZ(0,3) # number=27
prog += H(3) # number=28
prog += X(3) # number=24
prog += CNOT(0,3) # number=25
prog += CNOT(0,3) # number=12
prog += H(2) # number=29
prog += CZ(0,2) # number=30
prog += H(2) # number=31
prog += X(2) # number=21
prog += CNOT(0,2) # number=22
prog += H(1) # number=2
prog += H(2) # number=3
prog += H(3) # number=4
prog += H(0) # number=5
prog += Y(3) # number=36
prog += H(3) # number=16
prog += CZ(1,3) # number=17
prog += H(3) # number=18
prog += H(1) # number=6
prog += H(2) # number=37
prog += CNOT(1,0) # number=38
prog += Z(1) # number=39
prog += CNOT(1,0) # number=40
prog += H(2) # number=7
prog += H(3) # number=8
prog += H(0) # number=9
prog += CNOT(3,0) # number=13
prog += CNOT(3,0) # number=14
# circuit end
return prog
def summrise_results(bitstrings) -> dict:
d = {}
for l in bitstrings:
if d.get(l) is None:
d[l] = 1
else:
d[l] = d[l] + 1
return d
if __name__ == '__main__':
prog = make_circuit()
qvm = get_qc('4q-qvm')
results = qvm.run_and_measure(prog,1024)
bitstrings = np.vstack([results[i] for i in qvm.qubits()]).T
bitstrings = [''.join(map(str, l)) for l in bitstrings]
writefile = open("../data/startPyquil2701.csv","w")
print(summrise_results(bitstrings),file=writefile)
writefile.close()
| [
"[email protected]"
] | |
3811c8ded3c52d3c4297b523a72aef17f3e5b4ff | fe8bd31a416d7217c8b95d2ebf36158fdc0412de | /revscoring/languages/__init__.py | 8076663b037c06ed1909940273411b71a9b88537 | [
"MIT"
] | permissive | nealmcb/revscoring | f0020a9009e584a0f59576adcdd16eadae21ee06 | e5c889093c4f49443d12193a2da725065c87e6d6 | refs/heads/master | 2021-01-11T11:32:10.684223 | 2015-10-21T22:34:56 | 2015-10-21T22:34:56 | 44,418,672 | 0 | 0 | null | 2015-10-17T01:16:45 | 2015-10-17T01:16:45 | null | UTF-8 | Python | false | false | 788 | py | """
This module implements a set of :class:`revscoring.Language`
-- collections of features that are language specific.
languages
+++++++++
.. automodule:: revscoring.languages.english
.. automodule:: revscoring.languages.french
.. automodule:: revscoring.languages.hebrew
.. automodule:: revscoring.languages.indonesian
.. automodule:: revscoring.languages.persian
.. automodule:: revscoring.languages.portuguese
.. automodule:: revscoring.languages.spanish
:members:
.. automodule:: revscoring.languages.turkish
:members:
.. automodule:: revscoring.languages.vietnamese
:members:
Base classes
++++++++++++
.. automodule:: revscoring.languages.language
.. automodule:: revscoring.languages.space_delimited
"""
from .language import Language
__all__ = [Language]
| [
"[email protected]"
] | |
9f837590386b08c2bb7b840886d6c4846297c5db | 9130bdbd90b7a70ac4ae491ddd0d6564c1c733e0 | /venv/lib/python3.8/site-packages/virtualenv/create/via_global_ref/builtin/python2/python2.py | 6caf7949dd60cf3fde3fad0f2252a25efd921e37 | [] | no_license | baruwaa12/Projects | 6ca92561fb440c63eb48c9d1114b3fc8fa43f593 | 0d9a7b833f24729095308332b28c1cde63e9414d | refs/heads/main | 2022-10-21T14:13:47.551218 | 2022-10-09T11:03:49 | 2022-10-09T11:03:49 | 160,078,601 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | /home/runner/.cache/pip/pool/8e/42/70/9a4789553cf0ce8f7978c229b537dd040faa9b222a65ca6de3c88e8ad5 | [
"[email protected]"
] | |
7e3edaadd3fc130cc391da1bfd5cd75125fbd91d | 78b7a0f04a92499d7c7479d22a6d6ed0494f51d4 | /doc/future_bottumup.py | 2f3208851514d1180279d9e67312187043ba02fe | [] | no_license | duchesnay/pylearn-epac | 5a6df8a68dc121ed6f87720250f24d927d553a04 | 70b0a85b7614b722ce40c506dfcb2e0c7dca8027 | refs/heads/master | 2021-01-21T00:16:09.693568 | 2013-07-23T10:21:56 | 2013-07-23T10:21:56 | 6,781,768 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,240 | py | # -*- coding: utf-8 -*-
"""
Created on Thu May 23 15:21:35 2013
@author: ed203246
"""
from sklearn import datasets
from sklearn.svm import SVC
from sklearn.lda import LDA
from sklearn.feature_selection import SelectKBest
X, y = datasets.make_classification(n_samples=12, n_features=10,
n_informative=2)
from epac import Methods, Pipe
self = Methods(*[Pipe(SelectKBest(k=k), SVC(kernel=kernel, C=C)) for kernel in ("linear", "rbf") for C in [1, 10] for k in [1, 2]])
self = Methods(*[Pipe(SelectKBest(k=k), SVC(C=C)) for C in [1, 10] for k in [1, 2]])
import copy
self.fit_predict(X=X, y=y)
self.reduce()
[l.get_key() for l in svms.walk_nodes()]
[l.get_key(2) for l in svms.walk_nodes()] # intermediary key collisions: trig aggregation
"""
# Model selection using CV: CV + Grid
# -----------------------------------------
from epac import CVBestSearchRefit
# CV + Grid search of a simple classifier
wf = CVBestSearchRefit(*[SVC(C=C) for C in [1, 10]], n_folds=3)
wf.fit_predict(X=X, y=y)
wf.reduce()
"""
"""
import numpy as np
results_list = \
{'Methods/SelectKBest(k=1)/SVC(kernel=linear,C=1)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=1)/SVC(kernel=linear,C=10)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=1)/SVC(kernel=rbf,C=1)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=1)/SVC(kernel=rbf,C=10)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=2)/SVC(kernel=linear,C=1)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=2)/SVC(kernel=linear,C=10)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=2)/SVC(kernel=rbf,C=1)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=2)/SVC(kernel=rbf,C=10)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])}}
import numpy as np
run epac/utils.py
run epac/workflow/base.py
results_list=\
{'Methods/SelectKBest(k=1)/SVC(C=1)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=1)/SVC(C=10)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=2)/SVC(C=1)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te': np.array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])},
'Methods/SelectKBest(k=2)/SVC(C=10)': {'pred_te': np.array([1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0]),
'score_te': 0.83333333333333337,
'score_tr': 0.83333333333333337,
'true_te':np. array([1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0])}}
"""
keys_splited = [key_split(key, eval_args=True) for key in results_list.keys()]
first = keys_splited[0]
arg_grids = list() # list of [depth_idx, arg_idx, arg_name, [arg_values]]
for i in xrange(len(first)):
if len(first[i]) > 1: # has arguments
for arg_idx in xrange(len(first[i][1])):
arg_grids.append([i, arg_idx, first[i][1][arg_idx][0],
[first[i][1][arg_idx][1]]])
# Check if Results can be stacked same depth, same node type a,d argument names
# An enumerate all possible arguments values
for other in keys_splited[1:]:
if len(first) != len(other):
print results_list.keys()
raise ValueError("Results cannot be stacked: different depth")
for i in xrange(len(first)):
if first[i][0] != other[i][0]:
print results_list.keys()
raise ValueError("Results cannot be stacked: nodes have different type")
if len(first[i]) > 1 and len(first[i][1]) != len(other[i][1]):
print results_list.keys()
raise ValueError("Results cannot be stacked: nodes have different length")
if len(first[i]) > 1: # has arguments
for arg_idx in xrange(len(first[i][1])):
if first[i][1][arg_idx][0] != other[i][1][arg_idx][0]:
print results_list.keys()
raise ValueError("Results cannot be stacked: nodes have"
"argument name")
values = [item for item in arg_grids if i==item[0] and \
arg_idx==item[1]][0][3]
values.append(other[i][1][arg_idx][1])
#values[i][1][arg_idx][1].append(other[i][1][arg_idx][1])
for grid in arg_grids:
grid[3] = set(grid[3])
arg_grids
@classmethod
def stack_results(list_of_dict, axis_name=None,
axis_values=[]):
"""Stack a list of Result(s)
Example
-------
>>> _list_of_dicts_2_dict_of_lists([dict(a=1, b=2), dict(a=10, b=20)])
{'a': [1, 10], 'b': [2, 20]}
"""
dict_of_list = dict()
for d in list_of_dict:
#self.children[child_idx].signature_args
#sub_aggregate = sub_aggregates[0]
for key2 in d.keys():
#key2 = sub_aggregate.keys()[0]
result = d[key2]
# result is a dictionary
if isinstance(result, dict):
if not key2 in dict_of_list.keys():
dict_of_list[key2] = dict()
for key3 in result.keys():
if not key3 in dict_of_list[key2].keys():
dict_of_list[key2][key3] = ListWithMetaInfo()
dict_of_list[key2][key3].axis_name = axis_name
dict_of_list[key2][key3].axis_values = axis_values
dict_of_list[key2][key3].append(result[key3])
else: # simply concatenate
if not key2 in dict_of_list.keys():
dict_of_list[key2] = ListWithMetaInfo()
dict_of_list[key2].axis_name = axis_name
dict_of_list[key2].axis_values = axis_values
dict_of_list[key2].append(result)
return dict_of_list | [
"[email protected]"
] | |
2f6e31622147ccd5f16a2b68f420e3f8bf6471a0 | c9c4536cebddfc3cc20f43084ccdb2ce1320b7e6 | /experiments/utils.py | dfdf83bd5f97232f940217ba09e8103c9311d9a1 | [
"MIT"
] | permissive | jdc08161063/gym-miniworld | adaf03db39fc47b88dfc5faa4f3f9e926c7f25ca | 4e96db30cb574c6e0eb5db33e83c68a979094a7f | refs/heads/master | 2020-04-06T17:06:23.350527 | 2018-11-14T19:47:17 | 2018-11-14T19:47:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,863 | py | from functools import reduce
import operator
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
class Print(nn.Module):
"""
Layer that prints the size of its input.
Used to debug nn.Sequential
"""
def __init__(self):
super(Print, self).__init__()
def forward(self, x):
print('layer input:', x.shape)
return x
class GradReverse(torch.autograd.Function):
"""
Gradient reversal layer
"""
def __init__(self, lambd=1):
self.lambd = lambd
def forward(self, x):
return x.view_as(x)
def backward(self, grad_output):
return (grad_output * -self.lambd)
def init_weights(m):
classname = m.__class__.__name__
if classname.startswith('Conv'):
nn.init.orthogonal_(m.weight.data)
m.bias.data.fill_(0)
elif classname.find('Linear') != -1:
nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def print_model_info(model):
modelSize = 0
for p in model.parameters():
pSize = reduce(operator.mul, p.size(), 1)
modelSize += pSize
print(str(model))
print('Total model size: %d' % modelSize)
def make_var(arr):
arr = np.ascontiguousarray(arr)
arr = torch.from_numpy(arr).float()
arr = Variable(arr)
if torch.cuda.is_available():
arr = arr.cuda()
return arr
def save_img(file_name, img):
from skimage import io
if isinstance(img, Variable):
img = img.data.numpy()
if len(img.shape) == 4:
img = img.squeeze(0)
img = img.astype(np.uint8)
io.imsave(file_name, img)
def load_img(file_name):
from skimage import io
# Drop the alpha channel
img = io.imread(file_name)
img = img[:,:,0:3] / 255
# Flip the image vertically
img = np.flip(img, 0)
# Transpose the rows and columns
img = img.transpose(2, 0, 1)
# Make it a batch of size 1
var = make_var(img)
var = var.unsqueeze(0)
return var
def gen_batch(gen_data_fn, batch_size=2):
"""
Returns a tuple of PyTorch Variable objects
gen_data is expected to produce a tuple
"""
assert batch_size > 0
data = []
for i in range(0, batch_size):
data.append(gen_data_fn())
# Create arrays of data elements for each variable
num_vars = len(data[0])
arrays = []
for idx in range(0, num_vars):
vals = []
for datum in data:
vals.append(datum[idx])
arrays.append(vals)
# Make a variable out of each element array
vars = []
for array in arrays:
var = make_var(np.stack(array))
vars.append(var)
return tuple(vars)
| [
"[email protected]"
] | |
127d350e935ff500677c170ab861f0343b28e635 | e7b312b4cc3355f4ca98313ef2ac9f3b0d81f245 | /abc/229/g/g.TLE.py | 756dc1a784847d74805a2326514ab64db4f673f6 | [] | no_license | minus9d/programming_contest_archive | 75466ab820e45ee0fcd829e6fac8ebc2accbbcff | 0cb9e709f40460305635ae4d46c8ddec1e86455e | refs/heads/master | 2023-02-16T18:08:42.579335 | 2023-02-11T14:10:49 | 2023-02-11T14:10:49 | 21,788,942 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,868 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
類題 https://tutorialspoint.com/program-to-find (YをN個連続させるのに必要な最小スワップ回数を求める)
を見つけたので、これを使って二分探索で解こうとしたが、TLE
類題のコードは理解していない
https://twitter.com/kyopro_friends/status/1464593018451750919
を参考にとき直すこと
"""
import array
from bisect import *
from collections import *
import fractions
import heapq
from itertools import *
import math
import random
import re
import string
import sys
sys.setrecursionlimit(10 ** 9)
# https://www.tutorialspoint.com/program-to-find-minimum-adjacent-swaps-for-k-consecutive-ones-in-python
def calc_swap_num(nums, k):
j = val = 0
ans = 10 ** 100
loc = []
for i, x in enumerate(nums):
if x:
loc.append(i)
m = (j + len(loc) - 1)//2
val += loc[-1] - loc[m] - (len(loc)-j)//2
if len(loc) - j > k:
m = (j + len(loc))//2
val -= loc[m] - loc[j] - (len(loc)-j)//2
j += 1
if len(loc)-j == k:
ans = min(ans, val)
return ans
def solve(S, K):
nums = []
for ch in S:
if ch == 'Y':
nums.append(1)
else:
nums.append(0)
max_ans = sum(nums)
# for i in range(1, max_ans + 1):
# print(i, calc_swap_num(nums, i))
if max_ans == 0:
return 0
tmp = calc_swap_num(nums, max_ans)
if tmp <= K:
return max_ans
lo = 1
hi = max_ans
while hi - lo > 1:
mid = (lo + hi) // 2
tmp = calc_swap_num(nums, mid)
if tmp <= K:
lo = mid
else:
hi = mid
return lo
S = input()
K = int(input())
print(solve(S, K))
| [
"[email protected]"
] | |
67d1f7cd8d7bbddc37fe4bfd3e34c2c84521cfa4 | 5a8f9d8d1cc47ae83546b0e11279b1d891798435 | /enumerate_reversible.py | fcce362a8588dd9d6a470e2f099a5cfab00ea31f | [
"MIT"
] | permissive | cjrh/enumerate_reversible | d81af841129adbad3a3d69a4955bfba202a174c7 | d67044c78c1214c8749b60227d5c170d8c327770 | refs/heads/master | 2021-05-21T08:16:31.660568 | 2021-05-03T04:05:15 | 2021-05-03T04:05:15 | 252,613,686 | 0 | 0 | MIT | 2021-05-03T04:05:15 | 2020-04-03T02:27:01 | Python | UTF-8 | Python | false | false | 438 | py | original_enumerate = enumerate
def enumerate(iterable, start=0):
class Inner:
def __iter__(self):
yield from original_enumerate(iterable, start=start or 0)
def __reversed__(self):
stt = start or 0
rev = reversed(iterable) # First, for accurate exception msg
rng = range(len(iterable) - 1 + stt, -1 + stt, -1)
yield from zip(rng, rev)
return Inner()
| [
"[email protected]"
] | |
c2ad359b688548a3549a051c298426f0191150a1 | 492d3e666b87eff971628a74fe13facde01e2949 | /htmlcov/_python_Django_My Projects_student-portal_Lib_site-packages_PIL_Jpeg2KImagePlugin_py.html.py | b8330d31117b1128e355617407fbf98b05fbbbd7 | [] | no_license | OmarFateh/Student-Portal | 42050da15327aa01944dc79b5e00ca34deb51531 | 167ffd3a4183529c0cbc5db4ab232026711ea915 | refs/heads/master | 2023-06-13T01:03:16.475588 | 2021-07-08T11:09:09 | 2021-07-08T11:09:09 | 382,895,837 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 91,097 | py | XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XX
XXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXX
XXXXX XXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXX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XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX
XXXXXXX XX XXXXXXXXXX XXXXX XXXXX
XXXX
XXXXXX
XXXXXX
XXXXXXX
XXXXXXX
| [
"[email protected]"
] | |
2b9e188a0d339e9e9ab6c6f43ca76d30a7100206 | ca446c7e21cd1fb47a787a534fe308203196ef0d | /tests/graph/test_statement.py | 4835355ef9be96cbb32485a349d98a91c0e3b83d | [
"MIT"
] | permissive | critocrito/followthemoney | 1a37c277408af504a5c799714e53e0f0bd709f68 | bcad19aedc3b193862018a3013a66869e115edff | refs/heads/master | 2020-06-12T09:56:13.867937 | 2019-06-28T08:23:54 | 2019-06-28T08:23:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,279 | py | # from nose.tools import assert_raises
from unittest import TestCase
from followthemoney import model
from followthemoney.types import registry
from followthemoney.graph import Statement, Node
ENTITY = {
'id': 'test',
'schema': 'Person',
'properties': {
'name': 'Ralph Tester',
'birthDate': '1972-05-01',
'idNumber': ['9177171', '8e839023'],
'website': 'https://ralphtester.me',
'phone': '+12025557612',
'email': '[email protected]',
'passport': 'passportEntityId'
}
}
class StatementTestCase(TestCase):
def test_base(self):
prop = model.get_qname('Thing:name')
node = Node(registry.entity, 'banana')
stmt = Statement(node, prop, "Theodore Böln")
assert stmt.subject == node
value = stmt.to_tuple()
other = stmt.from_tuple(model, value)
assert other == stmt, (stmt, other)
assert hash(other) == hash(stmt)
assert repr(other) == repr(stmt)
def test_invert(self):
prop = model.get_qname('Thing:name')
node = Node(registry.entity, 'banana')
stmt = Statement(node, prop, "Theodore")
assert not stmt.inverted
inv = stmt.invert()
assert inv.inverted
assert inv.rdf() is None
banana = Node(registry.entity, 'banana')
peach = Node(registry.entity, 'peach')
prop = model.get_qname('Thing:sameAs')
stmt = Statement(banana, prop, peach.value)
inv = stmt.invert()
assert inv.subject == peach
assert inv.value_node == banana
assert inv.prop == stmt.prop
def test_make_statements(self):
statements = list(model.get_proxy(ENTITY).statements)
assert len(statements) == 8, len(statements)
def test_rdf(self):
statements = list(model.get_proxy(ENTITY).statements)
triples = [l.rdf() for l in statements]
assert len(triples) == 8, len(triples)
for (s, p, o) in triples:
assert 'test' in s, s
if str(o) == 'Ralph Tester':
assert str(p) == 'http://www.w3.org/2004/02/skos/core#prefLabel' # noqa
if p == registry.phone:
assert str(o) == 'tel:+12025557612', o
# assert False, triples
| [
"[email protected]"
] | |
2d7d3d140684312694eeceace7b7556b9773c49c | 2e22d14109f41ec84554a7994cd850619d73dc4d | /core/socketserver.py | acbb6e93f7ec0b453e50d8a8c82c25425d367983 | [
"MIT"
] | permissive | magus0219/clockwork | 35cefeac77e68c1b5e12ab275b7fde18fd07edfc | 78c08afdd14f226d7f5c13af633d41a2185ebb7f | refs/heads/master | 2021-01-10T07:49:09.539766 | 2015-09-28T08:17:46 | 2015-09-28T08:17:46 | 43,036,160 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,035 | py | # coding:utf-8
'''
Created on Feb 17, 2014
@author: magus0219
'''
import socket, logging, threading, pickle
from core.command import Command
def recv_until(socket, suffix):
'''
Receive message suffixed with specified char
@param socket:socket
@param suffix:suffix
'''
message = ''
while not message.endswith(suffix):
data = socket.recv(4096)
if not data:
raise EOFError('Socket closed before we see suffix.')
message += data
return message
class SocketServer(object):
'''
Socket Server
This socket server is started by clockwork server and only used to invoke methods
of JobManager
'''
def __init__(self, host, port, jobmanager):
'''
Constructor
'''
self.host = host
self.port = port
self.jobmanager = jobmanager
self.logger = logging.getLogger("Server.SocketThread")
def handleCommand(self, command):
'''
Handle one request command of client and return server's answer
@param command:Command to handle
This function return a Command object which contains result type and detail
information.
'''
cmd = command.cmd
try:
if cmd == Command.JOB_ADD:
jobid = int(command.data)
self.jobmanager.addJob(jobid)
return Command(Command.RESULT_SUCCESS, "Successful!")
elif cmd == Command.JOB_REMOVE:
jobid = int(command.data)
self.jobmanager.removeJob(jobid)
return Command(Command.RESULT_SUCCESS, "Successful!")
elif cmd == Command.JOB_RELOAD:
jobid = int(command.data)
self.jobmanager.reloadJob(jobid)
return Command(Command.RESULT_SUCCESS, "Successful!")
elif cmd == Command.TASK_RUN_IMMEDIATELY:
jobid, params = command.data
jobid = int(jobid)
task = self.jobmanager.spawnImmediateTask(jobid=jobid, params=params)
return Command(Command.RESULT_SUCCESS, "Successful!", task.get_taskid())
elif cmd == Command.TASK_CANCEL:
taskid = command.data
self.jobmanager.cancelTask(taskid)
return Command(Command.RESULT_SUCCESS, "Successful!")
elif cmd == Command.STATUS:
return Command(Command.RESULT_SUCCESS, self.jobmanager.getServerStatus())
except ValueError, e:
self.logger.exception(e)
return Command(Command.RESULT_FAIL, str(e))
def process(self, conn, address):
'''
Thread entry where new socket created
'''
self.logger.info("Accepted a connection from %s" % str(address))
self.logger.info("Socket connects %s and %s" % (conn.getsockname(), conn.getpeername()))
cmd = pickle.loads(recv_until(conn, '.'))
self.logger.info("Recieve Command:[%s]" % str(cmd))
while cmd.cmd != Command.EXIT:
conn.sendall(pickle.dumps(self.handleCommand(cmd)))
cmd = pickle.loads(recv_until(conn, '.'))
self.logger.info("Recieve Command:[%s]" % str(cmd))
self.logger.info("Socket is Over")
def start(self):
'''
Start the socket server and enter the main loop
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((self.host, self.port))
s.listen(10)
self.logger.info("SocketThread is Listening at %s:%s" % (self.host, str(self.port)))
while True:
conn, address = s.accept()
thread = threading.Thread(target=self.process, args=(conn, address))
thread.daemon = True
thread.start()
if __name__ == '__main__':
server = SocketServer("0.0.0.0", 3993)
server.start()
| [
"[email protected]"
] | |
d3c54bcbc564892dfd88c419f85921faa603d6a6 | a6610e191090e216b0e0f23018cecc5181400a7a | /robotframework-ls/tests/robotframework_ls_tests/test_code_analysis.py | dd34aae67913ad1d119eaee83156b557a906088b | [
"Apache-2.0"
] | permissive | JohanMabille/robotframework-lsp | d7c4c00157dd7c12ab15b7125691f7052f77427c | 610f0257fdcd79b8c38107a0ecf600f60160bc1f | refs/heads/master | 2023-01-19T10:29:48.982578 | 2020-11-25T13:46:22 | 2020-11-25T13:46:22 | 296,245,093 | 0 | 0 | NOASSERTION | 2020-09-17T06:58:54 | 2020-09-17T06:58:53 | null | UTF-8 | Python | false | false | 5,420 | py | def _collect_errors(workspace, doc, data_regression, basename=None, config=None):
from robotframework_ls.impl.completion_context import CompletionContext
from robotframework_ls.impl.code_analysis import collect_analysis_errors
completion_context = CompletionContext(doc, workspace=workspace.ws, config=config)
errors = [
error.to_lsp_diagnostic()
for error in collect_analysis_errors(completion_context)
]
data_regression.check(errors, basename=basename)
def test_keywords_analyzed(workspace, libspec_manager, data_regression):
workspace.set_root("case1", libspec_manager=libspec_manager)
doc = workspace.get_doc("case1.robot")
doc.source = doc.source + (
"\n This keyword does not exist" "\n [Teardown] Also not there"
)
_collect_errors(workspace, doc, data_regression)
def test_keywords_analyzed_templates(workspace, libspec_manager, data_regression):
workspace.set_root("case1", libspec_manager=libspec_manager)
doc = workspace.get_doc("case1.robot")
doc.source = """*** Settings ***
Test Template this is not there"""
_collect_errors(workspace, doc, data_regression)
def test_keywords_with_vars_no_error(workspace, libspec_manager, data_regression):
workspace.set_root("case1", libspec_manager=libspec_manager)
doc = workspace.get_doc("case1.robot")
doc.source = (
doc.source
+ """
I check ls
I execute "ls" rara "-lh"
*** Keywords ***
I check ${cmd}
Log ${cmd}
I execute "${cmd}" rara "${opts}"
Log ${cmd} ${opts}
"""
)
_collect_errors(workspace, doc, data_regression)
def test_keywords_with_prefix_no_error(workspace, libspec_manager, data_regression):
workspace.set_root("case1", libspec_manager=libspec_manager)
doc = workspace.get_doc("case1.robot")
# Ignore bdd-related prefixes (see: robotframework_ls.impl.robot_constants.BDD_PREFIXES)
doc.source = (
doc.source
+ """
given I check ls
then I execute
*** Keywords ***
I check ${cmd}
Log ${cmd}
I execute
Log foo
"""
)
_collect_errors(workspace, doc, data_regression, basename="no_error")
def test_keywords_prefixed_by_library(workspace, libspec_manager, data_regression):
workspace.set_root("case4", libspec_manager=libspec_manager)
doc = workspace.get_doc("case4.robot")
doc.source = """*** Settings ***
Library String
Library Collections
Resource case4resource.txt
*** Test Cases ***
Test
BuiltIn.Log Logging
case4resource3.Yet Another Equal Redefined
String.Should Be Titlecase Hello World
${list}= BuiltIn.Create List 1 2
Collections.Append To List ${list} 3"""
_collect_errors(workspace, doc, data_regression, basename="no_error")
def test_keywords_prefixed_with_alias(workspace, libspec_manager, data_regression):
workspace.set_root("case4", libspec_manager=libspec_manager)
doc = workspace.get_doc("case4.robot")
doc.source = """*** Settings ***
Library Collections WITH NAME Col1
*** Test Cases ***
Test
Col1.Append To List ${list} 3"""
_collect_errors(workspace, doc, data_regression, basename="no_error")
def test_keywords_name_matches(workspace, libspec_manager, data_regression):
workspace.set_root("case4", libspec_manager=libspec_manager)
doc = workspace.get_doc("case4.robot")
doc.source = """*** Settings ***
Library Collections
*** Test Cases ***
Test
AppendToList ${list} 3"""
_collect_errors(workspace, doc, data_regression, basename="no_error")
def test_resource_does_not_exist(workspace, libspec_manager, data_regression):
workspace.set_root("case4", libspec_manager=libspec_manager)
doc = workspace.get_doc("case4.robot")
doc.source = """*** Settings ***
Library DoesNotExist
Library .
Library ..
Library ../
Resource does_not_exist.txt
Resource ${foo}/does_not_exist.txt
Resource ../does_not_exist.txt
Resource .
Resource ..
Resource ../
Resource ../../does_not_exist.txt
Resource case4resource.txt
*** Test Cases ***
Test
case4resource3.Yet Another Equal Redefined"""
from robotframework_ls.robot_config import RobotConfig
config = RobotConfig()
# Note: we don't give errors if we can't resolve a resource.
_collect_errors(workspace, doc, data_regression, basename="no_error", config=config)
def test_casing_on_filename(workspace, libspec_manager, data_regression):
from robocorp_ls_core.protocols import IDocument
from pathlib import Path
# i.e.: Importing a python library with capital letters fails #143
workspace.set_root("case4", libspec_manager=libspec_manager)
doc: IDocument = workspace.get_doc("case4.robot")
p = Path(doc.path)
(p.parent / "myPythonKeywords.py").write_text(
"""
class myPythonKeywords(object):
ROBOT_LIBRARY_VERSION = 1.0
def __init__(self):
pass
def Uppercase_Keyword (self):
return "Uppercase does not work"
"""
)
doc.source = """*** Settings ***
Library myPythonKeywords.py
*** Test Cases ***
Test
Uppercase Keyword"""
from robotframework_ls.robot_config import RobotConfig
config = RobotConfig()
# Note: we don't give errors if we can't resolve a resource.
_collect_errors(workspace, doc, data_regression, basename="no_error", config=config)
| [
"[email protected]"
] | |
9ddff1fa09a2a5c49b82729b44d4140b40e1fa55 | cbdbb05b91a4463639deefd44169d564773cd1fb | /djangoproj/pos/invoices/migrations/0011_auto_20150718_0908.py | d24848402c8400bd25b51f8bef05d5d93aff8b99 | [] | no_license | blazprog/py3 | e26ef36a485809334b1d5a1688777b12730ebf39 | e15659e5d5a8ced617283f096e82135dc32a8df1 | refs/heads/master | 2020-03-19T20:55:22.304074 | 2018-06-11T12:25:18 | 2018-06-11T12:25:18 | 136,922,662 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 684 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('invoices', '0010_artikel_davek'),
]
operations = [
migrations.AddField(
model_name='racunpozicija',
name='txtNazivArtikla',
field=models.CharField(max_length=25, default='naziv'),
preserve_default=False,
),
migrations.AddField(
model_name='racunpozicija',
name='txtSifraArtikla',
field=models.CharField(max_length=5, default='sifra'),
preserve_default=False,
),
]
| [
"[email protected]"
] | |
5416209788d81dbbb8263cbf9614f1608d323758 | 03bf031efc1f171f0bb3cf8a565d7199ff073f96 | /utils/admin.py | ad5b99e1ae02e5c6358ca6949bc8b89a84e33e2a | [
"MIT"
] | permissive | emilps/onlineweb4 | a213175678ac76b1fbede9b0897c538c435a97e2 | 6f4aca2a4522698366ecdc6ab63c807ce5df2a96 | refs/heads/develop | 2020-03-30T01:11:46.941170 | 2019-05-10T19:49:21 | 2019-05-10T19:49:21 | 150,564,330 | 0 | 0 | MIT | 2019-05-10T19:49:22 | 2018-09-27T09:43:32 | Python | UTF-8 | Python | false | false | 802 | py | from django.contrib import admin
class DepositWithdrawalFilter(admin.SimpleListFilter):
"""
A simple filter to select deposits, withdrawals or empty transactions
"""
title = 'Transaction type'
parameter_name = 'amount'
def lookups(self, request, model_admin):
"""
Tuples with values for url and display term
"""
return (
('positive', 'Deposit'),
('negative', 'Withdrawal'),
('empty', 'Empty')
)
def queryset(self, request, queryset):
if self.value() == 'positive':
return queryset.filter(amount__gt=0)
if self.value() == 'negative':
return queryset.filter(amount__lt=0)
if self.value() == 'empty':
return queryset.filter(amount=0)
| [
"[email protected]"
] | |
c6de3f7935b22b0bd74ab9d330cc17353d8e8d40 | fa53fb89ca8c822acdd2f843073c36e30168edf8 | /manage.py | 5102e0b5c62daefba1742c6dbaae769d93ffa7d3 | [] | no_license | njokuifeanyigerald/honeypot-django | 6aab38c74a599bd70e27768edddd9609f59f7810 | 1065dee3ce160cfffdd52088c6a9cc4faaabd0b9 | refs/heads/master | 2022-04-14T19:02:18.426331 | 2020-04-14T11:04:47 | 2020-04-14T11:04:47 | 255,585,678 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 631 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'honeypotapp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
12ada9555cc15be06cd931a4408c0bd361b6eb02 | caf8cbcafd448a301997770165b323438d119f5e | /.history/chapter01/python_05_if_condition_20201128214052.py | 9ee4357bc39e5526dabfbdaecafa8175ebd0349b | [
"MIT"
] | permissive | KustomApe/nerdape | 03e0691f675f13ce2aefa46ee230111247e90c72 | aef6fb2d1f8c364b26d91bf8570b4487a24de69a | refs/heads/main | 2023-01-23T10:13:26.584386 | 2020-11-28T22:29:49 | 2020-11-28T22:29:49 | 309,897,105 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 977 | py | """[if文について]
もし〜だったら、こうして
"""
# if 条件:
# 実行するブロック
# 条件によって処理を適応したい場合
# 3000kmごとにオイル交換しないといけない
distance = 3403
# if distance > 3000:
# print('オイル交換時期です')
total = 123200
average = total / 3
print(average)
if average > 3000:
print('オイル交換時期ですよ!')
# 文字列を比較する/リストを比較する
# if 'abc' == "ABC":
# print('同類です')
# if 'CDE' == 'CDE':
# print('同類です')
# if 'あいうえお' == 'あいうえお':
# print('同類です')
# 文字列を検索する/リストの要素を検索する
# if 'abc' in "ABC":
# print('ヒットしました!')
# if 'ドリフト' in '僕はドリフトが好きです':
# print('ヒットしました!')
# if 'japan' in 'japanese domestic market vehicle':
# print('ヒットしました!')
# else文
# elif文
| [
"[email protected]"
] | |
e68d1c40e9032cb0617ca2a03de48c33736f012f | 9bd1daa53a7e5d65d4f7a3558f11d06006ecb000 | /conditioner/tests/actions/factories.py | f744f19bb34a5f1c829d51e2f8696013d030116f | [
"MIT"
] | permissive | pombredanne/django-conditioner | 55b01ac8e42a8e2c73025934c39aa72ee478c333 | d5d2ad1f016bc3e6b34c74ff68cd024e8fad5125 | refs/heads/master | 2020-09-25T21:16:29.274170 | 2017-03-17T08:34:00 | 2017-03-17T08:34:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 988 | py | """
Conditioner module actions related factories
"""
import random
import factory
from faker import Factory as FakerFactory
from conditioner.actions import LoggerAction, SendTemplatedEmailAction
from conditioner.tests.factories import BaseActionFactory
faker = FakerFactory.create()
class LoggerActionFactory(BaseActionFactory):
"""
Factory for `conditioner.actions.misc.LoggerAction` model
"""
level = random.choice(LoggerAction.LEVEL_CHOICES)[0]
message = factory.LazyAttribute(lambda n: faker.paragraph())
class Meta:
model = LoggerAction
class SendTemplatedEmailActionFactory(BaseActionFactory):
"""
Factory for `conditioner.actions.common.SendTemplatedEmailAction` model
"""
email = factory.LazyAttribute(lambda n: faker.email())
subject = factory.LazyAttribute(lambda n: faker.sentence())
template = factory.LazyAttribute(lambda n: faker.uri_path() + '.txt')
class Meta:
model = SendTemplatedEmailAction
| [
"[email protected]"
] | |
46b9c87173a3e66d65c3f277092f5263a0cc669f | b7ae24b0dd67a7fafbf0253f24c80924df88da62 | /lab/__init__.py | 626fd8575bd86bfeacf23439331383cd0297afc2 | [
"MIT"
] | permissive | gear/lab | b3a2b1e5babc1adb172f842651e4db5d20939a16 | ad1c5838acbcc98abb5d5d93d5c7a6c2b74bdfa2 | refs/heads/master | 2020-12-19T01:30:33.478027 | 2020-01-23T10:30:52 | 2020-01-23T10:30:52 | 235,579,450 | 0 | 0 | MIT | 2020-01-22T13:29:16 | 2020-01-22T13:29:15 | null | UTF-8 | Python | false | false | 28 | py | import lab.logger as logger
| [
"[email protected]"
] | |
1129328bacebf961f72d0c0b6cf180bcc0d9483c | ee6fb9095faef4c88848f5f769b296f672d37cd0 | /photomosaic/imgutils.py | 791cb03f378176e1dbb5c88b361c085704f9beeb | [] | no_license | cosmozhang1995/photo-mosaic | 76ca2846db0eefd6d7ded117fec1b2ac06e823ea | f5c57a9765887aeeb65804c5597727646b945814 | refs/heads/master | 2022-07-10T14:13:10.605884 | 2020-02-14T08:51:08 | 2020-02-14T08:51:08 | 240,463,724 | 0 | 0 | null | 2022-06-22T01:05:54 | 2020-02-14T08:41:38 | Python | UTF-8 | Python | false | false | 600 | py | import cv2
import numpy as np
def resize_cut(srcimg, dstsize):
dstheight, dstwidth = dstsize
img = srcimg
imgheight, imgwidth = img.shape[:2]
sc = max(dstheight/imgheight, dstwidth/imgwidth)
imgsize = (int(np.ceil(imgheight*sc)), int(np.ceil(imgwidth*sc)))
img = cv2.resize(img, (imgsize[1], imgsize[0]))
imgheight, imgwidth = img.shape[:2]
imgcut = (int((imgheight-dstheight)/2), int((imgwidth-dstwidth)/2))
imgcuttop, imgcutleft = imgcut
imgcutbottom, imgcutright = (imgcuttop + dstheight, imgcutleft + dstwidth)
img = img[imgcuttop:imgcutbottom, imgcutleft:imgcutright, :]
return img
| [
"[email protected]"
] | |
b4ffb6e7aa7720bf94408c4205e0d631a33ccac7 | c7d7bafdff29a9e0f91bec25e88b8db1b6694643 | /firebot/modules/mf.py | 37002a949a6c8212931fce04e72ad19042a64323 | [
"MIT"
] | permissive | ultra-noob/Vivek-UserBot | ebedb80d98ca72fe1167211c14e32c017fcdf903 | 6c371a4aaa0c05397efa36237e9a2118deeb0d91 | refs/heads/main | 2023-07-11T16:52:37.696359 | 2021-08-11T03:38:15 | 2021-08-11T03:38:15 | 394,882,145 | 0 | 1 | null | 2021-08-11T06:11:45 | 2021-08-11T06:11:45 | null | UTF-8 | Python | false | false | 2,724 | py | import sys
from telethon import __version__, functions
from firebot import CMD_HELP
from firebot.utils import fire_on_cmd
@fire.on(fire_on_cmd(pattern="mf ?(.*)", allow_sudo=True)) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
splugin_name = event.pattern_match.group(1)
if splugin_name in borg._modules:
s_help_string = borg._modules[splugin_name].__doc__
else:
s_help_string = ""
help_string = """
......................................../´¯/)
......................................,/¯../
...................................../..../
..................................../´.¯/
..................................../´¯/
..................................,/¯../
................................../..../
................................./´¯./
................................/´¯./
..............................,/¯../
............................./..../
............................/´¯/
........................../´¯./
........................,/¯../
......................./..../
....................../´¯/
....................,/¯../
.................../..../
............./´¯/'...'/´¯¯`·¸
........../'/.../..../......./¨¯\
........('(...´...´.... ¯~/'...')
.........\.................'...../
..........''...\.......... _.·´
............\..............(
..............\.............\...
""".format(
sys.version, __version__
)
tgbotusername = Config.TG_BOT_USER_NAME_BF_HER # pylint:disable=E0602
if tgbotusername is not None:
results = await borg.inline_query( # pylint:disable=E0602
tgbotusername, help_string + "\n\n" + s_help_string
)
await results[0].click(
event.chat_id, reply_to=event.reply_to_msg_id, hide_via=True
)
await event.delete()
else:
await event.reply(help_string + "\n\n" + s_help_string)
await event.delete()
@fire.on(fire_on_cmd(pattern="dc")) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
result = await borg(functions.help.GetNearestDcRequest()) # pylint:disable=E0602
await event.edit(result.stringify())
@fire.on(fire_on_cmd(pattern="config")) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
result = await borg(functions.help.GetConfigRequest()) # pylint:disable=E0602
result = result.stringify()
logger.info(result) # pylint:disable=E0602
await event.edit("""Telethon UserBot powered by @UniBorg""")
CMD_HELP.update(
{
"mf": "**Mf**\
\n\n**Syntax : **`.mf`\
\n**Usage :** funny plugin.\
\n\n**Syntax : **`.dc`\
\n**Usage :** shows nearest Dc."
}
)
| [
"[email protected]"
] | |
98ad144923dfcbae14b423be115a14fbb1c611c4 | 150464efa69db3abf328ef8cd912e8e248c633e6 | /_4.python/__code/Pythoneer-master/Jumbled Word/Jumbled(withouttkinter).py | 7211039e1c6397134008308e8017b3165e1a9494 | [] | no_license | bunshue/vcs | 2d194906b7e8c077f813b02f2edc70c4b197ab2b | d9a994e3afbb9ea84cc01284934c39860fea1061 | refs/heads/master | 2023-08-23T22:53:08.303457 | 2023-08-23T13:02:34 | 2023-08-23T13:02:34 | 127,182,360 | 6 | 3 | null | 2023-05-22T21:33:09 | 2018-03-28T18:33:23 | C# | UTF-8 | Python | false | false | 1,397 | py | import os
import sys
from collections import defaultdict
print " ";
print "................................Jumbled ......................................";
print "NOTE : Please make sure, you enter all the letters necessary to make the word!";
print " ";
print " ";
word = input("Enter the word: ")
print " ";
#word = sys.argv[1]
word1 = word
#print word1
leng=len(word)
no = leng
chek=''
dict = defaultdict(list)
#word = input("Enter the : ")
word = word.lower()
word = sorted(word)
word = ''.join(word)
word = "\n"+word
word = word.replace(" ", "")
file = open("C:\Python27\Jumbled\Dictionary.txt", "r")
line = file.readline()
print " "
count = 0;
while line:
if(line!=None):
line = file.readline()
j = line
line = sorted(line)
line = ''.join(line)
j = ''.join(j)
k = sorted(j)
k = ''.join(k)
k = k.lower()
if (word==k):
if(count<1):
print "Solution : "+j+"\n",
count=count+1;
if(count>1):
print "Another Combnation : "+j
if(j=="mazahir"):
print "'Mazahir' here! :), Hope you liked my program :D"
#dict[word].append(k)
file.close()
fo = open("C:/Mazahir/now.txt", "w")
line = fo.write( j )
fo.close()
file = open("C:/Mazahir/now1.txt", "w")
file.write( str(no) )
file.close()
| [
"[email protected]"
] | |
6545749e1fcb37b005fd8a17f1fe2d41493c78ba | c36679186f669c6e3bd1c106c96d4a17be1f5ab1 | /Ashraf/2.2.py | 82910eaba95d405311c4da597335040cd6ff75a0 | [] | no_license | touhiduzzaman-tuhin/python-code-university-life | 60a3d671b200a6f5222c6d176c13c5f20f013509 | 6d2e3d90d430faa5c83fe79e7fb1ebe516994762 | refs/heads/master | 2023-03-22T15:18:10.636203 | 2021-03-06T18:52:04 | 2021-03-06T18:52:04 | 332,467,190 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 56 | py | x = int(input())
y = int(input())
z = x - y
print(z)
| [
"[email protected]"
] | |
7e6c1f50001acdca960cd972aca451db26803155 | 68ea05d0d276441cb2d1e39c620d5991e0211b94 | /1940.py | a6e8f345cdc993bcae8b3a828ab9b0865b506f3b | [] | no_license | mcavalca/uri-python | 286bc43aa157d3a6880dc222e0136c80cf079565 | e22875d2609fe7e215f9f3ed3ca73a1bc2cf67be | refs/heads/master | 2021-11-23T08:35:17.614443 | 2021-10-05T13:26:03 | 2021-10-05T13:26:03 | 131,339,175 | 50 | 27 | null | 2021-11-22T12:21:59 | 2018-04-27T19:54:09 | Python | UTF-8 | Python | false | false | 236 | py | j, r = [int(x) for x in input().split()]
entrada = list(map(int, input().split()))
pontos = [0] * j
for k in range(j):
pontos[k] = sum(entrada[k::j])
pontos = pontos[::-1]
vencedor = j - pontos.index(max(pontos))
print(vencedor)
| [
"[email protected]"
] | |
6a26301089da81a8e292227e32da92a3e05f82e2 | f7d343efc7b48818cac4cf9b98423b77345a0067 | /training/Permutations.py | 10acfdf1568289dd3b55bcf473e76239ead669a4 | [] | no_license | vijaymaddukuri/python_repo | 70e0e24d0554c9fac50c5bdd85da3e15c6f64e65 | 93dd6d14ae4b0856aa7c6f059904cc1f13800e5f | refs/heads/master | 2023-06-06T02:55:10.393125 | 2021-06-25T16:41:52 | 2021-06-25T16:41:52 | 151,547,280 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 845 | py | def permutations1(string):
def factorial(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
repeat=len(string)-len(''.join(set(string)))
n=factorial(len(string))
k=factorial(repeat)
loop=n/(k**repeat)
final=[]
j=0
for i in range(loop):
if i>=2:
j=0
else:
j+=1
new = string[j-1:] + string[j-1:]
final.append(new)
string=new
return final
return loop
def permutations(string):
result = set(string)
if len(string) == 2:
result.add(string[1] + string[0])
elif len(string) > 2:
for i, c in enumerate(string):
for s in permutations(string[:i] + string[i + 1:]):
result.add(c + s)
return list(result)
a='abc'
per=permutations(a)
print(per)
| [
"[email protected]"
] | |
e48b80cea00aad77f599556a86f3688235cc9a93 | 6cfa568e2012dde5c86265226b0dd3a49849c7f7 | /website_sale_booking/__openerp__.py | 6573e2e4ae8e491f0af198340e85248ca9f2cfc3 | [] | no_license | arinno/odoo-website-sale-booking | c48771ee30dc8791656a7a9d75efa14fe07f88bc | dd2e45873e64ad0f5bdd24a23d905b70702cd85a | refs/heads/master | 2021-01-09T06:23:01.904899 | 2017-02-05T07:10:21 | 2017-02-05T07:10:21 | 80,975,669 | 0 | 0 | null | 2017-02-05T07:06:24 | 2017-02-05T07:06:24 | null | UTF-8 | Python | false | false | 425 | py | {
'name': 'Website Booking System',
'category': 'sale',
'description':"""
OpenERP Website Booking System view.
==========================
""",
'version': '1.0',
'js': [
],
'css': [
],
'author': 'Vertel AB',
'website': 'http://www.vertel.se',
'depends': ['website', 'product', 'hr_contract', 'resource'],
'data': ['view/website_sale_booking.xml'],
'installable': True,
}
| [
"[email protected]"
] | |
883364571d231534b05121da2095291109c936e8 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_handpicked.py | d8b02e24092556f8401358860df23874bd852d2b | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 448 | py |
#calss header
class _HANDPICKED():
def __init__(self,):
self.name = "HANDPICKED"
self.definitions = [u'Someone who is handpicked has been carefully chosen for a special job or purpose: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'adjectives'
def run(self, obj1, obj2):
self.jsondata[obj2] = {}
self.jsondata[obj2]['properties'] = self.name.lower()
return self.jsondata
| [
"[email protected]"
] | |
12752faa8e6f24d7152dd05c131acb18687b7faf | 94df6de2ab8eef7d21eaf08f32dd23d380ada52b | /src/generative_playground/models/pg_runner.py | ab4805df09129ee680a0e52f8490c728139b459c | [
"MIT"
] | permissive | iisuslik43/generative_playground | f6a59adb757265e55e7e12c906e9785735042127 | 3e0d8c137c3a8620461dd1a07fe46c51bb0d97eb | refs/heads/master | 2020-09-12T02:00:51.265874 | 2019-11-18T14:39:04 | 2019-11-18T14:39:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,266 | py | import os, inspect
from collections import deque
import torch.optim as optim
from torch.optim import lr_scheduler
import torch
import gzip, dill, cloudpickle
import copy
from generative_playground.models.reward_adjuster import adj_reward, AdjustedRewardCalculator
from generative_playground.models.temperature_schedule import TemperatureCallback
from generative_playground.molecules.molecule_saver_callback import MoleculeSaver
from generative_playground.molecules.visualize_molecules import model_process_fun
from generative_playground.utils.fit_rl import fit_rl
from generative_playground.utils.gpu_utils import to_gpu
from generative_playground.molecules.model_settings import get_settings
from generative_playground.metrics.metric_monitor import MetricPlotter
from generative_playground.models.problem.rl.task import SequenceGenerationTask
from generative_playground.models.decoder.decoder import get_decoder
from generative_playground.models.losses.policy_gradient_loss import PolicyGradientLoss
from generative_playground.models.problem.policy import SoftmaxRandomSamplePolicy, SoftmaxRandomSamplePolicySparse
from generative_playground.codec.codec import get_codec
from generative_playground.molecules.data_utils.zinc_utils import get_smiles_from_database
from generative_playground.data_utils.data_sources import GeneratorToIterable
class Saveable:
def save(self):
print('saving to ' + self.save_file_name + '...')
with gzip.open(self.save_file_name, 'wb') as f:
dill.dump(self, f)
print('done!')
return self.save_file_name
@classmethod
def load(cls, save_file_name):
print('loading from ' + save_file_name + '...')
with gzip.open(save_file_name, 'rb') as f:
inst = dill.load(f)
print('done!')
return inst
class PolicyGradientRunner(Saveable):
def __init__(self,
grammar,
smiles_source='ZINC',
BATCH_SIZE=None,
reward_fun=None,
max_steps=277,
num_batches=100,
lr=2e-4,
entropy_wgt=1.0,
lr_schedule=None,
root_name=None,
preload_file_root_name=None,
save_location=None,
plot_metrics=True,
metric_smooth=0.0,
decoder_type='graph_conditional',
on_policy_loss_type='advantage_record',
priors='conditional',
rule_temperature_schedule=None,
eps=0.0,
half_float=False,
extra_repetition_penalty=0.0):
self.num_batches = num_batches
self.save_location = save_location
self.molecule_saver = MoleculeSaver(None, gzip=True)
self.metric_monitor = None # to be populated by self.set_root_name(...)
zinc_data = get_smiles_from_database(source=smiles_source)
zinc_set = set(zinc_data)
lookbacks = [BATCH_SIZE, 10 * BATCH_SIZE, 100 * BATCH_SIZE]
history_data = [deque(['O'], maxlen=lb) for lb in lookbacks]
if root_name is not None:
pass
# gen_save_file = root_name + '_gen.h5'
if preload_file_root_name is not None:
gen_preload_file = preload_file_root_name + '_gen.h5'
settings = get_settings(molecules=True, grammar=grammar)
codec = get_codec(True, grammar, settings['max_seq_length'])
if BATCH_SIZE is not None:
settings['BATCH_SIZE'] = BATCH_SIZE
self.alt_reward_calc = AdjustedRewardCalculator(reward_fun, zinc_set, lookbacks, extra_repetition_penalty, 0,
discrim_model=None)
self.reward_fun = lambda x: adj_reward(0,
None,
reward_fun,
zinc_set,
history_data,
extra_repetition_penalty,
x,
alt_calc=self.alt_reward_calc)
task = SequenceGenerationTask(molecules=True,
grammar=grammar,
reward_fun=self.alt_reward_calc,
batch_size=BATCH_SIZE,
max_steps=max_steps,
save_dataset=None)
if 'sparse' in decoder_type:
rule_policy = SoftmaxRandomSamplePolicySparse()
else:
rule_policy = SoftmaxRandomSamplePolicy(temperature=torch.tensor(1.0), eps=eps)
# TODO: strip this down to the normal call
self.model = get_decoder(True,
grammar,
z_size=settings['z_size'],
decoder_hidden_n=200,
feature_len=codec.feature_len(),
max_seq_length=max_steps,
batch_size=BATCH_SIZE,
decoder_type=decoder_type,
reward_fun=self.alt_reward_calc,
task=task,
rule_policy=rule_policy,
priors=priors)[0]
if preload_file_root_name is not None:
try:
preload_path = os.path.realpath(save_location + gen_preload_file)
self.model.load_state_dict(torch.load(preload_path, map_location='cpu'), strict=False)
print('Generator weights loaded successfully!')
except Exception as e:
print('failed to load generator weights ' + str(e))
# construct the loader to feed the discriminator
def make_callback(data):
def hc(inputs, model, outputs, loss_fn, loss):
graphs = outputs['graphs']
smiles = [g.to_smiles() for g in graphs]
for s in smiles: # only store unique instances of molecules so discriminator can't guess on frequency
if s not in data:
data.append(s)
return hc
if plot_metrics:
# TODO: save_file for rewards data goes here?
self.metric_monitor_factory = lambda name: MetricPlotter(plot_prefix='',
loss_display_cap=float('inf'),
dashboard_name=name,
save_location=save_location,
process_model_fun=model_process_fun,
smooth_weight=metric_smooth)
else:
self.metric_monitor_factory = lambda x: None
# the on-policy fitter
gen_extra_callbacks = [make_callback(d) for d in history_data]
gen_extra_callbacks.append(self.molecule_saver)
if rule_temperature_schedule is not None:
gen_extra_callbacks.append(TemperatureCallback(rule_policy, rule_temperature_schedule))
nice_params = filter(lambda p: p.requires_grad, self.model.parameters())
self.optimizer = optim.Adam(nice_params, lr=lr, eps=1e-4)
if lr_schedule is None:
lr_schedule = lambda x: 1.0
self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_schedule)
self.loss = PolicyGradientLoss(on_policy_loss_type, entropy_wgt=entropy_wgt)
self.fitter_factory = lambda: make_fitter(BATCH_SIZE, settings['z_size'], [self.metric_monitor] + gen_extra_callbacks, self)
self.fitter = self.fitter_factory()
self.set_root_name(root_name)
print('Runner initialized!')
def run(self):
for i in range(self.num_batches):
next(self.fitter)
out = self.save()
return out
def set_root_name(self, root_name):
self.root_name = root_name
smiles_save_file = root_name + '_smiles.zip'
smiles_save_path = os.path.realpath(self.save_location + '/' + smiles_save_file)
self.molecule_saver.filename = smiles_save_path
print('Saving SMILES to {}'.format(smiles_save_path))
self.fitter.gi_frame.f_locals['callbacks'][0] = self.metric_monitor_factory(root_name)
print('publishing to ' + root_name)
self.save_file_name = os.path.realpath(self.save_location + '/' + root_name + '_runner.zip')
print('Runner to be saved to ' + self.save_file_name)
def __getstate__(self):
state = {key: value for key, value in self.__dict__.items() if key != 'fitter'}
return state
def __setstate__(self, state):
self.__dict__.update(state)
# need to use the factory because neither dill nor cloudpickle will serialize generators
self.fitter = self.fitter_factory()
def get_model_coeff_vector(self):
coeffvec = self.model.stepper.model.get_params_as_vector()
return coeffvec
def set_model_coeff_vector(self, vector_in):
self.model.stepper.model.set_params_from_vector(vector_in)
@property
def params(self):
return self.get_model_coeff_vector()
@params.setter
def params(self, vector_in):
self.set_model_coeff_vector(vector_in)
@classmethod
def load_from_root_name(cls, save_location, root_name):
full_save_file = os.path.realpath(save_location + '/' + root_name + '_runner.zip')
inst = cls.load(full_save_file)
return inst
def make_fitter(batch_size, z_size, callbacks, obj):
def my_gen(length=100):
for _ in range(length):
yield to_gpu(torch.zeros(batch_size, z_size)) #settings['z_size']
fitter = fit_rl(train_gen=GeneratorToIterable(my_gen),
model=obj.model,
optimizer=obj.optimizer,
scheduler=obj.scheduler,
loss_fn=obj.loss,
grad_clip=5,
callbacks=callbacks
)
return fitter | [
"[email protected]"
] | |
e7694b0db2814d86d4fe4e4c05b90604614b2138 | 91f30c829664ff409177e83776c9f4e2e98d9fc4 | /apps/events/migrations/0002_auto_20180607_0411.py | 0436f1e6422da2a9e882d0161aa9c56529c7231f | [] | no_license | TotalityHacks/madras | 3ac92dc6caf989efcb02590f6474ab333d1f93fa | 2395a703eed1a87cca3cdd6c0fb9162b69e8df27 | refs/heads/master | 2021-08-17T15:29:41.055074 | 2018-07-18T23:05:29 | 2018-07-18T23:05:29 | 105,232,414 | 4 | 5 | null | 2021-03-31T18:58:56 | 2017-09-29T05:13:41 | Python | UTF-8 | Python | false | false | 581 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-06-07 04:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='event',
name='description',
field=models.TextField(),
),
migrations.AlterField(
model_name='event',
name='title',
field=models.CharField(max_length=40),
),
]
| [
"[email protected]"
] | |
d4cb34b70a91e2240a08ad427a015525c61d1b39 | 7f8db5b974a747632729d16c431de7aca007af00 | /0x11-python-network_1/8-json_api.py | 482167a08bb420f6d28ad7b10c9d98d4c2ec9cbe | [] | no_license | thomasmontoya123/holbertonschool-higher_level_programming | 6f5ceb636167efba1e36ed2dee7bf83b458f6751 | 48b7c9dccac77ccb0f57da1dc1d150f356612b13 | refs/heads/master | 2020-07-22T22:31:13.744490 | 2020-02-13T22:54:17 | 2020-02-13T22:54:17 | 207,351,235 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 594 | py | #!/usr/bin/python3
'''sends a POST request with the letter as a parameter.'''
if __name__ == "__main__":
import requests
from sys import argv
url = 'http://0.0.0.0:5000/search_user'
if len(argv) == 2:
values = {'q': argv[1]}
result = requests.post(url, data=values)
try:
json = result.json()
if json:
print("[{}] {}".format(json.get("id"), json.get("name")))
else:
print("No result")
except Exception:
print("Not a valid JSON")
else:
print("No result")
| [
"[email protected]"
] | |
43f78419297092954ae2d68c3e9a6c3cdeb59b73 | 8bb2842aa73676d68a13732b78e3601e1305c4b2 | /1920.py | 5ce8ca2d8ffeda7120bfef402770ca16c94a7353 | [] | no_license | Avani18/LeetCode | 239fff9c42d2d5703c8c95a0efdc70879ba21b7d | 8cd61c4b8159136fb0ade96a1e90bc19b4bd302d | refs/heads/master | 2023-08-24T22:25:39.946426 | 2021-10-10T20:36:07 | 2021-10-10T20:36:07 | 264,523,162 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 277 | py | # Build Array from Permutation
class Solution(object):
def buildArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
for i in range(len(nums)):
ans.append(nums[nums[i]])
return ans
| [
"[email protected]"
] | |
b38cce92d3920a353b7dd2db6d9b362200d3e705 | 1f41b828fb652795482cdeaac1a877e2f19c252a | /maya_tools_backup/3dGroupTools/python/sgPWindow_projCoc_createSeparateView.py | 113fa85b9bb3bb9c577bba013bb7dbe3ab4cea18 | [] | no_license | jonntd/mayadev-1 | e315efe582ea433dcf18d7f1e900920f5590b293 | f76aeecb592df766d05a4e10fa2c2496f0310ca4 | refs/heads/master | 2021-05-02T07:16:17.941007 | 2018-02-05T03:55:12 | 2018-02-05T03:55:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,157 | py | import maya.cmds as cmds
from functools import partial
import sgBFunction_ui
class WinA_Global:
winName = 'sgPWindow_projCoc_createSeparateView'
title = 'UI Separate View Creator'
width = 450
height = 50
camField = ''
resField1 = ''
resField2 = ''
sepGroup1 = ''
sepGroup2 = ''
sepField1 = ''
sepField2 = ''
scaleField= ''
createWindowCheck = ''
class WinA_Cmd:
@staticmethod
def uiCmdChangeCondition( *args ):
resWidth = cmds.intField( WinA_Global.resField1, q=1, v=1 )
resHeight = cmds.intField( WinA_Global.resField2, q=1, v=1 )
sepGroupWidth = cmds.intField( WinA_Global.sepGroup1, q=1, v=1 )
sepGroupHeight = cmds.intField( WinA_Global.sepGroup2, q=1, v=1 )
sepFieldWidth = cmds.intField( WinA_Global.sepField1, q=1, v=1 )
sepFieldHeight = cmds.intField( WinA_Global.sepField2, q=1, v=1 )
resultWidth = float( resWidth ) / sepFieldWidth / sepGroupWidth
resultHeight = float( resHeight ) / sepFieldHeight / sepGroupHeight
cmds.floatField( WinA_Global.resultField1, e=1, v=resultWidth )
cmds.floatField( WinA_Global.resultField2, e=1, v=resultHeight )
@staticmethod
def uiCmdCheckOnOff( *args ):
createWindow = cmds.checkBox( WinA_Global.createWindowCheck, q=1, v=1 )
cmds.floatField( WinA_Global.scaleField, e=1, en=createWindow )
@staticmethod
def cmdCreate( *args ):
cam = cmds.textField( WinA_Global.camField, q=1, tx=1 )
width = cmds.intField( WinA_Global.resField1, q=1, v=1 )
height = cmds.intField( WinA_Global.resField2, q=1, v=1 )
sepGH = cmds.intField( WinA_Global.sepGroup1, q=1, v=1 )
sepGV = cmds.intField( WinA_Global.sepGroup2, q=1, v=1 )
sepH = cmds.intField( WinA_Global.sepField1, q=1, v=1 )
sepV = cmds.intField( WinA_Global.sepField2, q=1, v=1 )
scale = cmds.floatField( WinA_Global.scaleField, q=1, v=1 )
createWindow = cmds.checkBox( WinA_Global.createWindowCheck, q=1, v=1 )
import sgBProject_coc
sgBProject_coc.createUiSeparactedViewGroup( cam, width, height, sepGH, sepGV, sepH,sepV, scale, createWindow )
@staticmethod
def cmdClear( *args ):
cam = cmds.textField( WinA_Global.camField, q=1, tx=1 )
import sgBProject_coc
sgBProject_coc.removeUiSeparateView( cam )
class WinA_TwoIntField:
def __init__(self, label1, label2, w1, w2, h ):
self.label1 = label1
self.label2 = label2
self.width1 = w1
self.width2 = w2
self.height = h
def create(self):
form = cmds.formLayout()
text1 = cmds.text( l= self.label1, w=self.width1, h=self.height, al='right' )
text2 = cmds.text( l= self.label2, w=self.width1, h=self.height, al='right' )
field1 = cmds.intField( w=self.width2, h=self.height )
field2 = cmds.intField( w=self.width2, h=self.height )
cmds.setParent( '..' )
cmds.formLayout( form, e=1,
af=[( text1, 'top', 0 ), ( text1, 'left', 0 ),
( text2, 'top', 0 )],
ac=[( text1, 'right', 0, field1 ), ( field2, 'left', 0, text2 )],
ap=[( field1, 'right', 0, 50 ),( text2, 'left', 0, 50 )] )
self.field1 = field1
self.field2 = field2
self.form = form
return form
class WinA_TwoFloatField:
def __init__(self, label1, label2, w1, w2, h ):
self.label1 = label1
self.label2 = label2
self.width1 = w1
self.width2 = w2
self.height = h
def create(self):
form = cmds.formLayout()
text1 = cmds.text( l= self.label1, w=self.width1, h=self.height, al='right' )
text2 = cmds.text( l= self.label2, w=self.width1, h=self.height, al='right' )
field1 = cmds.floatField( w=self.width2, h=self.height )
field2 = cmds.floatField( w=self.width2, h=self.height )
cmds.setParent( '..' )
cmds.formLayout( form, e=1,
af=[( text1, 'top', 0 ), ( text1, 'left', 0 ),
( text2, 'top', 0 )],
ac=[( text1, 'right', 0, field1 ), ( field2, 'left', 0, text2 )],
ap=[( field1, 'right', 0, 50 ),( text2, 'left', 0, 50 )] )
self.field1 = field1
self.field2 = field2
self.form = form
return form
class WinA_FloatField:
def __init__(self, label1, w1, w2, h ):
self.label1 = label1
self.width1 = w1
self.width2 = w2
self.height = h
def create(self):
form = cmds.formLayout()
text1 = cmds.text( l= self.label1, w=self.width1, h=self.height, al='right' )
field1 = cmds.floatField( w=self.width2, h=self.height )
cmds.setParent( '..' )
cmds.formLayout( form, e=1,
af=[( text1, 'top', 0 ), ( text1, 'left', 0 )],
ac=[( text1, 'right', 0, field1 )],
ap=[( field1, 'right', 0, 50 )] )
self.field = field1
self.form = form
return form
class WinA:
def __init__(self):
self.winName = WinA_Global.winName
self.title = WinA_Global.title
self.width = WinA_Global.width
self.height = WinA_Global.height
self.uiTargetCam = sgBFunction_ui.PopupFieldUI_b( 'Target Camera : ' )
self.uiResolution = WinA_TwoIntField( "Resolusion Width : ", "Resolusion Height : ", 120, 80, 22 )
self.uiSepGroup = WinA_TwoIntField( "Sep Group Width num : ", "Sep Group Height num : ", 120, 80, 22 )
self.uiSeparate = WinA_TwoIntField( "Sep Width : ", "Sep Height : ", 120, 80, 22 )
self.uiResult = WinA_TwoFloatField( "Result Width : ", "Result Height", 120, 80, 22 )
self.uiWindowScale = WinA_FloatField( "Window Scale : ", 120, 80, 22 )
def create(self):
if cmds.window( self.winName, ex=1 ):
cmds.deleteUI( self.winName, wnd=1 )
cmds.window( self.winName, title=self.title )
form = cmds.formLayout()
uiTargetCamForm = self.uiTargetCam.create()
uiResolutionForm = self.uiResolution.create()
uiSepGroupForm = self.uiSepGroup.create()
uiSeparateForm = self.uiSeparate.create()
uiResultForm = self.uiResult.create()
uiCheckBox = cmds.checkBox( l='Create Window', cc= WinA_Cmd.uiCmdCheckOnOff )
uiWindowScaleForm= self.uiWindowScale.create()
uiButton1From = cmds.button( l='C R E A T E', c= WinA_Cmd.cmdCreate )
uiButton2From = cmds.button( l='C L E A R', c= WinA_Cmd.cmdClear )
cmds.setParent( '..' )
cmds.formLayout( form, e=1,
af=[( uiTargetCamForm, 'top', 5 ), ( uiTargetCamForm, 'left', 5 ), ( uiTargetCamForm, 'right', 5 ),
( uiResolutionForm, 'left', 5 ), ( uiResolutionForm, 'right', 5 ),
( uiSepGroupForm, 'left', 5 ), ( uiSepGroupForm, 'right', 5 ),
( uiSeparateForm, 'left', 5 ), ( uiSeparateForm, 'right', 5 ),
( uiResultForm, 'left', 5 ), ( uiResultForm, 'right', 5 ),
( uiCheckBox, 'left', 165 ),
( uiWindowScaleForm, 'left', 5 ),( uiWindowScaleForm, 'right', 5 ),
( uiButton1From, 'left', 2 ), ( uiButton1From, 'right', 2 ),
( uiButton2From, 'left', 2 ), ( uiButton2From, 'right', 2 ), ( uiButton2From, 'bottom', 2 )],
ac=[( uiResolutionForm, 'top', 10, uiTargetCamForm ),
( uiSepGroupForm, 'top', 10, uiResolutionForm ),
( uiSeparateForm, 'top', 10, uiSepGroupForm ),
( uiResultForm, 'top', 10, uiSeparateForm ),
( uiCheckBox, 'top', 10, uiResultForm ),
( uiWindowScaleForm, 'top', 10, uiCheckBox ),
( uiButton1From, 'top', 15, uiWindowScaleForm ),
( uiButton2From, 'top', 2, uiButton1From )])
cmds.window( self.winName, e=1, wh=[ self.width, self.height ], rtf=1 )
cmds.showWindow( self.winName )
cmds.intField( self.uiResolution.field1, e=1, v=1920, cc= WinA_Cmd.uiCmdChangeCondition )
cmds.intField( self.uiResolution.field2, e=1, v=1080, cc= WinA_Cmd.uiCmdChangeCondition )
cmds.intField( self.uiSepGroup.field1, e=1, v=1, cc= WinA_Cmd.uiCmdChangeCondition )
cmds.intField( self.uiSepGroup.field2, e=1, v=1, cc= WinA_Cmd.uiCmdChangeCondition )
cmds.intField( self.uiSeparate.field1, e=1, v=2, cc= WinA_Cmd.uiCmdChangeCondition )
cmds.intField( self.uiSeparate.field2, e=1, v=2, cc= WinA_Cmd.uiCmdChangeCondition )
cmds.floatField( self.uiResult.field1, e=1, v=960, en=0 )
cmds.floatField( self.uiResult.field2, e=1, v=540, en=0 )
cmds.floatField( self.uiWindowScale.field, e=1, v=0.5, pre=2, en=0 )
WinA_Global.camField = self.uiTargetCam._field
WinA_Global.resField1 = self.uiResolution.field1
WinA_Global.resField2 = self.uiResolution.field2
WinA_Global.sepGroup1 = self.uiSepGroup.field1
WinA_Global.sepGroup2 = self.uiSepGroup.field2
WinA_Global.sepField1 = self.uiSeparate.field1
WinA_Global.sepField2 = self.uiSeparate.field2
WinA_Global.resultField1 = self.uiResult.field1
WinA_Global.resultField2 = self.uiResult.field2
WinA_Global.scaleField= self.uiWindowScale.field
WinA_Global.createWindowCheck = uiCheckBox
| [
"[email protected]"
] | |
3323c4ec71a8a7d1a3ac28964a61aeacbeb33fd6 | 196eb2f5e3366987d7285bf980ac64254c4aec16 | /supervised/util.py | 4dbf6da6ffafcd128d865320bca7ad87e38b8408 | [
"MIT"
] | permissive | mfouda/codenames | f54e0c4366edbf65251aadefddef1fda6cd7de9d | ccd0bd7578b3deedeec60d0849ec4ebca48b6426 | refs/heads/master | 2022-01-07T02:03:42.529978 | 2018-12-21T13:16:27 | 2018-12-21T13:16:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 595 | py | import time
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import matplotlib.ticker as ticker # noqa: E402
def as_minutes(s):
m = s // 60
s -= m * 60
return '%dm %ds' % (m, s)
def time_since(since, percent):
now = time.time()
s = now - since
es = s / percent
rs = es - s
return '%s (- %s)' % (as_minutes(s), as_minutes(rs))
def show_plot(points):
plt.figure()
fig, ax = plt.subplots()
# this locator puts ticks at regular intervals
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
| [
"[email protected]"
] | |
7b80ef96fa22fd633d5e959b647de4b9f16faedc | c7f98de17088cb4df6c171f1e76614beb1f4e0f7 | /modules/vulnerability-analysis/w3af.py | 73cb1fc29cbd307d7038d2d133f512666a097029 | [] | no_license | fryjustinc/ptf | 6262ca5b94a43a51e984d3eee1649a16584b597b | ba85f9e867b65b4aa4f06b6232207aadac9782c9 | refs/heads/master | 2020-03-31T09:43:44.474563 | 2018-10-08T18:39:03 | 2018-10-08T18:39:03 | 152,107,950 | 0 | 0 | null | 2018-10-08T16:00:37 | 2018-10-08T16:00:37 | null | UTF-8 | Python | false | false | 244 | py | #!/usr/bin/env python
#####################################
# Installation module for w3af
#####################################
AUTHOR="Justin Fry"
INSTALL_TYPE="GIT"
REPOSITORY_LOCATION="https://github.com/andresriancho/w3af"
LAUNCHER="w3af"
| [
"[email protected]"
] | |
47bcf163541fb59722252c3f339c87df5bc27d1b | a8a5772674e62beaa4f5b1f115d280103fd03749 | /metstationdistance.py | 06718ded3fcc86dd7af918765369d469f2ed4e6b | [] | no_license | tahentx/pv_workbook | c6fb3309d9acde5302dd3ea06a34ad2aee0de4b7 | 08912b0ef36a5226d23fa0430216a3f277aca33b | refs/heads/master | 2022-12-12T20:39:35.688510 | 2021-03-30T03:20:54 | 2021-03-30T03:20:54 | 172,827,250 | 0 | 1 | null | 2022-12-08T16:47:39 | 2019-02-27T02:25:24 | Python | UTF-8 | Python | false | false | 591 | py | import csv
from haversine import haversine
with open('tucson.csv') as file:
has_header = csv.Sniffer().has_header(file.read(1024))
file.seek(0)
met = csv.reader(file)
if has_header:
next(met)
met_list = list(met)
coords = []
for x in met_list:
coords.append(x[1:])
print(coords)
#
# def find_backup_metstation(coordinates: list) -> list:
# backup_mets = []
# for i in range(len(coordinates)-1):
# backup_mets.append(haversine(coordinates[i], coordinates[i + 1],unit='mi'))
# print(type(coordinates[i]))
#
# find_backup_metstation(coords)
| [
"[email protected]"
] | |
ce1d4c9f9dae392dbcd0c9e6cec095469f9b8092 | 0fccee4c738449f5e0a8f52ea5acabf51db0e910 | /genfragments/ThirteenTeV/BulkGraviton/BulkGraviton_VBF_WW_inclu_narrow_M4000_13TeV-madgraph_cff.py | 2bcf409e757355e8832799dc74ad7539b4678a06 | [] | no_license | cms-sw/genproductions | f308ffaf3586c19b29853db40e6d662e937940ff | dd3d3a3826343d4f75ec36b4662b6e9ff1f270f4 | refs/heads/master | 2023-08-30T17:26:02.581596 | 2023-08-29T14:53:43 | 2023-08-29T14:53:43 | 11,424,867 | 69 | 987 | null | 2023-09-14T12:41:28 | 2013-07-15T14:18:33 | Python | UTF-8 | Python | false | false | 797 | py | import FWCore.ParameterSet.Config as cms
# link to cards:
# https://github.com/cms-sw/genproductions/tree/91ab3ea30e3c2280e4c31fdd7072a47eb2e5bdaa/bin/MadGraph5_aMCatNLO/cards/production/13TeV/exo_diboson/Spin-2/BulkGraviton_VBF_WW_inclu/BulkGraviton_VBF_WW_inclu_narrow_M4000
externalLHEProducer = cms.EDProducer("ExternalLHEProducer",
args = cms.vstring('/cvmfs/cms.cern.ch/phys_generator/gridpacks/slc6_amd64_gcc481/13TeV/madgraph/V5_2.2.2/exo_diboson/Spin-2/BulkGraviton_VBF_WW_inclu/narrow/v1/BulkGraviton_VBF_WW_inclu_narrow_M4000_tarball.tar.xz'),
nEvents = cms.untracked.uint32(5000),
numberOfParameters = cms.uint32(1),
outputFile = cms.string('cmsgrid_final.lhe'),
scriptName = cms.FileInPath('GeneratorInterface/LHEInterface/data/run_generic_tarball_cvmfs.sh')
)
| [
"[email protected]"
] | |
c441b84ad77af9e2410f70a7eb69c516673a72a5 | 8e67d8618b9be7c777597b650876fa20082a6ebb | /14501.py | 74d650e562528e9b9e0e32bd3b717523cf2ba523 | [] | no_license | ljm9748/practice_codingtest | c5a2cc315c1ccd8f48a9424d13d2097c9fed0efc | 367710238976c1a2f8b42bfc3fc2936c47b195c5 | refs/heads/master | 2023-01-14T12:29:32.530648 | 2020-11-18T17:49:50 | 2020-11-18T17:49:50 | 282,162,451 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 284 | py |
n=int(input())
myinp=[]
for _ in range(n):
myinp.append(list(map(int, input().split())))
dp=[0]*(n)
for i in range(n):
day=myinp[i][0]
val=myinp[i][1]
if i+day-1<=(n-1):
for j in range(i+day-1, n):
dp[j]=max(dp[j], dp[i+day-2]+val)
print(dp[n-1]) | [
"[email protected]"
] | |
2855a822a742a7fbeb6e50814966d36d5e36be0c | 61a856d931688a49435b3caab4e9d674ca2a32aa | /tests/test_zeroDS.py | 27f6636792c8ed111a8de6cd4169b2281cecf6d1 | [
"Apache-2.0"
] | permissive | kvt0012/NeMo | 3c9803be76c7a2ef8d5cab6995ff1ef058144ffe | 6ad05b45c46edb5d44366bd0703915075f72b4fc | refs/heads/master | 2020-08-14T16:59:18.702254 | 2019-10-14T22:46:48 | 2019-10-14T22:46:48 | 215,203,912 | 1 | 0 | Apache-2.0 | 2019-10-15T04:05:37 | 2019-10-15T04:05:34 | null | UTF-8 | Python | false | false | 4,613 | py | import unittest
import os
import tarfile
import torch
from ruamel.yaml import YAML
from nemo.core.neural_types import *
from .context import nemo, nemo_asr
from .common_setup import NeMoUnitTest
class TestZeroDL(NeMoUnitTest):
labels = ["'", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q",
"r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
manifest_filepath = "tests/data/asr/an4_train.json"
yaml = YAML(typ="safe")
def setUp(self) -> None:
super().setUp()
data_folder = "tests/data/"
print("Looking up for test ASR data")
if not os.path.exists(data_folder + "nemo_asr"):
print(f"Extracting ASR data to: {data_folder + 'nemo_asr'}")
tar = tarfile.open("tests/data/asr.tar.gz", "r:gz")
tar.extractall(path=data_folder)
tar.close()
else:
print("ASR data found in: {0}".format(data_folder + "asr"))
def test_simple_train(self):
print("Simplest train test with ZeroDL")
neural_factory = nemo.core.neural_factory.NeuralModuleFactory(
backend=nemo.core.Backend.PyTorch, create_tb_writer=False)
trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4)
data_source = nemo.backends.pytorch.common.ZerosDataLayer(
size=10000,
dtype=torch.FloatTensor,
batch_size=128,
output_ports={
"x": NeuralType({
0: AxisType(BatchTag),
1: AxisType(ChannelTag, dim=1)}),
"y": NeuralType({
0: AxisType(BatchTag),
1: AxisType(ChannelTag, dim=1)})})
loss = nemo.backends.pytorch.tutorials.MSELoss()
x, y = data_source()
y_pred = trainable_module(x=x)
loss_tensor = loss(predictions=y_pred, target=y)
callback = nemo.core.SimpleLossLoggerCallback(
tensors=[loss_tensor],
print_func=lambda x: print(f'Train Loss: {str(x[0].item())}'))
neural_factory.train(
[loss_tensor], callbacks=[callback],
optimization_params={"num_epochs": 3, "lr": 0.0003},
optimizer="sgd")
def test_asr_with_zero_ds(self):
print("Testing ASR NMs with ZeroDS and without pre-processing")
with open("tests/data/jasper_smaller.yaml") as file:
jasper_model_definition = self.yaml.load(file)
dl = nemo.backends.pytorch.common.ZerosDataLayer(
size=100, dtype=torch.FloatTensor,
batch_size=4,
output_ports={
"processed_signal": NeuralType(
{0: AxisType(BatchTag),
1: AxisType(SpectrogramSignalTag, dim=64),
2: AxisType(ProcessedTimeTag, dim=64)}),
"processed_length": NeuralType(
{0: AxisType(BatchTag)}),
"transcript": NeuralType({0: AxisType(BatchTag),
1: AxisType(TimeTag, dim=64)}),
"transcript_length": NeuralType({0: AxisType(BatchTag)})
})
jasper_encoder = nemo_asr.JasperEncoder(
feat_in=jasper_model_definition['AudioPreprocessing']['features'],
**jasper_model_definition["JasperEncoder"])
jasper_decoder = nemo_asr.JasperDecoderForCTC(
feat_in=1024,
num_classes=len(self.labels)
)
ctc_loss = nemo_asr.CTCLossNM(num_classes=len(self.labels))
# DAG
processed_signal, p_length, transcript, transcript_len = dl()
encoded, encoded_len = jasper_encoder(audio_signal=processed_signal,
length=p_length)
# print(jasper_encoder)
log_probs = jasper_decoder(encoder_output=encoded)
loss = ctc_loss(log_probs=log_probs,
targets=transcript,
input_length=encoded_len,
target_length=transcript_len)
callback = nemo.core.SimpleLossLoggerCallback(
tensors=[loss],
print_func=lambda x: print(f'Train Loss: {str(x[0].item())}'))
# Instantiate an optimizer to perform `train` action
neural_factory = nemo.core.NeuralModuleFactory(
backend=nemo.core.Backend.PyTorch, local_rank=None,
create_tb_writer=False)
neural_factory.train(
[loss], callbacks=[callback],
optimization_params={"num_epochs": 2, "lr": 0.0003},
optimizer="sgd")
| [
"[email protected]"
] | |
a18ded8aafe21fcfb2e4ec9504aab06e4e2a2770 | cad9ea1b8c1909d50a843426d994947f628bf890 | /MARS-IEEE_IOT-HAR/MARS-v3.py | da2ad002cac6dde0c51a29d2a4891eb889b18b39 | [] | no_license | xiaogaogaoxiao/MARS-IEEE_IoT-HAR | a50a34f0e8813f032d0dc326a2b397180dc13a7c | dfd5a83ef0fb9942aaba2a8c22f73e6c14c5e99f | refs/heads/main | 2023-07-01T00:18:56.583927 | 2021-08-10T08:25:06 | 2021-08-10T08:25:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,595 | py | # multi-model
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pickle as pkl
import matplotlib
import matplotlib.pyplot as plt
import sklearn.metrics as metrics
import torch.nn.functional as F
import itertools
import torch.utils.data as dataf
from sklearn import utils as skutils
import pandas as pd
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
import MARS_Code.utils as utils
import torch
from torch import nn
import argparse
from sliding_window import sliding_window
parser = argparse.ArgumentParser(description='MARS_HAR')
parser.add_argument('--batch-size', type=int, default=100, metavar='N',
help='input batch size for training (default: 100)')
parser.add_argument('--epochs', type=int, default=200, metavar='N',
help='number of epochs to train (default: 200)')
parser.add_argument('--lr', type=float, default=0.001, metavar='LR',
help='learning rate (default: 0.001)')
parser.add_argument('--weight-decay', '--wd', default=1e-3, type=float,
metavar='W', help='weight decay (default: 1e-3)')
parser.add_argument('--imu-num', type=int, default=3,
metavar='N', help='Imu number (default: 3)')
parser.add_argument('--window-length', type=int, default=60,
metavar='N', help='sliding window length (default: 60)')
parser.add_argument('--window-step', type=int, default=30,
metavar='N', help='window step (default: 30)')
args = parser.parse_args()
global IMU_NUM
IMU_NUM = args.imu_num
NB_SENSOR_CHANNELS = IMU_NUM * 12
SLIDING_WINDOW_LENGTH = args.window_length
SLIDING_WINDOW_STEP = args.window_step
BATCH_SIZE = args.batch_size
# Load Data
x_train, y_train, x_test, y_test = utils.load_dataset('/home/xspc/Downloads/Pose_dataset/xspc_DIP_dataset/DIP_8_2/DIP_3IMU_82.pkl')
print('size of yt_train is:', y_train.shape)
print("size of xt_train is", x_train.shape)
assert NB_SENSOR_CHANNELS == x_train.shape[1]
x_train, y_train = utils.opp_sliding_window(x_train, y_train, SLIDING_WINDOW_LENGTH, SLIDING_WINDOW_STEP)
x_test, y_test = utils.opp_sliding_window(x_test, y_test, SLIDING_WINDOW_LENGTH, SLIDING_WINDOW_STEP)
# Data is reshaped
X_train = np.array(x_train)
X_test = np.array(x_test)
X_train = X_train.reshape(-1, SLIDING_WINDOW_LENGTH, NB_SENSOR_CHANNELS) # for input to Conv1D
X_test = X_test.reshape(-1, SLIDING_WINDOW_LENGTH, NB_SENSOR_CHANNELS) # for input to Conv1D
print(" ..after sliding and reshaping, train data: inputs {0}, labels {1}".format(X_train.shape, y_train.shape))
print(" ..after sliding and reshaping, test data : inputs {0}, labels {1}".format(X_test.shape, y_test.shape))
X_train, y_train = skutils.shuffle(X_train, y_train, random_state=42)
X_test, y_test = skutils.shuffle(X_test, y_test, random_state=42)
y_train = y_train.astype(np.int8)
y_test = y_test.astype(np.int8)
dataset_train = utils.Dataset(X_train, y_train)
dataset_test = utils.Dataset(X_test, y_test)
train_loader = dataf.DataLoader(dataset_train, batch_size=100, drop_last=True)
test_loader = dataf.DataLoader(dataset_test, batch_size=100, drop_last=True)
class HARModel2(nn.Module):
def __init__(self, n_hidden=96, n_layers=1, n_filters=32, stride=2, stride1D = 1, BATCH_SIZE = 100,
n_classes=5, filter_size=4, fusion = 2): # out_channels= 32,
super(HARModel2, self).__init__()
self.fusion = fusion
self.n_layers = n_layers
self.n_hidden = n_hidden
self.n_filters = n_filters
self.n_classes = n_classes
self.filter_size = filter_size
self.stride = stride
self.stride1D = stride1D
self.in_channels = NB_SENSOR_CHANNELS
self.BATCH_SIZE = BATCH_SIZE
# self.out_channels = out_channels
self.net1d0 = nn.Sequential(
nn.Conv1d(self.in_channels, self.n_filters, kernel_size=self.filter_size, stride=stride1D),
nn.BatchNorm1d(n_filters),
nn.ReLU(),
nn.Conv1d(self.n_filters, 2 * self.n_filters, kernel_size=self.filter_size, stride=stride1D),
nn.BatchNorm1d(2 * n_filters),
nn.ReLU(),
nn.Conv1d(2 * self.n_filters, 3 * self.n_filters, kernel_size=self.filter_size, stride=stride1D),
nn.BatchNorm1d(3 * self.n_filters),
nn.ReLU(),
nn.Conv1d(3 * self.n_filters, 4 * self.n_filters, kernel_size=self.filter_size, stride=stride1D),
nn.BatchNorm1d(4 * n_filters),
nn.ReLU(),
)
self.net1d3 = nn.Sequential(
nn.ConvTranspose1d(4 * self.n_filters, 3 * self.n_filters, kernel_size=self.filter_size,
stride=stride1D, output_padding=stride1D - 1),
nn.BatchNorm1d(3 * self.n_filters),
nn.ReLU(),
nn.ConvTranspose1d(3 * self.n_filters, 2 * self.n_filters, kernel_size=self.filter_size,
stride=stride1D),
nn.BatchNorm1d(2 * n_filters),
nn.ReLU(),
nn.ConvTranspose1d(2 * self.n_filters, 1 * self.n_filters, kernel_size=self.filter_size,
stride=stride1D),
nn.BatchNorm1d(1 * self.n_filters),
nn.ReLU(),
nn.ConvTranspose1d(self.n_filters, self.in_channels, kernel_size=self.filter_size,
stride=stride1D, output_padding=stride1D - 1),
)
self.net2d0 = nn.Sequential(
nn.Conv2d(1, n_filters, kernel_size=self.filter_size, stride=self.stride), #
nn.BatchNorm2d(n_filters),
nn.ReLU(),
nn.Conv2d(n_filters, 2 * n_filters, kernel_size=self.filter_size, stride=self.stride),
nn.BatchNorm2d(2 * n_filters),
nn.ReLU(),
nn.Conv2d(2 * n_filters, 2 * n_filters, kernel_size=self.filter_size, stride=self.stride-1),
nn.BatchNorm2d(2 * n_filters),
nn.ReLU(),
nn.Conv2d(2 * n_filters, 3 * n_filters, kernel_size=self.filter_size, stride=self.stride-1),
nn.BatchNorm2d(3 * n_filters),
nn.ReLU(),
# nn.Flatten()
)
self.net2d3 = nn.Sequential(
nn.ConvTranspose2d(3 * n_filters, 2 * n_filters, kernel_size=self.filter_size, stride=self.stride-1),
nn.BatchNorm2d(2 * n_filters),
nn.ReLU(),
nn.ConvTranspose2d(2 * n_filters, 2 * n_filters, kernel_size=self.filter_size, stride=self.stride-1),
nn.BatchNorm2d(2 * n_filters),
nn.ReLU(),
nn.ConvTranspose2d(2 * n_filters, n_filters, kernel_size=self.filter_size, stride=self.stride, output_padding=(1,1)),
nn.BatchNorm2d(1 * n_filters),
nn.ReLU(),
nn.ConvTranspose2d(n_filters, 1, kernel_size=self.filter_size, stride=self.stride),
)
self.net1d1 = nn.Sequential(
nn.Linear(4 * self.n_filters * 48, self.n_hidden),
nn.ReLU(),
)
self.net1d2 = nn.Sequential(
nn.Linear(self.n_hidden, 4 * self.n_filters * 48),
nn.ReLU(),
)
self.net2d1 = nn.Sequential(
nn.Linear(672, self.n_hidden),
nn.ReLU(),
)
self.net2d2 = nn.Sequential(
nn.Linear(self.n_hidden, 672),
nn.ReLU(),
)
self.netC = nn.Sequential(
nn.Linear(self.n_hidden, self.n_classes),
nn.ReLU(),
nn.Linear(self.n_classes, self.n_classes),
# nn.ReLU(),
)
self.net_feature_fusion = nn.Sequential(
nn.Linear(self.n_hidden, self.n_hidden),
# nn.BatchNorm1d(self.n_classes),
nn.Sigmoid(),
)
self.fc = nn.Sequential(
nn.Linear(6816, 1024),
# nn.BatchNorm1d(self.n_classes),
nn.ReLU(),
nn.Linear(1024, self.n_hidden),
# nn.BatchNorm1d(self.n_classes),
nn.ReLU(),
nn.Linear(self.n_hidden, self.n_classes),
# nn.BatchNorm1d(self.n_classes),
nn.Sigmoid(),
)
# def latent_feature_fusion(self, latent_feature):
# latent_feature1 = nn.Linear(latent_feature.shape[1], self.n_hidden)
# return latent_feature_fused ### size equals to batch size * n_hidden
def KL_Distance(self, f1, f2):
criterion_KL = nn.KLDivLoss(reduce=True)
log_probs1 = F.log_softmax(f1, 1)
probs1 = F.softmax(f1, 1)
log_probs2 = F.log_softmax(f2, 1)
probs2 = F.softmax(f2, 1)
Distance_estimate = (criterion_KL(log_probs1, probs2) + criterion_KL(log_probs2, probs1))/2
return Distance_estimate
def forward(self, x):
### 1D
x1d = x.view(-1, NB_SENSOR_CHANNELS, SLIDING_WINDOW_LENGTH)
l1_1d = self.net1d0(x1d)
l1_1d = l1_1d.view(self.BATCH_SIZE, -1)
x1f = self.net1d1(l1_1d)
l3_1d = self.net1d2(x1f)
l3_1d = l3_1d.view(x1f.size(0), 4 * self.n_filters, 48)
recon_x_1d = self.net1d3(l3_1d)
recon_x_1d = recon_x_1d.view(-1, SLIDING_WINDOW_LENGTH, NB_SENSOR_CHANNELS)
### 2D
x2d = x.view(-1, 1, SLIDING_WINDOW_LENGTH, NB_SENSOR_CHANNELS)
l1_2d = self.net2d0(x2d)
l1_2d = l1_2d.view(self.BATCH_SIZE, -1)
x2f = self.net2d1(l1_2d)
l3_2d = self.net2d2(x2f)
l3_2d = l3_2d.view(x2f.size(0), 3 * self.n_filters, 7, 1)
recon_x_2d = self.net2d3(l3_2d)
latent_feature1, latent_feature2 = self.net_feature_fusion(x1f), self.net_feature_fusion(x2f)
# if self.fusion == 2:
reduced_dim_x = self.netC(x1f.mul(self.net_feature_fusion(x1f)) + x2f.mul(1 - self.net_feature_fusion(x2f)))
SDKL = self.KL_Distance(latent_feature1, latent_feature2)
# print('size of SDKL is:', SDKL.shape)
# reduced_dim_x = self.netC(x1f + x2f) # fusion method II
return recon_x_1d, reduced_dim_x, recon_x_2d, SDKL
def init_hidden(self):
""" Initializes hidden state """
# Create two new tensors with sizes n_layers x BATCH_SIZE x n_hidden,
# initialized to zero, for hidden state and cell state of LSTM
weight = next(self.parameters()).data
if train_on_gpu:
hidden = (nn.init.zeros_(weight.new(self.n_layers, self.BATCH_SIZE, self.n_hidden)).cuda(),
nn.init.zeros_(weight.new(self.n_layers, self.BATCH_SIZE, self.n_hidden)).cuda())
else:
hidden = (weight.new(self.n_layers, self.BATCH_SIZE, self.n_hidden).xavier_normal_(),
weight.new(self.n_layers, self.BATCH_SIZE, self.n_hidden).xavier_normal_())
return hidden
net = HARModel2()
# check if GPU is available
train_on_gpu = torch.cuda.is_available()
if train_on_gpu:
print('Training on GPU!')
else:
print('No GPU available, training on CPU; consider making n_epochs very small')
opt = torch.optim.Adam(net.parameters(), lr=args.lr)
criterion1 = nn.CrossEntropyLoss()
criterion2 = nn.MSELoss()
if train_on_gpu:
net.cuda()
best_acc = 0
def train(epoch):
net.train()
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode='min', factor=0.99, patience=4)
print("Learning rate:", opt.defaults['lr'])
train_losses = []
train_acc = 0
batch_j = 0
for i, data in enumerate(train_loader): # 一个batch、一个batch的往下走,对于train,先走完
x, y = data
inputs, targets = x, y
if train_on_gpu:
inputs, targets = inputs.cuda(), targets.cuda()
opt.zero_grad()
recon_output_1d, fused_output0, recon_output_2d, SDKL = net(inputs)
output01d = torch.squeeze(recon_output_1d)
output02d = torch.squeeze(recon_output_2d)
_, pred = torch.max(fused_output0, 1)
loss = criterion1(fused_output0, targets.long()) + 0.05 * criterion2(inputs, output01d) + \
0.05 * criterion2(inputs, output02d) + 0.01 * SDKL # 0.001 * 0.5 *
train_losses.append(loss.item())
train_acc += (pred == targets.long()).sum().item()
loss.backward() # 向后传播
opt.step()
print("第%d个epoch的学习率:%f" % (epoch + 1, opt.param_groups[0]['lr']))
scheduler.step(loss)
train_involved = (len(y_train) // BATCH_SIZE) * BATCH_SIZE
print("Epoch: {}/{}...".format(epoch + 1, args.epochs),
"Train Loss: {:.6f}...".format(np.mean(train_losses)),
"Train Acc: {:.6f}...".format(train_acc / train_involved), end=" ")
def test(epoch):
net.eval()
val_accuracy = 0
val_losses = []
global best_acc
with torch.no_grad():
for i, data in enumerate(test_loader): # 在一个batch中,一个个的往下走;
x, y = data
inputs, targets = x, y
if train_on_gpu:
inputs, targets = inputs.cuda(), targets.cuda()
_, fused_output, _, _ = net(inputs)
_, predicted = torch.max(fused_output, 1) # decision level fusion
val_loss = criterion1(fused_output, targets.long())
val_losses.append(val_loss.item())
val_accuracy += (predicted == targets.long()).sum().item()
test_involved = (len(y_test) // BATCH_SIZE) * BATCH_SIZE
print("Val Loss: {:.6f}...".format(np.mean(val_losses)),
"Val Acc: {:.6f}...".format(val_accuracy / test_involved))
if best_acc < val_accuracy / test_involved:
best_acc = val_accuracy / test_involved
print("best model find: {:.6f}...".format(best_acc))
torch.save(net,
'/home/xspc/Downloads/IMUPose_Code/xspc_test/MARS_Code/MARS_v3_result.pkl')
else:
print("no best model,the best is : {:.6f}...".format(best_acc))
try:
for epoch in range(args.epochs):
train(epoch)
test(epoch)
print("------Best Result--------")
print("Val Acc: {:.6f}...".format(best_acc))
except KeyboardInterrupt:
print("------Best Result--------")
print("Val Acc: {:.6f}...".format(best_acc))
| [
"[email protected]"
] | |
eaebb4666a97d396903989fc5c9df6e3c92ebdc2 | e13091c137650cd31c8d9778087b369033d0cf96 | /src/main/python/algo_expert/Algorithm Implementation /Sort/selection_sort.py | db348f63325d79466c26d8e70fdde8fcced1ec7b | [] | no_license | jwoojun/CodingTest | 634e2cfe707b74c080ddbe5f32f58c1e6d849968 | d62479d168085f13e73dfc1697c5438a97632d29 | refs/heads/master | 2023-08-22T09:03:32.392293 | 2021-10-31T01:00:33 | 2021-10-31T01:00:33 | 300,534,767 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 253 | py | # selection_sort
def selection_sort(lst) :
for i in range(len(lst)-1) :
min_ = i
for j in range(i+1, len(lst)) :
if lst[min_] > lst[j] :
min_ = j
lst[i], lst[min_] = lst[min_], lst[i]
return lst
| [
"[email protected]"
] | |
cabb3418558dc0ccf9392089c057427ce71ee217 | 48e124e97cc776feb0ad6d17b9ef1dfa24e2e474 | /sdk/python/pulumi_azure_native/containerregistry/v20210601preview/get_registry.py | 946c32d8ea4c071d5a7c0fdf5ea8694660f0870d | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | bpkgoud/pulumi-azure-native | 0817502630062efbc35134410c4a784b61a4736d | a3215fe1b87fba69294f248017b1591767c2b96c | refs/heads/master | 2023-08-29T22:39:49.984212 | 2021-11-15T12:43:41 | 2021-11-15T12:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,021 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetRegistryResult',
'AwaitableGetRegistryResult',
'get_registry',
'get_registry_output',
]
@pulumi.output_type
class GetRegistryResult:
"""
An object that represents a container registry.
"""
def __init__(__self__, admin_user_enabled=None, anonymous_pull_enabled=None, creation_date=None, data_endpoint_enabled=None, data_endpoint_host_names=None, encryption=None, id=None, identity=None, location=None, login_server=None, name=None, network_rule_bypass_options=None, network_rule_set=None, policies=None, private_endpoint_connections=None, provisioning_state=None, public_network_access=None, sku=None, status=None, system_data=None, tags=None, type=None, zone_redundancy=None):
if admin_user_enabled and not isinstance(admin_user_enabled, bool):
raise TypeError("Expected argument 'admin_user_enabled' to be a bool")
pulumi.set(__self__, "admin_user_enabled", admin_user_enabled)
if anonymous_pull_enabled and not isinstance(anonymous_pull_enabled, bool):
raise TypeError("Expected argument 'anonymous_pull_enabled' to be a bool")
pulumi.set(__self__, "anonymous_pull_enabled", anonymous_pull_enabled)
if creation_date and not isinstance(creation_date, str):
raise TypeError("Expected argument 'creation_date' to be a str")
pulumi.set(__self__, "creation_date", creation_date)
if data_endpoint_enabled and not isinstance(data_endpoint_enabled, bool):
raise TypeError("Expected argument 'data_endpoint_enabled' to be a bool")
pulumi.set(__self__, "data_endpoint_enabled", data_endpoint_enabled)
if data_endpoint_host_names and not isinstance(data_endpoint_host_names, list):
raise TypeError("Expected argument 'data_endpoint_host_names' to be a list")
pulumi.set(__self__, "data_endpoint_host_names", data_endpoint_host_names)
if encryption and not isinstance(encryption, dict):
raise TypeError("Expected argument 'encryption' to be a dict")
pulumi.set(__self__, "encryption", encryption)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if identity and not isinstance(identity, dict):
raise TypeError("Expected argument 'identity' to be a dict")
pulumi.set(__self__, "identity", identity)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if login_server and not isinstance(login_server, str):
raise TypeError("Expected argument 'login_server' to be a str")
pulumi.set(__self__, "login_server", login_server)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if network_rule_bypass_options and not isinstance(network_rule_bypass_options, str):
raise TypeError("Expected argument 'network_rule_bypass_options' to be a str")
pulumi.set(__self__, "network_rule_bypass_options", network_rule_bypass_options)
if network_rule_set and not isinstance(network_rule_set, dict):
raise TypeError("Expected argument 'network_rule_set' to be a dict")
pulumi.set(__self__, "network_rule_set", network_rule_set)
if policies and not isinstance(policies, dict):
raise TypeError("Expected argument 'policies' to be a dict")
pulumi.set(__self__, "policies", policies)
if private_endpoint_connections and not isinstance(private_endpoint_connections, list):
raise TypeError("Expected argument 'private_endpoint_connections' to be a list")
pulumi.set(__self__, "private_endpoint_connections", private_endpoint_connections)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if public_network_access and not isinstance(public_network_access, str):
raise TypeError("Expected argument 'public_network_access' to be a str")
pulumi.set(__self__, "public_network_access", public_network_access)
if sku and not isinstance(sku, dict):
raise TypeError("Expected argument 'sku' to be a dict")
pulumi.set(__self__, "sku", sku)
if status and not isinstance(status, dict):
raise TypeError("Expected argument 'status' to be a dict")
pulumi.set(__self__, "status", status)
if system_data and not isinstance(system_data, dict):
raise TypeError("Expected argument 'system_data' to be a dict")
pulumi.set(__self__, "system_data", system_data)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
if zone_redundancy and not isinstance(zone_redundancy, str):
raise TypeError("Expected argument 'zone_redundancy' to be a str")
pulumi.set(__self__, "zone_redundancy", zone_redundancy)
@property
@pulumi.getter(name="adminUserEnabled")
def admin_user_enabled(self) -> Optional[bool]:
"""
The value that indicates whether the admin user is enabled.
"""
return pulumi.get(self, "admin_user_enabled")
@property
@pulumi.getter(name="anonymousPullEnabled")
def anonymous_pull_enabled(self) -> Optional[bool]:
"""
Enables registry-wide pull from unauthenticated clients.
"""
return pulumi.get(self, "anonymous_pull_enabled")
@property
@pulumi.getter(name="creationDate")
def creation_date(self) -> str:
"""
The creation date of the container registry in ISO8601 format.
"""
return pulumi.get(self, "creation_date")
@property
@pulumi.getter(name="dataEndpointEnabled")
def data_endpoint_enabled(self) -> Optional[bool]:
"""
Enable a single data endpoint per region for serving data.
"""
return pulumi.get(self, "data_endpoint_enabled")
@property
@pulumi.getter(name="dataEndpointHostNames")
def data_endpoint_host_names(self) -> Sequence[str]:
"""
List of host names that will serve data when dataEndpointEnabled is true.
"""
return pulumi.get(self, "data_endpoint_host_names")
@property
@pulumi.getter
def encryption(self) -> Optional['outputs.EncryptionPropertyResponse']:
"""
The encryption settings of container registry.
"""
return pulumi.get(self, "encryption")
@property
@pulumi.getter
def id(self) -> str:
"""
The resource ID.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def identity(self) -> Optional['outputs.IdentityPropertiesResponse']:
"""
The identity of the container registry.
"""
return pulumi.get(self, "identity")
@property
@pulumi.getter
def location(self) -> str:
"""
The location of the resource. This cannot be changed after the resource is created.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter(name="loginServer")
def login_server(self) -> str:
"""
The URL that can be used to log into the container registry.
"""
return pulumi.get(self, "login_server")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="networkRuleBypassOptions")
def network_rule_bypass_options(self) -> Optional[str]:
"""
Whether to allow trusted Azure services to access a network restricted registry.
"""
return pulumi.get(self, "network_rule_bypass_options")
@property
@pulumi.getter(name="networkRuleSet")
def network_rule_set(self) -> Optional['outputs.NetworkRuleSetResponse']:
"""
The network rule set for a container registry.
"""
return pulumi.get(self, "network_rule_set")
@property
@pulumi.getter
def policies(self) -> Optional['outputs.PoliciesResponse']:
"""
The policies for a container registry.
"""
return pulumi.get(self, "policies")
@property
@pulumi.getter(name="privateEndpointConnections")
def private_endpoint_connections(self) -> Sequence['outputs.PrivateEndpointConnectionResponse']:
"""
List of private endpoint connections for a container registry.
"""
return pulumi.get(self, "private_endpoint_connections")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> str:
"""
The provisioning state of the container registry at the time the operation was called.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="publicNetworkAccess")
def public_network_access(self) -> Optional[str]:
"""
Whether or not public network access is allowed for the container registry.
"""
return pulumi.get(self, "public_network_access")
@property
@pulumi.getter
def sku(self) -> 'outputs.SkuResponse':
"""
The SKU of the container registry.
"""
return pulumi.get(self, "sku")
@property
@pulumi.getter
def status(self) -> 'outputs.StatusResponse':
"""
The status of the container registry at the time the operation was called.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter(name="systemData")
def system_data(self) -> 'outputs.SystemDataResponse':
"""
Metadata pertaining to creation and last modification of the resource.
"""
return pulumi.get(self, "system_data")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
The tags of the resource.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="zoneRedundancy")
def zone_redundancy(self) -> Optional[str]:
"""
Whether or not zone redundancy is enabled for this container registry
"""
return pulumi.get(self, "zone_redundancy")
class AwaitableGetRegistryResult(GetRegistryResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetRegistryResult(
admin_user_enabled=self.admin_user_enabled,
anonymous_pull_enabled=self.anonymous_pull_enabled,
creation_date=self.creation_date,
data_endpoint_enabled=self.data_endpoint_enabled,
data_endpoint_host_names=self.data_endpoint_host_names,
encryption=self.encryption,
id=self.id,
identity=self.identity,
location=self.location,
login_server=self.login_server,
name=self.name,
network_rule_bypass_options=self.network_rule_bypass_options,
network_rule_set=self.network_rule_set,
policies=self.policies,
private_endpoint_connections=self.private_endpoint_connections,
provisioning_state=self.provisioning_state,
public_network_access=self.public_network_access,
sku=self.sku,
status=self.status,
system_data=self.system_data,
tags=self.tags,
type=self.type,
zone_redundancy=self.zone_redundancy)
def get_registry(registry_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegistryResult:
"""
An object that represents a container registry.
:param str registry_name: The name of the container registry.
:param str resource_group_name: The name of the resource group to which the container registry belongs.
"""
__args__ = dict()
__args__['registryName'] = registry_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:containerregistry/v20210601preview:getRegistry', __args__, opts=opts, typ=GetRegistryResult).value
return AwaitableGetRegistryResult(
admin_user_enabled=__ret__.admin_user_enabled,
anonymous_pull_enabled=__ret__.anonymous_pull_enabled,
creation_date=__ret__.creation_date,
data_endpoint_enabled=__ret__.data_endpoint_enabled,
data_endpoint_host_names=__ret__.data_endpoint_host_names,
encryption=__ret__.encryption,
id=__ret__.id,
identity=__ret__.identity,
location=__ret__.location,
login_server=__ret__.login_server,
name=__ret__.name,
network_rule_bypass_options=__ret__.network_rule_bypass_options,
network_rule_set=__ret__.network_rule_set,
policies=__ret__.policies,
private_endpoint_connections=__ret__.private_endpoint_connections,
provisioning_state=__ret__.provisioning_state,
public_network_access=__ret__.public_network_access,
sku=__ret__.sku,
status=__ret__.status,
system_data=__ret__.system_data,
tags=__ret__.tags,
type=__ret__.type,
zone_redundancy=__ret__.zone_redundancy)
@_utilities.lift_output_func(get_registry)
def get_registry_output(registry_name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetRegistryResult]:
"""
An object that represents a container registry.
:param str registry_name: The name of the container registry.
:param str resource_group_name: The name of the resource group to which the container registry belongs.
"""
...
| [
"[email protected]"
] | |
6aff8bc6b2649dd67495d446bfea943bd810d87e | 24e7e0dfaaeaca8f911b40fcc2937342a0f278fd | /venv/Lib/site-packages/pygments/plugin.py | 76e8f6cb61c2c456a487266d8ae4197c7a0293af | [
"MIT"
] | permissive | BimiLevi/Covid19 | 90e234c639192d62bb87364ef96d6a46d8268fa0 | 5f07a9a4609383c02597373d76d6b6485d47936e | refs/heads/master | 2023-08-04T13:13:44.480700 | 2023-08-01T08:36:36 | 2023-08-01T08:36:36 | 288,455,446 | 1 | 0 | MIT | 2021-01-22T19:36:26 | 2020-08-18T12:53:43 | HTML | UTF-8 | Python | false | false | 1,734 | py | # -*- coding: utf-8 -*-
"""
pygments.plugin
~~~~~~~~~~~~~~~
Pygments setuptools plugin interface. The methods defined
here also work if setuptools isn't installed but they just
return nothing.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.formatters]
yourformatter = yourformatter:YourFormatter
/.ext = yourformatter:YourFormatter
As you can see, you can define extensions for the formatter
with a leading slash.
syntax plugins::
[pygments.styles]
yourstyle = yourstyle:YourStyle
filter plugin::
[pygments.filter]
yourfilter = yourfilter:YourFilter
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
LEXER_ENTRY_POINT = 'pygments.lexers'
FORMATTER_ENTRY_POINT = 'pygments.formatters'
STYLE_ENTRY_POINT = 'pygments.styles'
FILTER_ENTRY_POINT = 'pygments.filters'
def iter_entry_points(group_name):
try:
import pkg_resources
except (ImportError, IOError):
return []
return pkg_resources.iter_entry_points(group_name)
def find_plugin_lexers():
for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):
yield entrypoint.load()
def find_plugin_formatters():
for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_styles():
for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_filters():
for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
| [
"[email protected]"
] | |
964d74884c5d4fe523268950f181853cad302a7e | f77028577e88d228e9ce8252cc8e294505f7a61b | /web_backend/nvlserver/module/hw_module/specification/get_hw_module_specification.py | 2c708377f8fa3bf925fcbfc53584e58eb50737ec | [] | no_license | Sud-26/Arkally | e82cebb7f907a3869443b714de43a1948d42519e | edf519067d0ac4c204c12450b6f19a446afc327e | refs/heads/master | 2023-07-07T02:14:28.012545 | 2021-08-06T10:29:42 | 2021-08-06T10:29:42 | 392,945,826 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,170 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
get_hw_module_list_query = """
SELECT hwm.id AS id,
hwm.name AS name,
COALESCE(hwm.module_id::VARCHAR, '') AS module_id,
hwm.user_id AS user_id,
coalesce(usr.fullname, '') AS user_name,
hwm.traceable_object_id AS traceable_object_id,
coalesce(tob.name, '') AS traceable_object_name,
hwm.meta_information::json AS meta_information,
hwm.show_on_map AS show_on_map,
hwm.gprs_active AS gprs_active,
hwm.active AS active,
hwm.deleted AS deleted,
hwm.created_on AS created_on,
hwm.updated_on AS updated_on
FROM public.hw_module AS hwm
LEFT OUTER JOIN public.user AS usr ON usr.id = hwm.user_id
LEFT OUTER JOIN public.traceable_object AS tob on hwm.traceable_object_id = tob.id
WHERE hwm.deleted is FALSE
AND ($1::BIGINT = 0 OR hwm.user_id = $1::BIGINT)
AND (
$2::VARCHAR is NULL OR
hwm.name ILIKE $2::VARCHAR || '%' OR
hwm.name ILIKE '%' || $2::VARCHAR || '%' OR
hwm.name ILIKE $2::VARCHAR || '%')
"""
get_hw_module_list_user_id_hw_module_id_list_query = """
SELECT hwm.id AS id
FROM public.hw_module AS hwm
WHERE hwm.deleted is FALSE AND hwm.active is TRUE
AND hwm.show_on_map IS TRUE
AND ($1::BIGINT IS NULL OR hwm.user_id = $1::BIGINT)
AND (array_length($2::int[], 1) IS NULL OR hwm.traceable_object_id = any ($2::int[]))
"""
get_hw_module_list_dropdown_query = """
SELECT hwm.id AS id,
hwm.name AS name
FROM public.hw_module AS hwm
WHERE hwm.deleted is FALSE AND hwm.active is TRUE
AND ($1::BIGINT IS NULL OR hwm.user_id = $1::BIGINT)
AND (
$2::VARCHAR is NULL OR
hwm.name ILIKE $2::VARCHAR || '%' OR
hwm.name ILIKE '%' || $2::VARCHAR || '%' OR
hwm.name ILIKE $2::VARCHAR || '%')
"""
get_hw_module_list_count_query = """
SELECT count(*) AS hw_module_count
FROM public.hw_module AS hwm
LEFT OUTER JOIN public.user AS usr ON usr.id = hwm.user_id
WHERE hwm.deleted is FALSE
AND ($1::BIGINT = 0 OR hwm.user_id = $1::BIGINT)
AND (
$2::VARCHAR is NULL OR
hwm.name ILIKE $2::VARCHAR || '%' OR
hwm.name ILIKE '%' || $2::VARCHAR || '%' OR
hwm.name ILIKE $2::VARCHAR || '%')
"""
get_hw_module_element_query = """
SELECT hwm.id AS id,
hwm.name AS name,
COALESCE(hwm.module_id::VARCHAR, '') AS module_id,
hwm.user_id AS user_id,
coalesce(usr.fullname, '') AS user_name,
hwm.traceable_object_id AS traceable_object_id,
coalesce(tob.name, '') AS traceable_object_name,
hwm.meta_information::json AS meta_information,
hwm.show_on_map AS show_on_map,
hwm.gprs_active AS gprs_active,
hwm.active AS active,
hwm.deleted AS deleted,
hwm.created_on AS created_on,
hwm.updated_on AS updated_on
FROM public.hw_module AS hwm
LEFT OUTER JOIN public.user AS usr ON usr.id = hwm.user_id
LEFT OUTER JOIN public.traceable_object AS tob on hwm.traceable_object_id = tob.id
WHERE hwm.deleted is FALSE
AND hwm.id = $1;
"""
get_hw_module_element_by_traceable_object_id_query = """
SELECT hwm.id AS id,
hwm.name AS name,
COALESCE(hwm.module_id::VARCHAR, '') AS module_id,
hwm.user_id AS user_id,
coalesce(usr.fullname, '') AS user_name,
hwm.traceable_object_id AS traceable_object_id,
coalesce(tob.name, '') AS traceable_object_name,
hwm.meta_information::json AS meta_information,
hwm.gprs_active AS gprs_active,
hwm.show_on_map AS show_on_map,
hwm.active AS active,
hwm.deleted AS deleted,
hwm.created_on AS created_on,
hwm.updated_on AS updated_on
FROM public.hw_module AS hwm
LEFT OUTER JOIN public.user AS usr ON usr.id = hwm.user_id
LEFT OUTER JOIN public.traceable_object AS tob on hwm.traceable_object_id = tob.id
WHERE hwm.deleted is FALSE
AND ($1::BIGINT is NULL OR hwm.user_id = $1::BIGINT)
AND hwm.traceable_object_id = $2;
"""
get_hw_module_element_by_name_query = """
SELECT hwm.id AS id,
hwm.name AS name,
COALESCE(hwm.module_id::VARCHAR, '') AS module_id,
hwm.user_id AS user_id,
coalesce(usr.fullname, '') AS user_name,
hwm.traceable_object_id AS traceable_object_id,
coalesce(tob.name, '') AS traceable_object_name,
hwm.meta_information::json AS meta_information,
hwm.gprs_active AS gprs_active,
hwm.show_on_map AS show_on_map,
hwm.active AS active,
hwm.deleted AS deleted,
hwm.created_on AS created_on,
hwm.updated_on AS updated_on
FROM public.hw_module AS hwm
LEFT OUTER JOIN public.user AS usr ON usr.id = hwm.user_id
LEFT OUTER JOIN public.traceable_object AS tob on hwm.traceable_object_id = tob.id
WHERE hwm.deleted is FALSE
AND (
$1::VARCHAR is NULL OR
hwm.name ILIKE $1::VARCHAR || '%' OR
hwm.name ILIKE '%' || $1::VARCHAR || '%' OR
hwm.name ILIKE $1::VARCHAR || '%')
LIMIT 1;
"""
| [
"[email protected]"
] | |
42d1ab3ce84114a87a59d9c3f9a7720ae4e57ece | bffe3ed7c76d488a685f1a586f08270d5a6a847b | /side_service/utils/importer.py | a6ea97b8f8a7a02c6df5fb58ea6838cd08c9642a | [] | no_license | ganggas95/side-service | 86a863d7b8d164e05584938aa63e56aa1ed8f793 | c58ee47d1145cb704c4268006f135a141efc0667 | refs/heads/nizar_dev | 2021-06-21T11:37:54.771478 | 2019-10-14T23:45:39 | 2019-10-14T23:45:39 | 213,881,364 | 0 | 1 | null | 2021-05-06T19:55:47 | 2019-10-09T09:52:06 | Python | UTF-8 | Python | false | false | 2,443 | py | import os
from numpy import int64
import pandas as pd
from flask import current_app as app
from side_service.models.prov import Provinsi
from side_service.models.kab import Kabupaten
from side_service.models.kec import Kecamatan
from side_service.models.desa import Desa
class FileImporter:
temps = []
def __init__(self, filename):
if filename:
self.df = pd.read_csv(os.path.join(
app.config["FILE_IMPORT_FOLDER"],
filename), header=None)
class ImportProvinceFile(FileImporter):
def read_data(self):
for row in range(0, len(self.df.index)):
kode_prov = str(self.df[0][self.df.index[row]])
name = self.df[1][self.df.index[row]]
prov = Provinsi(kode_prov, name)
prov.save()
print("Import Province is success")
class ImportRegenciesFile(FileImporter):
@property
def provs(self):
return Provinsi.all()
def read_data(self):
for prov in self.provs:
df_prov = self.df.loc[self.df[1] == int64(prov.kode_prov)]
for row in range(0, len(df_prov.index)):
kode_kab = str(df_prov[0][df_prov.index[row]])
name = df_prov[2][df_prov.index[row]]
kab = Kabupaten(kode_kab, name, prov.kode_prov)
kab.save()
print("Import Kabupaten is success")
class ImportDistrictFile(FileImporter):
@property
def kabs(self):
return Kabupaten.all()
def read_data(self):
for kab in self.kabs:
df_kab = self.df.loc[self.df[1] == int64(kab.kode_kab)]
for row in range(0, len(df_kab.index)):
kode_kec = str(df_kab[0][df_kab.index[row]])
name = df_kab[2][df_kab.index[row]]
kec = Kecamatan(kode_kec, name, kab.kode_kab)
kec.save()
print("Import District Success")
class ImportVillagesFile(FileImporter):
@property
def kecs(self):
return Kecamatan.all()
def read_data(self):
for kec in self.kecs:
df_desa = self.df.loc[self.df[1] == int64(kec.kode_kec)]
for row in range(0, len(df_desa.index)):
kode_desa = str(df_desa[0][df_desa.index[row]])
name = df_desa[2][df_desa.index[row]]
desa = Desa(kode_desa, name, kec.kode_kec)
desa.save()
print("Import Villages Success")
| [
"[email protected]"
] | |
485fa53a3ac3eaa8756d5ab54cf31b30b0eb63c8 | 1daac610a9954619b136507cbef8db313c24fa42 | /app/memory_cache/models.py | f69cc50f13703162f1f43536e2de8361e6d3f27c | [] | no_license | waynerv/memory-cache | b17a8d1c57382313e0b646e079a65f303b47bc2f | aa63044d9138b1da6149e54c8e83cb8d584451a1 | refs/heads/master | 2020-04-17T22:43:41.890703 | 2019-04-22T01:56:26 | 2019-04-22T01:56:26 | 167,005,947 | 8 | 1 | null | null | null | null | UTF-8 | Python | false | false | 10,970 | py | import os
from datetime import datetime
from flask import current_app
from flask_avatars import Identicon
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from memory_cache.extensions import db
from memory_cache.extensions import whooshee
tagging = db.Table('tagging',
db.Column('photo_id', db.Integer, db.ForeignKey('photo.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)
roles_permissions = db.Table('roles_permissions',
db.Column('role.id', db.Integer, db.ForeignKey('role.id')),
db.Column('permission.id', db.Integer, db.ForeignKey('permission.id'))
)
class Collect(db.Model):
collector_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
collected_id = db.Column(db.Integer, db.ForeignKey('photo.id'), primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow())
collector = db.relationship('User', back_populates='collections', lazy='joined')
collected = db.relationship('Photo', back_populates='collectors', lazy='joined')
class Follow(db.Model):
follower_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
followed_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow())
follower = db.relationship('User', foreign_keys=[follower_id], back_populates='following', lazy='joined')
followed = db.relationship('User', foreign_keys=[followed_id], back_populates='followers', lazy='joined')
@whooshee.register_model('username', 'name')
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
username = db.Column(db.String(20), unique=True, index=True)
password_hash = db.Column(db.String(128))
email = db.Column(db.String(254), unique=True, index=True)
website = db.Column(db.String(255))
bio = db.Column(db.Text)
location = db.Column(db.String(30))
member_since = db.Column(db.DateTime, default=datetime.utcnow())
confirmed = db.Column(db.Boolean)
photos = db.relationship('Photo', back_populates='author', cascade='all, delete')
notifications = db.relationship('Notification', back_populates='receiver', cascade='all, delete')
collections = db.relationship('Collect', back_populates='collector', cascade='all')
following = db.relationship('Follow', foreign_keys=[Follow.follower_id], back_populates='follower', lazy='dynamic',
cascade='all')
followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], back_populates='followed', lazy='dynamic',
cascade='all')
role_id = db.Column(db.Integer, db.ForeignKey('role.id'))
role = db.relationship('Role', back_populates='users')
comments = db.relationship('Comment', back_populates='author')
avatar_raw = db.Column(db.String(64))
avatar_s = db.Column(db.String(64))
avatar_m = db.Column(db.String(64))
avatar_l = db.Column(db.String(64))
receive_comment_notification = db.Column(db.Boolean, default=True)
receive_follow_notification = db.Column(db.Boolean, default=True)
receive_collect_notification = db.Column(db.Boolean, default=True)
public_collections = db.Column(db.Boolean, default=True)
locked = db.Column(db.Boolean, default=False)
active = db.Column(db.Boolean, default=True)
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
self.set_role()
self.generate_avatar()
self.follow(self) # 关注自己
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def validate_password(self, password):
return check_password_hash(self.password_hash, password)
def set_role(self):
if self.role is None:
if self.email == current_app.config['APP_ADMIN_EMAIL']:
self.role = Role.query.filter(Role.name == 'Administrator').first()
else:
self.role = Role.query.filter(Role.name == 'User').first()
def can(self, permission_name):
permission = Permission.query.filter(Permission.name == permission_name).first()
return permission is not None and self.role is not None and permission in self.role.permissions
@property
def is_admin(self):
return self.role.name == 'Administrator'
def generate_avatar(self):
avatar = Identicon()
filenames = avatar.generate(text=self.username)
self.avatar_s = filenames[0]
self.avatar_m = filenames[1]
self.avatar_l = filenames[2]
def collect(self, photo):
if not self.is_collecting(photo):
collect = Collect(collector=self, collected=photo)
db.session.add(collect)
db.session.commit()
def uncollect(self, photo):
collect = Collect.query.with_parent(self).filter_by(collected_id=photo.id).first()
if collect:
db.session.delete(collect)
db.session.commit()
def is_collecting(self, photo):
return Collect.query.with_parent(self).filter_by(collected_id=photo.id).first() is not None
def follow(self, user):
if not self.is_following(user):
follow = Follow(follower=self, followed=user)
db.session.add(follow)
db.session.commit()
def unfollow(self, user):
follow = self.following.filter_by(followed_id=user.id).first()
if follow:
db.session.delete(follow)
db.session.commit()
def is_following(self, user):
if user.id is None:
return False
return self.following.filter_by(followed_id=user.id).first() is not None
def is_followed_by(self, user):
return self.followers.filter_by(follower_id=user.id).first() is not None
def lock(self):
self.locked = True
self.role = Role.query.filter_by(name='Locked').first()
db.session.commit()
def unlock(self):
self.locked = False
self.role = Role.query.filter_by(name='User').first()
db.session.commit()
@property
def is_active(self):
return self.active
def block(self):
self.active = False
db.session.commit()
def unblock(self):
self.active = True
db.session.commit()
@whooshee.register_model('description')
class Photo(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.Text)
filename = db.Column(db.String(64))
filename_s = db.Column(db.String(64))
filename_m = db.Column(db.String(64))
timestamp = db.Column(db.DateTime, default=datetime.utcnow())
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
author = db.relationship('User', back_populates='photos')
comments = db.relationship('Comment', back_populates='photo', cascade='all, delete')
tags = db.relationship('Tag', secondary=tagging, back_populates='photos')
collectors = db.relationship('Collect', back_populates='collected', cascade='all')
flag = db.Column(db.Integer, default=0)
can_comment = db.Column(db.Boolean, default=True)
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text)
timestamp = db.Column(db.DateTime, default=datetime.utcnow())
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
author = db.relationship('User', back_populates='comments')
photo_id = db.Column(db.Integer, db.ForeignKey('photo.id'))
photo = db.relationship('Photo', back_populates='comments')
replied_id = db.Column(db.Integer, db.ForeignKey('comment.id'))
replied = db.relationship('Comment', remote_side=[id], back_populates='replies')
replies = db.relationship('Comment', back_populates='replied', cascade='all, delete-orphan')
flag = db.Column(db.Integer, default=0)
@whooshee.register_model('name')
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
photos = db.relationship('Photo', secondary=tagging, back_populates='tags')
class Notification(db.Model):
id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.Text)
is_read = db.Column(db.Boolean, default=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow())
receiver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
receiver = db.relationship('User', back_populates='notifications')
class Role(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
permissions = db.relationship('Permission', secondary=roles_permissions, back_populates='roles')
users = db.relationship('User', back_populates='role')
@staticmethod
def init_role():
roles_permissions_map = {
'Locked': ['FOLLOW', 'COLLECT'],
'User': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD'],
'Moderator': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD', 'MODERATE'],
'Administrator': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD', 'MODERATE', 'ADMINISTER']
}
for role_name in roles_permissions_map:
role = Role.query.filter(Role.name == role_name).first()
if role is None:
role = Role(name=role_name)
db.session.add(role)
role.permissions = []
for permission_name in roles_permissions_map[role_name]:
permission = Permission.query.filter(Permission.name == permission_name).first()
if permission is None:
permission = Permission(name=permission_name)
db.session.add(permission)
role.permissions.append(permission)
db.session.commit()
class Permission(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
roles = db.relationship('Role', secondary=roles_permissions, back_populates='permissions')
@db.event.listens_for(Photo, 'after_delete', named=True)
def delete_photos(**kwargs):
target = kwargs['target']
for filename in target.filename, target.filename_s, target.filename_m:
if filename is not None:
path = os.path.join(current_app.config['APP_UPLOAD_PATH'], filename)
if os.path.exists(path):
os.remove(path)
@db.event.listens_for(User, 'after_delete', named=True)
def delete_avatars(**kwargs):
target = kwargs['target']
for filename in target.avatar_raw, target.avatar_s, target.avatar_m, target.avatar_l:
if filename is not None:
path = os.path.join(current_app.config['AVATARS_SAVE_PATH'], filename)
if os.path.exists(path):
os.remove(path)
| [
"[email protected]"
] | |
b637325039f49ef3a68474942e03ff5f45a15a45 | 6455c57f85289fae2195e15b9de126ef1f6bf366 | /project/job/models.py | d76497cb302d53dfa50245b326202b283d94f849 | [] | no_license | muhamed-mustafa/django-job-board | 8fcb76e8543509d233cb7697ced67c96f5d81fbc | 6b3fa1d7126d9c400c1c6cf3ccb4c8061db8692b | refs/heads/master | 2022-12-15T00:53:15.202174 | 2020-09-17T21:43:48 | 2020-09-17T21:43:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,523 | py | from django.db import models
from django.utils.translation import ugettext as _
from django.utils.text import slugify
from django.contrib.auth.models import User
def image_upload(instance, filename):
imagename, extension = filename.split(".")
return 'jobs/%s.%s' % (instance.id, extension)
class Job(models.Model):
objects = None
JOB_TYPE = (
('Full Time', 'Full Time'),
('Part Time', 'Part Time')
)
owner = models.ForeignKey(User, related_name='job_owner', on_delete=models.CASCADE)
like = models.ManyToManyField(User,blank=True)
location = models.CharField(max_length=20)
title = models.CharField(max_length=100)
job_type = models.CharField(max_length=100, choices=JOB_TYPE)
description = models.TextField(max_length=1000)
published_at = models.DateTimeField(auto_now=True)
vacancy = models.IntegerField(default=1)
salary = models.IntegerField(default=0)
experience = models.IntegerField(default=1)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_upload, null=True, blank=True)
slug = models.SlugField(null=True, blank=True)
facebook = models.CharField(max_length=500,null=True,blank=True)
instagram = models.CharField(max_length=500,null=True,blank=True)
google = models.CharField(max_length=500,null=True,blank=True)
twitter = models.CharField(max_length=500,null=True,blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Job, self).save(*args, **kwargs)
class meta:
verbose_name = _('Job')
verbose_name_plural = _('Jobs')
def __str__(self):
return self.title
class Category(models.Model):
name = models.CharField(max_length=25)
class meta:
verbose_name = _('Category')
verbose_name_plural = _('Categories')
def __str__(self):
return self.name
class Apply(models.Model):
job = models.ForeignKey(Job, related_name='apply_job', on_delete=models.CASCADE)
name = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
website = models.URLField()
cv = models.FileField(upload_to='apply/')
cover_letter = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now=True,null=True,blank=True)
class Meta:
verbose_name = _('Apply')
verbose_name_plural = _('Applies')
def __str__(self):
return self.name
| [
"[email protected]"
] | |
3d07fac9d2bb63738f35e626530cf62382648804 | 127e99fbdc4e04f90c0afc6f4d076cc3d7fdce06 | /2021_하반기 코테연습/boj16937.py | 6d06ddfaf0afe6fb35157d542a1476f2a0119f6a | [] | no_license | holim0/Algo_Study | 54a6f10239368c6cf230b9f1273fe42caa97401c | ce734dcde091fa7f29b66dd3fb86d7a6109e8d9c | refs/heads/master | 2023-08-25T14:07:56.420288 | 2021-10-25T12:28:23 | 2021-10-25T12:28:23 | 276,076,057 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 999 | py | from itertools import combinations
h, w = map(int, input().split())
n = int(input())
sti = []
for _ in range(n):
r, c = map(int, input().split())
if (r<=h and c<=w) or (r<=w and c<=h):
sti.append((r, c))
answer = -1
johab = list(combinations(sti, 2))
for cur in johab:
r1,c1, r2, c2 = cur[0][0], cur[0][1], cur[1][0], cur[1][1]
rest_r, rest_c = h-r1, w-c1
rest_r2, rest_c2 = h-c1, w-r1
if rest_r>=0 and rest_c>=0:
if (r2<=rest_r and c2<=w) or (r2<=h and c2<=rest_c):
answer = max(answer, r1*c1+r2*c2)
elif (c2<=rest_r and r2<=w) or (c2<=h and r2<=rest_c):
answer = max(answer, r1*c1+r2*c2)
if rest_r2>=0 and rest_c2>=0:
if (r2<=rest_r2 and c2<=w) or (r2<=h and c2<=rest_c2):
answer = max(answer, r1*c1+r2*c2)
elif (c2<=rest_r2 and r2<=w) or (c2<=h and r2<=rest_c2):
answer = max(answer, r1*c1+r2*c2)
if answer == -1:
print(0)
else:
print(answer) | [
"[email protected]"
] | |
925993af5a8f5017c130ba97532dac8831608bdd | 18c1cbda3f9f6ca9cc9a27e93ddfece583c4fe43 | /projects/DensePose/densepose/data/structures.py | 340c396d95257f5bcb1728753f7883a205924856 | [
"Apache-2.0"
] | permissive | zzzzzz0407/detectron2 | 0bd8e5def65eb72bc9477f08f8907958d9fd73a1 | 021fc5b1502bbba54e4714735736898803835ab0 | refs/heads/master | 2022-12-04T14:25:36.986566 | 2020-08-26T10:39:30 | 2020-08-26T10:39:30 | 276,800,695 | 1 | 0 | Apache-2.0 | 2020-07-03T03:42:26 | 2020-07-03T03:42:25 | null | UTF-8 | Python | false | false | 25,296 | py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import base64
import numpy as np
from io import BytesIO
from typing import BinaryIO, Dict, Union
import torch
from PIL import Image
from torch.nn import functional as F
class DensePoseTransformData(object):
# Horizontal symmetry label transforms used for horizontal flip
MASK_LABEL_SYMMETRIES = [0, 1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 14]
# fmt: off
POINT_LABEL_SYMMETRIES = [ 0, 1, 2, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15, 18, 17, 20, 19, 22, 21, 24, 23] # noqa
# fmt: on
def __init__(self, uv_symmetries: Dict[str, torch.Tensor], device: torch.device):
self.mask_label_symmetries = DensePoseTransformData.MASK_LABEL_SYMMETRIES
self.point_label_symmetries = DensePoseTransformData.POINT_LABEL_SYMMETRIES
self.uv_symmetries = uv_symmetries
self.device = torch.device("cpu")
def to(self, device: torch.device, copy: bool = False) -> "DensePoseTransformData":
"""
Convert transform data to the specified device
Args:
device (torch.device): device to convert the data to
copy (bool): flag that specifies whether to copy or to reference the data
in case the device is the same
Return:
An instance of `DensePoseTransformData` with data stored on the specified device
"""
if self.device == device and not copy:
return self
uv_symmetry_map = {}
for key in self.uv_symmetries:
uv_symmetry_map[key] = self.uv_symmetries[key].to(device=device, copy=copy)
return DensePoseTransformData(uv_symmetry_map, device)
@staticmethod
def load(io: Union[str, BinaryIO]):
"""
Args:
io: (str or binary file-like object): input file to load data from
Returns:
An instance of `DensePoseTransformData` with transforms loaded from the file
"""
import scipy.io
uv_symmetry_map = scipy.io.loadmat(io)
uv_symmetry_map_torch = {}
for key in ["U_transforms", "V_transforms"]:
uv_symmetry_map_torch[key] = []
map_src = uv_symmetry_map[key]
map_dst = uv_symmetry_map_torch[key]
for i in range(map_src.shape[1]):
map_dst.append(torch.from_numpy(map_src[0, i]).to(dtype=torch.float))
uv_symmetry_map_torch[key] = torch.stack(map_dst, dim=0)
transform_data = DensePoseTransformData(uv_symmetry_map_torch, device=torch.device("cpu"))
return transform_data
class DensePoseDataRelative(object):
"""
Dense pose relative annotations that can be applied to any bounding box:
x - normalized X coordinates [0, 255] of annotated points
y - normalized Y coordinates [0, 255] of annotated points
i - body part labels 0,...,24 for annotated points
u - body part U coordinates [0, 1] for annotated points
v - body part V coordinates [0, 1] for annotated points
segm - 256x256 segmentation mask with values 0,...,14
To obtain absolute x and y data wrt some bounding box one needs to first
divide the data by 256, multiply by the respective bounding box size
and add bounding box offset:
x_img = x0 + x_norm * w / 256.0
y_img = y0 + y_norm * h / 256.0
Segmentation masks are typically sampled to get image-based masks.
"""
# Key for normalized X coordinates in annotation dict
X_KEY = "dp_x"
# Key for normalized Y coordinates in annotation dict
Y_KEY = "dp_y"
# Key for U part coordinates in annotation dict
U_KEY = "dp_U"
# Key for V part coordinates in annotation dict
V_KEY = "dp_V"
# Key for I point labels in annotation dict
I_KEY = "dp_I"
# Key for segmentation mask in annotation dict
S_KEY = "dp_masks"
# Number of body parts in segmentation masks
N_BODY_PARTS = 14
# Number of parts in point labels
N_PART_LABELS = 24
MASK_SIZE = 256
def __init__(self, annotation, cleanup=False):
is_valid, reason_not_valid = DensePoseDataRelative.validate_annotation(annotation)
assert is_valid, "Invalid DensePose annotations: {}".format(reason_not_valid)
self.x = torch.as_tensor(annotation[DensePoseDataRelative.X_KEY])
self.y = torch.as_tensor(annotation[DensePoseDataRelative.Y_KEY])
self.i = torch.as_tensor(annotation[DensePoseDataRelative.I_KEY])
self.u = torch.as_tensor(annotation[DensePoseDataRelative.U_KEY])
self.v = torch.as_tensor(annotation[DensePoseDataRelative.V_KEY])
self.segm = DensePoseDataRelative.extract_segmentation_mask(annotation)
self.device = torch.device("cpu")
if cleanup:
DensePoseDataRelative.cleanup_annotation(annotation)
def to(self, device):
if self.device == device:
return self
new_data = DensePoseDataRelative.__new__(DensePoseDataRelative)
new_data.x = self.x
new_data.x = self.x.to(device)
new_data.y = self.y.to(device)
new_data.i = self.i.to(device)
new_data.u = self.u.to(device)
new_data.v = self.v.to(device)
new_data.segm = self.segm.to(device)
new_data.device = device
return new_data
@staticmethod
def extract_segmentation_mask(annotation):
import pycocotools.mask as mask_util
poly_specs = annotation[DensePoseDataRelative.S_KEY]
segm = torch.zeros((DensePoseDataRelative.MASK_SIZE,) * 2, dtype=torch.float32)
for i in range(DensePoseDataRelative.N_BODY_PARTS):
poly_i = poly_specs[i]
if poly_i:
mask_i = mask_util.decode(poly_i)
segm[mask_i > 0] = i + 1
return segm
@staticmethod
def validate_annotation(annotation):
for key in [
DensePoseDataRelative.X_KEY,
DensePoseDataRelative.Y_KEY,
DensePoseDataRelative.I_KEY,
DensePoseDataRelative.U_KEY,
DensePoseDataRelative.V_KEY,
DensePoseDataRelative.S_KEY,
]:
if key not in annotation:
return False, "no {key} data in the annotation".format(key=key)
return True, None
@staticmethod
def cleanup_annotation(annotation):
for key in [
DensePoseDataRelative.X_KEY,
DensePoseDataRelative.Y_KEY,
DensePoseDataRelative.I_KEY,
DensePoseDataRelative.U_KEY,
DensePoseDataRelative.V_KEY,
DensePoseDataRelative.S_KEY,
]:
if key in annotation:
del annotation[key]
def apply_transform(self, transforms, densepose_transform_data):
self._transform_pts(transforms, densepose_transform_data)
self._transform_segm(transforms, densepose_transform_data)
def _transform_pts(self, transforms, dp_transform_data):
import detectron2.data.transforms as T
# NOTE: This assumes that HorizFlipTransform is the only one that does flip
do_hflip = sum(isinstance(t, T.HFlipTransform) for t in transforms.transforms) % 2 == 1
if do_hflip:
self.x = self.segm.size(1) - self.x
self._flip_iuv_semantics(dp_transform_data)
for t in transforms.transforms:
if isinstance(t, T.RotationTransform):
xy_scale = np.array((t.w, t.h)) / DensePoseDataRelative.MASK_SIZE
xy = t.apply_coords(np.stack((self.x, self.y), axis=1) * xy_scale)
self.x, self.y = torch.tensor(xy / xy_scale, dtype=self.x.dtype).T
def _flip_iuv_semantics(self, dp_transform_data: DensePoseTransformData) -> None:
i_old = self.i.clone()
uv_symmetries = dp_transform_data.uv_symmetries
pt_label_symmetries = dp_transform_data.point_label_symmetries
for i in range(self.N_PART_LABELS):
if i + 1 in i_old:
annot_indices_i = i_old == i + 1
if pt_label_symmetries[i + 1] != i + 1:
self.i[annot_indices_i] = pt_label_symmetries[i + 1]
u_loc = (self.u[annot_indices_i] * 255).long()
v_loc = (self.v[annot_indices_i] * 255).long()
self.u[annot_indices_i] = uv_symmetries["U_transforms"][i][v_loc, u_loc].to(
device=self.u.device
)
self.v[annot_indices_i] = uv_symmetries["V_transforms"][i][v_loc, u_loc].to(
device=self.v.device
)
def _transform_segm(self, transforms, dp_transform_data):
import detectron2.data.transforms as T
# NOTE: This assumes that HorizFlipTransform is the only one that does flip
do_hflip = sum(isinstance(t, T.HFlipTransform) for t in transforms.transforms) % 2 == 1
if do_hflip:
self.segm = torch.flip(self.segm, [1])
self._flip_segm_semantics(dp_transform_data)
for t in transforms.transforms:
if isinstance(t, T.RotationTransform):
self._transform_segm_rotation(t)
def _flip_segm_semantics(self, dp_transform_data):
old_segm = self.segm.clone()
mask_label_symmetries = dp_transform_data.mask_label_symmetries
for i in range(self.N_BODY_PARTS):
if mask_label_symmetries[i + 1] != i + 1:
self.segm[old_segm == i + 1] = mask_label_symmetries[i + 1]
def _transform_segm_rotation(self, rotation):
self.segm = F.interpolate(self.segm[None, None, :], (rotation.h, rotation.w)).numpy()
self.segm = torch.tensor(rotation.apply_segmentation(self.segm[0, 0]))[None, None, :]
self.segm = F.interpolate(self.segm, [DensePoseDataRelative.MASK_SIZE] * 2)[0, 0]
def normalized_coords_transform(x0, y0, w, h):
"""
Coordinates transform that maps top left corner to (-1, -1) and bottom
right corner to (1, 1). Used for torch.grid_sample to initialize the
grid
"""
def f(p):
return (2 * (p[0] - x0) / w - 1, 2 * (p[1] - y0) / h - 1)
return f
class DensePoseOutput(object):
def __init__(self, S, I, U, V, confidences):
"""
Args:
S (`torch.Tensor`): coarse segmentation tensor of size (N, A, H, W)
I (`torch.Tensor`): fine segmentation tensor of size (N, C, H, W)
U (`torch.Tensor`): U coordinates for each fine segmentation label of size (N, C, H, W)
V (`torch.Tensor`): V coordinates for each fine segmentation label of size (N, C, H, W)
confidences (dict of str -> `torch.Tensor`) estimated confidence model parameters
"""
self.S = S
self.I = I # noqa: E741
self.U = U
self.V = V
self.confidences = confidences
self._check_output_dims(S, I, U, V)
def _check_output_dims(self, S, I, U, V):
assert (
len(S.size()) == 4
), "Segmentation output should have 4 " "dimensions (NCHW), but has size {}".format(
S.size()
)
assert (
len(I.size()) == 4
), "Segmentation output should have 4 " "dimensions (NCHW), but has size {}".format(
S.size()
)
assert (
len(U.size()) == 4
), "Segmentation output should have 4 " "dimensions (NCHW), but has size {}".format(
S.size()
)
assert (
len(V.size()) == 4
), "Segmentation output should have 4 " "dimensions (NCHW), but has size {}".format(
S.size()
)
assert len(S) == len(I), (
"Number of output segmentation planes {} "
"should be equal to the number of output part index "
"planes {}".format(len(S), len(I))
)
assert S.size()[2:] == I.size()[2:], (
"Output segmentation plane size {} "
"should be equal to the output part index "
"plane size {}".format(S.size()[2:], I.size()[2:])
)
assert I.size() == U.size(), (
"Part index output shape {} "
"should be the same as U coordinates output shape {}".format(I.size(), U.size())
)
assert I.size() == V.size(), (
"Part index output shape {} "
"should be the same as V coordinates output shape {}".format(I.size(), V.size())
)
def resize(self, image_size_hw):
# do nothing - outputs are invariant to resize
pass
def _crop(self, S, I, U, V, bbox_old_xywh, bbox_new_xywh):
"""
Resample S, I, U, V from bbox_old to the cropped bbox_new
"""
x0old, y0old, wold, hold = bbox_old_xywh
x0new, y0new, wnew, hnew = bbox_new_xywh
tr_coords = normalized_coords_transform(x0old, y0old, wold, hold)
topleft = (x0new, y0new)
bottomright = (x0new + wnew, y0new + hnew)
topleft_norm = tr_coords(topleft)
bottomright_norm = tr_coords(bottomright)
hsize = S.size(1)
wsize = S.size(2)
grid = torch.meshgrid(
torch.arange(
topleft_norm[1],
bottomright_norm[1],
(bottomright_norm[1] - topleft_norm[1]) / hsize,
)[:hsize],
torch.arange(
topleft_norm[0],
bottomright_norm[0],
(bottomright_norm[0] - topleft_norm[0]) / wsize,
)[:wsize],
)
grid = torch.stack(grid, dim=2).to(S.device)
assert (
grid.size(0) == hsize
), "Resampled grid expected " "height={}, actual height={}".format(hsize, grid.size(0))
assert grid.size(1) == wsize, "Resampled grid expected " "width={}, actual width={}".format(
wsize, grid.size(1)
)
S_new = F.grid_sample(
S.unsqueeze(0),
torch.unsqueeze(grid, 0),
mode="bilinear",
padding_mode="border",
align_corners=True,
).squeeze(0)
I_new = F.grid_sample(
I.unsqueeze(0),
torch.unsqueeze(grid, 0),
mode="bilinear",
padding_mode="border",
align_corners=True,
).squeeze(0)
U_new = F.grid_sample(
U.unsqueeze(0),
torch.unsqueeze(grid, 0),
mode="bilinear",
padding_mode="border",
align_corners=True,
).squeeze(0)
V_new = F.grid_sample(
V.unsqueeze(0),
torch.unsqueeze(grid, 0),
mode="bilinear",
padding_mode="border",
align_corners=True,
).squeeze(0)
return S_new, I_new, U_new, V_new
def crop(self, indices_cropped, bboxes_old, bboxes_new):
"""
Crop outputs for selected bounding boxes to the new bounding boxes.
"""
# VK: cropping is ignored for now
# for i, ic in enumerate(indices_cropped):
# self.S[ic], self.I[ic], self.U[ic], self.V[ic] = \
# self._crop(self.S[ic], self.I[ic], self.U[ic], self.V[ic],
# bboxes_old[i], bboxes_new[i])
pass
def hflip(self, transform_data: DensePoseTransformData) -> None:
"""
Change S, I, U and V to take into account a Horizontal flip.
"""
if self.I.shape[0] > 0:
for el in "SIUV":
self.__dict__[el] = torch.flip(self.__dict__[el], [3])
self._flip_iuv_semantics_tensor(transform_data)
self._flip_segm_semantics_tensor(transform_data)
def _flip_iuv_semantics_tensor(self, dp_transform_data: DensePoseTransformData) -> None:
point_label_symmetries = dp_transform_data.point_label_symmetries
uv_symmetries = dp_transform_data.uv_symmetries
N, C, H, W = self.U.shape
u_loc = (self.U[:, 1:, :, :].clamp(0, 1) * 255).long()
v_loc = (self.V[:, 1:, :, :].clamp(0, 1) * 255).long()
Iindex = torch.arange(C - 1, device=self.U.device)[None, :, None, None].expand(
N, C - 1, H, W
)
self.U[:, 1:, :, :] = uv_symmetries["U_transforms"][Iindex, v_loc, u_loc]
self.V[:, 1:, :, :] = uv_symmetries["V_transforms"][Iindex, v_loc, u_loc]
for el in "IUV":
self.__dict__[el] = self.__dict__[el][:, point_label_symmetries, :, :]
def _flip_segm_semantics_tensor(self, dp_transform_data):
if self.S.shape[1] == DensePoseDataRelative.N_BODY_PARTS + 1:
self.S = self.S[:, dp_transform_data.mask_label_symmetries, :, :]
def to_result(self, boxes_xywh):
"""
Convert DensePose outputs to results format. Results are more compact,
but cannot be resampled any more
"""
result = DensePoseResult(boxes_xywh, self.S, self.I, self.U, self.V)
return result
def __getitem__(self, item):
if isinstance(item, int):
S_selected = self.S[item].unsqueeze(0)
I_selected = self.I[item].unsqueeze(0)
U_selected = self.U[item].unsqueeze(0)
V_selected = self.V[item].unsqueeze(0)
conf_selected = {}
for key in self.confidences:
conf_selected[key] = self.confidences[key][item].unsqueeze(0)
else:
S_selected = self.S[item]
I_selected = self.I[item]
U_selected = self.U[item]
V_selected = self.V[item]
conf_selected = {}
for key in self.confidences:
conf_selected[key] = self.confidences[key][item]
return DensePoseOutput(S_selected, I_selected, U_selected, V_selected, conf_selected)
def __str__(self):
s = "DensePoseOutput S {}, I {}, U {}, V {}".format(
list(self.S.size()), list(self.I.size()), list(self.U.size()), list(self.V.size())
)
s_conf = "confidences: [{}]".format(
", ".join([f"{key} {list(self.confidences[key].size())}" for key in self.confidences])
)
return ", ".join([s, s_conf])
def __len__(self):
return self.S.size(0)
class DensePoseResult(object):
def __init__(self, boxes_xywh, S, I, U, V):
self.results = []
self.boxes_xywh = boxes_xywh.cpu().tolist()
assert len(boxes_xywh.size()) == 2
assert boxes_xywh.size(1) == 4
for i, box_xywh in enumerate(boxes_xywh):
result_i = self._output_to_result(box_xywh, S[[i]], I[[i]], U[[i]], V[[i]])
result_numpy_i = result_i.cpu().numpy()
result_encoded_i = DensePoseResult.encode_png_data(result_numpy_i)
result_encoded_with_shape_i = (result_numpy_i.shape, result_encoded_i)
self.results.append(result_encoded_with_shape_i)
def __str__(self):
s = "DensePoseResult: N={} [{}]".format(
len(self.results), ", ".join([str(list(r[0])) for r in self.results])
)
return s
def _output_to_result(self, box_xywh, S, I, U, V):
x, y, w, h = box_xywh
w = max(int(w), 1)
h = max(int(h), 1)
result = torch.zeros([3, h, w], dtype=torch.uint8, device=U.device)
assert (
len(S.size()) == 4
), "AnnIndex tensor size should have {} " "dimensions but has {}".format(4, len(S.size()))
s_bbox = F.interpolate(S, (h, w), mode="bilinear", align_corners=False).argmax(dim=1)
assert (
len(I.size()) == 4
), "IndexUV tensor size should have {} " "dimensions but has {}".format(4, len(S.size()))
i_bbox = (
F.interpolate(I, (h, w), mode="bilinear", align_corners=False).argmax(dim=1)
* (s_bbox > 0).long()
).squeeze(0)
assert len(U.size()) == 4, "U tensor size should have {} " "dimensions but has {}".format(
4, len(U.size())
)
u_bbox = F.interpolate(U, (h, w), mode="bilinear", align_corners=False)
assert len(V.size()) == 4, "V tensor size should have {} " "dimensions but has {}".format(
4, len(V.size())
)
v_bbox = F.interpolate(V, (h, w), mode="bilinear", align_corners=False)
result[0] = i_bbox
for part_id in range(1, u_bbox.size(1)):
result[1][i_bbox == part_id] = (
(u_bbox[0, part_id][i_bbox == part_id] * 255).clamp(0, 255).to(torch.uint8)
)
result[2][i_bbox == part_id] = (
(v_bbox[0, part_id][i_bbox == part_id] * 255).clamp(0, 255).to(torch.uint8)
)
assert (
result.size(1) == h
), "Results height {} should be equal" "to bounding box height {}".format(result.size(1), h)
assert (
result.size(2) == w
), "Results width {} should be equal" "to bounding box width {}".format(result.size(2), w)
return result
@staticmethod
def encode_png_data(arr):
"""
Encode array data as a PNG image using the highest compression rate
@param arr [in] Data stored in an array of size (3, M, N) of type uint8
@return Base64-encoded string containing PNG-compressed data
"""
assert len(arr.shape) == 3, "Expected a 3D array as an input," " got a {0}D array".format(
len(arr.shape)
)
assert arr.shape[0] == 3, "Expected first array dimension of size 3," " got {0}".format(
arr.shape[0]
)
assert arr.dtype == np.uint8, "Expected an array of type np.uint8, " " got {0}".format(
arr.dtype
)
data = np.moveaxis(arr, 0, -1)
im = Image.fromarray(data)
fstream = BytesIO()
im.save(fstream, format="png", optimize=True)
s = base64.encodebytes(fstream.getvalue()).decode()
return s
@staticmethod
def decode_png_data(shape, s):
"""
Decode array data from a string that contains PNG-compressed data
@param Base64-encoded string containing PNG-compressed data
@return Data stored in an array of size (3, M, N) of type uint8
"""
fstream = BytesIO(base64.decodebytes(s.encode()))
im = Image.open(fstream)
data = np.moveaxis(np.array(im.getdata(), dtype=np.uint8), -1, 0)
return data.reshape(shape)
def __len__(self):
return len(self.results)
def __getitem__(self, item):
result_encoded = self.results[item]
bbox_xywh = self.boxes_xywh[item]
return result_encoded, bbox_xywh
class DensePoseList(object):
_TORCH_DEVICE_CPU = torch.device("cpu")
def __init__(self, densepose_datas, boxes_xyxy_abs, image_size_hw, device=_TORCH_DEVICE_CPU):
assert len(densepose_datas) == len(
boxes_xyxy_abs
), "Attempt to initialize DensePoseList with {} DensePose datas " "and {} boxes".format(
len(densepose_datas), len(boxes_xyxy_abs)
)
self.densepose_datas = []
for densepose_data in densepose_datas:
assert isinstance(densepose_data, DensePoseDataRelative) or densepose_data is None, (
"Attempt to initialize DensePoseList with DensePose datas "
"of type {}, expected DensePoseDataRelative".format(type(densepose_data))
)
densepose_data_ondevice = (
densepose_data.to(device) if densepose_data is not None else None
)
self.densepose_datas.append(densepose_data_ondevice)
self.boxes_xyxy_abs = boxes_xyxy_abs.to(device)
self.image_size_hw = image_size_hw
self.device = device
def to(self, device):
if self.device == device:
return self
return DensePoseList(self.densepose_datas, self.boxes_xyxy_abs, self.image_size_hw, device)
def __iter__(self):
return iter(self.densepose_datas)
def __len__(self):
return len(self.densepose_datas)
def __repr__(self):
s = self.__class__.__name__ + "("
s += "num_instances={}, ".format(len(self.densepose_datas))
s += "image_width={}, ".format(self.image_size_hw[1])
s += "image_height={})".format(self.image_size_hw[0])
return s
def __getitem__(self, item):
if isinstance(item, int):
densepose_data_rel = self.densepose_datas[item]
return densepose_data_rel
elif isinstance(item, slice):
densepose_datas_rel = self.densepose_datas[item]
boxes_xyxy_abs = self.boxes_xyxy_abs[item]
return DensePoseList(
densepose_datas_rel, boxes_xyxy_abs, self.image_size_hw, self.device
)
elif isinstance(item, torch.Tensor) and (item.dtype == torch.bool):
densepose_datas_rel = [self.densepose_datas[i] for i, x in enumerate(item) if x > 0]
boxes_xyxy_abs = self.boxes_xyxy_abs[item]
return DensePoseList(
densepose_datas_rel, boxes_xyxy_abs, self.image_size_hw, self.device
)
else:
densepose_datas_rel = [self.densepose_datas[i] for i in item]
boxes_xyxy_abs = self.boxes_xyxy_abs[item]
return DensePoseList(
densepose_datas_rel, boxes_xyxy_abs, self.image_size_hw, self.device
)
| [
"[email protected]"
] | |
66249f846adc240a436f156b941e6d0a01b7be95 | 4bed9030031fc99f6ea3d5267bd9e773f54320f8 | /sparse/repos/katyhon/hello-world.git/setup.py | 9910a87c354430aea7dbbdccc76c28a3264a91f0 | [
"BSD-3-Clause"
] | permissive | yuvipanda/mybinder.org-analytics | c5f4b939541d29727bc8d3c023b4d140de756f69 | 7b654e3e21dea790505c626d688aa15640ea5808 | refs/heads/master | 2021-06-13T05:49:12.447172 | 2018-12-22T21:48:12 | 2018-12-22T21:48:12 | 162,839,358 | 1 | 1 | BSD-3-Clause | 2021-06-10T21:05:50 | 2018-12-22T20:01:52 | Jupyter Notebook | UTF-8 | Python | false | false | 1,133 | py | # -*- coding: utf-8 -*-
# @Author: Zebedee Nicholls
# @Date: 2017-04-10 13:42:11
# @Last Modified by: Chris Smith
# @Last Modified time: 2018-01-11 19:17:00
from setuptools import setup
from setuptools import find_packages
import versioneer
# README #
def readme():
with open('README.rst') as f:
return f.read()
setup(name='fair',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Python package to perform calculations with the FAIR simple climate model',
long_description=readme(),
keywords='simple climate model temperature response carbon cycle emissions forcing',
url='https://github.com/OMS-NetZero/FAIR',
author='OMS-NetZero, Chris Smith, Richard Millar, Zebedee Nicholls, Myles Allen',
author_email='[email protected], [email protected]',
license='Apache 2.0',
packages=find_packages(exclude=['tests*','docs*']),
package_data={'': ['*.csv']},
include_package_data=True,
install_requires=[
'numpy>=1.11.3',
'scipy>=0.19.0',
],
zip_safe=False,
)
| [
"[email protected]"
] | |
5aa1c34ec0e9bdc71669f247d97e9017b69ffe4c | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /python/pandas/2017/4/test_partial.py | 20cec2a3aa7db8b918db50da92411c32c9ee713d | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Python | false | false | 20,616 | py | """
test setting *parts* of objects both positionally and label based
TOD: these should be split among the indexer tests
"""
import pytest
from warnings import catch_warnings
import numpy as np
import pandas as pd
from pandas import Series, DataFrame, Panel, Index, date_range
from pandas.util import testing as tm
class TestPartialSetting(tm.TestCase):
def test_partial_setting(self):
# GH2578, allow ix and friends to partially set
# series
s_orig = Series([1, 2, 3])
s = s_orig.copy()
s[5] = 5
expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_orig.copy()
s.loc[5] = 5
expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_orig.copy()
s[5] = 5.
expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_orig.copy()
s.loc[5] = 5.
expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
# iloc/iat raise
s = s_orig.copy()
def f():
s.iloc[3] = 5.
pytest.raises(IndexError, f)
def f():
s.iat[3] = 5.
pytest.raises(IndexError, f)
# ## frame ##
df_orig = DataFrame(
np.arange(6).reshape(3, 2), columns=['A', 'B'], dtype='int64')
# iloc/iat raise
df = df_orig.copy()
def f():
df.iloc[4, 2] = 5.
pytest.raises(IndexError, f)
def f():
df.iat[4, 2] = 5.
pytest.raises(IndexError, f)
# row setting where it exists
expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]}))
df = df_orig.copy()
df.iloc[1] = df.iloc[2]
tm.assert_frame_equal(df, expected)
expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]}))
df = df_orig.copy()
df.loc[1] = df.loc[2]
tm.assert_frame_equal(df, expected)
# like 2578, partial setting with dtype preservation
expected = DataFrame(dict({'A': [0, 2, 4, 4], 'B': [1, 3, 5, 5]}))
df = df_orig.copy()
df.loc[3] = df.loc[2]
tm.assert_frame_equal(df, expected)
# single dtype frame, overwrite
expected = DataFrame(dict({'A': [0, 2, 4], 'B': [0, 2, 4]}))
df = df_orig.copy()
with catch_warnings(record=True):
df.ix[:, 'B'] = df.ix[:, 'A']
tm.assert_frame_equal(df, expected)
# mixed dtype frame, overwrite
expected = DataFrame(dict({'A': [0, 2, 4], 'B': Series([0, 2, 4])}))
df = df_orig.copy()
df['B'] = df['B'].astype(np.float64)
with catch_warnings(record=True):
df.ix[:, 'B'] = df.ix[:, 'A']
tm.assert_frame_equal(df, expected)
# single dtype frame, partial setting
expected = df_orig.copy()
expected['C'] = df['A']
df = df_orig.copy()
with catch_warnings(record=True):
df.ix[:, 'C'] = df.ix[:, 'A']
tm.assert_frame_equal(df, expected)
# mixed frame, partial setting
expected = df_orig.copy()
expected['C'] = df['A']
df = df_orig.copy()
with catch_warnings(record=True):
df.ix[:, 'C'] = df.ix[:, 'A']
tm.assert_frame_equal(df, expected)
with catch_warnings(record=True):
# ## panel ##
p_orig = Panel(np.arange(16).reshape(2, 4, 2),
items=['Item1', 'Item2'],
major_axis=pd.date_range('2001/1/12', periods=4),
minor_axis=['A', 'B'], dtype='float64')
# panel setting via item
p_orig = Panel(np.arange(16).reshape(2, 4, 2),
items=['Item1', 'Item2'],
major_axis=pd.date_range('2001/1/12', periods=4),
minor_axis=['A', 'B'], dtype='float64')
expected = p_orig.copy()
expected['Item3'] = expected['Item1']
p = p_orig.copy()
p.loc['Item3'] = p['Item1']
tm.assert_panel_equal(p, expected)
# panel with aligned series
expected = p_orig.copy()
expected = expected.transpose(2, 1, 0)
expected['C'] = DataFrame({'Item1': [30, 30, 30, 30],
'Item2': [32, 32, 32, 32]},
index=p_orig.major_axis)
expected = expected.transpose(2, 1, 0)
p = p_orig.copy()
p.loc[:, :, 'C'] = Series([30, 32], index=p_orig.items)
tm.assert_panel_equal(p, expected)
# GH 8473
dates = date_range('1/1/2000', periods=8)
df_orig = DataFrame(np.random.randn(8, 4), index=dates,
columns=['A', 'B', 'C', 'D'])
expected = pd.concat([df_orig, DataFrame(
{'A': 7}, index=[dates[-1] + 1])])
df = df_orig.copy()
df.loc[dates[-1] + 1, 'A'] = 7
tm.assert_frame_equal(df, expected)
df = df_orig.copy()
df.at[dates[-1] + 1, 'A'] = 7
tm.assert_frame_equal(df, expected)
exp_other = DataFrame({0: 7}, index=[dates[-1] + 1])
expected = pd.concat([df_orig, exp_other], axis=1)
df = df_orig.copy()
df.loc[dates[-1] + 1, 0] = 7
tm.assert_frame_equal(df, expected)
df = df_orig.copy()
df.at[dates[-1] + 1, 0] = 7
tm.assert_frame_equal(df, expected)
def test_partial_setting_mixed_dtype(self):
# in a mixed dtype environment, try to preserve dtypes
# by appending
df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"])
s = df.loc[1].copy()
s.name = 2
expected = df.append(s)
df.loc[2] = df.loc[1]
tm.assert_frame_equal(df, expected)
# columns will align
df = DataFrame(columns=['A', 'B'])
df.loc[0] = Series(1, index=range(4))
tm.assert_frame_equal(df, DataFrame(columns=['A', 'B'], index=[0]))
# columns will align
df = DataFrame(columns=['A', 'B'])
df.loc[0] = Series(1, index=['B'])
exp = DataFrame([[np.nan, 1]], columns=['A', 'B'],
index=[0], dtype='float64')
tm.assert_frame_equal(df, exp)
# list-like must conform
df = DataFrame(columns=['A', 'B'])
def f():
df.loc[0] = [1, 2, 3]
pytest.raises(ValueError, f)
# TODO: #15657, these are left as object and not coerced
df = DataFrame(columns=['A', 'B'])
df.loc[3] = [6, 7]
exp = DataFrame([[6, 7]], index=[3], columns=['A', 'B'],
dtype='object')
tm.assert_frame_equal(df, exp)
def test_series_partial_set(self):
# partial set with new index
# Regression from GH4825
ser = Series([0.1, 0.2], index=[1, 2])
# loc
expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3])
result = ser.loc[[3, 2, 3]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, 'x'])
result = ser.loc[[3, 2, 3, 'x']]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1])
result = ser.loc[[2, 2, 1]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, 'x', 1])
result = ser.loc[[2, 2, 'x', 1]]
tm.assert_series_equal(result, expected, check_index_type=True)
# raises as nothing in in the index
pytest.raises(KeyError, lambda: ser.loc[[3, 3, 3]])
expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3])
result = ser.loc[[2, 2, 3]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4])
result = Series([0.1, 0.2, 0.3], index=[1, 2, 3]).loc[[3, 4, 4]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3])
result = Series([0.1, 0.2, 0.3, 0.4],
index=[1, 2, 3, 4]).loc[[5, 3, 3]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4])
result = Series([0.1, 0.2, 0.3, 0.4],
index=[1, 2, 3, 4]).loc[[5, 4, 4]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2])
result = Series([0.1, 0.2, 0.3, 0.4],
index=[4, 5, 6, 7]).loc[[7, 2, 2]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5])
result = Series([0.1, 0.2, 0.3, 0.4],
index=[1, 2, 3, 4]).loc[[4, 5, 5]]
tm.assert_series_equal(result, expected, check_index_type=True)
# iloc
expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1])
result = ser.iloc[[1, 1, 0, 0]]
tm.assert_series_equal(result, expected, check_index_type=True)
def test_series_partial_set_with_name(self):
# GH 11497
idx = Index([1, 2], dtype='int64', name='idx')
ser = Series([0.1, 0.2], index=idx, name='s')
# loc
exp_idx = Index([3, 2, 3], dtype='int64', name='idx')
expected = Series([np.nan, 0.2, np.nan], index=exp_idx, name='s')
result = ser.loc[[3, 2, 3]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([3, 2, 3, 'x'], dtype='object', name='idx')
expected = Series([np.nan, 0.2, np.nan, np.nan], index=exp_idx,
name='s')
result = ser.loc[[3, 2, 3, 'x']]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([2, 2, 1], dtype='int64', name='idx')
expected = Series([0.2, 0.2, 0.1], index=exp_idx, name='s')
result = ser.loc[[2, 2, 1]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([2, 2, 'x', 1], dtype='object', name='idx')
expected = Series([0.2, 0.2, np.nan, 0.1], index=exp_idx, name='s')
result = ser.loc[[2, 2, 'x', 1]]
tm.assert_series_equal(result, expected, check_index_type=True)
# raises as nothing in in the index
pytest.raises(KeyError, lambda: ser.loc[[3, 3, 3]])
exp_idx = Index([2, 2, 3], dtype='int64', name='idx')
expected = Series([0.2, 0.2, np.nan], index=exp_idx, name='s')
result = ser.loc[[2, 2, 3]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([3, 4, 4], dtype='int64', name='idx')
expected = Series([0.3, np.nan, np.nan], index=exp_idx, name='s')
idx = Index([1, 2, 3], dtype='int64', name='idx')
result = Series([0.1, 0.2, 0.3], index=idx, name='s').loc[[3, 4, 4]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([5, 3, 3], dtype='int64', name='idx')
expected = Series([np.nan, 0.3, 0.3], index=exp_idx, name='s')
idx = Index([1, 2, 3, 4], dtype='int64', name='idx')
result = Series([0.1, 0.2, 0.3, 0.4], index=idx,
name='s').loc[[5, 3, 3]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([5, 4, 4], dtype='int64', name='idx')
expected = Series([np.nan, 0.4, 0.4], index=exp_idx, name='s')
idx = Index([1, 2, 3, 4], dtype='int64', name='idx')
result = Series([0.1, 0.2, 0.3, 0.4], index=idx,
name='s').loc[[5, 4, 4]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([7, 2, 2], dtype='int64', name='idx')
expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s')
idx = Index([4, 5, 6, 7], dtype='int64', name='idx')
result = Series([0.1, 0.2, 0.3, 0.4], index=idx,
name='s').loc[[7, 2, 2]]
tm.assert_series_equal(result, expected, check_index_type=True)
exp_idx = Index([4, 5, 5], dtype='int64', name='idx')
expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s')
idx = Index([1, 2, 3, 4], dtype='int64', name='idx')
result = Series([0.1, 0.2, 0.3, 0.4], index=idx,
name='s').loc[[4, 5, 5]]
tm.assert_series_equal(result, expected, check_index_type=True)
# iloc
exp_idx = Index([2, 2, 1, 1], dtype='int64', name='idx')
expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name='s')
result = ser.iloc[[1, 1, 0, 0]]
tm.assert_series_equal(result, expected, check_index_type=True)
def test_partial_set_invalid(self):
# GH 4940
# allow only setting of 'valid' values
orig = tm.makeTimeDataFrame()
df = orig.copy()
# don't allow not string inserts
def f():
with catch_warnings(record=True):
df.loc[100.0, :] = df.ix[0]
pytest.raises(TypeError, f)
def f():
with catch_warnings(record=True):
df.loc[100, :] = df.ix[0]
pytest.raises(TypeError, f)
def f():
with catch_warnings(record=True):
df.ix[100.0, :] = df.ix[0]
pytest.raises(TypeError, f)
def f():
with catch_warnings(record=True):
df.ix[100, :] = df.ix[0]
pytest.raises(ValueError, f)
# allow object conversion here
df = orig.copy()
with catch_warnings(record=True):
df.loc['a', :] = df.ix[0]
exp = orig.append(pd.Series(df.ix[0], name='a'))
tm.assert_frame_equal(df, exp)
tm.assert_index_equal(df.index,
pd.Index(orig.index.tolist() + ['a']))
assert df.index.dtype == 'object'
def test_partial_set_empty_series(self):
# GH5226
# partially set with an empty object series
s = Series()
s.loc[1] = 1
tm.assert_series_equal(s, Series([1], index=[1]))
s.loc[3] = 3
tm.assert_series_equal(s, Series([1, 3], index=[1, 3]))
s = Series()
s.loc[1] = 1.
tm.assert_series_equal(s, Series([1.], index=[1]))
s.loc[3] = 3.
tm.assert_series_equal(s, Series([1., 3.], index=[1, 3]))
s = Series()
s.loc['foo'] = 1
tm.assert_series_equal(s, Series([1], index=['foo']))
s.loc['bar'] = 3
tm.assert_series_equal(s, Series([1, 3], index=['foo', 'bar']))
s.loc[3] = 4
tm.assert_series_equal(s, Series([1, 3, 4], index=['foo', 'bar', 3]))
def test_partial_set_empty_frame(self):
# partially set with an empty object
# frame
df = DataFrame()
def f():
df.loc[1] = 1
pytest.raises(ValueError, f)
def f():
df.loc[1] = Series([1], index=['foo'])
pytest.raises(ValueError, f)
def f():
df.loc[:, 1] = 1
pytest.raises(ValueError, f)
# these work as they don't really change
# anything but the index
# GH5632
expected = DataFrame(columns=['foo'], index=pd.Index(
[], dtype='int64'))
def f():
df = DataFrame()
df['foo'] = Series([], dtype='object')
return df
tm.assert_frame_equal(f(), expected)
def f():
df = DataFrame()
df['foo'] = Series(df.index)
return df
tm.assert_frame_equal(f(), expected)
def f():
df = DataFrame()
df['foo'] = df.index
return df
tm.assert_frame_equal(f(), expected)
expected = DataFrame(columns=['foo'],
index=pd.Index([], dtype='int64'))
expected['foo'] = expected['foo'].astype('float64')
def f():
df = DataFrame()
df['foo'] = []
return df
tm.assert_frame_equal(f(), expected)
def f():
df = DataFrame()
df['foo'] = Series(range(len(df)))
return df
tm.assert_frame_equal(f(), expected)
def f():
df = DataFrame()
tm.assert_index_equal(df.index, pd.Index([], dtype='object'))
df['foo'] = range(len(df))
return df
expected = DataFrame(columns=['foo'],
index=pd.Index([], dtype='int64'))
expected['foo'] = expected['foo'].astype('float64')
tm.assert_frame_equal(f(), expected)
df = DataFrame()
tm.assert_index_equal(df.columns, pd.Index([], dtype=object))
df2 = DataFrame()
df2[1] = Series([1], index=['foo'])
df.loc[:, 1] = Series([1], index=['foo'])
tm.assert_frame_equal(df, DataFrame([[1]], index=['foo'], columns=[1]))
tm.assert_frame_equal(df, df2)
# no index to start
expected = DataFrame({0: Series(1, index=range(4))},
columns=['A', 'B', 0])
df = DataFrame(columns=['A', 'B'])
df[0] = Series(1, index=range(4))
df.dtypes
str(df)
tm.assert_frame_equal(df, expected)
df = DataFrame(columns=['A', 'B'])
df.loc[:, 0] = Series(1, index=range(4))
df.dtypes
str(df)
tm.assert_frame_equal(df, expected)
def test_partial_set_empty_frame_row(self):
# GH5720, GH5744
# don't create rows when empty
expected = DataFrame(columns=['A', 'B', 'New'],
index=pd.Index([], dtype='int64'))
expected['A'] = expected['A'].astype('int64')
expected['B'] = expected['B'].astype('float64')
expected['New'] = expected['New'].astype('float64')
df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
y = df[df.A > 5]
y['New'] = np.nan
tm.assert_frame_equal(y, expected)
# tm.assert_frame_equal(y,expected)
expected = DataFrame(columns=['a', 'b', 'c c', 'd'])
expected['d'] = expected['d'].astype('int64')
df = DataFrame(columns=['a', 'b', 'c c'])
df['d'] = 3
tm.assert_frame_equal(df, expected)
tm.assert_series_equal(df['c c'], Series(name='c c', dtype=object))
# reindex columns is ok
df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
y = df[df.A > 5]
result = y.reindex(columns=['A', 'B', 'C'])
expected = DataFrame(columns=['A', 'B', 'C'],
index=pd.Index([], dtype='int64'))
expected['A'] = expected['A'].astype('int64')
expected['B'] = expected['B'].astype('float64')
expected['C'] = expected['C'].astype('float64')
tm.assert_frame_equal(result, expected)
def test_partial_set_empty_frame_set_series(self):
# GH 5756
# setting with empty Series
df = DataFrame(Series())
tm.assert_frame_equal(df, DataFrame({0: Series()}))
df = DataFrame(Series(name='foo'))
tm.assert_frame_equal(df, DataFrame({'foo': Series()}))
def test_partial_set_empty_frame_empty_copy_assignment(self):
# GH 5932
# copy on empty with assignment fails
df = DataFrame(index=[0])
df = df.copy()
df['a'] = 0
expected = DataFrame(0, index=[0], columns=['a'])
tm.assert_frame_equal(df, expected)
def test_partial_set_empty_frame_empty_consistencies(self):
# GH 6171
# consistency on empty frames
df = DataFrame(columns=['x', 'y'])
df['x'] = [1, 2]
expected = DataFrame(dict(x=[1, 2], y=[np.nan, np.nan]))
tm.assert_frame_equal(df, expected, check_dtype=False)
df = DataFrame(columns=['x', 'y'])
df['x'] = ['1', '2']
expected = DataFrame(
dict(x=['1', '2'], y=[np.nan, np.nan]), dtype=object)
tm.assert_frame_equal(df, expected)
df = DataFrame(columns=['x', 'y'])
df.loc[0, 'x'] = 1
expected = DataFrame(dict(x=[1], y=[np.nan]))
tm.assert_frame_equal(df, expected, check_dtype=False)
| [
"[email protected]"
] | |
757fdd5ec99459542dde88e360700156603c2846 | ee8c4c954b7c1711899b6d2527bdb12b5c79c9be | /assessment2/amazon/run/core/controllers/vivacious.py | 6023c96df4e75d647fba458235af9ef85c64b4ef | [] | no_license | sqlconsult/byte | 02ac9899aebea4475614969b594bfe2992ffe29a | 548f6cb5038e927b54adca29caf02c981fdcecfc | refs/heads/master | 2021-01-25T14:45:42.120220 | 2018-08-11T23:45:31 | 2018-08-11T23:45:31 | 117,135,069 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 372 | py | #!/usr/bin/env python3
from flask import Blueprint, Flask, render_template, request, url_for
controller = Blueprint('vivacious', __name__, url_prefix='/vivacious')
# @controller.route('/<string:title>', methods=['GET'])
# def lookup(title):
# if title == 'Republic': # TODO 2
# return render_template('republic.html') # TODO 2
# else:
# pass
| [
"[email protected]"
] | |
0743fab55b7760c26dc13b3922aea2a97eec77c6 | 50008b3b7fb7e14f793e92f5b27bf302112a3cb4 | /recipes/Python/580763_Context_Manager_Arbitrary_Number_Files/recipe-580763.py | 150135fb1201d2a97d2a7f356d35cb1f5cb58577 | [
"MIT"
] | permissive | betty29/code-1 | db56807e19ac9cfe711b41d475a322c168cfdca6 | d097ca0ad6a6aee2180d32dce6a3322621f655fd | refs/heads/master | 2023-03-14T08:15:47.492844 | 2021-02-24T15:39:59 | 2021-02-24T15:39:59 | 341,878,663 | 0 | 0 | MIT | 2021-02-24T15:40:00 | 2021-02-24T11:31:15 | Python | UTF-8 | Python | false | false | 416 | py | class Files(tuple):
def __new__(cls, *filePaths):
files = []
try:
for filePath in filePaths:
files.append(open(filePath))
files[-1].__enter__()
except:
for file in files:
file.close()
raise
else:
return super(Files, cls).__new__(cls, files)
def __enter__(self):
return self
def __exit__(self, *args):
for file in self:
file.close()
| [
"[email protected]"
] | |
8bc30b4ffffdd2a9e6c67b806b72324ac9bcf8c5 | 699c7f26a91106a2fc79bb15299ce0cee532a2dd | /test/pivottest.py | a875542be8d7a661c68859711f9c108434bede2c | [] | no_license | samconnolly/astro | 70581a4d3f2086716aace3b5db65b74aaaa5df95 | 3731be313592c13dbb8af898e9734b98d83c0cc2 | refs/heads/master | 2020-04-06T03:40:27.454279 | 2014-03-12T14:36:34 | 2014-03-12T14:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,709 | py | # Programme to test how a pivoting spectral component, plus a
# constant soft component changes the shape of the flux-flux diagram
import numpy as np
from pylab import *
# parameters
epivot = 2.0 # KeV pivot energy
pivmin = 2.0
pivmax = 10.0
cindex = 2.0 # index of constant component
nsteps = 10.0
# constants
h = 6.63 # planck
e = 1.6e-19 # electron charge
# energy axis
energy = np.arange(0.5,10.0,0.01) # energy range of spectrum in KeV
logenergy = np.log(energy) # log of energy
freq = (energy*e*1000.0)/h # frequency range in Hz
stepsize = (pivmax-pivmin)/nsteps
pivnorm = ( ((epivot*e*1000.0)/h)**pivmin)
fluxflux = [[],[],[]]
# plotting the log spectrum components
# constant component
cflux = freq**(-cindex) # constant flux component
logcflux = np.log10(cflux) # log of constant flux
logvflux = []
# varying component
for piv in np.arange(pivmin,pivmax,stepsize):
currvflux = (freq**(-piv))
pnorm = (((epivot*e*1000.0)/h)**piv)
currvflux = (currvflux/pnorm)*pivnorm
logcurrvflux = np.log10(currvflux) # log thereof
logvflux.append(logcurrvflux)
# soft/hard delineaters
low = [np.log(0.5),np.log10(0.5)]
div = [np.log(2.0),np.log10(2.0)]
high = [np.log(10.0),np.log10(10.0)]
yrange = [logcflux[-1],logvflux[-1][0]]
subplot(1,2,1) # log spectrum plot
#plot(logenergy,logcflux,color="red")
plot(logenergy,logvflux[0],color="blue")
plot(logenergy,logvflux[len(logvflux)/2],color="blue")
plot(logenergy,logvflux[-1],color="blue")
#plot(low,yrange)
#plot(div,yrange)
#plot(high,yrange)
# total spectrum
subplot(1,2,2)
for x in [0,len(logvflux)/2,-1]:
logtotal = logvflux[x] + logcflux
plot(logenergy,logtotal)
show()
| [
"[email protected]"
] | |
cbb97a71e43ba0aeae79c64781b1c2a7c1f09cb8 | 8fb4f83ac4e13c4c6de7f412f68c280d86ddea15 | /eon/tests/unit/deployer/network/ovsvapp/test_vapp_util.py | 6e5508948b41971f8773c56807dceeb902078137 | [
"Apache-2.0"
] | permissive | ArdanaCLM/hpe-eon | cbd61afa0473bbd9c6953e5067dbe5a7ff42c084 | 48a4086d2ccc5ccac60385b183f0d43f247c0b97 | refs/heads/master | 2021-07-25T18:55:30.176284 | 2017-10-24T08:49:42 | 2017-10-24T08:49:42 | 103,971,673 | 0 | 1 | null | 2017-11-07T15:47:45 | 2017-09-18T17:43:45 | Python | UTF-8 | Python | false | false | 6,225 | py | #
# (c) Copyright 2015-2017 Hewlett Packard Enterprise Development Company LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import contextlib
from mock import patch
from pyVmomi import vim
from eon.deployer.network.ovsvapp.util.vapp_util import OVSvAppUtil
from eon.deployer.util import VMwareUtils
from eon.tests.unit import tests
from eon.tests.unit.deployer import fake_inputs
# TODO: Put all the helper classes in one location
class PrepFolder:
name = 'fake_folder'
childEntity = False
class MoveInto_Task:
def __init__(self, val):
self.val = val
class Destroy_Task:
pass
class MOB:
class content():
def rootFolder(self):
pass
def propertyCollector(self):
pass
class VM:
class Vm:
class config:
annotation = 'hp-ovsvapp'
class runtime:
powerState = 'poweredOn'
class PowerOff:
pass
class Destroy:
pass
vm = [Vm]
class Cluster:
@staticmethod
def ReconfigureComputeResource_Task(cluster_spec_ex, modify):
pass
class TestOVSvAppUtil(tests.BaseTestCase):
def setUp(self):
super(TestOVSvAppUtil, self).setUp()
self.ovs_vapp_util = OVSvAppUtil()
vc_info = fake_inputs.data.get('vcenter_configuration')
self.cluster = {'obj': Cluster(),
'name': vc_info.get('cluster'),
'configuration.dasConfig.enabled': True,
'configuration.drsConfig.enabled': True}
def test_get_ovsvapps(self):
fake_vms = [{'name': 'ovsvapp_fake_vm',
'config.annotation': 'hp-ovsvapp',
'runtime.host': 'host-1'}]
content = None
vm_folder = None
with contextlib.nested(
patch.object(VMwareUtils, 'get_view_ref'),
patch.object(VMwareUtils, 'collect_properties',
return_value=fake_vms))as (
mock_get_view_ref, mock_collect_properties):
output = self.ovs_vapp_util.get_ovsvapps(content, vm_folder,
fake_inputs.fake_clusters)
self.assertEqual(fake_vms[0], output['host-1'])
self.assertTrue(mock_get_view_ref.called)
self.assertTrue(mock_collect_properties.called)
def test_get_active_hosts(self):
host = {'obj': 'host1', 'name': 'fake_host'}
with patch.object(VMwareUtils, 'get_all_hosts',
return_value=[host]) as mock_get_all_hosts:
self.ovs_vapp_util.get_active_hosts(MOB, 'vm_folder',
['host1'], 'cluster')
self.assertTrue(mock_get_all_hosts.called)
def test_exec_multiprocessing(self):
pass
def test_get_folder(self):
pass
def test_create_host_folder(self):
with patch.object(OVSvAppUtil, '_get_folder',
return_value='fake_folder') as mock_get_folder:
self.ovs_vapp_util.create_host_folder(
'content', [{'cluster': {'name': self.cluster.get('name')}}],
'host_folder')
self.assertTrue(mock_get_folder.called)
def test_move_hosts_in_to_folder(self):
pass
def test_enter_maintenance_mode(self):
pass
def test_destroy_failed_commissioned_vapps(self):
host = {'obj': VM, 'name': 'fake_host'}
with patch.object(VMwareUtils, 'wait_for_task') as mock_wait_for_task:
self.ovs_vapp_util.destroy_failed_commissioned_vapps(host, MOB)
self.assertTrue(mock_wait_for_task.called)
def test_move_host_back_to_cluster(self):
host = {'obj': 'host', 'name': 'fake_host'}
cluster = {'obj': PrepFolder, 'name': 'fake_cluster'}
with contextlib.nested(
patch.object(OVSvAppUtil, 'destroy_failed_commissioned_vapps'),
patch.object(OVSvAppUtil, 'enter_maintenance_mode'),
patch.object(VMwareUtils, 'wait_for_task')) as (
mock_destroy, mock_enter_maintenance_mode,
mock_wait_for_task):
self.ovs_vapp_util.move_host_back_to_cluster(MOB, host, cluster,
PrepFolder, 'err')
self.assertTrue(mock_destroy.called)
self.assertTrue(mock_enter_maintenance_mode.called)
self.assertTrue(mock_wait_for_task.called)
def test_get_host_parent(self):
pass
def test_get_cluster_inventory_path(self):
pass
def test_get_eon_env(self):
pass
def test_exec_subprocess(self):
pass
def test_disable_ha_on_ovsvapp(self):
with contextlib.nested(
patch.object(vim.VirtualMachine, '__init__',
return_value=None),
patch.object(vim.HostSystem, '__init__', return_value=None),
patch.object(VMwareUtils, 'wait_for_task')) as (
mock_vm, mock_host, mock_wait_for_task):
vim.VirtualMachine.name = 'fake-vm'
self.vm_obj = vim.VirtualMachine()
self.host_obj = vim.HostSystem()
host = {'obj': self.host_obj,
'name': 'fake_host'}
self.ovs_vapp_util.disable_ha_on_ovsvapp(fake_inputs.session['si'],
self.vm_obj, self.cluster,
host)
self.assertTrue(mock_vm.called)
self.assertTrue(mock_host.called)
self.assertTrue(mock_wait_for_task.called)
| [
"[email protected]"
] | |
e646bb93cc2e371f15aec3b80cb3f8c0380cccc1 | 51a37b7108f2f69a1377d98f714711af3c32d0df | /src/leetcode/P292.py | 5c48dc1f6e7885796ce6210fadce7d6c63219433 | [] | no_license | stupidchen/leetcode | 1dd2683ba4b1c0382e9263547d6c623e4979a806 | 72d172ea25777980a49439042dbc39448fcad73d | refs/heads/master | 2022-03-14T21:15:47.263954 | 2022-02-27T15:33:15 | 2022-02-27T15:33:15 | 55,680,865 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 136 | py | class Solution:
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0
| [
"[email protected]"
] | |
632dde6bdbc21624a39c299566810a9f9a7bbac0 | 24a9c8f2fac4e2b20f731387336ec4e22d5fd2c7 | /AdministrativePenalty/天津市/1.保险监督管理局.py | 40398e49e4a5061da89e045b006e224c3d4e1126 | [] | no_license | yunli45/pycharmProjectHome | 94833822e3036bf2baf8700c4493132e63177d4c | 9a382c060963eb801a3da07423e84a4132257b02 | refs/heads/master | 2020-05-23T23:35:20.476973 | 2019-05-16T09:45:58 | 2019-05-16T09:49:16 | 186,986,803 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,095 | py | import requests
import re
import time
from bs4 import BeautifulSoup
import pymssql
# # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# 抓取天津市滨海新区 —银监分局数据
#
# # # # # # # # # # # # # # # # # # # # # # # # # # #
class Utils(object):
def __init__(self):
self.header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'}
self.OnlyID = 1
self.showId = 12300000
def getPage(self,url=None):
response = requests.get(url,headers = self.header)
response = response.content.decode('UTF-8')
return response
def parsePage(self,url=None,pageNo=None,baseUrl="http://ningxia.circ.gov.cn",path="F:\行政处罚数据\天津\/%s"):
if pageNo=='1':
response = self.getPage("http://ningxia.circ.gov.cn/web/site35/tab3385/module8892/page1.htm")
else:
response = self.getPage(url+pageNo+'.htm')
print("+++++++++++++++++++这是第:"+pageNo+"页++++++++++++++++")
soup = BeautifulSoup(response, 'lxml')
soup = soup.find_all('div', attrs={'id': "ess_ctr8892_contentpane"})
# print(soup)
rs = re.findall(re.compile(r'<a.*?href="(.*?)".*?title="(.*?)">'), str(soup))
RsdataID = re.findall(re.compile(r'<a.*?href=".*?" id="(.*?)".*?>'), str(soup))
rsTimeList = re.findall(re.compile(r'<td style="width: 70px; color: #c5c5c5;">(.*?)</td>'), str(soup))
# print(rs)
# print(rsTimeList)
# print(RsdataID)
srcList= []
titleList = []
# print(len(rs))
# print(rs)
for i in rs :
srcList.append(i[0])
titleList.append(i[1])
for src in srcList:
resTitle =titleList[srcList.index(src)]
resTime ='20'+ rsTimeList[srcList.index(src)].replace('(','').replace(')','')
dataId = RsdataID[srcList.index(src)]
if src.find("http") == -1:
ContentSrc = baseUrl + src
else:
ContentSrc = src
response2 = requests.get(ContentSrc,headers =self.header)
response2 = response2.content.decode('UTF-8')
soup2 = BeautifulSoup(response2,'lxml')
rs2 = soup2.find('span',attrs={'id':'zoom'})
# # # # # # # # # # # # # # # # #
#
# 提取文书号等信息
#
# # # # # # # # # # # # # # # # #
rs2 = str(rs2).replace('\xa0','').replace('\u3000','').replace("'","''")
rs2 = re.sub('<span.*?>','',rs2).replace('</span>','')
# print(rs2)
id = self.OnlyID
dataId = dataId
documentNum = re.sub(r'.*?处罚决定书','',resTitle).replace("(",'') .replace(")",'') # 书文号
# print(rs2)
RsbePunished =re.findall(re.compile(r'当事人.*?</p>',re.M|re.S), rs2)
if RsbePunished:
bePunished = RsbePunished[0].replace("\n",'').replace("</p>",'') # 被处罚人或机构 # 被处罚机构或单位
else:
bePunished = ''
print(bePunished)
Rsprincipal = re.findall(re.compile(r'法定代表人.*?</p>',re.M|re.S),rs2)
Rsprincipa2 = re.findall(re.compile(r'主要负责人.*?</p>',re.M|re.S), rs2) # 法定代表人 # 法定代表人
if Rsprincipal:
principal = Rsprincipal[0].replace("\n",'').replace("</p>",'') # 法定代表人
elif Rsprincipa2:
principal = Rsprincipa2[0].replace("\n",'').replace("</p>",'')
else:
principal=''
RslawEnforcement= re.findall(re.compile(r'当事人.*?:(.*?)</p>',re.M|re.S),rs2) # 被处罚机构或单位
if RslawEnforcement:
lawEnforcement= RslawEnforcement[0].replace("\n",'').replace("</p>",'')
else:
lawEnforcement=''
print(lawEnforcement)
RspunishedDate = re.findall(re.compile(r'<p.*?>.*?(.*?年.*?月.*?日.*?).*?</p>'), rs2) # s时间
if RspunishedDate and len(RspunishedDate[-1])<= 30:
punishedDate = RspunishedDate[-1] # 受处罚时间
else:
punishedDate = resTime
print(punishedDate)
content = rs2
uniqueSign = ContentSrc # url地址
address = '天津'# 省份
area = '所有区县'# 地区
agency = '中国保监会天津监管局' # 处罚机构
if len(content) <= 100:
grade = -1 # 级别
elif 100 < len(content)<= 200:
grade = 1 # 级别
elif 200< len(content)<= 1500:
grade = 2 # 级别
elif len(content)>1500:
grade = 0 # 级别
showId = self.showId # 系统ID
showAddress = None
showArea = None
# # # # # # # # # # # # # # # # #
#
# 附件下载
#
# # # # # # # # # # # # # # # # #
adjunct = re.findall(re.compile(r'<a.*?href="(.*?)".*?>(.*?)</a>', re.I | re.S), rs2)
if rs2:
conn = pymssql.connect(host='(local)', user='sa', password='123456', database='AdministrativePun')
# 打开游标
cur = conn.cursor();
if not cur:
raise Exception('数据库连接失败!')
else:
print("数据库链接成功")
sql1 = " INSERT INTO TJbhxqCBRC(dataId,title,documentNum,bePunished,principal,lawEnforcement,punishedDate,content,uniqueSign,address,area,agency,grade,showId,showAddress,showArea) values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') " % (dataId, resTitle, documentNum, bePunished,principal,lawEnforcement,punishedDate,content,uniqueSign,address, area, agency,grade,showId,showAddress,showArea)
# print(sql1)
if adjunct:
print("这条数据存在附件,可能会很大,请稍等,已经自动开始下载.....")
for xiaZai in adjunct:
rsDocuniqueSign = xiaZai[0]
rsDocName = xiaZai[1]
xiaZai = str(xiaZai)
rsDoc1 = re.findall(re.compile(r'.*?.doc', re.I), xiaZai)
rsPdF = re.findall(re.compile(r'.*?.pdf', re.I), xiaZai)
rsXlsx = re.findall(re.compile(r'.*?.xlsx|xls', re.I), xiaZai)
rsZip = re.findall(re.compile(r'.*?.zip', re.I), xiaZai)
rsRar = re.findall(re.compile(r'.*?.rar', re.I), xiaZai)
reJpg = re.findall(re.compile(r'.*?.jpg', re.I), xiaZai)
if rsDoc1:
rsDocName = rsDocName + ".doc"
rsDocName = rsDocName.replace("/", '_')
path1 = path % (rsDocName)
if rsDocuniqueSign.find("http") == -1:
rsDocuniqueSign = "%s" % (baseUrl) + rsDocuniqueSign
else:
rsDocuniqueSign = rsDocuniqueSign
# print(rsDocuniqueSign)
r = requests.get(rsDocuniqueSign, headers=self.header, timeout=300)
with open(path1, "wb") as f:
f.write(r.content)
f.close()
elif rsPdF:
rsDocName = rsDocName + ".PDF"
rsDocName = rsDocName.replace("/", '_')
path1 = path % (rsDocName)
if rsDocuniqueSign.find("http") == -1:
rsDocuniqueSign = baseUrl + rsDocuniqueSign
else:
rsDocuniqueSign = rsDocuniqueSign
# print(rsDocuniqueSign)
r = requests.get(rsDocuniqueSign, headers=self.header)
with open(path1, "wb") as f:
f.write(r.content)
f.close()
elif rsXlsx:
rsDocName = rsDocName + ".xlsx"
rsDocName = rsDocName.replace("/", '_')
path1 = path % (rsDocName)
if rsDocuniqueSign.find("http") == -1:
rsDocuniqueSign = baseUrl + rsDocuniqueSign
else:
rsDocuniqueSign = rsDocuniqueSign
# print(rsDocuniqueSign)
r = requests.get(rsDocuniqueSign, headers=self.header)
with open(path1, "wb") as f:
f.write(r.content)
f.close()
elif rsZip:
rsDocName = rsDocName + ".zip"
rsDocName = rsDocName.replace("/", '_')
path1 = path % (rsDocName)
if rsDocuniqueSign.find("http") == -1:
rsDocuniqueSign = baseUrl + rsDocuniqueSign
else:
rsDocuniqueSign = rsDocuniqueSign
# print(rsDocuniqueSign)
r = requests.get(rsDocuniqueSign, headers=self.header)
with open(path1, "wb") as f:
f.write(r.content)
f.close()
elif rsRar:
rsDocName = rsDocName + ".rar"
rsDocName = rsDocName.replace("/", '_')
path1 = path % (rsDocName)
if rsDocuniqueSign.find("http") == -1:
rsDocuniqueSign = baseUrl + rsDocuniqueSign
else:
rsDocuniqueSign = rsDocuniqueSign
# print(rsDocuniqueSign)
r = requests.get(rsDocuniqueSign, headers=self.header)
with open(path1, "wb") as f:
f.write(r.content)
f.close()
elif reJpg:
rsDocName = rsDocName + ".jpg"
rsDocName = rsDocName.replace("/", '_')
path1 = path % (rsDocName)
if rsDocuniqueSign.find("http") == -1:
rsDocuniqueSign = "%s" % (baseUrl) + rsDocuniqueSign
else:
rsDocuniqueSign = rsDocuniqueSign
# print(rsDocuniqueSign)
r = requests.get(rsDocuniqueSign, headers=self.header, timeout=300)
with open(path1, "wb") as f:
f.write(r.content)
f.close()
cur.execute(sql1)
self.OnlyID += 1
self.showId += 1
conn.commit()
conn.close()
print("下一页开始的id是" + str(self.OnlyID))
print("这一夜爬取成功相关数据和文件,文件保存的目录在" + path)
####### 执行 ########
if __name__ =="__main__":
url = "http://ningxia.circ.gov.cn/web/site35/tab3385/module8892/page"
AdminiStrative =Utils()
# parsePage(url)
for i in range(0,12):
AdminiStrative.parsePage(url,str(i+1))
time.sleep(3)
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.