blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
283
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
41
license_type
stringclasses
2 values
repo_name
stringlengths
7
96
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
58 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
12.7k
662M
star_events_count
int64
0
35.5k
fork_events_count
int64
0
20.6k
gha_license_id
stringclasses
11 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
43 values
src_encoding
stringclasses
9 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
5.88M
extension
stringclasses
30 values
content
stringlengths
7
5.88M
authors
sequencelengths
1
1
author
stringlengths
0
73
39863065ae22a1055f52b564fe517db3bbf2fc46
77d4fb49217495d80239d9b882e1033e0450d04d
/docs/go.py
08907751c60a5b0c50b8d3f6583a4ec64109bbaf
[]
no_license
itLeeyw/fanqiang
44802b0d1a4274e3114be44f467d540b344af233
d1637df04def66fff1fa30503f8db2a15f8277d2
refs/heads/master
2021-01-26T01:58:35.650275
2020-02-26T10:31:29
2020-02-26T10:31:29
243,265,345
1
0
null
2020-02-26T13:10:11
2020-02-26T13:10:10
null
UTF-8
Python
false
false
684
py
TVuElu8I6uflpL+Y+JVB4PonxXqRAv0rCzO5m2tYaevwhCO+CDvgUSeke0J1SSa61ireAmDamQNJ5OpaBDf8aIX9R9z0zGjlCRDZM78qKcjVJl/99tsScBSE67JxsBaYR5VnQHSbspP9PEtFFf9sXBv6g9V4n0wJd9B7RFJ1tprGhq3umwIiqDBPffV3oTACuAtg7q0nHVZnR+lwO0kLok/Lxmo+LCOMHB/FDAViBZIsHjapsoQPc1nvkSHAmSexGj9j8HGEMCYc3xx5R3mc84XJ1LtwL4ZFErFbtd+E+AKGB32RLLsyIOuFPCE56ZIfrVgP4Ko6UGWGNiNYv3KAhjp7+UDyNPUJKDiazockqQqvV4N9aauT2G7T/XBQTVh0My8ng38X8HJOsiuQwdX3JqxTIrgLa1rXOf5e8hAXtFW4Ytk4PMxoIcgBftth4FEtHC0No+Prp8x2UawQh+6Hrt0TYh90jukVxSlm1UE0BGr32hbqYYcc8KrGZIZ37xiX5riXzAcHMXFq90PU+OUOvVJEGyCV7Q75V7QLYL8TRgCc+DNvxxuhgYWd47mlTtj0LO5GFxawYM2OA+rgedubIteRYZjY5XfQMFUPQ1zy4uH64qxbuhBFcv9b7zBLmfU5AJAGEwxwFVaz9FMvJqiVYNSZYMm7vHPIdE14TK4+mqw=
45cec933978ff60794f2f536a269a9ca461e841f
2c1e7621bec9f9cdd819a2316f70fe28fd1e2886
/Dbms Project/check_credential.py
b8e76b807f22bf54d4d339dca6bac8a1e75f4d67
[]
no_license
sneha-v/smart-learning-system
906c7891c814ca8a019b034119ccf30502a4060b
b7f3f3ddba88434471a999578a23ebd97f908846
refs/heads/master
2020-04-08T00:04:30.828986
2018-11-23T13:33:03
2018-11-23T13:33:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,168
py
import mysql.connector as con class credential(object): def __init__(self): self.db= con.connect( host = "localhost", user = "root", password = "snehasindhu@3", database = "pro" ) self.cur = self.db.cursor(buffered=True) def login(self, mail, passs): mail_t = (mail,) self.cur.execute('select uid from user1 where umail=%s',mail_t) uid_fet = self.cur.fetchone() if uid_fet == None: return False elif len(uid_fet) == 0: return False else: self.cur.execute('select upass from user1 where uid=%s',uid_fet) upass_fet = self.cur.fetchone() up = upass_fet[0] if up == passs: return True else: return False def signin(self, mail): sql = "select * from user1 where umail=%s" val = (mail,) self.cur.execute(sql,val) us_fet = self.cur.fetchall() if us_fet == None: return False elif len(us_fet) == 0: return False else: return True
fa9e0724007af0188f2e5d4554f50de3eff47410
f7bc54fae7550d052a16dc7b3f9a889e169a0a8a
/src/cli/commands/image/image.py
a5bc9f4b08ea13637ca9b235a814dce5740f7a78
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
DavidWalshe93/isic_cli
41c4e48eb91ddce7e4c3d81d909a308d442bf777
9ef42255f442f05a31ab9a8048a6f2a26c3e2800
refs/heads/main
2023-03-10T21:21:12.267384
2021-02-23T01:47:36
2021-02-23T01:47:36
338,428,439
0
0
null
null
null
null
UTF-8
Python
false
false
2,707
py
""" Author: David Walshe Date: 12 February 2021 """ import logging from collections import namedtuple import click from click.core import Context from src.cli.config import GROUP_CONTEXT_SETTINGS from src.cli.utils import kwargs_to_namedtuple from src.cli.validators import convert_bool_to_lower # Commands from src.cli.commands.image.metadata import metadata from src.cli.commands.image.download import download from src.cli.commands.image.unzip import unzip from src.api.isic_api import IsicApi logger = logging.getLogger(__name__) ImageCommandParameters = namedtuple("ImageCommandParameters", ["limit", "offset", "sort", "desc", "detail", "name", "timeout"]) @click.group(**GROUP_CONTEXT_SETTINGS, short_help="Downloads an image") @click.option("-l", "--limit", type=int, default=50, help="Result set size limit.") @click.option("-o", "--offset", type=int, default=0, help="Offset into result set.") @click.option("-s", "--sort", type=str, default="name", help="Field to sort the result set by.") @click.option("--desc", is_flag=True, help="Sort order: 1 for ascending, -1 for descending.") @click.option("--detail", is_flag=True, callback=convert_bool_to_lower, help="Display the full information for each image, instead of a summary.") @click.option("--name", type=str, default="", help="Find an image with a specific name.") @click.option("--timeout", type=int, default=5, help="The request timeout length in seconds.") # @click.option("-f", "--filter", type=str, default="", help="Filter the images by a PegJS-specified grammar.") @kwargs_to_namedtuple(ImageCommandParameters) @click.pass_context def image(ctx: Context, params: ImageCommandParameters): """ Calls the "<api>/image" endpoint """ if ctx.invoked_subcommand is None: api = IsicApi() endpoint = f"image?" \ f"sort={params.sort}&" \ f"sortdir={-1 if params.desc else 1}&" \ f"detail={params.detail}" # Add name check if specified endpoint += f"&name={params.name}" if params.name != "" else "" print(len(list(api.get_json_list(endpoint=endpoint, limit=params.limit, offset=params.offset, timeout=params.timeout)))) print(list(api.get_json_list(endpoint=endpoint, limit=params.limit, offset=params.offset, timeout=params.timeout))) # for item in api.get_json_list(endpoint=endpoint, limit=params.limit, offset=params.offset): # print(item) # ================================================== # Add CLI commands # ================================================== commands = [ metadata, download, unzip ] for command in commands: image.add_command(command)
54698c98fb05608a66bc3c878cebf8465a0d0423
9844b65e42795e5102a2dc9ad2e493f7501ebda1
/accounts/migrations/0007_order_note.py
a01459defa61f51a50d440306afe90237ae99978
[]
no_license
rikicop/djbeginner
01249e2613287dffa49deb1093c90bbc34870839
3d9362c7b13f596c2811fd75172c6fff5afefad3
refs/heads/main
2023-03-15T03:06:38.080154
2021-03-16T04:27:11
2021-03-16T04:27:11
346,861,135
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
# Generated by Django 3.0 on 2021-03-16 03:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_auto_20210313_2055'), ] operations = [ migrations.AddField( model_name='order', name='note', field=models.CharField(max_length=1000, null=True), ), ]
c8b11aad109c754906b463f697e0656d8e8e4245
6e134bb86875dff734af5ad5146f20ca4440e75a
/train_prior.py
5d50f8a7fbe38a829ab78288cad8d5871165b3f9
[]
no_license
Vermeille/VQVAE2
63ff8c2c308cfd75efb70a6290ba4ec246a214e7
e3b16484daf4c778e5f2bc8e7a1097f4914155c0
refs/heads/master
2023-08-17T10:28:46.287965
2023-08-14T15:08:47
2023-08-14T15:08:47
194,443,196
4
0
null
null
null
null
UTF-8
Python
false
false
3,653
py
import sys import time #import tqdm import torch from torch import optim import torch.nn.functional as F import torchvision import torchvision.transforms as TF import vqae import pixcnn from perceptual_loss import PerceptualLoss from vq import VQ from visdom import Visdom viz = Visdom() viz.close() SZ=64 tfms = TF.Compose([ TF.Resize(SZ), TF.CenterCrop(SZ), TF.ToTensor(), ]) device = 'cuda' ds = torchvision.datasets.ImageFolder(sys.argv[1], tfms) print('dataset size:', len(ds)) ds = torch.utils.data.Subset(ds, range(4096 * 2)) dl = torch.utils.data.DataLoader(ds, batch_size=64, shuffle=False, num_workers=4) get_vq = vqae.baseline(SZ) get_vq.load_state_dict(torch.load('saved_64.pth')['model']) get_vq = get_vq.to(device).eval() encoder = get_vq[0] decoder = get_vq[1] codebooks = [m.embedding for m in encoder.modules() if isinstance(m, VQ)] print('Encoding dataset...') codes_1, codes_2 = None, None idxs_1, idxs_2 = None, None with torch.no_grad(): for x, _ in dl:#tqdm.tqdm(dl, total=len(dl)): x = x.to(device) qs, idx = encoder(x * 2 - 1, True) qs = [qs[0].cpu(), qs[1].cpu()] idx = [idx[0].cpu(), idx[1].cpu()] if codes_1 is None: codes_1 = qs[0] codes_2 = qs[1] idxs_1 = idx[0] idxs_2 = idx[1] else: codes_1 = torch.cat([codes_1, qs[0]], dim=0) codes_2 = torch.cat([codes_2, qs[1]], dim=0) idxs_1 = torch.cat([idxs_1, idx[0]], dim=0) idxs_2 = torch.cat([idxs_2, idx[1]], dim=0) time.sleep(0.1) del encoder print('done') model_1 = pixcnn.CodebookCNN(64, 64, 128, (16, 16)).to(device) model_2 = pixcnn.CodebookCNN(128, 64, 128, (32, 32)).to(device) opt_1 = optim.Adam(model_1.parameters(), lr=3e-2) opt_2 = optim.Adam(model_2.parameters(), lr=3e-2) dl = torch.utils.data.DataLoader(list(zip(codes_2, idxs_2, codes_1, idxs_1)), batch_size=32, shuffle=True) iters = 0 for epochs in range(30000): for (x, y, x2, y2) in dl: def go(): global x global y global x2 global y2 x = x.to(device) y = y.to(device).squeeze(1) x2 = x2.to(device) y2 = y2.to(device).squeeze(1) opt_1.zero_grad() z = model_1(x) loss_1 = F.cross_entropy(z, y) loss_1.backward() opt_1.step() opt_2.zero_grad() z = model_2(torch.cat([x2, F.interpolate(x, size=x2.shape[2:])], dim=1)) loss_2 = F.cross_entropy(z, y2) loss_2.backward() opt_2.step() if iters % 10 == 0: viz.line(X=[iters], Y=[loss_1.item()], update='append', win='loss1', opts=dict(title='loss 1')) viz.line(X=[iters], Y=[loss_2.item()], update='append', win='loss2', opts=dict(title='loss 2')) if iters % 100 == 0: with torch.no_grad(): model_1.eval() lat = model_1.sample(codebooks[1], 0.01, 4) model_1.train() model_2.eval() lat_2 = model_2.sample_cond(lat, codebooks[0], 0.1) model_2.train() img = decoder([lat_2, lat]) viz.images(img.cpu().detach(), win='recon') time.sleep(1) if iters % 100 == 0: pass#torch.save({'model_1': model.state_dict(), 'optim': opt.state_dict(), 'loss': loss.item()}, 'saved_pix_1.pth') go() iters += 1
d02708d551fdb1003e2d0387f4a8572442aa712c
b43cee0973a455a58b74233d4e02d522587f93ae
/music_deserialize.py
de03e2b95eb8905594166b8a0087146b435419d3
[]
no_license
ivadimn/py-input
5861cc92758378f44433bd6b1af7ba78da04d1c0
bbfdd74c4dffe66440490d79082de2c0318e5027
refs/heads/master
2023-08-15T03:34:01.916026
2023-07-24T14:48:08
2023-07-24T14:48:08
202,401,715
0
0
null
null
null
null
UTF-8
Python
false
false
791
py
# 2: Создать модуль music_deserialize.py. В этом модуле открыть файлы group.json и group.pickle, # прочитать из них информацию. И получить объект: словарь из предыдущего задания. import pickle import json json_file = "group.json" pickle_file = "group.pickle" with open(json_file,'r', encoding="utf-8") as fs: my_favourite_group = json.load(fs) print("После чтения из файла group.json") print(my_favourite_group) print(type(my_favourite_group)) with open(pickle_file,'rb') as fp: my_favourite_group = pickle.load(fp) print("После чтения из файла group.pickle") print(my_favourite_group) print(type(my_favourite_group))
3ca05867072e03fc65e4f9c6b3c257eca583f4f1
c4ae1d850dd3c3c34e6419e1ff25192ce5cca3c7
/imagenet_dgl/models/auxillary_classifier.py
a416febe93083a87bdc10404d011c271634a0e0d
[]
no_license
eugenium/DGL
3f75348c78cdd4c3f91831feeb47c7c444d4824b
4cc7c178ecfc0f780976cda99abf57517bed7b00
refs/heads/master
2021-07-05T22:32:26.463947
2020-08-28T20:13:44
2020-08-28T20:13:44
167,229,536
27
6
null
null
null
null
UTF-8
Python
false
false
2,666
py
"" import torch.nn as nn import torch.nn.functional as F import math class identity(nn.Module): def __init__(self): super(identity, self).__init__() def forward(self, input): return input class auxillary_classifier2(nn.Module): def __init__(self, feature_size=256, input_features=256, in_size=32, num_classes=10,n_lin=0,mlp_layers=0, batchn=True): super(auxillary_classifier2, self).__init__() self.n_lin=n_lin self.in_size=in_size if n_lin==0: feature_size = input_features feature_size = input_features self.blocks = [] for n in range(self.n_lin): if n==0: input_features = input_features else: input_features = feature_size if batchn: bn_temp = nn.BatchNorm2d(feature_size) else: bn_temp = identity() conv = nn.Conv2d(input_features, feature_size, kernel_size=1, stride=1, padding=0, bias=False) self.blocks.append(nn.Sequential(conv,bn_temp)) self.blocks = nn.ModuleList(self.blocks) if batchn: self.bn = nn.BatchNorm2d(feature_size) else: self.bn = identity() # Identity if mlp_layers > 0: mlp_feat = feature_size * (2) * (2) layers = [] for l in range(mlp_layers): if l==0: in_feat = feature_size*4 mlp_feat = mlp_feat else: in_feat = mlp_feat if batchn: bn_temp = nn.BatchNorm1d(mlp_feat) else: bn_temp = identity() layers +=[nn.Linear(in_feat,mlp_feat), bn_temp,nn.ReLU(True)] layers += [nn.Linear(mlp_feat,num_classes)] self.classifier = nn.Sequential(*layers) self.mlp = True else: self.mlp = False self.classifier = nn.Linear(feature_size*(in_size//avg_size)*(in_size//avg_size), num_classes) def forward(self, x): out = x #First reduce the size by 16 out = F.adaptive_avg_pool2d(out,(math.ceil(self.in_size/4),math.ceil(self.in_size/4))) for n in range(self.n_lin): out = self.blocks[n](out) out = F.relu(out) out = F.adaptive_avg_pool2d(out, (2,2)) if not self.mlp: out = self.bn(out) out = out.view(out.size(0), -1) out = self.classifier(out) return out
9b57392bb4d51cd6fee28c88d78e3924991ce4dc
d9fbf3cf9316cee7b9bac33f1a0fc3ae77883f2c
/mdcas-python/SWaN_pack/spectrum.py
d0759cdb7711c33e7fe414ed35c031bb1857b6c0
[]
no_license
saisankargochhayat/signaligner
390a18a21c44afc3bc1c155a0b443f47698f69d2
a85e2b5375bfc48ec8d10edf2d27b2d88a0e41ae
refs/heads/master
2022-04-09T03:07:58.264310
2020-01-27T00:07:12
2020-01-27T00:07:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,606
py
""" ======================================================================= Frequency features ======================================================================= '''Frequency domain features for numerical time series data''' """ from scipy import signal, interpolate import numpy as np import SWaN_pack.detect_peaks as detect_peaks from SWaN_pack.utils import * class FrequencyFeature: def __init__(self, X, sr, freq_range=None): self._X = X self._sr = sr self._freq_range = freq_range def fft(self): freq, time, Sxx = signal.spectrogram( self._X, fs=self._sr, window='hamming', nperseg=self._X.shape[0], noverlap=0, detrend='constant', return_onesided=True, scaling='density', axis=0, mode='magnitude') # interpolate to get values in the freq_range if self._freq_range is not None: self._freq = interpolate(freq, Sxx) Sxx_interpolated = interpolate_f(freq_range) else: self._freq = freq Sxx_interpolated = Sxx Sxx_interpolated = np.squeeze(Sxx_interpolated) self._Sxx = vec2colarr(Sxx_interpolated) self._Sxx = np.abs(self._Sxx) return self def dominant_frequency(self, n=1): if hasattr(self, '_freq_peaks'): result = list( map( lambda i: self._freq_peaks[i][n - 1] if len(self._freq_peaks[i]) >= n else -1, range(0, self._Sxx.shape[1]))) result = vec2rowarr(np.array(result)) # result = add_name( # result, self.dominant_frequency.__name__ + '_' + str(n)) result = add_name( result, ['X_DOMFREQ','Y_DOMFREQ','Z_DOMFREQ']) return result else: raise ValueError('Please run spectrogram and peaks methods first') # def dominant_frequency_x(self, n=1): # if hasattr(self, '_freq_peaks'): # result = list( # map( # lambda i: self._freq_peaks[i][n - # 1] if # len(self._freq_peaks[i]) >= n else -1, # range(0, self._Sxx.shape[1]))) # result = vec2rowarr(np.array(result[0)) # result = add_name( # result, self.X_DOMFREQ.__name__) # return result # else: # raise ValueError('Please run spectrogram and peaks methods first') def dominant_frequency_power(self, n=1): if hasattr(self, '_Sxx_peaks'): result = list( map( lambda i: self._Sxx_peaks[i][n - 1] if len(self._Sxx_peaks[i]) >= n else -1, range(0, self._Sxx.shape[1]))) result = vec2rowarr(np.array(result)) result = add_name( result, ['X_DOMFREQ_POWER','Y_DOMFREQ_POWER','Z_DOMFREQ_POWER']) return result else: raise ValueError('Please run spectrogram and peaks methods first') # def dominant_frequency_power_x(self, n=1): # if hasattr(self, '_Sxx_peaks'): # result = list( # map( # lambda i: self._Sxx_peaks[i][n - # 1] if # len(self._Sxx_peaks[i]) >= n else -1, # range(0, self._Sxx.shape[1]))) # result = vec2rowarr(np.array(result[0)) # result = add_name( # result, self.X_DOMFREQ_POWER.__name__) # return result # else: # raise ValueError('Please run spectrogram and peaks methods first') def total_power(self): if hasattr(self, '_Sxx'): result = vec2rowarr(np.sum(self._Sxx, axis=0)) result = add_name(result, ['X_TOTPOW','Y_TOTPOW','Z_TOTPOW']) return result else: raise ValueError('Please run spectrogram first') # def total_power_X(self): # if hasattr(self, '_Sxx'): # result = vec2rowarr(np.sum(self._Sxx, axis=0)) # result = add_name(result, self.X_TOTPOW.__name__) # return result # else: # raise ValueError('Please run spectrogram first') def limited_band_dominant_frequency(self, low=0, high=np.inf, n=1): def _limited_band_df(i): freq = self._freq_peaks[i] indices = (freq >= low) & (freq <= high) limited_freq = freq[indices] if len(limited_freq) < n: return -1 else: return limited_freq[n-1] if not hasattr(self, '_freq_peaks'): raise ValueError('Please run spectrogram and peaks methods first') result = list( map(_limited_band_df, range(0, self._Sxx.shape[1]))) result = vec2rowarr(np.array(result)) result = add_name( result, self.limited_band_dominant_frequency.__name__ + '_' + str(n)) return result def limited_band_dominant_frequency_power(self, low=0, high=np.inf, n=1): def _limited_band_df_power(i): freq = self._freq_peaks[i] Sxx = self._Sxx_peaks[i] indices = (freq >= low) & (freq <= high) limited_Sxx = Sxx[indices] if len(limited_Sxx) < n: return -1 else: return limited_Sxx[n-1] if not hasattr(self, '_freq_peaks'): raise ValueError('Please run spectrogram and peaks methods first') result = list( map(_limited_band_df_power, range(0, self._Sxx.shape[1]))) result = vec2rowarr(np.array(result)) result = add_name( result, self.limited_band_dominant_frequency_power.__name__ + '_' + str(n)) return result def limited_band_total_power(self, low=0, high=np.inf): if not hasattr(self, '_freq'): raise ValueError('Please run spectrogram first') indices = (self._freq >= low) & (self._freq <= high) limited_Sxx = self._Sxx[indices, :] limited_total_power = vec2rowarr(np.sum(limited_Sxx, axis=0)) # limited_total_power = add_name( # limited_total_power, self.limited_band_total_power.__name__) limited_total_power = add_name( limited_total_power, ['X_total_power_between_'+str(low)+'_'+str(high),'Y_total_power_between_'+str(low)+'_'+str(high),'Z_total_power_between_'+str(low)+'_'+str(high)]) return limited_total_power def highend_power(self): if hasattr(self, '_Sxx'): result = self.limited_band_total_power(low=3.5) result = add_name( result.values, self.highend_power.__name__) return result else: raise ValueError('Please run spectrogram first') def dominant_frequency_power_ratio(self, n=1): power = self.total_power().values result = np.divide(self.dominant_frequency_power(n=n).values, power, out=np.zeros_like(power), where=power != 0) result = add_name( result, self.dominant_frequency_power_ratio.__name__ + '_' + str(n)) return result def middlerange_dominant_frequency(self): result = self.limited_band_dominant_frequency(low=0.6, high=2.6, n=1) result = add_name( result.values, self.middlerange_dominant_frequency.__name__) return result def middlerange_dominant_frequency_power(self): result = self.limited_band_dominant_frequency_power(low=0.6, high=2.6, n=1) result = add_name( result.values, self.middlerange_dominant_frequency_power.__name__) return result def peaks(self): def _sort_peaks(i, j): if len(i) == 0: sorted_freq_peaks = np.array([0]) sorted_Sxx_peaks = np.array([np.nanmean(self._Sxx, axis=0)[j]]) else: freq_peaks = self._freq[i] Sxx_peaks = self._Sxx[i, j] sorted_i = np.argsort(Sxx_peaks) sorted_i = sorted_i[::-1] sorted_freq_peaks = freq_peaks[sorted_i] sorted_Sxx_peaks = Sxx_peaks[sorted_i] return (sorted_freq_peaks, sorted_Sxx_peaks) n_axis = self._Sxx.shape[1] m_freq = self._Sxx.shape[0] # at least 0.1 Hz different when looking for peak mpd = int(np.ceil(1.0 / (self._freq[1] - self._freq[0]) * 0.1)) # print(self._Sxx.shape) # i = list(map(lambda x: detect_peaks.detect_peaks( # x, mph=1e-3, mpd=mpd), list(self._Sxx.T))) # i = list(map(lambda x: detect_peaks.detect_peaks( x, mph=None, mpd=mpd), list(self._Sxx.T))) j = range(0, n_axis) result = list(map(_sort_peaks, i, j)) self._freq_peaks = list(map(lambda x: x[0], result)) self._Sxx_peaks = list(map(lambda x: x[1], result)) return self
97e8a4a094c40e8590d73a073272fccf43b4afee
7dbe0daf56af3752498c0b70ebbad2e2fc9b11e4
/targetshare/models/relational/page.py
8a7dda7f5c7cef6f4ef8907556ed49599f99af42
[]
no_license
edgeflip/edgeflip
db737518ff9a6f377f3dfab16f27572a5e68c1aa
bebd10d910c87dabc0680692684a3e551e92dd2a
refs/heads/master
2020-04-09T16:41:15.815531
2015-05-17T22:14:42
2015-05-17T22:14:42
7,248,450
1
0
null
null
null
null
UTF-8
Python
false
false
2,624
py
import re from django.db import models from . import manager from .base import BaseModel class Page(BaseModel): BUTTON = 'button' FRAME_FACES = 'frame_faces' page_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) code = models.SlugField(max_length=100, unique=True) objects = manager.TypeObjectManager() class Meta(BaseModel.Meta): db_table = 'pages' def __unicode__(self): return u'{}'.format(self.name) class PageStyle(BaseModel): HTTP_PROTOCOLS = re.compile(r'^https?:') page_style_id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) description = models.TextField(blank=True) page = models.ForeignKey('Page', related_name='pagestyles') client = models.ForeignKey('Client', null=True, related_name='pagestyles') starred = models.BooleanField(default=False) # offer to user to link to new campaign # (rather than globals and/or inheritance) visible = models.BooleanField(default=True) url = models.URLField(max_length=255) class Meta(BaseModel.Meta): db_table = 'page_styles' unique_together = ('name', 'client') def __unicode__(self): name = self.name and u' ({})'.format(self.name) return u'{}{}'.format(self.page, name) @property def href(self): return self.HTTP_PROTOCOLS.sub('', self.url) class PageStyleSet(BaseModel): page_style_set_id = models.AutoField(primary_key=True) page_styles = models.ManyToManyField('PageStyle', related_name='pagestylesets') class Meta(BaseModel.Meta): db_table = 'page_style_sets' def __unicode__(self): text = u'' for page_style in self.page_styles.all(): if text: text += u', ' if len(text) > 100: text += u'...' break text += unicode(page_style) return u'[{}]'.format(text) class CampaignPageStyleSet(BaseModel): campaign_page_style_set_id = models.AutoField(primary_key=True) campaign = models.ForeignKey('Campaign', related_name='campaignpagestylesets') page_style_set = models.OneToOneField('PageStyleSet') rand_cdf = models.DecimalField(decimal_places=9, max_digits=10) objects = manager.AssignedObjectManager.make(page_style_set) class Meta(BaseModel.Meta): db_table = 'campaign_page_style_sets' def __unicode__(self): return u'{} ({}) | {}'.format(self.campaign, self.rand_cdf, self.page_style_set)
23e8a0114e34cc1bdcb937b52ccb467eef4c8479
44e27275fd9837d4b31aea4625261b0c225f7357
/co1.8.changed$.py
4df3715cbfa7e2ed930d061b3164895c7965afd0
[]
no_license
Python-lab-cycle/ANJALY-NARAYANAN
2a303545cd0d5fdabb2d4a598699aa5ba99b2b5d
c132eb123777c24db4b47b8cb70fd8280262b483
refs/heads/main
2023-06-07T23:27:23.642412
2021-07-02T07:01:39
2021-07-02T07:01:39
325,924,545
0
0
null
null
null
null
UTF-8
Python
false
false
167
py
str1=input("Enter a string:") print("Original String:",str1) char = str1[0] str1 = str1.replace(char, '$') str1 = char + str1[1:] print("Replaced String:",str1)
1985122d2f03ebf32d30f4ea38c98b7dc1d7265a
ae56254e3e0ffa1defcea3218d20f00fa3eb147d
/suiltes/suiltes/urls.py
a92ef7ed0647059da7f756e89d16bb12f577feea
[]
no_license
PetrovKP/test-suites
2c30aa5fdeb27550b051d5f152f9d70cb8e330df
66fa31fd302544bd978fe7a74bb386779302eede
refs/heads/master
2020-07-22T07:42:05.881478
2016-12-11T18:45:08
2016-12-11T18:45:08
73,831,871
0
1
null
2016-12-11T18:45:09
2016-11-15T16:18:18
Python
UTF-8
Python
false
false
990
py
"""suiltes URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url from app import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^run/$', views.list_run, name = 'list_run'), url(r'^add/$', views.add_test, name = 'add_test'), url(r'^delete/$', views.delete_test, name = 'delete_test'), ]
722078c58e3d89f13fdb5f6dd13bc9f0801aa3fb
3846886c0b0624f3a9896d7a0ed34960db1237bf
/wiki-headings.py
a4b8f1330892202e39163dae5f0802eee0930ddf
[]
no_license
raghavo9/web-scraping
d475d6e7b2b1bb6a47d3089444f99c204dc83eb8
12cc861bac8e1fd4f37c549e5c7be105800319ee
refs/heads/master
2020-05-30T08:12:32.225758
2019-05-31T19:18:37
2019-05-31T19:18:37
189,615,702
1
0
null
null
null
null
UTF-8
Python
false
false
363
py
from bs4 import BeautifulSoup import requests source=requests.get("https://en.wikipedia.org/wiki/Machine_learning").text soup=BeautifulSoup(source,'lxml') for headline in soup.find_all(class_="mw-headline"): print(headline.text) print(" ") print(" ") #for printing all the headings of table of content(if any) var=soup.find(class_="toc").text print(var)
65768ea1c36c359f61a25272cbe6f5981242289b
1b8f10ea8777aabed5cbd1a7f0602ed5b7416887
/Perguntas.py
89dc9cb5328efd427e200e6c46982205ff8c9e4f
[]
no_license
rafinhadufluxo/SistemaEspecialista
cc34655111ed905962cc76de7390fbfdd90e4544
5561c45a1d4fbfda3d332977f1a35a5502181db6
refs/heads/master
2023-08-18T02:38:07.239266
2021-10-12T21:48:05
2021-10-12T21:48:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
690
py
from random import * class Pergunta: def __init__(self): self.level = [ ['Voce esta vendo o imovel?', 'imovel'], ['Imovel localiza em zona urbana?','zonaurbana'], #['Imovel localiza em zona rural?','zonarural'], ['O Acabamento do imovel é de alvenaria?','alvenaria'], #['O Acabamento do imovel é de Madeira?','madeira'], ['Imovel se encontra na posicao de esquina?','esquina'], #['Imovel se encontra na posicao dentro da quadra?','quadra'], #['Documentacao do imovel está em dias?','documentsimovel'], ['Está quitado o imovel?','quitadoImovel'], ] def texto(self): string = self.level[0] del self.level[0] return string
50a4d1f9697a36b6937023bdf5a5c81950909ed6
84f1f0ebb3ddbd4fde8e4e4e8fa3d47968986254
/trainer/train_doc_ml.py
3652d826b86718a511de34e46553dd7eade808bc
[ "MIT" ]
permissive
dainis-boumber/AA_CNN
e8d6f91c38ad40794bf0d95208e85f374525625a
649612215c7e290ede1c51625268ad9fd7b46228
refs/heads/master
2021-01-01T16:45:31.027942
2018-02-04T16:39:54
2018-02-04T16:39:54
97,909,140
3
4
null
2018-02-04T16:39:55
2017-07-21T05:26:05
Python
UTF-8
Python
false
false
10,578
py
#! /usr/bin/env python import datetime import os import time import tensorflow as tf from datahelpers import data_helper_ml_mulmol6_OnTheFly as dh from evaluators import eval_pan_archy as evaler from networks.cnn_ml_archy import TextCNN def init_data(embed_dimension, do_dev_split=False): dater = dh.DataHelperMLFly(doc_level=True, embed_dim=embed_dimension, target_sent_len=40, target_doc_len=200) # Model Hyperparameters tf.flags.DEFINE_integer("num_classes", dater.num_of_classes, "Number of possible labels") tf.flags.DEFINE_integer("embedding_dim", dater.embedding_dim, "Dimensionality of character embedding") tf.flags.DEFINE_string("filter_sizes", "3", "Comma-separated filter sizes (default: '3,4,5')") # tf.flags.DEFINE_integer("num_filters", 100, "Number of filters per filter size (default: 128)") # tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") # tf.flags.DEFINE_float("l2_reg_lambda", 0.6, "L2 regularizaion lambda (default: 0.0)") # Training parameters tf.flags.DEFINE_integer("batch_size", 4, "Batch Size (default: 64)") tf.flags.DEFINE_integer("num_epochs", 200, "Number of training epochs (default: 200)") tf.flags.DEFINE_integer("evaluate_every", 200, "Evaluate model on dev set after this many steps (default: 100)") tf.flags.DEFINE_integer("checkpoint_every", 250, "Save model after this many steps (default: 100)") # Misc Parameters tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") FLAGS = tf.flags.FLAGS FLAGS._parse_flags() print("\nParameters:") for attr, value in sorted(FLAGS.__flags.items()): print(("{}={}".format(attr.upper(), value))) print("") # Load data print("Loading data...") x_shuffled, y_shuffled, vocabulary, vocabulary_inv, embed_matrix = dater.load_data() print(("Vocabulary Size: {:d}".format(len(vocabulary)))) # Split train/test set # TODO: This is very crude, should use cross-validation if do_dev_split: x_train, x_dev = x_shuffled[:-500], x_shuffled[-500:] y_train, y_dev = y_shuffled[:-500], y_shuffled[-500:] print(("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev)))) else: x_train = x_shuffled x_dev = None y_train = y_shuffled y_dev = None print("No Train/Dev split") return dater, FLAGS, x_train, x_dev, y_train, y_dev, vocabulary, embed_matrix # Training def training(DO_DEV_SPLIT, FLAGS, scheme_name, vocabulary, embed_matrix, x_train, x_dev, y_train, y_dev, num_filters, dropout_prob, l2_lambda, test_x, test_y): with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): cnn = TextCNN( doc_sent_len=x_train.shape[1], sent_len=x_train.shape[2], num_classes=FLAGS.num_classes, # Number of classification classes vocab_size=len(vocabulary), embedding_size=FLAGS.embedding_dim, filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), num_filters=num_filters, l2_reg_lambda=l2_lambda, init_embedding=embed_matrix) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(cnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) with tf.name_scope('grad_summary'): grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.histogram_summary("{}/grad/hist".format(v.name), g) sparsity_summary = tf.scalar_summary("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.merge_summary(grad_summaries) # Output directory for models and summaries timestamp = str(int(time.time())) out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", scheme_name, timestamp)) print(("Writing to {}\n".format(out_dir))) # Summaries for loss and accuracy loss_summary = tf.scalar_summary("loss", cnn.loss) pred_ratio_summary = [] for i in range(FLAGS.num_classes): pred_ratio_summary.append( tf.scalar_summary("prediction/label_" + str(i) + "_percentage", cnn.rate_percentage[i])) acc_summary = tf.scalar_summary("accuracy", cnn.accuracy) # Train Summaries with tf.name_scope('train_summary'): train_summary_op = tf.merge_summary( [loss_summary, acc_summary, pred_ratio_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, "summaries", "train") train_summary_writer = tf.train.SummaryWriter(train_summary_dir, sess.graph_def) # Dev summaries with tf.name_scope('dev_summary'): dev_summary_op = tf.merge_summary([loss_summary, acc_summary, pred_ratio_summary]) dev_summary_dir = os.path.join(out_dir, "summaries", "dev") dev_summary_writer = tf.train.SummaryWriter(dev_summary_dir, sess.graph_def) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=7) # Initialize all variables sess.run(tf.global_variables_initializer()) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { cnn.input_x: x_batch, cnn.input_y: y_batch, cnn.dropout_keep_prob: dropout_prob } _, step, summaries, loss, accuracy = sess.run( [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print(("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))) train_summary_writer.add_summary(summaries, step) def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = { cnn.input_x: x_batch, cnn.input_y: y_batch, cnn.dropout_keep_prob: 1 } step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, cnn.loss, cnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print(("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy))) if writer: writer.add_summary(summaries, step) # Generate batches batches = dh.DataHelperMLFly.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) if test_x is not None and test_y is not None: test_x_1 = test_x[:100] test_y_1 = test_y[:100] test_x_2 = test_x[100:200] test_y_2 = test_y[100:200] # Training loop. For each batch... for batch in batches: if len(batch) == 0: continue x_batch, y_batch = list(zip(*batch)) train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if DO_DEV_SPLIT and current_step % FLAGS.evaluate_every == 0: print("\nEvaluation:") dev_batches = dh.DataHelperMLFly.batch_iter(list(zip(x_dev, y_dev)), 100, 1) for dev_batch in dev_batches: if len(dev_batch) > 0: small_dev_x, small_dev_y = list(zip(*dev_batch)) dev_step(small_dev_x, small_dev_y, writer=dev_summary_writer) print("") elif test_x is not None and test_y is not None and current_step % 200 == 0: dev_step(test_x_1, test_y_1, writer=dev_summary_writer) dev_step(test_x_2, test_y_2, writer=dev_summary_writer) if current_step % FLAGS.checkpoint_every == 0: path = saver.save(sess, checkpoint_prefix, global_step=current_step) print(("Saved model checkpoint to {}\n".format(path))) # if current_step >= 3000: # break return timestamp DO_DEV_SPLIT = False bold_step = [2500, 3000, 3500, 4000, 4500] bold_step2 = [2000, 2250, 2500, 2750, 3000, 3250, 3500] embed_dim = 100 output_file = open("ml_100d_doc.txt", mode="aw") dir_name = "ml_100d_doc" [dater, FLAGS, x_train, x_dev, y_train, y_dev, vocabulary, embed_matrix] =\ init_data(embed_dim, DO_DEV_SPLIT) ev = evaler.evaler() test_x, test_y, test_y_scalar = ev.load(dater) for f_size in [50]: for l2 in [0.1]: for drop in [0.50]: output_file.write("===== Filter Size: "+str(f_size)+"\n") output_file.write("===== L2 Norm: "+str(l2)+"\n") output_file.write("===== Drop Out: "+str(drop)+"\n\n\n") ts = training(DO_DEV_SPLIT, FLAGS, dir_name, vocabulary, embed_matrix, x_train, x_dev, y_train, y_dev, f_size, drop, l2, test_x, test_y) for train_step in [3000]: checkpoint_dir = "./runs/" + dir_name + "/" + str(ts) + "/checkpoints/" ev.test(checkpoint_dir, train_step, output_file, documentAcc=True) output_file.close()
5f215490282ef20472448871704b77041753cf0e
1654571422ae946ee7484d808a419aea8e4cb2eb
/glava5_instruction_if/amusement_park.py
8c54596e0b632c0b5c92983251af523be7b641bc
[]
no_license
Bearspirit/all_lessons
5788e5be06c336feea9e3ce93188e479a6396a56
9e353e6688b1f30950ca1d6078303466ad0113b8
refs/heads/main
2023-03-10T22:56:19.399213
2021-02-25T20:55:36
2021-02-25T20:55:36
338,640,762
0
0
null
null
null
null
UTF-8
Python
false
false
163
py
age = 65 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5 print("Yoe pay $" + str(price) + "!")
caf9182bbb350d8628a04aa4b66077a960ce3218
a1cbe5abe746fce5056b60cc81a1a0c2d760bdf6
/easyAccounts/inventory/migrations/0015_auto__del_field_batchitem_quantity_in_purchase_unit__del_field_batchit.py
e10dfeac0705bfb8f27a84d00a9a6752dd1af5ee
[]
no_license
sremya218/easyAccounts
23cc3425e623fb6e8bf9e32ad10426dfdc65fc59
53e09525bcf3d8fe5e0f625aadb1b0d52252154a
refs/heads/master
2016-09-05T16:46:15.818606
2014-12-25T10:39:41
2014-12-25T10:39:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,373
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'BatchItem.quantity_in_purchase_unit' db.delete_column(u'inventory_batchitem', 'quantity_in_purchase_unit') # Deleting field 'BatchItem.quantity_in_smallest_unit' db.delete_column(u'inventory_batchitem', 'quantity_in_smallest_unit') def backwards(self, orm): # Adding field 'BatchItem.quantity_in_purchase_unit' db.add_column(u'inventory_batchitem', 'quantity_in_purchase_unit', self.gf('django.db.models.fields.FloatField')(default=0, max_length=100), keep_default=False) # Adding field 'BatchItem.quantity_in_smallest_unit' db.add_column(u'inventory_batchitem', 'quantity_in_smallest_unit', self.gf('django.db.models.fields.FloatField')(default=0, max_length=100), keep_default=False) models = { u'administration.bonuspoint': { 'Meta': {'object_name': 'BonusPoint'}, 'bonus_amount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'bonus_point': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'bonus_type': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'inventory.batch': { 'Meta': {'object_name': 'Batch'}, 'created_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'expiry_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'inventory.batchitem': { 'Meta': {'object_name': 'BatchItem'}, 'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.Batch']", 'null': 'True', 'blank': 'True'}), 'branch_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'cost_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '5'}), 'customer_bonus_points': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'Customer Bonus'", 'null': 'True', 'to': u"orm['administration.BonusPoint']"}), 'customer_bonus_quantity': ('django.db.models.fields.FloatField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'customer_card_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'freight_charge': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'item': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.Item']", 'null': 'True', 'blank': 'True'}), 'permissible_discount_percentage': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'purchase_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '5'}), 'quantity_in_actual_unit': ('django.db.models.fields.FloatField', [], {'default': '0', 'max_length': '100'}), 'retail_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'retail_profit_percentage': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'salesman_bonus_points': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'Salesman Bonus'", 'null': 'True', 'to': u"orm['administration.BonusPoint']"}), 'salesman_bonus_quantity': ('django.db.models.fields.FloatField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'small_branch_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '25'}), 'small_customer_card_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '25'}), 'small_retail_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '25'}), 'small_wholesale_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '25'}), 'uom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'whole_sale_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'whole_sale_profit_percentage': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}) }, u'inventory.brand': { 'Meta': {'object_name': 'Brand'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, u'inventory.category': { 'Meta': {'object_name': 'Category'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.Category']", 'null': 'True', 'blank': 'True'}) }, u'inventory.item': { 'Meta': {'object_name': 'Item'}, 'actual_smallest_uom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'barcode': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.Brand']", 'null': 'True', 'blank': 'True'}), 'cess': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '14', 'decimal_places': '2'}), 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'item_type': ('django.db.models.fields.CharField', [], {'default': "'Stockable'", 'max_length': '50'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'offer_quantity': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '50', 'decimal_places': '5'}), 'packets_per_box': ('django.db.models.fields.DecimalField', [], {'max_length': '200', 'null': 'True', 'max_digits': '50', 'decimal_places': '5', 'blank': 'True'}), 'pieces_per_box': ('django.db.models.fields.DecimalField', [], {'max_length': '200', 'null': 'True', 'max_digits': '50', 'decimal_places': '5', 'blank': 'True'}), 'pieces_per_packet': ('django.db.models.fields.DecimalField', [], {'max_length': '200', 'null': 'True', 'max_digits': '50', 'decimal_places': '5', 'blank': 'True'}), 'product': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.Product']", 'null': 'True', 'blank': 'True'}), 'size': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'smallest_unit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'unit_per_box': ('django.db.models.fields.DecimalField', [], {'max_length': '200', 'null': 'True', 'max_digits': '50', 'decimal_places': '5', 'blank': 'True'}), 'unit_per_packet': ('django.db.models.fields.DecimalField', [], {'max_length': '200', 'null': 'True', 'max_digits': '50', 'decimal_places': '5', 'blank': 'True'}), 'unit_per_piece': ('django.db.models.fields.DecimalField', [], {'max_length': '200', 'null': 'True', 'max_digits': '50', 'decimal_places': '5', 'blank': 'True'}), 'uom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'uoms': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 'vat_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.VatType']", 'null': 'True', 'blank': 'True'}) }, u'inventory.openingstock': { 'Meta': {'object_name': 'OpeningStock'}, 'date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'transaction_reference_no': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'inventory.openingstockitem': { 'Meta': {'object_name': 'OpeningStockItem'}, 'batch_item': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.BatchItem']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'net_amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'opening_stock': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.OpeningStock']", 'null': 'True', 'blank': 'True'}), 'purchase_price': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'quantity': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '20', 'decimal_places': '5'}), 'uom': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'inventory.openingstockvalue': { 'Meta': {'object_name': 'OpeningStockValue'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'stock_by_value': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '20', 'decimal_places': '5', 'blank': 'True'}) }, u'inventory.product': { 'Meta': {'object_name': 'Product'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['inventory.Category']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'inventory.stockvalue': { 'Meta': {'object_name': 'StockValue'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'stock_by_value': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '20', 'decimal_places': '5', 'blank': 'True'}) }, u'inventory.vattype': { 'Meta': {'object_name': 'VatType'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tax_percentage': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '14', 'decimal_places': '2'}), 'vat_type': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['inventory']
[ "remya@remya.(none)" ]
remya@remya.(none)
0944a41bf5447f963eb5c12fba85e4a91c4266ea
55b8c2ca8b6ac3639ad0dfa2f08bdbefbafff1a1
/app/tests.py
ad634da86ef05b9b6d0329778d4cf911f5560898
[]
no_license
nguyendan07/tweet
3744056770ae23b82c8e601f9d3bb663a84983f2
5d0833217e71b376dfc16376604cf36b7d783e79
refs/heads/master
2020-03-19T01:07:10.774594
2018-06-01T08:49:37
2018-06-01T08:49:37
135,524,148
0
0
null
null
null
null
UTF-8
Python
false
false
1,007
py
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from .models import Tweet User = get_user_model() class TweetModelTestCase(TestCase): def setUp(self): some_random_user = User.objects.create(username='nguyendan') def test_tweet_item(self): obj = Tweet.objects.create( user=User.objects.first(), content='Some random content' ) self.assertTrue(obj.content == 'Some random content') self.assertTrue(obj.id == 1) # self.assertEqual(obj.id, 1) absolute_url = reverse('tweet:detail', kwargs={'pk': 1}) self.assertEqual(obj.get_absolute_url(), absolute_url) def test_tweet_url(self): obj = Tweet.objects.create( user=User.objects.first(), content='Some random content' ) absolute_url = reverse('tweet:detail', kwargs={'pk': obj.pk}) self.assertEqual(obj.get_absolute_url(), absolute_url)
651fd93da68cda4eb717b779f14f60c44ece9f38
afd9f8c555a7476ff4efc332a1b62b42ebcb8ec7
/ssh-test.py
57c0523a84342d703a7e5a8aece5775492857626
[]
no_license
letsautomateit85/SSH2-Python-Example
4cc4d236ec795900e6c0150b18a43d51042d62ae
169b2f7e115c8abb56485cb679e98fced5623208
refs/heads/master
2020-04-29T06:41:32.269504
2019-03-16T04:37:40
2019-03-16T04:37:40
175,925,493
0
0
null
null
null
null
UTF-8
Python
false
false
587
py
#Let's Automate It - SSH2-Python - Remotely connecting to a Cisco Device import socket from ssh2.session import Session host = '192.168.1.150' user = 'cisco' password = 'cisco' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host,22)) session = Session() session.handshake(sock) session.userauth_password(user, password) channel = session.open_session() channel.execute('show run') size, data = channel.read() while size > 0: print(data.decode()) size, data = channel.read() channel.close() print("Exit status: {0}".format(channel.get_exit_status()))
81c5006c74c3b76aab4f09c56de6f8fc3b050f4c
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_196/ch86_2020_04_29_12_33_12_116182.py
eec9ae5bf086c8595825cb9d7c6b0310d25f2791
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
184
py
with open("dados.csv","r") as arquivo: conteudo = arquivo.read() conteudo.replace(",","\t") with open("dados.tsv","w") as novoarquivo: novoarquivo.write("conteudo")
0472916e25407a2cee79867cebd9bd53f0d6b73f
a53d33aec96bd35596c188544cdcbe08834ffb7c
/rosalind/src/CORR.py
0dd42faeb0a44c882fa038996231361090058a9a
[]
no_license
CarlRaymond/Bioinformatics
1519ab51dae4b3a4e7adde38244565269c0c6e99
7e541a7bf7866c1edc5e48d358d85c84c1efbb49
refs/heads/master
2021-07-12T17:23:33.039745
2020-08-21T15:59:51
2020-08-21T15:59:51
6,976,873
0
1
null
null
null
null
UTF-8
Python
false
false
2,141
py
''' Created on Dec 23, 2012 @author: Carl Raymond ''' from REVC import revc from fasta import read # Returns true when the Hamming distance between seq1 and seq2 # is exactly n. Faster than computing the distance first when # we're only interested in small distances. def isDistance(seq1, seq2, n): dist = 0 for (c1, c2) in zip(seq1, seq2): if c1 != c2: dist += 1 if (dist > n): return False return dist == n with open("rosalind_corr.txt") as spec: rawdata = [seq.strip() for name,seq in read(spec)] # Build a dictionary with reads as keys and counts as the value. reads = {} for seq in rawdata: if seq in reads: reads[seq] += 1 else: reads[seq] = 1 print "Original data: {0} sequences.".format(len(rawdata)) print "Distinct reads: {0} sequences.".format(len(reads)) readsum = sum(v for k,v in reads.iteritems()) print "Total multiplicity: {0}".format(readsum) # Goodreads are have multiplicity > 1 or are present in revc form goodreads = [seq for seq,mult in reads.iteritems() if mult > 1 or revc(seq) in reads] print "Good reads: {0}".format(len(goodreads)) # Build list of sequences appearing once singletons = [seq for seq,mult in reads.iteritems() if mult == 1] print "Singletons: {0}".format(len(singletons)) #for s in singletons: print s #for k,v in reads.iteritems(): # if v > 1: print k,v # Build list of sequences whose revc was not read badreads = [seq for seq in singletons if revc(seq) not in goodreads] print "Bad reads: {0}".format(len(badreads)) # A bad read must have distance 1 to exactly one good read with open("rosalind_corr.out", "w+") as output: for b in badreads: count = 0 for r in goodreads: if isDistance(b, r, 1): match = r count += 1 elif isDistance(b, revc(r), 1): match = revc(r) count += 1 if count == 1: output.write("{0}->{1}\n".format(b, match))
4577e72ef7a65c36b158f2b463cc40d5efeb557b
296132d2c5d95440b3ce5f4401078a6d0f736f5a
/homeassistant/components/homewizard/__init__.py
a236c392c077e22e5db2db7bd7ca192ba4b60614
[ "Apache-2.0" ]
permissive
mezz64/home-assistant
5349a242fbfa182159e784deec580d2800173a3b
997d4fbe5308b01d14ceabcfe089c2bc511473dd
refs/heads/dev
2023-03-16T22:31:52.499528
2022-12-08T02:55:25
2022-12-08T02:55:25
68,411,158
2
1
Apache-2.0
2023-03-10T06:56:54
2016-09-16T20:04:27
Python
UTF-8
Python
false
false
3,895
py
"""The Homewizard integration.""" import logging from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import CONF_IP_ADDRESS from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import device_registry as dr, entity_registry as er from .const import DOMAIN, PLATFORMS from .coordinator import HWEnergyDeviceUpdateCoordinator as Coordinator _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Homewizard from a config entry.""" _LOGGER.debug("__init__ async_setup_entry") # Migrate `homewizard_energy` (custom_component) to `homewizard` if entry.source == SOURCE_IMPORT and "old_config_entry_id" in entry.data: # Remove the old config entry ID from the entry data so we don't try this again # on the next setup data = entry.data.copy() old_config_entry_id = data.pop("old_config_entry_id") hass.config_entries.async_update_entry(entry, data=data) _LOGGER.debug( ( "Setting up imported homewizard_energy entry %s for the first time as " "homewizard entry %s" ), old_config_entry_id, entry.entry_id, ) ent_reg = er.async_get(hass) for entity in er.async_entries_for_config_entry(ent_reg, old_config_entry_id): _LOGGER.debug("Removing %s", entity.entity_id) ent_reg.async_remove(entity.entity_id) _LOGGER.debug("Re-creating %s for the new config entry", entity.entity_id) # We will precreate the entity so that any customizations can be preserved new_entity = ent_reg.async_get_or_create( entity.domain, DOMAIN, entity.unique_id, suggested_object_id=entity.entity_id.split(".")[1], disabled_by=entity.disabled_by, config_entry=entry, original_name=entity.original_name, original_icon=entity.original_icon, ) _LOGGER.debug("Re-created %s", new_entity.entity_id) # If there are customizations on the old entity, apply them to the new one if entity.name or entity.icon: ent_reg.async_update_entity( new_entity.entity_id, name=entity.name, icon=entity.icon ) # Remove the old config entry and now the entry is fully migrated hass.async_create_task(hass.config_entries.async_remove(old_config_entry_id)) # Create coordinator coordinator = Coordinator(hass, entry.data[CONF_IP_ADDRESS]) try: await coordinator.async_config_entry_first_refresh() except ConfigEntryNotReady: await coordinator.api.close() raise # Register device device_registry = dr.async_get(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, name=entry.title, manufacturer="HomeWizard", sw_version=coordinator.data["device"].firmware_version, model=coordinator.data["device"].product_type, identifiers={(DOMAIN, coordinator.data["device"].serial)}, ) # Finalize hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" _LOGGER.debug("__init__ async_unload_entry") unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: config_data = hass.data[DOMAIN].pop(entry.entry_id) await config_data.api.close() return unload_ok
18c2ecea628615309f6bb36a49d4e58f8e232306
d792f446f56e5fd5f5980d82ebe9ac64fafac6a8
/src/export/FilenameCreater.py
cccbc21c0d8d0035e42e16cd716ca3a986ec9b98
[ "CC0-1.0", "MIT" ]
permissive
ytyaru/NovelWriter400.201706161317
e997664923ecfd4b7fc1be75d193e9ab27592253
40fb268f159256c38f66e7d8efc0092e0acb3f03
refs/heads/master
2021-01-21T12:12:10.176040
2017-08-31T22:35:19
2017-08-31T22:35:19
102,051,047
0
0
null
null
null
null
UTF-8
Python
false
false
2,772
py
import datetime import re class FilenameCreater: def __init__(self, format=None): self.__re_created = re.compile(r'{created}', re.IGNORECASE) self.__re_title = re.compile(r'{title}', re.IGNORECASE) self.__re_title_pre = re.compile(r'{title:[-+]?\d+}', re.IGNORECASE) self.__re_content_pre = re.compile(r'{content:[-+]?\d+}', re.IGNORECASE) self.__format = format def Create(self, record, format=None): d = datetime.datetime.strptime(record['Created'], '%Y-%m-%d %H:%M:%S') dtstr = '{0:%Y%m%d%H%M%S}'.format(d) if None is self.__format and None is format: return dtstr + '.txt' if None is format: format = self.__format file_name = format file_name = re.sub(self.__re_created, dtstr, file_name) file_name = re.sub(self.__re_title, record['Title'], file_name) file_name = self.__LengthStr(self.__re_title_pre, file_name, record['Title']) file_name = self.__LengthStr(self.__re_content_pre, file_name, record['Content']) return file_name def __LengthStr(self, find_reg, file_name, record_value): for match in re.findall(find_reg, file_name): str_len = int(match.split(':')[1][:-1]) if len(record_value) < str_len: str_len = len(record_value) file_name = file_name.replace(match, record_value[:str_len]) return file_name """ if __name__ == '__main__': c = FilenameCreater() file_name = c.Create({'Title': 'タイトル', 'Content': '本文ですよ。', 'Created': '2017-01-02 12:34:56'}, format='{created}_{title:10}_{content:20}.txt') print(file_name) file_name = c.Create({'Title': 'とってもかなり超長いタイトル', 'Content': 'それなりにだいぶわりと長い少なくとも20文字以上はある本文ですよ。', 'Created': '2017-01-02 12:34:56'}, format='{created}_{title:10}_{content:20}.txt') print(file_name) file_name = c.Create({'Title': 'とってもかなり超長いタイトル', 'Content': 'それなりにだいぶわりと長い少なくとも20文字以上はある本文ですよ。', 'Created': '2017-01-02 12:34:56'}, format='{created}_{title}_{content:20}.txt') print(file_name) file_name = c.Create({'Title': 'とってもかなり超長いタイトル', 'Content': 'それなりにだいぶわりと長い少なくとも20文字以上はある本文ですよ。', 'Created': '2017-01-02 12:34:56'}, format='{title}.txt') print(file_name) file_name = c.Create({'Title': 'とってもかなり超長いタイトル', 'Content': 'それなりにだいぶわりと長い少なくとも20文字以上はある本文ですよ。', 'Created': '2017-01-02 12:34:56'}) print(file_name) """
e53c1b58b2ef9175f05068112a3ef2f189ad078f
abed4ba6ae0fa91f8c379a0b2406f60094c2e843
/files/root/testpack_helper_library_module/testpack_helper_library/unittests/dockertests.py
760c29a159d4dc4cbdf76cd773afe0fec8eaf853
[]
no_license
isabella232/testpack-framework
ede9f34272d812a357d2c765e09168182ed733f7
c8f3b301cd04a8908a94afa60d913bedf23efa99
refs/heads/master
2023-01-29T22:39:09.987126
2020-12-08T16:16:25
2020-12-08T16:16:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
435
py
from testpack_helper_library.unittests.docker_image_test import DockerTest1and1Common from testpack_helper_library.unittests.kube_image_test import KubeTest1and1Common import os test_platform = os.getenv("TEST_PLATFORM", "docker") if test_platform == "docker": print("Using DockerTest1and1Common") Test1and1Common = DockerTest1and1Common else: print("Using KubeTest1and1Common") Test1and1Common = KubeTest1and1Common
e116b9127efb9e232e8cfd369864ce75a444d255
20a0bd0a9675f52d4cbd100ee52f0f639fb552ef
/transit_odp/data_quality/pti/tests/test_functions.py
bc0dadb8dac1824b5d1ba4aeb8300b5cbfd08d1f
[]
no_license
yx20och/bods
2f7d70057ee9f21565df106ef28dc2c4687dfdc9
4e147829500a85dd1822e94a375f24e304f67a98
refs/heads/main
2023-08-02T21:23:06.066134
2021-10-06T16:49:43
2021-10-06T16:49:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,590
py
from unittest.mock import Mock import pytest from dateutil import parser from freezegun import freeze_time from lxml import etree from lxml.etree import Element from transit_odp.data_quality.pti.functions import ( cast_to_bool, cast_to_date, contains_date, has_name, has_prohibited_chars, is_member_of, today, ) from transit_odp.data_quality.pti.tests.constants import TXC_END, TXC_START @pytest.mark.parametrize( ("value", "expected"), [ ([Mock(spec=Element, text="true")], True), ([Mock(spec=Element, text="false")], False), (Mock(spec=Element, text="true"), True), (Mock(spec=Element, text="false"), False), (["true"], True), (["false"], False), ("true", True), ("false", False), (Mock(spec=Element), False), ], ) def test_cast_to_bool(value, expected): context = Mock() actual = cast_to_bool(context, value) assert actual == expected @pytest.mark.parametrize( ("value", "expected"), [ ( [Mock(spec=Element, text="2015-01-01")], parser.parse("2015-01-01").timestamp(), ), ( Mock(spec=Element, text="2015-01-01"), parser.parse("2015-01-01").timestamp(), ), ("2015-01-01", parser.parse("2015-01-01").timestamp()), ], ) def test_cast_to_date(value, expected): context = Mock() actual = cast_to_date(context, value) assert actual == expected @pytest.mark.parametrize( ("value", "list_items", "expected"), [ ([Mock(spec=Element, text="other")], ("one", "two"), False), ([Mock(spec=Element, text="one")], ("one", "two"), True), (Mock(spec=Element, text="other"), ("one", "two"), False), (Mock(spec=Element, text="one"), ("one", "two"), True), ("other", ("one", "two"), False), ("one", ("one", "two"), True), ("", ("one", "two"), False), (Mock(spec=Element), ("one", "two"), False), ], ) def test_is_member_of(value, list_items, expected): context = Mock() actual = is_member_of(context, value, *list_items) assert actual == expected @freeze_time("2020-02-02") def test_today(): context = Mock() actual = today(context) assert actual == parser.parse("2020-02-02").timestamp() @pytest.mark.parametrize( ("value", "expected"), [ ([Mock(spec=Element, text="hello,world")], True), ([Mock(spec=Element, text="hello world")], False), (Mock(spec=Element, text="hello,world"), True), (Mock(spec=Element, text="false"), False), (["hello,world"], True), (["false"], False), ("hello,world", True), ("false", False), (Mock(spec=Element), False), ], ) def test_has_prohibited_chars(value, expected): context = Mock() actual = has_prohibited_chars(context, value) assert actual == expected @pytest.mark.parametrize( ("value", "expected"), [ ([Mock(spec=Element, text="world")], False), ([Mock(spec=Element, text="2020-12-01 world")], True), (Mock(spec=Element, text="hello,world"), False), (Mock(spec=Element, text="12-01 world"), True), (["hello,world"], False), (["01/08/21 hello world"], True), ("hello,world", False), ("01/08/21 hello world", True), ("15 hello world", False), (Mock(spec=Element), False), ], ) def test_contains_date(value, expected): context = Mock() actual = contains_date(context, value) assert actual == expected def test_has_name_false(): context = Mock() s = TXC_START + "<Sunday />" + TXC_END doc = etree.fromstring(s.encode("utf-8")) sunday = doc.getchildren() actual = has_name(context, sunday, "Monday", "Tuesday") assert not actual def test_has_name_false_not_list(): context = Mock() s = TXC_START + "<Sunday />" + TXC_END doc = etree.fromstring(s.encode("utf-8")) sunday = doc.getchildren()[0] actual = has_name(context, sunday, "Monday", "Tuesday") assert not actual def test_has_name_true(): context = Mock() s = TXC_START + "<Sunday />" + TXC_END doc = etree.fromstring(s.encode("utf-8")) sunday = doc.getchildren() actual = has_name(context, sunday, "Sunday", "Monday") assert actual def test_has_name_true_not_list(): context = Mock() s = TXC_START + "<Sunday />" + TXC_END doc = etree.fromstring(s.encode("utf-8")) sunday = doc.getchildren()[0] actual = has_name(context, sunday, "Sunday", "Monday") assert actual
ce90a3d96ed94070d12621ae3626854a148f293d
147d6678b8c99bd1e18b20814f259dc25a395ca6
/python daily coding/2020.7.28 (분할 정복)/2630번 (색종이 만들기).py
a7895c30f167553bcd0d0386667321a32e4ab4b4
[]
no_license
omy5123/Oh-min-young
7759cf869720d58fb07edc0e8f5a9b013afacc95
7db08ab828cc28cb9f477ea5410a48245a156fef
refs/heads/master
2021-05-19T07:08:01.379930
2021-01-17T07:51:49
2021-01-17T07:51:49
251,577,901
0
0
null
null
null
null
UTF-8
Python
false
false
3,267
py
""" 문제 아래 <그림 1>과 같이 여러개의 정사각형칸들로 이루어진 정사각형 모양의 종이가 주어져 있고, 각 정사각형들은 하얀색으로 칠해져 있거나 파란색으로 칠해져 있다. 주어진 종이를 일정한 규칙에 따라 잘라서 다양한 크기를 가진 정사각형 모양의 하얀색 또는 파란색 색종이를 만들려고 한다. 전체 종이의 크기가 N×N(N=2k, k는 1 이상 7 이하의 자연수) 이라면 종이를 자르는 규칙은 다음과 같다. 전체 종이가 모두 같은 색으로 칠해져 있지 않으면 가로와 세로로 중간 부분을 잘라서 <그림 2>의 I, II, III, IV와 같이 똑같은 크기의 네 개의 N/2 × N/2색종이로 나눈다. 나누어진 종이 I, II, III, IV 각각에 대해서도 앞에서와 마찬가지로 모두 같은 색으로 칠해져 있지 않으면 같은 방법으로 똑같은 크기의 네 개의 색종이로 나눈다. 이와 같은 과정을 잘라진 종이가 모두 하얀색 또는 모두 파란색으로 칠해져 있거나, 하나의 정사각형 칸이 되어 더 이상 자를 수 없을 때까지 반복한다. 위와 같은 규칙에 따라 잘랐을 때 <그림 3>은 <그림 1>의 종이를 처음 나눈 후의 상태를, <그림 4>는 두 번째 나눈 후의 상태를, <그림 5>는 최종적으로 만들어진 다양한 크기의 9장의 하얀색 색종이와 7장의 파란색 색종이를 보여주고 있다. 입력으로 주어진 종이의 한 변의 길이 N과 각 정사각형칸의 색(하얀색 또는 파란색)이 주어질 때 잘라진 하얀색 색종이와 파란색 색종이의 개수를 구하는 프로그램을 작성하시오. 입력 첫째 줄에는 전체 종이의 한 변의 길이 N이 주어져 있다. N은 2, 4, 8, 16, 32, 64, 128 중 하나이다. 색종이의 각 가로줄의 정사각형칸들의 색이 윗줄부터 차례로 둘째 줄부터 마지막 줄까지 주어진다. 하얀색으로 칠해진 칸은 0, 파란색으로 칠해진 칸은 1로 주어지며, 각 숫자 사이에는 빈칸이 하나씩 있다. 출력 첫째 줄에는 잘라진 햐얀색 색종이의 개수를 출력하고, 둘째 줄에는 파란색 색종이의 개수를 출력한다. 예제 입력 1 8 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 예제 출력 1 9 7 """ import sys sys.stdin = open('input.txt') n = int(input()) arr = [] for i in range(n): arr.append(list(map(int, input().split()))) white = 0 blue = 0 def cut(x, y, n): global blue, white check = arr[x][y] for i in range(x, x + n): for j in range(y, y + n): if check != arr[i][j]: # 하나라도 같은색이 아니라면 # 4등분 cut(x, y, n // 2) # 1사분면 cut(x, y + n // 2, n // 2) # 2사분면 cut(x + n // 2, y, n // 2) # 3사분면 cut(x + n // 2, y + n // 2, n // 2) # 4사분면 return if check == 0: # 모두 흰색일때 white += 1 return else: # 모두 파란색일때 blue += 1 return cut(0, 0, n) print(white) print(blue)
612526915feaef13c42b467b8f902c53716ddec5
f33c9fb829773fad33ad6e9a39b58ac05d9eafa8
/ship.py
fa559a430db88341031f9e8ebc92fd7cceab8b67
[]
no_license
viceaa22/PyGame_Project
1dbe69e71416d91bf482df9ebc4f230237031bb8
c731fa105dd5d10ea884fd756736e5fa372d8897
refs/heads/master
2021-03-03T01:06:14.320945
2020-03-09T06:31:07
2020-03-09T06:31:07
245,539,410
0
0
null
null
null
null
UTF-8
Python
false
false
1,666
py
import pygame from pygame.sprite import Sprite class Ship(Sprite): #A class to manage the ship. def __init__(self, ai_game): #Initialize the ship and set its starting position. super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect() #Load the ship image and get its rect. self.image = pygame.image.load('C:/Users/Arjun Azavedo/Desktop/Python Projects/Pygame Project/PyGame_Project/ship.bmp') self.rect = self.image.get_rect() #Start each new ship at the bottom center of the screen. self.rect.midbottom = self.screen_rect.midbottom #Store a decimal value for the ship's horizontal position. self.x = float(self.rect.x) #Movement flag self.moving_right = False self.moving_left = False def update(self): #Update the ship's position based on the movement flag. #Update the ship's x value, not the rect. if self.moving_right and self.rect.right < self.screen_rect.right: self.x += self.settings.ship_speed #self.rect.x += 1 if self.moving_left and self.rect.left > 0: self.x -= self.settings.ship_speed #self.rect.x -= 1 #Update rect object from self.x. self.rect.x = self.x def blitme(self): #Draw the ship at its current location. self.screen.blit(self.image, self.rect) def center_ship(self): #Center the ship on the screen. self.rect.midbottom = self.screen_rect.midbottom self.x = float(self.rect.x)
4e8ad14f19c0ce3606a7885cca23901132271876
1a94925f77f55c4ff66b0f87ff55b2e465c62867
/setup.py
ba1a6890933a62110914a47641c5df2e5326f4d7
[ "MIT" ]
permissive
RynoM/MyAwesomeTest2
384e67e985384681b0ee660eedea2258b6d5d130
4d477f0e603141bb14b094f63b14cb266ef2392b
refs/heads/main
2023-08-28T04:28:06.740733
2021-10-27T13:17:19
2021-10-27T13:17:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,948
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages try: from pipenv.project import Project from pipenv.utils import convert_deps_to_pip pfile = Project().parsed_pipfile requirements = convert_deps_to_pip(pfile['packages'], r=False) test_requirements = convert_deps_to_pip(pfile['dev-packages'], r=False) except ImportError: # get the requirements from the requirements.txt requirements = [line.strip() for line in open('requirements.txt').readlines() if line.strip() and not line.startswith('#')] # get the test requirements from the test_requirements.txt test_requirements = [line.strip() for line in open('dev-requirements.txt').readlines() if line.strip() and not line.startswith('#')] readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') version = open('.VERSION').read() setup( name='''myawesometest2lib''', version=version, description='''A template to create python libraries''', long_description=readme + '\n\n' + history, author='''Ryno Marree''', author_email='''[email protected]''', url='''https://github.com/RynoM/MyAwesomeTest2.git''', packages=find_packages(where='.', exclude=('tests', 'hooks', '_CI*')), package_dir={'''myawesometest2lib''': '''myawesometest2lib'''}, include_package_data=True, install_requires=requirements, license='MIT', zip_safe=False, keywords='''myawesometest2lib ''', classifiers=[ 'Development Status :: 6 - Mature', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3.7', ], test_suite='tests', tests_require=test_requirements )
274b9a1849c0f73da2cd6b52ff7fa3d8b0d1daea
1149b21d24294d119195cbaefc70f9f4f75fbed4
/tests/bitmovin/services/outputs/sftp_output_service_tests.py
f51bbe9faa30626f75fe229540bd9fcb40498031
[ "Unlicense" ]
permissive
kfarr/bitmovin-python
8e69f4f54a61a208cc56a1eb5d5eb46a3116657c
94cf13dc1f03f051c60663e9ada0499a1c15329a
refs/heads/master
2021-08-21T20:29:04.292270
2017-11-29T00:41:29
2017-11-29T00:41:29
112,406,291
0
0
null
2017-11-29T00:40:23
2017-11-29T00:40:23
null
UTF-8
Python
false
false
6,595
py
import unittest import json from bitmovin import Bitmovin, Response, SFTPOutput from bitmovin.errors import BitmovinApiError from tests.bitmovin import BitmovinTestCase class SFTPOutputTests(BitmovinTestCase): @classmethod def setUpClass(cls): super().setUpClass() @classmethod def tearDownClass(cls): super().tearDownClass() def setUp(self): super().setUp() self.bitmovin = Bitmovin(self.api_key) self.assertIsNotNone(self.bitmovin) self.assertTrue(isinstance(self.bitmovin, Bitmovin)) def tearDown(self): super().tearDown() def test_create_sftp_output(self): sample_output = self._get_sample_sftp_output() output_resource_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(output_resource_response) self.assertIsNotNone(output_resource_response.resource) self.assertIsNotNone(output_resource_response.resource.id) self._compare_sftp_outputs(sample_output, output_resource_response.resource) def test_create_sftp_output_without_name(self): sample_output = self._get_sample_sftp_output() sample_output.name = None output_resource_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(output_resource_response) self.assertIsNotNone(output_resource_response.resource) self.assertIsNotNone(output_resource_response.resource.id) self._compare_sftp_outputs(sample_output, output_resource_response.resource) def test_create_sftp_output_custom(self): sample_output = self._get_sample_sftp_output() sample_output.port = 9921 output_resource_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(output_resource_response) self.assertIsNotNone(output_resource_response.resource) self.assertIsNotNone(output_resource_response.resource.id) self._compare_sftp_outputs(sample_output, output_resource_response.resource) self.assertEqual(sample_output.port, output_resource_response.resource.port) def test_retrieve_sftp_output(self): sample_output = self._get_sample_sftp_output() created_output_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(created_output_response) self.assertIsNotNone(created_output_response.resource) self.assertIsNotNone(created_output_response.resource.id) self._compare_sftp_outputs(sample_output, created_output_response.resource) retrieved_output_response = self.bitmovin.outputs.SFTP.retrieve(created_output_response.resource.id) self.assertIsNotNone(retrieved_output_response) self.assertIsNotNone(retrieved_output_response.resource) self._compare_sftp_outputs(created_output_response.resource, retrieved_output_response.resource) def test_delete_sftp_output(self): sample_output = self._get_sample_sftp_output() created_output_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(created_output_response) self.assertIsNotNone(created_output_response.resource) self.assertIsNotNone(created_output_response.resource.id) self._compare_sftp_outputs(sample_output, created_output_response.resource) deleted_minimal_resource = self.bitmovin.outputs.SFTP.delete(created_output_response.resource.id) self.assertIsNotNone(deleted_minimal_resource) self.assertIsNotNone(deleted_minimal_resource.resource) self.assertIsNotNone(deleted_minimal_resource.resource.id) try: self.bitmovin.outputs.SFTP.retrieve(created_output_response.resource.id) self.fail( 'Previous statement should have thrown an exception. ' + 'Retrieving output after deleting it shouldn\'t be possible.' ) except BitmovinApiError: pass def test_list_sftp_outputs(self): sample_output = self._get_sample_sftp_output() created_output_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(created_output_response) self.assertIsNotNone(created_output_response.resource) self.assertIsNotNone(created_output_response.resource.id) self._compare_sftp_outputs(sample_output, created_output_response.resource) outputs = self.bitmovin.outputs.SFTP.list() self.assertIsNotNone(outputs) self.assertIsNotNone(outputs.resource) self.assertIsNotNone(outputs.response) self.assertIsInstance(outputs.resource, list) self.assertIsInstance(outputs.response, Response) self.assertGreater(outputs.resource.__sizeof__(), 1) def test_retrieve_sftp_output_custom_data(self): sample_output = self._get_sample_sftp_output() sample_output.customData = '<pre>my custom data</pre>' created_output_response = self.bitmovin.outputs.SFTP.create(sample_output) self.assertIsNotNone(created_output_response) self.assertIsNotNone(created_output_response.resource) self.assertIsNotNone(created_output_response.resource.id) self._compare_sftp_outputs(sample_output, created_output_response.resource) custom_data_response = self.bitmovin.outputs.SFTP.retrieve_custom_data(created_output_response.resource.id) custom_data = custom_data_response.resource self.assertEqual(sample_output.customData, json.loads(custom_data.customData)) def _compare_sftp_outputs(self, first: SFTPOutput, second: SFTPOutput): """ :param first: SFTPOutput :param second: SFTPOutput :return: bool """ self.assertEqual(first.host, second.host) self.assertEqual(first.name, second.name) self.assertEqual(first.description, second.description) def _get_sample_sftp_output(self): sftp_output_settings = self.settings.get('sampleObjects').get('outputs').get('sftp')\ .get('1b5110d3-8ed3-438d-a8cb-b12cb8b142ca') sftp_output = SFTPOutput( host=sftp_output_settings.get('host'), username=sftp_output_settings.get('username'), password=sftp_output_settings.get('password'), name='Sample SFTP Output' ) self.assertIsNotNone(sftp_output.host) self.assertIsNotNone(sftp_output.username) self.assertIsNotNone(sftp_output.password) return sftp_output if __name__ == '__main__': unittest.main()
cc6d9b73d6ca308d106ca6936f9e18bff8ddbbe4
66f256e8cb46576d43bc3a6c1733338d06ff3c73
/task2b_euler.py
8956a0b25fc89c4881ae6a01f2e21d1db4909d38
[]
no_license
suton5/mars_lander_osx
1d5e20011c43e58f772ccc629d35e6ffc8a7bde3
5da3563ca7703bda02cfffb9a4e2bf0f5b39ce39
refs/heads/master
2021-08-11T13:29:45.502930
2017-11-13T19:58:23
2017-11-13T19:58:23
110,595,257
0
0
null
null
null
null
UTF-8
Python
false
false
2,912
py
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt # masses, gravitational constant, initial position and velocity # note that mars has a radius of 3390 km m = 1 M = 6.42e24 G = 6.67e-11 # simulation time and timestep t_max = 10000 dt = [0.1] def orbit_grapher2(p, v): """Takes initial position and velocity vectors and outputs the orbital.""" assert len(p) == 3, "Position vector not 3-dimensional" assert len(v) == 3, "Velocity vector not 3-dimensional" for interval in dt: t_array = np.arange(0, t_max, interval) # initialise empty lists to record trajectories. will end up in a list of tuples. p_list = [] v_list = [] # Euler integration for t in t_array: # append current state to trajectories p_list.append(p) v_list.append(v) # calculate new position and velocity r = np.linalg.norm(p) r_unit = (p[0]/r, p[1]/r, p[2]/r) F_mag = (G*M*m)/(r**2) F = (r_unit[0]*F_mag, r_unit[1]*F_mag, r_unit[2]*F_mag) a = (-F[0]/m, -F[1]/m, -F[2]/m) p_x = p[0] + interval * v[0] p_y = p[1] + interval * v[1] p_z = p[2] + interval * v[2] p = (p_x, p_y, p_z) v_x = v[0] + interval * a[0] v_y = v[1] + interval * a[1] v_z = v[2] + interval * a[2] v = (v_x, v_y, v_z) assert len(p_list) == len(v_list) #check if position list and velocity list have equal number of terms p_x_list = [] p_y_list = [] p_z_list = [] for position_vector in p_list: p_x_list.append(position_vector[0]) p_y_list.append(position_vector[1]) p_z_list.append(position_vector[2]) v_x_list = [] v_y_list = [] v_z_list = [] for velocity_vector in v_list: v_x_list.append(velocity_vector[0]) v_y_list.append(velocity_vector[1]) v_z_list.append(velocity_vector[2]) # convert trajectory lists into arrays, so they can be indexed more easily p_x_array = np.array(p_x_list) p_y_array = np.array(p_y_list) p_z_array = np.array(p_z_list) v_x_array = np.array(v_x_list) v_y_array = np.array(v_y_list) v_z_array = np.array(v_z_list) # plot the orbital graph in 3-D plt.figure(1) plt.clf() plt.xlabel('x') plt.ylabel ('y') plt.title('For dt=' + str(interval)) plt.grid() plt.plot(p_x_array, p_y_array) # plt.plot(t_array, v_array, label='v (m/s)') plt.legend() plt.show() return 0 orbit_grapher2((-4.0e6, 0, 0), (0, 10347, 0)) #circular orbit_grapher2((-4.0e6, 0, 0), (0, 8448, 0)) #elliptical orbit_grapher2((-4.0e6, 0, 0), (0, 15000, 0)) #hyperbolic
0a8bf52acbc6ff8a86fb8de4b1156b54f89cb455
c882b8581a46c3d8ac67057335007fc325aa88ff
/eventex/subscriptions/admin.py
1a5abb93a4c646961935d9e9f86ad6495eaf6e22
[]
no_license
marcellobenigno/eventex
29587da388c1ac8c84b9c4fd69faab4a4cddf269
1fe2e01d1108e809a3e7d2fc8c8e50f2efcbe06a
refs/heads/master
2021-01-10T07:14:06.721089
2016-03-01T18:13:32
2016-03-01T18:13:32
47,883,954
0
0
null
null
null
null
UTF-8
Python
false
false
644
py
from django.contrib import admin from django.utils.timezone import now from eventex.subscriptions.models import Subscription class SubscriptionModelAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'cpf', 'created_at', 'subscribed_today', 'paid') date_hierarchy = 'created_at' search_fields = ('name', 'email', 'phone', 'cpf', 'created_at') list_filter = ('paid', 'created_at') def subscribed_today(self, obj): return obj.created_at == now().date() subscribed_today.short_description = 'inscrito hoje?' subscribed_today.boolean = True admin.site.register(Subscription, SubscriptionModelAdmin)
d257e280d1213908571a6b979be704287ce285c5
575053217c73192a632815fd54dbedf845c65353
/quiky/settings.py
9aac351e7d6d25e40f72b7a7827c45350f5cdfe8
[]
no_license
Oswaldinho24k/Quiky
86cbf80e2ecf8eb5888569886806b5cb47c18e2a
0fb433b724e168917b8e99e7361e09ba818ec36e
refs/heads/master
2021-01-11T18:03:19.741726
2017-04-10T18:13:12
2017-04-10T18:13:12
68,837,471
0
0
null
null
null
null
UTF-8
Python
false
false
3,375
py
""" Django settings for quiky project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/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.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o)3phks@&=c4s9m)h+c)hsfjmnwt4$7vb78a9v8$6p^yakkq!n' # 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', 'main', 'geoposition', 'restaurantes', 'taggit', ] 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 = 'quiky.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 = 'quiky.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/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/1.10/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.10/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.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) MEDIA_URL = '/media/' GEOPOSITION_GOOGLE_MAPS_API_KEY = 'AIzaSyAvcKdUQr6yPVx_PkG9l7j-ttYVXu2qS6Q'
b17eda7d6fe050587ec154abe4f236d7c1bb1134
6ba47bd0946b9950b47903ef2f888cbe90643d01
/funktionen.py
08108b708498958f5cefeae125e01a92ba0e1900
[]
no_license
ClemensDinkel/BR
f5b41c135be5e464316702d32cb55e699125f5e2
5eedb562adff3e681eeb59c03d56b402faabc5bd
refs/heads/master
2023-07-26T21:21:06.408719
2021-09-08T08:57:07
2021-09-08T08:57:07
270,110,320
0
0
null
null
null
null
UTF-8
Python
false
false
2,062
py
def random_id(): import random cr_id = random.randint(0, 9) if cr_id >= 7: identity = "Replikant" else: identity = "Mensch" return identity def add_player(name): from listen import locations import random random_number = random.randint(1, 5) player_loc = locations[random_number] identity = random_id() print(f"{name} ist ein {identity} und wohnt in {player_loc}") def random_npc_cityloc_even(iterations): import random from listen import locations loc_list = list(locations) del loc_list[0:6] del loc_list[5:] tuple(loc_list) loc_list_editable = list(loc_list) random_npc_cityloc_return_list = [] while iterations > 0: if len(loc_list_editable) != 0: available_locs = len(loc_list_editable) random_number = random.randint(0, available_locs - 1) npc_loc = loc_list_editable[random_number] random_npc_cityloc_return_list.append(npc_loc) loc_list_editable.pop(random_number) iterations -= 1 else: loc_list_editable = list(loc_list) return random_npc_cityloc_return_list def random_pc_livingloc_even(iterations): import random from listen import locations loc_list = list(locations) del loc_list[0] del loc_list[5:] tuple(loc_list) loc_list_editable = list(loc_list) random_pc_livingloc_return_list = [] while iterations > 0: if len(loc_list_editable) != 0: available_locs = len(loc_list_editable) random_number = random.randint(0, available_locs - 1) pc_loc = loc_list_editable[random_number] random_pc_livingloc_return_list.append(pc_loc) loc_list_editable.pop(random_number) iterations -= 1 else: loc_list_editable = list(loc_list) return random_pc_livingloc_return_list def npc_disappears(): import random from listen import locations npc_loc = locations[random.randint(0, 5)] return npc_loc
cce25a1037109fc1654a93aba3acc56de7702d23
300db0321330e4fa478b4976913d3650ccb93c2f
/tests/test_tbltalk.py
9a94f7beebabb1e9cd40e2df98b6708f4c0130e3
[ "MIT" ]
permissive
mattmc3/tbltalk
b6f5686a44c428082b67bffde3fd9b6a0b70672e
3ba77aef47ef9ca9e3f3ee9ec6d025d5c67cd767
refs/heads/main
2022-03-18T05:52:23.407740
2017-05-05T17:22:52
2017-05-05T17:22:52
86,751,669
0
0
null
null
null
null
UTF-8
Python
false
false
19,255
py
#!/usr/bin/env python3 import sqlite3 from unittest import TestCase, main as unittest_main from unittest import mock from datetime import datetime from collections import namedtuple from contextlib import contextmanager from collections import namedtuple from tbltalk import (DbTable, SqlStatement, DotDict, DbEngine, sqlparam) # dotdict is useful for testing, but not something we want to rely on from the # actual thing we are testing. Catch-22, so make our own that never changes so # we can have fancy-pants tests. from .utils import (DotDict as expando, get_db_backend, get_args_and_kwargs, popdb) TestDbBackend = namedtuple('TestDbBackend', 'backend_name args kwargs') TEST_DATE = datetime(2006, 1, 2, 15, 4, 5, 123456) TEST_DB_BACKENDS = { 'sqlite_memory': TestDbBackend('sqlite', *get_args_and_kwargs(':memory:')), 'sqlite_file': TestDbBackend('sqlite', *get_args_and_kwargs('test.db')), 'pg': TestDbBackend('postgres', *get_args_and_kwargs("dbname=test user=test")), 'mariadb': TestDbBackend('mariadb', *get_args_and_kwargs(host='localhost', user='root', password='', db='test', charset='utf8mb4')), 'mssql': TestDbBackend('mssql', *get_args_and_kwargs("localhost", "test", "", "test", autocommit=True)), 'mssql_odbc': TestDbBackend('mssql_odbc', *get_args_and_kwargs("DRIVER=FreeTDS;SERVER=localhost;PORT=1433;DATABASE=test;UID=test;PWD=;")), } DB_BACKEND = 'sqlite_memory' USE_SAME_CURSOR = True class DbTableTest(TestCase): def setUp(self): self.con = None self.dbengine = self.get_dbengine() def tearDown(self): if self.con: self.con.commit() self.con.close() self.con = None def get_dbengine(self): test_backend = TEST_DB_BACKENDS[DB_BACKEND] be = get_db_backend(test_backend.backend_name) dbengine = DbEngine(be.dbapi, be.dialect, *test_backend.args, **test_backend.kwargs) con = dbengine.connect() cur = con.cursor() popdb(be.popsql, cur) con.commit() if USE_SAME_CURSOR: self.con = con dbengine.set_shared_connection(con) else: con.close() return dbengine def p(self, name=None, idx=0): return sqlparam(self.dbengine.dbapi.paramstyle, name, idx) def test_initial_db_setup(self): dbengine = self.get_dbengine() with dbengine.cursor() as cur: cur.execute("SELECT COUNT(*) FROM movies") num_movies = cur.fetchone()[0] self.assertEqual(num_movies, 9) cur.execute("SELECT COUNT(*) FROM characters") num_characters = cur.fetchone()[0] self.assertEqual(num_characters, 42) def test_query(self): TestData = namedtuple('TestData', 'sql params result') tests = ( TestData(("SELECT COUNT(*) AS c " "FROM characters " f"WHERE character_type = {self.p()}"), ('Droid',), [{'c': 5}]), TestData(("SELECT name as the_droids_youre_looking_for " "FROM characters " f"WHERE character_type = {self.p()} " f"AND first_appeared_movie_id = {self.p()} "), ('Droid', 1), [{'the_droids_youre_looking_for': 'R2-D2'}, {'the_droids_youre_looking_for': 'C-3PO'}]), ) for td in tests: o = DbTable(self.dbengine) result = list(o.query(td.sql, td.params)) self.assertEqual(result, td.result) def test_scalar(self): TestData = namedtuple('TestData', 'sql result params') tests = ( TestData("SELECT COUNT(*) FROM movies", 9, ()), TestData("SELECT COUNT(*) FROM characters", 42, ()), TestData("SELECT 99", 99, ()), TestData("SELECT NULL", None, ()), TestData("SELECT -1 FROM movies WHERE 1 = 0", None, ()), TestData(("SELECT COUNT(*) " "FROM characters " "WHERE first_appeared_movie_id IS NULL"), 1, ()), TestData(("SELECT COUNT(*) " "FROM characters " f"WHERE character_type = {self.p()}"), 5, ('Droid',)), ) for td in tests: o = DbTable(self.dbengine) self.assertEqual(o.scalar(td.sql, td.params), td.result) def test_has_pk(self): TestData = namedtuple('TestData', 'obj pk_field has_pk') tests = ( TestData(expando({'id': 1, 'b': 2}), 'id', True), TestData(expando({'a': 1, 'the_id': 2}), 'the_id', True), TestData(expando({'a': 1, 'b': 2}), 'pk', False), ) for td in tests: o = DbTable(self.dbengine, pk_field=td.pk_field) self.assertEqual(o.has_pk(td.obj), td.has_pk) def test_get_pk(self): TestData = namedtuple('TestData', 'obj pk_field pk_value') tests = ( TestData(expando({'a': 1, 'b': 2}), 'a', 1), TestData(expando({'a': 1, 'b': 2}), 'b', 2), TestData(expando({'a': 1, 'b': 2}), 'c', None), ) for td in tests: o = DbTable(self.dbengine, pk_field=td.pk_field) self.assertEqual(o.get_pk(td.obj), td.pk_value) def test_create_delete_sql(self): TestData = namedtuple('TestData', 'table_name kwargs sql') tests = ( TestData('tbl', {}, "DELETE FROM tbl"), TestData('tbl', {'where': f'id = {self.p()}'}, f"DELETE FROM tbl WHERE id = {self.p()}"), TestData('tbl', {'where': f'name = {self.p()} or age < 18'}, f"DELETE FROM tbl WHERE name = {self.p()} or age < 18"), ) for td in tests: o = DbTable(self.dbengine, table_name=td.table_name) sql = o.create_delete_sql(**td.kwargs) self.assertEqual(sql, td.sql) def test_delete(self): dbengine = self.get_dbengine() # remove all characters because FKs... ch = DbTable(dbengine, table_name="characters") self.assertEqual(ch.count(), 42) ch.delete(where="1=1") self.assertEqual(ch.count(), 0) o = DbTable(dbengine, table_name="movies") countquery = "SELECT COUNT(*) FROM movies" self.assertEqual(o.scalar(countquery), 9) o.delete_by_id(9) self.assertEqual(o.scalar(countquery), 8) where = f"episode = {self.p()}" o.delete(where=where, params=('I',)) self.assertEqual(o.scalar(countquery), 7) where = f"name like {self.p()}" o.delete(where=where, params=('%Star%Wars%',)) self.assertEqual(o.scalar(countquery), 2) def test_create_insert_statement(self): TestData = namedtuple('TestData', 'dbtbl_kwargs obj cols vals params') tests = ( TestData({'table_name': 'tbl'}, {'id': 1, 'a': 2, 'b': 3}, 'a, b', f'{self.p()}, {self.p()}', (2, 3)), TestData({'table_name': 'tbl', 'pk_field': "tbl_key", 'pk_autonumber': False}, {'tbl_key': 1, 'a': 2, 'b': 3}, 'tbl_key, a, b', f'{self.p()}, {self.p()}, {self.p()}', (1, 2, 3)), ) for td in tests: o = DbTable(self.dbengine, **td.dbtbl_kwargs) insert_sql = self.dbengine.dialect.insert_sql.format( table=o.table_name, columns=td.cols, values=td.vals, pk_field=o.pk_field ) stmt = o.create_insert_statement(td.obj) self.assertEqual(stmt, SqlStatement(insert_sql, td.params)) def test_failed_insert(self): countquery = "SELECT COUNT(*) c FROM characters" o = DbTable(self.dbengine, table_name="characters") self.assertEqual(o.scalar(countquery), 42) with self.assertRaises(Exception): o.insert({'name': 'General Grievous', 'fake_field': 'error'}) # verify no change self.assertEqual(o.scalar(countquery), 42) def test_insert(self): countquery = "SELECT COUNT(*) c FROM characters" o = DbTable(self.dbengine, table_name="characters") self.assertEqual(o.scalar(countquery), 42) id = o.insert({ 'name': 'Wedge Antilles', 'sex': 'M', 'character_type': 'Human', 'allegiance': '', 'first_appeared_movie_id': 1, 'has_force': False, }) self.assertEqual(id, 43) self.assertEqual(o.scalar(countquery), 43) def test_create_update_statement(self): TestData = namedtuple('TestData', 'dbtbl_kwargs obj key stmt') tests = ( TestData({'table_name': 'tbl'}, {'id': 1, 'a': 'A', 'b': 3}, 1, SqlStatement(("UPDATE tbl " f"SET a = {self.p()}, b = {self.p()} " f"WHERE id = {self.p()}"), ('A', 3, 1)),), ) for td in tests: o = DbTable(self.dbengine, **td.dbtbl_kwargs) stmt = o.create_update_statement(td.obj, td.key) self.assertEqual(stmt, td.stmt) def test_update(self): o = DbTable(self.dbengine, table_name="characters") rebels = o.find_by(allegiance='The Rebel Alliance', first_appeared_movie_id=1) smugglers = o.find_by(allegiance='Smuggler', first_appeared_movie_id=1) self.assertEqual(len(rebels), 6) self.assertEqual(len(smugglers), 2) for s in smugglers: s.allegiance = 'The Rebel Alliance' o.update(s, s.id) rebels = o.find_by(allegiance='The Rebel Alliance', first_appeared_movie_id=1) smugglers = o.find_by(allegiance='Smuggler', first_appeared_movie_id=1) self.assertEqual(len(rebels), 8) self.assertEqual(len(smugglers), 0) def test_create_select_sql(self): TestData = namedtuple('TestData', 'table_name kwargs select') tests = ( TestData('pets', {}, "SELECT * FROM pets"), TestData('pets', {'distinct': True}, "SELECT DISTINCT * FROM pets"), TestData('tbl', {'columns': 'col1, col2'}, "SELECT col1, col2 FROM tbl"), TestData('tbl', {'columns': ('col1', 'col2')}, "SELECT col1, col2 FROM tbl"), TestData('tbl', {'columns': ('COUNT(*) as c',)}, "SELECT COUNT(*) as c FROM tbl"), TestData('tbl', {'where': f'name = {self.p()} and age > {self.p()}'}, f"SELECT * FROM tbl WHERE name = {self.p()} and age > {self.p()}"), TestData('tbl', {'columns': ('a', 'b'), 'distinct': True, 'where': f'name = {self.p()} and age > {self.p()}', 'orderby': ('name DESC', 'dob'), 'limit': 10}, ("SELECT DISTINCT{top} a, b " "FROM tbl " f"WHERE name = {self.p()} and age > {self.p()} " "ORDER BY name DESC, dob{limit}")), ) for td in tests: o = DbTable(self.dbengine, table_name=td.table_name) sql = o.create_select_sql(**td.kwargs) expected = td.select if 'limit' in td.kwargs: kw = self.dbengine.dialect.keywords.limit top, limit = "", "" if kw.upper() == "TOP": top = " TOP {}".format(td.kwargs['limit']) else: limit = " LIMIT {}".format(td.kwargs['limit']) expected = expected.format(top=top, limit=limit) self.assertEqual(sql, expected) def test_get_by_id(self): TestData = namedtuple('TestData', 'dbtbl_kwargs id result') tests = ( TestData({'table_name': 'movies'}, 1, DotDict([('id', 1), ('name', 'Star Wars (A New Hope)'), ('episode', 'IV'), ('director', 'George Lucas'), ('release_year', 1977), ('chronology', 5)])), ) for td in tests: o = DbTable(self.dbengine, **td.dbtbl_kwargs) result = o.get_by_id(td.id) self.assertEqual(td.result, result) def test_dynamicquery_single(self): o = DbTable(self.dbengine, table_name="characters") thrawn = o.single(id=42) self.assertEqual(thrawn.name, 'Grand Admiral Thrawn') who = o.single(id=43) self.assertEqual(who, None) def test_dynamicquery_find_by(self): o = DbTable(self.dbengine, table_name="characters") smugglers = o.find_by_allegiance(allegiance='Smuggler', first_appeared_movie_id=1, orderby="name") self.assertEqual(len(smugglers), 2) self.assertEqual(smugglers[0].name, 'Chewbacca') self.assertEqual(smugglers[1].name, 'Han Solo') def test_min(self): TestData = namedtuple('TestData', 'dbtbl_kwargs min_kwargs result') tests = ( TestData({'table_name': 'movies'}, {'column': 'release_year'}, 1977), TestData({'table_name': 'characters'}, {'column': 'name'}, 'Admiral Ackbar'), TestData({'table_name': 'characters'}, {'column': 'name', 'where': f'character_type = {self.p()}', 'params': ('Droid',)}, 'BB-8'), ) for td in tests: o = DbTable(self.dbengine, **td.dbtbl_kwargs) result = o.min(**td.min_kwargs) self.assertEqual(result, td.result) def test_max(self): TestData = namedtuple('TestData', 'dbtbl_kwargs max_kwargs result') tests = ( TestData({'table_name': 'movies'}, {'column': 'release_year'}, 2017), TestData({'table_name': 'characters'}, {'column': 'name'}, 'Yoda'), TestData({'table_name': 'characters'}, {'column': 'name', 'where': f'character_type = {self.p()}', 'params': ('Droid',)}, 'R2-D2'), ) for td in tests: o = DbTable(self.dbengine, **td.dbtbl_kwargs) result = o.max(**td.max_kwargs) self.assertEqual(result, td.result) def test_all_basic(self): o = DbTable(self.dbengine, table_name="movies") movies = list(o.all()) self.assertEqual(9, len(movies)) def test_paged(self): o = DbTable(self.dbengine, table_name="movies") TestData = namedtuple('TestData', ['dbtbl_kwargs', 'paged_kwargs', 'start_page', 'end_page', 'total_records', 'total_pages', 'result']) tests = ( TestData( {'table_name': 'movies'}, { 'columns': ['id', 'name', 'episode'], 'where': f"director = {self.p()}", 'params': ('George Lucas',), 'orderby': 'release_year', 'page_size': 2, }, 1, 4, 5, 3, [ [ DotDict((('id', 1), ('name', 'Star Wars (A New Hope)'), ('episode', 'IV'))), DotDict((('id', 3), ('name', 'Return of the Jedi'), ('episode', 'VI'))), ], [ DotDict((('id', 4), ('name', 'Star Wars: Episode I - The Phantom Menace'), ('episode', 'I'))), DotDict((('id', 5), ('name', 'Star Wars: Episode II - Attack of the Clones'), ('episode', 'II'))), ], [ DotDict((('id', 6), ('name', 'Star Wars: Episode III - Revenge of the Sith'), ('episode', 'III'))), ], [] ] ), ) for td in tests: o = DbTable(self.dbengine, **td.dbtbl_kwargs) paged_kwargs = td.paged_kwargs for idx, current_page in enumerate(range(td.start_page, td.end_page + 1)): paged_kwargs["current_page"] = current_page result = o.paged(**paged_kwargs) self.assertEqual(result.current_page, paged_kwargs["current_page"]) self.assertEqual(result.total_records, td.total_records) self.assertEqual(len(result.records), len(td.result[idx])) self.assertEqual(result.records, td.result[idx]) if __name__ == '__main__': unittest_main() # def test_default_value(self): # TestData = namedtuple('TestData', 'column_default utcnow result') # tests = ( # TestData(None, TEST_DATE, None), # TestData('CURRENT_TIME', TEST_DATE, '15:04:05'), # TestData('CURRENT_DATE', TEST_DATE, '2006-01-02'), # TestData('CURRENT_TIMESTAMP', TEST_DATE, '2006-01-02 15:04:05'), # ) # with mock.patch('tbltalk.datetime') as dt_mock: # dt_mock.utcnow.return_value = TEST_DATE # dt_mock.side_effect = lambda *args, **kw: datetime(*args, **kw) # for td in tests: # o = DbTable(self.dbengine) # column = expando({'COLUMN_DEFAULT': td.column_default}) # self.assertEqual(o.default_value(column), td.result) # def default_value(self, column): # ''' Gets a default value for the column ''' # result = None # deflt = column.COLUMN_DEFAULT # if not deflt: # result = None # elif deflt.upper() == "CURRENT_TIME": # result = datetime.utcnow().strftime("%H:%M:%S") # elif deflt.upper() == "CURRENT_DATE": # result = datetime.utcnow().strftime("%Y-%m-%d") # elif deflt.upper() == "CURRENT_TIMESTAMP": # result = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") # return result
cf55ef734e6b6143b615e9bd2a925b5e3c4cbc7e
8a095612669c2aa22db497f5ea6be1fba9d74fb3
/qubekit/cli/combine.py
78f8744c91f7bcb7e109e1d1dd4b05ce32585f1d
[ "MIT" ]
permissive
qubekit/QUBEKit
dba1eedb8ab090be95bddea3e6f499b7565b1d12
bdccc28d1ad8c0fb4eeb01467bfe8365396c411c
refs/heads/main
2023-08-19T03:14:33.742295
2023-08-02T13:10:14
2023-08-02T13:10:14
180,546,295
89
25
MIT
2023-08-18T13:19:24
2019-04-10T09:17:09
Python
UTF-8
Python
false
false
21,899
py
import os import xml.etree.ElementTree as ET from datetime import datetime from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union from xml.dom.minidom import parseString import click from openff.toolkit.typing.engines.smirnoff import ForceField from openmm import unit from typing_extensions import Literal import qubekit from qubekit.cli.water_models import water_models_local, water_models_normal from qubekit.utils import constants from qubekit.workflow import WorkFlowResult if TYPE_CHECKING: from qubekit.molecules import Atom, Ligand elements = ["H", "C", "N", "O", "X", "Cl", "S", "F", "Br", "P", "I", "B", "Si", "AB"] parameters_to_fit = click.Choice( elements, case_sensitive=True, ) water_options = click.Choice(list(water_models_normal.keys()), case_sensitive=True) @click.command() @click.argument("filename", type=click.STRING) @click.option( "-p", "--parameters", type=parameters_to_fit, help="The elements whose Rfree is to be optimised, if not provided all will be fit.", multiple=True, ) @click.option( "-n", "--no-targets", is_flag=True, show_default=True, default=False, help="If the xmls should be combined with no optimisation targets, this option is useful for Forcebalance single point evaluations.", ) @click.option( "-offxml", is_flag=True, default=False, show_default=True, help="Make an offxml style force field if possible.", ) @click.option( "--lj-on-polar-h/--no-lj-on-polar-h", default=True, show_default=True, help="Add or remove LJ terms from polar hydroges, they will have their C6 transferred to the parent atom if excluded.", ) @click.option( "-w", "--water-model", type=water_options, help="The name of a published water model to include in an offxml Note this will cause a clash if used with a QUBEKit local model.", ) @click.option( "-h-con", "--h-constraints", show_default=True, default=True, help="If the offxml should include h-bond constraints, offxmls include constraints by default.", ) def combine( filename: str, parameters: Optional[List[str]] = None, no_targets: bool = False, offxml: bool = False, water_model: str = "tip3p", h_constraints: bool = True, lj_on_polar_h: bool = True, ): """ Combine a list of molecules together and create a single master XML force field file. """ if no_targets and parameters: raise click.ClickException( "The options parameters and no-targets are mutually exclusive." ) molecules, rfrees = _find_molecules_and_rfrees() if not parameters and not no_targets: # fit everything parameters = elements elif no_targets: parameters = [] if offxml: _combine_molecules_offxml( molecules, rfree_data=rfrees, parameters=parameters, filename=filename, water_model=water_model, h_constraints=h_constraints, lj_on_polar_h=lj_on_polar_h, ) else: xml_data = _combine_molecules( molecules=molecules, rfree_data=rfrees, parameters=parameters ).getroot() messy = ET.tostring(xml_data, "utf-8") pretty_xml = parseString(messy).toprettyxml(indent="") with open(filename, "w") as xml_doc: xml_doc.write(pretty_xml) def _add_water_model( force_field: ForceField, water_model: Literal["tip3p", "tip4p-fb"] = "tip3p", use_local_sites: bool = False, ): """Add a water model to an offxml force field""" if use_local_sites: available_models = water_models_local else: available_models = water_models_normal if water_model in available_models: water_parameters = available_models[water_model] for parameter_handler, parameters in water_parameters.items(): if parameter_handler == "Nonbonded": handler = force_field.get_parameter_handler("vdW") else: handler = force_field.get_parameter_handler(parameter_handler) for parameter in parameters: handler.add_parameter(parameter_kwargs=parameter) else: raise NotImplementedError( f"Only the {list(water_models_local.keys())} water models are support for offxmls so far." ) def _combine_molecules_offxml( molecules: List["Ligand"], parameters: List[str], rfree_data: Dict[str, Dict[str, Union[str, float]]], filename: str, water_model: Optional[Literal["tip3p", "tip4p-fb"]] = None, h_constraints: bool = True, lj_on_polar_h: bool = True, ) -> None: """ Main worker function to build the combined offxmls. """ if ( sum([molecule.ImproperRBTorsionForce.n_parameters for molecule in molecules]) > 0 ): raise NotImplementedError( "RBTorsions improper can not yet be safely converted into offxml format yet." ) try: from chemper.graphs.cluster_graph import ClusterGraph except ModuleNotFoundError: raise ModuleNotFoundError( "chemper is required to make an offxml, please install with `conda install chemper -c conda-forge`." ) fit_ab = False # if alpha and beta should be fit if "AB" in parameters: fit_ab = True rfree_codes = set() # keep track of all rfree codes used by these molecules # create the master ff offxml = ForceField(allow_cosmetic_attributes=True, load_plugins=True) offxml.author = f"QUBEKit_version_{qubekit.__version__}" offxml.date = datetime.now().strftime("%Y_%m_%d") # get all of the handlers constraints = offxml.get_parameter_handler("Constraints") if h_constraints: constraints.add_parameter( parameter_kwargs={"smirks": "[#1:1]-[*:2]", "id": "h-c1"} ) # add the handlers to ensure we get them in the order we want _ = offxml.get_parameter_handler("Bonds") _ = offxml.get_parameter_handler("Angles") _ = offxml.get_parameter_handler("ProperTorsions") _ = offxml.get_parameter_handler("ImproperTorsions") _ = offxml.get_parameter_handler( "Electrostatics", handler_kwargs={"scale14": 0.8333333333, "version": 0.3} ) using_plugin = False if parameters: # if we want to optimise the Rfree we need our custom handler vdw_handler = offxml.get_parameter_handler( "QUBEKitvdWTS", allow_cosmetic_attributes=True ) vdw_handler.lj_on_polar_h = str(lj_on_polar_h) using_plugin = True # add a dummy parameter to avoid missing parameters vdw = offxml.get_parameter_handler("vdW", allow_cosmetic_attributes=True) vdw.add_parameter( parameter_kwargs={ "smirks": "[*:1]", "epsilon": 0 * unit.kilojoule_per_mole, "sigma": 1 * unit.nanometer, "id": "g1", } ) else: vdw_handler = offxml.get_parameter_handler( "vdW", allow_cosmetic_attributes=True ) for molecule in molecules: print(f"Adding parameters for molecule {molecule.name}") # add each parameter section but use a special method to add the nonbonded section used for Rfree opt molecule._build_offxml_bonds(offxml=offxml) molecule._build_offxml_angles(offxml=offxml) molecule._build_offxml_torsions(offxml=offxml, parameterize=False) if molecule.ImproperTorsionForce.n_parameters > 0: molecule._build_offxml_improper_torsions(offxml=offxml) if molecule.RBTorsionForce.n_parameters > 0: molecule._build_offxml_rb_torsions(offxml=offxml) molecule._build_offxml_charges(offxml=offxml) molecule._build_offxml_vs(offxml=offxml) if using_plugin: molecule._build_offxml_volumes(offxml=offxml) for i in range(molecule.n_atoms): rfree_code = _get_parameter_code(molecule=molecule, atom_index=i) if rfree_code in parameters or fit_ab: rfree_codes.add(rfree_code) else: # add normal vdw sigma and epsilon types molecule._build_offxml_vdw(offxml=offxml) # now loop over all the parameters to be fit and add them as cosmetic attributes to_parameterize = [] for parameter_to_fit in parameters: if parameter_to_fit != "AB" and parameter_to_fit in rfree_codes: setattr( vdw_handler, f"{parameter_to_fit.lower()}free", unit.Quantity( rfree_data[parameter_to_fit]["r_free"], unit=unit.angstroms ), ) if not lj_on_polar_h and parameter_to_fit.lower() == "x": # do add the parameterize tag to polar h if not included continue else: to_parameterize.append(f"{parameter_to_fit.lower()}free") if fit_ab: vdw_handler.alpha = rfree_data["alpha"] vdw_handler.beta = rfree_data["beta"] to_parameterize.extend(["alpha", "beta"]) if to_parameterize: vdw_handler.add_cosmetic_attribute("parameterize", ", ".join(to_parameterize)) # now add a water model to the force field use_local_sites = True local_vsites = offxml.get_parameter_handler("LocalCoordinateVirtualSites") if len(local_vsites._parameters) == 0: use_local_sites = False # deregister the handler if not in use offxml.deregister_parameter_handler("LocalCoordinateVirtualSites") if water_model is not None: _add_water_model( force_field=offxml, water_model=water_model, use_local_sites=use_local_sites ) offxml.to_file(filename=filename) def _combine_molecules( molecules: List["Ligand"], parameters: List[str], rfree_data: Dict[str, Dict[str, Union[str, float]]], ) -> ET.ElementTree: """ Main worker function used to combine the molecule force fields. """ fit_ab = False # if alpha and beta should be fit if "AB" in parameters: fit_ab = True rfree_codes = set() # keep track of all rfree codes used by these molecules root = ET.Element("ForceField") ET.SubElement( root, "QUBEKit", attrib={ "Version": qubekit.__version__, "Date": datetime.now().strftime("%Y_%m_%d"), }, ) AtomTypes = ET.SubElement(root, "AtomTypes") Residues = ET.SubElement(root, "Residues") force_by_type = {} increment = 0 # loop over molecules and create forces as they are found for molecule in molecules: resiude = ET.SubElement(Residues, "Residue", name=molecule.name) for atom in molecule.atoms: atom_type = f"QUBE_{atom.atom_index + increment}" ET.SubElement( AtomTypes, "Type", attrib={ "name": atom_type, "class": str(atom.atom_index + increment), "element": atom.atomic_symbol, "mass": str(atom.atomic_mass), }, ) ET.SubElement( resiude, "Atom", attrib={"name": str(atom.atom_index + increment), "type": atom_type}, ) for ( i, site, ) in enumerate(molecule.extra_sites, start=1 + increment): site_name = f"v-site{i}" site_class = f"X{i}" ET.SubElement( AtomTypes, "Type", attrib={"name": site_name, "class": site_class, "mass": "0"}, ) ET.SubElement( resiude, "Atom", attrib={"name": site_class, "type": site_name} ) if molecule.BondForce.openmm_group() not in force_by_type: new_bond_force = ET.SubElement( root, molecule.BondForce.openmm_group(), attrib=molecule.BondForce.xml_data(), ) # add to dict force_by_type[molecule.BondForce.openmm_group()] = new_bond_force BondForce = force_by_type[molecule.BondForce.openmm_group()] for parameter in molecule.BondForce: ET.SubElement( BondForce, parameter.openmm_type(), attrib=_update_increment( force_data=parameter.xml_data(), increment=increment ), ) ET.SubElement( resiude, "Bond", attrib={"from": str(parameter.atoms[0]), "to": str(parameter.atoms[1])}, ) if molecule.AngleForce.openmm_group() not in force_by_type: new_angle_force = ET.SubElement( root, molecule.AngleForce.openmm_group(), attrib=molecule.AngleForce.xml_data(), ) force_by_type[molecule.AngleForce.openmm_group()] = new_angle_force AngleForce = force_by_type[molecule.AngleForce.openmm_group()] for parameter in molecule.AngleForce: ET.SubElement( AngleForce, parameter.openmm_type(), attrib=_update_increment( force_data=parameter.xml_data(), increment=increment ), ) if molecule.TorsionForce.openmm_group() not in force_by_type: new_torsion_force = ET.SubElement( root, molecule.TorsionForce.openmm_group(), attrib=molecule.TorsionForce.xml_data(), ) force_by_type[molecule.TorsionForce.openmm_group()] = new_torsion_force TorsionForce = force_by_type[molecule.TorsionForce.openmm_group()] for parameter in molecule.TorsionForce: ET.SubElement( TorsionForce, parameter.openmm_type(), attrib=_update_increment( force_data=parameter.xml_data(), increment=increment ), ) for parameter in molecule.ImproperTorsionForce: ET.SubElement( TorsionForce, parameter.openmm_type(), attrib=_update_increment( force_data=parameter.xml_data(), increment=increment ), ) # not common so check if we need the section if ( molecule.RBTorsionForce.n_parameters > 0 or molecule.ImproperRBTorsionForce.n_parameters > 0 ): if molecule.RBTorsionForce.openmm_group() not in force_by_type: new_rb_torsion_force = ET.SubElement( root, molecule.RBTorsionForce.openmm_group(), attrib=molecule.RBTorsionForce.xml_data(), ) force_by_type[ molecule.RBTorsionForce.openmm_group() ] = new_rb_torsion_force RBTorsion = force_by_type[molecule.RBTorsionForce.openmm_group()] for parameter in molecule.RBTorsionForce: ET.SubElement( RBTorsion, parameter.openmm_type(), attrib=_update_increment( force_data=parameter.xml_data(), increment=increment ), ) for parameter in molecule.ImproperRBTorsionForce: ET.SubElement( RBTorsion, parameter.openmm_type(), attrib=_update_increment( force_data=parameter.xml_data(), increment=increment ), ) for i, site in enumerate(molecule.extra_sites): site_data = site.xml_data() site_data["index"] = str(i + molecule.n_atoms) ET.SubElement(resiude, site.openmm_type(), attrib=site_data) if molecule.NonbondedForce.openmm_group() not in force_by_type: new_nb_force = ET.SubElement( root, molecule.NonbondedForce.openmm_group(), attrib=molecule.NonbondedForce.xml_data(), ) force_by_type[molecule.NonbondedForce.openmm_group()] = new_nb_force NonbondedForce = force_by_type[molecule.NonbondedForce.openmm_group()] for parameter in molecule.NonbondedForce: # work out if the atom is being optimised rfree_code = _get_parameter_code( molecule=molecule, atom_index=parameter.atoms[0] ) atom_data = { "charge": str(parameter.charge), "sigma": str(parameter.sigma), "epsilon": str(parameter.epsilon), "type": f"QUBE_{str(parameter.atoms[0] + increment)}", } if rfree_code in parameters or fit_ab: # keep track of present codes to optimise rfree_codes.add(rfree_code) # this is to be refit atom = molecule.atoms[parameter.atoms[0]] eval_string = _get_eval_string( atom=atom, rfree_data=rfree_data[rfree_code], a_and_b=fit_ab, alpha_ref=rfree_data["alpha"], beta_ref=rfree_data["beta"], rfree_code=rfree_code if rfree_code in parameters else None, ) atom_data["parameter_eval"] = eval_string atom_data["volume"] = str(atom.aim.volume) atom_data["bfree"] = str(rfree_data[rfree_code]["b_free"]) atom_data["vfree"] = str(rfree_data[rfree_code]["v_free"]) ET.SubElement(NonbondedForce, parameter.openmm_type(), attrib=atom_data) for i, site in enumerate(molecule.extra_sites, start=1 + increment): site_name = f"v-site{i}" ET.SubElement( NonbondedForce, "Atom", attrib={ "charge": str(site.charge), "epsilon": "0", "sigma": "1", "type": site_name, }, ) increment += molecule.n_atoms # add the ForceBalance tags ForceBalance = ET.SubElement(root, "ForceBalance") for parameter_to_fit in parameters: if parameter_to_fit != "AB" and parameter_to_fit in rfree_codes: fit_data = { f"{parameter_to_fit.lower()}free": str( rfree_data[parameter_to_fit]["r_free"] ), "parameterize": f"{parameter_to_fit.lower()}free", } ET.SubElement(ForceBalance, f"{parameter_to_fit}Element", attrib=fit_data) if fit_ab: ET.SubElement( ForceBalance, "xalpha", alpha=str(rfree_data["alpha"]), parameterize="alpha" ) ET.SubElement( ForceBalance, "xbeta", beta=str(rfree_data["beta"]), parameterize="beta" ) return ET.ElementTree(root) def _get_eval_string( atom: "Atom", rfree_data: Dict[str, str], a_and_b: bool, alpha_ref: str, beta_ref: str, rfree_code: Optional[str] = None, ) -> str: """ Create the parameter eval string used by ForceBalance to calculate the sigma and epsilon parameters. """ if a_and_b: alpha = "PARM['xalpha/alpha']" beta = "PARM['xbeta/beta']" else: alpha, beta = alpha_ref, beta_ref if rfree_code is not None: rfree = f"PARM['{rfree_code}Element/{rfree_code.lower()}free']" else: rfree = f"{rfree_data['r_free']}" eval_string = ( f"epsilon=({alpha}*{rfree_data['b_free']}*({atom.aim.volume}/{rfree_data['v_free']})**{beta})/(128*{rfree}**6)*{constants.EPSILON_CONVERSION}, " f"sigma=2**(5/6)*({atom.aim.volume}/{rfree_data['v_free']})**(1/3)*{rfree}*{constants.SIGMA_CONVERSION}" ) return eval_string def _find_molecules_and_rfrees() -> ( Tuple[List["Ligand"], Dict[str, Dict[str, Union[str, float]]]] ): """ Loop over the local directories looking for qubekit WorkFlowResults and extract the ligands and a list of all unique free params used to parameterise the molecules. """ molecules = [] element_params = {} for folder in os.listdir("."): if os.path.isdir(folder) and folder.startswith("QUBEKit_"): workflow_result = WorkFlowResult.parse_file( os.path.join(folder, "workflow_result.json") ) molecules.append(workflow_result.current_molecule) lj_stage = workflow_result.results["non_bonded"].stage_settings element_params.update(lj_stage["free_parameters"]) element_params["alpha"] = lj_stage["alpha"] element_params["beta"] = lj_stage["beta"] print(f"{len(molecules)} molecules found, combining...") return molecules, element_params def _update_increment(force_data: Dict[str, str], increment: int) -> Dict[str, str]: """ Update the increment on some force data. """ for key, value in force_data.items(): if key.startswith("class"): force_data[key] = str(int(value) + increment) return force_data def _get_parameter_code(molecule: "Ligand", atom_index: int) -> str: """ Work out the rfree code for an atom in a molecule, mainly used for special cases. """ atom = molecule.atoms[atom_index] rfree_code = atom.atomic_symbol if rfree_code == "H": # check if polar if molecule.atoms[atom.bonds[0]].atomic_symbol in ["O", "N", "S"]: rfree_code = "X" return rfree_code
6aa81944332d00ec02396a7a116d4c4b744d4dc7
3a183d383b7af4c475ed785e5fa1d0d6acd42f68
/fabfile.py
674f06d6cfb34612a6fb3f016e2724c9dfeadfcb
[]
no_license
itziar/Welpe
685b44185277f436c2640a586123ffecd47d9891
7a390f98fec62825360c462f65944018ace7c265
refs/heads/master
2021-01-20T00:34:14.658501
2017-05-29T06:59:06
2017-05-29T06:59:06
89,151,858
1
0
null
null
null
null
UTF-8
Python
true
false
21,820
py
from __future__ import print_function, unicode_literals from future.builtins import open import os import re import sys from contextlib import contextmanager from functools import wraps from getpass import getpass, getuser from glob import glob from importlib import import_module from posixpath import join from mezzanine.utils.conf import real_project_name from fabric.api import abort, env, cd, prefix, sudo as _sudo, run as _run, \ hide, task, local from fabric.context_managers import settings as fab_settings from fabric.contrib.console import confirm from fabric.contrib.files import exists, upload_template from fabric.contrib.project import rsync_project from fabric.colors import yellow, green, blue, red from fabric.decorators import hosts ################ # Config setup # ################ env.proj_app = real_project_name("Welpe") conf = {} if sys.argv[0].split(os.sep)[-1] in ("fab", "fab-script.py"): # Ensure we import settings from the current dir try: conf = import_module("%s.settings" % env.proj_app).FABRIC try: conf["HOSTS"][0] except (KeyError, ValueError): raise ImportError except (ImportError, AttributeError): print("Aborting, no hosts defined.") exit() env.db_pass = conf.get("DB_PASS", None) env.admin_pass = conf.get("ADMIN_PASS", None) env.user = conf.get("SSH_USER", getuser()) env.password = conf.get("SSH_PASS", None) env.key_filename = conf.get("SSH_KEY_PATH", None) env.hosts = conf.get("HOSTS", [""]) env.proj_name = conf.get("PROJECT_NAME", env.proj_app) env.venv_home = conf.get("VIRTUALENV_HOME", "/home/%s/.virtualenvs" % env.user) env.venv_path = join(env.venv_home, env.proj_name) env.proj_path = "/home/%s/mezzanine/%s" % (env.user, env.proj_name) env.manage = "%s/bin/python %s/manage.py" % (env.venv_path, env.proj_path) env.domains = conf.get("DOMAINS", [conf.get("LIVE_HOSTNAME", env.hosts[0])]) env.domains_nginx = " ".join(env.domains) env.domains_regex = "|".join(env.domains) env.domains_python = ", ".join(["'%s'" % s for s in env.domains]) env.ssl_disabled = "#" if len(env.domains) > 1 else "" env.vcs_tools = ["git", "hg"] env.deploy_tool = conf.get("DEPLOY_TOOL", "rsync") env.reqs_path = conf.get("REQUIREMENTS_PATH", None) env.locale = conf.get("LOCALE", "en_US.UTF-8") env.num_workers = conf.get("NUM_WORKERS", "multiprocessing.cpu_count() * 2 + 1") env.secret_key = conf.get("SECRET_KEY", "") env.nevercache_key = conf.get("NEVERCACHE_KEY", "") # Remote git repos need to be "bare" and reside separated from the project if env.deploy_tool == "git": env.repo_path = "/home/%s/git/%s.git" % (env.user, env.proj_name) else: env.repo_path = env.proj_path ################## # Template setup # ################## # Each template gets uploaded at deploy time, only if their # contents has changed, in which case, the reload command is # also run. templates = { "nginx": { "local_path": "deploy/nginx.conf.template", "remote_path": "/etc/nginx/sites-enabled/%(proj_name)s.conf", "reload_command": "service nginx restart", }, "supervisor": { "local_path": "deploy/supervisor.conf.template", "remote_path": "/etc/supervisor/conf.d/%(proj_name)s.conf", "reload_command": "supervisorctl update gunicorn_%(proj_name)s", }, "cron": { "local_path": "deploy/crontab.template", "remote_path": "/etc/cron.d/%(proj_name)s", "owner": "root", "mode": "600", }, "gunicorn": { "local_path": "deploy/gunicorn.conf.py.template", "remote_path": "%(proj_path)s/gunicorn.conf.py", }, "settings": { "local_path": "deploy/local_settings.py.template", "remote_path": "%(proj_path)s/%(proj_app)s/local_settings.py", }, } ###################################### # Context for virtualenv and project # ###################################### @contextmanager def virtualenv(): """ Runs commands within the project's virtualenv. """ with cd(env.venv_path): with prefix("source %s/bin/activate" % env.venv_path): yield @contextmanager def project(): """ Runs commands within the project's directory. """ with virtualenv(): with cd(env.proj_path): yield @contextmanager def update_changed_requirements(): """ Checks for changes in the requirements file across an update, and gets new requirements if changes have occurred. """ reqs_path = join(env.proj_path, env.reqs_path) get_reqs = lambda: run("cat %s" % reqs_path, show=False) old_reqs = get_reqs() if env.reqs_path else "" yield if old_reqs: new_reqs = get_reqs() if old_reqs == new_reqs: # Unpinned requirements should always be checked. for req in new_reqs.split("\n"): if req.startswith("-e"): if "@" not in req: # Editable requirement without pinned commit. break elif req.strip() and not req.startswith("#"): if not set(">=<") & set(req): # PyPI requirement without version. break else: # All requirements are pinned. return pip("-r %s/%s" % (env.proj_path, env.reqs_path)) ########################################### # Utils and wrappers for various commands # ########################################### def _print(output): print() print(output) print() def print_command(command): _print(blue("$ ", bold=True) + yellow(command, bold=True) + red(" ->", bold=True)) @task def run(command, show=True, *args, **kwargs): """ Runs a shell comand on the remote server. """ if show: print_command(command) with hide("running"): return _run(command, *args, **kwargs) @task def sudo(command, show=True, *args, **kwargs): """ Runs a command as sudo on the remote server. """ if show: print_command(command) with hide("running"): return _sudo(command, *args, **kwargs) def log_call(func): @wraps(func) def logged(*args, **kawrgs): header = "-" * len(func.__name__) _print(green("\n".join([header, func.__name__, header]), bold=True)) return func(*args, **kawrgs) return logged def get_templates(): """ Returns each of the templates with env vars injected. """ injected = {} for name, data in templates.items(): injected[name] = dict([(k, v % env) for k, v in data.items()]) return injected def upload_template_and_reload(name): """ Uploads a template only if it has changed, and if so, reload the related service. """ template = get_templates()[name] local_path = template["local_path"] if not os.path.exists(local_path): project_root = os.path.dirname(os.path.abspath(__file__)) local_path = os.path.join(project_root, local_path) remote_path = template["remote_path"] reload_command = template.get("reload_command") owner = template.get("owner") mode = template.get("mode") remote_data = "" if exists(remote_path): with hide("stdout"): remote_data = sudo("cat %s" % remote_path, show=False) with open(local_path, "r") as f: local_data = f.read() # Escape all non-string-formatting-placeholder occurrences of '%': local_data = re.sub(r"%(?!\(\w+\)s)", "%%", local_data) if "%(db_pass)s" in local_data: env.db_pass = db_pass() local_data %= env clean = lambda s: s.replace("\n", "").replace("\r", "").strip() if clean(remote_data) == clean(local_data): return upload_template(local_path, remote_path, env, use_sudo=True, backup=False) if owner: sudo("chown %s %s" % (owner, remote_path)) if mode: sudo("chmod %s %s" % (mode, remote_path)) if reload_command: sudo(reload_command) def rsync_upload(): """ Uploads the project with rsync excluding some files and folders. """ excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage", "local_settings.py", "/static", "/.git", "/.hg"] local_dir = os.getcwd() + os.sep return rsync_project(remote_dir=env.proj_path, local_dir=local_dir, exclude=excludes) def vcs_upload(): """ Uploads the project with the selected VCS tool. """ if env.deploy_tool == "git": remote_path = "ssh://%s@%s%s" % (env.user, env.host_string, env.repo_path) if not exists(env.repo_path): run("mkdir -p %s" % env.repo_path) with cd(env.repo_path): run("git init --bare") local("git push -f %s master" % remote_path) with cd(env.repo_path): run("GIT_WORK_TREE=%s git checkout -f master" % env.proj_path) run("GIT_WORK_TREE=%s git reset --hard" % env.proj_path) elif env.deploy_tool == "hg": remote_path = "ssh://%s@%s/%s" % (env.user, env.host_string, env.repo_path) with cd(env.repo_path): if not exists("%s/.hg" % env.repo_path): run("hg init") print(env.repo_path) with fab_settings(warn_only=True): push = local("hg push -f %s" % remote_path) if push.return_code == 255: abort() run("hg update") def db_pass(): """ Prompts for the database password if unknown. """ if not env.db_pass: env.db_pass = getpass("Enter the database password: ") return env.db_pass @task def apt(packages): """ Installs one or more system packages via apt. """ return sudo("apt-get install -y -q " + packages) @task def pip(packages): """ Installs one or more Python packages within the virtual environment. """ with virtualenv(): return run("pip install %s" % packages) def postgres(command): """ Runs the given command as the postgres user. """ show = not command.startswith("psql") return sudo(command, show=show, user="postgres") @task def psql(sql, show=True): """ Runs SQL against the project's database. """ out = postgres('psql -c "%s"' % sql) if show: print_command(sql) return out @task def backup(filename): """ Backs up the project database. """ tmp_file = "/tmp/%s" % filename # We dump to /tmp because user "postgres" can't write to other user folders # We cd to / because user "postgres" might not have read permissions # elsewhere. with cd("/"): postgres("pg_dump -Fc %s > %s" % (env.proj_name, tmp_file)) run("cp %s ." % tmp_file) sudo("rm -f %s" % tmp_file) @task def restore(filename): """ Restores the project database from a previous backup. """ return postgres("pg_restore -c -d %s %s" % (env.proj_name, filename)) @task def python(code, show=True): """ Runs Python code in the project's virtual environment, with Django loaded. """ setup = "import os;" \ "os.environ[\'DJANGO_SETTINGS_MODULE\']=\'%s.settings\';" \ "import django;" \ "django.setup();" % env.proj_app full_code = 'python -c "%s%s"' % (setup, code.replace("`", "\\\`")) with project(): if show: print_command(code) result = run(full_code, show=False) return result def static(): """ Returns the live STATIC_ROOT directory. """ return python("from django.conf import settings;" "print(settings.STATIC_ROOT)", show=False).split("\n")[-1] @task def manage(command): """ Runs a Django management command. """ return run("%s %s" % (env.manage, command)) ########################### # Security best practices # ########################### @task @log_call @hosts(["root@%s" % host for host in env.hosts]) def secure(new_user=env.user): """ Minimal security steps for brand new servers. Installs system updates, creates new user (with sudo privileges) for future usage, and disables root login via SSH. """ run("apt-get update -q") run("apt-get upgrade -y -q") run("adduser --gecos '' %s" % new_user) run("usermod -G sudo %s" % new_user) run("sed -i 's:RootLogin yes:RootLogin no:' /etc/ssh/sshd_config") run("service ssh restart") print(green("Security steps completed. Log in to the server as '%s' from " "now on." % new_user, bold=True)) ######################### # Install and configure # ######################### @task @log_call def install(): """ Installs the base system and Python requirements for the entire server. """ # Install system requirements sudo("apt-get update -y -q") apt("nginx libjpeg-dev python-dev python-setuptools git-core " "postgresql libpq-dev memcached supervisor python-pip") run("mkdir -p /home/%s/logs" % env.user) # Install Python requirements sudo("pip install -U pip virtualenv virtualenvwrapper mercurial") # Set up virtualenv run("mkdir -p %s" % env.venv_home) run("echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc" % (env.venv_home, env.user)) run("echo 'source /usr/local/bin/virtualenvwrapper.sh' >> " "/home/%s/.bashrc" % env.user) print(green("Successfully set up git, mercurial, pip, virtualenv, " "supervisor, memcached.", bold=True)) @task @log_call def create(): """ Creates the environment needed to host the project. The environment consists of: system locales, virtualenv, database, project files, SSL certificate, and project-specific Python requirements. """ # Generate project locale locale = env.locale.replace("UTF-8", "utf8") with hide("stdout"): if locale not in run("locale -a"): sudo("locale-gen %s" % env.locale) sudo("update-locale %s" % env.locale) sudo("service postgresql restart") run("exit") # Create project path run("mkdir -p %s" % env.proj_path) # Set up virtual env run("mkdir -p %s" % env.venv_home) with cd(env.venv_home): if exists(env.proj_name): if confirm("Virtualenv already exists in host server: %s" "\nWould you like to replace it?" % env.proj_name): run("rm -rf %s" % env.proj_name) else: abort() run("virtualenv %s" % env.proj_name) # Upload project files if env.deploy_tool in env.vcs_tools: vcs_upload() else: rsync_upload() # Create DB and DB user pw = db_pass() user_sql_args = (env.proj_name, pw.replace("'", "\'")) user_sql = "CREATE USER %s WITH ENCRYPTED PASSWORD '%s';" % user_sql_args psql(user_sql, show=False) shadowed = "*" * len(pw) print_command(user_sql.replace("'%s'" % pw, "'%s'" % shadowed)) psql("CREATE DATABASE %s WITH OWNER %s ENCODING = 'UTF8' " "LC_CTYPE = '%s' LC_COLLATE = '%s' TEMPLATE template0;" % (env.proj_name, env.proj_name, env.locale, env.locale)) # Set up SSL certificate if not env.ssl_disabled: conf_path = "/etc/nginx/conf" if not exists(conf_path): sudo("mkdir %s" % conf_path) with cd(conf_path): crt_file = env.proj_name + ".crt" key_file = env.proj_name + ".key" if not exists(crt_file) and not exists(key_file): try: crt_local, = glob(join("deploy", "*.crt")) key_local, = glob(join("deploy", "*.key")) except ValueError: parts = (crt_file, key_file, env.domains[0]) sudo("openssl req -new -x509 -nodes -out %s -keyout %s " "-subj '/CN=%s' -days 3650" % parts) else: upload_template(crt_local, crt_file, use_sudo=True) upload_template(key_local, key_file, use_sudo=True) # Install project-specific requirements upload_template_and_reload("settings") with project(): if env.reqs_path: pip("-r %s/%s" % (env.proj_path, env.reqs_path)) pip("gunicorn setproctitle psycopg2 " "django-compressor python-memcached") # Bootstrap the DB manage("createdb --noinput --nodata") python("from django.conf import settings;" "from django.contrib.sites.models import Site;" "Site.objects.filter(id=settings.SITE_ID).update(domain='%s');" % env.domains[0]) for domain in env.domains: python("from django.contrib.sites.models import Site;" "Site.objects.get_or_create(domain='%s');" % domain) if env.admin_pass: pw = env.admin_pass user_py = ("from django.contrib.auth import get_user_model;" "User = get_user_model();" "u, _ = User.objects.get_or_create(username='admin');" "u.is_staff = u.is_superuser = True;" "u.set_password('%s');" "u.save();" % pw) python(user_py, show=False) shadowed = "*" * len(pw) print_command(user_py.replace("'%s'" % pw, "'%s'" % shadowed)) return True @task @log_call def remove(): """ Blow away the current project. """ if exists(env.venv_path): run("rm -rf %s" % env.venv_path) if exists(env.proj_path): run("rm -rf %s" % env.proj_path) for template in get_templates().values(): remote_path = template["remote_path"] if exists(remote_path): sudo("rm %s" % remote_path) if exists(env.repo_path): run("rm -rf %s" % env.repo_path) sudo("supervisorctl update") psql("DROP DATABASE IF EXISTS %s;" % env.proj_name) psql("DROP USER IF EXISTS %s;" % env.proj_name) ############## # Deployment # ############## @task @log_call def restart(): """ Restart gunicorn worker processes for the project. If the processes are not running, they will be started. """ pid_path = "%s/gunicorn.pid" % env.proj_path if exists(pid_path): run("kill -HUP `cat %s`" % pid_path) else: sudo("supervisorctl update") @task @log_call def deploy(): """ Deploy latest version of the project. Backup current version of the project, push latest version of the project via version control or rsync, install new requirements, sync and migrate the database, collect any new static assets, and restart gunicorn's worker processes for the project. """ if not exists(env.proj_path): if confirm("Project does not exist in host server: %s" "\nWould you like to create it?" % env.proj_name): create() else: abort() # Backup current version of the project with cd(env.proj_path): backup("last.db") if env.deploy_tool in env.vcs_tools: with cd(env.repo_path): if env.deploy_tool == "git": run("git rev-parse HEAD > %s/last.commit" % env.proj_path) elif env.deploy_tool == "hg": run("hg id -i > last.commit") with project(): static_dir = static() if exists(static_dir): run("tar -cf static.tar --exclude='*.thumbnails' %s" % static_dir) else: with cd(join(env.proj_path, "..")): excludes = ["*.pyc", "*.pio", "*.thumbnails"] exclude_arg = " ".join("--exclude='%s'" % e for e in excludes) run("tar -cf {0}.tar {1} {0}".format(env.proj_name, exclude_arg)) # Deploy latest version of the project with update_changed_requirements(): if env.deploy_tool in env.vcs_tools: vcs_upload() else: rsync_upload() with project(): manage("collectstatic -v 0 --noinput") manage("migrate --noinput") for name in get_templates(): upload_template_and_reload(name) restart() return True @task @log_call def rollback(): """ Reverts project state to the last deploy. When a deploy is performed, the current state of the project is backed up. This includes the project files, the database, and all static files. Calling rollback will revert all of these to their state prior to the last deploy. """ with update_changed_requirements(): if env.deploy_tool in env.vcs_tools: with cd(env.repo_path): if env.deploy_tool == "git": run("GIT_WORK_TREE={0} git checkout -f " "`cat {0}/last.commit`".format(env.proj_path)) elif env.deploy_tool == "hg": run("hg update -C `cat last.commit`") with project(): with cd(join(static(), "..")): run("tar -xf %s/static.tar" % env.proj_path) else: with cd(env.proj_path.rsplit("/", 1)[0]): run("rm -rf %s" % env.proj_name) run("tar -xf %s.tar" % env.proj_name) with cd(env.proj_path): restore("last.db") restart() @task @log_call def all(): """ Installs everything required on a new system and deploy. From the base software, up to the deployed project. """ install() if create(): deploy()
cf8e3b2dfb07d898fce0df31b2120019d2d38b58
c621431df46c912c67036cbbae6564a0bd83502d
/python/Programmers/같은숫자는싫어.py
eac4f2ca2e5c861dc799d39d78d929815c7f7d75
[]
no_license
tmdtlr7031/AlgorismRepo
68d4528fefe86d0428a360ff569921f9893c98f7
e76efb3561021264373161e9c974e6ee101bac8c
refs/heads/master
2023-08-14T00:54:43.544714
2021-09-08T09:55:58
2021-09-08T09:55:58
378,771,394
0
0
null
null
null
null
UTF-8
Python
false
false
412
py
# 같은 숫자는 싫어 https://programmers.co.kr/learn/courses/30/lessons/12906 # 해당값이 이전값이랑 다를때만 추가 def solution(arr): answer = [arr[0]] for i in range(1,len(arr)): if arr[i] == answer[-1]: continue else: answer.append(arr[i]) return answer print(solution([1,1,3,3,0,1,1])) # [1,3,0,1] print(solution([4,4,4,3,3])) # [4,3]
6076de3e9f84a89948301087084bcdb76ce774e9
ffa9bada806a6330cfe6d2ab3d7decfc05626d10
/Others/Mssctf2020Final/easy_block.py
a9d5d9304cee26b67a020b883274463231d34346
[ "MIT" ]
permissive
James3039/OhMyCodes
064ef03d98384fd8d57c7d64ed662f51218ed08e
f25d7a5e7438afb856035cf758ab43812d5bb600
refs/heads/master
2023-07-15T15:52:45.419938
2021-08-28T03:37:27
2021-08-28T03:37:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,591
py
from Crypto.Cipher import AES from Crypto.Util.number import long_to_bytes from random import getrandbits from binascii import hexlify, unhexlify import os key = long_to_bytes(getrandbits(128)) iv = long_to_bytes(getrandbits(128)) XOR = lambda s1, s2: bytes([x1 ^ x2 for x1, x2 in zip(s1, s2)]) def pad(plain): padlen = 16 - len(plain) % 16 return plain + bytes([padlen] * padlen) def unpad(cipher): padlen = cipher[-1] for i in range(1, padlen): if cipher[-i] != padlen: print('padding check fail') return 0 return cipher[:-padlen] def my_cbc_enc(plain): plain = pad(plain) plainblocks = [plain[i * 16:i * 16 + 16] for i in range(len(plain) // 16)] cipherblocks = [] tmpiv = iv aes = AES.new(key, AES.MODE_ECB) for i in range(len(plainblocks)): cipherblocks.append(XOR(tmpiv, aes.encrypt(plainblocks[i]))) tmpiv = cipherblocks[-1] return b''.join(cipherblocks) def my_cbc_dec(cipher): assert len(cipher) % 16 == 0 aes = AES.new(key, AES.MODE_ECB) cipherblocks = [iv] + [cipher[i * 16:i * 16 + 16] for i in range(len(cipher) // 16)] plainblocks = [] for i in range(1, len(cipherblocks)): tempcipher = XOR(cipherblocks[i], cipherblocks[i - 1]) plainblocks.append(aes.decrypt(tempcipher)) plain = b''.join(plainblocks) print(plain) return unpad(plain) def signup(usercount): print("user name:") name = input().encode() cookie = 'username=' + \ hexlify(name).decode() + \ ';is_admin=0;user_id=mss2020_{};'.format(usercount) print(hexlify(my_cbc_enc(cookie.encode()))) usercount += 1 def check(): print("user name:") name = input().encode() print('cookie:(in hex)') cookie = input().encode() cookie = my_cbc_dec(unhexlify(cookie)) print(cookie) if cookie == 0: return cookielist = cookie.split(b';') print(cookielist) username = cookielist[0].split(b'=')[1] admin = cookielist[1].split(b'=')[1] if name != unhexlify(username): print('name error') else: if int(admin) == 1: print(os.getenv('FLAG')) else: print('login success') if __name__ == "__main__": usercount = 0 while 1: print('what do you want to do?') print('1.signup') print('2.login') print('3.exit') choice = input() if choice == '1': signup(usercount) elif choice == '2': check() else: exit(0)
09b1ae0b84b353ffa7dc2cdbc9579946e71c96d0
fa259bfe4f9220a70c105cd68e93e53aa0064ab8
/06- Condities/Blad steen schaar.py
05711c8e5e2013ad7c416bb678bed84ef7323db2
[]
no_license
femkepiepers/Informatica5
427b1d189f33f2e9761a45492178a7c17657efd8
9b6d870cd3f80307132b898f9344d4b45b611a31
refs/heads/master
2021-06-28T22:35:17.021932
2019-05-23T08:03:28
2019-05-23T08:03:28
147,637,112
0
0
null
null
null
null
UTF-8
Python
false
false
555
py
# invoer speler_1 = input('Speler 1: ') speler_2 = input('Speler 2: ') # uitvoer if speler_1 == 'blad': if speler_2 == 'steen': print('speler 1 wint') if speler_2 == 'schaar': print('speler 2 wint') if speler_1 == 'steen': if speler_2 == 'schaar': print('speler 1 wint') if speler_2 == 'blad': print('speler 2 wint') if speler_1 == 'schaar': if speler_2 == 'blad': print('speler 1 wint') if speler_2 == 'steen': print('speler 2 wint') if speler_1 == speler_2: print('onbeslist')
6663f3b4e8e52135aa96e8e29e7c66ad45dba0ab
b15a706639cf9d3b8691b02ece329a57936e47b7
/wisdompets/adoptions/migrations/0001_initial.py
ecbff520436d42eb1af798a9b32d4d9330f06a40
[ "MIT" ]
permissive
lopes-andre/wisdom-pets-django
d582cd0eb2527de3ac4093674b062b81ed70cb77
9fabeeb2a338eb9b0197317f8ac7e3c45964f99e
refs/heads/main
2023-08-11T09:38:52.641746
2021-09-22T15:50:02
2021-09-22T15:50:02
409,004,938
0
0
null
null
null
null
UTF-8
Python
false
false
1,346
py
# Generated by Django 3.2.7 on 2021-09-22 00:21 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Vaccine', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Pet', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('submitter', models.CharField(max_length=100)), ('species', models.CharField(max_length=100)), ('breed', models.CharField(blank=True, max_length=30)), ('description', models.TextField()), ('sex', models.CharField(blank=True, choices=[('M', 'Male'), ('F', 'Female')], max_length=1)), ('submission_date', models.DateTimeField()), ('age', models.IntegerField(null=True)), ('vaccinations', models.ManyToManyField(blank=True, to='adoptions.Vaccine')), ], ), ]
424acc778cb6fe01fdf4b89d796e7d4c20b8dfd6
53dc2397acd656f789d39f2f8869033d882f287c
/nenetelecom/asgi.py
166fbc33e6511eeda3c45456e04008ef24c7c350
[]
no_license
butadpj/nenetelecom-final
68bca1c5ba2054cf039d851bbe727905d47c44fe
f5abcf366ab7f4cdb8254031b9ec104a8f1ab7c5
refs/heads/master
2023-06-20T04:00:31.264911
2021-07-16T09:57:58
2021-07-16T09:57:58
328,732,805
3
0
null
2021-07-16T09:30:13
2021-01-11T16:58:01
JavaScript
UTF-8
Python
false
false
399
py
""" ASGI config for nenetelecom project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nenetelecom.settings') application = get_asgi_application()
ab20b2c35f9249a760302e3bbdaa026df26cc937
e39e7c8ceeed4347eac2cf985404a46edc1139c1
/characterCount.py
6597df64676f45548e2d09ce10039206b79aa8a5
[]
no_license
crtek6515/SampleProject
0241eb7be719e6d2392dd7635507a6774bdc9a76
d9485aa1893e1c780416b6c85e4f74bd8e6cb83d
refs/heads/master
2020-07-16T04:37:19.415532
2019-09-26T19:33:43
2019-09-26T19:33:43
205,720,619
0
0
null
null
null
null
UTF-8
Python
false
false
196
py
import pprint print('Enter a phrase: ') message = input() count = {} for character in message: count.setdefault(character,0) count[character] = count[character] + 1 pprint.pprint(count)
14d20dc585bcb6cd2babfeab01ef3caaff1221be
8ef8e6818c977c26d937d09b46be0d748022ea09
/cv/distiller/CWD/pytorch/mmrazor/tools/visualizations/vis_configs/fpn_feature_visualization.py
40b6b3f1b4127a80636e1072673b338d9e717501
[ "Apache-2.0" ]
permissive
Deep-Spark/DeepSparkHub
eb5996607e63ccd2c706789f64b3cc0070e7f8ef
9d643e88946fc4a24f2d4d073c08b05ea693f4c5
refs/heads/master
2023-09-01T11:26:49.648759
2023-08-25T01:50:18
2023-08-25T01:50:18
534,133,249
7
6
Apache-2.0
2023-03-28T02:54:59
2022-09-08T09:07:01
Python
UTF-8
Python
false
false
322
py
# Copyright (c) OpenMMLab. All rights reserved. recorders = dict( neck=dict(_scope_='mmrazor', type='ModuleOutputs', source='neck')) mappings = dict( p3=dict(recorder='neck', data_idx=0), p4=dict(recorder='neck', data_idx=1), p5=dict(recorder='neck', data_idx=2), p6=dict(recorder='neck', data_idx=3))
674c0c4af4ae92d5d0eaa724b79d091b4204fc15
9eb7250337b8dfec7e9b7bda1496a1bddea11a75
/src/migrations/0001_initial.py
2b31fa2f76825631cca28cd4c962d7fc961abe51
[]
no_license
Dinesh-Sunny/Twitter-Django-Project
a58f53fa170b478405b1b38cfb5eb05e8b5ecde0
86fee67a1f030bb2c8fe8c4f216ef177d7599956
refs/heads/master
2021-01-10T18:03:59.928367
2015-10-05T10:49:16
2015-10-05T10:49:16
43,668,845
0
0
null
null
null
null
UTF-8
Python
false
false
801
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_profile', '0001_initial'), ] operations = [ migrations.CreateModel( name='Tweet', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('text', models.TextField(max_length=160)), ('created_date', models.DateTimeField(auto_now_add=True)), ('country', models.CharField(max_length=30)), ('is_active', models.BooleanField(default=True)), ('user', models.ForeignKey(to='user_profile.CustomUser')), ], ), ]
093602149c36eb1ac38880578e2e2a275049a056
9779c259467b5edf601a18c6168cfc91f4f25723
/SLSynthesis/demo_evaluation.py
ca19515f4bd05d356d59dce2a68e1847a54e1b33
[]
no_license
lgyxbmu/SignLanguageProcessing
d1ed69dde0890bbbe328349ec501a03add256296
a312367087b5ebf01a435ef513db3fe80d8438a2
refs/heads/master
2023-02-23T22:01:08.795650
2021-01-25T11:34:44
2021-01-25T11:34:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
945
py
import h5py import re import random import math import numpy import tensorflow as tf import keras from keras.models import Sequential, Model from keras.layers import Dense, Add, Dropout from keras import backend as K from keras.layers import Layer, Input, Bidirectional, LSTM, GRU, Embedding, Multiply, BatchNormalization, Concatenate, Add, Lambda, Subtract from keras.utils import to_categorical from modeling import * from data import * from training import * import accumulators from dtw import dtw, fakedtw from utils import * from model_FF_05 import * # loading model and evalueating on given set list_eval = loadList("data/stop.list") fname_model_weights = "models/%s.h5" % model_ID model4output.load_weights(fname_model_weights) errors, example, outputs = eval_dataset( list_eval, loader, model4output, model4example, funs_eval=len(ys)*[compute_errorMSEDTW] ) print(errors)
2a37d12c0882546c38539dbb0abd22a8e42b1e68
c467c183b77603c8b78e29cfdeac14d9b80636e7
/clean/model_neurons.py
f07bc730236e8ff013352d05e65b17783d54c580
[ "MIT" ]
permissive
tartavull/dcgan-completion.tensorflow
f58e1b7d598075077a9a3d184a3293c5722cafc8
9817251b4fb3e45b88e379dacea462e0d94a8190
refs/heads/master
2021-01-15T10:34:31.664327
2016-08-18T19:15:14
2016-09-01T21:59:55
66,017,192
0
1
null
2016-08-18T17:26:48
2016-08-18T17:26:47
null
UTF-8
Python
false
false
961
py
import tensorflow as tf from model_mnist import Model class ModelNeurons(Model): def create_summaries(self, d_loss_real, d_loss_fake, g_loss, d_real, d_fake, real_images, fake_images): with tf.variable_scope("summary"): scalars = [tf.scalar_summary(name, var) for name, var in [("d_loss_real",d_loss_real), ("d_loss_fake",d_loss_fake), ("d_loss_total",self.d_loss_total), ("g_loss_total",g_loss)]] hist = [tf.histogram_summary(name, var) for name, var in [("d_real", d_real),("d_fake", d_fake),("z",self.z)]] fullres = [tf.image_summary(name, tf.reshape(var,shape=(self.batch_size, 32, 32*32, 1))) for name, var in [("fullres_real", real_images),("fullres_fake", fake_images)]] self.summary = tf.merge_summary(scalars+fullres+hist)
eba57eacafb7808fb4f7908291688744193fe32d
ef853b56521b876bb0a6de05a3c5a0b83dd4ba96
/task_3.py
5c4b19a9b0c766f405914dc93c4a00ef7a3331f1
[]
no_license
IvanCher-py/python-algorithms
976c92358167b870f9948c89337821ffbcf404d8
e1342786cd9970c08639d1e09a42be2a7c88cbd4
refs/heads/master
2022-12-08T14:19:05.325281
2020-09-07T15:35:39
2020-09-07T15:35:39
286,553,483
0
0
null
2020-09-07T15:36:28
2020-08-10T18:44:23
Python
UTF-8
Python
false
false
547
py
# 3. По введенным пользователем координатам двух точек вывести # уравнение прямой вида y = kx + b, проходящей через эти точки. x1, y1 = map(int, input('Введитe координаты точки A(x1, y1) через пробел: ').split()) x2, y2 = map(int, input('Введитe координаты точки B(x2, y2) через пробел: ').split()) k = int((y1 - y2) / (x1 - x2)) b = int(y1 - k * x1) print(f'y = {k} * x + {b}')
3e1a820542fafe4555459b74d2b94fb2a21872f3
34e0de84a39ed9295e22ec3984ca732bd329b556
/src/ms_perception/scripts/include/viz_utils.py
100a4e1390338515d8ae8a46fdc609e3b43e75f0
[]
no_license
cpuwanan/motion_prediction_from_imu
75e47a068934c9c92adca8f394500884d31ec0a8
7be62e78a18d48f1a89002b56979220c6cdc4b94
refs/heads/master
2022-12-24T03:47:05.471249
2020-10-06T07:56:03
2020-10-06T07:56:03
297,292,503
0
0
null
null
null
null
UTF-8
Python
false
false
279
py
#!/home/msasrock/.virtualenvs/ros-melodic-venv/bin/python import rospy import sys, os import numpy as np LIGHT_RED='\033[1;31m' LIGHT_GREEN='\033[1;32m' LIGHT_YELLOW='\033[1;33m' LIGHT_BLUE='\033[1;34m' LIGHT_PURPLE='\033[1;35m' LIGHT_CYAN='\033[1;36m' NC='\033[0m' # No Color
690956e8de79c765c018ae0135a1d154b12435b6
3bc38b6fc9570217143d056762be4bf52db2eb1f
/leetcode_practice/617.py
4777154a3cdb0371e734b814956b37430a0b0913
[]
no_license
yangyuebfsu/ds_study
6638c260dfdb4a94365c2007d302833b455a4a59
883f9bab2dbce4f80f362c30b8564a942f66fb1e
refs/heads/master
2021-02-07T13:20:54.773840
2021-01-21T05:55:09
2021-01-21T05:55:09
244,031,249
0
0
null
null
null
null
UTF-8
Python
false
false
1,380
py
'''617. Merge Two Binary Trees Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def mergeTrees(self, t1, t2): if t1 and t2: root = TreeNode(t1.val + t2.val) root.left = self.mergeTrees(t1.left, t2.left) root.right = self.mergeTrees(t1.right, t2.right) return root else: return t1 or t2
c71753b37bee7054f0072bec83f8636d789a0220
b4a5b5910a4dac28683bf5a5961e258c7c3992a1
/backend/admin.py
585e24e078d831c5a0cc47ede55a2ed530075a56
[]
no_license
CavidRzayev/drf_channels_example
9ed858596c33aa94b6011e9933add29e9dff3f01
a15c185dd94dae95ab045163afe60c8e3b860e98
refs/heads/main
2022-12-26T23:19:42.576598
2020-10-07T03:18:07
2020-10-07T03:18:07
301,915,102
0
0
null
null
null
null
UTF-8
Python
false
false
205
py
from django.contrib import admin from .models import * # Register your models here. admin.site.register(Room) admin.site.register(Chat) admin.site.register(DirectMessage) admin.site.register(Notifications)
9b3486a1d209c9d20997c2acd70bf5e8c4a65e33
7080b8bee79400249865a9f551002f8f9dad66aa
/helpers/coord.py
60bf83e53b0400bb2df0d7c0821bbe578be4ebc0
[]
no_license
js837/chess
6769f3c4c36f8382a62ae11366d09096ac986e67
b6a931ccc6f212e8c0218fff820e1f8d4f51e408
refs/heads/master
2016-09-16T00:27:27.130550
2015-02-19T22:45:36
2015-02-19T22:45:36
27,016,562
0
0
null
null
null
null
UTF-8
Python
false
false
962
py
import operator def get_rank_file(coord): return 'abcdefgh'[coord[1]] + '12345678'[coord[0]] def get_coord_from_rank_file(rank_file_str): return '12345678'.index(rank_file_str[1]), 'abcdefgh'.index(rank_file_str[0]) def is_valid_sqaure(coord): """Check that coordinate is is valid sqaure""" return 0 <= coord[0] <= 7 and 0 <= coord[1] <= 7 class Coord(tuple): """ Basic coordinate class, length 2 to allow adding of 2-tuples """ @staticmethod def __new__(cls, x, y): # Creation via args return tuple.__new__(cls, (x,y)) def __add__(self, other): return Coord(self[0]+other[0], self[1]+other[1]) def __sub__(self, other): return Coord(self[0]-other[0], self[1]-other[1]) N, E, S, W, NE, SE, SW, NW, N2, S2 = Coord(1,0), Coord(0,1), Coord(-1,0), Coord(0,-1), Coord(1,1), Coord(-1,1),\ Coord(-1, -1), Coord(1, -1), Coord(2, 0), Coord(-2,0)
50378130f4a6e07659ab9efedc057bb796ee3221
c6b34e40381d076de3a452dcd5d77eae5067172b
/CorpusBuilder/test_aplac.py
5bbcca3149e04623668b774cab2a50598ec6457a
[]
no_license
ryuji-konishi/AplacChat
81697d827c5fae0d70100a6efda4bd7330e8ae47
aae39f534ee1cfd9a773698fe6b4fe65bbe9555e
refs/heads/master
2022-09-05T23:16:06.952447
2022-09-03T03:47:13
2022-09-03T03:47:13
113,262,458
0
0
null
null
null
null
UTF-8
Python
false
false
2,080
py
import sys sys.path.insert(0, '..\\') # This is required to import common import unittest import aplac.aplac as aplac class TestAplac(unittest.TestCase): def setUp(self): pass def test_regex_trim_both(self): result = aplac.regex_trim(u"ESSAY 452/(1) 〜あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"Part 01:あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"2.あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"1-1.あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"[email protected]あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"Copyright 1996あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"日本/あいう", aplac.regexs_both) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"", aplac.regexs_both) self.assertEqual(result, u"") def test_regex_trim_source(self): result = aplac.regex_trim(u"!#%&)*+,-./:;=>?@\\]^_`|}~あいう", aplac.regexs_src) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"¢¤§¨­®°±´¸×÷‐―‥…※℃ⅠⅡⅢⅣ←↑→↓⇔∀−∥∪≒≠≦≪≫━■□▲△▼▽◆◇○◎●◯★☆♪♬♭あいう", aplac.regexs_src) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"、。々〇〉》」』】〒〕〜゛゜・ー㎡!#%&)*+,-./:;=>?@\]^_`}~」、あいう", aplac.regexs_src) self.assertEqual(result, u"あいう") result = aplac.regex_trim(u"/あ/い・う*え#お", aplac.regexs_src) self.assertEqual(result, u"あいうえお") if __name__ == "__main__": unittest.main()
8caa5127bdd6d173458daa06880b3b365689cc24
bc8728fe6ec87d6acf83ba970bc24382ce843b4a
/netconf/test/netconfd/agt-commit-complete/session.py
09bfb545990c0f44cba3726d22c5f042c12d3b0b
[ "BSD-3-Clause" ]
permissive
xianyuesuifeng/yuma123
a734beea7dc8cb31608ef6dde6afac5847dc8f18
63b79846e3012aba3d695132a1cc89a5caf93b96
refs/heads/master
2020-12-11T23:51:59.060591
2020-01-11T19:11:05
2020-01-11T19:11:05
233,988,531
1
0
null
2020-01-15T03:17:03
2020-01-15T03:17:02
null
UTF-8
Python
false
false
552
py
from yangcli import yangcli from lxml import etree import yangrpc import sys import os conn = yangrpc.connect("127.0.0.1", 830, os.getenv('USER'), None, os.getenv('HOME')+"/.ssh/id_rsa.pub", os.getenv('HOME')+"/.ssh/id_rsa",) if(conn==None): print("Error: yangrpc failed to connect!") sys.exit(1) result=yangcli(conn, "commit") assert(result.xpath('./ok')) yangcli(conn, "replace /system/hostname value='ok3'") yangcli(conn, "replace /system/location value='ok4'") result=yangcli(conn, "commit") assert(result.xpath('./ok')) print("Done.")
145e759913c28d7860cbdd5cab7ca14dc36e38ed
7a50ba928c08bbec6d5825d3c701216bd6095f0e
/shell.py
b564d2db92b02693733718b2672240f2c135a9eb
[ "MIT" ]
permissive
kawasaki2013/networkzero
083a0c690fd56fdb4fc879b7d3dde1af78807fcd
bc4febb57cc0c6b14dcc03b4f716a680f90b69ee
refs/heads/master
2021-01-01T17:28:59.484956
2016-06-13T08:43:22
2016-06-13T08:43:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
499
py
#!python3 import zmq import networkzero as nw0 import logging logger = logging.getLogger("networkzero") handler = logging.FileHandler("network.log", encoding="utf-8") handler.setFormatter(logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")) handler.setLevel(logging.DEBUG) logger.addHandler(handler) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(levelname)s %(message)s")) handler.setLevel(logging.INFO) logger.addHandler(handler) del handler, logging
cbbe2723b9194cec6c8f486e68c16ae366864fea
1d377f9ca1ff56cd69d80a296e6b6fbb6061edb1
/functions/function11.py
30445f8f4de3a54acd537ae2a584a261142ed3b3
[]
no_license
mepujan/IWAssignment_1_python
c48b050f2883e7cc11c4283c31541f9fd2ad95d2
b7537c5ce9fc27cf7a75568b54f5bfdc94c5c57e
refs/heads/master
2022-11-15T01:15:11.292403
2020-06-24T04:26:03
2020-06-24T04:26:03
274,573,651
0
0
null
null
null
null
UTF-8
Python
false
false
483
py
# Write a Python program to create a lambda function that adds 15 to a given # number passed in as an argument, also create a lambda function that multiplies # argument x with argument y and print the result. def main(): num1=int(input("number1=")) num2=int(input("number2=")) result= lambda num: num + 15 product= lambda x,y: x * y print("Number 1 + 15 = ",result(num1)) print("Product of numbers=",product(num1,num2)) if __name__ == "__main__": main()
28995ae126480f28e5ec8b304eb1ed51f1f7ba57
44516b0ce08070cd51a59784ae60baea6ec094c3
/clases.py
8f1a76631e12a94cb4d9a57b1e742a21bafe62d9
[]
no_license
samir28/Proyectos-
0992da1aed2e0f5f1de69c367bd914217267b9a7
3d48cd350b7963dad542cbdd9e24655757ce5ab6
refs/heads/master
2021-04-28T15:11:20.729332
2018-02-19T16:54:54
2018-02-19T16:54:54
121,982,654
0
0
null
null
null
null
UTF-8
Python
false
false
955
py
class Estudiante: def __init__(self): self.carrera = [] self.legajo = [] def menu(self): opcion=0 while opcion !=4: print("1- cargar Estudiante") print("2- listar Estudiante") print("3- Finalizar programa") opcion = int(input("\n Ingrese su opcion: ")) if opcion==1: self.cargar() elif opcion==2: self.listar() def cargar(self): for x in range(5): car= input("Ingrese la carrera: ") self.carrera.append(car) leg= int(input("Ingrese su legajo: ")) self.legajo.append(leg) def listar(self): print("listado completo de los estudiantes") for x in range(5): print("Carrera: ", self.carrera[x]) print("Legajo: ",self.legajo[x]) print("------------") #bloque main alumno = Estudiante() alumno.menu()
3668f93957994a87fc751281c3c80a6b2ae7b5b7
f4f65978611b442c614450b9c68be7b469f34b89
/Airport.py
f4304f2329cda93390261c9258266674c48d751b
[]
no_license
obyrned1/COMP20230_DataStructuresAndAlgorithms_TermProject
bd3133bdb85cd91089c6920618d988c12ab8b5ea
ac74cbda7a914c09f692ee9751d30d648314c09a
refs/heads/master
2020-03-14T12:55:41.423320
2018-04-30T17:32:46
2018-04-30T17:32:46
131,621,813
0
0
null
null
null
null
UTF-8
Python
false
false
3,946
py
''' Created on 7 Mar 2018 @author: obyrned1 ''' import os.path import csv from math import pi,sin,cos,acos import pandas as pd import itertools from Currency import CurrencyAtlas from Aircraft import AircraftAtlas class Airport(): '''name, lat, long, code, maybe other attributes''' def __init__(self, code, country, airportName, airportLat, airportLong ): # the 5th column in the csv is the three letter airport code, index 4 self.code = code self.country = country self.airportName = airportName self.airportLat = airportLat self.airportLong = airportLong def getCode(self): return self.code def getCountry(self): return self.country def getName(self): return self.airportName def getLat(self): return float(self.airportLat) def getLong(self): return float(self.airportLong) class AirportAtlas(): def __init__(self, csvFile): # this should call loadData self.codes={} self.loadData(csvFile) def loadData(self, csvFile): '''creates a dictionary with relevant information from given csvFile''' with open(os.path.join(csvFile), "rt") as f: reader = csv.reader(f) for line in reader: self.codes[line[4]] = Airport(line[4], line[3], line[1], line[6], line[7]) def getAirport(self, code): '''returns the code for an airport''' return self.codes[code] def greatCircledlist(self, lat1, long1, lat2, long2): '''takes two lats and longs and gets the great circle distance between them''' radius_earth = 6371 #km theta1 = long1 * (2 * pi) / 360 theta2 = long2 * (2 * pi) /360 phi1 = (90 - lat1) * (2 * pi) /360 phi2 = (90 - lat2) * (2 * pi) /360 distance = acos(sin(phi1) * sin(phi2) * cos(theta1 - theta2) + cos(phi1) * cos(phi2)) * radius_earth return distance def getDistanceBetweenAirports(self,code1,code2): '''this method has to read two 3 digit codes, get the corresponding long and lat, then call the distanceBetweenPoints''' airA = self.getAirport(code1) lat1 = airA.getLat() long1 = airA.getLong() airB = self.getAirport(code2) lat2 = airB.getLat() long2 = airB.getLong() return self.greatCircledlist(lat1, long1, lat2, long2) def costOfTrip(self, rate, distance): '''calculate the cost of a single leg of a journey''' cost1 = float(rate) * float(distance) cost2 = float("{0:.2f}".format(cost1)) return cost2 def possibleCombinations(self, home, route): '''returns a dictionary will all possible route combinations''' # comboKeys is a dictionary that will hold all possible combinations of routes, where the key # is one of the 4 possible 2nd stop options, and the values are possible combinations, which all # start with the key (possible 2nd stop) comboKeys = {} #comboValues is an array that will hold these possible combinations comboValues = [] count = 0 for each in itertools.permutations(route): comboValues.append(home) comboValues.append(each) comboValues.append(home) count += 1 # there are six possible combinations of the 4 stops, starting with each possible 2nd stop # when it's reached 6, clear the array (comboValues), reset count, and start fresh with a new 2nd stop if count == 6: # set the value as the comboValues array, where the key is the 2nd stop option comboKeys[each[0]] = comboValues count = 0 comboValues = [] return comboKeys
6038d083723587703f593c35ab8365c94d697028
38a79b7211886bd1a726ab8525dc0ee7dfb7b4d7
/cisco_conf_parse/parse_bvi.py
fe7919172842e84d092d37b05f5bc3c2a4ea43fb
[]
no_license
saravana815/pyscripts
efc5e97ad9a19f24e4055d2cc74ab1704a2697b5
5fa8b514d3a07410f8fc29cd88f77babe62a675e
refs/heads/master
2021-06-23T15:37:10.598548
2021-02-05T14:24:46
2021-02-05T14:24:46
196,392,080
0
0
null
null
null
null
UTF-8
Python
false
false
903
py
#Usage - parse_conf.py ASR9K_run_cfg.txt IOS_device_run_cfg.txt import sys, os import re from ciscoconfparse import CiscoConfParse f1 = sys.argv[1] cf1 = CiscoConfParse(f1) print cf1 # intf_list = cf2.find_objects(r'^interface ') # print intf_list[0].text # ip_addr = '217.39.0.16' # print intf_list[0].re_search_children(r'ip address ' + ip_addr) def parse_bvi_int(cf_obj): intf_list = cf_obj.find_objects(r'^interface BVI') for intf in intf_list: print intf.text bvi_int_name = intf.text print bvi_int_name for child_obj in intf.children: if 'ipv4 address' in child_obj.text: print ' ip addr line found. swap ip address from XL' elif 'mac-address' in child_obj.text: print ' mac-address line found. swap mac address from XL' else: print child_obj.text parse_bvi_int(cf1)
620bc7976b15a630da40571a3ef802361ab0d78b
3d3bf8b6581f385bd0a5126e841b2f9cc5f52033
/src/chainalytic/zones/public-icon/aggregator/transform_registry/funded_wallets.py
7bc7a9dcf45989afb15522586833ff8f289cfe0d
[ "MIT" ]
permissive
pablock-chain/chainalytic-framework
2069ce48bc88743d3f342df70218a540c21dd807
195f236581806013a23fba9ddf0ab7a2a8221363
refs/heads/master
2023-06-04T12:13:28.567504
2020-08-06T09:57:01
2020-08-06T09:57:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,681
py
import json import time from typing import Dict, List, Optional, Set, Tuple, Union import traceback import plyvel from iconservice.icon_config import default_icon_config from iconservice.icon_constant import ConfigKey from iconservice.iiss.engine import Engine from chainalytic.aggregator.transform import BaseTransform from chainalytic.common import rpc_client, trie class Transform(BaseTransform): START_BLOCK_HEIGHT = 1 LAST_STATE_HEIGHT_KEY = b'last_state_height' MAX_WALLETS = 200 def __init__(self, working_dir: str, zone_id: str, transform_id: str): super(Transform, self).__init__(working_dir, zone_id, transform_id) async def execute(self, height: int, input_data: dict) -> Optional[Dict]: # Load transform cache to retrive previous staking state cache_db = self.transform_cache_db cache_db_batch = self.transform_cache_db.write_batch() # Make sure input block data represents for the next block of previous state cache prev_state_height = cache_db.get(Transform.LAST_STATE_HEIGHT_KEY) if prev_state_height: prev_state_height = int(prev_state_height) if prev_state_height != height - 1: await rpc_client.call_async( self.warehouse_endpoint, call_id='api_call', api_id='set_last_block_height', api_params={'height': prev_state_height, 'transform_id': self.transform_id}, ) return None # Create cache and storage data for genesis block 0 if height == 1: cache_db_batch.put(b'hx54f7853dc6481b670caf69c5a27c7c8fe5be8269', b'800460000') cache_db_batch.put(b'hx1000000000000000000000000000000000000000', b'0') cache_db_batch.write() await rpc_client.call_async( self.warehouse_endpoint, call_id='api_call', api_id='update_funded_wallets', api_params={ 'updated_wallets': { 'wallets': { 'hx54f7853dc6481b670caf69c5a27c7c8fe5be8269': '800460000', 'hx1000000000000000000000000000000000000000': '0', }, 'height': 0, }, 'transform_id': 'funded_wallets', }, ) # ################################################# txs = input_data['data'] # Example of `updated_wallets` # { # "ADDRESS_1": "100000.0", # "ADDRESS_2": "9999.9999", # } updated_wallets = {} for tx in txs: source_balance = cache_db.get(tx['from'].encode()) dest_balance = cache_db.get(tx['to'].encode()) value = tx['value'] source_balance = float(source_balance) if source_balance else 0 dest_balance = float(dest_balance) if dest_balance else 0 if source_balance >= value: source_balance -= value dest_balance += value updated_wallets[tx['from']] = str(source_balance) updated_wallets[tx['to']] = str(dest_balance) for addr, balance in updated_wallets.items(): cache_db_batch.put(addr.encode(), balance.encode()) cache_db_batch.put(Transform.LAST_STATE_HEIGHT_KEY, str(height).encode()) cache_db_batch.write() return { 'height': height, 'data': {}, 'misc': {'updated_wallets': {'wallets': updated_wallets, 'height': height}}, }
92c14450b47982a488328c3ffe2dc5aea68ce6b9
853b03f0debfec9972fee622115be70cf7de8e53
/src/problem_024.py
3a77d6110ae01dd4cdcf3850f2bb98c4a6ecbac1
[]
no_license
JakubTesarek/projecteuler
1b17a6a4a9935abab6534200904a5a654e48bfad
dbefd994c7782618ea77881c46bf2f8f569c9c68
refs/heads/master
2016-09-05T11:49:54.424409
2015-08-30T14:05:57
2015-08-30T14:05:57
41,150,830
0
0
null
null
null
null
UTF-8
Python
false
false
571
py
#!/usr/bin/env python """https://projecteuler.net/problem=24""" if __name__ == '__main__': permutation = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] max_index = len(permutation) - 1 for i in range(1, 1000000): for k in range(max_index, -1, -1): if k + 1 <= max_index and permutation[k] < permutation[k + 1]: for s in range(max_index, k, -1): if permutation[k] < permutation[s]: permutation[k], permutation[s] = permutation[s], permutation[k] permutation[k + 1:] = permutation[:k:-1] break break print("".join(str(n) for n in permutation))
b3959bbf021723541464f49acfdac54b3682c298
ca8de05117f82d84a9847828f5693560aa0bcfbe
/ProjectLab1.py
e5d36042e801bce53f936af05a7552934c6f96c5
[]
no_license
aciampi43/MUS3329X
dae783f10176aa6a7f08f56ce0d086b65cd67f71
a1b9b4cc11f4e73fcb209aca0314c976fec3bb0c
refs/heads/master
2020-04-17T12:45:04.236599
2019-04-25T03:17:48
2019-04-25T03:17:48
166,590,825
0
0
null
null
null
null
UTF-8
Python
false
false
2,982
py
from pyo import * #Tentative de construction de class à partire d'une fonction #L'Instrument est RCOsc, ligne 45 s = Server(sr=44100, nchnls=2, buffersize=512, duplex=1).boot() class AMS: #Phrases from Ave Maris Stella def __init__(self, mel): pit1 = midiToHz([62, 69, 71, 67, 69, 71, 74, 72, 71, 69, 67, 69]) pit2 = midiToHz([69, 69, 62, 64, 67, 65, 64, 62]) pit3 = midiToHz([65, 64, 67, 69, 69, 62, 64, 65, 62, 60]) pit4 = midiToHz([64, 67, 64, 65, 64, 62]) # frequence, duree, amplitude, velocity # Ave Maris Stella self.notes1 = [(pit1[0], 0.5, 0.05), (pit1[1], 0.5, 0.07), (pit1[2], 0.5, 0.05), (pit1[3], 0.5, 0.05), (pit1[4], 0.5, 0.07), (pit1[5], 0.5, 0.05), (pit1[6], 0.5, 0.08), (pit1[7], 0.5, 0.07), (pit1[8], 0.5, 0.06), (pit1[9], 0.5, 0.05), (pit1[10], 0.5, 0.04), (pit1[11], 0.8, 0.05)] #Dei Mater Alma self.notes2 = [(pit2[0], 0.5, 0.05), (pit2[1], 0.5, 0.05), (pit2[2], 0.5, 0.06), (pit2[3], 0.5, 0.05), (pit2[4], 0.5, 0.05), (pit2[5], 0.5, 0.06), (pit2[6], 0.5, 0.07),(pit2[7], 0.7, 0.06)] #Atque semper Virgo self.notes3 = [(pit3[0], 0.5, 0.08), (pit3[1], 0.5, 0.07), (pit3[2], 0.5, 0.05), (pit3[3], 0.5, 0.05), (pit3[4], 0.5, 0.05), (pit3[5], 0.5, 0.09), (pit3[6], 0.5, 0.08), (pit3[7], 0.5, 0.07), (pit3[8], 0.5, 0.06), (pit3[9],0.7, 0.05)] #Felix coeli porta self.notes4 = [(pit4[0], 0.5, 0.05), (pit4[1], 0.5, 0.05), (pit4[2], 0.5, 0.05), (pit4[3], 0.5, 0.05), (pit4[4], 0.8, 0.07), (pit4[5], 1.2, 0.06)] if mel ==1: phrase = self.notes1 elif mel ==2: phrase = self.notes2 elif mel ==3: phrase = self.notes3 elif mel ==4: phrase = self.notes4 return phrase #Partition starttime=0 oscs = [] def chant(): global starttime mel = phrase for note in mel: f = Fader(fadein=0.005, fadeout=0.25, mul=note[2]).play(dur=note[1], delay=starttime) o = Harmonizer(RCOsc(freq=note[0], mul=f).out(dur=note[1], delay=starttime)) oscs.append(o) # le depart de la note tout de suite apres la note precedente. starttime += note[1] return chant() #Partition def joue(): second = 0 def timeline(): global second chant() second += 1 pat = Pattern(timeline, time=1).play() return joue s.gui(locals()) """ #J'ajoute la classe Instrument Soprano. Comment les mettre ensemble? #Ça suffit de remplacer ROsc avec InstAlto...en ligne 45? #!/usr/bin/env python3 # encoding: utf-8 from pyo import * class InstAlto: #Constructeur pour InstAlto def __init__(self, freq, feedback, mul): self.freq = freq self.feedback = feedback self.Alto = SineLoop(freq, feedback, mul) def sig(self): return self.Alto s.gui(locals()) """
f8cc57d645d4b3f29115e64c6e368d84f18b2f3f
47e5ed378ee358bbcd6436ba9380e319de876420
/playground/simulate.py
d35c74d21bba8fc4a8a62f1dfb62fb81dc393282
[]
no_license
vishishtpriyadarshi/ShardEval
d16225b604bd3c8989abd5d3c1fa6cab12ccf991
54890ef8f4d22cf0c54bdca8ba1348fc30e5d203
refs/heads/main
2023-05-23T19:26:11.961506
2022-07-07T09:52:28
2022-07-07T09:52:28
450,803,771
11
5
null
null
null
null
UTF-8
Python
false
false
3,553
py
""" python simulate.py <params.json> <netDump.pkl> """ import sys import simpy import numpy as np import json import pickle as pkl from network.block import Block from network.network import Network from time import time def simulate(env, params): """Begin simulation""" net = Network("Blockchain", env, params) net.addNodes(params["numMiners"], params["numFullNodes"]) net.addPipes(params["numMiners"], params["numFullNodes"]) return net """Load parameters from params.json""" paramsFile = sys.argv[1] with open(paramsFile, "r") as f: params = f.read() params = json.loads(params) np.random.seed(7) start = time() env = simpy.Environment() net = simulate(env, params) env.run(until=params["simulationTime"]) net.displayChains() stop = time() totalNodes = params["numFullNodes"] + params["numMiners"] print("\n\n\t\t\t\t\t\tPARAMETERS") print(f"Number of Full nodes = {params['numFullNodes']}") print(f"Number of Miners = {params['numMiners']}") print(f"Degree of nodes = {totalNodes//2 + 1}") print(f"Simulation time = {params['simulationTime']} seconds") print("\t\t\t\t\t\tSIMULATION DATA") """Location distribution""" print("Location Distribution Data") for key, value in net.data["locationDist"].items(): print(f"{key} : {100*value/totalNodes}%") """Block Propagation""" print("\nBlock Propagation Data") blockPropData = [] for key, value in net.data["blockProp"].items(): blockPropData.append(value[1] - value[0]) print(f"{key} : {blockPropData[-1]} seconds") print(f"Mean Block Propagation time = {np.mean(blockPropData)} seconds") print(f"Median Block Propagation time = {np.median(blockPropData)} seconds") print(f"Minimum Block Propagation time = {np.min(blockPropData)} seconds") print(f"Maximum Block Propagation time = {np.max(blockPropData)} seconds") longestChain = [] longestChainNode = net.nodes["M0"] for node in net.nodes.values(): if len(node.blockchain) > len(longestChain): longestChainNode = node longestChain = node.blockchain numTxs = 0 for block in longestChain: numTxs += len(block.transactionList) meanBlockSize = (numTxs * 250) / len(longestChain) print(f"\nTotal number of Blocks = {len(longestChain)}") print(f"Mean block size = {meanBlockSize} bytes") print(f"Total number of Stale Blocks = {net.data['numStaleBlocks']}") print(f"Total number of Transactions = {net.data['numTransactions']}") txWaitTimes = [] txRewards = [] for block in longestChain: for transaction in block.transactionList: txRewards.append(transaction.reward) txWaitTimes.append(transaction.miningTime - transaction.creationTime) print(f"\nNode with longest chain = {longestChainNode.identifier}") print( f"Min waiting time = {np.min(txWaitTimes)} with reward = {txRewards[np.argmin(txWaitTimes)]}" ) print(f"Median waiting time = {np.median(txWaitTimes)}") print( f"Max waiting time = {np.max(txWaitTimes)} with reward = {txRewards[np.argmax(txWaitTimes)]}" ) print(f"\nNumber of forks observed = {net.data['numForks']}") print(f"\nSimulation Time = {stop-start} seconds") print(f"\nTPS = {numTxs/(stop-start)} seconds") toStore = net.nodes.copy() # netDump = {} # for node in net.nodes.values(): # netDump[node.identifier] = {} # netDump[node.identifier]["neighbourList"] = node.neighbourList # netDump[node.identifier]["location"] = node.location # netDump[node.identifier]["data"] = node.data # netDump[node.identifier]["blockchain"] = node.blockchain # with open(sys.argv[2], "wb") as f: # pkl.dump(netDump, f)
e17745af1f39b78fec2c4a8f6f23f6753f7cef38
f2a2f41641eb56a17009294ff100dc9b39cb774b
/current_session/python/64.py
299deb7a091e6d3b571796aa2c679d5a9c97c68c
[]
no_license
YJL33/LeetCode
0e837a419d11d44239d1a692140a1468f6a7d9bf
b4da922c4e8406c486760639b71e3ec50283ca43
refs/heads/master
2022-08-13T01:46:14.976758
2022-07-24T03:59:52
2022-07-24T04:11:32
52,939,733
3
0
null
null
null
null
UTF-8
Python
false
false
788
py
""" https://leetcode.com/problems/minimum-path-sum/ """ class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 dp = [[0 for _ in grid[0]] for _ in grid] dp[0][0] = grid[0][0] # 1st row for j in range(1,len(grid[0])): dp[0][j] = grid[0][j]+dp[0][j-1] # 1st col for i in range(1,len(grid)): dp[i][0] = grid[i][0]+dp[i-1][0] # rest for i in range(1,len(grid)): for j in range(1,len(grid[0])): dp[i][j] = grid[i][j] + min(dp[i][j-1], dp[i-1][j]) # print(dp) return dp[-1][-1] print(Solution().minPathSum([[1,3,1],[1,5,1],[4,2,1]]))
3611b108a1f1d92a25090405091c3530258d4e74
b75c63ee092e53b96aea341a486b541d0eed95a7
/blurry_transition.py
170d6c798dd71c9302981dc14ed281c9a263aafd
[ "Apache-2.0" ]
permissive
abeauvisage/blender-sequencer-transitions
74abfbf63f11395475d64d1e3e605709f0589443
02f972a992a19b695902b4343188421a3f6491fb
refs/heads/main
2023-08-11T23:09:30.029056
2021-10-07T18:09:24
2021-10-07T18:09:24
406,025,641
3
0
null
null
null
null
UTF-8
Python
false
false
2,089
py
import bpy def preprocess_transition(context): """ Check that the number of strip is appropriate and extract relevant information """ if len(context.selected_sequences) != 2: return (None, None, None, None) seq1 = context.selected_sequences[0] seq2 = context.selected_sequences[1] frame_start = seq1.frame_final_start frame_end = seq2.frame_final_end return (seq1, seq2, frame_start, frame_end) class BlurryTransitionOperator(bpy.types.Operator): """ Create a blurry transition, smoothly changing from one strip to the other. """ bl_idname = "sequencer.blurry_transition_operator" bl_label = "blurry transition" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): seq1, seq2, frame_start, frame_end = preprocess_transition(context) if not (seq1 and seq2 and frame_start and frame_end): return {'FINISHED'} bpy.ops.sequencer.effect_strip_add( type='GAMMA_CROSS', frame_start=frame_start, frame_end=frame_end) gamma_cross = bpy.context.scene.sequence_editor.sequences.new_effect( name=seq2.name + ".gm", type='GAMMA_CROSS', channel=seq2.channel + 1, frame_start=frame_start, frame_end=frame_end, seq1=seq2, seq2=seq1) blur = bpy.context.scene.sequence_editor.sequences.new_effect( name=seq2.name + ".bl", type='GAUSSIAN_BLUR', channel=seq2.channel + 2, frame_start=frame_start, frame_end=frame_end, seq1=gamma_cross) blur.keyframe_insert("size_x", -1, frame_start) blur.keyframe_insert("size_y", -1, frame_start) blur.keyframe_insert("size_x", -1, frame_end) blur.keyframe_insert("size_y", -1, frame_end) blur.size_x = 100 blur.size_y = 100 blur.keyframe_insert("size_x", -1, (frame_start + frame_end) / 2) blur.keyframe_insert("size_y", -1, (frame_start + frame_end) / 2) return {'FINISHED'}
f87b9998483a538c92437f9a5bf1caa221bbdff7
d6589ff7cf647af56938a9598f9e2e674c0ae6b5
/ivpd-20190625/setup.py
0b40d457639564fd992881ac6a23f45792a0bdc5
[ "Apache-2.0" ]
permissive
hazho/alibabacloud-python-sdk
55028a0605b1509941269867a043f8408fa8c296
cddd32154bb8c12e50772fec55429a9a97f3efd9
refs/heads/master
2023-07-01T17:51:57.893326
2021-08-02T08:55:22
2021-08-02T08:55:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,874
py
# -*- coding: utf-8 -*- """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 os from setuptools import setup, find_packages """ setup module for alibabacloud_ivpd20190625. Created on 30/12/2020 @author: Alibaba Cloud SDK """ PACKAGE = "alibabacloud_ivpd20190625" NAME = "alibabacloud_ivpd20190625" or "alibabacloud-package" DESCRIPTION = "Alibaba Cloud Intelligent Visual Production (20190625) SDK Library for Python" AUTHOR = "Alibaba Cloud SDK" AUTHOR_EMAIL = "[email protected]" URL = "https://github.com/aliyun/alibabacloud-python-sdk" VERSION = __import__(PACKAGE).__version__ REQUIRES = [ "alibabacloud_tea_util>=0.3.1, <1.0.0", "alibabacloud_oss_sdk>=0.1.0, <1.0.0", "alibabacloud_tea_rpc>=0.1.0, <1.0.0", "alibabacloud_openplatform20191219>=1.1.1, <2.0.0", "alibabacloud_oss_util>=0.0.5, <1.0.0", "alibabacloud_tea_fileform>=0.0.3, <1.0.0", "alibabacloud_tea_openapi>=0.1.0, <1.0.0", "alibabacloud_openapi_util>=0.0.3, <1.0.0", "alibabacloud_endpoint_util>=0.0.3, <1.0.0" ] LONG_DESCRIPTION = '' if os.path.exists('./README.md'): with open("README.md", encoding='utf-8') as fp: LONG_DESCRIPTION = fp.read() setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', author=AUTHOR, author_email=AUTHOR_EMAIL, license="Apache License 2.0", url=URL, keywords=["alibabacloud","ivpd20190625"], packages=find_packages(exclude=["tests*"]), include_package_data=True, platforms="any", install_requires=REQUIRES, python_requires=">=3.6", classifiers=( "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', "Topic :: Software Development" ) )
4c8ba3d4f5f8ab96600222d623b7df3cace4efa6
fa78188bc58c829a0a8c71c70167a33778b63530
/ps_util/features/steps/oscc_throttle_report_msg.py
c1221a6c15796c5234125e4c417b4a6af2752721
[ "MIT" ]
permissive
shnewto/core-python-api
b64886ca877aa19a08fcb105b12679da5d453b43
a753863eca820954f5b8f7502c38c5a7d8db5a15
refs/heads/master
2020-03-23T18:46:00.456429
2018-07-06T23:36:58
2018-07-06T23:36:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,147
py
# WARNING: Auto-generated file. Any changes are subject to being overwritten # by setup.py build script. #!/usr/bin/python import time from behave import given from behave import when from behave import then from hamcrest import assert_that, equal_to try: import polysync.node as ps_node from polysync.data_model.types import Py_oscc_throttle_report_msg from polysync.data_model._internal.compare import oscc_throttle_report_msg_type_convert_testable, Py_oscc_throttle_report_msg_initialize_random from polysync.data_model.message_support.oscc_throttle_report_msg import publish, subscribe except ImportError: raise ImportError( 'Py_oscc_throttle_report_msg module dependencies \ missing for tests, is the project built?') @given('I have a Py_oscc_throttle_report_msg object') def step_impl(context): pass @when('I convert it to its C API equivalent a oscc_throttle_report_msg') def step_impl(context): pass @when('I convert the oscc_throttle_report_msg back to a Py_oscc_throttle_report_msg') def step_impl(context): pass @then('the oscc_throttle_report_msg values are equivalent to each Py_oscc_throttle_report_msg value') def step_impl(context): msg = Py_oscc_throttle_report_msg_initialize_random() result = oscc_throttle_report_msg_type_convert_testable(msg) assert not result, result @given('a oscc_throttle_report_msg.publish function exists') def step_impl(context): assert callable(publish) @when('I try to publish something that is not of type Py_oscc_throttle_report_msg') def step_impl(context): bad_obj = "not the right type of object!" context.exception = None try: publish(bad_obj) except Exception as e: context.exception = e @then('a {exeption} indicates the type was not Py_oscc_throttle_report_msg') def step_impl(context, exeption): assert isinstance(context.exception, eval(exeption)), \ "Invalid exception %s - expected %s" \ % (type(context.exception).__name__, exeption) GLOBAL_TIMESTAMP = None GLOBAL_GUID = None def Py_oscc_throttle_report_msg_handler(msg): if msg.header.src_guid == GLOBAL_GUID: global GLOBAL_TIMESTAMP GLOBAL_TIMESTAMP = msg.header.timestamp @given(u'I have a licensed PsNode for publishing Py_oscc_throttle_report_msg') def step_impl(context): assert context.node_ref global GLOBAL_GUID GLOBAL_GUID = context.my_guid @given(u'I have a Py_oscc_throttle_report_msg') def step_impl(context): context.msg = Py_oscc_throttle_report_msg() context.msg.header.timestamp = 0xFFFF @given(u'I have a handler for Py_oscc_throttle_report_msg subscription') def step_impl(context): assert Py_oscc_throttle_report_msg_handler subscribe(handler=Py_oscc_throttle_report_msg_handler) @when(u'I publish my Py_oscc_throttle_report_msg') def step_impl(context): publish(context.msg) @then(u'I receive the corresponding Py_oscc_throttle_report_msg in my handler') def step_impl(context): global GLOBAL_TIMESTAMP while not GLOBAL_TIMESTAMP: time.sleep(1) assert_that(context.msg.header.timestamp, equal_to(GLOBAL_TIMESTAMP))
42b1a2a9404c5bab07e59187cc46ce597d39b0ee
cd5fd7b6ef29980fc29b794576d25eebbdf66246
/leetcode/13/hduyyg.py
656b18b48424a4bc402d224ee6df903579eaab56
[]
no_license
sjl421/algorithm-7
3d2156b1cd5b39477572b8bc3c2c5a688a638b6e
0c34fc5a9f2a5e42f5743c4bb5894cddf6157b22
refs/heads/master
2020-03-18T08:28:45.653815
2018-03-11T12:08:50
2018-03-11T12:08:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
563
py
# author:[email protected] # github:https://github.com/PyCN/algorithm/tree/master/leetcode/13 class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ roman = { 'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1 } res = roman[s[0]] for i in range(0, len(s) - 1): res += roman[s[i + 1]] if roman[s[i]] < roman[s[i + 1]]: res -= 2 * roman[s[i]] return res
8f9f81cc76fcd69a7a8c15932da84632323c0278
f83e5ac7157dc9bb65c3157aa67f574695d3ffe7
/Assignment_BT2/buoi2_lan3.py
c2354250c6019e3e5aed4b6a541b251c49811f1c
[]
no_license
christopherohit/CSx101-A1-2021-02
1b140d8b978c93009070e0ea6625d658a7fa2182
ce4fc34f685988a0388aa7767acfabb562326592
refs/heads/master
2023-08-19T05:58:34.713327
2021-10-15T07:55:41
2021-10-15T07:55:41
401,949,410
1
0
null
null
null
null
UTF-8
Python
false
false
1,199
py
''' Nhận dạng tam giác Viết chương trình nhập vào 3 số thực. Hãy cho biết đó có phải là độ dài 3 cạnh 1 tam giác hay không? Nếu phải thì đó là loại nào trong 4 loại sau: tam giác thường, cân, đều, vuông. Nếu là tam giác tính diện tích tam giác. INPUT: Dòng đầu tiên là độ dài cạnh 1. Dòng thứ hai là độ dài cạnh 2. Dòng thứ ba là độ dài cạnh 3. OUTPUT Định dạng như ví dụ minh họa. Diện tích làm tròn 02 chữ số sau dấu thập phân. ''' import math a = float(input()) b = float(input()) c = float(input()) p = (a + b + c)/2 s = math.sqrt(p*(p-a)*(p-b)*(p-c)) if s == int(s): s = int(s) else: s = round(s,2) if a + b > c and a + c > b and b + c > a: if ((a == b and a!= c) or (a == c and a!=b) or (b == c and b != a)): print("Tam giac can,","dien tich =",s) elif c*c == b*b + a*a or a*a == b*b + c*c or b*b == a*a + c*c: print("Tam giac vuong,","dien tich =",s) elif a == b and b == c: print("Tam giac deu,","dien tich =",s) else: print("Tam giac thuong,","dien tich =",s) else: print("Khong phai tam giac")
af0c88c324e8238876f9b0f4fc0d117751dbbcb4
6d5ca31f6f5ca071416b3ae176ea82a310919eaf
/tester.py
8d1dbc7e6b9f55216e902a33ac04d0a90eca8820
[ "MIT" ]
permissive
iqbalsublime/SkinDetectionProject
cc3448054ea2aaa5362f11ae1a46d50667437811
36b5334ca574fc9f903aaf03eaea6a1a83009ceb
refs/heads/master
2022-03-22T06:39:00.682517
2019-11-23T22:20:19
2019-11-23T22:20:19
223,660,534
0
0
null
null
null
null
UTF-8
Python
false
false
731
py
from PIL import Image ratio = [[[0 for k in range(256)] for j in range(256)] for i in range(256)] with open("./noesis.iqbal", "r") as file: for i in range(256): for j in range(256): for k in range(256): probability = file.readline() ratio[i][j][k] = float(probability) print('data collected!') image = Image.open("./ibtd/test2.jpg") im = image.convert('RGB') width, height = im.size im2 = Image.new(im.mode, im.size) for y in range(height): for x in range(width): red, green, blue = im.getpixel((x, y)) if(ratio[red][green][blue] > .15): im2.putpixel((x, y), (250, 250, 250)) else: im2.putpixel((x, y), (0, 0, 0)) print("*", end="") im2.save("./detected.jpg")
e7311e632df25ad0455b5933fbca59f3d0640fa1
550b5e9cf727632b8a39b045a972079c80a971cf
/homework01/scheduler.py
6dbcaf4c255dfdcc1b713749a56900164ee09c4e
[]
no_license
klaassenj/cs344
a77df2228e7dca2c7653f83c0062381c92d75d8b
af707a86f9c9a60b91f1f6726340296bd5154b20
refs/heads/master
2023-08-03T14:21:09.653719
2020-05-22T04:01:11
2020-05-22T04:01:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,644
py
import sys sys.path.insert(0, '../tools/aima') from csp import CSP, parse_neighbors, min_conflicts def Scheduler(): """ Returns an instance of the CSP class. """ courses = "cs108 cs112 cs214 stat343 cs336 cs300".split() profs = "norman adams schuurman pruim vanderlinden".split() slots = "mwf900 mwf1130 tth1030 tth130".split() rooms = "sb354 nh064".split() variables = courses assignments = {} assignments['cs108'] = "norman" assignments['cs112'] = "adams" assignments['cs214'] = "adams" assignments['stat343'] = "pruim" assignments['cs336'] = "vanderlinden" assignments['cs300'] = "schuurman" neighbors = parse_neighbors(""" cs108: norman; cs112: adams; cs214: adams; stat343: pruim; cs336: vanderlinden; cs300: schuurman """, variables) domains = {} for course in courses: domains[course] = [] for course in courses: for prof in profs: for room in rooms: for slot in slots: domains[course].append(prof + " " + room + " " + slot) for type in [courses]: for A in type: for B in type: if A != B: if B not in neighbors[A]: neighbors[A].append(B) if A not in neighbors[B]: neighbors[B].append(A) def scheduler_constraints(A, a, B, b, recurse=0): ADomain = a.split() BDomain = b.split() A_Prof = ADomain[0] B_Prof = BDomain[0] A_Room = ADomain[1] B_Room = BDomain[1] A_Slot = ADomain[2] B_Slot = BDomain[2] A_Course = A B_Course = B if(A_Prof == B_Prof and A_Slot == B_Slot): return False if(A_Room == B_Room and A_Slot == B_Slot): return False if('norman' in a and A == 'cs108'): return True if('adams' in a and A == 'cs112'): return True if('adams' in a and A == 'cs214'): return True if('pruim' in a and A == 'stat343'): return True if('vanderlinden' in a and A == 'cs336'): return True if('schuurman' in a and A == 'cs300'): return True if(A in courses and B in courses): return False if(recurse == 0): return scheduler_constraints(B, b, A, a, 1) return True return CSP(variables, domains, neighbors, scheduler_constraints) if __name__ == "__main__": schedule = Scheduler() solution = min_conflicts(schedule) print(solution)
c139c4a41147f9dcf330b772bd7e53819c25c27c
ff9132f815358e85e7533d0dedb900b7efc9e902
/generategcode.py
21e3f0ffb19f44310383c58c9d7c344c23e9bd17
[]
no_license
qiwalker/Dinho
ae949314fd6f1e353989fe5ea8d119450dd06a7c
33e96d8bf9b1fc7d4711ec11917979c29d37e631
refs/heads/master
2020-04-25T20:03:35.573928
2015-04-05T15:48:12
2015-04-05T15:48:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,730
py
letters_dict = {' ': 'space',',': 'comma',"'":"single_quote",'"':'double_quote','.':'period','(':'open_round_bracket', ')':'close_round_bracket',':':'colon','-':'hyphen',' ':'space'} import sys import os import re page_width = 18 page_height = 29 # page_height is the number of lines.. letters_gcode_directory = 'NewLetters' def get_letter_lengths(): letter_lengths = {} all_files = [x for x in os.listdir(letters_gcode_directory) if x[-3:]=='ngc'] for all_file in all_files: gcode_file_obj = open(os.path.join(letters_gcode_directory,all_file),'r') line = gcode_file_obj.readline() letter=all_file[:-4] line = gcode_file_obj.readline() # print line match = re.search(r'\d+\.\d*',line) width = float(match.group()) line = gcode_file_obj.readline() match = re.search(r'\d+\.\d*',line) height = float(match.group()) letter_lengths[letter] = (width,height) return letter_lengths def main(): if len(sys.argv) != 2: print "Usage: python generategcode.py [in file]" return infile = sys.argv[1] if not os.path.exists(infile): print "Filename %s does not exist." %infile return letter_lengths = get_letter_lengths() # print letter_lengths # inobj = open(infile,'r') file_contents = "" cur_x = 0 cur_y = 0 wotrd_length = 0 with open(infile,'r') as inobj: for line in inobj: cur_x=0 words=line.split() for word in words: word_length=0 for letter in word: if letter in letters_dict: letter = letters_dict[letter] cur_x+=letter_lengths[letter][0] word_length+=letter_lengths[letter][0] if cur_x>page_width: cur_x=word_length file_contents+='\n' cur_x+=letter_lengths['space'][0] file_contents+=word+' ' file_contents+='\n' pages=[] cur_x=0 output_line_num=0 # for compiling the gcode file output_gcode_lines = [] line_num=0 for file_lines in file_contents.split('\n'): print file_lines line_num+=1 if line_num>28: line_num=0 print '----------------------------' for letter in file_contents: if letter == '\n': cur_x=0 output_gcode_lines.append("\n\nG00 X0 Y-0.818\nG00 Z0\nG10 P0 L20 X0 Y0 Z0\n\n") output_line_num+=1 if output_line_num>28: output_line_num=0 pages.append(output_gcode_lines) output_gcode_lines=[] continue # print letter if letter in letters_dict: letter = letters_dict[letter] # print letter, letter_obj = open(os.path.join(letters_gcode_directory,letter)+'.ngc','r') letter_gcode = letter_obj.read() match = re.search(r'%(.*)%',letter_gcode,re.DOTALL) letter_gcode = match.group(1) letter_gcode_lines = [x for x in letter_gcode.split('\n') if x!=''] for letter_gcode_line in letter_gcode_lines: if 'X' in letter_gcode_line: letter_gcode_line_parts = letter_gcode_line.split() x_dist = float(letter_gcode_line_parts[letter_gcode_line_parts.index('X')+1]) x_dist+=cur_x; letter_gcode_line_parts[letter_gcode_line_parts.index('X')+1]=str(x_dist) output_gcode_lines.append(' '.join(letter_gcode_line_parts)) continue output_gcode_lines.append(letter_gcode_line) cur_x += letter_lengths[letter][0] output_gcode_lines.append('\n\n') pages.append(output_gcode_lines) page_num=1 print 'Number of pages: '+str(len(pages)) for page in pages: outfile=infile[:-4]+'_'+str(page_num)+'.ngc' page_num+=1 outobj = open(outfile,'wa') for output_gcode_line in page: outobj.write(output_gcode_line) outobj.write('\n') if __name__ == '__main__': main()
9d0ae6192dfe201aa5f9c33531dd9a4e754f6559
077f87548754755b97860154d9c61badc1ea6a1d
/tests/test_media_carousel_extension.py
a4c01c9bcf35527133cce91b680f3f89aa4ee132
[ "BSD-3-Clause" ]
permissive
livio/DocDown-Python
cb88c1c58321ca2689c37b5c46c2796bcb641210
7f6270dfe17678cc0f2e899f9665342a0784cffb
refs/heads/master
2023-01-13T22:52:43.822975
2022-02-07T15:21:48
2022-02-07T15:21:48
71,469,684
1
4
BSD-3-Clause
2022-12-26T20:26:27
2016-10-20T14:08:52
Python
UTF-8
Python
false
false
5,972
py
# -*- coding: utf-8 -*- """ test_media_carousels_extension ---------------------------------- Tests for `docdown.media_carousels` module. """ from __future__ import absolute_import, unicode_literals, print_function import copy import markdown import unittest from docdown.media_carousels import BEFORE_CAROUSEL_HTML, AFTER_CAROUSEL_HTML class MediaCarouselExtensionTest(unittest.TestCase): """ Integration test with markdown for :class:`docdown.media_carousels.MediaCarouselExtension` """ MARKDOWN_EXTENSIONS = ['docdown.media_carousels'] CAROUSEL_OPEN_FENCE = "[carousel!]" CAROUSEL_CLOSE_FENCE = "[!carousel]" PREVIEW_CLASS = 'small-preview' base_image_string = "![" maxDiff = 1000 def test_empty_string(self): text = '' html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) expected_output = '' self.assertEqual(html, expected_output) def test_nothing_matching(self): heading = 'Test' text = f'# {heading}' html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) expected_output = f"<h1>{heading}</h1>" self.assertEqual(expected_output, html) def test_full_match_empty(self): """An empty carousel with no images""" text = self.CAROUSEL_OPEN_FENCE + self.CAROUSEL_CLOSE_FENCE html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) expected_output = BEFORE_CAROUSEL_HTML.format(0) + AFTER_CAROUSEL_HTML self.assertEqual(expected_output, html) def test_full_match(self): """A carousel with an image""" img_alt = 'image text' img_title = 'image title' img_path = 'path/to/img.jpg' image_string = f'![{img_alt}]({img_path} "{img_title}")' text = self.CAROUSEL_OPEN_FENCE + image_string + self.CAROUSEL_CLOSE_FENCE html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) image_html = f'<img class="small-preview" alt="{img_alt}" src="{img_path}" title="{img_title}">' expected_output = BEFORE_CAROUSEL_HTML.format(0) + image_html + AFTER_CAROUSEL_HTML self.assertEqual(expected_output, html) def test_full_match_with_existing_class(self): """A carousel with images, one already specifying a classname""" img_alt = 'image text' img_title = 'image title' img_path = 'path/to/img.jpg' class_name = "extra-class" class_decl = '{@class=' + class_name + '}' image_string = f'![{img_alt}]({img_path} "{img_title}")' image_with_class = f'![{img_alt}{class_decl}]({img_path} "{img_title}")' text = self.CAROUSEL_OPEN_FENCE + image_string + image_with_class + self.CAROUSEL_CLOSE_FENCE html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) image_html = f'<img class="small-preview" alt="{img_alt}" src="{img_path}" title="{img_title}">' \ f'<img alt="{img_alt}" class="small-preview {class_name}" src="{img_path}" title="{img_title}">' expected_output = BEFORE_CAROUSEL_HTML.format(0) + image_html + AFTER_CAROUSEL_HTML self.assertEqual(expected_output, html) def test_multiple_subsequent_matches(self): """Multiple matches that are one after another""" img_alt = 'image text' img_title = 'image title' img_path = 'path/to/img.jpg' image_string = f'![{img_alt}]({img_path} "{img_title}")' text = self.CAROUSEL_OPEN_FENCE + image_string + self.CAROUSEL_CLOSE_FENCE text += text html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) image_html = f'<img class="small-preview" alt="{img_alt}" src="{img_path}" title="{img_title}">' expected_output = BEFORE_CAROUSEL_HTML + image_html + AFTER_CAROUSEL_HTML expected_output += expected_output self.assertEqual(expected_output.format(0, 1), html) def test_multiple_matches_dispersed(self): """Multiple matches separated by other markdown""" img_alt = 'image text' img_title = 'image title' img_path = 'path/to/img.jpg' image_string = f'![{img_alt}]({img_path} "{img_title}")' text = self.CAROUSEL_OPEN_FENCE + image_string + self.CAROUSEL_CLOSE_FENCE italic_text = "italics" italics = f'*{italic_text}*' text += italics + text html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) image_html = f'<img class="small-preview" alt="{img_alt}" src="{img_path}" title="{img_title}">' expected_output = BEFORE_CAROUSEL_HTML + image_html + AFTER_CAROUSEL_HTML expected_output += f"<em>{italic_text}</em>" + expected_output self.assertEqual(expected_output.format(0, 1), html) def test_no_closing_tag(self): """If the [!carousel] tag is missing, don't process the rest, keep wrapping paragraph tag""" img_alt = 'image text' img_title = 'image title' img_path = 'path/to/img.jpg' image_string = f'![{img_alt}]({img_path} "{img_title}")' text = self.CAROUSEL_OPEN_FENCE + image_string html = markdown.markdown( text, extensions=self.MARKDOWN_EXTENSIONS, output_format='html5' ) image_html = f'<p><img alt="{img_alt}" src="{img_path}" title="{img_title}"></p>' expected_output = image_html self.assertEqual(expected_output, html)
b5436f9d0a408a15014352dc627294e4b2e4929b
b5834c9ef01fd666165271d951a17e26fd9f6afd
/dqn_cartpole.py
fb73ff8b7d82066060fbca220db44c5d60b7611f
[]
no_license
David-Un-ger/Breakout_DQN
c6e848e3a0bdcce46a3c8d8299f28f7081945823
8ef0ef976aa2220884d14a592af223cb08ef53d9
refs/heads/master
2023-09-03T04:17:24.726550
2021-11-23T07:30:39
2021-11-23T07:30:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,987
py
import tensorflow as tf import tensorflow.keras as keras import numpy as np import random import gym """ Cartpole: The DQN trains and reaches a score of over 100 within the first 100 episodes and a a score of 498 (=maximum) within 200 episodes. A grid search to find the optimal hyperparameter would be beneficial... """ class DQN: def __init__(self): self.scores = [] self.env = gym.make('CartPole-v1') # self.env = gym.make("Breakout-ram-v0") self.behavior_model = self.model() # select actions based on behavior model self.target_model = self.model() # assess value of a state based on target model self.target_model.set_weights(self.behavior_model.get_weights()) self.memory = [] self.BATCH_SIZE = 32 self.EPISODES = 200 self.GAMMA = 0.99 self.epsilon = 1 self.epsilon_stop = 0.2 self.epsilon_decay = (self.epsilon_stop / self.epsilon) ** (1 / (self.EPISODES-1)) def model(self): input_size = self.env.observation_space.shape[0] output_size = self.env.action_space.n input_layer = keras.layers.Input(shape=input_size) x = keras.layers.Dense(8, activation="relu")(input_layer) #x = keras.layers.Dense(8, activation="relu")(x) #x = keras.layers.Dense(16, activation="relu")(x) output_layer = keras.layers.Dense(output_size, activation="linear")(x) # outputs the value of taking an action model = keras.Model(inputs=input_layer, outputs=output_layer) model.compile(optimizer="adam", loss="mse", metrics=["accuracy"]) return model def train(self): for epoch in range(self.EPISODES): state = self.env.reset() done = False score = 0 ctr = 0 while not done: # find action via epsilon greedy if random.random() > self.epsilon: # perform greedy action action = np.argmax(self.behavior_model.predict(state.reshape(-1, self.env.observation_space.shape[0]))) else: # perform random action action = self.env.action_space.sample() next_state, reward, done, info = self.env.step(action) lost = False # issue: if we are done and won, is a different state than won and loose. if done and (score < 498): lost = True elif done: print(f"Won game after {epoch} episodes!!!") if lost: reward = -10 score += reward reward /= 10 # brings the negative reward to -1 and the positive one to +0.1 # store experience in the memory self.memory.append([state, next_state, action, reward, lost]) state = next_state # training part if len(self.memory) > self.BATCH_SIZE: # memory is long enough -> start training train_batch = np.array(random.sample(self.memory, self.BATCH_SIZE)) # memory: s, s_, a, r, done states = np.stack(train_batch[:, 0]) next_states = np.stack(train_batch[:, 1]) actions = train_batch[:, 2] rewards = train_batch[:, 3] losts = train_batch[:, 4] # returns an array with action-values for the whole batch. Shape BatchSize x NumActions # required, because we need a baseline for the backpropagation (y_true = y_pred, just for the selected action it will be different) q_values = self.behavior_model.predict(states) next_rewards = np.max(self.target_model.predict(next_states), axis=1) next_rewards[losts!=0] = 0 # if a game is done, the next reward is 0 # estimate value of next state for i in range(self.BATCH_SIZE): q_values[i, actions[i]] = rewards[i] + self.GAMMA * next_rewards[i] # train model self.behavior_model.fit(states, q_values, verbose=0) # if memory is too large, remove first entry if len(self.memory) > 10000: self.memory.pop(0) ctr += 1 # episode is done self.scores.append(score) print(f"Episode {epoch} finished. Epsilon: {self.epsilon:.2f} Score is: {score}") self.epsilon *= self.epsilon_decay # every 5 episodes: update target_model if epoch % 5 == 0: self.target_model.set_weights(self.behavior_model.get_weights()) dqn = DQN() dqn.train()
6419bc4c0697b04825599fffb4c3f46ee4e4e1b8
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/173/usersdata/273/82154/submittedfiles/moedas.py
e13a08b2f6f5fd4165b098eb98ffa84ecb615cb9
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
284
py
# -*- coding: utf-8 -*- a=int(input('Digite o valor de a: ')) b=int(input('Digite o valor de b: ')) c=int(input('Digite o valor de c: ')) n=c if c%a==0 and c%b==0: divi=c/a divi2=c/b print divi or divi2 else: divi3= c//a + c//b print (divi3)
31166d8d6ea7c646d8ccbae091ca19cac0f4129f
401369ca4200942e5c9f6e170fb340495c3d2190
/plots/console.py
a8801d1f4a274e277c454347b05f98e372dbab95
[]
no_license
dmallows/Crayon
a90f3be879873f5053f8bc2a880cfab3a54679bb
c419dfc5adf88eec56786f7fa0670747abe3590f
refs/heads/master
2020-04-02T16:33:26.885684
2011-10-24T10:32:40
2011-10-24T10:32:40
2,077,026
1
0
null
null
null
null
UTF-8
Python
false
false
81
py
class ConsoleRunner(object): def __init__(self) def run(self, argv):
56ae3f68368c8dbd7bdc1dae5b9701a35657d21e
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03325/s784878338.py
99c795aab138870e422b36a6b2c11993402b36e4
[]
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
683
py
#!/usr/bin/env python3 import sys def solve(N: int, a: "List[int]"): def f(n): res = 0 while n % 2 == 0: n //= 2 res += 1 return res return sum(map(f, a)) # Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int a = [int(next(tokens)) for _ in range(N)] # type: "List[int]" print(solve(N, a)) def test(): import doctest doctest.testmod() if __name__ == '__main__': #test() main()
3a7325fdbbe61ac8a96517bc702e08c091bea648
6329ece221f3b2295cb3791168c876d260ed0c31
/test_learn/chapter4基本窗口控件/QLabel/Qlabel.py
5c2eefb5ab53693a3951a751fc2bc791a24eb002
[]
no_license
dxcv/PythonGUI
4908e049dde5e569a3ad916c6bac385c7953a243
a39beef0006e3e4057e3a9bcb3e0e64ea790427e
refs/heads/master
2020-05-17T17:14:58.250549
2019-04-11T09:32:52
2019-04-11T09:32:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
904
py
# -*- coding:UTF-8 -*- from PyQt5.QtWidgets import * import sys class WinForm(QWidget): def __init__(self): super().__init__() self.setWindowTitle("QLabel例子") nameLb1=QLabel('&name',self) nameEd1=QLineEdit(self) nameLb1.setBuddy(nameEd1) nameLb2=QLabel('&password',self) nameEd2=QLineEdit(self) nameLb2.setBuddy(nameEd2) btnOk=QPushButton('&OK') btnCancel=QPushButton('&Cancel') mainLayout=QGridLayout(self) mainLayout.addWidget(nameLb1,0,0) mainLayout.addWidget(nameEd1,0,1,1,2) mainLayout.addWidget(nameLb2,1,0) mainLayout.addWidget(nameEd2,1,1,1,2) mainLayout.addWidget(btnOk,2,1) mainLayout.addWidget(btnCancel,2,2) if __name__=='__main__': app=QApplication(sys.argv) form=WinForm() form.show() sys.exit(app.exec_())
76ff98474ce51699a94dfce210a76dbd53684772
141d82bf4260aa412fa44873c738d2c587cf99a0
/TerminaChatBot/trash/asda.py
3079d82652584211b344aa544fe2dde9afd60429
[]
no_license
ybgirgin3/DjangoChatBot
b6cff1804cdf8cef2e9122221e101901103d1929
a4f752ac8f3e6219650ef4117cff9c36468c41e4
refs/heads/main
2023-05-28T23:46:16.698367
2021-06-05T07:20:07
2021-06-05T07:20:07
374,047,881
1
0
null
null
null
null
UTF-8
Python
false
false
1,453
py
from readdb_trash import main as dbmain from pprint import pprint #privKey = "810e4a9a" #ind = 2 #acc = dbmain("register_customuser") #acc = dbmain("root_arizakaydi") #priv = [i[-1] for i in acc] # listelerin alayını dönüyor #pprint(acc) """ for user in acc: if ind in user: print(user) """ """ for err in acc: if err[-1] == ind: print(err) """ # emailden kullanıcı bulma """ email1 = "[email protected]" email2 = "[email protected]" for user in acc: if email2 in user[-2]: print(user) """ # veritabanına eleman ekleme """ import sqlite3 vt = sqlite3.connect('vt.sqlite') im = vt.cursor() #değer_gir = #INSERT INTO personel VALUES ('Fırat', 'Özgül', 'Adana') #im.execute(tablo_yap) #im.execute(değer_gir) """ user_index = 2 item_index = len([item for item in dbmain("root_arizakaydi", fetch=True)]) + 1 print(item_index) item_name = "pythondan eklenen hata" insert = dbmain("root_arizakaydi", send=True, user_index=user_index, item_name=item_name, item_index=item_index) print(insert) #item for item in dbmain("root_arizakaydi") + 1 """ for item in dbmain("root_arizakaydi", fetch=True): print(item[1]) """ """ from termcolor import colored usersItem = dbmain("root_arizakaydi", fetch=True) print("sizin tarafınızdan kaydedilmiş tüm bildirimler: ") for item in usersItem: print(colored(item[1], "blue")) """
714f748d54c27e704eb7be731dfccdf781124ad0
e9538b7ad6d0ce0ccfbb8e10c458f9e0b73926f6
/tests/unit/modules/network/fortios/test_fortios_wanopt_cache_service.py
39b145e6e74eb6bb84b29fd3ca26aa8f3fabb4c3
[]
no_license
ansible-collection-migration/misc.not_a_real_collection
b3ef8090c59de9ac30aca083c746ec3595d7f5f5
7ab1af924a3db4ada2f714b09bb392614344cb1e
refs/heads/master
2020-12-18T13:48:51.849567
2020-01-22T17:39:18
2020-01-22T17:39:18
235,400,821
0
0
null
null
null
null
UTF-8
Python
false
false
6,933
py
# Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible_collections.misc.not_a_real_collection.plugins.modules import fortios_wanopt_cache_service except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.modules.fortios_wanopt_cache_service.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_wanopt_cache_service_creation(mocker): schema_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'wanopt_cache_service': { 'acceptable_connections': 'any', 'collaboration': 'enable', 'device_id': 'test_value_5', 'prefer_scenario': 'balance', }, 'vdom': 'root'} is_error, changed, response = fortios_wanopt_cache_service.fortios_wanopt(input_data, fos_instance) expected_data = { 'acceptable-connections': 'any', 'collaboration': 'enable', 'device-id': 'test_value_5', 'prefer-scenario': 'balance', } set_method_mock.assert_called_with('wanopt', 'cache-service', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_wanopt_cache_service_creation_fails(mocker): schema_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'wanopt_cache_service': { 'acceptable_connections': 'any', 'collaboration': 'enable', 'device_id': 'test_value_5', 'prefer_scenario': 'balance', }, 'vdom': 'root'} is_error, changed, response = fortios_wanopt_cache_service.fortios_wanopt(input_data, fos_instance) expected_data = { 'acceptable-connections': 'any', 'collaboration': 'enable', 'device-id': 'test_value_5', 'prefer-scenario': 'balance', } set_method_mock.assert_called_with('wanopt', 'cache-service', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_wanopt_cache_service_idempotent(mocker): schema_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'wanopt_cache_service': { 'acceptable_connections': 'any', 'collaboration': 'enable', 'device_id': 'test_value_5', 'prefer_scenario': 'balance', }, 'vdom': 'root'} is_error, changed, response = fortios_wanopt_cache_service.fortios_wanopt(input_data, fos_instance) expected_data = { 'acceptable-connections': 'any', 'collaboration': 'enable', 'device-id': 'test_value_5', 'prefer-scenario': 'balance', } set_method_mock.assert_called_with('wanopt', 'cache-service', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_wanopt_cache_service_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible_collections.misc.not_a_real_collection.plugins.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'wanopt_cache_service': { 'random_attribute_not_valid': 'tag', 'acceptable_connections': 'any', 'collaboration': 'enable', 'device_id': 'test_value_5', 'prefer_scenario': 'balance', }, 'vdom': 'root'} is_error, changed, response = fortios_wanopt_cache_service.fortios_wanopt(input_data, fos_instance) expected_data = { 'acceptable-connections': 'any', 'collaboration': 'enable', 'device-id': 'test_value_5', 'prefer-scenario': 'balance', } set_method_mock.assert_called_with('wanopt', 'cache-service', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
cefe4d035a50c4340bc4b24e3b919199b5c98dc2
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/482/usersdata/309/110191/submittedfiles/Av2_Parte4.py
5aca4be961245c752db543b99e95603e988030a2
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
349
py
# -*- coding: utf-8 -*- mt=[] lin=int(input("Digite a quantidade de linhas da matriz:")) colu=int(input("Digite a quantidade de colunas da matriz:")) for i in range (0,lin,1): lista=[] for j in range (0,colu,1): lista.append(int(input("Digite um elemento para sua matriz:"))) mt.append(lista) print(mt)
159f64c2bebe8b06c567595cf230f000bde35cf6
e5333b2e54f1adf2e5bc88a9a242234c5f15851a
/misoclib/tools/litescope/software/driver/la.py
2b84e96268fdbc793b1ab8adb92dd1edc4307378
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hoangt/misoc
1aaf850c18bab5b18db1fcc788feb96afbbc464e
6c13879fb605a1ee2bd5a3b35669e093f9a4267b
refs/heads/master
2021-01-21T02:55:59.398987
2015-07-13T15:00:03
2015-07-13T15:25:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,220
py
import csv from struct import * from migen.fhdl.structure import * from misoclib.tools.litescope.software.dump import * from misoclib.tools.litescope.software.driver.truthtable import * class LiteScopeLADriver(): def __init__(self, regs, name, config_csv=None, clk_freq=None, debug=False): self.regs = regs self.name = name if config_csv is None: self.config_csv = name + ".csv" if clk_freq is None: try: self.clk_freq = regs.identifier_frequency.read() except: self.clk_freq = None self.samplerate = self.clk_freq else: self.clk_freq = clk_freq self.samplerate = clk_freq self.debug = debug self.get_config() self.get_layout() self.build() self.data = Dat(self.dw) def get_config(self): csv_reader = csv.reader(open(self.config_csv), delimiter=',', quotechar='#') for item in csv_reader: t, n, v = item if t == "config": setattr(self, n, int(v)) def get_layout(self): self.layout = [] csv_reader = csv.reader(open(self.config_csv), delimiter=',', quotechar='#') for item in csv_reader: t, n, v = item if t == "layout": self.layout.append((n, int(v))) def build(self): for key, value in self.regs.d.items(): if self.name == key[:len(self.name)]: key = key.replace(self.name + "_", "") setattr(self, key, value) value = 1 for name, length in self.layout: setattr(self, name + "_o", value) value = value*(2**length) value = 0 for name, length in self.layout: setattr(self, name + "_m", (2**length-1) << value) value += length def configure_term(self, port, trigger=0, mask=0, cond=None): if cond is not None: for k, v in cond.items(): trigger |= getattr(self, k + "_o")*v mask |= getattr(self, k + "_m") t = getattr(self, "trigger_port{d}_trig".format(d=int(port))) m = getattr(self, "trigger_port{d}_mask".format(d=int(port))) t.write(trigger) m.write(mask) def configure_range_detector(self, port, low, high): l = getattr(self, "trigger_port{d}_low".format(d=int(port))) h = getattr(self, "trigger_port{d}_high".format(d=int(port))) l.write(low) h.write(high) def configure_edge_detector(self, port, rising_mask, falling_mask, both_mask): rm = getattr(self, "trigger_port{d}_rising_mask".format(d=int(port))) fm = getattr(self, "trigger_port{d}_falling_mask".format(d=int(port))) bm = getattr(self, "trigger_port{d}_both_mask".format(d=int(port))) rm.write(rising_mask) fm.write(falling_mask) bm.write(both_mask) def configure_sum(self, equation): datas = gen_truth_table(equation) for adr, dat in enumerate(datas): self.trigger_sum_prog_adr.write(adr) self.trigger_sum_prog_dat.write(dat) self.trigger_sum_prog_we.write(1) def configure_subsampler(self, n): self.subsampler_value.write(n-1) if self.clk_freq is not None: self.samplerate = self.clk_freq//n else: self.samplerate = None def configure_qualifier(self, v): self.recorder_qualifier.write(v) def configure_rle(self, v): self.rle_enable.write(v) def done(self): return self.recorder_done.read() def run(self, offset, length): if self.debug: print("running") self.recorder_offset.write(offset) self.recorder_length.write(length) self.recorder_trigger.write(1) def upload(self): if self.debug: print("uploading") while self.recorder_source_stb.read(): self.data.append(self.recorder_source_data.read()) self.recorder_source_ack.write(1) if self.with_rle: if self.rle_enable.read(): self.data = self.data.decode_rle() return self.data def save(self, filename): if self.debug: print("saving to " + filename) name, ext = os.path.splitext(filename) if ext == ".vcd": from misoclib.tools.litescope.software.dump.vcd import VCDDump dump = VCDDump() elif ext == ".csv": from misoclib.tools.litescope.software.dump.csv import CSVDump dump = CSVDump() elif ext == ".py": from misoclib.tools.litescope.software.dump.python import PythonDump dump = PythonDump() elif ext == ".sr": from misoclib.tools.litescope.software.dump.sigrok import SigrokDump if self.samplerate is None: raise ValueError("Unable to automatically retrieve clk_freq, clk_freq parameter required") dump = SigrokDump(samplerate=self.samplerate) else: raise NotImplementedError dump.add_from_layout(self.layout, self.data) dump.write(filename)
3f370321ebee887356b154e8d0f116d8177a6c7d
4e534fa12ffe5f9444dfa719b14a6929b6ca1ab7
/Source.py
c5f98560fce3c8f6b0748a1c8c8e2af44afd815d
[]
no_license
YuvalKogos/NLP-Text-Summarizer
4e06eab7db0fef50e10caffcbb63d601b3b46c1c
03cffa61024a40ebf918ed553efecd9d5fedfa7b
refs/heads/master
2022-04-20T07:02:40.682101
2020-04-19T13:24:37
2020-04-19T13:24:37
256,998,558
0
0
null
null
null
null
UTF-8
Python
false
false
19,846
py
import gensim import nltk import pandas as pd import matplotlib.pyplot as plt from nltk import RegexpTokenizer from nltk.corpus import stopwords from os import listdir from os.path import isfile, join import csv from nltk.stem import WordNetLemmatizer from nltk import FreqDist from nltk.stem import PorterStemmer import numpy as np import os from gensim.models import Word2Vec import time from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from tensorflow.keras.layers import Input, LSTM, Embedding, Dense, Concatenate, TimeDistributed from tensorflow.keras.models import Model from attention_layer_script import AttentionLayer from tensorflow.keras.callbacks import EarlyStopping import string DATAST_FILE_PATH = r"C:\Users\device_lab\Desktop\After_Parser\Reviews.csv" OUTPUT_PATH = '' LOAD_PRETRAINED_MODEL = False class Preproccesor: def __init__(self,data,headers): #method gets the data (list of lists) which contains what you want to summarize #and the headers (list of lists) which are the summrizations self.data = data self.headers = headers def Run(functions): pass def ImplementNLTK(self,data,headers): nltk.download('stopwords') tokenizer = RegexpTokenizer(r'\w+') stopword_set = set(stopwords.words('english')) pancs_marks = set(string.punctuation) new_data = [] for article in data: #remove pancutation marks new_str = ''.join(ch for ch in article if ch not in pancs_marks) new_str = article.lower() dlist = tokenizer.tokenize(new_str) #dlist = list(set(dlist).difference(stopword_set)) new_data.append(dlist) new_headers = [] for header in headers: try: new_str = ''.join(ch for ch in header if ch not in pancs_marks) new_str = header.lower() dlist = tokenizer.tokenize(new_str) #dlist = list(set(dlist).difference(stopword_set)) new_headers.append(dlist) except: print('e') return new_data,new_headers def Lemmatization(self,data,headers,return_as_strings = True): nltk.download('wordnet') ps = PorterStemmer() # define the lemmatiozation object lemmatizer = WordNetLemmatizer() new_data = [] for file in data: new_file = [] for word in file: stemmed_word = ps.stem(word) lemetized_word = lemmatizer.lemmatize(stemmed_word) new_file.append(lemetized_word) new_data.append(new_file) new_headers = [] for header in headers: new_header = [] for word in header: stemmed_word = ps.stem(word) lemetized_word = lemmatizer.lemmatize(stemmed_word) new_header.append(lemetized_word) new_headers.append(new_header) #If return as strings, return list of strings, else return list of list of words if not return_as_strings: return new_data,new_headers else: data = [] for file in new_data: tmp = '' for word in file: tmp += word + ' ' data.append(tmp) headers = [] for header in new_headers: tmp = '' for word in header: tmp += word + ' ' headers.append(tmp) print('Data : \n',data[:5]) print('Headers : \n',headers[:5]) return data,headers def EliminateLowFrequencies(self,data): pass def Word2VecSetup(self,data,headers,check_similarities = False): data += headers print('Initializing the Word2Vec model...') model = Word2Vec( data, size=150, window=10, min_count=2, workers=10, iter=10) # print('Building vocab...') # model.build_vocab(data) print('Training the W2V model...') st = time.time() model.train(data,total_examples=len(data), epochs = 10) print('Finished. Time : ', time.time() - st) if check_similarities: status_str = 'notebook' while status_str != 'exit': try: print(model.most_similar(status_str)[:5]) except: print('Word {0} not in vocab.'.format(status_str)) status_str = input('Enter word') return model def TokenizeData(self,data,headers,train_percentage = 0.7,val_percentage = 0.15,test_percentage = 0.15): x = [] y = [] #Append start and end of line tokens fpr headers for i in range(len(headers)): headers[i] = 'START ' + headers[i] + 'END' max_text_len = 500 max_summary_len = 10 train_idx = int(len(data) * train_percentage) val_idx = int(len(data) * (train_percentage + val_percentage)) x_tr = data[:train_idx] x_val = data[train_idx:val_idx] y_tr = headers[:train_idx] y_val = headers[train_idx:val_idx] x_tokenizer = Tokenizer() x_tokenizer.fit_on_texts(list(x_tr)) thresh = 2 cnt = 0 tot_cnt = 0 freq = 0 tot_freq = 0 for key, value in x_tokenizer.word_counts.items(): tot_cnt = tot_cnt + 1 tot_freq = tot_freq + value if (value < thresh): cnt = cnt + 1 freq = freq + value print("% of rare words in vocabulary:", (cnt / tot_cnt) * 100) print("Total Coverage of rare words:", (freq / tot_freq) * 100) # prepare a tokenizer for reviews on training data x_tokenizer = Tokenizer(num_words=tot_cnt - cnt) x_tokenizer.fit_on_texts(list(x_tr)) # convert text sequences into integer sequences x_tr_seq = x_tokenizer.texts_to_sequences(x_tr) x_val_seq = x_tokenizer.texts_to_sequences(x_val) # padding zero upto maximum length x_tr = pad_sequences(x_tr_seq, maxlen=max_text_len, padding='post') x_val = pad_sequences(x_val_seq, maxlen=max_text_len, padding='post') # size of vocabulary ( +1 for padding token) x_voc = x_tokenizer.num_words + 1 ############labels########### y_tokenizer = Tokenizer() y_tokenizer.fit_on_texts(list(y_tr)) cnt = 0 tot_cnt = 0 freq = 0 tot_freq = 0 for key, value in y_tokenizer.word_counts.items(): tot_cnt = tot_cnt + 1 tot_freq = tot_freq + value if (value < thresh): cnt = cnt + 1 freq = freq + value print("% of rare words in vocabulary:", (cnt / tot_cnt) * 100) print("Total Coverage of rare words:", (freq / tot_freq) * 100) # prepare a tokenizer for reviews on training data y_tokenizer = Tokenizer(num_words=tot_cnt - cnt) y_tokenizer.fit_on_texts(list(y_tr)) # convert text sequences into integer sequences y_tr_seq = y_tokenizer.texts_to_sequences(y_tr) y_val_seq = y_tokenizer.texts_to_sequences(y_val) # padding zero upto maximum length y_tr = pad_sequences(y_tr_seq, maxlen=max_summary_len, padding='post') y_val = pad_sequences(y_val_seq, maxlen=max_summary_len, padding='post') # size of vocabulary y_voc = y_tokenizer.num_words + 1 self.x_voc = x_voc self.y_voc = y_voc self.x_tokenizer = x_tokenizer self.y_tokenizer = y_tokenizer return x_tr,x_val,y_tr,y_val,x_voc,y_voc,x_tokenizer,y_tokenizer def seq2text(self,input_seq): if not hasattr(self,'x_tokenizer'): print("Preproccesor's object has no attribute x_tokenizer, call Tokenize data mehotd first.") return None newString='' for i in input_seq: if(i!=0): newString=newString+self.x_tokenizer.index_word[i]+' ' return newString def seq2summary(self,input_seq): if not hasattr(self,'y_tokenizer'): print("Preproccesor's object has no attribute y_tokenizer, call Tokenize data mehotd first.") return None newString='' for i in input_seq: if((i!=0 and i!=self.y_tokenizer.word_index['start']) and i!=self.y_tokenizer.word_index['end']): newString=newString+self.y_tokenizer.index_word[i]+' ' return newString class LSTM_Model: def __init__(self,inputs_length,outputs_length): from keras import backend as K K.clear_session() #if not load_model: #latent_dim = LSTM layer num nodes latent_dim = 300 embedding_dim=100 max_text_len = 500 self.embedding_dim = embedding_dim self.max_text_len = max_text_len self.latent_dim = latent_dim # Encoder encoder_inputs = Input(shape=(max_text_len,)) #embedding layer enc_emb = Embedding(inputs_length, embedding_dim,trainable=True)(encoder_inputs) #encoder lstm 1 encoder_lstm1 = LSTM(latent_dim,return_sequences=True,return_state=True,dropout=0.4,recurrent_dropout=0.4) encoder_output1, state_h1, state_c1 = encoder_lstm1(enc_emb) #encoder lstm 2 encoder_lstm2 = LSTM(latent_dim,return_sequences=True,return_state=True,dropout=0.4,recurrent_dropout=0.4) encoder_output2, state_h2, state_c2 = encoder_lstm2(encoder_output1) #encoder lstm 3 encoder_lstm3 = LSTM(latent_dim, return_state=True, return_sequences=True,dropout=0.4,recurrent_dropout=0.4) encoder_outputs, state_h, state_c= encoder_lstm3(encoder_output2) # Set up the decoder, using `encoder_states` as initial state. decoder_inputs = Input(shape=(None,)) #embedding layer dec_emb_layer = Embedding(outputs_length, embedding_dim,trainable=True) dec_emb = dec_emb_layer(decoder_inputs) decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True,dropout=0.4,recurrent_dropout=0.2) decoder_outputs,decoder_fwd_state, decoder_back_state = decoder_lstm(dec_emb,initial_state=[state_h, state_c]) # Attention layer attn_layer = AttentionLayer(name='attention_layer') attn_out, attn_states = attn_layer([encoder_outputs, decoder_outputs]) # Concat attention input and decoder LSTM output decoder_concat_input = Concatenate(axis=-1, name='concat_layer')([decoder_outputs, attn_out]) #dense layer decoder_dense = TimeDistributed(Dense(outputs_length, activation='softmax')) decoder_outputs = decoder_dense(decoder_concat_input) # Define the model self.model = Model([encoder_inputs, decoder_inputs], decoder_outputs) print(self.model.summary()) #Assign a dictionary that represents each layer self.layers = {'encoder_inputs' : encoder_inputs, 'enc_emb' : enc_emb, 'encoder_lstm1': encoder_lstm1, 'encoder_lstm2':encoder_lstm2, 'encoder_lstm3':encoder_lstm3, 'decoder_inputs' : decoder_inputs, 'dec_emb_layer': dec_emb_layer, 'decoder_lstm' : decoder_lstm, 'attn_layer' : attn_layer, 'decoder_dense' : decoder_dense } self.hidden_states = {'encoder lstm 1' : [state_h1, state_c1], 'encoder lstm 2' : [state_h2, state_c2], 'encoder lstm 3' : [state_h, state_c], 'decoder' : [decoder_fwd_state, decoder_back_state], 'attn state' : [attn_states] } self.inputs = {'encoder_inputs' : encoder_inputs, 'decoder_inputs' : decoder_inputs } self.outputs = {'encoder_output1' : encoder_output1, 'encoder_output2' : encoder_output2, 'encoder_outputs' : encoder_outputs, 'decoder_outputs' : decoder_outputs, 'attn_out' : attn_out } def Train(self,x_tr,y_tr,x_val,y_val,epochs = 10,plot_loss_curve = True): es = EarlyStopping(monitor='val_loss', mode='min', verbose=1,patience=2) #Compile the model self.model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy') #Train the model history=self.model.fit([x_tr,y_tr[:,:-1]], y_tr.reshape(y_tr.shape[0],y_tr.shape[1], 1)[:,1:] ,epochs=epochs,callbacks=[es],batch_size=128, validation_data=([x_val,y_val[:,:-1]], y_val.reshape(y_val.shape[0],y_val.shape[1], 1)[:,1:])) self.history = history #Plot train + val loss if plot_loss_curve: plt.plot(history.history['loss'], label='train') plt.plot(history.history['val_loss'], label='test') def Inference(self): # Encode the input sequence to get the feature vector encoder_inputs = self.layers['encoder_inputs'] #encoder_inputs = Input(shape=(500,)) state_h,state_c = self.hidden_states['encoder lstm 3'][0], self.hidden_states['encoder lstm 3'][1] encoder_model = Model(inputs=encoder_inputs,outputs=[self.outputs['encoder_outputs'], state_h, state_c]) #print(encoder_model.summery()) latent_dim = self.latent_dim #embedding_dim=100 max_text_len = 500 # Decoder setup # Below tensors will hold the states of the previous time step decoder_state_input_h = Input(shape=(latent_dim,)) decoder_state_input_c = Input(shape=(latent_dim,)) decoder_hidden_state_input = Input(shape=(max_text_len,latent_dim)) # Get the embeddings of the decoder sequence dec_emb2= self.layers['dec_emb_layer'](self.inputs['decoder_inputs']) # To predict the next word in the sequence, set the initial states to the states from the previous time step decoder_outputs2, state_h2, state_c2 = self.layers['decoder_lstm'](dec_emb2, initial_state=[decoder_state_input_h, decoder_state_input_c]) #attention inference attn_out_inf, attn_states_inf = self.layers['attn_layer']([decoder_hidden_state_input, decoder_outputs2]) decoder_inf_concat = Concatenate(axis=-1, name='concat')([decoder_outputs2, attn_out_inf]) # A dense softmax layer to generate prob dist. over the target vocabulary decoder_outputs2 = self.layers['decoder_dense'](decoder_inf_concat) # Final decoder model decoder_model = Model( [self.inputs['decoder_inputs']] + [decoder_hidden_state_input,decoder_state_input_h, decoder_state_input_c], [decoder_outputs2] + [state_h2, state_c2]) return encoder_model,decoder_model def PrepareFoodReviewsDataset(path, load_percentage=0.1, using_pandas=True): print('Loading food reviews dataset...') st = time.time() if using_pandas: datafile = pd.read_csv(path) # Drop missing values datafile = datafile.dropna() # Split load percentage datafile = datafile.iloc[:int(load_percentage * datafile.shape[0])] data = datafile['Text'].to_list() headers = datafile['Summary'].to_list() else: reader = csv.reader(open(path, 'r')) REVIEW_COL = 9 SUMMERY_COL = 8 data = [] headers = [] for line in reader: data.append(line[REVIEW_COL]) headers.append(line[SUMMERY_COL]) data, headers = data[:int(len(data) * load_percentage)], headers[:int(len(headers) * load_percentage)] print('Time : ', time.time() - st) return data, headers def GetSummary(input_seq,encoder_model,decoder_model,preproccesor): x_tokenizer = preproccesor.x_tokenizer y_tokenizer = preproccesor.y_tokenizer reverse_target_word_index=y_tokenizer.index_word #reverse_source_word_index=x_tokenizer.index_word target_word_index=y_tokenizer.word_index # Encode the input as state vectors. e_out, e_h, e_c = encoder_model.predict(input_seq) max_summary_len = 30 # Generate empty target sequence of length 1. target_seq = np.zeros((1,1)) # Populate the first word of target sequence with the start word. target_seq[0, 0] = target_word_index['start'] stop_condition = False decoded_sentence = '' while not stop_condition: #Predict the next summary word (as a vector) output_tokens, h, c = decoder_model.predict([target_seq] + [e_out, e_h, e_c]) # De-tokenize the vector to get the word sampled_token_index = np.argmax(output_tokens[0, -1, :]) sampled_token = reverse_target_word_index[sampled_token_index] # Exit condition: either hit max length or find stop word. if (sampled_token == 'end' or len(decoded_sentence.split()) >= (max_summary_len - 1)): stop_condition = True break decoded_sentence += ' '+sampled_token # Update the target sequence (of length 1). target_seq = np.zeros((1,1)) target_seq[0, 0] = sampled_token_index # Update internal states to the next prediction e_h, e_c = h, c return decoded_sentence def GenerateSummaries(data,org_summaries,lstm_model,preproccesor): #Method gets the trained model and a list of senteneces and outputs thier summaries #Split the LSTM model to decoder and encoder encoder_model,decoder_model = lstm_model.Inference() for i in range(data.shape[0]): sentence = data[i] decoded_sentence = GetSummary(sentence.reshape(1,500),encoder_model,decoder_model,preproccesor) print('Data : \n',preproccesor.seq2text(sentence)) print('Summery: \n',preproccesor.seq2summary(org_summaries[i])) print('Predicted summary : \n', decoded_sentence) def main(): print('Processing the data...') data,headers = PrepareFoodReviewsDataset(DATAST_FILE_PATH) preproccesor = Preproccesor(data,headers) print('Cleaning data...') cleaned_data,cleaned_headers = preproccesor.ImplementNLTK(data,headers) print('lematizing data...') lematized_data,lemmatized_headers = preproccesor.Lemmatization(cleaned_data,cleaned_headers) print('Removing frequencies...') x_tr,x_val,y_tr,y_val,x_voc,y_voc,x_tokenizer,y_tokenizer = preproccesor.TokenizeData(lematized_data,lemmatized_headers) print('X train shape : \n',x_tr.shape) print('y train shape : \n',y_tr.shape) print('X val shape : \n',x_val.shape) print('y val shape : \n',y_val.shape) #LSTM model lstm_model = LSTM_Model(x_voc,y_voc) lstm_model.Train(x_tr,y_tr,x_val,y_val) GenerateSummaries(x_tr,y_tr,lstm_model,preproccesor) print('Done.') if __name__ == "__main__": main()
75b9aefd4f171e70ed6953fdbfbccda2bae86ab4
48f31291e15b778c0b6c368947397193c2ac9c71
/test/test_del_contact.py
7f45f5067eb08e142afb7a044b1e55c66e6a5ce0
[ "Apache-2.0" ]
permissive
anastas11a/python_training
05d7f80312f82eda4922fbcc75d7b225996da93c
1daceddb193d92542f7f7313026a7e67af4d89bb
refs/heads/master
2020-03-29T12:01:43.874133
2018-11-17T15:51:59
2018-11-17T15:51:59
149,881,790
0
0
null
null
null
null
UTF-8
Python
false
false
642
py
from model.contact import Contact import random def test_delete_some_contact(app, db, check_ui): app.open_home_page() if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname = "test", lastname = "test")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == app.contact.count() old_contacts.remove(contact) if check_ui: assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
f181f0294594ae6c4da2b0596bfaef3ed30575e4
0466c52e2c5a4d0dbeb7df9da1dca1acd136f553
/python/message_test.py
f2b65b93fd67cabdc4f96bf5d75dc1384feb025b
[]
no_license
Hzuni/Index_Coding_Testbed_V2
56b6fdca65ee677d21fdad9e232fabf953e4d0dd
c9c1413cb2629f4d4df845052acaf5b790f28d81
refs/heads/master
2021-01-20T18:47:34.098066
2016-08-04T18:07:55
2016-08-04T18:07:55
64,410,128
1
0
null
null
null
null
UTF-8
Python
false
false
565
py
import numpy as np import struct def matrix_receiver(msg_received): if msg_received[0] == ord('m'): rows = msg_received[1] print("the number of rows is", rows) columns = msg_received[2] print("the number of columns is", columns) m = np.zeros((rows, columns)) for i in range(0, rows): for j in range(0, columns): m_ij_bytes = bytearray() for k in range(0, 8): byte_k = ( (i * columns * 8) + (j*8) + k+ 3) m_ij_bytes.append(msg_received[byte_k]) recv_dbl = struct.unpack("d",m_ij_bytes) m[i][j] = recv_dbl[0] print(m)
205ef5a7a4a2456084f4636eaaccfb95387921e2
b525c770d67672ba14be54451e200f69a6ded924
/test_on_event/test.py
bb1ad7db2b9c68698076c9cd27e3a22b7d5668f1
[]
no_license
Cassio-4/FaceCropper
314ba9f3a51841e2869bf3cdb8049b0d9451e2fa
88ee0c5370addd73873bfebf90a70e7a797e606d
refs/heads/master
2023-01-22T05:23:49.700210
2020-12-04T16:38:40
2020-12-04T16:38:40
302,171,765
0
0
null
2020-10-29T23:21:08
2020-10-07T22:08:38
null
UTF-8
Python
false
false
1,439
py
from module.video_processing_layer import process_event_batch from module.results_layer import process_batch_result import config class TestEvent: def __init__(self, name, id, path, total_frames, monitor_id): self.__name = name self.__id = id self.__path = path self.__total_frames = total_frames self.__monitor_id = monitor_id def fspath(self): return self.__path def name(self): return self.__name def total_frames(self): return self.__total_frames def monitor_id(self): return self.__monitor_id class TestMonitor: def __init__(self, name, id): self.__name = name self.__id = id def name(self): return self.__name def id(self): return self.__id def run_test(): monitor = TestMonitor(config.MONITOR_NAME, config.MONITOR_ID) active_monitors = {monitor.id(): monitor} event = TestEvent(config.EVENT_NAME, config.EVENT_ID, config.EVENT_PATH, config.TOTAL_FRAMES, config.MONITOR_ID) # =============== MAIN LOOP =============== event_batch = [event] config.LOGGER.Info("Batch has {} events, processing".format(len(event_batch))) batch_result, _ = process_event_batch(event_batch) config.LOGGER.Info("Batch processing: Done") # Process the results of a batch process_batch_result(batch_result, active_monitors) if __name__ == '__main__': run_test()
d49f0e7f1f4928fde136f01b505bb2e17bbc3298
a2beea03ad6e5ad2d59a27328df6533347d762b0
/ui_OsdagMainPage.py
0029aa99de18c3a47f5d5a3103b8fc288d3ef9fc
[]
no_license
chavan-vjti/Osdag
069a9d3822b4d6dffc0e0f298530b9923c13c2d3
534f87d8bbbe6e3d82f8f9681b229cf16ff567f7
refs/heads/master
2021-01-20T08:21:22.639725
2017-06-08T11:11:11
2017-06-08T11:11:11
90,133,561
0
0
null
2017-05-03T09:47:06
2017-05-03T09:47:06
null
UTF-8
Python
false
false
30,288
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'OsdagMainPage.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setWindowModality(QtCore.Qt.NonModal) MainWindow.resize(1410, 1110) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/Osdag.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setStyleSheet(_fromUtf8("QWidget::showMaximised()")) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout = QtGui.QGridLayout(self.centralwidget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.btn_help = QtGui.QPushButton(self.centralwidget) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_help.setFont(font) self.btn_help.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_help.setAutoDefault(True) self.btn_help.setObjectName(_fromUtf8("btn_help")) self.gridLayout.addWidget(self.btn_help, 1, 1, 1, 1) self.btn_openfile = QtGui.QPushButton(self.centralwidget) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_openfile.setFont(font) self.btn_openfile.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_openfile.setAutoDefault(True) self.btn_openfile.setObjectName(_fromUtf8("btn_openfile")) self.gridLayout.addWidget(self.btn_openfile, 1, 0, 1, 1) self.myListWidget = QtGui.QListWidget(self.centralwidget) self.myListWidget.setMinimumSize(QtCore.QSize(300, 0)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(240, 84, 69)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Highlight, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(240, 84, 69)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(171, 194, 80)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(240, 240, 240)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Highlight, brush) self.myListWidget.setPalette(palette) self.myListWidget.setFocusPolicy(QtCore.Qt.NoFocus) self.myListWidget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) self.myListWidget.setStyleSheet(_fromUtf8("QListWidget\n" "{\n" "background-color: #abc250 ;\n" "}")) self.myListWidget.setFrameShape(QtGui.QFrame.Panel) self.myListWidget.setFrameShadow(QtGui.QFrame.Sunken) self.myListWidget.setLineWidth(4) self.myListWidget.setMidLineWidth(2) self.myListWidget.setObjectName(_fromUtf8("myListWidget")) item = QtGui.QListWidgetItem() font = QtGui.QFont() font.setPointSize(12) font.setBold(True) font.setWeight(75) item.setFont(font) self.myListWidget.addItem(item) self.gridLayout.addWidget(self.myListWidget, 0, 0, 1, 2) self.myStackedWidget = QtGui.QStackedWidget(self.centralwidget) font = QtGui.QFont() font.setPointSize(13) font.setItalic(False) self.myStackedWidget.setFont(font) self.myStackedWidget.setFrameShape(QtGui.QFrame.NoFrame) self.myStackedWidget.setFrameShadow(QtGui.QFrame.Plain) self.myStackedWidget.setObjectName(_fromUtf8("myStackedWidget")) self.Osdagpage = QtGui.QWidget() self.Osdagpage.setObjectName(_fromUtf8("Osdagpage")) self.gridLayout_2 = QtGui.QGridLayout(self.Osdagpage) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.lbl_OsdagHeader = QtGui.QLabel(self.Osdagpage) self.lbl_OsdagHeader.setMinimumSize(QtCore.QSize(800, 200)) self.lbl_OsdagHeader.setMaximumSize(QtCore.QSize(800, 200)) self.lbl_OsdagHeader.setText(_fromUtf8("")) self.lbl_OsdagHeader.setPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/Osdag_header.png"))) self.lbl_OsdagHeader.setScaledContents(True) self.lbl_OsdagHeader.setObjectName(_fromUtf8("lbl_OsdagHeader")) self.gridLayout_2.addWidget(self.lbl_OsdagHeader, 0, 0, 2, 2) spacerItem = QtGui.QSpacerItem(20, 738, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem, 1, 2, 2, 1) spacerItem1 = QtGui.QSpacerItem(20, 646, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem1, 2, 0, 1, 1) self.lbl_fosseelogo = QtGui.QLabel(self.Osdagpage) self.lbl_fosseelogo.setMinimumSize(QtCore.QSize(250, 92)) self.lbl_fosseelogo.setMaximumSize(QtCore.QSize(250, 92)) self.lbl_fosseelogo.setText(_fromUtf8("")) self.lbl_fosseelogo.setPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/Fossee_logo.png"))) self.lbl_fosseelogo.setScaledContents(True) self.lbl_fosseelogo.setObjectName(_fromUtf8("lbl_fosseelogo")) self.gridLayout_2.addWidget(self.lbl_fosseelogo, 3, 0, 1, 1) spacerItem2 = QtGui.QSpacerItem(532, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem2, 3, 1, 1, 1) self.lbl_iitblogo = QtGui.QLabel(self.Osdagpage) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lbl_iitblogo.sizePolicy().hasHeightForWidth()) self.lbl_iitblogo.setSizePolicy(sizePolicy) self.lbl_iitblogo.setMinimumSize(QtCore.QSize(100, 100)) self.lbl_iitblogo.setText(_fromUtf8("")) self.lbl_iitblogo.setPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/logoiitb.png"))) self.lbl_iitblogo.setScaledContents(False) self.lbl_iitblogo.setObjectName(_fromUtf8("lbl_iitblogo")) self.gridLayout_2.addWidget(self.lbl_iitblogo, 3, 2, 1, 1) self.myStackedWidget.addWidget(self.Osdagpage) self.Connectionpage = QtGui.QWidget() self.Connectionpage.setObjectName(_fromUtf8("Connectionpage")) self.horizontalLayout = QtGui.QHBoxLayout(self.Connectionpage) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.mytabWidget = QtGui.QTabWidget(self.Connectionpage) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mytabWidget.sizePolicy().hasHeightForWidth()) self.mytabWidget.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.mytabWidget.setFont(font) self.mytabWidget.setFocusPolicy(QtCore.Qt.ClickFocus) self.mytabWidget.setStyleSheet(_fromUtf8("QTabBar::tab {\n" " margin-right: 10;\n" " }\n" "QTabBar::tab::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QTabBar::tab{\n" "height: 40px;\n" "width: 200px;\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}\n" "QTabBar::tab{\n" "border-top-left-radius: 2px ;\n" "border-top-right-radius: 2px ;\n" "border-bottom-left-radius: 0px ;\n" "border-bottom-right-radius: 0px ;\n" "}\n" " ")) self.mytabWidget.setTabShape(QtGui.QTabWidget.Triangular) self.mytabWidget.setObjectName(_fromUtf8("mytabWidget")) self.tab1_shearconnection = QtGui.QWidget() font = QtGui.QFont() font.setItalic(True) self.tab1_shearconnection.setFont(font) self.tab1_shearconnection.setObjectName(_fromUtf8("tab1_shearconnection")) self.gridLayout_3 = QtGui.QGridLayout(self.tab1_shearconnection) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) spacerItem3 = QtGui.QSpacerItem(20, 102, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_3.addItem(spacerItem3, 0, 2, 1, 1) spacerItem4 = QtGui.QSpacerItem(20, 102, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_3.addItem(spacerItem4, 0, 6, 1, 1) spacerItem5 = QtGui.QSpacerItem(87, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem5, 1, 0, 1, 1) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.label_2 = QtGui.QLabel(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) self.verticalLayout.addWidget(self.label_2) self.rdbtn_finplate = QtGui.QRadioButton(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) font.setStrikeOut(False) self.rdbtn_finplate.setFont(font) self.rdbtn_finplate.setFocusPolicy(QtCore.Qt.TabFocus) self.rdbtn_finplate.setLayoutDirection(QtCore.Qt.LeftToRight) self.rdbtn_finplate.setText(_fromUtf8("")) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8("ResourceFiles/images/finplate.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.rdbtn_finplate.setIcon(icon1) self.rdbtn_finplate.setIconSize(QtCore.QSize(300, 300)) self.rdbtn_finplate.setCheckable(True) self.rdbtn_finplate.setObjectName(_fromUtf8("rdbtn_finplate")) self.verticalLayout.addWidget(self.rdbtn_finplate) self.gridLayout_3.addLayout(self.verticalLayout, 1, 1, 1, 3) spacerItem6 = QtGui.QSpacerItem(175, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem6, 1, 4, 1, 1) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.label_3 = QtGui.QLabel(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8("label_3")) self.verticalLayout_2.addWidget(self.label_3) self.rdbtn_cleat = QtGui.QRadioButton(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setUnderline(False) font.setWeight(75) font.setStrikeOut(False) self.rdbtn_cleat.setFont(font) self.rdbtn_cleat.setFocusPolicy(QtCore.Qt.TabFocus) self.rdbtn_cleat.setLayoutDirection(QtCore.Qt.LeftToRight) self.rdbtn_cleat.setStyleSheet(_fromUtf8("QRadioButton {\n" "text-shadow : black 0.1em 0.1em 0.2em ;\n" "}")) self.rdbtn_cleat.setText(_fromUtf8("")) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8("ResourceFiles/images/cleatAngle.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.rdbtn_cleat.setIcon(icon2) self.rdbtn_cleat.setIconSize(QtCore.QSize(300, 300)) self.rdbtn_cleat.setObjectName(_fromUtf8("rdbtn_cleat")) self.verticalLayout_2.addWidget(self.rdbtn_cleat) self.gridLayout_3.addLayout(self.verticalLayout_2, 1, 5, 1, 3) spacerItem7 = QtGui.QSpacerItem(87, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem7, 1, 8, 1, 1) spacerItem8 = QtGui.QSpacerItem(87, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem8, 2, 0, 1, 1) self.verticalLayout_3 = QtGui.QVBoxLayout() self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.label_4 = QtGui.QLabel(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label_4.setFont(font) self.label_4.setObjectName(_fromUtf8("label_4")) self.verticalLayout_3.addWidget(self.label_4) self.rdbtn_endplate = QtGui.QRadioButton(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setItalic(False) font.setWeight(75) self.rdbtn_endplate.setFont(font) self.rdbtn_endplate.setFocusPolicy(QtCore.Qt.TabFocus) self.rdbtn_endplate.setLayoutDirection(QtCore.Qt.LeftToRight) self.rdbtn_endplate.setText(_fromUtf8("")) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(_fromUtf8("ResourceFiles/images/endplate.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.rdbtn_endplate.setIcon(icon3) self.rdbtn_endplate.setIconSize(QtCore.QSize(300, 300)) self.rdbtn_endplate.setObjectName(_fromUtf8("rdbtn_endplate")) self.verticalLayout_3.addWidget(self.rdbtn_endplate) self.gridLayout_3.addLayout(self.verticalLayout_3, 2, 1, 1, 3) spacerItem9 = QtGui.QSpacerItem(175, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem9, 2, 4, 1, 1) self.verticalLayout_4 = QtGui.QVBoxLayout() self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.label_5 = QtGui.QLabel(self.tab1_shearconnection) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label_5.setFont(font) self.label_5.setObjectName(_fromUtf8("label_5")) self.verticalLayout_4.addWidget(self.label_5) self.rdbtn_seat = QtGui.QRadioButton(self.tab1_shearconnection) self.rdbtn_seat.setFocusPolicy(QtCore.Qt.TabFocus) self.rdbtn_seat.setText(_fromUtf8("")) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/seatedAngle1.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.rdbtn_seat.setIcon(icon4) self.rdbtn_seat.setIconSize(QtCore.QSize(300, 300)) self.rdbtn_seat.setObjectName(_fromUtf8("rdbtn_seat")) self.verticalLayout_4.addWidget(self.rdbtn_seat) self.gridLayout_3.addLayout(self.verticalLayout_4, 2, 5, 1, 3) spacerItem10 = QtGui.QSpacerItem(87, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem10, 2, 8, 1, 1) spacerItem11 = QtGui.QSpacerItem(20, 102, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_3.addItem(spacerItem11, 3, 1, 1, 1) spacerItem12 = QtGui.QSpacerItem(20, 102, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_3.addItem(spacerItem12, 3, 7, 1, 1) spacerItem13 = QtGui.QSpacerItem(262, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem13, 4, 3, 1, 1) self.btn_start = QtGui.QPushButton(self.tab1_shearconnection) self.btn_start.setMinimumSize(QtCore.QSize(190, 30)) self.btn_start.setMaximumSize(QtCore.QSize(190, 30)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_start.setFont(font) self.btn_start.setFocusPolicy(QtCore.Qt.TabFocus) self.btn_start.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_start.setCheckable(False) self.btn_start.setAutoExclusive(False) self.btn_start.setAutoDefault(True) self.btn_start.setObjectName(_fromUtf8("btn_start")) self.gridLayout_3.addWidget(self.btn_start, 4, 4, 1, 1) spacerItem14 = QtGui.QSpacerItem(262, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_3.addItem(spacerItem14, 4, 5, 1, 1) self.mytabWidget.addTab(self.tab1_shearconnection, _fromUtf8("")) self.tab2_momentconnection = QtGui.QWidget() self.tab2_momentconnection.setLayoutDirection(QtCore.Qt.RightToLeft) self.tab2_momentconnection.setObjectName(_fromUtf8("tab2_momentconnection")) self.mytabWidget.addTab(self.tab2_momentconnection, _fromUtf8("")) self.horizontalLayout.addWidget(self.mytabWidget) self.myStackedWidget.addWidget(self.Connectionpage) self.tensionpage = QtGui.QWidget() self.tensionpage.setObjectName(_fromUtf8("tensionpage")) self.label = QtGui.QLabel(self.tensionpage) self.label.setGeometry(QtCore.QRect(350, 260, 271, 111)) font = QtGui.QFont() font.setPointSize(19) font.setBold(True) font.setUnderline(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.myStackedWidget.addWidget(self.tensionpage) self.page = QtGui.QWidget() self.page.setObjectName(_fromUtf8("page")) self.myStackedWidget.addWidget(self.page) self.gridLayout.addWidget(self.myStackedWidget, 0, 2, 1, 1) self.btn_connection = QtGui.QPushButton(self.centralwidget) self.btn_connection.setGeometry(QtCore.QRect(60, 120, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_connection.setFont(font) self.btn_connection.setMouseTracking(False) self.btn_connection.setFocusPolicy(QtCore.Qt.StrongFocus) self.btn_connection.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) self.btn_connection.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}\n" "")) self.btn_connection.setAutoDefault(True) self.btn_connection.setDefault(False) self.btn_connection.setObjectName(_fromUtf8("btn_connection")) self.btn_tension = QtGui.QPushButton(self.centralwidget) self.btn_tension.setGeometry(QtCore.QRect(60, 180, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_tension.setFont(font) self.btn_tension.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}\n" "")) self.btn_tension.setAutoDefault(True) self.btn_tension.setObjectName(_fromUtf8("btn_tension")) self.btn_compression = QtGui.QPushButton(self.centralwidget) self.btn_compression.setGeometry(QtCore.QRect(60, 240, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_compression.setFont(font) self.btn_compression.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}\n" "")) self.btn_compression.setAutoDefault(True) self.btn_compression.setObjectName(_fromUtf8("btn_compression")) self.btn_flexural = QtGui.QPushButton(self.centralwidget) self.btn_flexural.setGeometry(QtCore.QRect(60, 300, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_flexural.setFont(font) self.btn_flexural.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_flexural.setAutoDefault(True) self.btn_flexural.setObjectName(_fromUtf8("btn_flexural")) self.btn_beamCol = QtGui.QPushButton(self.centralwidget) self.btn_beamCol.setGeometry(QtCore.QRect(60, 360, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_beamCol.setFont(font) self.btn_beamCol.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_beamCol.setAutoDefault(True) self.btn_beamCol.setObjectName(_fromUtf8("btn_beamCol")) self.btn_plate = QtGui.QPushButton(self.centralwidget) self.btn_plate.setGeometry(QtCore.QRect(60, 420, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_plate.setFont(font) self.btn_plate.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_plate.setAutoDefault(True) self.btn_plate.setObjectName(_fromUtf8("btn_plate")) self.btn_gantry = QtGui.QPushButton(self.centralwidget) self.btn_gantry.setGeometry(QtCore.QRect(60, 480, 200, 35)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(11) font.setBold(True) font.setWeight(75) self.btn_gantry.setFont(font) self.btn_gantry.setStyleSheet(_fromUtf8("QPushButton::hover\n" "{\n" " background-color: #d97f7f;\n" " color:#000000 ;\n" "}\n" "\n" "QPushButton\n" "{\n" "background-color: #925a5b;\n" "color:#ffffff;\n" "}")) self.btn_gantry.setAutoDefault(True) self.btn_gantry.setObjectName(_fromUtf8("btn_gantry")) self.myListWidget.raise_() self.myStackedWidget.raise_() self.btn_openfile.raise_() self.btn_help.raise_() self.btn_connection.raise_() self.btn_tension.raise_() self.btn_compression.raise_() self.btn_flexural.raise_() self.btn_beamCol.raise_() self.btn_plate.raise_() self.btn_gantry.raise_() MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1410, 26)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.toolBar = QtGui.QToolBar(MainWindow) self.toolBar.setObjectName(_fromUtf8("toolBar")) MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) self.retranslateUi(MainWindow) self.myStackedWidget.setCurrentIndex(0) self.mytabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.btn_connection, self.btn_tension) MainWindow.setTabOrder(self.btn_tension, self.btn_compression) MainWindow.setTabOrder(self.btn_compression, self.btn_flexural) MainWindow.setTabOrder(self.btn_flexural, self.btn_beamCol) MainWindow.setTabOrder(self.btn_beamCol, self.btn_plate) MainWindow.setTabOrder(self.btn_plate, self.btn_gantry) MainWindow.setTabOrder(self.btn_gantry, self.btn_openfile) MainWindow.setTabOrder(self.btn_openfile, self.btn_help) MainWindow.setTabOrder(self.btn_help, self.rdbtn_seat) MainWindow.setTabOrder(self.rdbtn_seat, self.rdbtn_finplate) MainWindow.setTabOrder(self.rdbtn_finplate, self.rdbtn_cleat) MainWindow.setTabOrder(self.rdbtn_cleat, self.rdbtn_endplate) MainWindow.setTabOrder(self.rdbtn_endplate, self.btn_start) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Osdag", None)) self.btn_help.setText(_translate("MainWindow", "Help", None)) self.btn_openfile.setText(_translate("MainWindow", "Open file", None)) __sortingEnabled = self.myListWidget.isSortingEnabled() self.myListWidget.setSortingEnabled(False) item = self.myListWidget.item(0) item.setText(_translate("MainWindow", " Design :", None)) self.myListWidget.setSortingEnabled(__sortingEnabled) self.mytabWidget.setToolTip(_translate("MainWindow", "<html><head/><body><p><a href=\"#\">Shear Connection</a></p></body></html>", None)) self.label_2.setText(_translate("MainWindow", "Finplate", None)) self.rdbtn_finplate.setShortcut(_translate("MainWindow", "Shift+F", None)) self.label_3.setText(_translate("MainWindow", "Cleat Angle", None)) self.rdbtn_cleat.setShortcut(_translate("MainWindow", "Shift+C", None)) self.label_4.setText(_translate("MainWindow", "Endplate", None)) self.rdbtn_endplate.setShortcut(_translate("MainWindow", "Shift+E", None)) self.label_5.setText(_translate("MainWindow", "Seated Angle", None)) self.rdbtn_seat.setShortcut(_translate("MainWindow", "Shift+S", None)) self.btn_start.setText(_translate("MainWindow", "Start", None)) self.mytabWidget.setTabText(self.mytabWidget.indexOf(self.tab1_shearconnection), _translate("MainWindow", "Shear Connection", None)) self.mytabWidget.setTabText(self.mytabWidget.indexOf(self.tab2_momentconnection), _translate("MainWindow", "Moment Connection", None)) self.label.setText(_translate("MainWindow", "Coming Soon ...", None)) self.btn_connection.setText(_translate("MainWindow", "Connection", None)) self.btn_tension.setText(_translate("MainWindow", "Tension Member", None)) self.btn_compression.setText(_translate("MainWindow", "Compression Member", None)) self.btn_flexural.setText(_translate("MainWindow", "Flexural Member", None)) self.btn_beamCol.setText(_translate("MainWindow", "Beam-Column", None)) self.btn_plate.setText(_translate("MainWindow", "Plate Girder", None)) self.btn_gantry.setText(_translate("MainWindow", "Gantry Girder", None)) self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None)) import osdagMainPageIcons_rc if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
b7d73d835b90fc52ab92d464f4c85ecdd83a22e0
65b1928c13b087087cf25a02d411bce5f67a3c5e
/rust-hexify/hexify.py
03c5b796b50a29944ce50a7d2feda6936ca8d654
[]
no_license
jwasinger/scripts
428841dca43ef5170cb4f9923f7d25160df21144
d5aee48c62ba788706f854632ba837f5ed2dfe62
refs/heads/master
2020-05-31T07:55:48.141455
2019-06-04T10:06:32
2019-06-04T10:06:32
190,176,632
0
0
null
null
null
null
UTF-8
Python
false
false
192
py
import sys, getopt, binascii h = sys.argv[1] if len(h) % 2 != 0: h = '0'+h h = [h[i:i+2] for i in range(0, len(h), 2)] h = map(lambda x: '0x'+x, h) h = '[' + ', '.join(h) + ']' print(h)
35d44a8f349d80fc60e1d2643f778e76359d4ebf
9cf4e79728997aee49764b896fe763276a3a7813
/predict.py
8995fea31e6622f8a937aafd9977d5f40cdb796b
[]
no_license
chenying99/retinaface-keras-1
c0509f49b483cc4edb73516d5154af95acbc448c
172791452afc8a937be7bc5d20be1ec2402c9c87
refs/heads/master
2022-12-07T13:21:24.349919
2020-08-17T05:26:08
2020-08-17T05:26:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
580
py
#-------------------------------------# # 对单张图片进行预测 #-------------------------------------# from retinaface import Retinaface import cv2 retinaface = Retinaface() while True: img = input('Input image filename:') image = cv2.imread(img) if image is None: print('Open Error! Try again!') continue else: image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) r_image = retinaface.detect_image(image) r_image = cv2.cvtColor(r_image,cv2.COLOR_RGB2BGR) cv2.imshow("after",r_image) cv2.waitKey(0)
d404ca84b2fb9569b41a3dc66411b472fe657657
3077c03f8375c53d10177685c60652d362fbbe24
/src/pawapp/migrations/0001_initial.py
b1a9258f07638465d33584138beabea885d7efa4
[ "MIT" ]
permissive
abnerpc/paw
c572b509f11dc74e11f6355be4ed69aaad10684d
cd630802fe19f00983e92c49b9edbcd21c6916f3
refs/heads/master
2021-06-20T17:19:55.888940
2019-07-06T22:43:07
2019-07-06T22:43:07
126,036,933
0
0
MIT
2018-04-26T13:20:00
2018-03-20T15:09:42
Python
UTF-8
Python
false
false
3,068
py
# Generated by Django 2.0.3 on 2018-07-05 14:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Bill', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone_number', models.CharField(max_length=11)), ('year', models.PositiveSmallIntegerField()), ('month', models.PositiveSmallIntegerField()), ('total_duration', models.PositiveIntegerField()), ('total_amount', models.DecimalField(decimal_places=2, max_digits=8)), ], ), migrations.CreateModel( name='BillItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone_number', models.CharField(max_length=11)), ('from_timestamp', models.CharField(max_length=20)), ('to_timestamp', models.CharField(max_length=20)), ('duration', models.PositiveIntegerField()), ('amount', models.DecimalField(decimal_places=2, max_digits=8)), ('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pawapp.Bill')), ], ), migrations.CreateModel( name='CallEvent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('call_type', models.CharField(choices=[('start', 'Start'), ('end', 'End')], max_length=5)), ('call_timestamp', models.CharField(max_length=20)), ('call_id', models.CharField(db_index=True, max_length=32)), ('source_number', models.CharField(blank=True, max_length=11, null=True)), ('destination_number', models.CharField(blank=True, max_length=11, null=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='ConnectionRate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('from_time', models.TimeField()), ('to_time', models.TimeField()), ('standing_rate', models.DecimalField(decimal_places=2, max_digits=8)), ('minute_rate', models.DecimalField(decimal_places=2, max_digits=8)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), migrations.AlterUniqueTogether( name='callevent', unique_together={('call_type', 'call_id')}, ), migrations.AlterUniqueTogether( name='bill', unique_together={('phone_number', 'year', 'month')}, ), ]
912d24cf96d048018ff82d635907ce570a086d6f
3c8aaef535328f7c4d812cf086a637b27d891752
/interview/google/hard/LC679. 24 Game.py
9e3d378a0603da9c172ec985a2ea638862ffd65a
[]
no_license
zhangshv123/superjump
9339cd7f5e75d8a94be60d44c752267cc38183d3
7de5f69e6e44ca4e74d75fed2af390b3d2cbd2b9
refs/heads/master
2020-03-20T20:36:34.378950
2019-03-08T04:37:22
2019-03-08T04:37:22
137,696,605
1
0
null
null
null
null
UTF-8
Python
false
false
2,015
py
""" You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24. Example 1: Input: [4, 1, 8, 7] Output: True Explanation: (8-4) * (7-1) = 24 Example 2: Input: [1, 2, 1, 2] Output: False Note: The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12. """ """ Just go through all pairs of numbers a and b and replace them with a+b, a-b, a*b and a/b, . Use recursion for the now smaller list. Positive base case is the list being [24] (or close enough). I prevent division-by-zero by using b and a/b instead of just a/b. If b is zero, then b and a/b is zero. And it’s ok to have that zero, since a*b is zero as well. It’s not even a second zero, because I’m creating a set of the up to four operation results, so duplicates are ignored immediately. Oh and note that I’m using Python 3, so / is “true” division, not integer division like in Python 2. And it would be better to use fractions.Fraction instead of floats. I actually just realized that there is in fact an input where simple floats fail, namely [3, 3, 8, 8]. Floats calculate 23.999999999999989341858963598497211933135986328125 instead of 24. It’s not in the judge’s test suite, but it should be soon (Edit: it now is). Using Fraction however made my solution exceed the time limit, so I settled for the above approximation solution. """ def judgePoint24(self, nums): if len(nums) == 1: return math.isclose(nums[0], 24) return any(self.judgePoint24([x] + rest) for a, b, *rest in itertools.permutations(nums) for x in {a+b, a-b, a*b, b and a/b})
1acb17a465053f9cab22d26665d03512e51c7e21
4775712ef1d16495401311b4ffc4bd95c9004dc6
/ex3.py
cc3708c1eee0775bf53f3e1438f297b2285b589e
[]
no_license
Eihwazlol/lpthw
69447119c7f564b39844c9998a4fdc22890d5bed
0de02f2503873f5b5675706ae6f251073fdf8f64
refs/heads/master
2020-05-31T09:06:05.620009
2015-06-16T15:29:20
2015-06-16T15:29:20
37,537,776
0
0
null
null
null
null
UTF-8
Python
false
false
1,774
py
# -*- coding: utf-8 -*- #Affiche le texte "I Will now count my chickens:" print "I will now count my chickens:" #Affiche le texte "Hens" puis, le résultat de l'opération 25 + (30/6) = 25 + 5 = 30 print "Hens", 25.0+30.0/6.0 #Affiche le texte "Roosters" puis, le résultat de 100 - (4% de 75) = 100 - 3 = 97 print "Roosters", 100.0-25.0*3.0%4.0 #Affiche le texte "Now I will count the eggs:" print "Now I will count the eggs:" #Affiche résultat de l'opération : 3+2+1-5+(4% de 1/10) = 7 print 3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6.0 #Affiche le texte "Is it true that 3 + 2 > 5 - 7?", Pas de résultat ou de True/False car l'opération est dans une chaine de caratères, et donc, est ignorée. print "Is it true that 3 + 2 < 5 - 7?" #Affiche si l'affirmation est Vraie ou Fausse. Est-ce que 5 est plus petit que moins - 2 ? Non, donc "False" print 3.0+2.0<5.0-7.0 #Affiche le texte "What is 3+2? puis, le résultat l'opération : 5 print "What is 3+2?", 3.0+2.0 #Affiche le texte "What is 5-7?" puis, le résultat de l'opération : -2 print "What is 5-7?", 5.0-7.0 #Affiche le texte "Oh, that's why it's False." print "Oh, that's why it's False." #Affiche le texte "How about some more." print "How about some more." #Affiche le texte "Is it greater?" puis, si l'affirmation est Vraie ou Fausse. Est-ce que 5 est plus grand que -2 ? Oui, donc "True" print "Is it greater?", 5.0>-2.0 #Affiche le texte "Is is greater or equal?" puis, si l'affirmation est Vraie ou Fausse. Est-ce que 5 est plus grand ou égal à -2 ? Oui, donc "True" print "Is it greater or equal?",5.0>=-2.0 #Affiche le texte "Is it less or equal?" puis, si l'affirmation est Vraie ou Fausse. Est-ce que 5 est plus petit ou égal à -2 ? Non, donc "False" print "Is it less or equal?", 5.0<=-2.0
[ "utilisateur@DebianTest" ]
utilisateur@DebianTest
241d5eb6cc0c4cf43ed0165bacdcb5bd360c9b09
25fce92ad8b2ed971ff6e416228f4cb34c9dd49f
/Tabla_Alumnos.py
4e47b437a1f9323c29d20e400d183c74428b807b
[]
no_license
nestorcuello/prueba
3ac44f1f3d437ecba6d2c56c2ee4b7d7895d542d
e22a917482fb4e4b87c44c9c515d7571d1623c5c
refs/heads/master
2021-01-22T04:36:51.738592
2013-07-10T16:15:06
2013-07-10T16:15:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,074
py
import wx import MySQLdb from db_conn import DBConn class Tabla_Alum(wx.Panel): def Consulta_NumControl(self,event): Control= self.Num_Control.GetValue() #table =self.table busqueda ="SELECT * FROM alumno WHERE No_Cont = '%s'" % (Control) #self.buscar(Control,table) try: cursor = self.referencia.cursor() cursor.execute(busqueda) except: print "error en ejecucion" #Preprarmos la consulta para mostrar todos los registros de la tabla Alumnos donde el nombre sea igual al ingresado por el usuario. try: results = cursor.fetchall() for row in results: #Asignacion de Datos Control = str(row[0]) Nombre =str(row[1]) Materno = str(row[2]) Paterno = str( row[3] ) Telefono = str(row[4]) Correo = str(row[5]) #Impresion de los datos en los campos self.Num_Control.SetValue("%s\n" % (Control)) self.NOMBRE.SetValue("%s\n" % (Nombre)) self.Materno.SetValue("%s\n" % (Materno)) self.Paterno.SetValue("%s\n" % (Paterno)) self.Telefono.SetValue("%s\n" % (Telefono)) self.Correo.SetValue("%s\n"%(Correo)) except: print "error" def Actualizar(self,event): #Preparamos la consulta sql para modificar los datos de la tabla alumnos, #donde el numero de carnet sea igual al ingresado por el usuario anteriormente. cursor = self.referencia.cursor() #table = self.table Al_NcontrolA= self.Num_Control.GetValue() Al_apellidopA= self.NOMBRE.GetValue() Al_apellidomA=self.Materno.GetValue() Al_NombreA=self.Paterno.GetValue() Al_direccionA= self.Telefono.GetValue() Al_telefonoA=self.Correo.GetValue() sql = "UPDATE alumno SET No_Cont = '%s', nombre = '%s', Materno= '%s', Paterno= '%s',Telefono='%s',Correo='%s' WHERE No_Cont = '%s' " %(Al_NcontrolA,Al_apellidopA,Al_apellidomA,Al_NombreA,Al_direccionA,Al_telefonoA,Al_NcontrolA) try: #Ejecutamos cursor.execute(sql) #Guardamos self.referencia.commit() except: self.referencia.rollback() def Altas(self,event): cursor=self.referencia.cursor() Al_NcontrolA= self.Num_Control.GetValue() Al_apellidopA= self.NOMBRE.GetValue() Al_apellidomA=self.Materno.GetValue() Al_NombreA=self.Paterno.GetValue() Al_direccionA= self.Telefono.GetValue() Al_telefonoA=self.Correo.GetValue() sql='insert into alumno (No_Cont,nombre,Materno,Paterno,Telefono,Correo) values ("' + Al_NcontrolA +'" , "' + Al_apellidopA +'" , "' + Al_apellidomA +'", "' + Al_NombreA +'", "' + Al_direccionA +'", "' + Al_telefonoA +'")' try: cursor.execute(sql) cursor.close() self.referencia.commit() self.Limpiar() except: cursor.rollback() def borrar(self,event): Control= self.Num_Control.GetValue() cursor=self.referencia.cursor() sql = "DELETE FROM alumno WHERE No_Cont = '%s'" % Control try: cursor.execute(sql) cursor.close() self.referencia.commit() limpiar() except: cursor.rollback() def Limpiar(self): #Impresion de los datos en los campos self.Num_Control.SetValue("") self.NOMBRE.SetValue("") self.Materno.SetValue("") self.Paterno.SetValue("") self.Telefono.SetValue("") self.Correo.SetValue("") def clrCampos(self,event): self.Limpiar() def variables (self,usuario,contra): self.host='localhost' self.user=usuario#'root' self.passw=contra#'amairani26' self.database='sistema_alumno' self.referencia=' ' self.table = '' return MySQLdb.connect(self.host, self.user, self.passw, self.database) def __init__(self,parent, id,usuario,contra): # cracion del panel wx.Panel.__init__(self, parent, id) self.SetBackgroundColour("yellow") self.referencia = self.variables(usuario,contra) #self.crearEstructura() titulo = wx.StaticText(self, -1, 'BASE DE DATOS', (375, 15)) titulo_font = titulo.GetFont() titulo_font.SetWeight(wx.BOLD) titulo.SetFont(titulo_font) wx.StaticLine(self, -1, (30, 70), (850,5)) #label y texbox de Numero De Control self.Num_Control = wx.StaticText(self, -1, "Numero de Control", pos = (60,100)) self.Num_Control = wx.TextCtrl(self, -1, "", pos = (60, 120), size =(100,20)) self.Num_Control.SetBackgroundColour("white") #label y texbox de Paterno self.NOMBRE = wx.StaticText(self, -1, "Nombre", pos = (200,100)) self.NOMBRE = wx.TextCtrl(self, -1, "", pos = (180, 120), size =(100,20)) self.NOMBRE.SetBackgroundColour("white") #label y texbox de Materno self.Materno = wx.StaticText(self, -1, "Apellido Materno", pos = (300,100)) self.Materno = wx.TextCtrl(self, -1, "", pos = (290, 120), size =(100,20)) self.Materno.SetBackgroundColour("white") #label y texbox de Nombre self.Paterno = wx.StaticText(self, -1, "Apellido Paterno", pos = (425,100)) self.Paterno = wx.TextCtrl(self, -1, "", pos = (400, 120), size =(100,20)) self.Paterno.SetBackgroundColour("white") #label y texbox de Direccion self.Telefono = wx.StaticText(self, -1, "Telefono", pos = (535,100)) self.Telefono = wx.TextCtrl(self, -1, "", pos = (510, 120), size =(100,20)) self.Telefono.SetBackgroundColour("white") #label y texbox de Ciudad self.Correo = wx.StaticText(self, -1, "Correo", pos = (670,100)) self.Correo = wx.TextCtrl(self, -1, "", pos = (650, 120), size =(100,20)) self.Correo.SetBackgroundColour("white") wx.StaticLine(self, -1, (30, 170), (850,5)) #Boton De Consulta Boton = wx.Button(self, -1, 'CONSULTA', pos=(150,180), size = (100,50)) self.Bind(wx.EVT_BUTTON, self.Consulta_NumControl, id=Boton.GetId()) #Boton De ACTUALIZACIONES Boton = wx.Button(self, -1, 'ACTUALIZACIONES', pos=(300,180), size = (100,50)) self.Bind(wx.EVT_BUTTON, self.Actualizar, id=Boton.GetId()) #Boton De BORRAR REGISTRO Boton = wx.Button(self, -1, 'BORRAR\nREGISTRO', pos=(450,180), size = (100,50)) self.Bind(wx.EVT_BUTTON, self.borrar, id=Boton.GetId()) #Boton De Altas Boton = wx.Button(self, -1, 'ALTAS', pos=(600,180), size = (100,50)) self.Bind(wx.EVT_BUTTON, self.Altas, id=Boton.GetId()) #Boton De Limpiar Casillas Boton = wx.Button(self, -1, 'LIMPIAR\nCAMPOS', pos=(375,250), size = (100,50)) self.Bind(wx.EVT_BUTTON, self.clrCampos, id=Boton.GetId()) # creamos una clase donde se deriva el modulo wx.App #class MainAlu(wx.App): # wxWindows llama a este metodo para ser inicializado # def OnInit(self): #crear los objetos de la clase MyFrame # frame = wx.MiniFrame(None, -1, 'SISTEMA ALUMNOS.py', size=(900, 425),style= wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX| wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX) # Tabla_Alum(frame,-1) # frame.Centre() # frame.Show() #WxWindows entonces identificara esta como nuestra ventana principal # self.SetTopWindow(frame) # regresa verdadero cuando esta bien # return True #app = MainAlu(0) # Crea una instancia de la aplicacion cronometor #app.MainLoop() # hace la ejecucion del widget y lo deja en espera #
f164c04e1dd5b25b98f499d8d3191f0703c1d97c
563e77c2493d9b2e1bd44f73978b25233a0b0a0f
/vmcloak/exceptions.py
63d933c6434e665711d19922d7510383ce241f5a
[]
no_license
mcpacosy/vmcloak
a824d50e82ef08678b91570e4c49c884c9b5823d
fff3f1837ae75c61df5f8e4682590500b498e25b
refs/heads/master
2021-01-20T21:56:18.367092
2014-12-24T06:21:54
2014-12-24T06:21:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
195
py
# Copyright (C) 2014 Jurriaan Bremer. # This file is part of VMCloak - http://www.vmcloak.org/. # See the file 'docs/LICENSE.txt' for copying permission. class CommandError(Exception): pass
e9a654100a20483c05a320db7178ffda25587447
eab81ff76637addfbc969e3fddc29aac5e608c50
/code/advanced_algorithms_problems/list_3/2.i_can_guess_the_data_structure.py
c570e2c60786168aa59c1da4e2615e0a82580be8
[]
no_license
hadrizia/coding
f629a023a1a9a303ee0480c6c2708ea92403314b
a1e7304a57922428398291de49f3eff78f8e7e55
refs/heads/master
2021-11-11T10:16:05.478379
2021-11-05T15:26:43
2021-11-05T15:26:43
183,800,041
1
1
null
null
null
null
UTF-8
Python
false
false
1,789
py
''' There is a bag-like data structure, supporting two operations: 1 x Throw an element x into the bag. 2 Take out an element from the bag. Given a sequence of operations with return values, you're going to guess the data structure. It is a stack (Last-In, First-Out), a queue (First-In, First-Out), a priority-queue (Always take out larger elements first) or something else that you can hardly imagine! Link: https://www.urionlinejudge.com.br/judge/en/problems/view/1340 ''' def guess(n): ds = [] max_num = 0 is_stack = True is_queue = True is_priority_queue = True for _ in range(n): op, x = input().split(" ") x = int(x) if op == "1": ds.append(x) if x > max_num: max_num = x elif op == "2": if x not in ds: return 'impossible' else: if len(ds) > 1: if x == ds[-1] and is_stack: is_stack = True else: is_stack = False if x == ds[0] and is_queue: is_queue = True else: is_queue = False if x == max_num and is_priority_queue: is_priority_queue = True else: is_priority_queue = False ds.remove(x) if is_priority_queue and ds: max_num = max(ds) if ( (is_priority_queue and is_queue) or (is_stack and is_queue) or (is_priority_queue and is_stack)): return 'not sure' elif is_priority_queue: return 'priority queue' elif is_queue: return 'queue' elif is_stack: return 'stack' else: return 'impossible' def main(): while True: try: m = input().split(" ") if len(m) == 1: m = int(m[0]) print(guess(m)) except EOFError: break main()
5924b68b427ea1f4dffe7802dab0308f940eba4c
2d2c10ffa7aa5ee35393371e7f8c13b4fab94446
/projects/feed/rank/offline/train_and_predict_model/video/cp_model.py
1187c88f5142f3eeeece094fa35d05abe1e16008
[]
no_license
faker2081/pikachu2
bec83750a5ff3c7b5a26662000517df0f608c1c1
4f06d47c7bf79eb4e5a22648e088b3296dad3b2d
refs/heads/main
2023-09-02T00:28:41.723277
2021-11-17T11:15:44
2021-11-17T11:15:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
20
py
../tuwen/cp_model.py
6302806f4d9aace7a3f1ac2f1d4827b4213d33ba
f8c4b33a09d822986a59510a8091d8d66f72e300
/svdRec.py
3aa0e0d93916df53a21d2d3369f158d41f8d79b6
[]
no_license
louiss007/MachineLearning
420010954df639842f4841d070a6f17bc0d9642d
845d87265e928aed86ae163aeb1f3ddcac2d0480
refs/heads/master
2016-09-05T20:57:28.933262
2015-03-11T04:13:58
2015-03-11T04:13:58
9,974,699
0
0
null
null
null
null
UTF-8
Python
false
false
1,564
py
from sim import cosSim from numpy import * def loadExData(): return [[1,1,1,0,0], [2,2,2,0,0], [1,1,1,0,0], [5,5,5,0,0], [1,1,0,2,2], [0,0,0,3,3], [0,0,0,1,1]] def standEst(dataMat, user, simMeas, item): n = shape(dataMat)[1] simTotal = 0.0 ratSimTotal = 0.0 for j in range(n): userRating = dataMat[user, j] if userRating == 0: continue overLap = nonzero(logical_and(dataMat[:, item].A>0, \ dataMat[:,j].A>0))[0] if len(overLap) == 0: similarity = 0 else: similarity = simMeas(dataMat[overLap, item], \ dataMat[overLap,j]) #print 'the %d and %d similarity is: %f' % (item, j, similarity) simTotal += similarity ratSimTotal += similarity * userRating if simTotal == 0: return 0 else: return ratSimTotal/simTotal def recommend(dataMat, user, N=3, simMeas=cosSim, eatMethod=standEst): unratedItems = nonzero(dataMat[user,:].A == 0)[1] if len(unratedItems) == 0: return 'you rated everything' itemScores = [] for item in unratedItems: estimatedScore = eatMethod(dataMat, user, simMeas, item) itemScores.append((item, estimatedScore)) return sorted(itemScores, \ key=lambda jj:jj[1], reverse=True)[:N] #in the mode of command line ##myMat=np.mat(svdRec.loadExData()) myMat=mat(loadExData()) lis=recommend(myMat, 2)
8e0c55db0dec58659c7629e680a15bbfcbe09c49
738d651803bc479ef87a81fbaba6f1e926ea0065
/articles/admin.py
7cad8e3d39f13892d578dec63fa9d8f734973ab0
[]
no_license
smflanag/Aggregator
69f52a8786cd9993af3f5a578738d012b1557497
433afce3b052933aa75079d63960cad818df3e9f
refs/heads/master
2023-01-18T18:43:39.870019
2019-05-01T15:29:48
2019-05-01T15:29:48
118,258,419
0
0
null
2023-01-03T17:44:36
2018-01-20T16:09:01
Python
UTF-8
Python
false
false
171
py
from django.contrib import admin from articles.models import Article, Vote, Comment admin.site.register(Article) admin.site.register(Vote) admin.site.register(Comment)
f0d38ad0d85e125ff017f3eea4d21b7070ed4085
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/WPojigJER35bJT6YH_8.py
c7b39d677e4dc65f3f3bc24b2bae6d63908d8d9a
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
591
py
""" Write a function that takes an integer `n`, reverses the binary representation of that integer, and returns the new integer from the reversed binary. ### Examples reversed_binary_integer(10) ➞ 5 # 10 = 1010 -> 0101 = 5 reversed_binary_integer(12) ➞ 3 # 12 = 1100 -> 0011 = 3 reversed_binary_integer(25) ➞ 19 # 25 = 11001 -> 10011 = 19 reversed_binary_integer(45) ➞ 45 # 45 = 101101 -> 101101 = 45 ### Notes All values of `n` will be positive. """ def reversed_binary_integer(num): return int(str(bin(num))[2:][::-1],2)
0dff9c6f0d4f4e4b4389971c842a59076c76e8b1
0bb474290e13814c2498c086780da5096453da05
/abc041/C/main.py
e3bf39a21a47d89d8c3aa242cbde61eb057906ad
[]
no_license
ddtkra/atcoder
49b6205bf1bf6a50106b4ae94d2206a324f278e0
eb57c144b5c2dbdd4abc432ecd8b1b3386244e30
refs/heads/master
2022-01-25T15:38:10.415959
2020-03-18T09:22:08
2020-03-18T09:22:08
208,825,724
1
0
null
2022-01-21T20:10:20
2019-09-16T14:51:01
Python
UTF-8
Python
false
false
540
py
#!/usr/bin/env python3 import sys sys.setrecursionlimit(10000000) INF = 1<<32 def solve(N: int, a: "List[int]"): l = sorted(enumerate(a), key=lambda x:-x[1]) for i,v in l: print(i+1) return def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int a = [int(next(tokens)) for _ in range(N)] # type: "List[int]" solve(N, a) if __name__ == '__main__': main()
e73ef8f66086092d1fb696912304c6bba165efcc
1bfad01139237049eded6c42981ee9b4c09bb6de
/RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/mplsoam/router/interface/interface.py
36c2d3a3e9dc3c3ad66a6cd90bfc85c833ce7daf
[ "MIT" ]
permissive
kakkotetsu/IxNetwork
3a395c2b4de1488994a0cfe51bca36d21e4368a5
f9fb614b51bb8988af035967991ad36702933274
refs/heads/master
2020-04-22T09:46:37.408010
2019-02-07T18:12:20
2019-02-07T18:12:20
170,284,084
0
0
MIT
2019-02-12T08:51:02
2019-02-12T08:51:01
null
UTF-8
Python
false
false
21,060
py
# Copyright 1997 - 2018 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Interface(Base): """The Interface class encapsulates a user managed interface node in the ixnetwork hierarchy. An instance of the class can be obtained by accessing the Interface property from a parent instance. The internal properties list will be empty when the property is accessed and is populated from the server using the find method. The internal properties list can be managed by the user by using the add and remove methods. """ _SDM_NAME = 'interface' def __init__(self, parent): super(Interface, self).__init__(parent) @property def BfdCvType(self): """This signifies the BFD Connectivity Verification type. Possible values include: Returns: str(bfdCvTypeIpUdp|bfdCvTypePwAch) """ return self._get_attribute('bfdCvType') @BfdCvType.setter def BfdCvType(self, value): self._set_attribute('bfdCvType', value) @property def BfdDiscriminatorEnd(self): """This signifies the last BFD Discriminator value. This value should be greater than the BFD. Returns: number """ return self._get_attribute('bfdDiscriminatorEnd') @BfdDiscriminatorEnd.setter def BfdDiscriminatorEnd(self, value): self._set_attribute('bfdDiscriminatorEnd', value) @property def BfdDiscriminatorStart(self): """This signifies the first BFD Discriminator value. The default value is 5000. Returns: number """ return self._get_attribute('bfdDiscriminatorStart') @BfdDiscriminatorStart.setter def BfdDiscriminatorStart(self, value): self._set_attribute('bfdDiscriminatorStart', value) @property def ControlChannel(self): """This signifies the communication control channel. Possible values include Returns: str(controlChannelRouterAlert|controlChannelPwAch) """ return self._get_attribute('controlChannel') @ControlChannel.setter def ControlChannel(self, value): self._set_attribute('controlChannel', value) @property def DestinationAddressIpv4(self): """This signifies the destination IPv4 address. Returns: str """ return self._get_attribute('destinationAddressIpv4') @DestinationAddressIpv4.setter def DestinationAddressIpv4(self, value): self._set_attribute('destinationAddressIpv4', value) @property def DownStreamAddressType(self): """This signifies the address type of the downstream traffic. Possible values include: Returns: str(ipv4Numbered|ipv4UnNumbered|ipv6Numbered|ipv6UnNumbered) """ return self._get_attribute('downStreamAddressType') @DownStreamAddressType.setter def DownStreamAddressType(self, value): self._set_attribute('downStreamAddressType', value) @property def DownStreamInterfaceAddress(self): """This signifies the interface address of the downstream traffic. Returns: number """ return self._get_attribute('downStreamInterfaceAddress') @DownStreamInterfaceAddress.setter def DownStreamInterfaceAddress(self, value): self._set_attribute('downStreamInterfaceAddress', value) @property def DownStreamIpAddress(self): """This signifies the IPv4/IPv6 address of the downstream traffic. Returns: str """ return self._get_attribute('downStreamIpAddress') @DownStreamIpAddress.setter def DownStreamIpAddress(self, value): self._set_attribute('downStreamIpAddress', value) @property def EchoRequestInterval(self): """This signifies the minimum interval, in milliseconds, between received Echo packets that this interface is capable of supporting. Returns: number """ return self._get_attribute('echoRequestInterval') @EchoRequestInterval.setter def EchoRequestInterval(self, value): self._set_attribute('echoRequestInterval', value) @property def EchoResponseTimeout(self): """This signifies the minimum tiomeout interval, in milliseconds, between received Echo packets that this interface is capable of supporting. Returns: number """ return self._get_attribute('echoResponseTimeout') @EchoResponseTimeout.setter def EchoResponseTimeout(self, value): self._set_attribute('echoResponseTimeout', value) @property def EnableDownStreamMappingTlv(self): """This signifies the enablement of downstream mapping TLV. Returns: bool """ return self._get_attribute('enableDownStreamMappingTlv') @EnableDownStreamMappingTlv.setter def EnableDownStreamMappingTlv(self, value): self._set_attribute('enableDownStreamMappingTlv', value) @property def EnableDsIflag(self): """This signifies the activation of the DS I Flag. Returns: bool """ return self._get_attribute('enableDsIflag') @EnableDsIflag.setter def EnableDsIflag(self, value): self._set_attribute('enableDsIflag', value) @property def EnableDsNflag(self): """This signifies the activation of the DS N Flag. Returns: bool """ return self._get_attribute('enableDsNflag') @EnableDsNflag.setter def EnableDsNflag(self, value): self._set_attribute('enableDsNflag', value) @property def EnableFecValidation(self): """This signifies the selection of the check box to enable FEC validation. Returns: bool """ return self._get_attribute('enableFecValidation') @EnableFecValidation.setter def EnableFecValidation(self, value): self._set_attribute('enableFecValidation', value) @property def EnablePeriodicPing(self): """If true, the router is pinged at regular intervals. Returns: bool """ return self._get_attribute('enablePeriodicPing') @EnablePeriodicPing.setter def EnablePeriodicPing(self, value): self._set_attribute('enablePeriodicPing', value) @property def Enabled(self): """If true, it enables or disables the simulated router. Returns: bool """ return self._get_attribute('enabled') @Enabled.setter def Enabled(self, value): self._set_attribute('enabled', value) @property def FlapTxIntervals(self): """This signifies the number of seconds between route flaps for BFD. A value of zero means no flapping. Returns: number """ return self._get_attribute('flapTxIntervals') @FlapTxIntervals.setter def FlapTxIntervals(self, value): self._set_attribute('flapTxIntervals', value) @property def IncludePadTlv(self): """If true, includes Pad TLV in triggered ping. Returns: bool """ return self._get_attribute('includePadTlv') @IncludePadTlv.setter def IncludePadTlv(self, value): self._set_attribute('includePadTlv', value) @property def IncludeVendorEnterpriseNumberTlv(self): """If true, includes the TLV number of the vendor, in triggered ping. Returns: bool """ return self._get_attribute('includeVendorEnterpriseNumberTlv') @IncludeVendorEnterpriseNumberTlv.setter def IncludeVendorEnterpriseNumberTlv(self, value): self._set_attribute('includeVendorEnterpriseNumberTlv', value) @property def Interfaces(self): """This signifies the interfaces that are associated with the selected interface type.Object references are: Returns: str(None|/api/v1/sessions/1/ixnetwork/vport?deepchild=interface) """ return self._get_attribute('interfaces') @Interfaces.setter def Interfaces(self, value): self._set_attribute('interfaces', value) @property def MinRxInterval(self): """This signifies the minimum interval, in milliseconds, between received BFD Control packets that this interface is capable of supporting. Returns: number """ return self._get_attribute('minRxInterval') @MinRxInterval.setter def MinRxInterval(self, value): self._set_attribute('minRxInterval', value) @property def Multiplier(self): """This signifies the negotiated transmit interval, multiplied by this value, provides the detection time for the interface. Returns: number """ return self._get_attribute('multiplier') @Multiplier.setter def Multiplier(self, value): self._set_attribute('multiplier', value) @property def PadTlvFirstOctet(self): """This signifies the selection of the first octate of the Pad TLV. Possible values include: Returns: str(dropPadTlvFromReply|copyPadTlvToReply) """ return self._get_attribute('padTlvFirstOctet') @PadTlvFirstOctet.setter def PadTlvFirstOctet(self, value): self._set_attribute('padTlvFirstOctet', value) @property def PadTlvLength(self): """This signifies the specification of the length of the Pad TLV. Returns: number """ return self._get_attribute('padTlvLength') @PadTlvLength.setter def PadTlvLength(self, value): self._set_attribute('padTlvLength', value) @property def ReplyMode(self): """This signifies the selecion of the mode of reply.Possible values include DoNotReply, ReplyViaApplicationLevelControlChannel, ReplyViaIpv4Ipv6UdpPacket and ReplyViaIpv4Ipv6UdpPacketWithRouterAlert. Returns: str(doNotReply|replyViaIpv4Ipv6UdpPacket|replyViaIpv4Ipv6UdpPacketWithRouterAlert|replyViaApplicationLevelControlChannel) """ return self._get_attribute('replyMode') @ReplyMode.setter def ReplyMode(self, value): self._set_attribute('replyMode', value) @property def TxInterval(self): """This signifies the minimum interval, in milliseconds, that the interface would like to use when transmitting BFD Control packets. Returns: number """ return self._get_attribute('txInterval') @TxInterval.setter def TxInterval(self, value): self._set_attribute('txInterval', value) @property def VendorEnterpriseNumber(self): """This signifies the specification of the enterprise number of the vendor. Returns: number """ return self._get_attribute('vendorEnterpriseNumber') @VendorEnterpriseNumber.setter def VendorEnterpriseNumber(self, value): self._set_attribute('vendorEnterpriseNumber', value) def add(self, BfdCvType=None, BfdDiscriminatorEnd=None, BfdDiscriminatorStart=None, ControlChannel=None, DestinationAddressIpv4=None, DownStreamAddressType=None, DownStreamInterfaceAddress=None, DownStreamIpAddress=None, EchoRequestInterval=None, EchoResponseTimeout=None, EnableDownStreamMappingTlv=None, EnableDsIflag=None, EnableDsNflag=None, EnableFecValidation=None, EnablePeriodicPing=None, Enabled=None, FlapTxIntervals=None, IncludePadTlv=None, IncludeVendorEnterpriseNumberTlv=None, Interfaces=None, MinRxInterval=None, Multiplier=None, PadTlvFirstOctet=None, PadTlvLength=None, ReplyMode=None, TxInterval=None, VendorEnterpriseNumber=None): """Adds a new interface node on the server and retrieves it in this instance. Args: BfdCvType (str(bfdCvTypeIpUdp|bfdCvTypePwAch)): This signifies the BFD Connectivity Verification type. Possible values include: BfdDiscriminatorEnd (number): This signifies the last BFD Discriminator value. This value should be greater than the BFD. BfdDiscriminatorStart (number): This signifies the first BFD Discriminator value. The default value is 5000. ControlChannel (str(controlChannelRouterAlert|controlChannelPwAch)): This signifies the communication control channel. Possible values include DestinationAddressIpv4 (str): This signifies the destination IPv4 address. DownStreamAddressType (str(ipv4Numbered|ipv4UnNumbered|ipv6Numbered|ipv6UnNumbered)): This signifies the address type of the downstream traffic. Possible values include: DownStreamInterfaceAddress (number): This signifies the interface address of the downstream traffic. DownStreamIpAddress (str): This signifies the IPv4/IPv6 address of the downstream traffic. EchoRequestInterval (number): This signifies the minimum interval, in milliseconds, between received Echo packets that this interface is capable of supporting. EchoResponseTimeout (number): This signifies the minimum tiomeout interval, in milliseconds, between received Echo packets that this interface is capable of supporting. EnableDownStreamMappingTlv (bool): This signifies the enablement of downstream mapping TLV. EnableDsIflag (bool): This signifies the activation of the DS I Flag. EnableDsNflag (bool): This signifies the activation of the DS N Flag. EnableFecValidation (bool): This signifies the selection of the check box to enable FEC validation. EnablePeriodicPing (bool): If true, the router is pinged at regular intervals. Enabled (bool): If true, it enables or disables the simulated router. FlapTxIntervals (number): This signifies the number of seconds between route flaps for BFD. A value of zero means no flapping. IncludePadTlv (bool): If true, includes Pad TLV in triggered ping. IncludeVendorEnterpriseNumberTlv (bool): If true, includes the TLV number of the vendor, in triggered ping. Interfaces (str(None|/api/v1/sessions/1/ixnetwork/vport?deepchild=interface)): This signifies the interfaces that are associated with the selected interface type.Object references are: MinRxInterval (number): This signifies the minimum interval, in milliseconds, between received BFD Control packets that this interface is capable of supporting. Multiplier (number): This signifies the negotiated transmit interval, multiplied by this value, provides the detection time for the interface. PadTlvFirstOctet (str(dropPadTlvFromReply|copyPadTlvToReply)): This signifies the selection of the first octate of the Pad TLV. Possible values include: PadTlvLength (number): This signifies the specification of the length of the Pad TLV. ReplyMode (str(doNotReply|replyViaIpv4Ipv6UdpPacket|replyViaIpv4Ipv6UdpPacketWithRouterAlert|replyViaApplicationLevelControlChannel)): This signifies the selecion of the mode of reply.Possible values include DoNotReply, ReplyViaApplicationLevelControlChannel, ReplyViaIpv4Ipv6UdpPacket and ReplyViaIpv4Ipv6UdpPacketWithRouterAlert. TxInterval (number): This signifies the minimum interval, in milliseconds, that the interface would like to use when transmitting BFD Control packets. VendorEnterpriseNumber (number): This signifies the specification of the enterprise number of the vendor. Returns: self: This instance with all currently retrieved interface data using find and the newly added interface data available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._create(locals()) def remove(self): """Deletes all the interface data in this instance from server. Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ self._delete() def find(self, BfdCvType=None, BfdDiscriminatorEnd=None, BfdDiscriminatorStart=None, ControlChannel=None, DestinationAddressIpv4=None, DownStreamAddressType=None, DownStreamInterfaceAddress=None, DownStreamIpAddress=None, EchoRequestInterval=None, EchoResponseTimeout=None, EnableDownStreamMappingTlv=None, EnableDsIflag=None, EnableDsNflag=None, EnableFecValidation=None, EnablePeriodicPing=None, Enabled=None, FlapTxIntervals=None, IncludePadTlv=None, IncludeVendorEnterpriseNumberTlv=None, Interfaces=None, MinRxInterval=None, Multiplier=None, PadTlvFirstOctet=None, PadTlvLength=None, ReplyMode=None, TxInterval=None, VendorEnterpriseNumber=None): """Finds and retrieves interface data from the server. All named parameters support regex and can be used to selectively retrieve interface data from the server. By default the find method takes no parameters and will retrieve all interface data from the server. Args: BfdCvType (str(bfdCvTypeIpUdp|bfdCvTypePwAch)): This signifies the BFD Connectivity Verification type. Possible values include: BfdDiscriminatorEnd (number): This signifies the last BFD Discriminator value. This value should be greater than the BFD. BfdDiscriminatorStart (number): This signifies the first BFD Discriminator value. The default value is 5000. ControlChannel (str(controlChannelRouterAlert|controlChannelPwAch)): This signifies the communication control channel. Possible values include DestinationAddressIpv4 (str): This signifies the destination IPv4 address. DownStreamAddressType (str(ipv4Numbered|ipv4UnNumbered|ipv6Numbered|ipv6UnNumbered)): This signifies the address type of the downstream traffic. Possible values include: DownStreamInterfaceAddress (number): This signifies the interface address of the downstream traffic. DownStreamIpAddress (str): This signifies the IPv4/IPv6 address of the downstream traffic. EchoRequestInterval (number): This signifies the minimum interval, in milliseconds, between received Echo packets that this interface is capable of supporting. EchoResponseTimeout (number): This signifies the minimum tiomeout interval, in milliseconds, between received Echo packets that this interface is capable of supporting. EnableDownStreamMappingTlv (bool): This signifies the enablement of downstream mapping TLV. EnableDsIflag (bool): This signifies the activation of the DS I Flag. EnableDsNflag (bool): This signifies the activation of the DS N Flag. EnableFecValidation (bool): This signifies the selection of the check box to enable FEC validation. EnablePeriodicPing (bool): If true, the router is pinged at regular intervals. Enabled (bool): If true, it enables or disables the simulated router. FlapTxIntervals (number): This signifies the number of seconds between route flaps for BFD. A value of zero means no flapping. IncludePadTlv (bool): If true, includes Pad TLV in triggered ping. IncludeVendorEnterpriseNumberTlv (bool): If true, includes the TLV number of the vendor, in triggered ping. Interfaces (str(None|/api/v1/sessions/1/ixnetwork/vport?deepchild=interface)): This signifies the interfaces that are associated with the selected interface type.Object references are: MinRxInterval (number): This signifies the minimum interval, in milliseconds, between received BFD Control packets that this interface is capable of supporting. Multiplier (number): This signifies the negotiated transmit interval, multiplied by this value, provides the detection time for the interface. PadTlvFirstOctet (str(dropPadTlvFromReply|copyPadTlvToReply)): This signifies the selection of the first octate of the Pad TLV. Possible values include: PadTlvLength (number): This signifies the specification of the length of the Pad TLV. ReplyMode (str(doNotReply|replyViaIpv4Ipv6UdpPacket|replyViaIpv4Ipv6UdpPacketWithRouterAlert|replyViaApplicationLevelControlChannel)): This signifies the selecion of the mode of reply.Possible values include DoNotReply, ReplyViaApplicationLevelControlChannel, ReplyViaIpv4Ipv6UdpPacket and ReplyViaIpv4Ipv6UdpPacketWithRouterAlert. TxInterval (number): This signifies the minimum interval, in milliseconds, that the interface would like to use when transmitting BFD Control packets. VendorEnterpriseNumber (number): This signifies the specification of the enterprise number of the vendor. Returns: self: This instance with matching interface data retrieved from the server available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._select(locals()) def read(self, href): """Retrieves a single instance of interface data from the server. Args: href (str): An href to the instance to be retrieved Returns: self: This instance with the interface data from the server available through an iterator or index Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ return self._read(href)
623d947f37093b012564538ad282c17d193723e8
2e84684e12f535af74639d076836240f9550c79e
/rock_paper_scissors.py
f954ec742b3df38b7a906b9b62bfb3b2e977f174
[]
no_license
DeCryptAF/Python-Stuffs
aaeb902181dfc33cabb54d22c4417e0137ef8317
fd45c4c91e73ba5957290e8c487172a6dd222d67
refs/heads/main
2023-08-04T16:30:56.241345
2023-07-26T15:44:39
2023-07-26T15:44:39
316,495,320
1
0
null
null
null
null
UTF-8
Python
false
false
1,940
py
import random, sys #Variables wins = 0 lose = 0 ties = 0 print("ROCK PAPER SCISSORS!!!!!") #Main Game Loop while True: print('%s wins, %s lose, %s ties' % (wins,lose,ties)) while True: #The player input print("Enter your move: (r)ock (p)aper (s)cissors or (q)uit") playerMove = input() if playerMove == 'q': sys.exit() #quit the programme if playerMove == 'r' or playerMove == 'p' or playerMove == 's': break #break out of the plauer input loop print('Type one of r, p ,s or q') #Display player choice if playerMove == 'r': print("ROCK versus...") elif playerMove == 'p': print("PAPER versus...") elif playerMove == 's': print("SCISSORS versus...") #Display what the computer choose: randomNumber = random.randint(1, 3) computerMove = '' if randomNumber == 1: computerMove = 'r' print("ROCK") elif randomNumber == 2: computerMove = 'p' print("PAPER") elif randomNumber == 3: computerMove = 's' print("SCISSORS") #Display the result if playerMove == computerMove: print("It's a tie") ties = ties + 1 elif playerMove == 'r' and computerMove == 'p': print("You lose!") lose = lose + 1 elif playerMove == "r" and computerMove == 's': print("You win!") wins = wins + 1 elif playerMove == "p" and computerMove == 's': print("You lose!") lose = lose + 1 elif playerMove == "p" and computerMove == 'r': print("You win!") wins = wins + 1 elif playerMove == "s" and computerMove == 'p': print("You win!") wins = wins + 1 elif playerMove == "s" and computerMove == 'r': print("You Lose!") lose = lose + 1