blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
04f43e8ab0e9d295b14bcbfa4554fa94ce8df0f8
e4c49a302d522b4230bfdb443c4a292fe5b678d2
/ex38.py
20c6e65889da9557926b2ddcd110adb3160812ac
[]
no_license
yangdm2015/learn_python_the_hard_way
d9de2f548d65601859469cf0bb76ed96136ce06b
7f945b2389cb564e53bfc0968d4a285a345fbbb1
refs/heads/master
2021-01-10T01:22:41.136884
2016-02-20T10:32:01
2016-02-20T10:32:01
52,142,021
0
0
null
null
null
null
UTF-8
Python
false
false
141
py
ten_things = "Apples Oranges Crows Telephone Light Sugar" stuff = ten_things.split(' ') print 'Here is stuff: ',stuff print ' # '.join(stuff)
[ "yangshan503@126.com" ]
yangshan503@126.com
09bc7adcc515d18792fa05913a8a68f4bad709ad
9f45343e8aa34745c4b35819daa624568abf92c7
/api/constants.py
502da57d64c00353185808743a1f885214f931d4
[]
no_license
prabhakar1998/restaurant_selection
d50fc120ee2fdec759dfc12373e719bbec240a65
e63fe089dd7c5f2ba99c6e558ae9eb9824079da9
refs/heads/main
2023-05-16T22:01:12.812360
2021-06-14T21:03:51
2021-06-14T21:10:11
374,348,468
0
0
null
null
null
null
UTF-8
Python
false
false
29
py
MAX_CONSECUTIVE_WINNINGS = 2
[ "findmebhanujha@gmail.com" ]
findmebhanujha@gmail.com
4f8cec0f654a36809e0c484a3e7513429f6ff74e
0d3b16041f49156b45a820c111af33f6b7f5ae90
/goodsave/models.py
6b4ff643c89cc38256ecdb644ab471b0cff2be29
[]
no_license
chuanzhangcyh/StrangeMarket
0b504c032023a15955d8e383f136b1daa0d64bb6
bd8e0bc9199b3420d6fa8973e28e6401bf1a38f8
refs/heads/master
2023-02-24T21:28:59.205924
2021-02-02T13:39:01
2021-02-02T13:39:01
335,293,333
0
1
null
null
null
null
UTF-8
Python
false
false
321
py
from django.db import models # Create your models here. class GoodSave(models.Model): open_id = models.CharField(max_length=32) good_id = models.IntegerField() create_time = models.DateTimeField(auto_now_add=True) # 创建时间 last_modified = models.DateTimeField(auto_now=True) # 最新修改时间
[ "1015223012@qq.com" ]
1015223012@qq.com
885943d426f74accbe87f137a32b7bb6732b1be4
3609e9566118cf82de78ce567379d9f39e0f7954
/twitterbot.py
f0db33d52006e9c01fbd6f226b11d2f4c32882cf
[]
no_license
DeveloperHarris/PythonMLPractice
d00c8dfe11f91633bcc13ed5d52489f0a7474c94
c5f7dc9b660326674fa5d205f61c9acac86c7e12
refs/heads/master
2020-06-10T03:32:06.891415
2017-02-19T18:55:51
2017-02-19T18:55:51
76,099,506
0
0
null
null
null
null
UTF-8
Python
false
false
1,284
py
import tweepy from textblob import TextBlob #authorization info consumer_key = consumer_secret = access_token = access_token_secret = auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) #search public tweets containing this string # public_tweets = api.search(input('Please enter your search query: ')) #print out the tweets found, and their sentiment analysis # for tweet in public_tweets: # print(tweet.text.encode("utf-8")) # print('Author: ' + str(tweet.user.screen_name)) # print('Created: ' + str(tweet.created_at)) # print('Location: ' + str(tweet.place)) # print('Favorites: ' + str(tweet.favorite_count)) # print('Retweets: ' + str(tweet.retweet_count)) # analysis = TextBlob(tweet.text) # print(analysis.sentiment) # print('\n') input_file = open('filename.txt', 'r') output_file = open('output.txt', 'wt') try: for i, line in enumerate(input_file): print(len(line)) if len(line) < 16: try: user = api.get_user(line) #print(line + str(user.created_at)) except tweepy.TweepError as e: if e.api_code == 50: print(e.reason) output_file.write(str(line)) pass finally: input_file.close() print ('{0} line(s) printed'.format(i+1))
[ "harris.rothaermel@gmail.com" ]
harris.rothaermel@gmail.com
90c1ea5703f6a090fdf56e2802b2a403cf913366
22209fb76ba21a2c381e6bacbeb21d9fa0d92edb
/Mundo01/Python/aula08-017.py
980663c33340d7cd9f98812c8d171d5deda73a94
[ "MIT" ]
permissive
molonti/CursoemVideo---Python
cfba0bd1824f547b24cf216811b1447160a47bd5
4f6a7af648f7f619d11e95fa3dc7a33b28fcfa11
refs/heads/master
2021-05-21T08:09:52.031493
2020-04-03T02:22:05
2020-04-03T02:22:05
252,613,245
0
0
null
null
null
null
UTF-8
Python
false
false
152
py
from math import sqrt ca = int(input('Cateto 1:')) co = int(input('Cateto 2:')) h1 = (ca**2)+(co**2) h2 = sqrt(h1) print(f'A sua hipotenusa é {h2:.3}')
[ "molonti@gmail.com" ]
molonti@gmail.com
fc526b517115f5105dc49480a99ef5a9b3c56011
09dc598de26b6007735c22aa64bbd977054340b9
/t_server.py
0772e4666edc1908fc0c49e19e797c30b615edb1
[]
no_license
327101303/Sproxy
117a758eda3b6266ad93832d50937fc711d97814
80477273a13b822e3d6f781f91d0ceb54da5d392
refs/heads/master
2020-03-17T05:54:13.898627
2018-05-15T09:06:02
2018-05-15T09:06:02
133,333,059
0
0
null
null
null
null
UTF-8
Python
false
false
4,189
py
#!/usr/bin/env python # -*- coding:utf-8 -*- from tornado.tcpserver import TCPServer from tornado.iostream import StreamClosedError from tornado import gen import tornado from tornado import iostream from tornado import ioloop import sys import socket import select # import SocketServer import struct import string import hashlib import os import json import logging import getopt def get_table(key): m = hashlib.md5() m.update(key) s = m.digest() (a, b) = struct.unpack('<QQ', s) table = [c for c in string.maketrans('', '')] for i in xrange(1, 1024): table.sort(lambda x, y: int(a % (ord(x) + i) - a % (ord(y) + i))) return table def send_all(sock, data): bytes_sent = 0 while True: r = sock.send(data[bytes_sent:]) if r < 0: return r bytes_sent += r if bytes_sent == len(data): return bytes_sent class Socks5Server(TCPServer): def handle_tcp(self, sock, remote): try: fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: data = sock.recv(4096) if len(data) <= 0: break result = send_all(remote, self.decrypt(data)) if result < len(data): raise Exception('failed to send all data') if remote in r: data = remote.recv(4096) if len(data) <= 0: break result = send_all(sock, self.encrypt(data)) if result < len(data): raise Exception('failed to send all data') finally: sock.close() remote.close() def encrypt(self, data): return data.translate(encrypt_table) def decrypt(self, data): return data.translate(decrypt_table) def handle_stream(self, stream, address): try: addrtype = ord(stream.read_bytes(1,self.decrypt)) # receive addr type print addrtype if addrtype == 1: addr = socket.inet_ntoa(stream.read_bytes(4,self.decrypt)) # get dst addr elif addrtype == 3: addr = self.decrypt(stream.read_bytes(ord((stream.read_bytes(1,self.decrypt))))) # read 1 byte of len, then get 'len' bytes name else: # not support logging.warn('addr_type not support') return port = struct.unpack('>H', stream.read_bytes(2,self.decrypt)) # get dst port into small endian try: logging.info('connecting %s:%d' % (addr, port[0])) remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) remote.connect((addr, port[0])) # connect to dst except socket.error, e: # Connection refused logging.warn(e) return self.handle_tcp(stream.fileon(),remote) except socket.error, e: logging.warn(e) if __name__ == '__main__': os.chdir(os.path.dirname(__file__) or '.') print 'shadowsocks v0.9' with open('config.json', 'rb') as f: config = json.load(f) SERVER = config['server'] PORT = config['server_port'] KEY = config['password'] optlist, args = getopt.getopt(sys.argv[1:], 'p:k:') for key, value in optlist: if key == '-p': PORT = int(value) elif key == '-k': KEY = value logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filemode='a+') encrypt_table = ''.join(get_table(KEY)) decrypt_table = string.maketrans(encrypt_table, string.maketrans('', '')) try: server = Socks5Server() server.listen(PORT) ioloop.IOLoop.current().start() logging.info("starting server at port %d ..." % PORT) except socket.error, e: logging.error(e)
[ "zhangj@ethicall.cn" ]
zhangj@ethicall.cn
284e563253c0a06dc1a2fbf3e70f0bba6c14e2d0
a6de5e180451b976164c31acbb51262286cdd205
/30_days/day7.py
ea3d566be717a06eddf9b5cb8b9dafcfecb4d4ef
[]
no_license
bkemmer/misc
78d5b7f41acef04b97e073a36af47cd46cf5c015
901fdce697d41cfead4041fddcaec5df4e56793c
refs/heads/master
2021-01-12T08:02:44.358151
2017-02-09T17:20:01
2017-02-09T17:20:01
77,110,297
0
0
null
null
null
null
UTF-8
Python
false
false
223
py
#!/bin/python3 import sys n = int(input().strip()) arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] arr_rev = [] for i in range(len(arr)-1,-1,-1): arr_rev.append(str(arr[i])) print(' '.join(arr_rev))
[ "brunokemmer@gmail.com" ]
brunokemmer@gmail.com
14734f5417042d0dc018df21e7c2288618e2f787
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
/PyTorch/contrib/cv/detection/FSAF_for_Pytorch/mmdetection/configs/hrnet/faster_rcnn_hrnetv2p_w40_1x_coco.py
c9a800942198281199446b535833fa0b50caaf0e
[ "GPL-1.0-or-later", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Ascend/ModelZoo-PyTorch
4c89414b9e2582cef9926d4670108a090c839d2d
92acc188d3a0f634de58463b6676e70df83ef808
refs/heads/master
2023-07-19T12:40:00.512853
2023-07-17T02:48:18
2023-07-17T02:48:18
483,502,469
23
6
Apache-2.0
2022-10-15T09:29:12
2022-04-20T04:11:18
Python
UTF-8
Python
false
false
1,005
py
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # _base_ = './faster_rcnn_hrnetv2p_w32_1x_coco.py' model = dict( pretrained='open-mmlab://msra/hrnetv2_w40', backbone=dict( type='HRNet', extra=dict( stage2=dict(num_channels=(40, 80)), stage3=dict(num_channels=(40, 80, 160)), stage4=dict(num_channels=(40, 80, 160, 320)))), neck=dict(type='HRFPN', in_channels=[40, 80, 160, 320], out_channels=256))
[ "wangjiangben@huawei.com" ]
wangjiangben@huawei.com
64d8f64c4f1d385fec3613bf4389a70ab9054e31
74e7276c55008f9f392dbfe77ccb43604c048ba5
/19/demo19.5.py
2e8131ba0a89e9d5b975137f87035ca1e2aa96d0
[ "MIT" ]
permissive
BillZong/CorePythonProgrammingDemos
6cfd7ba129890fa2766961203429c5c20eb48f0b
c97b6f2c1533a3eeaf35d2de39902b95e969a411
refs/heads/master
2021-09-15T20:28:52.154021
2018-06-10T15:12:47
2018-06-10T15:12:47
108,109,520
0
0
null
null
null
null
UTF-8
Python
false
false
1,505
py
#!/usr/bin/env python # encoding: UTF-8 """Demo 19.5 for chapter 19.""" # 运用 PFA 的路灯指示牌 GUI 程序(pfaGUI2.py) # 按照指示类型创建适当前景、背景色的路灯指示牌。使用 PFA 帮助“模板化”常用 GUI 参数。 from functools import partial as pto from Tkinter import Tk, Button, X from tkMessageBox import showinfo, showwarning, showerror WARN = 'Warn' CRIT = 'Crit' REGU = 'Regu' SIGNS = { 'do not enter': CRIT, 'railroad crossing': WARN, '55\nspeed limit': REGU, 'wrong way': CRIT, 'merging traffic': WARN, 'one way': REGU, } critCB = lambda: showerror('Error', 'Error Button Pressed!') warnCB = lambda: showwarning('Warning', 'Warning Button Pressed!') infoCB = lambda: showinfo('Info', 'Info Button Pressed!') top = Tk() top.title('Road Signs') # bg在Mac上无效, 建议使用ttk替代Tkinter Button(top, text='QUIT', command=top.quit, activebackground='red', activeforeground='white').pack() MyButton = pto(Button, top) CritButton = pto(MyButton, command=critCB, activebackground='white', activeforeground='red') WarnButton = pto(MyButton, command=warnCB, activebackground='goldenrod1') ReguButton = pto(MyButton, command=infoCB, activebackground='white') for eachSign in SIGNS: signType = SIGNS[eachSign] cmd = '%sButton(text=%r%s).pack(fill=X, expand=True)' %\ (signType.title(), eachSign, '.upper()' if signType == CRIT else '.title()') eval(cmd) top.mainloop()
[ "billzong2012@gmail.com" ]
billzong2012@gmail.com
9665365f693e62b8dc7d91943fa26603e997e3c2
67956397866409c3ac2ba1c1c33579b04cb97288
/ML/ch05/runner.py
650df08a79e21a69264e7ca79b7bbbb79245d554
[]
no_license
whogopu/ml_nlp_practice
df50cc70100fb77093294e1c5f24a12ba15a24d0
9e76ee21f52d88e418c7cb27b9491e874c8f2ba6
refs/heads/master
2022-11-20T18:40:24.961872
2020-07-03T03:51:51
2020-07-03T03:51:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,485
py
import LogisticRegression as LR import numpy as np dataArr,labelMat=LR.loadDataSet() # With gradient ascent weights = LR.gradAscent(dataArr,labelMat) LR.plotBestFit(weights.getA()) """ output: matrix([[ 4.12414349], [ 0.48007329], [-0.6168482 ]]) """ # with stocGradAscent0 weights = LR.stocGradAscent0(np.array(dataArr),labelMat) LR.plotBestFit(weights) # with stocGradAscent1 weights = LR.stocGradAscent1(np.array(dataArr),labelMat) LR.plotBestFit(weights) # with different number of iterations # weights = stocGradAscent1(np.array(dataArr),labelMat, 50) # plotBestFit(weights) # weights = stocGradAscent1(np.array(dataArr),labelMat,100) # plotBestFit(weights) # weights = stocGradAscent1(np.array(dataArr),labelMat,200) # plotBestFit(weights) # weights = stocGradAscent1(np.array(dataArr),labelMat,300) # plotBestFit(weights) # weights = stocGradAscent1(np.array(dataArr),labelMat,500) # plotBestFit(weights) # Test horse fatalities LR.multiTest() """ output: the error rate of this test is: 0.298507 the error rate of this test is: 0.417910 the error rate of this test is: 0.298507 the error rate of this test is: 0.268657 the error rate of this test is: 0.373134 the error rate of this test is: 0.343284 the error rate of this test is: 0.268657 the error rate of this test is: 0.507463 the error rate of this test is: 0.417910 the error rate of this test is: 0.313433 after 10 iterations the average error rate is: 0.350746 """
[ "gopal151295@gmail.com" ]
gopal151295@gmail.com
345b1b6277d570c99be35b32428422b5a8b249f4
85c30319fa7a54414fedae612e287b91ce9f10df
/modulo4_ciencia/bloco_36/dia_1/exercicio_conteudo_5_binary_search.py
9e877ca8187775517b87952870a5d9a8062a9c18
[]
no_license
Gustaft86/trybe-exercises
9892c1ef968c0dd44dd88ad9dbd01123731b96f0
5dc2abaa6f6dfd3f3a7b6e305dde6bd090568913
refs/heads/master
2023-08-22T19:05:03.570511
2021-10-08T22:40:25
2021-10-08T22:40:25
301,892,171
1
0
null
2021-10-08T22:40:26
2020-10-07T00:58:31
JavaScript
UTF-8
Python
false
false
618
py
# A estrutura deve estar ordenada para que a busca binária funcione data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def binary_search_iterative(array, element): mid = 0 start = 0 end = len(array) step = 0 while start <= end: print( "Subarray in step {}: {}".format(step, str(array[start: end + 1])) ) step = step + 1 mid = (start + end) // 2 if element == array[mid]: return mid if element < array[mid]: end = mid - 1 else: start = mid + 1 return -1 print(binary_search_iterative(data, 7))
[ "gustavo.fthirion@gmail.com" ]
gustavo.fthirion@gmail.com
a17a74f63e86ff17cb03d40cb8998710a86dc813
d993249601f3e8cad3db483873bb1bcd84551cbd
/2019_Mid/Problem_5.py
9221109dc18908719d11d11d2d97f2f4889f7838
[]
no_license
HyeonJun97/Python_study
b1721a89af5a9474f3f755ac615eaf7fb67ff876
dced6dbd5ba44e03f182e39a89323ffbf776a24c
refs/heads/main
2023-01-19T19:16:09.035135
2020-11-19T07:25:43
2020-11-19T07:25:43
314,167,602
0
0
null
null
null
null
UTF-8
Python
false
false
315
py
x1,y1= eval(input("첫 번째 점에 대한 x1과 y1을 입력하세요: ")) x2,y2=eval(input("두 번째 점에 대한 x2과 y2을 입력하세요: ")) if x2-x1 ==0: print("직선의 방정식은 x=",x1) else: m=(y2-y1)/(x2-x1) q=y1-m*x1 print("직선의 방정식은 y=",m,"x+",q)
[ "noreply@github.com" ]
HyeonJun97.noreply@github.com
50c8632820c206a0b794122efddaa32dde2a34c4
2e9184ce66c7be722a48bf0201679b7dba27baac
/make-ppa
f1992c3b2a1eeb978d48a7fde1a141194f6589d6
[]
no_license
SonjaCambria/scripts
3e02f2f72a78e55bf7e281c5aa738dc946e89eac
f2f5444298a2bcee19e193d4d1a0dc4574a7102e
refs/heads/master
2021-01-18T12:58:42.568481
2015-09-22T11:34:09
2015-09-22T11:34:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,973
#!/usr/bin/python # Creates source packages and uploads them to Launchpad. # # Put this script somewhere, then run it from a git repository containing # sources for a debian package. Resulting packages will be created in a # subdirectory next to the make-ppa script. import sys import os import subprocess import re import argparse CHANGELOG = 'debian/changelog' DISTS = ['precise', 'trusty', 'vivid', 'wily'] VERSION_PATTERN = re.compile( r'^(?P<name>[+-.a-z0-9]+)\s+\((?P<version>[^)]+)\)\s+(?P<dist>[^)]+); urgency=(?P<urgency>.+)$') OUTPUT_DIR = os.path.dirname(os.path.abspath(__file__)) class Package(object): def __init__(self, dists=DISTS, ppa='yubico/stable'): self.dists = dists file = open(CHANGELOG, 'r') self.changelog = file.readlines() file.close() match = VERSION_PATTERN.match(self.changelog[0]) self.ppa = ppa self.name = match.group('name') self.dist = match.group('dist') self.urgency = match.group('urgency') orig_version = match.group('version') base_target = "%s/%s/%s" % (OUTPUT_DIR, self.name, orig_version) if '~ppa' in orig_version: print "Version '%s %s' already looks like a ppa version!" % \ (orig_version, self.dist) sys.exit(1) ppa_version = 1 while os.path.exists('%s~ppa%d' % (base_target, ppa_version)): ppa_version += 1 self.version = '%s~ppa%s' % (orig_version, ppa_version) self.target = "%s/%s/%s" % (OUTPUT_DIR, self.name, self.version) def build_dist(self, dist): version = '%s~%s1' % (self.version, dist) line = "%s (%s) %s; urgency=%s" % \ (self.name, version, dist, self.urgency) print "Build %s" % line changelog = list(self.changelog) changelog[0] = line file = open(CHANGELOG, 'w') file.writelines(changelog) file.close() os.system('debuild -S -sa -us -uc') os.system('mv ../%s_%s* %s/' % (self.name, version, self.target)) def build(self): upstream_version = self.version.split('-', 1)[0] orig = '%s_%s.orig.tar.gz' % (self.name, upstream_version) if not os.path.exists('../%s' % orig): try: res = subprocess.check_output('pristine-tar list', shell=True) if not orig in res.split(): print "../%s is missing!" % orig sys.exit(1) os.system('pristine-tar checkout %s' % orig) os.system('mv %s ../' % orig) except: # Try without orig, might be a native package. pass os.system('mkdir -p %s' % self.target) os.system('cp ../%s %s/' % (orig, self.target)) for dist in self.dists: self.build_dist(dist) file = open(CHANGELOG, 'w') file.writelines(self.changelog) file.close() def sign(self, key): args = ("-k %s" % key) if key else "" cmd = ('debsign %s %s/%s_%s*_source.changes' % (args, self.target, self.name, self.version)) os.system(cmd) def upload(self): for file in os.listdir(self.target): if file.endswith('.changes'): os.system('dput ppa:%s %s/%s' % (self.ppa, self.target, file)) if __name__ == '__main__': parser = argparse.ArgumentParser('Create source packages for PPA', add_help=True) parser.add_argument('--no-sign', action='store_false', dest='sign', help='Do not sign the packages (implies --no-upload)') parser.add_argument('--no-upload', action='store_false', dest='upload', help='Do not upload the (signed) packages') parser.add_argument('--dists', nargs='+', default=DISTS, metavar='DIST', help='Distributions to build for') parser.add_argument('--ppa', nargs='?', default='yubico/stable', help='PPA to upload to') parser.add_argument('--force', action='store_true', dest='force', help='Do not prompt for confirmation before running') parser.add_argument('-k', '--key', nargs='?', help='GPG key id to use for signing') args = parser.parse_args() do_sign = args.sign do_upload = do_sign and args.upload package = Package(dists=args.dists, ppa=args.ppa) print "Building %s %s for distributions: %s" % \ (package.name, package.version, ', '.join(package.dists)) if do_sign: print "Will sign packages!" if do_upload: print "Will upload packages!" print "PPA: %s" % args.ppa if not args.force: raw_input("Enter to continue, Ctrl+C to abort") package.build() if do_sign: package.sign(args.key) if do_upload: package.upload() print "All done!"
[ "dain@yubico.com" ]
dain@yubico.com
c315b763972e237f11d2cfd87020eda5b905c3b3
6e8de6b748e1c43c2730c5888c09816c97a8aa6c
/amib/lab6/main.py
0c266cd4cd5b5017f5e6da7fab2b1174f5cd4d42
[]
no_license
maxadamski/wiwiwi
3f35e9c91430a69a8ad50c6b20efef2fb3cfbb9b
c0545dca29dc37f6e9b65920d8c36174e4b23793
refs/heads/master
2023-04-13T10:09:07.440602
2023-04-03T20:28:10
2023-04-03T20:28:10
115,282,771
38
18
null
null
null
null
UTF-8
Python
false
false
11,785
py
import argparse import os import sys import numpy as np from time import time from deap import creator, base, tools, algorithms, gp from FramsticksLib import FramsticksLib import frams # Note: this may be less efficient than running the evolution directly in Framsticks, so if performance is key, compare both options. def genotype_within_constraint(genotype, dict_criteria_values, criterion_name, constraint_value): REPORT_CONSTRAINT_VIOLATIONS = False if constraint_value is not None: actual_value = dict_criteria_values[criterion_name] if actual_value > constraint_value: if REPORT_CONSTRAINT_VIOLATIONS: print('Genotype "%s" assigned low fitness because it violates constraint "%s": %s exceeds threshold %s' % (genotype, criterion_name, actual_value, constraint_value)) return False return True def sub(a, b): a = a - b def frams_evaluate(frams_cli, individual): BAD_FITNESS = [-1] * len(OPTIMIZATION_CRITERIA) # fitness of -1 is intended to discourage further propagation of this genotype via selection ("this genotype is very poor") genotype = gp.compile(individual, pset) # individual[0] because we can't (?) have a simple str as a deap genotype/individual, only list of str. data = frams_cli.evaluate([genotype]) # print("Evaluated '%s'" % genotype, 'evaluation is:', data) valid = True try: first_genotype_data = data[0] evaluation_data = first_genotype_data["evaluations"] default_evaluation_data = evaluation_data[""] if default_evaluation_data['vertpos'] < 0: default_evaluation_data['vertpos'] = 0 fitness = [default_evaluation_data[crit] for crit in OPTIMIZATION_CRITERIA] except (KeyError, TypeError) as e: # the evaluation may have failed for an invalid genotype (such as X[@][@] with "Don't simulate genotypes with warnings" option) or for some other reason valid = False print('Problem "%s" so could not evaluate genotype "%s", hence assigned it low fitness: %s' % (str(e), genotype, BAD_FITNESS)) if valid: default_evaluation_data['numgenocharacters'] = len(genotype) # for consistent constraint checking below valid &= genotype_within_constraint(genotype, default_evaluation_data, 'numparts', parsed_args.max_numparts) valid &= genotype_within_constraint(genotype, default_evaluation_data, 'numjoints', parsed_args.max_numjoints) valid &= genotype_within_constraint(genotype, default_evaluation_data, 'numneurons', parsed_args.max_numneurons) valid &= genotype_within_constraint(genotype, default_evaluation_data, 'numconnections', parsed_args.max_numconnections) valid &= genotype_within_constraint(genotype, default_evaluation_data, 'numgenocharacters', parsed_args.max_numgenochars) if not valid: fitness = BAD_FITNESS return fitness def frams_crossover(frams_cli, individual1, individual2): geno1 = individual1[0] # individual[0] because we can't (?) have a simple str as a deap genotype/individual, only list of str. geno2 = individual2[0] # individual[0] because we can't (?) have a simple str as a deap genotype/individual, only list of str. individual1[0] = frams_cli.crossOver(geno1, geno2) individual2[0] = frams_cli.crossOver(geno1, geno2) return individual1, individual2 def frams_mutate(frams_cli, individual): individual[0] = frams_cli.mutate([individual[0]])[0] # individual[0] because we can't (?) have a simple str as a deap genotype/individual, only list of str. return individual, def frams_getsimplest(frams_cli, genetic_format, initial_genotype): return initial_genotype if initial_genotype is not None else frams_cli.getSimplest(genetic_format) def prepareToolbox(frams_cli, tournament_size, genetic_format, initial_genotype): creator.create("FitnessMax", base.Fitness, weights=[1.0] * len(OPTIMIZATION_CRITERIA)) creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMax) # would be nice to have "str" instead of unnecessary "list of str" toolbox = base.Toolbox() #toolbox.register("attr_simplest_genotype", frams_getsimplest, frams_cli, genetic_format, initial_genotype) # "Attribute generator" # (failed) struggle to have an individual which is a simple str, not a list of str # toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_frams) # https://stackoverflow.com/questions/51451815/python-deap-library-using-random-words-as-individuals # https://github.com/DEAP/deap/issues/339 # https://gitlab.com/santiagoandre/deap-customize-population-example/-/blob/master/AGbasic.py # https://groups.google.com/forum/#!topic/deap-users/22g1kyrpKy8 toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=10) toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", frams_evaluate, frams_cli) toolbox.register("mate", gp.cxOnePoint) toolbox.register("expr_mut", gp.genFull, min_=1, max_=10) toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset) if len(OPTIMIZATION_CRITERIA) <= 1: toolbox.register("select", tools.selTournament, tournsize=tournament_size) else: toolbox.register("select", tools.selNSGA2) return toolbox def parseArguments(): parser = argparse.ArgumentParser(description='Run this program with "python -u %s" if you want to disable buffering of its output.' % sys.argv[0]) parser.add_argument('-path', type=ensureDir, required=True, help='Path to Framsticks CLI without trailing slash.') parser.add_argument('-lib', required=False, help='Library name. If not given, "frams-objects.dll" or "frams-objects.so" is assumed depending on the platform.') parser.add_argument('-sim', required=False, default="eval-allcriteria.sim", help="The name of the .sim file with settings for evaluation, mutation, crossover, and similarity estimation. If not given, \"eval-allcriteria.sim\" is assumed by default. Must be compatible with the \"standard-eval\" expdef. If you want to provide more files, separate them with a semicolon ';'.") parser.add_argument('-genformat', required=False, help='Genetic format for the simplest initial genotype, for example 4, 9, or B. If not given, f1 is assumed.') parser.add_argument('-initialgenotype', required=False, help='The genotype used to seed the initial population. If given, the -genformat argument is ignored.') parser.add_argument('-opt', required=True, help='optimization criteria: vertpos, velocity, distance, vertvel, lifespan, numjoints, numparts, numneurons, numconnections (or other as long as it is provided by the .sim file and its .expdef). For multiple criteria optimization, separate the names by the comma.') parser.add_argument('-popsize', type=int, default=50, help="Population size, default: 50.") parser.add_argument('-generations', type=int, default=5, help="Number of generations, default: 5.") parser.add_argument('-tournament', type=int, default=5, help="Tournament size, default: 5.") parser.add_argument('-pmut', type=float, default=0.9, help="Probability of mutation, default: 0.9") parser.add_argument('-pxov', type=float, default=0.2, help="Probability of crossover, default: 0.2") parser.add_argument('-hof_size', type=int, default=10, help="Number of genotypes in Hall of Fame. Default: 10.") parser.add_argument('-hof_savefile', required=False, help='If set, Hall of Fame will be saved in Framsticks file format (recommended extension *.gen).') parser.add_argument('-max_numparts', type=int, default=None, help="Maximum number of Parts. Default: no limit") parser.add_argument('-max_numjoints', type=int, default=None, help="Maximum number of Joints. Default: no limit") parser.add_argument('-max_numneurons', type=int, default=None, help="Maximum number of Neurons. Default: no limit") parser.add_argument('-max_numconnections', type=int, default=None, help="Maximum number of Neural connections. Default: no limit") parser.add_argument('-max_numgenochars', type=int, default=None, help="Maximum number of characters in genotype (including the format prefix, if any). Default: no limit") return parser.parse_args() def ensureDir(string): if os.path.isdir(string): return string else: raise NotADirectoryError(string) def save_genotypes(filename, OPTIMIZATION_CRITERIA, hof): from framsfiles import writer as framswriter with open(filename, "w") as outfile: for ind in hof: keyval = {} for i, k in enumerate(OPTIMIZATION_CRITERIA): # construct a dictionary with criteria names and their values keyval[k] = ind.fitness.values[i] # TODO it would be better to save in Individual (after evaluation) all fields returned by Framsticks, and get these fields here, not just the criteria that were actually used as fitness in evolution. # Note: prior to the release of Framsticks 5.0, saving e.g. numparts (i.e. P) without J,N,C breaks re-calcucation of P,J,N,C in Framsticks and they appear to be zero (nothing serious). outfile.write(framswriter.from_collection({"_classname": "org", "genotype": ind[0], **keyval})) outfile.write("\n") print("Saved '%s' (%d)" % (filename, len(hof))) class Tree: pass class Seq: pass def frams_stick(tail): res = 'X' if tail is not None: res += tail return res def frams_paren(tail): if not tail: return '' if 'X' not in tail: return '' return '(' + tail + ')' def frams_branch(head, tail): res = '' if head is not None: res += head if tail is not None: res += ',' + tail return res def frams_modif(mod): def foo(tail): if not tail: return '' return mod + tail return foo pset = gp.PrimitiveSetTyped('main', [], Tree) pset.addPrimitive(frams_stick, [Tree], Tree) pset.addPrimitive(frams_paren, [Seq], Tree) pset.addPrimitive(frams_branch, [Tree, Seq], Seq) for mod in 'RrQqCcLlWwFf': pset.addPrimitive(frams_modif(mod), [Tree], Tree, name='mod_'+mod) pset.addTerminal('X', Tree) pset.addTerminal(None, Seq) pset.addTerminal('', Seq) if __name__ == "__main__": # random.seed(123) # see FramsticksLib.DETERMINISTIC below, set to True if you want full determinism FramsticksLib.DETERMINISTIC = False # must be set before FramsticksLib() constructor call parsed_args = parseArguments() print("Argument values:", ", ".join(['%s=%s' % (arg, getattr(parsed_args, arg)) for arg in vars(parsed_args)])) OPTIMIZATION_CRITERIA = parsed_args.opt.split(",") framsLib = FramsticksLib(parsed_args.path, parsed_args.lib, parsed_args.sim.split(";")) toolbox = prepareToolbox(framsLib, parsed_args.tournament, '1' if parsed_args.genformat is None else parsed_args.genformat, parsed_args.initialgenotype) pop = toolbox.population(n=parsed_args.popsize) hof = tools.HallOfFame(parsed_args.hof_size) stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean) stats.register("stddev", np.std) stats.register("min", np.min) stats.register("max", np.max) t = time() pop, log = algorithms.eaSimple(pop, toolbox, cxpb=parsed_args.pxov, mutpb=parsed_args.pmut, ngen=parsed_args.generations, stats=stats, halloffame=hof, verbose=True, hof_hist_path=parsed_args.hof_savefile + '_hist.txt') t = time() - t print('Best individuals:') for ind in hof: print(ind.fitness, '\t-->\t', gp.compile(ind, pset)) if parsed_args.hof_savefile is not None: path = parsed_args.hof_savefile save_genotypes(path + '_hof.txt', OPTIMIZATION_CRITERIA, hof) with open(path + '_hof.txt', 'w') as f: ind = hof[0] print(ind.fitness, file=f) print(gp.compile(ind, pset), file=f) with open(path + '_log.txt', 'w') as f: print(log, file=f) with open(path + '_time.txt', 'w') as f: print(t, file=f)
[ "maxadamski98@gmail.com" ]
maxadamski98@gmail.com
facae761933b2e6e7de763c41d592c3ecbfde2cb
5f7d6e95b6603cdae58212ed9747b48ad2466d7f
/blog_tutorial/blog/models.py
9291583caea1330a39a98dde921065ae232d07ad
[]
no_license
Davidy92/my-first-blog
364c6770258e6b2e5bbe43a294b1fba9b141b584
f502ee2a298e26e4788c58221cc2d78989977abe
refs/heads/master
2020-11-27T05:42:38.970891
2019-12-22T13:43:31
2019-12-22T13:43:31
229,325,916
0
0
null
null
null
null
UTF-8
Python
false
false
1,570
py
''' mauto models.AutoField() mbigint models.BigIntegerField() mbool models.BooleanField() mchar models.CharField() mcoseint models.CommaSeparatedIntegerField() mdate models.DateField() mdatetime models.DateTimeField() mdecimal models.DecimalField() memail models.EmailField() mfile models.FileField() mfilepath models.FilePathField() mfloat models.FloatField() mimg models.ImageField() mint models.IntegerField() mip models.IPAddressField() mnullbool models.NullBooleanField() mphone models.PhoneNumberField() mposint models.PositiveIntegerField() mpossmallin models.PositiveSmallIntegerField() mslug models.SlugField() msmallint models.SmallIntegerFiled() mtext models.TextField() mtime models.TimeField() murl models.URLField() musstate models.USStateField() mxml models.XMLField() fk models.ForeignKey() m2m models.ManyToManyField() o2o models.OneToOneField() ''' from django.conf import settings from django.db import models from django.utils import timezone ''' class creates objects, name should always start with capital letter, models.Model param tells django this is a model ''' class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
[ "davidyeritsyan@hotmail.com" ]
davidyeritsyan@hotmail.com
4dd251ea035235792579097d8424f1d000a713e1
46b09f7fb990ce5e1c2830d94e7c2628c2d77d93
/tests/test_checkers.py
8e2fe9b4b4b5c9c2af52afa67b182b3cd5117058
[ "MIT" ]
permissive
lpenz/omnilint
68b23115c2a5599fffb26eef64db0f40c759641a
359c5edab904afce19af674691f95645c897c7c7
refs/heads/main
2022-11-28T16:44:17.128396
2022-11-13T12:57:43
2022-11-13T13:27:26
81,490,304
3
1
null
null
null
null
UTF-8
Python
false
false
2,291
py
# Copyright (C) 2017 Leandro Lisboa Penz <lpenz@lpenz.org> # This file is subject to the terms and conditions defined in # file 'LICENSE', which is part of this source code package. """Test checkers""" import unittest import omnilint_test_common as common class TestCheckers(unittest.TestCase): def test_json(self): errs = common.checkthis( "json", ".json", """ { "x": "asdf", "y": 9, "z": false } """, ) self.assertEqual(errs, []) errs = common.checkthis( "json", ".json", """ { "x": "asdf", "y": 9, } """, ) self.assertEqual( [dict(e) for e in errs], [ { "line": 5, "column": 1, "message": "Expecting property name enclosed in double quotes", } ], ) def test_python_flake8(self): errs = common.checkthis("python.flake8", ".py", "import re\n") self.assertEqual( [dict(e) for e in errs], [{"line": 1, "column": 1, "message": "F401 're' imported but unused"}], ) def test_perl(self): errs = common.checkthis( "perl", ".pl", """ print "asdf\n"; """, ) self.assertEqual( [dict(e) for e in errs], [ {"line": 2, "column": 1, "message": 'Module does not end with "1;"'}, { "line": 2, "column": 1, "message": "Code not contained in explicit package", }, { "line": 2, "column": 1, "message": "Code before strictures are enabled", }, {"line": 2, "column": 1, "message": "Code before warnings are enabled"}, {"line": 2, "column": 7, "message": "Literal line breaks in a string"}, ], ) errs = common.checkthis( "perl", ".pl", """#!/usr/bin/perl use warnings; use strict; print "asdf\\n"; 1; """, ) self.assertEqual(errs, [])
[ "lpenz@lpenz.org" ]
lpenz@lpenz.org
05fea1c0bf8f06609868500456114262e1799e79
546c1b854b621898946bddc2c696ea631b442c4a
/create_friendship.py
e29e89e0b7f0b0ec8d03bafa66ba4516f1ef7503
[ "MIT" ]
permissive
agus-sideral/ln-title-generator
6ecfd08759fec682dfd1c3cb964a9f88c62809c0
dc7e6896c8d7f83e4b7a3b6c03a10a41464021ef
refs/heads/main
2023-02-13T04:53:28.773009
2021-01-15T17:40:57
2021-01-15T17:40:57
328,797,407
0
0
MIT
2021-01-14T19:16:51
2021-01-11T21:36:22
Python
UTF-8
Python
false
false
666
py
import tweepy from dotenv import load_dotenv load_dotenv() import os import twitter # Connect to Twitter api = twitter.api() # Create Friendship uwu (Follow followers) for follower in tweepy.Cursor(api.followers).items(): if not follower.following and not follower.protected: api.create_friendship(follower.id) print("Hello new friend! owo") # Destroy frienships x.x (Unfollow unfollowers) for friend in tweepy.Cursor(api.friends_ids).items(): friendship = api.show_friendship(source_id=os.getenv("ACCOUNT_ID"), target_id=str(friend)) if not friendship[0].followed_by: api.destroy_friendship(friend) print("Bye-bye friend ;_;")
[ "rabunovels@gmail.com" ]
rabunovels@gmail.com
2581774072c275bd1ba496c458dc014602629bc4
f30471b2acf537b4cce3a473296c21d38a8ca3cd
/db.py
36100be1128296e238b5a383be903d76115eaeeb
[]
no_license
AyahRamahi/cms
62f3cb0964fa455cef25ec048eb651d9ab460192
e4c47841f89d000a5251d3019b9b77beb6621dc9
refs/heads/master
2023-03-22T13:13:11.329320
2020-11-18T22:37:26
2020-11-18T22:37:26
266,096,725
1
0
null
2021-03-20T04:03:12
2020-05-22T11:44:24
CSS
UTF-8
Python
false
false
9,248
py
import pymongo import datetime import bson from werkzeug.security import generate_password_hash uri = 'mongodb+srv://admin:admin@cms-nano-lab-a2j1a.mongodb.net/test?retryWrites=true&w=majority' client = pymongo.MongoClient(uri,maxPoolSize=50, connect=False) ############################################################################## ############################# Course functions ############################### ############################################################################## def get_courses(): # returns all courses available on the db cms = client.cms courses = cms.courses courses_list = courses.find({},{'name':1, 'description':1, '_id':0}) return list(courses_list) def get_course_info(course_name): # return the content and description of a course cms = client.cms courses = cms.courses course_content = courses.find_one({'name': course_name},{'_id':0, 'content':1, 'description': 1}) return course_content def get_course_articles_count(course_name): # return the total number of articles in a course count =0 course_content = client.cms.courses.find_one({'name': course_name}, {'_id':0, 'content':1})['content'] for subject in course_content: count = count + len(subject['articles']) return count def add_new_course_subject(course_name, new_subject_name): return client.cms.courses.update_one( {'name':course_name}, {'$push': { 'content': { '$each':[{ 'subject': new_subject_name, 'articles': [] }] } } } ) def delete_course_subject(course_name, subject): content = client.cms.courses.find_one({'name': course_name}, {'_id':0, 'content':1})['content'] subject_articles = next((x for x in content if x['subject'] == subject), None)['articles'] for article in subject_articles: client.cms.articles.delete_one({'course_name': course_name, 'subject': subject, 'name': article}) return client.cms.courses.update_one( {'name':course_name}, {'$pull': { 'content': {'subject': subject } } } ) ############################################################################## ############################# Article functions ############################## ############################################################################## def get_article(course_name, subject, article_name): # returns the content of the article with given parameters cms = client.cms articles = cms.articles article = articles.find_one( {'course_name':course_name, 'subject':subject, 'name':article_name}, {'content':1, '_id':1} ) return article def mark_article_completed(username, id, course_name): # marks a specific article as completed client.cms.users.update_one( {'_id': username, 'ongoing_courses.course_name': course_name}, {'$inc': { 'ongoing_courses.$.finished_articles_count': 1 } } ) return client.cms.users.update_one( {'_id': username}, {'$push': { 'completed_articles': id } } ) def get_article_content(course_name, subject, article_name): return client.cms.articles.find_one( {'course_name':course_name, 'subject':subject, 'name':article_name}, {'_id':0, 'content':1} )['content'] def edit_article_content(course_name, subject, article_name, article_content): return client.cms.articles.update_one( {'course_name': course_name, 'subject': subject, 'name': article_name}, {'$set': { 'content': article_content } } ) def is_article_completed(username, id): # checks if a given article is completed completed_articles = client.cms.users.find_one({'_id': username}, {'_id':0, 'completed_articles':1})['completed_articles'] return str(id) in completed_articles def remove_article_from_completed(username, id, course_name): # removes an article from completed client.cms.users.update_one( {'_id': username, 'ongoing_courses.course_name': course_name}, {'$inc': { 'ongoing_courses.$.finished_articles_count': -1 } } ) return client.cms.users.update_one( {'_id': username}, {'$pull': { 'completed_articles': id } } ) ############################################################################## ############################# Comments functions ############################# ############################################################################## def get_comments(course_name, subject, article_name): # returns all comments posted on a specific article cms = client.cms articles = cms.articles article = articles.find_one( {'course_name':course_name, 'subject':subject, 'name':article_name}, {'comments':1, '_id':0} ) return article['comments'] def add_comment(course_name, subject, article_name, username, name, comment): # adds a comment on a specific article with username and name of a user and date return client.cms.articles.update_one( {'course_name':course_name, 'subject':subject, 'name':article_name}, {'$push': { 'comments': { '$each':[{ '_id': bson.objectid.ObjectId(), 'name': name, 'username': username, 'comment': comment, 'date': datetime.date.today().strftime("%d/%B/%Y") }], '$position': 0 } } } ) def delete_comment(course_name, subject, article_name, id): # deletes a comment from a specfic article with given id return client.cms.articles.update_one( {'course_name':course_name, 'subject':subject, 'name':article_name}, {'$pull': { 'comments': {'_id': bson.objectid.ObjectId(id) } } } ) ############################################################################## ############################# User functions ################################# ############################################################################## def find_user(username): # returns the user with the given username return client.cms.users.find_one({'_id': username}) def create_new_user(first_name, last_name, username, password): # creates a new user with specific info user = client.cms.users.insert_one({ '_id': username, 'password': generate_password_hash(password, method='pbkdf2:sha256'), 'first_name': first_name, 'last_name': last_name, 'completed_courses':[], 'ongoing_courses':[], 'completed_articles':[] }) return user.acknowledged def is_user_enrolled(username, course_name): # checks if the user is enrolled in a course, by checking if it's in ongoing_courses ongoing_courses = client.cms.users.find_one({'_id': username}, {'_id':0, 'ongoing_courses':1})['ongoing_courses'] completed_courses = client.cms.users.find_one({'_id': username}, {'_id':0, 'completed_courses':1})['completed_courses'] return any(courses['course_name'] == course_name for courses in ongoing_courses) or any(name == course_name for name in completed_courses) def enroll_user(username, course_name): # enrolls a user in a course by adding it to ongoing_courses return client.cms.users.update_one( {'_id': username}, {'$push': { 'ongoing_courses': { '$each':[{ 'course_name': course_name, 'finished_articles_count': 0 }], '$position': 0 } } } ) def get_ongoing_courses(username): # returns all ongoing_courses of a user return client.cms.users.find_one({'_id':username}, {'_id':0, 'ongoing_courses':1})['ongoing_courses'] def completed_course(username, course_name): # marks a course as completed by removing it from ongoing_courses and adding it # to completed courses client.cms.users.update_one( {'_id': username}, {'$pull': { 'ongoing_courses': {'course_name': course_name} } } ) return client.cms.users.update_one( {'_id': username}, {'$push': { 'completed_courses': course_name } } ) def get_completed_courses(username): # returns all completed courses of a user return client.cms.users.find_one({'_id':username}, {'_id':0, 'completed_courses':1})['completed_courses'] def change_name(username, first_name, last_name): # changes the first and last names of a user return client.cms.users.update_one( {'_id': username}, {'$set':{ 'first_name': first_name, 'last_name': last_name } } )
[ "ayah_alramahi@yahoo.com" ]
ayah_alramahi@yahoo.com
ef66ebc708185c1e459e914ea78f6c1e4dfc9942
7438407671d41035fc1896564a7e16e59ba8113d
/ecommerce/settings.py
efa3101984764637215227de619a6c6f6dd00ace
[]
no_license
angela80/tracker
92643498cbd8d5f30b1056d0f3b9da7841675b3b
102159a716376698504bb9b0146126ca7c2d33c9
refs/heads/master
2020-05-01T05:36:09.544480
2019-03-23T15:36:39
2019-03-23T15:36:39
177,306,491
0
0
null
null
null
null
UTF-8
Python
false
false
3,133
py
""" Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n)c@usl6j^)^ul37gh3f*pk990ru48k@1@g#3_=tci77d@0c0s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [os.environ.get ('C9_HOSTNAME')] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'ecommerce.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 = 'ecommerce.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
[ "angeedowling@yahoo.com" ]
angeedowling@yahoo.com
ba0ca8ac8c75d36e057ce99c43e6a42672d5a477
f33f90b60f6c454a72e0632cb1ed172ddb40b8d4
/PyNAU7802/__init__.py
ecd61cd95292c11ae2c5f371b248c68d05228b24
[ "MIT" ]
permissive
bunderhi/PyNAU7802
654354bc8ec22bd203f40d61eb68c68b3d8089ef
38d3a965ce55d0c983d30814ac854190e2e321f8
refs/heads/main
2023-06-18T11:17:23.007154
2021-07-10T00:54:01
2021-07-10T00:54:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
29
py
from .NAU7802 import NAU7802
[ "50412835+BrunoB81HK@users.noreply.github.com" ]
50412835+BrunoB81HK@users.noreply.github.com
8ce7541b66b59d98adda5d5aa0c34a877708c105
633a4d6e492d9b71ab0a091e5d83f0c6eebd6420
/baya/tests/views.py
697169322ff7ec57d2ed9f8da33cecdf3dcd0299
[ "MIT", "CC-BY-3.0" ]
permissive
counsyl/baya
d626d3930afa9dd0d21343cf220bcb9f1416af79
846a56a0eb6fc869715681b6ffe92301aa4397c8
refs/heads/master
2022-11-23T09:32:15.084945
2022-02-23T18:32:22
2022-02-23T18:32:22
51,116,568
4
6
MIT
2022-11-18T05:19:34
2016-02-05T00:45:34
Python
UTF-8
Python
false
false
447
py
from django.http import HttpResponse from baya import requires from baya import RolesNode as g A = g('a') AA = g('aa') AAA = g('aaa') B = g('b') @requires((AA | B), get=AAA, post=A) def my_view(request): return HttpResponse("my_view response") def my_undecorated_view(request): return HttpResponse("my_undecorated_view response") def query_param_view(request, name): return HttpResponse("query_param_view(%s) response" % name)
[ "sbuss@counsyl.com" ]
sbuss@counsyl.com
4d13ce8598c7756715d0365ee8af1feadd152ca1
ccbfc7818c0b75929a1dfae41dc061d5e0b78519
/aliyun-openapi-python-sdk-master/aliyun-python-sdk-dcdn/aliyunsdkdcdn/request/v20180115/DescribeDcdnUserDomainsRequest.py
a6ceff3b0d63a8ffec37cd92c60921b739b263ec
[ "Apache-2.0" ]
permissive
P79N6A/dysms_python
44b634ffb2856b81d5f79f65889bfd5232a9b546
f44877b35817e103eed469a637813efffa1be3e4
refs/heads/master
2020-04-28T15:25:00.368913
2019-03-13T07:52:34
2019-03-13T07:52:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,883
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class DescribeDcdnUserDomainsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'dcdn', '2018-01-15', 'DescribeDcdnUserDomains') def get_FuncFilter(self): return self.get_query_params().get('FuncFilter') def set_FuncFilter(self,FuncFilter): self.add_query_param('FuncFilter',FuncFilter) def get_CheckDomainShow(self): return self.get_query_params().get('CheckDomainShow') def set_CheckDomainShow(self,CheckDomainShow): self.add_query_param('CheckDomainShow',CheckDomainShow) def get_ResourceGroupId(self): return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self,ResourceGroupId): self.add_query_param('ResourceGroupId',ResourceGroupId) def get_SecurityToken(self): return self.get_query_params().get('SecurityToken') def set_SecurityToken(self,SecurityToken): self.add_query_param('SecurityToken',SecurityToken) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_DomainName(self): return self.get_query_params().get('DomainName') def set_DomainName(self,DomainName): self.add_query_param('DomainName',DomainName) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_FuncId(self): return self.get_query_params().get('FuncId') def set_FuncId(self,FuncId): self.add_query_param('FuncId',FuncId) def get_PageNumber(self): return self.get_query_params().get('PageNumber') def set_PageNumber(self,PageNumber): self.add_query_param('PageNumber',PageNumber) def get_DomainStatus(self): return self.get_query_params().get('DomainStatus') def set_DomainStatus(self,DomainStatus): self.add_query_param('DomainStatus',DomainStatus) def get_DomainSearchType(self): return self.get_query_params().get('DomainSearchType') def set_DomainSearchType(self,DomainSearchType): self.add_query_param('DomainSearchType',DomainSearchType)
[ "1478458905@qq.com" ]
1478458905@qq.com
1a571f39b973c0a7be26b6972ee2da790280f410
401398261624f41a0f44196880f50b95b315ea83
/lib/plot/summary.py
9a32230671f07cc22d938edcfc1aba960767b253
[]
no_license
knollejo/BeamImagingAnalysis
2a3b2d17e091d3d7fde1ff4518cf65799c830828
8eed4783e17226fd026e74e7a95c77ae88b63162
refs/heads/master
2022-05-30T05:34:47.787552
2020-04-28T14:37:49
2020-04-28T14:37:49
109,983,941
0
2
null
null
null
null
UTF-8
Python
false
false
4,000
py
"""Provides classes for creating summary plots. SummaryPlot: Plot summary for different models and bcids. CorrectionSummary: Plot summary of corrections for different models and bcids. ChiSquareSummary: Plot summary of chisquares for different models and bcids. """ from array import array from ROOT import TGraphErrors, TH2F, TLegend, TMultiGraph from lib.plot.plot import SingleGraphBase markers = lambda i: 20 colors = lambda i: i+1 class SummaryPlot(SingleGraphBase): """Plot a summary of values per model and bcid. __init__: Initialize. create_legend: Add a legend to the plot. """ def __init__(self, models, bcids, values, fill=4954, workinprogress=False): """Initialize a summary plot of values per model and bcid.""" nbcid, nmodels = len(bcids), len(models) order = sorted(range(nbcid), key=lambda i: bcids[i]) mini, maxi = 1.0e99, -1.0e99 multi = TMultiGraph('summary', '') for i, mod in enumerate(models): xval = array('d', [c+0.09*(i-0.5*nmodels) for c in range(nbcid)]) xerr = array('d', [0.0]*nbcid) yval = array('d', [values[i][j][0] for j in order]) yerr = array('d', [values[i][j][1] for j in order]) #[0.0]*nbcid) mini = min(mini, min([v-e for v,e in zip(yval, yerr)])) maxi = max(maxi, max([v+e for v,e in zip(yval, yerr)])) graph = TGraphErrors(nbcid, xval, yval, xerr, yerr) graph.SetName('summary_{0}'.format(mod)) multi.Add(graph) self._multi = multi mini, maxi = mini-0.08*(maxi-mini), maxi+0.25*(maxi-mini) hist = TH2F('axishist', '', nbcid, -0.5, nbcid-0.5, 100, mini, maxi) for i, j in enumerate(order): hist.GetXaxis().SetBinLabel(i+1, str(bcids[j])) SingleGraphBase.__init__(self, hist, 'summary', fill, workinprogress) for gr in multi.GetListOfGraphs(): self.add(gr, draw=False) self._xtitle = 'bcid' self._drawoption = 'AXIS' self.markers = [markers(i) for i in range(nmodels)] self.colors = [colors(i) for i in range(nmodels)] self.xrange(-0.5, nbcid-0.5) self.yrange(mini, maxi) def create_legend(self, models): """Add a legend with the model names to the plot.""" l = TLegend(0.15, 0.77, 0.85, 0.83) l.SetNColumns(3) l.SetBorderSize(0) for mod, gr, mark, clr in zip( models, self._multi.GetListOfGraphs(), self.markers, self.colors ): gr.SetMarkerStyle(mark) gr.SetMarkerColor(clr) entry = l.AddEntry(gr.GetName(), mod, 'P') entry.SetMarkerStyle(mark) entry.SetMarkerColor(clr) self.add(l) return l def _draw_first(self): SingleGraphBase._draw_first(self) self.xaxis().SetNdivisions(self._graph.GetNbinsX(), False) self._multi.Draw('P') def _draw_second(self): SingleGraphBase._draw_second(self) self.xaxis().SetLabelSize(0.03) class CorrectionSummary(SummaryPlot): """Plot a summary of corrections per model and bcid. __init__: Initialize. """ def __init__( self, models, bcids, corrections, fill=4954, workinprogress=False ): """Initialize a summary plot of corrections per model and bcid.""" SummaryPlot.__init__( self, models, bcids, corrections, fill=fill, workinprogress=workinprogress ) self._ytitle = 'correction [%]' class ChiSquareSummary(SummaryPlot): """Plot a summary of chisquares per model and bcid. __init__: Initialize. """ def __init__( self, models, bcids, chisq, fill=4954, workinprogress=False ): """Initialize a summary plot of chisquares per model and bcid.""" SummaryPlot.__init__( self, models, bcids, chisq, fill=fill, workinprogress=workinprogress ) self._ytitle = '#chi^{2}/d.o.f.'
[ "joscha.knolle@cern.ch" ]
joscha.knolle@cern.ch
8d0c8cc9cc01e3d228f1890675c4f7e08176b7b2
806ebdf404c4ee78c36dc78faf344bf7dcf66d63
/starbucks_analysis_app/__init__.py
5367a6f8aa30fd678a17e535c5d53a033e4229e9
[ "Apache-2.0" ]
permissive
matthewgela/udacity-starbucks-ui
b59a6cd56ac3498b3d89daac0d5ecca71f60c157
d828da17e4de35eefbe58ab56dd1e2704157bf23
refs/heads/main
2023-05-05T09:41:08.084220
2021-06-04T16:44:07
2021-06-04T16:44:07
336,858,504
0
0
Apache-2.0
2021-06-02T23:03:13
2021-02-07T18:24:24
Python
UTF-8
Python
false
false
90
py
from flask import Flask app = Flask(__name__) from starbucks_analysis_app import routes
[ "matthewgela@matts-mbp-2020.home" ]
matthewgela@matts-mbp-2020.home
6fd5046d2b672d4f207fae03da8e14b2c84b56ac
ffe97db1226d24a2591bb34ce89c83964f11e5b1
/mariadb/app.py
9ddbefe57f034b29b05c832d2416dd72644ca7c6
[]
no_license
sweetfruit77/kgitbank-python
60fec0aa5616227cf1f03d7a41ff043d44763fe4
e8213c93e583b55f21bc9404fc0014855a7928f5
refs/heads/master
2020-05-04T05:29:35.963902
2019-04-06T01:29:20
2019-04-06T01:29:20
178,985,997
0
0
null
2019-04-06T01:29:21
2019-04-02T02:47:22
Jupyter Notebook
UTF-8
Python
false
false
570
py
from flask import Flask, render_template, redirect,url_for,request import DBConn app = Flask(__name__) @app.route('/login', methods= ['GET','POST']) def login(): if request.method == 'GET': return render_template('login.html') else: uid = request.form.get('username') upw = request.form.get('password') row = DBConn.loginSQL(uid, upw) if row: return '로그인 되었습니다' else: return '로그인 실패' if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True)
[ "shimseonjo@gmail.com" ]
shimseonjo@gmail.com
e15796201cccdb83580cf1217070eadd0c82a6d6
189bd8fb013506fb53c0422615f3231369feaa7b
/client/models.py
e5a2c771163fd5de8ffe5e2e0eef468027924558
[]
no_license
aholodoff/living-and-dead
19443031867b9c04d17ac7f658d7c7392cb53b24
209de1ff1667a3962bfa7383f38b72401d6c7ff7
refs/heads/master
2021-07-14T03:45:49.189180
2017-10-15T19:06:46
2017-10-15T19:06:46
104,656,686
0
0
null
null
null
null
UTF-8
Python
false
false
6,909
py
from django.db import models from django.conf import settings from django.contrib.auth.models import Group # РЕГИОНЫ СТРАНЫ class Region(models.Model): """ Регион (область, край) """ name = models.CharField( 'Наименование республики/края/области/округа', max_length=80) def __str__(self): return self.name[:31] class Meta: ordering = ('id',) verbose_name = 'Республика / Край / Область / Округ' verbose_name_plural = 'Республики / Края / Области / Округа' # МУНИЦИПАЛЬНЫЕ ОБРАЗОВАНИЯ ПО РЕГИОНАМ class District(models.Model): """ Район (субъект) """ region = models.ForeignKey(Region, related_name='district') kind = models.CharField( 'Тип муниципального образования', max_length=80) name = models.CharField( 'Наименование муниципального образования', max_length=80) okato = models.CharField( """Общероссийский классификатор объектов административно-территориального деления""", max_length=32) oktmo = models.CharField( """Общероссийский классификатор территорий муниципальных образований""", max_length=32) def __str__(self): if 'район' in self.kind: return ' '.join([self.region.name, self.name, self.kind]) else: return ' '.join([self.region.name, self.kind, self.name]) class Meta: ordering = ('id',) verbose_name = 'Муниципальное образование' verbose_name_plural = 'Муниципальные образования' # АБСТРАКТНЫЙ КЛАСС ФИЗЛИЦА class Person(models.Model): """ Физическое лицо """ first_name = models.CharField( 'Имя', max_length=128) sur_name = models.CharField( 'Отчество', max_length=256, blank=True) last_name = models.CharField( 'Фамилия', max_length=128) birth_date = models.DateField( 'Дата рождения', blank=True, null=True) no_phone = models.TextField( 'Контактный телефон', blank=True) created = models.DateTimeField( 'Дата и время внесения в базу', auto_now_add=True) modified = models.DateTimeField( 'Дата и время изменения в базе', auto_now=True) def __str__(self): return ' '.join([self.last_name, self.first_name]) def full_name(self): return ' '.join([self.last_name, self.first_name, self.sur_name]) class Meta: abstract = True # ОРГАНИЗАЦИЯ, ЮРЛИЦО class Organization(models.Model): """ Организация """ with_us = models.BooleanField('Загегистрирована ли организация', default=False) group = models.ForeignKey(Group, default=1, on_delete=models.CASCADE, related_name='organization') full_name = models.CharField( 'Полное наименование', max_length=512) name = models.CharField( 'Сокращённое наименование', max_length=80) inn = models.CharField( 'ИНН', max_length=12) kpp = models.CharField( 'КПП', max_length=12) district = models.ForeignKey(District, default=6, help_text='Муниципальное образование', related_name='organization') legal_address = models.TextField( 'Юридический адрес') actual_address = models.TextField( 'Фактический адрес') no_phone = models.TextField( 'Телефон бухгалтерии') email = models.EmailField( 'e-mail') no_users = models.PositiveSmallIntegerField( 'Заявляемое количество пользователей', default=1) created = models.DateTimeField( 'Дата и время внесения в базу', auto_now_add=True) modified = models.DateTimeField( 'Дата и время изменения в базе', auto_now=True) def __str__(self): return self.name class Meta: verbose_name = 'Организация' verbose_name_plural = 'Организации' permissions = ( ('can_view', 'Могут видеть доступные организации'), ('can_change', 'Могут менять данные об организации'), ) # ПРАВОМОЧНЫЙ ПРЕДСТАВИТЕЛЬ ОРГАНИЗАЦИИ class AuthorizedPerson(Person): """ Подписывающее договор лицо """ organization = models.ForeignKey(Organization, related_name='authorized_person') class Meta: verbose_name = 'Подписывающее договор лицо' verbose_name_plural = 'Подписывающее договора лица' # КОНТАКТНОЕ ЛИЦО - АДМИН ОРГАНИЗАЦИИ class AdminOfOrganization(Person): """ Контактное лицо - администратор организации """ organization = models.ForeignKey(Organization, related_name='contact_person') class Meta: verbose_name = 'Контактный администратор' verbose_name_plural = 'Контактные администраторы' # ПРОФИЛЬ ПОЛЬЗОВАТЕЛЯ ОРГАНИЗАЦИИ class Profile(models.Model): """ Профиль клиента с аватарками и IP """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile') avatar = models.ImageField( upload_to='images/users', verbose_name='Изображение') ip = models.GenericIPAddressField( verbose_name='IP пользователя') organization = models.ForeignKey(Organization, related_name='profile') def get_user_ip(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip class Meta: verbose_name = 'Профиль Пользователя' verbose_name_plural = 'Профили Пользователей'
[ "frost4lex@gmail.com" ]
frost4lex@gmail.com
d66744191baeac33e55cdf0ea841e436dba3bb7c
e58c656f59f9d8c9f2b5893c6892d1651e028bed
/code_examples/chapter3/find_workers.py
ac5e6a344f737f6c6066cce2110af26688ca8a40
[ "MIT" ]
permissive
palao/RobustPython
c6f50ed6071b41daa78e933cacc70587308034a3
dafb95d801dff2c8ff7856ba46d3c052d54e0033
refs/heads/master
2023-06-13T05:28:13.156239
2021-07-05T23:45:01
2021-07-05T23:45:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,386
py
import datetime import random from typing import List class WorkerDatabase: def get_all_workers(self) -> list[str]: return [] def get_emergency_workers(): return [] def is_available(name: str): return True worker_database = WorkerDatabase() OWNER = 'Pat' def schedule(worker, open_time): pass def schedule_restaurant_open(open_time: datetime.datetime, workers_needed: int): workers = find_workers_available_for_time(open_time) # use random.sample to pick X available workers # where X is the number of workers needed. for worker in random.sample(workers, workers_needed): schedule(worker, open_time) def find_workers_available_for_time(open_time: datetime.datetime): workers = worker_database.get_all_workers() available_workers = [worker for worker in workers if is_available(worker)] if available_workers: return available_workers # fall back to workers who listed they are available in # in an emergency emergency_workers = [worker for worker in get_emergency_workers() if is_available(worker)] if emergency_workers: return emergency_workers # Schedule the owner to open, they will find someone else return [OWNER] assert find_workers_available_for_time(datetime.datetime.now()) == ["Pat"]
[ "patviafore@gmail.com" ]
patviafore@gmail.com
e2bcd08d485deb596bd260afb3ac629d3a8e9f43
5e9ac9c02e1b1b4da7242f10489e849b6141faee
/Python-Programming/Tree/Connect-Same-Level-Siblings.py
ac513e5228574839fc2ca1db3f2d1556c798ad94
[]
no_license
tuananh8497/technical-interview-prep
e4db316b69c314e25d4784db3922f687e060fdc4
8264606adf3da59612d5e4438fbfbfed19b7c93e
refs/heads/master
2022-12-14T16:51:19.807203
2020-09-09T23:24:56
2020-09-09T23:24:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,497
py
def connect_next_level(head): current = head next_level_head = None prev = None # keep track of the previously connected nodes while current != None: # If the current node has both the left and right child, connect them with each other and with the previously connected nodes if current.left != None and current.right != None: if next_level_head == None: next_level_head = current.left current.left.next = current.right if prev != None: prev.next = current.left prev = current.right # If the current node has only left child, connect it with previously connected nodes elif current.left != None: if next_level_head == None: next_level_head = current.left if prev != None: prev.next = current.left prev = current.left # If the current node has only right child, connect it with previously connected nodes elif current.right != None: if next_level_head == None: next_level_head = current.right if prev != None: prev.next = current.right prev = current.right current = current.next if prev != None: prev.next = None return next_level_head def populate_sibling_pointers(root): if root == None: return root.next = None while root != None: root = connect_next_level(root)
[ "le_j6@denison.edu" ]
le_j6@denison.edu
91d12b3fef71147938beea4f78739d3ed32ac7de
28c1be1f01ef60151c4236a53bafd0d41763249f
/rango/migrations/0001_initial.py
97180f752ce6d5acef5de9a3e36a20f92a2d643b
[]
no_license
michellemhey/django-tutorial
65a533e78c4044bbe04d98fc14701e28c0e1ceb5
71b7f44402de596234ac5772f25f340f5eccd01d
refs/heads/master
2020-03-23T20:48:31.642867
2018-07-24T18:33:16
2018-07-24T18:33:16
142,063,867
0
0
null
null
null
null
UTF-8
Python
false
false
1,098
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-07-24 16:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128, unique=True)), ], ), migrations.CreateModel( name='Page', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=128)), ('url', models.URLField()), ('views', models.IntegerField(default=0)), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rango.Category')), ], ), ]
[ "michellehey@Michelles-MacBook-Pro.local" ]
michellehey@Michelles-MacBook-Pro.local
b95a64c2cbd52bc20efcee22d1ed0e8e6a3f7fdd
44eb4b7c9cb8891cb3544936c7bbf8536eb2714c
/src/912_heapSort.py
c9bd6f8857cb035cb5a18df97e56f559cb46de74
[]
no_license
xf97/myLeetCodeSolutions
7a330089e14c6d44a0de0de8b034f2a759c17348
5de6aa3977117e59ef69307894e163351b1d88fa
refs/heads/master
2023-08-18T09:27:09.900780
2021-10-18T04:44:36
2021-10-18T04:44:36
291,883,909
1
0
null
null
null
null
UTF-8
Python
false
false
1,641
py
class Solution: def sortArray(self, nums: List[int]) -> List[int]: #干翻腾讯! #今天手写堆排序 #四个步骤 #主函数调用堆排序 #堆排序里,先初始化堆,再从后向前逐个构造堆 #初始化堆方法,从后向前,从当前i到最后元素构造堆 #构造堆方法,先交换当前最后元素和堆首元素,然后从0到当前元素构造堆 #如何构造堆,从root到尾,在左元素在堆中时,判断下一个要跟根元素比较的元素,然后看是否要和根元素的交换,如果要交换就交换后更改根几点,否则跳出循环 self.heapSort(nums) return nums def heapSort(self, nums): #先初始化堆 self.buildHeap(nums) #然后从后向前,交换每一个元素后重新构造堆 for i in range(len(nums) - 1, -1, -1): nums[i], nums[0] = nums[0], nums[i] self.maxHeap(nums, 0, i) #构造0-i的堆 return def buildHeap(self, nums): for i in range(len(nums) - 1, -1, -1): self.maxHeap(nums, i, len(nums)) def maxHeap(self, nums, root, length): p = root while p * 2 + 1 < length: l, r = p * 2 + 1, p * 2 + 2 #判断下一个节点是谁 if length <= r or nums[r] < nums[l]: nex = l else: nex = r if nums[p] < nums[nex]: #交换根节点 nums[p], nums[nex] = nums[nex], nums[p] p = nex else: break
[ "noreply@github.com" ]
xf97.noreply@github.com
b34a563e353764930fecdd0e6a533e634df2f1bd
251603f611d9661fcd7b6efa0a4f9b0f6f033b50
/stock-test_1.0.py
d41fbc07c06947f736f6d19f4eabad5ec0839749
[]
no_license
Alle-Projekte/Python--stock_information
ec671a7010b47baa8974558f3197ad1e0b9458b9
698a59461a3cac47b521fa7c263c95e4df7cb20f
refs/heads/master
2022-11-07T18:05:35.504074
2020-06-28T04:21:22
2020-06-28T04:21:22
268,558,468
0
0
null
null
null
null
UTF-8
Python
false
false
4,385
py
''' The goal of this program is to extract a list of stock symbols from an Excel file, get it's information from Yahoo Finance, and store it in a new Excel file. BTW idiot, this is the 1st-file. Learn how to document next time -_-, and come up with better names for these god damned variables. Some of them make no sense. ''' import bs4, requests, pyperclip, os, openpyxl, time from bs4 import BeautifulSoup as soup def getURLtd(something): #Takes the symbol, extracts the page and stores needed information in a variable. url = requests.get(r'https://finance.yahoo.com/quote/' + something + r'/key-statistics?p=' + something) html = soup(url.text, 'html.parser') starter_html = html.find('div', class_="Fl(start) smartphone_W(100%) W(100%)") start_html = html.find('div', class_="Fl(start) W(50%) smartphone_W(100%)") end_html = html.find('div', class_="Fl(end) W(50%) smartphone_W(100%)") dude = starter_html.findAll('td') dude1 = start_html.findAll('td') dude2 = end_html.findAll('td') h = 0 for x in dude[0:2]: dude1.insert(h, x) h += 1 dude1.extend(dude2) return dude1 def tdToText(something1): #Turns parsed information to text and stores it into a list list1 = [] for x in something1: list1.append(x.text) return list1 def getList1Even(something2): #Extracts even indexes from list1 list and stores it into list2 list2 = [] for i in range(1,len(something2),2): list2.append(something2[i]) return list2 def getList1Odd(something3): #Extracts odd indexes from list1 list and stores it into list3 list3 = [] for i in range(0,len(something3),2): list3.append(something3[i]) return list3 #Changes the current file path to your desktop. desktop = os.path.join(os.environ['USERPROFILE'], 'Desktop') os.chdir(desktop) #Creates an Excel workbook and gets its 1st sheet wb = openpyxl.Workbook() sheet = wb.get_sheet_by_name('Sheet') #This should be a funxtion and will loop through an Excel file to extract stock symbols #and store it in the 'symbol" list. #------------------------------------------------------------------------------------------ fileName = input('Enter the name of the file: ') wb1 = openpyxl.load_workbook(fileName.lower() + '.xlsx') sheet1 = wb1.get_sheet_by_name('Basic View') row = 1 symbol = [] #row < 1040 while row < sheet1.max_row: stock = sheet1['A' + str(row)].value symbol.append(stock) row += 1 #symbol1 = symbol[888:1041] # symbol1 = ['AVCT', 'OCGN', 'OCSL', 'ODP', 'ONCY', 'ONTX', 'OPTT', 'ORMP', 'OSG', 'PDLI'] #['AMZN', 'DYNT', 'GOOGL',] 'AMZN', 'NVDA', 'NFLX'] url = requests.get(r'https://finance.yahoo.com/quote/GOOGL/key-statistics?p=GOOGL') html = soup(url.text, 'html.parser') starter_html = html.find('div', class_="Fl(start) smartphone_W(100%) W(100%)") start_html = html.find('div', class_="Fl(start) W(50%) smartphone_W(100%)") end_html = html.find('div', class_="Fl(end) W(50%) smartphone_W(100%)") dude = starter_html.findAll('td') dude1 = start_html.findAll('td') dude2 = end_html.findAll('td') h = 0 for x in dude[0:2]: dude1.insert(h, x) h += 1 dude1.extend(dude2) list1 = [] for x in dude1: list1.append(x.text) list3 = getList1Odd(list1) list3_1 = [list3[x] for x in (0, 7, 15, 17, 23, 24, 33, 34, 35, 38)] #Specifies where to start and stores the list3 information into the Excel workbook. row, column = 1, 2 for a in list3_1: sheet.cell(row, column).value = a column += 1 row, column = 2, 1 for j in symbol: sheet.cell(row, column).value = j row += 1 count = 2 for w in symbol: try: td = getURLtd(w) tdList = tdToText(td) listEven = getList1Even(tdList) list2 = [listEven[x] for x in (0, 7, 15, 17, 23, 24, 33, 34, 35, 38)] #Specifies where to start and stores the list2 information into the Excel workbook. row, column = count, 2 for b in list2: sheet.cell(row, column).value = b column += 1 count += 1 time.sleep(1) except AttributeError: print(w) #Saves the Excel workbook in the current directory wb.save('heyThere.xlsx')
[ "facts82@yahoo.com" ]
facts82@yahoo.com
0323b8f4d610f2595f5e7520f90ac1a246c98bc1
f10abd5892380587f6e649c9cf49c2331361410e
/kaggle_competitions/molecular_activity/src/utils.py
db5882b4915c168bf9f22419c948862ced435716
[]
no_license
Pthinker/DataProjects
3ff2dc7c048e77781a0240dd2a9827f91f689cc6
d9a565b5e43a36f6c14f102b014c85980c1cd110
refs/heads/master
2020-12-24T17:17:42.301945
2018-02-06T18:56:01
2018-02-06T18:56:01
9,349,951
0
0
null
null
null
null
UTF-8
Python
false
false
937
py
#!/usr/bin/env python import numpy as np import config def read_train(fpath): fh = open(fpath) header = fh.readline().strip() arr = header.split(",") descriptors = arr[2:] molecules = [] act = [] matrix = [] for line in fh: line = line.strip() arr = line.split(",") molecules.append(arr.pop(0)) act.append(float(arr.pop(0))) matrix.append(map(int, arr)) return np.array(matrix), descriptors, molecules, np.array(act) def read_test(fpath): fh = open(fpath) header = fh.readline().strip() arr = header.split(",") descriptors = arr[1:] molecules = [] matrix = [] for line in fh: line = line.strip() arr = line.split(",") molecules.append(arr.pop(0)) matrix.append(map(int, arr)) return np.array(matrix), descriptors, molecules def main(): pass if __name__ == "__main__": main()
[ "davidzhang.seu@gmail.com" ]
davidzhang.seu@gmail.com
0c9dc0dd6c141afb46104b5b979626f540012553
220a4579178017aa984ee41a01ecdf1d17cae2e0
/poker/scraper/backup/ui_table_setup.py
e6d576ace8f367c2b4a3b757f6006bed4f73f246
[]
no_license
jinyiabc/Poker
6f4bc2bbb0fcb2092a5b4935732db5be7243274e
86401e6eebff5431992b506eccd94cb6b5497dce
refs/heads/master
2021-08-20T05:09:14.495827
2021-06-09T01:35:26
2021-06-09T01:35:26
170,704,274
0
0
null
2019-02-14T14:29:13
2019-02-14T14:29:13
null
UTF-8
Python
false
false
77,217
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_table_setup.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_table_setup_form(object): def setupUi(self, table_setup_form): table_setup_form.setObjectName("table_setup_form") table_setup_form.resize(1235, 962) self.scrollArea = QtWidgets.QScrollArea(table_setup_form) self.scrollArea.setGeometry(QtCore.QRect(10, 590, 841, 341)) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 839, 339)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents) self.gridLayout.setObjectName("gridLayout") self.screenshot_label = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.screenshot_label.setText("") self.screenshot_label.setObjectName("screenshot_label") self.gridLayout.addWidget(self.screenshot_label, 0, 0, 1, 1) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.crop = QtWidgets.QPushButton(table_setup_form) self.crop.setGeometry(QtCore.QRect(550, 270, 311, 41)) self.crop.setObjectName("crop") self.topleft_corner = QtWidgets.QPushButton(table_setup_form) self.topleft_corner.setGeometry(QtCore.QRect(720, 240, 141, 21)) self.topleft_corner.setObjectName("topleft_corner") self.tesseract = QtWidgets.QPushButton(table_setup_form) self.tesseract.setGeometry(QtCore.QRect(540, 370, 201, 31)) self.tesseract.setObjectName("tesseract") self.take_screenshot_button = QtWidgets.QPushButton(table_setup_form) self.take_screenshot_button.setGeometry(QtCore.QRect(550, 180, 311, 41)) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(8) font.setBold(False) font.setItalic(False) font.setWeight(50) self.take_screenshot_button.setFont(font) self.take_screenshot_button.setObjectName("take_screenshot_button") self.label_3 = QtWidgets.QLabel(table_setup_form) self.label_3.setGeometry(QtCore.QRect(540, 410, 131, 16)) self.label_3.setObjectName("label_3") self.tesseract_label = QtWidgets.QLabel(table_setup_form) self.tesseract_label.setGeometry(QtCore.QRect(660, 410, 81, 16)) self.tesseract_label.setObjectName("tesseract_label") self.tabWidget = QtWidgets.QTabWidget(table_setup_form) self.tabWidget.setGeometry(QtCore.QRect(10, 40, 511, 431)) self.tabWidget.setObjectName("tabWidget") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.groupBox = QtWidgets.QGroupBox(self.tab_2) self.groupBox.setGeometry(QtCore.QRect(10, 30, 227, 321)) self.groupBox.setObjectName("groupBox") self.gridLayout_6 = QtWidgets.QGridLayout(self.groupBox) self.gridLayout_6.setObjectName("gridLayout_6") self.gridLayout_3 = QtWidgets.QGridLayout() self.gridLayout_3.setObjectName("gridLayout_3") self.raise_button = QtWidgets.QPushButton(self.groupBox) self.raise_button.setObjectName("raise_button") self.gridLayout_3.addWidget(self.raise_button, 2, 0, 1, 1) self.all_in_call_button = QtWidgets.QPushButton(self.groupBox) self.all_in_call_button.setObjectName("all_in_call_button") self.gridLayout_3.addWidget(self.all_in_call_button, 6, 0, 1, 1) self.buttons_search_area = QtWidgets.QPushButton(self.groupBox) self.buttons_search_area.setObjectName("buttons_search_area") self.gridLayout_3.addWidget(self.buttons_search_area, 0, 0, 1, 1) self.fold_button = QtWidgets.QPushButton(self.groupBox) self.fold_button.setObjectName("fold_button") self.gridLayout_3.addWidget(self.fold_button, 4, 0, 1, 1) self.im_back = QtWidgets.QPushButton(self.groupBox) self.im_back.setObjectName("im_back") self.gridLayout_3.addWidget(self.im_back, 11, 0, 1, 1) self.lost_everything = QtWidgets.QPushButton(self.groupBox) self.lost_everything.setObjectName("lost_everything") self.gridLayout_3.addWidget(self.lost_everything, 10, 0, 1, 1) self.check_button = QtWidgets.QPushButton(self.groupBox) self.check_button.setObjectName("check_button") self.gridLayout_3.addWidget(self.check_button, 3, 0, 1, 1) self.call_button = QtWidgets.QPushButton(self.groupBox) self.call_button.setObjectName("call_button") self.gridLayout_3.addWidget(self.call_button, 1, 0, 1, 1) self.my_turn = QtWidgets.QPushButton(self.groupBox) self.my_turn.setObjectName("my_turn") self.gridLayout_3.addWidget(self.my_turn, 8, 0, 1, 1) self.my_turn_search_area = QtWidgets.QPushButton(self.groupBox) self.my_turn_search_area.setObjectName("my_turn_search_area") self.gridLayout_3.addWidget(self.my_turn_search_area, 7, 0, 1, 1) self.lost_everything_search_area = QtWidgets.QPushButton(self.groupBox) self.lost_everything_search_area.setObjectName("lost_everything_search_area") self.gridLayout_3.addWidget(self.lost_everything_search_area, 9, 0, 1, 1) self.fast_fold_button = QtWidgets.QPushButton(self.groupBox) self.fast_fold_button.setObjectName("fast_fold_button") self.gridLayout_3.addWidget(self.fast_fold_button, 5, 0, 1, 1) self.gridLayout_6.addLayout(self.gridLayout_3, 0, 0, 1, 1) self.groupBox_6 = QtWidgets.QGroupBox(self.tab_2) self.groupBox_6.setGeometry(QtCore.QRect(260, 30, 223, 91)) self.groupBox_6.setObjectName("groupBox_6") self.gridLayout_4 = QtWidgets.QGridLayout(self.groupBox_6) self.gridLayout_4.setObjectName("gridLayout_4") self.verticalLayout_4 = QtWidgets.QVBoxLayout() self.verticalLayout_4.setObjectName("verticalLayout_4") self.my_cards_area = QtWidgets.QPushButton(self.groupBox_6) self.my_cards_area.setObjectName("my_cards_area") self.verticalLayout_4.addWidget(self.my_cards_area) self.table_cards_area = QtWidgets.QPushButton(self.groupBox_6) self.table_cards_area.setObjectName("table_cards_area") self.verticalLayout_4.addWidget(self.table_cards_area) self.gridLayout_4.addLayout(self.verticalLayout_4, 1, 0, 1, 1) self.groupBox_10 = QtWidgets.QGroupBox(self.tab_2) self.groupBox_10.setGeometry(QtCore.QRect(260, 130, 221, 221)) self.groupBox_10.setObjectName("groupBox_10") self.gridLayout_7 = QtWidgets.QGridLayout(self.groupBox_10) self.gridLayout_7.setObjectName("gridLayout_7") self.verticalLayout_3 = QtWidgets.QVBoxLayout() self.verticalLayout_3.setObjectName("verticalLayout_3") self.total_pot_area = QtWidgets.QPushButton(self.groupBox_10) self.total_pot_area.setObjectName("total_pot_area") self.verticalLayout_3.addWidget(self.total_pot_area) self.current_round_pot = QtWidgets.QPushButton(self.groupBox_10) self.current_round_pot.setObjectName("current_round_pot") self.verticalLayout_3.addWidget(self.current_round_pot) self.raise_value = QtWidgets.QPushButton(self.groupBox_10) self.raise_value.setFlat(False) self.raise_value.setObjectName("raise_value") self.verticalLayout_3.addWidget(self.raise_value) self.call_value = QtWidgets.QPushButton(self.groupBox_10) self.call_value.setObjectName("call_value") self.verticalLayout_3.addWidget(self.call_value) self.all_in_call_value = QtWidgets.QPushButton(self.groupBox_10) self.all_in_call_value.setObjectName("all_in_call_value") self.verticalLayout_3.addWidget(self.all_in_call_value) self.game_number = QtWidgets.QPushButton(self.groupBox_10) self.game_number.setObjectName("game_number") self.verticalLayout_3.addWidget(self.game_number) self.gridLayout_7.addLayout(self.verticalLayout_3, 0, 0, 1, 1) self.tabWidget.addTab(self.tab_2, "") self.players_tab = QtWidgets.QWidget() self.players_tab.setObjectName("players_tab") self.groupBox_2 = QtWidgets.QGroupBox(self.players_tab) self.groupBox_2.setGeometry(QtCore.QRect(20, 40, 451, 191)) self.groupBox_2.setObjectName("groupBox_2") self.gridLayout_5 = QtWidgets.QGridLayout(self.groupBox_2) self.gridLayout_5.setObjectName("gridLayout_5") self.groupBox_4 = QtWidgets.QGroupBox(self.groupBox_2) self.groupBox_4.setObjectName("groupBox_4") self.current_player = QtWidgets.QComboBox(self.groupBox_4) self.current_player.setGeometry(QtCore.QRect(10, 30, 91, 22)) self.current_player.setObjectName("current_player") self.current_player.addItem("") self.current_player.addItem("") self.current_player.addItem("") self.current_player.addItem("") self.current_player.addItem("") self.current_player.addItem("") self.gridLayout_5.addWidget(self.groupBox_4, 1, 0, 1, 1) self.groupBox_3 = QtWidgets.QGroupBox(self.groupBox_2) self.groupBox_3.setObjectName("groupBox_3") self.max_players = QtWidgets.QComboBox(self.groupBox_3) self.max_players.setGeometry(QtCore.QRect(10, 20, 91, 22)) self.max_players.setObjectName("max_players") self.max_players.addItem("") self.gridLayout_5.addWidget(self.groupBox_3, 0, 0, 1, 1) self.formLayout_2 = QtWidgets.QFormLayout() self.formLayout_2.setObjectName("formLayout_2") self.player_pot_area = QtWidgets.QPushButton(self.groupBox_2) self.player_pot_area.setObjectName("player_pot_area") self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.player_pot_area) self.button_search_area = QtWidgets.QPushButton(self.groupBox_2) self.button_search_area.setObjectName("button_search_area") self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.button_search_area) self.player_funds_area = QtWidgets.QPushButton(self.groupBox_2) self.player_funds_area.setObjectName("player_funds_area") self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.player_funds_area) self.player_name_area = QtWidgets.QPushButton(self.groupBox_2) self.player_name_area.setObjectName("player_name_area") self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.player_name_area) self.covered_card_area = QtWidgets.QPushButton(self.groupBox_2) self.covered_card_area.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.covered_card_area.setToolTipDuration(9) self.covered_card_area.setObjectName("covered_card_area") self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.covered_card_area) self.gridLayout_5.addLayout(self.formLayout_2, 0, 1, 2, 1) self.tabWidget.addTab(self.players_tab, "") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.groupBox_5 = QtWidgets.QGroupBox(self.tab_4) self.groupBox_5.setGeometry(QtCore.QRect(10, 0, 491, 401)) self.groupBox_5.setObjectName("groupBox_5") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox_5) self.verticalLayout_2.setObjectName("verticalLayout_2") self.MYCARD_LEFT = QtWidgets.QVBoxLayout() self.MYCARD_LEFT.setObjectName("MYCARD_LEFT") self.horizontalLayout_10 = QtWidgets.QHBoxLayout() self.horizontalLayout_10.setObjectName("horizontalLayout_10") self.card_ahl = QtWidgets.QPushButton(self.groupBox_5) self.card_ahl.setObjectName("card_ahl") self.horizontalLayout_10.addWidget(self.card_ahl) self.card_khl = QtWidgets.QPushButton(self.groupBox_5) self.card_khl.setObjectName("card_khl") self.horizontalLayout_10.addWidget(self.card_khl) self.card_qhl = QtWidgets.QPushButton(self.groupBox_5) self.card_qhl.setObjectName("card_qhl") self.horizontalLayout_10.addWidget(self.card_qhl) self.card_jhl = QtWidgets.QPushButton(self.groupBox_5) self.card_jhl.setObjectName("card_jhl") self.horizontalLayout_10.addWidget(self.card_jhl) self.card_thl = QtWidgets.QPushButton(self.groupBox_5) self.card_thl.setObjectName("card_thl") self.horizontalLayout_10.addWidget(self.card_thl) self.card_9hl = QtWidgets.QPushButton(self.groupBox_5) self.card_9hl.setObjectName("card_9hl") self.horizontalLayout_10.addWidget(self.card_9hl) self.card_8hl = QtWidgets.QPushButton(self.groupBox_5) self.card_8hl.setObjectName("card_8hl") self.horizontalLayout_10.addWidget(self.card_8hl) self.card_7hl = QtWidgets.QPushButton(self.groupBox_5) self.card_7hl.setObjectName("card_7hl") self.horizontalLayout_10.addWidget(self.card_7hl) self.card_6hl = QtWidgets.QPushButton(self.groupBox_5) self.card_6hl.setObjectName("card_6hl") self.horizontalLayout_10.addWidget(self.card_6hl) self.card_5hl = QtWidgets.QPushButton(self.groupBox_5) self.card_5hl.setObjectName("card_5hl") self.horizontalLayout_10.addWidget(self.card_5hl) self.card_4hl = QtWidgets.QPushButton(self.groupBox_5) self.card_4hl.setObjectName("card_4hl") self.horizontalLayout_10.addWidget(self.card_4hl) self.card_3hl = QtWidgets.QPushButton(self.groupBox_5) self.card_3hl.setObjectName("card_3hl") self.horizontalLayout_10.addWidget(self.card_3hl) self.card_2hl = QtWidgets.QPushButton(self.groupBox_5) self.card_2hl.setObjectName("card_2hl") self.horizontalLayout_10.addWidget(self.card_2hl) self.MYCARD_LEFT.addLayout(self.horizontalLayout_10) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.card_asl = QtWidgets.QPushButton(self.groupBox_5) self.card_asl.setObjectName("card_asl") self.horizontalLayout_2.addWidget(self.card_asl) self.card_ksl = QtWidgets.QPushButton(self.groupBox_5) self.card_ksl.setObjectName("card_ksl") self.horizontalLayout_2.addWidget(self.card_ksl) self.card_qsl = QtWidgets.QPushButton(self.groupBox_5) self.card_qsl.setObjectName("card_qsl") self.horizontalLayout_2.addWidget(self.card_qsl) self.card_jsl = QtWidgets.QPushButton(self.groupBox_5) self.card_jsl.setObjectName("card_jsl") self.horizontalLayout_2.addWidget(self.card_jsl) self.card_tsl = QtWidgets.QPushButton(self.groupBox_5) self.card_tsl.setObjectName("card_tsl") self.horizontalLayout_2.addWidget(self.card_tsl) self.card_9sl = QtWidgets.QPushButton(self.groupBox_5) self.card_9sl.setObjectName("card_9sl") self.horizontalLayout_2.addWidget(self.card_9sl) self.card_8sl = QtWidgets.QPushButton(self.groupBox_5) self.card_8sl.setObjectName("card_8sl") self.horizontalLayout_2.addWidget(self.card_8sl) self.card_7sl = QtWidgets.QPushButton(self.groupBox_5) self.card_7sl.setObjectName("card_7sl") self.horizontalLayout_2.addWidget(self.card_7sl) self.card_6sl = QtWidgets.QPushButton(self.groupBox_5) self.card_6sl.setObjectName("card_6sl") self.horizontalLayout_2.addWidget(self.card_6sl) self.card_5sl = QtWidgets.QPushButton(self.groupBox_5) self.card_5sl.setObjectName("card_5sl") self.horizontalLayout_2.addWidget(self.card_5sl) self.card_4sl = QtWidgets.QPushButton(self.groupBox_5) self.card_4sl.setObjectName("card_4sl") self.horizontalLayout_2.addWidget(self.card_4sl) self.card_3sl = QtWidgets.QPushButton(self.groupBox_5) self.card_3sl.setObjectName("card_3sl") self.horizontalLayout_2.addWidget(self.card_3sl) self.card_2sl = QtWidgets.QPushButton(self.groupBox_5) self.card_2sl.setObjectName("card_2sl") self.horizontalLayout_2.addWidget(self.card_2sl) self.MYCARD_LEFT.addLayout(self.horizontalLayout_2) self.horizontalLayout_9 = QtWidgets.QHBoxLayout() self.horizontalLayout_9.setObjectName("horizontalLayout_9") self.card_adl = QtWidgets.QPushButton(self.groupBox_5) self.card_adl.setObjectName("card_adl") self.horizontalLayout_9.addWidget(self.card_adl) self.card_kdl = QtWidgets.QPushButton(self.groupBox_5) self.card_kdl.setObjectName("card_kdl") self.horizontalLayout_9.addWidget(self.card_kdl) self.card_qdl = QtWidgets.QPushButton(self.groupBox_5) self.card_qdl.setObjectName("card_qdl") self.horizontalLayout_9.addWidget(self.card_qdl) self.card_jdl = QtWidgets.QPushButton(self.groupBox_5) self.card_jdl.setObjectName("card_jdl") self.horizontalLayout_9.addWidget(self.card_jdl) self.card_tdl = QtWidgets.QPushButton(self.groupBox_5) self.card_tdl.setObjectName("card_tdl") self.horizontalLayout_9.addWidget(self.card_tdl) self.card_9dl = QtWidgets.QPushButton(self.groupBox_5) self.card_9dl.setObjectName("card_9dl") self.horizontalLayout_9.addWidget(self.card_9dl) self.card_8dl = QtWidgets.QPushButton(self.groupBox_5) self.card_8dl.setObjectName("card_8dl") self.horizontalLayout_9.addWidget(self.card_8dl) self.card_7dl = QtWidgets.QPushButton(self.groupBox_5) self.card_7dl.setObjectName("card_7dl") self.horizontalLayout_9.addWidget(self.card_7dl) self.card_6dl = QtWidgets.QPushButton(self.groupBox_5) self.card_6dl.setObjectName("card_6dl") self.horizontalLayout_9.addWidget(self.card_6dl) self.card_5dl = QtWidgets.QPushButton(self.groupBox_5) self.card_5dl.setObjectName("card_5dl") self.horizontalLayout_9.addWidget(self.card_5dl) self.card_4dl = QtWidgets.QPushButton(self.groupBox_5) self.card_4dl.setObjectName("card_4dl") self.horizontalLayout_9.addWidget(self.card_4dl) self.card_3dl = QtWidgets.QPushButton(self.groupBox_5) self.card_3dl.setObjectName("card_3dl") self.horizontalLayout_9.addWidget(self.card_3dl) self.card_2dl = QtWidgets.QPushButton(self.groupBox_5) self.card_2dl.setObjectName("card_2dl") self.horizontalLayout_9.addWidget(self.card_2dl) self.MYCARD_LEFT.addLayout(self.horizontalLayout_9) self.horizontalLayout_8 = QtWidgets.QHBoxLayout() self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.card_acl = QtWidgets.QPushButton(self.groupBox_5) self.card_acl.setObjectName("card_acl") self.horizontalLayout_8.addWidget(self.card_acl) self.card_kcl = QtWidgets.QPushButton(self.groupBox_5) self.card_kcl.setObjectName("card_kcl") self.horizontalLayout_8.addWidget(self.card_kcl) self.card_qcl = QtWidgets.QPushButton(self.groupBox_5) self.card_qcl.setObjectName("card_qcl") self.horizontalLayout_8.addWidget(self.card_qcl) self.card_jcl = QtWidgets.QPushButton(self.groupBox_5) self.card_jcl.setObjectName("card_jcl") self.horizontalLayout_8.addWidget(self.card_jcl) self.card_tcl = QtWidgets.QPushButton(self.groupBox_5) self.card_tcl.setObjectName("card_tcl") self.horizontalLayout_8.addWidget(self.card_tcl) self.card_9cl = QtWidgets.QPushButton(self.groupBox_5) self.card_9cl.setObjectName("card_9cl") self.horizontalLayout_8.addWidget(self.card_9cl) self.card_8cl = QtWidgets.QPushButton(self.groupBox_5) self.card_8cl.setObjectName("card_8cl") self.horizontalLayout_8.addWidget(self.card_8cl) self.card_7cl = QtWidgets.QPushButton(self.groupBox_5) self.card_7cl.setObjectName("card_7cl") self.horizontalLayout_8.addWidget(self.card_7cl) self.card_6cl = QtWidgets.QPushButton(self.groupBox_5) self.card_6cl.setObjectName("card_6cl") self.horizontalLayout_8.addWidget(self.card_6cl) self.card_5cl = QtWidgets.QPushButton(self.groupBox_5) self.card_5cl.setObjectName("card_5cl") self.horizontalLayout_8.addWidget(self.card_5cl) self.card_4cl = QtWidgets.QPushButton(self.groupBox_5) self.card_4cl.setObjectName("card_4cl") self.horizontalLayout_8.addWidget(self.card_4cl) self.card_3cl = QtWidgets.QPushButton(self.groupBox_5) self.card_3cl.setObjectName("card_3cl") self.horizontalLayout_8.addWidget(self.card_3cl) self.card_2cl = QtWidgets.QPushButton(self.groupBox_5) self.card_2cl.setObjectName("card_2cl") self.horizontalLayout_8.addWidget(self.card_2cl) self.MYCARD_LEFT.addLayout(self.horizontalLayout_8) self.verticalLayout_2.addLayout(self.MYCARD_LEFT) self.MYCARD_RIGHT = QtWidgets.QVBoxLayout() self.MYCARD_RIGHT.setObjectName("MYCARD_RIGHT") self.horizontalLayout_14 = QtWidgets.QHBoxLayout() self.horizontalLayout_14.setObjectName("horizontalLayout_14") self.card_ahr = QtWidgets.QPushButton(self.groupBox_5) self.card_ahr.setObjectName("card_ahr") self.horizontalLayout_14.addWidget(self.card_ahr) self.card_khr = QtWidgets.QPushButton(self.groupBox_5) self.card_khr.setObjectName("card_khr") self.horizontalLayout_14.addWidget(self.card_khr) self.card_qhr = QtWidgets.QPushButton(self.groupBox_5) self.card_qhr.setObjectName("card_qhr") self.horizontalLayout_14.addWidget(self.card_qhr) self.card_jhr = QtWidgets.QPushButton(self.groupBox_5) self.card_jhr.setObjectName("card_jhr") self.horizontalLayout_14.addWidget(self.card_jhr) self.card_thr = QtWidgets.QPushButton(self.groupBox_5) self.card_thr.setObjectName("card_thr") self.horizontalLayout_14.addWidget(self.card_thr) self.card_9hr = QtWidgets.QPushButton(self.groupBox_5) self.card_9hr.setObjectName("card_9hr") self.horizontalLayout_14.addWidget(self.card_9hr) self.card_8hr = QtWidgets.QPushButton(self.groupBox_5) self.card_8hr.setObjectName("card_8hr") self.horizontalLayout_14.addWidget(self.card_8hr) self.card_7hr = QtWidgets.QPushButton(self.groupBox_5) self.card_7hr.setObjectName("card_7hr") self.horizontalLayout_14.addWidget(self.card_7hr) self.card_6hr = QtWidgets.QPushButton(self.groupBox_5) self.card_6hr.setObjectName("card_6hr") self.horizontalLayout_14.addWidget(self.card_6hr) self.card_5hr = QtWidgets.QPushButton(self.groupBox_5) self.card_5hr.setObjectName("card_5hr") self.horizontalLayout_14.addWidget(self.card_5hr) self.card_4hr = QtWidgets.QPushButton(self.groupBox_5) self.card_4hr.setObjectName("card_4hr") self.horizontalLayout_14.addWidget(self.card_4hr) self.card_3hr = QtWidgets.QPushButton(self.groupBox_5) self.card_3hr.setObjectName("card_3hr") self.horizontalLayout_14.addWidget(self.card_3hr) self.card_2hr = QtWidgets.QPushButton(self.groupBox_5) self.card_2hr.setObjectName("card_2hr") self.horizontalLayout_14.addWidget(self.card_2hr) self.MYCARD_RIGHT.addLayout(self.horizontalLayout_14) self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.card_asr = QtWidgets.QPushButton(self.groupBox_5) self.card_asr.setObjectName("card_asr") self.horizontalLayout_6.addWidget(self.card_asr) self.card_ksr = QtWidgets.QPushButton(self.groupBox_5) self.card_ksr.setObjectName("card_ksr") self.horizontalLayout_6.addWidget(self.card_ksr) self.card_qsr = QtWidgets.QPushButton(self.groupBox_5) self.card_qsr.setObjectName("card_qsr") self.horizontalLayout_6.addWidget(self.card_qsr) self.card_jsr = QtWidgets.QPushButton(self.groupBox_5) self.card_jsr.setObjectName("card_jsr") self.horizontalLayout_6.addWidget(self.card_jsr) self.card_tsr = QtWidgets.QPushButton(self.groupBox_5) self.card_tsr.setObjectName("card_tsr") self.horizontalLayout_6.addWidget(self.card_tsr) self.card_9sr = QtWidgets.QPushButton(self.groupBox_5) self.card_9sr.setObjectName("card_9sr") self.horizontalLayout_6.addWidget(self.card_9sr) self.card_8sr = QtWidgets.QPushButton(self.groupBox_5) self.card_8sr.setObjectName("card_8sr") self.horizontalLayout_6.addWidget(self.card_8sr) self.card_7sr = QtWidgets.QPushButton(self.groupBox_5) self.card_7sr.setObjectName("card_7sr") self.horizontalLayout_6.addWidget(self.card_7sr) self.card_6sr = QtWidgets.QPushButton(self.groupBox_5) self.card_6sr.setObjectName("card_6sr") self.horizontalLayout_6.addWidget(self.card_6sr) self.card_5sr = QtWidgets.QPushButton(self.groupBox_5) self.card_5sr.setObjectName("card_5sr") self.horizontalLayout_6.addWidget(self.card_5sr) self.card_4sr = QtWidgets.QPushButton(self.groupBox_5) self.card_4sr.setObjectName("card_4sr") self.horizontalLayout_6.addWidget(self.card_4sr) self.card_3sr = QtWidgets.QPushButton(self.groupBox_5) self.card_3sr.setObjectName("card_3sr") self.horizontalLayout_6.addWidget(self.card_3sr) self.card_2sr = QtWidgets.QPushButton(self.groupBox_5) self.card_2sr.setObjectName("card_2sr") self.horizontalLayout_6.addWidget(self.card_2sr) self.MYCARD_RIGHT.addLayout(self.horizontalLayout_6) self.horizontalLayout_15 = QtWidgets.QHBoxLayout() self.horizontalLayout_15.setObjectName("horizontalLayout_15") self.card_adr = QtWidgets.QPushButton(self.groupBox_5) self.card_adr.setObjectName("card_adr") self.horizontalLayout_15.addWidget(self.card_adr) self.card_kdr = QtWidgets.QPushButton(self.groupBox_5) self.card_kdr.setObjectName("card_kdr") self.horizontalLayout_15.addWidget(self.card_kdr) self.card_qdr = QtWidgets.QPushButton(self.groupBox_5) self.card_qdr.setObjectName("card_qdr") self.horizontalLayout_15.addWidget(self.card_qdr) self.card_jdr = QtWidgets.QPushButton(self.groupBox_5) self.card_jdr.setObjectName("card_jdr") self.horizontalLayout_15.addWidget(self.card_jdr) self.card_tdr = QtWidgets.QPushButton(self.groupBox_5) self.card_tdr.setObjectName("card_tdr") self.horizontalLayout_15.addWidget(self.card_tdr) self.card_9dr = QtWidgets.QPushButton(self.groupBox_5) self.card_9dr.setObjectName("card_9dr") self.horizontalLayout_15.addWidget(self.card_9dr) self.card_8dr = QtWidgets.QPushButton(self.groupBox_5) self.card_8dr.setObjectName("card_8dr") self.horizontalLayout_15.addWidget(self.card_8dr) self.card_7dr = QtWidgets.QPushButton(self.groupBox_5) self.card_7dr.setObjectName("card_7dr") self.horizontalLayout_15.addWidget(self.card_7dr) self.card_6dr = QtWidgets.QPushButton(self.groupBox_5) self.card_6dr.setObjectName("card_6dr") self.horizontalLayout_15.addWidget(self.card_6dr) self.card_5dr = QtWidgets.QPushButton(self.groupBox_5) self.card_5dr.setObjectName("card_5dr") self.horizontalLayout_15.addWidget(self.card_5dr) self.card_4dr = QtWidgets.QPushButton(self.groupBox_5) self.card_4dr.setObjectName("card_4dr") self.horizontalLayout_15.addWidget(self.card_4dr) self.card_3dr = QtWidgets.QPushButton(self.groupBox_5) self.card_3dr.setObjectName("card_3dr") self.horizontalLayout_15.addWidget(self.card_3dr) self.card_2dr = QtWidgets.QPushButton(self.groupBox_5) self.card_2dr.setObjectName("card_2dr") self.horizontalLayout_15.addWidget(self.card_2dr) self.MYCARD_RIGHT.addLayout(self.horizontalLayout_15) self.horizontalLayout_16 = QtWidgets.QHBoxLayout() self.horizontalLayout_16.setObjectName("horizontalLayout_16") self.card_acr = QtWidgets.QPushButton(self.groupBox_5) self.card_acr.setObjectName("card_acr") self.horizontalLayout_16.addWidget(self.card_acr) self.card_kcr = QtWidgets.QPushButton(self.groupBox_5) self.card_kcr.setObjectName("card_kcr") self.horizontalLayout_16.addWidget(self.card_kcr) self.card_qcr = QtWidgets.QPushButton(self.groupBox_5) self.card_qcr.setObjectName("card_qcr") self.horizontalLayout_16.addWidget(self.card_qcr) self.card_jcr = QtWidgets.QPushButton(self.groupBox_5) self.card_jcr.setObjectName("card_jcr") self.horizontalLayout_16.addWidget(self.card_jcr) self.card_tcr = QtWidgets.QPushButton(self.groupBox_5) self.card_tcr.setObjectName("card_tcr") self.horizontalLayout_16.addWidget(self.card_tcr) self.card_9cr = QtWidgets.QPushButton(self.groupBox_5) self.card_9cr.setObjectName("card_9cr") self.horizontalLayout_16.addWidget(self.card_9cr) self.card_8cr = QtWidgets.QPushButton(self.groupBox_5) self.card_8cr.setObjectName("card_8cr") self.horizontalLayout_16.addWidget(self.card_8cr) self.card_7cr = QtWidgets.QPushButton(self.groupBox_5) self.card_7cr.setObjectName("card_7cr") self.horizontalLayout_16.addWidget(self.card_7cr) self.card_6cr = QtWidgets.QPushButton(self.groupBox_5) self.card_6cr.setObjectName("card_6cr") self.horizontalLayout_16.addWidget(self.card_6cr) self.card_5cr = QtWidgets.QPushButton(self.groupBox_5) self.card_5cr.setObjectName("card_5cr") self.horizontalLayout_16.addWidget(self.card_5cr) self.card_4cr = QtWidgets.QPushButton(self.groupBox_5) self.card_4cr.setObjectName("card_4cr") self.horizontalLayout_16.addWidget(self.card_4cr) self.card_3cr = QtWidgets.QPushButton(self.groupBox_5) self.card_3cr.setObjectName("card_3cr") self.horizontalLayout_16.addWidget(self.card_3cr) self.card_2cr = QtWidgets.QPushButton(self.groupBox_5) self.card_2cr.setObjectName("card_2cr") self.horizontalLayout_16.addWidget(self.card_2cr) self.MYCARD_RIGHT.addLayout(self.horizontalLayout_16) self.verticalLayout_2.addLayout(self.MYCARD_RIGHT) self.TABLE = QtWidgets.QVBoxLayout() self.TABLE.setObjectName("TABLE") self.horizontalLayout_17 = QtWidgets.QHBoxLayout() self.horizontalLayout_17.setObjectName("horizontalLayout_17") self.card_ah = QtWidgets.QPushButton(self.groupBox_5) self.card_ah.setObjectName("card_ah") self.horizontalLayout_17.addWidget(self.card_ah) self.card_kh = QtWidgets.QPushButton(self.groupBox_5) self.card_kh.setObjectName("card_kh") self.horizontalLayout_17.addWidget(self.card_kh) self.card_qh = QtWidgets.QPushButton(self.groupBox_5) self.card_qh.setObjectName("card_qh") self.horizontalLayout_17.addWidget(self.card_qh) self.card_jh = QtWidgets.QPushButton(self.groupBox_5) self.card_jh.setObjectName("card_jh") self.horizontalLayout_17.addWidget(self.card_jh) self.card_th = QtWidgets.QPushButton(self.groupBox_5) self.card_th.setObjectName("card_th") self.horizontalLayout_17.addWidget(self.card_th) self.card_9h = QtWidgets.QPushButton(self.groupBox_5) self.card_9h.setObjectName("card_9h") self.horizontalLayout_17.addWidget(self.card_9h) self.card_8h = QtWidgets.QPushButton(self.groupBox_5) self.card_8h.setObjectName("card_8h") self.horizontalLayout_17.addWidget(self.card_8h) self.card_7h = QtWidgets.QPushButton(self.groupBox_5) self.card_7h.setObjectName("card_7h") self.horizontalLayout_17.addWidget(self.card_7h) self.card_6h = QtWidgets.QPushButton(self.groupBox_5) self.card_6h.setObjectName("card_6h") self.horizontalLayout_17.addWidget(self.card_6h) self.card_5h = QtWidgets.QPushButton(self.groupBox_5) self.card_5h.setObjectName("card_5h") self.horizontalLayout_17.addWidget(self.card_5h) self.card_4h = QtWidgets.QPushButton(self.groupBox_5) self.card_4h.setObjectName("card_4h") self.horizontalLayout_17.addWidget(self.card_4h) self.card_3h = QtWidgets.QPushButton(self.groupBox_5) self.card_3h.setObjectName("card_3h") self.horizontalLayout_17.addWidget(self.card_3h) self.card_2h = QtWidgets.QPushButton(self.groupBox_5) self.card_2h.setObjectName("card_2h") self.horizontalLayout_17.addWidget(self.card_2h) self.TABLE.addLayout(self.horizontalLayout_17) self.horizontalLayout_7 = QtWidgets.QHBoxLayout() self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.card_as = QtWidgets.QPushButton(self.groupBox_5) self.card_as.setObjectName("card_as") self.horizontalLayout_7.addWidget(self.card_as) self.card_ks = QtWidgets.QPushButton(self.groupBox_5) self.card_ks.setObjectName("card_ks") self.horizontalLayout_7.addWidget(self.card_ks) self.card_qs = QtWidgets.QPushButton(self.groupBox_5) self.card_qs.setObjectName("card_qs") self.horizontalLayout_7.addWidget(self.card_qs) self.card_js = QtWidgets.QPushButton(self.groupBox_5) self.card_js.setObjectName("card_js") self.horizontalLayout_7.addWidget(self.card_js) self.card_ts = QtWidgets.QPushButton(self.groupBox_5) self.card_ts.setObjectName("card_ts") self.horizontalLayout_7.addWidget(self.card_ts) self.card_9s = QtWidgets.QPushButton(self.groupBox_5) self.card_9s.setObjectName("card_9s") self.horizontalLayout_7.addWidget(self.card_9s) self.card_8s = QtWidgets.QPushButton(self.groupBox_5) self.card_8s.setObjectName("card_8s") self.horizontalLayout_7.addWidget(self.card_8s) self.card_7s = QtWidgets.QPushButton(self.groupBox_5) self.card_7s.setObjectName("card_7s") self.horizontalLayout_7.addWidget(self.card_7s) self.card_6s = QtWidgets.QPushButton(self.groupBox_5) self.card_6s.setObjectName("card_6s") self.horizontalLayout_7.addWidget(self.card_6s) self.card_5s = QtWidgets.QPushButton(self.groupBox_5) self.card_5s.setObjectName("card_5s") self.horizontalLayout_7.addWidget(self.card_5s) self.card_4s = QtWidgets.QPushButton(self.groupBox_5) self.card_4s.setObjectName("card_4s") self.horizontalLayout_7.addWidget(self.card_4s) self.card_3s = QtWidgets.QPushButton(self.groupBox_5) self.card_3s.setObjectName("card_3s") self.horizontalLayout_7.addWidget(self.card_3s) self.card_2s = QtWidgets.QPushButton(self.groupBox_5) self.card_2s.setObjectName("card_2s") self.horizontalLayout_7.addWidget(self.card_2s) self.TABLE.addLayout(self.horizontalLayout_7) self.horizontalLayout_18 = QtWidgets.QHBoxLayout() self.horizontalLayout_18.setObjectName("horizontalLayout_18") self.card_ad = QtWidgets.QPushButton(self.groupBox_5) self.card_ad.setObjectName("card_ad") self.horizontalLayout_18.addWidget(self.card_ad) self.card_kd = QtWidgets.QPushButton(self.groupBox_5) self.card_kd.setObjectName("card_kd") self.horizontalLayout_18.addWidget(self.card_kd) self.card_qd = QtWidgets.QPushButton(self.groupBox_5) self.card_qd.setObjectName("card_qd") self.horizontalLayout_18.addWidget(self.card_qd) self.card_jd = QtWidgets.QPushButton(self.groupBox_5) self.card_jd.setObjectName("card_jd") self.horizontalLayout_18.addWidget(self.card_jd) self.card_td = QtWidgets.QPushButton(self.groupBox_5) self.card_td.setObjectName("card_td") self.horizontalLayout_18.addWidget(self.card_td) self.card_9d = QtWidgets.QPushButton(self.groupBox_5) self.card_9d.setObjectName("card_9d") self.horizontalLayout_18.addWidget(self.card_9d) self.card_8d = QtWidgets.QPushButton(self.groupBox_5) self.card_8d.setObjectName("card_8d") self.horizontalLayout_18.addWidget(self.card_8d) self.card_7d = QtWidgets.QPushButton(self.groupBox_5) self.card_7d.setObjectName("card_7d") self.horizontalLayout_18.addWidget(self.card_7d) self.card_6d = QtWidgets.QPushButton(self.groupBox_5) self.card_6d.setObjectName("card_6d") self.horizontalLayout_18.addWidget(self.card_6d) self.card_5d = QtWidgets.QPushButton(self.groupBox_5) self.card_5d.setObjectName("card_5d") self.horizontalLayout_18.addWidget(self.card_5d) self.card_4d = QtWidgets.QPushButton(self.groupBox_5) self.card_4d.setObjectName("card_4d") self.horizontalLayout_18.addWidget(self.card_4d) self.card_3d = QtWidgets.QPushButton(self.groupBox_5) self.card_3d.setObjectName("card_3d") self.horizontalLayout_18.addWidget(self.card_3d) self.card_2d = QtWidgets.QPushButton(self.groupBox_5) self.card_2d.setObjectName("card_2d") self.horizontalLayout_18.addWidget(self.card_2d) self.TABLE.addLayout(self.horizontalLayout_18) self.horizontalLayout_19 = QtWidgets.QHBoxLayout() self.horizontalLayout_19.setObjectName("horizontalLayout_19") self.card_ac = QtWidgets.QPushButton(self.groupBox_5) self.card_ac.setObjectName("card_ac") self.horizontalLayout_19.addWidget(self.card_ac) self.card_kc = QtWidgets.QPushButton(self.groupBox_5) self.card_kc.setObjectName("card_kc") self.horizontalLayout_19.addWidget(self.card_kc) self.card_qc = QtWidgets.QPushButton(self.groupBox_5) self.card_qc.setObjectName("card_qc") self.horizontalLayout_19.addWidget(self.card_qc) self.card_jc = QtWidgets.QPushButton(self.groupBox_5) self.card_jc.setObjectName("card_jc") self.horizontalLayout_19.addWidget(self.card_jc) self.card_tc = QtWidgets.QPushButton(self.groupBox_5) self.card_tc.setObjectName("card_tc") self.horizontalLayout_19.addWidget(self.card_tc) self.card_9c = QtWidgets.QPushButton(self.groupBox_5) self.card_9c.setObjectName("card_9c") self.horizontalLayout_19.addWidget(self.card_9c) self.card_8c = QtWidgets.QPushButton(self.groupBox_5) self.card_8c.setObjectName("card_8c") self.horizontalLayout_19.addWidget(self.card_8c) self.card_7c = QtWidgets.QPushButton(self.groupBox_5) self.card_7c.setObjectName("card_7c") self.horizontalLayout_19.addWidget(self.card_7c) self.card_6c = QtWidgets.QPushButton(self.groupBox_5) self.card_6c.setObjectName("card_6c") self.horizontalLayout_19.addWidget(self.card_6c) self.card_5c = QtWidgets.QPushButton(self.groupBox_5) self.card_5c.setObjectName("card_5c") self.horizontalLayout_19.addWidget(self.card_5c) self.card_4c = QtWidgets.QPushButton(self.groupBox_5) self.card_4c.setObjectName("card_4c") self.horizontalLayout_19.addWidget(self.card_4c) self.card_3c = QtWidgets.QPushButton(self.groupBox_5) self.card_3c.setObjectName("card_3c") self.horizontalLayout_19.addWidget(self.card_3c) self.card_2c = QtWidgets.QPushButton(self.groupBox_5) self.card_2c.setObjectName("card_2c") self.horizontalLayout_19.addWidget(self.card_2c) self.TABLE.addLayout(self.horizontalLayout_19) self.verticalLayout_2.addLayout(self.TABLE) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.dealer_button = QtWidgets.QPushButton(self.groupBox_5) self.dealer_button.setObjectName("dealer_button") self.horizontalLayout.addWidget(self.dealer_button) self.covered_card = QtWidgets.QPushButton(self.groupBox_5) self.covered_card.setObjectName("covered_card") self.horizontalLayout.addWidget(self.covered_card) self.verticalLayout_2.addLayout(self.horizontalLayout) self.tabWidget.addTab(self.tab_4, "") self.tab_5 = QtWidgets.QWidget() self.tab_5.setObjectName("tab_5") self.groupBox_8 = QtWidgets.QGroupBox(self.tab_5) self.groupBox_8.setGeometry(QtCore.QRect(10, 10, 401, 121)) self.groupBox_8.setObjectName("groupBox_8") self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox_8) self.gridLayout_2.setObjectName("gridLayout_2") self.mouse_fast_fold = QtWidgets.QPushButton(self.groupBox_8) self.mouse_fast_fold.setObjectName("mouse_fast_fold") self.gridLayout_2.addWidget(self.mouse_fast_fold, 1, 2, 1, 1) self.mouse_full_pot = QtWidgets.QPushButton(self.groupBox_8) self.mouse_full_pot.setObjectName("mouse_full_pot") self.gridLayout_2.addWidget(self.mouse_full_pot, 0, 3, 1, 1) self.mouse_call = QtWidgets.QPushButton(self.groupBox_8) self.mouse_call.setObjectName("mouse_call") self.gridLayout_2.addWidget(self.mouse_call, 1, 0, 1, 1) self.mouse_raise = QtWidgets.QPushButton(self.groupBox_8) self.mouse_raise.setObjectName("mouse_raise") self.gridLayout_2.addWidget(self.mouse_raise, 0, 1, 1, 1) self.mouse_call2 = QtWidgets.QPushButton(self.groupBox_8) self.mouse_call2.setObjectName("mouse_call2") self.gridLayout_2.addWidget(self.mouse_call2, 1, 1, 1, 1) self.mouse_fold = QtWidgets.QPushButton(self.groupBox_8) self.mouse_fold.setObjectName("mouse_fold") self.gridLayout_2.addWidget(self.mouse_fold, 0, 0, 1, 1) self.mouse_all_in = QtWidgets.QPushButton(self.groupBox_8) self.mouse_all_in.setObjectName("mouse_all_in") self.gridLayout_2.addWidget(self.mouse_all_in, 1, 3, 1, 1) self.mouse_half_pot = QtWidgets.QPushButton(self.groupBox_8) self.mouse_half_pot.setObjectName("mouse_half_pot") self.gridLayout_2.addWidget(self.mouse_half_pot, 0, 2, 1, 1) self.mouse_imback = QtWidgets.QPushButton(self.groupBox_8) self.mouse_imback.setObjectName("mouse_imback") self.gridLayout_2.addWidget(self.mouse_imback, 2, 1, 1, 1) self.mouse_check = QtWidgets.QPushButton(self.groupBox_8) self.mouse_check.setObjectName("mouse_check") self.gridLayout_2.addWidget(self.mouse_check, 2, 0, 1, 1) self.mouse_increase = QtWidgets.QPushButton(self.groupBox_8) self.mouse_increase.setObjectName("mouse_increase") self.gridLayout_2.addWidget(self.mouse_increase, 2, 2, 1, 1) self.tabWidget.addTab(self.tab_5, "") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.test_all_button = QtWidgets.QPushButton(self.tab) self.test_all_button.setGeometry(QtCore.QRect(20, 80, 371, 81)) self.test_all_button.setObjectName("test_all_button") self.label_4 = QtWidgets.QLabel(self.tab) self.label_4.setGeometry(QtCore.QRect(30, 30, 441, 16)) self.label_4.setObjectName("label_4") self.tabWidget.addTab(self.tab, "") self.groupBox_7 = QtWidgets.QGroupBox(table_setup_form) self.groupBox_7.setGeometry(QtCore.QRect(520, 0, 351, 91)) self.groupBox_7.setObjectName("groupBox_7") self.load = QtWidgets.QPushButton(self.groupBox_7) self.load.setGeometry(QtCore.QRect(0, 60, 91, 23)) self.load.setObjectName("load") self.label = QtWidgets.QLabel(self.groupBox_7) self.label.setGeometry(QtCore.QRect(0, 10, 61, 20)) self.label.setObjectName("label") self.table_name = QtWidgets.QComboBox(self.groupBox_7) self.table_name.setGeometry(QtCore.QRect(0, 30, 281, 22)) self.table_name.setObjectName("table_name") self.button_delete = QtWidgets.QPushButton(self.groupBox_7) self.button_delete.setGeometry(QtCore.QRect(110, 60, 91, 23)) self.button_delete.setObjectName("button_delete") self.scrollArea_2 = QtWidgets.QScrollArea(table_setup_form) self.scrollArea_2.setGeometry(QtCore.QRect(10, 470, 841, 81)) self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName("scrollArea_2") self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 839, 79)) self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2") self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents_2) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.preview_label = QtWidgets.QLabel(self.scrollAreaWidgetContents_2) self.preview_label.setText("") self.preview_label.setObjectName("preview_label") self.horizontalLayout_3.addWidget(self.preview_label) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.label_2 = QtWidgets.QLabel(table_setup_form) self.label_2.setGeometry(QtCore.QRect(530, 180, 21, 16)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.label_9 = QtWidgets.QLabel(table_setup_form) self.label_9.setGeometry(QtCore.QRect(530, 270, 21, 20)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_9.setFont(font) self.label_9.setObjectName("label_9") self.label_11 = QtWidgets.QLabel(table_setup_form) self.label_11.setGeometry(QtCore.QRect(540, 330, 261, 16)) font = QtGui.QFont() font.setPointSize(8) font.setBold(True) font.setWeight(75) self.label_11.setFont(font) self.label_11.setObjectName("label_11") self.label_10 = QtWidgets.QLabel(table_setup_form) self.label_10.setGeometry(QtCore.QRect(150, 20, 231, 16)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_10.setFont(font) self.label_10.setObjectName("label_10") self.label_13 = QtWidgets.QLabel(table_setup_form) self.label_13.setGeometry(QtCore.QRect(530, 160, 51, 16)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_13.setFont(font) self.label_13.setObjectName("label_13") self.label_14 = QtWidgets.QLabel(table_setup_form) self.label_14.setGeometry(QtCore.QRect(600, 160, 141, 16)) font = QtGui.QFont() font.setPointSize(8) font.setBold(False) font.setWeight(50) self.label_14.setFont(font) self.label_14.setObjectName("label_14") self.label_12 = QtWidgets.QLabel(table_setup_form) self.label_12.setGeometry(QtCore.QRect(470, 0, 51, 16)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_12.setFont(font) self.label_12.setObjectName("label_12") self.groupBox_9 = QtWidgets.QGroupBox(table_setup_form) self.groupBox_9.setGeometry(QtCore.QRect(520, 90, 351, 71)) self.groupBox_9.setObjectName("groupBox_9") self.blank_new = QtWidgets.QPushButton(self.groupBox_9) self.blank_new.setGeometry(QtCore.QRect(10, 40, 91, 23)) self.blank_new.setObjectName("blank_new") self.copy_to_new = QtWidgets.QPushButton(self.groupBox_9) self.copy_to_new.setGeometry(QtCore.QRect(100, 40, 71, 23)) self.copy_to_new.setObjectName("copy_to_new") self.new_name = QtWidgets.QLineEdit(self.groupBox_9) self.new_name.setGeometry(QtCore.QRect(10, 20, 251, 20)) self.new_name.setObjectName("new_name") self.label_15 = QtWidgets.QLabel(table_setup_form) self.label_15.setGeometry(QtCore.QRect(20, 570, 131, 16)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) font.setWeight(50) self.label_15.setFont(font) self.label_15.setObjectName("label_15") self.label_16 = QtWidgets.QLabel(table_setup_form) self.label_16.setGeometry(QtCore.QRect(20, 440, 491, 20)) font = QtGui.QFont() font.setPointSize(8) font.setBold(False) font.setWeight(50) self.label_16.setFont(font) self.label_16.setObjectName("label_16") self.label_17 = QtWidgets.QLabel(table_setup_form) self.label_17.setGeometry(QtCore.QRect(140, 570, 601, 20)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_17.setFont(font) self.label_17.setObjectName("label_17") self.label_18 = QtWidgets.QLabel(table_setup_form) self.label_18.setGeometry(QtCore.QRect(540, 350, 261, 16)) font = QtGui.QFont() font.setPointSize(8) font.setBold(False) font.setWeight(50) self.label_18.setFont(font) self.label_18.setObjectName("label_18") self.label_5 = QtWidgets.QLabel(table_setup_form) self.label_5.setGeometry(QtCore.QRect(550, 240, 171, 20)) self.label_5.setObjectName("label_5") self.retranslateUi(table_setup_form) self.tabWidget.setCurrentIndex(2) QtCore.QMetaObject.connectSlotsByName(table_setup_form) def retranslateUi(self, table_setup_form): _translate = QtCore.QCoreApplication.translate table_setup_form.setWindowTitle(_translate("table_setup_form", "Form")) self.crop.setToolTip(_translate("table_setup_form", "Crops the image to only show everything relative to the top left corner.")) self.crop.setText(_translate("table_setup_form", "Crop from top left corner")) self.topleft_corner.setToolTip(_translate("table_setup_form", "<html><head/><body><p>After selecting the top left corner (usually the poker sign at the top left of the windows window). It is used as a refernece point to find the poker window. CAREFUL: If you change the top left corner, all subsequent locations need to entered again!</p></body></html>")) self.topleft_corner.setText(_translate("table_setup_form", "Save new top left corner")) self.tesseract.setToolTip(_translate("table_setup_form", "Tries to use OCR on the last marked location to see if a number of name can be correctly recognized")) self.tesseract.setText(_translate("table_setup_form", "Recognize number")) self.take_screenshot_button.setToolTip(_translate("table_setup_form", "Takes a screenshot of the entire screen. This is the first step you need to take")) self.take_screenshot_button.setText(_translate("table_setup_form", "Take screenshot")) self.label_3.setText(_translate("table_setup_form", "Tesseract recognition")) self.tesseract_label.setText(_translate("table_setup_form", "na")) self.groupBox.setTitle(_translate("table_setup_form", "Button Images and their search areas")) self.raise_button.setToolTip(_translate("table_setup_form", "Only select the raise text, without the chainging element of the raise amount")) self.raise_button.setText(_translate("table_setup_form", "Raise Button")) self.all_in_call_button.setToolTip(_translate("table_setup_form", "Ensure to only select the portion that never changes")) self.all_in_call_button.setText(_translate("table_setup_form", "All in call Button")) self.buttons_search_area.setToolTip(_translate("table_setup_form", "Area where fold, call and raise buttons are located")) self.buttons_search_area.setText(_translate("table_setup_form", "Buttons search area")) self.fold_button.setText(_translate("table_setup_form", "Fold Button")) self.im_back.setToolTip(_translate("table_setup_form", "Image showing I\'m back, in case of tha time out")) self.im_back.setText(_translate("table_setup_form", "I\'m back")) self.lost_everything.setToolTip(_translate("table_setup_form", "An image showing no funds left: e.g. 0.00")) self.lost_everything.setText(_translate("table_setup_form", "Lost everything image")) self.check_button.setText(_translate("table_setup_form", "Check Button")) self.call_button.setToolTip(_translate("table_setup_form", "Only select a small portion of the button (e.g. the call text), without the actual call amount")) self.call_button.setText(_translate("table_setup_form", "Call Button")) self.my_turn.setToolTip(_translate("table_setup_form", "Best select the top left corner of the call button, or any other element that is always identical for all situations when it\'s your turn")) self.my_turn.setText(_translate("table_setup_form", "\"My Turn\" image")) self.my_turn_search_area.setToolTip(_translate("table_setup_form", "Select an area where to look for a single sign that it\'s your turn")) self.my_turn_search_area.setText(_translate("table_setup_form", "\"My turn\" search area")) self.lost_everything_search_area.setToolTip(_translate("table_setup_form", "Select area to look for a sign that all funds are lost. This is usually the area of the player\'s left funds.")) self.lost_everything_search_area.setText(_translate("table_setup_form", "Lost everything search area")) self.fast_fold_button.setText(_translate("table_setup_form", "Fast Fold Button")) self.groupBox_6.setTitle(_translate("table_setup_form", "Search areas for cards")) self.my_cards_area.setToolTip(_translate("table_setup_form", "Area where the player holds his cards")) self.my_cards_area.setText(_translate("table_setup_form", "My Cards area")) self.table_cards_area.setToolTip(_translate("table_setup_form", "Area where the cards appear on the table at flop, turn and river")) self.table_cards_area.setText(_translate("table_setup_form", "Table Cards area")) self.groupBox_10.setTitle(_translate("table_setup_form", "Values")) self.total_pot_area.setToolTip(_translate("table_setup_form", "Total pot. Make sure to only select the numbers very narrowly and test it by pressing the recognize number or text button")) self.total_pot_area.setText(_translate("table_setup_form", "Total Pot value")) self.current_round_pot.setToolTip(_translate("table_setup_form", "The pot of the current rount (e.g. flop). Select the area very narrowly and test it by pressing the recognize number button")) self.current_round_pot.setText(_translate("table_setup_form", "Current Round Pot value")) self.raise_value.setToolTip(_translate("table_setup_form", "The value on the raise button. Make sure to select very narrowly and then test with the recognize number button")) self.raise_value.setText(_translate("table_setup_form", "Raise Value")) self.call_value.setToolTip(_translate("table_setup_form", "Value on the call button, make sure to select narrowly and then test by pressing the recognize number button")) self.call_value.setText(_translate("table_setup_form", "Call value")) self.all_in_call_value.setToolTip(_translate("table_setup_form", "The all in call value may be in a different place in case the all in call button appears. Make sure to select the value narrowly and test it with the recognize number button")) self.all_in_call_value.setText(_translate("table_setup_form", "All in call value")) self.game_number.setToolTip(_translate("table_setup_form", "Game number for collusion, in partypoker available on top right")) self.game_number.setText(_translate("table_setup_form", "Game Number")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("table_setup_form", "Buttons and search areas")) self.groupBox_2.setTitle(_translate("table_setup_form", "Players")) self.groupBox_4.setTitle(_translate("table_setup_form", "Player (0=myself)")) self.current_player.setToolTip(_translate("table_setup_form", "0 is the bot, then clockwise the other players")) self.current_player.setItemText(0, _translate("table_setup_form", "0")) self.current_player.setItemText(1, _translate("table_setup_form", "1")) self.current_player.setItemText(2, _translate("table_setup_form", "2")) self.current_player.setItemText(3, _translate("table_setup_form", "3")) self.current_player.setItemText(4, _translate("table_setup_form", "4")) self.current_player.setItemText(5, _translate("table_setup_form", "5")) self.groupBox_3.setTitle(_translate("table_setup_form", "Table size")) self.max_players.setToolTip(_translate("table_setup_form", "Select the amount of players on the table")) self.max_players.setItemText(0, _translate("table_setup_form", "6")) self.player_pot_area.setToolTip(_translate("table_setup_form", "Pot of the player")) self.player_pot_area.setText(_translate("table_setup_form", "Player pot area")) self.button_search_area.setToolTip(_translate("table_setup_form", "Where the given player would have the button to indicate he is the dealer. ")) self.button_search_area.setText(_translate("table_setup_form", "Dealer button search area")) self.player_funds_area.setToolTip(_translate("table_setup_form", "area where the remaining player funds are shown. Use narrow selection and test it by pressing the Recognize number button")) self.player_funds_area.setText(_translate("table_setup_form", "Player funds area")) self.player_name_area.setText(_translate("table_setup_form", "Player name area")) self.covered_card_area.setToolTip(_translate("table_setup_form", "Area where the player has the cards, so the bot can detect if he is still in the game")) self.covered_card_area.setText(_translate("table_setup_form", "Covered card area (cards upside down)")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.players_tab), _translate("table_setup_form", "Players")) self.groupBox_5.setToolTip(_translate("table_setup_form", "Ensure to mark as narrowly as possible. Don\'t mark the full card, but only the number and the symbol.")) self.groupBox_5.setTitle(_translate("table_setup_form", "Images")) self.card_ahl.setText(_translate("table_setup_form", "AH")) self.card_khl.setText(_translate("table_setup_form", "KH")) self.card_qhl.setText(_translate("table_setup_form", "QH")) self.card_jhl.setText(_translate("table_setup_form", "JH")) self.card_thl.setText(_translate("table_setup_form", "TH")) self.card_9hl.setText(_translate("table_setup_form", "9H")) self.card_8hl.setText(_translate("table_setup_form", "8H")) self.card_7hl.setText(_translate("table_setup_form", "7H")) self.card_6hl.setText(_translate("table_setup_form", "6H")) self.card_5hl.setText(_translate("table_setup_form", "5H")) self.card_4hl.setText(_translate("table_setup_form", "4H")) self.card_3hl.setText(_translate("table_setup_form", "3H")) self.card_2hl.setText(_translate("table_setup_form", "2H")) self.card_asl.setText(_translate("table_setup_form", "AS")) self.card_ksl.setText(_translate("table_setup_form", "KS")) self.card_qsl.setText(_translate("table_setup_form", "QS")) self.card_jsl.setText(_translate("table_setup_form", "JS")) self.card_tsl.setText(_translate("table_setup_form", "TS")) self.card_9sl.setText(_translate("table_setup_form", "9S")) self.card_8sl.setText(_translate("table_setup_form", "8S")) self.card_7sl.setText(_translate("table_setup_form", "7S")) self.card_6sl.setText(_translate("table_setup_form", "6S")) self.card_5sl.setText(_translate("table_setup_form", "5S")) self.card_4sl.setText(_translate("table_setup_form", "4S")) self.card_3sl.setText(_translate("table_setup_form", "3S")) self.card_2sl.setText(_translate("table_setup_form", "2S")) self.card_adl.setText(_translate("table_setup_form", "AD")) self.card_kdl.setText(_translate("table_setup_form", "KD")) self.card_qdl.setText(_translate("table_setup_form", "QD")) self.card_jdl.setText(_translate("table_setup_form", "JD")) self.card_tdl.setText(_translate("table_setup_form", "TD")) self.card_9dl.setText(_translate("table_setup_form", "9D")) self.card_8dl.setText(_translate("table_setup_form", "8D")) self.card_7dl.setText(_translate("table_setup_form", "7D")) self.card_6dl.setText(_translate("table_setup_form", "6D")) self.card_5dl.setText(_translate("table_setup_form", "5D")) self.card_4dl.setText(_translate("table_setup_form", "4D")) self.card_3dl.setText(_translate("table_setup_form", "3D")) self.card_2dl.setText(_translate("table_setup_form", "2D")) self.card_acl.setText(_translate("table_setup_form", "AC")) self.card_kcl.setText(_translate("table_setup_form", "KC")) self.card_qcl.setText(_translate("table_setup_form", "QC")) self.card_jcl.setText(_translate("table_setup_form", "JC")) self.card_tcl.setText(_translate("table_setup_form", "TC")) self.card_9cl.setText(_translate("table_setup_form", "9C")) self.card_8cl.setText(_translate("table_setup_form", "8C")) self.card_7cl.setText(_translate("table_setup_form", "7C")) self.card_6cl.setText(_translate("table_setup_form", "6C")) self.card_5cl.setText(_translate("table_setup_form", "5C")) self.card_4cl.setText(_translate("table_setup_form", "4C")) self.card_3cl.setText(_translate("table_setup_form", "3C")) self.card_2cl.setText(_translate("table_setup_form", "2C")) self.card_ahr.setText(_translate("table_setup_form", "AH")) self.card_khr.setText(_translate("table_setup_form", "KH")) self.card_qhr.setText(_translate("table_setup_form", "QH")) self.card_jhr.setText(_translate("table_setup_form", "JH")) self.card_thr.setText(_translate("table_setup_form", "TH")) self.card_9hr.setText(_translate("table_setup_form", "9H")) self.card_8hr.setText(_translate("table_setup_form", "8H")) self.card_7hr.setText(_translate("table_setup_form", "7H")) self.card_6hr.setText(_translate("table_setup_form", "6H")) self.card_5hr.setText(_translate("table_setup_form", "5H")) self.card_4hr.setText(_translate("table_setup_form", "4H")) self.card_3hr.setText(_translate("table_setup_form", "3H")) self.card_2hr.setText(_translate("table_setup_form", "2H")) self.card_asr.setText(_translate("table_setup_form", "AS")) self.card_ksr.setText(_translate("table_setup_form", "KS")) self.card_qsr.setText(_translate("table_setup_form", "QS")) self.card_jsr.setText(_translate("table_setup_form", "JS")) self.card_tsr.setText(_translate("table_setup_form", "TS")) self.card_9sr.setText(_translate("table_setup_form", "9S")) self.card_8sr.setText(_translate("table_setup_form", "8S")) self.card_7sr.setText(_translate("table_setup_form", "7S")) self.card_6sr.setText(_translate("table_setup_form", "6S")) self.card_5sr.setText(_translate("table_setup_form", "5S")) self.card_4sr.setText(_translate("table_setup_form", "4S")) self.card_3sr.setText(_translate("table_setup_form", "3S")) self.card_2sr.setText(_translate("table_setup_form", "2S")) self.card_adr.setText(_translate("table_setup_form", "AD")) self.card_kdr.setText(_translate("table_setup_form", "KD")) self.card_qdr.setText(_translate("table_setup_form", "QD")) self.card_jdr.setText(_translate("table_setup_form", "JD")) self.card_tdr.setText(_translate("table_setup_form", "TD")) self.card_9dr.setText(_translate("table_setup_form", "9D")) self.card_8dr.setText(_translate("table_setup_form", "8D")) self.card_7dr.setText(_translate("table_setup_form", "7D")) self.card_6dr.setText(_translate("table_setup_form", "6D")) self.card_5dr.setText(_translate("table_setup_form", "5D")) self.card_4dr.setText(_translate("table_setup_form", "4D")) self.card_3dr.setText(_translate("table_setup_form", "3D")) self.card_2dr.setText(_translate("table_setup_form", "2D")) self.card_acr.setText(_translate("table_setup_form", "AC")) self.card_kcr.setText(_translate("table_setup_form", "KC")) self.card_qcr.setText(_translate("table_setup_form", "QC")) self.card_jcr.setText(_translate("table_setup_form", "JC")) self.card_tcr.setText(_translate("table_setup_form", "TC")) self.card_9cr.setText(_translate("table_setup_form", "9C")) self.card_8cr.setText(_translate("table_setup_form", "8C")) self.card_7cr.setText(_translate("table_setup_form", "7C")) self.card_6cr.setText(_translate("table_setup_form", "6C")) self.card_5cr.setText(_translate("table_setup_form", "5C")) self.card_4cr.setText(_translate("table_setup_form", "4C")) self.card_3cr.setText(_translate("table_setup_form", "3C")) self.card_2cr.setText(_translate("table_setup_form", "2C")) self.card_ah.setText(_translate("table_setup_form", "AH")) self.card_kh.setText(_translate("table_setup_form", "KH")) self.card_qh.setText(_translate("table_setup_form", "QH")) self.card_jh.setText(_translate("table_setup_form", "JH")) self.card_th.setText(_translate("table_setup_form", "TH")) self.card_9h.setText(_translate("table_setup_form", "9H")) self.card_8h.setText(_translate("table_setup_form", "8H")) self.card_7h.setText(_translate("table_setup_form", "7H")) self.card_6h.setText(_translate("table_setup_form", "6H")) self.card_5h.setText(_translate("table_setup_form", "5H")) self.card_4h.setText(_translate("table_setup_form", "4H")) self.card_3h.setText(_translate("table_setup_form", "3H")) self.card_2h.setText(_translate("table_setup_form", "2H")) self.card_as.setText(_translate("table_setup_form", "AS")) self.card_ks.setText(_translate("table_setup_form", "KS")) self.card_qs.setText(_translate("table_setup_form", "QS")) self.card_js.setText(_translate("table_setup_form", "JS")) self.card_ts.setText(_translate("table_setup_form", "TS")) self.card_9s.setText(_translate("table_setup_form", "9S")) self.card_8s.setText(_translate("table_setup_form", "8S")) self.card_7s.setText(_translate("table_setup_form", "7S")) self.card_6s.setText(_translate("table_setup_form", "6S")) self.card_5s.setText(_translate("table_setup_form", "5S")) self.card_4s.setText(_translate("table_setup_form", "4S")) self.card_3s.setText(_translate("table_setup_form", "3S")) self.card_2s.setText(_translate("table_setup_form", "2S")) self.card_ad.setText(_translate("table_setup_form", "AD")) self.card_kd.setText(_translate("table_setup_form", "KD")) self.card_qd.setText(_translate("table_setup_form", "QD")) self.card_jd.setText(_translate("table_setup_form", "JD")) self.card_td.setText(_translate("table_setup_form", "TD")) self.card_9d.setText(_translate("table_setup_form", "9D")) self.card_8d.setText(_translate("table_setup_form", "8D")) self.card_7d.setText(_translate("table_setup_form", "7D")) self.card_6d.setText(_translate("table_setup_form", "6D")) self.card_5d.setText(_translate("table_setup_form", "5D")) self.card_4d.setText(_translate("table_setup_form", "4D")) self.card_3d.setText(_translate("table_setup_form", "3D")) self.card_2d.setText(_translate("table_setup_form", "2D")) self.card_ac.setText(_translate("table_setup_form", "AC")) self.card_kc.setText(_translate("table_setup_form", "KC")) self.card_qc.setText(_translate("table_setup_form", "QC")) self.card_jc.setText(_translate("table_setup_form", "JC")) self.card_tc.setText(_translate("table_setup_form", "TC")) self.card_9c.setText(_translate("table_setup_form", "9C")) self.card_8c.setText(_translate("table_setup_form", "8C")) self.card_7c.setText(_translate("table_setup_form", "7C")) self.card_6c.setText(_translate("table_setup_form", "6C")) self.card_5c.setText(_translate("table_setup_form", "5C")) self.card_4c.setText(_translate("table_setup_form", "4C")) self.card_3c.setText(_translate("table_setup_form", "3C")) self.card_2c.setText(_translate("table_setup_form", "2C")) self.dealer_button.setToolTip(_translate("table_setup_form", "<html><head/><body><p>The dealer button image. Make sure to select very narrowly and don\'t include any background that might change depending on it\'s location</p></body></html>")) self.dealer_button.setText(_translate("table_setup_form", "Dealer button")) self.covered_card.setToolTip(_translate("table_setup_form", "Used to recognize which players are still in the game. Mark very narrowly to ensure it\'s the same for all players.")) self.covered_card.setText(_translate("table_setup_form", "Covered card")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("table_setup_form", "Cards")) self.groupBox_8.setTitle(_translate("table_setup_form", "Mouse Control")) self.mouse_fast_fold.setText(_translate("table_setup_form", "Fast Fold")) self.mouse_full_pot.setText(_translate("table_setup_form", "Full pot")) self.mouse_call.setText(_translate("table_setup_form", "Call")) self.mouse_raise.setText(_translate("table_setup_form", "Raise")) self.mouse_call2.setToolTip(_translate("table_setup_form", "Location of call button if no raise can be made (usally the same as normal call button, except for Pokerstars it is at the place of the raise button)")) self.mouse_call2.setText(_translate("table_setup_form", "Call2")) self.mouse_fold.setToolTip(_translate("table_setup_form", "Area of fold button to click")) self.mouse_fold.setText(_translate("table_setup_form", "Fold")) self.mouse_all_in.setText(_translate("table_setup_form", "All In")) self.mouse_half_pot.setText(_translate("table_setup_form", "Half pot")) self.mouse_imback.setToolTip(_translate("table_setup_form", "Location of I\'m back button")) self.mouse_imback.setText(_translate("table_setup_form", "I\'m back")) self.mouse_check.setToolTip(_translate("table_setup_form", "Location of I\'m back button")) self.mouse_check.setText(_translate("table_setup_form", "Check")) self.mouse_increase.setText(_translate("table_setup_form", "Increase")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), _translate("table_setup_form", "Mouse Targets")) self.test_all_button.setToolTip(_translate("table_setup_form", "Reads the table as per taken screenshot (use take screenshot button) and displays the results in the below box. That way you can see if further changes are necessary.")) self.test_all_button.setText(_translate("table_setup_form", "Test all")) self.label_4.setText(_translate("table_setup_form", "Take a screenshot and press Test all. Then check the console output for error messages.")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("table_setup_form", "Test")) self.groupBox_7.setTitle(_translate("table_setup_form", "Load Template for editing")) self.load.setToolTip(_translate("table_setup_form", "Load the template to show which items have already been learned. They can still be overwritten by simply marking the area or image and then pressing the corresponding butotn.")) self.load.setText(_translate("table_setup_form", "Load template")) self.label.setText(_translate("table_setup_form", "Table name")) self.table_name.setToolTip(_translate("table_setup_form", "Select a table to edit. You can only edit your own tables. To edit take a screenshot, crop it with the cop left corner, then select the area top left and bottom right and then choose the corresponding button")) self.button_delete.setToolTip(_translate("table_setup_form", "Load the template to show which items have already been learned. They can still be overwritten by simply marking the area or image and then pressing the corresponding butotn.")) self.button_delete.setText(_translate("table_setup_form", "delete")) self.label_2.setText(_translate("table_setup_form", "1")) self.label_9.setText(_translate("table_setup_form", "2")) self.label_11.setText(_translate("table_setup_form", "Step 5 (only for numbers, optional)")) self.label_10.setText(_translate("table_setup_form", "Step 4. Assign selection to save it")) self.label_13.setText(_translate("table_setup_form", "Steps")) self.label_14.setText(_translate("table_setup_form", "Ensure poker table is visible")) self.label_12.setText(_translate("table_setup_form", "Step 0")) self.groupBox_9.setTitle(_translate("table_setup_form", "Create a new template, USE GOOD NAMING OR IT WILL BE DELETED!!")) self.blank_new.setToolTip(_translate("table_setup_form", "Create a new blank template")) self.blank_new.setText(_translate("table_setup_form", "blank new")) self.copy_to_new.setToolTip(_translate("table_setup_form", "Take current template and create a new one that you can then edit")) self.copy_to_new.setText(_translate("table_setup_form", "copy to new")) self.label_15.setText(_translate("table_setup_form", "Full screenshot")) self.label_16.setText(_translate("table_setup_form", "Selection after clicking top left and bottom right of below screenshot")) self.label_17.setText(_translate("table_setup_form", "Step 3: click on top left and bottom right (2 separate clicks) of what you want to select")) self.label_18.setText(_translate("table_setup_form", "Check if recognition works correctly")) self.label_5.setText(_translate("table_setup_form", "Only do this once at the beginning:")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) table_setup_form = QtWidgets.QWidget() ui = Ui_table_setup_form() ui.setupUi(table_setup_form) table_setup_form.show() sys.exit(app.exec_())
[ "jinyiabc@gmail.com" ]
jinyiabc@gmail.com
de80fb420fc2beab227568af7d0bd7c23d052d4e
b80f33578744f5a168044aa6fe6def79f4a4271f
/cnn-activation2.py
5be8b79c5a51fb4bdbf09f5234dc6dceece71e14
[]
no_license
KVonY/Yikai-11747-HW1
69cab72eaac21f35292edb294dfd555b26c2eaf1
8a732731cb57d49d3e2dc20ffefa58e258543e7c
refs/heads/master
2020-04-23T09:50:27.710437
2019-02-17T05:01:36
2019-02-17T05:01:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,187
py
from collections import defaultdict import time import random import torch import numpy as np import io class CNNclass(torch.nn.Module): def __init__(self, nwords, emb_size, num_filters, window_size, ntags, weight_matrix): super(CNNclass, self).__init__() """ layers """ # self.embedding = torch.nn.Embedding(nwords, emb_size) self.embedding = torch.nn.Embedding(nwords, emb_size).from_pretrained(weight_matrix) # self.embedding.weight=weight_matrix.double() # uniform initialization # torch.nn.init.uniform_(self.embedding.weight, -0.25, 0.25) # self.embedding.load_state_dict({'weight': weight_matrix}) # Conv 1d # self.conv_1d = torch.nn.Conv1d(in_channels=emb_size, out_channels=num_filters, kernel_size=window_size, # stride=1, padding=0, dilation=1, groups=1, bias=True) self.layer1 = torch.nn.Sequential( torch.nn.Conv1d(emb_size, 128, kernel_size=window_size, stride=1, padding=0, dilation=1, groups=1, bias=True), # torch.nn.Dropout(0.2), torch.nn.ReLU()) self.layer2 = torch.nn.Sequential( torch.nn.Conv1d(128, num_filters, kernel_size=window_size, stride=1, padding=1, dilation=1, groups=1, bias=True), torch.nn.Dropout(0.5)) self.dropout = torch.nn.Dropout(0.5) self.relu = torch.nn.ReLU() self.projection_layer = torch.nn.Linear(in_features=num_filters, out_features=ntags, bias=True) # Initializing the projection layer # torch.nn.init.xavier_uniform_(self.projection_layer.weight) def forward(self, words, return_activations=False): emb = self.embedding(words) # nwords x emb_size emb = emb.unsqueeze(0).permute(0, 2, 1) # 1 x emb_size x nwords # h = self.conv_1d(emb) # 1 x num_filters x nwords h = self.layer1(emb) h = self.layer2(h) # h = self.layer3(h) activations = h.squeeze(0).max(dim=1)[1] # argmax along length of the sentence # Do max pooling h = h.max(dim=2)[0] # 1 x num_filters # h = self.dropout(h) h = self.relu(h) features = h.squeeze(0) out = self.projection_layer(h) # size(out) = 1 x ntags if return_activations: return out, activations.data.cpu().numpy(), features.data.cpu().numpy() return out # np.set_printoptions(linewidth=np.nan, threshold=np.nan) # Functions to read in the corpus w2i = defaultdict(lambda: len(w2i)) t2i = defaultdict(lambda: len(t2i)) UNK = w2i["<unk>"] def read_dataset(filename): with open(filename, "r") as f: for line in f: tag, words = line.lower().strip().split(" ||| ") words = words.split(" ") yield (words, [w2i[x] for x in words], t2i[tag]) # Read in the data train = list(read_dataset("topicclass/topicclass_train.txt")) nwords = len(w2i) w2i = defaultdict(lambda: UNK, w2i) dev = list(read_dataset("topicclass/topicclass_valid.txt")) ntags = len(t2i) test = list(read_dataset("topicclass/topicclass_test.txt")) def load_pretrained(w2i, nwords): # https://fasttext.cc/docs/en/english-vectors.html fin = io.open('wiki-news-300d-1M.vec', 'r', encoding='utf-8', newline='\n', errors='ignore') n, d = map(int, fin.readline().split()) data = {} weight_matrix = [] for line in fin: tokens = line.rstrip().split(' ') data[tokens[0]] = map(float, tokens[1:]) # w2i_keys = w2i.keys() w2i_inverse = defaultdict() for i in w2i.keys(): w2i_inverse[w2i[i]] = i for j in w2i_inverse.keys(): if w2i_inverse[j] in data.keys(): weight_matrix.append(list(data[w2i_inverse[j]])) else: weight_matrix.append(list(np.random.uniform(low=-0.25, high=0.25, size=300))) weight_matrix = torch.from_numpy(np.array(weight_matrix)).float() # print(weight_matrix.shape) return weight_matrix # Load pretrained embedding matrix weight_matrix = load_pretrained(w2i, nwords) # tag inverse t2i_inverse = defaultdict() for i in t2i.keys(): t2i_inverse[t2i[i]] = i # Define the model EMB_SIZE = 300 WIN_SIZE = 4 FILTER_SIZE = 100 # initialize the model model = CNNclass(nwords, EMB_SIZE, FILTER_SIZE, WIN_SIZE, ntags, weight_matrix) criterion = torch.nn.CrossEntropyLoss() # para tuning optimizer = torch.optim.Adam(model.parameters(), lr=1e-4, eps=1e-8, weight_decay=1e-4) type = torch.LongTensor use_cuda = torch.cuda.is_available() print("cuda:", use_cuda) if use_cuda: type = torch.cuda.LongTensor model.cuda() def calc_predict_and_activations(wids, tag, words): if len(wids) < WIN_SIZE: wids += [0] * (WIN_SIZE-len(wids)) words_tensor = torch.tensor(wids).type(type) scores, activations, features = model(words_tensor, return_activations=True) scores = scores.squeeze().cpu().data.numpy() print('%d ||| %s' % (tag, ' '.join(words))) predict = np.argmax(scores) print(display_activations(words, activations)) W = model.projection_layer.weight.data.cpu().numpy() bias = model.projection_layer.bias.data.cpu().numpy() print('scores=%s, predict: %d' % (scores, predict)) print(' bias=%s' % bias) contributions = W * features print(' very bad (%.4f): %s' % (scores[0], contributions[0])) print(' bad (%.4f): %s' % (scores[1], contributions[1])) print(' neutral (%.4f): %s' % (scores[2], contributions[2])) print(' good (%.4f): %s' % (scores[3], contributions[3])) print('very good (%.4f): %s' % (scores[4], contributions[4])) def display_activations(words, activations): pad_begin = (WIN_SIZE - 1) / 2 pad_end = WIN_SIZE - 1 - pad_begin words_padded = ['pad' for _ in range(int(pad_begin))] + words + ['pad' for _ in range(int(pad_end))] ngrams = [] for act in activations: ngrams.append('[' + ', '.join(words_padded[act:act+WIN_SIZE]) + ']') return ngrams num_iter = 3 for ITER in range(num_iter): # Perform training random.shuffle(train) train_loss = 0.0 train_correct = 0.0 start = time.time() for _, wids, tag in train: # Padding (can be done in the conv layer as well) if len(wids) < WIN_SIZE: wids += [0] * (WIN_SIZE - len(wids)) words_tensor = torch.tensor(wids).type(type) tag_tensor = torch.tensor([tag]).type(type) scores = model(words_tensor) predict = scores[0].argmax().item() if predict == tag: train_correct += 1 my_loss = criterion(scores, tag_tensor) train_loss += my_loss.item() # Do back-prop optimizer.zero_grad() my_loss.backward() optimizer.step() print("iter %r: train loss/sent=%.4f, acc=%.4f, time=%.2fs" % (ITER, train_loss/len(train), train_correct/len(train), time.time()-start)) # Perform dev if ITER == num_iter - 1: dev_pred = open('dev_pred_2', 'w') test_correct = 0.0 for _, wids, tag in dev: # Padding (can be done in the conv layer as well) if len(wids) < WIN_SIZE: wids += [0] * (WIN_SIZE - len(wids)) words_tensor = torch.tensor(wids).type(type) scores = model(words_tensor) predict = scores[0].argmax().item() if ITER == num_iter - 1: dev_pred.write(t2i_inverse[predict] + '\n') if predict == tag: test_correct += 1 if ITER == num_iter - 1: dev_pred.close() print("iter %r: test acc=%.4f" % (ITER, test_correct/len(dev))) # Perform test test_pred = open('test_pred_2', 'w') for _, wids, tag in test: # Padding (can be done in the conv layer as well) if len(wids) < WIN_SIZE: wids += [0] * (WIN_SIZE - len(wids)) words_tensor = torch.tensor(wids).type(type) scores = model(words_tensor) predict = scores[0].argmax().item() test_pred.write(t2i_inverse[predict] + '\n') test_pred.close() print("Test prediction done.") # for words, wids, tag in dev: # calc_predict_and_activations(wids, tag, words) # input()
[ "ZaloeVan@fengyikaideMacBook-Pro.local" ]
ZaloeVan@fengyikaideMacBook-Pro.local
77db28cb2c03ee4b05ac6fea38a0a9f15bf844ea
492e28a444c19e851a695eb99f682becf0231fdd
/Deployment/test2/test2/urls.py
ef6413dc0707a5808604b05466185763848db8e7
[ "MIT" ]
permissive
meddhafer97/Telecommunication-project
39cab81efce1b8362cf499a8602b523642ec68e3
30a732f817c6573b596806470e54f0e2e9cd0c59
refs/heads/master
2023-08-05T22:02:38.546553
2021-09-24T13:45:01
2021-09-24T13:45:01
403,689,598
0
0
null
null
null
null
UTF-8
Python
false
false
900
py
"""test2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('liste', include('deplacement.urls')), path('', include('login_example.urls')), path('internal', include('deplacement.urls')), ]
[ "79045282+meddhafer97@users.noreply.github.com" ]
79045282+meddhafer97@users.noreply.github.com
0cd9e581d7624e32f3b77d8b0b3cfdb11476d7af
aeac59dd8036bf185999d04f1a737e13ae191665
/confusion_matrics.py
1450cb1affa04e067f65e19d28db9ab309acd834
[]
no_license
MohamedAmineOuali/Facial-Emotion-Recognition
1b66e6dd314b24f20aba9c74c1035e9f02fc66ed
ffa6f5189d503b2d7da658aee5926c00f6811827
refs/heads/master
2020-03-22T10:26:43.598930
2018-07-05T21:38:32
2018-07-05T21:38:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,390
py
import numpy as np import matplotlib.pyplot as plt import os from data.load_data import load_val_data, load_training_data from models.simple_cnn_model import SimpleCnnModel from models.vgg_models import Vgg16Model model=SimpleCnnModel(False,sequence=True,stateful=True) dataPath="weights/simple_cnn_based/sequence/statefull" destination="confusion_matrix/simple_cnn_model/sequence/Statefull" def dataset_matrix(path,name): X_train, y_train, X_val, y_val = load_training_data(path, sequence=True, labels=True) model.save_confusion_matrix(X_train, y_train, os.path.join(curPath, "training {}.png".format(name)), ''.format(y_train.shape[0]),normalize=True) model.save_confusion_matrix(X_val, y_val, os.path.join(curPath, "val {}.png".format(name)), ''.format(y_val.shape[0]),normalize=True) for root, dirs, files in os.walk(dataPath): for filename in files: print(filename) curPath=os.path.join(root, filename) model.load_weights(curPath) curPath=curPath.replace(dataPath,destination) os.makedirs(curPath, exist_ok=True) # dataset_matrix("dataset/train_val","mix") # dataset_matrix("dataset/train_val2","CK+") # dataset_matrix("dataset/val_SFEW_2", "SFEW_2") dataset_matrix("dataset/sequences", "sequence") plt.close("all")
[ "M.Amine.wali@gmail.com" ]
M.Amine.wali@gmail.com
dcc5f2c0e93f1fb9799f6546eb4f6dcabab8b319
1a5da758ab873850b8bf499f075af28ebb8803ed
/nvim/rplugin/python3/denite/source/neoyank.py
a16c4637ff665273893202cdd6575653dceadcfc
[ "MIT" ]
permissive
orokasan/dotfiles
2e81d2912df8f3581b42e8a12d64a3b0bbabeed0
deb3e652987678c03b4bccad531c16b8ed848682
refs/heads/master
2023-04-08T09:02:38.957604
2023-03-23T09:48:30
2023-03-23T09:48:30
173,042,953
6
0
null
2020-03-07T10:43:10
2019-02-28T04:49:38
Vim script
UTF-8
Python
false
false
847
py
# ============================================================================ # FILE: neoyank.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ from .base import Base import re class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'neoyank' self.kind = 'word' def gather_candidates(self, context): self.vim.call('neoyank#update') candidates = [] for [register, history] in self.vim.call( 'neoyank#_get_yank_histories').items(): candidates += [{ 'word': register + ': ' + re.sub(r'\n', r'\\n', x[0])[:200], 'action__text': x[0], } for x in history] return candidates
[ "fuu989@gmail.com" ]
fuu989@gmail.com
0f6de30274e02c69ccbdbea3b6adf7ffb5b5c177
86367f34851c3c88a41894a99bc67b97c082c734
/src/root/nested/MakeParallelNetwork.py
e2399a8b1cae971f08f570e1ab25b6740aae752c
[]
no_license
klyap/StreamPy-UI
d1d6a40a113e399471fddce8f94bb3737021a906
f41be5d4a98534b4434fde05d1543c547136994f
refs/heads/master
2020-04-09T21:25:11.970675
2015-12-04T06:14:17
2015-12-04T06:14:17
41,704,201
2
1
null
null
null
null
UTF-8
Python
false
false
4,679
py
from Stream import Stream from Stream import _no_value, _multivalue from Agent import Agent #from OperatorsTest import stream_agent #from MakeNetworkNew import make_network, network_data_structures from OperatorsTestParallel import stream_agent from MakeNetworkParallel import make_network, network_data_structures from multiprocessing import Process, Queue def make_input_manager(input_queue, input_stream_dict): """ Make an object that waits continuously for a message on input_queue and then sends the message on the stream with the specified name. """ message = input_queue.get() print 'in make input manager, message = ', message stream_name, message_content = message input_stream_dict[stream_name].append(message) input_stream_dict[stream_name].print_recent() def make_output_manager(stream_dict, output_stream_names_dict): output_stream_names_list = output_stream_names_dict.keys() output_stream_list = \ [stream_dict[stream_name] for stream_name in output_stream_names_list] print ' output_stream_names_list', output_stream_names_list print 'output_stream_list', output_stream_list def send_message_to_queue(value_and_index_tuple): message_content, stream_index = value_and_index_tuple output_stream_name = output_stream_names_list[stream_index] receiver_queue = output_stream_names_dict[output_stream_name] message = (output_stream_name, message_content) receiver_queue.put(message) stream_agent( inputs=output_stream_list, outputs=None, f_type='asynch_element', f=send_message_to_queue, f_args=None) def make_process(input_queue, all_stream_names_tuple, input_stream_names_tuple, output_stream_names_dict, agent_descriptor_dict): print 'entered make_process' print 'input_queue', input_queue print 'input_stream_names_tuple', input_stream_names_tuple print 'output_stream_names_dict', output_stream_names_dict print 'agent_descriptor_dict', agent_descriptor_dict stream_dict, agent_dict = \ make_network(all_stream_names_tuple, agent_descriptor_dict) print 'stream_dict', stream_dict print 'agent_dict', agent_dict input_stream_dict = dict() for stream_name in input_stream_names_tuple: input_stream_dict[stream_name] = stream_dict[stream_name] print 'input_stream_dict', input_stream_dict # Create the input stream manager which takes # messages from the input queue and appends each message # to the specified input stream. make_input_manager(input_queue, input_stream_dict) # Create the output stream manager which subscribes # to messages on streams going outside the process. # The output stream manger takes each message m it receives # on a stream s and puts m in the input queues of each process # that receives s. output_manager = make_output_manager( stream_dict, output_stream_names_dict) def main(): # STEP 1 # PROVIDE CODE OR IMPORT PURE (NON-STREAM) FUNCTIONS def generate_numbers(): print 'in generate numbers' return _multivalue(range(5)) def print_message(v): print 'In process. message is', v return v # STEP 2 # SPECIFY THE NETWORK. queue_0 = Queue() queue_1 = Queue() # Specify names of all the streams. all_stream_names_tuple = ('source', 'trigger', 'echo') input_stream_names_tuple = ('trigger',) output_stream_names_dict = {'echo': queue_1} # Specify the agents: # key: agent name # value: list of input streams, list of output streams, function, function type, # tuple of arguments, state agent_descriptor_dict = { 'source_agent': [ [], ['source'], generate_numbers, 'element', None, None, ['trigger']], 'printer': [ ['source'], ['echo'], print_message, 'element', None, None, None] } # MAKE THE PROCESS ## queue_0 = Queue() ## queue_1 = Queue() process_0 = Process(target=make_process, args= (queue_0, all_stream_names_tuple, input_stream_names_tuple, output_stream_names_dict, agent_descriptor_dict) ) process_0.start() queue_0.put(('trigger', 0)) #while not queue_1.empty(): while True: v = queue_1.get() print 'v', v if __name__ == '__main__': main()
[ "kl.yap@hotmail.com" ]
kl.yap@hotmail.com
93f27067b99b2ce7b9bd942570d3e16f18af2a23
a382716034b91d86ac7c8a548a63d236d6da8032
/hat/vector_control/migrations/0028_auto_20190628_1342.py
69e7538031083c08b287d73a41b2abda708d0631
[ "MIT" ]
permissive
lpontis/iaso
336221335fe33ca9e07e40feb676f57bbdc749ca
4d3a9d3faa6b3ed3a2e08c728cc4f03e5a0bbcb6
refs/heads/main
2023-08-12T20:34:10.823260
2021-10-04T07:34:50
2021-10-04T07:34:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
768
py
# Generated by Django 2.0 on 2019-06-28 13:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("vector_control", "0027_auto_20190628_1129")] operations = [ migrations.AlterField( model_name="apiimport", name="import_type", field=models.TextField( blank=True, choices=[ ("trap", "Trap"), ("site", "Site"), ("catch", "Catch"), ("target", "Target"), ("orgUnit", "Org Unit"), ("instance", "Form instance"), ], max_length=25, null=True, ), ) ]
[ "tech@bluesquarehub.com" ]
tech@bluesquarehub.com
89a0ab975274ecd7bf88d0a14565525dbbc67930
8ebbd4f3fb5301e97a8dce308e8a80b882108384
/graphs/bfs/level_order_traversal_ii.py
63fe86794b2d095ce39d5fa0eba617461138e94f
[]
no_license
GlassWall/leetcode
6cde12382fabe28faa69b46b132ffde6e61a7a90
67297847ecc903bc519cdee0d7f8fb44524612f9
refs/heads/master
2022-11-25T05:45:58.586880
2020-08-05T14:57:16
2020-08-05T14:57:16
283,156,684
0
0
null
null
null
null
UTF-8
Python
false
false
857
py
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if root == None: return queue = [] queue.append(root) flag = False ans = [] while queue: level_len = len(queue) level_nodes = [] for i in range(level_len): current = queue.pop(0) level_nodes.append(current.val) if current.left: queue.append(current.left) if current.right: queue.append(current.right) ans.insert(0,level_nodes) return ans
[ "karthikravirsb@gmail.com" ]
karthikravirsb@gmail.com
16acc72525b2877d1c19433043ba5271cca5eb14
30fd9ecf6225fc4262f3932cc9cb9e63dc61aff2
/tempCodeRunnerFile.py
0792349a2e6e2dd8f7935fa253092c849cb15d4b
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
maks-p/dsc-1-07-07-object-oriented-shopping-cart-lab-nyc-ds-career-031119
8032164958b77c604fef0b6bb1a1dba5ed1f98e2
41d4e7f8a15bc2e55081e44d071ea53b9a9fc98e
refs/heads/master
2020-04-29T04:59:17.895983
2019-03-16T17:28:33
2019-03-16T17:28:33
175,866,098
0
0
null
2019-03-15T17:41:40
2019-03-15T17:41:39
null
UTF-8
Python
false
false
113
py
def median_item_price(self): # sorted_items = sorted(self.items) # if len(sorted_items) % 2 == 0:
[ "mpazuniak@gmail.com" ]
mpazuniak@gmail.com
37ca1c69a64c4b1c4e76037148a8135167a0c93a
7988457eb7021288ec89f7090cff7d27925f3f1f
/accounts/urls.py
40aefcb9a904c7acd726ce7639f5d0b89ef9dfc1
[]
no_license
DelroyBrown28/nueui-blog-template
cf292f3f2d3a2138a1260ca2b6c89af2b384002d
226f978ec0821d9c5d86311d03ed572d5bfb480e
refs/heads/main
2023-06-28T03:24:15.974189
2021-08-05T20:23:36
2021-08-05T20:23:36
393,127,417
0
0
null
null
null
null
UTF-8
Python
false
false
1,499
py
from django.urls import path from . import views from django.contrib.auth import views as auth_views from .forms import UserLoginForm, PwdResetForm, PwdResetConfirmForm, PwdChangeForm app_name = 'accounts' urlpatterns = [ path('password_change/', auth_views.PasswordChangeView.as_view( template_name="registration/password_change_form.html", form_class=PwdChangeForm), name='pwdforgot'), path('login/', auth_views.LoginView.as_view( template_name='registration/login.html', authentication_form=UserLoginForm), name='login'), path('password_reset/', auth_views.PasswordResetView.as_view( template_name="registration/password_reset_form.html", form_class=PwdResetForm), name='pwdreset'), path('password_reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html', form_class=PwdResetConfirmForm), name="pwdresetconfirm"), path('profile/', views.profile, name='profile'), path('profile/edit/', views.edit, name='edit'), path('fav/<int:id>', views.favorites_add, name='favorites_add'), path('thumbs/', views.thumbs, name='thumbs'), path('profile/favorites', views.favorites_list, name='favorites_list'), path('profile/delete/', views.delete_user, name='deleteuser'), path('register/', views.accounts_register, name='register'), path('activate/<slug:uidb64>/<slug:token>', views.activate, name='activate'), ]
[ "delroybrown.db@gmail.com" ]
delroybrown.db@gmail.com
e731b850003ce572dd84f80bac91daefa4dddaa4
bb091b112ea1a5d9c081ff06d485510dce0f865b
/app/config/secure.py
b4d2b6c71074dac4d6da9f1d8caf4ad021129aa5
[ "MIT" ]
permissive
wuqiufeng/TopSolid-cms-flask
ad09b80b4b1764b6981765966c7be11e1d103933
c90c8b246be98355e05bf8b046388803dfd9266c
refs/heads/master
2020-11-26T19:57:07.526002
2019-12-31T09:08:11
2019-12-31T09:08:11
229,193,502
0
0
null
null
null
null
UTF-8
Python
false
false
696
py
# 安全性配置 from app.config.setting import BaseConfig class DevelopmentSecure(BaseConfig): """ 开发环境安全性配置 """ SQLALCHEMY_DATABASE_URI = 'mysql+cymysql://root:ace123@127.0.0.1:3306/lin-cms' SQLALCHEMY_ECHO = False SECRET_KEY = '\x88W\xf09\x91\x07\x98\x89\x87\x96\xa0A\xc68\xf9\xecJJU\x17\xc5V\xbe\x8b\xef\xd7\xd8\xd3\xe6\x95*4' class ProductionSecure(BaseConfig): """ 生产环境安全性配置 """ SQLALCHEMY_DATABASE_URI = 'mysql+cymysql://root:ace123@127.0.0.1:3306/lin-cms' SQLALCHEMY_ECHO = False SECRET_KEY = '\x88W\xf09\x91\x07\x98\x89\x87\x96\xa0A\xc68\xf9\xecJJU\x17\xc5V\xbe\x8b\xef\xd7\xd8\xd3\xe6\x95*4'
[ "rootfuhongzhu@163.com" ]
rootfuhongzhu@163.com
bb389fcb42c582660b2afe6a9d80c2f28e77bb65
ccd0aa895fe2f59a6053718ef78ecbe5f641f863
/ex1.py
6986148dc338babd96911befeb637a13be5222d8
[ "MIT" ]
permissive
sriharivaleti/learn-python3-thw-code
447550c0909cc2fc454d335accaf0262d4e9faeb
d373a9d944196ae0cf7df23d2f1f681b56f8e40c
refs/heads/master
2022-11-09T21:28:32.082237
2020-07-04T10:34:17
2020-07-04T10:34:17
277,088,037
0
0
MIT
2020-07-04T10:28:39
2020-07-04T10:28:38
null
UTF-8
Python
false
false
191
py
print("Hello World!") print("Hello Again") print("I like typing this.") print("This is fun.") print('Yay! Printing.') print("I'd much rather you 'not'.") print('I "said" do not touch this.')
[ "zed.shaw+github@gmail.com" ]
zed.shaw+github@gmail.com
5c2268fe17969ab984f92eb53f373906b88b1c3a
7a482133553ff2416794ec99992b0a649d0e3bb1
/21Hour/21.py
e97135fa2112ef2091ce7900549ff3d0b62df50c
[]
no_license
aeron7/tessa
a3868242092cfa4f5265ce12e2ad7a208748e7da
981af88479cb3b25abca35987e9206e7b07ce429
refs/heads/main
2023-06-11T21:09:05.074819
2021-07-09T14:30:22
2021-07-09T14:30:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
20,326
py
from multiprocessing import Pool from pprint import pprint from jugaad_trader import Zerodha import pandas as pd import pytz from datetime import datetime, timedelta import csv import requests print("Om Namahshivaya:") kite = Zerodha() # Set access token loads the stored session. # Name chosen to keep it compatible with kiteconnect. kite.set_access_token() tickertape = {121345: '3MINDIA', 1147137: 'AARTIDRUGS', 1793: 'AARTIIND', 1378561: 'AAVAS', 3329: 'ABB', 4583169: 'ABBOTINDIA', 5533185: 'ABCAPITAL', 7707649: 'ABFRL', 5633: 'ACC', 6401: 'ADANIENT', 3861249: 'ADANIPORTS', 4617985: 'ADVENZYMES', 10241: 'AEGISCHEM', 3350017: 'AIAENG', 2079745: 'AJANTPHARM', 375553: 'AKZOINDIA', 20225: 'ALEMBICLTD', 2995969: 'ALKEM', 1148673: 'ALKYLAMINE', 4524801: 'ALOKINDS', 25601: 'AMARAJABAT', 303361: 'AMBER', 325121: 'AMBUJACEM', 82945: 'ANGELBRKG', 6599681: 'APLAPOLLO', 6483969: 'APLLTD', 40193: 'APOLLOHOSP', 41729: 'APOLLOTYRE', 1376769: 'ASAHIINDIA', 5166593: 'ASHOKA', 54273: 'ASHOKLEY', 60417: 'ASIANPAINT', 386049: 'ASTERDM', 3691009: 'ASTRAL', 1436161: 'ASTRAZEN', 67329: 'ATUL', 5436929: 'AUBANK', 70401: 'AUROPHARMA', 2031617: 'AVANTIFEED', 1510401: 'AXISBANK', 4267265: 'BAJAJ-AUTO', 4999937: 'BAJAJCON', 3848705: 'BAJAJELEC', 4268801: 'BAJAJFINSV', 78081: 'BAJAJHLDNG', 81153: 'BAJFINANCE', 3712257: 'BALAMINES', 85761: 'BALKRISIND', 86529: 'BALMLAWRIE', 87297: 'BALRAMCHIN', 579329: 'BANDHANBNK', 1195009: 'BANKBARODA', 1214721: 'BANKINDIA', 94209: 'BASF', 94977: 'BATAINDIA', 4589313: 'BAYERCROP', 97281: 'BBTC', 548865: 'BDL', 98049: 'BEL', 101121: 'BEML', 103425: 'BERGEPAINT', 108033: 'BHARATFORG', 981505: 'BHARATRAS', 2714625: 'BHARTIARTL', 112129: 'BHEL', 2911489: 'BIOCON', 122881: 'BIRLACORPN', 4931841: 'BLISSGVS', 126721: 'BLUEDART', 2127617: 'BLUESTARCO', 558337: 'BOSCHLTD', 134657: 'BPCL', 3887105: 'BRIGADE', 140033: 'BRITANNIA', 5013761: 'BSE', 1790465: 'BSOFT', 382465: 'BURGERKING', 2029825: 'CADILAHC', 87553: 'CAMS', 2763265: 'CANBK', 149249: 'CANFINHOME', 999937: 'CAPLIPOINT', 152321: 'CARBORUNIV', 320001: 'CASTROLIND', 2931713: 'CCL', 5420545: 'CDSL', 3905025: 'CEATLTD', 3812865: 'CENTRALBK', 3406081: 'CENTURYPLY', 160001: 'CENTURYTEX', 3849985: 'CERA', 160769: 'CESC', 5204225: 'CGCL', 2187777: 'CHALET', 163073: 'CHAMBLFERT', 175361: 'CHOLAFIN', 5565441: 'CHOLAHLDNG', 177665: 'CIPLA', 5215745: 'COALINDIA', 5506049: 'COCHINSHIP', 2955009: 'COFORGE', 3876097: 'COLPAL', 1215745: 'CONCOR', 189185: 'COROMANDEL', 1131777: 'CREDITACC', 193793: 'CRISIL', 4376065: 'CROMPTON', 3831297: 'CSBBANK', 1459457: 'CUB', 486657: 'CUMMINSIND', 1471489: 'CYIENT', 197633: 'DABUR', 2067201: 'DALBHARAT', 4630017: 'DBL', 5556225: 'DCAL', 3513601: 'DCBBANK', 207617: 'DCMSHRIRAM', 5105409: 'DEEPAKNTR', 3851265: 'DELTACORP', 3938305: 'DHANI', 6248705: 'DHANUKA', 3721473: 'DISHTV', 2800641: 'DIVISLAB', 5552641: 'DIXON', 3771393: 'DLF', 5097729: 'DMART', 225537: 'DRREDDY', 3885825: 'ECLERX', 3870465: 'EDELWEISS', 232961: 'EICHERMOT', 234497: 'EIDPARRY', 235265: 'EIHOTEL', 239873: 'ELGIEQUIP', 3460353: 'EMAMILTD', 4818433: 'ENDURANCE', 1256193: 'ENGINERSIN', 251137: 'EPL', 4314113: 'EQUITAS', 5415425: 'ERIS', 245249: 'ESCORTS', 173057: 'EXIDEIND', 7689729: 'FCONSUMER', 1253889: 'FDC', 261889: 'FEDERALBNK', 265729: 'FINCABLES', 958465: 'FINEORG', 266497: 'FINPIPE', 3520001: 'FLUOROCHEM', 3735553: 'FORTIS', 4704769: 'FRETAIL', 3661825: 'FSL', 2259969: 'GAEL', 1207553: 'GAIL', 336641: 'GALAXYSURF', 281601: 'GARFIBRES', 2012673: 'GEPIL', 3526657: 'GESHIP', 70913: 'GICRE', 403457: 'GILLETTE', 295169: 'GLAXO', 1895937: 'GLENMARK', 401921: 'GMMPFAUDLR', 3463169: 'GMRINFRA', 300545: 'GNFC', 302337: 'GODFRYPHLP', 36865: 'GODREJAGRO', 2585345: 'GODREJCP', 2796801: 'GODREJIND', 4576001: 'GODREJPROP', 5051137: 'GPPL', 3039233: 'GRANULES', 151553: 'GRAPHITE', 315393: 'GRASIM', 316161: 'GREAVESCOT', 3471361: 'GRINDWELL', 1401601: 'GRSE', 319233: 'GSFC', 3378433: 'GSPL', 324353: 'GUJALKALI', 2713345: 'GUJGASLTD', 1124097: 'GULFOILLUB', 589569: 'HAL', 12289: 'HAPPSTMNDS', 996353: 'HATSUN', 2513665: 'HAVELLS', 1850625: 'HCLTECH', 340481: 'HDFC', 1086465: 'HDFCAMC', 341249: 'HDFCBANK', 119553: 'HDFCLIFE', 342017: 'HEG', 592897: 'HEIDELBERG', 179457: 'HEMIPROP', 345089: 'HEROMOTOCO', 5619457: 'HFCL', 348929: 'HINDALCO', 4592385: 'HINDCOPPER', 359937: 'HINDPETRO', 356865: 'HINDUNILVR', 364545: 'HINDZINC', 874753: 'HONAUT', 3669505: 'HSCL', 5331201: 'HUDCO', 655873: 'HUHTAMAKI', 3699201: 'IBREALEST', 7712001: 'IBULHSGFIN', 1270529: 'ICICIBANK', 5573121: 'ICICIGI', 4774913: 'ICICIPRULI', 3068673: 'ICIL', 377857: 'IDBI', 3677697: 'IDEA', 3060993: 'IDFC', 2863105: 'IDFCFIRSTB', 56321: 'IEX', 380161: 'IFBIND', 2883073: 'IGL', 3343617: 'IIFLWAM', 387073: 'INDHOTEL', 387841: 'INDIACEM', 2745857: 'INDIAMART', 3663105: 'INDIANB', 2865921: 'INDIGO', 2989313: 'INDOCO', 1346049: 'INDUSINDBK', 7458561: 'INDUSTOWER', 4159745: 'INFIBEAM', 408065: 'INFY', 408833: 'INGERRAND', 3384577: 'INOXLEISUR', 1517057: 'INTELLECT', 2393089: 'IOB', 415745: 'IOC', 5225729: 'IOLCP', 418049: 'IPCALAB', 3920129: 'IRB', 1276417: 'IRCON', 3484417: 'IRCTC', 637185: 'ISEC', 424961: 'ITC', 428801: 'ITI', 5319169: 'JAMNAAUTO', 441857: 'JBCHEPHARM', 1149697: 'JCHAC', 774145: 'JINDALSAW', 1723649: 'JINDALSTEL', 3397121: 'JKCEMENT', 3453697: 'JKLAKSHMI', 3036161: 'JKPAPER', 3695361: 'JKTYRE', 3491073: 'JMFINANCIL', 2876417: 'JSL', 3149825: 'JSLHISAR', 4574465: 'JSWENERGY', 3001089: 'JSWSTEEL', 828673: 'JTEKTINDIA', 4632577: 'JUBLFOOD', 7670273: 'JUSTDIAL', 3877377: 'JYOTHYLAB', 462849: 'KAJARIACER', 464385: 'KALPATPOWR', 306177: 'KANSAINER', 470529: 'KARURVYSYA', 3394561: 'KEC', 3407361: 'KEI', 3912449: 'KNRCON', 492033: 'KOTAKBANK', 2478849: 'KPITTECH', 3817473: 'KPRMILL', 2707713: 'KRBL', 498945: 'KSB', 3832833: 'KSCL', 6386689: 'L&TFH', 2983425: 'LALPATHLAB', 3692289: 'LAOPALA', 4923905: 'LAURUSLABS', 506625: 'LAXMIMACH', 667137: 'LEMONTREE', 511233: 'LICHSGFIN', 416513: 'LINDEINDIA', 2939649: 'LT', 4561409: 'LTI', 4752385: 'LTTS', 2672641: 'LUPIN', 2893057: 'LUXIND', 519937: 'M&M', 3400961: 'M&MFIN', 2912513: 'MAHABANK', 3823873: 'MAHINDCIE', 98561: 'MAHLOG', 533761: 'MAHSCOOTER', 534529: 'MAHSEAMLES', 4879617: 'MANAPPURAM', 1041153: 'MARICO', 2815745: 'MARUTI', 50945: 'MASFIN', 5728513: 'MAXHEALTH', 130305: 'MAZDOCK', 2674433: 'MCDOWELL-N', 7982337: 'MCX', 2452737: 'METROPOLIS', 548353: 'MFSL', 4488705: 'MGL', 4437249: 'MHRIL', 630529: 'MIDHANI', 6629633: 'MINDACORP', 3623425: 'MINDAIND', 3675137: 'MINDTREE', 4596993: 'MMTC', 5332481: 'MOIL', 1076225: 'MOTHERSUMI', 3826433: 'MOTILALOFS', 1152769: 'MPHASIS', 582913: 'MRF', 584449: 'MRPL', 6054401: 'MUTHOOTFIN', 91393: 'NAM-INDIA', 1003009: 'NATCOPHARM', 1629185: 'NATIONALUM', 3520257: 'NAUKRI', 3756033: 'NAVINFLUOR', 8042241: 'NBCC', 593665: 'NCC', 3944705: 'NESCO', 4598529: 'NESTLEIND', 3612417: 'NETWORK18', 3564801: 'NFL', 3031041: 'NH', 4454401: 'NHPC', 102145: 'NIACL', 619777: 'NILKAMAL', 2197761: 'NLCINDIA', 3924993: 'NMDC', 625153: 'NOCIL', 2977281: 'NTPC', 5181953: 'OBEROIRLTY', 2748929: 'OFSS', 4464129: 'OIL', 633601: 'ONGC', 760833: 'ORIENTELEC', 7977729: 'ORIENTREF', 3689729: 'PAGEIND', 617473: 'PEL', 4701441: 'PERSISTENT', 2905857: 'PETRONET', 3660545: 'PFC', 676609: 'PFIZER', 648961: 'PGHH', 240641: 'PGHL', 678145: 'PHILIPCARB', 3725313: 'PHOENIXLTD', 681985: 'PIDILITIND', 6191105: 'PIIND', 2730497: 'PNB', 2402561: 'PNCINFRA', 2455041: 'POLYCAB', 6583809: 'POLYMED', 687873: 'POLYPLEX', 3834113: 'POWERGRID', 4724993: 'POWERINDIA', 5197313: 'PRESTIGE', 4107521: 'PRINCEPIPE', 701185: 'PRSMJOHNSN', 3365633: 'PVR', 4532225: 'QUESS', 2813441: 'RADICO', 3926273: 'RAIN', 1894657: 'RAJESHEXPO', 720897: 'RALLIS', 523009: 'RAMCOCEM', 3443457: 'RATNAMANI', 731905: 'RAYMOND', 4708097: 'RBLBANK', 733697: 'RCF', 3930881: 'RECLTD', 3649281: 'REDINGTON', 6201601: 'RELAXO', 738561: 'RELIANCE', 5202689: 'RESPONIND', 962817: 'RITES', 4968961: 'ROSSARI', 32769: 'ROUTE', 2445313: 'RVNL', 758529: 'SAIL', 369153: 'SANOFI', 4600577: 'SBICARD', 5582849: 'SBILIFE', 779521: 'SBIN', 258817: 'SCHAEFFLER', 7995905: 'SCHNEIDER', 780289: 'SCI', 3659777: 'SEQUENT', 4911105: 'SFL', 1277953: 'SHARDACROP', 4544513: 'SHILPAMED', 3024129: 'SHOPERSTOP', 794369: 'SHREECEM', 3005185: 'SHRIRAMCIT', 806401: 'SIEMENS', 5504257: 'SIS', 4834049: 'SJVN', 815617: 'SKFINDIA', 3539457: 'SOBHA', 940033: 'SOLARA', 3412993: 'SOLARINDS', 1688577: 'SONATSOFTW', 2927361: 'SPANDANA', 3785729: 'SPARC', 2930177: 'SPICEJET', 837889: 'SRF', 1102337: 'SRTRANSFIN', 1887745: 'STAR', 5399297: 'STARCEMENT', 2383105: 'STLTECH', 851713: 'SUDARSCHEM', 4378881: 'SUMICHEM', 7426049: 'SUNCLAYLTD', 854785: 'SUNDARMFIN', 856321: 'SUNDRMFAST', 857857: 'SUNPHARMA', 4516097: 'SUNTECK', 3431425: 'SUNTV', 2992385: 'SUPRAJIT', 860929: 'SUPREMEIND', 4593921: 'SUVENPHAR', 3076609: 'SUZLON', 6936321: 'SWANENERGY', 3197185: 'SWSOLAR', 6192641: 'SYMPHONY', 2622209: 'SYNGENE', 5143553: 'TASTYBITE', 871681: 'TATACHEM', 185345: 'TATACOFFEE', 952577: 'TATACOMM', 878593: 'TATACONSUM', 873217: 'TATAELXSI', 414977: 'TATAINVEST', 884737: 'TATAMOTORS', 4343041: 'TATAMTRDVR', 877057: 'TATAPOWER', 895745: 'TATASTEEL', 4921089: 'TCIEXP', 1068033: 'TCNSBRANDS', 2953217: 'TCS', 3255297: 'TEAMLEASE', 3465729: 'TECHM', 889601: 'THERMAX', 4360193: 'THYROCARE', 79873: 'TIINDIA', 3634689: 'TIMKEN', 897537: 'TITAN', 900609: 'TORNTPHARM', 3529217: 'TORNTPOWER', 502785: 'TRENT', 2479361: 'TRIDENT', 6549505: 'TRITURBINE', 907777: 'TTKPRESTIG', 3637249: 'TV18BRDCST', 2170625: 'TVSMOTOR', 4278529: 'UBL', 2873089: 'UCOBANK', 269569: 'UFLEX', 4369665: 'UJJIVAN', 3898369: 'UJJIVANSFB', 2952193: 'ULTRACEMCO', 2752769: 'UNIONBANK', 2889473: 'UPL', 134913: 'UTIAMC', 2909185: 'VAIBHAVGBL', 3415553: 'VAKRANGEE', 84481: 'VALIANTORG', 987393: 'VARROC', 4843777: 'VBL', 784129: 'VEDL', 961793: 'VENKEYS', 3932673: 'VGUARD', 4445185: 'VINATIORGA', 947969: 'VIPIND', 7496705: 'VMART', 951809: 'VOLTAS', 953345: 'VSTIND', 530689: 'VTL', 4330241: 'WABCOINDIA', 3026177: 'WELCORP', 2880769: 'WELSPUNIND', 2964481: 'WESTLIFE', 4610817: 'WHIRLPOOL', 969473: 'WIPRO', 1921537: 'WOCKPHARMA', 3050241: 'YESBANK', 975873: 'ZEEL', 275457: 'ZENSARTECH', 4514561: 'ZYDUSWELL'} watchlist = [121345, 1147137, 1793, 1378561, 3329, 4583169, 5533185, 7707649, 5633, 6401, 3861249, 4617985, 10241, 3350017, 2079745, 375553, 20225, 2995969, 1148673, 4524801, 25601, 303361, 325121, 82945, 6599681, 6483969, 40193, 41729, 1376769, 5166593, 54273, 60417, 386049, 3691009, 1436161, 67329, 5436929, 70401, 2031617, 1510401, 4267265, 4999937, 3848705, 4268801, 78081, 81153, 3712257, 85761, 86529, 87297, 579329, 1195009, 1214721, 94209, 94977, 4589313, 97281, 548865, 98049, 101121, 103425, 108033, 981505, 2714625, 112129, 2911489, 122881, 4931841, 126721, 2127617, 558337, 134657, 3887105, 140033, 5013761, 1790465, 382465, 2029825, 87553, 2763265, 149249, 999937, 152321, 320001, 2931713, 5420545, 3905025, 3812865, 3406081, 160001, 3849985, 160769, 5204225, 2187777, 163073, 175361, 5565441, 177665, 5215745, 5506049, 2955009, 3876097, 1215745, 189185, 1131777, 193793, 4376065, 3831297, 1459457, 486657, 1471489, 197633, 2067201, 4630017, 5556225, 3513601, 207617, 5105409, 3851265, 3938305, 6248705, 3721473, 2800641, 5552641, 3771393, 5097729, 225537, 3885825, 3870465, 232961, 234497, 235265, 239873, 3460353, 4818433, 1256193, 251137, 4314113, 5415425, 245249, 173057, 7689729, 1253889, 261889, 265729, 958465, 266497, 3520001, 3735553, 4704769, 3661825, 2259969, 1207553, 336641, 281601, 2012673, 3526657, 70913, 403457, 295169, 1895937, 401921, 3463169, 300545, 302337, 36865, 2585345, 2796801, 4576001, 5051137, 3039233, 151553, 315393, 316161, 3471361, 1401601, 319233, 3378433, 324353, 2713345, 1124097, 589569, 12289, 996353, 2513665, 1850625, 340481, 1086465, 341249, 119553, 342017, 592897, 179457, 345089, 5619457, 348929, 4592385, 359937, 356865, 364545, 874753, 3669505, 5331201, 655873, 3699201, 7712001, 1270529, 5573121, 4774913, 3068673, 377857, 3677697, 3060993, 2863105, 56321, 380161, 2883073, 3343617, 387073, 387841, 2745857, 3663105, 2865921, 2989313, 1346049, 7458561, 4159745, 408065, 408833, 3384577, 1517057, 2393089, 415745, 5225729, 418049, 3920129, 1276417, 3484417, 637185, 424961, 428801, 5319169, 441857, 1149697, 774145, 1723649, 3397121, 3453697, 3036161, 3695361, 3491073, 2876417, 3149825, 4574465, 3001089, 828673, 4632577, 7670273, 3877377, 462849, 464385, 306177, 470529, 3394561, 3407361, 3912449, 492033, 2478849, 3817473, 2707713, 498945, 3832833, 6386689, 2983425, 3692289, 4923905, 506625, 667137, 511233, 416513, 2939649, 4561409, 4752385, 2672641, 2893057, 519937, 3400961, 2912513, 3823873, 98561, 533761, 534529, 4879617, 1041153, 2815745, 50945, 5728513, 130305, 2674433, 7982337, 2452737, 548353, 4488705, 4437249, 630529, 6629633, 3623425, 3675137, 4596993, 5332481, 1076225, 3826433, 1152769, 582913, 584449, 6054401, 91393, 1003009, 1629185, 3520257, 3756033, 8042241, 593665, 3944705, 4598529, 3612417, 3564801, 3031041, 4454401, 102145, 619777, 2197761, 3924993, 625153, 2977281, 5181953, 2748929, 4464129, 633601, 760833, 7977729, 3689729, 617473, 4701441, 2905857, 3660545, 676609, 648961, 240641, 678145, 3725313, 681985, 6191105, 2730497, 2402561, 2455041, 6583809, 687873, 3834113, 4724993, 5197313, 4107521, 701185, 3365633, 4532225, 2813441, 3926273, 1894657, 720897, 523009, 3443457, 731905, 4708097, 733697, 3930881, 3649281, 6201601, 738561, 5202689, 962817, 4968961, 32769, 2445313, 758529, 369153, 4600577, 5582849, 779521, 258817, 7995905, 780289, 3659777, 4911105, 1277953, 4544513, 3024129, 794369, 3005185, 806401, 5504257, 4834049, 815617, 3539457, 940033, 3412993, 1688577, 2927361, 3785729, 2930177, 837889, 1102337, 1887745, 5399297, 2383105, 851713, 4378881, 7426049, 854785, 856321, 857857, 4516097, 3431425, 2992385, 860929, 4593921, 3076609, 6936321, 3197185, 6192641, 2622209, 5143553, 871681, 185345, 952577, 878593, 873217, 414977, 884737, 4343041, 877057, 895745, 4921089, 1068033, 2953217, 3255297, 3465729, 889601, 4360193, 79873, 3634689, 897537, 900609, 3529217, 502785, 2479361, 6549505, 907777, 3637249, 2170625, 4278529, 2873089, 269569, 4369665, 3898369, 2952193, 2752769, 2889473, 134913, 2909185, 3415553, 84481, 987393, 4843777, 784129, 961793, 3932673, 4445185, 947969, 7496705, 951809, 953345, 530689, 4330241, 3026177, 2880769, 2964481, 4610817, 969473, 1921537, 3050241, 975873, 275457, 4514561] class Ticker: def __init__(self, instrument_token, tradingsymbol, highest_high, lowest_low) -> None: self.instrument_token = instrument_token self.tradingsymbol = tradingsymbol self.highest_high = highest_high self.lowest_low = lowest_low self.open_long_trade = False self.open_short_trade = False def __repr__(self): return f"Instrument token: {self.instrument_token}, Trading symbol: {self.tradingsymbol}, Highest high: {self.highest_high}, Lowest low: {self.lowest_low}, Open Long Trade: {self.open_long_trade}, Open Short Trade: {self.open_short_trade}" today = datetime.today() today_data = "" historical_data = "" tickers = [] open_long_positions = [] open_short_positions = [] for instrument_token in watchlist: tradingsymbol = tickertape[instrument_token] try: historical_data = pd.DataFrame(kite.historical_data( instrument_token, today - timedelta(days=34), today, "day")) historical_data = historical_data.head(-1).tail(21) highest_high = historical_data.high.max() lowest_low = historical_data.low.max() tickers.append(Ticker(instrument_token, tradingsymbol, highest_high, lowest_low)) watchlist.append(instrument_token) except Exception as e: print( f"Exception raised while placing fetching historical data for Instrument_token: {instrument_token}, Tradingsymbol:{tradingsymbol}") print(e) continue def buy_instrument(ticker, last_candle): if instrument_token not in open_long_positions: try: buy_price = (last_candle.high + last_candle.low + last_candle.close) / 3 if last_candle.open > last_candle.close: stoploss = last_candle.close - last_candle.low else: stoploss = last_candle.open - last_candle.low trailing_stoploss = (last_candle.high - last_candle.low) * 0.618 buy_order_id = kite.place_order(tradingsymbol=tradingsymbol, exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_BUY, quantity=25, order_type=kite.ORDER_TYPE_LIMIT, product=kite.PRODUCT_NRML, variety=kite.VARIETY_BO, price=buy_price, stoploss=stoploss, trailing_stoploss=trailing_stoploss ) open_long_positions.append(instrument_token) ticker.open_long_trade = True return buy_order_id except requests.exceptions.Timeout: buy_instrument(ticker, last_candle) except Exception as e: print( f"Exception raised while placing buy order for ticker {ticker}") print(e) else: print(f"{tradingsymbol} is already an open long position") return 0 def sell_instrument(ticker, last_candle): if instrument_token in open_short_positions: try: sell_price = (last_candle.high + last_candle.low + last_candle.close) / 3 if last_candle.open < last_candle.close: stoploss = last_candle.close - last_candle.low else: stoploss = last_candle.open - last_candle.low trailing_stoploss = (last_candle.high - last_candle.low) * 0.618 sell_order_id = kite.place_order(tradingsymbol=tradingsymbol, exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_SELL, quantity=25, order_type=kite.ORDER_TYPE_LIMIT, product=kite.PRODUCT_NRML, variety=kite.VARIETY_BO, price=sell_price, stoploss=stoploss, trailing_stoploss=trailing_stoploss ) open_short_positions.append(instrument_token) ticker.open_short_trade = True return sell_order_id except requests.exceptions.Timeout: sell_instrument(ticker, last_candle) except Exception as e: print( f"Exception raised while placing sell order for ticker {ticker}") print(e) else: print(f"{tradingsymbol} is not an open short position") return 0 def hourly_close(ticker): try: today_data = pd.DataFrame(kite.historical_data( ticker.instrument_token, today - timedelta(hours=96), today, "hour")) last_candle = today_data.iloc[-1] # print(last_candle) if last_candle.close > ticker.highest_high: buy_instrument(ticker, last_candle) print(f"Buy {ticker.tradingsymbol}") if last_candle.close < ticker.lowest_low: sell_instrument(ticker, last_candle) print(f"Sell {ticker.tradingsymbol}") print(ticker.instrument_token) except Exception as e: print(f"Exception raised in function hourly close {ticker}") print(e) while True: pool = Pool(3) processes = pool.map(hourly_close, tickers) print("Long Trades:", [ ticker for ticker in tickers if ticker.open_long_trade == True]) print("Short Trades:", [ ticker for ticker in tickers if ticker.open_short_trade == True])
[ "noreply@github.com" ]
aeron7.noreply@github.com
934deec4b292e6fa10a2c0c9b75f4b0d1ecbfcaa
b4ca99fdb2e7f5da8eb559adf647a0bc69e2d7c5
/StandardSpider/SpiderRulesMap/Panasonic/CCT2016110400000005.py
50eb7cadfff9fdfa4eca07e2cd273175415ce8d7
[]
no_license
RoyalClown/MyPython
4f6b68e0f5f883c187cf8253df0c5feeab3de8fd
baf13612d8d36e519ce54825c4b664597789128a
refs/heads/master
2021-01-11T13:29:30.332280
2017-05-31T02:56:07
2017-05-31T02:56:07
81,513,648
1
0
null
null
null
null
UTF-8
Python
false
false
1,743
py
""" @description: 此单号与松下导电性聚合物钽固体电解电容器 (POSCAP)对应 @author: RoyalClown """ from DataAnalyse.dbDataGet.Util_data import DataProcessing from DataAnalyse.file_download.img_download import ImgDownload from DataAnalyse.file_download.pdf_download import PdfDownload from Lib.DBConnection.OracleConnection import OracleConnection from Spider.Panasonic.forth_type1.forthGo import forth_go class CCT2016110400000005: def __init__(self): self.url = "https://industrial.panasonic.cn/ea/products/capacitors/polymer-capacitors/poscap#quicktabs-line_up_page_tab=1" self.task_code = "CCT2016110400000005" self.task_id = self.get_task_id() def get_task_id(self): orcl_conn = OracleConnection() cursor = orcl_conn.conn.cursor() cursor.execute( "select cct_id from product$component_crawl_task where cct_taskid='{}'".format(self.task_code)) task_id = cursor.fetchone()[0] cursor.close() return task_id def go(self): print("开始进行爬取") forth_go(self.url, task_code=self.task_code, task_id=self.task_id) print("成功完成爬取数据到爬虫数据表\n------------------现在开始下载pdf、img文件-----------------") pdf_download = PdfDownload(self.task_id) pdf_download.go() img_download = ImgDownload() img_download.go() print("pdf、img下载完成,开始对数据进行分析并存入数据库") # 以下为数据分析,基本全部需要改 data_processing = DataProcessing() data_processing.go(self.task_id) if __name__ == "__main__": taskn = CCT2016110400000005() taskn.go()
[ "421581115@qq.com" ]
421581115@qq.com
103e6b6eeaaadf0b180cac71a97824dd983c6e08
c76779dd4682cdf252623a193d735a8893e872f2
/gs72/student/views.py
ddc28608005e88530c26ec017dfa43a3b0c337b9
[]
no_license
sailendrachettri/learning-django
fef240aa19303d876f760a5641d9d15b2716b61b
3c413628f0f4a3a560fa5c56a5228260c50e0230
refs/heads/main
2023-03-28T22:18:24.620614
2021-04-10T11:04:40
2021-04-10T11:04:40
355,099,833
1
0
null
null
null
null
UTF-8
Python
false
false
690
py
from django.shortcuts import render def setsession(request): request.session['name'] = 'Sonam' request.session.set_expiry(10) #Expire in 10 seconds return render(request, 'student/setsession.html') def getsession(request): name = request.session['name'] # print(request.session.get_session_cookie_age()) # print(request.session.get_expiry_age()) # print(request.session.get_expiry_date()) # print(request.session.get_expire_at_browser_close()) return render(request, 'student/getsession.html', {'name':name}) def delsession(request): request.session.flush() request.session.clear_expired() return render(request, 'student/delsession.html')
[ "sailendra9083@gmail.com" ]
sailendra9083@gmail.com
95472e497ca618aca3dd60dc0316048909aed9c6
7f2207627b2808b76bbb10b870f0567b2ead64b6
/agconnect/agro/weather.py
293536ba73b575a25bba2805a9eecf38088a94b7
[]
no_license
wcookie/AgConnect
0c412265ceb8a07fd674453cca0595f5186c05cc
700a8e2e48c3fdfee310080d79ab40fc1c25d156
refs/heads/master
2021-01-10T01:37:40.094792
2016-02-21T15:24:19
2016-02-21T15:24:19
52,139,590
1
0
null
null
null
null
UTF-8
Python
false
false
160
py
import requests WEATHER_SOURCE_KEY = "152730b019699f58c11e" def try_weather(lat, longi): base_url = "https://api.weathersource.com/v1/" + WEATHER_SOURCE_KEY
[ "wyattcook2018@u.northwestern.edu" ]
wyattcook2018@u.northwestern.edu
c82aba47a0e215c5028b4413f8a55519ba6d0ddd
c5e6122d8d739afe50e334883cd0a3b3363ff9a7
/supervisor/dbus/network/connection.py
2a273cb31abd26555369aa464f393ac3c6e613a5
[ "Apache-2.0" ]
permissive
tastenmo/supervisor
f9ca7b4684f8c08154bff27afcf8e1f14af672b0
ef5b6a5f4c94302fb8df4e01416219ac4e4b98b8
refs/heads/main
2023-09-05T00:06:42.050829
2021-10-19T09:26:58
2021-10-19T09:26:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,931
py
"""Connection object for Network Manager.""" from ipaddress import ip_address, ip_interface from typing import Optional from ...const import ATTR_ADDRESS, ATTR_PREFIX from ...utils.dbus import DBus from ..const import ( DBUS_ATTR_ADDRESS_DATA, DBUS_ATTR_CONNECTION, DBUS_ATTR_GATEWAY, DBUS_ATTR_ID, DBUS_ATTR_IP4CONFIG, DBUS_ATTR_IP6CONFIG, DBUS_ATTR_NAMESERVER_DATA, DBUS_ATTR_NAMESERVERS, DBUS_ATTR_STATE, DBUS_ATTR_TYPE, DBUS_ATTR_UUID, DBUS_NAME_CONNECTION_ACTIVE, DBUS_NAME_IP4CONFIG, DBUS_NAME_IP6CONFIG, DBUS_NAME_NM, DBUS_OBJECT_BASE, ) from ..interface import DBusInterfaceProxy from .configuration import IpConfiguration class NetworkConnection(DBusInterfaceProxy): """NetworkConnection object for Network Manager.""" def __init__(self, object_path: str) -> None: """Initialize NetworkConnection object.""" self.object_path = object_path self.properties = {} self._ipv4: Optional[IpConfiguration] = None self._ipv6: Optional[IpConfiguration] = None @property def id(self) -> str: """Return the id of the connection.""" return self.properties[DBUS_ATTR_ID] @property def type(self) -> str: """Return the type of the connection.""" return self.properties[DBUS_ATTR_TYPE] @property def uuid(self) -> str: """Return the uuid of the connection.""" return self.properties[DBUS_ATTR_UUID] @property def state(self) -> int: """Return the state of the connection.""" return self.properties[DBUS_ATTR_STATE] @property def setting_object(self) -> int: """Return the connection object path.""" return self.properties[DBUS_ATTR_CONNECTION] @property def ipv4(self) -> Optional[IpConfiguration]: """Return a ip4 configuration object for the connection.""" return self._ipv4 @property def ipv6(self) -> Optional[IpConfiguration]: """Return a ip6 configuration object for the connection.""" return self._ipv6 async def connect(self) -> None: """Get connection information.""" self.dbus = await DBus.connect(DBUS_NAME_NM, self.object_path) self.properties = await self.dbus.get_properties(DBUS_NAME_CONNECTION_ACTIVE) # IPv4 if self.properties[DBUS_ATTR_IP4CONFIG] != DBUS_OBJECT_BASE: ip4 = await DBus.connect(DBUS_NAME_NM, self.properties[DBUS_ATTR_IP4CONFIG]) ip4_data = await ip4.get_properties(DBUS_NAME_IP4CONFIG) self._ipv4 = IpConfiguration( ip_address(ip4_data[DBUS_ATTR_GATEWAY]) if ip4_data.get(DBUS_ATTR_GATEWAY) else None, [ ip_address(nameserver[ATTR_ADDRESS]) for nameserver in ip4_data.get(DBUS_ATTR_NAMESERVER_DATA, []) ], [ ip_interface(f"{address[ATTR_ADDRESS]}/{address[ATTR_PREFIX]}") for address in ip4_data.get(DBUS_ATTR_ADDRESS_DATA, []) ], ) # IPv6 if self.properties[DBUS_ATTR_IP6CONFIG] != DBUS_OBJECT_BASE: ip6 = await DBus.connect(DBUS_NAME_NM, self.properties[DBUS_ATTR_IP6CONFIG]) ip6_data = await ip6.get_properties(DBUS_NAME_IP6CONFIG) self._ipv6 = IpConfiguration( ip_address(ip6_data[DBUS_ATTR_GATEWAY]) if ip6_data.get(DBUS_ATTR_GATEWAY) else None, [ ip_address(bytes(nameserver)) for nameserver in ip6_data.get(DBUS_ATTR_NAMESERVERS) ], [ ip_interface(f"{address[ATTR_ADDRESS]}/{address[ATTR_PREFIX]}") for address in ip6_data.get(DBUS_ATTR_ADDRESS_DATA, []) ], )
[ "noreply@github.com" ]
tastenmo.noreply@github.com
30172d10d393b33cdae969d91e33f9c65cd100bc
11181fec04389375bad720a409fc2bcfd6cd35f9
/ex5.py
8befc99c373181f1b0fefa55699cdf7aae61ee1d
[]
no_license
DanielGorski/Learn-Python-The-Hard-Way
8a1aa0724624da4c8fc775a49d296ffa9662926c
13f7f0df4def9153d2d52f90cf82e45e875fe2f8
refs/heads/master
2020-04-24T20:59:24.105840
2019-02-23T20:53:47
2019-02-23T20:53:47
172,262,473
0
0
null
null
null
null
UTF-8
Python
false
false
588
py
#Example 5 from Learn Python the Hard Way 2018-7-13 name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print(f"Let's talk about {name}.") print(f"He's {height} inches tall.") print(f"He's {weight} pounds heavy.") print("Actually he's not too heavy.") print(f"He's got {eyes} eyes and {hair} hair.") print(f"His teeth are usually {teeth} depending on the coffee.") # this line is tricky, try to get it exactly right total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.")
[ "DanGorski7@gmail.com" ]
DanGorski7@gmail.com
fc588cfd5fd8bd56c711bb4fdb2931229a2a9ca4
4dc56e3a980f8a60b7c3f8e938d648905aa3fcba
/code/pyqgis/gui/save_attributes_dialog.py
b54f1d05919d5ec4f120c2455f9650cc1be19edd
[]
no_license
spatialthoughts/courses
e7de4985da57d199a97b895c931f1ed774872302
be887ed1a74407131e42287d9411412ba0619a15
refs/heads/master
2023-08-29T21:05:49.873828
2023-08-24T11:52:56
2023-08-24T11:52:56
217,205,928
36
19
null
2023-09-02T13:01:34
2019-10-24T03:45:23
Jupyter Notebook
UTF-8
Python
false
false
365
py
import os from PyQt5 import uic from PyQt5 import QtWidgets FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'save_attributes_dialog.ui')) class SaveAttributesDialog(QtWidgets.QDialog, FORM_CLASS): def __init__(self, parent=None): super(SaveAttributesDialog, self).__init__(parent) self.setupUi(self)
[ "ujaval@spatialthoughts.com" ]
ujaval@spatialthoughts.com
b84415b00df0635282f30b96086af8660c67b489
ef6229d281edecbea3faad37830cb1d452d03e5b
/ucsmsdk/mometa/sw/SwSubGroup.py
c426f0abffac3af41808abc46ce47362dc52dc61
[ "Apache-2.0" ]
permissive
anoop1984/python_sdk
0809be78de32350acc40701d6207631322851010
c4a226bad5e10ad233eda62bc8f6d66a5a82b651
refs/heads/master
2020-12-31T00:18:57.415950
2016-04-26T17:39:38
2016-04-26T17:39:38
57,148,449
0
0
null
null
null
null
UTF-8
Python
false
false
4,956
py
"""This module contains the general information for SwSubGroup ManagedObject.""" import sys, os from ...ucsmo import ManagedObject from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class SwSubGroupConsts(): LIC_STATE_LICENSE_EXPIRED = "license-expired" LIC_STATE_LICENSE_GRACEPERIOD = "license-graceperiod" LIC_STATE_LICENSE_INSUFFICIENT = "license-insufficient" LIC_STATE_LICENSE_OK = "license-ok" LIC_STATE_NOT_APPLICABLE = "not-applicable" LIC_STATE_UNKNOWN = "unknown" SWITCH_ID_A = "A" SWITCH_ID_B = "B" SWITCH_ID_NONE = "NONE" class SwSubGroup(ManagedObject): """This is SwSubGroup class.""" consts = SwSubGroupConsts() naming_props = set([u'slotId', u'aggrPortId']) mo_meta = MoMeta("SwSubGroup", "swSubGroup", "slot-[slot_id]-aggr-port-[aggr_port_id]", VersionMeta.Version302a, "InputOutput", 0xff, [], ["read-only"], [u'swAccessDomain', u'swEthLanBorder', u'swEthMon', u'swFcMon', u'swFcSanBorder', u'swPhys'], [u'swAccessEp', u'swEthEstcEp', u'swEthLanEp', u'swEthMonDestEp', u'swEthMonSrcEp', u'swFcoeEstcEp', u'swFcoeSanEp', u'swPhysEtherEp', u'swPhysFcEp'], [None]) prop_meta = { "aggr_port_id": MoPropertyMeta("aggr_port_id", "aggrPortId", "uint", VersionMeta.Version302a, MoPropertyMeta.NAMING, 0x2, None, None, None, [], ["1-48"]), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version302a, MoPropertyMeta.INTERNAL, 0x4, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "lic_gp": MoPropertyMeta("lic_gp", "licGP", "ulong", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []), "lic_state": MoPropertyMeta("lic_state", "licState", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["license-expired", "license-graceperiod", "license-insufficient", "license-ok", "not-applicable", "unknown"], []), "locale": MoPropertyMeta("locale", "locale", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((defaultValue|unknown|server|chassis|internal|external),){0,5}(defaultValue|unknown|server|chassis|internal|external){0,1}""", [], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version302a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, 0x20, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "slot_id": MoPropertyMeta("slot_id", "slotId", "uint", VersionMeta.Version302a, MoPropertyMeta.NAMING, 0x40, None, None, None, [], ["1-4"]), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version302a, MoPropertyMeta.READ_WRITE, 0x80, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "switch_id": MoPropertyMeta("switch_id", "switchId", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["A", "B", "NONE"], []), "transport": MoPropertyMeta("transport", "transport", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((defaultValue|unknown|ether|dce|fc),){0,4}(defaultValue|unknown|ether|dce|fc){0,1}""", [], []), "type": MoPropertyMeta("type", "type", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((defaultValue|unknown|lan|san|ipc),){0,4}(defaultValue|unknown|lan|san|ipc){0,1}""", [], []), } prop_map = { "aggrPortId": "aggr_port_id", "childAction": "child_action", "dn": "dn", "licGP": "lic_gp", "licState": "lic_state", "locale": "locale", "name": "name", "rn": "rn", "sacl": "sacl", "slotId": "slot_id", "status": "status", "switchId": "switch_id", "transport": "transport", "type": "type", } def __init__(self, parent_mo_or_dn, slot_id, aggr_port_id, **kwargs): self._dirty_mask = 0 self.slot_id = slot_id self.aggr_port_id = aggr_port_id self.child_action = None self.lic_gp = None self.lic_state = None self.locale = None self.name = None self.sacl = None self.status = None self.switch_id = None self.transport = None self.type = None ManagedObject.__init__(self, "SwSubGroup", parent_mo_or_dn, **kwargs)
[ "test@cisco.com" ]
test@cisco.com
6cfad16c21f58f2d65891d650566167822810235
9d6ba09c8c85259525e032627cfb4e16ed0883a9
/fonts/DejaVuSansMono_20.py
7fbae4ef383bbffc938a72f782baf84c3b9a0f17
[ "MIT" ]
permissive
ironss/micropython-lib
b24744c44cb04d7f759da572a94aafe71333ad3d
61719636dad9aaa581c8e39e71ccc515e75c2d43
refs/heads/master
2020-06-29T16:42:53.383626
2019-10-29T13:03:04
2019-10-29T13:03:04
200,569,031
0
2
null
null
null
null
UTF-8
Python
false
false
16,330
py
# Code generated by font-to-py.py. # Font: DejaVuSansMono.ttf version = '0.26' def height(): return 20 def max_width(): return 11 def hmap(): return False def reverse(): return False def monospaced(): return False def min_ch(): return 32 def max_ch(): return 126 _font =\ b'\x0b\x00\x0c\x00\x00\x06\x00\x00\x06\x6f\x00\x86\x6f\x00\xe6\x01'\ b'\x00\x7c\x00\x00\x38\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x67\x00\xfe\x67\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x3e\x00\x00\x3e\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x3e\x00\x00\x3e\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x06'\ b'\x00\x30\x46\x00\x30\x7e\x00\xf0\x0f\x00\x7e\x06\x00\x37\x66\x00'\ b'\x30\x7f\x00\xf8\x07\x00\x3f\x06\x00\x31\x06\x00\x30\x00\x00\x0b'\ b'\x00\xe0\x30\x00\xf0\x61\x00\x18\x61\x00\x18\x61\x00\xfe\xff\x03'\ b'\x18\x62\x00\x18\x62\x00\x30\x3e\x00\x00\x1c\x00\x00\x00\x00\x00'\ b'\x00\x00\x0b\x00\x3c\x00\x00\x7e\x02\x00\x42\x02\x00\x42\x01\x00'\ b'\x7e\x01\x00\xbc\x3d\x00\x80\x7e\x00\x80\x42\x00\x40\x42\x00\x40'\ b'\x7e\x00\x00\x3c\x00\x0b\x00\x00\x1e\x00\x00\x3f\x00\xbc\x71\x00'\ b'\xfe\x60\x00\xc6\x61\x00\x86\x63\x00\x06\x2f\x00\x06\x1c\x00\x00'\ b'\x78\x00\x00\x6f\x00\x00\x47\x00\x0b\x00\x3e\x00\x00\x3e\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xc0\x1f\x00'\ b'\xf8\xff\x00\x1e\xc0\x03\x02\x00\x02\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00'\ b'\x02\x00\x02\x1e\xc0\x03\xf8\xff\x00\xc0\x1f\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x0b\x00\x84\x00\x00\x48\x00\x00\x48\x00\x00\x30\x00\x00\xfe'\ b'\x01\x00\x30\x00\x00\x48\x00\x00\x48\x00\x00\x84\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x0b\x00\x00\x03\x00\x00\x03\x00\x00\x03\x00\x00'\ b'\x03\x00\xf0\x3f\x00\xf0\x3f\x00\x00\x03\x00\x00\x03\x00\x00\x03'\ b'\x00\x00\x03\x00\x00\x00\x00\x0b\x00\x00\x80\x01\x00\xf0\x00\x00'\ b'\x70\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x06\x00\x00'\ b'\x06\x00\x00\x06\x00\x00\x06\x00\x00\x06\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00'\ b'\x70\x00\x00\x70\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x0b\x00\x00\x00\x01\x00\xc0\x01\x00\xf8\x00\x00\x3e\x00\x80\x07'\ b'\x00\xf0\x01\x00\x7c\x00\x00\x0e\x00\x00\x02\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x0b\x00\xf0\x0f\x00\xfc\x3f\x00\x0e\x70\x00\x06\x60'\ b'\x00\x86\x61\x00\x86\x61\x00\x0e\x70\x00\xfc\x3f\x00\xf0\x0f\x00'\ b'\x00\x00\x00\x00\x00\x00\x0b\x00\x0c\x60\x00\x0c\x60\x00\x06\x60'\ b'\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x60\x00\x00\x60\x00\x00\x60\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x0c\x60\x00\x06\x70'\ b'\x00\x06\x78\x00\x06\x6c\x00\x06\x66\x00\x06\x67\x00\x8e\x63\x00'\ b'\xfc\x61\x00\xf8\x60\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x0c\x30'\ b'\x00\x06\x60\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00'\ b'\xce\x73\x00\xfc\x3f\x00\x78\x1e\x00\x00\x00\x00\x00\x00\x00\x0b'\ b'\x00\x00\x0e\x00\x00\x0f\x00\xc0\x0d\x00\x60\x0c\x00\x18\x0c\x00'\ b'\x0e\x0c\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x0c\x00\x00\x0c\x00\x00'\ b'\x00\x00\x0b\x00\x00\x30\x00\xfe\x61\x00\xfe\x60\x00\xc6\x60\x00'\ b'\xc6\x60\x00\xc6\x60\x00\xc6\x71\x00\x86\x3f\x00\x00\x1f\x00\x00'\ b'\x00\x00\x00\x00\x00\x0b\x00\xf0\x0f\x00\xf8\x3f\x00\x9c\x71\x00'\ b'\xce\x60\x00\xc6\x60\x00\xc6\x60\x00\xc6\x71\x00\x8c\x3f\x00\x00'\ b'\x1f\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x06\x00\x00\x06\x00\x00'\ b'\x06\x40\x00\x06\x78\x00\x06\x3f\x00\xc6\x07\x00\xfe\x01\x00\x3e'\ b'\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x38\x1e\x00'\ b'\x7c\x3f\x00\xce\x73\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00\xce'\ b'\x73\x00\x7c\x3f\x00\x38\x1e\x00\x00\x00\x00\x00\x00\x00\x0b\x00'\ b'\xf8\x00\x00\xfc\x31\x00\x8e\x63\x00\x06\x63\x00\x06\x63\x00\x06'\ b'\x73\x00\x8e\x39\x00\xfc\x1f\x00\xf0\x0f\x00\x00\x00\x00\x00\x00'\ b'\x00\x0b\x00\xe0\x70\x00\xe0\x70\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x0b\x00\x00\x80\x01\xe0\xf0\x00\xe0\x70\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x01\x00\x80\x03\x00\x80'\ b'\x02\x00\xc0\x06\x00\xc0\x06\x00\x40\x04\x00\x60\x0c\x00\x60\x0c'\ b'\x00\x20\x08\x00\x30\x18\x00\x00\x00\x00\x0b\x00\xc0\x0c\x00\xc0'\ b'\x0c\x00\xc0\x0c\x00\xc0\x0c\x00\xc0\x0c\x00\xc0\x0c\x00\xc0\x0c'\ b'\x00\xc0\x0c\x00\xc0\x0c\x00\xc0\x0c\x00\x00\x00\x00\x0b\x00\x30'\ b'\x18\x00\x20\x08\x00\x60\x0c\x00\x60\x0c\x00\x40\x04\x00\xc0\x06'\ b'\x00\xc0\x06\x00\x80\x02\x00\x80\x03\x00\x00\x01\x00\x00\x00\x00'\ b'\x0b\x00\x0c\x00\x00\x06\x00\x00\x06\x6f\x00\x86\x6f\x00\xe6\x01'\ b'\x00\x7c\x00\x00\x38\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x0b\x00\xc0\x3f\x00\xf0\xff\x00\x38\xc0\x01\x0c\x00'\ b'\x03\x84\x1f\x02\xc4\x3f\x02\x4c\x20\x02\xf8\x3f\x00\xf0\x3f\x00'\ b'\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x60\x00\x00\x7e\x00\xe0\x1f'\ b'\x00\xfe\x0d\x00\x1e\x0c\x00\xfe\x0d\x00\xe0\x1f\x00\x00\x7e\x00'\ b'\x00\x60\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f'\ b'\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00\xce\x73\x00'\ b'\xfc\x3f\x00\x78\x1e\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xe0\x07'\ b'\x00\xf8\x1f\x00\x1c\x38\x00\x0e\x70\x00\x06\x60\x00\x06\x60\x00'\ b'\x06\x60\x00\x06\x60\x00\x0c\x30\x00\x00\x00\x00\x00\x00\x00\x0b'\ b'\x00\xfe\x7f\x00\xfe\x7f\x00\x06\x60\x00\x06\x60\x00\x06\x60\x00'\ b'\x0e\x70\x00\x1c\x38\x00\xf8\x1f\x00\xf0\x0f\x00\x00\x00\x00\x00'\ b'\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f\x00\x86\x61\x00\x86\x61\x00'\ b'\x86\x61\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00\x86\x61\x00\x00'\ b'\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f\x00\x86\x01\x00'\ b'\x86\x01\x00\x86\x01\x00\x86\x01\x00\x86\x01\x00\x86\x01\x00\x06'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xe0\x07\x00\xf8\x1f\x00'\ b'\x1c\x38\x00\x0e\x60\x00\x06\x60\x00\x86\x61\x00\x86\x61\x00\x86'\ b'\x3f\x00\x8c\x3f\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00'\ b'\xfe\x7f\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80'\ b'\x01\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x00\x00\x00\x00\x00\x0b\x00'\ b'\x06\x60\x00\x06\x60\x00\x06\x60\x00\xfe\x7f\x00\xfe\x7f\x00\x06'\ b'\x60\x00\x06\x60\x00\x06\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x0b\x00\x00\x30\x00\x00\x60\x00\x06\x60\x00\x06\x60\x00\x06'\ b'\x60\x00\x06\x70\x00\xfe\x3f\x00\xfe\x1f\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f\x00\x80\x01\x00\xc0'\ b'\x01\x00\xe0\x03\x00\x38\x0f\x00\x1c\x1e\x00\x0e\x78\x00\x06\x70'\ b'\x00\x02\x40\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f\x00\x00'\ b'\x60\x00\x00\x60\x00\x00\x60\x00\x00\x60\x00\x00\x60\x00\x00\x60'\ b'\x00\x00\x60\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe'\ b'\x7f\x00\x1e\x00\x00\xf0\x01\x00\x00\x03\x00\xf0\x01\x00\x1e\x00'\ b'\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe'\ b'\x7f\x00\xfe\x7f\x00\x1e\x00\x00\x78\x00\x00\xc0\x03\x00\x00\x1e'\ b'\x00\x00\x78\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x00\x00\x00\x00\x00'\ b'\x0b\x00\xf0\x0f\x00\xfc\x3f\x00\x0e\x70\x00\x06\x60\x00\x06\x60'\ b'\x00\x06\x60\x00\x0e\x70\x00\xfc\x3f\x00\xf0\x0f\x00\x00\x00\x00'\ b'\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f\x00\x86\x01\x00\x86\x01'\ b'\x00\x86\x01\x00\x86\x01\x00\xce\x01\x00\xfc\x00\x00\x78\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x0b\x00\xf0\x0f\x00\xfc\x3f\x00\x0e\x70'\ b'\x00\x06\x60\x00\x06\x60\x00\x06\xe0\x00\x0e\xf0\x03\xfc\x3f\x01'\ b'\xf0\x0f\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f'\ b'\x00\x86\x01\x00\x86\x01\x00\x86\x01\x00\x86\x03\x00\xce\x07\x00'\ b'\xfc\x1e\x00\x78\x78\x00\x00\x60\x00\x00\x40\x00\x0b\x00\x78\x30'\ b'\x00\xfc\x60\x00\xce\x60\x00\xc6\x61\x00\x86\x61\x00\x86\x61\x00'\ b'\x86\x73\x00\x0c\x3f\x00\x00\x1e\x00\x00\x00\x00\x00\x00\x00\x0b'\ b'\x00\x06\x00\x00\x06\x00\x00\x06\x00\x00\x06\x00\x00\xfe\x7f\x00'\ b'\xfe\x7f\x00\x06\x00\x00\x06\x00\x00\x06\x00\x00\x06\x00\x00\x00'\ b'\x00\x00\x0b\x00\xfe\x1f\x00\xfe\x3f\x00\x00\x70\x00\x00\x60\x00'\ b'\x00\x60\x00\x00\x60\x00\x00\x70\x00\xfe\x3f\x00\xfe\x1f\x00\x00'\ b'\x00\x00\x00\x00\x00\x0b\x00\x06\x00\x00\x7e\x00\x00\xf8\x07\x00'\ b'\x80\x7f\x00\x00\x78\x00\x80\x7f\x00\xf8\x07\x00\x7e\x00\x00\x06'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x1e\x00\x00\xfe\x0f\x00'\ b'\xf0\x7f\x00\x00\x7c\x00\xe0\x07\x00\x60\x00\x00\xe0\x07\x00\x00'\ b'\x7c\x00\xf0\x7f\x00\xfe\x0f\x00\x1e\x00\x00\x0b\x00\x02\x40\x00'\ b'\x0e\x70\x00\x3e\x3c\x00\x78\x0f\x00\xe0\x03\x00\x78\x0f\x00\x1e'\ b'\x3c\x00\x0e\x70\x00\x02\x40\x00\x00\x00\x00\x00\x00\x00\x0b\x00'\ b'\x02\x00\x00\x0e\x00\x00\x3e\x00\x00\xf8\x00\x00\xe0\x7f\x00\xe0'\ b'\x7f\x00\xf8\x00\x00\x3e\x00\x00\x0e\x00\x00\x02\x00\x00\x00\x00'\ b'\x00\x0b\x00\x06\x60\x00\x06\x78\x00\x06\x7e\x00\x06\x6f\x00\xc6'\ b'\x63\x00\xf6\x60\x00\x7e\x60\x00\x1e\x60\x00\x06\x60\x00\x00\x00'\ b'\x00\x00\x00\x00\x0b\x00\xfe\xff\x03\xfe\xff\x03\x06\x00\x03\x06'\ b'\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x02\x00\x00\x0e\x00\x00\x7c'\ b'\x00\x00\xf0\x01\x00\x80\x07\x00\x00\x3e\x00\x00\xf8\x00\x00\xc0'\ b'\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x0b\x00\x06\x00\x03\x06'\ b'\x00\x03\xfe\xff\x03\xfe\xff\x03\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x20'\ b'\x00\x00\x30\x00\x00\x18\x00\x00\x0c\x00\x00\x06\x00\x00\x06\x00'\ b'\x00\x0c\x00\x00\x18\x00\x00\x30\x00\x00\x20\x00\x00\x00\x00\x00'\ b'\x0b\x00\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80'\ b'\x01\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80\x01'\ b'\x00\x80\x01\x0b\x00\x01\x00\x00\x03\x00\x00\x0e\x00\x00\x08\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x3c\x00\xc0\x3c\x00\x60\x66'\ b'\x00\x60\x66\x00\x60\x66\x00\x60\x66\x00\x60\x36\x00\xc0\x7f\x00'\ b'\xc0\x7f\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f'\ b'\x00\xc0\x30\x00\x60\x60\x00\x60\x60\x00\x60\x60\x00\xe0\x70\x00'\ b'\xc0\x3f\x00\x80\x1f\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x0f'\ b'\x00\xc0\x3f\x00\xc0\x30\x00\x60\x60\x00\x60\x60\x00\x60\x60\x00'\ b'\x60\x60\x00\xc0\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b'\ b'\x00\x80\x1f\x00\xc0\x3f\x00\xe0\x70\x00\x60\x60\x00\x60\x60\x00'\ b'\x60\x60\x00\xc0\x30\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x00\x00\x00'\ b'\x00\x00\x0b\x00\x00\x0f\x00\xc0\x3f\x00\xe0\x36\x00\x60\x66\x00'\ b'\x60\x66\x00\x60\x66\x00\xe0\x66\x00\xc0\x67\x00\x80\x37\x00\x00'\ b'\x00\x00\x00\x00\x00\x0b\x00\x60\x00\x00\x60\x00\x00\x60\x00\x00'\ b'\xfc\x7f\x00\xfe\x7f\x00\x66\x00\x00\x66\x00\x00\x66\x00\x00\x66'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x80\x1f\x00\xc0\x3f\x03'\ b'\xe0\x70\x06\x60\x60\x06\x60\x60\x06\x60\x60\x06\xc0\x30\x07\xe0'\ b'\xff\x03\xe0\xff\x01\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00'\ b'\xfe\x7f\x00\xc0\x00\x00\x40\x00\x00\x60\x00\x00\x60\x00\x00\xe0'\ b'\x00\x00\xc0\x7f\x00\x80\x7f\x00\x00\x00\x00\x00\x00\x00\x0b\x00'\ b'\x60\x60\x00\x60\x60\x00\x60\x60\x00\xe6\x7f\x00\xe6\x7f\x00\x00'\ b'\x60\x00\x00\x60\x00\x00\x60\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x0b\x00\x00\x00\x06\x60\x00\x06\x60\x00\x06\x60\x00\x06\xe6'\ b'\xff\x03\xe6\xff\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x0b\x00\xfe\x7f\x00\xfe\x7f\x00\x00\x06\x00\x00'\ b'\x07\x00\x80\x0f\x00\xc0\x3d\x00\xe0\x70\x00\x60\x60\x00\x20\x40'\ b'\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x06\x00\x00\x06\x00\x00\x06'\ b'\x00\x00\xfe\x1f\x00\xfe\x3f\x00\x00\x60\x00\x00\x60\x00\x00\x60'\ b'\x00\x00\x60\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xe0\x7f\x00\xe0'\ b'\x7f\x00\x40\x00\x00\x60\x00\x00\xe0\x7f\x00\xc0\x7f\x00\x60\x00'\ b'\x00\x60\x00\x00\xe0\x7f\x00\xc0\x7f\x00\x00\x00\x00\x0b\x00\xe0'\ b'\x7f\x00\xe0\x7f\x00\xc0\x00\x00\x40\x00\x00\x60\x00\x00\x60\x00'\ b'\x00\xe0\x00\x00\xc0\x7f\x00\x80\x7f\x00\x00\x00\x00\x00\x00\x00'\ b'\x0b\x00\x80\x1f\x00\xc0\x3f\x00\xe0\x70\x00\x60\x60\x00\x60\x60'\ b'\x00\x60\x60\x00\xe0\x70\x00\xc0\x3f\x00\x80\x1f\x00\x00\x00\x00'\ b'\x00\x00\x00\x0b\x00\xe0\xff\x07\xe0\xff\x07\xc0\x30\x00\x60\x60'\ b'\x00\x60\x60\x00\x60\x60\x00\xe0\x70\x00\xc0\x3f\x00\x80\x1f\x00'\ b'\x00\x00\x00\x00\x00\x00\x0b\x00\x80\x1f\x00\xc0\x3f\x00\xe0\x70'\ b'\x00\x60\x60\x00\x60\x60\x00\x60\x60\x00\xc0\x30\x00\xe0\xff\x07'\ b'\xe0\xff\x07\x00\x00\x00\x00\x00\x00\x0b\x00\xe0\x7f\x00\xe0\x7f'\ b'\x00\x80\x00\x00\x60\x00\x00\x60\x00\x00\x60\x00\x00\xc0\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xc0\x31'\ b'\x00\xc0\x63\x00\x60\x63\x00\x60\x63\x00\x60\x63\x00\x60\x66\x00'\ b'\x60\x66\x00\x60\x3e\x00\xc0\x3c\x00\x00\x00\x00\x00\x00\x00\x0b'\ b'\x00\x60\x00\x00\x60\x00\x00\x60\x00\x00\xfc\x3f\x00\xfc\x7f\x00'\ b'\x60\x60\x00\x60\x60\x00\x60\x60\x00\x60\x60\x00\x00\x00\x00\x00'\ b'\x00\x00\x0b\x00\xe0\x1f\x00\xe0\x3f\x00\x00\x70\x00\x00\x60\x00'\ b'\x00\x60\x00\x00\x20\x00\x00\x30\x00\xe0\x7f\x00\xe0\x7f\x00\x00'\ b'\x00\x00\x00\x00\x00\x0b\x00\x20\x00\x00\xe0\x01\x00\xc0\x0f\x00'\ b'\x00\x7e\x00\x00\x70\x00\x00\x7e\x00\xc0\x0f\x00\xe0\x01\x00\x20'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x60\x00\x00\xe0\x07\x00'\ b'\x80\x7f\x00\x00\x78\x00\x00\x1e\x00\x00\x03\x00\x00\x1e\x00\x00'\ b'\x78\x00\x80\x7f\x00\xe0\x07\x00\x60\x00\x00\x0b\x00\x20\x40\x00'\ b'\x60\x60\x00\xe0\x78\x00\xc0\x1f\x00\x00\x0f\x00\xc0\x1f\x00\xe0'\ b'\x78\x00\x60\x60\x00\x20\x40\x00\x00\x00\x00\x00\x00\x00\x0b\x00'\ b'\x20\x00\x00\xe0\x01\x06\xc0\x07\x06\x00\xdf\x07\x00\xf8\x03\x00'\ b'\x7e\x00\xc0\x0f\x00\xe0\x01\x00\x20\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x0b\x00\x60\x60\x00\x60\x70\x00\x60\x78\x00\x60\x7e\x00\x60'\ b'\x67\x00\xe0\x63\x00\xe0\x61\x00\xe0\x60\x00\x60\x60\x00\x00\x00'\ b'\x00\x00\x00\x00\x0b\x00\x00\x03\x00\x00\x03\x00\x00\x07\x00\xfc'\ b'\xff\x03\xfe\xfc\x07\x06\x00\x06\x06\x00\x06\x06\x00\x06\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x0b\x00\xfe\xff\x0f\xfe\xff\x0f\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x06\x00\x06\x06'\ b'\x00\x06\x06\x00\x06\xfe\xfc\x07\xfc\xff\x03\x00\x07\x00\x00\x03'\ b'\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00'\ b'\x03\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x80\x01\x00\x00\x03'\ b'\x00\x00\x03\x00\x00\x03\x00\x00\x03\x00\x80\x01\x00\x00\x00\x00'\ _index =\ b'\x00\x00\x23\x00\x46\x00\x69\x00\x8c\x00\xaf\x00\xd2\x00\xf5\x00'\ b'\x18\x01\x3b\x01\x5e\x01\x81\x01\xa4\x01\xc7\x01\xea\x01\x0d\x02'\ b'\x30\x02\x53\x02\x76\x02\x99\x02\xbc\x02\xdf\x02\x02\x03\x25\x03'\ b'\x48\x03\x6b\x03\x8e\x03\xb1\x03\xd4\x03\xf7\x03\x1a\x04\x3d\x04'\ b'\x60\x04\x83\x04\xa6\x04\xc9\x04\xec\x04\x0f\x05\x32\x05\x55\x05'\ b'\x78\x05\x9b\x05\xbe\x05\xe1\x05\x04\x06\x27\x06\x4a\x06\x6d\x06'\ b'\x90\x06\xb3\x06\xd6\x06\xf9\x06\x1c\x07\x3f\x07\x62\x07\x85\x07'\ b'\xa8\x07\xcb\x07\xee\x07\x11\x08\x34\x08\x57\x08\x7a\x08\x9d\x08'\ b'\xc0\x08\xe3\x08\x06\x09\x29\x09\x4c\x09\x6f\x09\x92\x09\xb5\x09'\ b'\xd8\x09\xfb\x09\x1e\x0a\x41\x0a\x64\x0a\x87\x0a\xaa\x0a\xcd\x0a'\ b'\xf0\x0a\x13\x0b\x36\x0b\x59\x0b\x7c\x0b\x9f\x0b\xc2\x0b\xe5\x0b'\ b'\x08\x0c\x2b\x0c\x4e\x0c\x71\x0c\x94\x0c\xb7\x0c\xda\x0c\xfd\x0c'\ b'\x20\x0d' _mvfont = memoryview(_font) def _chr_addr(ordch): offset = 2 * (ordch - 32) return int.from_bytes(_index[offset:offset + 2], 'little') def get_width(s): width = 0 for ch in s: ordch = ord(ch) ordch = ordch + 1 if ordch >= 32 and ordch <= 126 else 32 offset = _chr_addr(ordch) width += int.from_bytes(_font[offset:offset + 2], 'little') return width def get_ch(ch): ordch = ord(ch) ordch = ordch + 1 if ordch >= 32 and ordch <= 126 else 32 offset = _chr_addr(ordch) width = int.from_bytes(_font[offset:offset + 2], 'little') next_offs = _chr_addr(ordch +1) return _mvfont[offset + 2:next_offs], width
[ "ironss@users.noreply.github.com" ]
ironss@users.noreply.github.com
4887499dd7d6ba58377157d5fbabd448f931cd46
078bc261847e155d3f8cca2dcc0d2f363eedc84d
/server/server/create_db.py
46ec34febb45cdb70b659d610c642c09690e68b1
[]
no_license
SinyTim/PriceChecker
96bbbe9154c959375c8b6d08f4958c27c348e936
4720e35b2a87b6c236631d77d8a1b3ab31bf47a8
refs/heads/master
2022-04-01T04:25:50.737771
2020-02-04T21:00:36
2020-02-04T21:00:36
194,554,215
0
0
null
null
null
null
UTF-8
Python
false
false
1,103
py
from app import db from app import Product from app import Store from app import User if __name__ == '__main__': db.create_all() store0 = Store(address='г. Минск 0000') store1 = Store(address='г. Минск 0001') user0 = User(name='Тимур') user1 = User(name='Слава') products = [ Product(id='4811680006239', name='name 1', price=3.4, store=store0), Product(id='9785818319315', name='name 2', price=5.7, store=store1), Product(id='40822426', name='Водичка Славы', price=2.21, store=store0), Product(id='4810431004296', name='tim copybook 1', price=4.9, store=store0), Product(id='4690338982053', name='tim copybook 2', price=1.99, store=store1), Product(id='0000000000000', name='test 1', price=17.3, store=store1), Product(id='0000000000001', name='test 2', price=32.0, store=store0), ] db.session.add(store0) db.session.add(store1) db.session.add(user0) db.session.add(user1) for product in products: db.session.add(product) db.session.commit()
[ "sinytim@mail.ru" ]
sinytim@mail.ru
08bfd5060f4a0c9c22d5426ff027ee50bc243201
b15919c8f9ae25a46e116ed4c01157baffefbd02
/setup.py
ff6e4f50621d86f01b0c36bedcfb9145319e32ae
[ "CC0-1.0" ]
permissive
Rested/django-tabular-export
556919279546b3da00cac983b2bd7b9be5d57e17
bf3f3612a52d456e868b2df1871fc523f31317e9
refs/heads/master
2021-01-02T09:13:51.143993
2017-08-03T00:03:44
2017-08-03T00:03:44
99,171,042
0
0
null
2017-08-02T23:53:19
2017-08-02T23:53:18
null
UTF-8
Python
false
false
1,258
py
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import, division, print_function import os import re import sys from setuptools import setup readme = open('README.rst').read() setup( name='django-tabular-export', version='1.0.2', description="""Simple spreadsheet exports from Django""", long_description=readme, author='Chris Adams', author_email='cadams@loc.gov', url='https://github.com/LibraryOfCongress/django-tabular-export', packages=[ 'tabular_export', ], include_package_data=True, install_requires=[ 'Django', 'xlsxwriter', ], test_suite='tests.run_tests.run_tests', license='CC0', zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Intended Audience :: Developers', 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', ], )
[ "cadams@loc.gov" ]
cadams@loc.gov
7e352db04f5190ac30729e62f8c9a86f397adb88
b94fd62e07517f2ce957944b68bf2d5b45d44b03
/src/model.py
be157646d833ea369188822ce3b855ad32acb37e
[ "MIT" ]
permissive
luzpaz/floor-planner
405ae92482347218ae88270bb4bfcef12e3f747c
971334bb7054232035411419910bc860d5da9206
refs/heads/main
2023-02-21T15:51:38.510887
2021-01-14T20:36:16
2021-01-14T20:36:16
322,641,479
1
1
MIT
2020-12-18T16:03:58
2020-12-18T16:03:58
null
UTF-8
Python
false
false
16,918
py
import math, sdl2, sys, threading from actions import AddAction, DeleteAction from collections import deque from entities import Line, Window, Door, UserText, RectangularEntity from entity_types import EntityType, ModelMutex from threading import Lock from tools import Tools class Model: """Contains the application entities and provides queries on them.""" def __init__(self): """Initializes the entity containers, factories, and mutexes. """ self.lines = set() self.vertices = set() self.windows = set() self.doors = set() self.user_text = set() self.square_vertices = set() self.actions = deque() self.undos = deque() self.update_background = threading.Condition() self.line_factory = AbstractLineFactory() self.init_mutexes() # Whether the renderer must update the layers self.update_needed = False def add_line(self, type, start = (0, 0), end = (0, 0), color = (0, 0, 0)): """Adds a line and its vertices to the model. :param start: The starting vertex of the line :param end: The ending vertex of the line :type start, end: tuple(int, int) :param color: The r, g, b values for the line's rendering color :type color: tuple(int, int, int) """ line = self.line_factory.create(type, start, end, color) if not line: return None with self.mutexes[ModelMutex.LINES]: self.lines.add(line) self.update_vertices() self.update_needed = True with self.update_background: self.update_background.notify_all() if line: self.actions.append(AddAction(line)) return line def add_window(self, location = (0, 0), horizontal = True): """Adds a window to the model at the center location. :param location: Center location position coordinates for the window :type location: tuple(int, int) :param horizontal: Whether the window is horizontal or vertical :type horizontal: bool """ window = None if horizontal: window = Window(sdl2.SDL_Rect( int(location[0] - Window.LENGTH / 2), int(location[1] - Window.WIDTH / 2), Window.LENGTH, Window.WIDTH)) else: window = Window(sdl2.SDL_Rect( int(location[0] - Window.WIDTH / 2), int(location[1] - Window.LENGTH / 2), Window.WIDTH, Window.LENGTH)) with self.mutexes[ModelMutex.WINDOWS]: self.windows.add(window) self.update_needed = True if window: self.actions.append(AddAction(window)) return window def add_door(self, location = (0, 0), horizontal = True, thickness = 0): """Adds a door to the model at the center location. :param location: Center location position coordinates for the door :type location: tuple(int, int) :param horizontal: Whether the door is horizontal or vertical :type horizontal: bool :param thickness: Thickness of the door :type thickness: int """ door = None if horizontal: door = Door(sdl2.SDL_Rect( int(location[0] - Door.LENGTH / 2), int(location[1] - thickness / 2), Door.LENGTH, thickness)) else: door = Door(sdl2.SDL_Rect( int(location[0] - thickness / 2), int(location[1] - Door.LENGTH / 2), thickness, Door.LENGTH)) with self.mutexes[ModelMutex.DOORS]: self.doors.add(door) self.update_needed = True if door: self.actions.append(AddAction(door)) return door def add_vertices_from_line(self, line): """Adds starting and ending vertices of the line to the model. :param line: The line to add vertices for :type line: Line from 'entities.py' """ self.vertices.add((line.start[0], line.start[1])) self.vertices.add((line.end[0], line.end[1])) def add_user_text(self, text = '', position = (0, 0)): """Adds user text to the absolute position. :param text: Text to add :type text: str :param position: Absolute position of the text :type position: tuple(int, int) """ text = UserText(text, position) with self.mutexes[ModelMutex.TEXT]: self.user_text.add(text) self.update_needed = True self.actions.append(AddAction(text)) return text def add_entity(self, entity): """Adds the already created entity into the model. :param entity: The entity to add :type entity: Any entity type stored by the model """ entity.add_to_model(self) self.update_needed = True with self.update_background: self.update_background.notify_all() def remove_entity(self, entity, action = True): """Removes entity from the model. :param entity: The entity to remove :type entity: Any entity type stored by the model :param action: Whether the user did this removal explicitly. :type action: boolean """ if not entity: return entity.remove_from_model(self) self.update_needed = True with self.update_background: self.update_background.notify_all() if action: self.actions.append(DeleteAction(entity)) def update_vertices(self): """Clears current vertices and re-adds them for each line. """ with self.mutexes[ModelMutex.VERTICES]: self.vertices = set() for line in self.lines: self.add_vertices_from_line(line) self.square_vertices = set() for line in self.lines: self.close_gaps_between_walls(line) def get_vertex_within_range(self, origin = (0, 0), range = 6): """Returns nearest vertex from the origin that is within the range :param origin: Position to search for closest vertex :type origin: tuple(int, int) :param range: Amount of distance to search for closest vertex :type range: int """ nearest_vertex = None nearest_vertex_distance = sys.maxsize for vertex in self.vertices: distance = Line.distance(vertex, origin) if distance > range: continue if distance < nearest_vertex_distance: nearest_vertex = vertex nearest_vertex_distance = distance return nearest_vertex def get_vertex_on_axis(self, origin = (0, 0), horizontal = True): """Returns nearest vertex that is on the same horizontal or vertical axis as the origin vertex :param origin: Location to search axis for :type origin: tuple(int, int) :param horizontal: Whether the origin line is horizontal or vertical :type horizontal: boolean """ nearest_vertex = None nearest_vertex_distance = sys.maxsize for vertex in self.vertices: if horizontal: axis_distance = abs(vertex[0] - origin[0]) else: axis_distance = abs(vertex[1] - origin[1]) if axis_distance != 0: continue distance = Line.distance(vertex, origin) if distance < nearest_vertex_distance: nearest_vertex = vertex nearest_vertex_distance = distance return nearest_vertex def get_nearest_wall(self, location = (0, 0), exterior_only = False): """Returns the nearest horizontal or vertical wall to the location and the closest point on that wall, for window or door placement. :param location: Position coordinates to find nearest wall for :type location: tuple(int, int) """ closest_line = None closest_point = None closest_point_distance = sys.maxsize for line in self.lines: # Exterior walls only for windows if (exterior_only and line.thickness != Line.EXTERIOR_WALL)\ or (not exterior_only and line.thickness == Line.REGULAR_LINE): continue # Horizontal or vertical walls only if line.horizontal: point = (location[0], line.start[1]) elif line.vertical: point = (line.start[0], location[1]) else: continue # Find closest point distance = Line.distance(point, location) if distance < closest_point_distance: closest_line = line closest_point = point closest_point_distance = distance # No walls found near the location if closest_line == None or closest_point == None\ or closest_point_distance > Window.MAX_DISTANCE: return None return (closest_line, closest_point) def get_entity_on_location(self, location = (0, 0)): """Returns single entity that collides with the location :param location: Position coordinates to check collision against :type location: tuple(int, int) """ for door in self.doors: door.selected = False if door.check_collision( sdl2.SDL_Rect(int(location[0]), int(location[1]), 0, 0)): door.selected = True return door for window in self.windows: window.selected = False if window.check_collision( sdl2.SDL_Rect(int(location[0]), int(location[1]), 0, 0)): window.selected = True return window for line in self.lines: line.selected = False if line.check_point_collision(location): line.selected = True return line return None def get_entities_in_rectangle(self, rectangle = sdl2.SDL_Rect()): """Returns set of entities that collide with the rectangle :param rectangle: Rectangle to check collision against (x = top-left x-position, y = top-left y-position, w = width, h = height) :type rectangle: SDL_Rect """ entities = set() for door in self.doors: door.selected = False if door.check_collision(rectangle): entities.add(door) door.selected = True for window in self.windows: window.selected = False if window.check_collision(rectangle): entities.add(window) window.selected = True for line in self.lines: line.selected = False if line.check_rectangle_collision(rectangle): entities.add(line) line.selected = True for text in self.user_text: text.selected = False if text.check_collision(rectangle): entities.add(text) text.selected = True self.update_needed = True return entities def get_inventory(self): """Returns a string of entities grouped by type and lengths. For instance: - 4 x 8' exterior wall - 2 x 8' interior wall """ inventory = '' exterior_walls = {} interior_walls = {} # Tally up quantities for each wall length for line in self.lines: if line.thickness == Line.EXTERIOR_WALL: if line.length in exterior_walls: exterior_walls[line.length] += 1 else: exterior_walls[line.length] = 1 elif line.thickness == Line.INTERIOR_WALL: if line.length in interior_walls: interior_walls[line.length] += 1 else: interior_walls[line.length] = 1 # Add to inventory string for wall in exterior_walls: inventory += 'Exterior wall: '\ + str(exterior_walls[wall]) + ' x '\ + Tools.convert_to_unit_system(wall) + '\n' for wall in interior_walls: inventory += 'Interior wall: '\ + str(interior_walls[wall]) + ' x '\ + Tools.convert_to_unit_system(wall) + '\n' return inventory def close_gaps_between_walls(self, line): """Adds a square vertex to close gaps between two connecting walls for rendering. """ for other in self.lines: # Exterior and interior walls only if line.thickness == Line.REGULAR_LINE: continue # Do not compare against the same line if line is other: continue if line.start == other.start or line.start == other.end: vertex = RectangularEntity(sdl2.SDL_Rect( int(line.start[0] - line.thickness / 2), int(line.start[1] - line.thickness / 2), line.thickness, line.thickness)) vertex.layer = line.layer self.square_vertices.add(vertex) if line.end == other.end or line.end == other.start: vertex = RectangularEntity(sdl2.SDL_Rect( int(line.end[0] - line.thickness / 2), int(line.end[1] - line.thickness / 2), line.thickness, line.thickness)) vertex.layer = line.layer self.square_vertices.add(vertex) def init_mutexes(self): """Initializes the model mutexes for synchronization of accessing the entity containers. """ self.mutexes = {} self.mutexes[ModelMutex.LINES] = Lock() self.mutexes[ModelMutex.VERTICES] = Lock() self.mutexes[ModelMutex.WINDOWS] = Lock() self.mutexes[ModelMutex.DOORS] = Lock() self.mutexes[ModelMutex.TEXT] = Lock() self.mutexes[ModelMutex.SQUARE_VERTICES] = Lock() class ExteriorWallFactory: """Factory for exterior wall.""" def create(self, start = (0, 0), end = (0, 0), color = (0, 0, 0)): """Creates and returns an exterior wall line. :param start: The starting vertex of the line :param end: The ending vertex of the line :type start, end: tuple(int, int) :param color: The r, g, b values for the line's rendering color :type color: tuple(int, int, int)""" return Line(start, end, Line.EXTERIOR_WALL, color) class InteriorWallFactory: """Factory for interior wall.""" def create(self, start = (0, 0), end = (0, 0), color = (0, 0, 0)): """Creates and returns an interior wall line. :param start: The starting vertex of the line :param end: The ending vertex of the line :type start, end: tuple(int, int) :param color: The r, g, b values for the line's rendering color :type color: tuple(int, int, int)""" return Line(start, end, Line.INTERIOR_WALL, color) class RegularLineFactory: """Factory for regular line.""" def create(self, start = (0, 0), end = (0, 0), color = (0, 0, 0)): """Creates and returns an regular line. :param start: The starting vertex of the line :param end: The ending vertex of the line :type start, end: tuple(int, int) :param color: The r, g, b values for the line's rendering color :type color: tuple(int, int, int)""" return Line(start, end, Line.REGULAR_LINE, color) class AbstractLineFactory: """Abstract factory for creating lines.""" def __init__(self): """Initializes the line factories.""" self.factories = {} self.factories[EntityType.EXTERIOR_WALL] = ExteriorWallFactory() self.factories[EntityType.INTERIOR_WALL] = InteriorWallFactory() self.factories[EntityType.REGULAR_LINE] = RegularLineFactory() def create(self, type, start = (0, 0), end = (0, 0), color = (0, 0, 0)): """Creates and returns the line of type. :param type: The type of line to create. :type type: EntityType :param start: The starting vertex of the line :param end: The ending vertex of the line :type start, end: tuple(int, int) :param color: The r, g, b values for the line's rendering color :type color: tuple(int, int, int)""" if type in self.factories: return self.factories[type].create(start, end, color) return None
[ "fby1@pitt.edu" ]
fby1@pitt.edu
01f3f17a63579224f4d0ef5150061e175bb6dd44
59166105545cdd87626d15bf42e60a9ee1ef2413
/dbpedia/models/drama.py
872325e9ffb7b36418df93e3025bd0a2a48432c2
[]
no_license
mosoriob/dbpedia_api_client
8c594fc115ce75235315e890d55fbf6bd555fa85
8d6f0d04a3a30a82ce0e9277e4c9ce00ecd0c0cc
refs/heads/master
2022-11-20T01:42:33.481024
2020-05-12T23:22:54
2020-05-12T23:22:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
33,267
py
# coding: utf-8 """ DBpedia This is the API of the DBpedia Ontology # noqa: E501 The version of the OpenAPI document: v0.0.1 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from dbpedia.configuration import Configuration class Drama(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'previous_work': 'list[object]', 'coden': 'list[str]', 'translator': 'list[object]', 'alternative_title': 'list[str]', 'description': 'list[str]', 'subsequent_work': 'list[object]', 'chief_editor': 'list[object]', 'music_composer': 'list[object]', 'last_publication_date': 'list[str]', 'type': 'list[str]', 'lcc': 'list[str]', 'lccn': 'list[str]', 'main_character': 'list[object]', 'id': 'str', 'literary_genre': 'list[object]', 'based_on': 'list[object]', 'first_publisher': 'list[object]', 'first_publication_date': 'list[str]', 'film_version': 'list[object]', 'release_date': 'list[str]', 'number_of_volumes': 'list[int]', 'composer': 'list[object]', 'author': 'list[object]', 'preface_by': 'list[object]', 'runtime': 'list[object]', 'production_company': 'list[object]', 'label': 'list[str]', 'original_language': 'list[object]', 'license': 'list[object]', 'subject_term': 'list[str]', 'original_title': 'list[str]', 'circulation': 'list[int]', 'oclc': 'list[str]', 'producer': 'list[object]', 'starring': 'list[object]', 'completion_date': 'list[str]', 'writer': 'list[object]', 'magazine': 'list[object]' } attribute_map = { 'previous_work': 'previousWork', 'coden': 'coden', 'translator': 'translator', 'alternative_title': 'alternativeTitle', 'description': 'description', 'subsequent_work': 'subsequentWork', 'chief_editor': 'chiefEditor', 'music_composer': 'musicComposer', 'last_publication_date': 'lastPublicationDate', 'type': 'type', 'lcc': 'lcc', 'lccn': 'lccn', 'main_character': 'mainCharacter', 'id': 'id', 'literary_genre': 'literaryGenre', 'based_on': 'basedOn', 'first_publisher': 'firstPublisher', 'first_publication_date': 'firstPublicationDate', 'film_version': 'filmVersion', 'release_date': 'releaseDate', 'number_of_volumes': 'numberOfVolumes', 'composer': 'composer', 'author': 'author', 'preface_by': 'prefaceBy', 'runtime': 'runtime', 'production_company': 'productionCompany', 'label': 'label', 'original_language': 'originalLanguage', 'license': 'license', 'subject_term': 'subjectTerm', 'original_title': 'originalTitle', 'circulation': 'circulation', 'oclc': 'oclc', 'producer': 'producer', 'starring': 'starring', 'completion_date': 'completionDate', 'writer': 'writer', 'magazine': 'magazine' } def __init__(self, previous_work=None, coden=None, translator=None, alternative_title=None, description=None, subsequent_work=None, chief_editor=None, music_composer=None, last_publication_date=None, type=None, lcc=None, lccn=None, main_character=None, id=None, literary_genre=None, based_on=None, first_publisher=None, first_publication_date=None, film_version=None, release_date=None, number_of_volumes=None, composer=None, author=None, preface_by=None, runtime=None, production_company=None, label=None, original_language=None, license=None, subject_term=None, original_title=None, circulation=None, oclc=None, producer=None, starring=None, completion_date=None, writer=None, magazine=None, local_vars_configuration=None): # noqa: E501 """Drama - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._previous_work = None self._coden = None self._translator = None self._alternative_title = None self._description = None self._subsequent_work = None self._chief_editor = None self._music_composer = None self._last_publication_date = None self._type = None self._lcc = None self._lccn = None self._main_character = None self._id = None self._literary_genre = None self._based_on = None self._first_publisher = None self._first_publication_date = None self._film_version = None self._release_date = None self._number_of_volumes = None self._composer = None self._author = None self._preface_by = None self._runtime = None self._production_company = None self._label = None self._original_language = None self._license = None self._subject_term = None self._original_title = None self._circulation = None self._oclc = None self._producer = None self._starring = None self._completion_date = None self._writer = None self._magazine = None self.discriminator = None self.previous_work = previous_work self.coden = coden self.translator = translator self.alternative_title = alternative_title self.description = description self.subsequent_work = subsequent_work self.chief_editor = chief_editor self.music_composer = music_composer self.last_publication_date = last_publication_date self.type = type self.lcc = lcc self.lccn = lccn self.main_character = main_character if id is not None: self.id = id self.literary_genre = literary_genre self.based_on = based_on self.first_publisher = first_publisher self.first_publication_date = first_publication_date self.film_version = film_version self.release_date = release_date self.number_of_volumes = number_of_volumes self.composer = composer self.author = author self.preface_by = preface_by self.runtime = runtime self.production_company = production_company self.label = label self.original_language = original_language self.license = license self.subject_term = subject_term self.original_title = original_title self.circulation = circulation self.oclc = oclc self.producer = producer self.starring = starring self.completion_date = completion_date self.writer = writer self.magazine = magazine @property def previous_work(self): """Gets the previous_work of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The previous_work of this Drama. # noqa: E501 :rtype: list[object] """ return self._previous_work @previous_work.setter def previous_work(self, previous_work): """Sets the previous_work of this Drama. Description not available # noqa: E501 :param previous_work: The previous_work of this Drama. # noqa: E501 :type: list[object] """ self._previous_work = previous_work @property def coden(self): """Gets the coden of this Drama. # noqa: E501 CODEN is a six character, alphanumeric bibliographic code, that provides concise, unique and unambiguous identification of the titles of serials and non-serial publications from all subject areas. # noqa: E501 :return: The coden of this Drama. # noqa: E501 :rtype: list[str] """ return self._coden @coden.setter def coden(self, coden): """Sets the coden of this Drama. CODEN is a six character, alphanumeric bibliographic code, that provides concise, unique and unambiguous identification of the titles of serials and non-serial publications from all subject areas. # noqa: E501 :param coden: The coden of this Drama. # noqa: E501 :type: list[str] """ self._coden = coden @property def translator(self): """Gets the translator of this Drama. # noqa: E501 Translator(s), if original not in English # noqa: E501 :return: The translator of this Drama. # noqa: E501 :rtype: list[object] """ return self._translator @translator.setter def translator(self, translator): """Sets the translator of this Drama. Translator(s), if original not in English # noqa: E501 :param translator: The translator of this Drama. # noqa: E501 :type: list[object] """ self._translator = translator @property def alternative_title(self): """Gets the alternative_title of this Drama. # noqa: E501 The alternative title attributed to a work # noqa: E501 :return: The alternative_title of this Drama. # noqa: E501 :rtype: list[str] """ return self._alternative_title @alternative_title.setter def alternative_title(self, alternative_title): """Sets the alternative_title of this Drama. The alternative title attributed to a work # noqa: E501 :param alternative_title: The alternative_title of this Drama. # noqa: E501 :type: list[str] """ self._alternative_title = alternative_title @property def description(self): """Gets the description of this Drama. # noqa: E501 small description # noqa: E501 :return: The description of this Drama. # noqa: E501 :rtype: list[str] """ return self._description @description.setter def description(self, description): """Sets the description of this Drama. small description # noqa: E501 :param description: The description of this Drama. # noqa: E501 :type: list[str] """ self._description = description @property def subsequent_work(self): """Gets the subsequent_work of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The subsequent_work of this Drama. # noqa: E501 :rtype: list[object] """ return self._subsequent_work @subsequent_work.setter def subsequent_work(self, subsequent_work): """Sets the subsequent_work of this Drama. Description not available # noqa: E501 :param subsequent_work: The subsequent_work of this Drama. # noqa: E501 :type: list[object] """ self._subsequent_work = subsequent_work @property def chief_editor(self): """Gets the chief_editor of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The chief_editor of this Drama. # noqa: E501 :rtype: list[object] """ return self._chief_editor @chief_editor.setter def chief_editor(self, chief_editor): """Sets the chief_editor of this Drama. Description not available # noqa: E501 :param chief_editor: The chief_editor of this Drama. # noqa: E501 :type: list[object] """ self._chief_editor = chief_editor @property def music_composer(self): """Gets the music_composer of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The music_composer of this Drama. # noqa: E501 :rtype: list[object] """ return self._music_composer @music_composer.setter def music_composer(self, music_composer): """Sets the music_composer of this Drama. Description not available # noqa: E501 :param music_composer: The music_composer of this Drama. # noqa: E501 :type: list[object] """ self._music_composer = music_composer @property def last_publication_date(self): """Gets the last_publication_date of this Drama. # noqa: E501 Date of the last publication. # noqa: E501 :return: The last_publication_date of this Drama. # noqa: E501 :rtype: list[str] """ return self._last_publication_date @last_publication_date.setter def last_publication_date(self, last_publication_date): """Sets the last_publication_date of this Drama. Date of the last publication. # noqa: E501 :param last_publication_date: The last_publication_date of this Drama. # noqa: E501 :type: list[str] """ self._last_publication_date = last_publication_date @property def type(self): """Gets the type of this Drama. # noqa: E501 type of the resource # noqa: E501 :return: The type of this Drama. # noqa: E501 :rtype: list[str] """ return self._type @type.setter def type(self, type): """Sets the type of this Drama. type of the resource # noqa: E501 :param type: The type of this Drama. # noqa: E501 :type: list[str] """ self._type = type @property def lcc(self): """Gets the lcc of this Drama. # noqa: E501 The Library of Congress Classification (LCC) is a system of library classification developed by the Library of Congress. # noqa: E501 :return: The lcc of this Drama. # noqa: E501 :rtype: list[str] """ return self._lcc @lcc.setter def lcc(self, lcc): """Sets the lcc of this Drama. The Library of Congress Classification (LCC) is a system of library classification developed by the Library of Congress. # noqa: E501 :param lcc: The lcc of this Drama. # noqa: E501 :type: list[str] """ self._lcc = lcc @property def lccn(self): """Gets the lccn of this Drama. # noqa: E501 The Library of Congress Control Number or LCCN is a serially based system of numbering cataloging records in the Library of Congress in the United States. It has nothing to do with the contents of any book, and should not be confused with Library of Congress Classification. # noqa: E501 :return: The lccn of this Drama. # noqa: E501 :rtype: list[str] """ return self._lccn @lccn.setter def lccn(self, lccn): """Sets the lccn of this Drama. The Library of Congress Control Number or LCCN is a serially based system of numbering cataloging records in the Library of Congress in the United States. It has nothing to do with the contents of any book, and should not be confused with Library of Congress Classification. # noqa: E501 :param lccn: The lccn of this Drama. # noqa: E501 :type: list[str] """ self._lccn = lccn @property def main_character(self): """Gets the main_character of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The main_character of this Drama. # noqa: E501 :rtype: list[object] """ return self._main_character @main_character.setter def main_character(self, main_character): """Sets the main_character of this Drama. Description not available # noqa: E501 :param main_character: The main_character of this Drama. # noqa: E501 :type: list[object] """ self._main_character = main_character @property def id(self): """Gets the id of this Drama. # noqa: E501 identifier # noqa: E501 :return: The id of this Drama. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this Drama. identifier # noqa: E501 :param id: The id of this Drama. # noqa: E501 :type: str """ self._id = id @property def literary_genre(self): """Gets the literary_genre of this Drama. # noqa: E501 A literary genre is a category of literary composition. Genres may be determined by literary technique, tone, content, or even (as in the case of fiction) length. # noqa: E501 :return: The literary_genre of this Drama. # noqa: E501 :rtype: list[object] """ return self._literary_genre @literary_genre.setter def literary_genre(self, literary_genre): """Sets the literary_genre of this Drama. A literary genre is a category of literary composition. Genres may be determined by literary technique, tone, content, or even (as in the case of fiction) length. # noqa: E501 :param literary_genre: The literary_genre of this Drama. # noqa: E501 :type: list[object] """ self._literary_genre = literary_genre @property def based_on(self): """Gets the based_on of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The based_on of this Drama. # noqa: E501 :rtype: list[object] """ return self._based_on @based_on.setter def based_on(self, based_on): """Sets the based_on of this Drama. Description not available # noqa: E501 :param based_on: The based_on of this Drama. # noqa: E501 :type: list[object] """ self._based_on = based_on @property def first_publisher(self): """Gets the first_publisher of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The first_publisher of this Drama. # noqa: E501 :rtype: list[object] """ return self._first_publisher @first_publisher.setter def first_publisher(self, first_publisher): """Sets the first_publisher of this Drama. Description not available # noqa: E501 :param first_publisher: The first_publisher of this Drama. # noqa: E501 :type: list[object] """ self._first_publisher = first_publisher @property def first_publication_date(self): """Gets the first_publication_date of this Drama. # noqa: E501 Date of the first publication. # noqa: E501 :return: The first_publication_date of this Drama. # noqa: E501 :rtype: list[str] """ return self._first_publication_date @first_publication_date.setter def first_publication_date(self, first_publication_date): """Sets the first_publication_date of this Drama. Date of the first publication. # noqa: E501 :param first_publication_date: The first_publication_date of this Drama. # noqa: E501 :type: list[str] """ self._first_publication_date = first_publication_date @property def film_version(self): """Gets the film_version of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The film_version of this Drama. # noqa: E501 :rtype: list[object] """ return self._film_version @film_version.setter def film_version(self, film_version): """Sets the film_version of this Drama. Description not available # noqa: E501 :param film_version: The film_version of this Drama. # noqa: E501 :type: list[object] """ self._film_version = film_version @property def release_date(self): """Gets the release_date of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The release_date of this Drama. # noqa: E501 :rtype: list[str] """ return self._release_date @release_date.setter def release_date(self, release_date): """Sets the release_date of this Drama. Description not available # noqa: E501 :param release_date: The release_date of this Drama. # noqa: E501 :type: list[str] """ self._release_date = release_date @property def number_of_volumes(self): """Gets the number_of_volumes of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The number_of_volumes of this Drama. # noqa: E501 :rtype: list[int] """ return self._number_of_volumes @number_of_volumes.setter def number_of_volumes(self, number_of_volumes): """Sets the number_of_volumes of this Drama. Description not available # noqa: E501 :param number_of_volumes: The number_of_volumes of this Drama. # noqa: E501 :type: list[int] """ self._number_of_volumes = number_of_volumes @property def composer(self): """Gets the composer of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The composer of this Drama. # noqa: E501 :rtype: list[object] """ return self._composer @composer.setter def composer(self, composer): """Sets the composer of this Drama. Description not available # noqa: E501 :param composer: The composer of this Drama. # noqa: E501 :type: list[object] """ self._composer = composer @property def author(self): """Gets the author of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The author of this Drama. # noqa: E501 :rtype: list[object] """ return self._author @author.setter def author(self, author): """Sets the author of this Drama. Description not available # noqa: E501 :param author: The author of this Drama. # noqa: E501 :type: list[object] """ self._author = author @property def preface_by(self): """Gets the preface_by of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The preface_by of this Drama. # noqa: E501 :rtype: list[object] """ return self._preface_by @preface_by.setter def preface_by(self, preface_by): """Sets the preface_by of this Drama. Description not available # noqa: E501 :param preface_by: The preface_by of this Drama. # noqa: E501 :type: list[object] """ self._preface_by = preface_by @property def runtime(self): """Gets the runtime of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The runtime of this Drama. # noqa: E501 :rtype: list[object] """ return self._runtime @runtime.setter def runtime(self, runtime): """Sets the runtime of this Drama. Description not available # noqa: E501 :param runtime: The runtime of this Drama. # noqa: E501 :type: list[object] """ self._runtime = runtime @property def production_company(self): """Gets the production_company of this Drama. # noqa: E501 the company that produced the work e.g. Film, MusicalWork, Software # noqa: E501 :return: The production_company of this Drama. # noqa: E501 :rtype: list[object] """ return self._production_company @production_company.setter def production_company(self, production_company): """Sets the production_company of this Drama. the company that produced the work e.g. Film, MusicalWork, Software # noqa: E501 :param production_company: The production_company of this Drama. # noqa: E501 :type: list[object] """ self._production_company = production_company @property def label(self): """Gets the label of this Drama. # noqa: E501 short description of the resource # noqa: E501 :return: The label of this Drama. # noqa: E501 :rtype: list[str] """ return self._label @label.setter def label(self, label): """Sets the label of this Drama. short description of the resource # noqa: E501 :param label: The label of this Drama. # noqa: E501 :type: list[str] """ self._label = label @property def original_language(self): """Gets the original_language of this Drama. # noqa: E501 The original language of the work. # noqa: E501 :return: The original_language of this Drama. # noqa: E501 :rtype: list[object] """ return self._original_language @original_language.setter def original_language(self, original_language): """Sets the original_language of this Drama. The original language of the work. # noqa: E501 :param original_language: The original_language of this Drama. # noqa: E501 :type: list[object] """ self._original_language = original_language @property def license(self): """Gets the license of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The license of this Drama. # noqa: E501 :rtype: list[object] """ return self._license @license.setter def license(self, license): """Sets the license of this Drama. Description not available # noqa: E501 :param license: The license of this Drama. # noqa: E501 :type: list[object] """ self._license = license @property def subject_term(self): """Gets the subject_term of this Drama. # noqa: E501 The subject as a term, possibly a term from a formal classification # noqa: E501 :return: The subject_term of this Drama. # noqa: E501 :rtype: list[str] """ return self._subject_term @subject_term.setter def subject_term(self, subject_term): """Sets the subject_term of this Drama. The subject as a term, possibly a term from a formal classification # noqa: E501 :param subject_term: The subject_term of this Drama. # noqa: E501 :type: list[str] """ self._subject_term = subject_term @property def original_title(self): """Gets the original_title of this Drama. # noqa: E501 The original title of the work, most of the time in the original language as well # noqa: E501 :return: The original_title of this Drama. # noqa: E501 :rtype: list[str] """ return self._original_title @original_title.setter def original_title(self, original_title): """Sets the original_title of this Drama. The original title of the work, most of the time in the original language as well # noqa: E501 :param original_title: The original_title of this Drama. # noqa: E501 :type: list[str] """ self._original_title = original_title @property def circulation(self): """Gets the circulation of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The circulation of this Drama. # noqa: E501 :rtype: list[int] """ return self._circulation @circulation.setter def circulation(self, circulation): """Sets the circulation of this Drama. Description not available # noqa: E501 :param circulation: The circulation of this Drama. # noqa: E501 :type: list[int] """ self._circulation = circulation @property def oclc(self): """Gets the oclc of this Drama. # noqa: E501 Online Computer Library Center number # noqa: E501 :return: The oclc of this Drama. # noqa: E501 :rtype: list[str] """ return self._oclc @oclc.setter def oclc(self, oclc): """Sets the oclc of this Drama. Online Computer Library Center number # noqa: E501 :param oclc: The oclc of this Drama. # noqa: E501 :type: list[str] """ self._oclc = oclc @property def producer(self): """Gets the producer of this Drama. # noqa: E501 The producer of the creative work. # noqa: E501 :return: The producer of this Drama. # noqa: E501 :rtype: list[object] """ return self._producer @producer.setter def producer(self, producer): """Sets the producer of this Drama. The producer of the creative work. # noqa: E501 :param producer: The producer of this Drama. # noqa: E501 :type: list[object] """ self._producer = producer @property def starring(self): """Gets the starring of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The starring of this Drama. # noqa: E501 :rtype: list[object] """ return self._starring @starring.setter def starring(self, starring): """Sets the starring of this Drama. Description not available # noqa: E501 :param starring: The starring of this Drama. # noqa: E501 :type: list[object] """ self._starring = starring @property def completion_date(self): """Gets the completion_date of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The completion_date of this Drama. # noqa: E501 :rtype: list[str] """ return self._completion_date @completion_date.setter def completion_date(self, completion_date): """Sets the completion_date of this Drama. Description not available # noqa: E501 :param completion_date: The completion_date of this Drama. # noqa: E501 :type: list[str] """ self._completion_date = completion_date @property def writer(self): """Gets the writer of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The writer of this Drama. # noqa: E501 :rtype: list[object] """ return self._writer @writer.setter def writer(self, writer): """Sets the writer of this Drama. Description not available # noqa: E501 :param writer: The writer of this Drama. # noqa: E501 :type: list[object] """ self._writer = writer @property def magazine(self): """Gets the magazine of this Drama. # noqa: E501 Description not available # noqa: E501 :return: The magazine of this Drama. # noqa: E501 :rtype: list[object] """ return self._magazine @magazine.setter def magazine(self, magazine): """Sets the magazine of this Drama. Description not available # noqa: E501 :param magazine: The magazine of this Drama. # noqa: E501 :type: list[object] """ self._magazine = magazine def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Drama): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, Drama): return True return self.to_dict() != other.to_dict()
[ "maxiosorio@gmail.com" ]
maxiosorio@gmail.com
6c9e791386589630f38aa7ffd33c9322cf2502d6
709f7fafb1e6f9be16513de005b11766b4b62b85
/hw6/solve.py
dd93010c5d919da1f24a1e2795d737ca2ee70b4b
[]
no_license
k123321141/ctf
d785d0b2c3b4860f1db37c8dd70d1ef487373166
12f6289a1301566b596c77efd5b36170a7bc8b5a
refs/heads/master
2021-10-23T05:15:00.089299
2019-03-15T02:26:50
2019-03-15T02:26:50
105,388,880
0
0
null
null
null
null
UTF-8
Python
false
false
1,318
py
#!/usr/bin/env python ''' ais3_crackme has been developed by Tyler Nighswander (tylerni7) for ais3. It is an easy crackme challenge. It checks the command line argument. ''' import angr import claripy def main(): project = angr.Project("./eggReverse2") #create an initial state with a symbolic bit vector as argv1 argv1 = claripy.BVS("argv1",100*8) #since we do not the length now, we just put 100 bytes initial_state = project.factory.entry_state(args=["./crackme1",argv1]) #create a path group using the created initial state sm = project.factory.simulation_manager(initial_state) #symbolically execute the program until we reach the wanted value of the instruction pointer sm.explore(find=0x080485f8) #at this instruction the binary will print the "correct" message found = sm.found[0] #ask to the symbolic solver to get the value of argv1 in the reached state as a string solution = found.solver.eval(argv1, cast_to=str) print 'found' ,repr(solution) print dir(found) with open('./out','wb') as f: f.write(repr(solution)) solution = solution[:solution.find("\x00")] print solution return solution def test(): res = main() assert res == "ais3{I_tak3_g00d_n0t3s}" if __name__ == '__main__': print(repr(main()))
[ "kk123321141@gamil.com" ]
kk123321141@gamil.com
758432203fb57a0647f9fde6d47d73957a24fbd2
096be1cd22299ba0f3cddb474f965a6e72710c87
/dajaxexamples/urls.py
cad298d6f73a0546122c05a42faeef07731eadc5
[]
no_license
DarioGT/DAjax
3f0a43e21ce8d4f9692e09cc5a67e8c1851fcc7f
f90efd6dd9b727aadec124af244884385e176b8e
refs/heads/master
2020-05-07T14:36:32.085962
2011-08-20T03:43:12
2011-08-20T03:43:12
2,232,073
0
0
null
null
null
null
UTF-8
Python
false
false
1,367
py
from django.conf.urls.defaults import * from django.conf import settings from dajaxice.core import dajaxice_autodiscover dajaxice_autodiscover() # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('',) urlpatterns += patterns('', # Example: # (r'^dajaxTest/', include('dajaxTest.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), # Dajax URLS (r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')), #Website Examples (r'^multiply/?$', 'dajaxexamples.examples.views.multiply'), (r'^maps/?$', 'dajaxexamples.examples.views.maps'), (r'random/?$', 'dajaxexamples.examples.views.random_example'), (r'forms/?$', 'dajaxexamples.examples.views.form_example'), (r'pagination/?$', 'dajaxexamples.examples.views.pagination_example'), (r'full_form/?$', 'dajaxexamples.examples.views.full_form_example'), (r'flickr/?$', 'dajaxexamples.examples.views.flickr_example'), #Api examples (r'apiexamples/?$', 'dajaxexamples.apiexamples.views.api_examples'), (r'dajax', 'dajaxexamples.examples.views.index'), )
[ "dariogomezt@gmail.com" ]
dariogomezt@gmail.com
c75fc1c0d2e46c634eca757db0ac01e73c5b9a7c
4c016963d77c9dbe53941d6d2cd493008d2b5909
/homework/hw5/hw5.py
65350a646052d313e0dcdf892bb808266a139011
[]
no_license
diemacre/machine_learning_projects
b98c17f090a140efa0fb2676393f9047372cfdd6
c52188a42af8f3015833dd491829b0993b580c29
refs/heads/master
2020-04-13T06:18:15.977300
2019-05-19T23:35:05
2019-05-19T23:35:05
163,016,530
0
0
null
null
null
null
UTF-8
Python
false
false
3,356
py
ve#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 16 17:44:06 2018 @author: diego """ import matplotlib.pyplot as plt import numpy as np import pandas import sklearn.metrics as metrics import scipy import sklearn.svm as svm import statsmodels.api as sm import statsmodels.stats.weightstats as st wineQuality = pandas.read_csv('WineQuality.csv', delimiter=',') wineQuality= wineQuality.drop(wineQuality[['quality','type']], axis=1) wine=wineQuality #wine.loc[wine['type'] == 'white', ['type']] = 0 #wine.loc[wine['type'] == 'red', ['type']]= 1 target= wine[['quality_grp']] atributes= wine.drop(wine[['quality_grp']], axis=1) atributes_list= atributes.columns.values.tolist() ''' for atr in atributes_list: if atr == 'type': wine.boxplot(column=atr, by='quality_grp', vert=False, figsize=(10,5), layout=(1,1)) plt.xticks(np.arange(2), ('white', 'red')) plt.ylabel('quality_gpr') plt.xlabel(atr) plt.title('') else: wine.boxplot(column=atr, by='quality_grp', vert=False, figsize=(10,5)) plt.xlabel(atr) plt.ylabel('quality_grp') plt.title('') plt.show() ''' #print(scipy.stats.ttest_ind(atributes, wine[['quality_grp']])) #au1= wine[wine['quality_grp'] == 0]['type'] #au2= wine[wine['quality_grp'] == 0]['type'] #print('au1=:', au1) ''' for atr in atributes_list: au1= wine.loc[wine['quality_grp'] == 0, [atr]] au2= wine.loc[wine['quality_grp'] == 1, [atr]] #statistic, pvalue= scipy.stats.ttest_ind(atributes[[atr]], wine[['quality_grp']]) statistic, pvalue= scipy.stats.ttest_ind(au1, au2) print(atr,',',statistic[0],',', pvalue[0]) print('\n') ''' # Try the sklearn.svm.LinearSVC #atributes2= atributes.drop(atributes[['citric_acid','volatile_acidity','chlorides','fixed_acidity','residual_sugar','free_sulfur_dioxide','total_sulfur_dioxide']], axis=1) trainData = atributes[['volatile_acidity', 'chlorides', 'density', 'alcohol']] #trainData =atributes #trainData = atributes2 yTrain = target svm_Model = svm.LinearSVC(verbose = 1, random_state = 20181111, max_iter = 10000) thisFit = svm_Model.fit(trainData, yTrain) print('\nIntercept:\n', thisFit.intercept_) print('\nWeight Coefficients:\n', thisFit.coef_) y_predictClass = thisFit.predict(trainData) print('\nMean Accuracy = ', metrics.accuracy_score(yTrain, y_predictClass)) trainData['_PredictedClass_'] = y_predictClass svm_Mean = trainData.groupby('_PredictedClass_').mean() print(svm_Mean) svm_Mean25 = trainData.groupby('_PredictedClass_').quantile(0.25) print(svm_Mean25) svm_Mean75 = trainData.groupby('_PredictedClass_').quantile(0.75) print(svm_Mean75) ''' carray = ['red', 'green'] plt.figure(figsize=(10,10)) for i in range(2): subData = trainData[trainData['_PredictedClass_'] == i] plt.scatter(x = subData['alcohol'], y = subData['pH'], c = carray[i], label = i, s = 10) plt.scatter(x = svm_Mean['alcohol'], y = svm_Mean['pH'], c = ['black','blue'], marker = 'X', s = 150) #plt.plot([12.95, 10.75], [0, 40], color = 'black', linestyle = ':') plt.grid(True) plt.title('Support Vector Machines') plt.xlabel('X') plt.ylabel('Y') plt.legend(title = 'Predicted Class', loc = 'best', bbox_to_anchor = (1, 1), fontsize = 14) plt.show() '''
[ "dmartinc2009@gmail.com" ]
dmartinc2009@gmail.com
e951c143495204bff5313da8af9c3748f160624c
0529c424f9cc9558524bed12d40322b7727cb383
/code/draw_ruler.py
beb3874112795c16b857eb42f69ab55d07a06d6c
[]
no_license
leovam/algpy
00f2a595f8e07029df6b8d8e3d7f66c49b3d2c7f
c6311d1f629edec3584761f57b5c4013d19f0208
refs/heads/master
2020-04-25T19:26:40.241177
2019-05-30T01:49:41
2019-05-30T01:49:41
173,020,873
0
0
null
null
null
null
UTF-8
Python
false
false
805
py
def draw_line(tick_length, tick_label=''): """Draw one line with given tick length (followed by optional label)""" line = '-' * tick_length if tick_label: line += ' ' + tick_label print line def draw_interval(center_length): """Draw tick interval based upon a central tick length""" if center_length > 0: draw_interval(center_length-1) draw_line(center_length) draw_interval(center_length-1) def draw_ruler(number_inches, major_length): """Draw English ruler with given number of inches, major tick length""" draw_line(major_length,'0') for j in range(1,1+number_inches): draw_interval(major_length-1) draw_line(major_length, str(j)) if __name__ == '__main__': draw_line(1) draw_interval(3) draw_ruler(3,4)
[ "leovam171@gmail.com" ]
leovam171@gmail.com
bd155feeb7bcbb41b267ab9de609286408bc6b1e
127fa3dd454434b4c7526afe161177af2e10226e
/剑指offer/字符流中第一个不重复的字符.py
74cdc18011e3ffac030cf214191a1b06bda50b9b
[]
no_license
lunar-r/sword-to-offer-python
966c46a8ddcff8ce5c95697638c988d83da3beab
fab4c341486e872fb2926d1b6d50499d55e76a4a
refs/heads/master
2023-04-18T18:57:12.126441
2020-11-29T09:51:23
2020-11-29T09:51:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,451
py
# -*- coding: utf-8 -*- """ File Name: 字符流中第一个不重复的字符 Description : Author : simon date: 19-3-20 """ # -*- coding:utf-8 -*- class Solution: # 返回对应char def __init__(self): self.dic = {} self.queue = [] def FirstAppearingOnce(self): # write code here for c in self.queue: # 这里有bug 不知道是不是边弹出 边遍历会出现bug if self.dic[c] != 1: self.queue.pop(0) else: return c return '#' def Insert(self, char): # write code here if char not in self.dic.keys(): self.dic[char] = 0 self.dic[char] += 1 self.queue.append(char) # -*- coding:utf-8 -*- class Solution_: # 返回对应char def __init__(self): self.dic = {} self.queue = [] # 先进先出 不满足出现次数为1时直接删除元素 def FirstAppearingOnce(self): # write code here while len(self.queue) and self.dic[self.queue[0]] != 1: # 持续检查第一个元素是否满足条件 不满足条件直接删掉 self.queue.pop(0) if not len(self.queue): return '#' return self.queue[0] def Insert(self, char): # write code here if char not in self.dic.keys(): self.dic[char] = 0 self.dic[char] += 1 self.queue.append(char)
[ "2711772037@qq.com" ]
2711772037@qq.com
a98eec40823238def86e6b7e39a535c126f77352
1fe08ef06ba163ce41bc665b2d9868774a222bdd
/Lab-12.5.py
824b5c007160b1f13f4b40111d90a236b16331c3
[]
no_license
ShaneRandell/LAB12
9a7fd436074ce86dd0750e82eff7b7746e5a02eb
99cf482d49c98894b6bf11905916742d8e55c657
refs/heads/main
2023-04-01T13:04:09.937016
2021-04-05T18:47:42
2021-04-05T18:47:42
354,922,139
0
0
null
null
null
null
UTF-8
Python
false
false
505
py
import cv2 as cv import numpy as np img = cv.imread('lines.jpg') gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) edges = cv.Canny(gray, 50, 120) minLineLength = 20 maxLineGap = 5 lines = cv.HoughLinesP(edges, 1, np.pi/180.0, 20, minLineLength, maxLineGap) No_lines,a,b = np.shape(lines) print(No_lines) for index in range(No_lines): for x1, y1, x2, y2 in lines[index]: cv.line(img, (x1, y1), (x2, y2), (0,255,0),2) cv.imshow("edges", edges) cv.imshow("lines", img) cv.waitKey()
[ "noreply@github.com" ]
ShaneRandell.noreply@github.com
63776206d1c774a7744c1ab535eaaa36fc8365bb
ddf3332875770229c3f02f878f4f5b205eb3722c
/meerkat/writers/abstract.py
a688aae4559c95af3eb717cbe996163413349530
[ "Apache-2.0" ]
permissive
abidlabs/meerkat
8c330cfe9085d36ef970f98cb272261f1c6c3476
a5f40ac8738845a1b3f7981f02c9d515722a9e66
refs/heads/main
2023-06-29T05:43:21.951603
2021-06-28T17:41:08
2021-06-28T17:41:08
392,415,449
0
1
Apache-2.0
2021-08-03T18:24:22
2021-08-03T18:24:21
null
UTF-8
Python
false
false
777
py
import abc class AbstractWriter(abc.ABC): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __repr__(self): return f"{self.__class__.__name__}" def __str__(self): return f"{self.__class__.__name__}" @abc.abstractmethod def open(self, *args, **kwargs) -> None: return NotImplemented @abc.abstractmethod def write(self, data, *args, **kwargs) -> None: return NotImplemented @abc.abstractmethod def flush(self, *args, **kwargs) -> None: return NotImplemented @abc.abstractmethod def close(self, *args, **kwargs) -> None: return NotImplemented @abc.abstractmethod def finalize(self, *args, **kwargs) -> None: return NotImplemented
[ "noreply@github.com" ]
abidlabs.noreply@github.com
940b8ad58f623c59bcfc92f10be21cc0192216b7
778974c722faa2151ce359b368567d569dca6b03
/utils/awrams/utils/remote.py
abe124c876685f6e9060cfa02eedc3da9885d005
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
muguangyuze/awra_cms-1
aff8a1d8f48eab147b623c3c828763f969cbfe58
c4c1ca7c55161b051141e7207c121203bed90c68
refs/heads/master
2020-04-03T14:25:27.690913
2018-04-09T23:33:55
2018-04-09T23:33:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,674
py
import paramiko import os from getpass import getpass import re import copy class Interactor: def __init__(self,ssh_client): self.client = ssh_client def __call__(self,command): stdin, stdout, stderr = self.client.exec_command(command) err = [k.strip() for k in stderr.readlines()] return [k.strip() for k in stdout.readlines()], err def put(self,localfile,remotepath=None): if remotepath is None: remotepath = os.path.split(localfile)[-1] sftp = self.client.open_sftp() sftp.put(localfile, remotepath) sftp.close() def get(self,remotefile,localpath=None): filename = os.path.split(remotefile)[-1] if localpath is None: localpath = filename elif os.path.isdir(localpath): localpath = os.path.join(localpath,filename) sftp = self.client.open_sftp() sftp.get(remotefile,localpath) sftp.close() def establish_remote_session(username=None,host='raijin.nci.org.au'): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if username is None: username=input("Username:") client.connect(host, username=username,password=getpass('Password:')) return Interactor(client) def clone_to_raijin(session,remote_path,force=False,local_path=None,exclusions=None): ''' No error checking! This is for convenience only... ''' from subprocess import call from os import environ, chdir if local_path is None: local_path=environ['AWRAPATH'] os.chdir(local_path) if exclusions is None: exclusions = ['.git','AcceptanceTests','Samples','*ipynb*','WIRADA','River','*__pycache__*'] tar_cmd = 'tar -cf out.tgz *' for k in exclusions: tar_cmd = tar_cmd + ' --exclude='+k call(tar_cmd,shell=True) if force: session('rm -rf %s' % remote_path) session('mkdir -p %s' % remote_path) session.put('out.tgz',remote_path + '/out.tgz') session('cd %s; tar -xf out.tgz; rm out.tgz' % remote_path) call('rm out.tgz',shell=True) session('cd %s; mv raijin_activate.sh activate' % remote_path) session('cd %s/Config/; mv raijin_host_defaults.py host_defaults.py' % remote_path) class HostPath: def __init__(self,key,relpath=''): self.key = key self.relpath = relpath def __call__(self,relpath=''): return HostPath(self,relpath) def localise(self,pathmap): if isinstance(self.key,HostPath): mapped = self.key.localise(pathmap) elif isinstance(pathmap[self.key],HostPath): mapped = pathmap[self.key].localise(pathmap) else: mapped = pathmap[self.key] return os.path.join(mapped,self.relpath) def __repr__(self): return repr(self.key)+'/'+self.relpath def resolve_hostpaths(node,host_dict=None,parent=None,key=None,copydict=True): ''' Localise a full map of hostpaths ''' if host_dict is None: host_dict = node if parent is None and key is None and copydict == True: node = copy.deepcopy(node) if hasattr(node,'items'): for k,v in node.items(): resolve_hostpaths(v,host_dict,node,k) else: if isinstance(node,HostPath): parent[key] = node.localise(host_dict) return node class PBSJob: def __init__(self,client,job_name,pbs_name,outpath): self.client = client self.job_name = job_name self.pbs_name = pbs_name self.pbs_id = pbs_name.split('.')[0] self.outpath = outpath def get_status(self): status_str, error_str = self.client('qstat %s' % self.pbs_name) if len(error_str) > 0: if re.match('.*Job has finished.*',str(error_str)) is not None: return 'Finished' else: return status_str def get_output(self): res,err = self.client('qcat %s' % self.pbs_name) if len(res) > 0: if res[0] == 'PBS error: Job has finished': res = self.client('cat %s' % os.path.join(self.outpath,self.job_name+'.o'+self.pbs_id)) return res def get_errors(self): res,err = self.client('qcat -e %s' % self.pbs_name) if len(res) > 0: if res[0] == 'PBS error: Job has finished': res = self.client('cat %s' % os.path.join(self.outpath,self.job_name+'.e'+self.pbs_id)) return res def cancel(self): return self.client('qdel %s' % self.pbs_name)
[ "david.shipman@bom.gov.au" ]
david.shipman@bom.gov.au
0c43353b180feaf31b0f238a00b26c793c3b5632
e828d4fcaf9eec2bfc4c51980428068e797f5929
/ABC/abc144/a/main.py
9641140c7796bc7fc9e4a307dec636fdc66f846f
[]
no_license
sfus/try-AtCoder
c53694b9bcba5be1ef6f3a47a6b3c0b727becc16
1d5a3c7648b5b309b1fa05826b4f7e608d6629fa
refs/heads/master
2022-11-21T19:36:15.056633
2020-07-22T16:08:11
2020-07-25T02:20:45
198,068,565
0
0
null
null
null
null
UTF-8
Python
false
false
127
py
#!/usr/bin/env python a, b = input().split() if len(a) == 1 and len(b) == 1: print(int(a) * int(b)) else: print('-1')
[ "sfus.dev@gmail.com" ]
sfus.dev@gmail.com
4316c9cf00ec0e66cefb7d75872a232fb2b7d7b9
9a5e5536ecacbce585617ac991361484e086105e
/ps/swea/0319/tester.py
c6ebc69bce6fae59ec7cd348f24e6e3a162002bf
[]
no_license
kingssafy/til
8bc938f9fc2525e2efb6025a587ec03536f8bf2a
50ecf62465dfa7db57711b1a6130cbaaed90af30
refs/heads/master
2020-04-16T10:03:50.568961
2019-04-23T11:55:34
2019-04-23T11:55:34
165,488,462
1
0
null
null
null
null
UTF-8
Python
false
false
2,052
py
import sys sys.stdin = open("code_input.txt") code = { "0001101": 0, "0011001": 1,         "0010011": 2,         "0111101": 3,         "0100011": 4,         "0110001": 5,         "0101111": 6,         "0111011": 7,         "0110111": 8,         "0001011": 9,         }     def htd(n):     if n in '0123456789':         n = int(n)     else:         n = 10+ord(n) - ord("A")     return n   def dtb(n):     result = ""     for i in range(3,-1,-1):         if (1<<i)&n:             result += "1"         else:             result += "0"     return result   T = int(input()) for tc in range(T):     N, M = map(int, input().split())     grid = [list(input()) for _ in range(N)]     for r in grid:         ch = "".join(r)         if ch != "0"*M:             tt = r             break     cp=""     for i in tt:         cp += dtb(htd(i))     i = len(cp) -1;     rythm = []     while i >= 6:         if cp[i] != "0":             for s in range(1, 11):                 value = cp[i+1-7*s:i+1:s]                 if value in code:                     rythm.append(code[value])                     i = i-7*s                     break         else:             i -= 1;     rythm.reverse()     result = 0     for idx, value in enumerate(rythm):         if idx % 2:             result += value         else:             result += 3*value     if result % 10:         print(f"#{tc+1} 0")     else:         print(f"#{tc+1} {sum(rythm)}")
[ "inmak@INMAKs-MacBook-Air-2.local" ]
inmak@INMAKs-MacBook-Air-2.local
a502c8a11e80b706364583bb727874910781f564
3645e5fed01bee5945b0ab0ec6380826db5b4a2f
/infinitescrolling/infinitescrolling/infinitescrolling/spiders/ScrollScraper.py
8e74646a2c0b4187b3020854c67193b002941ca0
[]
no_license
aespois/scrapyfundamentals
d3162cc19d1f9a45c7d6706458308b6349eb7b7a
2f30aaec29a3a4dc389b8ca5e9c5a04467cf2e36
refs/heads/master
2021-06-09T04:59:47.262858
2016-12-05T16:49:47
2016-12-05T16:49:47
202,208,492
1
0
null
null
null
null
UTF-8
Python
false
false
759
py
import json from scrapy import Request, Spider from infinitescrolling.items import QuoteItem class ScrollScraper(Spider): name = "scrollingscraper" quote_url = "http://quotes.toscrape.com/api/quotes?page=" start_urls = [quote_url + "1"] def parse(self, response): quote_item = QuoteItem() print response.body data = json.loads(response.body) for item in data.get('quotes', []): quote_item["author"] = item.get('author', {}).get('name') quote_item['quote'] = item.get('text') quote_item['tags'] = item.get('tags') yield quote_item if data['has_next']: next_page = data['page'] + 1 yield Request(self.quote_url + str(next_page))
[ "attila@scrapingauthority.com" ]
attila@scrapingauthority.com
cb70c83ee58695be816e6ca2a7018f4ceafc932b
ee195f726d717a8866966914fbe1199b6a5c83e7
/ptree/management/commands/create_experiments.py
f141f34e469ef564f3ff4c9a65d81b4828af7652
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
rnehmer/django-ptree
57cc670672b981b36b2d3a2dfa6683c0b3c84059
afb513138be24432c0283fb6b331349db1de77b8
refs/heads/master
2021-01-22T16:56:49.825345
2013-12-02T07:48:25
2013-12-02T07:48:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,501
py
import ptree.common from django.utils.importlib import import_module from django.core.management.base import BaseCommand, CommandError from django.conf import settings from ptree.sequence_of_experiments.models import SequenceOfExperiments class Command(BaseCommand): help = "pTree: Create a sequence of experiments." args = 'num_participants app_name [app_name] ...' def handle(self, *args, **options): print 'Creating sequence of experiments...' if len(args) < 2: raise CommandError("Wrong number of arguments (expecting '{}')".format(self.args)) num_participants = int(args[0]) app_names = args[1:] experiments = [] for app_name in app_names: if app_name not in settings.INSTALLED_PTREE_APPS: print 'Before running this command you need to add "{}" to INSTALLED_PTREE_APPS.'.format(app_name) return models_module = import_module('{}.models'.format(app_name)) experiment = models_module.create_experiment_and_treatments() for i in range(num_participants): participant = models_module.Participant(experiment = experiment) participant.save() print 'Created objects for {}'.format(app_name) experiments.append(experiment) #TODO: allow passing in a --name parameter seq = ptree.sequence_of_experiments.models.SequenceOfExperiments() seq.add_experiments(experiments)
[ "c.wickens@gmail.com" ]
c.wickens@gmail.com
44e7dbeaea4968e3a57b662359309cb6fff1c5ba
38b19d85d492b25f550f381f13df0217bce5a154
/pset7/mario/more/mario.py
59fd9eaf4e18082b97f2bc11ff774d075166f872
[]
no_license
OolongTea0/CS50
8b1948b6a599c6399beac09546dda12121f15647
d11ffefe3356f48107c579ef967506efd8723977
refs/heads/master
2020-08-10T06:12:21.249846
2019-10-10T21:07:25
2019-10-10T21:07:25
214,279,265
0
0
null
null
null
null
UTF-8
Python
false
false
425
py
from cs50 import get_int x = 0 while x < 1 or x > 8: x = get_int("Height: ") for i in range(x): #Makes beginning spaces for j in range(x-(i+1)): print(" ", end="") #Creates first pyramid for j in range(i+1): print("#", end="") #Makes the space in the middle print(" ", end="") #Creates the second pyramid for j in range(i+1): print("#", end="") print("")
[ "you@example.com" ]
you@example.com
05b4df401f64144d9147a616b5ff5ac94d0b0eac
3f91729694722e686950dcc1b9b8bfeb0de9e6c9
/13.py
3f4c91cfabfe99d029a68e01227fe6177476f208
[]
no_license
Howardman2/Hello-World
21e1be32de397ec2f1f24621435ebbc5e63f77ba
827831fe887ad402045ba6944791b6475bec4e12
refs/heads/main
2023-08-14T06:19:16.256266
2021-09-16T04:19:36
2021-09-16T04:19:36
407,016,411
0
0
null
null
null
null
UTF-8
Python
false
false
485
py
print('Welcome to TRUE or FALSE') print ('Please answer with yes or no') Truth = input('Mr Gallo is the best: ') if Truth !='yes': print('wrong') if Truth =='yes': print('Correct!') Falth = input('Coding is dumb: ') if Falth =='yes': print('WRONG') if Falth !='yes': print('Correct!') Truce = input('Technology is the future: ') if Truce !='yes': print('WRONGGGG') if Truce =='yes': print('CORRRECTTT') print('Thanks for playing!!!!!!')
[ "noreply@github.com" ]
Howardman2.noreply@github.com
d952d17243c044a9fb65819c255151b9165338ea
3afda5855f23a2931b386692340829161625a88b
/assignments/week14/Day05/Q4.py
04f3e8f01a172c3189f78d1d7dd96c1484d69dfc
[]
no_license
mastan-vali-au28/My-Code
8ed8617806c1e5e8944d56e81fd6481e2875935a
0ee6f43d1289c9fbf0ce4e4c29b44de38a036111
refs/heads/main
2023-07-07T18:52:10.013933
2021-08-13T13:18:48
2021-08-13T13:18:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
827
py
""" Q-4) Remove Duplicates from Sorted List (3.75 marks) https://leetcode.com/problems/remove-duplicates-from-sorted-list/ (Easy) Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: Input: head = [1,1,2] Output: [1,2] """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ current = head while current!=None and current.next!=None: if current.val==current.next.val: current.next = current.next.next else: current = current.next return head
[ "roopamjoshi63@gmail.com" ]
roopamjoshi63@gmail.com
b562d629e6105bf261dd7b3377d268efe1f0cb04
721ba9724a60997b4b4761b3a3c8931ae3a949a9
/ipfs_video_index/database.py
60f4b31e5a614ac44b1992affcc519e45394799f
[]
no_license
bneijt/ipfs-video-index
f058416e45ff2f8e9877e81fd88200281bf0bafb
555c5d25fe95456dd4e5aa9ca0b04aa8736633e2
refs/heads/main
2023-07-26T02:24:40.108876
2021-08-21T20:22:54
2021-08-21T20:22:54
395,742,171
0
0
null
null
null
null
UTF-8
Python
false
false
569
py
import sqlite3 from dqp.queue import Project def open(project: Project) -> sqlite3.Connection: database_folder = project.state_folder("db") return sqlite3.connect(database_folder.child("index.db")) def create_schema(db) -> None: # db.execute( # "create table if not exists digest_sha1(digest text, cid text, primary key (digest, cid))" # ) db.execute("create table if not exists view_count(cid text primary key, count int)") db.execute( "create table if not exists names(cid text, name text, primary key (cid, name))" )
[ "bram@neijt.nl" ]
bram@neijt.nl
7a2ee23165915ec526ae1ff7686151ec37f514ba
d2f93e46dbb76c77387b71ca3f74c811bbbda40d
/python/435.py
7408b89bd1850603dafbd4eb05749b72ae0dd58a
[]
no_license
jsanhuo/LeetCode
10f587b92579c5690f016d38ad283b2ec5c9bf80
5d1ffe6234ac5c4ec34333c3bbd23a02184e18f2
refs/heads/main
2022-07-13T00:03:14.703108
2022-07-05T04:48:23
2022-07-05T04:48:23
150,763,782
0
1
null
null
null
null
UTF-8
Python
false
false
402
py
#time:6120ms;memory:17.9MB class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 intervals.sort() n = len(intervals) f = [1] for i in range(1, n): f.append(max((f[j] for j in range(i) if intervals[j][1] <= intervals[i][0]), default=0) + 1) return n - max(f)
[ "1483104508@qq.com" ]
1483104508@qq.com
39552add32829ee18f94dfec22ba9a0c53d45774
78675b8be1223892f94b9138bb28f2de3d14cc73
/defcon/blacksheep/core/dialog/findingcategory.py
07a9e2a1a8bdee0ec05cedcbb158aade78936c08
[]
no_license
anitha2012/evandrix.github.com
fb1aebae5616eb95b8ed026004b2e87d87942c9e
062a274f1f5d2b578193642bb5da742e6a9ba555
refs/heads/master
2021-01-24T17:18:48.163247
2012-03-19T02:58:59
2012-03-19T02:58:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,612
py
#!/usr/bin/env python """ BlackSheep -- Penetration testing framework by Romain Gaucher <r@rgaucher.info> - http://rgaucher.info Copyright (c) 2008-2010 Romain Gaucher <r@rgaucher.info> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from PyQt4.QtCore import * from PyQt4.QtGui import * class NewFindingCategoryDialog(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.category_name = QLineEdit() self.cwe_list = QLineEdit() self.cwe_list.setValidator(QRegExpValidator(QRegExp('[\d\s,]+'), self)) self.capec_list = QLineEdit() self.capec_list.setValidator(QRegExpValidator(QRegExp('[\d\s,]+'), self)) self.description = QTextEdit() self.description.setAcceptRichText(False) self.description.setAutoFormatting(QTextEdit.AutoNone) self.reference = QTextEdit() self.reference.setAcceptRichText(False) self.reference.setAutoFormatting(QTextEdit.AutoNone) self.acceptButton = QPushButton("OK") self.cancelButton = QPushButton("Cancel") QObject.connect(self.acceptButton, SIGNAL("pressed()"), self.accept_Slot) QObject.connect(self.cancelButton, SIGNAL("pressed()"), self.cancel_Slot) glayout = QGridLayout() glayout.addWidget(QLabel("Category name:"), 0, 0) glayout.addWidget(self.category_name, 0, 1) glayout.addWidget(QLabel("Description:"), 1, 0) glayout.addWidget(self.description, 1, 1) glayout.addWidget(QLabel("CWE ID list:"), 2, 0) glayout.addWidget(self.cwe_list, 2, 1) glayout.addWidget(QLabel("CAPEC ID list:"), 3, 0) glayout.addWidget(self.capec_list, 3, 1) glayout.addWidget(QLabel("Reference:"), 4, 0) glayout.addWidget(self.reference, 4, 1) hlayout = QHBoxLayout() hlayout.addWidget(self.acceptButton) hlayout.addWidget(self.cancelButton) layout = QVBoxLayout() layout.addWidget(QLabel("Add a new category and generic information that will beintegratedin the different findings.\nWe use CWE and CAPEC for generic mapping.")) layout.addLayout(glayout) layout.addLayout(hlayout) self.setModal(False) self.setLayout(layout) def accept_Slot(self): self.accept() def cancel_Slot(self): self.reject()
[ "evandrix@gmail.com" ]
evandrix@gmail.com
20cdb823c6baaf795d153aa1eb3036e981329dc3
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_209/441.py
2cd2a8af66ca17a00cd200e90fd5cd85cfeeec63
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,088
py
from math import pi from typing import List, NamedTuple, Dict, IO, Tuple from pathlib import Path class Pancake(object): radius: float height: float def __init__(self, radius, height): self.radius = radius self.height = height @property def lateral_surface(self) -> float: return self.radius * 2 * pi * self.height @property def surface(self) -> float: return (self.radius ** 2) * pi class Case(NamedTuple): howmany: int pancakes: List[Pancake] def read_case(f: IO) -> Case: pan = [] total, howmany = (int(x) for x in f.readline().split()) for _ in range(total): radius, height = (float(x) for x in f.readline().split()) pan.append(Pancake(radius, height)) return Case(howmany, pan) def read_input(f: IO) -> List[Case]: T = int(f.readline()) return [read_case(f) for _ in range(T)] def solve_rec(candidates: List[Pancake], left: int, idx: int, cache) -> float: if (idx, left) in cache: return cache[(idx, left)] if left > 0 and idx >= len(candidates): return -1 if left == 0: return 0 s = candidates[idx].surface if left == 1 else 0 m = max( candidates[idx].lateral_surface + solve_rec(candidates, left-1, idx+1, cache) + s, solve_rec(candidates, left, idx+1, cache), ) cache[(idx, left)] = m return m def solve(case: Case) -> float: case.pancakes.sort(key=lambda p: p.radius) cache = {} return solve_rec(case.pancakes, case.howmany, 0, cache) def main(): import sys sys.setrecursionlimit(10000) for in_path in Path('.').glob('*.in'): with in_path.open('r') as f: cases = read_input(f) out_path = in_path.parent / in_path.name.replace('.in', '.out') print(f"solving {in_path} -> {out_path}") with out_path.open('w') as out: for idx, case in enumerate(cases, start=1): solution = solve(case) print(f"Case #{idx}: {solution}", file=out) if __name__ == '__main__': main()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
4e94afdcc0766552cf05d34691bf5b5eb6b461b8
4e4c27eb76970148210ea1ad2c7b896ff48ed88e
/PPlay/tiledtmxloader/helperspygame.py
ee93b4256cb08350ba2a603b9054276a5040bac5
[]
no_license
matheus-erthal/a-fuga-do-dce
27d4b4c91c85a87350e1ee5f092669c283ce5082
6f196e99cbed586877dd93c9364ae2e4d2e60476
refs/heads/master
2020-12-21T09:52:16.909268
2020-01-26T23:41:33
2020-01-26T23:41:33
236,392,424
2
0
null
null
null
null
UTF-8
Python
false
false
41,619
py
# -*- coding: utf-8 -*- """ TileMap loader for python for Tiled, a generic tile map editor from http://mapeditor.org/ . It loads the \*.tmx files produced by Tiled. This is the code that helps using the tmx files using pygame. In this module there is a pygame specific loader and renderer. """ # Versioning scheme based on: # http://en.wikipedia.org/wiki/Versioning#Designating_development_stage # # +-- api change, probably incompatible with older versions # | +-- enhancements but no api change # | | # major.minor[.build[.revision]] # | # +-|* 0 for alpha (status) # |* 1 for beta (status) # |* 2 for release candidate # |* 3 for (public) release # # For instance: # * 1.2.0.1 instead of 1.2-a # * 1.2.1.2 instead of 1.2-b2 (beta with some bug fixes) # * 1.2.2.3 instead of 1.2-rc (release candidate) # * 1.2.3.0 instead of 1.2-r (commercial distribution) # * 1.2.3.5 instead of 1.2-r5 (commercial distribution with many bug fixes) __revision__ = "$Rev: 115 $" __version__ = "3.0.0." + __revision__[6:-2] __author__ = 'DR0ID @ 2009-2011' # ----------------------------------------------------------------------------- from math import ceil import pygame from . import tmxreader # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- class ResourceLoaderPygame(tmxreader.AbstractResourceLoader): """ Resource loader for pygame. Loads the images as pygame.Surfaces and saves them in the variable indexed_tiles. Example:: res_loader = ResourceLoaderPygame() # tile_map loaded the the TileMapParser.parse() method res_loader.load(tile_map) """ def __init__(self): tmxreader.AbstractResourceLoader.__init__(self) def load(self, tile_map): tmxreader.AbstractResourceLoader.load(self, tile_map) # delete the original images from memory, they are all saved as tiles self._img_cache.clear() # ISSUE 17: flipped tiles for layer in self.world_map.layers: if not layer.is_object_group: for gid in layer.decoded_content: if gid not in self.indexed_tiles: if gid & self.FLIP_X or gid & self.FLIP_Y: image_gid = gid & ~(self.FLIP_X | self.FLIP_Y) offx, offy, img = self.indexed_tiles[image_gid] img = img.copy() img = pygame.transform.flip(img, \ bool(gid & self.FLIP_X), \ bool(gid & self.FLIP_Y)) self.indexed_tiles[gid] = (offx, offy, img) def _load_image_parts(self, filename, margin, spacing, \ tile_width, tile_height, colorkey=None): #-> [images] source_img = self._load_image(filename, colorkey) width, height = source_img.get_size() # ISSUE 16 # if the image size does not match a multiple of tile_width or # tile_height it will mess up the number of tiles resulting in # wrong GID's for the tiles width = (width // tile_width) * tile_width height = (height // tile_height) * tile_height images = [] for ypos in range(margin, height, tile_height + spacing): for xpos in range(margin, width, tile_width + spacing): img_part = self._load_image_part(filename, xpos, ypos, \ tile_width, tile_height, colorkey) images.append(img_part) return images def _load_image_part(self, filename, xpos, ypos, width, height, \ colorkey=None): """ Loads a image from a sprite sheet. """ source_img = self._load_image(filename, colorkey) ## ISSUE 4: ## The following usage seems to be broken in pygame (1.9.1.): ## img_part = pygame.Surface((tile_width, tile_height), 0, source_img) img_part = pygame.Surface((width, height), \ source_img.get_flags(), \ source_img.get_bitsize()) source_rect = pygame.Rect(xpos, ypos, width, height) ## ISSUE 8: ## Set the colorkey BEFORE we blit the source_img if colorkey: img_part.set_colorkey(colorkey, pygame.RLEACCEL) img_part.fill(colorkey) img_part.blit(source_img, (0, 0), source_rect) return img_part def _load_image_file_like(self, file_like_obj, colorkey=None): # -> image # pygame.image.load can load from a path and from a file-like object # that is why here it is redirected to the other method return self._load_image(file_like_obj, colorkey) def _load_image(self, filename, colorkey=None): img = self._img_cache.get(filename, None) if img is None: img = pygame.image.load(filename) self._img_cache[filename] = img if colorkey: img.set_colorkey(colorkey, pygame.RLEACCEL) return img # def get_sprites(self): # pass # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- class SpriteLayerNotCompatibleError(Exception): pass class SpriteLayer(object): """ The SpriteLayer class. This class is used by the RendererPygame. """ class Sprite(object): """ The Sprite class used by the SpriteLayer class and the RendererPygame. """ def __init__(self, image, rect, source_rect=None, flags=0, key=None): """ Constructor. :Parameters: image : pygame.Surface the image of this sprite rect : pygame.Rect the rect used when drawing source_rect : pygame.Rect source area rect, defaults to None flags : int flags for the blit method, defaults to 0 key : any used internally for collapsing sprites """ self.image = image # TODO: dont use a rect for position self.rect = rect # blit rect self.source_rect = source_rect self.flags = flags self.is_flat = False self.z = 0 self.key = key def get_draw_cond(self): """ Defines if the sprite lays on the floor or if it is up-right. :returns: The bottom y coordinate so the sprites can be sorted in right draw order. """ if self.is_flat: return self.rect.top + self.z else: return self.rect.bottom def __init__(self, tile_layer_idx, resource_loader): """ :Parameters: tile_layer_idx : int Index of the tile layer to build upon resource_loader : ResourceLoaderPygame Instance of the ResourceLoaderPygame class which has loaded the resouces """ self._resource_loader = resource_loader _world_map = self._resource_loader.world_map self.layer_idx = tile_layer_idx _layer = _world_map.layers[tile_layer_idx] self.tilewidth = _world_map.tilewidth self.tileheight = _world_map.tileheight self.num_tiles_x = _world_map.width self.num_tiles_y = _world_map.height self.position_x = _layer.x self.position_y = _layer.y self._level = 1 # TODO: change scale attributes to properties? self.scale_x = 1.0 self.scale_y = 1.0 # TODO: either change paralax_* attributes to properties # or make them private self.paralax_factor_x = 1.0 self.paralax_factor_y = 1.0 self.sprites = [] self.is_object_group = _layer.is_object_group self.visible = _layer.visible self.bottom_margin = 0 self._bottom_margin = 0 # init data to default # self.content2D = [] # generate the needed lists # for xpos in xrange(self.num_tiles_x): # self.content2D.append([None] * self.num_tiles_y) self.content2D = [None] * self.num_tiles_y for ypos in range(self.num_tiles_y): self.content2D[ypos] = [None] * self.num_tiles_x # fill them _img_cache = {} _img_cache["hits"] = 0 for ypos_new in range(0, self.num_tiles_y): for xpos_new in range(0, self.num_tiles_x): coords = self._get_list_of_neighbour_coord(xpos_new, ypos_new, \ 1, self.num_tiles_x, self.num_tiles_y) if coords: key, sprites = SpriteLayer._get_sprites_fromt_tiled_layer(\ coords, _layer, self._resource_loader.indexed_tiles) sprite = None if sprites: sprite = SpriteLayer._union_sprites(sprites, key, \ _img_cache) if sprite.rect.height > self._bottom_margin: self._bottom_margin = sprite.rect.height self.content2D[ypos_new][xpos_new] = sprite self.bottom_margin = self._bottom_margin if __debug__: print('%s: Sprite Cache hits: %d' % \ (self.__class__.__name__, _img_cache["hits"])) del _img_cache def get_collapse_level(self): """ The level of collapsing. :returns: The collapse level. """ return self._level # TODO: test scale @staticmethod def scale(layer_orig, scale_w, scale_h): # -> sprite_layer """ Scales a layer and returns a new, scaled SpriteLayer. :Note: This method is slow and inefficient :Parameters: scale_w : float Width scale factor in range (0, ...] scale_h : float Height scale factor in range (0, ...] """ if layer_orig.is_object_group: return layer layer = SpriteLayer(layer_orig.layer_idx, layer_orig._resource_loader) layer.tilewidth = layer_orig.tilewidth * scale_w layer.tileheight = layer_orig.tileheight * scale_h layer.position_x = layer_orig.position_x layer.position_y = layer_orig.position_y layer._level = layer_orig._level layer.paralax_factor_x = layer_orig.paralax_factor_x layer.paralax_factor_y = layer_orig.paralax_factor_y layer.sprites = layer_orig.sprites layer.is_object_group = layer_orig.is_object_group layer.visible = layer_orig.visible layer.scale_x = scale_w layer.scale_y = scale_h layer.content2D = [0] * len(layer_orig.content2D) for yidx, row in enumerate(layer_orig.content2D): layer.content2D[yidx] = [0] * len(row) for xidx, sprite in enumerate(row): if sprite: w, h = sprite.image.get_size() new_w = w * scale_w new_h = h * scale_h rect = sprite.rect image = sprite.image # prevent fractional numbers and scaling glitches if w != ceil(new_w) or h != ceil(new_h): new_w = ceil(new_w) new_h = ceil(new_h) image = pygame.transform.smoothscale(sprite.image, \ (new_w, new_h)) x, y = sprite.rect.topleft rect = pygame.Rect(x * scale_w, y * scale_h, \ new_w, new_h) layer.content2D[yidx][xidx] = \ SpriteLayer.Sprite(image, rect) else: layer.content2D[yidx][xidx] = None return layer # TODO: implement merge @staticmethod def merge(layers): # -> sprite_layer """ Merges multiple Sprite layers into one. Only SpriteLayers are supported. All layers need to be equal in tile size, number of tiles and layer position. Otherwise a SpriteLayerNotCompatibleError is raised. :Parameters: layers : list The SpriteLayer to be merged :returns: new SpriteLayer with merged tiles """ tile_width = None tile_height = None num_tiles_x = None num_tiles_y = None position_x = None position_y = None new_layer = None for layer in layers: if layer.is_object_group: # skip object group layers continue assert isinstance(layer, SpriteLayer), "layer is not an instance of SpriteLayer" # just use the values from first layer tile_width = tile_width if tile_width else layer.tile_width tile_height = tile_height if tile_height else layer.tile_height num_tiles_x = num_tiles_x if num_tiles_x else layer.num_tiles_x num_tiles_y = num_tiles_y if num_tiles_y else layer.num_tiles_y position_x = position_x if position_x else layer.position_x position_y = position_y if position_y else layer.position_y # check they are equal for all layers if layer.tile_width != tile_width: raise SpriteLayerNotCompatibleError("layers do not have same tile_width") if layer.tile_height != tile_height: raise SpriteLayerNotCompatibleError("layers do not have same tile_height") if layer.num_tiles_x != num_tiles_x: raise SpriteLayerNotCompatibleError("layers do not have same number of tiles in x direction") if layer.num_tiles_y != num_tiles_y: raise SpriteLayerNotCompatibleError("layers do not have same number of tiles in y direction") if layer.position_x != position_x: raise SpriteLayerNotCompatibleError("layers are not at same position in x") if layer.position_y != position_y: raise SpriteLayerNotCompatibleError("layers are not at same position in y") if new_layer is None: new_layer = SpriteLayer(-2, layer._resource_loader) for ypos_new in range(0, num_tiles_y): for xpos_new in range(0, num_tiles_x): sprite = layer.content2D[ypos_new][xpos_new] if sprite: new_sprite = new_layer.content2D[ypos_new][xpos_new] if new_sprite: assert sprite.rect.topleft == new_sprite.rect.topleft assert sprite.rect.size == new_sprite.rect.size new_sprite.image.blit(sprite.image, (0, 0), \ sprite.source_rect, sprite.flags) else: new_sprite = sprite new_layer.content2D[ypos_new][xpos_new] = new_sprite return new_layer @staticmethod def collapse(layer): """ Makes 1 tile out of 4. The idea behind is that fewer tiles are faster to render, but that is not always true. Grouping them together into one bigger sprite is one way to get fewer sprites. :not: This only works for static layers without any dynamic sprites. :note: use with caution :Parameters: laser : SpriteLayer The layer to collapse :returns: new SpriteLayer with fewer sprites but double the size. """ # + 0' 1' 2' # 0 1 2 3 4 # 0' 0 +----+----+----+----+ # | | | | | # 1 +----+----+----+----+ # | | | | | # 1' 2 +----+----+----+----+ # | | | | | # 3 +----+----+----+----+ # | | | | | # 2' 4 +----+----+----+----+ if layer.is_object_group: return layer level = 2 new_tilewidth = layer.tilewidth * level new_tileheight = layer.tileheight * level new_num_tiles_x = int(layer.num_tiles_x / level) new_num_tiles_y = int(layer.num_tiles_y / level) if new_num_tiles_x * level < layer.num_tiles_x: new_num_tiles_x += 1 if new_num_tiles_y * level < layer.num_tiles_y: new_num_tiles_y += 1 # print "old size", layer.num_tiles_x, layer.num_tiles_y # print "new size", new_num_tiles_x, new_num_tiles_y _content2D = [None] * new_num_tiles_y # generate the needed lists for ypos in range(new_num_tiles_y): _content2D[ypos] = [None] * new_num_tiles_x # fill them _img_cache = {} _img_cache["hits"] = 0 for ypos_new in range(0, new_num_tiles_y): for xpos_new in range(0, new_num_tiles_x): coords = SpriteLayer._get_list_of_neighbour_coord(\ xpos_new, ypos_new, level, \ layer.num_tiles_x, layer.num_tiles_y) if coords: sprite = SpriteLayer._get_sprite_from(coords, layer, \ _img_cache) _content2D[ypos_new][xpos_new] = sprite # print "len content2D:", len(self.content2D) # TODO: separate constructor from init code (here the layer is parsed # for nothing, content2D will be replaced) new_layer = SpriteLayer( layer.layer_idx, layer._resource_loader) new_layer.tilewidth = new_tilewidth new_layer.tileheight = new_tileheight new_layer.num_tiles_x = new_num_tiles_x new_layer.num_tiles_y = new_num_tiles_y new_layer.content2D = _content2D # HACK: new_layer._level = layer._level * 2 if __debug__ and level > 1: print('%s: Sprite Cache hits: %d' % ("collapse", _img_cache["hits"])) return new_layer @staticmethod def _get_list_of_neighbour_coord(xpos_new, ypos_new, level, \ num_tiles_x, num_tiles_y): """ Finds the neighbours of a tile and returns them :Parameters: xpos_new : int x position ypos_new : int y position level : int collapse level because this uses original tiles num_tiles_x : int number of tiles in x direction num_tiles_y : int number of tiles in y direction :Returns: list of coordinates of the neighbour tiles """ xpos = xpos_new * level ypos = ypos_new * level coords = [] for y in range(ypos, ypos + level): for x in range(xpos, xpos + level): if x <= num_tiles_x and y <= num_tiles_y: coords.append((x, y)) return coords @staticmethod def _union_sprites(sprites, key, _img_cache): """ Unions sprites into one big one. :Parameters: sprites : list list of sprites to union key : iterable key of the sprite, internal use only _img_cache : dict cache dict :Returns: new Sprite that unites all the given sprites. """ key = tuple(key) # dont copy to a new image if only one sprite is in sprites # (reduce memory usage) # NOTE: this messes up the cache hits (only on non-collapsed maps) if len(sprites) == 1: sprite = sprites[0] sprite.key = key return sprite # combine found sprites into one sprite rect = sprites[0].rect.unionall(sprites) # cache the images to save memory if key in _img_cache: image = _img_cache[key] _img_cache["hits"] = _img_cache["hits"] + 1 else: # make new image image = pygame.Surface(rect.size, pygame.SRCALPHA | pygame.RLEACCEL) image.fill((0, 0, 0, 0)) x, y = rect.topleft for spr in sprites: image.blit(spr.image, spr.rect.move(-x, -y)) _img_cache[key] = image return SpriteLayer.Sprite(image, rect, key=key) @staticmethod def _get_sprites_fromt_tiled_layer(coords, layer, indexed_tiles): """ Get the sprites at the given coordinates from a tiled layer. :Parameters: coords : list list of coordinates tuples layer : TiledLayer layer to extract the sprites from indexed_tiles : dict indexed tiles list loaded by the resource loader. :Returns: (keys, sprites) the new keys and sprites """ sprites = [] key = [] for xpos, ypos in coords: ## ISSUE 14: maps was displayed only sqared because wrong ## boundary checks if xpos >= len(layer.content2D) or \ ypos >= len(layer.content2D[xpos]): # print "CONTINUE", xpos, ypos key.append(-1) # border and corner cases! continue idx = layer.content2D[xpos][ypos] if idx: offx, offy, img = indexed_tiles[idx] world_x = xpos * layer.tilewidth + offx world_y = ypos * layer.tileheight + offy w, h = img.get_size() rect = pygame.Rect(world_x, world_y, w, h) sprite = SpriteLayer.Sprite(img, rect, key=idx) key.append(idx) sprites.append(sprite) else: key.append(-1) return key, sprites @staticmethod def _get_sprite_from(coords, layer, _img_cache): """ Get one sprite for the given coordinates on the given layer. :Parameters: coords : list tuples of coordinates (x, y) layer : SpriteLayer the layer to get the united sprite from _img_cache : dict dict for caching, internal use only :returns: a single sprite, uniting all given sprites on the fiven coordinates. """ sprites = [] key = [] for xpos, ypos in coords: if ypos >= len(layer.content2D) or \ xpos >= len(layer.content2D[ypos]): # print "CONTINUE", xpos, ypos key.append(-1) # border and corner cases! continue idx = layer.content2D[ypos][xpos] if idx: sprite = idx key.append(sprite.key) sprites.append(sprite) else: key.append(-1) if sprites: sprite = SpriteLayer._union_sprites(sprites, key, _img_cache) if __debug__: x, y = sprite.rect.topleft pygame.draw.rect(sprite.image, (255, 0, 0), \ sprite.rect.move(-x, -y), \ layer.get_collapse_level()) del sprites return sprite return None def add_sprite(self, sprite): """ Add dynamic sprite to this layer. :Parameters: sprite : SpriteLayer.Sprite sprite to add """ self.sprites.append(sprite) if sprite.rect.height > self.bottom_margin: self.bottom_margin = sprite.rect.height def add_sprites(self, sprites): """ Add multiple dynamic sprites to this layer. :Parameters: sprites : list list of SpriteLayer.Sprite to add """ for sprite in sprites: self.add_sprite(sprite) def remove_sprite(self, sprite): """ Removes a dynamic sprite from this layer. :Parameters: sprite : SpriteLayer.Sprite sprite to remove """ if sprite in self.sprites: self.sprites.remove(sprite) self.bottom_margin = self._bottom_margin for spr in self.sprites: if spr.rect.height > self.bottom_margin: self.bottom_margin = spr.rect.height def remove_sprites(self, sprites): """ Remove multiple sprites at once. :Parameters: sprites : list list of SpriteLayer.Sprite to remove """ for sprite in sprites: self.remove_sprite(sprite) def contains_sprite(self, sprite): """ Check if the given sprites is already in this layer. :Parameters: sprite : SpriteLayer.Sprite sprite to check :Returns: bool, true if sprite is in this layer """ if sprite in self.sprites: return True return False def has_sprites(self): """ Checks if this layer has dynamic sprites at all. :Returns: bool, true if it contains at least 1 dynamic sprite. """ return (len(self.sprites) > 0) def set_layer_paralax_factor(self, factor_x=1.0, factor_y=None): """ Set the paralax factor. This is for paralax scrolling this layer. Values x < 0.0 will make the layer scroll in opposite direction Value x == 0.0 makes the layer fix to the screen (wont scroll) Values 0.0 < x < 1.0 will make scroll the layer slower. Value x == 1.0 is default and make scroll the layer normal. Values x > 1.0 make scroll the layer faster than normal :Parameters: factor_x : float Paralax factor in x direction. Defaults to 1.0 factor_y : float Paralax factor in y direction. If this is None then it will have the same value as the factor_x argument. """ self.paralax_factor_x = factor_x if factor_y: self.paralax_factor_y = factor_y else: self.paralax_factor_y = factor_x def get_layer_paralax_factor_x(self): """ Retrieve the current x paralax factor. :Returns: returns the current x paralax factor. """ return self.paralax_factor_x def get_layer_paralax_factor_y(self): """ Retrieve the current y paralax factor. :Returns: returns the current y paralax factor. """ return self.paralax_factor_y # ----------------------------------------------------------------------------- def get_layers_from_map(resource_loader): """ Creates SpriteLayers out of the map. :Parameters: resource_loader : ResourceLoaderPygame a resource loader instance :Returns: list of SpriteLayers """ layers = [] for idx, layer in enumerate(resource_loader.world_map.layers): layers.append(get_layer_at_index(idx, resource_loader)) return layers def get_layer_at_index(layer_idx, resource_loader): """ Creates one SpriteLayer from index out of the map. :Parameters: layer_idx : int Index of the layer to create. resource_loader : ResourceLoaderPygame a resource loader instance :Returns: a SpriteLayer instance """ layer = resource_loader.world_map.layers[layer_idx] if layer.is_object_group: return layer return SpriteLayer(layer_idx, resource_loader) # ----------------------------------------------------------------------------- class RendererPygame(object): """ A renderer for pygame. Should be fast enough for most purposes. Example:: # init sprite_layers = get_layers_from_map(resources) renderer = RendererPygame() # in main loop while running: # move camera renderer.set_camera_position(x, y) # draw layers for sprite_layer in sprite_layers: renderer.render_layer(screen, sprite_layer, clip_sprites) """ def __init__(self): """ Constructor. """ self._cam_rect = pygame.Rect(0, 0, 10, 10) self._margin = (0, 0, 0, 0) # left, right, top, bottom def set_camera_position(self, world_pos_x, world_pos_y, alignment='center'): """ Set the camera position in the world. :Parameters: world_pos_x : int position in x in world coordinates world_pos_y : int position in y in world coordinates alignment : string defines to which part of the cam rect the position belongs, can be any pygame.Rect attribute: 'center', 'topleft', 'topright', ... """ setattr(self._cam_rect, alignment, (world_pos_x, world_pos_y)) self.set_camera_margin(*self._margin) def set_camera_position_and_size(self, world_pos_x, world_pos_y, \ width, height, alignment='center'): """ Set the camera position and size in the world. :Parameters: world_pos_x : int Position in x in world coordinates. world_pos_y : int Position in y in world coordinates. witdh : int With of the camera rect (the rendered area). height : int The height of the camera rect (the rendered area). alignment : string Defines to which part of the cam rect the position belongs, can be any pygame.Rect attribute: 'center', 'topleft', 'topright', ... """ self._cam_rect.width = width self._cam_rect.height = height setattr(self._cam_rect, alignment, (world_pos_x, world_pos_y)) self.set_camera_margin(*self._margin) def set_camera_rect(self, cam_rect_world_coord): """ Set the camera position and size using a rect in world coordinates. :Parameters: cam_rect_world_coord : pygame.Rect A rect describing the cameras position and size in the world. """ self._cam_rect = cam_rect_world_coord self.set_camera_margin(*self._margin) def set_camera_margin(self, margin_left, margin_right, margin_top, margin_bottom): """ Set the margin around the camera (in pixels). :Parameters: margin_left : int number of pixels of the left side marging margin_right : int number of pixels of the right side marging margin_top : int number of pixels of the top side marging margin_bottom : int number of pixels of the left bottom marging """ self._margin = (margin_left, margin_right, margin_top, margin_bottom) self._render_cam_rect = pygame.Rect(self._cam_rect) # adjust left margin self._render_cam_rect.left = self._render_cam_rect.left - margin_left # adjust right margin self._render_cam_rect.width = self._render_cam_rect.width + \ margin_left + margin_right # adjust top margin self._render_cam_rect.top = self._render_cam_rect.top - margin_top # adjust bottom margin self._render_cam_rect.height = self._render_cam_rect.height + \ margin_top + margin_bottom self._render_cam_rect.left = self._cam_rect.left - margin_left self._render_cam_rect.top = self._cam_rect.top - margin_top def render_layer(self, surf, layer, clip_sprites=True, \ sort_key=lambda spr: spr.get_draw_cond()): """ Renders a layer onto the given surface. :Parameters: surf : Surface Surface to render onto. layer : SpriteLayer The layer to render. Invisible layers will be skipped. clip_sprites : boolean Optional, defaults to True. Clip the sprites of this layer to only draw the ones intersecting the visible part of the world. sort_key : function Optional: The sort function for the parameter 'key' of the sort method of the list. """ if layer.visible: if layer.is_object_group: return if layer.bottom_margin > self._margin[3]: left, right, top, bottom = self._margin self.set_camera_margin(left, right, top, layer.bottom_margin) # optimizations surf_blit = surf.blit layer_content2D = layer.content2D tile_h = layer.tileheight # self.paralax_factor_y = 1.0 # self.paralax_center_x = 0.0 cam_rect = self._render_cam_rect # print 'cam rect:', self._cam_rect # print 'render r:', self._render_cam_rect cam_world_pos_x = cam_rect.left * layer.paralax_factor_x + \ layer.position_x cam_world_pos_y = cam_rect.top * layer.paralax_factor_y + \ layer.position_y # camera bounds, restricting number of tiles to draw left = int(round(float(cam_world_pos_x) // layer.tilewidth)) right = int(round(float(cam_world_pos_x + cam_rect.width) // \ layer.tilewidth)) + 1 top = int(round(float(cam_world_pos_y) // tile_h)) bottom = int(round(float(cam_world_pos_y + cam_rect.height) // \ tile_h)) + 1 left = left if left > 0 else 0 right = right if right < layer.num_tiles_x else layer.num_tiles_x top = top if top > 0 else 0 bottom = bottom if bottom < layer.num_tiles_y else layer.num_tiles_y # sprites spr_idx = 0 len_sprites = 0 all_sprites = layer.sprites if all_sprites: # TODO: make filter visible sprites optional (maybe sorting too) # use a marging around it if clip_sprites: sprites = [all_sprites[idx] \ for idx in cam_rect.collidelistall(all_sprites)] else: sprites = all_sprites # could happend that all sprites are not visible by the camera if sprites: if sort_key: sprites.sort(key=sort_key) sprite = sprites[0] len_sprites = len(sprites) # render for ypos in range(top, bottom): # draw sprites in this layer # (skip the ones outside visible area/map) y = ypos + 1 while spr_idx < len_sprites and sprite.get_draw_cond() <= \ y * tile_h: surf_blit(sprite.image, \ sprite.rect.move(-cam_world_pos_x, \ -cam_world_pos_y - sprite.z),\ sprite.source_rect, \ sprite.flags) spr_idx += 1 if spr_idx < len_sprites: sprite = sprites[spr_idx] # next line of the map for xpos in range(left, right): tile_sprite = layer_content2D[ypos][xpos] # print '?', xpos, ypos, tile_sprite if tile_sprite: surf_blit(tile_sprite.image, \ tile_sprite.rect.move( -cam_world_pos_x, \ -cam_world_pos_y), \ tile_sprite.source_rect, \ tile_sprite.flags) def pick_layer(self, layer, screen_x, screen_y): """ Returns the sprite at the given screen position or None regardless of the layers visibility. :Note: This does not work wir object group layers. :Parameters: layer : SpriteLayer the layer to pick from screen_x : int The screen position in x direction. screen_y : int The screen position in y direction. :Returns: None if there is no sprite or the sprite (SpriteLayer.Sprite instance). """ if layer.is_object_group: pass else: world_pos_x, world_pos_y = \ self.get_world_pos(layer, screen_x, screen_y) tile_x = int(world_pos_x / layer.tilewidth) tile_y = int(world_pos_y / layer.tileheight) if 0 <= tile_x < layer.num_tiles_x and \ 0 <= tile_y < layer.num_tiles_y: sprite = layer.content2D[tile_y][tile_x] if sprite: return sprite return None def pick_layers_sprites(self, layer, screen_x, screen_y): """ Returns the sprites at the given screen positions or an empty list. The sprites are the same order as in the layers.sprites list. :Note: This does not work wir object group layers. :Parameters: layer : SpriteLayer the layer to pick from screen_x : int The screen position in x direction. screen_y : int The screen position in y direction. :Returns: A list of sprites or an empty list. """ if layer.is_object_group: pass else: world_pos_x, world_pos_y = \ self.get_world_pos(layer, screen_x, screen_y) r = pygame.Rect(world_pos_x, world_pos_y, 1, 1) indices = r.collidelistall(layer.sprites) return [layer.sprites[idx] for idx in indices] return [] def get_world_pos(self, layer, screen_x, screen_y): """ Returns the world coordinates for the given screen location and layer. :Note: this is important so one can check which entity is there in the model (knowing which sprite is there does not help much) :Parameters: layer : SpriteLayer the layer to pick from screen_x : int The screen position in x direction. screen_y : int The screen position in y direction. :Returns: Tuple of world coordinates: (world_x, world_y) """ # TODO: also use layer.x and layer.y offset return (screen_x + self._render_cam_rect.x * layer.paralax_factor_x, \ screen_y + self._render_cam_rect.y * layer.paralax_factor_y) # -----------------------------------------------------------------------------
[ "matheusamancio@id.uff.br" ]
matheusamancio@id.uff.br
77f0dd58da5e0eddc9f8369bdb0307b5df704ce7
7c787d84548b41ffb89c389fbaf5c62a055ab3cc
/dvid_to_neuprint/generate_SynapseSet_to_SynapseSet.py
b0ffd5a9e23e3961c75f375e74f1a38853bc91f9
[ "BSD-3-Clause" ]
permissive
Rachmanimir/neuPrint
bfe59dddfc7343a7e8ea0053d781650a41a92348
be02fc15b8f0e5fb19087fa70a614e6d739ec98d
refs/heads/master
2023-03-30T07:06:44.299852
2020-12-17T13:48:32
2020-12-17T13:49:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,298
py
#!/bin/env # python generate_SynapseSet_to_SynapseSet.py Sorted_All_Neuprint_Synapse_Connections_6f2cb.csv > Neuprint_SynapseSet_to_SynapseSet_6f2cb.csv # ------------------------- imports ------------------------- import json import sys import os import io import time import numpy as np from tqdm import trange from neuclease.dvid import * from libdvid import DVIDNodeService, ConnectionMethod if __name__ == '__main__': synapseSet_csv = sys.argv[1] synapseSets = open(synapseSet_csv,'r') unique_set = {} for line in synapseSets: if line[0].isdigit(): data_str = line.rstrip('\n') data = data_str.split(",") if data[10] == "PreSynTo": pre_syn_set = data[9] + "_" + data[20] + "_pre" post_syn_set = data[20] + "_" + data[9] + "_post" #print(pre_syn_set) unique_set[pre_syn_set] = post_syn_set print(":START_ID,:END_ID") for synSet in unique_set: connectToset = unique_set[synSet] #bodies = synSet.split("_") #reverse_set = bodies[1] + "_" + bodies[0] #if synSet == reverse_set: #print("Error", synSet, reverse_set, "same") # continue #else: print(synSet + "," + connectToset)
[ "umayaml@umayaml-lm5.hhmi.org" ]
umayaml@umayaml-lm5.hhmi.org
650cba3189b9484bb2e97f5fd53feb6ac412a035
81a4f3d1590e9819daad1a3fd8c495bf0b4b83d4
/ex11.py
0c915a073161b164ffcbdf6d93992d3ede25b34c
[]
no_license
zhenghaoyang/PythonCode
3095bab963184871f220666f32f442599e7ef5e3
7eb54de019bfa1cbf07b0e027a63e27b3819bda8
refs/heads/master
2021-04-15T12:13:14.309026
2018-04-08T09:41:23
2018-04-08T09:41:23
126,296,886
0
0
null
null
null
null
UTF-8
Python
false
false
547
py
# --coding: utf-8 -- print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "Which book do you like most?", book = raw_input("input:") type(book) #单引号需要被转义,从而防止它被识别为字符串的结尾。 #How old are you? 11'11" #How tall are you? 11"11" #How much do you weigh? 11"11' #Which book do you like most? input:'11"11" print "So you're %r old ,%r tall and %r heavy,you like this %s book"%(age,height,weight,book)
[ "532425107@qq.com" ]
532425107@qq.com
348a5ec1394a57134114eaf45d1db281e11f2089
65cc0da41bbe5ab78530775aa95f7d3732c3193d
/protos/gen/python/protos/public/uac/Organization_pb2.py
6136ad83b3579ea77617ea8ce4d72932a77fac8c
[ "Apache-2.0" ]
permissive
NaiboWang/modeldb
0bc9bf0fc2c0605c982532af1251d81dc2e9bd53
43faa8266f7134404fe5cb21954a477ed5963300
refs/heads/master
2023-03-27T21:20:49.150239
2021-04-01T10:42:19
2021-04-01T10:42:19
345,637,902
0
0
Apache-2.0
2021-04-01T10:42:19
2021-03-08T11:48:41
null
UTF-8
Python
false
true
41,804
py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: uac/Organization.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 from ..common import CommonService_pb2 as common_dot_CommonService__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='uac/Organization.proto', package='ai.verta.uac', syntax='proto3', serialized_options=b'P\001Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uac', serialized_pb=b'\n\x16uac/Organization.proto\x12\x0c\x61i.verta.uac\x1a\x1cgoogle/api/annotations.proto\x1a\x1a\x63ommon/CommonService.proto\"\xa8\x06\n\x0cOrganization\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x12\n\nshort_name\x18\x07 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\x10\n\x08owner_id\x18\x04 \x01(\t\x12\x19\n\x11\x63reated_timestamp\x18\x05 \x01(\x03\x12\x19\n\x11updated_timestamp\x18\x06 \x01(\x03\x12X\n\x18global_collaborator_type\x18\x08 \x01(\x0e\x32\x36.ai.verta.common.CollaboratorTypeEnum.CollaboratorType\x12?\n\x11global_can_deploy\x18\t \x01(\x0e\x32$.ai.verta.common.TernaryEnum.Ternary\x12^\n\x1e\x64\x65\x66\x61ult_repo_collaborator_type\x18\n \x01(\x0e\x32\x36.ai.verta.common.CollaboratorTypeEnum.CollaboratorType\x12\x62\n\"default_endpoint_collaborator_type\x18\x0b \x01(\x0e\x32\x36.ai.verta.common.CollaboratorTypeEnum.CollaboratorType\x12\x61\n!default_dataset_collaborator_type\x18\x0c \x01(\x0e\x32\x36.ai.verta.common.CollaboratorTypeEnum.CollaboratorType\x12j\n*default_registered_model_collaborator_type\x18\r \x01(\x0e\x32\x36.ai.verta.common.CollaboratorTypeEnum.CollaboratorType\x12\x14\n\x0cworkspace_id\x18\x0e \x01(\t\x12I\n\x1bregistered_model_can_deploy\x18\x0f \x01(\x0e\x32$.ai.verta.common.TernaryEnum.Ternary\"c\n\x13GetOrganizationById\x12\x0e\n\x06org_id\x18\x01 \x01(\t\x1a<\n\x08Response\x12\x30\n\x0corganization\x18\x01 \x01(\x0b\x32\x1a.ai.verta.uac.Organization\"g\n\x15GetOrganizationByName\x12\x10\n\x08org_name\x18\x01 \x01(\t\x1a<\n\x08Response\x12\x30\n\x0corganization\x18\x01 \x01(\x0b\x32\x1a.ai.verta.uac.Organization\"n\n\x1aGetOrganizationByShortName\x12\x12\n\nshort_name\x18\x01 \x01(\t\x1a<\n\x08Response\x12\x30\n\x0corganization\x18\x01 \x01(\x0b\x32\x1a.ai.verta.uac.Organization\"T\n\x13ListMyOrganizations\x1a=\n\x08Response\x12\x31\n\rorganizations\x18\x01 \x03(\x0b\x32\x1a.ai.verta.uac.Organization\"\x81\x01\n\x0fSetOrganization\x12\x30\n\x0corganization\x18\x01 \x01(\x0b\x32\x1a.ai.verta.uac.Organization\x1a<\n\x08Response\x12\x30\n\x0corganization\x18\x01 \x01(\x0b\x32\x1a.ai.verta.uac.Organization\"@\n\x12\x44\x65leteOrganization\x12\x0e\n\x06org_id\x18\x01 \x01(\t\x1a\x1a\n\x08Response\x12\x0e\n\x06status\x18\x01 \x01(\x08\"9\n\tListUsers\x12\x0e\n\x06org_id\x18\x01 \x01(\t\x1a\x1c\n\x08Response\x12\x10\n\x08user_ids\x18\x01 \x03(\t\"9\n\tListTeams\x12\x0e\n\x06org_id\x18\x01 \x01(\t\x1a\x1c\n\x08Response\x12\x10\n\x08team_ids\x18\x01 \x03(\t\"I\n\x07\x41\x64\x64User\x12\x0e\n\x06org_id\x18\x01 \x01(\t\x12\x12\n\nshare_with\x18\x02 \x01(\t\x1a\x1a\n\x08Response\x12\x0e\n\x06status\x18\x01 \x01(\x08\"L\n\nRemoveUser\x12\x0e\n\x06org_id\x18\x01 \x01(\t\x12\x12\n\nshare_with\x18\x02 \x01(\t\x1a\x1a\n\x08Response\x12\x0e\n\x06status\x18\x01 \x01(\x08\x32\xdb\n\n\x13OrganizationService\x12\x92\x01\n\x13getOrganizationById\x12!.ai.verta.uac.GetOrganizationById\x1a*.ai.verta.uac.GetOrganizationById.Response\",\x82\xd3\xe4\x93\x02&\x12$/v1/organization/getOrganizationById\x12\x9a\x01\n\x15getOrganizationByName\x12#.ai.verta.uac.GetOrganizationByName\x1a,.ai.verta.uac.GetOrganizationByName.Response\".\x82\xd3\xe4\x93\x02(\x12&/v1/organization/getOrganizationByName\x12\xae\x01\n\x1agetOrganizationByShortName\x12(.ai.verta.uac.GetOrganizationByShortName\x1a\x31.ai.verta.uac.GetOrganizationByShortName.Response\"3\x82\xd3\xe4\x93\x02-\x12+/v1/organization/getOrganizationByShortName\x12\x92\x01\n\x13listMyOrganizations\x12!.ai.verta.uac.ListMyOrganizations\x1a*.ai.verta.uac.ListMyOrganizations.Response\",\x82\xd3\xe4\x93\x02&\x12$/v1/organization/listMyOrganizations\x12\x85\x01\n\x0fsetOrganization\x12\x1d.ai.verta.uac.SetOrganization\x1a&.ai.verta.uac.SetOrganization.Response\"+\x82\xd3\xe4\x93\x02%\" /v1/organization/setOrganization:\x01*\x12\x91\x01\n\x12\x64\x65leteOrganization\x12 .ai.verta.uac.DeleteOrganization\x1a).ai.verta.uac.DeleteOrganization.Response\".\x82\xd3\xe4\x93\x02(\"#/v1/organization/deleteOrganization:\x01*\x12j\n\tlistTeams\x12\x17.ai.verta.uac.ListTeams\x1a .ai.verta.uac.ListTeams.Response\"\"\x82\xd3\xe4\x93\x02\x1c\x12\x1a/v1/organization/listTeams\x12j\n\tlistUsers\x12\x17.ai.verta.uac.ListUsers\x1a .ai.verta.uac.ListUsers.Response\"\"\x82\xd3\xe4\x93\x02\x1c\x12\x1a/v1/organization/listUsers\x12\x65\n\x07\x61\x64\x64User\x12\x15.ai.verta.uac.AddUser\x1a\x1e.ai.verta.uac.AddUser.Response\"#\x82\xd3\xe4\x93\x02\x1d\"\x18/v1/organization/addUser:\x01*\x12q\n\nremoveUser\x12\x18.ai.verta.uac.RemoveUser\x1a!.ai.verta.uac.RemoveUser.Response\"&\x82\xd3\xe4\x93\x02 \"\x1b/v1/organization/removeUser:\x01*B>P\x01Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uacb\x06proto3' , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,common_dot_CommonService__pb2.DESCRIPTOR,]) _ORGANIZATION = _descriptor.Descriptor( name='Organization', full_name='ai.verta.uac.Organization', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.uac.Organization.id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='name', full_name='ai.verta.uac.Organization.name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='short_name', full_name='ai.verta.uac.Organization.short_name', index=2, number=7, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='description', full_name='ai.verta.uac.Organization.description', index=3, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='owner_id', full_name='ai.verta.uac.Organization.owner_id', index=4, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='created_timestamp', full_name='ai.verta.uac.Organization.created_timestamp', index=5, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='updated_timestamp', full_name='ai.verta.uac.Organization.updated_timestamp', index=6, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='global_collaborator_type', full_name='ai.verta.uac.Organization.global_collaborator_type', index=7, number=8, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='global_can_deploy', full_name='ai.verta.uac.Organization.global_can_deploy', index=8, number=9, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='default_repo_collaborator_type', full_name='ai.verta.uac.Organization.default_repo_collaborator_type', index=9, number=10, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='default_endpoint_collaborator_type', full_name='ai.verta.uac.Organization.default_endpoint_collaborator_type', index=10, number=11, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='default_dataset_collaborator_type', full_name='ai.verta.uac.Organization.default_dataset_collaborator_type', index=11, number=12, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='default_registered_model_collaborator_type', full_name='ai.verta.uac.Organization.default_registered_model_collaborator_type', index=12, number=13, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='workspace_id', full_name='ai.verta.uac.Organization.workspace_id', index=13, number=14, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='registered_model_can_deploy', full_name='ai.verta.uac.Organization.registered_model_can_deploy', index=14, number=15, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=99, serialized_end=907, ) _GETORGANIZATIONBYID_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.GetOrganizationById.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='organization', full_name='ai.verta.uac.GetOrganizationById.Response.organization', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=948, serialized_end=1008, ) _GETORGANIZATIONBYID = _descriptor.Descriptor( name='GetOrganizationById', full_name='ai.verta.uac.GetOrganizationById', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.GetOrganizationById.org_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_GETORGANIZATIONBYID_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=909, serialized_end=1008, ) _GETORGANIZATIONBYNAME_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.GetOrganizationByName.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='organization', full_name='ai.verta.uac.GetOrganizationByName.Response.organization', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=948, serialized_end=1008, ) _GETORGANIZATIONBYNAME = _descriptor.Descriptor( name='GetOrganizationByName', full_name='ai.verta.uac.GetOrganizationByName', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_name', full_name='ai.verta.uac.GetOrganizationByName.org_name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_GETORGANIZATIONBYNAME_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1010, serialized_end=1113, ) _GETORGANIZATIONBYSHORTNAME_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.GetOrganizationByShortName.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='organization', full_name='ai.verta.uac.GetOrganizationByShortName.Response.organization', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=948, serialized_end=1008, ) _GETORGANIZATIONBYSHORTNAME = _descriptor.Descriptor( name='GetOrganizationByShortName', full_name='ai.verta.uac.GetOrganizationByShortName', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='short_name', full_name='ai.verta.uac.GetOrganizationByShortName.short_name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_GETORGANIZATIONBYSHORTNAME_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1115, serialized_end=1225, ) _LISTMYORGANIZATIONS_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.ListMyOrganizations.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='organizations', full_name='ai.verta.uac.ListMyOrganizations.Response.organizations', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1250, serialized_end=1311, ) _LISTMYORGANIZATIONS = _descriptor.Descriptor( name='ListMyOrganizations', full_name='ai.verta.uac.ListMyOrganizations', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[_LISTMYORGANIZATIONS_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1227, serialized_end=1311, ) _SETORGANIZATION_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.SetOrganization.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='organization', full_name='ai.verta.uac.SetOrganization.Response.organization', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=948, serialized_end=1008, ) _SETORGANIZATION = _descriptor.Descriptor( name='SetOrganization', full_name='ai.verta.uac.SetOrganization', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='organization', full_name='ai.verta.uac.SetOrganization.organization', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_SETORGANIZATION_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1314, serialized_end=1443, ) _DELETEORGANIZATION_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.DeleteOrganization.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='ai.verta.uac.DeleteOrganization.Response.status', index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1483, serialized_end=1509, ) _DELETEORGANIZATION = _descriptor.Descriptor( name='DeleteOrganization', full_name='ai.verta.uac.DeleteOrganization', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.DeleteOrganization.org_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_DELETEORGANIZATION_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1445, serialized_end=1509, ) _LISTUSERS_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.ListUsers.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='user_ids', full_name='ai.verta.uac.ListUsers.Response.user_ids', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1540, serialized_end=1568, ) _LISTUSERS = _descriptor.Descriptor( name='ListUsers', full_name='ai.verta.uac.ListUsers', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.ListUsers.org_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_LISTUSERS_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1511, serialized_end=1568, ) _LISTTEAMS_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.ListTeams.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='team_ids', full_name='ai.verta.uac.ListTeams.Response.team_ids', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1599, serialized_end=1627, ) _LISTTEAMS = _descriptor.Descriptor( name='ListTeams', full_name='ai.verta.uac.ListTeams', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.ListTeams.org_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_LISTTEAMS_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1570, serialized_end=1627, ) _ADDUSER_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.AddUser.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='ai.verta.uac.AddUser.Response.status', index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1483, serialized_end=1509, ) _ADDUSER = _descriptor.Descriptor( name='AddUser', full_name='ai.verta.uac.AddUser', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.AddUser.org_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='share_with', full_name='ai.verta.uac.AddUser.share_with', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_ADDUSER_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1629, serialized_end=1702, ) _REMOVEUSER_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.uac.RemoveUser.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='ai.verta.uac.RemoveUser.Response.status', index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1483, serialized_end=1509, ) _REMOVEUSER = _descriptor.Descriptor( name='RemoveUser', full_name='ai.verta.uac.RemoveUser', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.RemoveUser.org_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='share_with', full_name='ai.verta.uac.RemoveUser.share_with', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_REMOVEUSER_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1704, serialized_end=1780, ) _ORGANIZATION.fields_by_name['global_collaborator_type'].enum_type = common_dot_CommonService__pb2._COLLABORATORTYPEENUM_COLLABORATORTYPE _ORGANIZATION.fields_by_name['global_can_deploy'].enum_type = common_dot_CommonService__pb2._TERNARYENUM_TERNARY _ORGANIZATION.fields_by_name['default_repo_collaborator_type'].enum_type = common_dot_CommonService__pb2._COLLABORATORTYPEENUM_COLLABORATORTYPE _ORGANIZATION.fields_by_name['default_endpoint_collaborator_type'].enum_type = common_dot_CommonService__pb2._COLLABORATORTYPEENUM_COLLABORATORTYPE _ORGANIZATION.fields_by_name['default_dataset_collaborator_type'].enum_type = common_dot_CommonService__pb2._COLLABORATORTYPEENUM_COLLABORATORTYPE _ORGANIZATION.fields_by_name['default_registered_model_collaborator_type'].enum_type = common_dot_CommonService__pb2._COLLABORATORTYPEENUM_COLLABORATORTYPE _ORGANIZATION.fields_by_name['registered_model_can_deploy'].enum_type = common_dot_CommonService__pb2._TERNARYENUM_TERNARY _GETORGANIZATIONBYID_RESPONSE.fields_by_name['organization'].message_type = _ORGANIZATION _GETORGANIZATIONBYID_RESPONSE.containing_type = _GETORGANIZATIONBYID _GETORGANIZATIONBYNAME_RESPONSE.fields_by_name['organization'].message_type = _ORGANIZATION _GETORGANIZATIONBYNAME_RESPONSE.containing_type = _GETORGANIZATIONBYNAME _GETORGANIZATIONBYSHORTNAME_RESPONSE.fields_by_name['organization'].message_type = _ORGANIZATION _GETORGANIZATIONBYSHORTNAME_RESPONSE.containing_type = _GETORGANIZATIONBYSHORTNAME _LISTMYORGANIZATIONS_RESPONSE.fields_by_name['organizations'].message_type = _ORGANIZATION _LISTMYORGANIZATIONS_RESPONSE.containing_type = _LISTMYORGANIZATIONS _SETORGANIZATION_RESPONSE.fields_by_name['organization'].message_type = _ORGANIZATION _SETORGANIZATION_RESPONSE.containing_type = _SETORGANIZATION _SETORGANIZATION.fields_by_name['organization'].message_type = _ORGANIZATION _DELETEORGANIZATION_RESPONSE.containing_type = _DELETEORGANIZATION _LISTUSERS_RESPONSE.containing_type = _LISTUSERS _LISTTEAMS_RESPONSE.containing_type = _LISTTEAMS _ADDUSER_RESPONSE.containing_type = _ADDUSER _REMOVEUSER_RESPONSE.containing_type = _REMOVEUSER DESCRIPTOR.message_types_by_name['Organization'] = _ORGANIZATION DESCRIPTOR.message_types_by_name['GetOrganizationById'] = _GETORGANIZATIONBYID DESCRIPTOR.message_types_by_name['GetOrganizationByName'] = _GETORGANIZATIONBYNAME DESCRIPTOR.message_types_by_name['GetOrganizationByShortName'] = _GETORGANIZATIONBYSHORTNAME DESCRIPTOR.message_types_by_name['ListMyOrganizations'] = _LISTMYORGANIZATIONS DESCRIPTOR.message_types_by_name['SetOrganization'] = _SETORGANIZATION DESCRIPTOR.message_types_by_name['DeleteOrganization'] = _DELETEORGANIZATION DESCRIPTOR.message_types_by_name['ListUsers'] = _LISTUSERS DESCRIPTOR.message_types_by_name['ListTeams'] = _LISTTEAMS DESCRIPTOR.message_types_by_name['AddUser'] = _ADDUSER DESCRIPTOR.message_types_by_name['RemoveUser'] = _REMOVEUSER _sym_db.RegisterFileDescriptor(DESCRIPTOR) Organization = _reflection.GeneratedProtocolMessageType('Organization', (_message.Message,), { 'DESCRIPTOR' : _ORGANIZATION, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.Organization) }) _sym_db.RegisterMessage(Organization) GetOrganizationById = _reflection.GeneratedProtocolMessageType('GetOrganizationById', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _GETORGANIZATIONBYID_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetOrganizationById.Response) }) , 'DESCRIPTOR' : _GETORGANIZATIONBYID, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetOrganizationById) }) _sym_db.RegisterMessage(GetOrganizationById) _sym_db.RegisterMessage(GetOrganizationById.Response) GetOrganizationByName = _reflection.GeneratedProtocolMessageType('GetOrganizationByName', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _GETORGANIZATIONBYNAME_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetOrganizationByName.Response) }) , 'DESCRIPTOR' : _GETORGANIZATIONBYNAME, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetOrganizationByName) }) _sym_db.RegisterMessage(GetOrganizationByName) _sym_db.RegisterMessage(GetOrganizationByName.Response) GetOrganizationByShortName = _reflection.GeneratedProtocolMessageType('GetOrganizationByShortName', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _GETORGANIZATIONBYSHORTNAME_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetOrganizationByShortName.Response) }) , 'DESCRIPTOR' : _GETORGANIZATIONBYSHORTNAME, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetOrganizationByShortName) }) _sym_db.RegisterMessage(GetOrganizationByShortName) _sym_db.RegisterMessage(GetOrganizationByShortName.Response) ListMyOrganizations = _reflection.GeneratedProtocolMessageType('ListMyOrganizations', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _LISTMYORGANIZATIONS_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.ListMyOrganizations.Response) }) , 'DESCRIPTOR' : _LISTMYORGANIZATIONS, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.ListMyOrganizations) }) _sym_db.RegisterMessage(ListMyOrganizations) _sym_db.RegisterMessage(ListMyOrganizations.Response) SetOrganization = _reflection.GeneratedProtocolMessageType('SetOrganization', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _SETORGANIZATION_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.SetOrganization.Response) }) , 'DESCRIPTOR' : _SETORGANIZATION, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.SetOrganization) }) _sym_db.RegisterMessage(SetOrganization) _sym_db.RegisterMessage(SetOrganization.Response) DeleteOrganization = _reflection.GeneratedProtocolMessageType('DeleteOrganization', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _DELETEORGANIZATION_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.DeleteOrganization.Response) }) , 'DESCRIPTOR' : _DELETEORGANIZATION, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.DeleteOrganization) }) _sym_db.RegisterMessage(DeleteOrganization) _sym_db.RegisterMessage(DeleteOrganization.Response) ListUsers = _reflection.GeneratedProtocolMessageType('ListUsers', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _LISTUSERS_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.ListUsers.Response) }) , 'DESCRIPTOR' : _LISTUSERS, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.ListUsers) }) _sym_db.RegisterMessage(ListUsers) _sym_db.RegisterMessage(ListUsers.Response) ListTeams = _reflection.GeneratedProtocolMessageType('ListTeams', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _LISTTEAMS_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.ListTeams.Response) }) , 'DESCRIPTOR' : _LISTTEAMS, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.ListTeams) }) _sym_db.RegisterMessage(ListTeams) _sym_db.RegisterMessage(ListTeams.Response) AddUser = _reflection.GeneratedProtocolMessageType('AddUser', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _ADDUSER_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.AddUser.Response) }) , 'DESCRIPTOR' : _ADDUSER, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.AddUser) }) _sym_db.RegisterMessage(AddUser) _sym_db.RegisterMessage(AddUser.Response) RemoveUser = _reflection.GeneratedProtocolMessageType('RemoveUser', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _REMOVEUSER_RESPONSE, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.RemoveUser.Response) }) , 'DESCRIPTOR' : _REMOVEUSER, '__module__' : 'uac.Organization_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.RemoveUser) }) _sym_db.RegisterMessage(RemoveUser) _sym_db.RegisterMessage(RemoveUser.Response) DESCRIPTOR._options = None _ORGANIZATIONSERVICE = _descriptor.ServiceDescriptor( name='OrganizationService', full_name='ai.verta.uac.OrganizationService', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=1783, serialized_end=3154, methods=[ _descriptor.MethodDescriptor( name='getOrganizationById', full_name='ai.verta.uac.OrganizationService.getOrganizationById', index=0, containing_service=None, input_type=_GETORGANIZATIONBYID, output_type=_GETORGANIZATIONBYID_RESPONSE, serialized_options=b'\202\323\344\223\002&\022$/v1/organization/getOrganizationById', ), _descriptor.MethodDescriptor( name='getOrganizationByName', full_name='ai.verta.uac.OrganizationService.getOrganizationByName', index=1, containing_service=None, input_type=_GETORGANIZATIONBYNAME, output_type=_GETORGANIZATIONBYNAME_RESPONSE, serialized_options=b'\202\323\344\223\002(\022&/v1/organization/getOrganizationByName', ), _descriptor.MethodDescriptor( name='getOrganizationByShortName', full_name='ai.verta.uac.OrganizationService.getOrganizationByShortName', index=2, containing_service=None, input_type=_GETORGANIZATIONBYSHORTNAME, output_type=_GETORGANIZATIONBYSHORTNAME_RESPONSE, serialized_options=b'\202\323\344\223\002-\022+/v1/organization/getOrganizationByShortName', ), _descriptor.MethodDescriptor( name='listMyOrganizations', full_name='ai.verta.uac.OrganizationService.listMyOrganizations', index=3, containing_service=None, input_type=_LISTMYORGANIZATIONS, output_type=_LISTMYORGANIZATIONS_RESPONSE, serialized_options=b'\202\323\344\223\002&\022$/v1/organization/listMyOrganizations', ), _descriptor.MethodDescriptor( name='setOrganization', full_name='ai.verta.uac.OrganizationService.setOrganization', index=4, containing_service=None, input_type=_SETORGANIZATION, output_type=_SETORGANIZATION_RESPONSE, serialized_options=b'\202\323\344\223\002%\" /v1/organization/setOrganization:\001*', ), _descriptor.MethodDescriptor( name='deleteOrganization', full_name='ai.verta.uac.OrganizationService.deleteOrganization', index=5, containing_service=None, input_type=_DELETEORGANIZATION, output_type=_DELETEORGANIZATION_RESPONSE, serialized_options=b'\202\323\344\223\002(\"#/v1/organization/deleteOrganization:\001*', ), _descriptor.MethodDescriptor( name='listTeams', full_name='ai.verta.uac.OrganizationService.listTeams', index=6, containing_service=None, input_type=_LISTTEAMS, output_type=_LISTTEAMS_RESPONSE, serialized_options=b'\202\323\344\223\002\034\022\032/v1/organization/listTeams', ), _descriptor.MethodDescriptor( name='listUsers', full_name='ai.verta.uac.OrganizationService.listUsers', index=7, containing_service=None, input_type=_LISTUSERS, output_type=_LISTUSERS_RESPONSE, serialized_options=b'\202\323\344\223\002\034\022\032/v1/organization/listUsers', ), _descriptor.MethodDescriptor( name='addUser', full_name='ai.verta.uac.OrganizationService.addUser', index=8, containing_service=None, input_type=_ADDUSER, output_type=_ADDUSER_RESPONSE, serialized_options=b'\202\323\344\223\002\035\"\030/v1/organization/addUser:\001*', ), _descriptor.MethodDescriptor( name='removeUser', full_name='ai.verta.uac.OrganizationService.removeUser', index=9, containing_service=None, input_type=_REMOVEUSER, output_type=_REMOVEUSER_RESPONSE, serialized_options=b'\202\323\344\223\002 \"\033/v1/organization/removeUser:\001*', ), ]) _sym_db.RegisterServiceDescriptor(_ORGANIZATIONSERVICE) DESCRIPTOR.services_by_name['OrganizationService'] = _ORGANIZATIONSERVICE # @@protoc_insertion_point(module_scope)
[ "noreply@github.com" ]
NaiboWang.noreply@github.com
ccf7fd5776954f3438b3e7293e5bb7bca2b7282e
d1d067bad6b65e2be1b5488d5abd17c0e9cd1756
/perdiem/accounts/forms.py
20c24d3c8095715aeabec489decb0b29cd15f5bd
[]
no_license
localastronaut/perdiem-django
7b84cf34b83a49cc4695b735321f52eb2be01260
c273dc6fda5533c52710cde0f196886369b36c9d
refs/heads/master
2021-06-13T14:31:54.089816
2016-05-24T06:13:10
2016-05-24T06:13:10
59,598,476
0
0
null
2016-05-24T18:31:19
2016-05-24T18:31:18
null
UTF-8
Python
false
false
3,694
py
""" :Created: 5 April 2015 :Author: Lucas Connors """ from django import forms from django.conf import settings from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.core import validators from accounts.models import UserAvatar class RegisterAccountForm(UserCreationForm): email = forms.EmailField(required=True) subscribe_news = forms.BooleanField(required=False, label='Subscribe to general updates about PerDiem') class Meta(UserCreationForm.Meta): fields = ('username', 'email', 'password1', 'password2',) def save(self, commit=True): user = super(RegisterAccountForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user class EditNameForm(forms.Form): username = forms.CharField( max_length=150, validators=[ validators.RegexValidator( r'^[\w.@+-]+$', ('Enter a valid username. This value may contain only ' 'letters, numbers ' 'and @/./+/-/_ characters.') ), ] ) first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) invest_anonymously = forms.BooleanField(required=False) def __init__(self, user, *args, **kwargs): self.user = user super(EditNameForm, self).__init__(*args, **kwargs) def clean_username(self): username = self.cleaned_data['username'] if User.objects.exclude(id=self.user.id).filter(username=username).exists(): raise forms.ValidationError("A user with that username already exists.") return username class EditAvatarForm(forms.Form): custom_avatar = forms.ImageField(required=False) def __init__(self, user, *args, **kwargs): super(EditAvatarForm, self).__init__(*args, **kwargs) self.fields['avatar'] = forms.ChoiceField(choices=self.get_avatar_choices(user), required=False, widget=forms.RadioSelect) def get_avatar_choices(self, user): user_avatars = UserAvatar.objects.filter(user=user) return [('', 'Default',)] + [(avatar.id, avatar.get_provider_display(),) for avatar in user_avatars] def clean_avatar(self): avatar_id = self.cleaned_data['avatar'] if avatar_id: return UserAvatar.objects.get(id=avatar_id) def clean_custom_avatar(self): custom_avatar = self.cleaned_data['custom_avatar'] if custom_avatar and custom_avatar._size > settings.MAXIMUM_AVATAR_SIZE: raise forms.ValidationError("Image file too large (2MB maximum).") return custom_avatar class EmailPreferencesForm(forms.Form): subscription_news = forms.BooleanField(required=False, label='Subscribe to general updates about PerDiem') subscription_all = forms.BooleanField(required=False, label='Uncheck this box to unsubscribe from all emails from PerDiem') def clean(self): d = self.cleaned_data if d['subscription_news'] and not d['subscription_all']: raise forms.ValidationError("You cannot subscribe to general updates if you are unsubscribed from all emails.") return d class ContactForm(forms.Form): INQUIRY_CHOICES = ( ('Support', 'Support',), ('Feedback', 'Feedback',), ('General Inquiry', 'General Inquiry',), ) inquiry = forms.ChoiceField(choices=INQUIRY_CHOICES) email = forms.EmailField() first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) message = forms.CharField(widget=forms.Textarea)
[ "lucas.revolutiontech@gmail.com" ]
lucas.revolutiontech@gmail.com
42d4b344f2de8a111e67e56a51287107102826fb
001e9919220e498046af29831df057fdfac62a1b
/BOJ/py/4095.py
c6fdb7794521c93ae2e46f1cff6a284fa4cbbd0d
[]
no_license
jaehaaheaj/PS
5b4f72c9d56a6e8fcbee59d20a49594a03ed15d8
6a8655f1d32407951e738e3de8960706637bac39
refs/heads/main
2023-06-14T05:39:27.960154
2021-07-06T09:43:41
2021-07-06T09:43:41
378,353,558
0
0
null
null
null
null
UTF-8
Python
false
false
336
py
# tag: DP while 1: a,b=map(int,input().split()) if a==0:break l=[[*map(int,input().split())]for _ in range(a)] m=max([i[0] for i in l]+l[0]) for i in range(1,a): for j in range(1,b): l[i][j]*=min(l[i-1][j],l[i][j-1],l[i-1][j-1])+1 m=max(l[i][j],m) print(m) # related to: BOJ-1915
[ "jaehaaheaj@gmail.com" ]
jaehaaheaj@gmail.com
6bdc776a7e698bf3b035915ee1f7b6dbda4a67e8
7b5828edda7751700ca7002b40a214e39e5f48a8
/EA/simulation/sickness/symptom.py
52006bc352ee9d3ed06718c4bacdc35442f84d57
[]
no_license
daniela-venuta/Sims-4-Python-Script-Workspace
54c33dac02f84daed66f46b7307f222fede0fa62
f408b28fb34626b2e3b2953152343d591a328d66
refs/heads/main
2023-03-29T18:08:39.202803
2021-03-30T19:00:42
2021-03-30T19:00:42
353,111,243
1
0
null
null
null
null
UTF-8
Python
false
false
2,162
py
from sims4.localization import TunableLocalizedStringFactory from sims4.resources import Types from sims4.tuning.instances import HashedTunedInstanceMetaclass from sims4.tuning.tunable import HasTunableReference, TunableReference, TunableSet from sims4.tuning.tunable_base import GroupNames import services class Symptom(HasTunableReference, metaclass=HashedTunedInstanceMetaclass, manager=services.get_instance_manager(Types.SICKNESS)): INSTANCE_TUNABLES = {'display_name': TunableLocalizedStringFactory(description="\n The symptom's display name. This string is provided with the owning\n Sim as its only token.\n ", tuning_group=GroupNames.UI), 'associated_buffs': TunableSet(description='\n The associated buffs that will be added to the Sim when the symptom\n is applied, and removed when the symptom is removed.\n ', tunable=TunableReference(manager=services.get_instance_manager(Types.BUFF), pack_safe=True)), 'associated_statistics': TunableSet(description="\n The associated stats that will be added to the Sim when the symptom\n is applied, and removed when the symptom is removed.\n \n These are added at the statistic's default value.\n ", tunable=TunableReference(manager=services.get_instance_manager(Types.STATISTIC), pack_safe=True))} @classmethod def apply_to_sim_info(cls, sim_info): if sim_info is None: return for buff in cls.associated_buffs: if buff.can_add(sim_info) and not sim_info.has_buff(buff): sim_info.add_buff(buff, buff_reason=cls.display_name) for stat in cls.associated_statistics: if not sim_info.get_tracker(stat).has_statistic(stat): sim_info.add_statistic(stat, stat.default_value) @classmethod def remove_from_sim_info(cls, sim_info): if sim_info is None: return for buff in cls.associated_buffs: sim_info.remove_buff_by_type(buff) for stat in cls.associated_statistics: sim_info.remove_statistic(stat)
[ "44103490+daniela-venuta@users.noreply.github.com" ]
44103490+daniela-venuta@users.noreply.github.com
31a172f1ae913af6bcb4718877641f6db91db7d3
686781cbf18d2a34a3bb9c902c29f96402fbe032
/classes/types of variables.py
17febd50b16538a0e65a1cd2c9474361dd3835f7
[]
no_license
arvind-mocha/Python-Basics
962c4088361aee89b53f47f4d8e925b12722e0ee
6f079543b4cf69c18ed65e5b618851d24f36e716
refs/heads/main
2023-05-10T13:55:53.459362
2021-06-17T12:35:13
2021-06-17T12:35:13
343,633,921
1
0
null
null
null
null
UTF-8
Python
false
false
715
py
#there are bsically wo types of variables class cars: wheels=4 #class variables they are shared by each object they are also called static variable def __init__(self): self.mil=10 #object/instance variables they are also shared by ach objct obj=cars() obj1=cars() obj.wheel=200 #obj cant represent wheel since it belonged to class not function obj.mil=300 #change is only to the particular object print(obj.mil,cars.wheels) print(obj1.mil,cars.wheels) print() cars.wheels=600 #cars is the class name so it can represet wheels change happens to every object since all #methods belongs to a particular class print(obj.mil,cars.wheels) print(obj1.mil,cars.wheels)
[ "arvindarvind2210@.com" ]
arvindarvind2210@.com
20b8873fcc50f9d04d84b748f25dc8536b9e4ac6
342b3a308c50b9cea752c4dd1efa0b11c42e3f14
/remove_green.py
dd8689a12bc830c147d42c7458bd30e71c7ac155
[]
no_license
eggplants/mice-cable-remover
7133a9de7335c588bd4ef8bafcf666a310697af0
dd3795c3af230ce925a14eafd8d395e30e016571
refs/heads/main
2023-07-15T03:33:23.859098
2021-08-31T06:56:48
2021-08-31T06:56:48
385,130,296
0
0
null
null
null
null
UTF-8
Python
false
false
2,518
py
#!/usr/bin/env python from glob import glob from typing import Tuple import cv2 import numpy as np datas = glob('data/*') + glob('../data_with_cable/*') for i, n in enumerate(datas): print(i, ":", n) s = input("enter number: ") cap = cv2.VideoCapture(datas[int(s)]) def make_hsv_range(low: Tuple[int, int, int], up: Tuple[int, int, int] ) -> Tuple[np.ndarray, np.ndarray]: return np.array(low), np.array(up) def resize_frame(frame: np.ndarray, ratio: float = 0.5) -> np.ndarray: h, w = frame.shape[0:2] return cv2.resize(frame, (int(w*ratio), int(h*ratio))) # = make_hsv_range((0, 0, 0, ), (255, 47, 255,)) # = make_hsv_range((0, 0, 0, ), (71, 66, 255,)) # = make_hsv_range((0, 0, 0, ), (71, 34, 23,)) filter_ = make_hsv_range((0, 0, 0, ), (45, 255, 23,)) # = make_hsv_range((25, 52, 72, ), (200, 255, 255,)) # = make_hsv_range((36, 50, 70, ), (89, 255, 25,)) len_video = cap.get(cv2.CAP_PROP_FRAME_COUNT) ret, frame = cap.read() i = 1 x, y = 0, 0 while ret: mask = cv2.inRange(frame, *filter_) # mask = cv2.dilate(mask, kernel1) # mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) # mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel1) # mask = cv2.erode(mask, kernel2) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((20, 20), np.uint8)) mask = cv2.dilate(mask, np.ones((50, 50), np.uint8)) nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats( mask, 4) stats = stats[1:] for _ in range(len(stats)): a_, b_ = np.sort(stats[_, 2:4]) if a_/b_ < 0.1: stats[_, -1] = 0 if len(stats) > 0: max_ind = np.argmax(stats[:, -1]) + 1 x, y = centroids[max_ind] else: input() pass binarized_frame = cv2.circle(mask, (int(x), int(y), ), 10, (150, 150, 150), thickness=4) mono = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) side_by_side = np.hstack([mono, frame]) cv2.imshow('a', resize_frame(side_by_side)) if cv2.waitKey(1) & 0xFF == ord('q'): break ################################# print("[{}/{}]".format(i, len_video)) print("biggest components center:", "({}, {})".format(x, y)) print("components:", len(stats)) ################################# ret, frame = cap.read() i += 1 else: cap.release() cv2.destroyAllWindows()
[ "w10776e8w@yahoo.co.jp" ]
w10776e8w@yahoo.co.jp
543cc8985e89061a52b22fd93b9d4694a0b4d2bc
33058c8d32939c215ecbab9995fd68284d08f014
/starwarsdemo/settings/dev.py
6a973cd139d3d955fc5c2aa3d0b409e7d1ae6e79
[ "MIT" ]
permissive
stwdmwars/starwarsbckintegration
a5f8638422d17c9c5c82d267fe45fc8c394a522b
5ca91716a3fc1ebd02e7d7c86fc666f4f46d7f2b
refs/heads/master
2022-12-10T19:17:51.464996
2019-10-09T04:55:48
2019-10-09T04:55:48
213,822,847
0
0
MIT
2022-12-08T06:45:18
2019-10-09T04:45:20
Python
UTF-8
Python
false
false
188
py
# pylint: disable=missing-docstring # pylint: disable=unused-wildcard-import # pylint: disable=wildcard-import from starwarsdemo.settings.base import * DEBUG = True ALLOWED_HOSTS = ['*']
[ "parvinder@mediccreations.com" ]
parvinder@mediccreations.com
bfa6920ade78bcf81d6e424648d0adf7b69ba0bd
e89c6ecd408fab32a53299ba5f07f475d53dea68
/Lab7/lab7-q2.py
b807dbba1f8cd042fd7e46b9d356f93bdd84505a
[]
no_license
angelazb/CSCA20F19
3847fb9869aa4353df9475ded1257fb5e8839206
f13fb040aeb92303921dcd181eb79b3f0dc501b6
refs/heads/master
2020-09-11T08:36:20.481406
2019-11-15T23:08:37
2019-11-15T23:08:37
222,007,549
0
1
null
null
null
null
UTF-8
Python
false
false
319
py
# Enter the input number number = input("Enter a number: ") # Convert the item into an integer number = int(number) # Create a new list my_list = [] # Repeat until number = 0 while number > 0: # Add number to the list my_list.append(number) # Change number -1 number -= 1 # Print the list print(my_list)
[ "angelazb@Angelas-MacBook-Pro.local" ]
angelazb@Angelas-MacBook-Pro.local
b9de752ee9bdc24bd6431bf1cc4d1211806e0174
eded2d739d5a1e0c9e20a6cccd58f3d91e863ddb
/visualize.py
fd9051fe0618d2ac1236d6f2b55ddc024a08ef09
[ "MIT" ]
permissive
Abhinav43/LaMP
aa3f090c91f8dc4aa0f9f52dd8f2a929711ae8c2
a277c1ff39409bcd61b236698a2355eaf4fea366
refs/heads/master
2020-05-17T11:29:15.356064
2019-04-10T21:00:29
2019-04-10T21:00:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
32,975
py
import argparse import math import time # from pdb import set_trace as stop from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import models.Constants as Constants from models.Models import Transformer from models.Optim import ScheduledOptim from data_loader import DataLoader import numpy import numpy as np import os import evals from models.Beam import Beam from models.Translator import translate import warnings import os.path as path from evals import Logger from utils import get_pairwise_adj from IPython.core.debugger import set_trace as stop import utils from config_args import config_args,get_args import operator from data_loader import process_data import sklearn.preprocessing as preprocessing import sklearn.cluster as cluster import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable warnings.filterwarnings("ignore") # CUDA_VISIBLE_DEVICES=0 python visualize.py -dataset bookmarks -save_mode best -batch_size 32 -d_model 512 -d_inner_hid 512 -n_layers_enc 2 -n_layers_dec 2 -n_head 4 -epoch 50 -dropout 0.1 -dec_dropout 0.1 -lr 0.0002 -encoder 'graph' -decoder 'graph' -label_mask 'prior' -int_preds -viz get_enc_self_attns = False get_enc_dec_attns = True get_dec_self_attns = True parser = argparse.ArgumentParser() parser.add_argument('-one_sample', action='store_true') parser.add_argument('-save_root', type=str, default='visualizations') parser.add_argument('-normalize', action='store_true') parser.add_argument('-shuffle', action='store_true') args = get_args(parser) opt = config_args(args) if opt.n_layers_dec is None: opt.n_layers_dec = opt.n_layers_enc opt.epoch = 50 if opt.decoder in ['sa_m','pmlp']: opt.proj_share_weight = True else: opt.proj_share_weight = False if opt.dataset in ['deepsea','gm12878','gm12878_unique2','gm12878_unique']: opt.onehot=True if opt.test_batch_size <= 0: opt.test_batch_size = opt.batch_size if opt.d_v == -1: opt.d_v = int(opt.d_model/opt.n_head) if opt.d_k == -1: opt.d_k = int(opt.d_model/opt.n_head) if opt.dec_dropout == -1: opt.dec_dropout = opt.dropout if opt.dataset in ['bibtext','delicious','bookmarks']: opt.no_enc_pos_embedding = True elif opt.dataset == 'bookmarks': opt.max_encoder_len = 500 opt.max_ar_length = 48 if opt.d_inner_hid == -1: opt.d_inner_hid = int(opt.d_model*2) opt.cuda = True opt.save_dir = path.join(opt.save_root,opt.data_type) if not os.path.exists(opt.save_dir): os.makedirs(opt.save_dir) opt.results_dir = path.join('results',opt.data_type) opt.data = path.join(opt.dataset,'train_valid_test.pt') opt.mname='enc_graph.dec_graph.512.512.128.128.nlayers_2_2.nheads_4.proj_share.bsz_32.loss_ce.adam.lr_0002.drop_20_20.priormask.int_preds_02' # opt.mname='enc_sa.dec_pmlp.512.1024.128.128.nlayers_3_3.nheads_4.proj_share.bsz_32.loss_ce.adam.lr_0002.dropout_20_20.dec_reverse.no_residual' if (opt.adj_matrix_lambda > 0): label_adj_matrix = get_pairwise_adj(data['dict']['tgt'],path.join(opt.dataset,'tf_interactions.tsv')) else: label_adj_matrix = None opt.no_residual = True data = torch.load(opt.data) train_data,valid_data,test_data,label_adj_matrix,opt = process_data(data,opt) data_object = DataLoader( data['dict']['src'], data['dict']['tgt'], src_insts=data['train']['src'], tgt_insts=data['train']['tgt'], batch_size=opt.batch_size, shuffle=opt.shuffle, cuda=opt.cuda) # data_object = DataLoader( # data['dict']['src'], # data['dict']['tgt'], # src_insts=data['test']['src'], # tgt_insts=data['test']['tgt'], # batch_size=opt.batch_size, # shuffle=opt.shuffle, # cuda=opt.cuda) opt.src_vocab_size = data_object.src_vocab_size opt.tgt_vocab_size = data_object.tgt_vocab_size opt.tgt_vocab_size = opt.tgt_vocab_size - 4 opt.d_v = int(opt.d_model/opt.n_head) opt.d_k = int(opt.d_model/opt.n_head) opt.max_token_seq_len_e = data['settings'].max_seq_len opt.max_token_seq_len_d = 30 opt.proj_share_weight = True opt.d_word_vec = opt.d_model label_dict = {'ccat':'corporate/industrial','c11':'strategy/plans','c12':'legal/judicial','c13':'regulation/policy','c14':'share listings','c15':'performance','c151':'accounts/earnings','c1511':'annual results','c152':'comment/forecasts','c16':'insolvency/liquidity','c17':'funding/capital','c171':'share capital','c172':'bonds/debt issues','c173':'loans/credits','c174':'credit ratings','c18':'ownership changes','c181':'mergers/acquisitions','c182':'asset transfers','c183':'privatisations','c21':'production/services','c22':'new products/services','c23':'research/development','c24':'capacity/facilities','c31':'markets/marketing','c311':'domestic markets','c312':'external markets','c313':'market share','c32':'advertising/promotion','c33':'contracts/orders','c331':'defence contracts','c34':'monopolies/competition','c41':'management','c411':'management moves','c42':'labour','ecat':'economics','e11':'economic performance','e12':'monetary/economic','e121':'money supply','e13':'inflation/prices','e131':'consumer prices','e132':'wholesale prices','e14':'consumer finance','e141':'personal income','e142':'consumer credit','e143':'retail sales','e21':'government finance','e211':'expenditure/revenue','e212':'government borrowing','e31':'output/capacity','e311':'industrial production','e312':'capacity utilization','e313':'inventories','e41':'employment/labour','e411':'unemployment','e51':'trade/reserves','e511':'balance of payments','e512':'merchandise trade','e513':'reserves','e61':'housing starts','e71':'leading indicators','gcat':'government/social','g15':'european community','g151':'ec internal market','g152':'ec corporate policy','g153':'ec agriculture policy','g154':'ec monetary/economic','g155':'ec institutions','g156':'ec environment issues','g157':'ec competition/subsidy','g158':'ec external relations','g159':'ec general','gcrim':'crime/law enforcement','gdef':'defence','gdip':'international relations','gdis':'disasters and accidents','gent':'arts/culture/entertainment','genv':'environment and natural world','gfas':'fashion','ghea':'health','gjob':'labour issues','gmil':'millennium issues','gobit':'obituaries','godd':'human interest','gpol':'domestic politics','gpro':'biographies/personalities/people','grel':'religion','gsci':'science and technology','gspo':'sports','gtour':'travel and tourism','gvio':'war/civil war','gvote':'elections','gwea':'weather','gwelf':'welfare/social services','mcat':'markets','g15':'european community','gcrim':'crime/law enforcement','gdef':'defence','gdip':'international relations','gdis':'disasters and accidents','gent':'arts/culture/entertainment','genv':'environment and natural world','gfas':'fashion','ghea':'health','gjob':'labour issues','gmil':'millennium issues','gobit':'obituaries','godd':'human interest','gpol':'domestic politics','gpro':'biographies/personalities/people','grel':'religion','gsci':'science and technology','gspo':'sports','gtour':'travel and tourism','gvio':'war/civil war','gvote':'elections','gwea':'weather','gwelf':'welfare/social services','m11':'equity markets','m12':'bond markets','m13':'money markets','m131':'interbank markets','m132':'forex markets','m14':'commodity markets','m141':'soft commodities','m142':'metals trading','m143':'energy markets'} # label_dict = {'pou2f2':'pou2f2','rela':'rela','bcl3':'bcl3','maz':'maz','egr1':'egr1','foxm1':'foxm1','tcf7l1':'tcf7l1','stat1':'stat1','brca1':'brca1','rcor1':'rcor1','taf1':'taf1','nfe2':'nfe2','znf143':'znf143','tbl1xr1':'tbl1xr1','mxi1':'mxi1','bclaf1':'bclaf1','polr3g':'polr3g','myc':'myc','rxra':'rxra','stat5a':'stat5a','cebpb':'cebpb','znf274':'znf274','max':'max','e2f4':'e2f4','nr2c2':'nr2c2','stag1':'stag1','runx3':'runx3','ebf1':'ebf1','mef2c':'mef2c','chd2':'chd2','atf2':'atf2','usf1':'usf1','rest':'rest','sin3a':'sin3a','zzz3':'zzz3','mafk':'mafk','znf384':'znf384','brd4':'brd4','bcl11a':'bcl11a','usf2':'usf2','bhlhe40':'bhlhe40','gabpa':'gabpa','pml':'pml','mta3':'mta3','zeb1':'zeb1','nrf1':'nrf1','six5':'six5','stat3':'stat3','smc3':'smc3','jund':'jund','tp53':'tp53','irf3':'irf3','chd1':'chd1','ikzf1':'ikzf1','rad21':'rad21','atf3':'atf3','tbp':'tbp','mef2a':'mef2a','srebf1':'srebf1','yy1':'yy1','fos':'fos','esrra':'esrra','polr3a':'polr3a','pax5':'pax5','ets1':'ets1','elf1':'elf1','srebf2':'srebf2','ep300':'ep300','pbx3':'pbx3','creb1':'creb1','rfx5':'rfx5','irf4':'irf4','nfic':'nfic','elk1':'elk1','tcf12':'tcf12','nfyb':'nfyb','wrnip1':'wrnip1','zbtb33':'zbtb33','nfya':'nfya','cux1':'cux1','nfatc1':'nfatc1','ctcf':'ctcf','kat2b':'kat2b','batf':'batf','srf':'srf','ezh2':'ezh2'} num_layers = 2 num_attn_heads = 4 label_size = len(data['dict']['tgt'])-4 global_dec_self_attns = torch.zeros(num_layers,num_attn_heads,label_size,label_size).cuda() def get_average_attn_weights(data_object): # cmap = mpl.cm.bwr # cmap = mpl.colors.LinearSegmentedColormap.from_list('mycmap', ['black', 'lime']) # cmap = mpl.cm.viridis norm = mpl.colors.Normalize(vmin=0, vmax=1) Flag = False idx = 0 model = Transformer( opt.src_vocab_size, opt.tgt_vocab_size, opt.max_token_seq_len_e, opt.max_token_seq_len_d, proj_share_weight=opt.proj_share_weight, embs_share_weight=opt.embs_share_weight, d_k=opt.d_k, d_v=opt.d_v, d_model=opt.d_model, d_word_vec=opt.d_word_vec, d_inner_hid=opt.d_inner_hid, n_layers_enc=opt.n_layers_enc, n_layers_dec=opt.n_layers_dec, n_head=opt.n_head, n_head2=opt.n_head2, dropout=opt.dropout, dec_dropout=opt.dec_dropout, dec_dropout2=opt.dec_dropout2, encoder=opt.encoder, decoder=opt.decoder, enc_transform=opt.enc_transform, onehot=opt.onehot, no_enc_pos_embedding=opt.no_enc_pos_embedding, no_dec_self_att=opt.no_dec_self_att, loss=opt.loss, label_adj_matrix=label_adj_matrix, attn_type=opt.attn_type, label_mask=opt.label_mask, matching_mlp=opt.matching_mlp, graph_conv=opt.graph_conv, int_preds=opt.int_preds) print(model) if torch.cuda.device_count() > 1 and opt.multi_gpu: print("Using", torch.cuda.device_count(), "GPUs!") model = nn.DataParallel(model) if torch.cuda.is_available() and opt.cuda: model = model.cuda() if opt.gpu_id != -1: torch.cuda.set_device(opt.gpu_id) # state_dict = torch.load(opt.results_dir+'/'+opt.mname+'/model.chkpt') state_dict = torch.load(opt.model_name+'/model.chkpt') model.load_state_dict(state_dict['model']) model.eval() label_list = [] for key,value in data['dict']['tgt'].items(): if value >= 4: label_list.append(key) sorted_labels = sorted(data['dict']['tgt'].items(), key=operator.itemgetter(1)) rev_tgt_dict = {} for key,value in data['dict']['tgt'].items(): rev_tgt_dict[value] = key rev_src_dict = {} for key,value in data['dict']['src'].items(): rev_src_dict[value] = key def get_labels(tgt): ret_array = [] for label_index in tgt: for label, index in data['dict']['tgt'].items(): if index == label_index: ret_array.append(label) return ret_array def get_input(src): ret_array = [] for label_index in src: for label, index in data['dict']['src'].items(): if index == label_index: ret_array.append(label) return ret_array sample_count = 0 for batch in tqdm(data_object, mininterval=0.5,desc='(Training) ', leave=False): src,adj,tgt = batch gold = tgt[:, 1:] gold_binary = utils.get_gold_binary(gold.data.cpu(),opt.tgt_vocab_size).cuda() pred,enc_out,attns1,attns2 = model(src, adj,tgt, gold_binary, return_attns=True,int_preds=False) # pred,enc_output,*results = model(src,adj,tgt,gold_binary,int_preds=opt.int_preds) _,_,all_int_preds = model(src, adj,None, gold_binary, return_attns=False,int_preds=True) enc_self_attns_layers = attns1[0] dec_self_attns_layers = attns2[0] enc_dec_attn_layers = attns2[1] src = src[0].data tgt = tgt.data for sample_idx in range(src.size(0)): sample_count+=1 src_i = src[sample_idx][src[sample_idx].nonzero()[:,0]][1:-1] tgt_i = tgt[sample_idx][tgt[sample_idx].nonzero()[:,0]][1:-1] pred_i = pred[sample_idx] pred_i = F.sigmoid(pred_i).cpu().data gold = torch.zeros(pred_i.size(0)).index_fill_(0,tgt_i.cpu()-4,1) # inputs = get_input(src_i) labels = get_labels(tgt_i) if len(labels)>3 and sample_count>50: word_list = [] for pos1 in range(src_i.size(0)): word_list.append(rev_src_dict[src_i[pos1].item()]) pos_labels = [] pos_labels_tensor = [] sample_label_list = [] for key,value in sorted_labels: if value >= 4: if key in labels: pos_labels.append(value-4) # pos_labels_tensor.append(value) sample_label_list.append(key) pos_labels_tensor = torch.Tensor(pos_labels).long() enc_dec_self_attns = torch.zeros(len(enc_dec_attn_layers),num_attn_heads,enc_dec_attn_layers[0].size(1),src_i.size(0)).cuda() curr_dec_self_attns = torch.zeros(len(enc_dec_attn_layers),num_attn_heads,dec_self_attns_layers[0].size(1),dec_self_attns_layers[0].size(1)).cuda() for layer in range(len(dec_self_attns_layers)): enc_self_attns = enc_self_attns_layers[layer].data dec_self_attns = dec_self_attns_layers[layer].data enc_dec_attns = enc_dec_attn_layers[layer].data enc_self_attns = enc_self_attns.view(opt.n_head,-1,enc_self_attns.size(1),enc_self_attns.size(2)) dec_self_attns = dec_self_attns.view(opt.n_head,-1,dec_self_attns.size(1),dec_self_attns.size(2)) enc_dec_attns = enc_dec_attns.view(opt.n_head,-1,enc_dec_attns.size(1),enc_dec_attns.size(2)) # stop() if get_enc_self_attns: enc_self_attns_i = enc_self_attns[sample_idx][:,1:-1,1:-1] enc_self_attns_i = enc_self_attns_i[:,0:src_i.size(0),0:src_i.size(0)] enc_self_attns_i = torch.mean(enc_self_attns_i,0) # Mean across K heads if get_enc_dec_attns: # stop() enc_dec_attns_i = enc_dec_attns[:,sample_idx,:,:] enc_dec_attns_i = enc_dec_attns_i[:,:,1:src_i.size(0)+1] enc_dec_self_attns[layer] = enc_dec_attns_i if get_dec_self_attns: dec_self_attns_i = dec_self_attns[:,sample_idx,:,:] # undirected_dec_self_attns_i = (dec_self_attns_i + dec_self_attns_i.transpose(1,2))/2 undirected_dec_self_attns_i = dec_self_attns_i global_dec_self_attns[layer] += undirected_dec_self_attns_i curr_dec_self_attns[layer] = undirected_dec_self_attns_i enc_dec_self_attns = torch.index_select(enc_dec_self_attns,2,pos_labels_tensor.cuda()) ################## CLUSTERING ################ for layer in range(enc_dec_self_attns.size(0)): print(layer) mean_attns = enc_dec_self_attns[layer].mean(0).cpu().numpy() cluster_model = cluster.bicluster.SpectralBiclustering(n_clusters=4, method='log',random_state=0) cluster_model.fit(mean_attns) fit_data = mean_attns[np.argsort(cluster_model.row_labels_)] fit_data = fit_data[:, np.argsort(cluster_model.column_labels_)] word_list_np = np.array(word_list) labels_np = np.array(labels) row_indices = np.argsort(cluster_model.row_labels_) column_indices = np.argsort(cluster_model.column_labels_) word_list_np[row_indices] word_list_sorted = word_list_np[column_indices].tolist() labels_sorted = labels_np[row_indices].tolist() # fig = plt.figure() # ax = fig.add_subplot(111) # cax = ax.matshow(fit_data,cmap=plt.cm.Blues) # ax.set_xticks(np.arange(0,len(word_list_sorted),1)) # ax.set_xticklabels(word_list_sorted, fontsize=2) # plt.setp(ax.get_xticklabels(), rotation=90) # ax.set_yticks(np.arange(0,len(labels_sorted),1)) # ax.set_yticklabels(labels_sorted, fontsize=2) # # plt.title("After biclustering; rearranged to show biclusters") # plt.savefig('enc_dec_clustering'+str(layer)+'_1.png',dpi=500) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(np.outer(np.sort(cluster_model.row_labels_) + 1,np.sort(cluster_model.column_labels_) + 1),cmap=plt.cm.Blues) ax.set_xticks(np.arange(0,len(word_list_sorted),1)) ax.set_xticklabels(word_list_sorted, fontsize=2) plt.setp(ax.get_xticklabels(), rotation=90) ax.set_yticks(np.arange(0,len(labels_sorted),1)) ax.set_yticklabels(labels_sorted, fontsize=2) # plt.title("Checkerboard structure of rearranged data") plt.savefig('enc_dec_clustering'+str(layer)+'_2.png',dpi=500) ############################## mean_attns = curr_dec_self_attns[layer].mean(0).cpu().numpy() cluster_model = cluster.bicluster.SpectralBiclustering(n_clusters=4, method='log',random_state=0) cluster_model.fit(mean_attns) fit_data = mean_attns[np.argsort(cluster_model.row_labels_)] fit_data = fit_data[:, np.argsort(cluster_model.column_labels_)] row_indices = np.argsort(cluster_model.row_labels_) column_indices = np.argsort(cluster_model.column_labels_) full_labels = np.arange(4,len(data['dict']['tgt']),1) full_labels = get_labels(full_labels) labels_np = np.array(full_labels) labels_sorted_row = labels_np[row_indices].tolist() labels_sorted_column = labels_np[column_indices].tolist() # fig = plt.figure() # ax = fig.add_subplot(111) # cax = ax.matshow(fit_data,cmap=plt.cm.Blues) # ax.set_xticks(np.arange(0,len(labels_sorted_column),1)) # ax.set_xticklabels(labels_sorted_column, fontsize=2) # plt.setp(ax.get_xticklabels(), rotation=90) # ax.set_yticks(np.arange(0,len(labels_sorted_row),1)) # ax.set_yticklabels(labels_sorted_row, fontsize=4) # # plt.title("After biclustering; rearranged to show biclusters") # plt.savefig('dec_clustering'+str(layer)+'.1.png',dpi=500) fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(np.outer(np.sort(cluster_model.row_labels_) + 1,np.sort(cluster_model.column_labels_) + 1),cmap=plt.cm.Blues) ax.set_xticks(np.arange(0,len(labels_sorted_column),1)) ax.set_xticklabels(labels_sorted_column, fontsize=2) plt.setp(ax.get_xticklabels(), rotation=90) ax.set_yticks(np.arange(0,len(labels_sorted_row),1)) ax.set_yticklabels(labels_sorted_row, fontsize=2) # plt.title("Checkerboard structure of rearranged data") plt.savefig('dec_clustering'+str(layer)+'.2.png',dpi=500) stop() enc_dec_self_attns = torch.sum(enc_dec_self_attns,1).unsqueeze(1) for layer in range(enc_dec_self_attns.size(0)): for head in range(enc_dec_self_attns[layer].size(0)): adj_matrix = enc_dec_self_attns[layer][head].cpu().numpy() fig, ax = plt.subplots() # for edge, spine in ax.spines.items():spine.set_visible(False) cmap = mpl.cm.Blues im = ax.imshow(adj_matrix, cmap=cmap,norm= mpl.colors.Normalize(vmin=0, vmax=1)) ax.set_xticks(np.arange(0,adj_matrix.shape[1],1)) ax.set_yticks(np.arange(0,adj_matrix.shape[0],1)) ax.set_xticklabels(word_list, fontsize=8) # ax.set_yticklabels(label_list, fontsize=3) # for pos_label in pos_labels: ax.get_yticklabels()[pos_label].set_color("red") ax.set_yticklabels(labels, fontsize=8) plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False,pad=0,length=0,colors='red') plt.tick_params(axis='x',which='both',bottom=False,top=False,labelbottom=True,pad=0,length=0) ax.tick_params(axis='both', which='major', pad=1) plt.setp(ax.get_xticklabels(), rotation=90) cbar = fig.colorbar(im, ticks=[0, 0.5, 1]) cbar.ax.set_yticklabels(['0', '0.5', '1']) plot_file_name = path.join(opt.save_dir,'sample'+str(sample_count)+'.encdec.layer'+str(layer+1)+'.head'+str(head+1)+'.png') print(plot_file_name) plt.savefig(plot_file_name,dpi=500)#,bbox_inches = 'tight') curr_dec_self_attns = torch.index_select(curr_dec_self_attns,2,pos_labels_tensor.cuda()) curr_dec_self_attns = torch.index_select(curr_dec_self_attns,3,pos_labels_tensor.cuda()) curr_dec_self_attns = torch.sum(curr_dec_self_attns,1).unsqueeze(1) for layer in range(curr_dec_self_attns.size(0)): for head in range(curr_dec_self_attns[layer].size(0)): # mean_global = (global_dec_self_attns[layer][head] + global_dec_self_attns[layer][head].transpose(0,1))/2. # adj_matrix = mean_global.cpu().numpy() adj_matrix = curr_dec_self_attns[layer][head].cpu().numpy()# adj_matrix[adj_matrix == 0] = 'nan' if opt.normalize: max_vals = np.nanmax(adj_matrix, axis=1) min_vals = np.nanmin(adj_matrix, axis=1) max_vals = np.repeat(max_vals.reshape((-1,1)),adj_matrix.shape[1],1) min_vals = np.repeat(min_vals.reshape((-1,1)),adj_matrix.shape[1],1) adj_matrix = (adj_matrix-min_vals)/(max_vals-min_vals) if not opt.one_sample: adj_matrix = adj_matrix/sample_count adj_matrix = preprocessing.minmax_scale(adj_matrix,feature_range=(0,1)) fig, ax = plt.subplots() cmap = mpl.cm.Blues im = ax.imshow(adj_matrix, cmap=cmap,norm= mpl.colors.Normalize(vmin=0, vmax=1)) ax.set_xticks(np.arange(adj_matrix.shape[0])) ax.set_yticks(np.arange(adj_matrix.shape[1])) # ax.set_xticklabels(label_list, fontsize=3) # ax.set_yticklabels(label_list, fontsize=3) plt.xlabel('Input Features') plt.ylabel('Labels') ax.set_xticklabels(labels, fontsize=40) ax.set_yticklabels(labels, fontsize=40) plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False,pad=2,length=0,colors='red') plt.tick_params(axis='x',which='both',bottom=False,top=False,labelbottom=True,pad=2,length=0,colors='red') ax.tick_params(axis='both', which='major', pad=2) plt.setp(ax.get_xticklabels(), rotation=90) cbar = fig.colorbar(im, ticks=[0, 0.5, 1]) cbar.ax.set_yticklabels(['0', '0.5', '1']) # ax.set_title("adj matrix of head i") plot_file_name = path.join(opt.save_dir,'sample'+str(sample_count)+'.decself.layer'+str(layer+1)+'.head'+str(head+1)+'.png') print(plot_file_name) plt.savefig(plot_file_name,dpi=500,bbox_inches = 'tight') all_preds = torch.Tensor() for int_pred in all_int_preds: int_pred = F.sigmoid(int_pred[sample_idx]).cpu().data all_preds = torch.cat((all_preds,int_pred.unsqueeze(0)),0) all_preds = torch.cat((all_preds,pred_i.unsqueeze(0)),0) all_preds = torch.flip(all_preds,[0]) sample_label_list = [''] pos_labels = [] for key,value in sorted_labels: if value >= 4: if key in labels: pos_labels.append(value-4+1) sample_label_list.append(key) adj_matrix = all_preds.numpy() fig, ax = plt.subplots() cmap = mpl.cm.viridis im = ax.imshow(adj_matrix,cmap=cmap,norm= mpl.colors.Normalize(vmin=0, vmax=1)) ax.set_xticks(np.arange(-.5, len(sample_label_list),1)) ax.set_yticks(np.arange(0, adj_matrix.shape[0],1)) ax.set_yticklabels(['Step 2.2: Label-Label MP','Step 2.1: Feature-Label MP','Step 1.2: Label-Label MP','Step 1.1: Feature-Label MP'], fontsize=1.75) ax.set_xticklabels(sample_label_list, fontsize=1.75) plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False,pad=1.0,length=0) plt.tick_params(axis='x',which='both',bottom=False,top=False,labelbottom=True,pad=0.5,length=0) plt.setp(ax.get_xticklabels(), rotation=90, ha="right") ax.grid(linestyle='-', linewidth='0.0', color='w') plt.xlabel('Labels') plt.xlabel('Label Node Update Steps') cbar.ax.set_yticklabels(['0', '0.5', '1']) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig.colorbar(im, ticks=[0, 0.5, 1],cax=cax) for pos_label in pos_labels: ax.get_xticklabels()[pos_label].set_color("red") plot_file_name = path.join(opt.save_dir,'sample'+str(sample_count)+'.int_preds.png') print(plot_file_name) fig.tight_layout() plt.savefig(plot_file_name,dpi=1000) pos_labels_predictions = torch.index_select(all_preds,1,pos_labels_tensor) adj_matrix = pos_labels_predictions.numpy() fig, ax = plt.subplots() cmap = mpl.cm.viridis im = ax.imshow(adj_matrix,cmap=cmap,norm= mpl.colors.Normalize(vmin=0, vmax=1)) ax.set_xticks(np.arange(0.5, adj_matrix.shape[1],1)) ax.set_yticks(np.arange(0.5, adj_matrix.shape[0],1)) ax.set_yticklabels(['label to label out 2','label to input out 2','label to label out 1','label to input out 1'], fontsize=25) ax.set_xticklabels(labels, fontsize=30) plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False,pad=0.5,length=0) plt.tick_params(axis='x',which='both',bottom=False,top=False,labelbottom=True,pad=0.5,length=0) plt.setp(ax.get_xticklabels(), rotation=90, ha="right") ax.grid(linestyle='-', linewidth='0.3', color='w') cbar.ax.set_yticklabels(['0', '0.5', '1']) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig.colorbar(im, ticks=[0, 0.5, 1],cax=cax) plot_file_name = path.join(opt.save_dir,'sample'+str(sample_count)+'.int_preds2.png') print(plot_file_name) fig.tight_layout() plt.savefig(plot_file_name,dpi=500) montage = False if montage: if opt.normalize: montage_file_name = opt.save_dir+'/'+opt.data_type+'_norm.pdf' else: montage_file_name = opt.save_dir+'/'+opt.data_type+'.pdf' print('montage '+opt.save_dir+'/*.png -tile 4x2 -geometry +2+2 '+montage_file_name) os.system('montage '+opt.save_dir+'/*.png -tile 4x2 -geometry +2+2 '+montage_file_name) def get_int_preds(data_object): Flag = False idx = 0 model = Transformer( opt.src_vocab_size, opt.tgt_vocab_size, opt.max_token_seq_len_e, opt.max_token_seq_len_d, proj_share_weight=opt.proj_share_weight, embs_share_weight=opt.embs_share_weight, d_k=opt.d_k, d_v=opt.d_v, d_model=opt.d_model, d_word_vec=opt.d_word_vec, d_inner_hid=opt.d_inner_hid, n_layers_enc=opt.n_layers_enc, n_layers_dec=opt.n_layers_dec, n_head=opt.n_head, n_head2=opt.n_head2, dropout=opt.dropout, dec_dropout=opt.dec_dropout, dec_dropout2=opt.dec_dropout2, encoder=opt.encoder, decoder=opt.decoder, enc_transform=opt.enc_transform, onehot=opt.onehot, no_enc_pos_embedding=opt.no_enc_pos_embedding, no_dec_self_att=opt.no_dec_self_att, loss=opt.loss, label_adj_matrix=label_adj_matrix, attn_type=opt.attn_type, label_mask=opt.label_mask, matching_mlp=opt.matching_mlp, graph_conv=opt.graph_conv, int_preds=opt.int_preds) if torch.cuda.device_count() > 1 and opt.multi_gpu: print("Using", torch.cuda.device_count(), "GPUs!") model = nn.DataParallel(model) if torch.cuda.is_available() and opt.cuda: model = model.cuda() if opt.gpu_id != -1: torch.cuda.set_device(opt.gpu_id) # state_dict = torch.load(opt.results_dir+'/'+opt.mname+'/model.chkpt') state_dict = torch.load(opt.model_name+'/model.chkpt') model.load_state_dict(state_dict['model']) model.eval() label_list = [] for key,value in data['dict']['tgt'].items(): if value >= 4: label_list.append(key) sorted_labels = sorted(data['dict']['tgt'].items(), key=operator.itemgetter(1)) rev_tgt_dict = {} for key,value in data['dict']['tgt'].items(): rev_tgt_dict[value] = key rev_src_dict = {} for key,value in data['dict']['src'].items(): rev_src_dict[value] = key def get_labels(tgt): ret_array = [] for label_index in tgt: for label, index in data['dict']['tgt'].items(): if index == label_index: ret_array.append(label) return ret_array def get_input(src): ret_array = [] for label_index in src: for label, index in data['dict']['src'].items(): if index == label_index: ret_array.append(label) return ret_array cmap = mpl.cm.viridis # cmap = mpl.colors.LinearSegmentedColormap.from_list('mycmap', ['white','red']) norm = mpl.colors.Normalize(vmin=0, vmax=1) for batch in tqdm(data_object, mininterval=0.5,desc='(Training) ', leave=False): src,adj,tgt = batch gold = tgt[:, 1:] gold_binary = utils.get_gold_binary(gold.data.cpu(),opt.tgt_vocab_size).cuda() pred,enc_out,all_int_preds = model(src, adj,None, gold_binary, return_attns=False,int_preds=True) src = src[0].data tgt = tgt.data idx+=1 sample_idx = 0 src_i = src[sample_idx] tgt_i = tgt[sample_idx] src_i = src_i[src_i.nonzero()[:,0]][1:-1] tgt_i = tgt_i[tgt_i.nonzero()[:,0]][1:-1] pred_i = pred[sample_idx] pred_i = F.sigmoid(pred_i).cpu().data gold = torch.zeros(pred_i.size(0)).index_fill_(0,tgt_i.cpu()-4,1) labels = get_labels(tgt_i) # inputs = get_input(src_i) all_preds = torch.Tensor() for int_pred in all_int_preds: int_pred = F.sigmoid(int_pred[sample_idx]).cpu().data all_preds = torch.cat((all_preds,int_pred.unsqueeze(0)),0) all_preds = torch.cat((all_preds,pred_i.unsqueeze(0)),0) all_preds = torch.flip(all_preds,[0]) sample_label_list = [''] print(labels) pos_labels = [] for key,value in sorted_labels: if value >= 4: if key in labels: pos_labels.append(value-4+1) sample_label_list.append(key) print('saving plots') adj_matrix = all_preds.numpy() # stop() fig, ax = plt.subplots() for edge, spine in ax.spines.items():spine.set_visible(False) im = ax.imshow(adj_matrix,cmap=cmap,norm=norm) ax.set_xticks(np.arange(-.5, len(sample_label_list),1)) ax.set_yticks(np.arange(0, len(all_preds),1)) ax.set_yticklabels(['label to label out 2','label to input out 2','label to label out 1','label to input out 1'], fontsize=3) ax.set_xticklabels(sample_label_list, fontsize=3) plt.tick_params(axis='y',which='both',bottom=False,top=False,labelbottom=False,pad=0,length=0) plt.tick_params(axis='x',which='both',bottom=False,top=False,labelbottom=True,pad=0,length=0) plt.setp(ax.get_xticklabels(), rotation=90, ha="right")#,rotation_mode="anchor") for pos_label in pos_labels: ax.get_xticklabels()[pos_label].set_color("red") plot_file_name = path.join(opt.save_dir,'sample'+str(sample_idx+1)+'.int_preds.png') print(plot_file_name) fig.tight_layout() plt.savefig(plot_file_name,dpi=500)#,bbox_inches = 'tight') # ax.grid(linestyle='-', linewidth='0.3', color='w') if opt.one_sample: break def get_uncoditional_dependence(data): label_list = [] for key,value in data['dict']['tgt'].items(): if value >= 4: label_list.append(key) cmap = mpl.cm.bwr cdict = {'green': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.1), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'red': ((0.0, 0.0, 1.0), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0)) } # cmap = mpl.colors.LinearSegmentedColormap('green_red', cdict,N=256) cmap = mpl.colors.LinearSegmentedColormap.from_list('mycmap', ['red', 'black', 'lime']) norm = mpl.colors.Normalize(vmin=-1, vmax=1) train_label_vals = torch.zeros(len(data['train']['tgt']),len(data['dict']['tgt'])) for i in range(len(data['train']['tgt'])): indices = torch.from_numpy(np.array(data['train']['tgt'][i])) x = torch.zeros(len(data['dict']['tgt'])) x.index_fill_(0, indices, 1) train_label_vals[i] = x train_label_vals = train_label_vals[:,4:] co_occurence_matrix = torch.zeros(train_label_vals.size(1),train_label_vals.size(1)) for sample in data['train']['tgt']: sample2 = sample for i,idx1 in enumerate(sample[1:-1]): for idx2 in sample2[i+1:-1]: if idx1 != idx2: co_occurence_matrix[idx1-4,idx2-4] += 1 print(co_occurence_matrix.sum().item()) co_occurence_matrix[co_occurence_matrix>0]=1 print(co_occurence_matrix.sum().item()) pearson_matrix = np.corrcoef(train_label_vals.transpose(0,1).cpu().numpy()) adj_matrix = pearson_matrix adj_matrix[adj_matrix >= 0.9999] = 'nan' adj_matrix2 = np.nan_to_num(adj_matrix) print(abs(adj_matrix2).sum().item()) adj_matrix2[adj_matrix2 < 0] = 0 print(adj_matrix2.sum().item()) adj_matrix = pearson_matrix adj_matrix[adj_matrix >= 0.9999] = 'nan' adj_matrix2 = np.nan_to_num(adj_matrix) adj_matrix2[adj_matrix2 < 0.1] = 0 adj_matrix2[adj_matrix2 > 0] = 1 print(adj_matrix2.sum().item()) fig, ax = plt.subplots() im = ax.imshow(adj_matrix, cmap=cmap,norm=norm) ax.set_xticks(np.arange(len(label_list))) ax.set_yticks(np.arange(len(label_list))) ax.set_xticklabels(label_list, fontsize=3) ax.set_yticklabels(label_list, fontsize=3) ax.tick_params(axis='both', which='major', pad=1) plt.setp(ax.get_xticklabels(), rotation=90) fig.colorbar(im) plot_file_name = path.join(opt.save_dir,'unconditional_dependencies.png') plt.savefig(plot_file_name,dpi=500,bbox_inches = 'tight') def main(): get_average_attn_weights(data_object) # get_int_preds(data_object) # get_uncoditional_dependence(data) if __name__== "__main__": main()
[ "jacklanchantin@gmail.com" ]
jacklanchantin@gmail.com
2ebf1866f674c31898499d21661717a82ac7cfb2
44c7a640538d14235d197ac6115a92f1b02f8e4d
/volunteer_web/volunteer_web/wsgi.py
7080d88857e54ed16fe03391da68c3d2717e76f9
[]
no_license
LucyYYW/volunteer
a916712ba7a6eb393276e5f5226f92b7f57db266
c2256559234b436fe396d8ccca7e4ab2baeb1b6e
refs/heads/master
2021-08-23T04:03:35.912647
2017-12-03T05:11:11
2017-12-03T05:11:11
109,551,113
0
0
null
null
null
null
UTF-8
Python
false
false
404
py
""" WSGI config for volunteer_web project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "volunteer_web.settings") application = get_wsgi_application()
[ "frankpengyuan@gmail.com" ]
frankpengyuan@gmail.com
4d393f36f862945d3419726d34170ab00450523e
3570b26c21488f633ea3356bf40edb9c399c7d08
/mysite/settings.py
9e7d7b0aafb3ef1963d9dde07511a2f7029626e9
[]
no_license
VolchyokVladislav/djpr3
a49d5177ce7577ce354e1c0ba8daa22f4dea2495
b25f24cb983007b0d069824c96909460a939c3a5
refs/heads/master
2021-08-14T05:27:40.291933
2017-11-14T17:04:43
2017-11-14T17:04:43
110,272,654
0
0
null
null
null
null
UTF-8
Python
false
false
3,292
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.7. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^pv@1imb#$pal-rdp7jl66%&32s*255$$q)ur*v$5lcmx*k&=_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'loginsys.apps.LoginsysConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'mysite.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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'root', 'PASSWORD': 'adgjl\'', 'HOST': '127.0.0.1', 'PORT': '3306' } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'ru-ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')
[ "volchyokvlad@tut.by" ]
volchyokvlad@tut.by
68374d9fe2f5c1f61ae2cfdac1547bcd21120714
8a7ffae96734a50744a4adad2980a1335e0f3acc
/fitness/migrations/0001_initial.py
620055d06aecef5bc9eae7304a3f487def5867d2
[]
no_license
yashsinghbishen/Sarvesh_project
4b84900f83322129a75ccfeacbc6797198638f05
4f3e6cb148a7cd5cfb15d9d9f75c18d9a150bd85
refs/heads/master
2023-08-11T21:00:02.707366
2020-04-09T16:02:56
2020-04-09T16:02:56
250,279,010
1
0
null
2021-09-22T18:47:07
2020-03-26T14:20:30
HTML
UTF-8
Python
false
false
3,142
py
# Generated by Django 3.0.4 on 2020-03-15 08:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BodyPart', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Equipment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Food', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('calories', models.IntegerField(blank=True, null=True)), ], ), migrations.CreateModel( name='Goal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Meal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='FoodMealGoal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('food', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fitness.Food')), ('goal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fitness.Goal')), ('meal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fitness.Meal')), ], ), migrations.CreateModel( name='Excercise', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('equipment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fitness.Equipment')), ], ), migrations.CreateModel( name='BodyPartExcercise', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('body_part', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fitness.BodyPart')), ('excercise', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='fitness.Excercise')), ], ), ]
[ "yashsinghbishen@gmail.com" ]
yashsinghbishen@gmail.com
b452f5f7d06d655b2ca4c9ca4c5156cd3f023229
bbec931b6dec14c351452c31bdbff9197e6caee2
/src/models/detail_predict.py
16717e693b452504b5faf41e1b033cbdc5da5070
[]
no_license
cassiomedeiros/face-recognition-pca
2ab83c9512849f9f609beb246a864f6445bd1298
b3fec6582e7d6d8417e880a6731d5557c24b94eb
refs/heads/main
2023-01-16T04:36:35.514923
2020-11-25T03:58:17
2020-11-25T03:58:17
315,482,874
0
0
null
null
null
null
UTF-8
Python
false
false
2,468
py
import numpy as np import matplotlib.pyplot as plt class DetailPredict(): def __init__(self, predict_label: int, predicted_image: np.array, original_label: int, original_image: np.array, confidence: float, reconstruction_error: float, components: int, type_error: str = None): self._predict_label = predict_label self._predicted_image = predicted_image self._original_label = original_label self._original_image = original_image self._confidence = confidence self._reconstruction_error = reconstruction_error self._components = components self._type_error = type_error @property def reconstructed_image(self) -> np.array: return self._predicted_image.reshape(80, 80).T @property def original_image(self) -> np.array: return self._original_image.reshape(80, 80).T @property def type_error(self): return self._type_error @property def confidence(self): return self._confidence @property def reconstruction_error(self): return self._reconstruction_error @property def components(self): return self._components @property def okay_label(self): return self._predict_label == self._original_label def set_type_error(self, type_error): self._type_error = type_error def to_string(self): return f'Confidence: {round(self._confidence, 2)}\nReconstructed error: {round(self._reconstruction_error, 2)}\nComponents: {self._components}' def show_images(self): fig, (ax1, ax2) = plt.subplots(1, 2) fig.set_size_inches(6, 6) fig.suptitle(f'{self._type_error}', y=.82) ax1.imshow(self.reconstructed_image, cmap=plt.cm.bone) ax1.set_xticks([]) ax1.set_yticks([]) ax1.set_title(f'Reconstructed {self._predict_label}') ax1.text(0, -0.25, self.to_string(), verticalalignment='bottom', horizontalalignment='left', transform=ax1.transAxes, color='black', fontsize=10) ax2.imshow(self.original_image, cmap=plt.cm.bone) ax2.set_xticks([]) ax2.set_yticks([]) ax2.set_title(f'Original {self._original_label}')
[ "kssiomedeiros@live.com" ]
kssiomedeiros@live.com
d4e462a1702b757706b9bacaa9ff5de9da0d4f4e
68f4c7fad89ec1ec7d11fcb2371d1253fa7ddf8f
/Exercicio 3 - Listas.py
5b542f318f72e2663b6959a28dc3bb3ef8c657ed
[]
no_license
otaviohenrique1/python-projetos
f204e6bb9ded3e412de3acedd2b2dd4b38ef1ebc
40e71c8aed862187110fc7cad255f7cd5f9b69f5
refs/heads/master
2021-02-19T09:01:34.274369
2020-03-06T00:56:04
2020-03-06T00:56:04
245,298,281
0
0
null
null
null
null
UTF-8
Python
false
false
1,313
py
#Exemplo de lista x = ['1','2','3','4','5','6'] y = [1,2,3,4,5,6] c = ['a','b','c','d','e','f','g'] j = [15,25,35,45,55,65] k = [100,215,33,48,45,164] #Imprime lista print (x) print (y) # Varrendo a lista for a in j: print (j) # Trocar o último elemento x[-1] = '9' # Incluir item x.append('10') # Remover item x.remove('2') # Ordenar a lista k.sort() # Inverte a lista c.reverse() # Imprime numerado for i, b in enumerate(y): print (i + 1, '=>', b) # Imprime do segundo item em diante print (x[1:]) #Pilhas e filas #Metodo pop() facilita a implementação de filas e pilhas lista = ['A','B','C'] print ('lista:',lista) # A lista vazia é avaliada como falsa while lista: # Em filas, o primeiro item é o primeiro a sair # pop(0) remove e retorna o primeiro item print ('Saiu', lista.pop(0), ', faltam', len(lista)) # Mais itens na lista lista += ['D','E','F'] print ('lista:',lista) while lista: # Em pilhas, o primeiro item é o último a sair # pop() remove e retorna o último item print ('Saiu',lista.pop(),', faltam',len(lista)) #Tuplas tupla = (1,[2,3]) #Elementos da tupla referenciados primeiro_elemento = tupla[0] #Listas convertidas em tuplas tupla = tuple(lista) #Listas convertidas em tuplas lista = list(tupla)
[ "noreply@github.com" ]
otaviohenrique1.noreply@github.com
b74c0a7f4c3244164cddaffb4b61145a15f9aa9b
08f7c200e6737326bb2a69c06c8dddd03240b1d7
/house_turtle.py
e88d576c878e293ca3c7c7927b654e26c26fdf68
[]
no_license
Yogeshpandey01/Python_GUI
ff3a378505fda1f20285ada6c13cf309ff83dc35
0e58e99d6bcd96e82ddf41d7c8113e35962811b5
refs/heads/master
2020-12-22T08:14:56.387279
2020-05-04T10:15:36
2020-05-04T10:15:36
236,722,295
0
0
null
null
null
null
UTF-8
Python
false
false
2,096
py
import turtle import math #set background color screen = turtle.Screen() screen.bgcolor("skyblue") #creat out turtle george = turtle.Turtle() george.color("pink") george.shape("turtle") george.speed(2) #define a function to draw and fill a rectangle def drawRectangle(t,width ,height, color): t.fillcolor("red") t.begin_fill() t.forward(width) t.left(90) t.forward(height) t.left(90) t.forward(width) t.left(90) t.forward(height) t.left(90) t.end_fill() #define a function to fill and draw a equlateral right traingle def drawTriangle(t, length, color): t.fillcolor(color) t.begin_fill() t.forward(length) t.left(135) t.forward(length / math.sqrt(2)) t.left(90) t.forward(length / math.sqrt(2)) t.left(135) t.end_fill() #define a function to draw and fill a parallelogram def drawParallelogram(t,width,height,color): t.fillcolor(color) t.begin_fill() t.left(30) t.forward(width) t.left(60) t.forward(height) t.left(120) t.forward(width) t.left(60) t.forward(height) t.left(90) t.end_fill() #draw and fill the front of the house george.penup() george.goto(-150, -120) george.pendown() drawRectangle(george, 100, 110, "blue") #draw and fill the front door george.penup() george.goto(-120, -120) george.pendown() drawRectangle(george, 40, 60, "lightgreen") #front roof george.penup() george.goto(-150, -10) george.pendown() drawTriangle(george, 100, "magenta") #side of the house george.penup() george.goto(-50 ,-120) george.pendown() drawParallelogram(george, 60 ,110, "yellow") #window george.penup() george.goto(-30, -60) george.pendown() #side of roof george.penup() george.goto(-50, -10) george.pendown() george.fillcolor("orange") george.begin_fill() george.left(30) george.forward(60) george.left(105) george.forward(100 / math.sqrt(2)) george.left(75) george.forward(60) george.left(100 / math.sqrt(2)) george.left(45) george.end_fill() #bring the turtle down to the front door ,and we're done george.penup() george.goto(-100, -150) george.left(90)
[ "59746038+Yogeshpandey01@users.noreply.github.com" ]
59746038+Yogeshpandey01@users.noreply.github.com
ce305113ff2d36d87b9ac6a540fa3e96f94b8bd4
3f719f9f3efbf6d08195001c8b5cc768e541cdc5
/model/models.py
5a97e658857c89efa0417d21f9202ccf70161b06
[]
no_license
ask95/CS395T-DeepLearning-Fall17
c138509d9d9d7ed65ab04a9d7a7fed003a101085
d07314ed47c8e7c2124e3f3b70ad8051b775cc5c
refs/heads/master
2021-07-13T01:22:27.718325
2017-10-09T23:14:12
2017-10-09T23:14:12
103,861,694
0
0
null
null
null
null
UTF-8
Python
false
false
1,069
py
from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D input_shape = (171, 186, 1) num_classes = 109 def get_model1(): model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.50)) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) return model def get_model2(): model = Sequential() model.add(Conv2D(4, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(8, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dense(num_classes, activation='softmax')) return model
[ "picsou@login1.maverick.tacc.utexas.edu" ]
picsou@login1.maverick.tacc.utexas.edu
7503e989dac759ff91b5aeb29d5011778c7eebb4
bc01e1d158e7d8f28451a7e108afb8ec4cb7d5d4
/sage/src/sage/modules/free_module_integer.py
e852b907c656890d00520c300bab78d4d1102dac
[]
no_license
bopopescu/geosci
28792bda1ec1f06e23ba8dcb313769b98f793dad
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
refs/heads/master
2021-09-22T17:47:20.194233
2018-09-12T22:19:36
2018-09-12T22:19:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
30,901
py
# -*- coding: utf-8 -*- """ Discrete Subgroups of `\\ZZ^n`. AUTHORS: - Martin Albrecht (2014-03): initial version - Jan Pöschko (2012-08): some code in this module was taken from Jan Pöschko's 2012 GSoC project TESTS:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice(random_matrix(ZZ, 10, 10)) sage: TestSuite(L).run() """ from __future__ import absolute_import ############################################################################## # Copyright (C) 2012 Jan Poeschko <jan@poeschko.com> # Copyright (C) 2014 Martin Albrecht <martinralbecht@googlemail.com> # # Distributed under the terms of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # The full text of the GPL is available at: # # http://www.gnu.org/licenses/ ############################################################################## from sage.rings.integer_ring import ZZ from sage.matrix.constructor import matrix from sage.misc.cachefunc import cached_method from sage.modules.free_module import FreeModule_submodule_with_basis_pid, FreeModule_ambient_pid from sage.modules.free_module_element import vector from sage.rings.number_field.number_field_element import OrderElement_absolute def IntegerLattice(basis, lll_reduce=True): r""" Construct a new integer lattice from ``basis``. INPUT: - ``basis`` -- can be one of the following: - a list of vectors - a matrix over the integers - an element of an absolute order - ``lll_reduce`` -- (default: ``True``) run LLL reduction on the basis on construction. EXAMPLES: We construct a lattice from a list of rows:: sage: from sage.modules.free_module_integer import IntegerLattice sage: IntegerLattice([[1,0,3], [0,2,1], [0,2,7]]) Free module of degree 3 and rank 3 over Integer Ring User basis matrix: [-2 0 0] [ 0 2 1] [ 1 -2 2] Sage includes a generator for hard lattices from cryptography:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = sage.crypto.gen_lattice(type='modular', m=10, seed=1337, dual=True) sage: IntegerLattice(A) Free module of degree 10 and rank 10 over Integer Ring User basis matrix: [-1 1 2 -2 0 1 0 -1 2 1] [ 1 0 0 -1 -2 1 -2 3 -1 0] [ 1 2 0 2 -1 1 -2 2 2 0] [ 1 0 -1 0 2 3 0 0 -1 -2] [ 1 -3 0 0 2 1 -2 -1 0 0] [-3 0 -1 0 -1 2 -2 0 0 2] [ 0 0 0 1 0 2 -3 -3 -2 -1] [ 0 -1 -4 -1 -1 1 2 -1 0 1] [ 1 1 -2 1 1 2 1 1 -2 3] [ 2 -1 1 2 -3 2 2 1 0 1] You can also construct the lattice directly:: sage: from sage.modules.free_module_integer import IntegerLattice sage: sage.crypto.gen_lattice(type='modular', m=10, seed=1337, dual=True, lattice=True) Free module of degree 10 and rank 10 over Integer Ring User basis matrix: [-1 1 2 -2 0 1 0 -1 2 1] [ 1 0 0 -1 -2 1 -2 3 -1 0] [ 1 2 0 2 -1 1 -2 2 2 0] [ 1 0 -1 0 2 3 0 0 -1 -2] [ 1 -3 0 0 2 1 -2 -1 0 0] [-3 0 -1 0 -1 2 -2 0 0 2] [ 0 0 0 1 0 2 -3 -3 -2 -1] [ 0 -1 -4 -1 -1 1 2 -1 0 1] [ 1 1 -2 1 1 2 1 1 -2 3] [ 2 -1 1 2 -3 2 2 1 0 1] We construct an ideal lattice from an element of an absolute order:: sage: K.<a> = CyclotomicField(17) sage: O = K.ring_of_integers() sage: f = O.random_element(); f -a^15 + a^13 + 4*a^12 - 12*a^11 - 256*a^10 + a^9 - a^7 - 4*a^6 + a^5 + 210*a^4 + 2*a^3 - 2*a^2 + 2*a - 2 sage: from sage.modules.free_module_integer import IntegerLattice sage: IntegerLattice(f) Free module of degree 16 and rank 16 over Integer Ring User basis matrix: [ -2 2 -2 2 210 1 -4 -1 0 1 -256 -12 4 1 0 -1] [ 33 48 44 48 256 -209 28 51 45 49 -1 35 44 48 44 48] [ 1 -1 3 -1 3 211 2 -3 0 1 2 -255 -11 5 2 1] [-223 34 50 47 258 0 29 45 46 47 2 -11 33 48 44 48] [ -13 31 46 42 46 -2 -225 32 48 45 256 -2 27 43 44 45] [ -16 33 42 46 254 1 -19 32 44 45 0 -13 -225 32 48 45] [ -15 -223 30 50 255 1 -20 32 42 47 -2 -11 -15 33 44 44] [ -11 -11 33 48 256 3 -17 -222 32 53 1 -9 -14 35 44 48] [ -12 -13 32 45 257 0 -16 -13 32 48 -1 -10 -14 -222 31 51] [ -9 -13 -221 32 52 1 -11 -12 33 46 258 1 -15 -12 33 49] [ -5 -2 -1 0 -257 -13 3 0 -1 -2 -1 -3 1 -3 1 209] [ -15 -11 -15 33 256 -1 -17 -14 -225 33 4 -12 -13 -14 31 44] [ 11 11 11 11 -245 -3 17 10 13 220 12 5 12 9 14 -35] [ -18 -15 -20 29 250 -3 -23 -16 -19 30 -4 -17 -17 -17 -229 28] [ -15 -11 -15 -223 242 5 -18 -12 -16 34 -2 -11 -15 -11 -15 33] [ 378 120 92 147 152 462 136 96 99 144 -52 412 133 91 -107 138] We construct `\ZZ^n`:: sage: from sage.modules.free_module_integer import IntegerLattice sage: IntegerLattice(ZZ^10) Free module of degree 10 and rank 10 over Integer Ring User basis matrix: [1 0 0 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0 0 0] [0 0 1 0 0 0 0 0 0 0] [0 0 0 1 0 0 0 0 0 0] [0 0 0 0 1 0 0 0 0 0] [0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 0 1 0 0 0] [0 0 0 0 0 0 0 1 0 0] [0 0 0 0 0 0 0 0 1 0] [0 0 0 0 0 0 0 0 0 1] Sage also interfaces with fpylll's lattice generator:: sage: from sage.modules.free_module_integer import IntegerLattice sage: from fpylll import IntegerMatrix sage: A = IntegerMatrix.random(8, "simdioph", bits=20, bits2=10) sage: A = A.to_matrix(matrix(ZZ, 8, 8)) sage: IntegerLattice(A, lll_reduce=False) Free module of degree 8 and rank 8 over Integer Ring User basis matrix: [ 1024 829556 161099 11567 521155 769480 639201 689979] [ 0 1048576 0 0 0 0 0 0] [ 0 0 1048576 0 0 0 0 0] [ 0 0 0 1048576 0 0 0 0] [ 0 0 0 0 1048576 0 0 0] [ 0 0 0 0 0 1048576 0 0] [ 0 0 0 0 0 0 1048576 0] [ 0 0 0 0 0 0 0 1048576] """ if isinstance(basis, OrderElement_absolute): basis = basis.matrix() elif isinstance(basis, FreeModule_ambient_pid): basis = basis.basis_matrix() try: basis = matrix(ZZ, basis) except TypeError: raise NotImplementedError("only integer lattices supported") return FreeModule_submodule_with_basis_integer(ZZ**basis.ncols(), basis=basis, lll_reduce=lll_reduce) class FreeModule_submodule_with_basis_integer(FreeModule_submodule_with_basis_pid): r""" This class represents submodules of `\ZZ^n` with a distinguished basis. However, most functionality in excess of standard submodules over PID is for these submodules considered as discrete subgroups of `\ZZ^n`, i.e. as lattices. That is, this class provides functions for computing LLL and BKZ reduced bases for this free module with respect to the standard Euclidean norm. EXAMPLE:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice(sage.crypto.gen_lattice(type='modular', m=10, seed=1337, dual=True)); L Free module of degree 10 and rank 10 over Integer Ring User basis matrix: [-1 1 2 -2 0 1 0 -1 2 1] [ 1 0 0 -1 -2 1 -2 3 -1 0] [ 1 2 0 2 -1 1 -2 2 2 0] [ 1 0 -1 0 2 3 0 0 -1 -2] [ 1 -3 0 0 2 1 -2 -1 0 0] [-3 0 -1 0 -1 2 -2 0 0 2] [ 0 0 0 1 0 2 -3 -3 -2 -1] [ 0 -1 -4 -1 -1 1 2 -1 0 1] [ 1 1 -2 1 1 2 1 1 -2 3] [ 2 -1 1 2 -3 2 2 1 0 1] sage: L.shortest_vector() (-1, 1, 2, -2, 0, 1, 0, -1, 2, 1) """ def __init__(self, ambient, basis, check=True, echelonize=False, echelonized_basis=None, already_echelonized=False, lll_reduce=True): r""" Construct a new submodule of `\ZZ^n` with a distinguished basis. INPUT: - ``ambient`` -- ambient free module over a principal ideal domain `\ZZ`, i.e. `\ZZ^n` - ``basis`` -- either a list of vectors or a matrix over the integers - ``check`` -- (default: ``True``) if ``False``, correctness of the input will not be checked and type conversion may be omitted, use with care - ``echelonize`` -- (default:``False``) if ``True``, ``basis`` will be echelonized and the result will be used as the default basis of the constructed submodule - `` echelonized_basis`` -- (default: ``None``) if not ``None``, must be the echelonized basis spanning the same submodule as ``basis`` - ``already_echelonized`` -- (default: ``False``) if ``True``, ``basis`` must be already given in the echelonized form - ``lll_reduce`` -- (default: ``True``) run LLL reduction on the basis on construction EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: IntegerLattice([[1,0,-2], [0,2,5], [0,0,7]]) Free module of degree 3 and rank 3 over Integer Ring User basis matrix: [ 1 0 -2] [ 1 -2 0] [ 2 2 1] sage: IntegerLattice(random_matrix(ZZ, 5, 5, x=-2^20, y=2^20)) Free module of degree 5 and rank 5 over Integer Ring User basis matrix: [ -7945 -381123 85872 -225065 12924] [-158254 120252 189195 -262144 -345323] [ 232388 -49556 306585 -31340 401528] [-353460 213748 310673 158140 172810] [-287787 333937 -145713 -482137 186529] sage: K.<a> = NumberField(x^8+1) sage: O = K.ring_of_integers() sage: f = O.random_element(); f a^7 - a^6 + 4*a^5 - a^4 + a^3 + 1 sage: IntegerLattice(f) Free module of degree 8 and rank 8 over Integer Ring User basis matrix: [ 0 1 0 1 0 3 3 0] [ 1 0 0 1 -1 4 -1 1] [ 0 0 1 0 1 0 3 3] [-4 1 -1 1 0 0 1 -1] [ 1 -3 0 0 0 3 0 -2] [ 0 -1 1 -4 1 -1 1 0] [ 2 0 -3 -1 0 -3 0 0] [-1 0 -1 0 -3 -3 0 0] """ basis = matrix(ZZ, basis) self._basis_is_LLL_reduced = False if lll_reduce: basis = matrix([v for v in basis.LLL() if v]) self._basis_is_LLL_reduced = True basis.set_immutable() FreeModule_submodule_with_basis_pid.__init__(self, ambient=ambient, basis=basis, check=check, echelonize=echelonize, echelonized_basis=echelonized_basis, already_echelonized=already_echelonized) self._reduced_basis = basis.change_ring(ZZ) @property def reduced_basis(self): """ This attribute caches the currently best known reduced basis for ``self``, where "best" is defined by the Euclidean norm of the first row vector. EXAMPLE:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice(random_matrix(ZZ, 10, 10), lll_reduce=False) sage: L.reduced_basis [ -8 2 0 0 1 -1 2 1 -95 -1] [ -2 -12 0 0 1 -1 1 -1 -2 -1] [ 4 -4 -6 5 0 0 -2 0 1 -4] [ -6 1 -1 1 1 -1 1 -1 -3 1] [ 1 0 0 -3 2 -2 0 -2 1 0] [ -1 1 0 0 1 -1 4 -1 1 -1] [ 14 1 -5 4 -1 0 2 4 1 1] [ -2 -1 0 4 -3 1 -5 0 -2 -1] [ -9 -1 -1 3 2 1 -1 1 -2 1] [ -1 2 -7 1 0 2 3 -1955 -22 -1] sage: _ = L.LLL() sage: L.reduced_basis [ 1 0 0 -3 2 -2 0 -2 1 0] [ -1 1 0 0 1 -1 4 -1 1 -1] [ -2 0 0 1 0 -2 -1 -3 0 -2] [ -2 -2 0 -1 3 0 -2 0 2 0] [ 1 1 1 2 3 -2 -2 0 3 1] [ -4 1 -1 0 1 1 2 2 -3 3] [ 1 -3 -7 2 3 -1 0 0 -1 -1] [ 1 -9 1 3 1 -3 1 -1 -1 0] [ 8 5 19 3 27 6 -3 8 -25 -22] [ 172 -25 57 248 261 793 76 -839 -41 376] """ return self._reduced_basis def LLL(self, *args, **kwds): r""" Return an LLL reduced basis for ``self``. A lattice basis `(b_1, b_2, ..., b_d)` is `(\delta, \eta)`-LLL-reduced if the two following conditions hold: - For any `i > j`, we have `\lvert \mu_{i, j} \rvert \leq η`. - For any `i < d`, we have `\delta \lvert b_i^* \rvert^2 \leq \lvert b_{i+1}^* + \mu_{i+1, i} b_i^* \rvert^2`, where `\mu_{i,j} = \langle b_i, b_j^* \rangle / \langle b_j^*,b_j^* \rangle` and `b_i^*` is the `i`-th vector of the Gram-Schmidt orthogonalisation of `(b_1, b_2, \ldots, b_d)`. The default reduction parameters are `\delta = 3/4` and `\eta = 0.501`. The parameters `\delta` and `\eta` must satisfy: `0.25 < \delta \leq 1.0` and `0.5 \leq \eta < \sqrt{\delta}`. Polynomial time complexity is only guaranteed for `\delta < 1`. INPUT: - ``*args`` -- passed through to :meth:`sage.matrix.matrix_integer_dense.Matrix_integer_dense.LLL` - ``**kwds`` -- passed through to :meth:`sage.matrix.matrix_integer_dense.Matrix_integer_dense.LLL` OUTPUT: An integer matrix which is an LLL-reduced basis for this lattice. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = random_matrix(ZZ, 10, 10, x=-2000, y=2000) sage: L = IntegerLattice(A, lll_reduce=False); L Free module of degree 10 and rank 10 over Integer Ring User basis matrix: [ -645 -1037 -1775 -1619 1721 -1434 1766 1701 1669 1534] [ 1303 960 1998 -1838 1683 -1332 149 327 -849 -1562] [-1113 -1366 1379 669 54 1214 -1750 -605 -1566 1626] [-1367 1651 926 1731 -913 627 669 -1437 -132 1712] [ -549 1327 -1353 68 1479 -1803 -456 1090 -606 -317] [ -221 -1920 -1361 1695 1139 111 -1792 1925 -656 1992] [-1934 -29 88 890 1859 1820 -1912 -1614 -1724 1606] [ -590 -1380 1768 774 656 760 -746 -849 1977 -1576] [ 312 -242 -1732 1594 -439 -1069 458 -1195 1715 35] [ 391 1229 -1815 607 -413 -860 1408 1656 1651 -628] sage: min(v.norm().n() for v in L.reduced_basis) 3346.57... sage: L.LLL() [ -888 53 -274 243 -19 431 710 -83 928 347] [ 448 -330 370 -511 242 -584 -8 1220 502 183] [ -524 -460 402 1338 -247 -279 -1038 -28 -159 -794] [ 166 -190 -162 1033 -340 -77 -1052 1134 -843 651] [ -47 -1394 1076 -132 854 -151 297 -396 -580 -220] [-1064 373 -706 601 -587 -1394 424 796 -22 -133] [-1126 398 565 -1418 -446 -890 -237 -378 252 247] [ -339 799 295 800 425 -605 -730 -1160 808 666] [ 755 -1206 -918 -192 -1063 -37 -525 -75 338 400] [ 382 -199 -1839 -482 984 -15 -695 136 682 563] sage: L.reduced_basis[0].norm().n() 1613.74... """ basis = self.reduced_basis basis = [v for v in basis.LLL(*args, **kwds) if v] basis = matrix(ZZ, len(basis), len(basis[0]), basis) basis.set_immutable() if self.reduced_basis[0].norm() > basis[0].norm(): self._reduced_basis = basis return basis def BKZ(self, *args, **kwds): """ Return a Block Korkine-Zolotareff reduced basis for ``self``. INPUT: - ``*args`` -- passed through to :meth:`sage.matrix.matrix_integer_dense.Matrix_integer_dense.BKZ` - ``*kwds`` -- passed through to :meth:`sage.matrix.matrix_integer_dense.Matrix_integer_dense.BKZ` OUTPUT: An integer matrix which is a BKZ-reduced basis for this lattice. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = sage.crypto.gen_lattice(type='random', n=1, m=60, q=2^60, seed=42) sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 4.17330740711759e15 sage: L.LLL() 60 x 60 dense matrix over Integer Ring (use the '.str()' method to see the entries) sage: min(v.norm().n() for v in L.reduced_basis) 5.19615242270663 sage: L.BKZ(block_size=10) 60 x 60 dense matrix over Integer Ring (use the '.str()' method to see the entries) sage: min(v.norm().n() for v in L.reduced_basis) 4.12310562561766 .. NOTE:: If ``block_size == L.rank()`` where ``L`` is this lattice, then this function performs Hermite-Korkine-Zolotareff (HKZ) reduction. """ basis = self.reduced_basis basis = [v for v in basis.BKZ(*args, **kwds) if v] basis = matrix(ZZ, len(basis), len(basis[0]), basis) basis.set_immutable() if self.reduced_basis[0].norm() > basis[0].norm(): self._reduced_basis = basis return basis def HKZ(self, *args, **kwds): r""" Hermite-Korkine-Zolotarev (HKZ) reduce the basis. A basis `B` of a lattice `L`, with orthogonalized basis `B^*` such that `B = M \cdot B^*` is HKZ reduced, if and only if, the following properties are satisfied: #. The basis `B` is size-reduced, i.e., all off-diagonal coefficients of `M` satisfy `|\mu_{i,j}| \leq 1/2` #. The vector `b_1` realizes the first minimum `\lambda_1(L)`. #. The projection of the vectors `b_2, \ldots,b_r` orthogonally to `b_1` form an HKZ reduced basis. .. NOTE:: This is realized by calling :func:`sage.modules.free_module_integer.FreeModule_submodule_with_basis_integer.BKZ` with ``block_size == self.rank()``. INPUT: - ``*args`` -- passed through to :meth:`BKZ` - ``*kwds`` -- passed through to :meth:`BKZ` OUTPUT: An integer matrix which is a HKZ-reduced basis for this lattice. EXAMPLE:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = sage.crypto.gen_lattice(type='random', n=1, m=40, q=2^60, seed=1337, lattice=True) sage: L.HKZ() 40 x 40 dense matrix over Integer Ring (use the '.str()' method to see the entries) sage: L.reduced_basis[0] (0, 0, -1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 1, 0, 0, 1, 1, 1, -1, 0, 0, 1, -1, 0, 0, -1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 1, 0, 0, -2) """ return self.BKZ(block_size=self.rank()) @cached_method def volume(self): r""" Return `vol(L)` which is `\sqrt{\det(B \cdot B^T)}` for any basis `B`. OUTPUT: An integer. EXAMPLE:: sage: L = sage.crypto.gen_lattice(m=10, seed=1337, lattice=True) sage: L.volume() 14641 """ if self.rank() == self.degree(): return abs(self.reduced_basis.determinant()) else: return self.gram_matrix().determinant().sqrt() @cached_method def discriminant(self): r""" Return `|\det(G)|`, i.e. the absolute value of the determinant of the Gram matrix `B \cdot B^T` for any basis `B`. OUTPUT: An integer. EXAMPLE:: sage: L = sage.crypto.gen_lattice(m=10, seed=1337, lattice=True) sage: L.discriminant() 214358881 """ return abs(self.gram_matrix().determinant()) @cached_method def is_unimodular(self): """ Return ``True`` if this lattice is unimodular. OUTPUT: A boolean. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice([[1, 0], [0, 1]]) sage: L.is_unimodular() True sage: IntegerLattice([[2, 0], [0, 3]]).is_unimodular() False """ return self.volume() == 1 @cached_method def shortest_vector(self, update_reduced_basis=True, algorithm="fplll", *args, **kwds): r""" Return a shortest vector. INPUT: - ``update_reduced_basis`` -- (default: ``True``) set this flag if the found vector should be used to improve the basis - ``algorithm`` -- (default: ``"fplll"``) either ``"fplll"`` or ``"pari"`` - ``*args`` -- passed through to underlying implementation - ``**kwds`` -- passed through to underlying implementation OUTPUT: A shortest non-zero vector for this lattice. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = sage.crypto.gen_lattice(type='random', n=1, m=30, q=2^40, seed=42) sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 6.03890756700000e10 sage: L.shortest_vector().norm().n() 3.74165738677394 sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 6.03890756700000e10 sage: L.shortest_vector(algorithm="pari").norm().n() 3.74165738677394 sage: L = IntegerLattice(A, lll_reduce=True) sage: L.shortest_vector(algorithm="pari").norm().n() 3.74165738677394 """ if algorithm == "pari": if self._basis_is_LLL_reduced: B = self.basis_matrix().change_ring(ZZ) qf = self.gram_matrix() else: B = self.reduced_basis.LLL() qf = B*B.transpose() count, length, vectors = qf._pari_().qfminim() v = vectors.python().columns()[0] w = v*B elif algorithm == "fplll": from fpylll import IntegerMatrix, SVP L = IntegerMatrix.from_matrix(self.reduced_basis) w = vector(ZZ, SVP.shortest_vector(L, *args, **kwds)) else: raise ValueError("algorithm '{}' unknown".format(algorithm)) if update_reduced_basis: self.update_reduced_basis(w) return w def update_reduced_basis(self, w): """ Inject the vector ``w`` and run LLL to update the basis. INPUT: - ``w`` -- a vector OUTPUT: Nothing is returned but the internal state is modified. EXAMPLE:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = sage.crypto.gen_lattice(type='random', n=1, m=30, q=2^40, seed=42) sage: L = IntegerLattice(A) sage: B = L.reduced_basis sage: v = L.shortest_vector(update_reduced_basis=False) sage: L.update_reduced_basis(v) sage: bool(L.reduced_basis[0].norm() < B[0].norm()) True """ w = matrix(ZZ, w) L = w.stack(self.reduced_basis).LLL() assert(L[0] == 0) self._reduced_basis = L.matrix_from_rows(range(1, L.nrows())) @cached_method def voronoi_cell(self, radius=None): """ Compute the Voronoi cell of a lattice, returning a Polyhedron. INPUT: - ``radius`` -- (default: automatic determination) radius of ball containing considered vertices OUTPUT: The Voronoi cell as a Polyhedron instance. The result is cached so that subsequent calls to this function return instantly. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice([[1, 0], [0, 1]]) sage: V = L.voronoi_cell() sage: V.Vrepresentation() (A vertex at (1/2, -1/2), A vertex at (1/2, 1/2), A vertex at (-1/2, 1/2), A vertex at (-1/2, -1/2)) The volume of the Voronoi cell is the square root of the discriminant of the lattice:: sage: L = IntegerLattice(Matrix(ZZ, 4, 4, [[0,0,1,-1],[1,-1,2,1],[-6,0,3,3,],[-6,-24,-6,-5]])); L Free module of degree 4 and rank 4 over Integer Ring User basis matrix: [ 0 0 1 -1] [ 1 -1 2 1] [ -6 0 3 3] [ -6 -24 -6 -5] sage: V = L.voronoi_cell() # long time sage: V.volume() # long time 678 sage: sqrt(L.discriminant()) 678 Lattices not having full dimension are handled as well:: sage: L = IntegerLattice([[2, 0, 0], [0, 2, 0]]) sage: V = L.voronoi_cell() sage: V.Hrepresentation() (An inequality (-1, 0, 0) x + 1 >= 0, An inequality (0, -1, 0) x + 1 >= 0, An inequality (1, 0, 0) x + 1 >= 0, An inequality (0, 1, 0) x + 1 >= 0) ALGORITHM: Uses parts of the algorithm from [Vit1996]_. REFERENCES: .. [Vit1996] \E. Viterbo, E. Biglieri. *Computing the Voronoi Cell of a Lattice: The Diamond-Cutting Algorithm*. IEEE Transactions on Information Theory, 1996. """ if not self._basis_is_LLL_reduced: self.LLL() B = self.reduced_basis from .diamond_cutting import calculate_voronoi_cell return calculate_voronoi_cell(B, radius=radius) def voronoi_relevant_vectors(self): """ Compute the embedded vectors inducing the Voronoi cell. OUTPUT: The list of Voronoi relevant vectors. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice([[3, 0], [4, 0]]) sage: L.voronoi_relevant_vectors() [(-1, 0), (1, 0)] """ V = self.voronoi_cell() def defining_point(ieq): """ Compute the point defining an inequality. INPUT: - ``ieq`` -- an inequality in the form [c, a1, a2, ...] meaning a1 * x1 + a2 * x2 + ... ≦ c OUTPUT: The point orthogonal to the hyperplane defined by ``ieq`` in twice the distance from the origin. """ c = ieq[0] a = ieq[1:] n = sum(y ** 2 for y in a) return vector([2 * y * c / n for y in a]) return [defining_point(ieq) for ieq in V.inequality_generator()] def closest_vector(self, t): """ Compute the closest vector in the embedded lattice to a given vector. INPUT: - ``t`` -- the target vector to compute the closest vector to OUTPUT: The vector in the lattice closest to ``t``. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: L = IntegerLattice([[1, 0], [0, 1]]) sage: L.closest_vector((-6, 5/3)) (-6, 2) ALGORITHM: Uses the algorithm from [Mic2010]_. REFERENCES: .. [Mic2010] \D. Micciancio, P. Voulgaris. *A Deterministic Single Exponential Time Algorithm for Most Lattice Problems based on Voronoi Cell Computations*. Proceedings of the 42nd ACM Symposium Theory of Computation, 2010. """ voronoi_cell = self.voronoi_cell() def projection(M, v): Mt = M.transpose() P = Mt * (M * Mt) ** (-1) * M return P * v t = projection(matrix(self.reduced_basis), vector(t)) def CVPP_2V(t, V, voronoi_cell): t_new = t while not voronoi_cell.contains(t_new.list()): v = max(V, key=lambda v: t_new * v / v.norm() ** 2) t_new = t_new - v return t - t_new V = self.voronoi_relevant_vectors() t = vector(t) p = 0 while not (ZZ(2 ** p) * voronoi_cell).contains(t): p += 1 t_new = t i = p while i >= 1: V_scaled = [v * (2 ** (i - 1)) for v in V] t_new = t_new - CVPP_2V(t_new, V_scaled, ZZ(2 ** (i - 1)) * voronoi_cell) i -= 1 return t - t_new
[ "valber@HPC" ]
valber@HPC
95a585c5b4d9c5b6708275b6961fe7d8177a942a
c1aa8134217bcdd0eeb1bbccebdf3c02666aef17
/conduit/utils.py
77648fd6c1b6adfd27f0d710e40c9352911fab8d
[ "MIT" ]
permissive
mohamed-aziz/realworld-flask
c8d8378b6c3a2fbe4cf3d79c5e5031e19f735c15
9b0cfb6d057ceab18f33a3203548c54e1caf02cc
refs/heads/master
2021-01-20T09:30:02.588900
2017-05-16T21:22:04
2017-05-21T19:59:08
90,258,841
1
1
null
2017-05-07T17:01:57
2017-05-04T12:07:38
Python
UTF-8
Python
false
false
1,212
py
# -*- coding: utf-8 -*- """Helper utilities and decorators.""" from flask import flash, _request_ctx_stack from functools import wraps from flask_jwt import _jwt import jwt def jwt_optional(realm=None): def wrapper(fn): @wraps(fn) def decorator(*args, **kwargs): token = _jwt.request_callback() try: payload = _jwt.jwt_decode_callback(token) except jwt.exceptions.DecodeError: pass else: _request_ctx_stack.top.current_identity = _jwt.identity_callback(payload) return fn(*args, **kwargs) return decorator return wrapper from conduit.user.models import User # noqa def flash_errors(form, category='warning'): """Flash all errors for a form.""" for field, errors in form.errors.items(): for error in errors: flash('{0} - {1}'.format(getattr(form, field).label.text, error), category) def jwt_identity(payload): user_id = payload['identity'] return User.get_by_id(user_id) def authenticate(email, password): user = User.query.filter_by(email=email).first() if user and user.check_password(password): return user
[ "medazizknani@gmail.com" ]
medazizknani@gmail.com
37bff83c1ae906bb1ecd9a05bef289f0b551e84b
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_118/ch46_2020_03_26_18_29_25_823814.py
5f5c8a66f4540efd1b37403adaa0978dbe9b3f3d
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
161
py
def numero_no_indice(n): n=[] n=str(input('diga uma lista: ')) i=0 while i<=len(n) and i==n[i]: i+=1 print (numero_no_indice(n))
[ "you@example.com" ]
you@example.com
e25c7ba018bbd800ad2a501962985c475c85e543
97e9ed64842ebdb7d6ea4083009436514b5cecfb
/CONTACT/models.py
6812f90a0af68967b140704ef512860dd7041538
[]
no_license
ErDeepakSingh/FoodSanta
eca52b816f2978d04daf7ca48f8be87f3b71facf
82b3794d466aa5678d28b7398e162f16425e41e9
refs/heads/master
2020-07-11T05:07:30.191761
2019-08-26T10:37:47
2019-08-26T10:37:47
204,452,346
0
0
null
null
null
null
UTF-8
Python
false
false
409
py
from django.db import models # from ACCOUNTS.models import User class Contact_Post(models.Model): name=models.CharField(max_length=150) mobile_no=models.CharField(max_length=150) email=models.EmailField(max_length=150) message=models.TextField(max_length=500) # recieved = models.DateTimeField(auto_now_add=True) # author=models.ForeignKey(User) def __str__(self): return
[ "deepakthakur755@gmail.com" ]
deepakthakur755@gmail.com
a0db2ab09deeba431374218941ddfe688d3288bd
c73d0e70a156c080dd798f06a56407c2f0697fba
/zemwrapper.py
6555e9ab370a1263315c5364cc9b8dfe3137738f
[]
no_license
sparkica/zem-api-wrapper
67c383a992210fb666e8320a7f74ebba9cebbb87
1de823eb706084c39c410e0569d92f0f387fe387
refs/heads/master
2020-04-25T18:06:24.379351
2013-05-17T08:53:42
2013-05-17T08:53:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,461
py
#!/usr/bin/env python """wrapper.py: Simple NIF Wrapper for Zemanta API. You need Zemanta API key.""" import urllib import hashlib import simplejson as json from rdflib import BNode, Graph, Literal, Namespace, RDF, URIRef from rdflib import plugin from rdflib import RDF, RDFS, XSD from rdflib.serializer import Serializer plugin.register('pretty-xml', Serializer, 'rdflib.plugins.serializers.rdfxml', 'PrettyXMLSerializer') plugin.register('n3', Serializer, 'rdflib.plugins.serializers.n3', 'N3Serializer') plugin.register('turtle', Serializer, 'rdflib.plugins.serializers.turtle', 'TurtleSerializer') plugin.register('xml', Serializer, 'rdflib.plugins.serializers.rdfxml', 'XMLSerializer') plugin.register('nt', Serializer, 'rdflib.plugins.serializers.nt', 'NTSerializer') plugin.register("rdf-json", Serializer, "rdflib_rdfjson.rdfjson_serializer", "RdfJsonSerializer") gateway = 'http://api.zemanta.com/services/rest/0.0/' STRING = Namespace("http://nlp2rdf.lod2.eu/schema/string/") SSO = Namespace("http://nlp2rdf.lod2.eu/schema/sso/") ZEM = Namespace("http://s.zemanta.com/ns#") ZEM_TARGETS = Namespace("http://s.zemanta.com/ns/targets/#") ZEM_OBJ = Namespace("http://s.zemanta.com/obj/") OWL = Namespace("http://www.w3.org/2002/07/owl#") FREEBASE = Namespace("http://rdf.freebase.com/ns/") NIF = Namespace("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#") XSD = Namespace("http://www.w3.org/2001/XMLSchema#") ITSRDF = Namespace("http://www.w3.org/2005/11/its/rdf#") FORMAT_MAPPINGS = { 'rdfxml': 'pretty-xml', 'ntriples': 'nt', 'turtle': 'turtle', 'n3': 'n3', 'json': 'rdf-json' } FORMATS_ZEMANTA = ['xml', 'json','wnjson', 'rdfxml'] class Wrapper(): def __init__(self, api_key, args): self.args = args self.format = "json" self.nif = False self.isGraph = False self.zem_args = {} self.graph = Graph() # input-type = "text" it is always text def parse_parameters(self): msg = "" status = "ok" #NIF parameters # nif = "true" | "nif-1.0" if 'nif' in self.args: self.nif = True if self.nif == True: self.isGraph = True # NIF PARAMETERS # input-type = "text" if 'input-type' in self.args: if self.args['input-type'] != 'text': status = 'error' msg = "Zemanta only supports plain text input." # NIF: input = "some text" # Zemanta: text = "some text" if 'input' in self.args: self.zem_args['text'] = self.args['input'] if ('text' in self.args): if self.args['input'] != self.args['text']: msg = "Parameters input and text do not match." status = "error" elif 'text' in self.args: self.zem_args['text'] = self.args['text'] else: msg = "No text is provided." status = "error" # output format = "rdfxml" | "ntriples" | "turtle" | "n3" | "json" if ('format' in self.args): self.zem_args['format'] = 'json' if self.args['format'] in FORMAT_MAPPINGS.keys(): self.format = FORMAT_MAPPINGS[self.args['format']] else: status = 'error' msg = "Invalid output format. It should be one of the following: rdfxml, ntriples, turtle, n3, json." else: status = 'error' msg = "Please specify output format." # Default zemanta parameters if 'method' in self.args: self.zem_args['method'] = self.args['method'] else: self.zem_args['method'] = 'zemanta.suggest_markup' # default if 'api_key' in self.args: self.zem_args['api_key'] = self.args['api_key'] else: self.zem_args = self.args if 'format' in self.args: #wrapper for turtle, n3, ntriples if self.args['format'] not in FORMATS_ZEMANTA: self.zem_args['format'] = 'json' self.format = FORMAT_MAPPINGS[self.args['format']] self.isGraph = True else: #default format self.zem_args['format'] = 'xml' return (status, msg) def nlp2rdf(self): """Converts Zemanta result into triples and NIF format""" (status, msg) = self.parse_parameters() if status == "error": return self.generate_error_response(msg) result = {} #make zem-api call result = self.make_zem_api_request() if self.isGraph == False: return result # Parse result into triples rid = result['rid'] docuri = "http://d.zemanta.com/rid/%s" % (rid) doc_id = URIRef(docuri) markup = [] if result.has_key('markup'): markup = result['markup'] # create binds self.graph.bind('z', ZEM) self.graph.bind('zobj', ZEM_OBJ) self.graph.bind('ztarget', ZEM_TARGETS) self.graph.bind('rdf', RDF) self.graph.bind('rdfs', RDFS) self.graph.bind('owl', OWL) self.graph.bind('xsd', XSD) self.graph.bind('base', docuri) # NIF specific binds self.graph.bind('nif', NIF) self.graph.bind('itsrdf', ITSRDF) if self.nif: self.create_nif(doc_id, markup) else: self.create_document(doc_id, rid) if result.has_key('articles'): self.create_articles(result['articles'], doc_id) if result.has_key('images'): self.create_images(result['images'], doc_id) if result.has_key('keywords'): self.create_keywords(result['keywords'], doc_id) if result.has_key('categories'): self.create_categories(result['categories'], doc_id) if result.has_key('markup'): self.create_markup(markup, doc_id) return self.graph.serialize(format=self.format, encoding="utf-8") def create_nif(self, doc_id, markup): context_id = URIRef(doc_id + '#char=0,') # Context self.graph.add((context_id, RDF.type, NIF.Context)) self.graph.add((context_id, RDF.type, NIF.String)) self.graph.add((context_id, RDF.type, NIF.RFC5147String)) self.graph.add((context_id, NIF.isString, Literal(self.zem_args['text']))) # Entity linking for n,k in enumerate(markup['links']): #first occurence of the entity start_index = self.zem_args['text'].find(k['anchor']) end_index = start_index + len(k['anchor']) if start_index < 1: msg = "Invalid entity start index." return generate_error_response(msg) entity_id = URIRef(doc_id+'#char=%i,%i' % (start_index, end_index)) self.graph.add((entity_id, RDF.type, NIF.String)) self.graph.add((entity_id, RDF.type, NIF.RFC5147String)) self.graph.add((entity_id, NIF.referenceContext, context_id)) self.graph.add((entity_id, NIF.beginIndex, Literal(start_index, datatype=XSD.int))) self.graph.add((entity_id, NIF.beginIndex, Literal(end_index, datatype = XSD.int))) self.graph.add((entity_id, NIF.anchorOf, Literal(k['anchor']))) self.graph.add((entity_id, ITSRDF.taConfidence, Literal(k['confidence'], datatype=XSD.float))) # entity types for entity_type in k.get("entity_type", []): self.graph.add((entity_id, ITSRDF.taClassRef, URIRef(FREEBASE.schema + entity_type))) # targets for target in k['target']: if target['type'] == 'rdf': self.graph.add((entity_id, ITSRDF.taIdentRef, URIRef(target['url']))) else: target_id = URIRef(target['url']) self.graph.add((entity_id, ITSRDF.taIdentRef, target_id)) self.graph.add((target_id, RDF.type, ZEM.target)) self.graph.add((target_id, ZEM.targetType, URIRef(ZEM_TARGETS + target['type']))) def create_document(self, doc_id, rid): #bindings self.graph.add((doc_id, RDF.type, ZEM.Document)) self.graph.add((doc_id, ZEM.text, Literal(self.zem_args['text']))) self.graph.add((doc_id, ZEM.rid, Literal(rid))) def create_articles(self, articles, doc_id): for n,a in enumerate(articles): article_id = URIRef('#Related%i' % (n+1)) self.graph.add((article_id, RDF.type, ZEM.Related)) self.graph.add((article_id, ZEM.doc, doc_id)) self.graph.add((article_id, ZEM.confidence, Literal(a['confidence'], datatype=XSD.float))) target_id = URIRef(a['url']) self.graph.add((article_id, ZEM.target, target_id)) self.graph.add((target_id, RDF.type, ZEM.Target)) self.graph.add((target_id, ZEM.targetType, ZEM_TARGETS.article)) self.graph.add((target_id, ZEM.article_id, Literal(a['article_id']))) self.graph.add((target_id, ZEM.published_datetime, Literal(a['published_datetime'], datatype=XSD.date))) self.graph.add((target_id, ZEM.title, Literal(a['title']))) self.graph.add((target_id, ZEM.zemified, Literal(a['zemified']))) self.graph.add((target_id, ZEM.text_preview, Literal(a['text_preview']))) self.graph.add((target_id, ZEM.retweets, Literal(a['retweets'], datatype=XSD.integer))) def create_images(self, images, doc_id): for n,a in enumerate(images): image_id = URIRef("#Image%i" % (n + 1)) self.graph.add((image_id, RDF.type, ZEM.Image)) self.graph.add((image_id, ZEM.doc, doc_id)) self.graph.add((image_id, ZEM.description, Literal(a['description']))) self.graph.add((image_id, ZEM.attribution, Literal(a['attribution']))) self.graph.add((image_id, ZEM.license_text, Literal(a['license']))) self.graph.add((image_id, ZEM.source_url, URIRef(a['source_url']))) self.graph.add((image_id, ZEM.confidence, Literal(a['confidence'], datatype=XSD.float))) self.graph.add((image_id, ZEM.url_s, URIRef(a['url_s']))) self.graph.add((image_id, ZEM.url_s_w, Literal(a['url_s_w']))) self.graph.add((image_id, ZEM.url_s_h, Literal(a['url_s_h']))) self.graph.add((image_id, ZEM.url_m, URIRef(a['url_m']))) self.graph.add((image_id, ZEM.url_m_w, Literal(a['url_m_w']))) self.graph.add((image_id, ZEM.url_m_h, Literal(a['url_m_h']))) self.graph.add((image_id, ZEM.url_m, URIRef(a['url_l']))) self.graph.add((image_id, ZEM.url_m_w, Literal(a['url_l_w']))) self.graph.add((image_id, ZEM.url_m_h, Literal(a['url_l_h']))) def create_keywords(self, keywords, doc_id): for n,k in enumerate(keywords): keyword_id = URIRef("#Keyword%i" % (n + 1)) self.graph.add((keyword_id, RDF.type, ZEM.Keyword)) self.graph.add((keyword_id, ZEM.doc, doc_id)) self.graph.add((keyword_id, ZEM.confidence, Literal(k['confidence'], datatype = XSD.float))) self.graph.add((keyword_id,ZEM.name, Literal(k['name']))) self.graph.add((keyword_id,ZEM.scheme, Literal(k['scheme']))) def create_categories(self, categories, doc_id): for n, c in enumerate(categories): category_id = URIRef("#Category %i" % (n + 1)) self.graph.add((category_id,RDF.type, ZEM.Category)) self.graph.add((category_id,ZEM.doc, doc_id)) self.graph.add((category_id,ZEM.confidence,Literal(c['confidence'], datatype = XSD.float))) self.graph.add((category_id,ZEM.name, Literal(c['name']))) self.graph.add((category_id,ZEM.categorization, Literal(c['categorization']))) def create_markup(self, markup, doc_id): for n,k in enumerate(markup['links']): link_id = URIRef("#Recognition%i" % (n+1)) self.graph.add((link_id, RDF.type, ZEM.Recognition)) self.graph.add((link_id, ZEM.doc, doc_id)) self.graph.add((link_id, ZEM.confidence, Literal(k['confidence'], datatype=XSD.float))) self.graph.add((link_id, ZEM.relevance, Literal(k['relevance'], datatype=XSD.float))) self.graph.add((link_id, ZEM.anchor, Literal(k['anchor']))) object_id = URIRef("#Object%i" % (n + 1)) self.graph.add((link_id, ZEM.object, object_id)) self.graph.add((object_id, RDF.type, ZEM.Object)) #entity types for entity_type in k.get("entity_type", []): self.graph.add((object_id, ZEM.entity_type, URIRef(FREEBASE.schema + entity_type))) # targets for target in k['target']: if target['type'] == 'rdf': self.graph.add((object_id, OWL.sameAs, URIRef(target['url']))) target_id = URIRef(target['url']) self.graph.add((object_id, ZEM.target, target_id)) self.graph.add((target_id, RDF.type, ZEM.target)) self.graph.add((target_id, ZEM.title, Literal(target['title']))) self.graph.add((target_id, ZEM.targetType, URIRef(ZEM_TARGETS + target['type']))) def generate_error_response(self, msg): ERROR = Namespace("http://nlp2rdf.lod2.eu/schema/error/") e_graph = Graph() e_graph.bind('error', ERROR) error = URIRef(ERROR.Error) e_graph.add((error, ERROR.fatal, Literal(1))) e_graph.add((error, ERROR.hasMessage, Literal(msg))) return e_graph.serialize(format=self.format, encoding="utf-8") def make_zem_api_request(self): gateway = 'http://api.zemanta.com/services/rest/0.0/' args_enc = urllib.urlencode(self.zem_args) raw_output = urllib.urlopen(gateway, args_enc).read() if self.isGraph == False: return raw_output output = json.loads(raw_output) if 'status' in output and output['status'] == 'ok': return output else: msg = "Error calling Zemanta API." return self.generate_error_response(msg) def get_info(self): info = Graph() NS0 = Namespace("http://usefulinc.com/ns/doap#") NS1 = Namespace("http://nlp2rdf.org/") wrapper_id = URIRef(NS1 + 'implementations/zemanta') BASE = Namespace(wrapper_id) info.bind("rdf", RDF) info.bind("ns0", NS0) info.bind("ns1", NS1) content = "NIF wrapper for Zemanta API." info.add((wrapper_id, NS0.homepage, URIRef("http://www.zemanta.com"))) info.add((wrapper_id, NS1.additionalparameter, Literal("You need Zemanta API key. For other parameters check Zemanta API documentation."))) info.add((wrapper_id, NS1.status, Literal("NIF 2.0 compliant without RDF/XML input and JSON output"))) info.add((wrapper_id, NS1.webserviceurl, Literal(" - Add URL here - "))) info.add((wrapper_id, NS1.demo, Literal(" - Add URL here - "))) info.add((wrapper_id, NS1.code, URIRef("https://github.com/sparkica/zem-api-wrapper"))) return info.serialize(format=self.format, encoding="utf-8")
[ "mateja.verlic@gmail.com" ]
mateja.verlic@gmail.com