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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6585753cd7b6f354d9dcadc036862f1c9917be0c | b12de4e5869f413b3f7e96ff9ad9805dc582abb8 | /catkey.py | f9a6d8141b154562c9428e688bde96806a6362d5 | [] | no_license | JungleCatSW/pythings | 9ac4b3e82257899a20517eef31743bb6b8700363 | c5d9a9a132a1ad22ffc8bddf97460e6751146785 | refs/heads/master | 2021-05-05T05:03:24.739425 | 2018-02-09T21:08:38 | 2018-02-09T21:08:38 | 118,653,585 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,975 | py | import colorsys
import random
from openrazer.client import DeviceManager
from openrazer.client import constants as razer_constants
# Create a DeviceManager. This is used to get specific devices
device_manager = DeviceManager()
print("Found {} Razer devices".format(len(device_manager.devices)))
print()
# Disable daemon effect syncing.
# Without this, the daemon will try to set the lighting effect to every device.
device_manager.sync_effects = False
# Helper funciton to generate interesting colors
red = (255,8,8)
green = (100,255,0)
blue = (0,0,255)
lightblue = (128,128,255)
yellow = (255,255,0)
purple = (255,0,255)
mint = (0,255,255)
orange = (255,80,0)
white = (255,255,255)
def random_color():
rgb = colorsys.hsv_to_rgb(random.uniform(0, 1), random.uniform(0.5, 1), 1)
return tuple(map(lambda x: int(256 * x), rgb))
# Set random colors for each zone of each device
for device in device_manager.devices:
rows, cols = device.fx.advanced.rows, device.fx.advanced.cols
for row in range(rows):
for col in range(cols):
device.fx.advanced.matrix[row, col] = red
# f1 keys
device.fx.advanced.matrix[0, 1] = white
device.fx.advanced.matrix[0, 2] = blue
device.fx.advanced.matrix[0, 3] = purple
device.fx.advanced.matrix[0, 4] = purple
device.fx.advanced.matrix[0, 9] = yellow
device.fx.advanced.matrix[0, 10] = yellow
device.fx.advanced.matrix[0, 11] = lightblue
device.fx.advanced.matrix[0, 12] = lightblue
device.fx.advanced.matrix[0, 14] = white
device.fx.advanced.matrix[0, 15] = yellow
#number keys
device.fx.advanced.matrix[1, 1] = orange
device.fx.advanced.matrix[1, 12] = orange
device.fx.advanced.matrix[1, 13] = orange
device.fx.advanced.matrix[1, 14] = yellow
#first row letter keys
#tab
device.fx.advanced.matrix[2, 0] = lightblue
#device.fx.advanced.matrix[2, 1] = lightblue
device.fx.advanced.matrix[2, 12] = lightblue
device.fx.advanced.matrix[2, 13] = lightblue
# caps
device.fx.advanced.matrix[3, 0] = white
device.fx.advanced.matrix[3, 11] = purple
device.fx.advanced.matrix[3, 12] = purple
device.fx.advanced.matrix[3, 14] = green
device.fx.advanced.matrix[3, 15] = green
#shift rows
device.fx.advanced.matrix[4, 0] = mint
device.fx.advanced.matrix[4, 1] = mint
device.fx.advanced.matrix[4, 11] = orange
device.fx.advanced.matrix[4, 10] = orange
device.fx.advanced.matrix[4, 9] = orange
device.fx.advanced.matrix[4, 14] = mint
#ctrl
device.fx.advanced.matrix[5, 0] = yellow
device.fx.advanced.matrix[5, 1] = purple
device.fx.advanced.matrix[5, 2] = white
device.fx.advanced.matrix[5, 3] = blue
device.fx.advanced.matrix[5, 9] = blue
device.fx.advanced.matrix[5, 10] = purple
device.fx.advanced.matrix[5, 11] = yellow
device.fx.advanced.matrix[5, 12] = white
device.fx.advanced.matrix[5, 14] = white
device.fx.advanced.draw()
| [
"[email protected]"
] | |
8d7da6f2c9292a2ad5a6f2a3890fae0886b60128 | b1eec83eaeb12cd052e30cd573099134ee3be3c7 | /week2-medium2.py | 3cdf41f5087432ca3fbda521a5dbf86230fcfca4 | [] | no_license | helloangely/HackerRankPractice | 426071db299b675241bd5d7b7aa172b0fab7966b | b980ec790c416aec774b4d30a8134cf45029fee7 | refs/heads/master | 2020-12-30T12:54:47.197472 | 2017-05-23T02:59:05 | 2017-05-23T02:59:05 | 91,364,542 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 219 | py | # Python, Math, TrianlgeQuest
# https://www.hackerrank.com/challenges/python-quest-1
for i in range(1,input()): #More than 2 lines will result in 0 score. Do not leave a blank line also
print (pow(10,i)/9) * i
| [
"[email protected]"
] | |
621fefd7d64406e47dba080a9f797df2e99acd2c | a572609f6088998bbca1f5c90f03e0c546165904 | /foo.py | 94a3af51ec64ed8ddcfb9b111d58e2729800ce06 | [] | no_license | aayush240/Verse-Bot | d4a840875fa8b361969ffee6b247b3da8ef816d7 | 9950c2d7ddad8df6a65ab62b07af701841be9d05 | refs/heads/main | 2023-07-07T03:50:53.082035 | 2021-08-12T16:55:49 | 2021-08-12T16:55:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 337 | py | import os
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
VERIFY_TOKEN = "abc"
# MONGO_URI = "mongodb://localhost:27017/FbMessenger?retryWrites=true&w=majority"
MONGO_URI = os.getenv("MONGO_URI")
# AWS_ACCESS_KEY_ID = ""
# AWS_SECRET_ACCESS_KEY = ""
# S3_BUCKET_NAME = "verse-recordings"
# S3_URL_EXPIRE_AFTER = 7 * 24 * 60 * 60
| [
"[email protected]"
] | |
006edbae8c22e29bd133e000c53bd3de630964fb | 02c204cb9d4d0e4ed6642890db2b58f4d10b7ee0 | /saldo/cli/fetch.py | f7628a6d1a935019a7cbf4e6800f94c7272bca4d | [
"MIT"
] | permissive | dr-duplo/python-saldo | 493d14bc3564e86c3f21ab66484bb26c4477d7f9 | 4391296f8999b08303edd08bc93b961aed5b69f1 | refs/heads/master | 2020-06-03T05:37:52.348099 | 2019-07-20T10:43:09 | 2019-07-20T10:43:09 | 191,463,886 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,203 | py | import click
from colorama import Fore
from .transactions import print_transaction
class ClickProgressBarUpdater:
def __init__(self, bar):
self.bar = bar
self.progress = 0
def __call__(self, progress):
self.bar.update(progress - self.progress)
self.progress = progress
@click.command(name='fetch', help='Fetch and update account data.')
@click.option('--auto-tag', '-t', is_flag=True, help='Automatically tag new transactions.')
@click.option('--account-id', '-a', type=int, help='Account id to fetch data from.')
@click.pass_obj
def cli_fetch(model, auto_tag, account_id):
# try get account from option
account = model.accounts(id=account_id) if account_id else None
if account:
accounts = [account]
else:
accounts = model.accounts()
for account in accounts:
label = Fore.MAGENTA + "[%u]" % account.id + Fore.RESET
label += " Fetching data from " + Fore.WHITE + account.name + Fore.RESET
nt = []
with click.progressbar(length=100, label=label) as bar:
nt = model.fetch(auto_tag, account, ClickProgressBarUpdater(bar))
for t in nt:
print_transaction(t)
| [
"[email protected]"
] | |
f374980c9fb94d9f5da8904ed7b09f87afb80646 | b6d531f6f75c35556f9e0354d26deab8de721982 | /src/python/controller_server.py | 1cc3a9a501fc040c7633de1a2cdfc8824f721095 | [] | no_license | RajatGarga/Transport-Communication | e4e37899e40be95f215d0dc39e70b4770f6b5aad | 8b81ae1fccf381853bd856e6fe65286cc49b241e | refs/heads/master | 2020-05-09T20:40:50.161063 | 2019-12-01T14:08:43 | 2019-12-01T14:08:43 | 181,415,875 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 720 | py | from py4j.java_gateway import JavaGateway
from py4j.java_gateway import java_import
#to be done only once
gateway = JavaGateway()
java_import(gateway.jvm, 'tcom.Message')
java_import(gateway.jvm, 'wifi.WifiClient')
#use appropriate ip address for the communication module machine
client = gateway.jvm.WifiClient("127.0.0.1")
client.makeConnection()
m = gateway.jvm.Message('controller', 'small', '1')
m.setConnection("https://postb.in/1574061120923-6563683485146", "POST")
m.addRequestProperty("key1", "value1")
m.addRequestProperty("key2", "value2")
m.addRequestProperty("key3", "value3")
m.setData('Hello to the server!!') #POST data
response = client.sendMessage(m.getJSONString())
print("response : " + response) | [
"[email protected]"
] | |
b6af62fc18510a98e774b330e678fc1811193926 | dd251d101e70e84c92dcfb61a2c09696a8bc4103 | /main.py | 686005b4b2d1086e3269d7c1213192039ec2f118 | [] | no_license | ianwhale/dl_genomics | 7a222587ec658e2baf3204862a2768cab193e9a6 | 395a3902a94254b524323bd0e975f418b0eb18b0 | refs/heads/master | 2020-03-19T08:11:19.959332 | 2018-06-22T14:24:07 | 2018-06-22T14:24:07 | 136,183,065 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,029 | py | import os
import time
import torch
import random
import argparse
import numpy as np
import torch.optim as optim
from torch.autograd import Variable
from utils.stats import pearson_correlation
from torch.utils.data import TensorDataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from models.extractor import get_extractor
from models.regressor import Regressor
random.seed(0)
np.random.seed(0)
torch.manual_seed(0)
def str2bool(v):
"""See: https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse"""
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def main(args):
"""
Main entry point.
"""
cuda = torch.cuda.is_available()
X, y = torch.load("./data/geno_oh.pt"), torch.load("./data/pheno.pt").float()
args.input_length = X.shape[-1]
extractor = get_extractor(args)
out = extractor(Variable(X[0:1]))
if isinstance(out, tuple):
out, _ = out
extractor.zero_grad()
model = Regressor(out.shape[-1] * out.shape[-2], 1, extractor)
model.initialize_weights()
# metric = torch.nn.MSELoss()
n = int(0.8 * X.shape[0])
permuatation = [i for i in range(X.shape[0])]
random.shuffle(permuatation)
testing = permuatation[n:]
m = int(0.8 * n)
validation = permuatation[m:n]
training = permuatation[:m]
dataloaders = {
"train": DataLoader(TensorDataset(X, y), batch_size=args.batch_size, sampler=SubsetRandomSampler(training)),
"valid": DataLoader(TensorDataset(X, y), batch_size=args.batch_size, sampler=SubsetRandomSampler(validation)),
"test": DataLoader(TensorDataset(X, y), batch_size=args.batch_size, sampler=SubsetRandomSampler(testing))
}
if cuda:
model = model.cuda()
# metric = metric.cuda()
optimizer = optim.RMSprop(model.parameters())
if args.extractor == "sae":
# Need to train the autoencoder first.
if os.path.isfile("sae.pt"):
extractor.load_state_dict(torch.load("sae.pt"))
else:
# Train from scratch.
adam = optim.Adam(extractor.parameters())
mse = torch.nn.MSELoss()
if cuda:
mse = mse.cuda()
extractor.train()
for epoch in range(args.epochs):
start = time.time()
losses = []
for batch, _ in dataloaders["train"]:
batch = Variable(batch)
if cuda:
batch = batch.cuda()
_, decoded = extractor(batch)
loss = mse(decoded, batch)
loss.backward()
adam.step()
losses.append(loss.item())
print("Epoch {}: AE Training Loss: {:0.4f}, {:0.4f}s"
.format(epoch, np.mean(losses), time.time() - start))
torch.save(extractor.state_dict(), "sae.pt")
try:
for epoch in range(args.epochs):
start_time = time.time()
train_losses = []
train_accs = []
valid_accs = []
for stage in ["train", "valid"]:
if stage == "train":
model.train()
else:
model.eval()
loader = dataloaders[stage]
for batch, target in loader:
batch, target = Variable(batch), Variable(target)
if cuda:
batch, target = batch.cuda(), target.cuda()
optimizer.zero_grad()
output = model(batch)
if stage == "train":
# Multiply the correlation by -1 since we want to maximize correlation.
loss = -1 * pearson_correlation(output.squeeze(), target.squeeze())
loss.backward()
optimizer.step()
train_losses.append(loss.item())
train_accs.append(pearson_correlation(output.squeeze(), target.squeeze()).item())
if stage == "valid":
valid_accs.append(pearson_correlation(output.squeeze(), target.squeeze()).item())
print("Epoch {}, train loss {:0.4f}, train acc {:0.4f}, valid acc {:0.4f}, {:0.4f}s"
.format(epoch, np.mean(train_losses), np.mean(train_accs),
np.mean(valid_accs), time.time() - start_time))
except KeyboardInterrupt:
print("Caught keyboard interrupt, testing model.")
model.eval()
accs = []
for batch, target in dataloaders["test"]:
if cuda:
batch, target = batch.cuda(), target.cuda()
output = model(batch)
accs.append(pearson_correlation(output.squeeze(), target.squeeze()).item())
print("*" * 40)
print("Test acc {:0.4f}".format(np.mean(accs)))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="DL Genomics")
parser.add_argument("--in_channels", type=int, default=3, help="input channels of the genotype data")
parser.add_argument("--out_channels", type=int, default=16)
parser.add_argument("--filter_length", type=int, default=26)
parser.add_argument("--pool_length", type=int, default=3)
parser.add_argument("--pool_stride", type=int, default=3)
parser.add_argument("--epochs", type=int, default=10)
parser.add_argument("--batch_size", type=int, default=32)
parser.add_argument("--lstm", type=str2bool, default='true')
parser.add_argument("--extractor", type=str, default="sae", help="options: sae, danq")
parser.add_argument("--stacks", type=int, default=1)
parser.add_argument("--intermediate_size", type=int, default=256)
args = parser.parse_args()
main(args)
| [
"[email protected]"
] | |
d54b6f8b688482be6b329a67f8e9436cbad3c94f | 6d339650a11d79da9232d084b62107f0b60ab4f4 | /eval.py | 4ab74c97a24bdd268404e6802aa599856e65f8a4 | [
"MIT"
] | permissive | rajatmodi62/CVPR20_FGVC_PlantPatho | ca6211639cdbf90274519ab08f8803245e2a198e | 09dd0fca0d976670a38eac616905c1dcc3eee356 | refs/heads/master | 2022-09-01T00:13:30.553562 | 2020-05-27T05:00:21 | 2020-05-27T05:00:21 | 247,008,196 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,958 | py | import torch
from torch.utils.data import DataLoader
from os import (path, environ)
from tqdm import (trange, tqdm)
from dataset.dataset_factory import DatasetFactory
from transformer.transformer_factory import TransformerFactory
from model.model_factory import ModelFactory
from utils.evaluation_utils import EvaluationHelper
from utils.print_util import cprint
from utils.seed_backend import (seed_all, seed_worker)
def eval(config, device):
# Create pipeline objects
dataset_factory = DatasetFactory(org_data_dir='./data')
transformer_factory = TransformerFactory()
model_factory = ModelFactory()
evaluation_helper = EvaluationHelper(
config['experiment_name'],
overwrite=True,
ensemble=config['ensemble']
)
# =============================== Experiment loop =================================
for experiment_item in config['experiment_list']:
cprint("[ Experiment : ", experiment_item['experiment']
['path'], " ]", type="info2")
# seed backend
seed_all(config['seed'])
# ==================== Model testing / evaluation setup ========================
test_dataset = dataset_factory.get_dataset(
'test',
config['test_dataset']['name'],
transformer_factory.get_transformer(
height=experiment_item['experiment']['resize_dims'],
width=experiment_item['experiment']['resize_dims'],
pipe_type=experiment_item['experiment']['transform']
)
)
model = model_factory.get_model(
experiment_item['experiment']['name'],
config['num_classes'],
experiment_item['experiment']['pred_type'],
experiment_item['experiment']['hyper_params'],
None,
experiment_item['experiment']['path'],
experiment_item['experiment']['weight_type']
).to(device)
# ===============================================================================
# ===================== Model testing / evaluation loop ========================
model.eval()
test_output_list = []
experiment_item['experiment']["tta"] and cprint(
"[ TTA : ", str(experiment_item['experiment']["tta"]), " ]", type="success")
for tta_idx in range(5 if experiment_item['experiment']["tta"] else 1):
experiment_item['experiment']["tta"] and cprint(
"[ TTA index: ", str(tta_idx), " ]", type="info1")
intermediate_output_list = []
for batch_ndx, sample in enumerate(tqdm(DataLoader(
test_dataset,
batch_size=8,
num_workers=4,
worker_init_fn=seed_worker,
shuffle=False),
desc="Samples : ")
):
with torch.no_grad():
input = sample
input = input.to(device)
output = model.forward(input)
intermediate_output_list.append(output)
intermediate_output_list = torch.cat(
intermediate_output_list, dim=0)
test_output_list.append(intermediate_output_list)
test_output_list = torch.stack(test_output_list, dim=2)
# use this list to write using a helper
evaluation_helper.evaluate(
experiment_item['experiment']['pred_type'],
config['num_classes'],
experiment_item['experiment']['path'],
test_dataset.get_csv_path(),
test_output_list,
)
# ===============================================================================
if config['ensemble']:
evaluation_helper.ensemble(
test_dataset.get_csv_path(),
type="mean"
)
# ===================================================================================
| [
"[email protected]"
] | |
974c9ad08b078197e3468399af34ab42e855ee0c | 6411bd07879a36fa7ca89f92b78ed74f42c4344c | /hammerdemo/tests.py | ac560b6d9ae8c9551ecd7496742c26c4b0300c74 | [
"MIT"
] | permissive | hodgesds/django-hammer | 3b62c823888d02bf89ce54abbeaca8a432d0dba8 | 20594b79e12c4a9f6dd9ced1b46bd20d1ed53539 | refs/heads/master | 2023-08-09T11:23:51.511930 | 2014-12-15T03:45:28 | 2014-12-15T03:45:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 39,693 | py | import unittest
from django.test import TestCase, Client
from django.test import RequestFactory
import doctest
from django.core.urlresolvers import reverse, reverse_lazy
from hammerdemo import models
from hammerdemo.models import (
DemoPersonSiblings,
DemoPerson,
DemoPersonParents,
DemoFamilyPets,
DemoFamily,
DemoFamilyMembers,
DemoPet,
DemoPersonChildren,
)
from hammerdemo.views import (
DemopersonsiblingsListView,
DemopersonsiblingsDetailView,
DemopersonsiblingsCreateView,
DemopersonsiblingsUpdateView,
DemopersonsiblingsDeleteView,
DemopersonListView,
DemopersonDetailView,
DemopersonCreateView,
DemopersonUpdateView,
DemopersonDeleteView,
DemopersonparentsListView,
DemopersonparentsDetailView,
DemopersonparentsCreateView,
DemopersonparentsUpdateView,
DemopersonparentsDeleteView,
DemofamilypetsListView,
DemofamilypetsDetailView,
DemofamilypetsCreateView,
DemofamilypetsUpdateView,
DemofamilypetsDeleteView,
DemofamilyListView,
DemofamilyDetailView,
DemofamilyCreateView,
DemofamilyUpdateView,
DemofamilyDeleteView,
DemofamilymembersListView,
DemofamilymembersDetailView,
DemofamilymembersCreateView,
DemofamilymembersUpdateView,
DemofamilymembersDeleteView,
DemopetListView,
DemopetDetailView,
DemopetCreateView,
DemopetUpdateView,
DemopetDeleteView,
DemopersonchildrenListView,
DemopersonchildrenDetailView,
DemopersonchildrenCreateView,
DemopersonchildrenUpdateView,
DemopersonchildrenDeleteView,
)
class DemopersonsiblingsListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonsiblings_list"))
view = DemopersonsiblingsListView.as_view(template_name='demopersonsiblings_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopersonsiblings_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopersonsiblings_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonsiblings_list"))
view = DemopersonsiblingsListView.as_view(template_name='demopersonsiblings_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemopersonsiblingsDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonsiblings_detail", kwargs={'pk':1}))
view = DemopersonsiblingsDetailView.as_view(template_name='demopersonsiblings_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonsiblings_detail", kwargs={'pk':1}))
view = DemopersonsiblingsDetailView.as_view(template_name='demopersonsiblings_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemopersonsiblingsCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonsiblings_create"))
view = DemopersonsiblingsCreateView.as_view(template_name='demopersonsiblings_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonsiblings_create"))
view = DemopersonsiblingsCreateView.as_view(template_name='demopersonsiblings_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemopersonsiblingsUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonsiblings_update", kwargs={'pk':1}))
view = DemopersonsiblingsUpdateView.as_view(template_name='demopersonsiblings_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopersonsiblings_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopersonsiblings_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonsiblings_update", kwargs={'pk':1}))
view = DemopersonsiblingsUpdateView.as_view(template_name='demopersonsiblings_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonsiblingsDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonsiblings_delete", kwargs={'pk':1}))
view = DemopersonsiblingsDeleteView.as_view(template_name='demopersonsiblings_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonsiblings_delete", kwargs={'pk':1}))
view = DemopersonsiblingsDeleteView.as_view(template_name='demopersonsiblings_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demoperson_list"))
view = DemopersonListView.as_view(template_name='demoperson_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demoperson_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demoperson_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demoperson_list"))
view = DemopersonListView.as_view(template_name='demoperson_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemopersonDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demoperson_detail", kwargs={'pk':1}))
view = DemopersonDetailView.as_view(template_name='demoperson_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demoperson_detail", kwargs={'pk':1}))
view = DemopersonDetailView.as_view(template_name='demoperson_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemopersonCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demoperson_create"))
view = DemopersonCreateView.as_view(template_name='demoperson_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demoperson_create"))
view = DemopersonCreateView.as_view(template_name='demoperson_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemopersonUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demoperson_update", kwargs={'pk':1}))
view = DemopersonUpdateView.as_view(template_name='demoperson_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demoperson_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demoperson_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demoperson_update", kwargs={'pk':1}))
view = DemopersonUpdateView.as_view(template_name='demoperson_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demoperson_delete", kwargs={'pk':1}))
view = DemopersonDeleteView.as_view(template_name='demoperson_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demoperson_delete", kwargs={'pk':1}))
view = DemopersonDeleteView.as_view(template_name='demoperson_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonparentsListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonparents_list"))
view = DemopersonparentsListView.as_view(template_name='demopersonparents_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopersonparents_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopersonparents_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonparents_list"))
view = DemopersonparentsListView.as_view(template_name='demopersonparents_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemopersonparentsDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonparents_detail", kwargs={'pk':1}))
view = DemopersonparentsDetailView.as_view(template_name='demopersonparents_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonparents_detail", kwargs={'pk':1}))
view = DemopersonparentsDetailView.as_view(template_name='demopersonparents_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemopersonparentsCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonparents_create"))
view = DemopersonparentsCreateView.as_view(template_name='demopersonparents_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonparents_create"))
view = DemopersonparentsCreateView.as_view(template_name='demopersonparents_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemopersonparentsUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonparents_update", kwargs={'pk':1}))
view = DemopersonparentsUpdateView.as_view(template_name='demopersonparents_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopersonparents_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopersonparents_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonparents_update", kwargs={'pk':1}))
view = DemopersonparentsUpdateView.as_view(template_name='demopersonparents_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonparentsDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonparents_delete", kwargs={'pk':1}))
view = DemopersonparentsDeleteView.as_view(template_name='demopersonparents_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonparents_delete", kwargs={'pk':1}))
view = DemopersonparentsDeleteView.as_view(template_name='demopersonparents_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemofamilypetsListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilypets_list"))
view = DemofamilypetsListView.as_view(template_name='demofamilypets_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demofamilypets_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demofamilypets_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilypets_list"))
view = DemofamilypetsListView.as_view(template_name='demofamilypets_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemofamilypetsDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilypets_detail", kwargs={'pk':1}))
view = DemofamilypetsDetailView.as_view(template_name='demofamilypets_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilypets_detail", kwargs={'pk':1}))
view = DemofamilypetsDetailView.as_view(template_name='demofamilypets_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemofamilypetsCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilypets_create"))
view = DemofamilypetsCreateView.as_view(template_name='demofamilypets_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilypets_create"))
view = DemofamilypetsCreateView.as_view(template_name='demofamilypets_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemofamilypetsUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilypets_update", kwargs={'pk':1}))
view = DemofamilypetsUpdateView.as_view(template_name='demofamilypets_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demofamilypets_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demofamilypets_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilypets_update", kwargs={'pk':1}))
view = DemofamilypetsUpdateView.as_view(template_name='demofamilypets_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemofamilypetsDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilypets_delete", kwargs={'pk':1}))
view = DemofamilypetsDeleteView.as_view(template_name='demofamilypets_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilypets_delete", kwargs={'pk':1}))
view = DemofamilypetsDeleteView.as_view(template_name='demofamilypets_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemofamilyListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamily_list"))
view = DemofamilyListView.as_view(template_name='demofamily_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demofamily_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demofamily_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamily_list"))
view = DemofamilyListView.as_view(template_name='demofamily_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemofamilyDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamily_detail", kwargs={'pk':1}))
view = DemofamilyDetailView.as_view(template_name='demofamily_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamily_detail", kwargs={'pk':1}))
view = DemofamilyDetailView.as_view(template_name='demofamily_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemofamilyCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamily_create"))
view = DemofamilyCreateView.as_view(template_name='demofamily_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamily_create"))
view = DemofamilyCreateView.as_view(template_name='demofamily_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemofamilyUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamily_update", kwargs={'pk':1}))
view = DemofamilyUpdateView.as_view(template_name='demofamily_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demofamily_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demofamily_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamily_update", kwargs={'pk':1}))
view = DemofamilyUpdateView.as_view(template_name='demofamily_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemofamilyDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamily_delete", kwargs={'pk':1}))
view = DemofamilyDeleteView.as_view(template_name='demofamily_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamily_delete", kwargs={'pk':1}))
view = DemofamilyDeleteView.as_view(template_name='demofamily_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemofamilymembersListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilymembers_list"))
view = DemofamilymembersListView.as_view(template_name='demofamilymembers_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demofamilymembers_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demofamilymembers_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilymembers_list"))
view = DemofamilymembersListView.as_view(template_name='demofamilymembers_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemofamilymembersDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilymembers_detail", kwargs={'pk':1}))
view = DemofamilymembersDetailView.as_view(template_name='demofamilymembers_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilymembers_detail", kwargs={'pk':1}))
view = DemofamilymembersDetailView.as_view(template_name='demofamilymembers_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemofamilymembersCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilymembers_create"))
view = DemofamilymembersCreateView.as_view(template_name='demofamilymembers_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilymembers_create"))
view = DemofamilymembersCreateView.as_view(template_name='demofamilymembers_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemofamilymembersUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilymembers_update", kwargs={'pk':1}))
view = DemofamilymembersUpdateView.as_view(template_name='demofamilymembers_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demofamilymembers_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demofamilymembers_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilymembers_update", kwargs={'pk':1}))
view = DemofamilymembersUpdateView.as_view(template_name='demofamilymembers_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemofamilymembersDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demofamilymembers_delete", kwargs={'pk':1}))
view = DemofamilymembersDeleteView.as_view(template_name='demofamilymembers_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demofamilymembers_delete", kwargs={'pk':1}))
view = DemofamilymembersDeleteView.as_view(template_name='demofamilymembers_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopetListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopet_list"))
view = DemopetListView.as_view(template_name='demopet_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopet_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopet_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopet_list"))
view = DemopetListView.as_view(template_name='demopet_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemopetDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopet_detail", kwargs={'pk':1}))
view = DemopetDetailView.as_view(template_name='demopet_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopet_detail", kwargs={'pk':1}))
view = DemopetDetailView.as_view(template_name='demopet_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemopetCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopet_create"))
view = DemopetCreateView.as_view(template_name='demopet_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopet_create"))
view = DemopetCreateView.as_view(template_name='demopet_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemopetUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopet_update", kwargs={'pk':1}))
view = DemopetUpdateView.as_view(template_name='demopet_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopet_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopet_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopet_update", kwargs={'pk':1}))
view = DemopetUpdateView.as_view(template_name='demopet_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopetDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopet_delete", kwargs={'pk':1}))
view = DemopetDeleteView.as_view(template_name='demopet_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopet_delete", kwargs={'pk':1}))
view = DemopetDeleteView.as_view(template_name='demopet_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonchildrenListViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def tearDown(self):
pass
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonchildren_list"))
view = DemopersonchildrenListView.as_view(template_name='demopersonchildren_list.html')
response = view(request)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopersonchildren_list") + "?format=json")
json_response = view(json_request)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopersonchildren_list") + "?format=xml")
xml_response = view(xml_request)
self.assertEqual(xml_response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonchildren_list"))
view = DemopersonchildrenListView.as_view(template_name='demopersonchildren_list.html')
response = view(request)
self.assertEqual(response.status_code, 405)
class DemopersonchildrenDetailViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonchildren_detail", kwargs={'pk':1}))
view = DemopersonchildrenDetailView.as_view(template_name='demopersonchildren_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonchildren_detail", kwargs={'pk':1}))
view = DemopersonchildrenDetailView.as_view(template_name='demopersonchildren_detail.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 405)
class DemopersonchildrenCreateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonchildren_create"))
view = DemopersonchildrenCreateView.as_view(template_name='demopersonchildren_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonchildren_create"))
view = DemopersonchildrenCreateView.as_view(template_name='demopersonchildren_create.html')
response = view(request)
self.assertEqual(response.status_code, 200)
class DemopersonchildrenUpdateViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonchildren_update", kwargs={'pk':1}))
view = DemopersonchildrenUpdateView.as_view(template_name='demopersonchildren_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
json_request = RequestFactory().get(reverse_lazy("demopersonchildren_update", kwargs={'pk':1}) + "?format=json")
json_response = view(request, pk=1)
self.assertEqual(json_response.status_code, 200)
xml_request = RequestFactory().get(reverse_lazy("demopersonchildren_update", kwargs={'pk':1}) + "?format=xml")
xml_response = view(xml_request, pk=1)
self.assertEqual(xml_request.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonchildren_update", kwargs={'pk':1}))
view = DemopersonchildrenUpdateView.as_view(template_name='demopersonchildren_update.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemopersonchildrenDeleteViewTest(TestCase):
multi_db = True
def setUp(self):
self.client = Client()
def test_get(self):
request = RequestFactory().get(reverse_lazy("demopersonchildren_delete", kwargs={'pk':1}))
view = DemopersonchildrenDeleteView.as_view(template_name='demopersonchildren_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
def test_post(self):
request = RequestFactory().post(reverse_lazy("demopersonchildren_delete", kwargs={'pk':1}))
view = DemopersonchildrenDeleteView.as_view(template_name='demopersonchildren_delete.html')
response = view(request, pk=1)
self.assertEqual(response.status_code, 200)
class DemoPersonSiblingsTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoPersonSiblings.objects.create(id = 1, from_person_id = 1, to_person_id = 1)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoPersonTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoPerson.objects.create(id = 1, sex = 1, first = 'test', last = 'test', age = 1, alive = True, spouse_id = 1)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoPersonParentsTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoPersonParents.objects.create(id = 1, from_person_id = 1, to_person_id = 1)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoFamilyPetsTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoFamilyPets.objects.create(id = 1, family_id = 1, pet_id = 1)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoFamilyTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoFamily.objects.create(id = 1, name = 'test')
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoFamilyMembersTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoFamilyMembers.objects.create(id = 1, family_id = 1, person_id = 1)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoPetTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoPet.objects.create(id = 1, sex = 1, owner_id = 1, name = 'test', age = 1, species = 'test', alive = True)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
class DemoPersonChildrenTest(TestCase):
multi_db = True
def setUp(self):
self.object = DemoPersonChildren.objects.create(id = 1, from_person_id = 1, to_person_id = 1)
def test_unicode(self):
self.assertEqual(self.object.__unicode__() == str(self.object.pk))
def tearDown(self):
self.object.delete()
# to enable doctests
#def load_tests(loader, tests, ignore):
# tests.addTests(doctest.DocTestSuite(models))
# return tests
| [
"[email protected]"
] | |
00ad15e722bbe99f8bd525bdc09a86c07a586422 | 2d77d81aca3e48c546fa3a6666437bcd7d82e46a | /Rest_Tuto/ApiTest/resources.py | 4d3f6e9b7b7c10428b72ce934346ade2e8e49522 | [] | no_license | DeveloperRachit/PythonDevelopment | 68e73af937a415a55e6dba980ca224e8ddb5bc7f | d11e2e83f7efbfebbf9f704c19eb117db499421b | refs/heads/master | 2020-03-30T12:02:39.962827 | 2019-02-08T02:45:34 | 2019-02-08T02:45:34 | 151,205,450 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 331 | py | from tastypie.resources import ModelResource
from ApiTest.models import Note
from tastypie.authorization import Authorization
class NoteResource(ModelResource):
class Meta:
queryset = Note.objects.all()
resource_name = 'note'
authorization=Authorization()
fields = ['title','created_at', 'body'] | [
"[email protected]"
] | |
db620e2a28a3a9ebb508d57da125d42cb9db8711 | f3cdad925bb118d8d8af8cf7ff54742755dc5452 | /chat/utils.py | a1cf3bacd2998e72d279fa91fe77548cf2673879 | [] | no_license | samul-1/channels-chat | 3a0049e12576e764e5887823afb868c1ec60d52c | 6f2f9203c79716437b513153ff48f06494f9eb71 | refs/heads/master | 2022-11-22T20:48:00.238819 | 2020-07-29T12:38:03 | 2020-07-29T12:38:03 | 273,239,496 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,050 | py | from channels.db import database_sync_to_async
from .exceptions import ClientError
from .models import Room
# This decorator turns this function from a synchronous function into an async one
# we can call from our async consumers, that handles Django DBs correctly.
# For more, see http://channels.readthedocs.io/en/latest/topics/databases.html
@database_sync_to_async
def get_room_or_error(room_id, user):
"""
Tries to fetch a room for the user, checking permissions along the way.
"""
# Check if the user is logged in
if not user.is_authenticated:
raise ClientError("USER_HAS_TO_LOGIN")
# Find the room they requested (by ID)
try:
room = Room.objects.get(pk=room_id)
except Room.DoesNotExist:
raise ClientError("ROOM_INVALID")
# Check permissions
# if room.staff_only and not user.is_staff:
# raise ClientError("ROOM_ACCESS_DENIED")
if not room.is_public and user != room.user_1 and user != room.user_2:
raise ClientError("ROOM_ACCESS_DENIED")
return room
| [
"[email protected]"
] | |
51cadcb33a6cacc2f3171f46e3f650426016e4f3 | 884fb2eea3496724619cf57e61eb1684057c33e5 | /task_02_03.py | 637fe6c268cd5abb080dae67354ca0e6835b3961 | [] | no_license | aleksandr-net/homework | bc82264d9374825e1d94127d5bd16ce815378ca5 | 16147714d9d831df2f6ba911887f869c695b0141 | refs/heads/master | 2021-05-16T13:24:35.647265 | 2017-11-13T11:40:20 | 2017-11-13T11:40:20 | 105,395,259 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 129 | py | #!/usr/bin/python3.5
def average(lst):
summa = 0
for i in lst:
summa += i
return round(summa / len(lst), 3)
| [
"[email protected]"
] | |
cede8c2ba0876a968c07602c23a489a154a733bd | 0e63fdc3a7523bbc65a21c59f16c6c69476f6349 | /tests/test_utils.py | e61c4a686693d21887c45771c4db709391862934 | [] | no_license | TTS1209/cdata | 847c657bc3d282e421b0f6e39ae3b7dfdba0ffa6 | b3fe55892cdb58dcc4d37213da4abdbf9990e57c | refs/heads/master | 2021-01-19T12:19:27.941304 | 2015-06-10T14:34:18 | 2015-06-10T14:34:18 | 69,587,482 | 1 | 0 | null | 2016-09-29T16:43:49 | 2016-09-29T16:43:48 | Python | UTF-8 | Python | false | false | 6,392 | py | import pytest
from cdata.utils import \
indent, comment, comment_wrap, empty_iterable, char_literal
def test_indent():
# By default it should not indent a single empty line
assert indent("") == ""
# ...unless forced
assert indent("", indent_empty_lines=True) == " "
assert indent("", indentation="\t", indent_empty_lines=True) == "\t"
# Should indent a non-empty line
assert indent("Hello, World!") == " Hello, World!"
assert indent("Hello, World!", indentation="\t") == "\tHello, World!"
# Should indent several lines
assert indent("Hello, World!\n"
"How are you?") == (" Hello, World!\n"
" How are you?")
assert indent("Hello, World!\n"
"How are you?",
indentation="\t") == ("\tHello, World!\n"
"\tHow are you?")
# Should skip blank lines
assert indent("Hello, World!\n"
"\n"
"How are you?") == (" Hello, World!\n"
"\n"
" How are you?")
# ...unless told otherwise
assert indent("Hello, World!\n"
"\n"
"How are you?",
indent_empty_lines=True) == (" Hello, World!\n"
" \n"
" How are you?")
def test_comment():
# Special case: empty comment
assert comment("") == ("/* */")
# Single line comment
assert comment("One-liner!") == ("/* One-liner! */")
# Multi-line comment
assert comment("Two-\nliner!") == ("/* Two-\n"
" * liner! */")
# Empty lines should have any excess whitespace trimmed
assert comment("Empty\n\nLine") == ("/* Empty\n"
" *\n"
" * Line */")
# Alternative comment style should be possible
assert comment("Alternative\n\nComment\nStyle", "// ", "// ", "") == \
("// Alternative\n"
"//\n"
"// Comment\n"
"// Style")
@pytest.mark.parametrize("string",
# |-----20 chars-----|
["no comment",
# Empty comments
"before\n"
"with /**/\n"
"after",
"before\n"
"with /* */\n"
"after",
"before\n"
"with /* */\n"
"after",
# Single line, non wrapping
"before\n"
"with /* no wrap */\n"
"after",
# Single line, non wrapping with end on own line
"before\n"
"with /* no wrap\n"
" */\n"
"after",
# Multi line, non wrapping
"before\n"
"with /* no wrap\n"
" * for me */\n"
"after",
# Multi line, non wrapping with end on its own line
"before\n"
"with /* no wrap\n"
" * for me\n"
" */\n"
"after",
# Multi line, with blank lines
"before\n"
"with /*\n"
" * no wrap\n"
" *\n"
" * for me\n"
" */\n"
"after",
# Multi line, with blank lines + trialing spaces
"before\n"
"with /* \n"
" * no wrap\n"
" * \n"
" * for me\n"
" */\n"
"after",
# Multiple comments
"before\n"
"with /* first */\n"
"between\n"
"again /* second */\n"
"after",
])
def test_comment_wrap_nop(string):
# Test that examples which require no wrapping are left unchanged.
assert comment_wrap(string, 20) == string
@pytest.mark.parametrize("string",
# |-----20 chars-----|
[
# Single line, wrapping
"before\n"
"with /* wrap right now */\n"
"after",
# Single line, wrapping with end on own line
"before\n"
"with /* wrap right now\n"
" */\n"
"after",
# Multi line, wrapping
"before\n"
"with /* wrap right now\n"
" * wrap again now */\n"
"after",
# Multi line, wrapping with end on its own line
"before\n"
"with /* wrap right now\n"
" * wrap again now\n"
" */\n"
"after",
# Multi line, with blank lines
"before\n"
"with /*\n"
" * wrap right now\n"
" *\n"
" * wrap again now\n"
" */\n"
"after",
# Multi line, with blank lines + trialing spaces
"before\n"
"with /* \n"
" * wrap right now\n"
" * \n"
" * wrap again now\n"
" */\n"
"after",
# Multiple comments
"before\n"
"with /* wrap right now */\n"
"between\n"
"again /* wrap again now */\n"
"after",
])
def test_comment_wrap(string):
max_length = 20
# Test that examples which require wrapping are wrapped appropriately
wrapped = comment_wrap(string, max_length)
# The line wrapping process should only *add* characters (e.g. add
# whitespace and comment continuations). Check that this is the case.
wi = 0
for char in string:
while wrapped[wi] != char:
wi += 1
assert wi < len(wrapped)
# Check that the intended goal of reducing the line-length has been achieved
for line in wrapped.splitlines():
assert len(line) < max_length
def test_empty_iterable():
# The empty iterable should work multiple times!
for _ in range(10):
assert list(empty_iterable) == []
def test_char_literal():
# Printable characters should be represented as literals (just test a random
# selection
assert char_literal(b"!") == "'!'"
assert char_literal(b"a") == "'a'"
assert char_literal(b"0") == "'0'"
assert char_literal(b"?") == "'?'"
assert char_literal(b"\"") == "'\"'"
# Characters which require escaping should be
assert char_literal(b"'") == "'\\''"
# Common special characters should work
assert char_literal(b"\n") == "'\\n'"
assert char_literal(b"\r") == "'\\r'"
assert char_literal(b"\t") == "'\\t'"
# Non-printable characters should be shown in hex
assert char_literal(b"\x00") == "'\\x00'"
assert char_literal(b"\xAA") == "'\\xaa'"
assert char_literal(b"\xFF") == "'\\xff'"
| [
"[email protected]"
] | |
3913619caa1e3098fd4baeb6c259119db89859a0 | bf815da9cc16326bd397c939bf4e5a7ce0d3261e | /Python3/Code_Challenges/ControlFlowAdvanced.py | 3e11387f437244277b2edf484e53a9e217d4bdde | [] | no_license | StingzLD/Codecademy | 2e6979afe49cfba1c0fc1038dc1a50f0649f5924 | a1a6f175758f6cd561cabd5bf050e219c1432930 | refs/heads/master | 2022-12-15T08:38:50.316955 | 2021-08-02T00:10:11 | 2021-08-02T00:10:11 | 172,606,261 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,295 | py | """
1. In Range
Create a function named in_range() that has three parameters named num, lower, and upper.
The function should return True if num is greater than or equal to lower and less than or equal to upper. Otherwise, return False.
"""
# Write your in_range function here:
def in_range(num, lower, upper):
if lower <= num and num <= upper:
return True
return False
# Uncomment these function calls to test your in_range function:
print(in_range(10, 10, 10))
# should print True
print(in_range(5, 10, 20))
# should print False
"""
2. Same Name
Create a function named same_name() that has two parameters named your_name and my_name.
If our names are identical, return True. Otherwise, return False.
"""
# Write your same_name function here:
def same_name(your_name, my_name):
if your_name == my_name:
return True
return False
# Uncomment these function calls to test your same_name function:
print(same_name("Colby", "Colby"))
# should print True
print(same_name("Tina", "Amber"))
# should print False
"""
3. Always False
Create a function named always_false() that has one parameter named num.
Using an if statement, your variable num, and the operators >, and <, make it so your function will return False no matter what number is stored in num.
An if statement that is always false is called a contradiction. You will rarely want to do this while programming, but it is important to realize it is possible to do this.
"""
# Write your always_false function here:
def always_false(num):
if num > 0 and num < 0:
return True
return False
# Uncomment these function calls to test your always_false function:
print(always_false(0))
# should print False
print(always_false(-1))
# should print False
print(always_false(1))
# should print False
"""
4. Movie Review
Create a function named movie_review() that has one parameter named rating.
If rating is less than or equal to 5, return "Avoid at all costs!". If rating is between 5 and 9, return "This one was fun.". If rating is 9 or above, return "Outstanding!"
"""
# Write your movie_review function here:
def movie_review(rating):
if rating <= 5:
return "Avoid at all costs!"
if rating < 9:
return "This one is fun."
return "Outstanding!"
# Uncomment these function calls to test your movie_review function:
print(movie_review(9))
# should print "Outstanding!"
print(movie_review(4))
# should print "Avoid at all costs!"
print(movie_review(6))
# should print "This one was fun."
"""
5. Max Number
Create a function called max_num() that has three parameters named num1, num2, and num3.
The function should return the largest of these three numbers. If any of two numbers tie as the largest, you should return "It's a tie!".
"""
# Write your max_num function here:
def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
if num2 > num1 and num2 > num3:
return num2
if num3 > num1 and num3 > num2:
return num3
return "It's a tie!"
# Uncomment these function calls to test your max_num function:
print(max_num(-10, 0, 10))
# should print 10
print(max_num(-10, 5, -30))
# should print 5
print(max_num(-5, -10, -10))
# should print -5
print(max_num(2, 3, 3))
# should print "It's a tie!"
| [
"[email protected]"
] | |
186a9c837d36c3d6fa05169927789c91eb09afa6 | 3134d27741953caa1ee0ec39e7ff974a8d86c6a8 | /06 sort&search/run.py | 0f077dd1d0f781a58936a25a80dbca5689ae880b | [] | no_license | Singularity0909/DS | 84364cfbf7c8976aafe285e79c3b5ebf6f167376 | 6afef12489b367f25b72aed2ea93583c2e6d9f25 | refs/heads/master | 2022-03-09T13:41:50.930048 | 2021-03-05T10:38:07 | 2021-03-05T10:38:07 | 242,893,756 | 0 | 1 | null | 2022-02-13T03:07:58 | 2020-02-25T02:45:16 | C++ | UTF-8 | Python | false | false | 4,213 | py | import requests
import json
import sys
import os
users = {}
data = []
def getUsers():
if os.path.exists('./users.json') == False:
url = 'https://codeforces.com/api/user.ratedList?activeOnly=false'
r = requests.get(url)
with open('./users.json', 'w') as f:
f.write(r.text)
def getAcNum(handle):
url = 'https://codeforces.com/api/user.status?handle=' + handle
r = requests.get(url)
submit_all = json.loads(r.text)['result']
ac = set() # 集合去重
for submit_each in submit_all:
if submit_each['problem'].get('contestId'):
probId = str(submit_each['problem'][
'contestId']) + submit_each['problem']['index']
else:
probId = submit_each['problem'][
'problemsetName'] + submit_each['problem']['index']
if submit_each['verdict'] == 'OK': # 筛选出 Accepted
ac.add(probId)
return len(ac)
def getData():
global data, users
if os.path.exists('./data.txt'):
with open('./data.txt', 'r') as f:
data = eval(f.read())
pre = len(data)
with open('./users.json', 'r') as f:
users = json.load(f)['result']
# return # 测试用
while pre < len(users): # 自动重试和断点续爬
try:
for i in range(pre, len(users)):
handle = users[i]['handle']
rating = users[i].get('rating')
country = users[i].get('country')
acnumber = getAcNum(handle)
data.append({'handle': handle, 'rating': rating,
'country': country, 'acnumber': acnumber})
print(i + 1, '/', len(users), data[-1])
except:
print('Saved. Error:', handle)
with open('./data.txt', 'w') as f: # 爬取完毕或网络错误时跳出保存
f.write(str(data))
pre = len(data)
def partition(arr, low, high, key):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j][key] >= pivot[key]:
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quickSort(arr, low, high, key):
if low < high:
pi = partition(arr, low, high, key)
quickSort(arr, low, pi - 1, key)
quickSort(arr, pi + 1, high, key)
def dispData():
print('Rank', 'Handle', 'Rating', 'Country', 'Accepted')
for i in range(len(data)):
print(i + 1, data[i]['handle'], data[i]['rating'],
data[i]['country'], data[i]['acnumber'])
def upper_bound(arr, low, high, x, key):
if arr[low][key] <= x:
return 0
while low < high:
mid = (low + high + 1) // 2
if arr[mid][key] > x:
low = mid
else:
high = mid - 1
return low + 1
def chooseFunc():
opt = input('Please enter a command: ')
if opt == '1':
quickSort(data, 0, len(data) - 1, 'rating')
dispData()
elif opt == '2':
quickSort(data, 0, len(data) - 1, 'acnumber')
dispData()
elif opt == '3':
x = int(input('Please input the lower limit of rating: '))
quickSort(data, 0, len(data) - 1, 'rating')
print(upper_bound(data, 0, len(data) - 1, x, 'rating'))
elif opt == '4':
x = int(input('Please input the lower limit of problems: '))
quickSort(data, 0, len(data) - 1, 'acnumber')
print(upper_bound(data, 0, len(data) - 1, x, 'acnumber'))
elif opt != '5':
print('Wrong command, plese try again.')
return opt != '5'
def showMenu():
while True:
print('1. Output all info ordered by rating')
print('2. Output all info ordered by number of accepted problems')
print('3. Count the number of users whose rating exceeds ___')
print('4. Count the number of users who pass problems more than ___')
print('5. Quit')
if chooseFunc() == False:
break
if __name__ == '__main__':
sys.setrecursionlimit(1000000) # 避免因递归深度过大引发异常
print('Initializing, please wait.')
getUsers()
getData()
showMenu()
| [
"[email protected]"
] | |
07b9e4f09eea96140309aef71b664c8aed45dd78 | b377edf57ea1eb661ee42cf655317f27aa14e700 | /DFSChaeng.py | 7053a2cfe1079050796f9dfd73d87520b5bddf45 | [] | no_license | irvinzato/Algoritmos-Distribuidos | 17ef01ef31b1e8f3daf7dba7194bcdd690a99f08 | 0e4392a9951a757e9a2663a71466f781ffa7c192 | refs/heads/master | 2020-09-29T09:03:11.915854 | 2019-12-10T01:55:06 | 2019-12-10T01:55:06 | 227,005,909 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,422 | py | # Este archivo sirve de modelo para la creacion de aplicaciones, i.e. algoritmos concretos
""" Implementa la simulacion del algoritmo de Propagacion de Informacion (Segall) como ejemplo
de aplicacion """
import sys
from event import Event
from model import Model
#from process import Process
#from simulator import Simulator
from simulation import Simulation
class DFSChange(Model):
""" La clase Algorithm desciende de la clase Model e implementa los metodos
"init()" y "receive()", que en la clase madre se definen como abstractos """
def init(self):
""" Aqui se definen e inicializan los atributos particulares del algoritmo """
self.padre = self.id
self.sinVisitar = self.neighbors
self.visited = False
print ("inicializo algoritmo")
def go(self):
if(len(self.sinVisitar) != 0 ):
k = self.sinVisitar.pop(0)
newevent = Event("DESC", self.clock+1.0, k, self.id)
print (" Soy el nodo ", self.id, " y mando DESC a mi vecino ", k, " en el tiempo de ", self.clock)
self.transmit(newevent)
elif(self.padre != self.id):
newevent = Event("REG", self.clock+1.0, self.padre, self.id)
print (" Soy el nodo ", self.id, " y mando REG a mi padre ", self.padre, " en el tiempo de ", self.clock)
self.transmit(newevent)
def receive(self, event):
#print (event.getName(), "Padre = ", self.padre, "Fuente = ", event.getSource())
if(event.getName() == "DESC"):
if(event.getSource() in self.sinVisitar):
self.sinVisitar.remove(event.getSource())
if(self.visited):
newevent = Event("RECHAZO", self.clock+1.0, event.getSource(), self.id)
print (" Soy el nodo ", self.id, " y mando RECHAZO a ", event.getSource(), " en el tiempo de ", self.clock)
self.transmit(newevent)
else:
self.visited = True
self.padre = event.getSource()
self.go()
else:
self.go()
"""
Aqui se definen las acciones concretas que deben ejecutarse cuando se
recibe un evento
if self.visited == False:
print ("soy ", self.id, " recibo mensaje a las ", self.clock, " desde ", event.getSource())
self.visited = True
for t in self.neighbors:
newevent = Event("C", self.clock+1.0, t, self.id)
print (" proximo evento a las ", newevent.getTime())
self.transmit(newevent)
"""
# ----------------------------------------------------------------------------------------
# "main()"
# ----------------------------------------------------------------------------------------
# construye una instancia de la clase Simulation recibiendo como parametros el nombre del
# archivo que codifica la lista de adyacencias de la grafica y el tiempo max. de simulacion
if len(sys.argv) != 2:
print ("Please supply a file name")
raise SystemExit(1)
experiment = Simulation(sys.argv[1], 100)
# asocia un pareja proceso/modelo con cada nodo de la grafica
for i in range(1,len(experiment.graph)+1):
m = DFSChange()
experiment.setModel(m, i)
# inserta un evento semilla en la agenda y arranca
seed = Event("DESC", 0.0, 1, 1)
experiment.init(seed)
experiment.run()
| [
"[email protected]"
] | |
cbe331ffe5e2a0da54c4dcd55325e4f2edb9749c | b1123c216ce7ade0a999118cf90c1ceed5751152 | /venv/bin/streamlit | 7191743b178416b45f84363b08d8308f83f61e27 | [] | no_license | pierresegonne/streamlit_import_keyerror | c3ea58d7670bec81d8f0121645eccd0a90478dcf | 950a50435d97a3c81e46867ef0288cc5049041ca | refs/heads/master | 2022-12-22T22:56:31.935228 | 2020-06-29T14:16:47 | 2020-06-29T14:16:47 | 275,832,866 | 0 | 1 | null | 2022-12-10T08:48:57 | 2020-06-29T14:05:16 | Python | UTF-8 | Python | false | false | 260 | #!/Users/Ashitaka2/PycharmProjects/streamlit_error/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from streamlit.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
] | ||
2736fa9c52895528cb942534bddb2afa906c6106 | 6121da376efe804fc8d9a5b33731c7c35f6d5fc0 | /tkinter_learn/ex1.py | 0396f70fb8d423cb26f08de3907712b1bb91c64a | [] | no_license | Gitus-Maximus/Skills | 4e67b5cdc19d695aef0ab1f768d9ab5c2a9591ac | 1ba6bd63de18afe2ca698430aaa4b5bd5434351b | refs/heads/main | 2023-04-30T18:35:31.654718 | 2021-05-22T11:56:06 | 2021-05-22T11:56:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 157 | py | from tkinter import *
root = Tk()
#creating label widget
myLabel = Label(root, text='Hello World!')
#showing it onto screen
myLabel.pack()
root.mainloop()
| [
"[email protected]"
] | |
ca18b217ba01e3c2db0c8ed520a70c0585fb405a | 8eb74661275827b4c6a21d138348d02170d8576c | /04_orc.py | f0b25a02dbde02b74031828207e2b5016df5dd36 | [] | no_license | CraftyDragon678/Lord-of-SQL-Injection | 5f721ff91cc346cb3c762ab3fa60f2d665598487 | 4823b50c9600b08ba5b5e554dbbaa342f002e637 | refs/heads/master | 2022-12-05T21:52:19.054905 | 2020-08-22T12:43:12 | 2020-08-22T12:43:12 | 262,752,996 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 760 | py | import requests
import string
import os
from dotenv import load_dotenv
load_dotenv()
pw = ""
a = string.printable
a = a[:-38]
base_url = "https://los.rubiya.kr/chall/orc_60e5b360f95c1f9688e4f3a86c5dd494.php"
cookies = {'PHPSESSID': os.getenv("PHPSESSID")}
pw_length = 0
for i in range(10):
res = requests.get(base_url, params={
'pw': f"1' or length(pw)={i}#"}, cookies=cookies).text
if "Hello admin" in res:
print("length: " + str(i))
pw_length = i
break
for i in range(1, pw_length + 1):
for j in a:
res = requests.get(base_url, params={
'pw': f"1' or substr(pw,{i},1)='{j}'#"
}, cookies=cookies).text
if "Hello admin" in res:
pw += j
break
print(pw)
| [
"[email protected]"
] | |
1c5d45fa2429072f4d4862d447aa6369c79cd3a0 | 565e8557bd528992059a38e25b8f93f9495e4f56 | /Week4/Day1/exercises/exercise_xp/exercise8/untitled.py | 19fca146bf7cdfdde1d1e86947b3cd8de4ab949b | [] | no_license | eranfuchs1/DI_Bootcamp | 2f753bfa9381e01d3f99b7f39a6faa8d794143c9 | a19885444459e7f6ffd552fe32eef9003e7fda14 | refs/heads/main | 2023-08-14T09:36:14.300816 | 2021-10-05T18:22:06 | 2021-10-05T18:22:06 | 381,000,955 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 68 | py | if input('what\'s your name?').title() == 'Eran':
print('\n'*9)
| [
"xer@xer-labtop"
] | xer@xer-labtop |
a5397ba84caf3dc1c0703dc74417050cbfef2108 | fe86b8dc870c9b02085861b04b404965137f296b | /server/app/__init__.py | de7fd36af509ae59148b16d484d8efae52686d85 | [] | no_license | zixuzhang/Basedata | b4e3aefa3bef2b61c12cb8123aca0181fe20952c | df8452645146f4a4075ae7b085a3193c67d8e70c | refs/heads/master | 2021-04-06T11:28:22.846375 | 2018-03-14T03:25:11 | 2018-03-14T03:25:11 | 125,149,779 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 712 | py | #coding=utf-8
import os
from flask import Flask
from config import config
from flask_restful import Resource, Api
from flask_mongoengine import MongoEngine
from pymongo import MongoClient
env = os.getenv('FALSK_CONFIG') or 'default'
URI = 'mongodb://%s:%d' % (config[env].MONGO_HOST, config[env].MONGO_PORT)
client = MongoClient(URI)
pydb = client[config[env].MONGO_DBNAME]
api = Api()
db = MongoEngine()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
api.init_app(app)
db.init_app(app)
#蓝图
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app | [
"[email protected]"
] | |
f8762a025c081b938a4c0b9290ed26292d7c80bc | d1ddb9e9e75d42986eba239550364cff3d8f5203 | /google-cloud-sdk/lib/surface/billing/accounts/projects/link.py | 3e7d6395b66b15bf8139d9533f1c18bd3f177b42 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bopopescu/searchparty | 8ecd702af0d610a7ad3a8df9c4d448f76f46c450 | afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6 | refs/heads/master | 2022-11-19T14:44:55.421926 | 2017-07-28T14:55:43 | 2017-07-28T14:55:43 | 282,495,798 | 0 | 0 | Apache-2.0 | 2020-07-25T17:48:53 | 2020-07-25T17:48:52 | null | UTF-8 | Python | false | false | 1,712 | py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to update a new project."""
from googlecloudsdk.api_lib.billing import billing_client
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.billing import flags
from googlecloudsdk.command_lib.billing import utils
class Link(base.Command):
"""Link a project with a billing account."""
detailed_help = {
'DESCRIPTION': """\
This command links a billing account to a project.
If the specified billing account is open, this enables billing on the
project.
"""
}
@staticmethod
def Args(parser):
account_args_group = parser.add_mutually_exclusive_group(required=True)
flags.GetOldAccountIdArgument(positional=False).AddToParser(
account_args_group)
flags.GetAccountIdArgument(positional=False).AddToParser(account_args_group)
flags.GetProjectIdArgument().AddToParser(parser)
def Run(self, args):
client = billing_client.ProjectsClient()
project_ref = utils.ParseProject(args.project_id)
account_ref = utils.ParseAccount(args.billing_account)
return client.Link(project_ref, account_ref)
| [
"[email protected]"
] | |
cb246f9f242dfd2fd6751ecbff80844462dc79b8 | 65dc01443e75bd8d889f14039f2994d01c47a19a | /app/scripts/fridge_control.py | 01cce83006d65b703f90c0826eee32f980bd5815 | [
"MIT"
] | permissive | seanon414/flask_fridge | 7de9d0145d4f8c9b0b8e0b6c823e6040e19a6baa | 25ef988c10c612c5a2a23a085b91c04edd3135c3 | refs/heads/master | 2021-07-11T00:53:37.019277 | 2020-06-23T17:24:09 | 2020-06-23T17:24:09 | 147,256,106 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 410 | py | import os
def turn_off_fridge():
"""Turns off fridge"""
# logging.info('Sending code to turn off fridge')
print('Sending code to turn off fridge')
os.system('/home/pi/rfoutlet/codesend 1054012')
def turn_on_fridge():
"""Turns on fridge"""
# logging.info('Sending code to turn on fridge')
print('Sending code to turn on fridge')
os.system('/home/pi/rfoutlet/codesend 1054003')
| [
"[email protected]"
] | |
3a18a80502c84ad5e880721d9bc37a6c72e57e32 | a56252fda5c9e42eff04792c6e16e413ad51ba1a | /resources/usr/local/lib/python2.7/dist-packages/sklearn/decomposition/truncated_svd.py | 15e135598e9cbf6795969a4469a691972c272a16 | [
"Apache-2.0"
] | permissive | edawson/parliament2 | 4231e692565dbecf99d09148e75c00750e6797c4 | 2632aa3484ef64c9539c4885026b705b737f6d1e | refs/heads/master | 2021-06-21T23:13:29.482239 | 2020-12-07T21:10:08 | 2020-12-07T21:10:08 | 150,246,745 | 0 | 0 | Apache-2.0 | 2019-09-11T03:22:55 | 2018-09-25T10:21:03 | Python | UTF-8 | Python | false | false | 6,054 | py | # -*- coding: utf-8 -*-
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA).
"""
# Author: Lars Buitinck <[email protected]>
# License: 3-clause BSD.
import numpy as np
try:
from scipy.sparse.linalg import svds
except ImportError:
from ..utils.arpack import svds
from ..base import BaseEstimator, TransformerMixin
from ..utils import (array2d, as_float_array, atleast2d_or_csr,
check_random_state)
from ..utils.extmath import randomized_svd, safe_sparse_dot, svd_flip
__all__ = ["TruncatedSVD"]
class TruncatedSVD(BaseEstimator, TransformerMixin):
"""Dimensionality reduction using truncated SVD (aka LSA).
This transformer performs linear dimensionality reduction by means of
truncated singular value decomposition (SVD). It is very similar to PCA,
but operates on sample vectors directly, instead of on a covariance matrix.
This means it can work with scipy.sparse matrices efficiently.
In particular, truncated SVD works on term count/tf–idf matrices as
returned by the vectorizers in sklearn.feature_extraction.text. In that
context, it is known as latent semantic analysis (LSA).
Parameters
----------
n_components : int, default = 2
Desired dimensionality of output data.
Must be strictly less than the number of features.
The default value is useful for visualisation. For LSA, a value of
100 is recommended.
algorithm : string, default = "randomized"
SVD solver to use. Either "arpack" for the ARPACK wrapper in SciPy
(scipy.sparse.linalg.svds), or "randomized" for the randomized
algorithm due to Halko (2009).
n_iterations : int, optional
Number of iterations for randomized SVD solver. Not used by ARPACK.
random_state : int or RandomState, optional
(Seed for) pseudo-random number generator. If not given, the
numpy.random singleton is used.
tol : float, optional
Tolerance for ARPACK. 0 means machine precision. Ignored by randomized
SVD solver.
Attributes
----------
`components_` : array, shape (n_components, n_features)
See also
--------
PCA
RandomizedPCA
References
----------
Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 (arXiv:909) http://arxiv.org/pdf/0909.4061
Notes
-----
SVD suffers from a problem called "sign indeterminancy", which means the
sign of the ``components_`` and the output from transform depend on the
algorithm and random state. To work around this, fit instances of this
class to data once, then keep the instance around to do transformations.
"""
def __init__(self, n_components=2, algorithm="randomized",
n_iterations=5, random_state=None, tol=0.):
self.algorithm = algorithm
self.n_components = n_components
self.n_iterations = n_iterations
self.random_state = random_state
self.tol = tol
def fit(self, X, y=None):
"""Fit LSI model on training data X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Returns
-------
self : object
Returns the transformer object.
"""
self._fit(X)
return self
def fit_transform(self, X, y=None):
"""Fit LSI model to X and perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Returns
-------
X_new : array, shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
"""
U, Sigma, VT = self._fit(X)
Sigma = np.diag(Sigma)
# or (X * VT.T).T, whichever takes fewer operations...
return np.dot(U, Sigma.T)
def _fit(self, X):
X = as_float_array(X, copy=False)
random_state = check_random_state(self.random_state)
if self.algorithm == "arpack":
U, Sigma, VT = svds(X, k=self.n_components, tol=self.tol)
# svds doesn't abide by scipy.linalg.svd/randomized_svd
# conventions, so reverse its outputs.
Sigma = Sigma[::-1]
U, VT = svd_flip(U[:, ::-1], VT[::-1])
elif self.algorithm == "randomized":
k = self.n_components
n_features = X.shape[1]
if k >= n_features:
raise ValueError("n_components must be < n_features;"
" got %d >= %d" % (k, n_features))
U, Sigma, VT = randomized_svd(X, self.n_components,
n_iter=self.n_iterations,
random_state=random_state)
else:
raise ValueError("unknown algorithm %r" % self.algorithm)
self.components_ = VT
return U, Sigma, VT
def transform(self, X):
"""Perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
New data.
Returns
-------
X_new : array, shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
"""
X = atleast2d_or_csr(X)
return safe_sparse_dot(X, self.components_.T)
def inverse_transform(self, X):
"""Transform X back to its original space.
Returns an array X_original whose transform would be X.
Parameters
----------
X : array-like, shape (n_samples, n_components)
New data.
Returns
-------
X_original : array, shape (n_samples, n_features)
Note that this is always a dense array.
"""
X = array2d(X)
return np.dot(X, self.components_)
| [
"[email protected]"
] | |
09a3b3f6d6fd326f7537420a76d2639c640ca428 | 06e9222bab21119a0b254cbba365ac82aaacfdb9 | /week-04/day5/r1.py | 6cd59595b392a85d3314e25eb273d6f5bad5fe1d | [] | no_license | greenfox-velox/DDL | f83dfa49b408fb2de8dafedb1722566a838d7003 | 8dd8732734d0f6edde8aa07f7fe89237d8acdcf8 | refs/heads/master | 2021-01-21T15:19:44.988846 | 2016-07-18T17:52:12 | 2016-07-18T17:52:12 | 58,042,851 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 355 | py | # create a 300x300 canvas.
# fill it with a checkerboard pattern.
from tkinter import *
root = Tk()
canvas_width= 300
canvas_height= 300
canvas = Canvas(root, width = canvas_width, height = canvas_height)
canvas.pack()
x = 1
for i in range(1, 28):
rect = canvas.create_rectangle(1+x, 1+x, 10+x, 10+x, fill='purple')
x += 11
root.mainloop()
| [
"[email protected]"
] | |
4ee6686aacceb240cae551bb59a988b1420dbb50 | ccf4bf15bb82460922f76dce67d960c4ee7155b9 | /1-pack_web_static.py | a119ca3186d3e7e00f66e86953d1b333c49296e4 | [] | no_license | camilooob/AirBnB_clone_v2 | b6afb01089ad3cdf996b047e8f057709424b7ccd | 1445177afd5e3779d614b5b2601b41894eba2a2c | refs/heads/master | 2022-04-21T17:37:53.193359 | 2020-04-23T01:48:11 | 2020-04-23T01:48:11 | 258,065,385 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 417 | py | #!/usr/bin/python3
from fabric.api import run, local, put
from datetime import datetime
import os
def do_pack():
""" fabric script that generates a .tgz """
date = datetime.now().strftime("%Y%m%d%H%M%S")
path = "versions/web_static_{}.tgz".format(date)
try:
local("mkdir -p versions")
local("tar -czvf {} web_static".format(path))
return path
except:
return None
| [
"[email protected]"
] | |
436bec37ae79c90e8a6958a74766798f87e07f69 | 0e3f17892bf42e70c9db005abae21b4fb4c52507 | /Launcher.py | 552fc2783982bd14c9919cee60ee11bc42054516 | [] | no_license | alxiden/Food-Stock-Contol-System | 17ae556aee41646114e5d9ba998a693ce1e26f03 | d262d901d9fa3b660fb35844098270efece3d3ef | refs/heads/master | 2022-12-03T20:00:14.374906 | 2020-08-10T08:18:31 | 2020-08-10T08:18:31 | 286,412,122 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 937 | py | import Setup as s
import Stock as t
from tkinter import *
import os
a = os.listdir()
root = Tk()
root.title("SWM Launcher")
welcome = Label(root, text = "Welcome to the Stock and Wastage Manager Launcher")
welcome.grid(row = 0, column =1, columnspan =3)
l1 = Label (root, text = "Please choose from the options below")
l1.grid(row = 1, column =1, columnspan =3)
submit = Button(root, text = "Exsisting Account", height = "1", width = "15", command = lambda: t.startup())
submit.grid(row = 3, column =1)
submit = Button(root, text = "New Account", height = "1", width = "15", command = lambda: s.setep())
submit.grid(row = 3, column =2)
submit = Button(root, text = "Master Account", height = "1", width = "15", command = lambda: t.startup())
submit.grid(row = 5, column =1)
submit = Button(root, text = "Something probably", height = "1", width = "15", command = lambda: t.startup())
submit.grid(row = 5, column =2)
| [
"[email protected]"
] | |
b1ace0e756998d873ed27c026f0c31f85ae7d33e | f77a9351d481f457d813b753a6c27aac1b6a5fe6 | /dev/DroneKit_Code/garys_test.py | 888f456645d63009ab9b2cfccaf380990e618524 | [] | no_license | keikofujii/PulsedLight | 8a8af10f2093c32b7d8f5ff19fd7c4b8934ab9fc | 1145805211d1172b7c4c28b8d150b98a1e0fdc8f | refs/heads/master | 2021-01-10T08:53:06.577640 | 2016-10-02T19:11:15 | 2016-10-02T19:11:15 | 43,270,240 | 0 | 4 | null | 2015-11-09T23:46:49 | 2015-09-27T23:40:29 | C++ | UTF-8 | Python | false | false | 2,506 | py | """
garys_test.py
A module to test and see if the drone can be armed, switched to GUIDED mode, moved, and
then give the control back to the user in LOITER mode
"""
from dronekit import connect, VehicleMode, LocationGlobalRelative
import time
from pymavlink import mavutil
#Set up option parsing to get connection string
import argparse
parser = argparse.ArgumentParser(description='Print out vehicle state information. Connects to Raspberry Pi by default.')
# This connection string defaults to the connection string for the Raspberry Pi
parser.add_argument('--connect', default='/dev/ttyACM0',
help="vehicle connection target. Default '/dev/ttyACM0'")
args = parser.parse_args()
# Connect to the Vehicle
print 'Connecting to vehicle on: %s' % args.connect
vehicle = connect(args.connect, wait_ready=True)
def arm_and_takeoff(aTargetAltitude):
"""
A method to arm the vehicle and to take off. The drone will fly to a specified altitude.
Params:
aTargetAltitude - An int that represents the altitude to fly to
"""
print "Basic pre-arm checks"
# Don't try to arm until autopilot is ready
while not vehicle.is_armable:
print " Waiting for vehicle to initialise..."
time.sleep(1)
# Confirm vehicle armed before attempting to take off
while not vehicle.armed:
print " Waiting for arming..."
time.sleep(1)
# The user will take off and go to a specified altitude
# Wait until the vehicle is just below target altitude
while not (vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95):
print " Altitude: ", vehicle.location.global_relative_frame.alt
time.sleep(1)
print "Reached target altitude"
# Switch into GUIDED mode
print "Going into guided mode"
vehicle.mode = VehicleMode("GUIDED")
arm_and_takeoff(2)
# Set the airspeed of the drone
print "Set default/target airspeed to 1"
vehicle.airspeed = 1
# Go toward Austrail for a bit
print "Going towards first point for 5 seconds ..."
point1 = LocationGlobalRelative(-35.361354, 149.165218, 20)
vehicle.simple_goto(point1)
# sleep so we can see the change (this sets how long you go towards a point)
time.sleep(5)
# Switch into the user mode LOITER
print "Going to LOITER"
vehicle.mode = VehicleMode("LOITER")
#Close vehicle object before exiting script
print "Close vehicle object"
vehicle.close()
| [
"[email protected]"
] | |
2c5c8b0c873d7ac5bd9e05080f0d5facda39b249 | aad164e4efe1d55cc189c35956bfd435b14a0f52 | /eve-8.21.494548/eve/client/script/ui/control/eveScroll.py | 74d7fc4f99fd06f59fcc61b0507b82fd0dbc3c8a | [] | no_license | Pluckyduck/eve | 61cc41fe8fd4dca4fbdcc4761a37bcfeb27ed84f | 9a277707ab1f162c6bd9618faf722c0be3ea93ad | refs/heads/master | 2020-12-28T23:35:29.992875 | 2013-05-06T14:24:33 | 2013-05-06T14:24:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,688 | py | #Embedded file name: c:/depot/games/branches/release/EVE-TRANQUILITY/eve/client/script/ui/control/eveScroll.py
import xtriui
import uix
import uiutil
import uiconst
import util
import _weakref
import weakref
import blue
import base
import uthread
import types
import listentry
import stackless
import lg
import html
import sys
import dbg
import trinity
import fontConst
import uicls
import uiutil
import uiconst
SCROLLMARGIN = 0
MINCOLUMNWIDTH = 24
class Scroll(uicls.ScrollCore):
__guid__ = 'uicls.Scroll'
headerFontSize = fontConst.EVE_SMALL_FONTSIZE
sortGroups = False
def ApplyAttributes(self, attributes):
uicls.ScrollCore.ApplyAttributes(self, attributes)
sm.GetService('window').CheckControlAppearance(self)
def Prepare_ScrollControls_(self):
self.sr.scrollcontrols = uicls.ScrollControls(name='__scrollcontrols', parent=self.sr.maincontainer, align=uiconst.TORIGHT, width=7, state=uiconst.UI_HIDDEN, idx=0)
self.sr.scrollcontrols.Startup(self)
def Prepare_Underlay_(self):
self.sr.underlay = uicls.BumpedUnderlay(parent=self, name='background')
def Startup(self, minZ = None):
pass
def HideBackground(self, alwaysHidden = 0):
frame = None
if uiutil.GetAttrs(self, 'sr', 'underlay'):
self.sr.underlay.state = uiconst.UI_HIDDEN
frame = self.sr.underlay
if frame and getattr(frame, 'parent'):
underlayFrame = frame.parent.FindChild('underlayFrame')
underlayFill = frame.parent.FindChild('underlayFill')
if underlayFrame:
underlayFrame.state = uiconst.UI_HIDDEN
if underlayFill:
underlayFill.state = uiconst.UI_HIDDEN
if alwaysHidden:
self.SetNoBackgroundFlag(alwaysHidden)
def OnMouseWheel(self, *etc):
if getattr(self, 'wheeling', 0):
return 1
if len(uicore.layer.menu.children):
focus = uicore.registry.GetFocus()
if focus and isinstance(focus, uicls.ScrollCore):
if not uiutil.IsUnder(focus, uicore.layer.menu):
return 1
self.wheeling = 1
self.Scroll(uicore.uilib.dz / 240.0)
self.wheeling = 0
self.sr.scrollcontrols.AnimFade()
return 1
def GetNoItemNode(self, text, sublevel = 0, *args):
return listentry.Get('Generic', {'label': text,
'sublevel': sublevel})
def ShowHint(self, hint = None):
isNew = self.sr.hint is None or self.sr.hint.text != hint
if self.sr.hint is None and hint:
clipperWidth = self.GetContentWidth()
self.sr.hint = uicls.EveCaptionMedium(parent=self.sr.clipper, align=uiconst.TOPLEFT, left=16, top=32, width=clipperWidth - 32, text=hint)
elif self.sr.hint is not None and hint:
self.sr.hint.text = hint
self.sr.hint.state = uiconst.UI_DISABLED
isNew = isNew or self.sr.hint.display == False
elif self.sr.hint is not None and not hint:
self.sr.hint.state = uiconst.UI_HIDDEN
if self.sr.hint and self.sr.hint.display and isNew:
uicore.animations.FadeTo(self.sr.hint, 0.0, 0.5, duration=0.3)
def RecyclePanel(self, panel, fromWhere = None):
if panel.__guid__ == 'listentry.VirtualContainerRow':
subnodes = [ node for node in panel.sr.node.internalNodes if node is not None ]
for node in subnodes:
node.panel = None
uicls.ScrollCore.RecyclePanel(self, panel, fromWhere)
class ScrollControls(uicls.ScrollControlsCore):
__guid__ = 'uicls.ScrollControls'
def ApplyAttributes(self, attributes):
uicls.ScrollControlsCore.ApplyAttributes(self, attributes)
self.animFadeThread = None
def Prepare_(self):
self.Prepare_ScrollHandle_()
uicls.Fill(name='underlay', bgParent=self, color=util.Color.GetGrayRGBA(0.3, 0.1), shadowOffset=(-1, 0))
def Prepare_ScrollHandle_(self):
subparent = uicls.Container(name='subparent', parent=self, align=uiconst.TOALL, padding=(0, 0, 0, 0))
self.sr.scrollhandle = uicls.ScrollHandle(name='__scrollhandle', parent=subparent, align=uiconst.TOPLEFT, pos=(0, 0, 0, 0), state=uiconst.UI_NORMAL)
def AnimFade(self):
self.fadeEndTime = blue.os.GetTime() + 0.3 * SEC
if not self.animFadeThread:
uicore.animations.FadeIn(self.sr.scrollhandle.sr.hilite, 0.5, duration=0.1)
uthread.new(self._AnimFadeThread)
def _AnimFadeThread(self):
while blue.os.GetTime() < self.fadeEndTime:
blue.synchro.Yield()
if uicore.uilib.mouseOver != self.sr.scrollhandle:
uicore.animations.FadeOut(self.sr.scrollhandle.sr.hilite, duration=0.5)
self.animFadeThread = None
class ScrollHandle(uicls.ScrollHandleCore):
__guid__ = 'uicls.ScrollHandle'
def Prepare_(self):
self.fill = uicls.GradientSprite(bgParent=self, rotation=0, rgbData=[(0, (1.0, 1.0, 1.0))], alphaData=[(0.0, 0.0),
(0.1, 0.1),
(0.9, 0.1),
(1.0, 0.0)])
self.Prepare_Hilite_()
def Prepare_Hilite_(self):
self.sr.hilite = uicls.Fill(name='hilite', parent=self, color=(1.0, 1.0, 1.0, 0.0))
class ColumnHeader(uicls.ScrollColumnHeaderCore):
__guid__ = 'uicls.ScrollColumnHeader'
def Prepare_Label_(self):
textclipper = uicls.Container(name='textclipper', parent=self, align=uiconst.TOALL, padding=(6, 2, 6, 0), state=uiconst.UI_PICKCHILDREN, clipChildren=1)
self.sr.label = uicls.EveLabelSmall(text='', parent=textclipper, hilightable=1, state=uiconst.UI_DISABLED) | [
"[email protected]"
] | |
4005a43041bf0fa2f6259164c5612a18782ebfa7 | 3d8a1dd6d6e0035ff6baf7e3df5ea51bbdf7b322 | /vowelorconsonant.py | c7eb1268251f3818fb54b2c3453ca120d55b03fb | [] | no_license | bharanim11598/code-kata | 9a48b6a14595c05815b161d6725ad77518cf21f4 | 5b1b1467af7b34786618df94423df92c86542083 | refs/heads/master | 2021-04-27T15:17:27.385746 | 2018-07-23T08:47:43 | 2018-07-23T08:47:43 | 122,466,249 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 113 | py | print("enter the character")
c=input()
if c in('a','e','i','o','u'):
print("vowel")
else:
print("consonant")
| [
"[email protected]"
] | |
99127105d73f4aff46625f3f1a24bd57cb25454b | edd8d0c8c35b9278ab94adb743468611dc5363a7 | /company/forms.py | a40242fb9a172008676196d7a7011e156f97f133 | [] | no_license | Ruby1996/Online-Job-Portal-EasyJobs | e0255aec15e0215f9eb07b6083a90da9c718a751 | f17ddd73b79c57b0b7dc09f614b2bf7332f7affb | refs/heads/master | 2021-01-04T06:45:42.967849 | 2020-05-22T14:59:20 | 2020-05-22T14:59:20 | 240,435,638 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 174 | py | from django import forms
from company.models import com_pro
class CompanyForm(forms.ModelForm):
class Meta:
model = com_pro
fields = "__all__" | [
"[email protected]"
] | |
0f72d3ccd5c1a713719a0d156ab773fc55542879 | 1ea5c42db5aa83d748d068c8b3e5820d69816f94 | /lab9-100pt.py | be97146adf2f6be73395b4224277b3ebc2105c12 | [] | no_license | ChrisMatthewLee/Lab-9 | 012d391b3846550ac5dae80ef1fb5cb343db794e | 4fc17668d108e020701d4c4fdb557a453430b515 | refs/heads/master | 2021-01-13T02:16:23.695349 | 2014-10-21T19:25:43 | 2014-10-21T19:25:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,079 | py | ############################################
# #
# 100pt #
# Patient Diagnosis #
############################################
# Create a program that tests if patients needs to be admitted to the hospital.
# Ask the user for their temperature, and if they have been sick in the last 24 hours.
# Additionally, ask if the user has recently travelled to West Africa.
# The program should continue to run until there are no patients left to diagnose (i.e. a while loop).
# Criteria for Diagnosis:
# - A temperature of over 105F
# - A temperature of over 102F and they have been sick in the last 24 hours
# - A temperature over 100, OR they've been sick in the last 24 hours, AND they've recently travelled to West Africa.
#_________________________________________________________________________________________________________________________
print "Hello there! Lets take your temperature! Type only the number of your temperature."
userTemp = int(raw_input())
print userTemp | [
"[email protected]"
] | |
bc2b4badc6d17614052123ee0ffd86e964f7573d | 31abda0b7866de64f075648b6a19d9481074c53d | /api_challenge/tests/test_post_method.py | 7da9b4b9bb804cdeef6f36c265a39de217c45b80 | [] | no_license | SThomasP/Api-Challenge | 1d32e15cffa49151d822e35d01c2119879655b8a | a00ad212e833364660ea7ca407608f41d472674b | refs/heads/master | 2020-04-10T18:27:13.607506 | 2018-12-10T16:32:19 | 2018-12-10T16:32:19 | 161,204,888 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,251 | py | from pymongo import MongoClient
from api_challenge.tests.api_framework import post, example_data_update, example_data_merged, example_data_basic, client
# test adding a document to the database using an api
def test_post_add(client):
test_data = example_data_basic.copy()
response = post(client, test_data)
# check that it returned the correct status code
assert 200 == response.status_code
# check that the response is correct
assert response.is_json
assert {'message': 'data successfully added'} == response.get_json()
with MongoClient() as mongo:
db = mongo.challenge
# find the data in the database
data_object = db.integrations.find_one({'tenant': test_data['tenant'], 'integration_type': test_data['integration_type']})
# check that there's something there
assert data_object is not None
data_object.pop('_id')
# check that the data is correct.
assert data_object == example_data_basic
# test updating existing data using the api
def test_post_update(client):
test_data_one = example_data_basic.copy()
test_data_two = example_data_update.copy()
with MongoClient() as mongo:
# write the initial data to the database
db = mongo.challenge
db.integrations.insert_one(test_data_one)
# test the method
response = post(client, test_data_two)
# check the status code is correct
assert 200 == response.status_code
# check that it's a valid json and that it's correct
assert response.is_json
assert {'message': 'data successfully updated'} == response.get_json()
# get the object from the database
data_object = db.integrations.find_one({'tenant': test_data_one['tenant'], 'integration_type': test_data_one['integration_type']})
# check that there is one
assert data_object is not None
# check that the ids are the same
assert test_data_one['_id'] == data_object['_id']
data_object.pop('_id')
# check that the data is correct
assert data_object == example_data_merged
# test that data can be added and then the same document gets updated
def test_post_add_then_update(client):
test_data_one = example_data_basic.copy()
test_data_two = example_data_update.copy()
# check that they have the same tenant and integration type
assert test_data_one['tenant'] == test_data_two['tenant']
assert test_data_one['integration_type'] == test_data_two['integration_type']
search_data = {'tenant': test_data_one['tenant'], 'integration_type': test_data_one['integration_type']}
with MongoClient() as mongo:
db = mongo.challenge
# test the first response
response_one = post(client, test_data_one)
assert 200 == response_one.status_code
assert response_one.is_json
assert {'message': 'data successfully added'} == response_one.get_json()
result_data_one = db.integrations.find_one(search_data)
id_one = result_data_one.pop('_id')
assert result_data_one == example_data_basic
# test the second
response_two = post(client, test_data_two)
assert 200 == response_two.status_code
assert response_two.is_json
assert {'message': 'data successfully updated'} == response_two.get_json()
result_data_two = db.integrations.find_one(search_data)
id_two = result_data_two.pop("_id")
assert result_data_two == example_data_merged
# make sure that they have the same object_id
assert id_one == id_two
# test adding two datasets with different integration types, they should create two different documents
def test_post_two_adds_same_tenant(client):
test_data_one = example_data_basic.copy()
test_data_two = example_data_update.copy()
test_data_two['integration_type'] = 'pilot-scheduling-system'
assert test_data_one['tenant'] == test_data_two['tenant']
assert test_data_one['integration_type'] != test_data_two['integration_type']
response_one = post(client, test_data_one)
assert 200 == response_one.status_code
assert response_one.is_json
assert {'message': 'data successfully added'} == response_one.get_json()
response_two = post(client, test_data_two)
assert 200 == response_two.status_code
assert response_two.is_json
assert {'message': 'data successfully added'} == response_two.get_json()
with MongoClient() as mongo:
db = mongo.challenge
assert db.integrations.count_documents({'tenant': test_data_one['tenant']}) == 2
# test adding two data sets with different tenants, they should create two different documents.
def test_post_two_adds_same_integration_type(client):
test_data_one = example_data_basic.copy()
test_data_two = example_data_update.copy()
test_data_two['tenant'] = 'competitor'
assert test_data_one['tenant'] != test_data_two['tenant']
assert test_data_one['integration_type'] == test_data_two['integration_type']
response_one = post(client, test_data_one)
assert 200 == response_one.status_code
assert response_one.is_json
assert {'message': 'data successfully added'} == response_one.get_json()
response_two = post(client, test_data_two)
assert 200 == response_two.status_code
assert response_two.is_json
assert {'message': 'data successfully added'} == response_two.get_json()
with MongoClient() as mongo:
db = mongo.challenge
# check that two documents were created
assert db.integrations.count_documents({'integration_type': test_data_one['integration_type']}) == 2
# test that the request fails correctly when no tenant is included
def test_post_fail_no_tenant(client):
test_data = example_data_basic.copy()
test_data.pop('tenant')
response = post(client, test_data)
with MongoClient() as mongo:
db = mongo.challenge
assert db.integrations.find_one(test_data) is None
assert 400 == response.status_code
assert response.is_json
assert {"error": 400, 'message': 'required variable(s) are missing'} == response.get_json()
# test that the request fails correctly when no integration type is included
def test_post_fail_no_integration_type(client):
test_data = example_data_basic.copy()
test_data.pop('integration_type')
response = post(client, test_data)
with MongoClient() as mongo:
db = mongo.challenge
assert db.integrations.find_one(test_data) is None
assert 400 == response.status_code
assert response.is_json
assert {"error": 400, 'message': 'required variable(s) are missing'} == response.get_json()
# test that request fails correctly when the _id field is included
def test_post_fail_id_included(client):
test_data = example_data_basic.copy()
test_data['_id'] = "CompleteRubbish"
response = post(client, test_data)
with MongoClient() as mongo:
db = mongo.challenge
assert db.integrations.find_one(test_data) is None
assert 400 == response.status_code
assert response.is_json
assert {"error": 400, 'message': 'illegal variable(s) were found'} == response.get_json()
| [
"[email protected]"
] | |
dc2298ea3f809e95f96f14e997ebd950108666c4 | 3533c4cea61230c05f8f7d6db634358885b1326d | /model/lmdtm.py | b51b2830b06ed15b9e5ded7f3bac2885f73bc4c8 | [
"MIT"
] | permissive | denyssilveira/gsdtm_lmdtm_topic_model | 205f10f069a28bf8ccb20a255bd1937378af01b0 | e97136e630b37166c5273f510ea899034c9df800 | refs/heads/master | 2020-03-14T19:21:54.987807 | 2018-08-27T23:29:51 | 2018-08-27T23:29:51 | 131,759,658 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,019 | py | """
GSDTM and LMDTM VAEs Implementation
This code provides an implementation of the LMDTM VAE Model.
Code partially adapted from https://github.com/RuiShu/vae-clustering (Author: Rui Shu)
"""
import tensorflow as tf
import numpy as np
import pickle
import sys
import os
from model import utils
slim = tf.contrib.slim
# Distribution over qy
def qy_graph(x, n_hidden, n_topic=50):
reuse = len(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='qy')) > 0
with tf.variable_scope('qy'):
net = slim.stack(x, slim.fully_connected, [n_hidden, n_hidden], reuse=reuse)
qy_logit = slim.fully_connected(net, n_topic, activation_fn=None)
qy = tf.nn.softmax(qy_logit, name='prob')
return qy_logit, qy
# Distribution over qz
def qz_graph(x, y, n_hidden, flags, batch_size=64, n_topic=50, keep_prob=0.4):
reuse = len(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='qz')) > 0
with tf.variable_scope('qz'):
xy = tf.concat((x, y), 1, name='xy/concat')
net = slim.stack(xy, slim.fully_connected, [n_hidden, n_hidden], scope='net', reuse=reuse)
if flags.dropout:
layer_do = tf.nn.dropout(net, keep_prob)
else:
layer_do = net
net_mean = slim.fully_connected(layer_do, n_topic, activation_fn=None, scope='mean', reuse=reuse)
net_log_sigma = slim.fully_connected(layer_do, n_topic, activation_fn=None, scope='log_sigma', reuse=reuse)
if flags.batch_norm:
mean = tf.contrib.layers.batch_norm(net_mean, scope='bn1', reuse=reuse)
log_sigma = tf.contrib.layers.batch_norm(net_log_sigma, scope='bn2', reuse=reuse)
else:
mean = net_mean
log_sigma = net_log_sigma
sigma = tf.exp(log_sigma)
eps = tf.random_normal((tf.shape(x)[0], flags.n_topic), 0, 1, dtype=tf.float32)
z = tf.add(mean, tf.multiply(sigma, eps))
z_softmax = tf.nn.softmax(z)
return z_softmax, mean, sigma, log_sigma
# Distribution over px
def px_graph(z, y, batch_size, n_topic, vocabsize, hidden_size, flags, keep_prob=0.4):
reuse = len(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='px')) > 0
with tf.variable_scope('pz'):
net_prior_mean = slim.fully_connected(y, n_topic, activation_fn=tf.nn.relu, scope='prior_mean', reuse=reuse)
net_prior_log_sigma = slim.fully_connected(y, n_topic, activation_fn=tf.nn.relu, scope='prior_log_sq_sigma', reuse=reuse)
if flags.batch_norm:
mean_prior = tf.contrib.layers.batch_norm(net_prior_mean, scope='bn6',reuse=reuse)
log_sigma_prior = tf.contrib.layers.batch_norm(net_prior_log_sigma, scope='bn7', reuse=reuse)
else:
mean_prior = net_prior_mean
log_sigma_prior = net_prior_log_sigma
with tf.variable_scope('px'):
if flags.dropout:
layer_do_decoder = tf.nn.dropout(z, keep_prob)
else:
layer_do_decoder = z
output = slim.fully_connected(layer_do_decoder, vocabsize, activation_fn=None, scope='embedding', reuse=reuse)
if flags.batch_norm:
logits_x = tf.contrib.layers.batch_norm(output, scope='bn5', reuse=reuse)
else:
logits_x = output
return mean_prior, log_sigma_prior, logits_x
class LMDTM(object):
def __init__(self, vocabsize, flags):
self.learning_rate = flags.learning_rate
self.batch_size = flags.batch_size
self.n_hidden = flags.n_hidden
self.n_component = flags.n_component
print('Network Architecture')
print('Length of layers: {0}'.format(self.n_hidden))
print('Learning Rate: {0}'.format(self.learning_rate))
print('Batch size: {0}'.format(self.batch_size))
with tf.Session(config=tf.ConfigProto(
inter_op_parallelism_threads = flags.num_cores,
intra_op_parallelism_threads = flags.num_cores,
gpu_options=tf.GPUOptions(allow_growth=True))) as self.sess:
# TF Graph input
self.x = tf.placeholder(tf.float32, [None, vocabsize])
self.keep_prob = tf.placeholder(tf.float32)
with tf.name_scope('y_'):
y_ = tf.fill(tf.stack([tf.shape(self.x)[0],
flags.n_component]), 0.0)
# Distribution over y
qy_logit, qy = qy_graph(
self.x,
self.n_hidden,
n_topic=flags.n_topic)
self.z, self.mean, self.sigma, self.log_sigma, \
self.prior_mean, self.log_prior_sigma, self.logits_x, \
self.log_p_x = [[None] * flags.n_component for i in range(8)]
# Create graph for each component
for i in range(flags.n_component):
with tf.name_scope('graphs/hot_at{:d}'.format(i)):
y = tf.add(y_, tf.constant(
np.eye(flags.n_component)[i],
name='hot_at_{:d}'.format(i),
dtype=tf.float32))
self.z[i], self.mean[i], self.sigma[i], \
self.log_sigma[i] = qz_graph(self.x, y, \
self.n_hidden, flags,
batch_size=self.batch_size,
n_topic=flags.n_topic,
keep_prob=self.keep_prob)
self.prior_mean[i], self.log_prior_sigma[i], \
self.logits_x[i] = px_graph(self.z[i], y,
flags.batch_size,
flags.n_topic,
vocabsize,
self.n_hidden,
flags)
self.log_p_x[i] = tf.nn.log_softmax(self.logits_x[i])
utils.variable_summaries(self.log_p_x[i], 'decoder/log_px{:d}'.format(i))
# Multinomial KL
self.KLD_discrete = tf.add_n([qy[:, i] * tf.log(flags.n_component * qy[:, i] + 1e-12)
for i in range(flags.n_component)]) / flags.n_component
# Gaussian KL
self.KLD_gaussian = tf.add_n(
[
0.5 * tf.reduce_sum((2 * (self.log_prior_sigma[i] - self.log_sigma[i])) +\
tf.div(tf.square(self.sigma[i]) + tf.square(self.mean[i] - self.prior_mean[i]), \
# exp(2 * log(sigma)) == sigma^2
tf.exp(2 * self.log_prior_sigma[i])) - 1, 1)
for i in range(flags.n_component)
]) / flags.n_component
self.reconstruction_loss = tf.add_n([tf.reduce_sum(tf.multiply(self.log_p_x[i], self.x), 1)
for i in range(flags.n_component)]) / flags.n_component
self.elbo = self.reconstruction_loss - self.KLD_gaussian - self.KLD_discrete
self.loss = tf.reduce_mean(-self.elbo)
self.optimizer = \
tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss, var_list=slim.get_model_variables())
# Extract word embedding space
self.R = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='px/embedding/weights:0')[0]
init = tf.global_variables_initializer()
self.embedding_var = tf.Variable(tf.transpose(self.R), name='word_embedding')
utils.set_embedding_visualization(self.embedding_var, flags)
self.sess.run(init)
def vectors(self, batch_xs, keep_prob):
return self.sess.run(self.z,
feed_dict={self.x: batch_xs,
self.keep_prob: keep_prob}
)
| [
"[email protected]"
] | |
c361ace07797c254c612162de468530d995c7834 | 0cf6728548830b42c60e37ea1c38b54d0e019ddd | /__各种测试/MT5系列测试/Python与MT5集成测试.py | cd1b4a0374f035c3ebd2f69e698b7099dbfe351f | [] | no_license | MuSaCN/PythonLearning | 8efe166f66f2bd020d00b479421878d91f580298 | 507f1d82a9228d0209c416626566cf390e1cf758 | refs/heads/master | 2022-11-11T09:13:08.863712 | 2022-11-08T04:20:09 | 2022-11-08T04:20:09 | 299,617,217 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,577 | py | # Author:Zhang Yuan
from MyPackage import *
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
import statsmodels.api as sm
from scipy import stats
# ------------------------------------------------------------
__mypath__ = MyPath.MyClass_Path("") # 路径类
mylogging = MyDefault.MyClass_Default_Logging(activate=False) # 日志记录类,需要放在上面才行
myfile = MyFile.MyClass_File() # 文件操作类
myword = MyFile.MyClass_Word() # word生成类
myexcel = MyFile.MyClass_Excel() # excel生成类
mytime = MyTime.MyClass_Time() # 时间类
myplt = MyPlot.MyClass_Plot() # 直接绘图类(单个图窗)
mypltpro = MyPlot.MyClass_PlotPro() # Plot高级图系列
myfig = MyPlot.MyClass_Figure(AddFigure=False) # 对象式绘图类(可多个图窗)
myfigpro = MyPlot.MyClass_FigurePro(AddFigure=False) # Figure高级图系列
mynp = MyArray.MyClass_NumPy() # 多维数组类(整合Numpy)
mypd = MyArray.MyClass_Pandas() # 矩阵数组类(整合Pandas)
mypdpro = MyArray.MyClass_PandasPro() # 高级矩阵数组类
myDA = MyDataAnalysis.MyClass_DataAnalysis() # 数据分析类
myDefault = MyDefault.MyClass_Default_Matplotlib() # 画图恢复默认设置类
# myMql = MyMql.MyClass_MqlBackups() # Mql备份类
# myBaidu = MyWebCrawler.MyClass_BaiduPan() # Baidu网盘交互类
# myImage = MyImage.MyClass_ImageProcess() # 图片处理类
myBT = MyBackTest.MyClass_BackTestEvent() # 事件驱动型回测类
myBTV = MyBackTest.MyClass_BackTestVector() # 向量型回测类
myML = MyMachineLearning.MyClass_MachineLearning() # 机器学习综合类
mySQL = MyDataBase.MyClass_MySQL(connect=False) # MySQL类
mySQLAPP = MyDataBase.MyClass_SQL_APPIntegration() # 数据库应用整合
myWebQD = MyWebCrawler.MyClass_QuotesDownload(tushare=False) # 金融行情下载类
myWebR = MyWebCrawler.MyClass_Requests() # Requests爬虫类
myWebS = MyWebCrawler.MyClass_Selenium(openChrome=False) # Selenium模拟浏览器类
myWebAPP = MyWebCrawler.MyClass_Web_APPIntegration() # 爬虫整合应用类
myEmail = MyWebCrawler.MyClass_Email() # 邮箱交互类
myReportA = MyQuant.MyClass_ReportAnalysis() # 研报分析类
myFactorD = MyQuant.MyClass_Factor_Detection() # 因子检测类
myKeras = MyDeepLearning.MyClass_tfKeras() # tfKeras综合类
myTensor = MyDeepLearning.MyClass_TensorFlow() # Tensorflow综合类
myMT5 = MyMql.MyClass_ConnectMT5(connect=False) # Python链接MetaTrader5客户端类
myMT5Pro = MyMql.MyClass_ConnectMT5Pro(connect=False) # Python链接MT5高级类
myMT5Indi = MyMql.MyClass_MT5Indicator() # MT5指标Python版
myMT5Report = MyMT5Report.MyClass_StratTestReport(AddFigure=False) # MT5策略报告类
myDefault.set_backend_default("Pycharm") # Pycharm下需要plt.show()才显示图
# ------------------------------------------------------------
mypd.__init__(0)
#%%
myMT5.__init__(connect=True)
myMT5.version
myMT5.account_info
myMT5.terminal_info
myMT5.last_error()
#%%
myMT5.symbols_total()
myMT5.symbols_get("EURUSD")
myMT5.symbol_info("EURUSD")["volume_min"]
myMT5.symbol_info_tick("EURUSD")
#%%
myMT5.symbol_select("USDCNH", False)
myMT5.market_book_add("EURUSD")
myMT5.market_book_get("EURUSD")
myMT5.market_book_release("EURUSD")
#%%
# 获取活动挂单的数量
myMT5.orders_total()
myMT5.orders_get(symbol="EURUSD")
myMT5.orders_get(group="*USD*")
myMT5.orders_get(ticket=2248047902)
# 获取未结持仓的数量。
myMT5.positions_total()
myMT5.positions_get(symbol="EURUSD")
myMT5.positions_get(group="*USD*")
myMT5.positions_get(ticket=2248047631)
# 返回预付款(用账户货币表示)来执行指定的交易操作。
myMT5.order_calc_margin("ORDER_TYPE_BUY","EURUSD",0.01)
myMT5.order_calc_margin("ORDER_TYPE_SELL","EURUSD",0.01)
# 返回指定交易操作的盈利(用账户货币表示)。
myMT5.order_calc_profit("ORDER_TYPE_BUY","EURUSD", 1, 1, 2.0)
myMT5.order_calc_profit("ORDER_TYPE_BUY","EURUSD", 1, 1, None, 100)
myMT5.order_calc_profit("ORDER_TYPE_BUY","EURUSD", 1, None, 1.18)
myMT5.order_calc_profit("ORDER_TYPE_BUY","EURUSD", 1, 1.17, 1.18)
myMT5.order_calc_profit("ORDER_TYPE_SELL","EURUSD", 1, None, None, 100)
#%% 未完
myMT5.mt5.history_deals_total()
from datetime import datetime
# 获取历史中的交易数量
from_date = datetime(2020, 1, 1)
to_date = datetime.now()
deals = myMT5.mt5.history_deals_total(from_date, to_date)
if deals > 0:
print("Total deals=", deals)
print("Deals not found in history")
deals = myMT5.mt5.history_deals_get(from_date, to_date)
| [
"[email protected]"
] | |
38dfdf6e8b73dee04feccca63e184b2da23c48f1 | c857d225b50c5040e132d8c3a24005a689ee9ce4 | /problem74.py | 830b6b07b7f1eda9fcb6355d6e2c15703adc1fc8 | [] | no_license | pythonsnake/project-euler | 0e60a6bd2abeb5bf863110c2a551d5590c03201e | 456e4ef5407d2cf021172bc9ecfc2206289ba8c9 | refs/heads/master | 2021-01-25T10:44:27.876962 | 2011-10-21T00:46:02 | 2011-10-21T00:46:02 | 2,335,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 816 | py | """
The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:
1! + 4! + 5! = 1 + 24 + 120 = 145
perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist:
169 363601 1454 169
871 45361 871
872 45362 872
it is not difficult to prove that every starting number will eventually get stuck in a loop. for example,
69 363600 1454 169 363601 ( 1454)
78 45360 871 45361 ( 871)
540 145 ( 145)
starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.
how many chains, with a starting number below one million, contain exactly sixty non-repeating terms?
""" | [
"[email protected]"
] | |
afa035c2c1ac97098db9c97d1bdbca8d2eed6990 | 99fed597dba66f6b2198425d36e338afb670d91a | /djangoStudy/placeholder/placeholder.py | 9854580d0fcfe1817728518f4516e2f3849906e5 | [] | no_license | JanPingZHANG/pyStudy_miscellaneous | 28a5aac59020225ed95e5863f188bf374fc03333 | 80c82df242fcce4f5eff90aa6fe08b4721c9bc9d | refs/heads/master | 2021-01-22T04:15:11.656191 | 2017-02-10T03:48:33 | 2017-02-10T03:48:33 | 81,523,369 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,364 | py | import sys
from django.conf import settings
import os
from django.core.cache import cache
from django.views.decorators.http import etag
import hashlib
from django.conf.urls import url
from django.http import HttpResponse,HttpResponseBadRequest
from django import forms
from io import BytesIO
from PIL import Image,ImageDraw
from django.core.wsgi import get_wsgi_application
from django.core.management import execute_from_command_line
from django.core.urlresolvers import reverse
from django.shortcuts import render
DEBUG = os.environ.get('DEBUG','on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY','t(2i7(m^8m!p9=et39f#uo3c0cg=8nt=1r_8p=qb#qz$woi885')
BASE_DIR = os.path.dirname(__file__)
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS','localhost').split(',')
settings.configure(
DEBUG = DEBUG,
SECRET_KEY = SECRET_KEY,
ROOT_URLCONF = __name__,
ALLOWED_HOSTS = ALLOWED_HOSTS,
MIDDLEWARE_CLASS=(
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking,XFrameOptionsMiddleware',
),
INSTALLED_APPS=('django.contrib.staticfiles',),
TEMPLATES=(
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':(os.path.join(BASE_DIR,'templates'),),
},
),
STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'),),
STATIC_URL='/static/',
)
def index(request):
example = reverse('placeholder',kwargs={'width':50,'height':50})
context = {'example':request.build_absolute_uri(example)}
return render(request,'home.html',context)
class ImageForm(forms.Form):
"""Form to validate requested placeholder image."""
height = forms.IntegerField(min_value=1,max_value=2000)
width = forms.IntegerField(min_value=1,max_value=2000)
def generate(self,image_format='PNG'):
"""Generate an image of the given type and return as raw bytes."""
height = self.cleaned_data['height']
width = self.cleaned_data['width']
print 'generate a new image width: ',width,' height: ',height
key = '{}.{}.{}'.format(height,width,image_format)
content = cache.get(key)
if content is None:
print 'create a new image width: ',width,' height: ',height
image = Image.new('RGB',(width,height))
draw = ImageDraw.Draw(image)
text = '{0} X {1}'.format(width,height)
textWidth,textHeight = draw.textsize(text)
if textWidth<width and textHeight < height:
texttop = (height - textHeight) // 2
textleft = (width - textWidth) // 2
draw.text((textleft,texttop),text,fill=(255,255,255))
content = BytesIO()
image.save(content,image_format)
content.seek(0)
cache.set(key,content,60*60)
return content
def generate_etag(request,width,height):
content = 'Placeholder: {0} x {1}'.format(width,height)
return hashlib.sha1(content.encode('utf-8')).hexdigest()
@etag(generate_etag)
def placeholder(request,width,height):
form = ImageForm({'height':height,'width':width})
if form.is_valid():
image = form.generate()
height = form.cleaned_data['height']
width = form.cleaned_data['width']
return HttpResponse(image,content_type='image/png')
else:
return HttpResponseBadRequest('invalid image request')
urlpatterns = (
url(r'image/(?P<width>[0-9]+)x(?P<height>[0-9]+)',placeholder,name='placeholder'),
url(r'^$',index,name='homepage'),
)
application = get_wsgi_application()
if __name__ == '__main__':
execute_from_command_line(sys.argv)
| [
"[email protected]"
] | |
e6ad0964ad8bc5b1e1ba768bbdf8fcd8758bfe97 | 856732853b2ccc3ce20e2295c1fda1c5a17acc03 | /dash_app.py | 79b1d5f986f5c515f5da27090fe476271f986e2b | [] | no_license | Shreyajaiswal22/Stock_Price_Prediction-Webapp | a8080bdd188248be5024f125fc6902dc95ba0b67 | 3de0d6e37e3adf3034aee9eee0c76154401753c1 | refs/heads/main | 2023-07-11T00:53:09.778124 | 2021-08-03T12:35:44 | 2021-08-03T12:35:44 | 392,310,334 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,887 | py | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import datetime as dt
import yfinance as yf
from MLTrader import MLTrader
from util import pull_prices_viz
from dateutil.relativedelta import relativedelta
app = dash.Dash(name=__name__)
periods_list = ["5 Days", "1 Month", "3 Months", "6 Months",
"1 Year", "2 Years", "5 Years"]
#reading in NYSE stock tickers
tickers = pd.read_csv("yfinance_tickers.csv")
tickers_str = ' '.join(tickers.Symbol.values)
#initializing data and graph
prices = pull_prices_viz(tickers_str, "5y")
#setting layout and title
app.title = "Stock Price Prediction App"
app.layout = html.Div(className='main-body', children=[
#intro section on top
html.Div(id='title', className='title-div', children=[
html.H3(className='title', children="Stock Price Prediction App"),
dcc.Markdown(className='intro', children="""
This app shows you the adjusted closing stock prices for a few
different technology companies and predict the closing price for
today. Play around, and make some money!
""")
]),
#Top div
html.Div(id='card-left', className='card-left', children=[
html.Div(className='card', children=[
html.Div(className='labels', children='Company Name:'),
html.Br(),
dcc.Dropdown(
id='company-name',
className='dropdown',
options=[{'label': i, 'value': i} for i in tickers.Name],
value=tickers.Name[0],
),
]),
html.Div(className='card', children=[
html.Div(className='labels', children='Graph Filter:'),
html.Br(),
dcc.Dropdown(
id='timeframe',
className='dropdown',
options=[{'label': i, 'value': i} for i in periods_list],
value="5 Years",
multi=False,
),
]),
html.Div(className='card', children=[
html.Div(className='labels', children="Stock Ticker:"),
html.Br(),
html.Div(className='values', id='company-ticker', children='Ticker: AAPL'),
]),
html.Div(className='card', children=[
html.Div(className='labels', children="Yesterday's Closing Price:"),
html.Br(),
html.Div(id="current-price", className='values'),
]),
html.Div(className='card', children=[
html.Div(className='labels', children="Today's Predicted Closing Price:"),
html.Br(),
html.Div(id="predicted-price", className='values'),
]),
]),
html.Br(),
html.Div(className='graph', id='prices-div',
children=dcc.Graph(id='prices-plot', style={'width':'100%'},
config={'responsive':True})),
])
@app.callback(
Output('prices-plot', 'figure'),
[Input('company-name', 'value'),
Input('timeframe', 'value')]
)
def create_plot(name, timeframe):
#retrieving stock ticker
ticker = tickers[tickers.Name == name].Symbol.values[0]
#filtering prices by selected stock
prices_one = prices.filter(items=["Date",ticker],axis=1)
#splitting time input
t_list = timeframe.split(' ')
t_qty, t_unit = int(t_list[0]),t_list[1]
#retrieving the start and end dates
end_date = dt.datetime.today() #.today()
if t_unit[:3] == "Day":
start_date = end_date - relativedelta(days=t_qty)
elif t_unit[:5] == "Month":
start_date = end_date - relativedelta(months=t_qty)
else:
start_date = end_date - relativedelta(years=t_qty)
#filtering prices by start and end dates
mask = (prices_one['Date'] >= start_date) & (prices_one['Date'] <= end_date)
prices_one = prices_one.loc[mask]
#creating graph
title = "{} Price over the last {}".format(ticker.upper(), timeframe)
fig = px.line(prices_one, x="Date", y=ticker, title=title)
#updating graph layout (docs: https://plot.ly/python/reference/#layout)
fig["layout"].update(paper_bgcolor="#0a2863", plot_bgcolor="#0a2863",
title={'xanchor':'center', 'y':0.9, 'x':0.5,
'font':{'color':'white'}},
xaxis={'showgrid': False, 'color':'white'},
yaxis={'showgrid': False, 'color':'white',
'title':'Stock Price'},
height=400)
return fig
@app.callback(
[Output('current-price', 'children'),
Output('predicted-price', 'children'),
Output('predicted-price', 'style'),
Output('company-ticker', 'children')],
[Input('company-name', 'value')]
)
def show_prices(name):
#retrieving stock ticker
ticker = tickers[tickers.Name == name].Symbol.values[0]
#creating the trader and loading the given stock's model
trader = MLTrader(None, n=10)
trader.load_learner(ticker)
#getting the current stock price and predicting tomorrow's price
current_price = round(prices[ticker].values[-1],2)
predicted_price = round(trader.predict_today(ticker),2)
#deciding if the predicted price is higher or lower than the current price
if predicted_price > current_price:
color = "green"
elif predicted_price < current_price:
color = "red"
else:
color = "white"
#formatting strings to display
current_str = "${:,.2f}".format(current_price)
predicted_str = "${:,.2f}".format(predicted_price)
predicted_style = {'color':color, 'textAlign':'center'}
return current_str,predicted_str,predicted_style,ticker
if __name__ == "__main__":
app.run_server(debug=False)
| [
"[email protected]"
] | |
0996061417561852c10f79d2242c01108fe13d62 | 84114158f5e2e628a4ff18058238434218ecd4ad | /celery_tasks/urls.py | 2dae7442b06b340bf7894fe549fb3dc2061bff17 | [] | no_license | shawnhuang90s/oms_test | 8c781e1e86d3e28f73fe130c9201c7773e07f441 | 764df78c59d6e9c2dafee65e875b29df2635d33c | refs/heads/master | 2023-03-25T14:33:42.460115 | 2021-03-17T06:21:42 | 2021-03-17T06:21:42 | 317,149,804 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 177 | py | from django.urls import path
from .views import DealExcelInfoView
urlpatterns = [
path('test_celery/', DealExcelInfoView.as_view()), # 测试 Celery 处理 excel 接口
]
| [
"[email protected]"
] | |
cc9a3d32b613a6927dbab941b2f1ca3bdf727698 | 7f18929d4af4a1744eec90d1f0c712e78b31f7c2 | /reconstruct_image.py | 2763d6660e1438e69156b60ff6f88d23100afa25 | [
"MIT"
] | permissive | mckib2/mri-variationalnetwork | b4958ca52e5570d530d1963434230d7033074ef9 | d9d7790f2ac5677316114ea683ac2ee8f57699c0 | refs/heads/master | 2020-07-16T12:15:05.963778 | 2019-09-02T06:19:17 | 2019-09-02T06:19:17 | 205,787,662 | 0 | 0 | MIT | 2019-09-02T06:06:20 | 2019-09-02T06:06:19 | null | UTF-8 | Python | false | false | 4,096 | py | import os
import sys
import argparse
import glob
import traceback
import time
import vn
import tensorflow as tf
import numpy as np
from mridata import VnMriReconstructionData
import mriutils
parser = argparse.ArgumentParser(description='reconstruct a given image data using a model')
parser.add_argument('image_config', type=str, help='config file for reconstruct')
parser.add_argument('model_name', type=str, help='name of the model in the log dir')
parser.add_argument('--o', dest='output_name', type=str, default='result', help='output name')
parser.add_argument('--epoch', type=int, default=None, help='epoch to evaluate')
parser.add_argument('--training_config', type=str, default='./configs/training.yaml', help='training config file')
if __name__ == '__main__':
# parse the input arguments
args = parser.parse_args()
# image and model
data_config = tf.contrib.icg.utils.loadYaml(args.image_config, ['data_config'])
model_name = args.model_name
output_name = args.output_name
epoch = args.epoch
checkpoint_config = tf.contrib.icg.utils.loadYaml(args.training_config, ['checkpoint_config'])
all_models = glob.glob(checkpoint_config['log_dir'] + '/*')
all_models = sorted([d.split('/')[-1] for d in all_models if os.path.isdir(d)])
if not model_name in all_models:
print('model not found in "{}"'.format(checkpoint_config['log_dir']))
sys.exit(-1)
ckpt_dir = checkpoint_config['log_dir'] + '/' + model_name + '/checkpoints/'
eval_output_dir = checkpoint_config['log_dir'] + '/' + model_name + '/test/'
with tf.Session() as sess:
try:
# load from checkpoint if required
epoch = vn.utils.loadCheckpoint(sess, ckpt_dir, epoch=epoch)
except Exception as e:
print(traceback.print_exc())
# extract operators and variables from the graph
u_op = tf.get_collection('u_op')[0]
u_var = tf.get_collection('u_var')
c_var = tf.get_collection('c_var')
m_var = tf.get_collection('m_var')
f_var = tf.get_collection('f_var')
g_var = tf.get_collection('g_var')
# create data object
data = VnMriReconstructionData(data_config,
u_var=u_var,
f_var=f_var,
c_var=c_var,
m_var=m_var,
g_var=g_var,
load_eval_data=False,
load_target=False)
# run the model
print('start reconstruction')
eval_start_time = time.time()
feed_dict, norm = data.get_test_feed_dict(data_config['dataset'],
data_config['dataset']['patient'],
data_config['dataset']['slice'],
return_norm=True)
# get the reconstruction, re-normalize and postprocesss it
u_i = sess.run(u_op, feed_dict=feed_dict)[0]
u_i = u_i * norm # renormalize
u_i = mriutils.postprocess(u_i, data_config['dataset']['name'])
time_reco = time.time() - eval_start_time
print('reconstruction of {} image took {:f}s'.format(u_i.shape, time_reco))
print('saving reconstructed image to "{}"'.format(output_name))
# save mat file
patient_id = '%s-p%d-sl%d' % (data_config['dataset']['name'],
data_config['dataset']['patient'],
data_config['dataset']['slice'])
mriutils.saveAsMat(u_i, '%s-vn-%s.mat' % (output_name, patient_id), 'result_vn',
mat_dict={'normalization': np.asarray(norm)})
# enhance image and save as png
u_i_enhanced = mriutils.contrastStretching(np.abs(u_i), 0.002)
mriutils.imsave(u_i_enhanced,
'%s-vn-%s.png' % (output_name, patient_id))
| [
"[email protected]"
] | |
cf8c15b9224beaccab5c660cd47744dc8577cc30 | ddda7862304a4a461bd493b007adc2d2d1d4ea96 | /examples/overconfident_stephen.py | c2403e6d39f97d4034fda61905de06581ed22db9 | [] | no_license | TTomm1/complex_models_hackaton | de7b9d92940f2cde14320aba0282d670e47485b5 | 8153ed128584312e3f02b052d018a5063b5e0208 | refs/heads/master | 2021-01-11T16:03:48.946501 | 2017-01-26T08:56:03 | 2017-01-26T08:56:03 | 79,997,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 589 | py | import sys
from flask import Flask
from flask import jsonify
from flask_restful import Api
from flask_restful import Resource
app = Flask(__name__)
api = Api(app)
class Predict(Resource):
def get(self):
result = {
'probability': 1.,
'label': 0.,
}
return jsonify(**result)
api.add_resource(Predict, '/api/v1/predict')
if __name__ == '__main__':
if len(sys.argv) > 1:
host = sys.argv[1]
port = int(sys.argv[2])
else:
host = None
port = None
app.run(host=host, port=port, debug=False)
| [
"[email protected]"
] | |
cf35b505462e57733af9ed369adf171cbe9e1c6f | d9eef8dd3489682c8db41f2311e3058d1f369780 | /.history/abel-network-files/mcmc_alg_implementation_own_two_20180629100410.py | 9afb4c6e97b928d31297f3d7d92f4679db900c8c | [] | no_license | McKenzie-Lamb/Gerrymandering | 93fe4a49fe39a0b307ed341e46ba8620ea1225be | b7a7c4129d6b0fcd760ba8952de51eafa701eac3 | refs/heads/master | 2021-01-25T06:06:43.824339 | 2018-10-16T14:27:01 | 2018-10-16T14:27:01 | 93,526,515 | 0 | 0 | null | 2018-07-12T19:07:35 | 2017-06-06T14:17:47 | Python | UTF-8 | Python | false | false | 2,852 | py | # Author: Abel Gonzalez
# Date: 06/26/18
#
# Description:
# This program uses the .shp file to create a network graph where each node
# represents a census tract and the edge represents adjacency between each
# tract, usign graph-tool instead of networkx
import random
import numpy as np
import graph_tool.all as gt
from pathlib import Path
def create_graph_views(district_total_no):
graph_views = list()
for i in range(district_total_no):
main_graph_view = gt.GraphView(graph)
graph_view_check = main_graph_view.new_vertex_property("bool")
matched_vertices = gt.find_vertex(graph, district_no, i)
for j in matched_vertices:
graph_view_check[j] = True
graph_view = gt.GraphView(main_graph_view, vfilt=graph_view_check)
graph_views.append(graph_view)
return graph_views
def turn_off_edges(districts_graphs):
selected_edges = dict()
turned_off_graphs = list()
# Iterate through districts and selects random edges
for district in range(len(districts_graphs)):
edges = districts_graphs[district].get_edges()
half = len(edges)//2
no = random.randint(half,half+len(edges)//3)
selected = edges[np.random.randint(edges.shape[0], size = no), :]
selected_edges[district] = selected
turned_off_graphs.append(gt.GraphView(districts_graphs[district], selected))
return turned_off_graphs
# Paths
main_folder = Path("abel-network-files/")
data_folder = Path("abel-network-files/data/")
images_folder = Path("abel-network-files/images/")
# Loading the previous created Graph and creating the prop maps
graph = gt.load_graph(str(data_folder / "tmp_graph.gt"))
color = graph.new_vertex_property("vector<double>")
ring_color = graph.new_vertex_property("vector<double>")
# Init variables
district_total_no = 2
gt.graph_draw(graph, pos=graph.vp.pos,
output=str(main_folder / ('tmp.png')),
bg_color=(255, 255, 255, 1), vertex_text=graph.vertex_index)
# Separates graph into blocks
districts = gt.minimize_blockmodel_dl(graph, district_total_no, district_total_no)
district_no = districts.get_blocks()
districts.draw(output='tmp.png', vertex_text=graph.vertex_index)
# Create the different graphs
districts_graphs = create_graph_views(district_total_no)
for i in range(len(districts_graphs)):
gt.graph_draw(
districts_graphs[i], pos=graph.vp.pos,
output=str(main_folder / ('tmp'+str(i)+'.png')),
bg_color=(255, 255, 255, 1), vertex_text=graph.vertex_index)
turned_on_graphs = turn_off_edges(districts_graphs)
print(len(turned_on_graphs))
for i in range(len(districts_graphs)):
gt.graph_draw(
turned_on_graphs[i], pos=graph.vp.pos,
output=str(main_folder / ('tmp'+str(i)+'.png')))
| [
"[email protected]"
] | |
24b75b5f89da3c46ae9db66ffdf2fa0d12d9531f | d350e03f6e6b44e943d225046fb7d7314689289b | /boot/test.py | 833d6da337c75abd7a669e99b3d9b956afe78ed9 | [] | no_license | RonFrancesca/Alfred-The-SmartButler | caf9a1ffddfe08374166d1d2ab9f1d06cdb57ae6 | 4e34ddad0629a6a2fa8f1f727a6a6d9048ccfaa7 | refs/heads/master | 2021-06-09T10:28:54.322100 | 2018-09-30T23:13:31 | 2018-09-30T23:13:31 | 150,957,181 | 0 | 0 | null | 2021-05-07T14:44:58 | 2018-09-30T10:27:35 | Python | UTF-8 | Python | false | false | 45,837 | py |
<!DOCTYPE html>
<html class=" ">
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#">
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>jasper-client/boot/test.py at master · jasperproject/jasper-client</title>
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub" />
<link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-114.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-144.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144.png" />
<meta property="fb:app_id" content="1401488693436528"/>
<meta content="@github" name="twitter:site" /><meta content="summary" name="twitter:card" /><meta content="jasperproject/jasper-client" name="twitter:title" /><meta content="jasper-client - Client code for Jasper voice computing platform" name="twitter:description" /><meta content="https://avatars3.githubusercontent.com/u/7000742?s=400" name="twitter:image:src" />
<meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="https://avatars3.githubusercontent.com/u/7000742?s=400" property="og:image" /><meta content="jasperproject/jasper-client" property="og:title" /><meta content="https://github.com/jasperproject/jasper-client" property="og:url" /><meta content="jasper-client - Client code for Jasper voice computing platform" property="og:description" />
<link rel="assets" href="https://assets-cdn.github.com/">
<link rel="conduit-xhr" href="https://ghconduit.com:25035">
<link rel="xhr-socket" href="/_sockets" />
<meta name="msapplication-TileImage" content="/windows-tile.png" />
<meta name="msapplication-TileColor" content="#ffffff" />
<meta name="selected-link" value="repo_source" data-pjax-transient />
<meta name="google-analytics" content="UA-3769691-2">
<meta content="collector.githubapp.com" name="octolytics-host" /><meta content="collector-cdn.github.com" name="octolytics-script-host" /><meta content="github" name="octolytics-app-id" /><meta content="52349173:4763:1150BD:53933297" name="octolytics-dimension-request_id" /><meta content="6977612" name="octolytics-actor-id" /><meta content="Bea24" name="octolytics-actor-login" /><meta content="cb57b92d52416c340f69dcd3ab125a37eb442410c67f69ece887bfc787875fb9" name="octolytics-actor-hash" />
<link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico" />
<meta content="authenticity_token" name="csrf-param" />
<meta content="+WCgAd5jLa/gzsWI/V5Mov4uzzzUO+Uug/AQnUoSBk4Hr1B6BCrQroSYTQlRT0hmoMk3Yyc+wVP93u64liY5iw==" name="csrf-token" />
<link href="https://assets-cdn.github.com/assets/github-1aeb426322c64c12b92d56bda5b110fc1093f75e.css" media="all" rel="stylesheet" type="text/css" />
<link href="https://assets-cdn.github.com/assets/github2-b2cccfcac1a522b6ce675606f61388d36bf2c080.css" media="all" rel="stylesheet" type="text/css" />
<meta http-equiv="x-pjax-version" content="6b9e40027b6fe719e1c3d0a9180a2d6a">
<meta name="description" content="jasper-client - Client code for Jasper voice computing platform" />
<meta content="7000742" name="octolytics-dimension-user_id" /><meta content="jasperproject" name="octolytics-dimension-user_login" /><meta content="18272539" name="octolytics-dimension-repository_id" /><meta content="jasperproject/jasper-client" name="octolytics-dimension-repository_nwo" /><meta content="true" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="18272539" name="octolytics-dimension-repository_network_root_id" /><meta content="jasperproject/jasper-client" name="octolytics-dimension-repository_network_root_nwo" />
<link href="https://github.com/jasperproject/jasper-client/commits/master.atom" rel="alternate" title="Recent Commits to jasper-client:master" type="application/atom+xml" />
</head>
<body class="logged_in env-production windows vis-public page-blob">
<a href="#start-of-content" tabindex="1" class="accessibility-aid js-skip-to-content">Skip to content</a>
<div class="wrapper">
<div class="header header-logged-in true">
<div class="container clearfix">
<a class="header-logo-invertocat" href="https://github.com/">
<span class="mega-octicon octicon-mark-github"></span>
</a>
<a href="/notifications" aria-label="You have no unread notifications" class="notification-indicator tooltipped tooltipped-s" data-hotkey="g n">
<span class="mail-status all-read"></span>
</a>
<div class="command-bar js-command-bar in-repository">
<form accept-charset="UTF-8" action="/search" class="command-bar-form" id="top_search_form" method="get">
<div class="commandbar">
<span class="message"></span>
<input type="text" data-hotkey="s, /" name="q" id="js-command-bar-field" placeholder="Search or type a command" tabindex="1" autocapitalize="off"
data-username="Bea24"
data-repo="jasperproject/jasper-client"
data-branch="master"
data-sha="993cf94dc9a47d457d522f40a2764e3badf91c55"
>
<div class="display hidden"></div>
</div>
<input type="hidden" name="nwo" value="jasperproject/jasper-client" />
<div class="select-menu js-menu-container js-select-menu search-context-select-menu">
<span class="minibutton select-menu-button js-menu-target" role="button" aria-haspopup="true">
<span class="js-select-button">This repository</span>
</span>
<div class="select-menu-modal-holder js-menu-content js-navigation-container" aria-hidden="true">
<div class="select-menu-modal">
<div class="select-menu-item js-navigation-item js-this-repository-navigation-item selected">
<span class="select-menu-item-icon octicon octicon-check"></span>
<input type="radio" class="js-search-this-repository" name="search_target" value="repository" checked="checked" />
<div class="select-menu-item-text js-select-button-text">This repository</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-all-repositories-navigation-item">
<span class="select-menu-item-icon octicon octicon-check"></span>
<input type="radio" name="search_target" value="global" />
<div class="select-menu-item-text js-select-button-text">All repositories</div>
</div> <!-- /.select-menu-item -->
</div>
</div>
</div>
<span class="help tooltipped tooltipped-s" aria-label="Show command bar help">
<span class="octicon octicon-question"></span>
</span>
<input type="hidden" name="ref" value="cmdform">
</form>
<ul class="top-nav">
<li class="explore"><a href="/explore">Explore</a></li>
<li><a href="https://gist.github.com">Gist</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="https://help.github.com">Help</a></li>
</ul>
</div>
<ul id="user-links">
<li>
<a href="/Bea24" class="name">
<img alt="Beatrice Gaia Baleani" class=" js-avatar" data-user="6977612" height="20" src="https://avatars1.githubusercontent.com/u/6977612?s=140" width="20" /> Bea24
</a>
</li>
<li class="new-menu dropdown-toggle js-menu-container">
<a href="#" class="js-menu-target tooltipped tooltipped-s" aria-label="Create new...">
<span class="octicon octicon-plus"></span>
<span class="dropdown-arrow"></span>
</a>
<div class="new-menu-content js-menu-content">
</div>
</li>
<li>
<a href="/settings/profile" id="account_settings"
class="tooltipped tooltipped-s"
aria-label="Account settings ">
<span class="octicon octicon-tools"></span>
</a>
</li>
<li>
<form class="logout-form" action="/logout" method="post">
<button class="sign-out-button tooltipped tooltipped-s" aria-label="Sign out">
<span class="octicon octicon-sign-out"></span>
</button>
</form>
</li>
</ul>
<div class="js-new-dropdown-contents hidden">
<ul class="dropdown-menu">
<li>
<a href="/new"><span class="octicon octicon-repo"></span> New repository</a>
</li>
<li>
<a href="/organizations/new"><span class="octicon octicon-organization"></span> New organization</a>
</li>
<li class="section-title">
<span title="jasperproject/jasper-client">This repository</span>
</li>
<li>
<a href="/jasperproject/jasper-client/issues/new"><span class="octicon octicon-issue-opened"></span> New issue</a>
</li>
</ul>
</div>
</div>
</div>
<div id="start-of-content" class="accessibility-aid"></div>
<div class="site" itemscope itemtype="http://schema.org/WebPage">
<div id="js-flash-container">
</div>
<div class="pagehead repohead instapaper_ignore readability-menu">
<div class="container">
<ul class="pagehead-actions">
<li class="subscription">
<form accept-charset="UTF-8" action="/notifications/subscribe" class="js-social-container" data-autosubmit="true" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="RoHuLs+fEi568JXOUGgYQPrvlQfSrKwVzY9GxoYghuOxozGX2l8zG/3bfP3m/1TONzkK228jVYZOGTxYRPmCBQ==" /></div> <input id="repository_id" name="repository_id" type="hidden" value="18272539" />
<div class="select-menu js-menu-container js-select-menu">
<a class="social-count js-social-count" href="/jasperproject/jasper-client/watchers">
90
</a>
<span class="minibutton select-menu-button with-count js-menu-target" role="button" tabindex="0" aria-haspopup="true">
<span class="js-select-button">
<span class="octicon octicon-eye"></span>
Watch
</span>
</span>
<div class="select-menu-modal-holder">
<div class="select-menu-modal subscription-menu-modal js-menu-content" aria-hidden="true">
<div class="select-menu-header">
<span class="select-menu-title">Notification status</span>
<span class="octicon octicon-x js-menu-close"></span>
</div> <!-- /.select-menu-header -->
<div class="select-menu-list js-navigation-container" role="menu">
<div class="select-menu-item js-navigation-item selected" role="menuitem" tabindex="0">
<span class="select-menu-item-icon octicon octicon-check"></span>
<div class="select-menu-item-text">
<input checked="checked" id="do_included" name="do" type="radio" value="included" />
<h4>Not watching</h4>
<span class="description">You only receive notifications for conversations in which you participate or are @mentioned.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="octicon octicon-eye"></span>
Watch
</span>
</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<span class="select-menu-item-icon octicon octicon octicon-check"></span>
<div class="select-menu-item-text">
<input id="do_subscribed" name="do" type="radio" value="subscribed" />
<h4>Watching</h4>
<span class="description">You receive notifications for all conversations in this repository.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="octicon octicon-eye"></span>
Unwatch
</span>
</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<span class="select-menu-item-icon octicon octicon-check"></span>
<div class="select-menu-item-text">
<input id="do_ignore" name="do" type="radio" value="ignore" />
<h4>Ignoring</h4>
<span class="description">You do not receive any notifications for conversations in this repository.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="octicon octicon-mute"></span>
Stop ignoring
</span>
</div>
</div> <!-- /.select-menu-item -->
</div> <!-- /.select-menu-list -->
</div> <!-- /.select-menu-modal -->
</div> <!-- /.select-menu-modal-holder -->
</div> <!-- /.select-menu -->
</form>
</li>
<li>
<div class="js-toggler-container js-social-container starring-container ">
<form accept-charset="UTF-8" action="/jasperproject/jasper-client/unstar" class="js-toggler-form starred" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="QAyEoWCA8G7tvRUicy+fZ40Vem+miDLaPgf2yZWj9cAfwe0P9kEmOwxXS46TyMTPRWWKfPVpetGaWEFUZFoPQQ==" /></div>
<button
class="minibutton with-count js-toggler-target star-button"
aria-label="Unstar this repository" title="Unstar jasperproject/jasper-client">
<span class="octicon octicon-star"></span><span class="text">Unstar</span>
</button>
<a class="social-count js-social-count" href="/jasperproject/jasper-client/stargazers">
884
</a>
</form>
<form accept-charset="UTF-8" action="/jasperproject/jasper-client/star" class="js-toggler-form unstarred" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="qMiJ2YEvWXX8Cg9Fyp+69KTqGP8Y56p2rb8g2opH7LaKWnZ/bbOyHauCj/Dg0SJxjioA8qBC5HMSAduyHE6vsQ==" /></div>
<button
class="minibutton with-count js-toggler-target star-button"
aria-label="Star this repository" title="Star jasperproject/jasper-client">
<span class="octicon octicon-star"></span><span class="text">Star</span>
</button>
<a class="social-count js-social-count" href="/jasperproject/jasper-client/stargazers">
884
</a>
</form> </div>
</li>
<li>
<a href="/jasperproject/jasper-client/fork" class="minibutton with-count js-toggler-target fork-button lighter tooltipped-n" title="Fork your own copy of jasperproject/jasper-client to your account" aria-label="Fork your own copy of jasperproject/jasper-client to your account" rel="facebox nofollow">
<span class="octicon octicon-repo-forked"></span><span class="text">Fork</span>
</a>
<a href="/jasperproject/jasper-client/network" class="social-count">177</a>
</li>
</ul>
<h1 itemscope itemtype="http://data-vocabulary.org/Breadcrumb" class="entry-title public">
<span class="repo-label"><span>public</span></span>
<span class="mega-octicon octicon-repo"></span>
<span class="author"><a href="/jasperproject" class="url fn" itemprop="url" rel="author"><span itemprop="title">jasperproject</span></a></span><!--
--><span class="path-divider">/</span><!--
--><strong><a href="/jasperproject/jasper-client" class="js-current-repository js-repo-home-link">jasper-client</a></strong>
<span class="page-context-loader">
<img alt="" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</span>
</h1>
</div><!-- /.container -->
</div><!-- /.repohead -->
<div class="container">
<div class="repository-with-sidebar repo-container new-discussion-timeline js-new-discussion-timeline ">
<div class="repository-sidebar clearfix">
<div class="sunken-menu vertical-right repo-nav js-repo-nav js-repository-container-pjax js-octicon-loaders">
<div class="sunken-menu-contents">
<ul class="sunken-menu-group">
<li class="tooltipped tooltipped-w" aria-label="Code">
<a href="/jasperproject/jasper-client" aria-label="Code" class="selected js-selected-navigation-item sunken-menu-item" data-hotkey="g c" data-pjax="true" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches /jasperproject/jasper-client">
<span class="octicon octicon-code"></span> <span class="full-word">Code</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
<li class="tooltipped tooltipped-w" aria-label="Issues">
<a href="/jasperproject/jasper-client/issues" aria-label="Issues" class="js-selected-navigation-item sunken-menu-item js-disable-pjax" data-hotkey="g i" data-selected-links="repo_issues /jasperproject/jasper-client/issues">
<span class="octicon octicon-issue-opened"></span> <span class="full-word">Issues</span>
<span class='counter'>25</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
<li class="tooltipped tooltipped-w" aria-label="Pull Requests">
<a href="/jasperproject/jasper-client/pulls" aria-label="Pull Requests" class="js-selected-navigation-item sunken-menu-item js-disable-pjax" data-hotkey="g p" data-selected-links="repo_pulls /jasperproject/jasper-client/pulls">
<span class="octicon octicon-git-pull-request"></span> <span class="full-word">Pull Requests</span>
<span class='counter'>3</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
<li class="tooltipped tooltipped-w" aria-label="Wiki">
<a href="/jasperproject/jasper-client/wiki" aria-label="Wiki" class="js-selected-navigation-item sunken-menu-item js-disable-pjax" data-hotkey="g w" data-selected-links="repo_wiki /jasperproject/jasper-client/wiki">
<span class="octicon octicon-book"></span> <span class="full-word">Wiki</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
</ul>
<div class="sunken-menu-separator"></div>
<ul class="sunken-menu-group">
<li class="tooltipped tooltipped-w" aria-label="Pulse">
<a href="/jasperproject/jasper-client/pulse" aria-label="Pulse" class="js-selected-navigation-item sunken-menu-item" data-pjax="true" data-selected-links="pulse /jasperproject/jasper-client/pulse">
<span class="octicon octicon-pulse"></span> <span class="full-word">Pulse</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
<li class="tooltipped tooltipped-w" aria-label="Graphs">
<a href="/jasperproject/jasper-client/graphs" aria-label="Graphs" class="js-selected-navigation-item sunken-menu-item" data-pjax="true" data-selected-links="repo_graphs repo_contributors /jasperproject/jasper-client/graphs">
<span class="octicon octicon-graph"></span> <span class="full-word">Graphs</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
<li class="tooltipped tooltipped-w" aria-label="Network">
<a href="/jasperproject/jasper-client/network" aria-label="Network" class="js-selected-navigation-item sunken-menu-item js-disable-pjax" data-selected-links="repo_network /jasperproject/jasper-client/network">
<span class="octicon octicon-repo-forked"></span> <span class="full-word">Network</span>
<img alt="" class="mini-loader" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif" width="16" />
</a> </li>
</ul>
</div>
</div>
<div class="only-with-full-nav">
<div class="clone-url open"
data-protocol-type="http"
data-url="/users/set_protocol?protocol_selector=http&protocol_type=clone">
<h3><strong>HTTPS</strong> clone URL</h3>
<div class="clone-url-box">
<input type="text" class="clone js-url-field"
value="https://github.com/jasperproject/jasper-client.git" readonly="readonly">
<span class="url-box-clippy">
<button aria-label="copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="https://github.com/jasperproject/jasper-client.git" data-copied-hint="copied!" type="button"><span class="octicon octicon-clippy"></span></button>
</span>
</div>
</div>
<div class="clone-url "
data-protocol-type="ssh"
data-url="/users/set_protocol?protocol_selector=ssh&protocol_type=clone">
<h3><strong>SSH</strong> clone URL</h3>
<div class="clone-url-box">
<input type="text" class="clone js-url-field"
value="[email protected]:jasperproject/jasper-client.git" readonly="readonly">
<span class="url-box-clippy">
<button aria-label="copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="[email protected]:jasperproject/jasper-client.git" data-copied-hint="copied!" type="button"><span class="octicon octicon-clippy"></span></button>
</span>
</div>
</div>
<div class="clone-url "
data-protocol-type="subversion"
data-url="/users/set_protocol?protocol_selector=subversion&protocol_type=clone">
<h3><strong>Subversion</strong> checkout URL</h3>
<div class="clone-url-box">
<input type="text" class="clone js-url-field"
value="https://github.com/jasperproject/jasper-client" readonly="readonly">
<span class="url-box-clippy">
<button aria-label="copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="https://github.com/jasperproject/jasper-client" data-copied-hint="copied!" type="button"><span class="octicon octicon-clippy"></span></button>
</span>
</div>
</div>
<p class="clone-options">You can clone with
<a href="#" class="js-clone-selector" data-protocol="http">HTTPS</a>,
<a href="#" class="js-clone-selector" data-protocol="ssh">SSH</a>,
or <a href="#" class="js-clone-selector" data-protocol="subversion">Subversion</a>.
<span class="help tooltipped tooltipped-n" aria-label="Get help on which URL is right for you.">
<a href="https://help.github.com/articles/which-remote-url-should-i-use">
<span class="octicon octicon-question"></span>
</a>
</span>
</p>
<a href="github-windows://openRepo/https://github.com/jasperproject/jasper-client" class="minibutton sidebar-button" title="Save jasperproject/jasper-client to your computer and use it in GitHub Desktop." aria-label="Save jasperproject/jasper-client to your computer and use it in GitHub Desktop.">
<span class="octicon octicon-device-desktop"></span>
Clone in Desktop
</a>
<a href="/jasperproject/jasper-client/archive/master.zip"
class="minibutton sidebar-button"
aria-label="Download jasperproject/jasper-client as a zip file"
title="Download jasperproject/jasper-client as a zip file"
rel="nofollow">
<span class="octicon octicon-cloud-download"></span>
Download ZIP
</a>
</div>
</div><!-- /.repository-sidebar -->
<div id="js-repo-pjax-container" class="repository-content context-loader-container" data-pjax-container>
<a href="/jasperproject/jasper-client/blob/f2de63d707cbc85c80df9610442cb80bb67556d2/boot/test.py" class="hidden js-permalink-shortcut" data-hotkey="y">Permalink</a>
<!-- blob contrib key: blob_contributors:v21:635273dd69a78bc91b42896de776afa7 -->
<p title="This is a placeholder element" class="js-history-link-replace hidden"></p>
<a href="/jasperproject/jasper-client/find/master" data-pjax data-hotkey="t" class="js-show-file-finder" style="display:none">Show File Finder</a>
<div class="file-navigation">
<div class="select-menu js-menu-container js-select-menu" >
<span class="minibutton select-menu-button js-menu-target" data-hotkey="w"
data-master-branch="master"
data-ref="master"
role="button" aria-label="Switch branches or tags" tabindex="0" aria-haspopup="true">
<span class="octicon octicon-git-branch"></span>
<i>branch:</i>
<span class="js-select-button">master</span>
</span>
<div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax aria-hidden="true">
<div class="select-menu-modal">
<div class="select-menu-header">
<span class="select-menu-title">Switch branches/tags</span>
<span class="octicon octicon-x js-menu-close"></span>
</div> <!-- /.select-menu-header -->
<div class="select-menu-filters">
<div class="select-menu-text-filter">
<input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="js-filterable-field js-navigation-enable" placeholder="Filter branches/tags">
</div>
<div class="select-menu-tabs">
<ul>
<li class="select-menu-tab">
<a href="#" data-tab-filter="branches" class="js-select-menu-tab">Branches</a>
</li>
<li class="select-menu-tab">
<a href="#" data-tab-filter="tags" class="js-select-menu-tab">Tags</a>
</li>
</ul>
</div><!-- /.select-menu-tabs -->
</div><!-- /.select-menu-filters -->
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
<div class="select-menu-item js-navigation-item selected">
<span class="select-menu-item-icon octicon octicon-check"></span>
<a href="/jasperproject/jasper-client/blob/master/boot/test.py"
data-name="master"
data-skip-pjax="true"
rel="nofollow"
class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target"
title="master">master</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item ">
<span class="select-menu-item-icon octicon octicon-check"></span>
<a href="/jasperproject/jasper-client/blob/nowifi/boot/test.py"
data-name="nowifi"
data-skip-pjax="true"
rel="nofollow"
class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target"
title="nowifi">nowifi</a>
</div> <!-- /.select-menu-item -->
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div> <!-- /.select-menu-list -->
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div> <!-- /.select-menu-list -->
</div> <!-- /.select-menu-modal -->
</div> <!-- /.select-menu-modal-holder -->
</div> <!-- /.select-menu -->
<div class="breadcrumb">
<span class='repo-root js-repo-root'><span itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"><a href="/jasperproject/jasper-client" data-branch="master" data-direction="back" data-pjax="true" itemscope="url"><span itemprop="title">jasper-client</span></a></span></span><span class="separator"> / </span><span itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"><a href="/jasperproject/jasper-client/tree/master/boot" data-branch="master" data-direction="back" data-pjax="true" itemscope="url"><span itemprop="title">boot</span></a></span><span class="separator"> / </span><strong class="final-path">test.py</strong> <button aria-label="copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="boot/test.py" data-copied-hint="copied!" type="button"><span class="octicon octicon-clippy"></span></button>
</div>
</div>
<div class="commit file-history-tease">
<img alt="Charles Marsh" class="main-avatar js-avatar" data-user="1309177" height="24" src="https://avatars1.githubusercontent.com/u/1309177?s=140" width="24" />
<span class="author"><a href="/crm416" rel="contributor">crm416</a></span>
<time datetime="2014-05-26T23:44:50-07:00" is="relative-time">May 26, 2014</time>
<div class="commit-title">
<a href="/jasperproject/jasper-client/commit/6897e6003b6ce912c48d975bae37de8e3a4d0839" class="message" data-pjax="true" title="finalized test">finalized test</a>
</div>
<div class="participation">
<p class="quickstat"><a href="#blob_contributors_box" rel="facebox"><strong>1</strong> contributor</a></p>
</div>
<div id="blob_contributors_box" style="display:none">
<h2 class="facebox-header">Users who have contributed to this file</h2>
<ul class="facebox-user-list">
<li class="facebox-user-list-item">
<img alt="Charles Marsh" class=" js-avatar" data-user="1309177" height="24" src="https://avatars1.githubusercontent.com/u/1309177?s=140" width="24" />
<a href="/crm416">crm416</a>
</li>
</ul>
</div>
</div>
<div class="file-box">
<div class="file">
<div class="meta clearfix">
<div class="info file-name">
<span class="icon"><b class="octicon octicon-file-text"></b></span>
<span class="mode" title="File Mode">file</span>
<span class="meta-divider"></span>
<span>43 lines (32 sloc)</span>
<span class="meta-divider"></span>
<span>1.314 kb</span>
</div>
<div class="actions">
<div class="button-group">
<a class="minibutton tooltipped tooltipped-w"
href="github-windows://openRepo/https://github.com/jasperproject/jasper-client?branch=master&filepath=boot%2Ftest.py" aria-label="Open this file in GitHub for Windows">
<span class="octicon octicon-device-desktop"></span> Open
</a>
<a class="minibutton tooltipped tooltipped-n js-update-url-with-hash"
aria-label="Clicking this button will automatically fork this project so you can edit the file"
href="/jasperproject/jasper-client/edit/master/boot/test.py"
data-method="post" rel="nofollow">Edit</a>
<a href="/jasperproject/jasper-client/raw/master/boot/test.py" class="button minibutton " id="raw-url">Raw</a>
<a href="/jasperproject/jasper-client/blame/master/boot/test.py" class="button minibutton js-update-url-with-hash">Blame</a>
<a href="/jasperproject/jasper-client/commits/master/boot/test.py" class="button minibutton " rel="nofollow">History</a>
</div><!-- /.button-group -->
<a class="minibutton danger empty-icon tooltipped tooltipped-s"
href="/jasperproject/jasper-client/delete/master/boot/test.py"
aria-label="Fork this project and delete file"
data-method="post" data-test-id="delete-blob-file" rel="nofollow">
Delete
</a>
</div><!-- /.actions -->
</div>
<div class="blob-wrapper data type-python js-blob-data">
<table class="file-code file-diff tab-size-8">
<tr class="file-code-line">
<td class="blob-line-nums">
<span id="L1" rel="#L1">1</span>
<span id="L2" rel="#L2">2</span>
<span id="L3" rel="#L3">3</span>
<span id="L4" rel="#L4">4</span>
<span id="L5" rel="#L5">5</span>
<span id="L6" rel="#L6">6</span>
<span id="L7" rel="#L7">7</span>
<span id="L8" rel="#L8">8</span>
<span id="L9" rel="#L9">9</span>
<span id="L10" rel="#L10">10</span>
<span id="L11" rel="#L11">11</span>
<span id="L12" rel="#L12">12</span>
<span id="L13" rel="#L13">13</span>
<span id="L14" rel="#L14">14</span>
<span id="L15" rel="#L15">15</span>
<span id="L16" rel="#L16">16</span>
<span id="L17" rel="#L17">17</span>
<span id="L18" rel="#L18">18</span>
<span id="L19" rel="#L19">19</span>
<span id="L20" rel="#L20">20</span>
<span id="L21" rel="#L21">21</span>
<span id="L22" rel="#L22">22</span>
<span id="L23" rel="#L23">23</span>
<span id="L24" rel="#L24">24</span>
<span id="L25" rel="#L25">25</span>
<span id="L26" rel="#L26">26</span>
<span id="L27" rel="#L27">27</span>
<span id="L28" rel="#L28">28</span>
<span id="L29" rel="#L29">29</span>
<span id="L30" rel="#L30">30</span>
<span id="L31" rel="#L31">31</span>
<span id="L32" rel="#L32">32</span>
<span id="L33" rel="#L33">33</span>
<span id="L34" rel="#L34">34</span>
<span id="L35" rel="#L35">35</span>
<span id="L36" rel="#L36">36</span>
<span id="L37" rel="#L37">37</span>
<span id="L38" rel="#L38">38</span>
<span id="L39" rel="#L39">39</span>
<span id="L40" rel="#L40">40</span>
<span id="L41" rel="#L41">41</span>
<span id="L42" rel="#L42">42</span>
</td>
<td class="blob-line-code"><div class="code-body highlight"><pre><div class='line' id='LC1'><span class="kn">import</span> <span class="nn">os</span></div><div class='line' id='LC2'><span class="kn">import</span> <span class="nn">sys</span></div><div class='line' id='LC3'><span class="kn">import</span> <span class="nn">unittest</span></div><div class='line' id='LC4'><span class="kn">from</span> <span class="nn">mock</span> <span class="kn">import</span> <span class="n">patch</span></div><div class='line' id='LC5'><span class="kn">import</span> <span class="nn">vocabcompiler</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="n">lib_path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="s">'../client'</span><span class="p">)</span></div><div class='line' id='LC8'><span class="n">mod_path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="s">'../client/modules/'</span><span class="p">)</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">lib_path</span><span class="p">)</span></div><div class='line' id='LC11'><span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">mod_path</span><span class="p">)</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'><span class="kn">import</span> <span class="nn">g2p</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'><br/></div><div class='line' id='LC16'><span class="k">class</span> <span class="nc">TestVocabCompiler</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span></div><div class='line' id='LC17'><br/></div><div class='line' id='LC18'> <span class="k">def</span> <span class="nf">testWordExtraction</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span></div><div class='line' id='LC19'> <span class="n">sentences</span> <span class="o">=</span> <span class="s">"temp_sentences.txt"</span></div><div class='line' id='LC20'> <span class="n">dictionary</span> <span class="o">=</span> <span class="s">"temp_dictionary.dic"</span></div><div class='line' id='LC21'> <span class="n">languagemodel</span> <span class="o">=</span> <span class="s">"temp_languagemodel.lm"</span></div><div class='line' id='LC22'><br/></div><div class='line' id='LC23'> <span class="n">words</span> <span class="o">=</span> <span class="p">[</span></div><div class='line' id='LC24'> <span class="s">'HACKER'</span><span class="p">,</span> <span class="s">'LIFE'</span><span class="p">,</span> <span class="s">'FACEBOOK'</span><span class="p">,</span> <span class="s">'THIRD'</span><span class="p">,</span> <span class="s">'NO'</span><span class="p">,</span> <span class="s">'JOKE'</span><span class="p">,</span></div><div class='line' id='LC25'> <span class="s">'NOTIFICATION'</span><span class="p">,</span> <span class="s">'MEANING'</span><span class="p">,</span> <span class="s">'TIME'</span><span class="p">,</span> <span class="s">'TODAY'</span><span class="p">,</span> <span class="s">'SECOND'</span><span class="p">,</span></div><div class='line' id='LC26'> <span class="s">'BIRTHDAY'</span><span class="p">,</span> <span class="s">'KNOCK KNOCK'</span><span class="p">,</span> <span class="s">'INBOX'</span><span class="p">,</span> <span class="s">'OF'</span><span class="p">,</span> <span class="s">'NEWS'</span><span class="p">,</span> <span class="s">'YES'</span><span class="p">,</span></div><div class='line' id='LC27'> <span class="s">'TOMORROW'</span><span class="p">,</span> <span class="s">'EMAIL'</span><span class="p">,</span> <span class="s">'WEATHER'</span><span class="p">,</span> <span class="s">'FIRST'</span><span class="p">,</span> <span class="s">'MUSIC'</span><span class="p">,</span> <span class="s">'SPOTIFY'</span></div><div class='line' id='LC28'> <span class="p">]</span></div><div class='line' id='LC29'><br/></div><div class='line' id='LC30'> <span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">object</span><span class="p">(</span><span class="n">g2p</span><span class="p">,</span> <span class="s">'translateWords'</span><span class="p">)</span> <span class="k">as</span> <span class="n">translateWords</span><span class="p">:</span></div><div class='line' id='LC31'> <span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">object</span><span class="p">(</span><span class="n">vocabcompiler</span><span class="p">,</span> <span class="s">'text2lm'</span><span class="p">)</span> <span class="k">as</span> <span class="n">text2lm</span><span class="p">:</span></div><div class='line' id='LC32'> <span class="n">vocabcompiler</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">sentences</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">,</span> <span class="n">languagemodel</span><span class="p">)</span></div><div class='line' id='LC33'><br/></div><div class='line' id='LC34'> <span class="c"># 'words' is appended with ['MUSIC', 'SPOTIFY']</span></div><div class='line' id='LC35'> <span class="c"># so must be > 2 to have received WORDS from modules</span></div><div class='line' id='LC36'> <span class="n">translateWords</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="n">words</span><span class="p">)</span></div><div class='line' id='LC37'> <span class="bp">self</span><span class="o">.</span><span class="n">assertTrue</span><span class="p">(</span><span class="n">text2lm</span><span class="o">.</span><span class="n">called</span><span class="p">)</span></div><div class='line' id='LC38'> <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">sentences</span><span class="p">)</span></div><div class='line' id='LC39'> <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">dictionary</span><span class="p">)</span></div><div class='line' id='LC40'><br/></div><div class='line' id='LC41'><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">'__main__'</span><span class="p">:</span></div><div class='line' id='LC42'> <span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">()</span></div></pre></div></td>
</tr>
</table>
</div>
</div>
</div>
<a href="#jump-to-line" rel="facebox[.linejump]" data-hotkey="l" class="js-jump-to-line" style="display:none">Jump to Line</a>
<div id="jump-to-line" style="display:none">
<form accept-charset="UTF-8" class="js-jump-to-line-form">
<input class="linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" autofocus>
<button type="submit" class="button">Go</button>
</form>
</div>
</div>
</div><!-- /.repo-container -->
<div class="modal-backdrop"></div>
</div><!-- /.container -->
</div><!-- /.site -->
</div><!-- /.wrapper -->
<div class="container">
<div class="site-footer">
<ul class="site-footer-links right">
<li><a href="https://status.github.com/">Status</a></li>
<li><a href="http://developer.github.com">API</a></li>
<li><a href="http://training.github.com">Training</a></li>
<li><a href="http://shop.github.com">Shop</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/about">About</a></li>
</ul>
<a href="/">
<span class="mega-octicon octicon-mark-github" title="GitHub"></span>
</a>
<ul class="site-footer-links">
<li>© 2014 <span title="0.05208s from github-fe139-cp1-prd.iad.github.net">GitHub</span>, Inc.</li>
<li><a href="/site/terms">Terms</a></li>
<li><a href="/site/privacy">Privacy</a></li>
<li><a href="/security">Security</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div><!-- /.site-footer -->
</div><!-- /.container -->
<div class="fullscreen-overlay js-fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents" class="fullscreen-contents js-fullscreen-contents" placeholder="" data-suggester="fullscreen_suggester"></textarea>
</div>
</div>
<div class="fullscreen-sidebar">
<a href="#" class="exit-fullscreen js-exit-fullscreen tooltipped tooltipped-w" aria-label="Exit Zen Mode">
<span class="mega-octicon octicon-screen-normal"></span>
</a>
<a href="#" class="theme-switcher js-theme-switcher tooltipped tooltipped-w"
aria-label="Switch themes">
<span class="octicon octicon-color-mode"></span>
</a>
</div>
</div>
<div id="ajax-error-message" class="flash flash-error">
<span class="octicon octicon-alert"></span>
<a href="#" class="octicon octicon-x close js-ajax-error-dismiss"></a>
Something went wrong with that request. Please try again.
</div>
<script crossorigin="anonymous" src="https://assets-cdn.github.com/assets/frameworks-e87aa86ffae369acf33a96bb6567b2b57183be57.js" type="text/javascript"></script>
<script async="async" crossorigin="anonymous" src="https://assets-cdn.github.com/assets/github-100ee281915e20c71d6b0ff254fbbb70b3fcaf3a.js" type="text/javascript"></script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
</body>
</html>
| [
"[email protected]"
] | |
7948bf0679671efa21e236cadeae4d3fb051b4f2 | 0b4d3cab6dfc1cf317106f1c8fcc05111ea40ee9 | /src/fparser/two/tests/fortran2003/test_cray_pointer_stmt.py | f725220aeee9fff3de948727d13a33e3c660c77f | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | mlange05/fparser | 43a34d286fc4e4da9ebe9d0379335e9c15727c10 | 94939a561107fdeb307d1dd0070a4d15b951f6ac | refs/heads/master | 2020-08-20T06:31:33.051967 | 2019-10-05T23:31:49 | 2019-10-05T23:31:49 | 215,991,981 | 0 | 0 | null | 2019-10-18T09:44:41 | 2019-10-18T09:44:40 | null | UTF-8 | Python | false | false | 4,439 | py | # Copyright (c) 2019 Science and Technology Facilities Council
# All rights reserved.
# Modifications made as part of the fparser project are distributed
# under the following license:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''Test Fortran 2003 Cray-pointers: This file tests the support for the
Cray-pointer statement.
'''
import pytest
from fparser.api import get_reader
from fparser.two.Fortran2003 import Cray_Pointer_Stmt
from fparser.two.utils import NoMatchError
def test_cray_pointer_stmt(f2003_create):
'''Check that a basic Cray-pointer statement is parsed
correctly. Input separately as a string and as a reader object
'''
def check_use(reader):
'''Internal helper function to avoid code replication.'''
ast = Cray_Pointer_Stmt(reader)
assert "POINTER(a, b)" in str(ast)
assert (repr(ast) ==
"Cray_Pointer_Stmt('POINTER', Cray_Pointer_Decl_List(',', "
"(Cray_Pointer_Decl(Name('a'), Name('b')),)))")
line = "pointer (a, b)"
check_use(line)
reader = get_reader(line)
check_use(reader)
def test_spaces(f2003_create):
'''Check that spaces are allowed.'''
line = " pointer ( a , b ) "
ast = Cray_Pointer_Stmt(line)
assert "POINTER(a, b)" in str(ast)
def test_case(f2003_create):
'''Check that different case is allowed.'''
line = "PoInTeR (a, b)"
ast = Cray_Pointer_Stmt(line)
assert "POINTER(a, b)" in str(ast)
def test_list(f2003_create):
'''Check that a list of Cray-pointers is supported.'''
line = "pointer (a, b), (c, d(1:n)), (e, f)"
ast = Cray_Pointer_Stmt(line)
assert "POINTER(a, b), (c, d(1 : n)), (e, f)" in str(ast)
def test_errors(f2003_create):
'''Check that syntax errors produce a NoMatchError exception.'''
for line in ["", " ", "ponter (a, b)", "pointer", "pointer a, b"
"pointer (a, b) (a, b)"]:
with pytest.raises(NoMatchError) as excinfo:
_ = Cray_Pointer_Stmt(line)
assert "Cray_Pointer_Stmt: '{0}'".format(line) in str(excinfo)
def test_invalid_cray_pointer(f2003_create, monkeypatch):
'''Test that the cray-pointer extension to the standard raises an
exception if it is not named as a valid extension.
'''
from fparser.two import utils
monkeypatch.setattr(utils, "EXTENSIONS", [])
myinput = "pointer (mypointer, mypointee)"
with pytest.raises(NoMatchError) as excinfo:
_ = Cray_Pointer_Stmt(myinput)
assert "Cray_Pointer_Stmt: '{0}'".format(myinput) \
in str(excinfo.value)
def test_valid_cray_pointer(f2003_create, monkeypatch):
'''Test that the cray-pointer extension to the standard produces the
expected output if it is named as a valid extension.
'''
from fparser.two import utils
monkeypatch.setattr(utils, "EXTENSIONS", ["cray-pointer"])
myinput = "pointer(mypointer, mypointee)"
result = Cray_Pointer_Stmt(myinput)
assert str(result).lower() == myinput
| [
"[email protected]"
] | |
d1c1c05e9c930cce236b42fc2ad41c4641d8950f | 575a2a170fd6ccd449b6d17bf864eb46c210b265 | /nestedtensor/nn/mha.py | 86625bd97f6e07596a0c9527537c8186cc55c1f7 | [
"BSD-3-Clause"
] | permissive | isabella232/nestedtensor | 9bdc2d2d8ee79f6ca7f2568218bbc0cf446f1159 | f79ec60c02c783defbc0b3f586eefa721496fa07 | refs/heads/master | 2023-04-15T21:03:29.833914 | 2021-04-17T00:10:21 | 2021-04-17T00:10:21 | 358,856,234 | 0 | 0 | BSD-3-Clause | 2021-04-17T11:15:15 | 2021-04-17T11:04:34 | null | UTF-8 | Python | false | false | 7,373 | py | from torch.nn.init import constant_
from torch.nn.init import xavier_uniform_
from torch.nn.init import xavier_normal_
from torch.nn.parameter import Parameter
from torch import nn, Tensor
from torch.nn.modules.module import Module
import torch
import torch.nn.functional as F
import nestedtensor
# NT case query, key, value have nested_dim 1 and are of shape (bsz, tgt_len, embed_dim)
def multi_head_attention_forward(query,
key,
value,
embed_dim_to_check,
num_heads,
in_proj_weight,
in_proj_bias,
bias_k,
bias_v,
add_zero_attn,
dropout_p,
out_proj_weight,
out_proj_bias,
training=True,
key_padding_mask=None,
need_weights=True,
attn_mask=None,
use_separate_proj_weight=False,
q_proj_weight=None,
k_proj_weight=None,
v_proj_weight=None,
static_k=None,
static_v=None
):
assert isinstance(query, nestedtensor.NestedTensor)
assert isinstance(key, nestedtensor.NestedTensor)
assert isinstance(value, nestedtensor.NestedTensor)
assert torch.is_tensor(out_proj_weight)
assert torch.is_tensor(out_proj_bias)
# TODO: Explicitly unsupported flags
assert not use_separate_proj_weight
assert attn_mask is None
assert key_padding_mask is None
assert bias_k is None
assert bias_v is None
assert static_k is None
assert static_v is None
assert not add_zero_attn
assert not need_weights
bsz, tgt_len, embed_dim = query.size()
assert embed_dim == embed_dim_to_check
# allow MHA to have different sizes for the feature dimension
assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
head_dim = embed_dim // num_heads
assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
scaling = float(head_dim) ** -0.5
return nestedtensor.nested.nested._wrap_result(
torch.ops.nestedtensor.min_mha(num_heads,
head_dim,
dropout_p,
training,
query._impl,
key._impl,
value._impl,
in_proj_weight,
in_proj_bias,
scaling,
out_proj_weight,
out_proj_bias)), None
class MultiheadAttention(Module):
__annotations__ = {
'bias_k': torch._jit_internal.Optional[torch.Tensor],
'bias_v': torch._jit_internal.Optional[torch.Tensor],
}
__constants__ = ['q_proj_weight', 'k_proj_weight',
'v_proj_weight', 'in_proj_weight']
def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None):
super(MultiheadAttention, self).__init__()
self.embed_dim = embed_dim
self.kdim = kdim if kdim is not None else embed_dim
self.vdim = vdim if vdim is not None else embed_dim
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * \
num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
if self._qkv_same_embed_dim is False:
self.q_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim))
self.k_proj_weight = Parameter(torch.Tensor(embed_dim, self.kdim))
self.v_proj_weight = Parameter(torch.Tensor(embed_dim, self.vdim))
self.register_parameter('in_proj_weight', None)
else:
self.in_proj_weight = Parameter(
torch.empty(3 * embed_dim, embed_dim))
self.register_parameter('q_proj_weight', None)
self.register_parameter('k_proj_weight', None)
self.register_parameter('v_proj_weight', None)
if bias:
self.in_proj_bias = Parameter(torch.empty(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = Parameter(torch.empty(1, 1, embed_dim))
self.bias_v = Parameter(torch.empty(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self._reset_parameters()
def _reset_parameters(self):
if self._qkv_same_embed_dim:
xavier_uniform_(self.in_proj_weight)
else:
xavier_uniform_(self.q_proj_weight)
xavier_uniform_(self.k_proj_weight)
xavier_uniform_(self.v_proj_weight)
if self.in_proj_bias is not None:
constant_(self.in_proj_bias, 0.)
constant_(self.out_proj.bias, 0.)
if self.bias_k is not None:
xavier_normal_(self.bias_k)
if self.bias_v is not None:
xavier_normal_(self.bias_v)
def __setstate__(self, state):
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
if '_qkv_same_embed_dim' not in state:
state['_qkv_same_embed_dim'] = True
super(MultiheadAttention, self).__setstate__(state)
def forward(self, query, key, value, key_padding_mask=None,
need_weights=True, attn_mask=None):
if not self._qkv_same_embed_dim:
return multi_head_attention_forward(
query, key, value, self.embed_dim, self.num_heads,
self.in_proj_weight, self.in_proj_bias,
self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask, need_weights=need_weights,
attn_mask=attn_mask, use_separate_proj_weight=True,
q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight)
else:
return multi_head_attention_forward(
query, key, value, self.embed_dim, self.num_heads,
self.in_proj_weight, self.in_proj_bias,
self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training,
key_padding_mask=key_padding_mask, need_weights=need_weights,
attn_mask=attn_mask)
| [
"[email protected]"
] | |
0fc3eaf9e643c59f0f874c9386529b454a8bb439 | 9ca9cad46f2358717394f39e2cfac2af4a2f5aca | /Week07/[실습]Logistic_Regression/[실습]Logistic_Regression_LJO.py | 499d844b688aba16ed9bda3767b57c2e0f1f177f | [] | no_license | Artinto/Python_and_AI_Study | ddfd165d1598914e99a125c3019a740a7791f6f6 | 953ff3780287825afe9ed5f9b45017359707d07a | refs/heads/main | 2023-05-05T15:42:25.963855 | 2021-05-24T12:24:31 | 2021-05-24T12:24:31 | 325,218,591 | 1 | 3 | null | null | null | null | UTF-8 | Python | false | false | 31,245 | py | from torch import tensor
from torch import nn
from torch import sigmoid
import torch.optim as optim
import numpy as np
dataset_path="/content/drive/MyDrive/diabetes.csv"
dataset=np.loadtxt(dataset_path, delimiter=',',dtype=np.float32)
x_data=tensor(dataset[:,:-1])
y_data=tensor(dataset[:,[-1]])
#y_data=y_data.unsqueeze(1)
count=0
ans=0
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = nn.Linear(8, 1)
def forward(self, x):
y_pred = sigmoid(self.linear(x))
return y_pred
model = Model()
criterion = nn.BCELoss(reduction='mean')
optimizer = optim.SGD(model.parameters(), lr=0.08)
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(f'Epoch {epoch + 1}/1000 | Loss: {loss.item():.4f}')
optimizer.zero_grad()
loss.backward()
optimizer.step()
for i in range(len(y_data)):
if y_pred[i] > 0.5:
ans=1
else:
ans=0
if ans==y_data[i]:
count+=1
hour_var = tensor(x_data[0])
y_pred = model(hour_var)
print("Prediction (after training)", x_data[0],":", y_pred.item())
print("accuracy : ",(count/len(x_data))*100)
#결과
Epoch 1/1000 | Loss: 0.6688
Epoch 2/1000 | Loss: 0.6660
Epoch 3/1000 | Loss: 0.6634
Epoch 4/1000 | Loss: 0.6610
Epoch 5/1000 | Loss: 0.6587
Epoch 6/1000 | Loss: 0.6566
Epoch 7/1000 | Loss: 0.6545
Epoch 8/1000 | Loss: 0.6526
Epoch 9/1000 | Loss: 0.6508
Epoch 10/1000 | Loss: 0.6491
Epoch 11/1000 | Loss: 0.6474
Epoch 12/1000 | Loss: 0.6459
Epoch 13/1000 | Loss: 0.6444
Epoch 14/1000 | Loss: 0.6430
Epoch 15/1000 | Loss: 0.6416
Epoch 16/1000 | Loss: 0.6403
Epoch 17/1000 | Loss: 0.6391
Epoch 18/1000 | Loss: 0.6379
Epoch 19/1000 | Loss: 0.6367
Epoch 20/1000 | Loss: 0.6356
Epoch 21/1000 | Loss: 0.6345
Epoch 22/1000 | Loss: 0.6335
Epoch 23/1000 | Loss: 0.6325
Epoch 24/1000 | Loss: 0.6315
Epoch 25/1000 | Loss: 0.6305
Epoch 26/1000 | Loss: 0.6296
Epoch 27/1000 | Loss: 0.6287
Epoch 28/1000 | Loss: 0.6278
Epoch 29/1000 | Loss: 0.6269
Epoch 30/1000 | Loss: 0.6261
Epoch 31/1000 | Loss: 0.6253
Epoch 32/1000 | Loss: 0.6245
Epoch 33/1000 | Loss: 0.6237
Epoch 34/1000 | Loss: 0.6229
Epoch 35/1000 | Loss: 0.6221
Epoch 36/1000 | Loss: 0.6214
Epoch 37/1000 | Loss: 0.6206
Epoch 38/1000 | Loss: 0.6199
Epoch 39/1000 | Loss: 0.6192
Epoch 40/1000 | Loss: 0.6185
Epoch 41/1000 | Loss: 0.6178
Epoch 42/1000 | Loss: 0.6171
Epoch 43/1000 | Loss: 0.6164
Epoch 44/1000 | Loss: 0.6158
Epoch 45/1000 | Loss: 0.6151
Epoch 46/1000 | Loss: 0.6145
Epoch 47/1000 | Loss: 0.6138
Epoch 48/1000 | Loss: 0.6132
Epoch 49/1000 | Loss: 0.6125
Epoch 50/1000 | Loss: 0.6119
Epoch 51/1000 | Loss: 0.6113
Epoch 52/1000 | Loss: 0.6107
Epoch 53/1000 | Loss: 0.6101
Epoch 54/1000 | Loss: 0.6095
Epoch 55/1000 | Loss: 0.6089
Epoch 56/1000 | Loss: 0.6083
Epoch 57/1000 | Loss: 0.6077
Epoch 58/1000 | Loss: 0.6071
Epoch 59/1000 | Loss: 0.6065
Epoch 60/1000 | Loss: 0.6059
Epoch 61/1000 | Loss: 0.6053
Epoch 62/1000 | Loss: 0.6048
Epoch 63/1000 | Loss: 0.6042
Epoch 64/1000 | Loss: 0.6037
Epoch 65/1000 | Loss: 0.6031
Epoch 66/1000 | Loss: 0.6025
Epoch 67/1000 | Loss: 0.6020
Epoch 68/1000 | Loss: 0.6015
Epoch 69/1000 | Loss: 0.6009
Epoch 70/1000 | Loss: 0.6004
Epoch 71/1000 | Loss: 0.5998
Epoch 72/1000 | Loss: 0.5993
Epoch 73/1000 | Loss: 0.5988
Epoch 74/1000 | Loss: 0.5983
Epoch 75/1000 | Loss: 0.5977
Epoch 76/1000 | Loss: 0.5972
Epoch 77/1000 | Loss: 0.5967
Epoch 78/1000 | Loss: 0.5962
Epoch 79/1000 | Loss: 0.5957
Epoch 80/1000 | Loss: 0.5952
Epoch 81/1000 | Loss: 0.5947
Epoch 82/1000 | Loss: 0.5942
Epoch 83/1000 | Loss: 0.5937
Epoch 84/1000 | Loss: 0.5932
Epoch 85/1000 | Loss: 0.5927
Epoch 86/1000 | Loss: 0.5922
Epoch 87/1000 | Loss: 0.5917
Epoch 88/1000 | Loss: 0.5912
Epoch 89/1000 | Loss: 0.5908
Epoch 90/1000 | Loss: 0.5903
Epoch 91/1000 | Loss: 0.5898
Epoch 92/1000 | Loss: 0.5893
Epoch 93/1000 | Loss: 0.5889
Epoch 94/1000 | Loss: 0.5884
Epoch 95/1000 | Loss: 0.5879
Epoch 96/1000 | Loss: 0.5875
Epoch 97/1000 | Loss: 0.5870
Epoch 98/1000 | Loss: 0.5866
Epoch 99/1000 | Loss: 0.5861
Epoch 100/1000 | Loss: 0.5857
Epoch 101/1000 | Loss: 0.5852
Epoch 102/1000 | Loss: 0.5848
Epoch 103/1000 | Loss: 0.5843
Epoch 104/1000 | Loss: 0.5839
Epoch 105/1000 | Loss: 0.5834
Epoch 106/1000 | Loss: 0.5830
Epoch 107/1000 | Loss: 0.5826
Epoch 108/1000 | Loss: 0.5821
Epoch 109/1000 | Loss: 0.5817
Epoch 110/1000 | Loss: 0.5813
Epoch 111/1000 | Loss: 0.5808
Epoch 112/1000 | Loss: 0.5804
Epoch 113/1000 | Loss: 0.5800
Epoch 114/1000 | Loss: 0.5796
Epoch 115/1000 | Loss: 0.5792
Epoch 116/1000 | Loss: 0.5788
Epoch 117/1000 | Loss: 0.5783
Epoch 118/1000 | Loss: 0.5779
Epoch 119/1000 | Loss: 0.5775
Epoch 120/1000 | Loss: 0.5771
Epoch 121/1000 | Loss: 0.5767
Epoch 122/1000 | Loss: 0.5763
Epoch 123/1000 | Loss: 0.5759
Epoch 124/1000 | Loss: 0.5755
Epoch 125/1000 | Loss: 0.5751
Epoch 126/1000 | Loss: 0.5747
Epoch 127/1000 | Loss: 0.5743
Epoch 128/1000 | Loss: 0.5740
Epoch 129/1000 | Loss: 0.5736
Epoch 130/1000 | Loss: 0.5732
Epoch 131/1000 | Loss: 0.5728
Epoch 132/1000 | Loss: 0.5724
Epoch 133/1000 | Loss: 0.5720
Epoch 134/1000 | Loss: 0.5717
Epoch 135/1000 | Loss: 0.5713
Epoch 136/1000 | Loss: 0.5709
Epoch 137/1000 | Loss: 0.5706
Epoch 138/1000 | Loss: 0.5702
Epoch 139/1000 | Loss: 0.5698
Epoch 140/1000 | Loss: 0.5695
Epoch 141/1000 | Loss: 0.5691
Epoch 142/1000 | Loss: 0.5687
Epoch 143/1000 | Loss: 0.5684
Epoch 144/1000 | Loss: 0.5680
Epoch 145/1000 | Loss: 0.5677
Epoch 146/1000 | Loss: 0.5673
Epoch 147/1000 | Loss: 0.5670
Epoch 148/1000 | Loss: 0.5666
Epoch 149/1000 | Loss: 0.5663
Epoch 150/1000 | Loss: 0.5659
Epoch 151/1000 | Loss: 0.5656
Epoch 152/1000 | Loss: 0.5652
Epoch 153/1000 | Loss: 0.5649
Epoch 154/1000 | Loss: 0.5645
Epoch 155/1000 | Loss: 0.5642
Epoch 156/1000 | Loss: 0.5639
Epoch 157/1000 | Loss: 0.5635
Epoch 158/1000 | Loss: 0.5632
Epoch 159/1000 | Loss: 0.5629
Epoch 160/1000 | Loss: 0.5625
Epoch 161/1000 | Loss: 0.5622
Epoch 162/1000 | Loss: 0.5619
Epoch 163/1000 | Loss: 0.5616
Epoch 164/1000 | Loss: 0.5612
Epoch 165/1000 | Loss: 0.5609
Epoch 166/1000 | Loss: 0.5606
Epoch 167/1000 | Loss: 0.5603
Epoch 168/1000 | Loss: 0.5600
Epoch 169/1000 | Loss: 0.5597
Epoch 170/1000 | Loss: 0.5593
Epoch 171/1000 | Loss: 0.5590
Epoch 172/1000 | Loss: 0.5587
Epoch 173/1000 | Loss: 0.5584
Epoch 174/1000 | Loss: 0.5581
Epoch 175/1000 | Loss: 0.5578
Epoch 176/1000 | Loss: 0.5575
Epoch 177/1000 | Loss: 0.5572
Epoch 178/1000 | Loss: 0.5569
Epoch 179/1000 | Loss: 0.5566
Epoch 180/1000 | Loss: 0.5563
Epoch 181/1000 | Loss: 0.5560
Epoch 182/1000 | Loss: 0.5557
Epoch 183/1000 | Loss: 0.5554
Epoch 184/1000 | Loss: 0.5551
Epoch 185/1000 | Loss: 0.5548
Epoch 186/1000 | Loss: 0.5545
Epoch 187/1000 | Loss: 0.5543
Epoch 188/1000 | Loss: 0.5540
Epoch 189/1000 | Loss: 0.5537
Epoch 190/1000 | Loss: 0.5534
Epoch 191/1000 | Loss: 0.5531
Epoch 192/1000 | Loss: 0.5528
Epoch 193/1000 | Loss: 0.5526
Epoch 194/1000 | Loss: 0.5523
Epoch 195/1000 | Loss: 0.5520
Epoch 196/1000 | Loss: 0.5517
Epoch 197/1000 | Loss: 0.5515
Epoch 198/1000 | Loss: 0.5512
Epoch 199/1000 | Loss: 0.5509
Epoch 200/1000 | Loss: 0.5506
Epoch 201/1000 | Loss: 0.5504
Epoch 202/1000 | Loss: 0.5501
Epoch 203/1000 | Loss: 0.5498
Epoch 204/1000 | Loss: 0.5496
Epoch 205/1000 | Loss: 0.5493
Epoch 206/1000 | Loss: 0.5490
Epoch 207/1000 | Loss: 0.5488
Epoch 208/1000 | Loss: 0.5485
Epoch 209/1000 | Loss: 0.5483
Epoch 210/1000 | Loss: 0.5480
Epoch 211/1000 | Loss: 0.5478
Epoch 212/1000 | Loss: 0.5475
Epoch 213/1000 | Loss: 0.5472
Epoch 214/1000 | Loss: 0.5470
Epoch 215/1000 | Loss: 0.5467
Epoch 216/1000 | Loss: 0.5465
Epoch 217/1000 | Loss: 0.5462
Epoch 218/1000 | Loss: 0.5460
Epoch 219/1000 | Loss: 0.5458
Epoch 220/1000 | Loss: 0.5455
Epoch 221/1000 | Loss: 0.5453
Epoch 222/1000 | Loss: 0.5450
Epoch 223/1000 | Loss: 0.5448
Epoch 224/1000 | Loss: 0.5445
Epoch 225/1000 | Loss: 0.5443
Epoch 226/1000 | Loss: 0.5441
Epoch 227/1000 | Loss: 0.5438
Epoch 228/1000 | Loss: 0.5436
Epoch 229/1000 | Loss: 0.5433
Epoch 230/1000 | Loss: 0.5431
Epoch 231/1000 | Loss: 0.5429
Epoch 232/1000 | Loss: 0.5426
Epoch 233/1000 | Loss: 0.5424
Epoch 234/1000 | Loss: 0.5422
Epoch 235/1000 | Loss: 0.5420
Epoch 236/1000 | Loss: 0.5417
Epoch 237/1000 | Loss: 0.5415
Epoch 238/1000 | Loss: 0.5413
Epoch 239/1000 | Loss: 0.5411
Epoch 240/1000 | Loss: 0.5408
Epoch 241/1000 | Loss: 0.5406
Epoch 242/1000 | Loss: 0.5404
Epoch 243/1000 | Loss: 0.5402
Epoch 244/1000 | Loss: 0.5399
Epoch 245/1000 | Loss: 0.5397
Epoch 246/1000 | Loss: 0.5395
Epoch 247/1000 | Loss: 0.5393
Epoch 248/1000 | Loss: 0.5391
Epoch 249/1000 | Loss: 0.5389
Epoch 250/1000 | Loss: 0.5386
Epoch 251/1000 | Loss: 0.5384
Epoch 252/1000 | Loss: 0.5382
Epoch 253/1000 | Loss: 0.5380
Epoch 254/1000 | Loss: 0.5378
Epoch 255/1000 | Loss: 0.5376
Epoch 256/1000 | Loss: 0.5374
Epoch 257/1000 | Loss: 0.5372
Epoch 258/1000 | Loss: 0.5370
Epoch 259/1000 | Loss: 0.5368
Epoch 260/1000 | Loss: 0.5366
Epoch 261/1000 | Loss: 0.5364
Epoch 262/1000 | Loss: 0.5362
Epoch 263/1000 | Loss: 0.5360
Epoch 264/1000 | Loss: 0.5358
Epoch 265/1000 | Loss: 0.5356
Epoch 266/1000 | Loss: 0.5354
Epoch 267/1000 | Loss: 0.5352
Epoch 268/1000 | Loss: 0.5350
Epoch 269/1000 | Loss: 0.5348
Epoch 270/1000 | Loss: 0.5346
Epoch 271/1000 | Loss: 0.5344
Epoch 272/1000 | Loss: 0.5342
Epoch 273/1000 | Loss: 0.5340
Epoch 274/1000 | Loss: 0.5338
Epoch 275/1000 | Loss: 0.5336
Epoch 276/1000 | Loss: 0.5334
Epoch 277/1000 | Loss: 0.5332
Epoch 278/1000 | Loss: 0.5330
Epoch 279/1000 | Loss: 0.5329
Epoch 280/1000 | Loss: 0.5327
Epoch 281/1000 | Loss: 0.5325
Epoch 282/1000 | Loss: 0.5323
Epoch 283/1000 | Loss: 0.5321
Epoch 284/1000 | Loss: 0.5319
Epoch 285/1000 | Loss: 0.5317
Epoch 286/1000 | Loss: 0.5316
Epoch 287/1000 | Loss: 0.5314
Epoch 288/1000 | Loss: 0.5312
Epoch 289/1000 | Loss: 0.5310
Epoch 290/1000 | Loss: 0.5308
Epoch 291/1000 | Loss: 0.5307
Epoch 292/1000 | Loss: 0.5305
Epoch 293/1000 | Loss: 0.5303
Epoch 294/1000 | Loss: 0.5301
Epoch 295/1000 | Loss: 0.5300
Epoch 296/1000 | Loss: 0.5298
Epoch 297/1000 | Loss: 0.5296
Epoch 298/1000 | Loss: 0.5294
Epoch 299/1000 | Loss: 0.5293
Epoch 300/1000 | Loss: 0.5291
Epoch 301/1000 | Loss: 0.5289
Epoch 302/1000 | Loss: 0.5287
Epoch 303/1000 | Loss: 0.5286
Epoch 304/1000 | Loss: 0.5284
Epoch 305/1000 | Loss: 0.5282
Epoch 306/1000 | Loss: 0.5281
Epoch 307/1000 | Loss: 0.5279
Epoch 308/1000 | Loss: 0.5277
Epoch 309/1000 | Loss: 0.5276
Epoch 310/1000 | Loss: 0.5274
Epoch 311/1000 | Loss: 0.5272
Epoch 312/1000 | Loss: 0.5271
Epoch 313/1000 | Loss: 0.5269
Epoch 314/1000 | Loss: 0.5268
Epoch 315/1000 | Loss: 0.5266
Epoch 316/1000 | Loss: 0.5264
Epoch 317/1000 | Loss: 0.5263
Epoch 318/1000 | Loss: 0.5261
Epoch 319/1000 | Loss: 0.5260
Epoch 320/1000 | Loss: 0.5258
Epoch 321/1000 | Loss: 0.5256
Epoch 322/1000 | Loss: 0.5255
Epoch 323/1000 | Loss: 0.5253
Epoch 324/1000 | Loss: 0.5252
Epoch 325/1000 | Loss: 0.5250
Epoch 326/1000 | Loss: 0.5249
Epoch 327/1000 | Loss: 0.5247
Epoch 328/1000 | Loss: 0.5246
Epoch 329/1000 | Loss: 0.5244
Epoch 330/1000 | Loss: 0.5243
Epoch 331/1000 | Loss: 0.5241
Epoch 332/1000 | Loss: 0.5240
Epoch 333/1000 | Loss: 0.5238
Epoch 334/1000 | Loss: 0.5237
Epoch 335/1000 | Loss: 0.5235
Epoch 336/1000 | Loss: 0.5234
Epoch 337/1000 | Loss: 0.5232
Epoch 338/1000 | Loss: 0.5231
Epoch 339/1000 | Loss: 0.5229
Epoch 340/1000 | Loss: 0.5228
Epoch 341/1000 | Loss: 0.5226
Epoch 342/1000 | Loss: 0.5225
Epoch 343/1000 | Loss: 0.5223
Epoch 344/1000 | Loss: 0.5222
Epoch 345/1000 | Loss: 0.5221
Epoch 346/1000 | Loss: 0.5219
Epoch 347/1000 | Loss: 0.5218
Epoch 348/1000 | Loss: 0.5216
Epoch 349/1000 | Loss: 0.5215
Epoch 350/1000 | Loss: 0.5213
Epoch 351/1000 | Loss: 0.5212
Epoch 352/1000 | Loss: 0.5211
Epoch 353/1000 | Loss: 0.5209
Epoch 354/1000 | Loss: 0.5208
Epoch 355/1000 | Loss: 0.5207
Epoch 356/1000 | Loss: 0.5205
Epoch 357/1000 | Loss: 0.5204
Epoch 358/1000 | Loss: 0.5202
Epoch 359/1000 | Loss: 0.5201
Epoch 360/1000 | Loss: 0.5200
Epoch 361/1000 | Loss: 0.5198
Epoch 362/1000 | Loss: 0.5197
Epoch 363/1000 | Loss: 0.5196
Epoch 364/1000 | Loss: 0.5194
Epoch 365/1000 | Loss: 0.5193
Epoch 366/1000 | Loss: 0.5192
Epoch 367/1000 | Loss: 0.5190
Epoch 368/1000 | Loss: 0.5189
Epoch 369/1000 | Loss: 0.5188
Epoch 370/1000 | Loss: 0.5187
Epoch 371/1000 | Loss: 0.5185
Epoch 372/1000 | Loss: 0.5184
Epoch 373/1000 | Loss: 0.5183
Epoch 374/1000 | Loss: 0.5181
Epoch 375/1000 | Loss: 0.5180
Epoch 376/1000 | Loss: 0.5179
Epoch 377/1000 | Loss: 0.5178
Epoch 378/1000 | Loss: 0.5176
Epoch 379/1000 | Loss: 0.5175
Epoch 380/1000 | Loss: 0.5174
Epoch 381/1000 | Loss: 0.5173
Epoch 382/1000 | Loss: 0.5171
Epoch 383/1000 | Loss: 0.5170
Epoch 384/1000 | Loss: 0.5169
Epoch 385/1000 | Loss: 0.5168
Epoch 386/1000 | Loss: 0.5167
Epoch 387/1000 | Loss: 0.5165
Epoch 388/1000 | Loss: 0.5164
Epoch 389/1000 | Loss: 0.5163
Epoch 390/1000 | Loss: 0.5162
Epoch 391/1000 | Loss: 0.5161
Epoch 392/1000 | Loss: 0.5159
Epoch 393/1000 | Loss: 0.5158
Epoch 394/1000 | Loss: 0.5157
Epoch 395/1000 | Loss: 0.5156
Epoch 396/1000 | Loss: 0.5155
Epoch 397/1000 | Loss: 0.5153
Epoch 398/1000 | Loss: 0.5152
Epoch 399/1000 | Loss: 0.5151
Epoch 400/1000 | Loss: 0.5150
Epoch 401/1000 | Loss: 0.5149
Epoch 402/1000 | Loss: 0.5148
Epoch 403/1000 | Loss: 0.5147
Epoch 404/1000 | Loss: 0.5145
Epoch 405/1000 | Loss: 0.5144
Epoch 406/1000 | Loss: 0.5143
Epoch 407/1000 | Loss: 0.5142
Epoch 408/1000 | Loss: 0.5141
Epoch 409/1000 | Loss: 0.5140
Epoch 410/1000 | Loss: 0.5139
Epoch 411/1000 | Loss: 0.5138
Epoch 412/1000 | Loss: 0.5136
Epoch 413/1000 | Loss: 0.5135
Epoch 414/1000 | Loss: 0.5134
Epoch 415/1000 | Loss: 0.5133
Epoch 416/1000 | Loss: 0.5132
Epoch 417/1000 | Loss: 0.5131
Epoch 418/1000 | Loss: 0.5130
Epoch 419/1000 | Loss: 0.5129
Epoch 420/1000 | Loss: 0.5128
Epoch 421/1000 | Loss: 0.5127
Epoch 422/1000 | Loss: 0.5126
Epoch 423/1000 | Loss: 0.5125
Epoch 424/1000 | Loss: 0.5123
Epoch 425/1000 | Loss: 0.5122
Epoch 426/1000 | Loss: 0.5121
Epoch 427/1000 | Loss: 0.5120
Epoch 428/1000 | Loss: 0.5119
Epoch 429/1000 | Loss: 0.5118
Epoch 430/1000 | Loss: 0.5117
Epoch 431/1000 | Loss: 0.5116
Epoch 432/1000 | Loss: 0.5115
Epoch 433/1000 | Loss: 0.5114
Epoch 434/1000 | Loss: 0.5113
Epoch 435/1000 | Loss: 0.5112
Epoch 436/1000 | Loss: 0.5111
Epoch 437/1000 | Loss: 0.5110
Epoch 438/1000 | Loss: 0.5109
Epoch 439/1000 | Loss: 0.5108
Epoch 440/1000 | Loss: 0.5107
Epoch 441/1000 | Loss: 0.5106
Epoch 442/1000 | Loss: 0.5105
Epoch 443/1000 | Loss: 0.5104
Epoch 444/1000 | Loss: 0.5103
Epoch 445/1000 | Loss: 0.5102
Epoch 446/1000 | Loss: 0.5101
Epoch 447/1000 | Loss: 0.5100
Epoch 448/1000 | Loss: 0.5099
Epoch 449/1000 | Loss: 0.5098
Epoch 450/1000 | Loss: 0.5097
Epoch 451/1000 | Loss: 0.5096
Epoch 452/1000 | Loss: 0.5095
Epoch 453/1000 | Loss: 0.5094
Epoch 454/1000 | Loss: 0.5093
Epoch 455/1000 | Loss: 0.5092
Epoch 456/1000 | Loss: 0.5092
Epoch 457/1000 | Loss: 0.5091
Epoch 458/1000 | Loss: 0.5090
Epoch 459/1000 | Loss: 0.5089
Epoch 460/1000 | Loss: 0.5088
Epoch 461/1000 | Loss: 0.5087
Epoch 462/1000 | Loss: 0.5086
Epoch 463/1000 | Loss: 0.5085
Epoch 464/1000 | Loss: 0.5084
Epoch 465/1000 | Loss: 0.5083
Epoch 466/1000 | Loss: 0.5082
Epoch 467/1000 | Loss: 0.5081
Epoch 468/1000 | Loss: 0.5080
Epoch 469/1000 | Loss: 0.5080
Epoch 470/1000 | Loss: 0.5079
Epoch 471/1000 | Loss: 0.5078
Epoch 472/1000 | Loss: 0.5077
Epoch 473/1000 | Loss: 0.5076
Epoch 474/1000 | Loss: 0.5075
Epoch 475/1000 | Loss: 0.5074
Epoch 476/1000 | Loss: 0.5073
Epoch 477/1000 | Loss: 0.5072
Epoch 478/1000 | Loss: 0.5072
Epoch 479/1000 | Loss: 0.5071
Epoch 480/1000 | Loss: 0.5070
Epoch 481/1000 | Loss: 0.5069
Epoch 482/1000 | Loss: 0.5068
Epoch 483/1000 | Loss: 0.5067
Epoch 484/1000 | Loss: 0.5066
Epoch 485/1000 | Loss: 0.5066
Epoch 486/1000 | Loss: 0.5065
Epoch 487/1000 | Loss: 0.5064
Epoch 488/1000 | Loss: 0.5063
Epoch 489/1000 | Loss: 0.5062
Epoch 490/1000 | Loss: 0.5061
Epoch 491/1000 | Loss: 0.5060
Epoch 492/1000 | Loss: 0.5060
Epoch 493/1000 | Loss: 0.5059
Epoch 494/1000 | Loss: 0.5058
Epoch 495/1000 | Loss: 0.5057
Epoch 496/1000 | Loss: 0.5056
Epoch 497/1000 | Loss: 0.5055
Epoch 498/1000 | Loss: 0.5055
Epoch 499/1000 | Loss: 0.5054
Epoch 500/1000 | Loss: 0.5053
Epoch 501/1000 | Loss: 0.5052
Epoch 502/1000 | Loss: 0.5051
Epoch 503/1000 | Loss: 0.5051
Epoch 504/1000 | Loss: 0.5050
Epoch 505/1000 | Loss: 0.5049
Epoch 506/1000 | Loss: 0.5048
Epoch 507/1000 | Loss: 0.5047
Epoch 508/1000 | Loss: 0.5047
Epoch 509/1000 | Loss: 0.5046
Epoch 510/1000 | Loss: 0.5045
Epoch 511/1000 | Loss: 0.5044
Epoch 512/1000 | Loss: 0.5043
Epoch 513/1000 | Loss: 0.5043
Epoch 514/1000 | Loss: 0.5042
Epoch 515/1000 | Loss: 0.5041
Epoch 516/1000 | Loss: 0.5040
Epoch 517/1000 | Loss: 0.5040
Epoch 518/1000 | Loss: 0.5039
Epoch 519/1000 | Loss: 0.5038
Epoch 520/1000 | Loss: 0.5037
Epoch 521/1000 | Loss: 0.5037
Epoch 522/1000 | Loss: 0.5036
Epoch 523/1000 | Loss: 0.5035
Epoch 524/1000 | Loss: 0.5034
Epoch 525/1000 | Loss: 0.5034
Epoch 526/1000 | Loss: 0.5033
Epoch 527/1000 | Loss: 0.5032
Epoch 528/1000 | Loss: 0.5031
Epoch 529/1000 | Loss: 0.5031
Epoch 530/1000 | Loss: 0.5030
Epoch 531/1000 | Loss: 0.5029
Epoch 532/1000 | Loss: 0.5028
Epoch 533/1000 | Loss: 0.5028
Epoch 534/1000 | Loss: 0.5027
Epoch 535/1000 | Loss: 0.5026
Epoch 536/1000 | Loss: 0.5025
Epoch 537/1000 | Loss: 0.5025
Epoch 538/1000 | Loss: 0.5024
Epoch 539/1000 | Loss: 0.5023
Epoch 540/1000 | Loss: 0.5023
Epoch 541/1000 | Loss: 0.5022
Epoch 542/1000 | Loss: 0.5021
Epoch 543/1000 | Loss: 0.5020
Epoch 544/1000 | Loss: 0.5020
Epoch 545/1000 | Loss: 0.5019
Epoch 546/1000 | Loss: 0.5018
Epoch 547/1000 | Loss: 0.5018
Epoch 548/1000 | Loss: 0.5017
Epoch 549/1000 | Loss: 0.5016
Epoch 550/1000 | Loss: 0.5016
Epoch 551/1000 | Loss: 0.5015
Epoch 552/1000 | Loss: 0.5014
Epoch 553/1000 | Loss: 0.5013
Epoch 554/1000 | Loss: 0.5013
Epoch 555/1000 | Loss: 0.5012
Epoch 556/1000 | Loss: 0.5011
Epoch 557/1000 | Loss: 0.5011
Epoch 558/1000 | Loss: 0.5010
Epoch 559/1000 | Loss: 0.5009
Epoch 560/1000 | Loss: 0.5009
Epoch 561/1000 | Loss: 0.5008
Epoch 562/1000 | Loss: 0.5007
Epoch 563/1000 | Loss: 0.5007
Epoch 564/1000 | Loss: 0.5006
Epoch 565/1000 | Loss: 0.5005
Epoch 566/1000 | Loss: 0.5005
Epoch 567/1000 | Loss: 0.5004
Epoch 568/1000 | Loss: 0.5003
Epoch 569/1000 | Loss: 0.5003
Epoch 570/1000 | Loss: 0.5002
Epoch 571/1000 | Loss: 0.5002
Epoch 572/1000 | Loss: 0.5001
Epoch 573/1000 | Loss: 0.5000
Epoch 574/1000 | Loss: 0.5000
Epoch 575/1000 | Loss: 0.4999
Epoch 576/1000 | Loss: 0.4998
Epoch 577/1000 | Loss: 0.4998
Epoch 578/1000 | Loss: 0.4997
Epoch 579/1000 | Loss: 0.4996
Epoch 580/1000 | Loss: 0.4996
Epoch 581/1000 | Loss: 0.4995
Epoch 582/1000 | Loss: 0.4995
Epoch 583/1000 | Loss: 0.4994
Epoch 584/1000 | Loss: 0.4993
Epoch 585/1000 | Loss: 0.4993
Epoch 586/1000 | Loss: 0.4992
Epoch 587/1000 | Loss: 0.4991
Epoch 588/1000 | Loss: 0.4991
Epoch 589/1000 | Loss: 0.4990
Epoch 590/1000 | Loss: 0.4990
Epoch 591/1000 | Loss: 0.4989
Epoch 592/1000 | Loss: 0.4988
Epoch 593/1000 | Loss: 0.4988
Epoch 594/1000 | Loss: 0.4987
Epoch 595/1000 | Loss: 0.4987
Epoch 596/1000 | Loss: 0.4986
Epoch 597/1000 | Loss: 0.4985
Epoch 598/1000 | Loss: 0.4985
Epoch 599/1000 | Loss: 0.4984
Epoch 600/1000 | Loss: 0.4984
Epoch 601/1000 | Loss: 0.4983
Epoch 602/1000 | Loss: 0.4982
Epoch 603/1000 | Loss: 0.4982
Epoch 604/1000 | Loss: 0.4981
Epoch 605/1000 | Loss: 0.4981
Epoch 606/1000 | Loss: 0.4980
Epoch 607/1000 | Loss: 0.4979
Epoch 608/1000 | Loss: 0.4979
Epoch 609/1000 | Loss: 0.4978
Epoch 610/1000 | Loss: 0.4978
Epoch 611/1000 | Loss: 0.4977
Epoch 612/1000 | Loss: 0.4977
Epoch 613/1000 | Loss: 0.4976
Epoch 614/1000 | Loss: 0.4975
Epoch 615/1000 | Loss: 0.4975
Epoch 616/1000 | Loss: 0.4974
Epoch 617/1000 | Loss: 0.4974
Epoch 618/1000 | Loss: 0.4973
Epoch 619/1000 | Loss: 0.4973
Epoch 620/1000 | Loss: 0.4972
Epoch 621/1000 | Loss: 0.4971
Epoch 622/1000 | Loss: 0.4971
Epoch 623/1000 | Loss: 0.4970
Epoch 624/1000 | Loss: 0.4970
Epoch 625/1000 | Loss: 0.4969
Epoch 626/1000 | Loss: 0.4969
Epoch 627/1000 | Loss: 0.4968
Epoch 628/1000 | Loss: 0.4968
Epoch 629/1000 | Loss: 0.4967
Epoch 630/1000 | Loss: 0.4967
Epoch 631/1000 | Loss: 0.4966
Epoch 632/1000 | Loss: 0.4965
Epoch 633/1000 | Loss: 0.4965
Epoch 634/1000 | Loss: 0.4964
Epoch 635/1000 | Loss: 0.4964
Epoch 636/1000 | Loss: 0.4963
Epoch 637/1000 | Loss: 0.4963
Epoch 638/1000 | Loss: 0.4962
Epoch 639/1000 | Loss: 0.4962
Epoch 640/1000 | Loss: 0.4961
Epoch 641/1000 | Loss: 0.4961
Epoch 642/1000 | Loss: 0.4960
Epoch 643/1000 | Loss: 0.4960
Epoch 644/1000 | Loss: 0.4959
Epoch 645/1000 | Loss: 0.4959
Epoch 646/1000 | Loss: 0.4958
Epoch 647/1000 | Loss: 0.4958
Epoch 648/1000 | Loss: 0.4957
Epoch 649/1000 | Loss: 0.4957
Epoch 650/1000 | Loss: 0.4956
Epoch 651/1000 | Loss: 0.4955
Epoch 652/1000 | Loss: 0.4955
Epoch 653/1000 | Loss: 0.4954
Epoch 654/1000 | Loss: 0.4954
Epoch 655/1000 | Loss: 0.4953
Epoch 656/1000 | Loss: 0.4953
Epoch 657/1000 | Loss: 0.4952
Epoch 658/1000 | Loss: 0.4952
Epoch 659/1000 | Loss: 0.4951
Epoch 660/1000 | Loss: 0.4951
Epoch 661/1000 | Loss: 0.4950
Epoch 662/1000 | Loss: 0.4950
Epoch 663/1000 | Loss: 0.4949
Epoch 664/1000 | Loss: 0.4949
Epoch 665/1000 | Loss: 0.4948
Epoch 666/1000 | Loss: 0.4948
Epoch 667/1000 | Loss: 0.4947
Epoch 668/1000 | Loss: 0.4947
Epoch 669/1000 | Loss: 0.4947
Epoch 670/1000 | Loss: 0.4946
Epoch 671/1000 | Loss: 0.4946
Epoch 672/1000 | Loss: 0.4945
Epoch 673/1000 | Loss: 0.4945
Epoch 674/1000 | Loss: 0.4944
Epoch 675/1000 | Loss: 0.4944
Epoch 676/1000 | Loss: 0.4943
Epoch 677/1000 | Loss: 0.4943
Epoch 678/1000 | Loss: 0.4942
Epoch 679/1000 | Loss: 0.4942
Epoch 680/1000 | Loss: 0.4941
Epoch 681/1000 | Loss: 0.4941
Epoch 682/1000 | Loss: 0.4940
Epoch 683/1000 | Loss: 0.4940
Epoch 684/1000 | Loss: 0.4939
Epoch 685/1000 | Loss: 0.4939
Epoch 686/1000 | Loss: 0.4938
Epoch 687/1000 | Loss: 0.4938
Epoch 688/1000 | Loss: 0.4938
Epoch 689/1000 | Loss: 0.4937
Epoch 690/1000 | Loss: 0.4937
Epoch 691/1000 | Loss: 0.4936
Epoch 692/1000 | Loss: 0.4936
Epoch 693/1000 | Loss: 0.4935
Epoch 694/1000 | Loss: 0.4935
Epoch 695/1000 | Loss: 0.4934
Epoch 696/1000 | Loss: 0.4934
Epoch 697/1000 | Loss: 0.4933
Epoch 698/1000 | Loss: 0.4933
Epoch 699/1000 | Loss: 0.4933
Epoch 700/1000 | Loss: 0.4932
Epoch 701/1000 | Loss: 0.4932
Epoch 702/1000 | Loss: 0.4931
Epoch 703/1000 | Loss: 0.4931
Epoch 704/1000 | Loss: 0.4930
Epoch 705/1000 | Loss: 0.4930
Epoch 706/1000 | Loss: 0.4929
Epoch 707/1000 | Loss: 0.4929
Epoch 708/1000 | Loss: 0.4929
Epoch 709/1000 | Loss: 0.4928
Epoch 710/1000 | Loss: 0.4928
Epoch 711/1000 | Loss: 0.4927
Epoch 712/1000 | Loss: 0.4927
Epoch 713/1000 | Loss: 0.4926
Epoch 714/1000 | Loss: 0.4926
Epoch 715/1000 | Loss: 0.4926
Epoch 716/1000 | Loss: 0.4925
Epoch 717/1000 | Loss: 0.4925
Epoch 718/1000 | Loss: 0.4924
Epoch 719/1000 | Loss: 0.4924
Epoch 720/1000 | Loss: 0.4923
Epoch 721/1000 | Loss: 0.4923
Epoch 722/1000 | Loss: 0.4923
Epoch 723/1000 | Loss: 0.4922
Epoch 724/1000 | Loss: 0.4922
Epoch 725/1000 | Loss: 0.4921
Epoch 726/1000 | Loss: 0.4921
Epoch 727/1000 | Loss: 0.4921
Epoch 728/1000 | Loss: 0.4920
Epoch 729/1000 | Loss: 0.4920
Epoch 730/1000 | Loss: 0.4919
Epoch 731/1000 | Loss: 0.4919
Epoch 732/1000 | Loss: 0.4918
Epoch 733/1000 | Loss: 0.4918
Epoch 734/1000 | Loss: 0.4918
Epoch 735/1000 | Loss: 0.4917
Epoch 736/1000 | Loss: 0.4917
Epoch 737/1000 | Loss: 0.4916
Epoch 738/1000 | Loss: 0.4916
Epoch 739/1000 | Loss: 0.4916
Epoch 740/1000 | Loss: 0.4915
Epoch 741/1000 | Loss: 0.4915
Epoch 742/1000 | Loss: 0.4914
Epoch 743/1000 | Loss: 0.4914
Epoch 744/1000 | Loss: 0.4914
Epoch 745/1000 | Loss: 0.4913
Epoch 746/1000 | Loss: 0.4913
Epoch 747/1000 | Loss: 0.4912
Epoch 748/1000 | Loss: 0.4912
Epoch 749/1000 | Loss: 0.4912
Epoch 750/1000 | Loss: 0.4911
Epoch 751/1000 | Loss: 0.4911
Epoch 752/1000 | Loss: 0.4911
Epoch 753/1000 | Loss: 0.4910
Epoch 754/1000 | Loss: 0.4910
Epoch 755/1000 | Loss: 0.4909
Epoch 756/1000 | Loss: 0.4909
Epoch 757/1000 | Loss: 0.4909
Epoch 758/1000 | Loss: 0.4908
Epoch 759/1000 | Loss: 0.4908
Epoch 760/1000 | Loss: 0.4907
Epoch 761/1000 | Loss: 0.4907
Epoch 762/1000 | Loss: 0.4907
Epoch 763/1000 | Loss: 0.4906
Epoch 764/1000 | Loss: 0.4906
Epoch 765/1000 | Loss: 0.4906
Epoch 766/1000 | Loss: 0.4905
Epoch 767/1000 | Loss: 0.4905
Epoch 768/1000 | Loss: 0.4904
Epoch 769/1000 | Loss: 0.4904
Epoch 770/1000 | Loss: 0.4904
Epoch 771/1000 | Loss: 0.4903
Epoch 772/1000 | Loss: 0.4903
Epoch 773/1000 | Loss: 0.4903
Epoch 774/1000 | Loss: 0.4902
Epoch 775/1000 | Loss: 0.4902
Epoch 776/1000 | Loss: 0.4902
Epoch 777/1000 | Loss: 0.4901
Epoch 778/1000 | Loss: 0.4901
Epoch 779/1000 | Loss: 0.4900
Epoch 780/1000 | Loss: 0.4900
Epoch 781/1000 | Loss: 0.4900
Epoch 782/1000 | Loss: 0.4899
Epoch 783/1000 | Loss: 0.4899
Epoch 784/1000 | Loss: 0.4899
Epoch 785/1000 | Loss: 0.4898
Epoch 786/1000 | Loss: 0.4898
Epoch 787/1000 | Loss: 0.4898
Epoch 788/1000 | Loss: 0.4897
Epoch 789/1000 | Loss: 0.4897
Epoch 790/1000 | Loss: 0.4897
Epoch 791/1000 | Loss: 0.4896
Epoch 792/1000 | Loss: 0.4896
Epoch 793/1000 | Loss: 0.4895
Epoch 794/1000 | Loss: 0.4895
Epoch 795/1000 | Loss: 0.4895
Epoch 796/1000 | Loss: 0.4894
Epoch 797/1000 | Loss: 0.4894
Epoch 798/1000 | Loss: 0.4894
Epoch 799/1000 | Loss: 0.4893
Epoch 800/1000 | Loss: 0.4893
Epoch 801/1000 | Loss: 0.4893
Epoch 802/1000 | Loss: 0.4892
Epoch 803/1000 | Loss: 0.4892
Epoch 804/1000 | Loss: 0.4892
Epoch 805/1000 | Loss: 0.4891
Epoch 806/1000 | Loss: 0.4891
Epoch 807/1000 | Loss: 0.4891
Epoch 808/1000 | Loss: 0.4890
Epoch 809/1000 | Loss: 0.4890
Epoch 810/1000 | Loss: 0.4890
Epoch 811/1000 | Loss: 0.4889
Epoch 812/1000 | Loss: 0.4889
Epoch 813/1000 | Loss: 0.4889
Epoch 814/1000 | Loss: 0.4888
Epoch 815/1000 | Loss: 0.4888
Epoch 816/1000 | Loss: 0.4888
Epoch 817/1000 | Loss: 0.4887
Epoch 818/1000 | Loss: 0.4887
Epoch 819/1000 | Loss: 0.4887
Epoch 820/1000 | Loss: 0.4886
Epoch 821/1000 | Loss: 0.4886
Epoch 822/1000 | Loss: 0.4886
Epoch 823/1000 | Loss: 0.4885
Epoch 824/1000 | Loss: 0.4885
Epoch 825/1000 | Loss: 0.4885
Epoch 826/1000 | Loss: 0.4884
Epoch 827/1000 | Loss: 0.4884
Epoch 828/1000 | Loss: 0.4884
Epoch 829/1000 | Loss: 0.4884
Epoch 830/1000 | Loss: 0.4883
Epoch 831/1000 | Loss: 0.4883
Epoch 832/1000 | Loss: 0.4883
Epoch 833/1000 | Loss: 0.4882
Epoch 834/1000 | Loss: 0.4882
Epoch 835/1000 | Loss: 0.4882
Epoch 836/1000 | Loss: 0.4881
Epoch 837/1000 | Loss: 0.4881
Epoch 838/1000 | Loss: 0.4881
Epoch 839/1000 | Loss: 0.4880
Epoch 840/1000 | Loss: 0.4880
Epoch 841/1000 | Loss: 0.4880
Epoch 842/1000 | Loss: 0.4879
Epoch 843/1000 | Loss: 0.4879
Epoch 844/1000 | Loss: 0.4879
Epoch 845/1000 | Loss: 0.4879
Epoch 846/1000 | Loss: 0.4878
Epoch 847/1000 | Loss: 0.4878
Epoch 848/1000 | Loss: 0.4878
Epoch 849/1000 | Loss: 0.4877
Epoch 850/1000 | Loss: 0.4877
Epoch 851/1000 | Loss: 0.4877
Epoch 852/1000 | Loss: 0.4876
Epoch 853/1000 | Loss: 0.4876
Epoch 854/1000 | Loss: 0.4876
Epoch 855/1000 | Loss: 0.4876
Epoch 856/1000 | Loss: 0.4875
Epoch 857/1000 | Loss: 0.4875
Epoch 858/1000 | Loss: 0.4875
Epoch 859/1000 | Loss: 0.4874
Epoch 860/1000 | Loss: 0.4874
Epoch 861/1000 | Loss: 0.4874
Epoch 862/1000 | Loss: 0.4873
Epoch 863/1000 | Loss: 0.4873
Epoch 864/1000 | Loss: 0.4873
Epoch 865/1000 | Loss: 0.4873
Epoch 866/1000 | Loss: 0.4872
Epoch 867/1000 | Loss: 0.4872
Epoch 868/1000 | Loss: 0.4872
Epoch 869/1000 | Loss: 0.4871
Epoch 870/1000 | Loss: 0.4871
Epoch 871/1000 | Loss: 0.4871
Epoch 872/1000 | Loss: 0.4871
Epoch 873/1000 | Loss: 0.4870
Epoch 874/1000 | Loss: 0.4870
Epoch 875/1000 | Loss: 0.4870
Epoch 876/1000 | Loss: 0.4869
Epoch 877/1000 | Loss: 0.4869
Epoch 878/1000 | Loss: 0.4869
Epoch 879/1000 | Loss: 0.4869
Epoch 880/1000 | Loss: 0.4868
Epoch 881/1000 | Loss: 0.4868
Epoch 882/1000 | Loss: 0.4868
Epoch 883/1000 | Loss: 0.4867
Epoch 884/1000 | Loss: 0.4867
Epoch 885/1000 | Loss: 0.4867
Epoch 886/1000 | Loss: 0.4867
Epoch 887/1000 | Loss: 0.4866
Epoch 888/1000 | Loss: 0.4866
Epoch 889/1000 | Loss: 0.4866
Epoch 890/1000 | Loss: 0.4866
Epoch 891/1000 | Loss: 0.4865
Epoch 892/1000 | Loss: 0.4865
Epoch 893/1000 | Loss: 0.4865
Epoch 894/1000 | Loss: 0.4864
Epoch 895/1000 | Loss: 0.4864
Epoch 896/1000 | Loss: 0.4864
Epoch 897/1000 | Loss: 0.4864
Epoch 898/1000 | Loss: 0.4863
Epoch 899/1000 | Loss: 0.4863
Epoch 900/1000 | Loss: 0.4863
Epoch 901/1000 | Loss: 0.4863
Epoch 902/1000 | Loss: 0.4862
Epoch 903/1000 | Loss: 0.4862
Epoch 904/1000 | Loss: 0.4862
Epoch 905/1000 | Loss: 0.4861
Epoch 906/1000 | Loss: 0.4861
Epoch 907/1000 | Loss: 0.4861
Epoch 908/1000 | Loss: 0.4861
Epoch 909/1000 | Loss: 0.4860
Epoch 910/1000 | Loss: 0.4860
Epoch 911/1000 | Loss: 0.4860
Epoch 912/1000 | Loss: 0.4860
Epoch 913/1000 | Loss: 0.4859
Epoch 914/1000 | Loss: 0.4859
Epoch 915/1000 | Loss: 0.4859
Epoch 916/1000 | Loss: 0.4859
Epoch 917/1000 | Loss: 0.4858
Epoch 918/1000 | Loss: 0.4858
Epoch 919/1000 | Loss: 0.4858
Epoch 920/1000 | Loss: 0.4858
Epoch 921/1000 | Loss: 0.4857
Epoch 922/1000 | Loss: 0.4857
Epoch 923/1000 | Loss: 0.4857
Epoch 924/1000 | Loss: 0.4857
Epoch 925/1000 | Loss: 0.4856
Epoch 926/1000 | Loss: 0.4856
Epoch 927/1000 | Loss: 0.4856
Epoch 928/1000 | Loss: 0.4856
Epoch 929/1000 | Loss: 0.4855
Epoch 930/1000 | Loss: 0.4855
Epoch 931/1000 | Loss: 0.4855
Epoch 932/1000 | Loss: 0.4855
Epoch 933/1000 | Loss: 0.4854
Epoch 934/1000 | Loss: 0.4854
Epoch 935/1000 | Loss: 0.4854
Epoch 936/1000 | Loss: 0.4854
Epoch 937/1000 | Loss: 0.4853
Epoch 938/1000 | Loss: 0.4853
Epoch 939/1000 | Loss: 0.4853
Epoch 940/1000 | Loss: 0.4853
Epoch 941/1000 | Loss: 0.4852
Epoch 942/1000 | Loss: 0.4852
Epoch 943/1000 | Loss: 0.4852
Epoch 944/1000 | Loss: 0.4852
Epoch 945/1000 | Loss: 0.4851
Epoch 946/1000 | Loss: 0.4851
Epoch 947/1000 | Loss: 0.4851
Epoch 948/1000 | Loss: 0.4851
Epoch 949/1000 | Loss: 0.4850
Epoch 950/1000 | Loss: 0.4850
Epoch 951/1000 | Loss: 0.4850
Epoch 952/1000 | Loss: 0.4850
Epoch 953/1000 | Loss: 0.4850
Epoch 954/1000 | Loss: 0.4849
Epoch 955/1000 | Loss: 0.4849
Epoch 956/1000 | Loss: 0.4849
Epoch 957/1000 | Loss: 0.4849
Epoch 958/1000 | Loss: 0.4848
Epoch 959/1000 | Loss: 0.4848
Epoch 960/1000 | Loss: 0.4848
Epoch 961/1000 | Loss: 0.4848
Epoch 962/1000 | Loss: 0.4847
Epoch 963/1000 | Loss: 0.4847
Epoch 964/1000 | Loss: 0.4847
Epoch 965/1000 | Loss: 0.4847
Epoch 966/1000 | Loss: 0.4846
Epoch 967/1000 | Loss: 0.4846
Epoch 968/1000 | Loss: 0.4846
Epoch 969/1000 | Loss: 0.4846
Epoch 970/1000 | Loss: 0.4846
Epoch 971/1000 | Loss: 0.4845
Epoch 972/1000 | Loss: 0.4845
Epoch 973/1000 | Loss: 0.4845
Epoch 974/1000 | Loss: 0.4845
Epoch 975/1000 | Loss: 0.4844
Epoch 976/1000 | Loss: 0.4844
Epoch 977/1000 | Loss: 0.4844
Epoch 978/1000 | Loss: 0.4844
Epoch 979/1000 | Loss: 0.4844
Epoch 980/1000 | Loss: 0.4843
Epoch 981/1000 | Loss: 0.4843
Epoch 982/1000 | Loss: 0.4843
Epoch 983/1000 | Loss: 0.4843
Epoch 984/1000 | Loss: 0.4842
Epoch 985/1000 | Loss: 0.4842
Epoch 986/1000 | Loss: 0.4842
Epoch 987/1000 | Loss: 0.4842
Epoch 988/1000 | Loss: 0.4842
Epoch 989/1000 | Loss: 0.4841
Epoch 990/1000 | Loss: 0.4841
Epoch 991/1000 | Loss: 0.4841
Epoch 992/1000 | Loss: 0.4841
Epoch 993/1000 | Loss: 0.4841
Epoch 994/1000 | Loss: 0.4840
Epoch 995/1000 | Loss: 0.4840
Epoch 996/1000 | Loss: 0.4840
Epoch 997/1000 | Loss: 0.4840
Epoch 998/1000 | Loss: 0.4839
Epoch 999/1000 | Loss: 0.4839
Epoch 1000/1000 | Loss: 0.4839
Prediction (after training) tensor([-0.2941, 0.4874, 0.1803, -0.2929, 0.0000, 0.0015, -0.5312, -0.0333]) : 0.4202234447002411
accuracy : 76.54808959156784
| [
"[email protected]"
] | |
a6be4bc05b34c3818a461dcf867dc8f31a9607b8 | 2aace9bb170363e181eb7520e93def25f38dbe5c | /build/idea-sandbox/system/python_stubs/cache/994b47397c595c2116d95bdf9b1e3e5465645d7d44dbe497e47183b32b528ed6/win32gui.py | 070a2a5a8acf656f7baeddd3573c209f4ae67612 | [] | no_license | qkpqkp/PlagCheck | 13cb66fd2b2caa2451690bb72a2634bdaa07f1e6 | d229904674a5a6e46738179c7494488ca930045e | refs/heads/master | 2023-05-28T15:06:08.723143 | 2021-06-09T05:36:34 | 2021-06-09T05:36:34 | 375,235,940 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 25,613 | py | # encoding: utf-8
# module win32gui
# from C:\Users\Doly\Anaconda3\lib\site-packages\win32\win32gui.pyd
# by generator 1.147
# no doc
# imports
from pywintypes import error
# Variables with simple values
CLR_NONE = -1
dllhandle = 1541144576
ILC_COLOR = 0
ILC_COLOR16 = 16
ILC_COLOR24 = 24
ILC_COLOR32 = 32
ILC_COLOR4 = 4
ILC_COLOR8 = 8
ILC_COLORDDB = 254
ILC_MASK = 1
ILD_BLEND = 4
ILD_BLEND25 = 2
ILD_BLEND50 = 4
ILD_FOCUS = 2
ILD_MASK = 16
ILD_NORMAL = 0
ILD_SELECTED = 4
ILD_TRANSPARENT = 1
IMAGE_BITMAP = 0
IMAGE_CURSOR = 2
IMAGE_ICON = 1
LR_CREATEDIBSECTION = 8192
LR_DEFAULTCOLOR = 0
LR_DEFAULTSIZE = 64
LR_LOADFROMFILE = 16
LR_LOADMAP3DCOLORS = 4096
LR_LOADTRANSPARENT = 32
LR_MONOCHROME = 1
LR_SHARED = 32768
LR_VGACOLOR = 128
NIF_ICON = 2
NIF_INFO = 16
NIF_MESSAGE = 1
NIF_STATE = 8
NIF_TIP = 4
NIIF_ERROR = 3
NIIF_ICON_MASK = 15
NIIF_INFO = 1
NIIF_NONE = 0
NIIF_NOSOUND = 16
NIIF_WARNING = 2
NIM_ADD = 0
NIM_DELETE = 2
NIM_MODIFY = 1
NIM_SETVERSION = 4
TPM_BOTTOMALIGN = 32
TPM_CENTERALIGN = 4
TPM_LEFTALIGN = 0
TPM_LEFTBUTTON = 0
TPM_NONOTIFY = 128
TPM_RETURNCMD = 256
TPM_RIGHTALIGN = 8
TPM_RIGHTBUTTON = 2
TPM_TOPALIGN = 0
TPM_VCENTERALIGN = 16
UNICODE = True
# functions
def AbortPath(*args, **kwargs): # real signature unknown
pass
def AlphaBlend(*args, **kwargs): # real signature unknown
pass
def AngleArc(*args, **kwargs): # real signature unknown
pass
def AnimateWindow(*args, **kwargs): # real signature unknown
pass
def AppendMenu(*args, **kwargs): # real signature unknown
pass
def Arc(*args, **kwargs): # real signature unknown
pass
def ArcTo(*args, **kwargs): # real signature unknown
pass
def BeginPaint(*args, **kwargs): # real signature unknown
pass
def BeginPath(*args, **kwargs): # real signature unknown
pass
def BitBlt(*args, **kwargs): # real signature unknown
pass
def BringWindowToTop(*args, **kwargs): # real signature unknown
pass
def CallWindowProc(*args, **kwargs): # real signature unknown
pass
def CheckMenuItem(*args, **kwargs): # real signature unknown
pass
def CheckMenuRadioItem(*args, **kwargs): # real signature unknown
pass
def ChildWindowFromPoint(*args, **kwargs): # real signature unknown
pass
def ChildWindowFromPointEx(*args, **kwargs): # real signature unknown
pass
def Chord(*args, **kwargs): # real signature unknown
pass
def ClientToScreen(*args, **kwargs): # real signature unknown
pass
def CloseFigure(*args, **kwargs): # real signature unknown
pass
def CloseWindow(*args, **kwargs): # real signature unknown
pass
def CombineRgn(*args, **kwargs): # real signature unknown
pass
def CombineTransform(*args, **kwargs): # real signature unknown
pass
def CommDlgExtendedError(*args, **kwargs): # real signature unknown
pass
def CopyIcon(*args, **kwargs): # real signature unknown
pass
def CreateAcceleratorTable(*args, **kwargs): # real signature unknown
pass
def CreateBitmap(*args, **kwargs): # real signature unknown
pass
def CreateBrushIndirect(*args, **kwargs): # real signature unknown
pass
def CreateCaret(*args, **kwargs): # real signature unknown
pass
def CreateCompatibleBitmap(*args, **kwargs): # real signature unknown
pass
def CreateCompatibleDC(*args, **kwargs): # real signature unknown
pass
def CreateDC(*args, **kwargs): # real signature unknown
pass
def CreateDialogIndirect(*args, **kwargs): # real signature unknown
pass
def CreateDialogIndirectParam(*args, **kwargs): # real signature unknown
pass
def CreateEllipticRgnIndirect(*args, **kwargs): # real signature unknown
pass
def CreateFontIndirect(*args, **kwargs): # real signature unknown
pass
def CreateHatchBrush(*args, **kwargs): # real signature unknown
pass
def CreateIconFromResource(*args, **kwargs): # real signature unknown
pass
def CreateIconIndirect(*args, **kwargs): # real signature unknown
pass
def CreateMenu(*args, **kwargs): # real signature unknown
pass
def CreatePatternBrush(*args, **kwargs): # real signature unknown
pass
def CreatePen(*args, **kwargs): # real signature unknown
pass
def CreatePolygonRgn(*args, **kwargs): # real signature unknown
pass
def CreatePopupMenu(*args, **kwargs): # real signature unknown
pass
def CreateRectRgnIndirect(*args, **kwargs): # real signature unknown
pass
def CreateRoundRectRgn(*args, **kwargs): # real signature unknown
pass
def CreateSolidBrush(*args, **kwargs): # real signature unknown
pass
def CreateWindow(*args, **kwargs): # real signature unknown
pass
def CreateWindowEx(*args, **kwargs): # real signature unknown
pass
def DefWindowProc(*args, **kwargs): # real signature unknown
pass
def DeleteDC(*args, **kwargs): # real signature unknown
pass
def DeleteMenu(*args, **kwargs): # real signature unknown
pass
def DeleteObject(*args, **kwargs): # real signature unknown
pass
def DestroyAcceleratorTable(*args, **kwargs): # real signature unknown
pass
def DestroyCaret(*args, **kwargs): # real signature unknown
pass
def DestroyIcon(*args, **kwargs): # real signature unknown
pass
def DestroyMenu(*args, **kwargs): # real signature unknown
pass
def DestroyWindow(*args, **kwargs): # real signature unknown
pass
def DialogBox(*args, **kwargs): # real signature unknown
pass
def DialogBoxIndirect(*args, **kwargs): # real signature unknown
pass
def DialogBoxIndirectParam(*args, **kwargs): # real signature unknown
pass
def DialogBoxParam(*args, **kwargs): # real signature unknown
pass
def DispatchMessage(*args, **kwargs): # real signature unknown
pass
def DragAcceptFiles(*args, **kwargs): # real signature unknown
pass
def DragDetect(*args, **kwargs): # real signature unknown
pass
def DrawAnimatedRects(*args, **kwargs): # real signature unknown
pass
def DrawEdge(*args, **kwargs): # real signature unknown
pass
def DrawFocusRect(*args, **kwargs): # real signature unknown
pass
def DrawIcon(*args, **kwargs): # real signature unknown
pass
def DrawIconEx(*args, **kwargs): # real signature unknown
pass
def DrawMenuBar(*args, **kwargs): # real signature unknown
pass
def DrawText(*args, **kwargs): # real signature unknown
pass
def DrawTextW(*args, **kwargs): # real signature unknown
pass
def Edit_GetLine(*args, **kwargs): # real signature unknown
pass
def Ellipse(*args, **kwargs): # real signature unknown
pass
def EnableMenuItem(*args, **kwargs): # real signature unknown
pass
def EnableWindow(*args, **kwargs): # real signature unknown
pass
def EndDialog(*args, **kwargs): # real signature unknown
pass
def EndPaint(*args, **kwargs): # real signature unknown
pass
def EndPath(*args, **kwargs): # real signature unknown
pass
def EnumChildWindows(*args, **kwargs): # real signature unknown
pass
def EnumFontFamilies(*args, **kwargs): # real signature unknown
pass
def EnumPropsEx(*args, **kwargs): # real signature unknown
pass
def EnumThreadWindows(*args, **kwargs): # real signature unknown
pass
def EnumWindows(*args, **kwargs): # real signature unknown
pass
def EqualRgn(*args, **kwargs): # real signature unknown
pass
def ExtCreatePen(*args, **kwargs): # real signature unknown
pass
def ExtFloodFill(*args, **kwargs): # real signature unknown
pass
def ExtractIcon(*args, **kwargs): # real signature unknown
pass
def ExtractIconEx(*args, **kwargs): # real signature unknown
pass
def ExtTextOut(*args, **kwargs): # real signature unknown
pass
def FillPath(*args, **kwargs): # real signature unknown
pass
def FillRect(*args, **kwargs): # real signature unknown
pass
def FillRgn(*args, **kwargs): # real signature unknown
pass
def FindWindow(*args, **kwargs): # real signature unknown
pass
def FindWindowEx(*args, **kwargs): # real signature unknown
pass
def FlashWindow(*args, **kwargs): # real signature unknown
pass
def FlashWindowEx(*args, **kwargs): # real signature unknown
pass
def FlattenPath(*args, **kwargs): # real signature unknown
pass
def FrameRect(*args, **kwargs): # real signature unknown
pass
def FrameRgn(*args, **kwargs): # real signature unknown
pass
def GetActiveWindow(*args, **kwargs): # real signature unknown
pass
def GetArcDirection(*args, **kwargs): # real signature unknown
pass
def GetBkColor(*args, **kwargs): # real signature unknown
pass
def GetBkMode(*args, **kwargs): # real signature unknown
pass
def GetCapture(*args, **kwargs): # real signature unknown
pass
def GetCaretPos(*args, **kwargs): # real signature unknown
pass
def GetClassLong(*args, **kwargs): # real signature unknown
pass
def GetClassName(*args, **kwargs): # real signature unknown
pass
def GetClientRect(*args, **kwargs): # real signature unknown
pass
def GetCurrentObject(*args, **kwargs): # real signature unknown
pass
def GetCurrentPositionEx(*args, **kwargs): # real signature unknown
pass
def GetCursor(*args, **kwargs): # real signature unknown
pass
def GetCursorInfo(*args, **kwargs): # real signature unknown
pass
def GetCursorPos(*args, **kwargs): # real signature unknown
pass
def GetDC(*args, **kwargs): # real signature unknown
pass
def GetDesktopWindow(*args, **kwargs): # real signature unknown
pass
def GetDlgCtrlID(*args, **kwargs): # real signature unknown
pass
def GetDlgItem(*args, **kwargs): # real signature unknown
pass
def GetDlgItemInt(*args, **kwargs): # real signature unknown
pass
def GetDlgItemText(*args, **kwargs): # real signature unknown
pass
def GetDoubleClickTime(*args, **kwargs): # real signature unknown
pass
def GetFocus(*args, **kwargs): # real signature unknown
pass
def GetForegroundWindow(*args, **kwargs): # real signature unknown
pass
def GetGraphicsMode(*args, **kwargs): # real signature unknown
pass
def GetIconInfo(*args, **kwargs): # real signature unknown
pass
def GetLayeredWindowAttributes(*args, **kwargs): # real signature unknown
pass
def GetLayout(*args, **kwargs): # real signature unknown
pass
def GetMapMode(*args, **kwargs): # real signature unknown
pass
def GetMenu(*args, **kwargs): # real signature unknown
pass
def GetMenuDefaultItem(*args, **kwargs): # real signature unknown
pass
def GetMenuInfo(*args, **kwargs): # real signature unknown
pass
def GetMenuItemCount(*args, **kwargs): # real signature unknown
pass
def GetMenuItemID(*args, **kwargs): # real signature unknown
pass
def GetMenuItemInfo(*args, **kwargs): # real signature unknown
pass
def GetMenuItemRect(*args, **kwargs): # real signature unknown
pass
def GetMenuState(*args, **kwargs): # real signature unknown
pass
def GetMessage(*args, **kwargs): # real signature unknown
pass
def GetMiterLimit(*args, **kwargs): # real signature unknown
pass
def GetModuleHandle(*args, **kwargs): # real signature unknown
pass
def GetNextDlgGroupItem(*args, **kwargs): # real signature unknown
pass
def GetNextDlgTabItem(*args, **kwargs): # real signature unknown
pass
def GetObject(*args, **kwargs): # real signature unknown
pass
def GetObjectType(*args, **kwargs): # real signature unknown
pass
def GetOpenFileName(*args, **kwargs): # real signature unknown
pass
def GetOpenFileNameW(*args, **kwargs): # real signature unknown
pass
def GetParent(*args, **kwargs): # real signature unknown
pass
def GetPath(*args, **kwargs): # real signature unknown
pass
def GetPixel(*args, **kwargs): # real signature unknown
pass
def GetPolyFillMode(*args, **kwargs): # real signature unknown
pass
def GetRgnBox(*args, **kwargs): # real signature unknown
pass
def GetROP2(*args, **kwargs): # real signature unknown
pass
def GetSaveFileNameW(*args, **kwargs): # real signature unknown
pass
def GetScrollInfo(*args, **kwargs): # real signature unknown
pass
def GetStockObject(*args, **kwargs): # real signature unknown
pass
def GetStretchBltMode(*args, **kwargs): # real signature unknown
pass
def GetSubMenu(*args, **kwargs): # real signature unknown
pass
def GetSysColor(*args, **kwargs): # real signature unknown
pass
def GetSysColorBrush(*args, **kwargs): # real signature unknown
pass
def GetSystemMenu(*args, **kwargs): # real signature unknown
pass
def GetTextAlign(*args, **kwargs): # real signature unknown
pass
def GetTextCharacterExtra(*args, **kwargs): # real signature unknown
pass
def GetTextColor(*args, **kwargs): # real signature unknown
pass
def GetTextExtentPoint32(*args, **kwargs): # real signature unknown
pass
def GetTextFace(*args, **kwargs): # real signature unknown
pass
def GetTextMetrics(*args, **kwargs): # real signature unknown
pass
def GetUpdateRgn(*args, **kwargs): # real signature unknown
pass
def GetViewportExtEx(*args, **kwargs): # real signature unknown
pass
def GetViewportOrgEx(*args, **kwargs): # real signature unknown
pass
def GetWindow(*args, **kwargs): # real signature unknown
pass
def GetWindowDC(*args, **kwargs): # real signature unknown
pass
def GetWindowExtEx(*args, **kwargs): # real signature unknown
pass
def GetWindowLong(*args, **kwargs): # real signature unknown
pass
def GetWindowOrgEx(*args, **kwargs): # real signature unknown
pass
def GetWindowPlacement(*args, **kwargs): # real signature unknown
pass
def GetWindowRect(*args, **kwargs): # real signature unknown
pass
def GetWindowRgn(*args, **kwargs): # real signature unknown
pass
def GetWindowText(*args, **kwargs): # real signature unknown
pass
def GetWindowTextLength(*args, **kwargs): # real signature unknown
pass
def GetWorldTransform(*args, **kwargs): # real signature unknown
pass
def GradientFill(*args, **kwargs): # real signature unknown
pass
def HideCaret(*args, **kwargs): # real signature unknown
pass
def HIWORD(*args, **kwargs): # real signature unknown
pass
def ImageList_Add(*args, **kwargs): # real signature unknown
pass
def ImageList_Create(*args, **kwargs): # real signature unknown
pass
def ImageList_Destroy(*args, **kwargs): # real signature unknown
pass
def ImageList_Draw(*args, **kwargs): # real signature unknown
pass
def ImageList_DrawEx(*args, **kwargs): # real signature unknown
pass
def ImageList_GetIcon(*args, **kwargs): # real signature unknown
pass
def ImageList_GetImageCount(*args, **kwargs): # real signature unknown
pass
def ImageList_LoadBitmap(*args, **kwargs): # real signature unknown
pass
def ImageList_LoadImage(*args, **kwargs): # real signature unknown
pass
def ImageList_Remove(*args, **kwargs): # real signature unknown
pass
def ImageList_Replace(*args, **kwargs): # real signature unknown
pass
def ImageList_ReplaceIcon(*args, **kwargs): # real signature unknown
pass
def ImageList_SetBkColor(*args, **kwargs): # real signature unknown
pass
def ImageList_SetOverlayImage(*args, **kwargs): # real signature unknown
pass
def InitCommonControls(*args, **kwargs): # real signature unknown
pass
def InitCommonControlsEx(*args, **kwargs): # real signature unknown
pass
def InsertMenu(*args, **kwargs): # real signature unknown
pass
def InsertMenuItem(*args, **kwargs): # real signature unknown
pass
def InvalidateRect(*args, **kwargs): # real signature unknown
pass
def InvalidateRgn(*args, **kwargs): # real signature unknown
pass
def InvertRect(*args, **kwargs): # real signature unknown
pass
def InvertRgn(*args, **kwargs): # real signature unknown
pass
def IsChild(*args, **kwargs): # real signature unknown
pass
def IsIconic(*args, **kwargs): # real signature unknown
pass
def IsWindow(*args, **kwargs): # real signature unknown
pass
def IsWindowEnabled(*args, **kwargs): # real signature unknown
pass
def IsWindowVisible(*args, **kwargs): # real signature unknown
pass
def LineTo(*args, **kwargs): # real signature unknown
pass
def ListView_SortItems(*args, **kwargs): # real signature unknown
pass
def ListView_SortItemsEx(*args, **kwargs): # real signature unknown
pass
def LoadCursor(*args, **kwargs): # real signature unknown
pass
def LoadIcon(*args, **kwargs): # real signature unknown
pass
def LoadImage(*args, **kwargs): # real signature unknown
pass
def LoadMenu(*args, **kwargs): # real signature unknown
pass
def LOGFONT(*args, **kwargs): # real signature unknown
pass
def LOWORD(*args, **kwargs): # real signature unknown
pass
def lpstr(*args, **kwargs): # real signature unknown
pass
def MaskBlt(*args, **kwargs): # real signature unknown
pass
def MessageBeep(*args, **kwargs): # real signature unknown
pass
def MessageBox(*args, **kwargs): # real signature unknown
pass
def ModifyMenu(*args, **kwargs): # real signature unknown
pass
def ModifyWorldTransform(*args, **kwargs): # real signature unknown
pass
def MoveToEx(*args, **kwargs): # real signature unknown
pass
def MoveWindow(*args, **kwargs): # real signature unknown
pass
def OffsetRgn(*args, **kwargs): # real signature unknown
pass
def PaintDesktop(*args, **kwargs): # real signature unknown
pass
def PaintRgn(*args, **kwargs): # real signature unknown
pass
def PatBlt(*args, **kwargs): # real signature unknown
pass
def PathToRegion(*args, **kwargs): # real signature unknown
pass
def PeekMessage(*args, **kwargs): # real signature unknown
pass
def Pie(*args, **kwargs): # real signature unknown
pass
def PlgBlt(*args, **kwargs): # real signature unknown
pass
def PolyBezier(*args, **kwargs): # real signature unknown
pass
def PolyBezierTo(*args, **kwargs): # real signature unknown
pass
def Polygon(*args, **kwargs): # real signature unknown
pass
def Polyline(*args, **kwargs): # real signature unknown
pass
def PolylineTo(*args, **kwargs): # real signature unknown
pass
def PostMessage(*args, **kwargs): # real signature unknown
pass
def PostQuitMessage(*args, **kwargs): # real signature unknown
pass
def PostThreadMessage(*args, **kwargs): # real signature unknown
pass
def PtInRect(*args, **kwargs): # real signature unknown
pass
def PtInRegion(*args, **kwargs): # real signature unknown
pass
def PumpMessages(*args, **kwargs): # real signature unknown
pass
def PumpWaitingMessages(*args, **kwargs): # real signature unknown
pass
def PyGetArraySignedLong(*args, **kwargs): # real signature unknown
pass
def PyGetBufferAddressAndLen(*args, **kwargs): # real signature unknown
pass
def PyGetMemory(*args, **kwargs): # real signature unknown
pass
def PyGetString(*args, **kwargs): # real signature unknown
pass
def PyMakeBuffer(*args, **kwargs): # real signature unknown
pass
def PySetMemory(*args, **kwargs): # real signature unknown
pass
def PySetString(*args, **kwargs): # real signature unknown
pass
def Rectangle(*args, **kwargs): # real signature unknown
pass
def RectInRegion(*args, **kwargs): # real signature unknown
pass
def RedrawWindow(*args, **kwargs): # real signature unknown
pass
def RegisterClass(*args, **kwargs): # real signature unknown
pass
def RegisterDeviceNotification(*args, **kwargs): # real signature unknown
pass
def RegisterHotKey(*args, **kwargs): # real signature unknown
pass
def RegisterWindowMessage(*args, **kwargs): # real signature unknown
pass
def ReleaseCapture(*args, **kwargs): # real signature unknown
pass
def ReleaseDC(*args, **kwargs): # real signature unknown
pass
def RemoveMenu(*args, **kwargs): # real signature unknown
pass
def ReplyMessage(*args, **kwargs): # real signature unknown
pass
def RestoreDC(*args, **kwargs): # real signature unknown
pass
def RoundRect(*args, **kwargs): # real signature unknown
pass
def SaveDC(*args, **kwargs): # real signature unknown
pass
def ScreenToClient(*args, **kwargs): # real signature unknown
pass
def ScrollWindowEx(*args, **kwargs): # real signature unknown
pass
def SelectObject(*args, **kwargs): # real signature unknown
pass
def SendMessage(*args, **kwargs): # real signature unknown
pass
def SendMessageTimeout(*args, **kwargs): # real signature unknown
pass
def SetActiveWindow(*args, **kwargs): # real signature unknown
pass
def SetArcDirection(*args, **kwargs): # real signature unknown
pass
def SetBkColor(*args, **kwargs): # real signature unknown
pass
def SetBkMode(*args, **kwargs): # real signature unknown
pass
def SetCapture(*args, **kwargs): # real signature unknown
pass
def SetCaretPos(*args, **kwargs): # real signature unknown
pass
def SetCursor(*args, **kwargs): # real signature unknown
pass
def SetDlgItemInt(*args, **kwargs): # real signature unknown
pass
def SetDlgItemText(*args, **kwargs): # real signature unknown
pass
def SetDoubleClickTime(*args, **kwargs): # real signature unknown
pass
def SetFocus(*args, **kwargs): # real signature unknown
pass
def SetForegroundWindow(*args, **kwargs): # real signature unknown
pass
def SetGraphicsMode(*args, **kwargs): # real signature unknown
pass
def SetLayeredWindowAttributes(*args, **kwargs): # real signature unknown
pass
def SetLayout(*args, **kwargs): # real signature unknown
pass
def SetMapMode(*args, **kwargs): # real signature unknown
pass
def SetMenu(*args, **kwargs): # real signature unknown
pass
def SetMenuDefaultItem(*args, **kwargs): # real signature unknown
pass
def SetMenuInfo(*args, **kwargs): # real signature unknown
pass
def SetMenuItemBitmaps(*args, **kwargs): # real signature unknown
pass
def SetMenuItemInfo(*args, **kwargs): # real signature unknown
pass
def SetMiterLimit(*args, **kwargs): # real signature unknown
pass
def SetParent(*args, **kwargs): # real signature unknown
pass
def SetPixel(*args, **kwargs): # real signature unknown
pass
def SetPixelV(*args, **kwargs): # real signature unknown
pass
def SetPolyFillMode(*args, **kwargs): # real signature unknown
pass
def SetRectRgn(*args, **kwargs): # real signature unknown
pass
def SetROP2(*args, **kwargs): # real signature unknown
pass
def SetScrollInfo(*args, **kwargs): # real signature unknown
pass
def SetStretchBltMode(*args, **kwargs): # real signature unknown
pass
def SetTextAlign(*args, **kwargs): # real signature unknown
pass
def SetTextCharacterExtra(*args, **kwargs): # real signature unknown
pass
def SetTextColor(*args, **kwargs): # real signature unknown
pass
def SetViewportExtEx(*args, **kwargs): # real signature unknown
pass
def SetViewportOrgEx(*args, **kwargs): # real signature unknown
pass
def SetWindowExtEx(*args, **kwargs): # real signature unknown
pass
def SetWindowLong(*args, **kwargs): # real signature unknown
pass
def SetWindowOrgEx(*args, **kwargs): # real signature unknown
pass
def SetWindowPlacement(*args, **kwargs): # real signature unknown
pass
def SetWindowPos(*args, **kwargs): # real signature unknown
pass
def SetWindowRgn(*args, **kwargs): # real signature unknown
pass
def SetWindowText(*args, **kwargs): # real signature unknown
pass
def SetWorldTransform(*args, **kwargs): # real signature unknown
pass
def set_logger(*args, **kwargs): # real signature unknown
pass
def Shell_NotifyIcon(*args, **kwargs): # real signature unknown
pass
def ShowCaret(*args, **kwargs): # real signature unknown
pass
def ShowWindow(*args, **kwargs): # real signature unknown
pass
def StretchBlt(*args, **kwargs): # real signature unknown
pass
def StrokeAndFillPath(*args, **kwargs): # real signature unknown
pass
def StrokePath(*args, **kwargs): # real signature unknown
pass
def SystemParametersInfo(*args, **kwargs): # real signature unknown
pass
def TrackPopupMenu(*args, **kwargs): # real signature unknown
pass
def TranslateAccelerator(*args, **kwargs): # real signature unknown
pass
def TranslateMessage(*args, **kwargs): # real signature unknown
pass
def TransparentBlt(*args, **kwargs): # real signature unknown
pass
def UnregisterClass(*args, **kwargs): # real signature unknown
pass
def UnregisterDeviceNotification(*args, **kwargs): # real signature unknown
pass
def UpdateLayeredWindow(*args, **kwargs): # real signature unknown
pass
def UpdateWindow(*args, **kwargs): # real signature unknown
pass
def ValidateRgn(*args, **kwargs): # real signature unknown
pass
def WaitMessage(*args, **kwargs): # real signature unknown
pass
def WidenPath(*args, **kwargs): # real signature unknown
pass
def WindowFromDC(*args, **kwargs): # real signature unknown
pass
def WindowFromPoint(*args, **kwargs): # real signature unknown
pass
def WNDCLASS(*args, **kwargs): # real signature unknown
pass
def _TrackMouseEvent(*args, **kwargs): # real signature unknown
pass
# no classes
# variables with complex values
__loader__ = None # (!) real value is '<_frozen_importlib_external.ExtensionFileLoader object at 0x0000025EBE595470>'
__spec__ = None # (!) real value is "ModuleSpec(name='win32gui', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x0000025EBE595470>, origin='C:\\\\Users\\\\Doly\\\\Anaconda3\\\\lib\\\\site-packages\\\\win32\\\\win32gui.pyd')"
| [
"[email protected]"
] | |
8314f6c7c49d0a6de1a0685c547ee62149778c68 | 22b929e324edc89ec28e9087e9f8dd943a15fe4b | /headlines.py | 19945fcc2078cb6405e487949d4e7616055d7f60 | [] | no_license | tspradeepece/headlines | aaca83f421c72f1bfa4174d58a611c6015ed175d | b42978c6681c7662f72326767928f6c041e5b358 | refs/heads/master | 2021-04-26T22:25:27.710235 | 2018-03-06T14:29:24 | 2018-03-06T14:29:24 | 124,090,014 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 194 | py |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello to the World of Flask!'
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8081)
| [
"[email protected]"
] | |
6c79da4ab166033ef433a784b9c63f51cb34e592 | cc28e2ec6e9e7ead33d212d8f19b32afd017593e | /week7/8.1inheritance.py | 62b430d3449eb6845b356c6d494732fb80312f19 | [] | no_license | BruceHi/web | 1445eda9313716f34943125d20cac0a6c13149cb | e5e6222b0cb5f2bd5838672f25183fe63f7b7e72 | refs/heads/master | 2023-01-31T23:32:50.801858 | 2020-12-18T12:19:43 | 2020-12-18T12:19:43 | 298,217,291 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 427 | py | # 父类
class People:
def __init__(self):
self.gene = 'XY'
def walk(self):
print('I can walk')
# 子类
class Man(People):
def __init__(self, name):
self.name = name
def work(self):
print('work hard')
class Woman(People):
def __init__(self, name):
self.name = name
def shopping(self):
print('buy buy')
p1 = Man('Adam')
p2 = Woman('eve')
p1.gene
| [
"[email protected]"
] | |
3a902a6d97ca8e8a6de9075792ef6fd028d2fa84 | 8e7389a43ac1b70787bcfa497b20034462a63589 | /extra_apps/pagedown/widgets.py | e70017e7e1b46cdfe4c1eae4b42c0996b333574a | [] | no_license | bluenknight/xadmin-markdown-editor | abf7fd42d77149aaaf7f4baf8a1ca9e7af06ea46 | 1a2b84404934c1b620b0d14dcf743e9ba4322aea | refs/heads/master | 2021-01-20T04:25:44.923995 | 2017-04-28T10:35:05 | 2017-04-28T10:35:05 | 89,691,063 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,894 | py | from django import VERSION, forms
from django.contrib.admin import widgets as admin_widgets
try:
from django.forms.utils import flatatt
except ImportError:
from django.forms.util import flatatt # <1.7
from django.utils.html import conditional_escape
from django.template import Context, loader
from pagedown import settings as pagedown_settings
from pagedown.utils import compatible_staticpath
try:
from django.utils.encoding import force_unicode
except ImportError: # python3
# https://docs.djangoproject.com/en/1.5/topics/python3/#string-handling
from django.utils.encoding import force_text as force_unicode
class PagedownWidget(forms.Textarea):
def __init__(self, *args, **kwargs):
self.show_preview = kwargs.pop("show_preview", pagedown_settings.SHOW_PREVIEW)
self.template = kwargs.pop("template", pagedown_settings.WIDGET_TEMPLATE)
self.css = kwargs.pop("css", pagedown_settings.WIDGET_CSS)
super(PagedownWidget, self).__init__(*args, **kwargs)
def _media(self):
return forms.Media(
css={
"all": self.css
},
js=(
compatible_staticpath("vendor/editormd/js/editormd.js"),
# compatible_staticpath("pagedown/Markdown.Converter.js"),
# compatible_staticpath('pagedown-extra/pagedown/Markdown.Converter.js'),
# compatible_staticpath("pagedown/Markdown.Sanitizer.js"),
# compatible_staticpath("pagedown/Markdown.Editor.js"),
# compatible_staticpath('pagedown-extra/Markdown.Extra.js'),
# compatible_staticpath("pagedown_init.js"),
))
media = property(_media)
def render(self, name, value, attrs=None):
if value is None:
value = ""
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, name=name)
else:
final_attrs = self.build_attrs(attrs, {'name': name})
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
class AdminPagedownWidget(PagedownWidget, admin_widgets.AdminTextareaWidget):
class Media:
css = {
"all": (compatible_staticpath("vendor/editormd/css/editormd.css"),)
}
js = (
compatible_staticpath("vendor/editormd/js/editormd.js"),
)
| [
"[email protected]"
] | |
eb159b1f57253af0fd250bc76264d1d43c2af422 | 2424063d657d643c1f8ccc6cca343271d6d0f708 | /Project26/app26/migrations/0001_initial.py | 54027c79041590b52df83cbe14295bb2cc4ef3b5 | [] | no_license | pythonwithnaveen/DjangoExamples | a0a07cbc53564522cf39649c235716ef5c3a4ba0 | 57c7a6302ada4079bd3625481e660587bf8015c6 | refs/heads/main | 2023-07-16T02:36:01.283938 | 2021-08-12T07:26:22 | 2021-08-12T07:26:22 | 371,881,524 | 0 | 3 | null | null | null | null | UTF-8 | Python | false | false | 742 | py | # Generated by Django 3.1.4 on 2021-08-09 05:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='EmployeeModel',
fields=[
('idno', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=100)),
('designation', models.CharField(choices=[('Developer', 'Developer'), ('Designaer', 'Designear'), ('Manager', 'Manager')], max_length=100)),
('contact', models.IntegerField()),
('photo', models.ImageField(upload_to='employee_images/')),
],
),
]
| [
"="
] | = |
aaef15a384b643214d5eb221a37a482f2bbef6b1 | 948fd3984bacd9ff59495f0ff72885d826281da0 | /dynamic_programming/n_cents_min.py | 803cdef08cbf5f1c1115e0d61c242c8a40bcf9d7 | [] | no_license | sabya14/cs_with_python | 8268344d59b05b532bdbbb30ed2100a0effaaa1d | e5e21aabf6126b93f42ab04785c5d0fa49a1528c | refs/heads/master | 2023-04-14T16:37:40.773598 | 2021-04-27T15:30:40 | 2021-04-27T15:30:40 | 112,823,987 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,177 | py | """
8.11 Problem from cracking the coding interview Modified, return the min cents
https://practice.geeksforgeeks.org/problems/coin-change/0
"""
def n_cents(n, cent_list, index, _dict, min):
global minimum
if n == 0:
if min < minimum:
minimum = min
return 1
if index > len(cent_list) - 1:
return 0
cent = cent_list[index]
possible_way_to_use = n // cent
result = 0
while possible_way_to_use > -1:
print(
f"Adding {possible_way_to_use} cents of value {cent},"
f" left value {n - (possible_way_to_use * cent)}")
if not ((n - (possible_way_to_use * cent), index + 1) in _dict):
_dict[(n - (possible_way_to_use * cent), index + 1)] = n_cents(n - (possible_way_to_use * cent),
cent_list, index + 1, _dict,
min + possible_way_to_use)
result += _dict[(n - (possible_way_to_use * cent), index + 1)]
possible_way_to_use -= 1
return minimum
minimum = 99999
print(n_cents(11, [5, 2, 1], 0, {}, 0))
| [
"="
] | = |
09fdeab3f804d99ecbf8189de26c9b455a439baa | 3816f02c6e1e31d4ba0c6e2893697500d1ca9b26 | /exc2/plotPeriodic.py | 0305f42e1ff9241b99a2a2b9e028c1efcf3fad7b | [] | no_license | taylorvd/KTHDriverless | 3b3786438e842f4932e1507562e66ab4864b0782 | 75d4991792038c3314a726b7e66b1fc072e5d755 | refs/heads/master | 2023-08-07T01:34:05.435450 | 2021-09-19T12:26:50 | 2021-09-19T12:26:50 | 401,480,140 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,552 | py | import numpy as np
from Tkinter import *
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
class PlotPeriodic:
"""
Class to produce and plot data given by periodic function
"""
def __init__ (self):
self.t = 0
self.y = 0
def get_data(self):
self.t = np.arange(0,1,0.001)
self.y = (3*np.pi*np.exp(-5*np.sin(2*np.pi*self.t)))
return self, self.y
def plot_function(self):
self.get_data()
plt.plot(self.t, self.y)
plt.show()
class GUIPlot(PlotPeriodic):
"""
Subclass to use Tkinter GUI with periodic plot
-used https://www.tutorialspoint.com/how-can-we-run-matplotlib-in-tkinter as reference
-used code from https://stackoverflow.com/questions/31440167/placing-plot-on-tkinter-main-window-in-python
"""
def __init__(self, window):
self.window = window
self.box = Entry(window)
self.button = Button (window, text="check", command=self.plot)
self.box.pack ()
self.button.pack()
self.t = PlotPeriodic.get_data(self)[0]
self.y = PlotPeriodic.get_data(self)[1]
def plot (self):
fig = Figure(figsize=(6,6))
gui = fig.add_subplot(111)
gui.plot(self.t, self.y,color='blue')
gui.set_title ("Periodic Function", fontsize=16)
gui.set_ylabel("y", fontsize=14)
gui.set_xlabel("t", fontsize=14)
canvas = FigureCanvasTkAgg(fig, master=self.window)
canvas.get_tk_widget().pack()
canvas.draw()
def edit_t_axis(self):
#implement using tkinter based on this example
#https://stackoverflow.com/questions/9997869/interactive-plot-based-on-tkinter-and-matplotlib
pass
def real_time_plot(self):
#implement using matplotlib.animation based on this example
#https://matplotlib.org/stable/api/animation_api.html
pass
window= Tk()
start= GUIPlot (window)
window.mainloop()
'''
def plotFigure(self):
gui = Tk()
matplotlib.use("TkAgg")
# figure = Figure()
# plot = plt.figure.add_subplot(1,1,1)
figure = PlotPeriodic.plot_function(self)
canvas = FigureCanvasTkAgg(figure, gui)
canvas.get_tk_widget().grid(row=0, column=0)
gui.mainloop()
'''
#change to button that moves data to csv file
if __name__ == "__main__":
testGui = GUIPlot()
| [
"[email protected]"
] | |
e46bacecad8733e21bef0850d692e7718ed1fdf3 | 7d949b9f19e4c5c897b3aef76e604f2c0eee7112 | /src-python/saccade_analysis/density/coord_conversions.py | 86446b0202bcc38d41bf7ca6a549153e9e5dc676 | [] | no_license | AndreaCensi/saccade_analysis | d3fad3a1a406b97c4dcf9cdc82b9b2ce1fbf42df | 71b87e9225b16317ffa9a581b3c62d8343fe7bfa | refs/heads/master | 2016-09-11T06:49:22.254391 | 2011-12-20T06:39:30 | 2011-12-20T06:39:30 | 952,465 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 987 | py | from . import contract, np
from ..tammero.tammero_analysis import compute_axis_angle
from contracts import new_contract
new_contract('angle_pi', 'float,>=-pi,<=pi')
@contract(x='float', y='float', theta='angle_pi', radius='>0,x',
returns='tuple(angle_pi,(>=0,<=x))')
def axisangle_distance_from_x_y_theta(x, y, theta, radius):
axis_angle = compute_axis_angle(x, y, theta)
r = np.hypot(x, y)
assert r <= radius, 'r=%s radius=%s' % (r, radius)
distance = radius - r
return axis_angle, distance
@contract(axis_angle='angle_pi', distance='>=0,x',
assumed_theta='angle_pi', radius='>0,>=x',
returns='tuple(float, float)')
def x_y_from_axisangle_distance(axis_angle,
distance,
assumed_theta,
radius):
phi = assumed_theta - axis_angle
norm = radius - distance
x = np.cos(phi) * norm
y = np.sin(phi) * norm
return x, y
| [
"[email protected]"
] | |
f2417fed67dbee63f20a3862ee6f3d4eb7807552 | fe94d8a1eff731ff488976b71df1d378ba0a8d09 | /Course_01_Automation_testing_with_Selenium/modul_3/mod3_2_step10.py | 54a91247a47ff15aabee4a43b83be3d22247c223 | [] | no_license | pinkwhale/stepik | 598252a5c3fbc667aefeb059b9fe457a1ab70ab8 | 78495d0df12a7df083b63f862221717d5ca7f6b1 | refs/heads/main | 2023-03-01T20:15:51.602962 | 2021-02-08T21:34:34 | 2021-02-08T21:34:34 | 334,087,491 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 629 | py | #STEP 10
print("\nStep 10")
def test_abs1():
assert abs(42) == 42, "Should be absolute value of a number"
def test_abs2():
assert abs(42) == -42, "Should be absolute value of a number"
if __name__ == '__main__':
test_abs1()
#test_abs2()
print("All tests passed!")
# STEP 11
print("\nStep 11\n")
import unittest
class TestAbs(unittest.TestCase):
def test_abs3(self):
self.assertEqual(abs(42), 42, "Should be absolute value of a number")
def test_abs4(self):
self.assertEqual(abs(42), -42, "Should be absolute value of a number")
if __name__ == "__main__":
unittest.main()
| [
"[email protected]"
] | |
4085c70aef43c511bcd49554afe355a3624b5b4d | 8886d5c77f9839c2f37967c5a4494d30a6341e8a | /django/Misitio/apps/blog/views.py | 4b8086c583b573c7ae853824d2137b55cca20b62 | [] | no_license | danielyerena6/intro_django | aa8e8657b29b930e4abc61a4f25216dd5895e335 | d458c8aa8989568363bfbdaea44a8ff5a82202d8 | refs/heads/master | 2022-11-14T16:44:07.452996 | 2020-06-30T22:06:34 | 2020-06-30T22:06:34 | 276,218,271 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 208 | py | from django.shortcuts import render,HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<h1>Lenguajes de Internet</h1> Alumno: Carlos Daniel Yerena Mercado <br> Grupo: 8CM11") | [
"[email protected]"
] | |
b25b43e1a4f8d5dfb2c1790fb87ac6cae1200a86 | 976685bd14758eff010d858820b2c6751d14f873 | /functions/dynamodb.py | b6b5cc6841e43655da3cffe4a26e08bf8f2d6fe1 | [] | no_license | sethschori/top_sites | 218ddcf22388ec0059e6b07b910246eedd2f6b3f | 1ca227f406916bd588475bb1b2d2ca5cdfa7fa86 | refs/heads/master | 2020-03-10T07:16:45.733385 | 2018-06-04T23:29:54 | 2018-06-04T23:29:54 | 129,259,521 | 0 | 0 | null | 2018-05-15T18:08:15 | 2018-04-12T13:55:55 | Python | UTF-8 | Python | false | false | 2,935 | py | """
AWS DynamoDB functions
"""
import boto3
from botocore.exceptions import ClientError
from error_handling import handle_error
class Dynamo(object):
"""
Class for AWS DynamoDB functions.
"""
def __init__(self, profile_name='default'):
"""
Initialize the Dynamo object using profile_name.
:param profile_name: If you're using AWS for other purposes beyond
top_sites, then you likely already have a config and/or credentials
file. (See details here: https://docs.aws.amazon.com/cli/latest
/userguide/cli-chap-getting-started.html) If you're using the
default profile to store 'region', 'aws_access_key_id', and
'aws_secret_access_key' values, then you don't need to pass
profile_name when instantiating a Dynamo object.
"""
self.profile_name = profile_name
self.boto_sess = boto3.session.Session(
profile_name=self.profile_name,
)
self.dynamodb = self.boto_sess.resource('dynamodb')
def get_all_rows(self, table_name):
"""
Retrieves all rows by scanning a DynamoDB table.
:param table_name: the name of the table to scan
:return: returns all rows as a list of dicts if successful, returns
None if unsuccessful
"""
table = self.dynamodb.Table(table_name)
try:
response = table.scan()
except ClientError as e:
error = e.response['Error']['Code']
if error == 'ResourceNotFoundException':
handle_error(
exc=error,
err=e,
msg='table_name "{t}" was not found'.format(t=table_name)
)
else:
handle_error(
exc=error,
err=e,
msg='unknown error'
)
return None
items = response['Items']
while 'LastEvaluatedKey' in response:
response = table.scan(
ExclusiveStartKey=response['LastEvaluatedKey']
)
items.extend(response['Items'])
return items
def batch_update_rows(self, table_name, items):
"""
Takes a list of object(s) and updates those in DynamoDB table_name
:param table_name: the name of the DynamoDB table to be updated
:param items: a list of object(s)
:return: True if succeeded, false if failed
"""
table = self.dynamodb.Table(table_name)
try:
with table.batch_writer() as batch:
for item in items:
item = vars(item)
batch.put_item(Item=item)
except ClientError as e:
handle_error(
exc=ClientError,
err=e,
msg="unknown error"
)
return False
return True
| [
"[email protected]"
] | |
92e4d2f41371ddd5c62efeaba8193be1bcacc333 | b93bb165f350fb5546da969224e805f6556f3e0c | /hwk12_p2-McKendreeSpringer.py | 0e4af9ee2950ebc4d2eea58c05f33c780ea3a6cf | [] | no_license | McKendree/Homework-12 | 90a113b78dd3c054948e636ac0eb9ab5e9b058c4 | 4613ca5e49c7989db76a7a47b95ed898dc28bf44 | refs/heads/main | 2023-04-16T12:22:44.731616 | 2021-04-29T02:55:32 | 2021-04-29T02:55:32 | 362,667,791 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,631 | py | import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import sys
if __name__ == "__main__":
I = 51 #starting x position
j = 51 #starting y position
xCoord = []
yCoord = []
#creates figure
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
counter = 0
def animate(i):
global counter
global I
global j
if counter >= 10000:
#stops after 10000 steps and plots full particle path
plt.plot(xCoord, yCoord)
plt.title('Brownian Motion')
plt.axis([0,101,0,101])
plt.savefig('Brownian_Motion.png')
sys.exit()
#plots new position
ax1.clear()
ax1.scatter(I,j,c='purple')
ax1.axis([0,101,0,101])
ax1.grid()
xCoord.append(I)
yCoord.append(j)
#chooses random direction to move
rand = random.choice(['north','south','east','west'])
if rand == 'north':
if j != 101:
j += 1
counter += 1
if rand == 'south':
if j != 1:
j -= 1
counter += 1
if rand == 'east':
if I != 101:
I += 1
counter += 1
if rand == 'west':
if I != 1:
I -= 1
counter += 1
#animates and shows figure
ani = animation.FuncAnimation(fig,animate,interval=1)
plt.title('Brownian Motion')
plt.show()
plt.clf()
| [
"[email protected]"
] | |
35b1f95de33a522185f4ed54e90f7fab31cb33c9 | 22da2a0870905adaa6aa245ddeed53feda883e42 | /textingMain.py | c553aa703044cb9fc10618d25e06db4a1afc68c6 | [] | no_license | hiteshishah/CG | a5b1e186f26610853856c0924e89bf7b94c9efe8 | 883c3e9d3b2e5172a3dafb6742f60c7c5126a4c5 | refs/heads/master | 2020-04-11T05:55:13.099094 | 2018-12-13T01:02:33 | 2018-12-13T01:02:33 | 161,564,181 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,035 | py | import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
from numpy import array, arange
from teapot import teapot
from quad import quad
from shaderSetup import shaderSetup
from viewParams import viewParams
from textures import *
from lighting import *
from simpleShape import *
from bufferSet import *
class textingMain (object) :
# our viewparams
view = viewParams ()
# lighting and textures
tex = textures ()
light = lighting()
# dimensions of the drawing window
w_width = 600
w_height = 600
# buffer information
quadBuffers = bufferSet(None)
teapotBuffers = bufferSet(None)
# animation flag
animating = False
# initial rotations
rotQuad = 0.0
rotTeapot = 0.0
# program IDs...for program and parameters
pshader = GLuint (0)
tshader = GLuint (0)
# vertex array object
qVao = GLuint(0)
tVao = GLuint(0)
#
# initialization
#
def init (self):
# Load your textures
self.tex.loadTexture()
# Load shaders and verify each
myShaders = shaderSetup(None)
self.tshader = myShaders.readAndCompile("texture.vert", "texture.frag")
if self.tshader <= 0:
print ("Error setting up Texture shaders")
raise Exception("Error setting up Texture Shaders", "fatal")
sys.exit(1)
self.pshader = myShaders.readAndCompile("phong.vert", "phong.frag")
if self.pshader <= 0:
print ("Error setting up Phong shaders")
raise Exception("Error setting up Phong Shaders", "fatal")
sys.exit(1)
# Other OpenGL initialization
glEnable( GL_DEPTH_TEST )
glClearColor( 0.0, 0.0, 0.0, 0.0 )
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL )
glClearDepth( 1.0 )
# create teapot
myShape = teapot()
myShape.clear()
myShape.makeTeapot()
self.tVao = self.createVAO(myShape, self.pshader, self.teapotBuffers )
# create quad
myShape = quad ()
myShape.clear()
myShape.makeQuad()
self.qVao = self.createVAO(myShape, self.tshader, self.quadBuffers )
'''
* Creates VAO for given set of objects. Returns the VAO ID
'''
def createVAO (self, shape, program, B) :
# Get yourself an ID
vaoID = GLuint(0)
glGenVertexArrays(1, vaoID)
# You'll need the correct program to get the location of the vertex
# attributes
glUseProgram(program)
# Bind the vertex array object
glBindVertexArray (vaoID)
# Make and fill your buffer
# create the buffers
B.createBuffers (shape)
# set buffers to correct vertext attribute
vPosition = glGetAttribLocation(program,"vPosition")
glEnableVertexAttribArray(vPosition)
glBindBuffer (GL_ARRAY_BUFFER, B.vbuffer);
glVertexAttribPointer(vPosition,4,GL_FLOAT,GL_FALSE,0,ctypes.c_void_p(0))
# color data
if( B.cSize > 0) :
vColor = glGetAttribLocation( program, "vColor" )
glEnableVertexAttribArray( vColor )
glBindBuffer (GL_ARRAY_BUFFER, B.cbuffer);
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p (0))
# normal data
if( B.nSize > 0 ) :
vNormal = glGetAttribLocation( program, "vNormal" )
glEnableVertexAttribArray( vNormal )
glBindBuffer (GL_ARRAY_BUFFER, B.nbuffer);
glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p (0))
# texture coord data
if( B.tSize > 0 ) :
vTexCoord = glGetAttribLocation( program, "vTexCoord" )
glEnableVertexAttribArray( vTexCoord );
glBindBuffer (GL_ARRAY_BUFFER, B.tbuffer);
glVertexAttribPointer( vTexCoord, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p (0))
# return your ID
return vaoID
#
# keyboard function
#
def keyPressed(self,*args):
#Get the key that was pressed
key = str(args[0].decode())
# animate
if(key == 'a'):
self.animating = True
# stop animating
elif (key == 's') :
self.animating = False
# reset rotations
elif (key == 'r') :
self.rotTeapot = 0.0
self.rotQuad = 0.0
self.display()
# quit
elif(key == 'q' or key == 'Q'):
sys.exit()
elif(args[0] == '\033'): #Escape character
sys.exit()
# Animate the objects (maybe)
def animate( self ) :
if( self.animating ) :
self.rotTeapot = self.rotTeapot + 0.5
self.rotQuad = self.rotQuad + 0.5
self.display()
#
# display function
#
def display( self ) :
# clear the frame buffer
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )
# first the quad
glUseProgram (self.tshader)
# set up viewing and projection parameters
self.view.setUpFrustum( self.tshader )
# set up the texture information
self.tex.setUpTexture( self.tshader )
# set up the camera
self.view.setUpCamera( self.tshader, 0.2, 3.0, 6.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0 )
# set up transformations for the quad
self.view.setUpTransforms( self.tshader, 1.5, 1.5, 1.5, 0.0, self.rotQuad, 0.0, -1.25, 1.0, -1.5)
# draw it
glBindVertexArray (self.qVao)
glDrawArrays(GL_TRIANGLES, 0, self.quadBuffers.numElements)
# now the teapot
glUseProgram( self.pshader )
# set up viewing and projection parameters
self.view.setUpFrustum( self.pshader )
# set up the Phong shading information
self.light.setUpPhong( self.pshader )
# set up the camera
self.view.setUpCamera( self.pshader, 0.2, 3.0, 6.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0)
# set up transforms
self.view.setUpTransforms( self.pshader, 2.0, 2.0, 2.0, 0.0, self.rotTeapot, 0.0, 1.5, 0.5, -1.5 )
# draw it
glBindVertexArray (self.tVao)
glDrawArrays(GL_TRIANGLES, 0, self.teapotBuffers.numElements)
#Swap the buffers
glutSwapBuffers()
# main function
def main(self):
glutInit()
glutInitDisplayMode(GLUT_RGBA|GLUT_ALPHA|GLUT_DOUBLE|GLUT_DEPTH|GLUT_3_2_CORE_PROFILE)
glutInitWindowSize(512,512)
glutCreateWindow(b"Transformation Demo")
self.init()
glutDisplayFunc(self.display)
glutIdleFunc(self.animate)
glutKeyboardFunc(self.keyPressed)
glutMainLoop()
self.dispose()
if __name__ == '__main__':
textingMain().main()
| [
"[email protected]"
] | |
be6add5c01d46db2bd86d34d5aa963f88ecbf4b9 | db5a17d376348d0911e5f606e416eada523d8806 | /venvRH/bin/chardetect | 6a1d64520e42772cb68eb03e23959ec286369906 | [] | no_license | black-mirror-1/GCPComputeUsageAndCost | 1bf29169cb3e170368886ff951df555828b7a91a | 7e04fb3915b1ac5714135729184b6f30a8b04884 | refs/heads/master | 2020-03-28T04:31:16.120348 | 2018-10-16T19:02:29 | 2018-10-16T19:02:29 | 147,719,838 | 0 | 1 | null | 2018-10-16T19:02:30 | 2018-09-06T18:58:09 | Python | UTF-8 | Python | false | false | 264 | #!/home/hisands/GCPComputeUsageAndCost/venvRH/bin/python2
# -*- coding: utf-8 -*-
import re
import sys
from chardet.cli.chardetect import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
] | ||
75859b1915c1620b964ee8b32bde267d4857f1d5 | 241c2365e9d8e21bbf6425993cfefb65ad2e5e41 | /src/babylon/models/ingredient.py | 25c06a406dd0e42bd7e35e77a94c155ec9521f67 | [
"MIT"
] | permissive | t-persson/babylon | 905d2f13e6a387849d1bceecd0464c259df24e01 | 7bfcef35802fe53e2cb15d8dedc05a6cf6ba5f02 | refs/heads/master | 2023-08-21T18:31:51.808228 | 2021-10-19T18:43:17 | 2021-10-19T18:43:17 | 224,975,876 | 0 | 1 | MIT | 2021-10-02T22:34:18 | 2019-11-30T07:27:22 | Python | UTF-8 | Python | false | false | 642 | py | from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from ..database import Base
class ModelIngredient(Base):
__tablename__ = "ingredient"
id = Column('id', Integer, primary_key=True)
name = Column('name', String, unique=True)
recipes = relationship("IngredientAssociation", back_populates="ingredient")
measured_in_id = Column(Integer, ForeignKey("measured_in.id"))
measured_in = relationship("ModelMeasuredIn", back_populates="ingredients")
def __init__(self, name, measured_in, *args, **kwargs):
self.name = name
self.measured_in = measured_in
| [
"[email protected]"
] | |
ef4029a1dd579c99589e416602be1cd5de30b58e | 9f5e114dfe13252f82b28481436cd27553a7463c | /doc/conf.py | 27695c80689c2b2771cd181cdcde59736826cc65 | [] | no_license | jove1/ae | bf676b1fee74c710de71593d36af1edbd0e03b76 | 560c3120e7ff4ce566a4015ad3cd2dd29361c54e | refs/heads/master | 2020-05-21T03:13:01.706171 | 2018-01-25T14:34:03 | 2018-01-25T14:34:03 | 16,833,666 | 3 | 7 | null | null | null | null | UTF-8 | Python | false | false | 7,764 | py | # -*- coding: utf-8 -*-
#
# AE documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 14 12:33:24 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'AE'
copyright = u'2014, Jozef Veselý'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'AEdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'AE.tex', u'AE Documentation',
u'Jozef Veselý', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'ae', u'AE Documentation',
[u'Jozef Veselý'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'AE', u'AE Documentation',
u'Jozef Veselý', 'AE', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| [
"[email protected]"
] | |
fe0ed9260d74e01cce466d2887f6cddd43e0a1c4 | 68ed11df9c9844cf204f4de36de072b1b9d782b1 | /gallery/pg/admin.py | 9aa347946857bfbc6b283b984d084dbe617b2560 | [] | no_license | mananarora200/django-basic | 6e1929f0ff59fa532cb472817c482799dd1d2012 | 144df6d2ab9b68f2055df481a60e383c50961f33 | refs/heads/master | 2023-02-27T19:17:34.087249 | 2021-02-05T11:20:47 | 2021-02-05T11:20:47 | 336,250,044 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 95 | py | from django.contrib import admin
from . import models
admin.site.register(models.Image_Model)
| [
"[email protected]"
] | |
dd7a380dff497a8de25ce45fba2a1a72ccdb531f | 973630f5ebe79c4823448b6391725bc8a5af7b23 | /build/xunjian_nav/catkin_generated/pkg.develspace.context.pc.py | 37f131ac2b67245023fe78146f5fcf51eb99a111 | [] | no_license | yhwalker/ros_robot | 18d786262c6158220309166bf4bdc0f26fe3f07d | 9d61789eb011fcb7c218e9016d6211e9192f1850 | refs/heads/master | 2020-05-15T14:41:36.644052 | 2017-08-22T07:57:33 | 2017-08-22T07:57:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 574 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/robot/ros/devel/include;/home/robot/ros/src/xunjian_nav/include".split(';') if "/home/robot/ros/devel/include;/home/robot/ros/src/xunjian_nav/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;rospy;std_msgs;serial;message_runtime".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lxunjian_nav".split(';') if "-lxunjian_nav" != "" else []
PROJECT_NAME = "xunjian_nav"
PROJECT_SPACE_DIR = "/home/robot/ros/devel"
PROJECT_VERSION = "0.0.0"
| [
"[email protected]"
] | |
a813a26b990666f7bf937f3ba85285afcbf2ac2e | d6a31cfac7f6c899399c492f450ff832f2f2f4f5 | /sample_codes/smallest-divisor-intege.py | fd2397e5e11aee343ef009dbce06925516c8ac1c | [] | no_license | gvnsai/python_practice | c2e51e9c73bc901375b1fb397b80a28802d85754 | dffe4b6bb4a991d2caa790415c1e5b041ed95ee3 | refs/heads/master | 2020-03-26T17:55:25.713217 | 2018-11-10T05:56:48 | 2018-11-10T05:56:48 | 145,187,300 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 267 | py | #To Find the Smallest Divisor of an Integer.
n=int(input("Enter an integer:"))
a=[]
for i in range(2,n+1):
if(n%i==0):
a.append(i)
a.sort()
print("Smallest divisor is:",a[0])
"""
output:--
Enter an integer:66
Smallest divisor is: 2
"""
| [
"[email protected]"
] | |
a244fe45bedc72b808bfa00a8452e402d3264b6b | a76401f82ed1c9ac47ddaff27681b90f37627426 | /.history/student_olx/registration/views_20210921231029.py | fb75f0720d8a0526addb133e034831f33e8a4213 | [] | no_license | RiteshK555/itw-project | e90e1dd13517ee8b07d72cc3bd5a42af367ab587 | a2e4c8682c2030ff77da9ade5ae4677bd475f87a | refs/heads/master | 2023-08-30T03:48:58.904979 | 2021-11-10T09:50:59 | 2021-11-10T09:50:59 | 410,032,076 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 968 | py | from django.shortcuts import render
from django.contrib.auth import models
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from .models import money
# Create your views here.
def register(response):
# if response.method == 'GET':
if response.method=="POST":
form=UserCreationForm(response.POST)
if form.is_valid():
if form.is_valid():
form.save()
current_signedin_user=User.objects.get(username='ritesh')
m=money(amount=0,holder=current_signedin_user)
m.save()
return redirect("/")
else:
form=UserCreationForm()
else:
form=UserCreationForm()
return render(response,"registration/register.html",{"form":form})
def login(response):
# if money.holder==User:
# print("hi")
return render(response,"registration/login.html") | [
""
] | |
2b853f7ff88a9670288ae7edaac66dcc3384f2fb | 930d3a81debaea0cbf05a3813afdba03605aa53e | /ex2.py | 2e3486d866b270732cdc6dfab6498c143ae33408 | [] | no_license | CM-David/Pythonexercises | 34f3a609622d8ec83c1e76c5c298641903d377aa | b0782fbfc5acf6ab4f349fa34f25d2fab35892fd | refs/heads/master | 2022-10-02T03:51:28.309842 | 2020-06-03T01:48:16 | 2020-06-03T01:48:16 | 268,898,697 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 168 | py | name = input("WHAT IS YOUR NAME? ")
name_length = len(name)
print(f'HELLO {name.upper()}')
print(f'WOW YOUR {name.upper()} HAS {name_length} LETTERS IN IT. AWESOME') | [
"[email protected]"
] | |
d14ead75da82647856872b5606530802cf9d95e5 | 49828e3eb4660770382a3a597230d502e3ac6b9b | /test/functional/listsinceblock.py | 25692dda8439922fefe333fcae056a9ab5ba8d3e | [
"MIT"
] | permissive | BitBridgeCoin/BitBridgeCoin | 839970f253baf0b966abda66a5934be438a0908f | 7d4d78472bf9dbfd6458498cdef78954796674da | refs/heads/master | 2023-04-17T18:48:55.454093 | 2021-05-07T07:18:26 | 2021-05-07T07:18:26 | 355,376,877 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,241 | py | #!/usr/bin/env python3
# Copyright (c) 2017 The BitBridgeCoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listsincelast RPC."""
from test_framework.test_framework import BitBridgeCoinTestFramework
from test_framework.util import assert_equal
class ListSinceBlockTest (BitBridgeCoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def run_test(self):
self.nodes[2].generate(101)
self.sync_all()
self.test_reorg()
self.test_double_spend()
self.test_double_send()
def test_reorg(self):
'''
`listsinceblock` did not behave correctly when handed a block that was
no longer in the main chain:
ab0
/ \
aa1 [tx0] bb1
| |
aa2 bb2
| |
aa3 bb3
|
bb4
Consider a client that has only seen block `aa3` above. It asks the node
to `listsinceblock aa3`. But at some point prior the main chain switched
to the bb chain.
Previously: listsinceblock would find height=4 for block aa3 and compare
this to height=5 for the tip of the chain (bb4). It would then return
results restricted to bb3-bb4.
Now: listsinceblock finds the fork at ab0 and returns results in the
range bb1-bb4.
This test only checks that [tx0] is present.
'''
# Split network into two
self.split_network()
# send to nodes[0] from nodes[2]
senttx = self.nodes[2].sendtoaddress(self.nodes[0].getnewaddress(), 1)
# generate on both sides
lastblockhash = self.nodes[1].generate(6)[5]
self.nodes[2].generate(7)
self.log.info('lastblockhash=%s' % (lastblockhash))
self.sync_all([self.nodes[:2], self.nodes[2:]])
self.join_network()
# listsinceblock(lastblockhash) should now include tx, as seen from nodes[0]
lsbres = self.nodes[0].listsinceblock(lastblockhash)
found = False
for tx in lsbres['transactions']:
if tx['txid'] == senttx:
found = True
break
assert found
def test_double_spend(self):
'''
This tests the case where the same UTXO is spent twice on two separate
blocks as part of a reorg.
ab0
/ \
aa1 [tx1] bb1 [tx2]
| |
aa2 bb2
| |
aa3 bb3
|
bb4
Problematic case:
1. User 1 receives BTC in tx1 from utxo1 in block aa1.
2. User 2 receives BTC in tx2 from utxo1 (same) in block bb1
3. User 1 sees 2 confirmations at block aa3.
4. Reorg into bb chain.
5. User 1 asks `listsinceblock aa3` and does not see that tx1 is now
invalidated.
Currently the solution to this is to detect that a reorg'd block is
asked for in listsinceblock, and to iterate back over existing blocks up
until the fork point, and to include all transactions that relate to the
node wallet.
'''
self.sync_all()
# Split network into two
self.split_network()
# share utxo between nodes[1] and nodes[2]
utxos = self.nodes[2].listunspent()
utxo = utxos[0]
privkey = self.nodes[2].dumpprivkey(utxo['address'])
self.nodes[1].importprivkey(privkey)
# send from nodes[1] using utxo to nodes[0]
change = '%.8f' % (float(utxo['amount']) - 1.0003)
recipientDict = {
self.nodes[0].getnewaddress(): 1,
self.nodes[1].getnewaddress(): change,
}
utxoDicts = [{
'txid': utxo['txid'],
'vout': utxo['vout'],
}]
txid1 = self.nodes[1].sendrawtransaction(
self.nodes[1].signrawtransaction(
self.nodes[1].createrawtransaction(utxoDicts, recipientDict))['hex'])
# send from nodes[2] using utxo to nodes[3]
recipientDict2 = {
self.nodes[3].getnewaddress(): 1,
self.nodes[2].getnewaddress(): change,
}
self.nodes[2].sendrawtransaction(
self.nodes[2].signrawtransaction(
self.nodes[2].createrawtransaction(utxoDicts, recipientDict2))['hex'])
# generate on both sides
lastblockhash = self.nodes[1].generate(3)[2]
self.nodes[2].generate(4)
self.join_network()
self.sync_all()
# gettransaction should work for txid1
assert self.nodes[0].gettransaction(txid1)['txid'] == txid1, "gettransaction failed to find txid1"
# listsinceblock(lastblockhash) should now include txid1, as seen from nodes[0]
lsbres = self.nodes[0].listsinceblock(lastblockhash)
assert any(tx['txid'] == txid1 for tx in lsbres['removed'])
# but it should not include 'removed' if include_removed=false
lsbres2 = self.nodes[0].listsinceblock(blockhash=lastblockhash, include_removed=False)
assert 'removed' not in lsbres2
def test_double_send(self):
'''
This tests the case where the same transaction is submitted twice on two
separate blocks as part of a reorg. The former will vanish and the
latter will appear as the true transaction (with confirmations dropping
as a result).
ab0
/ \
aa1 [tx1] bb1
| |
aa2 bb2
| |
aa3 bb3 [tx1]
|
bb4
Asserted:
1. tx1 is listed in listsinceblock.
2. It is included in 'removed' as it was removed, even though it is now
present in a different block.
3. It is listed with a confirmations count of 2 (bb3, bb4), not
3 (aa1, aa2, aa3).
'''
self.sync_all()
# Split network into two
self.split_network()
# create and sign a transaction
utxos = self.nodes[2].listunspent()
utxo = utxos[0]
change = '%.8f' % (float(utxo['amount']) - 1.0003)
recipientDict = {
self.nodes[0].getnewaddress(): 1,
self.nodes[2].getnewaddress(): change,
}
utxoDicts = [{
'txid': utxo['txid'],
'vout': utxo['vout'],
}]
signedtxres = self.nodes[2].signrawtransaction(
self.nodes[2].createrawtransaction(utxoDicts, recipientDict))
assert signedtxres['complete']
signedtx = signedtxres['hex']
# send from nodes[1]; this will end up in aa1
txid1 = self.nodes[1].sendrawtransaction(signedtx)
# generate bb1-bb2 on right side
self.nodes[2].generate(2)
# send from nodes[2]; this will end up in bb3
txid2 = self.nodes[2].sendrawtransaction(signedtx)
assert_equal(txid1, txid2)
# generate on both sides
lastblockhash = self.nodes[1].generate(3)[2]
self.nodes[2].generate(2)
self.join_network()
self.sync_all()
# gettransaction should work for txid1
self.nodes[0].gettransaction(txid1)
# listsinceblock(lastblockhash) should now include txid1 in transactions
# as well as in removed
lsbres = self.nodes[0].listsinceblock(lastblockhash)
assert any(tx['txid'] == txid1 for tx in lsbres['transactions'])
assert any(tx['txid'] == txid1 for tx in lsbres['removed'])
# find transaction and ensure confirmations is valid
for tx in lsbres['transactions']:
if tx['txid'] == txid1:
assert_equal(tx['confirmations'], 2)
# the same check for the removed array; confirmations should STILL be 2
for tx in lsbres['removed']:
if tx['txid'] == txid1:
assert_equal(tx['confirmations'], 2)
if __name__ == '__main__':
ListSinceBlockTest().main()
| [
"[email protected]"
] | |
4301f7ee191ae8b2e11ec7c6e0406c340b7a7776 | 00ec0c8b3c802a9305f46be6dbe76b57a238d3d2 | /core_db/src/smile_api/migrations/0003_workinghours.py | c96696387acef134625201df614ec77293241763 | [
"MIT"
] | permissive | Opportunity-Hack-2016-SJC-SVCC/TeamSmile | 403781928fe88c3aa85b7191f8f6b11fa947864c | c13697197813187a0fed0c66572c8c744138587e | refs/heads/master | 2021-05-03T19:07:39.366952 | 2016-09-26T00:21:34 | 2016-09-26T00:21:34 | 69,121,007 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,077 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-25 08:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('smile_api', '0002_remove_foodsource_description_1'),
]
operations = [
migrations.CreateModel(
name='WorkingHours',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start', models.IntegerField()),
('end', models.IntegerField()),
('day_of_the_week', models.CharField(choices=[(b'Monday', b'Monday'), (b'Tuesday', b'Tuesday'), (b'Wednesday', b'Wednesday'), (b'Thursday', b'Thursday'), (b'Friday', b'Friday'), (b'Saturday', b'Saturday'), (b'Sunday', b'Sunday')], default=b'Monday', max_length=15)),
('food_source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='smile_api.FoodSource')),
],
),
]
| [
"[email protected]"
] | |
6acefcb7b0c6a3fbb0f54ac6cc35263cee4797e8 | 5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d | /alipay/aop/api/domain/ApprovalCityDTO.py | 4e34e0e4fb8346afe04ea87f7b390a6b2cbaa319 | [
"Apache-2.0"
] | permissive | alipay/alipay-sdk-python-all | 8bd20882852ffeb70a6e929038bf88ff1d1eff1c | 1fad300587c9e7e099747305ba9077d4cd7afde9 | refs/heads/master | 2023-08-27T21:35:01.778771 | 2023-08-23T07:12:26 | 2023-08-23T07:12:26 | 133,338,689 | 247 | 70 | Apache-2.0 | 2023-04-25T04:54:02 | 2018-05-14T09:40:54 | Python | UTF-8 | Python | false | false | 1,356 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ApprovalCityDTO(object):
def __init__(self):
self._city_code = None
self._city_name = None
@property
def city_code(self):
return self._city_code
@city_code.setter
def city_code(self, value):
self._city_code = value
@property
def city_name(self):
return self._city_name
@city_name.setter
def city_name(self, value):
self._city_name = value
def to_alipay_dict(self):
params = dict()
if self.city_code:
if hasattr(self.city_code, 'to_alipay_dict'):
params['city_code'] = self.city_code.to_alipay_dict()
else:
params['city_code'] = self.city_code
if self.city_name:
if hasattr(self.city_name, 'to_alipay_dict'):
params['city_name'] = self.city_name.to_alipay_dict()
else:
params['city_name'] = self.city_name
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = ApprovalCityDTO()
if 'city_code' in d:
o.city_code = d['city_code']
if 'city_name' in d:
o.city_name = d['city_name']
return o
| [
"[email protected]"
] | |
cb0872c8c90772706c42ca5f268501b957e15b6d | 59a7ed399768b35b712d41e445624fb1c79bd503 | /src/orders/migrations/0003_auto_20190801_2007.py | 5de32c0872c785fdd92006aa1494558293efb040 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-copyleft",
"GPL-1.0-or-later",
"bzip2-1.0.6",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-newlib-historical",
"OpenSSL",
"Python-2.0",
"TCL",
"LicenseRef-scancode-python-cwi"
] | permissive | HuyNguyen260398/python-ecommerce | e82b3a0b68e31e0a819a99c69050287a5431f8cc | 609600058bf4268f4dbe00e179bf3fd75e9a3a79 | refs/heads/master | 2022-12-11T18:20:33.570522 | 2019-08-24T04:55:09 | 2019-08-24T04:55:09 | 191,665,509 | 0 | 0 | MIT | 2022-12-08T06:00:24 | 2019-06-13T01:00:21 | Tcl | UTF-8 | Python | false | false | 921 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-08-01 13:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('addresses', '0002_auto_20190801_2007'),
('orders', '0002_auto_20190731_1810'),
]
operations = [
migrations.AddField(
model_name='order',
name='billing_address',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='billing_address', to='addresses.Address'),
),
migrations.AddField(
model_name='order',
name='shipping_address',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='shipping_address', to='addresses.Address'),
),
]
| [
"[email protected]"
] | |
eff74af9a35de395a61a1dce7942f6ec3f572eae | dd4ad255de9395c656a9b69174adb87cb7164bc4 | /linodecli/response.py | 6d879293498b1f887259e80129dfafe7df79e05d | [
"BSD-3-Clause"
] | permissive | ginkgomzd/linode-cli | 516574b6d94904a1feab3f80a93654b9e78b78ea | 94f36c037453429861e5da133418baf031370e40 | refs/heads/master | 2020-03-22T06:23:13.084234 | 2018-07-03T18:08:00 | 2018-07-03T18:08:00 | 139,629,870 | 0 | 0 | BSD-3-Clause | 2018-07-03T19:38:47 | 2018-07-03T19:38:47 | null | UTF-8 | Python | false | false | 2,325 | py | """
Classes related to parsing responses and display output from the API, based
on the OpenAPI spec.
"""
from __future__ import print_function
from colorclass import Color
class ModelAttr:
def __init__(self, name, filterable, display, color_map=None):
self.name = name
self.value = None
self.filterable = filterable
self.display = display
self.column_name = self.name.split('.')[-1]
self.color_map = color_map
def _get_value(self, model):
"""
Returns the raw value from a model
"""
# walk down json paths to find the value
value = model
for part in self.name.split('.'):
if value is None:
return None
value = value[part]
return value
def render_value(self, model):
"""
Given the model returned from the API, returns the correctly- rendered
version of it. This can transform text based on various rules
configured in the spec using custom tags. Currently supported tags:
x-linode-cli-color
A list of key-value pairs that represent the value, and its ideal color.
The key "default_" is used to colorize anything that is not included.
If omitted, no color is applied.
"""
value = self._get_value(model)
if isinstance(value, list):
value = ', '.join([str(c) for c in value])
if self.color_map is not None:
# apply colors
value = str(value) # just in case
color = self.color_map.get(value) or self.color_map['default_']
value = str(Color('{'+color+'}'+value+'{/'+color+'}'))
if value is None:
# don't print the word "None"
value = ''
return value
def get_string(self, model):
"""
Returns the raw value from a model, cleaning up Nones and other values
that won't render properly as strings
"""
value = self._get_value(model)
if value is None:
value = ''
elif isinstance(value, list):
value = ' '.join([str(c) for c in value])
else:
value = str(value)
return value
class ResponseModel:
def __init__(self, attrs):
self.attrs = attrs
| [
"[email protected]"
] | |
f015e2fe088559ce92649e330e8d5809672a131e | a958ce2f52dc7bd6d95e81f7d37e3a27a6c233a1 | /map/DefaultMap_4ways_StopSigns.py | 6727b02c0864c375c956be05454eb4838ae9c110 | [] | no_license | pulei-student/PyTrafficSim | 839946485795987c5ae153bcf089a42744778a8d | 1664ab305a35624b1cab2d2d826e0a170a576c9f | refs/heads/main | 2023-03-12T20:36:31.096294 | 2021-03-06T06:07:05 | 2021-03-06T06:07:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,642 | py | from util import *
# lane rules counting from the center towards the right (right side driving rules)
# empty outbounds -> default (Dynamic)
lanes_rule_3 = [{
"directions": ["L"],
"outbounds": [],
}, {
"directions": ["F"],
"outbounds": [],
}, {
"directions": ["R", "F"],
"outbounds": [],
}]
lanes_rule_4 = [{
"directions": ["L"],
"outbounds": [],
}, {
"directions": ["F"],
"outbounds": [],
}, {
"directions": ["F"],
"outbounds": [],
}, {
"directions": ["R", "F"],
"outbounds": [],
}]
class Map:
def __init__(self):
# from the Skinker-Forest intersection
self.tl_yellow = [True, True, True] # left, forward, right
self.roads = [{
"out_number": 3,
"in_number": 3,
"pc": (2.68, -18.35),
"length": 3.09,
"direction": -3.01942,
"rules": lanes_rule_3
}, {
"out_number": 3,
"in_number": 2,
"pc": (15.29, 0.48),
"length": 3.52,
"direction": -1.48353,
"rules": lanes_rule_3
}, {
"out_number": 4,
"in_number": 2,
"pc": (-4.12, 16.19),
"length": 3.09,
"direction": 0.122173,
"rules": lanes_rule_4
}, {
"out_number": 4,
"in_number": 2,
"pc": (-16.16, -0.56),
"length": 3.09,
"direction": 1.65647,
"rules": lanes_rule_4
}]
self.traffic_lights_schedules = [
[
99999999, {"color": ["yellow", "yellow", "yellow", "yellow"], "flashing": [False, False, False, False],# [True, True, True, True],
"rule": [self.tl_yellow, self.tl_yellow, self.tl_yellow, self.tl_yellow]},
]]
def get_point_from_map(self, intersection, lane, scale, window_size, outbound=True, extend=0):
window_w, window_h = window_size
road_dic = self.roads[intersection]
pc = (road_dic["pc"][0]*scale, (road_dic["pc"][1])*scale)
length = road_dic["length"]
direction = road_dic["direction"]
if outbound:
rotated_spawn_pt = tuple_recenter(rotate(pc, (pc[0]+length*(0.5+lane)*scale, pc[1]),
direction, tuple=True), window_w, window_h)
else:
# inbound
rotated_spawn_pt = tuple_recenter(rotate(pc, (pc[0]+length*(-0.5-lane)*scale, pc[1]),
direction, tuple=True), window_w, window_h)
return rotated_spawn_pt
| [
"SunQiao"
] | SunQiao |
e94a4b2dcbce33230756e8982b71dffd2417bc5c | 14856ffe01c711af7a41af0b1abf0378ba4ffde6 | /Python/Fundamentals/The_Requests_Library.py | 1fb502a9b63431fac2c071f74afb40a2de5b392a | [] | no_license | sharonanchel/coding-dojo | 9a8db24eec17b0ae0c220592e6864510297371c3 | d6c4a7efd0804353b27a49e16255984c4f4b7f2a | refs/heads/master | 2021-05-05T18:17:48.101853 | 2017-06-23T23:53:51 | 2017-06-23T23:53:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 121 | py | import requests
r = requests.get('http://pokeapi.co/api/v2/pokemon/5/')
x = r.json()
# print x
print x['abilities'][0]
| [
"[email protected]"
] | |
80041892cee422614b4280d8f1182026a15c6a64 | 9af0eb00ffb8808fca1d2978f336cf241dfb395c | /2.2/netmgr/pm_netmgr_cli.py | b859340be51f8f04fda99e4df339fe7b8d2a8245 | [] | no_license | KAV178/pmon | a2db70f4a2c1ff6c9639052f4382de17be8427a6 | 0d3b5f4f9fb5c3745cbad175ae325abd01c1f3c6 | refs/heads/master | 2020-04-09T02:57:14.038468 | 2018-12-14T07:57:02 | 2018-12-14T07:57:02 | 159,961,645 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,344 | py | # -*- coding: utf-8 -*-
from __future__ import print_function
from sys import argv, exit
from argparse import ArgumentParser
from multiprocessing.managers import BaseManager
from multiprocessing.pool import ThreadPool
from re import match, findall
from socket import error as socket_err
from time import sleep
from pm_netmgr_srv import COMMANDS
from system.config_worker.main import PMonConfig
__author__ = 'Kostreno A.V.'
class PMonNetMgrCli(object):
def __init__(self, args):
p_args = self.__parse_args(args)
cfg_data = PMonConfig()
if not any((v for k, v in vars(p_args).items() if k.startswith('netmgr_'))):
for a in ((k for k in vars(p_args).keys() if k.startswith('netmgr_'))):
if not vars(p_args)[a]:
p_args.__setattr__(a, cfg_data.__getattribute__(a))
self.conn = BaseManager(address=(p_args.netmgr_host, p_args.netmgr_port), authkey='2.2')
for c in COMMANDS.keys():
self.conn.register(typeid=c)
print('Trying to connect with {hp.netmgr_host}:{hp.netmgr_port} ... '.format(hp=p_args), end='')
try:
self.conn.connect()
print("OK")
except socket_err as e:
print("Fail\n\n{0}\n".format(e))
exit(0)
def __parse_args(self, args):
parser = ArgumentParser(add_help=True, version='Client for PMon version 2.2')
parser.add_argument('-s', '--srv', type=str, default=None, dest='netmgr_host',
help='hostname or ip address with running pmon service')
parser.add_argument('-p', '--port', type=int, default=None, dest='netmgr_port',
help='port for connecting to pmon service')
return parser.parse_args(args)
def run(self):
def req_processing():
return self.conn.__getattribute__(parsed_req[0])(parsed_req[1:])
while True:
in_cmd = raw_input('pmon_mgr> ').strip()
if len(in_cmd):
if in_cmd.lower() not in ('exit', 'quit'):
t_pool = ThreadPool(processes=1)
req_res = None
parsed_req = tuple(in_cmd.split())
if parsed_req[0] in self.conn._registry.keys():
try:
_tr = t_pool.apply_async(func=req_processing, args=())
while not _tr.ready():
sleep(0.5)
print(".", end="")
req_res = _tr.get().decode('utf-8')
except Exception as e:
print(e)
print("\n{0}\n".format(req_res))
else:
print("Unknown command \"{0}\". Use help for get list of available commands.".format(parsed_req[0]))
continue
if len(findall(r'no active monitoring processes left\.', req_res)):
print("Exiting...")
break
else:
print("Exiting...")
break
exit(0)
if __name__ == '__main__':
cli = PMonNetMgrCli(argv[1:])
cli.run()
| [
"[email protected]"
] | |
e35537cf7871666516799a92abf9282330cee569 | b1368c648fc9c68db81669235c2338d2535ccec2 | /Chapitre_6/code RAM dispo.py | 02a077c08b17d0fbe2dc23941043155d65e73361 | [] | no_license | MBottinIUT/nRF52840-CircuitPython | 09c2041cd10291fbbdaf52d3c5df1d07ec96abf5 | bbe56f806360b1e2bb0f0251b5b2a4535d32818e | refs/heads/master | 2023-03-12T18:51:34.454620 | 2021-03-03T10:22:32 | 2021-03-03T10:22:32 | 271,368,611 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 263 | py | """ Test de la mémoire RAM disponible """
# Importation des librairies natives utiles
#from time import *
from time import sleep
from gc import *
sleep(0.5)
print ("memoire allouee : {}".format(mem_alloc()))
print ("memoire disponible : {}".format(mem_free()))
| [
"[email protected]"
] | |
54c1621791fb2b2a9380f6319860640fbeefde16 | 28c0bcb13917a277cc6c8f0a34e3bb40e992d9d4 | /koku/api/query_filter.py | 73a193355416b2e6579fa150fd2ba46b1ab1ebf5 | [
"Apache-2.0"
] | permissive | luisfdez/koku | 43a765f6ba96c2d3b2deda345573e1d97992e22f | 2979f03fbdd1c20c3abc365a963a1282b426f321 | refs/heads/main | 2023-06-22T13:19:34.119984 | 2021-07-20T12:01:35 | 2021-07-20T12:01:35 | 387,807,027 | 0 | 1 | Apache-2.0 | 2021-07-20T13:50:15 | 2021-07-20T13:50:14 | null | UTF-8 | Python | false | false | 10,198 | py | #
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""QueryFilterfor Reports."""
from collections import defaultdict
from collections import UserDict
from functools import total_ordering
from django.db.models import Q
@total_ordering
class QueryFilter(UserDict):
"""Dict-like object representing a single query filter."""
SEP = "__" # separator
table = None
field = None
operation = None
parameter = None
composition_key = None
def __init__(
self,
table=None,
field=None,
operation=None,
parameter=None,
composition_key=None,
custom=None,
logical_operator=None,
):
"""Constructor.
Args:
table (str) - The name of a DB table
field (str) - The name of a DB field
operation (str) - The name of a DB operation, e.g. 'in' or 'gte'
parameter (object) - A valid query target, e.g. a list or datetime
composition_key(str) - A key used for composing filters on different fields into an OR
logical_operator (str) - 'and' or 'or'
"""
super().__init__(table=table, field=field, operation=operation, parameter=parameter)
self.table = table
self.field = field
self.operation = operation
self.parameter = parameter
self.composition_key = composition_key
self.logical_operator = "or"
if logical_operator:
self.logical_operator = logical_operator
def composed_query_string(self):
"""Return compiled query string."""
fields = [entry for entry in [self.table, self.field, self.operation] if entry is not None]
return self.SEP.join(fields)
def compose_key(self):
"""Return compose key or composed_query_string."""
key = self.composition_key
if key is None:
key = self.composed_query_string()
return key
def composed_Q(self):
"""Return a Q object formatted for Django's ORM."""
query_dict = {self.composed_query_string(): self.parameter}
return Q(**query_dict)
def from_string(self, query_string):
"""Parse a string representing a filter.
Returns:
QueryFilter instance.
Args:
query_string (str) A string representing a query filter.
Example:
QueryFilter().from_string('mytable__myfield__contains')
"""
parts = query_string.split(self.SEP)
if len(parts) == 3:
self.table, self.field, self.operation = parts
elif len(parts) == 2:
self.table, self.operation = parts
else:
message = "Incorrect number of parts in query string. " + "Need at least two of [table, field, operation]."
raise TypeError(message)
return self
def __eq__(self, other):
"""Exact comparison."""
return self.data == other.data and self.logical_operator == other.logical_operator
def __lt__(self, other):
"""Decide if self < other."""
return str(self.data) < str(other.data)
def __repr__(self):
"""Return string representation."""
return str(self.composed_Q())
class QueryFilterCollection:
"""Object representing a set of filters for a query.
This object behaves in list-like ways.
"""
def __init__(self, filters=None):
"""Constructor.
Args:
filters (list) a list of QueryFilter instances.
"""
if filters is None:
self._filters = list() # a list of QueryFilter objects
else:
if not isinstance(filters, list):
raise TypeError("filters must be a list")
if not all(isinstance(item, QueryFilter) for item in filters):
raise TypeError("Filters list must contain QueryFilters.")
self._filters = filters
def add(self, query_filter=None, table=None, field=None, operation=None, parameter=None):
"""Add a query filter to the collection.
QueryFilterCollection does try to maintain filter uniqueness. A new
object will not be added to the collection if it already exists.
Args:
query_filter (QueryFilter) a QueryFilter object
- or -
table (str) db table name
field (str) db field/row name
operation (str) db operation
parameter (object) query object
"""
error_message = "query_filter can not be defined with other parameters"
if query_filter and (table or field or operation or parameter):
raise AttributeError(error_message)
if query_filter and query_filter not in self:
self._filters.append(query_filter)
if table or field or operation or parameter:
qf = QueryFilter(table=table, field=field, operation=operation, parameter=parameter)
if qf not in self:
self._filters.append(qf)
def compose(self, logical_operator=None):
"""Compose filters into a dict for submitting to Django's ORM.
Args:
logical_operator (str): 'and' or 'or' -- how to combine the filters.
"""
composed_query = None
compose_dict = defaultdict(list)
operator = "and"
if logical_operator == "or":
operator = "or"
for filt in self._filters:
filt_key = filt.compose_key()
compose_dict[filt_key].append(filt)
for filter_list in compose_dict.values():
or_filter = None
for filter_item in filter_list:
if or_filter is None:
or_filter = filter_item.composed_Q()
elif filter_item.logical_operator == "and":
or_filter = or_filter & filter_item.composed_Q()
else:
or_filter = or_filter | filter_item.composed_Q()
if composed_query is None:
composed_query = or_filter
else:
if operator == "or":
composed_query = composed_query | or_filter
else:
composed_query = composed_query & or_filter
return composed_query
def __contains__(self, item):
"""Return a boolean about whether `item` is in the collection.
This will do both an exact and a fuzzy match. Exact matches are
preferred over fuzzy matches. However, if there is no exact match,
__contains__ will return `True` if there is an object that contains all
of the same properties as `item`, even if additional properties are
set on the object in our collection. (See: `QueryFilterCollection.get()`)
Args:
item (QueryFilter or dict) object to search for.
Returns:
(bool) Whether a matching object was found.
"""
if isinstance(item, QueryFilter):
return item in self._filters
if isinstance(item, dict) and self.get(item):
return True
return False
def __eq__(self, other):
"""Exact comparison."""
return sorted(self._filters) == sorted(other._filters)
def __iter__(self):
"""Return an iterable of the collection."""
return self._filters.__iter__()
def __getitem__(self, key):
"""Return object identified by key.
Args:
key (int) the index of the QueryFilter to return.
"""
return self._filters[key]
def __repr__(self):
"""Return string representation."""
out = f"{self.__class__}: "
for filt in self._filters:
out += filt.__repr__() + ", "
return out
def __len__(self):
"""Return the length of the collection."""
return len(self._filters)
def delete(self, query_filter=None, table=None, field=None, operation=None, parameter=None):
"""Delete a query filter from the collection.
Args:
query_filter (QueryFilter) a QueryFilter object
- or -
table (str) db table name
field (str) db field/row name
operation (str) db operation
parameter (object) query object
"""
error_message = "query_filter can not be defined with other parameters"
if query_filter and (table or field or operation or parameter):
raise AttributeError(error_message)
if query_filter and query_filter in self:
self._filters.remove(query_filter)
if table or field or operation or parameter:
qf = QueryFilter(table=table, field=field, operation=operation, parameter=parameter)
if qf in self:
self._filters.remove(qf)
def get(self, search):
"""Retrieve the first matching filter in the collection.
This is a "fuzzy" search. This method looks for an object that matches
all key-value pairs of `search` with an object in the collection. The
matched object may have additional properties set to a non-None value.
Args:
search (dict) A dictionary of filter parameters to search for.
Example:
These examples are in order of least-specific (most likely to have
more than one result) to most-specific (most likely to have exactly
one result).
QueryFilterCollection.get({'operation': 'contains'})
QueryFilterCollection.get({'table': 'mytable', 'operation': 'gte'})
QueryFilterCollection.get({'table': 'mytable',
'field': 'myfield',
'operation': 'in'})
"""
for idx, filt in enumerate(self._filters):
filter_values = [filt.get(key) for key in search.keys() if filt.get(key)]
search_values = [search.get(key) for key in search.keys() if search.get(key)]
filter_values.sort()
search_values.sort()
if search_values == filter_values:
return (idx, filt)
return None
| [
"[email protected]"
] | |
c0089d4e13429eddbfd3535a60745129cf124aa1 | 36a991ef95701fb8626e627380bafdb30a7b1e7e | /rogueone/app.py | 041c608bbc6106e14cb874c94e17877156fd9349 | [] | no_license | bjorngylling/rogue-one | a6a5bf4ff9a4d3dd03fd3411e65c11b4ce55146b | 0f2a96fec152085faf8f5a55bbd7ea536a3a4cba | refs/heads/master | 2021-05-04T11:07:56.484070 | 2017-01-04T18:50:52 | 2017-01-04T18:50:52 | 47,639,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,583 | py | import tdl
import esper
import operator
from rogueone import components, processors, constants
MOVEMENT_OPS = {
'UP': (0, -1), 'DOWN': (0, 1),
'LEFT': (-1, 0), 'RIGHT': (1, 0),
'K': (0, -1), 'J': (0, 1),
'H': (-1, 0), 'L': (1, 0)
}
class RogueOneApp(tdl.event.App):
def __init__(self, renderer):
super().__init__()
self.renderer = renderer
self.generate_map()
self.setup_world()
def setup_world(self):
self.world = esper.World()
self.player = self.world.create_entity(
components.Collision(),
components.Position(1, 1),
components.Velocity(),
components.Renderable("@"))
self.world.create_entity(
components.Collision(),
components.Position(1, 3),
components.Velocity(),
components.Renderable("k"))
self.world.add_processor(
processors.CollisionProcessor(self.player, self.map_sections),
priority=100)
self.world.add_processor(processors.MovementProcessor(), priority=90)
self.world.add_processor(
processors.RenderProcessor(self.renderer,
self.player,
self.map_sections), priority=0)
def generate_map(self):
map_section = Map(80, 50)
for x, y in map_section:
wall = False
if ((x, y) in [(4, 4), (4, 5), (4, 6), (5, 7)]):
wall = True
map_section.transparent[x, y] = not wall
map_section.walkable[x, y] = not wall
self.map_sections = [map_section]
def ev_QUIT(self, ev):
raise SystemExit('The window has been closed.')
def key_ESCAPE(self, ev):
raise SystemExit('The window has been closed.')
def ev_KEYDOWN(self, ev):
if ev.keychar.upper() in MOVEMENT_OPS:
vel = self.world.component_for_entity(self.player,
components.Velocity)
dx, dy = MOVEMENT_OPS[ev.keychar.upper()]
vel.dx += dx
vel.dy += dy
def update(self, dt):
self.world.process()
tdl.flush()
class Map(tdl.map.Map):
def char_for_pos(self, x, y):
if self.walkable[x, y]:
return '.'
else:
return '#'
def color_for_pos(self, x, y):
if self.walkable[x, y]:
return (constants.COLOR_FLOOR, constants.COLOR_BG)
else:
return (constants.COLOR_WALLS, constants.COLOR_BG)
| [
"[email protected]"
] | |
3b5a3c2a5e7b93866aeb318a63e99e7a0a60442d | 3d285ed6f52046a26489f2f56b9b4b428c6fafa0 | /python/codewars/3.py | 382f773b1687080fcd050116d1a98319595f92a4 | [] | no_license | rayray2002/TPE-2014 | 761a2a1d75210902485038013a29b259817c664d | a5d0b844e146d14abd7e30d13a6d9bca03c85d5a | refs/heads/master | 2021-01-17T09:19:53.064534 | 2016-06-10T05:26:14 | 2016-06-10T05:26:14 | 30,918,698 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 656 | py | import sys
def num_3():
try:
line = raw_input("")
while(line):
error = 0
index = []
for l in line:
index.append(l)
if index[0] == 'A':
index[0] = 1
elif index[0] == 'E':
index[0] = 9
elif index[0] == 'P':
index[0] = 17
elif index[0] == 'M':
index[0] = 25
else:
error = 1
if error == 1:
print "Fail"
line = raw_input("")
break
sum = 0
for i in range(7):
sum += int(index[i+1])*(i+1)
sum = (index[0]+sum)%10
if (10-sum) == int(index[8]):
print "Success"
else:
print "Fail"
line = raw_input("")
except EOFError:
pass
if __name__ == "__main__":
num_3() | [
"[email protected]"
] | |
bfce6d92e26a13ffda213cbf8f8760f5cd2af773 | d700b9ad1e0b7225871b65ce0dafb27fb408c4bc | /students/k3343/laboratory_works/Lukina_Anastasia/laboratiry_work_1/lab1/main_interface/migrations/0010_comment_date.py | 1a0a412cd86cc443cebea13bbf56d096f9f8b57f | [
"MIT"
] | permissive | TonikX/ITMO_ICT_WebProgramming_2020 | a8c573ed467fdf99327777fb3f3bfeee5714667b | ba566c1b3ab04585665c69860b713741906935a0 | refs/heads/master | 2023-01-11T22:10:17.003838 | 2020-10-22T11:22:03 | 2020-10-22T11:22:03 | 248,549,610 | 10 | 71 | MIT | 2023-01-28T14:04:21 | 2020-03-19T16:18:55 | Python | UTF-8 | Python | false | false | 391 | py | # Generated by Django 2.1.5 on 2020-04-12 10:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_interface', '0009_comment_user'),
]
operations = [
migrations.AddField(
model_name='comment',
name='date',
field=models.DateField(default='2020-01-01'),
),
]
| [
"[email protected]"
] | |
9bfadc0aa24176d22eca17f59c51ca6447754978 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/86/usersdata/174/58567/submittedfiles/pico.py | aa9fa8881f25a79c86d6262d2c18c92b63d05e8a | [] | 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 | 557 | py | # -*- coding: utf-8 -*-
def pico(lista):
cont=0
for i in range(0,len(lista)-1,1):
if a[i]<a[i+1]:
cont=cont+1
y=len(lista)/2
for i in range(0,len(lista)-1,1):
if i>=y:
if a[i]>a[i+1]:
cont=cont+1
if cont==len(lista)-1:
return True
else:
return False
n = int(input('Digite a quantidade de elementos da lista: ')
a=[]
for i in range(1,n+1,1):
a.append(int(input('Digite os valores:' )))
if pico(a):
print('S')
else:
print('N') | [
"[email protected]"
] | |
a800e838f3bf2ca1c44ee2657132a33488f50b84 | 8a4ded6b300e28278a8b1f952209fd3b2ae4af5e | /huTools/huTools/http/tools.py | d1affa9f40a713342ef16afa578b48f21eab7458 | [] | no_license | mario206/jsNaughty | 8bb76c0f37f6d1d1e1b675d4a360d53f4c405cbb | a5d46d2bddedf7dbc708166b1777ac96b51056bb | refs/heads/master | 2020-04-02T06:25:06.811612 | 2017-05-08T20:42:15 | 2017-05-08T20:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,544 | py | #!/usr/bin/env python
# encoding: utf-8
"""
tools.py - various helpers for HTTP access
Created by Maximillian Dornseif on 2010-10-24.
Copyright (c) 2010, 2011 HUDORA. All rights reserved.
"""
# quoting based on
# http://svn.python.org/view/python/branches/release27-maint/Lib/urllib.py?view=markup&pathrev=82940
# by Matt Giuca
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-')
_safe_map = {}
for i, c in zip(xrange(256), [chr(x) for x in xrange(256)]):
_safe_map[c] = c if (i < 128 and c in always_safe) else ('%%%02X' % i)
_safe_quoters = {}
def quote(s, safe='/', encoding=None, errors=None):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
Each of these characters is reserved in some component of a URL,
but not necessarily in all of them.
By default, the quote function is intended for quoting the path
section of a URL. Thus, it will not encode '/'. This character
is reserved, but in typical usage the quote function is being
called on a path where the existing slash characters are used as
reserved characters.
string and safe may be either str or unicode objects.
The optional encoding and errors parameters specify how to deal with the
non-ASCII characters, as accepted by the unicode.encode method.
By default, encoding='utf-8' (characters are encoded with UTF-8), and
errors='strict' (unsupported characters raise a UnicodeEncodeError).
"""
# fastpath
if not s:
return s
if encoding is not None or isinstance(s, unicode):
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'strict'
s = s.encode(encoding, errors)
if isinstance(safe, unicode):
# Normalize 'safe' by converting to str and removing non-ASCII chars
safe = safe.encode('ascii', 'ignore')
cachekey = (safe, always_safe)
try:
(quoter, safe) = _safe_quoters[cachekey]
except KeyError:
safe_map = _safe_map.copy()
safe_map.update([(c, c) for c in safe])
quoter = safe_map.__getitem__
safe = always_safe + safe
_safe_quoters[cachekey] = (quoter, safe)
if not s.rstrip(safe):
return s
return ''.join(map(quoter, s))
def quote_plus(s, safe='', encoding=None, errors=None):
"""Quote the query fragment of a URL; replacing ' ' with '+'"""
if ' ' in s:
s = quote(s, safe + ' ', encoding, errors)
return s.replace(' ', '+')
return quote(s, safe, encoding, errors)
def urlencode(query):
"""Encode a sequence of two-element tuples or dictionary into a URL query string.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.
"""
if hasattr(query, 'items'):
# mapping objects
query = query.items()
l = []
for k, v in query:
k = quote_plus(k)
if isinstance(v, basestring):
v = quote_plus(v)
l.append(k + '=' + v)
else:
v = quote_plus(unicode(v))
l.append(k + '=' + v)
return '&'.join(l)
| [
"[email protected]"
] | |
8a45390e0f4d118d9f5af08c0a5bb57aa75506ae | e49f078323bc2064e18be25b57718d682c72dcb7 | /WEEK 1/ArunimSamudra/nested list.py | 16bb13a667cee9783ba8ac153300e3114999e022 | [] | no_license | aarohikulkarni10/ML-winter-mentorship | b0c1c72a5c65a65bb61cd2a3e411adb00c083a98 | cfd89de881245c7185f2aabcd44c463ca3743608 | refs/heads/master | 2020-11-27T10:41:05.455031 | 2020-01-17T18:53:52 | 2020-01-17T18:53:52 | 229,408,456 | 0 | 0 | null | 2019-12-21T09:58:05 | 2019-12-21T09:58:04 | null | UTF-8 | Python | false | false | 562 | py | if __name__ == '__main__':
arr = []
sc = []
for _ in range(int(input())):
name = input()
score = float(input())
sc.append(score)
x = [name,score]
arr.append(x)
sc.sort(reverse=True)
max = sc[len(sc)-1]
max2 = sc[0]
for i in range(len(sc)):
if sc[i] < max2 and sc[i] > max:
max2 = sc[i]
n = []
for i in range(len(arr)):
if arr[i][1] == max2:
n.append(arr[i][0])
n.sort()
for i in range(len(n)):
print(n[i])
| [
"[email protected]"
] | |
a8bc33a1fe53741f61a2e8d07756e4b84438b931 | d09ccdaac3aa4acefb42f656dbd5eaaaa5e68eef | /limebet/profiles/models.py | 59052a632f72014d339be13fee6459991e94bb5e | [
"ISC"
] | permissive | Igordr1999/LimeBet | efb7fa83ce54c4414687e850e382e0d8194aadc8 | f19f69d76dccc147e87217142e56edf4e1eece04 | refs/heads/master | 2022-12-13T13:13:40.466023 | 2020-01-29T14:00:26 | 2020-01-29T14:00:26 | 236,992,986 | 4 | 1 | null | 2022-12-08T03:33:18 | 2020-01-29T13:51:07 | Python | UTF-8 | Python | false | false | 173 | py | from django.contrib.auth.models import AbstractUser, UserManager
class ProfileManager(UserManager):
pass
class Profile(AbstractUser):
objects = ProfileManager()
| [
"[email protected]"
] | |
9731cdcdf05e9cec4dd1d32d5b4fe92c24477c57 | 223f232bcbe5f34c07485ef005558dda10a95554 | /Backend/node_modules/fibers/build/config.gypi | 6b5ff94c1b7dc684fae1716a92bbec1d2a726688 | [
"Apache-2.0",
"MIT"
] | permissive | sbenstewart/peekabook | 6c32ff29363b23ccdcbcff391cb95cf42763ddfe | 906796e2b375f8abcffd23d64d9d79ae0abbdab5 | refs/heads/master | 2020-03-23T08:06:05.867572 | 2020-01-18T05:28:11 | 2020-01-18T05:28:11 | 141,307,597 | 0 | 2 | Apache-2.0 | 2020-01-18T05:28:34 | 2018-07-17T15:17:35 | CSS | UTF-8 | Python | false | false | 5,188 | gypi | # Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"asan": 0,
"build_v8_with_gn": "false",
"coverage": "false",
"debug_http2": "false",
"debug_nghttp2": "false",
"force_dynamic_crt": 0,
"gas_version": "2.27",
"host_arch": "x64",
"icu_data_in": "../../deps/icu-small/source/data/in/icudt61l.dat",
"icu_endianness": "l",
"icu_gyp_path": "tools/icu/icu-generic.gyp",
"icu_locales": "en,root",
"icu_path": "deps/icu-small",
"icu_small": "true",
"icu_ver_major": "61",
"llvm_version": 0,
"node_byteorder": "little",
"node_debug_lib": "false",
"node_enable_d8": "false",
"node_enable_v8_vtunejit": "false",
"node_install_npm": "true",
"node_module_version": 64,
"node_no_browser_globals": "false",
"node_prefix": "/",
"node_release_urlbase": "https://nodejs.org/download/release/",
"node_shared": "false",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_nghttp2": "false",
"node_shared_openssl": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_target_type": "executable",
"node_use_bundled_v8": "true",
"node_use_dtrace": "false",
"node_use_etw": "false",
"node_use_openssl": "true",
"node_use_perfctr": "false",
"node_use_v8_platform": "true",
"node_without_node_options": "false",
"openssl_fips": "",
"openssl_no_asm": 0,
"shlib_suffix": "so.64",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_enable_i18n_support": 1,
"v8_enable_inspector": 1,
"v8_no_strict_aliasing": 1,
"v8_optimized_debug": 0,
"v8_promise_internal_field_count": 1,
"v8_random_seed": 0,
"v8_trace_maps": 0,
"v8_typed_array_max_size_in_heap": 0,
"v8_use_snapshot": "true",
"want_separate_host_toolset": 0,
"nodedir": "/home/nandy/.node-gyp/10.1.0",
"standalone_static_library": 1,
"cache_lock_stale": "60000",
"ham_it_up": "",
"legacy_bundling": "",
"sign_git_tag": "",
"user_agent": "npm/5.6.0 node/v10.1.0 linux x64",
"always_auth": "",
"bin_links": "true",
"key": "",
"allow_same_version": "",
"description": "true",
"fetch_retries": "2",
"heading": "npm",
"if_present": "",
"init_version": "1.0.0",
"user": "1000",
"prefer_online": "",
"force": "",
"only": "",
"read_only": "",
"cache_min": "10",
"init_license": "ISC",
"editor": "vi",
"rollback": "true",
"tag_version_prefix": "v",
"cache_max": "Infinity",
"timing": "",
"userconfig": "/home/nandy/.npmrc",
"engine_strict": "",
"init_author_name": "",
"init_author_url": "",
"tmp": "/tmp",
"depth": "Infinity",
"package_lock_only": "",
"save_dev": "",
"usage": "",
"metrics_registry": "https://registry.npmjs.org/",
"otp": "",
"package_lock": "true",
"progress": "true",
"https_proxy": "",
"save_prod": "",
"cidr": "",
"onload_script": "",
"sso_type": "oauth",
"rebuild_bundle": "true",
"save_bundle": "",
"shell": "/bin/bash",
"dry_run": "",
"prefix": "/home/nandy/.nvm/versions/node/v10.1.0",
"scope": "",
"browser": "",
"cache_lock_wait": "10000",
"ignore_prepublish": "",
"registry": "https://registry.npmjs.org/",
"save_optional": "",
"searchopts": "",
"versions": "",
"cache": "/home/nandy/.npm",
"send_metrics": "",
"global_style": "",
"ignore_scripts": "",
"version": "",
"local_address": "",
"viewer": "man",
"node_gyp": "/home/nandy/.nvm/versions/node/v10.1.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js",
"prefer_offline": "",
"color": "true",
"fetch_retry_mintimeout": "10000",
"maxsockets": "50",
"offline": "",
"sso_poll_frequency": "500",
"umask": "0002",
"fetch_retry_maxtimeout": "60000",
"logs_max": "10",
"message": "%s",
"ca": "",
"cert": "",
"global": "",
"link": "",
"access": "",
"also": "",
"save": "true",
"unicode": "",
"long": "",
"production": "",
"searchlimit": "20",
"unsafe_perm": "true",
"auth_type": "legacy",
"node_version": "10.1.0",
"tag": "latest",
"git_tag_version": "true",
"commit_hooks": "true",
"script_shell": "",
"shrinkwrap": "true",
"fetch_retry_factor": "10",
"save_exact": "",
"strict_ssl": "true",
"dev": "",
"globalconfig": "/home/nandy/.nvm/versions/node/v10.1.0/etc/npmrc",
"init_module": "/home/nandy/.npm-init.js",
"parseable": "",
"globalignorefile": "/home/nandy/.nvm/versions/node/v10.1.0/etc/npmignore",
"cache_lock_retries": "10",
"searchstaleness": "900",
"node_options": "",
"save_prefix": "^",
"scripts_prepend_node_path": "warn-only",
"group": "1000",
"init_author_email": "",
"searchexclude": "",
"git": "git",
"optional": "true",
"json": ""
}
}
| [
"[email protected]"
] | |
aad39cf1261bc40afcf30799fd0f03423b9754b8 | 49ff6718d9f956de0f8511db88d61d55df21ec8b | /cxxopts/conanfile.py | da15b5cf71f6fd3702e473fd493d2f893234b187 | [] | no_license | borgmanJeremy/emulator8080 | 9db0513d5c7907316b90dea9cd6e1e63b45547c3 | d76c9814addbb96ef0173c28fd842ee18f2ffd3f | refs/heads/master | 2020-08-22T13:14:29.614486 | 2019-11-30T20:02:41 | 2019-12-06T23:05:38 | 216,402,695 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,293 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class CxxOptsConan(ConanFile):
name = "cxxopts"
version = "v2.2.0"
description = "Lightweight C++ command line option parser"
# topics can get used for searches, GitHub topics, Bintray tags etc. Add here keywords about the library
topics = ("conan", "cxxopts", "command line")
url = "https://github.com/inexorgame/conan-cxxopts"
homepage = "https://github.com/jarro2783/cxxopts"
author = "Inexor <[email protected]>"
license = "MIT" # Indicates license type of the packaged library; please use SPDX Identifiers https://spdx.org/licenses/
no_copy_source = True
# Packages the license for the conanfile.py
exports = ["LICENSE.md"]
# Custom attributes for Bincrafters recipe conventions
_source_subfolder = "cxxopts"
def source(self):
git = tools.Git(folder=self._source_subfolder)
git.clone("https://github.com/jarro2783/cxxopts")
git.checkout(self.version)
def build(self):
cmake = CMake(self)
cmake.configure(source_folder="cxxopts")
cmake.build()
def package(self):
cmake = CMake(self)
cmake.configure(source_folder="cxxopts")
cmake.install()
| [
"[email protected]"
] | |
d6a21ad4df33ff3c0f412dc4bb2b10c3a3d4763d | 5e10458a85d9469184f5d9a3afa197d1f1ba61d8 | /django_web_app/django_web_app/settings.py | 90388987d56d74b6621ecda81267a707c79da985 | [] | no_license | Atilla45/FileSharing | 663efc6a7d21568820561750a8abff3fbe332920 | ac443928318ca4b4c414ee16eb6fdb44d2374393 | refs/heads/master | 2023-02-18T14:02:01.992803 | 2021-01-13T20:58:09 | 2021-01-13T20:58:09 | 328,118,970 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,508 | py | """
Django settings for django_web_app project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@5&-q%^o=@mb@=@e%b9yz^b#l-2)w&_s0ick#=wy3kw36$z($g'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'users.apps.UsersConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
'channels',
'django_celery_beat',
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
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 = 'django_web_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_web_app.wsgi.application'
ASGI_APPLICATION = 'django_web_app.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'TEST': {
'NAME': os.path.join(BASE_DIR, 'db_test.sqlite3')
}
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT= os.path.join(BASE_DIR, 'static'),
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'blog-home'
LOGIN_URL = 'login'
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
}
}
# django setting.
BROKER_URL='redis://localhost:6379/0'
logging = 'DEBUG' | [
"[email protected]"
] | |
c99f2a2863ba58406fc25d8b515b61a03613fede | 10b70a3ca9932d0db56a259a2ac5cea51d3e1b2e | /runner/runs/paper_doom_battle_appo.py | a2c06c4eed1c72474c31e20f873b5fc11cd83ad5 | [
"MIT"
] | permissive | gitter-badger/sample-factory | cfddd2d4df5276267f0f5396a91d97ad54bcf831 | 65660239c43c18a3c5e280a654017be1701e6e86 | refs/heads/master | 2022-11-21T18:14:30.308816 | 2020-07-28T06:01:04 | 2020-07-28T06:01:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 660 | py | from runner.run_description import RunDescription, Experiment, ParamGrid
_params = ParamGrid([
('seed', [1111, 2222, 3333, 4444]),
])
_experiments = [
Experiment(
'battle_fs4',
'python -m algorithms.appo.train_appo --env=doom_battle --train_for_env_steps=4000000000 --algo=APPO --env_frameskip=4 --use_rnn=True --num_workers=72 --num_envs_per_worker=8 --num_policies=1 --ppo_epochs=1 --rollout=32 --recurrence=32 --batch_size=2048 --wide_aspect_ratio=False --max_grad_norm=0.0',
_params.generate_params(randomize=False),
),
]
RUN_DESCRIPTION = RunDescription('paper_doom_battle_appo_v102_fs4', experiments=_experiments)
| [
"[email protected]"
] | |
cac24c8abe1ad0130881d912cd3a6f7ace5a0584 | fbbe424559f64e9a94116a07eaaa555a01b0a7bb | /Tensorflow_Pandas_Numpy/source3.6/tensorflow/contrib/distributions/python/ops/mvn_diag_plus_low_rank.py | ee3e02e0203a3338b7e6a40b7e3ff30c0a0940f0 | [
"MIT"
] | permissive | ryfeus/lambda-packs | 6544adb4dec19b8e71d75c24d8ed789b785b0369 | cabf6e4f1970dc14302f87414f170de19944bac2 | refs/heads/master | 2022-12-07T16:18:52.475504 | 2022-11-29T13:35:35 | 2022-11-29T13:35:35 | 71,386,735 | 1,283 | 263 | MIT | 2022-11-26T05:02:14 | 2016-10-19T18:22:39 | Python | UTF-8 | Python | false | false | 9,726 | py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Multivariate Normal distribution classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import linalg
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.contrib.distributions.python.ops import mvn_linear_operator as mvn_linop
from tensorflow.python.framework import ops
__all__ = [
"MultivariateNormalDiagPlusLowRank",
]
class MultivariateNormalDiagPlusLowRank(
mvn_linop.MultivariateNormalLinearOperator):
"""The multivariate normal distribution on `R^k`.
The Multivariate Normal distribution is defined over `R^k` and parameterized
by a (batch of) length-`k` `loc` vector (aka "mu") and a (batch of) `k x k`
`scale` matrix; `covariance = scale @ scale.T` where `@` denotes
matrix-multiplication.
#### Mathematical Details
The probability density function (pdf) is,
```none
pdf(x; loc, scale) = exp(-0.5 ||y||**2) / Z,
y = inv(scale) @ (x - loc),
Z = (2 pi)**(0.5 k) |det(scale)|,
```
where:
* `loc` is a vector in `R^k`,
* `scale` is a linear operator in `R^{k x k}`, `cov = scale @ scale.T`,
* `Z` denotes the normalization constant, and,
* `||y||**2` denotes the squared Euclidean norm of `y`.
A (non-batch) `scale` matrix is:
```none
scale = diag(scale_diag + scale_identity_multiplier ones(k)) +
scale_perturb_factor @ diag(scale_perturb_diag) @ scale_perturb_factor.T
```
where:
* `scale_diag.shape = [k]`,
* `scale_identity_multiplier.shape = []`,
* `scale_perturb_factor.shape = [k, r]`, typically `k >> r`, and,
* `scale_perturb_diag.shape = [r]`.
Additional leading dimensions (if any) will index batches.
If both `scale_diag` and `scale_identity_multiplier` are `None`, then
`scale` is the Identity matrix.
The MultivariateNormal distribution is a member of the [location-scale
family](https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be
constructed as,
```none
X ~ MultivariateNormal(loc=0, scale=1) # Identity scale, zero shift.
Y = scale @ X + loc
```
#### Examples
```python
ds = tf.contrib.distributions
# Initialize a single 3-variate Gaussian with covariance `cov = S @ S.T`,
# `S = diag(d) + U @ diag(m) @ U.T`. The perturbation, `U @ diag(m) @ U.T`, is
# a rank-2 update.
mu = [-0.5., 0, 0.5] # shape: [3]
d = [1.5, 0.5, 2] # shape: [3]
U = [[1., 2],
[-1, 1],
[2, -0.5]] # shape: [3, 2]
m = [4., 5] # shape: [2]
mvn = ds.MultivariateNormalDiagPlusLowRank(
loc=mu
scale_diag=d
scale_perturb_factor=U,
scale_perturb_diag=m)
# Evaluate this on an observation in `R^3`, returning a scalar.
mvn.prob([-1, 0, 1]).eval() # shape: []
# Initialize a 2-batch of 3-variate Gaussians; `S = diag(d) + U @ U.T`.
mu = [[1., 2, 3],
[11, 22, 33]] # shape: [b, k] = [2, 3]
U = [[[1., 2],
[3, 4],
[5, 6]],
[[0.5, 0.75],
[1,0, 0.25],
[1.5, 1.25]]] # shape: [b, k, r] = [2, 3, 2]
m = [[0.1, 0.2],
[0.4, 0.5]] # shape: [b, r] = [2, 2]
mvn = ds.MultivariateNormalDiagPlusLowRank(
loc=mu,
scale_perturb_factor=U,
scale_perturb_diag=m)
mvn.covariance().eval() # shape: [2, 3, 3]
# ==> [[[ 15.63 31.57 48.51]
# [ 31.57 69.31 105.05]
# [ 48.51 105.05 162.59]]
#
# [[ 2.59 1.41 3.35]
# [ 1.41 2.71 3.34]
# [ 3.35 3.34 8.35]]]
# Compute the pdf of two `R^3` observations (one from each batch);
# return a length-2 vector.
x = [[-0.9, 0, 0.1],
[-10, 0, 9]] # shape: [2, 3]
mvn.prob(x).eval() # shape: [2]
```
"""
def __init__(self,
loc=None,
scale_diag=None,
scale_identity_multiplier=None,
scale_perturb_factor=None,
scale_perturb_diag=None,
validate_args=False,
allow_nan_stats=True,
name="MultivariateNormalDiagPlusLowRank"):
"""Construct Multivariate Normal distribution on `R^k`.
The `batch_shape` is the broadcast shape between `loc` and `scale`
arguments.
The `event_shape` is given by last dimension of the matrix implied by
`scale`. The last dimension of `loc` (if provided) must broadcast with this.
Recall that `covariance = scale @ scale.T`. A (non-batch) `scale` matrix is:
```none
scale = diag(scale_diag + scale_identity_multiplier ones(k)) +
scale_perturb_factor @ diag(scale_perturb_diag) @ scale_perturb_factor.T
```
where:
* `scale_diag.shape = [k]`,
* `scale_identity_multiplier.shape = []`,
* `scale_perturb_factor.shape = [k, r]`, typically `k >> r`, and,
* `scale_perturb_diag.shape = [r]`.
Additional leading dimensions (if any) will index batches.
If both `scale_diag` and `scale_identity_multiplier` are `None`, then
`scale` is the Identity matrix.
Args:
loc: Floating-point `Tensor`. If this is set to `None`, `loc` is
implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where
`b >= 0` and `k` is the event size.
scale_diag: Non-zero, floating-point `Tensor` representing a diagonal
matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`,
and characterizes `b`-batches of `k x k` diagonal matrices added to
`scale`. When both `scale_identity_multiplier` and `scale_diag` are
`None` then `scale` is the `Identity`.
scale_identity_multiplier: Non-zero, floating-point `Tensor` representing
a scaled-identity-matrix added to `scale`. May have shape
`[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled
`k x k` identity matrices added to `scale`. When both
`scale_identity_multiplier` and `scale_diag` are `None` then `scale` is
the `Identity`.
scale_perturb_factor: Floating-point `Tensor` representing a rank-`r`
perturbation added to `scale`. May have shape `[B1, ..., Bb, k, r]`,
`b >= 0`, and characterizes `b`-batches of rank-`r` updates to `scale`.
When `None`, no rank-`r` update is added to `scale`.
scale_perturb_diag: Floating-point `Tensor` representing a diagonal matrix
inside the rank-`r` perturbation added to `scale`. May have shape
`[B1, ..., Bb, r]`, `b >= 0`, and characterizes `b`-batches of `r x r`
diagonal matrices inside the perturbation added to `scale`. When
`None`, an identity matrix is used inside the perturbation. Can only be
specified if `scale_perturb_factor` is also specified.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
ValueError: if at most `scale_identity_multiplier` is specified.
"""
parameters = locals()
def _convert_to_tensor(x, name):
return None if x is None else ops.convert_to_tensor(x, name=name)
with ops.name_scope(name):
with ops.name_scope("init", values=[
loc, scale_diag, scale_identity_multiplier, scale_perturb_factor,
scale_perturb_diag]):
has_low_rank = (scale_perturb_factor is not None or
scale_perturb_diag is not None)
scale = distribution_util.make_diag_scale(
loc=loc,
scale_diag=scale_diag,
scale_identity_multiplier=scale_identity_multiplier,
validate_args=validate_args,
assert_positive=has_low_rank)
scale_perturb_factor = _convert_to_tensor(
scale_perturb_factor,
name="scale_perturb_factor")
scale_perturb_diag = _convert_to_tensor(
scale_perturb_diag,
name="scale_perturb_diag")
if has_low_rank:
scale = linalg.LinearOperatorUDVHUpdate(
scale,
u=scale_perturb_factor,
diag_update=scale_perturb_diag,
is_diag_update_positive=scale_perturb_diag is None,
is_non_singular=True, # Implied by is_positive_definite=True.
is_self_adjoint=True,
is_positive_definite=True,
is_square=True)
super(MultivariateNormalDiagPlusLowRank, self).__init__(
loc=loc,
scale=scale,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=name)
self._parameters = parameters
| [
"[email protected]"
] | |
bb1662f34b1e825d918edbf0a75eabd6e5a58ea1 | cf5e1a31131ca71f981ab1935443f3c22ebbb0f9 | /sensors/runfolder_sensor.py | dc41a9ab02f3a5c9d2d8bc29cfaf88103460f84f | [
"MIT"
] | permissive | arteria-project/arteria-packs | e6def02f35d1222adb884153f84591079a2c6eaf | 9960286f9f5c190c9558d9b47438899a73db2903 | refs/heads/master | 2022-12-14T11:48:56.398390 | 2022-12-06T11:46:33 | 2022-12-06T11:46:33 | 37,130,995 | 9 | 21 | MIT | 2022-12-06T11:46:34 | 2015-06-09T12:36:27 | Python | UTF-8 | Python | false | false | 2,629 | py | from st2reactor.sensor.base import PollingSensor
from runfolder_client import RunfolderClient
from datetime import datetime
import yaml
import os
class RunfolderSensor(PollingSensor):
def __init__(self, sensor_service, config=None, poll_interval=None, trigger='arteria.runfolder_ready'):
super(RunfolderSensor, self).__init__(sensor_service=sensor_service,
config=config,
poll_interval=poll_interval)
self._logger = self._sensor_service.get_logger(__name__)
self._infolog("__init__")
self._client = None
self._trigger = trigger
self._hostconfigs = {}
def setup(self):
self._infolog("setup")
client_urls = self._config["runfolder_service_url"]
self._client = RunfolderClient(client_urls, self._logger)
self._infolog("Created client: {0}".format(self._client))
self._infolog("setup finished")
def poll(self):
self._infolog("poll")
self._infolog("Checking for available runfolders")
result = self._client.next_ready()
self._infolog("Result from client: {0}".format(result))
if result:
self._handle_result(result)
def cleanup(self):
self._infolog("cleanup")
def add_trigger(self, trigger):
self._infolog("add_trigger")
def update_trigger(self, trigger):
self._infolog("update_trigger")
def remove_trigger(self, trigger):
self._infolog("remove_trigger")
def _handle_result(self, result):
self._infolog("_handle_result")
trigger = self._trigger
runfolder_path = result['response']['path']
runfolder_name = os.path.split(runfolder_path)[1]
payload = {
'host': result['response']['host'],
'runfolder': runfolder_path,
'runfolder_name': runfolder_name,
'link': result['response']['link'],
'timestamp': datetime.utcnow().isoformat(),
'destination': ""
}
if result['requesturl'] in self._hostconfigs:
payload['destination'] = self._hostconfigs[result['requesturl']].get('dest_folder', "")
payload['remote_user'] = self._hostconfigs[result['requesturl']].get('remote_user', "")
payload['user_key'] = self._hostconfigs[result['requesturl']].get('user_key', "")
self._sensor_service.dispatch(trigger=trigger, payload=payload, trace_tag=runfolder_name)
def _infolog(self, msg):
self._logger.info("[arteria-packs." + self.__class__.__name__ + "] " + msg)
| [
"[email protected]"
] | |
b8fb59d5c971f596df5980d04781e292bfc41822 | 719024856effd0f00d7700268e8e555f8613d0dd | /common_conception/generator.py | 0dc52f6865b6e54d721b92c570f26a487d5ca551 | [] | no_license | Hydracoe/my_python_memorial | cf7d2d1356f8defc5e0d3a97a25c9d4bde9d9023 | 5c47b421842bcb9ed41f1577b56ca2c5c2bfde18 | refs/heads/master | 2020-04-09T01:25:44.703242 | 2019-01-10T22:09:46 | 2019-01-10T22:09:46 | 159,903,786 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 689 | py | def test():
"""
协程,又称微线程,英文名Coroutine,是运行在单线程中的“并发”
协程相比多线程的一大优势就是省去了多线程之间的切换开销,获得了更高的运行效率。
Python中的异步IO模块asyncio就是基本的协程模块。
但是需要注意的是,多线程和协程的区别在于,协程是单一函数的执行!
程序员通过高超的代码能力,在代码执行流程中人为的实现多任务并发,是单个线程内的任务调度技巧
:return:
"""
n = 1
n += 1
yield n
if __name__ == '__main__':
T = test()
print(T)
print(next(T))
try:
print(next(T))
except StopIteration as _:
pass
| [
"[email protected]"
] | |
8e5abca6dd719d84956159c19ad32d152f66228d | b6d48defc1d5359ee351403b0906b6beb6cb64a7 | /tensorflow2/class6/tensorflow2_mnist_callback_tb.py | eb764bccac78765afcc1a6c624d310f41948ed21 | [
"Apache-2.0"
] | permissive | CrazyVertigo/SimpleCVReproduction | 2c6d2d23b0e234d976eefbdb56d6460798559b0d | 9699f600e6cde89ad0002ca552f8b6119e96990c | refs/heads/master | 2022-09-24T16:29:33.263625 | 2020-06-03T14:53:18 | 2020-06-03T14:53:18 | 269,344,314 | 1 | 0 | Apache-2.0 | 2020-06-04T11:43:10 | 2020-06-04T11:43:09 | null | UTF-8 | Python | false | false | 2,535 | py | import math
import numpy as np
from sklearn import preprocessing, model_selection, svm
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import datetime
import tensorflow as tf
from tensorflow.keras.utils import plot_model
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train[:, :, :, np.newaxis]
x_test = x_test[:, :, :, np.newaxis]
n_classes = 10
y_train = tf.keras.utils.to_categorical(y_train, n_classes)
y_test = tf.keras.utils.to_categorical(y_test, n_classes)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
inputs = tf.keras.Input(shape=(28, 28, 1), name='data')
x = tf.keras.layers.Conv2D(6, kernel_size=(5, 5), strides=(1, 1), activation='relu', padding='same')(inputs)
x = tf.keras.layers.MaxPooling2D(2,strides=(2,2))(x)
x = tf.keras.layers.Conv2D(16, kernel_size=(5, 5), strides=(1, 1), activation='relu', padding='valid')(x)
x = tf.keras.layers.MaxPooling2D(2,strides=(2,2))(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(120, activation='relu')(x)
#p1. all zeros initialization
#x = tf.keras.layers.Dense(84, activation='relu',kernel_initializer='zeros',bias_initializer='zeros')(x)
x = tf.keras.layers.Dense(84, activation='relu')(x)
#p2. no softmax
#outputs = tf.keras.layers.Dense(n_classes)(x)
outputs = tf.keras.layers.Dense(n_classes, activation='softmax')(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs, name='lenet')
plot_model(model,'lenet.png',show_shapes=True,expand_nested=True,rankdir='TB')
model.summary()
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),
loss=tf.keras.losses.categorical_crossentropy,
metrics=['accuracy']
)
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="fit_logs\\", histogram_freq=1)
history =model.fit(x_train, y_train, batch_size=100, epochs=20, validation_data=(x_test, y_test), callbacks=[tensorboard_callback])
# 绘制训练 & 验证的准确率值
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show() | [
"[email protected]"
] | |
75bc25b2b8c947fe07aa8f0196c792c46e0a39da | 2c27de02cb39a71e66b9d7169d41d519c56087ea | /tensorflow_oop/bag_of_words.py | f41cb691de2e3197e68459eeab99e067f29cec62 | [] | no_license | ravil23/tensorflow_oop | d3188e224261c694e5f86d7e285408edc3deed52 | 5159cfc3c03b480dd8cfdc94ac89056fe9bbc46c | refs/heads/master | 2021-01-19T20:33:49.223795 | 2018-09-07T06:51:56 | 2018-09-07T06:51:56 | 101,228,195 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 5,514 | py | """
Bag of words.
"""
import numpy as np
from collections import Counter
import operator
class TFBagOfWords(object):
"""
Bag of words model.
Attributes:
size Dictionary length.
non_chars String with chars for excluding.
lower_case Indicator of case insensitive mode.
digit_as_zero Indicator of converting all digits to zero.
min_count Filter minimum words count for adding to dictionary.
max_count Filter maximum words count for adding to dictionary.
words_counter Counter object of all words in texts.
dictionary Dict object of correct words in texts.
"""
__slots__ = ['size',
'non_chars', 'lower_case', 'digit_as_zero',
'min_count', 'max_count',
'words_counter', 'dictionary']
def __init__(self,
texts,
non_chars=None,
lower_case=True,
digit_as_zero=True,
min_count=1,
max_count=np.inf):
"""Constructor.
Arguments:
texts List of texts for building dictionary.
non_chars String with chars for excluding.
lower_case Indicator of case insensitive mode.
digit_as_zero Indicator of converting all digits to zero.
min_count Filter minimum words count for adding to dictionary.
max_count Filter maximum words count for adding to dictionary.
"""
# Save properties
if non_chars is not None:
self.non_chars = non_chars
else:
self.non_chars = '/.,!?()_-";:*=&|%<>@\'\t\n\r'
self.lower_case = lower_case
self.digit_as_zero = digit_as_zero
self.min_count = min_count
self.max_count = max_count
# Calculate statistic
words = self.list_of_words(' '.join(texts))
self.words_counter = Counter(words)
# Calculate dictionary
self.dictionary = {}
for word in sorted(self.words_counter):
if self.min_count <= self.words_counter[word] <= self.max_count:
self.dictionary[word] = len(self.dictionary)
self.size = len(self.dictionary)
def list_of_words(self, text):
"""Get list of standart words from text.
Arguments:
text Text in string format.
Return:
words List of extracted words.
"""
words = self.preprocessing(text).split(' ')
if '' in words:
words.remove('')
return words
def vectorize(self, text, binary):
"""Calculate vector by text.
Arguments:
text Conversation text.
binary Indicator of using only {0, 1} instead rational from [0, 1].
Return:
vector Numeric representation vector.
"""
# Calculate statistic
words = self.list_of_words(text)
vector = np.zeros(self.size)
for word in words:
if word in self.dictionary:
index = self.dictionary[word]
if binary:
vector[index] = 1.
else:
vector[index] += 1.
# Validate data
valid_count = np.sum(vector)
assert valid_count > 0, \
'''Valid words count should be greater then zero:
valid_count = %s''' % valid_count
# Normalize if necessary
if not binary:
vector /= valid_count
return vector
def preprocessing(self, old_text):
"""Standartize text to one format.
Arguments:
old_text Text to preprocessing in string format.
Return:
new_text Processed text.
"""
if self.lower_case:
new_text = old_text.lower()
for non_char in self.non_chars:
new_text = new_text.replace(non_char, ' ')
if self.digit_as_zero:
for i in range(1, 10):
new_text = new_text.replace(str(i), '0')
while new_text.find(' ') >= 0:
new_text = new_text.replace(' ', ' ')
new_text = new_text.strip()
return new_text
def __len__(self):
"""Unique words count in dictionary."""
return self.size
def __str__(self):
"""String formatting."""
string = 'TFBagOfWords object:\n'
for attr in self.__slots__:
if attr != 'words_counter' and attr != 'dictionary':
string += '%20s: %s\n' % (attr, getattr(self, attr))
sorted_words_counter = sorted(self.words_counter.items(),
key=operator.itemgetter(1),
reverse=True)
string += '%20s:\n%s\n...\n%s\n' % ('words_counter',
'\n'.join([str(elem) for elem in sorted_words_counter[:10]]),
'\n'.join([str(elem) for elem in sorted_words_counter[-10:]]))
sorted_dictionary = sorted(self.dictionary.items(),
key=operator.itemgetter(0),
reverse=False)
string += '%20s:\n%s\n...\n%s\n' % ('dictionary',
'\n'.join([str(elem) for elem in sorted_dictionary[:10]]),
'\n'.join([str(elem) for elem in sorted_dictionary[-10:]]))
return string[:-1]
| [
"[email protected]"
] | |
c81ab3f9ab778e4417f35aefb8686598814c98e5 | b2646000cf8064bbddd1f609ec05f1f0038c29cf | /Rapsberry/catkin_ws/src/clips_ros/clips_node/ros_pyclips_node.py | 4ad626cab28dd2ee24d8849201894bfda340b897 | [] | no_license | Oscaryanezgomez/R2D2- | 2fc27a4b1979ed11341066a914840eb9204e18e6 | cc93663f5e815659a9f5f742ba71c6a8d41f7b64 | refs/heads/master | 2020-07-25T16:34:21.203034 | 2019-09-17T17:34:39 | 2019-09-17T17:34:39 | 208,356,674 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,483 | py | #!/usr/bin/env python
import time, threading, os
import Tkinter as tk
import clipsFunctions
from clipsFunctions import clips, _clipsLock
import pyRobotics.BB as BB
from pyRobotics.Messages import Command, Response
from clips_ros.msg import *
from clips_ros.srv import *
from std_msgs.msg import Bool, String
import BBFunctions
import rospy
import rospkg
defaultTimeout = 2000
defaultAttempts = 1
logLevel = 1
def setLogLevelTest():
_clipsLock.acquire()
clips.SendCommand('(bind ?*logLevel* ' + 'getloglevel' + ')')
#clipsFunctions.PrintOutput()
_clipsLock.release()
def callbackCommandResponse(data):
print "callbackCommandResponse name command:" + data.name
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.name)
clipsFunctions.Assert('(BB_received "{0}" {1} {2} "{3}")'.format(data.name, data.id, data.successful, data.params))
clipsFunctions.PrintOutput()
clipsFunctions.Run(BBFunctions.gui.getRunTimes())
clipsFunctions.PrintOutput()
def callbackCommandSendCommand(data):
clips.SendCommand(data.command, True)
clipsFunctions.PrintOutput()
def callbackCommandRunCLIPS(data):
print "callbackCommandRUNCLIPS "
clipsFunctions.Run('') # aqui se manda el numero de pasos que ejecutara CLIPS con [''] se ejecutan todos los pasos sin detenerse
clipsFunctions.PrintOutput()
def callbackCommandClearCLIPS(data):
clipsFunctions.Clear();
print "Enviroment was clear"
setLogLevelTest()
def callbackCommandResetCLIPS(data):
clipsFunctions.Reset()
print 'Facts were reset!'
setLogLevelTest()
def callbackCommandFactCLIPS(data):
print 'LIST OF FACTS'
clipsFunctions.PrintFacts()
def callbackCommandRuleCLIPS(data):
print 'LIST OF RULES'
clipsFunctions.PrintRules()
def callbackCommandAgendaCLIPS(data):
print 'AGENDA'
clipsFunctions.PrintAgenda()
def callbackCommandSendCLIPS(data):
print 'SEND COMMAND'
_clipsLock.acquire()
clips.SendCommand(data.data, True)
clipsFunctions.PrintOutput()
_clipsLock.release()
def callbackCommandSendAndRunClips(data):
print 'SEND AND RUN COMMAND'
_clipsLock.acquire()
clips.SendCommand(data.data, True)
clipsFunctions.PrintOutput()
_clipsLock.release()
clipsFunctions.Run('')
clipsFunctions.PrintOutput()
def callbackCommandLoadCLIPS(data):
print 'LOAD FILE'
filePath = data.data
if not filePath:
print 'OPEN FILE, Click on the botton and select a file to be loaded.'
return
if filePath[-3:] == 'clp':
_clipsLock.acquire()
clips.BatchStar(filePath)
clipsFunctions.PrintOutput()
_clipsLock.release()
print 'File Loaded!'
return
path = os.path.dirname(os.path.abspath(filePath))
f = open(filePath, 'r')
line = f.readline()
_clipsLock.acquire()
while line:
clips.BatchStar((path + os.sep + line).strip())
line = f.readline()
f.close()
clipsFunctions.PrintOutput()
_clipsLock.release()
print 'Files Loaded!'
clipsFunctions.Reset()
print 'Facts were reset!'
setLogLevelTest()
def setCmdTimer(t, cmd, cmdId):
t = threading.Thread(target=cmdTimerThread, args = (t, cmd, cmdId))
t.daemon = True
t.start()
return True
def cmdTimerThread(t, cmd, cmdId):
time.sleep(t/1000)
clipsFunctions.Assert('(BB_timer "{0}" {1})'.format(cmd, cmdId))
clipsFunctions.PrintOutput()
#clipsFunctions.Run(gui.getRunTimes())
#clipsFunctions.PrintOutput()
def setTimer(t, sym):
t = threading.Thread(target=timerThread, args = (t, sym))
t.daemon = True
t.start()
return True
def timerThread(t, sym):
time.sleep(t/1000)
clipsFunctions.Assert('(BB_timer {0})'.format(sym))
clipsFunctions.PrintOutput()
#clipsFunctions.Run(gui.getRunTimes())
#clipsFunctions.PrintOutput()
def SendCommand(cmdName, params, timeout = defaultTimeout, attempts = defaultAttempts):
global pubUnknown
print 'Function name ' + cmdName
cmd = Command(cmdName, params)
func = fmap.get(cmdName)
if func != None:
func(cmd)
else:
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubUnknown.publish(request)
return cmd._id
def str_query_KDB(req):
print 'QUERY IN KDB ' + req.query
_clipsLock.acquire()
clips.SendCommand(req.query, True)
clipsFunctions.PrintOutput()
_clipsLock.release()
clipsFunctions.Run('')
result = str(clips.StdoutStream.Read())
print 'RESULT OF QUERY= ' + result
print ''
return StrQueryKDBResponse(result)
def init_KDB(req):
print 'INIT KDB'
print 'LOAD FILE'
global file_gpsr
rospack = rospkg.RosPack()
#file_gpsr = rospack.get_path('simulator') + '/src/rules_base/oracle.dat'
if not req.filePath:
filePath = file_gpsr
else:
filepath = rospack.get_path('simulator')
#clips.BatchStar(filepath + os.sep + 'CLIPS' + os.sep + 'BB_interface.clp')
filePath = filepath + req.filePath
#filePath = req.filePath
print 'Load file in path' + filePath
if filePath[-3:] == 'clp':
_clipsLock.acquire()
clips.BatchStar(filePath)
clipsFunctions.PrintOutput()
_clipsLock.release()
print 'File Loaded!'
return
path = os.path.dirname(os.path.abspath(filePath))
f = open(filePath, 'r')
line = f.readline()
_clipsLock.acquire()
while line:
clips.BatchStar((path + os.sep + line).strip())
line = f.readline()
f.close()
clipsFunctions.PrintOutput()
_clipsLock.release()
print 'Files Loaded!'
clipsFunctions.Reset()
print 'Facts were reset!'
setLogLevelTest()
if req.run == True:
clipsFunctions.Run('')
return InitKDBResponse()
def clear_KDB(req):
print "CLEAR KDB"
clipsFunctions.Clear()
setLogLevelTest()
return clearKDBResponse(True)
#def SendResponse(cmdName, cmd_id, result, response):
#result = str(result).lower() not in ['false', '0']
#r = Response(cmdName, result, response)
#r._id = cmd_id
#BB.Send(r)
def Initialize():
clips.Memory.Conserve = True
clips.Memory.EnvironmentErrorsEnabled = True
clips.RegisterPythonFunction(SendCommand)
clips.RegisterPythonFunction(setCmdTimer)
clips.RegisterPythonFunction(setTimer)
clips.BuildGlobal('defaultTimeout', defaultTimeout)
clips.BuildGlobal('defaultAttempts', defaultAttempts)
filePath = os.path.dirname(os.path.abspath(__file__))
clips.BatchStar(filePath + os.sep + 'CLIPS' + os.sep + 'BB_interface.clp')
clips.BatchStar(filePath + os.sep + 'CLIPS' + os.sep + 'functions.clp')
clips.BatchStar(filePath + os.sep + 'CLIPS' + os.sep + 'monitor.clp')
clips.BatchStar(filePath + os.sep + 'CLIPS' + os.sep + 'virbot_blackboard.clp')
#file_gpsr = filePath + '/virbot_test/oracle.dat'
rospack = rospkg.RosPack()
file_gpsr = rospack.get_path('simulator') + '/src/expert_system/oracle.dat'
print file_gpsr
BBFunctions.gui.putFileName(file_gpsr)
# Savage BBFunctions.gui.loadFile()
BBFunctions.gui.reset()
#Funcions to fmap, this functions are publish to topics to do the tasks
def cmd_speech(cmd):
global pubCmdSpeech
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdSpeech.publish(request)
return cmd._id
def cmd_int(cmd):
global pubCmdInt
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdInt.publish(request)
return cmd._id
def cmd_conf(cmd):
global pubCmdInt
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdConf.publish(request)
return cmd._id
def cmd_task(cmd):
global pubCmdInt
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdGetTask.publish(request)
return cmd._id
def goto(cmd):
global pubCmdGoto
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdGoto.publish(request)
print "send pub"
return cmd._id
def answer(cmd):
global pubCmdAnswer
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdAnswer.publish(request)
return cmd._id
def find_object(cmd):
global pubCmdFindObject
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdFindObject.publish(request)
return cmd._id
def ask_for(cmd):
global pubCmdAskFor
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdAskFor.publish(request)
return cmd._id
def status_object(cmd):
global pubCmdStatusObject
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdStatusObject.publish(request)
return cmd._id
def move_actuator(cmd):
global pubCmdMoveActuator
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdMoveActuator.publish(request)
return cmd._id
def drop(cmd):
global pubDrop
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubDrop.publish(request)
return cmd._id
def ask_person(cmd):
global pubCmdAskPerson
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubCmdAskPerson.publish(request)
return cmd._id
def clips_ros(cmd):
global pubClipsToRos
print "Executing function:" + cmd.name;
request = PlanningCmdClips(cmd.name, cmd.params, cmd._id, False)
pubClipsToRos.publish(request)
return cmd._id
#Define the function map, this function are the functions that represent of task in the clips rules.
fmap = {
'cmd_speech': cmd_speech,
'cmd_int': cmd_int,
'cmd_conf': cmd_conf,
'cmd_task': cmd_task,
'find_object': find_object,
'move_actuator': move_actuator,
#'grab': grab,
'drop': drop,
'status_object': status_object,
'goto': goto,
#'speak': speak,
'ask_for': ask_for,
'answer' : answer,
'clips_ros': clips_ros,
'ask_person': ask_person
}
def quit():
global tk
tk.quit()
def main():
global pubCmdSpeech, pubCmdInt, pubCmdConf, pubCmdGetTask, pubUnknown
global pubCmdGoto, pubCmdAnswer, pubCmdFindObject, pubCmdAskFor, pubCmdStatusObject, pubCmdMoveActuator, pubDrop, pubCmdAskPerson, pubClipsToRos
rospy.init_node('planning_rm')
rospy.Subscriber("/planning_rm/command_response", PlanningCmdClips, callbackCommandResponse)
rospy.Subscriber("/planning_rm/command_send_command", PlanningCmdSend, callbackCommandSendCommand)
rospy.Subscriber("/planning_rm/command_runCLIPS",Bool, callbackCommandRunCLIPS)
rospy.Subscriber("/planning_rm/command_resetCLIPS",Bool, callbackCommandResetCLIPS)
rospy.Subscriber("/planning_rm/command_clearCLIPS",Bool, callbackCommandClearCLIPS)
rospy.Subscriber("/planning_rm/command_factCLIPS",Bool, callbackCommandFactCLIPS)
rospy.Subscriber("/planning_rm/command_ruleCLIPS",Bool, callbackCommandRuleCLIPS)
rospy.Subscriber("/planning_rm/command_agendaCLIPS",Bool, callbackCommandAgendaCLIPS)
rospy.Subscriber("/planning_rm/command_sendCLIPS",String, callbackCommandSendCLIPS)
rospy.Subscriber("/planning_rm/command_sendAndRunCLIPS", String, callbackCommandSendAndRunClips)
rospy.Subscriber("/planning_rm/command_loadCLIPS",String, callbackCommandLoadCLIPS)
rospy.Service('/planning_rm/str_query_KDB', StrQueryKDB, str_query_KDB)
rospy.Service('/planning_rm/init_kdb', InitKDB, init_KDB)
rospy.Service('/planning_rm/clear_kdb', clearKDB, clear_KDB)
pubCmdSpeech = rospy.Publisher('/planning_rm/cmd_speech', PlanningCmdClips, queue_size=1)
pubCmdInt = rospy.Publisher('/planning_rm/cmd_int', PlanningCmdClips, queue_size=1)
pubCmdConf = rospy.Publisher('/planning_rm/cmd_conf', PlanningCmdClips, queue_size=1)
pubCmdGetTask = rospy.Publisher('/planning_rm/cmd_task', PlanningCmdClips, queue_size=1)
pubCmdGoto = rospy.Publisher('/planning_rm/cmd_goto', PlanningCmdClips, queue_size=1)
pubCmdAnswer = rospy.Publisher('/planning_rm/cmd_answer', PlanningCmdClips, queue_size=1)
pubCmdFindObject = rospy.Publisher('/planning_rm/cmd_find_object', PlanningCmdClips, queue_size=1)
pubCmdAskFor = rospy.Publisher('/planning_rm/cmd_ask_for', PlanningCmdClips, queue_size=1)
pubCmdStatusObject = rospy.Publisher('/planning_rm/cmd_status_object', PlanningCmdClips, queue_size=1)
pubCmdMoveActuator = rospy.Publisher('/planning_rm/cmd_move_actuator', PlanningCmdClips, queue_size=1)
pubDrop = rospy.Publisher('/planning_rm/cmd_drop', PlanningCmdClips, queue_size=1)
pubUnknown = rospy.Publisher('/planning_rm/cmd_unknown', PlanningCmdClips, queue_size=1)
pubCmdAskPerson = rospy.Publisher('/planning_rm/cmd_ask_person', PlanningCmdClips, queue_size=1)
pubClipsToRos = rospy.Publisher('/planning_rm/clips_to_ros', PlanningCmdClips, queue_size=1)
Initialize()
tk.mainloop()
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
653f2017b1d2a38b243d234fcd889251d9456780 | ee194bcb5c1f92fb30d45093da4a51b47a264034 | /blog1/forms.py | ea1ad5c5c0ca62cfe1b352489993ac714514e473 | [] | no_license | samfubuki/Blog-Task-Internship | 576abe439490220f71452e16cf43dd2e04b1b67d | 113ba3f7a2f92e7f5761d84d8226cbf911a403da | refs/heads/main | 2023-04-04T20:34:08.792136 | 2021-04-20T13:52:44 | 2021-04-20T13:52:44 | 359,832,858 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 503 | py | from django import forms
from .models import BlogDatabase
class BlogForm(forms.ModelForm):
class Meta:
model=BlogDatabase
fields = ['blog_title','blog_description','blog_image']
labels = {'blog_title':'Blog Title','blog_description':'Blog Description','profile_image':'Profile Image'}
widgets = {
'blog_title':forms.TextInput(attrs={'class':'form-control'}),
'blog_description':forms.TextInput(attrs={'class':'form-control'}),
}
| [
"[email protected]"
] | |
bc2d9c7b587f1bef9592022ea45f8b722730e5d9 | 688ea92b2581fcbf28d53166040c5c5dfbe9ebd1 | /venv/Scripts/pip3-script.py | c0ebd807c2bd8eefd542610a784d5563e63e4679 | [] | no_license | springs101/changeDataStream | ed01dd50ef3073a298ae228b4931987bdefd1855 | d65e92bf09b96d07396726fdc379e867bb528fb8 | refs/heads/master | 2020-05-17T08:25:49.951274 | 2019-08-07T06:27:35 | 2019-08-07T06:27:35 | 183,605,750 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 394 | py | #!D:\changeDataStream\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip3')()
)
| [
"[email protected]"
] | |
a34d5ceaaeda2800046b7b64ab0ea699a204680e | bf832585a096c973349dc05ab087135f5a981185 | /test/docker_tests/5/test5_1.py | c1da617a4989ff93532f36bf355d2ad8c26d3c44 | [
"MIT"
] | permissive | ianmiell/shutit-test | a803e8aa870e1e4338b110a48de72e3f7bcb0691 | 03387f8c4aa0c8eda3d0730e43cc84a7d71e9e46 | refs/heads/master | 2021-12-27T23:38:28.264755 | 2021-10-30T09:37:10 | 2021-10-30T09:37:10 | 59,279,847 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,353 | py | #Copyright (C) 2014 OpenBet Limited
#
#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 shutit_module import ShutItModule
class test5_1(ShutItModule):
def is_installed(self, shutit):
return False
def build(self, shutit):
shutit.send('touch /tmp/test5_1')
return True
def module():
return test5_1('shutit.tk.test.test5_1',5.1, depends=['shutit.tk.setup'])
| [
"[email protected]"
] | |
ebad171d221d4c775c6bef6116562014b58d9264 | ea04dda2dcc636daf23eb4fb1ad587a60b5f2d74 | /Assignment2/getkey1.py | 91fda9a3a89255d0a8a53bc4db3a934618a16e67 | [] | no_license | kunal14053/FCS-Assignments | 270692baf1d38786fdae7f95b6d9366220f242e2 | 9e06edd81dc832c46c7ff3ab0181b46b6e4029a1 | refs/heads/master | 2021-05-01T15:24:57.850905 | 2016-11-08T17:30:57 | 2016-11-08T17:30:57 | 66,966,907 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 954 | py | from Crypto.Cipher import DES
import enchant
def dictionary(string):
wordList = string.split(" ")
d = enchant.Dict("en_US");
for x in wordList:
if(not d.check(x)):
return False;
return True;
def only_letters(string):
wordList = string.split(" ")
for x in wordList:
if(not all(letter.isalpha() for letter in x)):
return False;
return True;
cipher_text=b"\xc5\x81\x97~\xb4\x0b:U\x13^\x9c\xb2:\xedcC\xe5\n\xab\xb2\xbas\xbe/\r\xa8\x00'\x87\x91Ch\xb8\x060\xfb\xf8V\xf7)\x1d\xfb\x12\xe7\x16\xf0\x12\x1dQ\x99Gs`\xf5qZjQL\xe1\x1f\xfd\x90E";
result = open("result.txt", 'w');
for i in range(0,99999999):
Key = str(i);
size=len(Key);
for j in range(0,8-size):
Key="0"+Key;
des = DES.new(Key, DES.MODE_ECB);
decrypted_pt = des.decrypt(cipher_text);
print decrypted_pt
if (only_letters(str(decrypted_pt)) and dictionary(str(decrypted_pt))):
result.write("Text: "+decrypted_pt+" Key: "+Key+'\n');
result.close();
| [
"[email protected]"
] | |
aff36db96b7c0890610d5856587ceaffdc29c442 | 3a36e5b1d0229c20492e582ff1d60cf02436ffe8 | /waterbutler/tasks/settings.py | d7ae6dbdb4ae18639959745bdf908e01d01ac1b6 | [
"Apache-2.0"
] | permissive | brianjgeiger/waterbutler | fccd9733f3c7e7716f9fafa8afbf1ae9345b7e72 | b71e083f821c4f8c9597287d8bf0d527fc7c212f | refs/heads/master | 2021-01-14T11:11:34.991413 | 2015-03-30T19:18:07 | 2015-03-30T19:18:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 932 | py | import os
from pkg_resources import iter_entry_points
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('TASKS_CONFIG', {})
BROKER_URL = config.get(
'BROKER_URL',
'amqp://{}:{}//'.format(
os.environ.get('RABBITMQ_PORT_5672_TCP_ADDR', ''),
os.environ.get('RABBITMQ_PORT_5672_TCP_PORT', ''),
)
)
CELERY_RESULT_BACKEND = config.get(
'CELERY_RESULT_BACKEND',
'redis://{}:{}'.format(
os.environ.get('REDIS_PORT_6379_TCP_ADDR', ''),
os.environ.get('REDIS_PORT_6379_TCP_PORT', ''),
)
)
CELERY_DISABLE_RATE_LIMITS = config.get('CELERY_DISABLE_RATE_LIMITS', True)
CELERY_TASK_RESULT_EXPIRES = config.get('CELERY_TASK_RESULT_EXPIRES', 60)
# CELERY_ALWAYS_EAGER = config.get('CELERY_ALWAYS_EAGER', True)
CELERY_IMPORTS = [
entry.module_name
for entry in iter_entry_points(group='waterbutler.providers.tasks', name=None)
]
| [
"[email protected]"
] | |
4a616bb7539920d4e02fdf9af4a9d24041b2be58 | 0667727bec468deafbe4d0951521493a78f0a8f1 | /app/migrations/0001_initial.py | c3e69ff3d68a336fc18669645aa401720e924b4a | [] | no_license | pw94/RapidAlert | ce4b76079829353f94a96607a16efcea5aa00755 | 92f50b032199a6fc0eeeab27c88de7f9e2dede46 | refs/heads/master | 2021-01-19T07:46:14.683785 | 2017-04-07T17:24:14 | 2017-04-07T17:24:14 | 87,570,094 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,992 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-19 12:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('taggit', '0002_auto_20150616_2121'),
('sessions', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Confirmation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('description', models.CharField(max_length=150)),
('latitude', models.DecimalField(decimal_places=8, max_digits=10)),
('longitude', models.DecimalField(decimal_places=8, max_digits=11)),
('added_at', models.DateTimeField(default=django.utils.timezone.now)),
('session_key', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='sessions.Session')),
('tags', taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags')),
],
),
migrations.AddField(
model_name='confirmation',
name='event',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.Event'),
),
migrations.AddField(
model_name='confirmation',
name='session_key',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='sessions.Session'),
),
]
| [
"[email protected]"
] | |
6d53a2cc86926c0fa1ccf29294e998b98fd7dae3 | cd329ea8a865e6ab982b129671832f36c6f995e5 | /clases/Consulta.py | 895310fa097c3265f7a22c710d6b7547860c7afa | [] | no_license | ridiazcampos/bdd-e4 | 8b43963d487db44aab570d7eb0ad92fee7af8cee | fc11d65110956d3fb91aa8057cd28e64ce5dd6cf | refs/heads/master | 2022-11-16T20:34:44.198627 | 2020-07-09T00:45:29 | 2020-07-09T00:45:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,147 | py | import requests
import itertools
import threading
import time
import sys
from datetime import datetime
class SeDemora(Exception):
def __init__(self, texto=""):
super().__init__(texto)
class Consulta:
diccionario = ["mid", "message", "sender", "receptant", "lat", "long", "date"]
ids = set(list(range(1, 221)))
diccionario_usuarios = ["uid", "name", "age", "description"]
guarda, nombre_archivo = True, ""
def __init__(self, ruta, api="https://iic2413-2020-1-api.herokuapp.com", grupo="http://localhost:5000"):
self.ruta = ruta
self.api = api
self.grupo = grupo
self.llaves = []
self.g1 = []
self.esperar = False
self.inicio = None
self.atributos = True
self.atributos_encontrados = []
self.estado = None
self.json_grupo = None
self.json_api = None
self.json_grupo_adaptado = None
self.json_grupo_original = None
self._mensaje = ""
def puntos(self):
if self.respuesta:
return self._puntos
return 0
def mensaje(self):
if not self.atributos:
self._mensaje = "Faltan atributos por mostrar"
if self.respuesta:
return f"{self.nombre}: {self.respuesta} [{self.puntos()} puntos] {self._mensaje}"
else:
return f"{self.nombre}: {self.respuesta} [{self.puntos()} puntos] {self._mensaje}"#"
def encontrar(respuesta, llaves=None, filtro=4):
primero = False
if llaves is None:
llaves = []
primero = True
if type(respuesta) == dict:
#print("es diccionario")
contador = 0
for i in ["mid", "sender", "receptant", "date", "lat", "long", "message"]:
if i in respuesta:
contador += 1
if contador >= filtro:
#print("mayor o igual a 4")
if len(llaves) >= 1:
#print(":")
#print(respuesta, llaves)
if type(llaves[-1]) == int or str(llaves[-1]).isnumeric():
llaves.pop(len(llaves)-1)
if primero:
#print("primero")
return Consulta.obtener(respuesta, llaves, filtro)
else:
#print("else")
return llaves
retorno = False
for key in respuesta:
retorno = Consulta.encontrar(respuesta[key], llaves.copy() + [key], filtro)
if retorno is not False:
if primero:
return Consulta.obtener(respuesta, retorno, filtro)
else:
return retorno
elif type(respuesta) == list:
retorno = 0
for key in range(len(respuesta)):
retorno = Consulta.encontrar(respuesta[key], llaves.copy() + [key], filtro)
#print("retorno para", key, ":", retorno, "donde respuesta[key] = ", respuesta[key])
if retorno is not False:
#print("hola")
if primero:
#print("es primero")
return Consulta.obtener(respuesta, retorno, filtro)
else:
#print("no es primero")
return retorno
if primero and filtro != 2:
return Consulta.encontrar(respuesta, None, 2)
return False
def encontrar_2(respuesta, llaves=None, filtro=2):
primero = False
if llaves is None:
llaves = []
primero = True
if type(respuesta) == dict:
#print("es diccionario")
contador = 0
for i in ["uid", "name", "age", "description"]:
if i in respuesta:
contador += 1
if contador >= filtro:
#print("mayor o igual a 4")
if len(llaves) >= 1:
#print(":")
#print(respuesta, llaves)
if type(llaves[-1]) == int or str(llaves[-1]).isnumeric():
llaves.pop(len(llaves)-1)
if primero:
#print("primero")
return Consulta.obtener_2(respuesta, llaves, filtro)
else:
#print("else")
return llaves
retorno = False
for key in respuesta:
retorno = Consulta.encontrar_2(respuesta[key], llaves.copy() + [key], filtro)
if retorno is not False:
if primero:
return Consulta.obtener_2(respuesta, retorno, filtro)
else:
return retorno
elif type(respuesta) == list:
retorno = 0
for key in range(len(respuesta)):
retorno = Consulta.encontrar_2(respuesta[key], llaves.copy() + [key], filtro)
#print("retorno para", key, ":", retorno, "donde respuesta[key] = ", respuesta[key])
if retorno is not False:
#print("hola")
if primero:
#print("es primero")
return Consulta.obtener_2(respuesta, retorno, filtro)
else:
#print("no es primero")
return retorno
if primero and filtro != 1:
return Consulta.encontrar_2(respuesta, None, 1)
return False
def obtener_2(respuesta, ruta, filtro=2):
#print(respuesta, ruta)
for i in range(len(ruta)):
respuesta = respuesta[ruta[i]]
if i == len(ruta) - 2:
super_contador = 0
for key in respuesta:
contador = 0
for llave in ["uid", "name", "description", "age"]:
if llave in respuesta[key]:
contador += 1
if contador >= filtro:
super_contador += 1
if super_contador == len(respuesta):
return list(respuesta.values())
if type(respuesta) != list:
return [respuesta]
return respuesta
def obtener(respuesta, ruta, filtro=4):
#print(respuesta, ruta)
for i in range(len(ruta)):
respuesta = respuesta[ruta[i]]
if i == len(ruta) - 2:
super_contador = 0
for key in respuesta:
contador = 0
for llave in ["mid", "sender", "receptant", "date", "lat", "long", "message"]:
if llave in respuesta[key]:
contador += 1
if contador >= filtro:
super_contador += 1
if super_contador == len(respuesta):
return list(respuesta.values())
if type(respuesta) != list:
return [respuesta]
return respuesta
def animate(self):
iconos2 = ['|', '/', '-', '\\']
iconos = ['.', '..', '...', '..']
datetime.now()
for c in itertools.cycle(iconos2):
if self.done:
break
if self.inicio:
holi = (datetime.now() - self.inicio).seconds
if holi >= 0:
self.done = True
raise SeDemora("holi")
sys.stdout.write('\rCargando ' + c)
sys.stdout.flush()
time.sleep(0.1)
#sys.stdout.write('\r¡Listo! ')
def todos_atributos(self, consulta):
atributos = [i.strip().lower() for i in consulta[0]]
encontrados = True
for i in Consulta.diccionario:
if i.strip().lower() not in atributos:
encontrados = False
self.atributos = encontrados # True o False
self.atributos_encontrados = atributos # Lista
return encontrados
def todos_atributos_2(self, consulta):
atributos = [i.strip().lower() for i in consulta[0]]
encontrados = True
for i in Consulta.diccionario_usuarios:
if i.strip().lower() not in atributos:
encontrados = False
self.atributos = encontrados
self.atributos_encontrados = atributos
return encontrados
def requests_get(*args, **kwargs):
for i in range(10):
a = requests.get(*args, **kwargs)
if a.status_code != 503:
return a
break
time.sleep(1)
#GET
return a
def requests_delete(*args, **kwargs):
for i in range(10):
a = requests.delete(*args, **kwargs)
if a.status_code != 503:
return a
break
time.sleep(1)
return a
def requests_post(*args, **kwargs):
for i in range(10):
a = requests.post(*args, **kwargs)
if a.status_code != 503:
return a
break
time.sleep(1)
return a
def ids_disponibles(self):
try:
recibido = Consulta.requests_get(self.grupo + "/messages", timeout=10)
recibido = Consulta.encontrar(recibido.json())
lista = [int(i["mid"]) if str(i).isnumeric() else (int(float("mid" in i and str(i["mid"])))) for i in recibido if "mid" in i and str(i["mid"]).isnumeric() or "mid" in i and str(i["mid"]).replace(".", "").isnumeric()]
Consulta.ids = set(lista)
except requests.exceptions.ReadTimeout:
print("Al parecer /messages está teniendo problemas par obtener todos los mensajes")
print("¿Desea utilizar el predeterminado? (ids del 1 al 220)? ¿O mejor obtener los mensajes haciendo consulta id por id?")
print(" [0] Asumir que las ids van de 1 al 220")
print(" [1] Obtener id por id (esto puede tardar unos minutos)")
entrada = input(">> ")
while entrada.strip() not in ["0", "1"]:
print("No se reconoció el comando :O ¡Puede intentarlo de nuevo!")
entrada = input(">> ")
if entrada == "0":
return Consulta.ids
lista = []
for i in range(1, 240):
try:
sys.stdout.write(f"\r [{'*'*int(i*50/239)}{' '*(50-int((i)*50/220))}] ({i}/239)")
sys.stdout.flush()
recibido = Consulta.requests_get(self.grupo + "/messages/" + str(i))
recibido = Consulta.encontrar(recibido.json())
lista.append(recibido[0]["mid"] if str(recibido[0]["mid"]).isnumeric() else (int(float(str(recibido[0]["mid"])))))
except:
continue
Consulta.ids = set(lista)
return Consulta.ids
#consulta = Consulta("/messages", "https://iic2413-2020-1-api.herokuapp.com", "localhost:5000")
#consulta.cargar_g1()
#consulta.correr_g1()
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.