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
7ae4c1888b01980193aa49fb4a43d3018126d1dd
0f60645e9939fa0653f0c7e15002881489b757df
/urls.py
9345225fbaadd9558ca114b5be52a3e628b2936c
[]
no_license
0sn/nameremoved
bbae43091ca4459d6dd8219b1e0837b8feaf58f7
879a5644a7cd2ee74f9b3b8a42d9ae649eb43804
refs/heads/master
2020-06-04T15:13:29.521645
2011-05-13T04:48:03
2011-05-13T04:48:03
118,075
2
1
null
null
null
null
UTF-8
Python
false
false
3,036
py
from django.conf.urls.defaults import * from django.conf import settings from django.http import HttpResponsePermanentRedirect, HttpResponseGone, HttpResponse from nr_comics.feeds import LatestEntries from sitemap import sitemap from django.contrib import admin admin.autodiscover() from nr_linkmanager.context import navigation navigation.linkregistry.register_static("/","Home") navigation.linkregistry.register_static("/comics/", "Archive") navigation.linkregistry.register_static("/storylines/", "Storylines") navigation.linkregistry.register_static("/contribute/", "Contribute") navigation.autodiscover() def old_feed(request): """People should use the feedburner url for their feeds.""" return HttpResponsePermanentRedirect("http://feeds.feedburner.com/NameRemoved") urlpatterns = patterns('', (r'^$', 'nr_comics.views.index'), (r'^comics/', include('nr_comics.urls')), (r'^contribute/', include('nr_contributions.urls')), (r'^storylines/', include('nr_storylines.urls')), (r'^feeds/latest/$', old_feed), (r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': {'feedburner': LatestEntries}}), (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemap}), (r'^admin/nr_contributions/report/$', 'nr_contributions.views.report'), (r'^admin/memcache/$', 'nr_utils.mstat.view'), (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/(.*)', admin.site.root), ) # redirects for old urls def no_extra(request, rest_of_path): """used to have 'extra' objects instead of flatpages!""" return HttpResponsePermanentRedirect(rest_of_path) def old_index(request): """sends everyone with the old bad php comic app url to the front page""" return HttpResponsePermanentRedirect("/") def favicon(request): """the favicon lives on the static server""" return HttpResponsePermanentRedirect("http://static.nameremoved.com/favicon.ico") def movedpics(request, rest_of_path): """the old pics directory lives on the static server""" return HttpResponsePermanentRedirect("http://static.nameremoved.com/pix" + rest_of_path) def randomimage(request): """the random images aren't around any more""" return HttpResponseGone() def robots(request): """Don't try adding a closing / to the robots.txt request.""" return HttpResponse("") urlpatterns += patterns('', (r'^extra(/.*)', no_extra), (r'^feed/rss.xml$', old_feed), (r'^index.php', old_index), (r'^favicon\.ico', favicon), (r'^pix(/.*)', movedpics), (r'^randomimage/.*', randomimage), (r'^robots.txt$', robots), ) # static serving for debug mode if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }), (r'^comic_files/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT + 'comic_files'}), )
[ "github@nickwolfe.ca" ]
github@nickwolfe.ca
4886fa758195ab52c63d607d1fea0b3841c51fbc
ced95de5c2498b9fe12aab6b35afd2f41f7e01ec
/components/dialog-acts/src/textability/dialog_acts/nlp/negations.py
a6ee05c4f4f496fff007bcf63ac0e9d8e220087b
[]
no_license
schutza/textability-nlp
f76a32fb0895a79239334aa931d56bb7a90a90c3
75f0d7144e5c2eb3e26fa41d925bf10f59df548a
refs/heads/master
2021-03-10T04:46:18.084928
2020-03-10T23:23:47
2020-03-10T23:23:47
246,420,256
0
0
null
2020-08-30T10:50:02
2020-03-10T22:20:41
Python
UTF-8
Python
false
false
1,702
py
from spacy.matcher import Matcher from spacy.matcher import PhraseMatcher from textability.dialog_acts.base_detectors import DialogActDetector from textability.dialog_acts.nlp.language_processor import NLP negation_outright_pattern = [ {"LOWER": {"IN": ["no", "nah", "nay", "ney", "nope", "never", "incorrect"]}} ] negation_then_affirmation_pattern = [ {"DEP": {"IN": ["neg", "advmod"]}}, {"LOWER": {"IN": ["right", "correct", "true"]}} ] affirmation_then_negation_pattern = [ {"LOWER": {"IN": ["absolutely", "certainly", "definitely"]}}, {"LOWER": "not"} ] patterns = [ negation_outright_pattern, negation_then_affirmation_pattern, affirmation_then_negation_pattern ] negation_phrases = [ "not what I said" ] class SpacyNegationDetector(DialogActDetector): def __init__(self): self._nlp = NLP.get('en') self._phrase_matcher = PhraseMatcher(self._nlp.vocab, attr="LOWER") negation_phrase_patterns = [self._nlp.make_doc(text) for text in negation_phrases] self._phrase_matcher.add("AffirmationPhrases", None, *negation_phrase_patterns) self._matcher = Matcher(self._nlp.vocab) self._matcher.add("Negation", None, *patterns) def detect(self, text, language='en'): doc = self._nlp(text) phrase_matches = self._phrase_matcher(doc) if phrase_matches: (match_id, start, end) = phrase_matches[0] span = doc[start:end] return True, span.text matches = self._matcher(doc) if matches: (match_id, start, end) = matches[0] span = doc[start:end] return True, span.text return False, None
[ "alexander.schutz@textability.com" ]
alexander.schutz@textability.com
917d05bbe6e04eb8e4e580a3bfbc314c8747db4b
fb1a11419934d0c91dcf59a961a8cba207b1224f
/entorno1/bin/easy_install-2.7
9cac5a60cf6034e04ad4d48689c7f95b02ec079d
[]
no_license
danodine/Clase_6
e9028893be3d4e3ed7b6dbf1f0c8471047e8b009
5274fc437ef92485fa1daabc197bb3f091b871fa
refs/heads/master
2020-12-24T06:16:51.859681
2016-11-11T15:31:38
2016-11-11T15:31:38
73,481,953
0
0
null
null
null
null
UTF-8
Python
false
false
260
7
#!/home/salae/misentornos/entorno1/bin/python # -*- coding: utf-8 -*- import re import sys from setuptools.command.easy_install import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "davidnodine@gmail.com" ]
davidnodine@gmail.com
d99e95002c2eb33b94698179ff532f256977809a
b7681e5cb6b5b919aa8fe2fb21e3cf267eeca840
/A3/constants.py
d7850fc17f95a113ae8242925f7de179178c232c
[]
no_license
chloe-glave/comp1510-assignments
4ea568e91f440ff326488ee0fe72652ae628c74e
928605581914d20c71c7219a556d1c9a9ab05e1d
refs/heads/master
2022-04-02T22:34:11.996495
2019-12-07T02:47:27
2019-12-07T02:47:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,913
py
""" File containing all constants in the SUD. Room descriptions credit: Matthew Sernett, wizards.com """ # monster info to pull from MONSTER_TYPES = ['dragon', 'goblin', 'ghost', 'slime', 'vampire', 'gelatinous cube', 'slaad', 'zombie', 'banshee'] MONSTER_DESCRIPTIONS = ['horrible', 'dark', 'terrifying', 'deadly', 'pale', 'wicked', 'flying', 'sinister'] # a matrix, a list containing lists containing dicts with room info GAME_BOARD = [ # first row - [0][0] through [0][4] [{"description": "A large forge squats against the far wall of this room, and coals glow dimly inside. " "Before the forge stands a wide block of iron with a heavy-looking hammer lying atop it, no doubt " "for use in pounding out shapes in hot metal. Other forge tools hang in racks nearby, and a " "barrel of water and bellows rest on the floor nearby."}, {"description": "This small room contains several pieces of well-polished wood furniture. Eight ornate, " "high-backed chairs surround a long oval table, and a side table stands next to the far exit. All " "bear delicate carvings of various shapes. One bears carvings of skulls and bones, another is " "carved with shields and magic circles, and a third is carved with shapes like " "flames and lightning strokes."}, {"description": "This otherwise bare room has one distinguishing feature. The stone around one of the other doors " "has been pulled over its edges, as though the rock were as soft as clay and could be moved with " "fingers. The stone of the door and wall seems hastily molded together."}, {"description": "This chamber served as an armory for some group of creatures. Armor and weapon racks line the " "walls and rusty and broken weapons litter the floor. It hasn't been used in a long time, and " "all the useful weapons have been taken but for a single sword. Unlike the other weapons in the " "room, this one gleams untarnished in the light."}, {"description": "Huge rusted metal blades jut out of cracks in the walls, and rusting spikes project down from " "the ceiling almost to the floor. This room may have once been trapped heavily, but someone " "triggered them, apparently without getting killed. The traps were never reset and now " "seem rusted in place."}], # second row - [1][0] through [1][4] [{"description": "The strong, sour-sweet scent of vinegar assaults your nose as you enter this room. Sundered casks" " and broken bottle glass line the walls of this room. Clearly this was someone's wine cellar for " "a time. The shards of glass are somewhat dusty, and the spilled wine is nothing more than a " "sticky residue in some places. Only one small barrel remains unbroken amid the rubbish."}, {"description": "Several white marble busts that rest on white pillars dominate this room. Most appear to be male " "or female humans of middle age, but one clearly bears small horns projecting from its forehead " "and another is spread across the floor in a thousand pieces, leaving one pillar empty."}, {"description": "A crack in the ceiling above the middle of the north wall allows a trickle of water to flow down " "to the floor. The water pools near the base of the wall, and a rivulet runs along the wall an " "out into the hall. The water smells fresh."}, {"description": "Thick cobwebs fill the corners of the room, and wisps of webbing hang from the ceiling and waver " "in a wind you can barely feel. One corner of the ceiling has a particularly large clot of " "webbing within which a goblin's bones are tangled."}, {"description": "A liquid-filled pit extends to every wall of this chamber. The liquid lies about 10 feet below " "your feet and is so murky that you can't see its bottom. The room smells sour. A rope bridge " "extends from your door to the room's other exit."}], # third row - [2][0] through [2][4] [{"description": "Fire crackles and pops in a small cooking fire set in the center of the room. The smoke from a " "burning rat on a spit curls up through a hole in the ceiling. Around the fire lie several fur " "blankets and a bag. It looks like someone camped here until not long ago, " "but then left in a hurry."}, {"description": "A flurry of bats suddenly flaps through the doorway, their screeching barely audible as they " "careen past your heads. They flap past you into the rooms and halls beyond. The room " "from which they came seems barren at first glance."}, {"description": "Rusting spikes line the walls and ceiling of this chamber. The dusty floor shows no sign that " "the walls move over it, but you can see the skeleton of some humanoid impaled on some " "wall spikes nearby."}, {"description": "You gaze into the room and hundreds of skulls gaze coldly back at you. They're set in niches " "in the walls in a checkerboard pattern, each skull bearing a half-melted candle on its head. " "The grinning bones stare vacantly into the room, which otherwise seems empty."}, {"description": "Unlike the flagstone common throughout the dungeon, this room is walled and floored with black " "marble veined with white. The ceiling is similarly marbled, but the thick pillars " "that hold it up are white. A brown stain drips down one side of a nearby pillar."}], # fourth row - [3][0] through [3][4] [{"description": "This room is hung with hundreds of dusty tapestries. All show signs of wear: moth holes, " "scorch marks, dark stains, and the damage of years of neglect. They hang on all the walls and " "hang from the ceiling to brush against the floor, blocking your view of the rest of the room."}, {"description": "Three low, oblong piles of rubble lie near the center of this small room. Each has a weapon " "jutting upright from one end -- a longsword, a spear, and a quarterstaff. " "The piles resemble cairns used to bury dead adventurers."}, {"description": "Huge rusted metal blades jut out of cracks in the walls, and rusting spikes project down from " "the ceiling almost to the floor. This room may have once been trapped heavily, but someone " "triggered them, apparently without getting killed. " "The traps were never reset and now seem rusted in place."}, {"description": "Many doors fill the room ahead. Doors of varied shape, size, and design are set in every wall " "and even the ceiling and floor. Barely a hand's width lies between one door and the next. " "All the doors but the one you entered by are shut, and many have obvious locks."}, {"description": "A strange ceiling is the focal point of the room before you. It's honeycombed with hundreds of " "holes about as wide as your head. They seem to penetrate the ceiling to some height beyond a " "couple feet, but you can't be sure from your vantage point."}], # fifth row - [4][0] through [4][4] [{"description": "This chamber was clearly smaller at one time, but something knocked down the wall that separated " "it from an adjacent room. Looking into that space, you see signs of another wall knocked over. " "It doesn't appear that anyone made an effort to clean up the rubble, but some paths through " "see more usage than others."}, {"description": "You pull open the door and hear the scrape of its opening echo throughout what must be a massive " "room. Peering inside, you see a vast cavern. Stalactites drip down from the ceiling in sharp " "points while flowstone makes strange shapes on the floor."}, {"description": "Many small desks with high-backed chairs stand in three long rows in this room. Each desk has " "an inkwell, book stand, and a partially melted candle in a rusting tin candleholder. " "Everything is covered with dust."}, {"description": "You open the door and before you is a dragon's hoard of treasure. Coins cover every inch of " "the room, and jeweled objects of precious metal jut up from the money like glittering islands " "in a sea of gold."}, # treasure room {"description": "In the center of this large room lies a 30-foot-wide round pit, its edges lined with rusting " "iron spikes. About 5 feet away from the pit's edge stand several stone semicircular benches. " "The scent of sweat and blood lingers, which makes the pit's resemblance to a " "fighting pit or gladiatorial arena even stronger."} ] ] VICTORY_ROOM = [4, 3] # character description PLAYER = {'name': 'Alberto the Mighty', 'description': 'An intrepid traveller seeking the riches of this dungeon.', 'goal': 'To find the treasure hidden within this maze of twisty tunnels', 'HP': 10, 'max_HP': 10, 'hit_die': 6} # display DIVIDING_LINE = '\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'
[ "cragzu@gmail.com" ]
cragzu@gmail.com
642970365fed7bfc8cbf093fa7c039f2dabdf121
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_4_2/xenosoz.here/B.py
f9e220dfa29b3b7d75a9504d7711ce8867464aa9
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
1,203
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Google Code Jam: Round 2 2016 # Problem B. Red Tape Committee # # by xenosoz on May 28, 2016. # from collections import defaultdict def combine_prob(_A, _B): X = defaultdict(float) A = _A[1] B = _B[1] M = 0 for a, pa in A.items(): for b, pb in B.items(): X[a + b] += pa * pb for x, px in X.items(): M = max(M, px) return (M, X) def make_prob(p): return (max(p, 1-p), {1: p, -1: (1-p)}) def unit_prob(): return (1, {0: 1}) from itertools import combinations def solve(N, K, Probs): best_p = 0 best_P = None for S in combinations(Probs, K): P = unit_prob() for p in S: P = combine_prob(P, make_prob(p)) if P[0] < best_p: break if P[1][0] >= best_p: best_p = P[1][0] best_P = P return best_P[1][0] def main(): T = int(input()) for case_id in range(1, T+1): N, K = map(int, input().split()) Probs = list(map(float, input().split())) print("Case #%d: %.8f" % (case_id, solve(N, K, Probs))) if __name__ == '__main__': main()
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
2806759db5d7067e3121d5daa205116da8119514
c910ba6315f9a92f7810f4df718b31bf41049286
/binLabels/qrprint.py
5819d375e4f15ed581a7759cf51a6cb12cdbbf20
[]
no_license
robzach/partsPages
e4c1b851ca0a83f2f9fc73fd83b308e9f89ebe2c
7c710eea2b2c5541aed5111582d42775eee5644a
refs/heads/master
2021-01-01T06:51:59.590032
2017-10-06T16:09:23
2017-10-06T16:09:23
97,533,919
0
0
null
null
null
null
UTF-8
Python
false
false
251
py
import pyqrcode import pypng text = pyqrcode.create('example') print(text.text()) print('\n') print(text.terminal()) ##print(text.terminal(module_color='red', background='yellow')) ##print(text.terminal(module_color=5, background=123, quiet_zone=1))
[ "bobby.zacharias@gmail.com" ]
bobby.zacharias@gmail.com
0fa7779d3cfa1ede6127305e69fd4edf9722c05a
bc137234505aa010cd4bd666358ee45a73a4e448
/manage.py
a6a3fdf19660f41e013d568aa5ead8f366de71e0
[]
no_license
szk128/sjtusite1
6b1891d133566242f8398e5168a3c0569004879a
84a2da9598c995ba4eca857097be78a68783f8f4
refs/heads/master
2022-06-22T15:03:11.546402
2020-05-11T02:44:11
2020-05-11T02:44:11
262,926,355
0
0
null
null
null
null
UTF-8
Python
false
false
720
py
#!/usr/bin/env python """ Command-line utility for administrative tasks. # For more information about this file, visit # https://docs.djangoproject.com/en/2.1/ref/django-admin/ """ import os import sys if __name__ == '__main__': os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'sjtusite1.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
[ "1360059346@qq.com" ]
1360059346@qq.com
44badcc169b52b983e5ac2197685ea49cf114a73
d37ba86275573dfcb8aded9f98041a6bc159436a
/manage.py
7316da0ee3334f8af921b35080af72aa1c9b6c31
[]
no_license
AnotherGuyver/SVGTutorien
5fbcf8cc1e163a17b66356f07861f0dfd9be63de
3e2c18b4def9413f78c24cda430cf8fa6b5b19a5
refs/heads/master
2020-12-06T19:17:06.381715
2013-11-13T13:28:29
2013-11-13T13:28:29
14,364,459
0
0
null
null
null
null
UTF-8
Python
false
false
250
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SVGTuts.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "neptunslawa@googlemail.com" ]
neptunslawa@googlemail.com
df57a79e6d386f716fd8c2b2ab84072da2757d6b
3d0645021735b8cbd5f8ad680dea14305cc538bc
/leveltwo/database/init/insert_levels.py
0df752c48427bc0799fa72e1383346532f384abe
[ "MIT" ]
permissive
LilianBoulard/LevelTwo
2d858616392f058ca6e7be2131bab8f5437d21eb
23013a53100875d77dfae99494d2ef415d12b0df
refs/heads/main
2023-05-03T23:51:42.944850
2021-05-27T22:51:21
2021-05-27T22:51:21
350,278,019
1
0
MIT
2021-04-06T08:34:20
2021-03-22T09:12:16
Python
UTF-8
Python
false
false
237
py
""" Inserts an example level into the database. """ from .default_levels import all_levels def insert_levels(db) -> None: with db.init_session() as session: for level in all_levels: session.add(level.to_dbo())
[ "lilian@boulard.fr" ]
lilian@boulard.fr
e9ac33b4e7ffb25caa4573bac8232f73c0cdafe0
33665bd85fe8b14aac8effc6a37044b7ebd015ec
/keywordextract.py
eedb4ff07b21d2e01fab502cd0c2c2687f220fb3
[]
no_license
pigliangliang/nlp_coding
90e898994fa9fd439841fecd8653024a7bfe1036
3c7028569efd03d3d0d8c9b7da72d41aa2577423
refs/heads/master
2020-03-22T15:07:12.919961
2018-09-05T02:47:15
2018-09-05T02:47:15
140,230,177
1
0
null
null
null
null
UTF-8
Python
false
false
9,637
py
#author_by zhuxiaoliang #2018-07-18 下午4:35 import math import jieba import jieba.posseg as psg from gensim import corpora, models from jieba import analyse import functools # 停用词表加载方法 def get_stopword_list(): # 停用词表存储路径,每一行为一个词,按行读取进行加载 # 进行编码转换确保匹配准确率 stop_word_path = 'data/stopword' stopword_list = [sw.replace('\n', '') for sw in open(stop_word_path).readlines()] return stopword_list def seg_to_list(sentence,pos=False): if not pos: #不进行词性标注的分词方法 seg_list = jieba.cut(sentence) else: #进行词性标注的分词方法 seg_list = psg.cut(sentence) return seg_list #去除干扰词 def word_filter(seg_list,pos = False): stopword_list = get_stopword_list() filter_list = [] for seg in seg_list: if not pos: word = seg flag = 'n' else: word= seg.word flag = seg.flag if not flag.startswith('n'): continue #过滤停用词和长度小于2的词 if not word in stopword_list and len(word)>1: filter_list.append(word) return filter_list #加载语料库 def load_data(pos=False,corpus_path='data/corpus'): doc_list = [] for line in open(corpus_path,'r'): content = line.strip() seg_list = seg_to_list(content,pos) filer_list = word_filter(seg_list) doc_list.append(filer_list) return doc_list #idf def train_idf(doc_list): idf_dic ={} #总文档数 tt_count= len(doc_list) #每个词出现的文档数 for doc in doc_list: for word in set(doc): idf_dic[word] = idf_dic.get(word,0.0)+1.0 #按照公式转换为idf值 for k,v in idf_dic.items(): idf_dic[k]=math.log(tt_count/(1.0+v)) #对于没有在字典中的词,默认其仅在一个文档中出现 default_idf=math.log(tt_count/1.0) return idf_dic,default_idf # 排序函数,用于topK关键词的按值排序 def cmp(e1, e2): import numpy as np res = np.sign(e1[1] - e2[1]) if res != 0: return res else: a = e1[0] + e2[0] b = e2[0] + e1[0] if a > b: return 1 elif a == b: return 0 else: return -1 # TF-IDF类 class TfIdf(object): # 四个参数分别是:训练好的idf字典,默认idf值,处理后的待提取文本,关键词数量 def __init__(self, idf_dic, default_idf, word_list, keyword_num): self.word_list = word_list self.idf_dic, self.default_idf = idf_dic, default_idf self.tf_dic = self.get_tf_dic() self.keyword_num = keyword_num # 统计tf值 def get_tf_dic(self): tf_dic = {} for word in self.word_list: tf_dic[word] = tf_dic.get(word, 0.0) + 1.0 tt_count = len(self.word_list) for k, v in tf_dic.items(): tf_dic[k] = float(v) / tt_count return tf_dic # 按公式计算tf-idf def get_tfidf(self): tfidf_dic = {} for word in self.word_list: idf = self.idf_dic.get(word, self.default_idf) tf = self.tf_dic.get(word, 0) tfidf = tf * idf tfidf_dic[word] = tfidf tfidf_dic.items() # 根据tf-idf排序,去排名前keyword_num的词作为关键词 for k, v in sorted(tfidf_dic.items(), key=functools.cmp_to_key(cmp), reverse=True)[:self.keyword_num]: print(k + "/ ", end='') print() def tfidf_extract(word_list, pos=False, keyword_num=10): doc_list = load_data(pos) idf_dic, default_idf = train_idf(doc_list) tfidf_model = TfIdf(idf_dic, default_idf, word_list, keyword_num) tfidf_model.get_tfidf() ''' if __name__ == '__main__': text = '6月19日,《2012年度“中国爱心城市”公益活动新闻发布会》在京举行。' + \ '中华社会救助基金会理事长许嘉璐到会讲话。基金会高级顾问朱发忠,全国老龄' + \ '办副主任朱勇,民政部社会救助司助理巡视员周萍,中华社会救助基金会副理事长耿志远,' + \ '重庆市民政局巡视员谭明政。晋江市人大常委会主任陈健倩,以及10余个省、市、自治区民政局' + \ '领导及四十多家媒体参加了发布会。中华社会救助基金会秘书长时正新介绍本年度“中国爱心城' + \ '市”公益活动将以“爱心城市宣传、孤老关爱救助项目及第二届中国爱心城市大会”为主要内容,重庆市' + \ '、呼和浩特市、长沙市、太原市、蚌埠市、南昌市、汕头市、沧州市、晋江市及遵化市将会积极参加' + \ '这一公益活动。中国雅虎副总编张银生和凤凰网城市频道总监赵耀分别以各自媒体优势介绍了活动' + \ '的宣传方案。会上,中华社会救助基金会与“第二届中国爱心城市大会”承办方晋江市签约,许嘉璐理' + \ '事长接受晋江市参与“百万孤老关爱行动”向国家重点扶贫地区捐赠的价值400万元的款物。晋江市人大' + \ '常委会主任陈健倩介绍了大会的筹备情况。' pos = True seg_list = seg_to_list(text, pos) filter_list = word_filter(seg_list, pos) print('TF-IDF模型结果:') tfidf_extract(filter_list) ''' def textrank_extract(text, pos=False, keyword_num=10): textrank = analyse.textrank keywords = textrank(text, keyword_num) # 输出抽取出的关键词 for keyword in keywords: print(keyword + "/ ", end='') print() text = '6月19日,《2012年度“中国爱心城市”公益活动新闻发布会》在京举行。' + \ '中华社会救助基金会理事长许嘉璐到会讲话。基金会高级顾问朱发忠,全国老龄' + \ '办副主任朱勇,民政部社会救助司助理巡视员周萍,中华社会救助基金会副理事长耿志远,' + \ '重庆市民政局巡视员谭明政。晋江市人大常委会主任陈健倩,以及10余个省、市、自治区民政局' + \ '领导及四十多家媒体参加了发布会。中华社会救助基金会秘书长时正新介绍本年度“中国爱心城' + \ '市”公益活动将以“爱心城市宣传、孤老关爱救助项目及第二届中国爱心城市大会”为主要内容,重庆市' + \ '、呼和浩特市、长沙市、太原市、蚌埠市、南昌市、汕头市、沧州市、晋江市及遵化市将会积极参加' + \ '这一公益活动。中国雅虎副总编张银生和凤凰网城市频道总监赵耀分别以各自媒体优势介绍了活动' + \ '的宣传方案。会上,中华社会救助基金会与“第二届中国爱心城市大会”承办方晋江市签约,许嘉璐理' + \ '事长接受晋江市参与“百万孤老关爱行动”向国家重点扶贫地区捐赠的价值400万元的款物。晋江市人大' + \ '常委会主任陈健倩介绍了大会的筹备情况。' textrank_extract(text,pos=False,keyword_num=10) class TopicModel(object): def __init__(self,doc_list,keyword_num,model='LSI',num_topics=4): self.dictionary = corpora.Dictionary(doc_list) corpus = [self.dictionary.doc2bow(doc) for doc in doc_list] self.tfidf_model = models.TfidfModel(corpus) self.corpus_tfidf = self.tfidf_model[corpus] self.keyword_num = keyword_num self.num_topics = num_topics if model =='LSI': self.model = self.train_lsi() else: self.model = self.train_lda() word_dic = self.word_dictionary(doc_list) self.wordtopic_dic = self.get_wordtopic(word_dic) def train_lsi(self): lsi = models.LsiModel(self.corpus_tfidf,id2word=self.dictionary,num_topics=self.num_topics) return lsi def train_lda(self): lda = models.LdaModel(self.corpus_tfidf,id2word=self.dictionary,num_topics=self.num_topics) return lda def get_wordtopic(self,word_dic): wordtopic_dic ={} for word in word_dic: single_list = [word] wordcorpus = self.tfidf_model[self.dictionary.doc2bow(single_list)] wordtopic = self.model[wordcorpus] wordtopic_dic[word] = wordtopic return wordtopic_dic # 计算词的分布和文档的分布的相似度,取相似度最高的keyword_num个词作为关键词 def get_simword(self, word_list): sentcorpus = self.tfidf_model[self.dictionary.doc2bow(word_list)] senttopic = self.model[sentcorpus] # 余弦相似度计算 def calsim(l1, l2): a, b, c = 0.0, 0.0, 0.0 for t1, t2 in zip(l1, l2): x1 = t1[1] x2 = t2[1] a += x1 * x1 b += x1 * x1 c += x2 * x2 sim = a / math.sqrt(b * c) if not (b * c) == 0.0 else 0.0 return sim # 计算输入文本和每个词的主题分布相似度 sim_dic = {} for k, v in self.wordtopic_dic.items(): if k not in word_list: continue sim = calsim(v, senttopic) sim_dic[k] = sim for k, v in sorted(sim_dic.items(), key=functools.cmp_to_key(cmp), reverse=True)[:self.keyword_num]: print(k + "/ ", end='') print()
[ "836904717@qq.com" ]
836904717@qq.com
d823a78a75fcad633609e97c3ad3610c05e553e5
e2543581bb705e2f56dd7e0910fa8dc2a9eabae2
/utils.py
800b23385d79e13c0a335a3f45d762505d1928de
[]
no_license
rodo/calorine
41bd00b8604eb16e764246a4d7f29fdf26c49161
4919242b0f2442007b50d1ef602a2df6d414a6c6
refs/heads/master
2021-01-19T07:57:16.804274
2015-01-12T21:09:52
2015-01-12T21:09:52
7,069,027
1
0
null
2012-12-18T14:59:06
2012-12-08T15:46:59
Python
UTF-8
Python
false
false
2,538
py
# -*- coding: utf-8 -*- # # Copyright (c) 2012 Rodolphe Quiédeville <rodolphe@quiedeville.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import socket import os, os.path import syslog import hashlib import mutagen def strtag(fname): """Return a string based on ID3 tags """ muts = mutagen.File(fname, easy=True) return strdetag(muts) def strdetag(muts): """Return a string based on ID3 tags """ datas = {} fields = ['album', 'artist', 'title', 'genre', 'date', 'tracknumber'] for fld in fields: if not muts.has_key(fld): datas[fld] = '' else: data = muts[fld] datas[fld] = data[0] return "%s - %s (%s)" % (datas['artist'], datas['title'], datas['album']) def trigger(fname, socket_fname=None): if socket_fname is None: socket_fname = "/tmp/python_unix_sockets_example" connected = False if os.path.exists(socket_fname): client = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM ) try: client.connect(socket_fname) connected = True except socket.error: syslog.syslog("Couldn't Connect to %s " % socket_fname) if connected: try: client.send( "On AIR : %s" % strtag(fname)) except: syslog.syslog("can't send data on %s " % socket_fname) client.close() else: syslog.syslog("socket does not exists %s " % socket_fname) def hashfile(filepath): """ Calculate the sha1 value of a file """ sha1 = hashlib.sha1() f = open(filepath, 'rb') try: sha1.update(f.read()) finally: f.close() return sha1.hexdigest() def extract_command(line): """ Extract the command from a message on irc """ datas = line.split(':') command = datas[1].strip() return command
[ "rodolphe@quiedeville.org" ]
rodolphe@quiedeville.org
b5ef6871304dd2f465b2110219d0e8e378f85877
f15df8f7ebdb77ca4ad2525e51b3259195bdf01b
/econ/common_services/models.py
23d1dbf31aa9d72ea10f7455f09bc25ec2f9cfb0
[]
no_license
naveenmotpuse/knanalytics
474d74ed4699655a3801f4254a307cf86dfe36ff
e355927950545c810aa3eab35309d7c41f1ccf65
refs/heads/master
2020-03-28T17:00:11.683442
2018-09-26T06:22:15
2018-09-26T06:22:15
148,749,278
0
0
null
null
null
null
UTF-8
Python
false
false
14,519
py
''' Created on 15-Apr-2016 @author: naveen@knowdl.com ''' #from _mysql import NULL #import new ''' Updated on 06-Feb-2017 @author: naveen@knowdl.com Note: Updated to track Qualsim attempt data. ''' from django.utils.deconstruct import deconstructible import requests import json from django.conf import settings from django.db import models from datetime import datetime import decimal from gldata.models import SessionData from django.db import connection @deconstructible class FredOperations(object): @classmethod def fetchFredData(cls): for frq in cls.frequency_array: url_base = settings.FRED_API_BASE_URL + '&series_id=%s&frequency=%s&units=%s' % (cls.series_id, frq, cls.units) response = requests.get(url_base, stream=True) if response.json().get('observations'): cls.objects.filter(freq=frq).delete() object_list = [cls(observation_date=datetime.strptime(item.get('date'), "%Y-%m-%d"), observation_value=decimal.Decimal(item.get('value')), freq=frq, ) for item in response.json().get('observations') if item.get('value') != '.'] cls.objects.bulk_create(object_list) @classmethod def getFredData(cls, start_date=None, end_date=None, frequency="m"): if not start_date: start_date = cls.default_start_date if not end_date: end_date = datetime.today().strftime("%Y-%m-%d") return cls.objects.values_list('observation_date', 'observation_value').filter(observation_date__range=[start_date, end_date], freq=frequency) class FredUSRegConGasPrice(models.Model, FredOperations): observation_date = models.DateField(db_index=True) observation_value = models.DecimalField(max_digits=10, decimal_places=3) freq = models.CharField(max_length=50) class Meta: unique_together = (('observation_date', 'observation_value', 'freq'),) observation_type = "US Regular Conventional Gas Price" #frequency = "m","q","sa","a" frequency = "m" series_id = "GASREGCOVW" units = "lin" default_start_date = "1991-01-01" frequency_array = ["m", "q", "sa", "a"] class FredUSRegAllFormGasPrice(models.Model, FredOperations): observation_date = models.DateField(db_index=True) observation_value = models.DecimalField(max_digits=10, decimal_places=3) freq = models.CharField(max_length=50) class Meta: unique_together = (('observation_date', 'observation_value', 'freq'),) observation_type = "US Regular All Formulations Gas Price" #frequency = "m","q","sa","a" frequency = "m" series_id = "GASREGW" units = "lin" default_start_date = "1991-01-01" frequency_array = ["m", "q", "sa", "a"] class FredCrudeOilPrices(models.Model, FredOperations): observation_date = models.DateField(db_index=True) observation_value = models.DecimalField(max_digits=10, decimal_places=3) freq = models.CharField(max_length=50) class Meta: unique_together = (('observation_date', 'observation_value', 'freq'),) observation_type = "Crude Oil Prices: West Texas Intermediate (WTI) - Cushing, Oklahoma" #frequency = "m","q","sa","a" frequency = "m" series_id = "DCOILWTICO" units = "lin" default_start_date = "1991-01-01" frequency_array = ["m", "q", "sa", "a"] class QLAssignmentAdditionalDetails(models.Model): QL_Id = models.CharField(max_length=200,db_index=True) Assignment_Id = models.CharField(max_length=200,db_index=True) AssignmentLocation = models.CharField(max_length=200) TotalScore = models.DecimalField(max_digits=10, decimal_places=3) TotalUsers = models.IntegerField(default=0) Id = models.IntegerField(primary_key=True) ''' @classmethod def getClassAverageScore(cls, qlid, asgnid, maxscore, score): sql_query = """SELECT QL_Id, Assignment_Id, TotalScore FROM common_services_qlassignmentadditionaldetails WHERE QL_Id=%s and Assignment_Id=%s""" adddetails = cls.objects.raw(sql_query, [qlid, asgnid]) if(sum(1 for result in adddetails) > 0): if(score!=-1): # user had better score or its first attempt if(maxscore==-1): #Update score and user count -- user's first attempt. sql_updatequery = """UPDATE common_services_qlassignmentadditionaldetails SET TotalScore = (TotalScore + %s), TotalUsers = (TotalUsers + %s) WHERE QL_Id=%s and Assignment_Id=%s""" cursor.execute( sql_updatequery, (score, 1, qlid, asgnid)) else: #update score different only -- user's next attempt with better score sql_updatequery = """UPDATE common_services_qlassignmentadditionaldetails SET TotalScore = (TotalScore + %s) WHERE QL_Id=%s and Assignment_Id=%s""" cursor.execute( sql_updatequery, (score, qlid, asgnid)) else: #Insert New Record sql_insertcommand = """INSERT INTO common_services_qlassignmentadditionaldetails (QL_Id, Assignment_Id, AssignmentLocation, TotalScore, TotalUsers) VALUES (%s, %s, %s, %s, %s)""" with connection.cursor() as cursor: cursor.execute(sql_insertcommand, (qlid, asgnid, '', score, 1)) #get average score sql_query = """SELECT (TotalScore/TotalUsers) as AvgScore FROM common_services_qlassignmentadditionaldetails WHERE QL_Id=%s and Assignment_Id=%s""" scoredetail = cls.objects.raw(sql_query, [qlid, asgnid]) avgscore = 0 if(sum(1 for result in scoredetail) > 0): avgscore = scoredetail[0].AvgScore return avgscore ''' class kQualsimAttempts(models.Model): session_id = models.CharField(max_length=200, db_index=True) start_date = models.DateTimeField(auto_now_add=True, editable=True) end_date = models.DateTimeField(auto_now=True, editable=True) status = models.CharField(max_length=20, default='inprogress') att_index = models.IntegerField(default=0) state_data = models.TextField(default='{}') @classmethod def createAttempt(cls, sessionId, jsonData): attIndex = cls.objects.filter(session_id=sessionId).count() session = SessionData.objects.get(session_id=sessionId) lnchdata = json.loads(session.launch_data) allatt = int(lnchdata['custom_attemptsallowed']) if (allatt <= 0 or (allatt > 0 and attIndex < allatt)): jsonDataStr = json.dumps(jsonData) sql_insertcommand = """INSERT INTO common_services_kqualsimattempts (session_id, start_date, end_date, status, att_index, state_data) VALUES (%s, %s, %s, %s, %s,compress(%s))""" sql_selectcommand = """SELECT id, session_id, start_date, end_date, status, att_index, uncompress(state_data) as state_data FROM common_services_kqualsimattempts WHERE session_id=%s order by att_index desc""" with connection.cursor() as cursor: cursor.execute(sql_insertcommand, (sessionId, str(datetime.today()), str( datetime.today()),'inprogress', attIndex, jsonDataStr)) attemptsnm = cls.objects.raw(sql_selectcommand, [sessionId]) return attemptsnm[0] @classmethod def initAttemptData(cls, sessionId, jsonData): trackdata = '' attstatus = jsonData['Attempts'][0]['status'] trackdata = trackdata + attstatus + ',' + sessionId + ',' try: sql_query = """SELECT id, status, att_index FROM common_services_kqualsimattempts WHERE session_id=%s order by att_index desc""" attempts = cls.objects.raw(sql_query, [sessionId]) if(sum(1 for result in attempts) > 0): attempt = attempts[0] if(attempt.status == 'complete'): cls.createAttempt(sessionId, jsonData) trackdata = trackdata + 'create new,' else: with connection.cursor() as cursor: jsonDataStr = json.dumps(jsonData) sql_query = """UPDATE common_services_kqualsimattempts SET state_data=compress(%s),status=%s, end_date=%s WHERE id=%s""" cursor.execute( sql_query, (json.dumps(jsonData), attstatus, str(datetime.today()), attempt.id)) trackdata = trackdata + 'update existing,' else: cls.createAttempt(sessionId, jsonData) trackdata = trackdata + 'count0 create new1,' return trackdata except Exception as e: cls.createAttempt(sessionId, jsonData) return trackdata + ' Exception:' + str(e) + '- create new2' @classmethod def saveAttemptData(cls, sessionId, jsonData): trackdata = '' attstatus = jsonData['Attempts'][0]['status'] trackdata = trackdata + attstatus + ',' + sessionId + ',' try: #attempts = cls.objects.filter(session_id=sessionId) sql_query = """SELECT id, status, att_index FROM common_services_kqualsimattempts WHERE session_id=%s order by att_index desc""" attempts = cls.objects.raw(sql_query, [sessionId]) if(sum(1 for result in attempts) > 0): attmpt = attempts[0] if(attmpt.status != 'complete'): #dbjsondata = json.loads(attmpt.state_data) sql_query = """SELECT id, uncompress(state_data) as state_data FROM common_services_kqualsimattempts WHERE id=%s""" attemptsnm = cls.objects.raw(sql_query, [attmpt.id]) #trackdata = trackdata + attemptsnm[0].state_data dbjsondata = json.loads(attemptsnm[0].state_data) trackdata = trackdata + 'json.loads ,' dbreqno = 0 currreqno = 0 if dbjsondata.get('Attempts') and dbjsondata['Attempts'][0].get('requestNo'): dbreqno = dbjsondata['Attempts'][0]['requestNo'] if jsonData.get('Attempts') and jsonData['Attempts'][0].get('requestNo'): currreqno = jsonData['Attempts'][0]['requestNo'] if (dbreqno <= currreqno): sql_query = """UPDATE common_services_kqualsimattempts SET state_data=compress(%s), status=%s, end_date=%s WHERE id=%s""" jsonDataStr = json.dumps(jsonData) with connection.cursor() as cursor: cursor.execute( sql_query, (json.dumps(jsonData), attstatus, str(datetime.today()), attmpt.id)) else: trackdata = trackdata + 'count > 0 else' return trackdata except Exception as e: return trackdata + 'exception occure:' + str(e) @classmethod def getAttemptData(cls, sessionId, attIndex=0): try: sql_query = """SELECT id, session_id, start_date, end_date, status, att_index, uncompress(state_data) as state_data FROM common_services_kqualsimattempts WHERE session_id=%s AND att_index=%s""" attempts = cls.objects.raw(sql_query, [sessionId, attIndex]) if(sum(1 for result in attempts) > 0): return attempts[0] else: return {} except: return {} @classmethod def getLastAttemptData(cls, sessionId): errorobj = {} errorobj["tracedata"] = "" try: #attempts = cls.objects.filter(session_id=sessionId) sql_query = """SELECT id, session_id, start_date, end_date, status, att_index, uncompress(state_data) as state_data FROM common_services_kqualsimattempts WHERE session_id=%s order by att_index desc""" attempts = cls.objects.raw(sql_query, [sessionId]) if(sum(1 for result in attempts) > 0): errorobj["tracedata"] += str(sum(1 for result in attempts)) return attempts[0] else: errorobj["tracedata"] += "inside else" attIndex = cls.objects.filter(session_id=sessionId).count() with connection.cursor() as cursor: sql_query = """INSERT INTO common_services_kqualsimattempts (session_id, start_date, end_date, status, att_index, state_data) VALUES (%s,%s,%s,%s,%s,compress(%s))""" cursor.execute(sql_query, (sessionId, str(datetime.today()), str( datetime.today()), 'inprogress', attIndex, '{}')) sql_query = """SELECT id, session_id, start_date, end_date, status, att_index, uncompress(state_data) as state_data FROM common_services_kqualsimattempts WHERE session_id=%s order by att_index desc""" errorobj["tracedata"] += "inside else after select" attempt = cls.objects.raw(sql_query, [sessionId]) return attempt[0] except Exception as e: errorobj["tracedata"] += str(e) return errorobj @classmethod def getAllAttemptData(cls, sessionId, pstatus): #attempts = cls.objects.filter(session_id=sessionId, status=pstatus) sql_query = """SELECT id, session_id, start_date, end_date, status, att_index, uncompress(state_data) as state_data FROM common_services_kqualsimattempts WHERE session_id=%s AND status=%s order by att_index desc""" attempts = cls.objects.raw(sql_query, [sessionId, pstatus]) if(sum(1 for result in attempts) > 0): return attempts else: return [] @classmethod def getAttemptCount(cls, sessionId, pstatus): return cls.objects.filter(session_id=sessionId, status=pstatus).count() class testdata(models.Model): session_id = models.CharField(max_length=200, db_index=True) status = models.CharField(max_length=20, default='inprogress') # end of file
[ "naveen@knowdl.com" ]
naveen@knowdl.com
6e6cfff84023a4412c770e4d621a3b6c7283cbba
936e02343adc37c59a777f29dcbb2efe525d79c7
/알고리즘/스택, 큐/BOJ괄호9012.py
f0fd346c17d9ea947abb94f3743884e039020515
[]
no_license
hyun98/python
7bc818cd4dfacc4d7ca58d133b16728a9d6a91c2
1e92c3c9281db957d61207d885ddae81987e8492
refs/heads/master
2023-03-21T14:58:44.959682
2021-03-06T11:54:15
2021-03-06T11:54:15
344,914,818
0
0
null
null
null
null
UTF-8
Python
false
false
533
py
def check(g): if len(g)%2 == 1: print("NO") return 0 else: if g[0] == ")" or ")" not in g: print("NO") return 0 else: g = g.split("()") g = "".join(g) if len(g) == 0: print("YES") return 0 else: check(g) return 0 if __name__ == "__main__": import sys N = int(input()) for i in range(N): G = sys.stdin.readline().strip() check(G)
[ "hyun0404woo@gmail.com" ]
hyun0404woo@gmail.com
5868e39552c16ffa26487d3e1937eaa8079ba5da
54f3dbf30921f5d0078db8132811400993627fb7
/tgif/submissions/time_limit_exceeded/tgif-simulate-py3.py
b8f41ce1479b7bb5a0fd685d3c343d9b0f0fb2dc
[]
no_license
thorehusfeldt/will-code-for-drinks-F2019
9deef8efd5d79e228788624397f98e3746aa6d7b
c454ff4ab22d4e1b79d2025d73f26223fd56e8b5
refs/heads/master
2020-08-06T22:04:42.018855
2019-12-01T20:21:54
2019-12-01T20:21:54
213,172,740
0
0
null
null
null
null
UTF-8
Python
false
false
983
py
#!/usr/bin/python3 # TLE by failing to increase month in simulation M = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ] L = [ 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] D = [ 'FRI' , 'SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU' ] line = input().split() today_d = int(line[0]) today_m = M.index(line[1]) jan1 = D.index(input().strip()) def days(lengths): d, m = 1, 0 total = jan1 while (d, m) != (today_d, today_m): d += 1 total = (total + 1) % 7 if d > lengths[m]: d = 1 # TLE here: forgets to increase month counter return total ok_if_leap_year = (days([31, 29] + L)) % 7 == 0 feb29 = today_d == 29 and today_m == 1 if not feb29: ok_if_not_leap_year = (days([31, 28] + L)) % 7 == 0 if ok_if_leap_year and (feb29 or ok_if_not_leap_year): print ("TGIF") elif ok_if_leap_year or (not feb29 and ok_if_not_leap_year): print ("not sure") else: print (":(")
[ "thore.husfeldt@gmail.com" ]
thore.husfeldt@gmail.com
53620fddadab6a487c0d0375226ce24552b81916
ff179669ea4174c9a295d3c00860507f17288e6f
/app.py
169f2228c8554b2b291f0f003fa924deb4dcf2c8
[]
no_license
cdelfau/login_app
2918bfa47fa4b50f09b82f999a0ade924df33877
1f3db8da5aa652faa90464b03656a3d785f92def
refs/heads/master
2020-05-29T09:16:33.922452
2016-10-06T16:53:41
2016-10-06T16:53:41
69,494,829
0
0
null
null
null
null
UTF-8
Python
false
false
2,582
py
'''Chloe Delfau SoftDev1 pd 8 HW 04 -- Into a Zone of Danger 2016-10-04''' #all of the necessary imports from flask import Flask, render_template, request, redirect, url_for import hashlib import csv #create the flask app app = Flask(__name__) data = dict() #home route @app.route("/") def home(): readFile() return render_template("login.html") #the route when you register for @app.route("/register", methods=['POST']) def register(): usr = request.form["usr"] #register with a username pw = request.form["pw"] #register with a password if usr == "" or pw == "": #if either the username or the password is invalid return "<center>Please fill in both the username and password textboxes!</center>" elif usr in data: #username already exists return "<center>Username already exist please try a new one!</center>" else: #the username is unique and botht eh username and password are valid hashObj = hashlib.sha1() hashObj.update(pw) #hashcode the password postPw = hashObj.hexdigest() writeFile(usr,postPw) #add the username and hashed password to the csv file readFile() return render_template("register_success.html") #route for new register page html @app.route("/registerNew", methods=['POST']) def registerPage(): return render_template("register.html") #route to check login @app.route("/auth", methods=['POST']) def loginCheck(): hashObj = hashlib.sha1() usr = request.form["usr"] #get the username hashObj.update(request.form["pw"]) #hash the password submitted pw = hashObj.hexdigest() #compare hashed password submitted and existing password for the username if usr in data: if data[usr] == pw: return "<center>Login Success!</center>" #correct password! else: return "<center>Incorrect password!</center>" #incorrect password else: return "<center>User name doesn't exist!</center>" #user doesnt exist, make a new user #read into the csv file def readFile(): with open('data.csv','r') as csvfile: dataReader = csv.reader(csvfile) for row in dataReader: if row[0] != "Usr" and row[1] != "Pw" and (row[0] not in data) : data[row[0]] = row[1] #write into the csv file def writeFile(u,p): with open('data.csv','w') as csvfile: dataWriter = csv.writer(csvfile) dataWriter.writerow([u,p]) @app.route("/jacobo") def js(): return redirect('http://xkcd.com') #debug if __name__ == "__main__": app.debug = True app.run()
[ "cdelfau@stuy.edu" ]
cdelfau@stuy.edu
7fe1642c6b608add3b737b97d6c11a34bfc1dd33
548c26cc8e68c3116cecaf7e5cd9aadca7608318
/users/migrations/0055_auto__add_profileremap.py
bd6c68731fe779e656ef9aa51dddb228ade65deb
[]
no_license
Morphnus-IT-Solutions/riba
b69ecebf110b91b699947b904873e9870385e481
90ff42dfe9c693265998d3182b0d672667de5123
refs/heads/master
2021-01-13T02:18:42.248642
2012-09-06T18:20:26
2012-09-06T18:20:26
4,067,896
0
1
null
null
null
null
UTF-8
Python
false
false
24,876
py
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ProfileRemap' db.create_table('users_profileremap', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('email', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.Email'], null=True, blank=True)), ('phone', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.Phone'], null=True, blank=True)), ('old_profile', self.gf('django.db.models.fields.related.ForeignKey')(related_name='oldprofiles', to=orm['users.Profile'])), ('new_profile', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.Profile'])), )) db.send_create_signal('users', ['ProfileRemap']) def backwards(self, orm): # Deleting model 'ProfileRemap' db.delete_table('users_profileremap') models = { 'accounts.account': { 'Meta': {'object_name': 'Account'}, 'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['accounts.Client']"}), 'code': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'confirmed_order_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> order@chaupaati.com'", 'max_length': '500'}), 'confirmed_order_helpline': ('django.db.models.fields.CharField', [], {'default': "'0-922-222-1947'", 'max_length': '25'}), 'customer_support_no': ('django.db.models.fields.CharField', [], {'max_length': '150', 'blank': 'True'}), 'dni': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}), 'greeting_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'greeting_title': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_exclusive': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pending_order_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> lead@chaupaati.com'", 'max_length': '500'}), 'pending_order_helpline': ('django.db.models.fields.CharField', [], {'default': "'0-922-222-1947'", 'max_length': '25'}), 'pg_return_url': ('django.db.models.fields.URLField', [], {'default': "'http://www.chaupaati.in'", 'max_length': '200', 'blank': 'True'}), 'primary_email': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'primary_phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'returns_policy': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'secondary_email': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'secondary_phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'share_product_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> share@chaupaati.com'", 'max_length': '500'}), 'shipping_policy': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'signature': ('django.db.models.fields.TextField', [], {}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'sms_mask': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'tos': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'Channel'", 'max_length': '100'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) }, 'accounts.client': { 'Meta': {'object_name': 'Client'}, 'clientdomain_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'confirmed_order_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> order@chaupaati.com'", 'max_length': '500'}), 'confirmed_order_helpline': ('django.db.models.fields.CharField', [], {'default': "'0-922-222-1947'", 'max_length': '25'}), 'emi_amount': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '10', 'decimal_places': '2'}), 'feedback_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> feedback@chaupaati.com'", 'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'list_pricelist': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'noreply_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> noreply@chaupaati.com'", 'max_length': '200'}), 'order_prefix': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '5', 'null': 'True', 'blank': 'True'}), 'pending_order_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> lead@chaupaati.com'", 'max_length': '500'}), 'pending_order_helpline': ('django.db.models.fields.CharField', [], {'default': "'0-922-222-1947'", 'max_length': '25'}), 'promotions_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> promotions@chaupaati.com'", 'max_length': '200'}), 'sale_pricelist': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'share_product_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> share@chaupaati.com'", 'max_length': '500'}), 'signature': ('django.db.models.fields.TextField', [], {}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'sms_mask': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'terms_and_conditions': ('django.db.models.fields.TextField', [], {}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'users.dailysubscription': { 'Meta': {'object_name': 'DailySubscription'}, 'email_alert_on': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Email']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_email_alert': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_sms_alert': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'last_modified_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 3, 19, 16, 38, 41, 908040)', 'auto_now': 'True', 'blank': 'True'}), 'newsletter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.NewsLetter']"}), 'sms_alert_on': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Phone']", 'null': 'True', 'blank': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'verification_code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'verified_on': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'users.email': { 'Meta': {'object_name': 'Email'}, 'cleaned_email': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '100', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}) }, 'users.facebookappscore': { 'Meta': {'object_name': 'FacebookAppScore'}, 'facebook_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'facebook_user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'users.facebookinfo': { 'Meta': {'object_name': 'FacebookInfo'}, 'email': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Email']"}), 'facebook_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_new_email': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'linked_to': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '200'}), 'linking_denied': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'linking_done': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}) }, 'users.newsletter': { 'Meta': {'object_name': 'NewsLetter'}, 'affiliate_logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'affiliate_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'affiliate_text': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'client': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['accounts.Client']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'newsletter': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'users.permission': { 'Meta': {'unique_together': "(('user', 'system', 'object_id'),)", 'object_name': 'Permission'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'system': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'users.phone': { 'Meta': {'object_name': 'Phone'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '15'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'verification_code': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '50', 'null': 'True', 'blank': 'True'}), 'verified_on': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'users.ppdadminuser': { 'Meta': {'object_name': 'PpdAdminUser'}, 'accounts': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['accounts.Account']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'profile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}) }, 'users.profile': { 'Meta': {'object_name': 'Profile'}, 'acquired_through_account': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_customers'", 'null': 'True', 'to': "orm['accounts.Account']"}), 'atg_login': ('django.db.models.fields.CharField', [], {'max_length': '40', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'atg_password': ('django.db.models.fields.CharField', [], {'max_length': '35', 'null': 'True', 'blank': 'True'}), 'atg_username': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'buyer_or_seller': ('django.db.models.fields.CharField', [], {'default': "'Buyer'", 'max_length': '100'}), 'cod_status': ('django.db.models.fields.CharField', [], {'default': "'neutral'", 'max_length': '25'}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'customer_of_accounts': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'customers'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['accounts.Account']"}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'email_notification': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'facebook': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'full_name': ('django.db.models.fields.CharField', [], {'max_length': '150', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'default': "'m'", 'max_length': '1'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_agent': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'managed_accounts': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'account_staff'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['accounts.Account']"}), 'marketing_alerts': ('django.db.models.fields.CharField', [], {'default': "'neutral'", 'max_length': '25'}), 'passcode': ('django.db.models.fields.CharField', [], {'max_length': '36', 'blank': 'True'}), 'primary_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'primary_phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'profession': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'salt': ('django.db.models.fields.CharField', [], {'max_length': '36', 'blank': 'True'}), 'salutation': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'secondary_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'secondary_phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'sms_alert': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['users.UserTag']", 'null': 'True', 'blank': 'True'}), 'transaction_password': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'twitter': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'user_photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'verification_code': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'verify_code': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'webpage': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}) }, 'users.profileremap': { 'Meta': {'object_name': 'ProfileRemap'}, 'email': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Email']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_profile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}), 'old_profile': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'oldprofiles'", 'to': "orm['users.Profile']"}), 'phone': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Phone']", 'null': 'True', 'blank': 'True'}) }, 'users.shoppingpage': { 'Meta': {'object_name': 'ShoppingPage'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'newsletter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.NewsLetter']"}), 'redirect_page': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, 'users.subscription': { 'Meta': {'unique_together': "(('contact', 'newsletter'),)", 'object_name': 'Subscription'}, 'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['accounts.Client']", 'null': 'True', 'blank': 'True'}), 'contact': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'contact_type': ('django.db.models.fields.CharField', [], {'default': "'email'", 'max_length': '10'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'newsletter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.NewsLetter']"}), 'source': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}), 'subscribed_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'subscription_alert': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'verification_code': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'verified_on': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'users.tab': { 'Meta': {'object_name': 'Tab'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'system': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'tab_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'users.usermerges': { 'Meta': {'unique_together': "(('user', 'email', 'phone', 'merged_to'),)", 'object_name': 'UserMerges'}, 'email': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Email']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'merged_to': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['users.Profile']"}), 'phone': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Phone']", 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Profile']"}) }, 'users.usertab': { 'Meta': {'object_name': 'UserTab'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tab': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.Tab']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tabs'", 'to': "orm['users.Profile']"}) }, 'users.usertag': { 'Meta': {'object_name': 'UserTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tag': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '25'}) } } complete_apps = ['users']
[ "dalal.saumil@gmail.com" ]
dalal.saumil@gmail.com
b51b918ccd2af4eb40c1c21f2b6ec04489ddf5bb
3c8bc614c9f09db5efce54af3cbcaf78e0f48b54
/0x01-python-if_else_loops_functions/8-uppercase.py
5d019f17c68fc69029ea1eb34fa15ee5e1d724e3
[]
no_license
davidknoppers/holbertonschool-higher_level_programming
7848d301c4bf5c1fa285314392adfb577d6d082f
beaf6e5ece426c2086f34763e50c3ce0f56923ac
refs/heads/master
2021-04-29T10:10:27.071278
2017-05-03T02:46:44
2017-05-03T02:46:44
77,847,936
1
0
null
null
null
null
UTF-8
Python
false
false
198
py
#!/usr/bin/python3 def uppercase(str): for char in str: if 97 <= ord(char) <= 122: char = chr(ord(char) - 32) print("{}".format(char), end="") print("".format())
[ "david.knoppers@holbertonschool.com" ]
david.knoppers@holbertonschool.com
6f1cccb96642b850eb3cc83009fc1cb0e4e36c9b
57091f10b6a322a3c539dd24f0e9d00b32401281
/bin/rac.py
09c3f964ddb9c7092c6a824b11526d332723528d
[]
no_license
taqiu/accounting
547f0913a9f5e4101b2252c6dffdcda85039c439
dbb04e13edc7b12ad7d1770cb68d0a6577a36376
refs/heads/master
2021-01-22T09:04:23.156327
2014-05-02T00:51:13
2014-05-02T00:51:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
773
py
#! /usr/bin/python ######################################### # # Request Account Create # ######################################### import argparse from amie.accounting import process_rac if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--packet_rec_id", required=False, default=None, help="process single packet with the given receive id") parser.add_argument("--verbose", action='store_true', default=False, help="print out the processing detail") parser.add_argument("--checkpt", action='store_true', default=False, help="enable check point") args = parser.parse_args() process_rac(args.packet_rec_id, args.verbose, args.checkpt)
[ "taqiu@indiana.edu" ]
taqiu@indiana.edu
b2841814c9b48d48bd5e6f83e79c09e3da9ec6ca
bbc39f22380a3bc6f043575a2e82f6226114cde3
/Fetch.py
4ccc90d2db7a7f656a744c5f68a8fed4d2b596a4
[]
no_license
lkeab/TensorflowLearning
41b2c398dbb31d9b9d1f68f803d70302456710e8
10966895ea75cd535a0bf4afa7f3b315034af688
refs/heads/master
2021-06-15T23:47:35.048270
2017-04-28T15:57:18
2017-04-28T15:57:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
327
py
import tensorflow as tf input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) intermed = tf.add(input2, input3) mul = tf.multiply(input1, intermed) with tf.Session() as sess: result = sess.run([mul, intermed]) print (result) # 输出: # [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
[ "kelei@kelei-MacBook-Pro.local" ]
kelei@kelei-MacBook-Pro.local
da52bea8aec81d030e60989ed400f41ae565ab4e
bb33e6be8316f35decbb2b81badf2b6dcf7df515
/source/res/scripts/client/AvatarInputHandler/AimingSystems/magnetic_aim.py
e98baddd2fcd5c83008ec64dec6e1581580a0d82
[]
no_license
StranikS-Scan/WorldOfTanks-Decompiled
999c9567de38c32c760ab72c21c00ea7bc20990c
d2fe9c195825ececc728e87a02983908b7ea9199
refs/heads/1.18
2023-08-25T17:39:27.718097
2022-09-22T06:49:44
2022-09-22T06:49:44
148,696,315
103
39
null
2022-09-14T17:50:03
2018-09-13T20:49:11
Python
UTF-8
Python
false
false
4,511
py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/AvatarInputHandler/AimingSystems/magnetic_aim.py from collections import namedtuple from itertools import chain import math import BigWorld from Math import Vector3, Matrix import math_utils class MagneticAimSettings(object): MAGNETIC_ANGLE = 2.25 KEY_DELAY_SEC = 0.5 @staticmethod def getMagneticAngle(): return math.cos(math.radians(MagneticAimSettings.MAGNETIC_ANGLE)) _TargetVeh = namedtuple('TargetVehicle', ('vehicleRef', 'dotResult', 'distance')) def magneticAimProcessor(previousSimpleTarget=None, previousMagneticTarget=None): if BigWorld.target() is None: target = magneticAimFindTarget() if target and target != previousSimpleTarget and target != previousMagneticTarget: BigWorld.player().autoAim(target=target, magnetic=True) return target return previousSimpleTarget def magneticAimFindTarget(): vehicleAttached = BigWorld.player().getVehicleAttached() aimCamera = BigWorld.player().inputHandler.ctrl.camera aimCameraDirection = aimCamera.aimingSystem.matrixProvider.applyToAxis(2) if vehicleAttached is None or not vehicleAttached.isAlive(): return else: minAngleVehicle = None for vehicleID in BigWorld.player().arena.vehicles.iterkeys(): vehicle = BigWorld.entity(vehicleID) if vehicle is None: continue allyOrSelfVehicle = vehicle.publicInfo['team'] == BigWorld.player().team or vehicle.isPlayerVehicle if allyOrSelfVehicle or not vehicle.isStarted or not vehicle.isAlive(): continue vehiclePositionDirection = vehicle.position - aimCamera.camera.position vehiclePositionDirection.normalise() dotResult = vehiclePositionDirection.dot(aimCameraDirection) targetDistance = vehicle.position - vehicleAttached.position if dotResult < MagneticAimSettings.getMagneticAngle(): continue if not isVehicleVisibleFromCamera(vehicle, aimCamera): continue veh = _TargetVeh(vehicleRef=vehicle, dotResult=dotResult, distance=targetDistance.length) if minAngleVehicle is None or dotResult >= minAngleVehicle.dotResult: minAngleVehicle = veh if minAngleVehicle is not None and math_utils.almostZero(dotResult - minAngleVehicle.dotResult): if targetDistance.length < minAngleVehicle.distance: minAngleVehicle = veh pickedVehicle = None if minAngleVehicle: pickedVehicle = minAngleVehicle.vehicleRef return pickedVehicle def getVehiclePointsGen(vehicle): vehicleDesr = vehicle.typeDescriptor hullPos = vehicleDesr.chassis.hullPosition hullBboxMin, hullBboxMax, _ = vehicleDesr.hull.hitTester.bbox turretPosOnHull = vehicleDesr.hull.turretPositions[0] turretLocalTopY = max(hullBboxMax.y, turretPosOnHull.y + vehicleDesr.turret.hitTester.bbox[1].y) yield Vector3(0.0, hullPos.y + turretLocalTopY, 0.0) gunPosOnHull = turretPosOnHull + vehicleDesr.turret.gunPosition yield hullPos + gunPosOnHull hullLocalCenterY = (hullBboxMin.y + hullBboxMax.y) / 2.0 hullLocalPt1 = Vector3(0.0, hullLocalCenterY, hullBboxMax.z) yield hullPos + hullLocalPt1 hullLocalPt2 = Vector3(0.0, hullLocalCenterY, hullBboxMin.z) yield hullPos + hullLocalPt2 hullLocalCenterZ = (hullBboxMin.z + hullBboxMax.z) / 2.0 hullLocalPt3 = Vector3(hullBboxMax.x, gunPosOnHull.y, hullLocalCenterZ) yield hullPos + hullLocalPt3 hullLocalPt4 = Vector3(hullBboxMin.x, gunPosOnHull.y, hullLocalCenterZ) yield hullPos + hullLocalPt4 def getVisibilityCheckPointsGen(vehicle): matrix = Matrix(vehicle.matrix) return chain((vehicle.position,), (matrix.applyPoint(pt) for pt in getVehiclePointsGen(vehicle))) def isVehicleVisibleFromCamera(vehicle, aimCamera): for vehiclePoint in getVisibilityCheckPointsGen(vehicle): startPos = aimCamera.camera.position endPos = vehiclePoint testResStatic = BigWorld.wg_collideSegment(BigWorld.player().spaceID, startPos, endPos, 128) if testResStatic is None: testResDynamic = BigWorld.wg_collideDynamic(BigWorld.player().spaceID, startPos, endPos, BigWorld.player().playerVehicleID) if testResDynamic is None: return True return False
[ "StranikS_Scan@mail.ru" ]
StranikS_Scan@mail.ru
a74f8e12e408316a956d67875682a887f06f6857
b403c7fe56209472855dff451f0b6283d5471008
/Supplemental_Material/PythonProjects/13. PYGAME/Pygames/beep.py
42146572cce333a753c6e70e94d4ea0706a3a94b
[]
no_license
Sandbox4KidsTM/Python_Basics
842bde52796896e913fdb5cc349034c52092555f
68c95547ec1567958fc8069e6a4bb119e436211a
refs/heads/master
2020-03-23T01:06:29.363196
2018-08-10T04:32:58
2018-08-10T04:32:58
140,901,128
0
0
null
null
null
null
UTF-8
Python
false
false
506
py
import pygame import time pygame.init() soundObj = pygame.mixer.Sound('beep1.ogg') beep2 = pygame.mixer.Sound('beep2.ogg') DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32) pygame.display.set_caption('Animation') time.sleep(5) i = 0 while i < 5: soundObj.play() time.sleep(1.5) # wait and let the sound play for 1 second soundObj.stop() time.sleep(.5) beep2.play() time.sleep(1.5) beep2.stop() i = i + 1 pygame.quit() #end pygame
[ "mitchslabrenz@gmail.com" ]
mitchslabrenz@gmail.com
1eee9e934a9cde950b55b870575bbfa1fae421f8
ce9cc55a0df31f5a50ea941c20070d6bc629bf2b
/artificial NN/ANN.py
9a1294b55be7d19fdf43f86d230e641bed27fc5b
[]
no_license
Prathmesh311/Machine-Learning
46fcff88ea9214cab9c7f931ff420eeae379adf7
bc75704b221bcd717fec1f4d839449c6d12d7acf
refs/heads/master
2022-10-23T03:37:59.058901
2020-06-19T16:04:08
2020-06-19T16:04:08
266,613,962
2
0
null
null
null
null
UTF-8
Python
false
false
2,137
py
# -*- coding: utf-8 -*- """ Created on Tue May 5 12:13:29 2020 @author: Psbho """ #import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing dataset dataset= pd.read_csv("Churn_Modelling.csv") x= dataset.iloc[:, 3:13].values y= dataset.iloc[:, 13].values #Encoding categorical data from sklearn.compose import ColumnTransformer from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_x1 = LabelEncoder() x[:, 1]= labelencoder_x1.fit_transform(x[:, 1]) labelencoder_x2 = LabelEncoder() x[:, 2]= labelencoder_x2.fit_transform(x[:, 2]) ct = ColumnTransformer([('encoder', OneHotEncoder(), [1])], remainder='passthrough') x = np.array(ct.fit_transform(x), dtype=np.float) x = x[:, 1:] #onehotencoder = OneHotEncoder(categories[1]) #x= onehotencoder.fit_transform(x).toarray() #splitting data n training and test sets from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test= train_test_split(x,y, test_size=0.2, random_state=0) #Feature scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train= sc.fit_transform(x_train) x_test= sc.transform(x_test) #importing Keras library and packages import keras from keras.models import Sequential from keras.layers import Dense #initializing ANN classifier = Sequential() #Adding input layer and first hiddden layer classifier.add(Dense(output_dim=6, init="uniform", activation="relu", input_dim=11)) #Adding Second hidden layer classifier.add(Dense(output_dim=6, init="uniform", activation="relu")) #Adding output layer classifier.add(Dense(output_dim=1, init="uniform", activation="sigmoid")) #Compiling ANN classifier.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]) #Fitting training set to ANN classifier.fit(x_train, y_train, batch_size=10, epochs=100) #Predicting the test set result y_pred= classifier.predict(x_test) y_pred= (y_pred> 0.5) #making confusion metrix from sklearn.metrics import confusion_matrix cm= confusion_matrix(y_test, y_pred)
[ "noreply@github.com" ]
Prathmesh311.noreply@github.com
d6457e1f59aa2e7f58e030cdc15209bc2e73432b
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/templates/Recursion, Backtracking and Dynamic Programming in Python/Section 3 Search Algorithms/LinearSearch.py
9c9fe6d57bb2d080e174b09a72e7864fd9de6359
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
489
py
___ linear_search(container, item # the running time of this algorithms is O(N) # USE LINEAR SEARCH IF THE DATA STRUCTURE IS UNORDERED !!! ___ index __ ra__(le_(container)): __ container[index] __ item: # if we find the item: we return the index of that item r_ index # search miss - when the item is not present in the # underlying data structure (container) r_ -1 nums [1, 5, -3, 10, 55, 100] print(linear_search(nums, 10))
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
9da3dc63c4160bddf0412161e64b56f96fa24a61
b66e26e274fbbd6b88c7a34f357a278983a8165c
/July_04_SelfNote_RandomDataGenerationExercise.py
e5917f89680dd5668d8e781bcad230cb9932c72b
[]
no_license
shubhs15/python_practise_files
5c90f316622670e366652be83e06895ae77bac9d
40b74dcfae641c218951136ceca91c66a34eba7b
refs/heads/master
2023-01-07T22:36:28.156789
2020-11-07T10:58:46
2020-11-07T10:58:46
282,397,406
0
0
null
null
null
null
UTF-8
Python
false
false
4,276
py
# -*- coding: utf-8 -*- """ Created on Sat Jul 4 15:56:59 2020 @author: shubhs """ # Python random Data generation Exercise # Question 1: # Generate 3 random integers between 100 and 999 which is divisible by 5 import random print("Generating 3 random integer number between 100 and 999 divisible by 5") for num in range(3): print(random.randrange(100, 999, 5)) # Question 2: # Random Lottery Pick. Generate 50 random lottery tickets and # pick two lucky tickets from it as a winner. Note you must adhere to the following conditions: # Cond:1 - The lottery number must be 10 digits long. # Cond:2 - All 100 ticket number must be unique. lottery_tickets_list = [] print("creating 50 random lottery tickets") # to get 100 ticket for i in range(50): # ticket number must be 10 digit (1000000000, 9999999999) lottery_tickets_list.append(random.randrange(1000000000, 9999999999)) # pick 2 luck tickets winners = random.sample(lottery_tickets_list, 2) print("Lucky 2 lottery tickets are", winners) # Question 3: Generate 6 digit random secure OTP import secrets #Getting systemRandom class instance out of secrets module secretsGenerator = secrets.SystemRandom() print("Generating 6 digit random OTP") otp = secretsGenerator.randrange(100000, 999999) print("Secure random OTP is ", otp) # Question 4: Pick a random character from a given String name = 'shubhamselflearning' char = random.choice(name) print("random char is ", char) # Question 5: Generate random String of length 5 # Note: String must be the combination of the UPPER case and lower case letters only. # No numbers and a special symbol. import string def randomString(stringLength): """Generate a random string of 7 charcters""" letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(stringLength)) print ("Random String is ", randomString(7) ) # Question 6: Generate a random Password which meets the following conditions # Password length must be 10 characters long. # It must contain at least 2 upper case letters, 1 digit, and 1 special symbol. def randomPassword(): randomSource = string.ascii_letters + string.digits + string.punctuation password = random.sample(randomSource, 6) password += random.sample(string.ascii_uppercase, 2) password += random.choice(string.digits) password += random.choice(string.punctuation) passwordList = list(password) random.SystemRandom().shuffle(passwordList) password = ''.join(passwordList) return password print ("Password is ", randomPassword()) # Question 7: Calculate multiplication of two random float numbers # Note: # First random float number must be between 0.1 and 1 # Second random float number must be between 9.5 and 99.5 num1 = random.random() print("First Random float is ", num1) num2 = random.uniform(9.5, 99.5) print("Second Random float is ", num2) num3 = num1 * num2 print("Multiplication is ", num3) # Question 8: Generate random secure token of 64 bytes and random URL print("Random secure Hexadecimal token is ", secrets.token_hex(64)) print("Random secure URL is ", secrets.token_urlsafe(64)) # Question 9: Roll dice in such a way that every time you get the same number # Dice has 6 numbers (from 1 to 6). Roll dice in such a way that every time # you must get the same output number. do this 3 times. dice = [1, 2, 3, 4, 5, 6] print("Randomly selecting same number of a dice") for i in range(3): random.seed(9) print(random.choice(dice)) # Question 10: Generate a random date between given start and end dates import time def getRandomDate(startDate, endDate ): print("Printing random date between", startDate, " and ", endDate) randomGenerator = random.random() dateFormat = '%m/%d/%Y' startTime = time.mktime(time.strptime(startDate, dateFormat)) endTime = time.mktime(time.strptime(endDate, dateFormat)) randomTime = startTime + randomGenerator * (endTime - startTime) randomDate = time.strftime(dateFormat, time.localtime(randomTime)) return randomDate print ("Random Date = ", getRandomDate("1/1/2001", "12/12/2020"))
[ "noreply@github.com" ]
shubhs15.noreply@github.com
16c23d2345c5255cce4a8dd667ccae1d48a43dd6
2ffc81240edc918734d7de8f714fc3b0952a1641
/src/openprocurement/api/tests/chronograph.py
b3f0f69ac25ec9cb8093ba5ad7dd73b3d0d4dec9
[ "Apache-2.0" ]
permissive
VolVoz/openprocurement.api
4d0289260a630499991411eb0002fc90c760f0bf
9b3cbcaa39c900b67c928e1cb3099f4e9b9c2dca
refs/heads/master
2021-01-16T17:42:15.902838
2016-06-07T10:07:18
2016-06-07T10:07:18
50,173,269
1
0
null
2016-01-22T10:03:06
2016-01-22T10:03:06
null
UTF-8
Python
false
false
22,757
py
# -*- coding: utf-8 -*- import unittest from datetime import datetime, timedelta from openprocurement.api.models import get_now from openprocurement.api.tests.base import BaseTenderWebTest, test_lots, test_bids, test_organization class TenderSwitchTenderingResourceTest(BaseTenderWebTest): def test_switch_to_tendering_by_enquiryPeriod_endDate(self): self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertNotEqual(response.json['data']["status"], "active.tendering") self.set_status('active.tendering', {'status': 'active.enquiries', "tenderPeriod": {"startDate": None}}) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], "active.tendering") def test_switch_to_tendering_by_tenderPeriod_startDate(self): self.set_status('active.tendering', {'status': 'active.enquiries', "tenderPeriod": {}}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertNotEqual(response.json['data']["status"], "active.tendering") self.set_status('active.tendering', {'status': self.initial_status, "enquiryPeriod": {}}) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], "active.tendering") def test_switch_to_tendering_auctionPeriod(self): self.set_status('active.tendering', {'status': 'active.enquiries', "tenderPeriod": {"startDate": None}}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], "active.tendering") self.assertIn('auctionPeriod', response.json['data']) class TenderSwitchQualificationResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_bids = test_bids[:1] def test_switch_to_qualification(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active.qualification") self.assertEqual(len(response.json['data']["awards"]), 1) class TenderSwitchAuctionResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' initial_bids = test_bids def test_switch_to_auction(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active.auction") class TenderSwitchUnsuccessfulResourceTest(BaseTenderWebTest): initial_status = 'active.tendering' def test_switch_to_unsuccessful(self): response = self.set_status('active.auction', {'status': self.initial_status}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "unsuccessful") if self.initial_lots: self.assertEqual(set([i['status'] for i in response.json['data']["lots"]]), set(["unsuccessful"])) class TenderLotSwitchQualificationResourceTest(TenderSwitchQualificationResourceTest): initial_lots = test_lots class TenderLotSwitchAuctionResourceTest(TenderSwitchAuctionResourceTest): initial_lots = test_lots class TenderLotSwitchUnsuccessfulResourceTest(TenderSwitchUnsuccessfulResourceTest): initial_lots = test_lots class TenderAuctionPeriodResourceTest(BaseTenderWebTest): initial_bids = test_bids def test_set_auction_period(self): self.set_status('active.tendering', {'status': 'active.enquiries'}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], 'active.tendering') if self.initial_lots: item = response.json['data']["lots"][0] else: item = response.json['data'] self.assertIn('auctionPeriod', item) self.assertIn('shouldStartAfter', item['auctionPeriod']) self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertEqual(response.json['data']['next_check'], response.json['data']['tenderPeriod']['endDate']) if self.initial_lots: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": "9999-01-01T00:00:00+00:00"}}]}}) item = response.json['data']["lots"][0] else: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": "9999-01-01T00:00:00+00:00"}}}) item = response.json['data'] self.assertEqual(response.status, '200 OK') self.assertEqual(item['auctionPeriod']['startDate'], '9999-01-01T00:00:00+00:00') if self.initial_lots: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": None}}]}}) item = response.json['data']["lots"][0] else: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": None}}}) item = response.json['data'] self.assertEqual(response.status, '200 OK') self.assertNotIn('startDate', item['auctionPeriod']) def test_reset_auction_period(self): self.set_status('active.tendering', {'status': 'active.enquiries'}) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], 'active.tendering') if self.initial_lots: item = response.json['data']["lots"][0] else: item = response.json['data'] self.assertIn('auctionPeriod', item) self.assertIn('shouldStartAfter', item['auctionPeriod']) self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertEqual(response.json['data']['next_check'], response.json['data']['tenderPeriod']['endDate']) if self.initial_lots: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": "9999-01-01T00:00:00"}}]}}) item = response.json['data']["lots"][0] else: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": "9999-01-01T00:00:00"}}}) item = response.json['data'] self.assertEqual(response.status, '200 OK') self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertIn('9999-01-01T00:00:00', item['auctionPeriod']['startDate']) self.set_status('active.auction', {'status': 'active.tendering'}) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], 'active.auction') item = response.json['data']["lots"][0] if self.initial_lots else response.json['data'] self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) if self.initial_lots: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": "9999-01-01T00:00:00"}}]}}) item = response.json['data']["lots"][0] else: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": "9999-01-01T00:00:00"}}}) item = response.json['data'] self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], 'active.auction') self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertIn('9999-01-01T00:00:00', item['auctionPeriod']['startDate']) self.assertIn('9999-01-01T00:00:00', response.json['data']['next_check']) now = get_now().isoformat() tender = self.db.get(self.tender_id) if self.initial_lots: tender['lots'][0]['auctionPeriod']['startDate'] = now else: tender['auctionPeriod']['startDate'] = now self.db.save(tender) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], 'active.auction') item = response.json['data']["lots"][0] if self.initial_lots else response.json['data'] self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertGreater(response.json['data']['next_check'], item['auctionPeriod']['startDate']) self.assertEqual(response.json['data']['next_check'], self.db.get(self.tender_id)['next_check']) if self.initial_lots: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": response.json['data']['tenderPeriod']['endDate']}}]}}) item = response.json['data']["lots"][0] else: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": response.json['data']['tenderPeriod']['endDate']}}}) item = response.json['data'] self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], 'active.auction') self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertNotIn('9999-01-01T00:00:00', item['auctionPeriod']['startDate']) self.assertGreater(response.json['data']['next_check'], response.json['data']['tenderPeriod']['endDate']) tender = self.db.get(self.tender_id) self.assertGreater(tender['next_check'], response.json['data']['tenderPeriod']['endDate']) tender['tenderPeriod']['endDate'] = tender['tenderPeriod']['startDate'] if self.initial_lots: tender['lots'][0]['auctionPeriod']['startDate'] = tender['tenderPeriod']['startDate'] else: tender['auctionPeriod']['startDate'] = tender['tenderPeriod']['startDate'] self.db.save(tender) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) if self.initial_lots: item = response.json['data']["lots"][0] else: item = response.json['data'] self.assertGreater(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertNotIn('next_check', response.json['data']) self.assertNotIn('next_check', self.db.get(self.tender_id)) shouldStartAfter = item['auctionPeriod']['shouldStartAfter'] response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) if self.initial_lots: item = response.json['data']["lots"][0] else: item = response.json['data'] self.assertEqual(item['auctionPeriod']['shouldStartAfter'], shouldStartAfter) self.assertNotIn('next_check', response.json['data']) if self.initial_lots: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"lots": [{"auctionPeriod": {"startDate": "9999-01-01T00:00:00"}}]}}) item = response.json['data']["lots"][0] else: response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {"auctionPeriod": {"startDate": "9999-01-01T00:00:00"}}}) item = response.json['data'] self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["status"], 'active.auction') self.assertEqual(item['auctionPeriod']['shouldStartAfter'], response.json['data']['tenderPeriod']['endDate']) self.assertIn('9999-01-01T00:00:00', item['auctionPeriod']['startDate']) self.assertIn('9999-01-01T00:00:00', response.json['data']['next_check']) class TenderLotAuctionPeriodResourceTest(TenderAuctionPeriodResourceTest): initial_lots = test_lots class TenderComplaintSwitchResourceTest(BaseTenderWebTest): def test_switch_to_pending(self): response = self.app.post_json('/tenders/{}/complaints'.format(self.tender_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': test_organization, 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') tender = self.db.get(self.tender_id) tender['complaints'][0]['dateSubmitted'] = (get_now() - timedelta(days=1 if 'procurementMethodDetails' in tender else 4)).isoformat() self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["complaints"][0]['status'], 'pending') def test_switch_to_complaint(self): for status in ['invalid', 'resolved', 'declined']: self.app.authorization = ('Basic', ('token', '')) response = self.app.post_json('/tenders/{}/complaints'.format(self.tender_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': test_organization, 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') complaint = response.json['data'] response = self.app.patch_json('/tenders/{}/complaints/{}?acc_token={}'.format(self.tender_id, complaint['id'], self.tender_token), {"data": { "status": "answered", "resolution": status * 4, "resolutionType": status }}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "answered") self.assertEqual(response.json['data']["resolutionType"], status) tender = self.db.get(self.tender_id) tender['complaints'][-1]['dateAnswered'] = (get_now() - timedelta(days=1 if 'procurementMethodDetails' in tender else 4)).isoformat() self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']["complaints"][-1]['status'], status) class TenderLotComplaintSwitchResourceTest(TenderComplaintSwitchResourceTest): initial_lots = test_lots class TenderAwardComplaintSwitchResourceTest(BaseTenderWebTest): initial_status = 'active.qualification' initial_bids = test_bids def setUp(self): super(TenderAwardComplaintSwitchResourceTest, self).setUp() # Create award response = self.app.post_json('/tenders/{}/awards'.format( self.tender_id), {'data': {'suppliers': [test_organization], 'status': 'pending', 'bid_id': self.initial_bids[0]['id']}}) award = response.json['data'] self.award_id = award['id'] def test_switch_to_pending(self): response = self.app.post_json('/tenders/{}/awards/{}/complaints'.format(self.tender_id, self.award_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': test_organization, 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') response = self.app.patch_json('/tenders/{}/awards/{}'.format(self.tender_id, self.award_id), {"data": {"status": "active"}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active") tender = self.db.get(self.tender_id) tender['awards'][0]['complaints'][0]['dateSubmitted'] = (get_now() - timedelta(days=1 if 'procurementMethodDetails' in tender else 4)).isoformat() self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']['awards'][0]["complaints"][0]['status'], 'pending') def test_switch_to_complaint(self): response = self.app.patch_json('/tenders/{}/awards/{}'.format(self.tender_id, self.award_id), {"data": {"status": "active"}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "active") for status in ['invalid', 'resolved', 'declined']: self.app.authorization = ('Basic', ('token', '')) response = self.app.post_json('/tenders/{}/awards/{}/complaints'.format(self.tender_id, self.award_id), {'data': { 'title': 'complaint title', 'description': 'complaint description', 'author': test_organization, 'status': 'claim' }}) self.assertEqual(response.status, '201 Created') self.assertEqual(response.json['data']['status'], 'claim') complaint = response.json['data'] response = self.app.patch_json('/tenders/{}/awards/{}/complaints/{}?acc_token={}'.format(self.tender_id, self.award_id, complaint['id'], self.tender_token), {"data": { "status": "answered", "resolution": status * 4, "resolutionType": status }}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.json['data']["status"], "answered") self.assertEqual(response.json['data']["resolutionType"], status) tender = self.db.get(self.tender_id) tender['awards'][0]['complaints'][-1]['dateAnswered'] = (get_now() - timedelta(days=1 if 'procurementMethodDetails' in tender else 4)).isoformat() self.db.save(tender) self.app.authorization = ('Basic', ('chronograph', '')) response = self.app.patch_json('/tenders/{}'.format(self.tender_id), {'data': {'id': self.tender_id}}) self.assertEqual(response.status, '200 OK') self.assertEqual(response.json['data']['awards'][0]["complaints"][-1]['status'], status) class TenderLotAwardComplaintSwitchResourceTest(TenderAwardComplaintSwitchResourceTest): initial_lots = test_lots def setUp(self): super(TenderAwardComplaintSwitchResourceTest, self).setUp() # Create award response = self.app.post_json('/tenders/{}/awards'.format(self.tender_id), {'data': { 'suppliers': [test_organization], 'status': 'pending', 'bid_id': self.initial_bids[0]['id'], 'lotID': self.initial_bids[0]['lotValues'][0]['relatedLot'] }}) award = response.json['data'] self.award_id = award['id'] def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TenderAwardComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderLotAwardComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderLotComplaintSwitchResourceTest)) suite.addTest(unittest.makeSuite(TenderLotSwitchAuctionResourceTest)) suite.addTest(unittest.makeSuite(TenderLotSwitchQualificationResourceTest)) suite.addTest(unittest.makeSuite(TenderLotSwitchUnsuccessfulResourceTest)) suite.addTest(unittest.makeSuite(TenderSwitchAuctionResourceTest)) suite.addTest(unittest.makeSuite(TenderSwitchQualificationResourceTest)) suite.addTest(unittest.makeSuite(TenderSwitchUnsuccessfulResourceTest)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
[ "krzroman@gmail.com" ]
krzroman@gmail.com
8b532e6ce010f813501d899e1d31df5b9d3f6088
c6fa02c9a344fa00ef2c84acd92c6b486d91112f
/testwikipedia.py
b1d3444f3e1122d2be88cd784bc275e6602950fc
[]
no_license
akpamaboris/Projet-5---Grandpy-Bot
3c5d43a2f92965c96652e7eef2894e9dac35b0fa
131dc42300dca3e3558f7faa707b08e79e451894
refs/heads/main
2023-03-02T13:12:01.232394
2021-02-09T09:16:57
2021-02-09T09:16:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
310
py
import wikipedia #ask what the user want searchRequest = input("type what you want") #display the result of the original search print(wikipedia.summary(searchRequest, sentences= 5)) #display some suggestion searchResult = wikipedia.search(str(searchRequest),results=10,suggestion=True) print(searchResult)
[ "zeliwipin@gmail.com" ]
zeliwipin@gmail.com
3448dac14a3b727d73daa977c7f47b07628d492b
4316e03d2238e35a83b5d9c30f7bd4fff1fd75c7
/utrader/strategy/firstTrader.py
e785bd07730282b2a87362c9b466c6096b3849aa
[ "MIT" ]
permissive
ongbe/pymisc
bde92c85dc2042095967346f997e0c100454bcdf
cab57edbbd63b7808a634a9be9f6f7b299e77a0b
refs/heads/master
2021-01-22T10:18:34.644743
2015-01-16T02:24:04
2015-01-16T02:24:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,906
py
# -*- coding: utf-8 -*- import datetime, time, csv, os import numpy as np from utils.db import SqliteDB from utils.rwlogging import log from utils.rwlogging import strategyLogger as logs from utils.rwlogging import balLogger as logb from trader import Trader from indicator import ma, macd, bolling, rsi, kdj from strategy.pool import StrategyPool mas = emas = smas = std = prices = None def runStrategy(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) pool = StrategyPool(100) #t = doTrade(pool, 25, 1.0, 'MA', 7, 'SMA', 12, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.0, 'MA', 7, 'SMA', 13, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.0, 'MA', 7, 'SMA', 12, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) # #t = doTrade(pool, 25, 1.1, 'MA', 7, 'SMA', 12, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.1, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.1, 'MA', 7, 'SMA', 13, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.1, 'MA', 7, 'SMA', 12, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) # #t = doTrade(pool, 25, 1.2, 'MA', 7, 'SMA', 12, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.2, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.2, 'MA', 7, 'SMA', 13, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.2, 'MA', 7, 'SMA', 12, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) # #t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 12, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 13, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 12, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.0, 'MA', 7, 'SMA', 13, 'EMA', 26, 'SMA', 7, 'MA', 12, 'MA', 12) pool.showStrategies() return log.debug('running first strategy ...') starttime = datetime.datetime.now() matypes = ['MA', 'EMA', 'SMA'] #farr = [2, 3, 4, 5, 6, 7, ] #s1arr = [4, 6, 8, 10, 12, 14, 16, 18, 20, ] #s2arr = [0, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, ] farr = [2,] s1arr = [4, ] s2arr = [0, ] pool = StrategyPool(100) for stdPeriod in [20, ]: stdGuage = 0.5 for stdGuage in [1.3, ]: maxAEquity = maxBEquity = 0 poola = StrategyPool(5) poolb = StrategyPool(5) for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA'): continue t = doTrade(poola, stdPeriod, stdGuage, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) if t.equity > maxAEquity: maxAEquity = t.equity maxEAs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info('find A time: ' + str(elapsed) + ' ') #poola.showStrategies() for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA'): continue t = doTrade(poolb, stdPeriod, stdGuage, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) if t.equity > maxBEquity: maxBEquity = t.equity maxEBs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info('find B time: ' + str(elapsed) + ' ') #poolb.showStrategies() logb.info(str(stdPeriod) + ',' + str(stdGuage) + ',' + str(maxAEquity) + ',' + str(maxBEquity)) logb.info(str(maxEAs)) logb.info(str(maxEBs)) for i in range(5): sa = poola.strategies[i] sb = poolb.strategies[i] t = doTrade(pool, stdPeriod, stdGuage, sa[0].args[2], sa[0].args[3], sa[0].args[4], sa[0].args[5], sa[0].args[6], sa[0].args[7], sb[0].args[8], sb[0].args[9], sb[0].args[10], sb[0].args[11], sb[0].args[12], sb[0].args[13]) t.generateGraph() #pool.estimate(t) #stdGuage += 0.1 pool.showStrategies() def doTrade(pool, stdPeriod, stdGuage, afmt, af, as1mt, as1, as2mt, as2, bfmt, bf, bs1mt, bs1, bs2mt, bs2): global std, prices sname = str(stdPeriod) + '_' + str(stdGuage) sname += '_' + afmt + '_' + str(af) + '_' + as1mt + '_' + str(as1) if as2 > 0: sname += '_' + as2mt + '_' + str(as2) sname += '_' + bfmt + '_' + str(bf) + '_' + bs1mt + '_' +str(bs1) if bs2 > 0: sname += '_' + bs2mt + '_' + str(bs2) afma, as1ma, as2ma = getMas(afmt, af), getMas(as1mt, as1), getMas(as2mt, as2) bfma, bs1ma, bs2ma = getMas(bfmt, bf), getMas(bs1mt, bs1), getMas(bs2mt, bs2) front = max(as1, as2, bs1, bs2) t = Trader(sname) t.args = [stdPeriod, stdGuage, afmt, af, as1mt, as1, as2mt, as2, bfmt, bf, bs1mt, bs1, bs2mt, bs2] for i in range(front, len(prices)): price = prices[i] if std[stdPeriod][i] > stdGuage: t.switchActiveCounter(1, price['dt'], price['rmb']) else: t.switchActiveCounter(0, price['dt'], price['rmb']) #if std[stdPeriod][i] > 1.3: # t.switchActiveCounter(1, price['dt'], price['rmb']) #elif std[stdPeriod][i] > stdGuage: # t.switchActiveCounter(0, price['dt'], price['rmb']) #else: # t.switchActiveCounter(2, price['dt'], price['rmb']) if as1 > 0 and afma[i - 1] <= as1ma[i - 1] and afma[i] > as1ma[i]: notes = 'af>as1;' + str(afma[i - 1]) + ';' + str(as1ma[i - 1]) + ';' + str(afma[i]) + ';' + str(as1ma[i]) t.buy(price['dt'], price['rmb'], cntNo=0, notes=notes) if as1 > 0 and afma[i - 1] >= as1ma[i - 1] and afma[i] < as1ma[i]: notes = 'af<as1;' + str(afma[i - 1]) + ';' + str(as1ma[i - 1]) + ';' + str(afma[i]) + ';' + str(as1ma[i]) t.sell(price['dt'], price['rmb'], cntNo=0, notes=notes) if as2 > 0 and afma[i - 1] <= as2ma[i - 1] and afma[i] > as2ma[i]: notes = 'af>as2;' + str(afma[i - 1]) + ';' + str(as2ma[i - 1]) + ';' + str(afma[i]) + ';' + str(as2ma[i]) t.buy(price['dt'], price['rmb'], cntNo=0, notes=notes) if as2 > 0 and afma[i - 1] >= as2ma[i - 1] and afma[i] < as2ma[i]: notes = 'af<as2;' + str(afma[i - 1]) + ';' + str(as2ma[i - 1]) + ';' + str(afma[i]) + ';' + str(as2ma[i]) t.sell(price['dt'], price['rmb'], cntNo=0, notes=notes) if bs1 > 0 and bfma[i - 1] <= bs1ma[i - 1] and bfma[i] > bs1ma[i]: notes = 'bf>bs1;' + str(bfma[i - 1]) + ';' + str(bs1ma[i - 1]) + ';' + str(bfma[i]) + ';' + str(bs1ma[i]) t.buy(price['dt'], price['rmb'], cntNo=1, notes=notes) if bs1 > 0 and bfma[i - 1] >= bs1ma[i - 1] and bfma[i] < bs1ma[i]: notes = 'bf<bs1,' + str(bfma[i - 1]) + ';' + str(bs1ma[i - 1]) + ';' + str(bfma[i]) + ';' + str(bs1ma[i]) t.sell(price['dt'], price['rmb'], cntNo=1, notes=notes) if bs2 > 0 and bfma[i - 1] <= bs2ma[i - 1] and bfma[i] > bs2ma[i]: notes = 'bf>bs2;' + str(bfma[i - 1]) + ';' + str(bs2ma[i - 1]) + ';' + str(bfma[i]) + ';' + str(bs2ma[i]) t.buy(price['dt'], price['rmb'], cntNo=1, notes=notes) if bs2 > 0 and bfma[i - 1] >= bs2ma[i - 1] and bfma[i] < bs2ma[i]: notes = 'bf<bs2;' + str(bfma[i - 1]) + ';' + str(bs2ma[i - 1]) + ';' + str(bfma[i]) + ';' + str(bs2ma[i]) t.sell(price['dt'], price['rmb'], cntNo=1, notes=notes) t.show(price['dt'], price['rmb']) pool.estimate(t) return t def getMas(matype, period): global mas, emas, smas if matype == 'MA': return mas[period] elif matype == 'EMA': return emas[period] elif matype == 'SMA': return smas[period] else: return None def runStrategy_0(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug('running first strategy ...') starttime = datetime.datetime.now() matypes = ['MA', 'EMA', 'SMA'] farr = [2, 3, 4, 5, 6, 7, ] s1arr = [4, 6, 8, 10, 12, 14, 16, 18, 20, ] s2arr = [0, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, ] pool = StrategyPool(100) for stdPeriod in [20, 30, 40]: stdGuage = 1.0 while stdGuage <= 1.3: maxAEquity = maxBEquity = 0 poola = StrategyPool(5) poolb = StrategyPool(5) for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA'): continue t = doTrade(poola, stdPeriod, stdGuage, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) if t.equity > maxAEquity: maxAEquity = t.equity maxEAs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info('find A time: ' + str(elapsed) + ' ') poola.showStrategies() for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA'): continue t = doTrade(poolb, stdPeriod, stdGuage, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) if t.equity > maxBEquity: maxBEquity = t.equity maxEBs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info('find B time: ' + str(elapsed) + ' ') poolb.showStrategies() logb.info(str(stdPeriod) + ',' + str(stdGuage) + ',' + str(maxAEquity) + ',' + str(maxBEquity)) logb.info(str(maxEAs)) logb.info(str(maxEBs)) for i in range(5): sa = poola.strategies[i] sb = poolb.strategies[i] t = doTrade(pool, stdPeriod, stdGuage, sa[0].args[2], sa[0].args[3], sa[0].args[4], sa[0].args[5], sa[0].args[6], sa[0].args[7], sb[0].args[8], sb[0].args[9], sb[0].args[10], sb[0].args[11], sb[0].args[12], sb[0].args[13]) t.generateGraph() pool.estimate(t) stdGuage += 0.1 pool.showStrategies() def runStrategy_1(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug('running first strategy ...') starttime = datetime.datetime.now() strat_as = [ ['MA',6,'SMA',14,'EMA',39], ['MA',7,'SMA',10,'SMA',12], ['MA',7,'SMA',12,'EMA',18], ['MA',7,'SMA',12,'MA',27], ['MA',7,'SMA',12,'SMA',12], ['MA',7,'SMA',14,'EMA',27], ['MA',7,'SMA',14,'EMA',30], ['MA',7,'SMA',14,'EMA',33], ['MA',7,'SMA',14,'EMA',45], ['MA',7,'SMA',14,'MA',27], ['MA',7,'SMA',14,'SMA',15], ['MA',7,'SMA',14,'SMA',30], ['MA',7,'SMA',16,'EMA',24], ['MA',7,'SMA',16,'EMA',27], ['MA',7,'SMA',16,'EMA',30], ['MA',7,'SMA',16,'MA',30] ] strat_bs = [ ['EMA',3,'EMA',16,'MA',42], ['EMA',3,'EMA',16,'MA',45], ['EMA',6,'SMA',6,'MA',30 ], ['EMA',7,'MA',4,'EMA',51 ], ['MA',6,'SMA',16,'EMA',45], ['MA',6,'SMA',18,'MA',36 ], ['MA',6,'SMA',20,'MA',36 ], ['MA',6,'SMA',20,'MA',39 ], ['MA',7,'EMA',18,'EMA',45], ['MA',7,'SMA',12,'EMA',42], ['MA',7,'SMA',12,'SMA',21], ['MA',7,'SMA',14,'EMA',42], ['MA',7,'SMA',14,'MA',45 ], ['MA',7,'SMA',14,'SMA',21], ['SMA',2,'EMA',16,'MA',42], ['SMA',4,'MA',4,'EMA',51 ], ['SMA',5,'MA',4,'MA',15 ], ['SMA',5,'MA',6,'MA',42 ], ['SMA',6,'EMA',10,'MA',36], ['SMA',6,'MA',12,'MA',12 ], ['SMA',7,'MA',12,'EMA',18], ['SMA',7,'MA',12,'EMA',27], ['SMA',7,'MA',12,'EMA',36], ['SMA',7,'MA',12,'EMA',45], ['SMA',7,'MA',12,'EMA',48], ['SMA',7,'MA',12,'MA',12 ], ['SMA',7,'MA',12,'MA',18 ], ['SMA',7,'MA',12,'MA',33 ], ['SMA',7,'MA',12,'MA',36 ], ['SMA',7,'MA',12,'MA',51 ], ['SMA',7,'MA',12,'SMA',15] ] pool = StrategyPool(100) for stdPeriod in [5, 8, 10, 12, 15, 18, 19, 20, 21, 22, 25, 30, 32, 34, 38, 40]: stdGuage = 0.6 while stdGuage <= 2: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + str(stdPeriod) + ',' + str(stdGuage) + ' ==') for sa in strat_as: for sb in strat_bs: doTrade(pool, stdPeriod, stdGuage, sa[0], sa[1], sa[2], sa[3], sa[4], sa[5], sb[0], sb[1], sb[2], sb[3], sb[4], sb[5]) stdGuage += 0.1 pool.showStrategies() return def runStrategy_2(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug('running first strategy ...') starttime = datetime.datetime.now() strat_as = [ ['MA',7,'SMA',10,'SMA',12], ['MA',7,'SMA',14,'EMA',33], ['MA',7,'SMA',16,'EMA',27], ] strat_bs = [ ['SMA',7,'MA',12,'MA',12 ], ['SMA',7,'MA',12,'MA',36 ], ['MA',7,'SMA',14,'EMA',33], ] pool = StrategyPool(100) for stdPeriod in [25]: stdGuage = 1.3 while stdGuage <= 1.3: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + str(stdPeriod) + ',' + str(stdGuage) + ' ==') for sa in strat_as: for sb in strat_bs: doTrade(pool, stdPeriod, stdGuage, sa[0], sa[1], sa[2], sa[3], sa[4], sa[5], sb[0], sb[1], sb[2], sb[3], sb[4], sb[5]) stdGuage += 0.02 pool.showStrategies() return
[ "rolandwz@live.cn" ]
rolandwz@live.cn
7ff75df2b1c5c0598e410fe69b426aac9c93a5e6
40a98f04cba8a8cebda553d5a4bde3ceb95fce3c
/HW2-1 Mathieu equation, discrete variable representation, Matrix - QR algorithm/HW2-1(4).py
385c4250da053a8d1d225a827ade942e0cfd29cf
[]
no_license
Kevinwty0107/Computational-Physics
027551fdb72056ce1459c9af0c4eb21d02321ecb
7ac7f5f17aa8bf71df4c1e38164ceaa932a980d2
refs/heads/master
2020-06-18T07:41:43.525185
2019-07-10T14:22:39
2019-07-10T14:22:39
196,199,186
0
0
null
null
null
null
UTF-8
Python
false
false
7,321
py
#!/usr/bin/python # -*- coding: UTF-8 -*- import math import cmath import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from pylab import * # 导入pylab,构建类似于MATLAB的环境,用于画图 temp = input("请输入M值: ") M = int(temp) n = 2 * M + 1 phi = [0 for i in range(2 * M + 2)] for i in range(1, 2 * M + 2, 1): phi[i] = (2 * math.pi * i) / (2 * M + 1) ql = 10 qr = 11 mr = 11 pxl = [[0 for i in range(qr - ql)] for i in range(n)] bzxl = [[0 for i in range(qr - ql)] for i in range(n)] def sign1(a): if a > 0: return 1 if a < 0: return -1 def fs2(a, m): # 定义2范数函数 c = 0 for i in range(0, m, 1): c += a[i] ** 2 c = math.sqrt(c) return c def jdz(a): if a >= 0: return a else: return -a for q in range(ql, qr, 1): A = [[0 for i in range(2 * M + 2)] for i in range(2 * M + 2)] for j in range(1, 2 * M + 2, 1): for k in range(1, 2 * M + 2, 1): if j == k: A[j][j] = M * (M + 1) / 3 + 2 * q * math.cos(2 * phi[j]) else: A[j][k] = ((-1) ** (j - k)) * math.cos(math.pi * (j - k) / (2 * M + 1)) / ( 2 * math.sin(math.pi * (j - k) / (2 * M + 1)) ** 2) A = np.asarray(A) Uk = [[0 for i in range(2 * M + 1)] for i in range(2 * M + 1)] for i in range(0, 2 * M + 1, 1): Uk[i][i] = 1.0 Uk = np.asarray(Uk) for k in range(1, 2 * M, 1): x = A[k + 1:2 * M + 2, k] e1 = [0 for i in range(2 * M - k + 1)] e1[0] = 1.0 e1 = np.asarray(e1) v = sign1(x[0]) * fs2(x, 2 * M - k + 1) * e1 + x v = v / fs2(v, 2 * M - k + 1) vvT = [[0 for i in range(2 * M - k + 1)] for i in range(2 * M - k + 1)] Uk0 = [[0 for i in range(2 * M + 2)] for i in range(2 * M + 2)] for i in range(1, 2 * M + 2, 1): Uk0[i][i] = 1.0 Uk0 = np.asarray(Uk0) for i in range(0, 2 * M - k + 1, 1): for j in range(0, 2 * M - k + 1, 1): vvT[i][j] = v[i] * v[j] vvT = np.asarray(vvT) Uk0[k + 1:2 * M + 2, k + 1:2 * M + 2] = Uk0[k + 1:2 * M + 2, k + 1:2 * M + 2] - 2 * vvT Uk0 = Uk0[1:2 * M + 2, 1:2 * M + 2] Uk = np.matmul(Uk, Uk0) A[k + 1:2 * M + 2, k:2 * M + 2] = A[k + 1:2 * M + 2, k:2 * M + 2] - 2 * np.matmul(vvT, A[k + 1:2 * M + 2, k:2 * M + 2]) A[1:2 * M + 2, k + 1:2 * M + 2] = A[1:2 * M + 2, k + 1:2 * M + 2] - 2 * np.matmul( A[1:2 * M + 2, k + 1:2 * M + 2], vvT) A = np.asarray(A[1:2 * M + 2, 1:2 * M + 2]) for i in range(0, 2 * M + 1, 1): for j in range(0, 2 * M + 1, 1): if jdz(A[i][j]) < 10 ** (-10): A[i][j] = 0 GT = [[0 for i in range(n)] for i in range(n)] for i in range(0, n, 1): GT[i][i] = 1.0 GT = np.asarray(GT) k = 2 * M while k > 0: if jdz(A[k][k - 1]) < 10 ** (-12): # A[k][k-1]=0 k = k - 1 # print(k) s = A[k][k] for j in range(0, k + 1, 1): A[j][j] -= s for i in range(1, k + 1, 1): a = math.sqrt(A[i - 1][i - 1] ** 2 + A[i][i - 1] ** 2) c = A[i - 1][i - 1] / a s1 = A[i][i - 1] / a G = [[0 for i in range(k + 1)] for i in range(k + 1)] for j in range(0, k + 1, 1): G[j][j] = 1.0 G[i][i] = G[i - 1][i - 1] = A[i - 1][i - 1] / a G[i][i - 1] = -s1 G[i - 1][i] = s1 G = np.asarray(G) A[0:k + 1, 0:k + 1] = np.matmul(G, A[0:k + 1, 0:k + 1]) Gni = G Gni[i][i - 1] = s1 Gni[i - 1][i] = -s1 Gni = np.asarray(Gni) A[0:k + 1, 0:k + 1] = np.matmul(A[0:k + 1, 0:k + 1], Gni) GT0 = [[0 for i in range(n)] for i in range(n)] for i in range(0, n, 1): GT0[i][i] = 1.0 GT0 = np.asarray(GT0) GT0[0:k + 1, 0:k + 1] = Gni GT = np.matmul(GT, GT0) # print(GT) for j in range(0, k + 1, 1): A[j][j] += s Q = np.matmul(Uk, GT) B = [0 for i in range(2 * M + 1)] # c存储按照从小到大排的本征值 pp = [i for i in range(2 * M + 1)] # 存储本征值变换的顺序 for i in range(0, 2 * M + 1, 1): B[i] = A[i][i] for i in range(0, 2 * M + 1, 1): for j in range(i + 1, 2 * M + 1, 1): if B[j] < B[i]: # 按照从小到大排序 sxs = pp[i] pp[i] = pp[j] pp[j] = sxs cc = B[j] B[j] = B[i] B[i] = cc sd = 0 for l in range(0, n, 1): # 按顺序对所有本征值遍历 maxdf = 0 maxddf = 0 #print(B[l]) #print(l) for i in range(1, M + 1, 1): df = 0 ddf = 0 for k in range(0, n, 1): df += Q[k][pp[l]] * math.sin(i * phi[k + 1]) # ddf += Q[k][pp[l]] * math.cos(i * phi[k + 1]) if maxdf < jdz(df): maxdf = jdz(df) if maxddf < jdz(ddf): maxddf = jdz(ddf) if maxddf == 0: continue ggg = maxdf / maxddf if jdz(ggg) < 0.01: # 对任何n,此时sin函数前面系数均为0,即为偶函数 pxl[sd][q - ql] = B[l] # 存本征值 bzxl[sd][q - ql] = pp[l] sd += 1 #print("haha") if sd == 6: break # print(sd) jiaodu = [0.0 for i in range(101)] # 0到90度取100个数 for i in range(0, 101, 1): jiaodu[i] = i * math.pi / 200 # 每个数赋值 jiaodu = np.asarray(jiaodu) for i in range(0, 6, 1): wz = bzxl[i][0] # wz就是本征向量在Q的列数 y = [0.0 for j in range(101)] y = np.asarray(y) # y就是每个本征值下的解函数 for nn in range(1, M + 1, 1): osx = 0.0 jsx = 0.0 for k in range(0, n, 1): osx += Q[k][wz] * math.cos(nn * phi[k + 1]) # 用来计算每个cos函数前的系数 jsx += Q[k][wz] * math.sin(nn * phi[k + 1]) # 用来计算每个sin函数前的系数 y += osx * np.cos(nn * jiaodu) + jsx * np.sin(nn * jiaodu) # 角度相关赋予 print(osx) print(jsx) y *= 2 for k in range(0, n, 1): y += Q[k][wz] # 加上常数项 y=y/(2*math.pi*n) if y[1] < 0: y = -y plt.plot(jiaodu, y, label=pxl[i][0]) plt.legend() show() for q in range(ql, qr, 1): A = [[0 for i in range(2 * M + 2)] for i in range(2 * M + 2)] for j in range(1, 2 * M + 2, 1): for k in range(1, 2 * M + 2, 1): if j == k: A[j][j] = M * (M + 1) / 3 + 2 * q * math.cos(2 * phi[j]) else: A[j][k] = ((-1) ** (j - k)) * math.cos(math.pi * (j - k) / (2 * M + 1)) / ( 2 * math.sin(math.pi * (j - k) / (2 * M + 1)) ** 2) A = np.asarray(A) for i in range(n): print(np.matmul(A[1:n+1,1:n+1],Q[:,pp[i]])-B[i]*Q[:,pp[i]])
[ "noreply@github.com" ]
Kevinwty0107.noreply@github.com
f5bfde126a6a29df67ecd1d7a45fad17ddaf16e7
2e7d48b0364e7c3ec50e2f01f4523092547f0b8c
/employee/settings.py
a6b423bd2a286935b9d13f937589944d29ef4088
[]
no_license
Keval-panchal/employee-management
338cdc4904dceafbe5ee071d00b928422621f28f
cb3de71c40f146049dd6a6b8e2b32112d80426f0
refs/heads/master
2023-02-25T10:20:42.527422
2021-02-04T11:46:50
2021-02-04T11:46:50
335,952,295
0
0
null
null
null
null
UTF-8
Python
false
false
3,172
py
""" Django settings for employee project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&^i0gg7gi@d__u4f1kz2*_&oy*9l!z8ts1)b_lwn8gegh%86r9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'employee_management', ] 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 = 'employee.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 = 'employee.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'EmployeeDB', 'USER':'postgres', 'PASSWORD' : 'root', 'HOST' : 'localhost' } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/'
[ "kevalpan16.com" ]
kevalpan16.com
fa8ea96429fc4b294c397204d76fff3738c33ffb
39230d5ba9ded4155f362c83c472b6b1015ef4db
/movies_django/settings.py
a96d26c841525f1466c8ad51766e07a5eb9c037f
[]
no_license
arjunrawal07/Movie-Plots
b86613b69372acc06601d41ae7610860f2ebca81
074828d6d1feb85342fc2eff0fd6d0fb15d74348
refs/heads/master
2023-01-08T00:40:23.180199
2020-11-10T19:10:43
2020-11-10T19:10:43
311,683,042
0
0
null
null
null
null
UTF-8
Python
false
false
3,219
py
""" Django settings for movies_django project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2d3r+dy1rtbb9job30kb$+*e$m-++0bryl%&-n16f&l72ey9%2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'movies', 'rest_framework', 'django_extensions' ] 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 = 'movies_django.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 = 'movies_django.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'movies', 'USER': 'moviesuser', 'PASSWORD': 'movies', 'HOST': 'localhost' } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/'
[ "arjunrawal07@gmail.com" ]
arjunrawal07@gmail.com
66f644a91d7add2131a05963c6eb5dac0ff9b621
1d583fb6fb8a6661f368cc25c528d87a7536bfa0
/settings.py
ef84ec02f9f8e8a1b38e750bdf8459d953e142ad
[ "Apache-2.0" ]
permissive
gtxll8/Project-P4-Conference-Organization-App
43cd550a0330653e0dde37e9e632f02c2ebddf8b
23ad8773aebcf3ba6bacc4a634a6739ddc89b3a9
refs/heads/master
2020-04-05T22:54:00.339481
2015-09-17T09:28:42
2015-09-17T09:28:42
35,813,384
0
0
null
null
null
null
UTF-8
Python
false
false
569
py
#!/usr/bin/env python """settings.py Udacity conference server-side Python App Engine app user settings $Id$ created/forked from conference.py by wesc on 2014 may 24 """ # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = 'change this with yours.apps.googleusercontent.com' ANDROID_CLIENT_ID = 'replace with Android client ID' IOS_CLIENT_ID = 'replace with iOS client ID' ANDROID_AUDIENCE = WEB_CLIENT_ID
[ "george@chessborg.com" ]
george@chessborg.com
4e3f41a323d30710143803f160a04747c356ac10
469b6c6e2b65778765b29d155396b080f3ee29b6
/qscli/symbol.py
22cd5c814333c4677e06482dc4bbd36210ab15aa
[]
no_license
lexBuright/qscli
2ef8d5c40c4f08142c3ea08c456adcb1e8f4ea48
cb88a6a6abd64b5740d8dd62bd1da834172c36ab
refs/heads/master
2020-12-02T01:04:15.291557
2016-12-08T12:13:26
2016-12-08T12:13:26
67,081,486
3
0
null
null
null
null
UTF-8
Python
false
false
304
py
class Symbol(object): def __init__(self, name): self._name = name def __repr__(self): return 'Symbol({!r})'.format(self._name) def __eq__(self, other): if isinstance(other, Symbol): return self._name == other._name else: return False
[ "lex.buright@gmail.com" ]
lex.buright@gmail.com
e3705b6e3e6596ddd767432482b987a329d5b992
8c8ee70cd4fa1bf99180b5690ad56d806a3a96aa
/auth-service/app/core/startup_message.py
06290494a487e698f38a8828429312fb66a03cf6
[]
no_license
dharm1k987/canvote
705751e5e995992621b6201672315793a84757b7
92f6ff55a8bf87342b66dfe9ff7467377e17bdba
refs/heads/master
2023-03-11T06:32:35.797158
2021-02-20T18:56:59
2021-02-20T18:56:59
289,162,232
0
0
null
null
null
null
UTF-8
Python
false
false
353
py
import logging def log(): logging.info( "\n ____ __ __ _ \n" "/ ___|__ _ _ _\ \ / /__ | |_ ___ \n" "| | / _` | '_ \ \ / / _ \| __/ _ \ \n" "| |__| (_| | | | \ V / (_) | || __/\n" " \____\__,_|_| |_|\_/ \___/ \__\___|\n" "Dharmik Shah; Alvin Tang; Mikhail Makarov\n" )
[ "alvin.tang@mail.utoronto.ca" ]
alvin.tang@mail.utoronto.ca
bc735b594f08d9cb31e34ac012ba93917a178661
993c29f923427c109660d3bdf468dbc093138b0d
/home/models.py
77098972f9d0d35f00e1710a76ed0764a029a521
[]
no_license
kavyak19inapp/BLOG
1b7911bfd3cb52843a485d811efc774eb413b08a
6c0dd6c914f92e653ee8e24941335be8686c999b
refs/heads/master
2020-03-25T01:30:53.656432
2018-08-02T04:19:07
2018-08-02T04:19:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
373
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Post(models.Model): title=models.CharField(max_length=500) user=models.ForeignKey(User) date=models.DateTimeField(auto_now=True) text=models.TextField(null=True) def __str__(self): return self.title
[ "kavya.k@inapp.com" ]
kavya.k@inapp.com
42326f79d5563207aaa63ef2efacb5a69da5ad3f
ddf19cdb482804479d5591f579251a7554514114
/contactproject/contactapp/migrations/0001_initial.py
5b208dae2ce665f2e41a79c58d23ee446c666506
[]
no_license
RAM1119/FEED-BACK-FORM
435d5c95c29bc2f7f9b6676b9fc9f28351cb8131
3cd00d4f07c9aadf3d1f517d3e2397024c5e76f4
refs/heads/main
2023-06-26T18:00:27.928839
2021-07-24T07:57:18
2021-07-24T07:57:18
389,033,415
0
0
null
null
null
null
UTF-8
Python
false
false
597
py
# Generated by Django 3.0.8 on 2021-06-15 06:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('email', models.EmailField(max_length=254)), ('subject', models.TextField()), ], ), ]
[ "66633022+RAM1119@users.noreply.github.com" ]
66633022+RAM1119@users.noreply.github.com
6278bc47adfd78ab192a9368c3a4bd8619e60f7b
6d8565e2412125db2ab4c458e74826558ec36aab
/Old Data Filling Scripts/First_Mission_Scripts.py
a0b167925b780448be482a524167c9c679e1c72d
[]
no_license
Matt88Ac/Hilbert-Huang-Transform-Super-Resolution
61fced1012d1105b02c8dbb78a0059baec9a7287
c03ab4598c044ae893c9d88e03cf75f8d947cd12
refs/heads/master
2023-01-04T20:12:06.347773
2020-11-10T14:24:40
2020-11-10T14:24:40
286,526,251
0
1
null
null
null
null
UTF-8
Python
false
false
7,525
py
from Develop.EMD2D import EMD2D import numpy as np import pandas as pd # from matplotlib.pyplot import imshow, imread import cv2 import os import platform from PIL.Image import fromarray # import time class Run: def __init__(self, csv_name: str): self.table = pd.read_csv(csv_name) # self.table = self.table.dropna() self.table = self.table.drop_duplicates(subset='File Name', keep=False) self.emd = EMD2D self.emd.MAX_ITERATION = 10 ** 4 # self.emd.mean_thr = 0.0001 # self.emd.mse_thr = 0.001 self.name = csv_name self.platform = platform.system() def checkExistence(self): temp = self.table['File Name'].copy() temp = np.array(temp, dtype=str) l1 = self.getFileNames() if len(temp) == 0: return l1 l2 = ['DATA/' + y for y in l1] l1 = np.setdiff1d(l2, temp) return np.array([y[5:] for y in l1], dtype=str) def getFileNames(self): if self.platform == 'Windows': dirc = os.getcwd() dirc = dirc.replace(dirc[2], '/') + '/DATA' self.dir = dirc return np.array(os.listdir(dirc), dtype=str) else: dirc = os.getcwd() + "/DATA" self.dir = dirc return np.array(os.listdir(dirc), dtype=str) def AddToCSV(self, fname: str, mode, resolution, mean, median, mx, mn, imfs, rmse, trace, diff0, diff1): to_append = pd.DataFrame({'File Name': [fname], 'Color Mode': [mode], 'Resolution': [resolution], 'Mean Pixel Value': [mean], 'Median Pixel Value': [median], 'Max Pixel Value': [mx], 'Min Pixel Value': [mn], 'Log Trace': [np.log(trace)], 'Difference-Axis0': [diff0], 'Difference-Axis1': [diff1], 'Number of IMFs': [imfs], 'RMSE': rmse}) self.table = self.table.append(to_append) self.table.to_csv(self.name, index=False) def RunGreys(self): toOpen = self.checkExistence() toOpen = toOpen[::-1] def RMSE(expected: np.ndarray, estimated: np.ndarray): if expected.shape != estimated.shape: x1 = fromarray(expected) x2 = fromarray(np.sum(estimated, axis=0)) x1.show() x2.show() return 300 diff = np.sum((expected - estimated) ** 2) pixSize = expected.shape[0] * expected.shape[1] return (diff / pixSize) ** 0.5 def Trace(pic: np.ndarray): mx = max(pic.shape[0], pic.shape[1]) to_ret = np.zeros((mx, mx)) to_ret[:pic.shape[0], :pic.shape[1]] = pic.copy() return np.trace(to_ret) def Diffs(pic: np.ndarray): return abs(np.diff(pic.astype(int), axis=0)).max(), abs(np.diff(pic.astype(int), axis=1)).max() for name in toOpen: print(name) fname = 'DATA/' + name # 'road_image.jpg' img = cv2.imread(fname, 0) resolution = img.shape color_mode = 'Grey' maxp = img.max() minp = img.min() med = np.median(img) mean = img.mean() tr = Trace(img) dif0, dif1 = Diffs(img) try: picDecomposed = self.emd(img) # X, Y = self.emd.find_extrema(img) # print('X = ', X) # print('Y = ', Y) # print(self.emd.find_extrema(img)) # x1 = fromarray(picDecomposed[0]+picDecomposed[1]) # x1.show() # print(picDecomposed.shape) # tr = Trace(img) # dif0, dif1 = Diffs(img) numOfIMFs = picDecomposed.IMFs.shape[0] rmse = RMSE(img, picDecomposed.reConstruct()) self.AddToCSV(fname=fname, mode=color_mode, resolution=resolution, mean=mean, median=med, mx=maxp, mn=minp, imfs=numOfIMFs, rmse=rmse, trace=tr, diff0=dif0, diff1=dif1) except ValueError: # TODO: Research into traceback of errors on the "bad images", and check for the conditions required. # Add yet images to the csv file to avoid re-running on bad files. self.AddToCSV(fname, color_mode, resolution, mean, med, maxp, minp, -1, -1, trace=tr, diff0=dif0, diff1=dif1) print("Error occured during process {}".format(name)) def RunColored(self): toOpen = self.checkExistence() def RMSE(expected: np.ndarray, estimated: np.ndarray): if expected.shape != estimated.shape: x1 = fromarray(expected) x2 = fromarray(np.sum(estimated, axis=0)) x1.show() x2.show() return 300 diff = np.sum((expected - estimated) ** 2) pixSize = expected.shape[0] * expected.shape[1] * 3 return (diff / pixSize) ** 0.5 def Trace(pic: np.ndarray): def getT(i: int): mx = max(pic.shape[0], pic.shape[1]) to_ret = np.zeros((mx, mx)) to_ret[:pic.shape[0], :pic.shape[1]] = pic[:, :, i].copy() return np.trace(to_ret) return (getT(0) + getT(1) + getT(2)) / 3 def Diffs(pic: np.ndarray): return abs(np.diff(pic.astype(int), axis=0)).max(), abs(np.diff(pic.astype(int), axis=1)).max() for name in toOpen: print(name) fname = 'DATA/' + name # 'road_image.jpg' img = cv2.imread(fname) resolution = img.shape color_mode = 'RGB' maxp = img.max() minp = img.min() med = np.median(img) mean = img.mean() tr = Trace(img) dif0, dif1 = Diffs(img) try: picDecomposed = self.emd(img) # X, Y = self.emd.find_extrema(img) # print('X = ', X) # print('Y = ', Y) # print(self.emd.find_extrema(img)) # x1 = fromarray(picDecomposed[0]+picDecomposed[1]) # x1.show() # print(picDecomposed.shape) # tr = Trace(img) # dif0, dif1 = Diffs(img) numOfIMFs = picDecomposed.NoIMFs rmse = RMSE(img, picDecomposed.reConstruct()) self.AddToCSV(fname=fname, mode=color_mode, resolution=resolution, mean=mean, median=med, mx=maxp, mn=minp, imfs=numOfIMFs, rmse=rmse, trace=tr, diff0=dif0, diff1=dif1) except Exception as ex: # TODO: Research into traceback of errors on the "bad images", and check for the conditions required. # Add yet images to the csv file to avoid re-running on bad files. self.AddToCSV(fname, color_mode, resolution, mean, med, maxp, minp, -1, -1, trace=tr, diff0=dif0, diff1=dif1) print("Error occured during process {}".format(name))
[ "Matt8ac@gmail.com" ]
Matt8ac@gmail.com
808a63ee09068286a0356c2c688589f9f0f8c100
0ce9a72c7d66b71f95ce34ac9103b11026a14e4e
/brisk/src/util.py
ae08b60db6ce08bfb862743c2c9b99371e3ece46
[]
no_license
yanqingda/web-crawlers
9eebafdb55cd9d968f8b33d2f835ad905c300cd0
0b4b04e5b432f2bbfd930b11cb71f0e144ad9cfe
refs/heads/master
2020-09-25T13:57:51.417822
2019-09-23T09:02:07
2019-09-23T09:02:07
226,018,013
0
0
null
2019-12-05T04:45:34
2019-12-05T04:45:34
null
UTF-8
Python
false
false
4,035
py
import abc import logging import os import random import threading from configparser import ConfigParser import bs4 import redis import requests from requests.models import Response from src.constant import ua class Logger(): _instance_lock = threading.Lock() def __new__(cls, *args, **kwargs): if not hasattr(Logger, "_instance"): with Logger._instance_lock: if not hasattr(Logger, "_instance"): Logger._instance = object.__new__(cls) return Logger._instance def __init__(self): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(threadName)s: %(message)s') logging.root.setLevel(level=logging.INFO) self.logger = logging.getLogger() class Config(): _instance_lock = threading.Lock() _config_parser = ConfigParser() def __new__(cls, *args, **kwargs): if not hasattr(Config, "_instance"): with Config._instance_lock: if not hasattr(Config, "_instance"): Config._instance = object.__new__(cls) return Config._instance def __init__(self): self.__path = r'./config.ini' self.config = Config._config_parser self.config.read(self.__path, encoding='utf-8') class DB(): _instance_lock = threading.Lock() def __new__(cls, *args, **kwargs): if not hasattr(DB, "_instance"): with DB._instance_lock: if not hasattr(DB, "_instance"): DB._instance = object.__new__(cls) return DB._instance def __init__(self): super(DB, self).__init__() # TODO self.default_db = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) self.proxy_db = redis.Redis(host='localhost', port=6379, db=1, decode_responses=True) self.db = self.default_db class Request(): def __init__(self): self.__ua = random.choice(ua) self.__headers = { 'User-Agent': '{}'.format(self.__ua), 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.8' } self.__cookies = None self.__session = requests.Session() def make(self, headers=None, cookies=None): self.headers = headers self.cookies = cookies @property def headers(self): return self.__headers @headers.setter def headers(self, value): self.__headers = { 'User-Agent': '{}'.format(self.__ua), 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.8' } if not value else value @property def session(self): return self.__session @abc.abstractmethod def get_token(self): pass @abc.abstractmethod def set_token(self, **kwargs): self.__headers.update(**kwargs) @abc.abstractmethod def clear_token(self): pass @abc.abstractmethod def refresh_token(self): pass @property def cookies(self): return self.__cookies @cookies.setter def cookies(self, value): self.__cookies = value def get(self, url, params=None, **kwargs): return requests.get(url=url, params=params, headers=self.headers, cookies=self.cookies, **kwargs) def post(self, url, data, **kwargs): return requests.post(url=url, data=data, headers=self.headers, cookies=self.cookies, **kwargs) def res2soup(self, response: Response): return bs4.BeautifulSoup(response.content, 'lxml') def res2json(self, response: Response): return response.json() def get_soup(self, url, params=None, **kwargs): return self.res2soup(self.get(url=url, params=params, **kwargs)) def get_json(self, url, params=None, **kwargs): return self.res2json(self.get(url=url, params=params, **kwargs)) if __name__ == '__main__': obj1 = Request() obj2 = Request() print(id(obj1), id(obj2))
[ "96486d9b@gmail.com" ]
96486d9b@gmail.com
79c72c07ad565a711f39bbc2ccd572d86aab50e6
3929e04d4f075a22fd12817366046ab8db5cf5f8
/km-52/Mitrokhin_Oleksii/project/Code/source/dao/user_stuff.py
0184719ec801e05d2e15cdceec568c46eb67f7ee
[]
no_license
oMitrokhin/dbisworkshops
29c2dd3cd102bf36d5cf886f969885a4619885ba
9e780aadaa462b76102ff0a2c68394aa40afdec5
refs/heads/master
2020-04-05T19:14:55.030318
2019-01-23T05:52:15
2019-01-23T05:52:15
157,125,628
0
0
null
2018-11-11T22:04:36
2018-11-11T22:04:36
null
UTF-8
Python
false
false
5,853
py
import cx_Oracle from source.dao.connect_info import * from datetime import date, datetime def getUserIndex(user_email): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.execute('select * from "User"') result = cursor.fetchall() index_m = [row[0] for row in result].index(user_email) cursor.close() return index_m def getUserPass(user_email): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.execute('select * from "User"') result = cursor.fetchall() user_pass = result[getUserIndex(user_email)][2] return user_pass def getUserRole(user_email): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.execute('select * from "User"') result = cursor.fetchall() user_role = result[getUserIndex(user_email)][1] return user_role def regUser(user_email, user_password, user_information): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.callproc("User_auth.registration", [user_email, user_password, user_information]) cursor.close() connection.close() return user_email def getUsers(): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() query = 'SELECT * FROM table(P_User.get_users_list)' cursor.execute(query) result = cursor.fetchall() cursor.close() connection.close() return result def blockUser(user_email): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.callproc("P_User.block_un_user", [user_email]) cursor.close() connection.close() return user_email def deleteUser(user_email): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.callproc("P_User.delete_user", [user_email]) cursor.close() connection.close() return user_email def getUserProduct(user_email): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() query = 'SELECT * FROM table(P_user_product.get_user_product(:user_email))' cursor.execute(query, user_email=user_email) result = cursor.fetchall() cursor.close() connection.close() return result def deleteUserProduct(user_email, product_name, purchase_date): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.callproc("P_user_product.delete_user_product", [user_email, product_name, purchase_date]) cursor.close() connection.close() return product_name def editUserProduct(user_email, product_name, purchase_date, product_price, product_count, product_priority): connection = cx_Oracle.connect(username,password,databaseName) cursor = connection.cursor() cursor.callproc("P_user_product.edit_product_in_userbase", [user_email, product_name, purchase_date, product_price, product_count, product_priority]) cursor.close() connection.close() return product_name def getProducts(): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() query = 'SELECT * FROM table(P_Av_PR.get_available_product())' cursor.execute(query) result = cursor.fetchall() cursor.close() connection.close() return result def addProduct(user_email, product_name, purchase_date, user_product_price, product_count, product_priority): connection = cx_Oracle.connect(username, password, databaseName) product_list = getUserProduct(user_email) prod_name = [row[0] for row in product_list] product_purchase_date=[]; i=0; pr_list=[] while i<len(product_list): product_purchase_date.append(datetime.strftime(product_list[i][2],'%Y-%m-%d')) pr_list.append([prod_name[i],product_purchase_date[i]]) i=i+1 if [product_name,datetime.strftime(purchase_date,'%Y-%m-%d')] in pr_list: connection.close() return 1 else: cursor = connection.cursor() cursor.callproc("P_user_product.add_product_to_userbase", [user_email, product_name, purchase_date, user_product_price, product_count, product_priority]) cursor.close() connection.close() return 0 def deleteProductFromBase(product_name): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() cursor.callproc("P_Av_PR.delete_product_from_base", [product_name]) cursor.close() connection.close() return product_name def addNewProductToBase(product_name,product_price): connection = cx_Oracle.connect(username, password, databaseName) product_list = getProducts() if product_name in ([row[0] for row in product_list]): connection.close() return 1 else: cursor = connection.cursor() cursor.callproc("P_Av_PR.add_product_to_base", [product_name, product_price]) cursor.close() connection.close() return 0 def recomendation(user_email, from_date, to_date, count): connection = cx_Oracle.connect(username, password, databaseName) cursor = connection.cursor() query = 'SELECT * FROM TABLE (P_Recomendation.get_recomendation(:check_email, :start_date, :end_date, :total_count))' cursor.execute(query,check_email = user_email, start_date = from_date, end_date = to_date, total_count = count) result = cursor.fetchall() cursor.close() connection.close() return result
[ "noreply@github.com" ]
oMitrokhin.noreply@github.com
52f9db58c0d8c17852b4481883512118c48a03cb
24b1fa231f4e89f1a588c09ebee6fe4da6915c53
/Python/ComplexNumbers.py
8fc7cf399e2d2410ccb14b48589942a35939b65c
[]
no_license
cyrt63/demos
a429214154cf0e51b58710f67670e1d902bfcac6
a4b54b862dba4ad33a707511896324829f4cc7b1
refs/heads/master
2020-04-08T13:51:40.823058
2015-04-21T14:01:41
2015-04-21T14:01:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
437
py
from cmath import * z = complex(11.0, 7.0) w = complex(5, 3) print z.real print z.imag print "----------" print z print str(z) print repr(z) print "----------" print z + w print z - w print z * w print z / w print "----------" print z == z print z != z print z == w print z != w print "----------" print phase(complex(-1.0, 0.0)) print phase(z) print type(1.0) print type(z)(1.0,3) print type(z) print str(type(z)) print repr(type(z))
[ "geometryzen@gmail.com" ]
geometryzen@gmail.com
a5e0a9363d93f8f79bc98a1cb66fb9397826adc5
e693f5662dfca3d66297f9633ade77b6f4165319
/balance_keeper/withdraw_all.py
9be1a8c1a5129eb34d5f08cb044d245b896261d8
[]
no_license
AlexChien/operation_tools
8c502b54472f86d063adfcaf18f3c524092be732
e3d137ba7c5c7122a42237f820b58d90181ac139
refs/heads/master
2021-01-18T12:01:10.444027
2015-01-13T16:56:46
2015-01-13T16:56:46
27,987,778
0
1
null
null
null
null
UTF-8
Python
false
false
1,963
py
#!/usr/bin/env python # coding=utf8 # withdraw all delegate pay to the account specified in the config import requests import sys import os import json import getpass import time import datetime from pprint import pprint BTS_PRECISION = 100000 config_data = open('config.json') config = json.load(config_data) config_data.close() auth = (config["bts_rpc"]["username"], config["bts_rpc"]["password"]) url = config["bts_rpc"]["url"] WALLET_NAME = config["wallet_name"] DELEGATE_NAME = config["delegate_name"] PAYTO = config["payto_account"] THRESH = config["balance_threshold"] def parse_date(date): return datetime.datetime.strptime(date, "%Y%m%dT%H%M%S") def call(method, params=[]): headers = {'content-type': 'application/json'} request = { "method": method, "params": params, "jsonrpc": "2.0", "id": 1 } while True: try: response = requests.post(url, data=json.dumps(request), headers=headers, auth=auth) result = json.loads(vars(response)["_content"]) #print "Method:", method #print "Result:", result return result except: print "Warnning: rpc call error, retry 5 seconds later" time.sleep(5) continue break return None os.system("clear") response = call("wallet_get_account", [DELEGATE_NAME] ) if "error" in response: print("FATAL: Failed to get info:") print(result["error"]) exit(1) response = response["result"] balance = response["delegate_info"]["pay_balance"] / BTS_PRECISION print ("Balance for %s is currently: %s BTS" % (DELEGATE_NAME, balance)) print("wallet_delegate_withdraw_pay %s, %s, %s" % (DELEGATE_NAME, PAYTO, balance)) response = call("wallet_delegate_withdraw_pay", [DELEGATE_NAME, PAYTO, balance]) if "error" in response: print("FATAL: Failed to wallet_delegate_withdraw_pay:") print(response ["error"]) exit(1) else: print("Successfully withdrawn %s BTS to %s!" % (balance, PAYTO))
[ "alex.chien@koocaa.com" ]
alex.chien@koocaa.com
3f9b3067b2302ff609c39947cbfd6ebfa43915a4
bfc7f86ed56ad6398e177b1411256cfb4cc1b172
/models.py
a87493b10e430bf2c8fe9acbff759e0b22c070cd
[]
no_license
nnkkmto/product-based-neural-networks-tf2
7043db4378bf3472b492018919aeb98d8617cd7c
5ea500529d981ea7e7d84d46b1db92c922ed8505
refs/heads/master
2022-12-24T10:11:07.790384
2020-09-24T12:52:13
2020-09-24T12:52:13
298,277,658
1
0
null
null
null
null
UTF-8
Python
false
false
5,952
py
""" ちょっと論文と相違あるが、 https://github.com/Atomu2014/product-nets をベースに実装する """ import itertools from collections import OrderedDict import tensorflow as tf class EmbeddingLayer(tf.keras.layers.Layer): def __init__(self, features_info, emb_dim, name_prefix=''): """ sequence対応のembedding layer """ super(EmbeddingLayer, self).__init__() self.features_info = features_info self.feature_to_embedding_layer = OrderedDict() for feature in features_info: initializer = tf.keras.initializers.RandomNormal(stddev=0.01, seed=None) if feature['is_sequence']: # sequenceのembedding self.feature_to_embedding_layer[feature['name']] = tf.keras.layers.Embedding( feature['dim'], emb_dim, mask_zero=True, name=f"embedding_{name_prefix}{feature['name']}", embeddings_initializer=initializer) else: self.feature_to_embedding_layer[feature['name']] = tf.keras.layers.Embedding( feature['dim'], emb_dim, name=f"embedding_{name_prefix}{feature['name']}", embeddings_initializer=initializer) def concatenate_embeddings(self, embeddings, name_prefix=''): if len(embeddings) >= 2: embeddings = tf.keras.layers.Concatenate(axis=1, name=name_prefix+'embeddings_concat')(embeddings) else: embeddings = embeddings[0] return embeddings def call(self, inputs): embeddings = [] for feature_input, feature in zip(inputs, self.features_info): # embeddingの作成 embedding = self.feature_to_embedding_layer[feature['name']](feature_input) if feature['is_sequence']: # sequenceの場合はaverage pooling embedding = tf.math.reduce_mean(embedding, axis=1, keepdims=True) embeddings.append(embedding) # concatenate embeddings = self.concatenate_embeddings(embeddings) return embeddings class InnerProductLayer(tf.keras.layers.Layer): def __init__(self, emb_dim, pair_num): super(InnerProductLayer, self).__init__() self.inner_weights = tf.Variable(tf.random.normal([pair_num, emb_dim],0.0,0.01)) def call(self, p, q): weights = tf.expand_dims(self.inner_weights, 0) # (1, pair_num, emb_dim) lp = tf.reduce_sum(p * q * weights, -1) # (batch_size, pair_num) return lp class OuterProductLayer(tf.keras.layers.Layer): def __init__(self, emb_dim, pair_num): super(InnerProductLayer, self).__init__() self.outer_weights = tf.Variable(tf.random.normal([emb_dim, pair_num, emb_dim],0.0,0.01)) def call(self, p, q): p = tf.expand_dims(p, 1) # (batch_size, 1, pair_num, emb_dim) p = tf.multiply(p, self.outer_weights) # (batch_size, emb_dim, pair_num, emb_dim) p = tf.reduce_sum(p, -1) # (batch_size, emb_dim, pair_num) p = tf.transpose(p, [0, 2, 1]) # (batch_size, pair_num, emb_dim) lp = tf.multiply(p, q) # (batch_size, pair_num, emb_dim) lp = tf.reduce_sum(lp, -1) # (batch_size, pair_num) return lp class ProductLayer(tf.keras.layers.Layer): def __init__(self, features_info, emb_dim, implementation_type='inner'): super(ProductLayer, self).__init__() self.implementation_type = implementation_type self.field_index_pairs = list(itertools.combinations(range(len(features_info)), 2)) pair_num = len(self.field_index_pairs) self.field_index_row = [combination[0] for combination in self.field_index_pairs] self.field_index_col = [combination[1] for combination in self.field_index_pairs] if implementation_type == 'inner': self.layer = InnerProductLayer(emb_dim, pair_num) elif implementation_type == 'outer': self.layer = OuterProductLayer(emb_dim, pair_num) else: # 指定なければ両方のconcatenateを返す self.inner_layer = InnerProductLayer(emb_dim, pair_num) self.outer_layer = OuterProductLayer(emb_dim, pair_num) def call(self, embeddings): p = tf.gather(tf.transpose(embeddings, [1, 0, 2]), self.field_index_row) # (pair_num, batch_size, emb_dim) p = tf.transpose(p, [1, 0, 2]) # (batch_size, pair_num, emb_dim) q = tf.gather(tf.transpose(embeddings, [1, 0, 2]), self.field_index_col) q = tf.transpose(q, [1, 0, 2]) if self.implementation_type in ['inner', 'outer']: lp = self.layer(p, q) else: lp_inner = self.inner_layer(p, q) lp_outer = self.outer_layer(p, q) lp = tf.keras.layers.Concatenate(axis=1, name='lp_concat')([lp_inner, lp_outer]) return lp class PNN(tf.keras.Model): def __init__(self, features_info, emb_dim=20, deep_layer_size=30, dropout_rate=0.3): super(PNN, self).__init__() self.dropout_rate = dropout_rate self.embedding_layer = EmbeddingLayer(features_info, emb_dim) self.product_layer = ProductLayer(features_info, emb_dim) self.d1 = tf.keras.layers.Dense(deep_layer_size, activation='relu') self.d2 = tf.keras.layers.Dense(1, activation='sigmoid') def call(self, inputs): embeddings = self.embedding_layer(inputs) # (batch_size, field_num, emb_dim) lz = tf.keras.layers.Flatten()(embeddings) # (batch_size, field_num*emb_dim) lp = self.product_layer(embeddings) output = tf.keras.layers.Concatenate(axis=1, name='lp_concat')([lz, lp]) # deep layer output = self.d1(output) output = tf.keras.layers.Dropout(self.dropout_rate)(output) output = self.d2(output) return output
[ "rbnok.lec@gmail.com" ]
rbnok.lec@gmail.com
02207e34859396112b0390e2fa0cd14679d35a75
4cc17852dfa61c508cccc50325bea34f02fbe711
/spotbox/spotboxplayback.py
fb7a9f2dae53183f971a9fe156948ab0ae57c060
[]
no_license
kzsu/spotbox
a408a2d192ba05c5f2b3ee760e482e4ee079cf5d
a888c3a957f25e1576ac46a0243e361d10a615e9
refs/heads/master
2021-01-21T19:27:26.280329
2019-04-17T04:55:40
2019-04-17T04:55:40
18,824,477
0
0
null
2019-04-17T04:55:42
2014-04-16T02:46:08
Python
UTF-8
Python
false
false
3,097
py
#!/usr/bin/python """SPOTBOX media playback backend""" # Note-- non-iTunes mode is not yet fully implemented. class Playback: """A playback object, allows for audio files to be loaded, played back, and stopped whilst playing. """ def __init__(self): pass def initialize_one_player(self, spotnumber): pass def load(self, spotnumber, filepath): pass def play(self, spotnumber): pass def stop(self): pass class iTunesPlayback(Playback): # imperfect: itunes volume/ repeat mode is not currently handled directly. def __init__(self): import appscript import mactypes # TODO - number of playlists. self.itunes = self.appscript.app('iTunes') # make sure iTunes is opened???? TODO # USEFUL: applescript directory: # http://www.mugginsoft.com/html/kosmictask/ASDictionaryDocs/Apple/ #iTunes/OS-X-10.7/iTunes-10.6.1/html/ def initialize_one_player(self, spotnumber): # iTunes doesn't need to, assuming the playlists # have been created (TODO - check?) #try: # tab.visible() #except: # throw a toplevel warning to create such a playlist... pass def stop(self): self.itunes.stop() def load(self, spotnumber, filepath): playlisttoload = self.itunes.playlists['SPOTBOX' + str(spotnumber + 1)] playlisttracks = playlisttoload.tracks() if len(playlisttracks) > 0: self.itunes.delete(playlisttoload.tracks) self.itunes.add(self.mactypes.Alias(filepath), to=playlisttoload) # Now check to make sure the file actually loaded: playlisttracks = playlisttoload.tracks() if len(playlisttracks) == 0: # if the playlist is now empty, it's an error. don't continue. # possible reasons: it's a non-music file, that iTunes won't accept # it's a corrupted mp3, etc # Don't list the name in the 'load' text. return False # Check (enable) the file, (index 0 because # there can be only one) to make sure it plays! playlisttracks[0].enabled.set(1) return True def play(self, spotnumber): self.itunes.play(self.itunes.playlists['SPOTBOX'+str(spotnumber+1)]) class PygletPlayback(Playback): def __init__(self): import pyglet self.playerarray = [] def initialize_one_player(self, spotnumber): pygplayer = self.pyglet.media.Player() self.playerarray.append(pygplayer) def stop(self): for player in self.playerarray: player.pause() def load(self, spotnumber, filepath): # at moment, throws "NOT A WAVE" exception, even for .wav print filepath media = self.pyglet.media.load(filepath, streaming=False) del self.playerarray[spotnumber] self.playerarray[spotnumber].queue(media) def play(self, spotnumber): self.playerarray[spotnumber].play() if __name__ == '__main__': pass
[ "bufordsharkley@gmail.com" ]
bufordsharkley@gmail.com
4cc4ac19939b02652c2a1adf8f6b0f1df2edc107
09edc17c381061e2725f3b4bd67cfb7e546e0918
/Zylabs10-19.py
c11415c497acc80d4fb338b6ce14f6724bff00a4
[]
no_license
AMOviedo15/Homework3
ab34d35131e85d0a51c5d1dbe254b9c0cc3a903e
c1977af43fd33fdc72223124b2087c982e01f5a5
refs/heads/main
2023-03-29T02:30:23.170717
2021-03-31T02:00:22
2021-03-31T02:00:22
352,417,735
0
0
null
null
null
null
UTF-8
Python
false
false
5,568
py
# Aaron Oviedo 1990958 class ItemToPurchase: def __init__(self, item_name = "none", item_price = 0, item_quantity = 0, item_description = "none"): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity self.item_description = item_description def print_item_cost(self): print(self.item_name + " " + str(self.item_quantity) + " @ $" + str(self.item_price) + " = $" + str(self.item_price * self.item_quantity)) def print_item_description(self): print(self.item_name + ": " + str(self.item_description)) class ShoppingCart: def __init__(self, customer_name='none', current_date='January 1, 2016'): self.customer_name = customer_name self.current_date = current_date self.cart_items = [] def add_item(self, ItemToPurchase): self.cart_items.append(ItemToPurchase) def remove_item(self, itemName): RemoveIt = False for item in self.cart_items: if item.item_name == itemName: self.cart_items.remove(item) RemoveIt = True break if not RemoveIt: print('Item not found in cart. Nothing removed.') def modify_item(self, itemToPurchase): ModifyIt = False for i in range(len(self.cart_items)): if self.cart_items[i].item_name == itemToPurchase.item_name: ModifyIt = True if ( itemToPurchase.item_price == 0 and itemToPurchase.item_quantity == 0 and itemToPurchase.item_description == 'none'): break else: if (itemToPurchase.item_price != 0): self.cart_items[i].item_price = itemToPurchase.item_price if (itemToPurchase.item_quantity != 0): self.cart_items[i].item_quantity = itemToPurchase.item_quantity if (itemToPurchase.item_description != 'none'): self.cart_items[i].item_description = itemToPurchase.item_description break if not ModifyIt: print('Item not found in cart. Nothing modified.') def get_num_items_in_cart(self): num_items = 0 for item in self.cart_items: num_items = num_items + item.item_quantity return num_items def get_cost_of_cart(self): total_cost = 0 cost = 0 for item in self.cart_items: cost = (item.item_quantity * item.item_price) total_cost += cost return total_cost def print_total(self): total_cost = self.get_cost_of_cart() print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date)) print('Number of Items: %d\n' % self.get_num_items_in_cart()) for item in self.cart_items: item.print_item_cost() if (total_cost == 0): print('SHOPPING CART IS EMPTY') print('\nTotal: $%d' % (total_cost)) def print_descriptions(self): if len(self.cart_items) == 0: print('SHOPPING CART IS EMPTY') else: print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date)) print('\nItem Descriptions') for item in self.cart_items: item.print_item_description() def print_menu(newCart): customer_Cart = newCart menu = ('\nMENU\n' 'a - Add item to cart\n' 'r - Remove item from cart\n' 'c - Change item quantity\n' "i - Output items' descriptions\n" 'o - Output shopping cart\n' 'q - Quit\n') command = '' while (command != 'q'): print(menu) command = input('Choose an option:\n') while ( command != 'a' and command != 'o' and command != 'i' and command != 'q' and command != 'r' and command != 'c'): command = input('Choose an option:\n') if (command == 'a'): print("\nADD ITEM TO CART") item_name = input('Enter the item name:\n') item_description = input('Enter the item description:\n') item_price = int(input('Enter the item price:\n')) item_quantity = int(input('Enter the item quantity:\n')) itemtoPurchase = ItemToPurchase(item_name, item_price, item_quantity, item_description) customer_Cart.add_item(itemtoPurchase) elif (command == 'o'): print('OUTPUT SHOPPING CART') customer_Cart.print_total() elif (command == 'i'): print('\nOUTPUT ITEMS\' DESCRIPTIONS') customer_Cart.print_descriptions() elif (command == 'r'): print('REMOVE ITEM FROM CART') itemName = input('Enter name of item to remove:\n') customer_Cart.remove_item(itemName) elif (command == 'c'): print('\nCHANGE ITEM QUANTITY') itemName = input('Enter the item name:\n') qty = int(input('Enter the new quantity:\n')) itemToPurchase = ItemToPurchase(itemName, 0, qty) customer_Cart.modify_item(itemToPurchase) if __name__ == "__main__": customer_name = input("Enter customer's name:\n") current_date = input("Enter today's date:\n") print("\nCustomer name: %s" % customer_name) print("Today's date: %s" % current_date) newCart = ShoppingCart(customer_name, current_date) print_menu(newCart)
[ "noreply@github.com" ]
AMOviedo15.noreply@github.com
50d9481dbc0429d159fb1ee590a9643f6adb4098
e82b761f53d6a3ae023ee65a219eea38e66946a0
/All_In_One/addons/vb25/plugins/SettingsDMCSampler.py
5efb838f6b0f38ed09b7546196157f7e15f47e50
[]
no_license
2434325680/Learnbgame
f3a050c28df588cbb3b14e1067a58221252e2e40
7b796d30dfd22b7706a93e4419ed913d18d29a44
refs/heads/master
2023-08-22T23:59:55.711050
2021-10-17T07:26:07
2021-10-17T07:26:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,919
py
''' V-Ray/Blender http://vray.cgdo.ru Author: Andrey M. Izrantsev (aka bdancer) E-Mail: izrantsev@cgdo.ru This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. All Rights Reserved. V-Ray(R) is a registered trademark of Chaos Software. ''' ''' Blender modules ''' import bpy from bpy.props import * ''' vb modules ''' from vb25.utils import * from vb25.ui import ui TYPE= 'SETTINGS' ID= 'SettingsDMCSampler' NAME= 'DMC sampler' DESC= "DMC sampler options" PARAMS= ( 'time_dependent', 'adaptive_amount', 'adaptive_threshold', 'adaptive_min_samples', 'subdivs_mult', ) def add_properties(rna_pointer): class SettingsDMCSampler(bpy.types.PropertyGroup): pass bpy.utils.register_class(SettingsDMCSampler) rna_pointer.SettingsDMCSampler= PointerProperty( name= "DMC Sampler", type= SettingsDMCSampler, description= "DMC Sampler settings" ) SettingsDMCSampler.adaptive_threshold= FloatProperty( name= "Noise threshold", description= "Controls V-Ray's judgement of when a blurry value is \"good enough\" to be used", min= 0.0, max= 1.0, soft_min= 0.001, soft_max= 0.1, default= 0.01, precision= 3 ) SettingsDMCSampler.adaptive_min_samples= IntProperty( name= "Min samples", description= "The minimum number of samples that must be made before the early termination algorithm is used", min= 1, max= 1000, default= 8 ) SettingsDMCSampler.adaptive_amount= FloatProperty( name= "Adaptive amount", description= "A value of 1.0 means full adaptation; a value of 0.0 means no adaptation", min= 0.0, max= 1.0, soft_min= 0.0, soft_max= 1.0, default= 0.85, precision= 2 ) SettingsDMCSampler.time_dependent= BoolProperty( name= "Time dependent", description= "This make the samping pattern change with time", default= 0 ) SettingsDMCSampler.subdivs_mult= FloatProperty( name= "Subdivs mult", description= "This will multiply all subdivs values everywhere during rendering", min= 0.0, max= 100.0, soft_min= 0.0, soft_max= 10.0, default= 1.0 ) ''' OUTPUT ''' def write(bus): ofile= bus['files']['scene'] scene= bus['scene'] rna_pointer= getattr(scene.vray, ID) ofile.write("\n%s %s {" % (ID,ID)) for param in PARAMS: value= getattr(rna_pointer, param) ofile.write("\n\t%s= %s;"%(param, p(value))) ofile.write("\n}\n")
[ "root@localhost.localdomain" ]
root@localhost.localdomain
2386c917a9a025f2355f298daccaee6c493f51b8
000c243b4c30bd089867f73ca1bcfede1c3ef801
/catkin_ws/src/mobile_mini/nodes/odom_node.py
f8573100b78c49d0563828fdf837aa651876695d
[]
no_license
dangkhoa1210/SLAM-AND-NAVIGATION-FOR-MOBILE-ROBOT-OUTDOOR-INDOOR-
b4d9bf2757d839d9766d512c2272731300320925
7273ea9e966353440d3993dcba112bc0a2262b98
refs/heads/master
2023-07-15T14:07:17.123812
2021-09-02T10:12:30
2021-09-02T10:12:30
402,361,868
0
0
null
null
null
null
UTF-8
Python
false
false
2,943
py
#!/usr/bin/env python import math from math import sin, cos, pi import rospy import tf from nav_msgs.msg import Odometry from std_msgs.msg import Float32 from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3, Vector3Stamped class Odom: def __init__(self): rospy.init_node('odometry') self.odom_pub = rospy.Publisher("odom", Odometry, queue_size=50) #self.odom_broadcaster = tf.TransformBroadcaster() self.x = 0.0 self.y = 0.0 self.th = 0.0 self.vx = 0 self.vy = 0 self.vth = 0 # self.quat = Quaternion() self.last_time = rospy.Time.now() rospy.Subscriber('vel_pub', Twist, self.vel_callback) # rospy.Subscriber('quat_pub', Quaternion, self.quat_callback) #rospy.Subscriber('theta_pub', Float32, self.yaw_callback) #rospy.Subscriber('imu/rpy/filtered', Vector3Stamped, self.yaw_callback) def spin(self): r = rospy.Rate(10) while not rospy.is_shutdown(): self.pubAndBroadcast() r.sleep() def pubAndBroadcast(self): current_time = rospy.Time.now() # compute odometry in a typical way given the velocities of the robot dt = (current_time - self.last_time).to_sec() delta_x = (self.vx * cos(self.th) - self.vy * sin(self.th)) * dt delta_y = (self.vx * sin(self.th) + self.vy * cos(self.th)) * dt delta_th = self.vth * dt self.x += delta_x self.y += delta_y self.th += delta_th # since all odometry is 6DOF we'll need a quaternion created from yaw odom_quat = tf.transformations.quaternion_from_euler(0, 0, self.th) # first, we'll publish the transform over tf # self.odom_broadcaster.sendTransform( # (self.x, self.y, 0.), # odom_quat, # current_time, # "base_link", # "odom" #) # next, we'll publish the odometry message over ROS odom = Odometry() odom.header.stamp = current_time odom.header.frame_id = "odom" # set the position odom.pose.pose = Pose(Point(self.x, self.y, 0.), Quaternion(*odom_quat)) # set the velocity odom.child_frame_id = "base_link" odom.twist.twist = Twist(Vector3(self.vx, self.vy, 0), Vector3(0, 0, self.vth)) # publish the message for i in range(1): self.odom_pub.publish(odom) rospy.loginfo(odom) self.last_time = current_time def vel_callback(self,vel): self.vx = vel.linear.x self.vth = vel.angular.z # def quat_callback(self,quat): # self.quat.w = quat.w # self.quat.x = quat.x # self.quat.y = quat.y # self.quat.z = quat.z #def yaw_callback(self,_yaw): # self.th = _yaw.vector.z if __name__ == '__main__': odom_object = Odom() odom_object.spin()
[ "dangkhoaphamdang1210@gmail.com" ]
dangkhoaphamdang1210@gmail.com
ab55dfbe379ee0110feb62dc7fbdb9dca0599ae0
5d65b2a333e540ce56beef40f9bc1cb3eb47acc4
/lab5/lab5_c_1.py
37f627074803d841bfaba7c10576ab5ccb828638
[]
no_license
gsrinivasaragavan/Frosh_year
92acd0198916c3b992292118643e2c4a1dceac51
0c66c320426701724838b1635b0e8a12a381be2e
refs/heads/master
2021-05-02T08:41:28.185717
2018-02-09T05:22:09
2018-02-09T05:22:09
120,812,088
0
0
null
null
null
null
UTF-8
Python
false
false
1,359
py
from tkinter import * import random # Graphics commands. # Event handlers. def key_handler(event): '''Handle key presses.''' global randcol key = event.keysym if key == 'x': circles.remove(o) elif key == 'c': randcol = random_color() def button_handler(event): '''Handle left mouse button click events.''' size = random.randint(20,50) x = event.x y = event.y #gives x and y coordinats of where you press the button so you can draw #around it global o o = canvas.create_oval(x-size/2, y-size/2, x+size/2, y+size/2, fill = randcol, outline = randcol) circles.append(o) def random_color(): '''This function will generate random color values in hexadecimal form''' list1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] hexadecimal = '' for i in range(6): hexadecimal+= random.choice(list1) return '#' + hexadecimal if __name__ == '__main__': root = Tk() root.geometry('800x800') canvas = Canvas(root, width=800, height=800) canvas.pack() randcol = random_color() circles = [] # Bind events to handlers. root.bind('<Key>', key_handler) canvas.bind('<Button-1>', button_handler) root.bind('<q>', quit) # Start it up. root.mainloop()
[ "noreply@github.com" ]
gsrinivasaragavan.noreply@github.com
21ea83c155990c96c2221f51b606827f36853cca
0779b779ad4146086dfa05a0834161859cda3412
/chessfftomo_process_changes.py
02a83c1646a39d760a0010b0074ea4cfbfc1f6d5
[]
no_license
mskoly/nsls2-xf-utils
4adb755862943c1cd7ad00fd862890f8f5a505e8
aa9c4c7021d0361687991e642d67e2c262832996
refs/heads/master
2021-06-15T15:34:52.457459
2017-03-22T12:11:31
2017-03-22T12:11:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,060
py
import tifffile import matplotlib.pyplot as plt import os import numpy as np from scipy.ndimage.interpolation import shift import tomopy import scipy.ndimage import skimage.measure import cv2 def chess_fileio_proj(datapath, prefix, fnumstart, fnumend, imgsize = [2048, 2048], print_infile = False, print_fcounter = False): ''' load frames from datapath with prefix in order ''' numframes = fnumend - fnumstart + 1 frames = np.zeros([numframes, imgsize[0], imgsize[1]]) for fnum in range(fnumstart, fnumend+1): infile = os.path.join(datapath,prefix+'{0:05d}'.format(fnum)+'.tif') if print_infile is True: print(infile) frames[fnum-fnumstart, :, :] = tifffile.imread(infile) frames = np.array(frames) print(' loaded all projects.') return frames def chess_proj(chess_datapath, fname, imgsize = [664, 590]): ''' Load image stacking ''' image_files = chess_datapath # Your list of files image_height = imgsize[0] image_width = imgsize[1] image_stack = np.empty((image_height, image_width, 1441)) # Create empty HxWxN array/matrix for i, fname in enumerate(image_files): #img = cv2.imread(fname, cv2.CV_LOAD_IMAGE_GRAYSCALE) img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) image_stack[:,:,i] = img # Set the i:th slice to this image proj = image_stack return proj def srxfftomo_findcenter(corrected_proj_tiff = None, proj = None, save_find_center = True, autocheck = False, check_cen_range_step = [390, 410, 1], auto_selecslice = True, cen_slice = 400, outpath = None, samplename = None): ''' input needs to be either 1) corrected_proj_tiff, provided as a file path and name, e.g. '/home/xf05id1/localdata/TomoCommissioning/testsample_01/testsample_01_corrected.tiff' it is a stack of tiff generated by srxfftomo_correction, where background and stage round out have been corrected 2) projection numpy array, returned from srxfftomo_correction The 'proj' array assignment has priority. If it is None, proj was be read from corrected_proj_tiff input example: check_cen_range_step = [390, 410, 1] cen_slice = 400 return: proj (numpy array, float), with negative natural log has been taken ''' if proj is None: print('proj is not asigned, load corrected projection from:', corrected_proj_tiff) proj = tifffile.imread(chess_proj) else: print('proj array is not None, use it as is') if save_find_center is True: center_check_path = outpath +'/' + samplename + '/center_check/' print('saving find center value into ' + center_check_path) theta = tomopy.angles(proj.shape[0]) if autocheck is True: check_cen_range_step = [int(proj.shape[2]/2)-50, int(proj.shape[2])/2+50, 5] if auto_selecslice is True: cen_slice = int(proj.shape[1]/2) tomopy.write_center(proj, theta, center_check_path, cen_range = check_cen_range_step, ind = cen_slice, mask = True) return proj # def srxfftomo_recon(corrected_proj_tiff = None, proj = None, rot_center = None, recon_algorithm = 'art', recon_section = None, outpath = None, recon_outpath = 'recon', samplename = None): ''' input needs to be either 1) corrected_proj_tiff, provided as a file path and name, e.g. '/home/xf05id1/localdata/TomoCommissioning/testsample_01/testsample_01_corrected.tiff' it is a stack of tiff generated by srxfftomo_correction, where background and stage round out have been corrected 2) projection numpy array, returned from srxfftomo_correction The 'proj' array assignment has priority. If it is None, proj was be read from corrected_proj_tiff recon_section is a list of upper and lower bounds for y range, e.g. [380, 420] ''' if proj is None: print('proj is not asigned, load corrected projection from:', chess_proj) proj = tifffile.imread(chess_proj) else: print('proj array is not None, use it as is') print('running reconstruction') if recon_section is not None: proj = proj [:, recon_section[0]:recon_section[1], :] theta = tomopy.angles(proj.shape[0]) rec = tomopy.recon(proj, theta, center=rot_center, algorithm= recon_algorithm) print('saving reconstruction into') recon_outfile = outpath +'/' + samplename + '/' + recon_outpath +'/' + samplename + '_recon' tomopy.write_tiff_stack(rec, fname=recon_outfile) return rec
[ "gwilliams@bnl.gov" ]
gwilliams@bnl.gov
bc902c545cc284279a0d4febb73e91c0e6ea1c96
03f89bd5b468c2d7b55109b2b0cf895e504d5a2c
/vehiculos/urls.py
0ed703c03839b4ef3d85afb8437a32c10f2e33ad
[]
no_license
juanse021/CRUD-Django
be3bf3b0f4cd76b94001e7abb6e5636485631753
ab539c5c764376ee47ae49002c1904bc1ff80406
refs/heads/master
2020-04-01T22:19:47.669123
2018-10-29T21:03:27
2018-10-29T21:03:27
153,702,334
0
0
null
null
null
null
UTF-8
Python
false
false
413
py
from django.urls import path from . import views app_name = "vehiculos" urlpatterns = [ path('', views.IndexVehiculo.as_view(), name='index-vehiculo'), path('editar/<int:pk>/', views.ModificarVehiculo.as_view(), name="editar-vehiculo"), path('eliminar/<int:pk>/', views.EliminarVehiculo.as_view(), name="eliminar-vehiculo"), path('nuevo/', views.CrearVehiculo.as_view(), name="crear-vehiculo") ]
[ "juanse032194@hotmail.com" ]
juanse032194@hotmail.com
07eaa71415a1a424745e8bb3b8715c3faa56c03c
c1b05f9d1d142684e85e4f68873882004f64e46a
/parser.py
001576ea1c1f23425a52b8552f142d563223e4d6
[]
no_license
pablopgus/GoogleHash2018
3a89f426b74342511c894308f683cd48b799c6a8
f88dc5ba17bfccd8d5111f4dde430bad436bd022
refs/heads/master
2021-01-25T12:14:09.195099
2018-03-01T20:19:21
2018-03-01T20:19:21
123,460,743
0
0
null
null
null
null
UTF-8
Python
false
false
29
py
import problem import ride
[ "pablopg@us.es" ]
pablopg@us.es
2b2dab1db3a1529bd37c531880c4c62094e555df
0545ffca7c830950b0ff1d7f5f5c4557377dc97d
/PYTHON/crud-intro/crud/urls.py
8d6b1654f4940168ade84306b4793d444013f72f
[]
no_license
snb5412/TIL
cb7b9cd4ed1ef60983fcc4981593afbfdc8c85b4
8f320ee1533347e541489d14e8ede6998c31631a
refs/heads/master
2020-05-26T21:37:47.077307
2019-06-18T04:14:51
2019-06-18T04:14:51
188,382,788
0
0
null
null
null
null
UTF-8
Python
false
false
814
py
"""crud URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/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('boards/', include('boards.urls')), path('admin/', admin.site.urls), ]
[ "snb5412@naver.com" ]
snb5412@naver.com
fd0ebb7e1af5468798010ada34fdf844a3079daa
cfe889896d8ab67abdb8bd072caab6e4d424dd1c
/tools/stm32writer/stm32writer.py
72783c9749003f1e72ca38b55d2b400ea62209cb
[]
no_license
tokuhira/my-first-stm32
a72d386d790c9f3413bb0b78f664b755abb44075
6fc4ba59af6e31ca478f2123393467ad501ee16d
refs/heads/master
2021-09-03T09:48:08.469740
2018-01-08T05:21:53
2018-01-08T05:21:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,121
py
#!/usr/bin/python # coding=utf-8 import sys, optparse, datetime import stm32_serial, stm32_cmd, stm32_data, stm32_prm import time def print_time(t): seconds = t.days * 3600 * 24 + t.seconds + t.microseconds * 1.E-6 print " time: %.3f s" % seconds try: # バージョン情報 version = "20171231py" print "stm32writer (version: " + version + ")" # オプションの解析 parser = optparse.OptionParser() parser.add_option( "-p", "--port", action="store", dest="port", default="", help="set serial port") parser.add_option( "-r", "--baudrate", action="store", dest="baudrate", default=115200, help="set baudrate") parser.add_option( "-l", "--show-command-list", action="store_true", dest="command_list_flag", default=False, help="show command list") parser.add_option( "-o", "--show-option-bytes", action="store_true", dest="option_byte_flag", default=False, help="show option bytes") parser.add_option( "-u", "--unprotect", action="store_true", dest="unprotect_flag", default=False, help="write unprotect") parser.add_option( "-c", "--compare", action="store_true", dest="compare_flag", default=False, help="compare written data with original mot data") parser.add_option( "-g", "--go", action="store_true", dest="jump_flag", default=False, help="jump to start address after writing") parser.add_option( "-e", "--show-erase-page", action="store_true", dest="erase_page_flag", default=False, help="show page/sector numbers erased before writing to FLASH") parser.add_option( "-t", "--time", action="store_true", dest="time_flag", default=False, help="print time after the start of connection with a device") parser.add_option( "--no-writing", action="store_true", dest="no_writing_flag", default=False, help="no writing to FLASH") (options, args) = parser.parse_args() if not args: print "no mot file" sys.exit(1) # boot loader # print "try to boot loader!" ser = stm32_serial.open_port_with_control(options.port, options.baudrate) # ser.rts = False #boot0 = 1 ser.dtr = True #reset time.sleep(0.5) ser.dtr = False # stm32_serial.close_port(ser) # print "boot loader!" # ポートを開く # ser = stm32_serial.open_port(options.port, options.baudrate) # STM32へ接続 stm32_serial.connect_to_device(ser) t0 = datetime.datetime.now() if options.time_flag: print_time(datetime.timedelta(0)) # Bootloaderのバージョンと使用できるコマンドリストを取得する (BL_version, commands) = stm32_cmd.Get(ser) # Bootloaderのバージョンを表示する print "Bootloader version: V%d.%d" % (BL_version>>4, BL_version&0x0f) # Product IDを取得する PID = stm32_cmd.Get_ID(ser) print "Product ID: %4x" % PID # Product IDに基づきデバイス情報を表示する stm32_prm.show_device_info(PID) # コマンドリストの表示 if options.command_list_flag: print "Supported commands:" for x in commands: print "0x%02x" % x # option byteを読み込む if options.option_byte_flag: (BL_version, option_bytes) = stm32_cmd.Get_Version_And_Read_Protection_Status(ser) print "Bootloader version: V%d.%d" % (BL_version>>4, BL_version&0x0f) print "Option Byte 1: %d" % option_bytes[0] print "Option Byte 2: %d" % option_bytes[1] # 書き込みプロテクト解除 if options.unprotect_flag: stm32_cmd.Write_Unprotect(ser) print "Write protect was unprotected" for filename in args: # motファイルからデータ抽出 (addr, data, start_addr) = stm32_data.analyze_mot_file(filename) # データレコード再構成 (addr, data) = stm32_data.reconstruct_records(addr, data) if options.time_flag: print_time(datetime.datetime.now() - t0) # 書き込み予定領域のページ番号,セクター番号を取得 (pages, sectors) = stm32_data.make_erase_page_list(addr, data, PID) if options.erase_page_flag: if pages: print "Pages to be erased:", for x in pages: print " " + str(x), print if sectors: print "Sectors to be erased:", for x in sectors: print " " + str(x), print # 消去する stm32_data.erase_flash(ser, pages, sectors, commands) if options.time_flag: print_time(datetime.datetime.now() - t0) # 書き込み if not options.no_writing_flag: stm32_data.write_data(ser, addr, data) if options.time_flag: print_time(datetime.datetime.now() - t0) # 書き込んだデータとオリジナルの比較 if options.compare_flag: stm32_data.compare_data(ser, addr, data) if options.time_flag: print_time(datetime.datetime.now() - t0) print # スタートアドレスにジャンプ if options.jump_flag: stm32_cmd.Go(ser, start_addr) print "Jumped to 0x%08x" % start_addr # ポートを閉じる stm32_serial.close_port(ser) # 自動起動 # ser = stm32_serial.open_port_with_control(options.port, options.baudrate) # ser.dtr = True #reset # ser.dtr = False # stm32_serial.close_port(ser) except KeyboardInterrupt: print sys.exit(1) except: print(sys.exc_info()) sys.exit(1)
[ "fukuno@TPC0165.local" ]
fukuno@TPC0165.local
09b41fe1713c499a3707221a8f4147fc00b88691
9990c9561b72398d9f6a2cb29b7ee63a68cf9607
/.history/higherarchy/urls_20200305145619.py
dded658b6051e4927f3520e6e40e3aa5c48988c8
[]
no_license
Imraj423/HierarchyD
46c78ea3be6836039ce357b06a3a3e32140d1868
f175f57bc0afd3f8366bec9d03c964d228877c4a
refs/heads/master
2021-02-19T01:43:25.018148
2020-03-05T20:50:20
2020-03-05T20:50:20
245,262,927
0
0
null
null
null
null
UTF-8
Python
false
false
1,122
py
"""higherarchy 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 dropbox.views import tree_view, login_view, register_user_view, logout_view, new_file_view from mptt.admin import DraggableMPTTAdmin from django.urls import path from . import views urlpatterns = [ path('', views.show_files, name='home'), path('newfile/', views.new_file_view, name='newfile'), path('logout/', views.logout_view, name='logout'), path('login/', views.login_view, name="loginview"), path('register/', register_user_view, name="registerview"), ]
[ "dahqniss@gmail.com" ]
dahqniss@gmail.com
cc58a0b6338f4dfdb20fded6efa4f8e0c8a200b6
2c7ac4b8924e14e3a2b6ceb8b0ebcee42a9e11c2
/moderngl-first/21_basic_colors_and_texture.py
0dc8d45601dc654c030e09742e67ceee7af89014
[]
no_license
curtkim/python-first
68c8b6559f01effcc3e31d723738ca08ad35a8c6
37dc399200940a40a489fa46375b186bb85aea8f
refs/heads/master
2023-05-25T05:56:57.910113
2023-05-21T13:48:15
2023-05-21T13:48:15
175,553,035
3
0
null
2022-12-30T21:33:45
2019-03-14T05:17:32
Jupyter Notebook
UTF-8
Python
false
false
3,619
py
''' Renders a floating, oscillating, 3d islans with lights ''' import numpy as np from pyrr import Matrix44 import moderngl from ported._example import Example vertex_shader = ''' #version 330 uniform mat4 Mvp; in vec3 in_position; in vec3 in_normal; in vec2 in_texcoord_0; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_position, 1.0); v_vert = in_position; v_norm = in_normal; v_text = in_texcoord_0; } ''' fragment_shader = ''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''' class ColorsAndTexture(Example): gl_version = (3, 3) title = "Colors and Textures" def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program(vertex_shader=vertex_shader, fragment_shader=fragment_shader) # Note: This is a fairly manual way to loading and rendering wavefront files. # There are easier ways when loading mutiple objects in a single obj file. # Load obj files self.scene_ground = self.load_scene('scene-1-ground.obj') self.scene_grass = self.load_scene('scene-1-grass.obj') self.scene_billboard = self.load_scene('scene-1-billboard.obj') self.scene_holder = self.load_scene('scene-1-billboard-holder.obj') self.scene_image = self.load_scene('scene-1-billboard-image.obj') # Extract the VAOs from the scene self.vao_ground = self.scene_ground.root_nodes[0].mesh.vao.instance(self.prog) self.vao_grass = self.scene_grass.root_nodes[0].mesh.vao.instance(self.prog) self.vao_billboard = self.scene_billboard.root_nodes[0].mesh.vao.instance(self.prog) self.vao_holder = self.scene_holder.root_nodes[0].mesh.vao.instance(self.prog) self.vao_image = self.scene_image.root_nodes[0].mesh.vao.instance(self.prog) # texture on billboard self.texture = self.load_texture_2d('infographic-1.jpg') def render(self, time: float, frame_time: float): self.ctx.clear(1.0, 1.0, 1.0) self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE) proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0) lookat = Matrix44.look_at( (47.697, -8.147, 24.498), (0.0, 0.0, 8.0), (0.0, 0.0, 1.0), ) rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2) self.prog['UseTexture'].value = False self.prog['Light'].value = (67.69, -8.14, 52.49) self.prog['Mvp'].write((proj * lookat * rotate).astype('f4')) self.prog['Color'].value = (0.67, 0.49, 0.29) self.vao_ground.render() self.prog['Color'].value = (0.46, 0.67, 0.29) self.vao_grass.render() self.prog['Color'].value = (1.0, 1.0, 1.0) self.vao_billboard.render() self.prog['Color'].value = (0.2, 0.2, 0.2) self.vao_holder.render() self.prog['UseTexture'].value = True self.texture.use() self.vao_image.render() if __name__ == '__main__': ColorsAndTexture.run()
[ "iamteri@gmail.com" ]
iamteri@gmail.com
9abcce63356d59e66361230494b2b23d14306055
edcd74f8f65119bdbe737360c2ca33b4a6da160a
/python/problem-tree/construct_binary_tree_from_preorder_and_postorder_traversal.py
76aaec59ae60e971b3783fc4617a300b0e2335a2
[]
no_license
hyunjun/practice
72e83de6a1d5e04ddcd16526f16110ea2dd00373
5376dd48b1cefb4faba9d2ef6a8a497b6b1d6c67
refs/heads/master
2023-08-31T07:00:37.320351
2023-08-17T07:29:24
2023-08-17T07:29:24
2,704,126
3
2
null
2022-12-14T20:25:07
2011-11-03T18:28:44
Python
UTF-8
Python
false
false
1,396
py
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal from TreeNode import TreeNode from typing import List class Solution: # runtime; 44ms, 96.25% # memory; 12.8MB, 100.00% def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: if pre is None or 0 == len(pre) or post is None or 0 == len(post): return None def construct(pres, posts): if pres is None or 0 == len(pres) or posts is None or 0 == len(posts): return None print(pres, posts) node = TreeNode(pres[0]) if 2 <= len(pres) and 2 <= len(posts): leftVal, rightVal = pres[1], posts[-2] if leftVal == rightVal: node.left = construct(pres[1:], posts[:-1]) else: lIdx, rIdx = pres.index(rightVal), posts.index(leftVal) node.left = construct(pres[1:lIdx], posts[:rIdx + 1]) node.right = construct(pres[lIdx:], posts[rIdx + 1:-1]) return node return construct(pre, post) s = Solution() data = [([1,2,4,5,3,6,7], [4,5,2,6,7,3,1], [1,2,3,4,5,6,7]), ] for pre, post, expected in data: real = s.constructFromPrePost(pre, post) print(f'{pre} {post} expected {expected} real {real} result {expected == real}')
[ "hyunjun.chung@agoda.com" ]
hyunjun.chung@agoda.com
06222960a80ce7b75c855ff580d8c7f29a6fe26e
522d1d73ce4fbcf120346353cd0fc891d335aab0
/jupyter_notebook/Constant strain triangle FEM.py
ccedd24750f1391a4b128cc517b63fdd79b296b5
[]
no_license
YuanzhongLi/ryouiki_project
253ee7c1474929b5928e3047030bc5892358e36f
88e4ca1154d18edbbe30df90fe5bef6d1182a1d9
refs/heads/master
2022-11-30T00:05:13.546978
2019-05-30T14:05:58
2019-05-30T14:05:58
185,770,812
0
0
null
2022-11-22T03:52:55
2019-05-09T09:41:35
Jupyter Notebook
UTF-8
Python
false
false
6,804
py
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd from copy import copy import matplotlib import matplotlib.pyplot as plt node_data = np.array([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=np.float64) # connect_infoは要素を作っているnodeのglobal番号, Aは要素面積 element_data = np.array([{"connect_info": [1, 4, 3], "A": 0.5}, {"connect_info": [4, 1, 2], "A": 0.5}]) # 境界条件より既知となる部分 known_part_of_d = { "u1": 0, "v1": 0, "v2": 0, "u3": 0 } known_part_of_F = { "H2": 5, "V3": 0, "H4": 5, "V4": 0 } E = 100 PR = (1 / 3) node_data2 = np.array([[1, 1], [1, 0], [0, 1], [0, 0]], dtype=np.float64) element_data2 = np.array([{"connect_info": [1, 2, 4], "A": 0.5}, {"connect_info": [1, 3, 4], "A": 0.5}]) known_part_of_d2 = { "u3": 0, "v3": 0, "u4": 0, "v4": 0 } known_part_of_F2 = { "H1": 0, "V1": 0, "H2": 0, "V2": -100 } E2 = 100 PR2 = 0 # E: Young's module PR: Poisson's ratio def elastic_matrix(E, PR): return (E / (1 - PR ** 2)) * np.array([[1, PR, 0], [PR, 1, 0], [0, 0, (1 - PR) / 2]]) # + # ex) nodes = np.array([[1, 1], [1, 0], [0, 0]]) def shape_fucntions(nodes): DSF = np.hstack([np.array([[1], [1], [1]]), nodes]) N1 = np.linalg.solve(DSF, np.array([1, 0, 0])) N2 = np.linalg.solve(DSF, np.array([0, 1, 0])) N3 = np.linalg.solve(DSF, np.array([0, 0, 1])) N = np.array([N1, N2, N3]) return N # - def B_matrix(connect_info, A, node_data): node1 = node_data[connect_info[0] - 1] node2 = node_data[connect_info[1] - 1] node3 = node_data[connect_info[2] - 1] nodes = np.array([node1, node2, node3]) N = shape_fucntions(nodes) B = (1 / (2 * A)) * np.array([\ np.array([N[0][1], 0, N[1][1], 0, N[2][1], 0]),\ np.array([0, N[0][2], 0, N[1][2], 0, N[2][2]]),\ np.array([N[0][2], N[0][1], N[1][2], N[1][1], N[2][2], N[2][1]])\ ]) return B def K_matrix(B_matrix, elastic_matrix, A): return A * np.dot(np.dot(B_matrix.T, elastic_matrix), B_matrix) # dの未知の要素に対応する行、列を削除 def compress_K_F(K, d, F): compressed_K = K compressed_d = d compressed_F = F # いくつ削除したかを記憶する delete_count = 0 for index, element_d in enumerate(d): if element_d != None: # 削除する行と列が上から数えて何番目のものか delete_num = index + 1 - delete_count compressed_K = np.delete(compressed_K, delete_num - 1, 0) compressed_K = np.delete(compressed_K, delete_num - 1, 1) compressed_d = np.delete(compressed_d, delete_num - 1, 0) compressed_F = np.delete(compressed_F, delete_num - 1, 0) delete_count += 1 return { "compressed_K": compressed_K, "compressed_F": compressed_F } # + # connect_infoは要素を作っているnode番号, Aは要素面積 # known_part_of_dとknow_part_of_Fは境界条件より既知となる部分 # E: Young's module PR: Poisson's ratio def CST_FEM(node_data, element_data, known_part_of_d, known_part_of_F, E, PR): # Kを0で初期化 K = np.zeros([node_data.shape[0] * 2, node_data.shape[0] * 2]) element_elastic_matrix = elastic_matrix(E, PR) # assembling for element in element_data: element_B_matrix = B_matrix(element['connect_info'], element['A'], node_data) element_K_matrix = K_matrix(element_B_matrix, element_elastic_matrix, element['A']) # Kに対応する部分を足していく # node_i, node_jはnodeのglobal番号 for i, node_i in enumerate(element['connect_info']): for j, node_j in enumerate(element['connect_info']): K[2*(node_i - 1)][2*(node_j - 1)] += element_K_matrix[2 * i][2 * j] K[2*(node_i - 1)][2*(node_j - 1) + 1] += element_K_matrix[2 * i][2 * j + 1] K[2*(node_i - 1) + 1][2*(node_j - 1)] += element_K_matrix[2 * i + 1][2 * j] K[2*(node_i - 1) + 1][2*(node_j - 1) + 1] += element_K_matrix[2 * i + 1][2 * j + 1] # dとFをNoneで初期化 d = [None] * (node_data.shape[0] * 2) F = [None] * (node_data.shape[0] * 2) # dとFに既知の部分を代入 for k, v in known_part_of_d.items(): # vecはuまたはv方向 vec = k[0] node_num = int(k[1]) if vec == 'u': d[(node_num - 1) * 2] = v elif vec == 'v': d[(node_num - 1) * 2 + 1] = v for k, v in known_part_of_F.items(): # vecはHまたはV方向 vec = k[0] node_num = int(k[1]) if vec == 'H': F[(node_num - 1) * 2] = v elif vec == 'V': F[(node_num - 1) * 2 + 1] = v # uが既知の部分のkd = Fを削除して未知の部分のdを求める compressed_K_F_dict = compress_K_F(K, d, F) compressed_K = compressed_K_F_dict['compressed_K'].astype(np.float64) compressed_F = compressed_K_F_dict['compressed_F'].astype(np.float64) compressed_d = np.linalg.solve(compressed_K, compressed_F) # dの未知の部分に求めたcompressed_dを代入 # compressed_dの対応するindex compressed_d_index = 0 for index, element_d in enumerate(d): if element_d == None: d[index] = compressed_d[compressed_d_index] compressed_d_index += 1 for index, element_F in enumerate(F): if element_F == None: F[index] = np.dot(K[index], d) cordinates = copy(node_data) for i in range(0, node_data.shape[0]): cordinates[i][0] += d[i * 2] cordinates[i][1] += d[i * 2 + 1] return { 'd': d, 'F': F, 'cordinates': cordinates } # - result = CST_FEM(node_data, element_data, known_part_of_d, known_part_of_F, E, PR) result = CST_FEM(node_data2, element_data2, known_part_of_d2, known_part_of_F2, E2, PR2) result cordinates = result['cordinates'] # + X = np.zeros(4, dtype=np.float64) Y = np.zeros(4, dtype=np.float64) for i in range(0, 4): X[i] += node_data2[i][0] Y[i] += node_data2[i][1] # + x = np.zeros(4, dtype=np.float64) y = np.zeros(4, dtype=np.float64) for i in range(0, 4): x[i] += cordinates[i][0] y[i] += cordinates[i][1] # + {} def main(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(x, y, c='red') ax.scatter(X, Y, c='blue') ax.set_aspect('equal') plt.show() if __name__ == '__main__': main() # -
[ "liyuanzhongutokyos1@gmail.com" ]
liyuanzhongutokyos1@gmail.com
f3f8702eff0c3a6aa0948c50adf4412c1c23fde0
da961430b06561ade3bd52ac3a51306f0b9c38c1
/weatherManager.py
0d46e79d4d8e48fd7877057c784b8a061e6bb5bb
[]
no_license
diegomtzg/MirrorX
b26bb96e37419df827341f702fe1314a5cc854a4
1bbf2283b50232ba07652ed252363efe0ad6f058
refs/heads/master
2021-05-12T03:00:00.175011
2021-02-24T02:07:59
2021-02-24T02:07:59
117,604,099
0
2
null
null
null
null
UTF-8
Python
false
false
5,828
py
import requests import json import smartMirrorManager from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QHBoxLayout from PyQt5.QtGui import * from PyQt5.QtCore import * import cv2 weather_api_token = '9435a4c25a087440d56cc46775e1eb0d' icon_lookup = { 'clear-day': "assets/Sun.png", # clear sky day 'wind': "assets/Wind.png", #wind 'cloudy': "assets/Cloud.png", # cloudy day 'partly-cloudy-day': "assets/PartlySunny.png", # partly cloudy day 'rain': "assets/Rain.png", # rain day 'snow': "assets/Snow.png", # snow day 'snow-thin': "assets/Snow.png", # sleet day 'fog': "assets/Haze.png", # fog day 'clear-night': "assets/Moon.png", # clear sky night 'partly-cloudy-night': "assets/PartlyMoon.png", # scattered clouds night 'thunderstorm': "assets/Storm.png", # thunderstorm 'tornado': "assests/Tornado.png", # tornado 'hail': "assests/Hail.png" # hail } class Weather(QWidget): def __init__(self): super(Weather, self).__init__() self.initUI() def initUI(self): weatherFont = QFont('Helvetica', smartMirrorManager.med_fontsize) temperatureFont = QFont('Helvetica', 45) self.vbox = QVBoxLayout() self.temperature = '' self.forecast = '' self.location = '' self.currently = '' self.icon = '' self.tempLabel = QLabel() self.tempLabel.setFont(temperatureFont) self.tempLabel.setText("<font color='white'>temporary temp</font>") self.iconLabel = QLabel() self.currentlyLabel = QLabel() self.currentlyLabel.setFont(weatherFont) self.currentlyLabel.setText("<font color='white'>temporary curr</font>") self.forecastLabel = QLabel() self.forecastLabel.setFont(weatherFont) self.forecastLabel.setWordWrap(True) self.forecastLabel.setText("<font color='white'>temporary forecast</font>") self.locLabel = QLabel() self.locLabel.setFont(weatherFont) self.locLabel.setText("<font color='white'>temporary loc</font>") self.hbox = QHBoxLayout() self.vbox = QVBoxLayout() self.vbox1 = QVBoxLayout() self.hbox.addWidget(self.tempLabel) self.hbox.addWidget(self.iconLabel) self.hbox.setAlignment(Qt.AlignLeft) self.vbox1.addWidget(self.currentlyLabel) self.vbox1.addWidget(self.forecastLabel) self.vbox1.addWidget(self.locLabel) self.vbox1.addStretch(1) self.vbox.addLayout(self.hbox) self.vbox.addLayout(self.vbox1) self.vbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.vbox) self.getWeather() self.updateWeather() def updateWeather(self): self.timer = QTimer(self) self.timer.timeout.connect(self.getWeather) self.timer.start(150000) # Update weather every 2.5ish minutes def getIP(self): try: # Fetch IP from jsonip.com and parse returned JSON ip_url = "http://jsonip.com" req = requests.get(ip_url) ip_json = json.loads(req.text) return ip_json['ip'] except Exception as e: return "Error %s. Cannot get ip." % e def getWeather(self): try: loc_req_url = "http://freegeoip.net/json/%s" % self.getIP() req = requests.get(loc_req_url) loc_json = json.loads(req.text) lat = loc_json['latitude'] lon = loc_json['longitude'] weather_req_url = "https://api.darksky.net/forecast/%s/%s,%s" % (weather_api_token, lat,lon) req = requests.get(weather_req_url, timeout=1) weather_json = json.loads(req.text) degree_symbol = u'\N{DEGREE SIGN}' far = int(weather_json['currently']['temperature']) cel = int(5 * (far - 32) / 9) newTemp = "%s%s" % (str(far), degree_symbol) newCurrently = weather_json['currently']['summary'] newForecast = weather_json['hourly']['summary'] iconID = weather_json['currently']['icon'] icon2 = None if iconID in icon_lookup: icon2 = icon_lookup[iconID] # Display icon image from assets if icon2 is not None: if self.icon != icon2: self.icon = icon2 image = cv2.imread(icon2) image = cv2.resize(image, (50, 50), interpolation=cv2.INTER_CUBIC) image = QImage(image, image.shape[1], image.shape[0], image.strides[0], QImage.Format_RGB888) self.iconLabel.setPixmap(QPixmap.fromImage(image)) else: self.iconLbl.setPixmap(QPixmap('')) # Remove image if self.currently != newCurrently: self.currently = newCurrently temp = "<font color='white'>" + newCurrently + "</font>" self.currentlyLabel.setText(temp) if self.forecast != newForecast: self.forecast = newForecast newForecast = newForecast.replace("<", "less than") newForecast = newForecast.replace(">", "more than") temp = "<font color='white'>" + newForecast + "</font>" self.forecastLabel.setText(temp) if self.temperature != newTemp: self.temperature = newTemp temp = "<font color='white'>" + newTemp + "</font>" self.tempLabel.setText(temp) newLoc = "%s, %s" % (loc_json['city'], loc_json['region_code']) temp = "<font color='white'>" + newLoc + "</font>" self.locLabel.setText(temp) except Exception as e: print("Error")
[ "diegomtzg96@gmail.com" ]
diegomtzg96@gmail.com
11522354a2bbbd3a1bbc767b1e20a0c49805ff61
cabf0d5e3a975856372e524ca36c5d86ef03693e
/bandits/uniform.py
5643655303f787791760b54aeec601c3943dde59
[ "MIT" ]
permissive
XiaoMutt/ucbc
37d418b7e27872128cba569539e728d3793df712
f8aeb65dc5a11ecd82fd969d120f3a848d61c064
refs/heads/main
2023-04-02T20:10:48.079061
2021-03-27T18:57:57
2021-03-27T18:57:57
342,926,612
0
0
null
2021-03-26T06:38:10
2021-02-27T18:18:28
Python
UTF-8
Python
false
false
442
py
from .basis import Bandit import numpy as np class UniformBandit(Bandit): def __init__(self, thetas): self.thetas = thetas self.means = [sum(theta) / 2 for theta in self.thetas] self._narms = len(self.thetas) self._qstar = max(self.means) def reward(self, action): return np.random.uniform(*self.thetas[action]) def regret(self, action): return self._qstar - self.means[action]
[ "4534614+XiaoMutt@users.noreply.github.com" ]
4534614+XiaoMutt@users.noreply.github.com
e75a79d3dc9901ae6c20f864ed8084b64d6b70ec
bdc50b6a605b7547ebb5ac943a74ed32f5e072db
/tvshows/models.py
1b78d77a2b174ae04372ddcdb8021945c5f5e56e
[]
no_license
oliwiajakobsche/TVShowsWatchlist
344e93f833e6979736991d150e13cbe769ef4700
55fd6d4b7fbe70b3d937ca91a8a3bc9f3e795a70
refs/heads/main
2023-03-16T10:09:15.678132
2021-03-02T08:02:18
2021-03-02T08:02:18
343,084,109
0
0
null
null
null
null
UTF-8
Python
false
false
1,861
py
from django.db import models from django.urls import reverse class TvShow(models.Model): title = models.CharField(max_length=100) genre = models.CharField(max_length=100) poster = models.CharField(max_length=1000) description = models.CharField(max_length=2500) productionCountry = models.CharField(max_length=40) def get_absolute_url(self): return reverse('tvshows:details', kwargs={'tvShowId': self.id}) def __str__(self): return "[" + str(self.id) + "] " + self.title + " (" + self.productionCountry + ") - " + self.genre + "\n" + self.description[0:100] + "(...)" class Season(models.Model): tvShow = models.ForeignKey(TvShow, on_delete=models.CASCADE) number = models.SmallIntegerField() def get_success_url(self): return reverse('tvshows:details', kwargs={'tvShowId': self.tvShow.id}) def get_absolute_url(self): return reverse('tvshows:details', kwargs={'tvShowId': self.tvShow.id}) def __str__(self): return self.tvShow.title + " - season " + str(self.number) class Episode(models.Model): season = models.ForeignKey(Season, on_delete=models.CASCADE) number = models.SmallIntegerField() title = models.CharField(max_length=100) description = models.CharField(max_length=2500) duration = models.DurationField() releaseDate = models.DateField() videoUrl = models.CharField(max_length=2500) def get_success_url(self): return reverse('tvshows:details', kwargs={'tvShowId': self.season.tvShow.id}) def get_absolute_url(self): return reverse('tvshows:details', kwargs={'tvShowId': self.season.tvShow.id}) def __str__(self): return self.season.tvShow.title + " [S" + str(self.season.number) + "E" + str(self.number) + "] [duration: " + str(self.duration) + "] released: " + str(self.releaseDate)
[ "liqhta@gmail.com" ]
liqhta@gmail.com
07a24f1729d4a2432a856375330304ab95d63532
80301f1cffc5afce13256e2ecab6323c5df00194
/en.sc/py/T3118.py
3fdd76440f95aa378f5b9d1f5c80e21089975bce
[]
no_license
ZhenjianYang/SoraVoiceScripts
c1ddf7c1bbcb933243754f9669bd6b75777c87b9
94a948090aba0f63b10b2c69dc845dc99c822fc4
refs/heads/master
2023-04-18T04:54:44.306652
2023-04-06T11:15:17
2023-04-06T11:15:17
103,167,541
43
11
null
2021-03-06T08:52:54
2017-09-11T17:36:55
Python
UTF-8
Python
false
false
24,466
py
from ED6SCScenarioHelper import * def main(): SetCodePage("ms932") # 蔡斯 CreateScenaFile( FileName = 'T3118 ._SN', MapName = 'Zeiss', Location = 'T3118.x', MapIndex = 1, MapDefaultBGM = "ed60013", Flags = 1, EntryFunctionIndex = 0, Reserved = 0, IncludedScenario = [ '', 'ED6_DT21/T3118_1 ._SN', '', '', '', '', 'ED6_DT21/SUB000 ._SN', '' ], ) BuildStringList( '@FileName', # 8 'Dr. Miriam', # 9 'Antoine', # 10 'Antoine', # 11 ) DeclEntryPoint( Unknown_00 = 0, Unknown_04 = 0, Unknown_08 = 6000, Unknown_0C = 4, Unknown_0E = 0, Unknown_10 = 0, Unknown_14 = 9500, Unknown_18 = -10000, Unknown_1C = 0, Unknown_20 = 0, Unknown_24 = 0, Unknown_28 = 2800, Unknown_2C = 262, Unknown_30 = 45, Unknown_32 = 0, Unknown_34 = 360, Unknown_36 = 0, Unknown_38 = 0, Unknown_3A = 0, InitScenaIndex = 0, InitFunctionIndex = 0, EntryScenaIndex = 0, EntryFunctionIndex = 1, ) AddCharChip( 'ED6_DT07/CH01430 ._CH', # 00 'ED6_DT07/CH01700 ._CH', # 01 ) AddCharChipPat( 'ED6_DT07/CH01430P._CP', # 00 'ED6_DT07/CH01700P._CP', # 01 ) DeclNpc( X = -1410, Z = 0, Y = 6690, Direction = 90, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x101, InitFunctionIndex = 6, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 3, ) DeclNpc( X = -5510, Z = 0, Y = -3140, Direction = 0, Unknown2 = 0, Unknown3 = 1, ChipIndex = 0x1, NpcIndex = 0x181, InitFunctionIndex = 6, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 4, ) DeclNpc( X = -5510, Z = 0, Y = -3140, Direction = 0, Unknown2 = 0, Unknown3 = 1, ChipIndex = 0x1, NpcIndex = 0x181, InitFunctionIndex = 6, InitScenaIndex = 2, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) DeclActor( TriggerX = -5510, TriggerZ = 0, TriggerY = -3140, TriggerRange = 1000, ActorX = -5510, ActorZ = 500, ActorY = -3140, Flags = 0x7C, TalkScenaIndex = 1, TalkFunctionIndex = 1, Unknown_22 = 0, ) ScpFunction( "Function_0_13E", # 00, 0 "Function_1_16F", # 01, 1 "Function_2_19F", # 02, 2 "Function_3_200", # 03, 3 "Function_4_17D0", # 04, 4 ) def Function_0_13E(): pass label("Function_0_13E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x400, 0)), scpexpr(EXPR_END)), "loc_15B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x405, 7)), scpexpr(EXPR_END)), "loc_158") ClearChrFlags(0x9, 0x80) OP_43(0x9, 0x0, 0x0, 0x2) label("loc_158") Jump("loc_16E") label("loc_15B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x282, 6)), scpexpr(EXPR_END)), "loc_16E") ClearChrFlags(0x9, 0x80) OP_43(0x9, 0x0, 0x0, 0x2) label("loc_16E") Return() # Function_0_13E end def Function_1_16F(): pass label("Function_1_16F") Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0x4), scpexpr(EXPR_PUSH_LONG, 0x8), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_19A") OP_6F(0x0, 29) OP_72(0x0, 0x10) OP_79(0xFF, 0x2) OP_7A(0x7, 0x2) OP_7B() OP_72(0x6, 0x4) OP_72(0x7, 0x4) label("loc_19A") OP_64(0x0, 0x1) Return() # Function_1_16F end def Function_2_19F(): pass label("Function_2_19F") Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_1FF") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x6F, 0x1, 0x400)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_EXEC_OP, "OP_29(0x6F, 0x0, 0x8)"), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "OP_29(0x6F, 0x0, 0x40)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_EXEC_OP, "OP_29(0x6F, 0x0, 0x10)"), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_1E5") OP_8D(0xFE, -3860, -2270, -5240, -3760, 1000) Jump("loc_1FC") label("loc_1E5") OP_8D(0xFE, -6290, -6030, -3150, 520, 1000) label("loc_1FC") Jump("Function_2_19F") label("loc_1FF") Return() # Function_2_19F end def Function_3_200(): pass label("Function_3_200") TalkBegin(0x8) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x400, 0)), scpexpr(EXPR_END)), "loc_76B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x41A, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_601") Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x6)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_292") TurnDirection(0xFE, 0x107, 0) ChrTalk( #0 0xFE, "Oh, bracers...\x02", ) CloseMessageWindow() ChrTalk( #1 0xFE, "And, Tita, too.\x02", ) CloseMessageWindow() ChrTalk( #2 0x107, "#560FHi, Dr. Miriam.\x02", ) CloseMessageWindow() ChrTalk( #3 0x101, "#1000FAhaha, it's been a while.\x02", ) CloseMessageWindow() Jump("loc_2CA") label("loc_292") ChrTalk( #4 0xFE, "Oh, bracers...\x02", ) CloseMessageWindow() ChrTalk( #5 0x101, "#1000FYeah, it's been a while.\x02", ) CloseMessageWindow() label("loc_2CA") TurnDirection(0xFE, 0x101, 400) ChrTalk( #6 0xFE, "I'm glad to see you all look well.\x02", ) CloseMessageWindow() ChrTalk( #7 0x101, ( "#1000FYou too, Dr. Miriam.\x02\x03", "#1007FWell, I mean, aside from all the craziness\x01", "going on right now, anyway. I imagine\x01", "work's pretty tough.\x02", ) ) CloseMessageWindow() ChrTalk( #8 0xFE, ( "Yes, for now I'm checking over our\x01", "stocks of medical supplies.\x02", ) ) CloseMessageWindow() ChrTalk( #9 0xFE, ( "We'll be in deep trouble if we don't\x01", "have medicine when it's needed.\x02", ) ) CloseMessageWindow() ChrTalk( #10 0x102, ( "#1043FYeah...\x02\x03", "At the moment, it's not exactly easy to\x01", "restock with transportation so limited.\x02", ) ) CloseMessageWindow() ChrTalk( #11 0xFE, ( "Indeed. We'll just have to be very conservative\x01", "in our use of the supplies we do have.\x02", ) ) CloseMessageWindow() ChrTalk( #12 0xFE, "So, you all be careful too.\x02", ) CloseMessageWindow() ChrTalk( #13 0xFE, ( "If you get hurt really badly and dragged in\x01", "here, I will give you an absolute earful.\x02", ) ) CloseMessageWindow() Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x5)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_5C2") ChrTalk( #14 0x101, ( "#1016FAhaha... We'll be careful.\x02\x03", "...Right, Agate?\x02", ) ) CloseMessageWindow() ChrTalk( #15 0x106, "#552FWhat're you looking at me for?\x02", ) CloseMessageWindow() Jump("loc_5F8") label("loc_5C2") ChrTalk( #16 0x101, "#1016FAhaha...\x02", ) CloseMessageWindow() ChrTalk( #17 0x102, "#1035FWe'll be very careful.\x02", ) CloseMessageWindow() label("loc_5F8") OP_A2(0x0) OP_A2(0x20D3) Jump("loc_768") label("loc_601") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x405, 7)), scpexpr(EXPR_END)), "loc_6F6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_684") ChrTalk( #18 0xFE, ( "We'll just have to be very conservative\x01", "in our use of the supplies we do have.\x02", ) ) CloseMessageWindow() ChrTalk( #19 0xFE, "You all be very careful.\x02", ) CloseMessageWindow() Jump("loc_6F3") label("loc_684") ChrTalk( #20 0xFE, ( "Seems like it's the first time\x01", "I've seen Antoine in a while.\x02", ) ) CloseMessageWindow() ChrTalk( #21 0xFE, "Really, where was this kitty, I wonder.\x02", ) CloseMessageWindow() label("loc_6F3") Jump("loc_768") label("loc_6F6") ChrTalk( #22 0xFE, ( "We'll just have to be very conservative\x01", "in our use of the supplies we do have.\x02", ) ) CloseMessageWindow() ChrTalk( #23 0xFE, "You all be very careful.\x02", ) CloseMessageWindow() label("loc_768") Jump("loc_17CC") label("loc_76B") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x285, 6)), scpexpr(EXPR_END)), "loc_F85") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_F24") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x2C0, 0)), scpexpr(EXPR_END)), "loc_9E6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_882") ChrTalk( #24 0xFE, ( "The priests of the Septian Church are\x01", "developing new medicines even now.\x02", ) ) CloseMessageWindow() ChrTalk( #25 0xFE, ( "It's still a mystery how they can\x01", "innovate so much, but...\x02", ) ) CloseMessageWindow() ChrTalk( #26 0xFE, ( "Reading this treatise I can accept it. Basically,\x01", "it seems like they've got some incredible people.\x02", ) ) CloseMessageWindow() Jump("loc_9E3") label("loc_882") ChrTalk( #27 0xFE, ( "A while back, I was reading a treatise in\x01", "a medicinal journal written by a priest.\x02", ) ) CloseMessageWindow() ChrTalk( #28 0xFE, ( "And it was just...really impressive.\x01", "I admit to being a little shocked.\x02", ) ) CloseMessageWindow() ChrTalk( #29 0xFE, ( "For the church to not just have knowledge about\x01", "traditional medicine, but also modern medicine...\x02", ) ) CloseMessageWindow() ChrTalk( #30 0xFE, ( "I'd love to have the chance to talk in\x01", "depth with the writer, Father Divine.\x02", ) ) CloseMessageWindow() OP_A2(0x1) label("loc_9E3") Jump("loc_F21") label("loc_9E6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x284, 0)), scpexpr(EXPR_END)), "loc_BCF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_A9C") ChrTalk( #31 0xFE, ( "One of my recent research themes has\x01", "been analysis of medicines prescribed\x01", "by the church.\x02", ) ) CloseMessageWindow() ChrTalk( #32 0xFE, ( "If I can arrange what we know,\x01", "I'm sure I'll find something out.\x02", ) ) CloseMessageWindow() Jump("loc_BCC") label("loc_A9C") ChrTalk( #33 0xFE, ( "One of my recent research themes has\x01", "been analysis of medicines prescribed\x01", "by the church.\x02", ) ) CloseMessageWindow() ChrTalk( #34 0xFE, ( "I've had some results, such as I found their\x01", "shoulder pain medicine is constructed in\x01", "a pharmacological manner.\x02", ) ) CloseMessageWindow() ChrTalk( #35 0xFE, ( "It's a very small first step, but building up\x01", "those is how we make new discoveries.\x02", ) ) CloseMessageWindow() OP_A2(0x1) label("loc_BCC") Jump("loc_F21") label("loc_BCF") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x282, 6)), scpexpr(EXPR_END)), "loc_DFC") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_CF5") ChrTalk( #36 0xFE, ( "Modern medicine which medical scientists rely\x01", "upon as a foundation has a very short history.\x02", ) ) CloseMessageWindow() ChrTalk( #37 0xFE, ( "Surgical fields have had some success,\x01", "but our understanding of medicine is still\x01", "far from the church's.\x02", ) ) CloseMessageWindow() ChrTalk( #38 0xFE, ( "After all, they have over a thousand\x01", "years of experience on us.\x02", ) ) CloseMessageWindow() Jump("loc_DF9") label("loc_CF5") ChrTalk( #39 0xFE, ( "There was that Septian Church medicine\x01", "that saved Agate, remember?\x02", ) ) CloseMessageWindow() ChrTalk( #40 0xFE, ( "It was very interesting, so I tried to analyze\x01", "it, but...\x02", ) ) CloseMessageWindow() ChrTalk( #41 0xFE, ( "I couldn't figure out how it\x01", "worked in the slightest.\x02", ) ) CloseMessageWindow() ChrTalk( #42 0xFE, ( "*sigh* Modern medical science still has a\x01", "long way to go.\x02", ) ) CloseMessageWindow() OP_A2(0x1) label("loc_DF9") Jump("loc_F21") label("loc_DFC") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x281, 2)), scpexpr(EXPR_END)), "loc_F21") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_EA3") ChrTalk( #43 0xFE, ( "There are dangerous medical substances\x01", "in the central factory labs as well.\x02", ) ) CloseMessageWindow() ChrTalk( #44 0xFE, ( "If any bottles were to break or crack,\x01", "it wouldn't be pretty...\x02", ) ) CloseMessageWindow() Jump("loc_F21") label("loc_EA3") ChrTalk( #45 0xFE, ( "Doesn't seem like there was much\x01", "damage from the earthquake.\x02", ) ) CloseMessageWindow() ChrTalk( #46 0xFE, ( "Phew! Thank goodness the shaking\x01", "wasn't too strong.\x02", ) ) CloseMessageWindow() OP_A2(0x1) label("loc_F21") Jump("loc_F82") label("loc_F24") ChrTalk( #47 0xFE, "If anything comes up, stop by any time.\x02", ) CloseMessageWindow() ChrTalk( #48 0xFE, "I'll probably be right here if you need me.\x02", ) CloseMessageWindow() label("loc_F82") Jump("loc_17CC") label("loc_F85") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x240, 1)), scpexpr(EXPR_END)), "loc_1341") OP_62(0xFE, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1) Sleep(400) ChrTalk( #49 0xFE, "Oh, you all...\x02", ) CloseMessageWindow() ChrTalk( #50 0x101, ( "#1011FAh, Dr. Miriam.\x02\x03", "#1007FThank you very much again for your\x01", "help back then.\x02", ) ) CloseMessageWindow() ChrTalk( #51 0x106, "#053FYeah, I owe you.\x02", ) CloseMessageWindow() TurnDirection(0xFE, 0x106, 400) ChrTalk( #52 0xFE, "Agate. I'm glad to see you're well.\x02", ) CloseMessageWindow() ChrTalk( #53 0xFE, "How have you been since then?\x02", ) CloseMessageWindow() ChrTalk( #54 0x106, ( "#050FNo problem at all. I'm totally back to normal.\x01", "Thanks for askin'.\x02", ) ) CloseMessageWindow() ChrTalk( #55 0xFE, ( "Well, that's good. It doesn't seem like\x01", "there were any aftereffects, in that case.\x02", ) ) CloseMessageWindow() ChrTalk( #56 0xFE, ( "That's some vitality.\x01", "I guess that's a bracer for you. Your body\x01", "is your capital.\x02", ) ) CloseMessageWindow() ChrTalk( #57 0x101, ( "#1016FWell, that's Agate, anyway. If nothing else,\x01", "he's a walking damage sponge.\x02", ) ) CloseMessageWindow() Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x6)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_11EC") ChrTalk( #58 0x107, "#067FAhaha...\x02", ) CloseMessageWindow() label("loc_11EC") ChrTalk( #59 0xFE, "If anything comes up, stop by any time.\x02", ) CloseMessageWindow() ChrTalk( #60 0xFE, ( "Of course, I never want to see\x01", "an injury like that again.\x02", ) ) CloseMessageWindow() ChrTalk( #61 0x106, ( "#051FYeah, no worries.\x02\x03", "I never wanna be injured like that again,\x01", "anyway.\x02", ) ) CloseMessageWindow() ChrTalk( #62 0xFE, "Yes, don't forget those words.\x02", ) CloseMessageWindow() ChrTalk( #63 0xFE, "Do be very careful as you attend to your work.\x02", ) CloseMessageWindow() ChrTalk( #64 0x101, ( "#1006FYeah, you got it.\x02\x03", "Well, see you later, Dr. Miriam.\x02", ) ) CloseMessageWindow() Jump("loc_17C6") label("loc_1341") TurnDirection(0xFE, 0x101, 0) OP_62(0xFE, 0x0, 2000, 0x26, 0x26, 0xFA, 0x1) Sleep(400) ChrTalk( #65 0xFE, "Oh, you all...\x02", ) CloseMessageWindow() ChrTalk( #66 0x101, ( "#1011FOh, Dr. Miriam.\x02\x03", "#1007FThank you very much again for your\x01", "help back then.\x02", ) ) CloseMessageWindow() Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x6)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_13EA") ChrTalk( #67 0x107, "#562FY-Yeah...\x02", ) CloseMessageWindow() label("loc_13EA") ChrTalk( #68 0xFE, "No, I didn't do anything.\x02", ) CloseMessageWindow() ChrTalk( #69 0xFE, ( "If you want to thank anyone, you should thank\x01", "the priest who supplied the medicine.\x02", ) ) CloseMessageWindow() ChrTalk( #70 0xFE, "So...is Agate well?\x02", ) CloseMessageWindow() ChrTalk( #71 0x101, ( "#1006FYeah, no problem. Seems like\x01", "he's totally back to normal.\x02", ) ) CloseMessageWindow() ChrTalk( #72 0xFE, "I see, good to hear that.\x02", ) CloseMessageWindow() ChrTalk( #73 0xFE, ( "That's some vitality.\x01", "I guess that's a bracer for you. Your body\x01", "is your capital.\x02", ) ) CloseMessageWindow() ChrTalk( #74 0x101, ( "#1016FWell, that's Agate, anyway. If nothing else,\x01", "he's a walking damage sponge.\x02", ) ) CloseMessageWindow() Jc((scpexpr(EXPR_EXEC_OP, "OP_42(0x6)"), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_NEG), scpexpr(EXPR_NEQ), scpexpr(EXPR_END)), "loc_15AD") ChrTalk( #75 0x107, "#067FAhaha...\x02", ) CloseMessageWindow() label("loc_15AD") ChrTalk( #76 0xFE, "If anything comes up, stop by any time.\x02", ) CloseMessageWindow() ChrTalk( #77 0xFE, ( "Of course, I never want to see\x01", "an injury like that again.\x02", ) ) CloseMessageWindow() ChrTalk( #78 0x101, ( "#1015FYeah... We'll stay on our toes.\x02\x03", "Any job could have danger in it, after all...\x02", ) ) CloseMessageWindow() ChrTalk( #79 0x103, ( "#026FYes, absolutely, Estelle.\x02\x03", "To perpetually sharpen your awareness\x01", "to prepare for unseen threats...\x02\x03", "#027FCassius often spoke of that as\x01", "the mindset of a bracer.\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x103, 400) ChrTalk( #80 0xFE, "Yes, don't forget those words.\x02", ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( #81 0xFE, ( "Continue to be careful as you attend\x01", "to your work.\x02", ) ) CloseMessageWindow() ChrTalk( #82 0x101, ( "#1006FYeah, you got it.\x02\x03", "Well, see you later, Dr. Miriam.\x02", ) ) CloseMessageWindow() label("loc_17C6") OP_A2(0x142E) OP_A2(0x0) label("loc_17CC") TalkEnd(0x8) Return() # Function_3_200 end def Function_4_17D0(): pass label("Function_4_17D0") TalkBegin(0x9) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x400, 0)), scpexpr(EXPR_END)), "loc_17F9") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x405, 7)), scpexpr(EXPR_END)), "loc_17F6") OP_22(0x192, 0x0, 0x64) ChrTalk( #83 0xFE, "Nya~~go.\x02", ) CloseMessageWindow() label("loc_17F6") Jump("loc_180A") label("loc_17F9") OP_22(0x192, 0x0, 0x64) ChrTalk( #84 0xFE, "Nya-o.\x02", ) CloseMessageWindow() label("loc_180A") TalkEnd(0x9) Return() # Function_4_17D0 end SaveToFile() Try(main)
[ "zj.yang@qq.com" ]
zj.yang@qq.com
27b370638101e981b31018588db62b2ab0f4b00e
ecad2803537295a24fe8274f99dfb85ead3a7191
/debian/python-nova/usr/lib/python2.7/dist-packages/nova/console/rpcapi.py
68d2a9caed42d286fb0d97ff1c12b0a077894ce8
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
permissive
bopopescu/stacklab-nova
98400585ec3b4e3e94269dcb41578fffe7e2c8c1
4ab1698659b663ef222255610d1a5c042706dd65
refs/heads/master
2022-11-20T12:07:18.250829
2012-12-13T04:43:00
2012-12-13T04:43:00
282,166,345
0
0
Apache-2.0
2020-07-24T08:31:57
2020-07-24T08:31:56
null
UTF-8
Python
false
false
52
py
../../../../../share/pyshared/nova/console/rpcapi.py
[ "yuanotes@gmail.com" ]
yuanotes@gmail.com
5d445ef9a92772fcdbfe91bec49281ac6d79d587
61d3d9791a6365d5b9b4f1bbbbed3f7aa7474dec
/day6/part1.py
433c318c4d451891925fd288d918438d2679bcb4
[]
no_license
aezick/adventofcode2018
45067234b34499a3fe4d43d6c038e1a7cdd981ce
62b030628a51d21502e7c3d1935edce918434ae7
refs/heads/master
2020-04-09T16:59:20.539655
2019-01-13T20:40:49
2019-01-13T20:40:49
160,468,035
0
0
null
null
null
null
UTF-8
Python
false
false
2,252
py
import sys from string import ascii_lowercase import itertools # from https://stackoverflow.com/a/29351603/2521402 def iter_all_strings(): for size in itertools.count(1): for s in itertools.product(ascii_lowercase, repeat=size): yield "".join(s) def get_xy(loc_str): x,y = loc_str.strip().split(",") y = y.strip() return x,y # make list of all starting locations # set max bounds of map from max,min x,y of locations # init 2d map of spaces, fill in starting locations {"coordinate": "LOC"} # iterate around each LOC, fill in {"coordinate": "loc+Round"} while # also tracking the size of each LOC # e.g. {"123,456": "AB2"}, so 123,456 is 2 dist from AB with open("input6.txt", "r") as f: it = iter_all_strings() locs = {} the_map = {} sizes = {} min_x = min_y = 10000 max_x = max_y = -1 for line in f: c = next(it) x,y = get_xy(line) # set map limits if min_x > int(x): min_x = int(x) if min_y > int(y): min_y = int(y) if max_x < int(x): max_x = int(x) if max_y < int(y): max_y = int(y) sizes[c] = 1 locs[c] = x + "," + y the_map[locs[c]] = c.upper() dist = 1 some_not_oob = True # oob = out of bounds aka infinite space while some_not_oob: some_not_oob = False for loc in locs: x,y = get_xy(locs[loc]) x = int(x) y = int(y) walk_x = -dist walk_y = 0 # for s in sizes: # if sizes[s] > 1: # print(dist, s, sizes[s]) while walk_x <= dist: new_x = x + walk_x new_y = y + walk_y new_loc = str(new_x) + "," + str(new_y) if new_loc not in the_map: the_map[new_loc] = loc + "," + str(dist) sizes[loc] += 1 elif the_map[new_loc] == ".": pass else: if "," in the_map[new_loc]: loc_id, claim = the_map[new_loc].split(",") if int(claim) == dist: # if contested the_map[new_loc] = "." sizes[loc_id] -= 1 if not some_not_oob or new_x <= min_x or \ new_x >= max_x or new_y <= min_y or \ new_y >= max_y: sizes[loc] = -1234567 else: some_not_oob = True walk_x += 1 walk_y += 1 if walk_y > dist: # reset to bottommost coor walk_y = -dist walk_x = 0 dist += 1 print("sizes:") print(sizes) print(sorted(sizes, key=sizes.get))
[ "aezick@umich.edu" ]
aezick@umich.edu
0f59ff4bae4e87d53ecbc7d9321cb49e072f21bc
51a065360b8b2f4a8cde43842a357b729ce6931a
/computer/roadLine_main.py
cdc86a2b3620244f9fc989312dab770727ae14ef
[]
no_license
muratory/perception
8fd95c1a865c5f2317c61110906856fd1eaa9f2d
23b03a3d33d526318e85748d978c48782298fd4f
refs/heads/master
2021-05-15T22:39:28.659715
2018-06-17T16:43:44
2018-06-17T16:43:44
106,734,394
0
0
null
null
null
null
UTF-8
Python
false
false
16,382
py
import cv2 import numpy as np import threading import Queue import time from scipy import stats from RoadLaneDetection.road_lane_detector import PID_process from roadLineDetectionModel import LineDetectionModel #libraries from deep drive from commonDeepDriveDefine import * from commonDeepDriveTools import * from KeyboardThread import * from VideoThread import * from pathControlClientThread import * ####################################### Deep Drive Thread ############################## class roadLine(threading.Thread): def __init__(self): # call init threading.Thread.__init__(self) # create Video Stream Client Thread self.sctVideoStream = VideoThread() self.sctVideoStream.name = 'VideoSocketThread' self.sctVideoStream.start() # create Keyboard Thread self.keyboardThread = keyboardThread() self.keyboardThread.name = 'roadLine_main_Kb' self.keyboardThread.start() #create Gps Thread self.srvRoadLine = serverThread() self.srvRoadLine.name = 'srvRoadLineThread' self.srvRoadLine.start() #create pathControlCommand client to receive the command such as SPEED for car control self.sctPathControlCommandClientThread = pathControlCommandClientThread() self.sctPathControlCommandClientThread.name = 'sctPathControlCommandClientThread_RL' self.sctPathControlCommandClientThread.start() def ConnectClient(self): # loop until all client connected videoClientConnected = False steerClientConnected = False roadLineSteeringConnected = False pathControlCommandConnected = False # launch connection thread for all client if videoClientEnable == True: self.sctVideoStream.cmd_q.put(ClientCommand( ClientCommand.CONNECT, 'http://' + CAR_IP + ':' + str(PORT_VIDEO_NN_SERVER) + '/?action=stream')) if roadLineSteeringEnable == True: self.srvRoadLine.cmd_q.put(ClientCommand(ClientCommand.CONNECT, PORT_ROADLINE_STEERING_SERVER)) if pathControlCommandEnable == True: self.sctPathControlCommandClientThread.cmd_q.put(ClientCommand(ClientCommand.CONNECT, ADDR_PATH_CONTROL_COMMAND_SERVER)) while ((videoClientConnected != videoClientEnable) or (pathControlCommandConnected != pathControlCommandEnable) or (roadLineSteeringConnected != roadLineSteeringEnable)): # wait for .5 second before to check time.sleep(0.5) if (videoClientConnected != videoClientEnable): try: reply = self.sctVideoStream.reply_q.get(False) if reply.type == ClientReply.SUCCESS: videoClientConnected = True print 'Video stream server connected' except Queue.Empty: print 'Video Client not connected' if (roadLineSteeringConnected != roadLineSteeringEnable): try: reply = self.srvRoadLine.reply_q.get(False) if reply.type == ClientReply.SUCCESS: roadLineSteeringConnected = True print 'Road line steering server connected' except Queue.Empty: print 'Road line steering server not ready' if (pathControlCommandConnected != pathControlCommandEnable): try: reply = self.sctPathControlCommandClientThread.reply_q.get(False) if reply.type == ClientReply.SUCCESS: pathControlCommandConnected=True print 'pathControl Command Client connected' except Queue.Empty: print 'pathControl Command Client not connected' try: reply = self.keyboardThread.reply_q.get(False) if reply.type == ClientReply.SUCCESS: if reply.data == 'exit': return False except Queue.Empty: time.sleep(0.5) pass def run(self): pathControlCommandLabel = 'NONE' keyBoardOverride = 0 lastKeyPressed = 0 forceRoadLineLabel = 'NONE' mainSelectionByGpsps = False lastSteerControlTime = time.time() if gpsEnable == True and pathControlCommandEnable == True: mainSelectionByGpsps = True else: forceRoadLineLabel = 'IDLE' #get LineDetect model roadLineModel = LineDetectionModel('LineDetectionModel') predictionValuesSteeringAngle = np.zeros(NB_SAMPLE_RUNNING_AVERAGE_PREDICTION, dtype=np.int) predictionIndexSteeringAngle = 0 lastAngleSent = 0 # initial steer command set to stop try: # start keyboard thread to get keyboard input self.keyboardThread.cmd_q.put(ClientCommand(ClientCommand.RECEIVE, '')) # connect All client if self.ConnectClient() == False : return print 'Start Main Thread for Road Line detect estimate' # start receiver thread client to receive continuously data self.sctVideoStream.cmd_q.put(ClientCommand(ClientCommand.RECEIVE, '')) #receive command from path cotronl such as IDLE ... self.sctPathControlCommandClientThread.cmd_q.put(ClientCommand(ClientCommand.RECEIVE,'')) while True: ############################# Manage IMAGE for Deep neural network to extract Steer Command ############### try: # try to see if image ready for CAM1 replyVideo = self.sctVideoStream.reply_q.get(False) if replyVideo.type == ClientReply.SUCCESS: # print length as debug # print 'length =' + str(len(self.sctVideoStream.lastImage)) # decode jpg into array image2RoadLine = cv2.imdecode(np.fromstring(self.sctVideoStream.lastImage, dtype=np.uint8),-1) # for all model , make a prediction and average it # (could be other processing here) roadLineUseCase = 0 totalWeight = 0 #start timer to measure the time of the predictions e1 = cv2.getTickCount() if forceRoadLineLabel != 'NONE': roadLineUseCase = forceRoadLineLabel else: if mainSelectionByGpsps == True: #gps2MainRoadLabel always return STRAIGHT in case of interesction roadLineUseCase = pathControlCommandLabel else: forceRoadLineLabel = 'IDLE' roadLineUseCase = forceRoadLineLabel #now getting value for steering (roadLineOffset, roadLineSteerCommand) = roadLineModel.predict(image2RoadLine,roadLineUseCase) # print 'roadLineSteerCommand = ',roadLineSteerCommand, predictionValuesSteeringAngle[predictionIndexSteeringAngle] = round(roadLineSteerCommand) # Steer from PID based on offset if roadLineOffset != 999 : # pidSteerCommand = PID_process (roadLineOffset) # print 'roadLineOffset= ',roadLineOffset,'\troadLineSteerCommand= ',roadLineSteerCommand,'\tpidSteerCommand= ',pidSteerCommand # predictionValuesSteeringAngle[predictionIndexSteeringAngle] = round(pidSteerCommand) pass # fill average angle table based on prediction # predictionValuesSteeringAngle[predictionIndexSteeringAngle] = round(pidSteerCommand) #print 'Prediction Average = ', + self.predictionValuesToAverage predictionIndexSteeringAngle += 1 if predictionIndexSteeringAngle >= NB_SAMPLE_RUNNING_AVERAGE_PREDICTION: predictionIndexSteeringAngle = 0 e2 = cv2.getTickCount() t = (e2 - e1)/cv2.getTickFrequency() if (t > STEERING_PREDICTION_SAMPLING_TIME): print 'WARNING : too much time to predict = ', t cv2.putText(image2RoadLine, 'PREDICT TIME TOO HIGH=' + str(int(t*1000)), (0,IMAGE_PIXELS_Y/2), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1) else: #we have time to display some stuff #write speed cv2.putText(image2RoadLine, 'RoadUseCase = ' + roadLineUseCase, (0,IMAGE_PIXELS_Y/2 + 15), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1) cv2.putText(image2RoadLine, 'PredicTime = ' + str(int(t*1000)), (0,IMAGE_PIXELS_Y/2 + 30), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1) cv2.putText(image2RoadLine, 'SteerAngle = ' + str(lastAngleSent), (0,IMAGE_PIXELS_Y/2 + 45), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1) if forceRoadLineLabel != 'NONE': cv2.putText(image2RoadLine, 'MANUAL SELECTION', (0,IMAGE_PIXELS_Y/2 + 75), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1) else : if mainSelectionByGpsps == True: cv2.putText(image2RoadLine, 'GPS SELECTION', (0,IMAGE_PIXELS_Y/2 + 75), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1) showLabel(lastAngleSent,'roadLinevision', image2RoadLine) cv2.imshow('roadLinevision', image2RoadLine) # check if we want to stop autonomous driving if cv2.waitKey(1) & 0xFF == ord('q'): break else: print 'Error getting image :' + str(replyVideo.data) break except Queue.Empty: # queue empty most of the time because image not ready pass #############################get Command from PathControlCommand server ############### try: # try to see if data ready reply = self.sctPathControlCommandClientThread.reply_q.get(False) if reply.type == ClientReply.SUCCESS: strCommand = str(reply.data) #filter only interesting command for neural network if strCommand == 'IDLE' or strCommand == 'LEFT_TURN' or strCommand == 'RIGHT_TURN' or strCommand == 'STRAIGHT' : pathControlCommandLabel = strCommand else: print 'Error getting path control command :' + str(reply.data) break except Queue.Empty: # queue empty most of the time because data not ready pass ######################## Get control from the keyboard if any ######################### try: # keyboard queue filled ? reply = self.keyboardThread.reply_q.get(False) if reply.type == ClientReply.SUCCESS: # new keyboard input found keyPressed = reply.data strText = keyPressed if keyPressed == 'exit': turn_angle = 0 # get out of the loop break elif keyPressed == 'help': strText = 'Key:Q,R,I,L,S,G(ps)' elif (keyPressed == 'RIGHT_TURN') or (keyPressed == 'IDLE') or (keyPressed == 'LEFT_TURN') or (keyPressed == 'STRAIGHT'): forceRoadLineLabel = keyPressed elif (keyPressed == 'GPS'): forceRoadLineLabel = 'NONE' mainSelectionByGpsps = True elif keyPressed == 'none': #no handle of no keyboard pressed strText='' else: # key not known display error self.keyboardThread.displayText() strText='' if strText != '': self.keyboardThread.displayText(strText) # record lastkey that can be use for consecutive command action lastKeyPressed = keyPressed else: print 'Error getting keyboard input :' + str(reply.data) break except Queue.Empty: # queue empty most of the time because keyboard not hit pass ############### Compute/send Angle to the server#################### # send control command according to sampling dedicated for it timeNow = time.time() if timeNow > (lastSteerControlTime + STEERING_PREDICTION_SAMPLING_TIME): prediction = np.sum(predictionValuesSteeringAngle, dtype=int) / NB_SAMPLE_RUNNING_AVERAGE_PREDICTION #print 'NN prediction = ' + str(predictionValuesSteeringAngle) + ' , average_value = ' + str(prediction) #print 'UseCasePredict = ' + str(predictionValuesRoadUseCase) + ' , Best_Value = ' + roadLineUseCase ) # Send angle to the server and all client connected if lastAngleSent != prediction: self.srvRoadLine.cmd_q.put(ClientCommand(ClientCommand.SEND, prediction)) lastAngleSent = prediction lastSteerControlTime = timeNow finally: print 'ending road Line detection main' # stop and close all client and close them self.srvRoadLine.cmd_q.put(ClientCommand(ClientCommand.STOP)) self.srvRoadLine.cmd_q.put(ClientCommand(ClientCommand.CLOSE)) self.sctVideoStream.cmd_q.put(ClientCommand(ClientCommand.STOP)) self.sctVideoStream.cmd_q.put(ClientCommand(ClientCommand.CLOSE)) self.keyboardThread.cmd_q.put(ClientCommand(ClientCommand.STOP)) self.keyboardThread.cmd_q.put(ClientCommand(ClientCommand.CLOSE)) self.sctPathControlCommandClientThread.cmd_q.put(ClientCommand(ClientCommand.STOP)) self.sctPathControlCommandClientThread.cmd_q.put(ClientCommand(ClientCommand.CLOSE)) # and make sure all of them ended properly self.srvRoadLine.join() self.sctVideoStream.join() self.keyboardThread.join() self.sctPathControlCommandClientThread.join() print ' road Line detection main Done' if __name__ == '__main__': # create Deep drive thread and strt print "Create RoadLine Main" roadLine = roadLine() roadLine.name = 'nnMain' # start print "Start RoadLine Main" roadLine.start() roadLine.join() print 'end'
[ "pierre.muratory@gmail.com" ]
pierre.muratory@gmail.com
fd50dc99e889727458cb06d43d27cffc4a7f7eea
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02957/s350657390.py
f4234eb1e4a776337083c3a01b5e677877675e22
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
112
py
a, b = map(int, input().split()) if (a + b) % 2 == 0: print(int((a + b) / 2)) else: print('IMPOSSIBLE')
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
6656b3302df4f76204c5bf1b99e54910109616bf
3cda2dc11e1b7b96641f61a77b3afde4b93ac43f
/test/algo/nas/oneshot/test_supermodules.py
adced554c2d8fce7979ba530084a26eaf6441a89
[ "MIT" ]
permissive
Eurus-Holmes/nni
6da51c352e721f0241c7fd26fa70a8d7c99ef537
b84d25bec15ece54bf1703b1acb15d9f8919f656
refs/heads/master
2023-08-23T10:45:54.879054
2023-08-07T02:39:54
2023-08-07T02:39:54
163,079,164
3
2
MIT
2023-08-07T12:35:54
2018-12-25T12:04:16
Python
UTF-8
Python
false
false
28,697
py
import pytest import numpy as np import torch import torch.nn as nn import nni from nni.mutable import MutableList, frozen from nni.nas.nn.pytorch import LayerChoice, ModelSpace, Cell, MutableConv2d, MutableBatchNorm2d, MutableLayerNorm, MutableLinear, MutableMultiheadAttention from nni.nas.oneshot.pytorch.differentiable import DartsLightningModule from nni.nas.oneshot.pytorch.strategy import RandomOneShot, DARTS from nni.nas.oneshot.pytorch.supermodule.base import BaseSuperNetModule from nni.nas.oneshot.pytorch.supermodule.differentiable import ( MixedOpDifferentiablePolicy, DifferentiableMixedLayer, DifferentiableMixedInput, GumbelSoftmax, DifferentiableMixedRepeat, DifferentiableMixedCell ) from nni.nas.oneshot.pytorch.supermodule.sampling import ( MixedOpPathSamplingPolicy, PathSamplingLayer, PathSamplingInput, PathSamplingRepeat, PathSamplingCell ) from nni.nas.oneshot.pytorch.supermodule.operation import MixedConv2d, NATIVE_MIXED_OPERATIONS from nni.nas.oneshot.pytorch.supermodule.proxyless import ProxylessMixedLayer, ProxylessMixedInput from nni.nas.oneshot.pytorch.supermodule._operation_utils import Slicable as S, MaybeWeighted as W from nni.nas.oneshot.pytorch.supermodule._expression_utils import * from ut.nas.nn.models import ( CellSimple, CellDefaultArgs, CellCustomProcessor, CellLooseEnd, CellOpFactory ) @pytest.fixture(autouse=True) def context(): frozen._ENSURE_FROZEN_STRICT = False yield frozen._ENSURE_FROZEN_STRICT = True def test_slice(): weight = np.ones((3, 7, 24, 23)) assert S(weight)[:, 1:3, :, 9:13].shape == (3, 2, 24, 4) assert S(weight)[:, 1:W(3)*2+1, :, 9:13].shape == (3, 6, 24, 4) assert S(weight)[:, 1:W(3)*2+1].shape == (3, 6, 24, 23) # Ellipsis assert S(weight)[..., 9:13].shape == (3, 7, 24, 4) assert S(weight)[:2, ..., 1:W(3)+1].shape == (2, 7, 24, 3) assert S(weight)[..., 1:W(3)*2+1].shape == (3, 7, 24, 6) assert S(weight)[..., :10, 1:W(3)*2+1].shape == (3, 7, 10, 6) # no effect assert S(weight)[:] is weight # list assert S(weight)[[slice(1), slice(2, 3)]].shape == (2, 7, 24, 23) assert S(weight)[[slice(1), slice(2, W(2) + 1)], W(2):].shape == (2, 5, 24, 23) # weighted weight = S(weight)[:W({1: 0.5, 2: 0.3, 3: 0.2})] weight = weight[:, 0, 0, 0] assert weight[0] == 1 and weight[1] == 0.5 and weight[2] == 0.2 weight = np.ones((3, 6, 6)) value = W({1: 0.5, 3: 0.5}) weight = S(weight)[:, 3 - value:3 + value, 3 - value:3 + value] for i in range(0, 6): for j in range(0, 6): if 2 <= i <= 3 and 2 <= j <= 3: assert weight[0, i, j] == 1 else: assert weight[1, i, j] == 0.5 # weighted + list value = W({1: 0.5, 3: 0.5}) weight = np.ones((8, 4)) weight = S(weight)[[slice(value), slice(4, value + 4)]] assert weight.sum(1).tolist() == [4, 2, 2, 0, 4, 2, 2, 0] with pytest.raises(ValueError, match='one distinct'): # has to be exactly the same instance, equal is not enough weight = S(weight)[:W({1: 0.5}), : W({1: 0.5})] def test_valuechoice_utils(): chosen = {"exp": 3, "add": 1} vc0 = nni.choice('exp', [3, 4, 6]) * 2 + nni.choice('add', [0, 1]) assert vc0.freeze(chosen) == 7 vc = vc0 + nni.choice('exp', [3, 4, 6]) assert vc.freeze(chosen) == 10 assert list(MutableList([vc0, vc]).simplify().keys()) == ['exp', 'add'] assert traverse_all_options(vc) == [9, 10, 12, 13, 18, 19] weights = dict(traverse_all_options(vc, weights={'exp': [0.5, 0.3, 0.2], 'add': [0.4, 0.6]})) ans = dict([(9, 0.2), (10, 0.3), (12, 0.12), (13, 0.18), (18, 0.08), (19, 0.12)]) assert len(weights) == len(ans) for value, weight in ans.items(): assert abs(weight - weights[value]) < 1e-6 assert evaluate_constant(nni.choice('x', [3, 4, 6]) - nni.choice('x', [3, 4, 6])) == 0 with pytest.raises(ValueError): evaluate_constant(nni.choice('x', [3, 4, 6]) - nni.choice('y', [3, 4, 6])) assert evaluate_constant(nni.choice('x', [3, 4, 6]) * 2 / nni.choice('x', [3, 4, 6])) == 2 def test_expectation(): vc = nni.choice('exp', [3, 4, 6]) * 2 + nni.choice('add', [0, 1]) assert expression_expectation(vc, {'exp': [0.5, 0.3, 0.2], 'add': [0.4, 0.6]}) == 8.4 vc = sum([nni.choice(f'e{i}', [0, 1]) for i in range(100)]) assert expression_expectation(vc, {f'e{i}': [0.5] * 2 for i in range(100)}) == 50 vc = nni.choice('a', [1, 2, 3]) * nni.choice('b', [1, 2, 3]) - nni.choice('c', [1, 2, 3]) probs1 = [0.2, 0.3, 0.5] probs2 = [0.1, 0.2, 0.7] probs3 = [0.3, 0.4, 0.3] expect = sum( (i * j - k) * p1 * p2 * p3 for i, p1 in enumerate(probs1, 1) for j, p2 in enumerate(probs2, 1) for k, p3 in enumerate(probs3, 1) ) assert abs(expression_expectation(vc, {'a': probs1, 'b': probs2, 'c': probs3}) - expect) < 1e-12 vc = nni.choice('a', [1, 2, 3]) + 1 assert expression_expectation(vc, {'a': [0.2, 0.3, 0.5]}) == 3.3 def test_weighted_sum(): weights = [0.1, 0.2, 0.7] items = [1, 2, 3] assert abs(weighted_sum(items, weights) - 2.6) < 1e-6 assert weighted_sum(items) == 6 with pytest.raises(TypeError, match='Unsupported'): weighted_sum(['a', 'b', 'c'], weights) assert abs(weighted_sum(np.arange(3), weights).item() - 1.6) < 1e-6 items = [torch.full((2, 3, 5), i) for i in items] assert abs(weighted_sum(items, weights).flatten()[0].item() - 2.6) < 1e-6 items = [torch.randn(2, 3, i) for i in [1, 2, 3]] with pytest.raises(ValueError, match=r'does not match.*\n.*torch\.Tensor\(2, 3, 1\)'): weighted_sum(items, weights) items = [(1, 2), (3, 4), (5, 6)] res = weighted_sum(items, weights) assert len(res) == 2 and abs(res[0] - 4.2) < 1e-6 and abs(res[1] - 5.2) < 1e-6 items = [(1, 2), (3, 4), (5, 6, 7)] with pytest.raises(ValueError): weighted_sum(items, weights) items = [{"a": i, "b": np.full((2, 3, 5), i)} for i in [1, 2, 3]] res = weighted_sum(items, weights) assert res['b'].shape == (2, 3, 5) assert abs(res['b'][0][0][0] - res['a']) < 1e-6 assert abs(res['a'] - 2.6) < 1e-6 def test_pathsampling_valuechoice(): orig_conv = MutableConv2d(3, nni.choice('123', [3, 5, 7]), kernel_size=3) conv = MixedConv2d.mutate(orig_conv, 'dummy', {}, {'mixed_op_sampling': MixedOpPathSamplingPolicy}) conv.resample(memo={'123': 5}) assert conv(torch.zeros((1, 3, 5, 5))).size(1) == 5 conv.resample(memo={'123': 7}) assert conv(torch.zeros((1, 3, 5, 5))).size(1) == 7 assert conv.export({})['123'] in [3, 5, 7] def test_differentiable_valuechoice(): orig_conv = MutableConv2d(3, nni.choice('456', [3, 5, 7]), kernel_size=nni.choice('123', [3, 5, 7]), padding=nni.choice('123', [3, 5, 7]) // 2 ) memo = { '123': nn.Parameter(torch.zeros(3)), '456': nn.Parameter(torch.zeros(3)), } conv = MixedConv2d.mutate(orig_conv, 'dummy', memo, {'mixed_op_sampling': MixedOpDifferentiablePolicy}) assert conv(torch.zeros((1, 3, 7, 7))).size(2) == 7 assert set(conv.export({}).keys()) == {'123', '456'} def test_differentiable_layerchoice_dedup(): layerchoice1 = LayerChoice([MutableConv2d(3, 3, 3), MutableConv2d(3, 3, 3)], label='a') layerchoice2 = LayerChoice([MutableConv2d(3, 3, 3), MutableConv2d(3, 3, 3)], label='a') memo = {'a': nn.Parameter(torch.zeros(2))} DifferentiableMixedLayer.mutate(layerchoice1, 'x', memo, {}) DifferentiableMixedLayer.mutate(layerchoice2, 'x', memo, {}) assert len(memo) == 1 and 'a' in memo def _mutate_op_path_sampling_policy(operation): for native_op in NATIVE_MIXED_OPERATIONS: if native_op.bound_type == type(operation): mutate_op = native_op.mutate(operation, 'dummy', {}, {'mixed_op_sampling': MixedOpPathSamplingPolicy}) break return mutate_op def _mixed_operation_sampling_sanity_check(operation, memo, *input): mutate_op = _mutate_op_path_sampling_policy(operation) mutate_op.resample(memo=memo) return mutate_op(*input) def _mixed_operation_state_dict_sanity_check(operation, model, memo, *input): mutate_op = _mutate_op_path_sampling_policy(operation) mutate_op.resample(memo=memo) frozen_op = mutate_op.freeze(memo) return frozen_op(*input), mutate_op(*input) def _mixed_operation_differentiable_sanity_check(operation, *input): memo = {k: nn.Parameter(torch.zeros(len(v))) for k, v in operation.simplify().items()} for native_op in NATIVE_MIXED_OPERATIONS: if native_op.bound_type == type(operation): mutate_op = native_op.mutate(operation, 'dummy', memo, {'mixed_op_sampling': MixedOpDifferentiablePolicy}) break mutate_op(*input) mutate_op.export({}) mutate_op.export_probs({}) def test_mixed_linear(): linear = MutableLinear(nni.choice('shared', [3, 6, 9]), nni.choice('xx', [2, 4, 8])) _mixed_operation_sampling_sanity_check(linear, {'shared': 3}, torch.randn(2, 3)) _mixed_operation_sampling_sanity_check(linear, {'shared': 9}, torch.randn(2, 9)) _mixed_operation_differentiable_sanity_check(linear, torch.randn(2, 9)) linear = MutableLinear(nni.choice('shared', [3, 6, 9]), nni.choice('xx', [2, 4, 8]), bias=False) _mixed_operation_sampling_sanity_check(linear, {'shared': 3}, torch.randn(2, 3)) with pytest.raises(TypeError): linear = MutableLinear(nni.choice('shared', [3, 6, 9]), nni.choice('xx', [2, 4, 8]), bias=nni.choice('yy', [False, True])) _mixed_operation_sampling_sanity_check(linear, {'shared': 3}, torch.randn(2, 3)) linear = MutableLinear(nni.choice('in_features', [3, 6, 9]), nni.choice('out_features', [2, 4, 8]), bias=True) kwargs = {'in_features': 6, 'out_features': 4} out1, out2 = _mixed_operation_state_dict_sanity_check(linear, MutableLinear(**kwargs), kwargs, torch.randn(2, 6)) assert torch.allclose(out1, out2) def test_mixed_conv2d(): conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('out', [2, 4, 8]) * 2, 1) assert _mixed_operation_sampling_sanity_check(conv, {'in': 3, 'out': 4}, torch.randn(2, 3, 9, 9)).size(1) == 8 _mixed_operation_differentiable_sanity_check(conv, torch.randn(2, 9, 3, 3)) # stride conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('out', [2, 4, 8]), 1, stride=nni.choice('stride', [1, 2])) assert _mixed_operation_sampling_sanity_check(conv, {'in': 3, 'stride': 2}, torch.randn(2, 3, 10, 10)).size(2) == 5 assert _mixed_operation_sampling_sanity_check(conv, {'in': 3, 'stride': 1}, torch.randn(2, 3, 10, 10)).size(2) == 10 with pytest.raises(ValueError, match='must not be mutable'): _mixed_operation_differentiable_sanity_check(conv, torch.randn(2, 9, 10, 10)) # groups, dw conv conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('in', [3, 6, 9]), 1, groups=nni.choice('in', [3, 6, 9])) assert _mixed_operation_sampling_sanity_check(conv, {'in': 6}, torch.randn(2, 6, 10, 10)).size() == torch.Size([2, 6, 10, 10]) # groups, invalid case conv = MutableConv2d(nni.choice('in', [9, 6, 3]), nni.choice('in', [9, 6, 3]), 1, groups=9) with pytest.raises(RuntimeError): assert _mixed_operation_sampling_sanity_check(conv, {'in': 6}, torch.randn(2, 6, 10, 10)) # groups, differentiable conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('out', [3, 6, 9]), 1, groups=nni.choice('in', [3, 6, 9])) _mixed_operation_differentiable_sanity_check(conv, torch.randn(2, 9, 3, 3)) conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('in', [3, 6, 9]), 1, groups=nni.choice('in', [3, 6, 9])) _mixed_operation_differentiable_sanity_check(conv, torch.randn(2, 9, 3, 3)) with pytest.raises(ValueError): conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('in', [3, 6, 9]), 1, groups=nni.choice('groups', [3, 9])) _mixed_operation_differentiable_sanity_check(conv, torch.randn(2, 9, 3, 3)) with pytest.raises(RuntimeError): conv = MutableConv2d(nni.choice('in', [3, 6, 9]), nni.choice('in', [3, 6, 9]), 1, groups=nni.choice('in', [3, 6, 9]) // 3) _mixed_operation_differentiable_sanity_check(conv, torch.randn(2, 10, 3, 3)) # make sure kernel is sliced correctly conv = MutableConv2d(1, 1, nni.choice('k', [1, 3]), bias=False) conv = MixedConv2d.mutate(conv, 'dummy', {}, {'mixed_op_sampling': MixedOpPathSamplingPolicy}) with torch.no_grad(): conv.weight.zero_() # only center is 1, must pick center to pass this test conv.weight[0, 0, 1, 1] = 1 conv.resample({'k': 1}) assert conv(torch.ones((1, 1, 3, 3))).sum().item() == 9 # only `in_channels`, `out_channels`, `kernel_size`, and `groups` influence state_dict conv = MutableConv2d( nni.choice('in_channels', [2, 4, 8]), nni.choice('out_channels', [6, 12, 24]), kernel_size=nni.choice('kernel_size', [3, 5, 7]), groups=nni.choice('groups', [1, 2]) ) kwargs = { 'in_channels': 8, 'out_channels': 12, 'kernel_size': 5, 'groups': 2 } out1, out2 = _mixed_operation_state_dict_sanity_check(conv, MutableConv2d(**kwargs), kwargs, torch.randn(2, 8, 16, 16)) assert torch.allclose(out1, out2) def test_mixed_batchnorm2d(): bn = MutableBatchNorm2d(nni.choice('dim', [32, 64])) assert _mixed_operation_sampling_sanity_check(bn, {'dim': 32}, torch.randn(2, 32, 3, 3)).size(1) == 32 assert _mixed_operation_sampling_sanity_check(bn, {'dim': 64}, torch.randn(2, 64, 3, 3)).size(1) == 64 _mixed_operation_differentiable_sanity_check(bn, torch.randn(2, 64, 3, 3)) bn = MutableBatchNorm2d(nni.choice('num_features', [32, 48, 64])) kwargs = {'num_features': 48} out1, out2 = _mixed_operation_state_dict_sanity_check(bn, MutableBatchNorm2d(**kwargs), kwargs, torch.randn(2, 48, 3, 3)) assert torch.allclose(out1, out2) def test_mixed_layernorm(): ln = MutableLayerNorm(nni.choice('normalized_shape', [32, 64]), elementwise_affine=True) assert _mixed_operation_sampling_sanity_check(ln, {'normalized_shape': 32}, torch.randn(2, 16, 32)).size(-1) == 32 assert _mixed_operation_sampling_sanity_check(ln, {'normalized_shape': 64}, torch.randn(2, 16, 64)).size(-1) == 64 _mixed_operation_differentiable_sanity_check(ln, torch.randn(2, 16, 64)) import itertools ln = MutableLayerNorm(nni.choice('normalized_shape', list(itertools.product([16, 32, 64], [8, 16])))) assert list(_mixed_operation_sampling_sanity_check(ln, {'normalized_shape': (16, 8)}, torch.randn(2, 16, 8)).shape[-2:]) == [16, 8] assert list(_mixed_operation_sampling_sanity_check(ln, {'normalized_shape': (64, 16)}, torch.randn(2, 64, 16)).shape[-2:]) == [64, 16] _mixed_operation_differentiable_sanity_check(ln, torch.randn(2, 64, 16)) ln = MutableLayerNorm(nni.choice('normalized_shape', [32, 48, 64])) kwargs = {'normalized_shape': 48} out1, out2 = _mixed_operation_state_dict_sanity_check(ln, MutableLayerNorm(**kwargs), kwargs, torch.randn(2, 8, 48)) assert torch.allclose(out1, out2) def test_mixed_mhattn(): mhattn = MutableMultiheadAttention(nni.choice('emb', [4, 8]), 4) assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 4}, torch.randn(7, 2, 4), torch.randn(7, 2, 4), torch.randn(7, 2, 4))[0].size(-1) == 4 assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 8}, torch.randn(7, 2, 8), torch.randn(7, 2, 8), torch.randn(7, 2, 8))[0].size(-1) == 8 _mixed_operation_differentiable_sanity_check(mhattn, torch.randn(7, 2, 8), torch.randn(7, 2, 8), torch.randn(7, 2, 8)) mhattn = MutableMultiheadAttention(nni.choice('emb', [4, 8]), nni.choice('heads', [2, 3, 4])) assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 4, 'heads': 2}, torch.randn(7, 2, 4), torch.randn(7, 2, 4), torch.randn(7, 2, 4))[0].size(-1) == 4 with pytest.raises(AssertionError, match='divisible'): assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 4, 'heads': 3}, torch.randn(7, 2, 4), torch.randn(7, 2, 4), torch.randn(7, 2, 4))[0].size(-1) == 4 mhattn = MutableMultiheadAttention(nni.choice('emb', [4, 8]), 4, kdim=nni.choice('kdim', [5, 7])) assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 4, 'kdim': 7}, torch.randn(7, 2, 4), torch.randn(7, 2, 7), torch.randn(7, 2, 4))[0].size(-1) == 4 assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 8, 'kdim': 5}, torch.randn(7, 2, 8), torch.randn(7, 2, 5), torch.randn(7, 2, 8))[0].size(-1) == 8 mhattn = MutableMultiheadAttention(nni.choice('emb', [4, 8]), 4, vdim=nni.choice('vdim', [5, 8])) assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 4, 'vdim': 8}, torch.randn(7, 2, 4), torch.randn(7, 2, 4), torch.randn(7, 2, 8))[0].size(-1) == 4 assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 8, 'vdim': 5}, torch.randn(7, 2, 8), torch.randn(7, 2, 8), torch.randn(7, 2, 5))[0].size(-1) == 8 _mixed_operation_differentiable_sanity_check(mhattn, torch.randn(5, 3, 8), torch.randn(5, 3, 8), torch.randn(5, 3, 8)) mhattn = MutableMultiheadAttention(embed_dim=nni.choice('embed_dim', [4, 8, 16]), num_heads=nni.choice('num_heads', [1, 2, 4]), kdim=nni.choice('kdim', [4, 8, 16]), vdim=nni.choice('vdim', [4, 8, 16])) kwargs = {'embed_dim': 16, 'num_heads': 2, 'kdim': 4, 'vdim': 8} (out1, _), (out2, _) = _mixed_operation_state_dict_sanity_check(mhattn, MutableMultiheadAttention(**kwargs), kwargs, torch.randn(7, 2, 16), torch.randn(7, 2, 4), torch.randn(7, 2, 8)) assert torch.allclose(out1, out2) @pytest.mark.skipif(torch.__version__.startswith('1.7'), reason='batch_first is not supported for legacy PyTorch') def test_mixed_mhattn_batch_first(): # batch_first is not supported for legacy pytorch versions # mark 1.7 because 1.7 is used on legacy pipeline mhattn = MutableMultiheadAttention(nni.choice('emb', [4, 8]), 2, kdim=(nni.choice('kdim', [3, 7])), vdim=nni.choice('vdim', [5, 8]), bias=False, add_bias_kv=True, batch_first=True) assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 4, 'kdim': 7, 'vdim': 8}, torch.randn(2, 7, 4), torch.randn(2, 7, 7), torch.randn(2, 7, 8))[0].size(-1) == 4 assert _mixed_operation_sampling_sanity_check(mhattn, {'emb': 8, 'kdim': 3, 'vdim': 5}, torch.randn(2, 7, 8), torch.randn(2, 7, 3), torch.randn(2, 7, 5))[0].size(-1) == 8 _mixed_operation_differentiable_sanity_check(mhattn, torch.randn(1, 7, 8), torch.randn(1, 7, 7), torch.randn(1, 7, 8)) def test_pathsampling_layer_input(): op = PathSamplingLayer({'a': MutableLinear(2, 3, bias=False), 'b': MutableLinear(2, 3, bias=True)}, label='ccc') with pytest.raises(RuntimeError, match='sample'): op(torch.randn(4, 2)) op.resample({}) assert op(torch.randn(4, 2)).size(-1) == 3 assert op.simplify()['ccc'].values == ['a', 'b'] assert op.export({})['ccc'] in ['a', 'b'] input = PathSamplingInput(5, 2, 'concat', 'ddd') sample = input.resample({}) assert 'ddd' in sample assert len(sample['ddd']) == 2 assert input([torch.randn(4, 2) for _ in range(5)]).size(-1) == 4 assert len(input.export({})['ddd']) == 2 def test_differentiable_layer_input(): op = DifferentiableMixedLayer({'a': MutableLinear(2, 3, bias=False), 'b': MutableLinear(2, 3, bias=True)}, nn.Parameter(torch.randn(2)), nn.Softmax(-1), 'eee') assert op(torch.randn(4, 2)).size(-1) == 3 assert op.export({})['eee'] in ['a', 'b'] probs = op.export_probs({}) assert len(probs) == 1 assert len(probs['eee']) == 2 assert abs(probs['eee']['a'] + probs['eee']['b'] - 1) < 1e-4 assert len(list(op.parameters())) == 4 assert len(list(op.arch_parameters())) == 1 with pytest.raises(ValueError): op = DifferentiableMixedLayer({'a': MutableLinear(2, 3), 'b': MutableLinear(2, 4)}, nn.Parameter(torch.randn(2)), nn.Softmax(-1), 'eee') op(torch.randn(4, 2)) input = DifferentiableMixedInput(5, 2, nn.Parameter(torch.zeros(5)), GumbelSoftmax(-1), 'ddd') assert input([torch.randn(4, 2) for _ in range(5)]).size(-1) == 2 assert len(input.export({})['ddd']) == 2 assert len(input.export_probs({})) == 1 assert len(input.export_probs({})['ddd']) == 5 assert 3 in input.export_probs({})['ddd'] def test_proxyless_layer_input(): op = ProxylessMixedLayer({'a': MutableLinear(2, 3, bias=False), 'b': MutableLinear(2, 3, bias=True)}, nn.Parameter(torch.randn(2)), nn.Softmax(-1), 'eee') assert op.resample({})['eee'] in ['a', 'b'] assert op(torch.randn(4, 2)).size(-1) == 3 assert op.export({})['eee'] in ['a', 'b'] assert len(list(op.parameters())) == 4 assert len(list(op.arch_parameters())) == 1 input = ProxylessMixedInput(5, 2, nn.Parameter(torch.zeros(5)), GumbelSoftmax(-1), 'ddd') assert all(x in list(range(5)) for x in input.resample({})['ddd']) assert input([torch.randn(4, 2) for _ in range(5)]).size() == torch.Size([4, 2]) exported = input.export({})['ddd'] assert len(exported) == 2 and all(e in list(range(5)) for e in exported) def test_pathsampling_repeat(): op = PathSamplingRepeat([MutableLinear(16, 16), MutableLinear(16, 8), MutableLinear(8, 4)], nni.choice('ccc', [1, 2, 3])) sample = op.resample({}) assert sample['ccc'] in [1, 2, 3] for i in range(1, 4): op.resample({'ccc': i}) out = op(torch.randn(2, 16)) assert out.shape[1] == [16, 8, 4][i - 1] op = PathSamplingRepeat([MutableLinear(i + 1, i + 2) for i in range(7)], 2 * nni.choice('ddd', [1, 2, 3]) + 1) sample = op.resample({}) assert sample['ddd'] in [1, 2, 3] for i in range(1, 4): op.resample({'ddd': i}) out = op(torch.randn(2, 1)) assert out.shape[1] == (2 * i + 1) + 1 def test_differentiable_repeat(): op = DifferentiableMixedRepeat( [MutableLinear(8 if i == 0 else 16, 16) for i in range(4)], nni.choice('ccc', [0, 1]) * 2 + 1, GumbelSoftmax(-1), {'ccc': nn.Parameter(torch.randn(2))}, ) op.resample({}) assert op(torch.randn(2, 8)).size() == torch.Size([2, 16]) sample = op.export({}) assert 'ccc' in sample and sample['ccc'] in [0, 1] assert sorted(op.export_probs({})['ccc'].keys()) == [0, 1] class TupleModule(nn.Module): def __init__(self, num): super().__init__() self.num = num def forward(self, *args, **kwargs): return torch.full((2, 3), self.num), torch.full((3, 5), self.num), {'a': 7, 'b': [self.num] * 11} class CustomSoftmax(nn.Softmax): def forward(self, *args, **kwargs): return [0.3, 0.3, 0.4] op = DifferentiableMixedRepeat( [TupleModule(i + 1) for i in range(4)], nni.choice('ccc', [1, 2, 4]), CustomSoftmax(), {'ccc': nn.Parameter(torch.randn(3))}, ) op.resample({}) res = op(None) assert len(res) == 3 assert res[0].shape == (2, 3) and res[0][0][0].item() == 2.5 assert res[2]['a'] == 7 assert len(res[2]['b']) == 11 and res[2]['b'][-1] == 2.5 def test_pathsampling_cell(): for cell_cls in [CellSimple, CellDefaultArgs, CellCustomProcessor, CellLooseEnd, CellOpFactory]: model = cell_cls() strategy = RandomOneShot() model = strategy.mutate_model(model) nas_modules = [m for m in model.modules() if isinstance(m, BaseSuperNetModule)] result = {} for module in nas_modules: result.update(module.resample(memo=result)) assert len(result) == model.cell.num_nodes * model.cell.num_ops_per_node * 2 result = {} for module in nas_modules: result.update(module.export(memo=result)) assert len(result) == model.cell.num_nodes * model.cell.num_ops_per_node * 2 if cell_cls in [CellLooseEnd, CellOpFactory]: assert isinstance(model.cell, PathSamplingCell) else: assert not isinstance(model.cell, PathSamplingCell) inputs = { CellSimple: (torch.randn(2, 16), torch.randn(2, 16)), CellDefaultArgs: (torch.randn(2, 16),), CellCustomProcessor: (torch.randn(2, 3), torch.randn(2, 16)), CellLooseEnd: (torch.randn(2, 16), torch.randn(2, 16)), CellOpFactory: (torch.randn(2, 3), torch.randn(2, 16)), }[cell_cls] output = model(*inputs) if cell_cls == CellCustomProcessor: assert isinstance(output, tuple) and len(output) == 2 and \ output[1].shape == torch.Size([2, 16 * model.cell.num_nodes]) else: # no loose-end support for now assert output.shape == torch.Size([2, 16 * model.cell.num_nodes]) def test_differentiable_cell(): for cell_cls in [CellSimple, CellDefaultArgs, CellCustomProcessor, CellLooseEnd, CellOpFactory]: model = cell_cls() strategy = DARTS() model = strategy.mutate_model(model) nas_modules = [m for m in model.modules() if isinstance(m, BaseSuperNetModule)] result = {} for module in nas_modules: result.update(module.export(memo=result)) assert len(result) == model.cell.num_nodes * model.cell.num_ops_per_node * 2 for k, v in result.items(): if 'input' in k: assert isinstance(v, list) and len(v) == 1 result_prob = {} for module in nas_modules: result_prob.update(module.export_probs(memo=result_prob)) ctrl_params = [] for m in nas_modules: ctrl_params += list(m.arch_parameters()) if cell_cls in [CellLooseEnd, CellOpFactory]: assert len(ctrl_params) == model.cell.num_nodes * (model.cell.num_nodes + 3) // 2 assert len(result_prob) == len(ctrl_params) # len(op_names) == 2 for v in result_prob.values(): assert len(v) == 2 assert isinstance(model.cell, DifferentiableMixedCell) else: assert not isinstance(model.cell, DifferentiableMixedCell) inputs = { CellSimple: (torch.randn(2, 16), torch.randn(2, 16)), CellDefaultArgs: (torch.randn(2, 16),), CellCustomProcessor: (torch.randn(2, 3), torch.randn(2, 16)), CellLooseEnd: (torch.randn(2, 16), torch.randn(2, 16)), CellOpFactory: (torch.randn(2, 3), torch.randn(2, 16)), }[cell_cls] output = model(*inputs) if cell_cls == CellCustomProcessor: assert isinstance(output, tuple) and len(output) == 2 and \ output[1].shape == torch.Size([2, 16 * model.cell.num_nodes]) else: # no loose-end support for now assert output.shape == torch.Size([2, 16 * model.cell.num_nodes]) def test_memo_sharing(): class TestModelSpace(ModelSpace): def __init__(self): super().__init__() self.linear1 = Cell( [nn.Linear(16, 16), nn.Linear(16, 16, bias=False)], num_nodes=3, num_ops_per_node=2, num_predecessors=2, merge_op='loose_end', label='cell' ) self.linear2 = Cell( [nn.Linear(16, 16), nn.Linear(16, 16, bias=False)], num_nodes=3, num_ops_per_node=2, num_predecessors=2, merge_op='loose_end', label='cell' ) strategy = DARTS() model = strategy.mutate_model(TestModelSpace()) assert model.linear1._arch_alpha['cell/2_0'] is model.linear2._arch_alpha['cell/2_0'] def test_parameters(): class Model(ModelSpace): def __init__(self): super().__init__() self.op = DifferentiableMixedLayer( { 'a': MutableLinear(2, 3, bias=False), 'b': MutableLinear(2, 3, bias=True) }, nn.Parameter(torch.randn(2)), nn.Softmax(-1), 'abc' ) def forward(self, x): return self.op(x) model = Model() assert len(list(model.parameters())) == 4 assert len(list(model.op.arch_parameters())) == 1 optimizer = torch.optim.SGD(model.parameters(), 0.1) assert len(DartsLightningModule(model).arch_parameters()) == 1 optimizer = DartsLightningModule(model).postprocess_weight_optimizers(optimizer) assert len(optimizer.param_groups[0]['params']) == 3
[ "noreply@github.com" ]
Eurus-Holmes.noreply@github.com
5c914f4e2ba72ae4caca56ff63339c0e19d94c73
4fbc38e98155271715af079619e0bed99c94a4a7
/tasks.py
855b83a923d235c899a83737a23a4e581c99743e
[ "MIT" ]
permissive
alexwall1/souocr
f6c3f04beb1ae74ceb4dd91700168fe227a7e0f2
1be89e0128ee88df70dcb0ee4c1b9875c9c066c5
refs/heads/master
2020-03-21T05:32:54.635280
2018-07-18T05:59:11
2018-07-18T05:59:11
138,165,780
0
0
null
null
null
null
UTF-8
Python
false
false
2,095
py
# coding=utf-8 from db import init_db from processing import preprocess_pdf, match_patter_in_pdf, generate_images_from_pdf, ocr_images, create_xlsx from flask_mail import Message from app import app, mail from celery import Celery def make_celery(app): celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(app) @celery.task(name='tasks.process_file') def process_file(email, file_id): conn, c = init_db() results = c.execute("""SELECT id FROM file WHERE id = ?""", (file_id,)).fetchone() file_id = results[0] pattern = 'Utredningen (föreslår|bedömer)' creator = preprocess_pdf(file_id) app.logger.info('Pre-processing done of file %s.' % file_id) message = Message("Hello", recipients=[email]) if u'Microsoft' in creator: match_patter_in_pdf(file_id, pattern) app.logger.info('Done matching pattern in file %s.' % file_id) generate_images_from_pdf(file_id) app.logger.info('Done generating images from file %s' % file_id) ocr_images(file_id) app.logger.info('Done OCR\'ing images from pdf %s' % file_id) xlsx_path = create_xlsx(file_id) app.logger.info('Created XLSX file %s' % xlsx_path) message.body = u'Please find attached the result XLSX file.' with app.open_resource(xlsx_path) as f: message.attach(xlsx_path.split("/")[-1], 'application/pdf', f.read()) else: message.body = u'Only native PDF files created by Microsoft Word are supported. The uploaded PDF was created ' \ u'by: %s.' % creator mail.send(message) app.logger.info('E-mail sent to %s' % email)
[ "wall.alexander@gmail.com" ]
wall.alexander@gmail.com
e5ad0cf35b8e6f7ada167ad241b0c009ca450d51
65c42b99dc30a14f4e69107ceac469040360262b
/kattis/froggie.py
f71c36be82b0defaf47286168a7b92a28aedc7e5
[]
no_license
jeffriesd/competitive-programming
4bee021ce6c33863160abb75613f92bf3db96d80
4381f49fa96fcc029ed5af417660ffc57366edd5
refs/heads/master
2023-08-11T03:50:35.510865
2021-09-20T00:16:35
2021-09-20T00:16:35
404,136,105
0
0
null
null
null
null
UTF-8
Python
false
false
4,378
py
# problem: https://open.kattis.com/problems/froggie SAFE = 0 CAR = 1 HIT = 2 class Lane(object): def __init__(self, width, offset, interval, speed, direction): self.lane = [0] * width self.width = width self.offset = offset self.interval = interval self.speed = speed self.direction = direction # build initial lane with only CAR and SAFE self.build_lane() def build_lane(self): for i in range(self.width): self.lane[i] = CAR if (i - offset) % interval == 0 else SAFE def update_lane(self): car_steps_left = 0 first_car_index = -1 for i, current in enumerate(self.lane): # if still in the path of a moving car, # mark this cell if car_steps_left > 1: self.lane[i] = HIT elif car_steps_left == 0: # final position of this car self.lane[i] = CAR else: # car has finished its path if current == CAR: # is this the leftmost car? if first_car_index == -1: # calculate leftmost position after this car moves first_car_index = i + self.speed car_steps_left = self.speed # car at current position is moving out of the way self.lane[i] = SAFE else: self.lane[i] = SAFE # current car path is one step closer to completion car_steps_left -= 1 # check for incoming car if first_car_index != -1 and first_car_index >= self.interval: # incoming car will be at self.interval - first_car_index new_leftmost = first_car_index - self.interval for i in range(self.interval - first_car_index): self.lane[i] = HIT self.lane[new_leftmost] = CAR def _squished(self, x_coord): # left to right lanes if self.direction == 1: return self.lane[x_coord] != SAFE # reversed lanes return self.lane[self.width - 1 - x_coord] != SAFE def squished(self, x_coord, time): # print("lane = o=%s, i=%s, s=%s" % (self.offset, self.interval, self.speed)) if self.direction == -1: x_coord = self.width - 1 - x_coord # determine position of cars to froggie's left and right car_position = self.offset + (self.speed * time) # move it by intervals until right of froggie while car_position <= x_coord: car_position += self.interval # now move it back left (may have been way past froggie to begin with) while car_position >= x_coord: car_position -= self.interval left_car = car_position right_car = car_position + self.interval # print("t =", time, ", x =", x_coord, ", lc =", left_car, ", rc =", right_car, end="") # check if left car is in froggie's way if left_car > 0 and left_car < self.width and left_car == x_coord: return True # check if right_car already passed over froggie's coordinate if right_car > 0 and right_car < self.width: r_prev = right_car - self.speed # print(", r_prev =", r_prev) if r_prev > 0 and x_coord > r_prev and x_coord <= right_car: return True else: print("") return False def move_froggie(x, y, move): if move == "U": return (x, y+1) if move == "D": return (x, y-1) if move == "R": return (x+1, y) if move == "L": return (x-1, y) def simulate(grid, start, moves, length): frog_x = start frog_y = -1 t = 0 for step in moves: if frog_y >= length: return "safe" # check if frog was hit if frog_y != -1 and grid[frog_y].squished(frog_x, t): return "squish" # update car positions # for lane in grid: # lane.update_lane() # update frog position frog_x, frog_y = move_froggie(frog_x, frog_y, step) t += 1 # check if froggie escaped top lane return "safe" if frog_y >= length else "squish" if __name__ == '__main__': l, w = map(int, input().split()) grid = [] possible = True for row in range(l): # top lane moves L -> R direction = 1 if row % 2 == 0 else -1 offset, interval, speed = map(int, input().split()) if interval <= speed: possible = False lane = Lane(w, offset, interval, speed, direction) grid.insert(0, lane) frog_start, moves = input().split() frog_start = int(frog_start) if possible: print(simulate(grid, frog_start, moves, l)) else: print("squish")
[ "danjeffries96@github.com" ]
danjeffries96@github.com
1b92f16bfc8e23a009a4585ed7666b003279827e
d597f0ae563840819dc8e91a15af7970cd26bf34
/ch1-straightline/straightline_prog.py
7580d0c1433f1e6677aa0f3ec57124d97d94607c
[]
no_license
mgasner/compilers
d8fdaa07cfddbdfbadfe8416cf277ef131fcae77
7cf2034fb311d6e69051e3a13c30403f3a7af527
refs/heads/master
2016-09-06T04:54:20.448847
2011-09-12T15:39:37
2011-09-12T15:39:37
2,370,178
0
0
null
null
null
null
UTF-8
Python
false
false
439
py
from straightline_ast import * from straightline_interp import * # a := 5 + 3; # b := (print(a, a - 1), 10 * a); # print(b); prog = CompoundStm(AssignStm("a", OpExp(NumExp(5), OpExp.Plus, NumExp(3))), CompoundStm(AssignStm("b", EseqExp(PrintStm(PairExpList(IdExp("a"), LastExpList(OpExp(IdExp("a"), OpExp.Minus, NumExp(1))))), OpExp(NumExp(10), OpExp.Times, IdExp("a")))), PrintStm(LastExpList(IdExp("b"))))) maxargs(prog) interp(prog)
[ "max@naviasystems.com" ]
max@naviasystems.com
e9adaec2a1a45e9847c2b9f5915e8a03220872e7
ace860f60e380d47ad40ad9e21192cb069853bd8
/DjangoWebProject3/app/tests.py
844ba9b1e8a6d95c8211cb12ed29a58726692bfc
[]
no_license
wilsonmwiti/djangoXumpesa
9b28b3063490dd536867e517ee546436cc72b0f5
1e74fb6c7e79504831a1ce8a568375b1ab5d0a56
refs/heads/master
2023-03-15T15:13:46.567278
2020-09-08T11:44:03
2020-09-08T11:44:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
459
py
from django.test import TestCase # Create your tests here. from django.db import models class UserInfo(models.Model): full_name = models.CharField(max_length=120, blank=True, null=True) email = models.EmailField() phone_no = models.CharField(max_length=14) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, default=0) def __str__(self): return self.email
[ "lewicpro@gmail.com" ]
lewicpro@gmail.com
05305e4124e3a937e6a0aa02bb0d251fc129ad9f
510bf23603569b8934ad03b3f94bb3764d40b5ad
/python/tagger.py
e550549a85ea2ed94faaa66d09a0e9e8b8c8ebea
[]
no_license
adambro52/projects
b036cfa7732a2ed90ed8bddfd4b7e19974594be2
2384a0a31a5007bc246afd2fb695b9c54be251b6
refs/heads/master
2020-05-04T11:14:04.123688
2019-05-24T04:06:30
2019-05-24T04:06:30
179,104,037
0
0
null
null
null
null
UTF-8
Python
false
false
3,015
py
import nltk, re from nltk.tag.brill import Template, Pos, Word from nltk.corpus import brown # Training and testing data: data = brown.tagged_sents(categories=['news', 'editorial']) train_data = [] test_data = [] for i, sent in enumerate(data): if i % 10 > 0: train_data.append(sent) else: test_data.append(sent) # Development set (to test taggers before final evaulation on test_data): dev_data = brown.tagged_sents(categories="government") # A useful function: def get_words(tagged_sentence): """Strip the POS tags from a tagged sentence.""" return [word for word, tag in tagged_sentence] # Part 1: Regular expression tagger # These are the patterns from the NLTK text. Add 10 additional patterns to # this list. Keep in mind that the order in which patterns are applied affects # the performance of your tagger. The last pattern is a default rule that # assigns the singular noun tag NN to every token. patterns = [ # conjunction, coordinating (r'\s([Aa]nd?|[Nn]?or|[Bb]ut|&|[Nn]?[Ee]ither|[Yy]et|\'n\'|and/or|[Mm]inus)\s', 'CC'), (r'\s([Dd]ost|[Dd]o)\s', 'DO'), # verb 'to do', uninflected present tense, infinitive or imperative (r'\s([Qq]uite|[Ss]uch|[Rr]ather)\s', 'ABL'), # determiner/pronoun, pre-qualifier (r'\s([Aa]ll|[Hh]alf|[Mm]any|[Nn]ary)\s', 'ABN'), # determiner/pronoun, pre-qualifier (r'\s[Bb]oth\s', 'ABX'), # determiner/pronoun, double conjunction or pre-quantifier (r'\s[Dd]oes\s', 'DOZ'), # verb 'to do', present tense, 3rd person singular (r'\s([Tt]h[e\']|[Aa]n?|[Nn]o|[Ee]ver[y\']|[Yy]e\')\s', 'AT'), # article (r'\s[Bb]e\s', 'BE'), # verb 'to be', infinitive or imperative (r'\s[Ww]ere\s', 'BED'), # verb 'to be', past tense, 2nd person singular or all persons plural (r'\s[Ww]eren\'t\s', 'BED*'), # verb 'to be', past tense, 2nd person singular or all persons plural, negated (r'.*ing$', 'VBG'), # gerunds (r'.*ed$', 'VBD'), # simple past (r'.*es$', 'VBZ'), # 3rd singular present (r'.*ould$', 'MD'), # modals (r'.*\'s$', 'NN$'), # possessive nouns (r'.*s$', 'NNS'), # plural nouns (r'^-?[0-9]+(.[0-9]+)?$', 'CD'), # cardinal numbers (r'.*', 'NN') # nouns (default) ] regexp_tagger = nltk.RegexpTagger(patterns) regexp_tagger.evaluate() ## Part 2: Transformation-based learning and tagging # Define rule templates # templates = [ # Template(Pos([-1])), # previous POS tag # Template(Pos([-1]), Word([0])) # previous POS tag + current word # ] # # # # Train a error-driven, transformation-based tagger # tt = nltk.BrillTaggerTrainer(regexp_tagger, templates, trace=3) # brill_tagger = tt.train(train_data, max_rules=25) ## Part 3: Evalutation ## A unigram baseline tagger: #default_tagger = nltk.DefaultTagger('NN') #unigram_tagger = nltk.UnigramTagger(train_data, backoff=default_tagger)
[ "noreply@github.com" ]
adambro52.noreply@github.com
2a606b13ecc95df1c9b75fb44178d4e46ce24fca
39a1540e602e316d7cbc0d85665490ae44c5f91b
/recommend/recommend.py
4ce7d52d53815ec2c01dc8e68dbbbd2cfc8a151f
[]
no_license
gmg0829/pythonLearninng
d60d2b828021dc3c8cd759b49691d6e1b27af9c5
fa4f98678878bbe3fa1c2d7d688871949194971e
refs/heads/master
2020-03-28T07:28:23.090774
2019-06-27T07:58:43
2019-06-27T07:58:43
147,903,689
0
0
null
null
null
null
UTF-8
Python
false
false
3,786
py
# 构造一份打分数据集,可以去movielens下载真实的数据做实验 users = {"小明": {"中国合伙人": 5.0, "太平轮": 3.0, "荒野猎人": 4.5, "老炮儿": 5.0, "我的少女时代": 3.0, "肖洛特烦恼": 4.5, "火星救援": 5.0}, "小红": {"小时代4": 4.0, "荒野猎人": 3.0, "我的少女时代": 5.0, "肖洛特烦恼": 5.0, "火星救援": 3.0, "后会无期": 3.0}, "小阳": {"小时代4": 2.0, "中国合伙人": 5.0, "我的少女时代": 3.0, "老炮儿": 5.0, "肖洛特烦恼": 4.5, "速度与激情7": 5.0}, "小四": {"小时代4": 5.0, "中国合伙人": 3.0, "我的少女时代": 4.0, "匆匆那年": 4.0, "速度与激情7": 3.5, "火星救援": 3.5, "后会无期": 4.5}, "六爷": {"小时代4": 2.0, "中国合伙人": 4.0, "荒野猎人": 4.5, "老炮儿": 5.0, "我的少女时代": 2.0}, "小李": {"荒野猎人": 5.0, "盗梦空间": 5.0, "我的少女时代": 3.0, "速度与激情7": 5.0, "蚁人": 4.5, "老炮儿": 4.0, "后会无期": 3.5}, "隔壁老王": {"荒野猎人": 5.0, "中国合伙人": 4.0, "我的少女时代": 1.0, "Phoenix": 5.0, "甄嬛传": 4.0, "The Strokes": 5.0}, "邻村小芳": {"小时代4": 4.0, "我的少女时代": 4.5, "匆匆那年": 4.5, "甄嬛传": 2.5, "The Strokes": 3.0} } # 定义几种距离计算函数 # 更高效的方式为把得分向量化之后使用scipy中定义的distance方法 # https://blog.csdn.net/cc_want/article/details/85001762 from math import sqrt def pearson_dis(rating1, rating2): """计算2个打分序列间的pearson距离. 输入的rating1和rating2都是打分dict 格式为{'小时代4': 1.0, '疯狂动物城': 5.0}""" sum_xy = 0 sum_x = 0 sum_y = 0 sum_x2 = 0 sum_y2 = 0 n = 0 for key in rating1: if key in rating2: n += 1 x = rating1[key] y = rating2[key] sum_xy += x * y sum_x += x sum_y += y sum_x2 += pow(x, 2) sum_y2 += pow(y, 2) # now compute denominator denominator = sqrt(sum_x2 - pow(sum_x, 2) / n) * sqrt(sum_y2 - pow(sum_y, 2) / n) if denominator == 0: return 0 else: return (sum_xy - (sum_x * sum_y) / n) / denominator # 查找最近邻 def computeNearestNeighbor(username, users): """在给定username的情况下,计算其他用户和它的距离并排序""" print("查找最近邻") distances = [] for user in users: if user != username: # distance = manhattan_dis(users[user], users[username]) distance = pearson_dis(users[user], users[username]) distances.append((distance, user)) # 根据距离排序,距离越近,排得越靠前 distances.sort() print("distances => ", distances) return distances # 推荐 def recommend(username, users): print("输入=》", username) """对指定的user推荐电影""" # 找到最近邻 nearest = computeNearestNeighbor(username, users)[0][1] recommendations = [] # 找到最近邻看过,但是我们没看过的电影,计算推荐 neighborRatings = users[nearest] print("nearest -> ", nearest) print("neighborRatings -> ", neighborRatings) userRatings = users[username] print("userRatings -> ", userRatings) for artist in neighborRatings: if not artist in userRatings: recommendations.append((artist, neighborRatings[artist])) print("recommendations -> ", recommendations) results = sorted(recommendations, key=lambda artistTuple: artistTuple[1], reverse=True) for result in results: print(result[0], result[1]) if __name__ == "__main__": recommend('小明', users)
[ "minggang0829@gmail.com" ]
minggang0829@gmail.com
efc550766d2f85d636167c06605c01fa750912d7
5c34a86394aa1acc7d3749fdf573864b7f0a0b0e
/Patterns/2_1_Factory.py
3125ad419fec7bb9b92ab1d401287a0b5b579c09
[]
no_license
anuragbisht12/Object-Oriented-Design
0e7bbfec6768274e9a89e97613c386014adace9e
673b14271373b2af50baba44015f62f938b88235
refs/heads/master
2022-11-15T21:14:05.822629
2020-07-10T18:31:01
2020-07-10T18:31:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
609
py
# Advantages loose coupling # debugging modifcation is easier from abc import ABCMeta,abstractmethod class Animal(metaclass=ABCMeta): @abstractmethod def do_say(self): pass class Dog(Animal): def do_say(self): print("Bhow") class Cat(Animal): def do_say(self): print("Meow") # forest factory defined class ForestFactory(object): def make_sound(self,object_type): return eval(object_type)().do_say() # client code if __name__ == "__main__": ff=ForestFactory() animal=input('Which animal should make sound Dog or Cat?') ff.make_sound(animal)
[ "anuragbisht12@gmail.com" ]
anuragbisht12@gmail.com
c66ff98294745a6e4ff0c9969ddbb0a46ddd5b7d
a4c187b20bd8086357272207272cba67f8c94e5b
/Applications/flask_website/main_website.py
ab3cde4157f52999a189fdde49ed56fcd46a0317
[]
no_license
robdale110/PythonCourse
a687216c8e7a1ff01dbd819e5839b5e4df0742d0
df2db16ced3ee4300987d3f62b9f38e771ced788
refs/heads/master
2020-04-15T00:12:47.525889
2017-05-19T12:51:04
2017-05-19T12:51:04
83,202,712
0
0
null
null
null
null
UTF-8
Python
false
false
284
py
""" A Website """ from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return render_template("home.html") @app.route("/about/") def about(): return render_template("about.html") if __name__ == '__main__': app.run(debug=True)
[ "rob@robdale.me.uk" ]
rob@robdale.me.uk
e2919e6bd61973c23957b075902f53293404f478
9c0a2147c5d5438fb851d5db765d658861b2b1a9
/Weather/Weather.py
279ba55fc51a995bb9203f0e8b28f1e49296c6c4
[]
no_license
SviatikKh/Python
280e53af3bca0082a525122919e51d0c430ba34d
e3ce8aae1f7436bf9f5a690c832c50b14a39d247
refs/heads/master
2021-01-01T22:20:34.588843
2020-05-01T19:10:30
2020-05-01T19:10:30
239,367,854
0
0
null
null
null
null
UTF-8
Python
false
false
6,493
py
import os #клас одноразової реєстрації метеорологічних показників class MetHour: #Конструктор класу MetHour def __init__(self): self.temp = 0 #температура повітря self.press = 0 #атмосферний тиск self.humid = 0 #вологість повітря self.precip = 0 #ймовірність опадів self.speed_wind = 0 #швидкість вітру self.direct_wind = ['південний', 'північний', 'східний', 'західний'] #Визначення напряму вітру def Wind(self): s = '' #найменування напряму вітру n = int(input('Напрям вітру (південний (1), північний (2), східний (3), західний (4)): ')) if n == 1 or n == 2 or n == 3 or n == 4: s = self.direct_wind[n - 1] else: print('Напрям вітру не визначено') return s #Формування кортежу даних про метеорологічні прказники def EnterData(self): self.temp = input('Температура повітря (град): ') self.press = input('Атмосферний тиск (мм.рт.ст.): ') self.humid = input('Вологість повітря (%): ') self.precip = input('Ймовірність опадів (%): ') self.speed_wind = input('Швидкість вітру (м/сек): ') #визначення напряму вітру x = '' while x == '': x = self.Wind() #запис даних у кортеж data = [] data.append(self.temp) #(0-Температура повітря (град)) data.append(self.press) #(1-Атмосферний тиск (мм.рт.ст.)) data.append(self.humid) #(2-Вологість повітря (%)) data.append(self.precip) #(3-Ймовірність опадів (%)) data.append(self.speed_wind) #(4-Швидкість вітру (м/сек)) data.append(x) #(5-Напрям вітру) return data #Виведення найменувань метеорологічних показників def ShowHead(self): print('{0:20s}'.format('Температура'), end = '') print('{0:20s}'.format('Атмосферний'), end = '') print('{0:20s}'.format('Вологість'), end = '') print('{0:20s}'.format('Ймовірність'), end = '') print('{0:20s}'.format('Швидкість'), end = '') print('{0:20s}'.format('Напрям'), end = '') print('{0:20s}'.format('повітря (град)'), end = '') print('{0:20s}'.format('тиск (мм.рт.ст.)'), end = '') print('{0:20s}'.format('повітря (%)'), end = '') print('{0:20s}'.format('опадів (%)'), end = '') print('{0:20s}'.format('вітру (м/сек)'), end = '') print('{0:20s}'.format('вітру'), end = '') #Виведення метеорологічних показників def ShowData(self, indicators): for i in range(6): print('{0:20s}'.format(str(indicators[i])), end = '') #print('\n') #Виконання операції реєстрації метеорологічних показників та їх виведення на екран def Execute(self): induc = self.EnterData() if len(induc) > 0: self.ShowHead() self.ShowData(induc) else: print('Помилки у вхідних даних') #клас реєстрації метеорологічних показників за день class MetDay(MetHour): #Конструктор класу MetDay def __init__(self): self.count = 1 #кількість реєстрацій метеорологічних показників за день self.dic = {} #словник метеорологічних показників за день #self.direct_wind = ['південний', 'північний', 'східний', 'західний'] super().__init__() #Формування ключів словника - годин реєстрації метеорологічних показників за день def Hours(self): self.dic = {} #список годин реєстрації метеорологічних показників за день n = int(input('Кількість реєстрацій метеорологічних показників за день (1, 2, 4, 6, 12, 24)')) if n == 1 or n == 2 or n == 4 or n == 6 or n == 12 or n == 24: step = 24 // n x = 0 self.dic[x] = [] for i in range(n - 1): x += step self.dic[x] = [] else: print('Значення невірне') return self.dic #Формування списків метеорологічних показників за день def ListMet(self): m = len(self.Hours()) if m > 0: list_keys = self.dic.keys() for key in list_keys: print(key) self.dic[key] = self.EnterData() return self.dic #Виведення метеорологічних показників за день def ShowDic(self): self.ShowHead() list_keys = self.dic.keys() for key in list_keys: lst = self.dic[key] self.ShowData(lst) #Перевизначений метод #Виконання операції реєстрації метеорологічних показників у визначені години та їх виведення на екран def Execute(self): self.ListMet() print('\n') self.ShowDic() #Перевірка роботи методів класу MetHour #H = MetHour() #H.Execute() #Перевірка роботи методів класу MetDay D = MetDay() D.Execute()
[ "48651894+SviatikKh@users.noreply.github.com" ]
48651894+SviatikKh@users.noreply.github.com
20fd760807bbdf261bf2f9e8a228adfe5f009701
ac55f4bb4beb49f1ae6a1f0741f6b076cf39ea62
/multimedia.py
4e80344312b6920d13bceae8bff261623d4851a3
[]
no_license
ccpabonu/ReproductorMulti
44dd76d9f8b56b474cd6f98d6355c53c867d4f61
badaae8273498f2ebf179ec51afa8246d1664117
refs/heads/main
2023-03-21T04:01:57.124344
2021-03-12T01:40:52
2021-03-12T01:40:52
346,897,621
1
0
null
null
null
null
UTF-8
Python
false
false
27,286
py
import data.main as main #Importa todas las funciones y clases creadas en el archivo main.py import os "--------------------------------------------------------------------------------------------------------------------------------------------------------------------" #Creamos objetos de cada clase que usaremos en la interfaz buscador1 = main.Buscadores() definir1 = main.Definir() archivo1 = main.Archivos() xml1 = main.XML() def mainW (): "pantalla principal del programa" print("----------------------------REPRODUCTOR MULTIMEDIA-----------------------------") print("1. MUSICA") print("2. VIDEOS") print("3. IMAGENES") print("4. AGREGAR CONTENIDO") print("5. SALIR") a=input("Escoja la Opción : \n") if a=="1": os.system("cls") t="MUSICA" multimediaW(t) elif a=="2": os.system('cls') t ="VIDEOS" multimediaW(t) elif a=="3": os.system('cls') t = "IMAGENES" multimediaW(t) elif a=="4": os.system('cls') if not archivo1.listar(): print('No hay posibles archivos para agregar.') else: print("Posibles archivos para agregar:") for i in archivo1.listar(): print(i) arch = str(input('Escoja el archivo: \n')) archivo1.agregar(arch) xml1.actualizar() mainW() elif a=="5": print("BYE") else: os.system('cls') print("Introduzca un valor correcto") mainW() def multimediaW(t): "Funcion multimedia que recibe 't' como parametro para reconocer si es el menu mltimedia de Musica,Videos o Imagenes" print() print("----------------------------"+t+"-----------------------------") print("1. Ver "+t.capitalize()) print("2. Ver Albumes") print("3. Ver Listas de reproducción") print("4. Atras") print() a = input("Escoja una Opción : \n") print() os.system('cls') if a=="1": if t=="MUSICA": pintarNom(definir1.musica()) #Pinta el arreglo devuelto por musica() que son el nombre de todos los archivos musica print() #existentes en multimedia print("1. Detalles o Editar") print("2. Busqueda") print("3. Atras") b = int(input("Escoja un opción : \n")) if b==1: c=input("Escriba el nombre del archivo : \n") n=buscador1.bus_nombre(c) #Busca los detalles del archivo con el nombre del archivo y los pinta pintarDet(n) d=input("¿Desea editar? S / N \n") if d.upper()=="S": eti=str(input("¿Que atributo desea editar?")) txt=str(input("Escriba el cambio ")) xml1.editar(c,eti.lower(),txt.capitalize()) #Llama la funcion editar que recibe 3 parametros, el nombre de archivo, atributo a modificar multimediaW(t) #print("edito") #y el nuevo valor else : multimediaW(t) elif b==2: os.system('cls') pintarBusM(t) else: multimediaW(t) elif t=="VIDEOS": pintarNom(definir1.videos()) print() print("1. Detalles o Editar") print("2. Busqueda") print("3. Atras") b = int(input("Escoja un opción : \n")) if b == 1: c = input("Escriba el nombre del archivo : \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N \n") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif b == 2: os.system('cls') pintarBusV(t) else: multimediaW(t) else : pintarNom(definir1.fotos()) print() print("1. Detalles o Editar") print("2. Busqueda") print("3. Atras") b = int(input("Escoja un opción : \n")) if b == 1: c = input("Escriba el nombre del archivo : \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N \n") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif b == 2: os.system('cls') pintarBusI(t) else: multimediaW(t) elif a=="2": os.system('cls') if t=="MUSICA": print("-------------ALBUMES------------") pintarAlbM(t) elif t=="VIDEOS": print("-------------ALBUMES------------") pintarAlbV(t) else: print("-------------ALBUMES------------") pintarAlbI(t) elif a=="3": if t=="MUSICA": pintarListM(t) elif t=="VIDEOS": pintarListV(t) elif t=="IMAGENES": pintarListI(t) else: multimediaW(t) elif a=="4": mainW() else: print("Introduzca un valor correcto") multimediaW(t) def pintarNom(l): "funcion que pinta un arreglo " for i in range(len(l)): print(l[i]) def pintarDet(n): "funcion que recibe un arreglo con la info del archivo y pinta de una mejor manera " print("Nombre Archivo : " + n[0] + " Nombre : " + n[1] + " Interpetre : " + n[2]) print("Album : " + n[3] + " Fecha : " + n[4] + " Genero: " + n[5]) def pintarBusM(t): "funcion que crea y pinta el menu de busqueda para la musica" print("Buscar por : ") print("1. Nombre") print("2. Autor") print("3. Fecha") print("4. Genero") bb = int(input("Escoja un opción : \n")) if bb==1: c = input("Escriba el nombre: \n") print("Cancion con este nombre :") pintarNom(buscador1.bus_tag_mus('nombre',c) ) c = input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==2: c = input("Escriba el autor: \n") print("Canciones con ese interpetre :") pintarNom(buscador1.bus_tag_mus('interpetre', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==3: c = input("Escriba el Fecha: \n") print("Canciones de ese Fecha :") pintarNom(buscador1.bus_tag_mus('fecha', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==4: c = input("Escriba el Genero \n") print("Canciones de ese genero :") pintarNom(buscador1.bus_tag_mus('genero', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) def pintarBusV(t): "funcion que crea y pinta el menu de busqueda para los videos" print("Buscar por : ") print("1. Nombre") print("2. Interpetre") print("3. Fecha") print("4. Genero") bb = int(input("Escoja un opción : \n")) if bb==1: c = input("Escriba el nombre: \n") print("Video con este nombre :") pintarNom(buscador1.bus_tag_vid('nombre',c) ) c = input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==2: c = input("Escriba el interprete: \n") print("Videos de ese interprete :") pintarNom(buscador1.bus_tag_vid('interprete', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==3: c = input("Escriba el Fecha: \n") print("Videos de ese Fecha :") pintarNom(buscador1.bus_tag_vid('fecha', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==4: c = input("Escriba el Genero \n") print("Videos de ese genero :") pintarNom(buscador1.bus_tag_vid('genero', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) def pintarBusI(t): os.system('cls') "funcion que crea y pinta el menu de busqueda para las imagenes" print("Buscar por : ") print("1. Nombre") print("2. Autor") print("3. Fecha") print("4. Genero") bb = int(input("Escoja un opción : \n")) os.system('cls') if bb==1: c = input("Escriba el nombre: \n") print("Imagen con este nombre :") pintarNom(buscador1.bus_tag_fot('nombre',c) ) c = input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==2: c = input("Escriba el autor: \n") print("Imagenes de ese autor :") pintarNom(buscador1.bus_tag_fot('autor', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==3: c = input("Escriba el Fecha: \n") print("Imagenes de ese Fecha :") pintarNom(buscador1.bus_tag_fot('fecha', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) elif bb==4: c = input("Escriba el Genero \n") print("Imagenes de ese genero :") pintarNom(buscador1.bus_tag_fot('genero', c)) c= input("Escriba el nombre del archivo para ver detalles: \n") n = buscador1.bus_nombre(c) pintarDet(n) d = input("¿Desea editar? S / N ") if d.upper() == "S": eti = str(input("¿Que atributo desea editar?")) txt = str(input("Escriba el cambio ")) xml1.editar(c, eti.lower(), txt.capitalize()) multimediaW(t) # print("edito") else: multimediaW(t) def pintarAlbM(t): os.system('cls') "funcion que crea y pinta el menu de albumes para la musica" print("1. Ver Albumes") print("2. Crear Albumes") print("3. Atras") b = int(input("Escoja un opción : \n")) os.system('cls') if b==1: print("-------------ALBUMES DE MUSICA-----------") pintarNom(buscador1.tag_mus('album')) bb=input("Ingrese el album que desea ver : \n") print ("-------------"+bb+"-------------") pintarNom(buscador1.bus_tag_mus('album',bb)) c=str(input("¿Quiere modificar el album? S / N \n")) if c.upper()=="S": print("1. Agregar musica") print("2. Eliminar musica") bt = int(input("Escoja un opción : \n")) if bt==1: pintarNom(definir1.musica()) name=input("Nombre del archivo que desea agregar al album : \n") xml1.editar(name,'album',bb) pintarAlbM(t) else: name=input("Nombre del archivo que desea eliminar del album : \n") xml1.editar(name,'album','desconocido') pintarAlbM(t) else: multimediaW(t) elif b == 2: albumn = str(input("Nombre del album a crear : \n")) # crear album print("Imagenes que puede agregar") pintarNom(definir1.musica()) bc = " " bc = input("Escriba nombre del archivo que va agregar : \n") while bc != "": xml1.editar(bc, 'album', albumn) print("Cerrar Bucle oprima enter") bc = input("Escriba nombre del archivo que va agregar : \n") pintarAlbM(t) else: multimediaW(t) def pintarAlbV(t): os.system('cls') "funcion que crea y pinta el menu de albumes para los videos" print("1. Ver Albumes") print("2. Crear Albumes") print("3. Atras") b = int(input("Escoja un opción : \n")) os.system('cls') if b==1: print("-------------ALBUMES DE VIDEOS-----------") pintarNom(buscador1.tag_vid('album')) bb=input("Ingrese el album que desea ver : \n") print ("-------------"+bb+"-------------") pintarNom(buscador1.bus_tag_vid('album',bb)) c=str(input("¿Quiere modificar el album? S / N \n")) if c.upper()=="S": print("1. Agregar video") print("2. Eliminar video") bt = int(input("Escoja un opción : \n")) if bt==1: pintarNom(definir1.videos()) name=input("Nombre del archivo que desea agregar al album : \n") xml1.editar(name,'album',bb) pintarAlbV(t) else: name=input("Nombre del archivo que desea eliminar del album : \n") xml1.editar(name,'album','desconocido') pintarAlbV(t) else: multimediaW(t) elif b == 2: albumn = str(input("Nombre del album a crear : \n")) # crear album print("Imagenes que puede agregar") pintarNom(definir1.videos()) bc = " " bc = input("Escriba nombre del archivo que va agregar : \n") while bc != "": xml1.editar(bc, 'album', albumn) print("Cerrar Bucle oprima enter") bc = input("Escriba nombre del archivo que va agregar : \n") pintarAlbV(t) else: multimediaW(t) def pintarAlbI(t): os.system('cls') "funcion que crea y pinta el menu de albumes para las imagenes" print("1. Ver Albumes") print("2. Crear Albumes") print("3. Atras") b = int(input("Escoja un opción : \n")) os.system('cls') if b==1: print("-------------ALBUMES DE IMAGENES-----------") pintarNom(buscador1.tag_fot('album')) bb=input("Ingrese el album que desea ver : \n") print ("-------------"+bb+"-------------") pintarNom(buscador1.bus_tag_fot('album',bb)) c=str(input("¿Quiere modificar el album? S / N \n")) if c.upper()=="S": print("1. Agregar imagen") print("2. Eliminar imagen") bt = int(input("Escoja un opción : \n")) if bt==1: pintarNom(definir1.fotos()) name=input("Nombre del archivo que desea agregar al album : \n") xml1.editar(name,'album',bb) pintarAlbI(t) else: name=input("Nombre del archivo que desea eliminar del album : \n") xml1.editar(name,'album','desconocido') pintarAlbI(t) else: multimediaW(t) elif b==2: albumn=str(input("Nombre del album a crear : \n")) #crear album print("Imagenes que puede agregar") pintarNom(definir1.fotos()) bc=" " bc = input("Escriba nombre del archivo que va agregar : \n") while bc!="": xml1.editar(bc,'album',albumn) print("Cerrar Bucle oprima enter") bc = input("Escriba nombre del archivo que va agregar : \n") pintarAlbI(t) else: multimediaW(t) def pintarListM(t): os.system('cls') "funcion que crea y pinta el menu de listas para la musica" print("-----------------LISTAS MUSICA----------------------") print("1. Crear Listas") print("2. Ver Listas") print("3. Atras") b = int(input("Escoja un opción : \n")) os.system('cls') if b==1: nom=input("Ingrese al nombre de la lista nueva: \n") xml1.cre_list(1,nom) print("Se ha creado la lista "+nom) bg=input("¿Desea agregar musica a la lista? S / N ") if bg.upper()=='S': pintarNom(definir1.musica()) bgg=input("Ingrese el nombre del archivo a agregar :") while bgg!="": xml1.cre_cancion(1,nom,bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a agregar :") pintarListM(t) else: pintarListM(t) elif b==2: print("------ -----LISTAS DE MUSICA-----------") pintarNom(xml1.listas(1)) nom=input("Ingrese el nombre de la lista que desea ver : \n") print("------------"+nom+"-------------") pintarNom(xml1.lis_list(1,nom)) bg = input("¿Desea editar esta lista? S / N ") if bg.upper()=='S': print("1. Agregar Cancion") print("2. Eliminar Cancion") print("3. Eliminar lista") bk = int(input("Escoja un opción : \n")) if bk==1: pintarNom(definir1.musica()) bgg = input("Ingrese el nombre del archivo a agregar :") while bgg != "": xml1.cre_cancion(1, nom, bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a agregar :") pintarListM(t) elif bk==2: pintarNom(xml1.lis_list(1,nom)) bgg = input("Ingrese el nombre del archivo a eliminar :") while bgg != "": xml1.eli_cancion(1, nom, bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a eliminar :") pintarListM(t) elif bk==3: xml1.eli_list(1,nom) print("Se ha eliminado la lista "+nom) pintarListM(t) else: pintarListM(t) else: multimediaW(t) def pintarListV(t): os.system('cls') "funcion que crea y pinta el menu de listas para los videos" print("-----------------LISTAS VIDEOS----------------------") print("1. Crear Listas") print("2. Ver Listas") print("3. Atras") b = int(input("Escoja un opción : \n")) os.system('cls') if b==1: nom=input("Ingrese al nombre de la lista nueva: \n") xml1.cre_list(0,nom) print("Se ha creado la lista "+nom) bg=input("¿Desea agregar videos a la lista? S / N ") if bg.upper()=='S': pintarNom(definir1.videos()) bgg=input("Ingrese el nombre del archivo a agregar :") while bgg!="": xml1.cre_cancion(0,nom,bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a agregar :") pintarListV(t) else: pintarListV(t) elif b==2: print("------ -----LISTAS DE VIDEOS-----------") pintarNom(xml1.listas(0)) nom=input("Ingrese el nombre de la lista que desea ver : \n") print("------------"+nom+"-------------") pintarNom(xml1.lis_list(0,nom)) bg = input("¿Desea editar esta lista? S / N ") if bg.upper()=='S': print("1. Agregar Video") print("2. Eliminar Video") print("3. Eliminar lista") bk = int(input("Escoja un opción : \n")) if bk==1: pintarNom(definir1.videos()) bgg = input("Ingrese el nombre del archivo a agregar :") while bgg != "": xml1.cre_cancion(0, nom, bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a agregar :") pintarListV(t) elif bk==2: pintarNom(xml1.lis_list(0,nom)) bgg = input("Ingrese el nombre del archivo a eliminar :") while bgg != "": xml1.eli_cancion(0, nom, bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a eliminar :") pintarListV(t) elif bk==3: xml1.eli_list(0,nom) print("Se ha eliminado la lista "+nom) pintarListV(t) else: pintarListV(t) else: multimediaW(t) def pintarListI(t): os.system('cls') "funcion que crea y pinta el menu de listas para las imagenes" print("-----------------LISTAS IMAGENES----------------------") print("1. Crear Listas") print("2. Ver Listas") print("3. Atras") b = int(input("Escoja un opción : \n")) os.system('cls') if b==1: nom=input("Ingrese al nombre de la lista nueva: \n") xml1.cre_list(2,nom) print("Se ha creado la lista "+nom) bg=input("¿Desea agregar imagenes a la lista? S / N ") if bg.upper()=='S': pintarNom(definir1.fotos()) bgg=input("Ingrese el nombre del archivo a agregar :") while bgg!="": xml1.cre_cancion(2,nom,bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a agregar :") pintarListI(t) else: pintarListI(t) elif b==2: print("------ -----LISTAS DE IMAGENES-----------") pintarNom(xml1.listas(2)) nom=input("Ingrese el nombre de la lista que desea ver : \n") print("------------"+nom+"-------------") pintarNom(xml1.lis_list(2,nom)) bg = input("¿Desea editar esta lista? S / N ") if bg.upper()=='S': print("1. Agregar Imagen") print("2. Eliminar Imagen") print("3. Eliminar lista") bk = int(input("Escoja un opción : \n")) if bk==1: pintarNom(definir1.fotos()) bgg = input("Ingrese el nombre del archivo a agregar :") while bgg != "": xml1.cre_cancion(2, nom, bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a agregar :") pintarListI(t) elif bk==2: pintarNom(xml1.lis_list(2,nom)) bgg = input("Ingrese el nombre del archivo a eliminar :") while bgg != "": xml1.eli_cancion(2, nom, bgg) print("Cerrar Bucle oprima enter") bgg = input("Ingrese el nombre del archivo a eliminar :") pintarListI(t) elif bk==3: xml1.eli_list(2,nom) print("Se ha eliminado la lista "+nom) pintarListI(t) else: pintarListI(t) else: multimediaW(t) if __name__ == '__main__': mainW()
[ "ccpabonu@unal.edu.co" ]
ccpabonu@unal.edu.co
8bb7883c390b5da7949d4597cd2a21c3eaba4a97
566f939e79ad4b55f6af2d216a4e7456cb427bca
/src/auto_register.py
c764bf34a7f000e143579ee63a86b26f818c97ff
[]
no_license
kenkioko/UDA_REGISTRY
d55bba46ba05846f9d653ab15dfca5d556a13130
45430bdebf4b239220dfc79de816c10d54143561
refs/heads/main
2023-04-30T08:59:00.886545
2021-05-16T20:38:06
2021-05-16T20:38:06
366,666,874
0
0
null
null
null
null
UTF-8
Python
false
false
2,498
py
import sys, time from src.csv_std.read import ReadCSV from src.csv_std.write import WriteCSV from src.request.register import Register from src.random.random_details import RandomMembers class AutoRegister: random_values = None skip = False input_file = None output_file = 'output_files/South C Members ' + str(time.time_ns()) + '.csv' def __init__(self, **kwargs): # set input file if kwargs['input_file']: self.input_file = 'input_files/' + kwargs['input_file'] # set output file if kwargs['output_file']: self.output_file = 'output_files/' + kwargs['output_file'] # set skip set member no if kwargs['skip']: self.skip = kwargs['skip'] # set random values if kwargs['random_values']: self.random_values = kwargs['random_values'] def register_members(self, members, wait = 0): registered_members = [] # send register url register = Register() for detail in members: response = register.post(detail, self.skip) # add member's detail registered_members.append(response['details']) # pause for seconds if wait > 0: time.sleep(wait) # return members return registered_members def run(self): # read csv file read = ReadCSV(self.input_file) members = read.read_file() # run random if self.random_values: self.run_random(members) # run default with input files elif self.input_file: self.run_default(members) # run default with input files else: raise Exception("No input file or random value parsed") def run_default(self, members): # register members registered_members = self.register_members(members) # write output file write = WriteCSV(self.output_file) write.write_file(registered_members) def run_random(self, members): # generate random members rmembers = RandomMembers(members) random_members = rmembers.random(self.random_values) # register members registered_members = self.register_members(random_members, 2) # write output file write = WriteCSV(self.output_file) write.write_file(registered_members)
[ "kmkioko@gmail.com" ]
kmkioko@gmail.com
46bcaa0577681801f0e6d6c7405d4a6153fcd0f6
fdfb52b582d6d18963790a3e7bba0addecdee1cf
/snakegame.py
561b93390e27faa3f81fd7e42f36cc6161ff869d
[]
no_license
animeshsrivastava24/PythonScriptsForBeginners
bdf75fd871e282d973e3762abb7fb71d7a0b0170
19ad16b357403840ee7de0fab74a6039754bd149
refs/heads/master
2023-01-30T08:07:09.680960
2020-10-23T01:08:44
2020-10-23T01:08:44
300,156,826
14
23
null
2020-12-09T18:00:14
2020-10-01T05:30:37
Jupyter Notebook
UTF-8
Python
false
false
3,469
py
import pygame import time import random pygame.init() white = (255, 255, 255) yellow = (255, 255, 102) black = (0, 0, 0) red = (213, 50, 80) green = (0, 255, 0) blue = (50, 153, 213) dis_width = 600 dis_height = 400 dis = pygame.display.set_mode((dis_width, dis_height)) pygame.display.set_caption('Snake Game') clock = pygame.time.Clock() snake_block = 10 snake_speed = 15 font_style = pygame.font.SysFont("bahnschrift", 25) score_font = pygame.font.SysFont("comicsansms", 35) def Your_score(score): value = score_font.render("Your Score: " + str(score), True, yellow) dis.blit(value, [0, 0]) def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block]) def message(msg, color): mesg = font_style.render(msg, True, color) dis.blit(mesg, [dis_width / 6, dis_height / 3]) def gameLoop(): game_over = False game_close = False x1 = dis_width / 2 y1 = dis_height / 2 x1_change = 0 y1_change = 0 snake_List = [] Length_of_snake = 1 foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 while not game_over: while game_close == True: dis.fill(blue) message("You Lost! Press C-Play Again or Q-Quit", red) Your_score(Length_of_snake - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_UP: y1_change = -snake_block x1_change = 0 elif event.key == pygame.K_DOWN: y1_change = snake_block x1_change = 0 if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change dis.fill(blue) pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block]) snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] for x in snake_List[:-1]: if x == snake_Head: game_close = True our_snake(snake_block, snake_List) Your_score(Length_of_snake - 1) pygame.display.update() if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 Length_of_snake += 1 clock.tick(snake_speed) pygame.quit() quit() gameLoop()
[ "zaireneann740@gmail.com" ]
zaireneann740@gmail.com
68f641c2cfef118e547fa4cd9a42dec6d4ca387a
ec1f0946f00840ca0bc8e708e94e730a1af5ffc5
/econ_indicator/models.py
778aa5c27e2296e694913cf726bb17737e46aef5
[]
no_license
jineshpaloor/Economic-Indicator
7a27c26b83018d49c4d2e774d66d0f1f35502c4d
fd05ea0eb44b11558c257d83f288c501d8ad65af
refs/heads/master
2020-04-06T04:00:34.581537
2012-11-08T20:43:41
2012-11-08T20:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,047
py
from django.db import models class EconomicIndicator(models.Model): Periods = ( ('yearly', 'Yearly'), ('quarterly', 'Quarterly'), ('monthly', 'Monthly'), ('weekly', 'Weekly'), ('biweekly', 'BiWeekly'), ('daily', 'Daily'), ) short_name = models.CharField(max_length=20) long_name = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True) publish_period = models.CharField(max_length=30, choices=Periods) parent_id = models.IntegerField(default=0) class History(models.Model): country = models.CharField(max_length=100) state = models.CharField(max_length=100) year = models.CharField(max_length=10,choices=[(str(year),str(year)) for year in range(2000,2013)]) month = models.CharField(max_length=10,choices=[(str(month),str(month)) for month in range(1,13)]) nominal = models.CharField(max_length=100) indicator = models.ForeignKey(EconomicIndicator)
[ "jineshpaloor@gmail.com" ]
jineshpaloor@gmail.com
873c11839f67f65389a683fca96939f3635e339e
0874abd0a592c952a7aad6f4642776168312aee6
/08-字典/04-改.py
50b13bfa6bbb04ef269cf75172a9449fe5d70b62
[]
no_license
EndIFbiu/python-study
075742d3923adad8061b5f720cabd4a33d3eb0a2
62a64a587077ef5f2dcd8a119ba56d3709073bf6
refs/heads/master
2023-02-10T08:14:08.144442
2020-12-27T12:23:14
2020-12-27T12:23:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
dict1 = {'name': 'tom', 'age': 20, 'gender': '男'} dict1['name'] = 'lily' print(dict1) # {'name': 'lily', 'age': 20, 'gender': '男'}
[ "270017772@qq.com" ]
270017772@qq.com
0ebbb1881fcb3109da74ad01e14f1f874de28ac0
c589d79394d3c010a3bf58eefb89e05b2dff3809
/scripts/stitch_ilastik_output.py
131e297d71fd8a10594167c231f1e6ade34e822f
[]
no_license
awedwards/bidc
94514f72b0f784fecf0f42d1f98102ce399d4fa3
fb3f16c3f82ad59eaf651b1af5919bf42683eb2e
refs/heads/master
2021-10-07T22:53:08.386219
2021-09-30T23:09:51
2021-09-30T23:09:51
172,561,313
0
0
null
null
null
null
UTF-8
Python
false
false
6,876
py
import os, sys import h5py import numpy as np import pandas as pd def stitch(dir_, filename='', output_file_base=""): files = os.listdir(dir_) pixel_map_files = [x for x in files if ("pixel" in x)] object_map_files = [x for x in files if ("Object" in x)] if len(pixel_map_files) > 0: do_pixel = True else: do_pixel = False print(object_map_files) if len(object_map_files) > 0: do_object = True else: do_object = False print(do_pixel) xstart = [] xend = [] ystart = [] yend = [] if do_pixel: interval_file_list = pixel_map_files else: interval_file_list = object_map_files for f in interval_file_list: _, xs, xe, ys, ye, *_ = f[:-3].split("_") xstart.append(int(xs)) xend.append(int(xe)) ystart.append(int(ys)) yend.append(int(ye)) xstart = np.array(sorted(list(set(xstart)))) xend = np.array(sorted(list(set(xend)))) ystart = np.array(sorted(list(set(ystart)))) yend = np.array(sorted(list(set(yend)))) # load in first file to get number of channels if not do_pixel: first_file = h5py.File(os.path.join(dir_, object_map_files[0]),'r') data = first_file['exported_data'] else: first_file = h5py.File(os.path.join(dir_, pixel_map_files[0]),'r') data = first_file['exported_data'] if len(data.shape) == 3: x,y,c=data.shape offset = 0 elif len(data.shape) == 5: _,_,x,y,c = data.shape offset = 2 big_pixel_file = np.zeros((int(np.max(xend)), int(np.max(yend)), c), dtype=np.uint8) big_object_file = big_pixel_file[:,:,0].copy() xt = (xend[0]-xstart[1])/2 yt = (yend[0]-ystart[1])/2 xdiv = np.hstack(([0], xend-xt)) xdiv[-1] = max(xend) ydiv = np.hstack(([0], yend-yt)) ydiv[-1] = max(yend) xbound=[0,0] ybound=[0,0] last_object_id = 0 print("Stitching...") for i in np.arange(len(xstart)): for j in np.arange(len(ystart)): rs = int(xstart[i]) re = int(xend[i]) cs = int(ystart[j]) ce = int(yend[j]) pixelpath = os.path.join(dir_, "_".join(["tmp", str(rs), str(re), str(cs), str(ce), "pixel_probabilities"]) + ".h5") objectpath = os.path.join(dir_, "_".join(["tmp", str(rs), str(re), str(cs), str(ce), "Object_Prediction"]) + ".h5") if do_pixel: pixel_file = h5py.File(pixelpath, 'r') pixel_data = pixel_file['exported_data'] xe = pixel_data.shape[0+offset] ye = pixel_data.shape[1+offset] if do_object: object_file = h5py.File(objectpath,'r') object_data = object_file['exported_data'] xe = object_data.shape[0+offset] ye = object_data.shape[1+offset] if i == 0: xs = 0 xbound[0]=-1 else: xs = int(xt) xbound[0] = xs if i == len(xstart)-1: xe = int(xe) xbound[1] = xe else: xe = int(xe - xt) xbound[1] = xe if j == 0: ys = 0 ybound[0]=-1 else: ys = int(yt) ybound[0] = ys if j == len(ystart)-1: ye = int(ye) ybound[1] = ye else: ye = int(ye - yt) ybound[1] = ye if do_pixel: if len(pixel_data.shape) == 3: big_pixel_file[int(xdiv[i]):int(xdiv[i+1]), int(ydiv[j]):int(ydiv[j+1]), :] = pixel_data[xs:xe, ys:ye, :] if len(pixel_data.shape) == 5: big_pixel_file[int(xdiv[i]):int(xdiv[i+1]), int(ydiv[j]):int(ydiv[j+1]), :] = pixel_data[0,0,xs:xe, ys:ye, :] if do_object: if len(object_data.shape) == 3: big_object_file[int(xdiv[i]):int(xdiv[i+1]), int(ydiv[j]):int(ydiv[j+1])] = object_data[xs:xe, ys:ye, 0] if len(object_data.shape) == 5: big_object_file[int(xdiv[i]):int(xdiv[i+1]), int(ydiv[j]):int(ydiv[j+1])] = object_data[0,0,xs:xe, ys:ye, 0] df = pd.read_csv(os.path.join(dir_, "_".join(["object_feature_output-tmp",str(rs),str(re),str(cs),str(ce),"table.csv"]))) filtered = df[( df['Center of the object_1'] > xbound[0] ) & ( df['Center of the object_1'] <= xbound[1] ) & ( df['Center of the object_0'] > ybound[0] ) & ( df['Center of the object_0'] <= ybound[1] )] if i == 0: filtered['Center of the object_1'] += xdiv[i] filtered['Bounding Box Minimum_1'] += xdiv[i] filtered['Bounding Box Maximum_1'] += xdiv[i] else: filtered['Center of the object_1'] += xdiv[i]-xt filtered['Bounding Box Minimum_1'] += xdiv[i]-xt filtered['Bounding Box Maximum_1'] += xdiv[i]-xt if j == 0: filtered['Center of the object_0'] += ydiv[j] filtered['Bounding Box Minimum_0'] += ydiv[j] filtered['Bounding Box Maximum_0'] += ydiv[j] else: filtered['Center of the object_0'] += ydiv[j]-yt filtered['Bounding Box Minimum_0'] += ydiv[j]-yt filtered['Bounding Box Maximum_0'] += ydiv[j]-yt if (i == 0) and (j == 0): big_data_frame = filtered else: try: filtered['object_id'] += last_object_id big_data_frame = big_data_frame.append(filtered, ignore_index=True) except KeyError: pass try: object_id_list = filtered['object_id'] if len(object_id_list) > 0: last_object_id = max(filtered['object_id']) except KeyError: pass if do_pixel: with h5py.File(os.path.join(dir_, "_".join(["full",filename,output_file_base,"pixel_probabilities.h5"])), "w") as out: dset = out.create_dataset("data", data=big_pixel_file) if do_object: with h5py.File(os.path.join(dir_, "_".join(["full",filename,output_file_base,"object_predictions.h5"])), "w") as out: dset = out.create_dataset("data", data=big_object_file) big_data_frame.to_csv(os.path.join(dir_, "_".join(["full",filename,output_file_base,"object_feature_output.csv"])))
[ "edwardsa@janelia.hhmi.org" ]
edwardsa@janelia.hhmi.org
f9c366cb6661374e0faacd2a30747609a9745b24
bb10214f18c3d8bfa5a5b38dfa010e565d248fbe
/impares.py
e5ebe79b57ca1356a7a034f366eead5933032c1e
[]
no_license
samanta-antonio/python_basics
5651e4b076aabee01ed0d2ecd12411f4d6906e40
d139a19a1febf00d8450193ad0d4c6fba2f09572
refs/heads/master
2023-04-20T06:19:50.981350
2021-05-04T23:31:16
2021-05-04T23:31:16
364,412,485
1
0
null
null
null
null
UTF-8
Python
false
false
291
py
#Receba um número inteiro positivo na entrada e imprima os n n primeiros números ímpares naturais. n = int(input("Digite o valor de n: ")) i = 1 contador = 1 if n == 0: print(i) else: while contador <= n: print(i) i = i+2 contador = contador + 1
[ "samantantonio@outlook.com" ]
samantantonio@outlook.com
7470c799cd2717e35010688327af5806f5713a5c
fed837fd141882bef3e7597a2ec92102e0a5adfc
/tests/tests_payment.py
7587e095028e7c037414676a4b1de13b81fd2b78
[]
no_license
junyuanxue/till_tech_test_python
55a0692cceaaae9bf3f73ee10fe1f7219c6e632c
99ac90cadb7226e499320191f7bdbe3e3eb74662
refs/heads/master
2021-01-12T19:24:28.588086
2016-05-23T19:57:38
2016-05-23T19:57:38
59,299,361
1
0
null
null
null
null
UTF-8
Python
false
false
510
py
import unittest from unittest.mock import MagicMock from app.payment import Payment class PaymentTestCase(unittest.TestCase): def setUp(self): self.order = MagicMock() self.payment = Payment(self.order) self.payment.pay(15) def test_pay_and_show_paid_amount(self): self.assertEqual(self.payment.show_paid_amount(), 15) def test_calculate_change(self): self.order.total.return_value = 12.45 self.assertEqual(self.payment.calculate_change(), 2.55)
[ "junyuanxue.is@gmail.com" ]
junyuanxue.is@gmail.com
c2e1b815accd196ae0e558abdb02f1f8af0d0ce5
2dd894afaecfe61feab44b139a040d3535357443
/lab3_sorting_analysis/lab3.py
e3c3bf015b623f03d8056525ef0c5e9e46b15290
[]
no_license
drakesong/algorithm_analysis
0c4675bb901da6894874df6c21fb155da179ac52
6e648830d93a599cd9f008bb9b5424bfe975c282
refs/heads/master
2021-04-03T09:27:11.702210
2018-03-12T05:55:51
2018-03-12T05:55:51
124,837,380
1
0
null
null
null
null
UTF-8
Python
false
false
4,529
py
# CS 317 Algorithm Anaylsis Lab 3 # Drake Song # Python 3.6 # All of the following sorting algorithms have been copied from CodeCodex with # some adjustments to make sure the program runs smoothly as a whole. import numpy as np import timeit import csv def bubblesort(input_list): lst = input_list[:] swapped = True while swapped: swapped = False for i in range(len(lst)-1): if lst[i] < lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i] swapped = True return lst def insertsort(input_list): lst = input_list[:] for removed_index in range(1, len(lst)): removed_value = lst[removed_index] insert_index = removed_index while insert_index > 0 and lst[insert_index - 1] > removed_value: lst[insert_index] = lst[insert_index - 1] insert_index -= 1 lst[insert_index] = removed_value return lst def selectionsort(input_list): lst = input_list[:] l=lst[:] srt_lst=[] while len(l): lowest=l[0] for x in l: if x<lowest: lowest=x srt_lst.append(lowest) l.remove(lowest) return srt_lst def mergesort(input_list): lst = input_list[:] if len(lst) == 1: return lst m = round(len(lst) / 2) l = mergesort(lst[:m]) r = mergesort(lst[m:]) if not len(l) or not len(r): return l or r result = [] i = j = 0 while (len(result) < len(r)+len(l)): if l[i] < r[j]: result.append(l[i]) i += 1 else: result.append(r[j]) j += 1 if i == len(l) or j == len(r): result.extend(l[i:] or r[j:]) break return result def quicksort(input_list): lst = input_list[:] if len(lst)<=1: return lst pivot=lst[0] less= [x for x in lst if x<pivot] equal= [x for x in lst if x==pivot] greater= [x for x in lst if x>pivot] lst = quicksort(less)+equal+quicksort(greater) return lst def shellsort(input_list): lst = input_list[:] inc = int(round(len(lst) / 2)) while inc: for i in range(len(lst)): j = i temp = lst[i] while j >= inc and lst[j-inc] > temp: lst[j] = lst[j-inc] j -= inc lst[j] = temp inc = int(inc/2) if inc/2 else (0 if inc==1 else 1) return lst time_bub = [] time_ins = [] time_sel = [] time_mer = [] time_she = [] time_qui = [] time_sor = [] n = [1, 5, 10, 50, 100, 500, 1000, 2500, 5000, 10000] with open('data.csv', 'w', newline='') as f: writer = csv.writer(f) for j in n: print("starting n = {}".format(j)) for i in range(25): x = np.random.randint(-1000000, 1000000, size=(j*10)).tolist() tic = timeit.default_timer() bubblesort(x) toc = timeit.default_timer() time_bub.append((toc-tic)*1000000) print("bubblesort is done") tic = timeit.default_timer() insertsort(x) toc = timeit.default_timer() time_ins.append((toc-tic)*1000000) print("insertsort is done") tic = timeit.default_timer() selectionsort(x) toc = timeit.default_timer() time_sel.append((toc-tic)*1000000) print("selectionsort is done") tic = timeit.default_timer() mergesort(x) toc = timeit.default_timer() time_mer.append((toc-tic)*1000000) print("mergesort is done") tic = timeit.default_timer() shellsort(x) toc = timeit.default_timer() time_she.append((toc-tic)*1000000) print("shellsort is done") tic = timeit.default_timer() quicksort(x) toc = timeit.default_timer() time_qui.append((toc-tic)*1000000) print("quicksort is done") tic = timeit.default_timer() sorted(x) toc = timeit.default_timer() time_sor.append((toc-tic)*1000000) print("sorted is done") bub = sum(time_bub)/25 ins = sum(time_ins)/25 sel = sum(time_sel)/25 mer = sum(time_mer)/25 she = sum(time_she)/25 qui = sum(time_qui)/25 sor = sum(time_sor)/25 writer.writerow((j, bub, ins, sel, mer, she, qui, sor)) print("{} is done\n".format(j))
[ "drakesong216@gmail.com" ]
drakesong216@gmail.com
eb853cf090f273cd03482c3f9b264451ad4cd807
21696d3fdf99945efddfb16abfbe397d812e5263
/tests/PyPI-pytest/run_all.py
7fbd3f3263e73b4270389c15c3168bb2d73bc427
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
cuulee/Nuitka
3a24518308a09ad0d5e4f762444f991a08cb6828
8e2357ee8e9a93d835e98d5a88ca0181cc34dabc
refs/heads/master
2022-11-10T03:20:53.685313
2020-06-06T08:02:00
2020-06-06T08:02:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,533
py
#!/usr/bin/env python # Copyright 2020, Tommy Li, mailto:<tommyli3318@gmail.com> # # Python test originally created or extracted from other peoples work. The # parts from me are licensed as below. It is at least Free Software where # it's copied from other people. In these cases, that will normally be # indicated. # # 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. # """ Runner for PyPI Pytest comparison This script automates the comparing of pytest results of a nuitka compiled wheel using `python setup.py bdist_nuitka` to the pytest results of an uncompiled wheel built using `python setup.py bdist_wheel` for the most popular PyPI packages. Testing is done to ensure that nuitka is building the wheel correctly. If the pytests pass/fail in the same way, that means Nuitka built the wheel properly. Else if the tests differ, then something is wrong. Virtualenv is used to create a clean environment with no outside pollution. """ import os import sys import json # Find nuitka package relative to us. sys.path.insert( 0, os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..") ), ) # isort:start import nuitka from nuitka.tools.testing.Common import ( createSearchMode, my_print, reportSkip, setup, ) from nuitka.tools.testing.OutputComparison import compareOutput from nuitka.tools.testing.Virtualenv import withVirtualenv from nuitka.utils.AppDirs import getCacheDir def executeCommand(command): my_print("Executing:", command, style="blue") return os.system(command) == 0 def gitClone(package, url, directory): """ Update package with git if already existing in directory else git clone the package into directory """ os.chdir(directory) if not executeCommand( "cd %s && git fetch -q && git reset -q --hard origin && git clean -q -dfx" % package ): assert executeCommand( "git clone %s %s --depth 1 --single-branch --no-tags" % (url, package) ), ("Error while git cloning package %s, aborting..." % package) def main(): # pylint: disable=broad-except,too-many-branches,too-many-locals,too-many-statements _python_version = setup() # cache_dir is where the git clones are cached cache_dir = os.path.join(getCacheDir(), "pypi-git-clones") base_dir = os.getcwd() if not os.path.isdir(cache_dir): os.mkdir(cache_dir) search_mode = createSearchMode() results = [] # load json with open("packages.json", "r") as f: packages = json.load(f) for package_name, details in sorted(packages.items()): active = search_mode.consider(dirname=None, filename=package_name) if not active: continue if str is not bytes: # running on python3 if package_name in ("futures", "future"): reportSkip("Does not run on Python3", ".", package_name) if search_mode.abortIfExecuted(): break continue if os.name == "nt": if package_name in ("cryptography",): reportSkip("Not working on Windows", ".", package_name) if search_mode.abortIfExecuted(): break continue if package_name == "pyyaml": reportSkip("Not yet supported, see Issue #476", ".", package_name) if search_mode.abortIfExecuted(): break continue if package_name in ("pycparser", "numpy"): reportSkip("Not yet supported, see Issue #477", ".", package_name) if search_mode.abortIfExecuted(): break continue if package_name in ( "google-auth", # bdist_nuitka fails AttributeError: single_version_externally_managed "jinja2", # ModuleNotFoundError: No module named 'jinja2.tests' "pandas", # ModuleNotFoundError: No module named 'Cython' "pytz", # need to 'make build' "rsa", # Now uses Poetry (no setup.py) ): if search_mode.abortIfExecuted(): break continue package_dir = os.path.join(cache_dir, package_name) try: gitClone(package_name, details["url"], cache_dir) os.chdir(base_dir) with withVirtualenv( "venv_%s" % package_name, delete=False, style="blue" ) as venv: dist_dir = os.path.join(package_dir, "dist") # delete ignored tests if any if details["ignored_tests"]: for test in details["ignored_tests"]: venv.runCommand("rm -rf %s" % os.path.join(package_dir, test)) # setup for pytest cmds = [ "python -m pip install pytest", "cd %s" % os.path.join(os.path.dirname(nuitka.__file__), ".."), "python setup.py develop", "cd %s" % package_dir, ] if details["requirements_file"]: cmds.append( "python -m pip install -r %s" % details["requirements_file"] ) if details.get("extra_commands"): cmds += details["extra_commands"] # build uncompiled .whl cmds.append("python setup.py bdist_wheel") venv.runCommand(commands=cmds) # install and print out if the active .whl is compiled or not venv.runCommand( commands=[ "python -m pip install -U %s" % os.path.join(dist_dir, os.listdir(dist_dir)[0]), # use triple quotes for linux """python -c "print(getattr(__import__('%s'),'__compiled__','__uncompiled_version__'))" """ % details.get("package_name", package_name), ] ) # get uncompiled pytest results uncompiled_stdout, uncompiled_stderr = venv.runCommandWithOutput( commands=[ "cd %s" % package_dir, "python -m pytest --disable-warnings", ], style="blue", ) # clean up before building compiled .whl cmds = ["cd %s" % package_dir, "git clean -dfx"] if details.get("extra_commands"): cmds += details["extra_commands"] # build nuitka compiled .whl cmds.append("python setup.py bdist_nuitka") venv.runCommand(commands=cmds) # install and print out if the active .whl is compiled or not venv.runCommand( commands=[ "python -m pip install -U %s" % os.path.join(dist_dir, os.listdir(dist_dir)[0]), # use triple quotes for linux """python -c "print(getattr(__import__('%s'),'__compiled__','__uncompiled_version__'))" """ % details.get("package_name", package_name), ] ) # get compiled pytest results compiled_stdout, compiled_stderr = venv.runCommandWithOutput( commands=[ "cd %s" % package_dir, "python -m pytest --disable-warnings", ], style="blue", ) venv.runCommand(commands=["cd %s" % package_dir, "git clean -q -dfx"]) except Exception as e: my_print( "Package", package_name, "ran into an exception during execution, traceback: ", ) my_print(e) results.append((package_name, "ERROR", "ERROR")) if search_mode.abortIfExecuted(): break continue # compare outputs stdout_diff = compareOutput( "stdout", uncompiled_stdout, compiled_stdout, ignore_warnings=True, ignore_infos=True, syntax_errors=True, ) stderr_diff = compareOutput( "stderr", uncompiled_stderr, compiled_stderr, ignore_warnings=True, ignore_infos=True, syntax_errors=True, ) results.append((package_name, stdout_diff, stderr_diff)) exit_code = stdout_diff or stderr_diff my_print( "\n=================================================================================", "\n--- %s ---" % package_name, "exit_stdout:", stdout_diff, "exit_stderr:", stderr_diff, "\nError, outputs differed for package %s." % package_name if exit_code else "\nNo differences found for package %s." % package_name, "\n=================================================================================\n", style="red" if exit_code else "green", ) if exit_code != 0 and search_mode.abortOnFinding( dirname=None, filename=package_name ): break if search_mode.abortIfExecuted(): break search_mode.finish() # give a summary of all packages my_print( "\n\n=====================================SUMMARY=====================================", style="yellow", ) for package_name, stdout_diff, stderr_diff in results: my_print( package_name, "-", end=" ", style="red" if (stdout_diff or stderr_diff) else "green", ) my_print( "stdout:", stdout_diff, end=" ", style="red" if stdout_diff else "green" ) my_print( "stderr:", stderr_diff, end="", style="red" if stderr_diff else "green" ) my_print( "\n---------------------------------------------------------------------------------" ) my_print("TOTAL NUMBER OF PACKAGES TESTED: %s" % len(results), style="yellow") num_failed = 0 num_errors = 0 # tally the number of errors and failed for _, y, z in results: if type(y) is str: # this means the package ran into an exception num_errors += 1 elif y or z: num_failed += 1 my_print( "TOTAL PASSED: %s" % (len(results) - num_failed - num_errors), style="green" ) my_print("TOTAL FAILED (differences): %s" % num_failed, style="red") my_print("TOTAL ERRORS (exceptions): %s" % num_errors, style="red") if __name__ == "__main__": main()
[ "kay.hayen@gmail.com" ]
kay.hayen@gmail.com
687f8708d600726685a989d8b1fda1b775002b0d
b1edcbadbffdeeaa0cb4a8536235413eeb1bfa47
/prime_sieve.py
1b85d8c5b5ecc03fc3104fb4a865c92bbc552beb
[]
no_license
sangazh/pythonds
5c883e3c27767e65647ca4df4b6ea7af119ee77c
1e7cbb11fc7e6ca9b432aba6a047dc3a35fe7b87
refs/heads/master
2020-07-14T03:50:43.658698
2017-09-05T07:49:40
2017-09-05T07:51:14
94,296,440
0
0
null
null
null
null
UTF-8
Python
false
false
2,044
py
input="""4 20 """ data = input.split() N = data.pop(0) def trial_division(n): if n < 2: return [] prime_factors = [] sieve = prime_sieve(n) for p in sieve: if p * p > n: break while n % p == 0: prime_factors.append(p) n //= p if n > 1: prime_factors.append(n) return list(set(prime_factors)) # n means length of prime list is n def prime_sieve(n): result = [2,3] i = 10 lst = [] while n > len(result): result = sieve_helper(i, lst, result) i += 10 lst = result print(result) return result def sieve_helper(n, lst, factor): if lst == []: lst = list(range(2, n)) for i in range(0, int(n**0.5)): if lst != [] and lst[0] not in factor: factor.append(lst[0]) lst = [x for x in lst if x % lst[0] != 0] return factor def prime_list(n): primes = [2, 3] i = 4 if n <= len(primes): return primes[n-1] while n != len(primes): if i % 2 == 0 or i % 3 == 0: i += 1 continue if i < 10: primes.append(i) i += 1 continue sqrt = n**0.5 for p in primes[2:]: if p > sqrt: if i % p == 0: break if i not in primes: primes.append(i) i += 1 print(primes) return primes[-1] def primes(n): if n < 2: return 2 primes = prime_sieve(n) print(primes) if n <= len(primes): return primes[n-1] print(n, len(primes)) exit() i = 1 while n > len(primes): b = int((10 * i/10) * n) primes += prime_sieve(a, b) i += 1 a = b print(n, len(primes)) return primes[n-1] for i in data: # print(primes(int(i)), end=' ') # a = 10 print(prime_sieve(30))
[ "zhangshan574@pingan.com.cn" ]
zhangshan574@pingan.com.cn
9d6179a77178aca3a8cdbdcc523d44497b168416
637a586746f6082c0f9bbc14580c392846ced059
/blog/admin.py
e6b9e4fdd99f38e5e0e67b70cb48041872620b38
[]
no_license
ZucchiniZe/genius
e7b1f3e950fec9e7945e14ccf8bf644f23c584bb
4631e2986505ab6ac6192c40ac6fe36e595a6152
refs/heads/master
2021-01-01T04:44:12.699055
2016-06-02T17:14:35
2016-06-02T17:14:35
59,334,963
0
0
null
null
null
null
UTF-8
Python
false
false
185
py
from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'pub_date') admin.site.register(Post, PostAdmin)
[ "me@alexb.io" ]
me@alexb.io
e20607e7a54ed7e62c1d072206a5705632f3c2ae
d1cbae2014aa4b3d2643df12b047ef2572c6fd31
/softqlearning/policies/nn_policy.py
ffaec9f1991c61c0df723157d3e02498a9185209
[]
no_license
DaomingLyu/softqlearning
d102921f17039ae009fc988fe46d98c53582d35c
aca29d2aee66c44ee052a298f049a22fa14792a5
refs/heads/master
2021-07-20T17:21:52.505369
2017-10-29T19:37:30
2017-10-29T19:37:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,899
py
import tensorflow as tf from rllab.misc.overrides import overrides from rllab.policies.base import Policy from rllab.core.serializable import Serializable class NNPolicy(Policy, Serializable): """ NeuralNetwork wrapper that implements the rllab Policy interface. """ def __init__(self, env_spec, obs_pl, action): Serializable.quick_init(self, locals()) self._obs_pl = obs_pl self._action = action self._scope_name = tf.get_variable_scope().name super().__init__(env_spec) @overrides def get_params_internal(self, **tags): if len(tags) > 0: raise NotImplementedError scope = self._scope_name # Add "/" to 'scope' unless it's empty (otherwise get_collection will # return all parameters that start with 'scope'. scope = scope if scope == '' else scope + '/' return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope) @overrides def get_action(self, observation): feeds = {self._obs_pl: observation[None]} action = tf.get_default_session().run(self._action, feeds) return action.squeeze(), None def plot_samples(self, ax_lst, obs_lst, output=None): output = self._action if output is None else output feed = {self._obs_pl: obs_lst} actions_lst = tf.get_default_session().run(output, feed) for ax, actions in zip(ax_lst, actions_lst): x, y = actions[:, 0], actions[:, 1] ax.plot(x, y, '*') def __getstate__(self): d = Serializable.__getstate__(self) d.update({ 'params': self.get_param_values(), }) return d def __setstate__(self, d): Serializable.__setstate__(self, d) tf.get_default_session().run( tf.variables_initializer(self.get_params()) ) self.set_param_values(d['params'])
[ "haarnoja@berkeley.edu" ]
haarnoja@berkeley.edu
138d1d06c40cb5d586879d84a2f0c29bb44699fc
2f44b715e473fab30d413987b228406e370903b0
/utils/other_utils.py
f5cb01b2cf0694e294b2a77513d0fc28ad3da765
[]
no_license
morduspordus/Gauss
b98f58c51fb2cc5676515a6698dfdeb2dfc0fc47
9c485fb8694170baed9d760b0c3a3ce67d8d4b9f
refs/heads/master
2023-02-19T13:05:08.178408
2021-01-12T01:50:36
2021-01-12T01:50:36
319,195,321
0
0
null
null
null
null
UTF-8
Python
false
false
6,581
py
import sys from utils.file_utils import FileWrite import os import random import numpy as np import torch class Logger(object): def __init__(self,file_name): self.terminal = sys.stdout self.log = open(file_name, "w",1) def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): #this flush method is needed for python 3 compatibility. #this handles the flush command by doing nothing. #you might want to specify some extra behavior here. pass def close(self): self.log.close() sys.stdout = self.terminal def create_string(valid_logs, dataset_name, model_name, kernel, image_height): str_to_return = "\ndataset: {} model: {} kernel: {} img_h: {}".format(dataset_name, model_name, kernel, image_height) str_logs = ['{} - {:.4}'.format(k, v) for k, v in valid_logs.items()] str_logs = ', '.join(str_logs) return str_to_return + ' ::: ' + str_logs def create_string_pascal(valid_logs, cl, len_train=None, len_val=None): str_to_return = "\nclass: {} class_name: {} ".format(cl,pascal_class_names[cl]) if len_train is not None: str_to_return = str_to_return+ "len_train: {}".format(len_train) if len_train is not None: str_to_return = str_to_return+ "len_val: {}".format(len_val) str_logs = ['{} - {:.4}'.format(k, v) for k, v in valid_logs.items()] str_logs = ', '.join(str_logs) return str_to_return + ' ::: ' + str_logs def param_to_string(param): str_params = ['{} - {:.4}'.format(k, v) for k, v in param.items()] s = ', '.join(str_params) return s def create_string_anneal(param, train_metric, val_metric): str_to_return = "train_metric: {} val_metric: {}".format(train_metric, val_metric) str_params = param_to_string(param) return str_params + ':::' + str_to_return + '\n' def model_file_name(dataset_name, model_name, valid_metric, model_load, model_params, dataset_params): smooth_kernel = model_params["smooth_kernel"] image_height = dataset_params["image_height"] valid_metric = "{0:.2f}".format(valid_metric * 100) if model_load == None: from_model = "None" elif model_load == "Anneal": from_model = "Anneal" else: x = model_load.split("\\") x = x[2] y = x.split('.pt') from_model = y[0] if len(from_model) > 40: from_model = from_model[:40] if smooth_kernel == None: kernel_str = "_nosmooth_" else: kernel_str ="_smooth" + str(smooth_kernel)+"_" model_weights_name = os.path.join(WEIGHTS_DIR, dataset_name +str(image_height)+"_" + model_name + kernel_str + '_M_' + valid_metric + '_FFOM_' + from_model + '.pt') return model_weights_name def create_string_pascal(valid_logs, cl, len_train=None, len_val=None): str_to_return = "\nclass: {} class_name: {} ".format(cl,pascal_class_names[cl]) if len_train is not None: str_to_return = str_to_return+ "len_train: {}".format(len_train) if len_train is not None: str_to_return = str_to_return+ "len_val: {}".format(len_val) str_logs = ['{} - {:.4}'.format(k, v) for k, v in valid_logs.items()] str_logs = ', '.join(str_logs) return str_to_return + ' ::: ' + str_logs def create_string_from_logs(valid_logs, valid_metric): str_to_return = "\nvalid metric: {}".format(valid_metric) str_logs = ['{} - {}'.format(k, v) for k, v in valid_logs.items()] str_logs = ', '.join(str_logs) return str_to_return + ' ::: ' + str_logs def create_string_from_args(args): str_args = ['{} - {}'.format(k, v) for k, v in args.items()] str_args = '\n'.join(str_args) return str_args def create_file_name(dataset_name, model_name, im_size, training_type, output_dir): version = 1 add_to_file_path = dataset_name + '_' + model_name + '_' + str(im_size) + '_' + training_type + '_V' + str(version) model_save = os.path.join(output_dir, add_to_file_path + '.pt') while os.path.exists(model_save): version += 1 add_to_file_path = dataset_name + '_' + model_name + '_' + str(im_size) + '_' + training_type + '_V' + str(version) model_save = os.path.join(output_dir, add_to_file_path + '.pt') return add_to_file_path, model_save def create_dir_name(dataset_name, model_name, im_size, training_type, output_dir): version = 1 add_to_file_path = dataset_name + '_' + model_name + '_' + str(im_size) + '_' + training_type + '_V' + str(version) model_save = os.path.join(output_dir, add_to_file_path) while os.path.exists(model_save): version += 1 add_to_file_path = dataset_name + '_' + model_name + '_' + str(im_size) + '_' + training_type + '_V' + str(version) model_save = os.path.join(output_dir, add_to_file_path) return model_save def save_args_outcome(add_to_file_path, args, valid_logs, valid_metric, output_dir): file_args_name = os.path.join(output_dir, add_to_file_path + '_args.txt') fw = FileWrite(file_args_name, True) str_to_write = create_string_from_args(args) fw.write_to_file(str_to_write) file_outcome_name = os.path.join(output_dir, add_to_file_path + '_outcome.txt') fw = FileWrite(file_outcome_name, True) str_to_write = create_string_from_logs(valid_logs, valid_metric) fw.write_to_file(str_to_write) class AvgMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def set_seed(seed, use_cudnn_benchmark): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) torch.manual_seed(seed) # torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. torch.backends.cudnn.enabled = True if use_cudnn_benchmark: print("We will use `torch.backends.cudnn.benchmark`") else: print("We will not use `torch.backends.cudnn.benchmark`") torch.backends.cudnn.benchmark = use_cudnn_benchmark torch.backends.cudnn.deterministic = True torch.set_printoptions(precision=10) def reg_weight_list(start_reg_weight, num_iter, reg_weight_increment): return list(range(start_reg_weight, start_reg_weight + num_iter * reg_weight_increment, reg_weight_increment))
[ "kira14allon14" ]
kira14allon14
9d4dac40c4b17e570a2ca7b01e4d657925f34c0d
39b46908c644092202261589e0a571b5e46cfc64
/stockpractice/main.py
c50f605e68fd2422beb9ec2d550764d9e3a36943
[]
no_license
rhkdrod12/python_practice
7d66f31d5a3e0c707722f5434275e3fe4f5c0df2
40709ae98afd3d81c7a1353e887926f54524ba60
refs/heads/master
2023-02-17T06:48:56.897390
2021-01-06T07:24:07
2021-01-06T07:24:07
327,233,016
0
0
null
null
null
null
UTF-8
Python
false
false
1,717
py
import os import time import fitz import requests # # doc = fitz.open("./test.pdf") # # print(len(doc) ) # page = doc.loadPage(0) # text = page.getText() # # print(text) # # total_text ="" # # for i in doc: # total_text = total_text+i.getText() # # file = open("./total_text.txt",'wb') # file.write(total_text.encode("UTF-8")) # file.close() file = open("./total_text.txt",'rb') lines = file.readlines() file.close() last_list = list() temp ="" for i in lines: i = i.decode("UTF-8") i = i.replace("\n"," ") if len(temp + i)>5000: last_list.append(temp) temp ="" else: temp = temp+i print(len(last_list)) request_url = "https://openapi.naver.com/v1/papago/n2mt" headers = {"X-Naver-Client-Id":"Ucbjhq7NFh3QAtoTWBQS", "X-Naver-Client-Secret": "mueqwp9q6Y"} params = {"source": "en", "target":"ko","text": last_list[0]} response = requests.post(request_url,headers=headers, data= params) result = response.json() print(result) print(result['message']['result']['translatedText']) file = open("./trans.txt",'wb') file.write(result['message']['result']['translatedText'].encode("UTF-8")) file.close() # path_dir = "C:\\Users\\Kim\\test" # file_list = os.listdir(path_dir) # # print(file_list) # # image_list = list() # # for i in file_list: # try: # if i.split(".")[1] =="jpg" or i.split(".")[1] == "png": # image_list.append(i) # except Exception as error: # print(error) # # print(image_list) # # get_time = os.path.getmtime(path_dir+"\\"+image_list[0]) # print(get_time) # # time.localtime(get_time) # # file_data = time.strftime("%YY %mM %dD _ %HH %MM",time.localtime(get_time)) # print(file_data) # # print(type(file_data))
[ "rhkdrod12@gmail.com" ]
rhkdrod12@gmail.com
df0187d579f668c038a8699defe70436d549b641
545ed7962aaa0999585ab3004dcb8849832db7bb
/lib/tokenization/bert_finetune_tokenization.py
ee51d5d7a8982ad77c56803a99e529793fe445e7
[]
no_license
empty2enrich/QANet
7593f94e426419d6034ef33f03359e3944e758d9
d94550ce95c15af81dac1661d1aaa505bcd872d7
refs/heads/master
2023-02-27T15:40:43.070036
2021-02-09T07:42:51
2021-02-09T07:42:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,013
py
# -*- coding: utf-8 -*- # Copyright 2019 Huairuo.ai. # Author: Lin Li (li.lin@huairuo.ai) # # cython: language_level=3 # import collections import re import unicodedata import six import tensorflow as tf def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with tf.gfile.GFile(vocab_file, "r") as reader: while True: token = convert_to_unicode(reader.readline()) if not token: break token = token.strip() vocab[token] = index index += 1 return vocab def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, str): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") def convert_by_vocab(vocab, items): """Converts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: output.append(vocab[item]) return output def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): return True cat = unicodedata.category(char) if cat.startswith("P"): return True return False def is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False class FullTokenizer(object): """Runs end-to-end tokenziation.""" def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.inv_vocab = {v: k for k, v in self.vocab.items()} self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) def tokenize(self, text): split_tokens = [] for token in self.basic_tokenizer.tokenize(text): for sub_token in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) return split_tokens def convert_tokens_to_ids(self, tokens): return convert_by_vocab(self.vocab, tokens) def convert_ids_to_tokens(self, ids): return convert_by_vocab(self.inv_vocab, ids) class BasicTokenizer(object): """Runs basic tokenization (punctuation splitting, lower casing, etc.).""" def __init__(self, do_lower_case=True): """Constructs a BasicTokenizer. Args: do_lower_case: Whether to lower case the input. """ self.do_lower_case = do_lower_case def tokenize(self, text): """Tokenizes a piece of text.""" text = convert_to_unicode(text) text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not trained on any Chinese data # and generally don't have any Chinese data in them (there are Chinese # characters in the vocabulary because Wikipedia does have some Chinese # words in the English Wikipedia.). text = self._tokenize_chinese_chars(text) orig_tokens = whitespace_tokenize(text) split_tokens = [] for token in orig_tokens: if self.do_lower_case: token = token.lower() token = self._run_strip_accents(token) split_tokens.extend(self._run_split_on_punc(token)) output_tokens = whitespace_tokenize(" ".join(split_tokens)) return output_tokens def _run_strip_accents(self, text): """Strips accents from a piece of text.""" text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) return "".join(output) def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if _is_punctuation(char): output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1 return ["".join(x) for x in output] def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") else: output.append(char) return "".join(output) def _is_chinese_char(self, cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ((cp >= 0x4E00 and cp <= 0x9FFF) or # (cp >= 0x3400 and cp <= 0x4DBF) or # (cp >= 0x20000 and cp <= 0x2A6DF) or # (cp >= 0x2A700 and cp <= 0x2B73F) or # (cp >= 0x2B740 and cp <= 0x2B81F) or # (cp >= 0x2B820 and cp <= 0x2CEAF) or (cp >= 0xF900 and cp <= 0xFAFF) or # (cp >= 0x2F800 and cp <= 0x2FA1F)): # return True return False def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xfffd or _is_control(char): continue if is_whitespace(char): output.append(" ") else: output.append(char) return "".join(output) class WordpieceTokenizer(object): """Runs WordPiece tokenziation.""" def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): """Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] Args: text: A single token or whitespace separated tokens. This should have already been passed through `BasicTokenizer. Returns: A list of wordpiece tokens. """ text = convert_to_unicode(text) output_tokens = [] for token in whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) continue is_bad = False start = 0 sub_tokens = [] while start < len(chars): end = len(chars) cur_substr = None while start < end: substr = "".join(chars[start:end]) if start > 0: substr = "##" + substr if substr in self.vocab: cur_substr = substr break end -= 1 if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start = end if is_bad: output_tokens.append(self.unk_token) else: output_tokens.extend(sub_tokens) return output_tokens
[ "li.lin@huairuo.ai" ]
li.lin@huairuo.ai
a01098d3dbf5ee37122139e3341bac107cf7f612
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/1/c43.py
34d1e9279b6f0f045156e977f84d5cbd62ef33f1
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'c43': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
87376efbe2418c17219977963bfaa8733fe5bd4e
f28a2348e07e7ca2ff065d73ed90262977080c4e
/zava-py/docs/source/_code/animation-demo.py
8f4967bf3e1b051df4d9316d1a081f7d0666bbc6
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
oneoffcoder/zava
18aa531e44643141a4095661358401f885bf3a06
95eba827a4422ab260a127794b33b2813746a634
refs/heads/main
2023-02-02T22:06:16.117497
2020-12-20T03:27:28
2020-12-20T03:27:28
320,114,529
8
1
null
null
null
null
UTF-8
Python
false
false
1,972
py
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import animation from zava.core import GrandTour from zava.plot import SinglePlotter, MultiPlotter # 1. create or get your data columns = ['v0', 'v1', 'v2', 'v3'] M1 = np.array([ [1, 1, 1, 1], [2, 2, 2, 1], [3, 3, 3, 3] ]) M2 = np.array([ [1, 2, 3, 4], [2, 2, 1, 1], [1, 1, 3, 3] ]) M1 = pd.DataFrame(M1, columns=columns) M2 = pd.DataFrame(M2, columns=columns) # 2. create your GrandTour instances c = 0.0 d = 100.0 gt1 = GrandTour(M1, c, d) gt2 = GrandTour(M2, c, d) # 3. create your plotters for each GrandTour instance # Note how the first dataset will have red lines # and the second dataset will have green lines. # The parameters passed in go into drawing the lines # and will help create powerful parallel coordinate with # grand tour visuals with hue and saturation effects. sp1 = SinglePlotter(gt1, params={'color': 'r'}) sp2 = SinglePlotter(gt2, params={'color': 'g'}) # 4. setup plotting and animation # don't forget to disable warnings and set the style plt.rcParams.update({'figure.max_open_warning': 0}) plt.style.use('ggplot') # Note how we use MultiPlotter to plot both datasets? fig, ax = plt.subplots(figsize=(15, 3)) mp = MultiPlotter([sp1, sp2], ax=ax) # matplotlib.animation will help us create animations params = { 'fig': fig, 'func': mp, 'frames': np.linspace(0, 360, 360), 'interval': 20, 'init_func': mp.init } anim = animation.FuncAnimation(**params) plt.close(fig) # 5. save the animation params = { 'filename': 'test.mov', 'dpi': 500, 'progress_callback': lambda i, n: print(f'Saving frame {i} of {n}'), 'metadata': { 'title': 'Parallel Coordinates with Grand Tour', 'artist': 'Clint Eastwood', 'genre': 'Action', 'subject': 'Exploratory data visualization', 'copyright': '2020', 'comment': 'One-Off Coder' } } anim.save(**params)
[ "vangjee@gmail.com" ]
vangjee@gmail.com
6e3177191a4c67ffa80a3bfa59dd3232067b3abc
fc804267cfd53ef0f91cb799a1d13d97c2a72f06
/PacMan/Main.py
9de28437b0560872a05c6d151fd1428efeef6375
[]
no_license
Valentin2508247/pacman
b082ee262c7ff9ea1bdd7155ba369e081bb44015
33fa6c26ab38934ca955c105fe99fb7df18f795a
refs/heads/master
2020-08-16T16:23:48.294489
2019-10-16T11:03:55
2019-10-16T11:03:55
215,523,386
0
0
null
null
null
null
UTF-8
Python
false
false
2,057
py
import pygame import sys import Map import Packman import GameObject import Blinky import Game WIDTH = 800 HEIGHT = 600 TILE_SIZE = 16 KEY_UP = pygame.K_w KEY_DOWN = pygame.K_s KEY_LEFT = pygame.K_a KEY_RIGHT = pygame.K_d user = None def main(): if True: game = Game.Game() game.main_menu() else: clock = pygame.time.Clock() pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF) #pacman = Packman.Packman(16, 16, "right") map = Map.Map() blinky = Blinky.Blinky(300, 300, "right", map) cnt = 0 while True: for i in pygame.event.get(): if i.type == pygame.QUIT: pygame.quit() sys.exit(0) if i.type == pygame.KEYDOWN: if i.key == KEY_UP: map.pacman.change_direction("up") if i.key == KEY_DOWN: map.pacman.change_direction("down") if i.key == KEY_LEFT: map.pacman.change_direction("left") if i.key == KEY_RIGHT: map.pacman.change_direction("right") # Calling the 'my_group.update' function calls the 'update' function of all # its member sprites. Calling the 'my_group.draw' function uses the 'image' # and 'rect' attributes of its member sprites to draw the sprite. screen.fill((0, 0, 50)) map.update() map.draw(screen) cnt += 1 if cnt == 25: cnt = 0 if blinky.direction == "left": blinky.change_direction("right") else: blinky.change_direction("left") blinky.update() blinky.draw(screen) #pacman.draw(screen) #pacman.update() pygame.display.flip() clock.tick(30) if __name__ == '__main__': main()
[ "Valentin2508247@mail.ru" ]
Valentin2508247@mail.ru
339aa95ff2ec61542229fc440a57b8e800234f8d
e98fb92c8a7515cfb6a29a42858f311bbdcbec80
/scripts/play_cv_video.py
47d7a22fd9c207172cafb32006aa2d8e2d6c05ae
[]
no_license
rtarun/kojaks-1
27f6474e361faecdf82c62394b252b60a95eef90
133bae2136d650acbef02818641a5feba0332ef0
refs/heads/master
2021-01-02T23:17:16.314474
2017-06-01T06:52:55
2017-06-01T06:52:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
857
py
#!/usr/bin/env python import roslib roslib.load_manifest('kojaks') import sys import rospy import cv2 from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError # Tracklet generation import generate_tracklet class PlayCvVideo: def __init__(self): self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/image_raw",Image, self.imageCb) def imageCb(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) cv2.imshow("Image window", cv_image) cv2.waitKey(3) def main(args): play_cv_video = PlayCvVideo() rospy.init_node('play_cv_video', anonymous=True) try: rospy.spin() except KeyboardInterrupt: print("Shutting down") cv2.destroyAllWindows() if __name__ == '__main__': main(sys.argv)
[ "ry2277@columbia.edu" ]
ry2277@columbia.edu
5e9a62071712485457c057213fd73ab8ddbee3d6
29e06be5515737c8452ac2b7e415765c38410ccb
/quicker.py
ad8e5053b52c2fc21aacd0cbf819b0040401a56c
[]
no_license
liaokongVFX/quicker
73dbd68414ceac0a7f4649608aef83989e89653a
fabb28881cf02f06b6f26c863a0c420a3372d555
refs/heads/main
2023-03-03T14:13:33.496222
2021-02-17T11:12:35
2021-02-17T11:12:35
332,411,019
5
0
null
null
null
null
UTF-8
Python
false
false
10,989
py
# -*- coding: utf-8 -*- # Time : 2021/2/8 20:32 # Author : LiaoKong import os import time from PySide2.QtWidgets import * from PySide2.QtCore import * from notification import NotificationWindow from core.plugin_register import PluginRegister from core.action_register import ActionRegister from timing_tasks_manager import TimingTasksManager from hotkey import HotkeyThread from quicker_menus import QuickerMenusWidget from libs import keyboard import setting import utils log = utils.get_logger(u'Quicker') class Quicker(QWidget): def __init__(self, parent=None): super(Quicker, self).__init__(parent) self.placeholder = u'hello, Quicker!' self.RESULT_ITEM_HEIGHT = 62 self.clipboard = QApplication.clipboard() pos = QDesktopWidget().availableGeometry().center() pos.setX(pos.x() - (self.width() / 2) - 150) pos.setY(pos.y() - 350) self.move(pos) self.init_ui() self.plugin_register = PluginRegister(self) self.action_register = ActionRegister(self) # 定时任务 self.timing_task_manager = TimingTasksManager() self.timing_task_manager.show_msg_sig.connect(self.show_timing_task_msg) self.init_hotkey() self.update_result_list_height(0) @staticmethod def show_timing_task_msg(msg): NotificationWindow.success(u'提醒', msg) def init_hotkey(self): global_shortcuts = setting.GLOBAL_HOTKEYS plugin_shortcuts = self.plugin_register.get_keyword_by_shortcut() if set(global_shortcuts) & set(plugin_shortcuts): log.error('There are duplicate shortcuts.') log.error(u'global_shortcuts: {}'.format(global_shortcuts)) log.error(u'plugin_shortcuts: {}'.format(plugin_shortcuts)) raise ValueError('There are duplicate shortcuts.') global_shortcuts.update(self.plugin_register.get_keyword_by_shortcut()) hotkeys = HotkeyThread(global_shortcuts, self) hotkeys.show_main_sign.connect(self.set_visible) hotkeys.shortcut_triggered.connect(self.shortcut_triggered) hotkeys.start() def shortcut_triggered(self, plugin_name): if self.plugin_register.get_plugin(plugin_name): self.set_show() self.input_line_edit.setText(plugin_name + ' ') if plugin_name in setting.GLOBAL_HOTKEYS.values(): getattr(self, plugin_name)() def show_menus(self): utils.clear_clipboard() keyboard.press_and_release('ctrl+c') time.sleep(0.25) urls = self.clipboard.mimeData().urls() urls = [u.toLocalFile() for u in urls if os.path.exists(u.toLocalFile())] text = self.clipboard.mimeData().text() if not urls and not text: data = { 'type': 'empty' } elif not urls and text: data = { 'type': 'text', 'text': text } else: data = { 'type': 'urls', 'urls': urls } log.info(u'已调用quicker menus,{}'.format(data)) menus_widget = QuickerMenusWidget(data, self) menus_widget.show_window() def init_ui(self): self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setFixedSize(QSize(850, 600)) self.load_style() self.installEventFilter(self) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(5) self.input_line_edit = QLineEdit() self.input_line_edit.setPlaceholderText(self.placeholder) self.input_line_edit.setFocusPolicy(Qt.ClickFocus) self.input_line_edit.setMinimumHeight(66) self.input_line_edit.returnPressed.connect(self.input_line_edit_return_pressed) self.input_line_edit.textChanged.connect(self.input_line_edit_text_changed) self.result_list_widget = QListWidget() self.result_list_widget.setObjectName('result_list_widget') self.result_list_widget.setFocusPolicy(Qt.ClickFocus) self.result_list_widget.keyPressEvent = self.result_list_key_press_event self.result_list_widget.itemClicked.connect(self.execute_result_item) layout.addWidget(self.input_line_edit) layout.addWidget(self.result_list_widget) layout.addItem(QSpacerItem(40, 100, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.input_line_edit.setFocus(Qt.MouseFocusReason) self.set_visible() def eventFilter(self, obj, event): if event.type() == QEvent.WindowDeactivate: self.set_visible() return QObject.eventFilter(self, obj, event) # 交由其他控件处理 def input_line_edit_text_changed(self, text): if (text.endswith(' ') and self.result_list_widget.count() == 1 and ' ' not in text.strip() and self.result_list_widget.itemWidget(self.result_list_widget.item(0)).keyword != text.strip()): self.input_line_edit.setText( self.result_list_widget.itemWidget(self.result_list_widget.item(0)).keyword + ' ' ) return if ' ' not in text.strip(): plugin_keyword = text.strip() result_items = self.plugin_register.search_plugin(plugin_keyword) else: plugin_keyword, query_str = text.strip().split(' ', 1) result_items = self.plugin_register.get_query_result(plugin_keyword, query_str) if result_items: self.add_items(result_items) def update_result_list_height(self, result_items_num): # list高度需要根据数据个数自动调整 height = result_items_num * self.RESULT_ITEM_HEIGHT if height > 6 * self.RESULT_ITEM_HEIGHT: height = 6 * self.RESULT_ITEM_HEIGHT self.result_list_widget.setFixedHeight(height) def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.set_visible() current_widget = QApplication.focusWidget() if event.key() == Qt.Key_Down: if self.result_list_widget.count() < 1: return if isinstance(current_widget, QLineEdit): self.result_list_widget.setFocus(Qt.MouseFocusReason) self.result_list_widget.setCurrentRow(0) return elif (isinstance(current_widget, QListWidget) and self.result_list_widget.currentRow() + 1 == self.result_list_widget.count()): self.input_line_edit.setFocus(Qt.MouseFocusReason) self.result_list_widget.setCurrentRow(-1) return elif event.key() == Qt.Key_Up: if isinstance(current_widget, QListWidget): self.input_line_edit.setFocus(Qt.MouseFocusReason) self.result_list_widget.setCurrentRow(-1) return elif isinstance(current_widget, QLineEdit) and self.result_list_widget.count(): self.result_list_widget.setFocus(Qt.MouseFocusReason) self.result_list_widget.setCurrentRow(self.result_list_widget.count() - 1) return return super(Quicker, self).keyPressEvent(event) def result_list_key_press_event(self, event): if event.key() == Qt.Key_Return: return self.execute_result_item(self.result_list_widget.currentItem()) if event.key() == Qt.Key_Backspace: self.input_line_edit.setFocus(Qt.MouseFocusReason) self.result_list_widget.setCurrentRow(-1) self.input_line_edit.setText(self.input_line_edit.text()[:-1]) return super(QListWidget, self.result_list_widget).keyPressEvent(event) def execute_result_item(self, item): result_item = self.result_list_widget.itemWidget(item) if not result_item: return input_text = self.input_line_edit.text().strip() if result_item.keyword and ( input_text == result_item.keyword or not input_text.startswith(result_item.keyword)): self.input_line_edit.setText(result_item.keyword + ' ') self.input_line_edit.setFocus(Qt.MouseFocusReason) self.result_list_widget.setCurrentRow(-1) else: self.input_line_edit_return_pressed() def input_line_edit_return_pressed(self): if self.result_list_widget.count() < 1: return text = self.input_line_edit.text().strip() if len(text.split(' ', 1)) == 2: plugin_keyword, execute_str = text.strip().split(' ', 1) else: plugin_keyword = next(iter( self.result_list_widget.itemWidget(self.result_list_widget.item(i)).keyword for i in range(self.result_list_widget.count()) if self.result_list_widget.itemWidget(self.result_list_widget.item(i)).keyword == text ), '') execute_str = '' if not plugin_keyword: return result_item = None if self.result_list_widget.selectedItems(): result_item = self.result_list_widget.itemWidget(self.result_list_widget.currentItem()) elif self.result_list_widget.count() == 1: result_item = self.result_list_widget.itemWidget(self.result_list_widget.item(0)) result_items = self.plugin_register.execute( plugin_keyword, execute_str, result_item, self.plugin_register.plugins() ) if not result_items: self.close() else: self.add_items(result_items) def load_style(self): with open('res/theme.css') as f: self.setStyleSheet(f.read()) def show(self): self.input_line_edit.setText('') super(Quicker, self).show() def reload_plugin(self): self.plugin_register.reload_plugins() def reload_actions(self): self.action_register.reload_actions() def add_items(self, result_items): self.result_list_widget.clear() for item in result_items: self.add_item(item) self.update_result_list_height(len(result_items)) def add_item(self, result_item): item = QListWidgetItem() item.setSizeHint(QSize(200, self.RESULT_ITEM_HEIGHT)) self.result_list_widget.addItem(item) self.result_list_widget.setItemWidget(item, result_item) def set_visible(self): if self.isVisible(): self.input_line_edit.setText('') self.result_list_widget.clear() self.update_result_list_height(0) self.setVisible(False) else: self.set_show() def set_show(self): self.setVisible(True) self.activateWindow() self.input_line_edit.setFocus(Qt.MouseFocusReason)
[ "568250549@qq.com" ]
568250549@qq.com
96ca71b3d149e7149dca50481675f72cddda958b
5945accf9fec028cc9e76cd54e94e09cbd0843eb
/LearnRegexPyQt5.py
0fc452239a83aead1626d304c30fe0d515f7288f
[]
no_license
kanishksharan12/Regex
d1fe4064b76658979648d8e24a26da8e8b9ae21e
fea900f27b6169434839bfef0b289d67ea04d596
refs/heads/master
2021-07-21T17:31:50.417777
2017-11-01T07:42:06
2017-11-01T07:42:06
109,101,877
0
0
null
null
null
null
UTF-8
Python
false
false
5,046
py
# Python Regular Expressions - GUI Interactive Tool # Kanishk Sharan # # Compatible with 3.x version of python import sys from PyQt5 import QtGui, QtWidgets #modified from PyQt4 to PyQt5 for anaconda 3.5 distr import re import time class LearnRegex(QtWidgets.QWidget): def __init__(self): super(LearnRegex, self).__init__() self.init_ui() def init_ui(self): self.setFont(QtGui.QFont("Sans Serif", 11)) self.txtPattern = QtWidgets.QLineEdit() self.txtRepPattern = QtWidgets.QLineEdit() # Changed to plain text self.txtText= QtWidgets.QPlainTextEdit() self.txtResult = QtWidgets.QTextEdit() self.regex = None self.regexText = None lblPattern = QtWidgets.QLabel('Pattern') lblRepPattern = QtWidgets.QLabel('Replacement Pattern') lblText = QtWidgets.QLabel('Text') lblResult = QtWidgets.QLabel('Result') btnMatch = QtWidgets.QPushButton('Match') btnNextMatch = QtWidgets.QPushButton('Next Match') btnReplace = QtWidgets.QPushButton('Replace') btnSplit = QtWidgets.QPushButton('Split') btnMatch.clicked.connect(self.match_click) btnNextMatch.clicked.connect(self.next_match_click) btnReplace.clicked.connect(self.replace_click) btnSplit.clicked.connect(self.split_click) grid = QtWidgets.QGridLayout() grid.setSpacing(10) grid.addWidget(lblPattern, 1, 0) grid.addWidget(self.txtPattern, 1, 1, 1, 4) grid.addWidget(lblRepPattern, 2, 0) grid.addWidget(self.txtRepPattern, 2, 1, 1, 4) grid.addWidget(lblText, 3, 0) grid.addWidget(self.txtText, 3, 1, 1, 4) grid.addWidget(btnMatch, 4, 1) grid.addWidget(btnNextMatch, 4, 2) grid.addWidget(btnReplace, 4, 3) grid.addWidget(btnSplit, 4, 4) grid.addWidget(lblResult, 5, 0) grid.addWidget(self.txtResult, 5, 1, 5, 4) self.setLayout(grid) self.setGeometry(300, 300, 860, 620) self.setWindowTitle('Learning Regex with Python') self.show() def match_click(self): self.txtResult.setText ('Value,Index,Length,ElapsedTime(s)') try: self.regex = re.compile(self.txtPattern.text()) except Exception as e: QtWidgets.QMessageBox.critical(self, 'Error', 'Pattern error: {0}'.format(str(e))) return self.regex_text = self.txtText.toPlainText() self.regex_group_index = dict((v,k) for k,v in self.regex.groupindex.items()) self.match_iter = self.regex.finditer(self.regex_text) self.highlight_match() def next_match_click(self): self.highlight_match() def replace_click(self): self.txtResult.setText(re.sub(self.txtPattern.text(), self.txtRepPattern.text(), self.txtText.toPlainText())) def split_click(self): self.txtResult.setText("") for s in re.split(self.txtPattern.text(), self.txtText.toPlainText()): self.txtResult.append(s) def highlight_match(self): start_time = None try: #self.txtText.setAcceptRichText(False) self.txtText.setPlainText(self.regex_text) start_time = time.time() match = self.match_iter.__next__() end_time = time.time() self.txtResult.append ('{0},{1},{2},{3:.2f}'.format(match.group(0),match.start(), match.end()-match.start(), end_time - start_time)) for i in range(0, len(match.groups())): gn = i+1 group_name = None if gn in self.regex_group_index: group_name = self.regex_group_index[gn] self.txtResult.append (' Group:{0}, Name:{1}, Value: {2}'.format(gn, group_name, match.group(gn))) self.highlighter(match.start(), match.end()) except StopIteration: end_time = time.time() self.txtResult.append ('End, Elapsed Time (s): {0:0.2f}'.format(end_time - start_time)) def highlighter(self,start,end): format = QtGui.QTextCharFormat() format.setBackground(QtGui.QBrush(QtGui.QColor("yellow"))) cursor = self.txtText.textCursor() cursor.setPosition(start) cursor.movePosition(QtGui.QTextCursor.Right,QtGui.QTextCursor.KeepAnchor,end-start) cursor.mergeCharFormat(format) def main(): app = QtWidgets.QApplication(sys.argv) ex = LearnRegex() sys.exit(app.exec_()) if __name__ == '__main__': main()
[ "noreply@github.com" ]
kanishksharan12.noreply@github.com
b2b4708016f292f7bfcecce49e0442265d4acb2f
c7eacd8ecb635968106cb240f24613d80526565f
/handlers/private/admin/command/__init__.py
b6fae0778024336206bbe322043de236c47f1e13
[]
no_license
ExissBrr/Telegram-Bot-Template
fa256b17225a0dcc39028e51b4cc8a0bf933b8a8
04f18d435445c44d050f0d4558f13e931ab56375
refs/heads/main
2023-04-25T09:31:30.127825
2021-05-16T23:05:55
2021-05-16T23:05:55
367,700,530
0
0
null
2021-05-15T18:10:44
2021-05-15T18:10:43
null
UTF-8
Python
false
false
113
py
from .start import dp from .help import dp from .bun_user import dp from .unbun_user import dp __all__ = ["dp"]
[ "veenrokdalv@protonmail.com" ]
veenrokdalv@protonmail.com
9d2ef47b6d41b7f98bf0166663ae827e6347e044
e4c4b05954f62fce107e481996e79a73b4fb5803
/cogs/monitors/report.py
2ce9da981f1a2099cfae280fcc91551199be219d
[ "MIT" ]
permissive
Ultra03/BottyMcBotface
ccf937cd801bb2327ea59f53c8148cb7e0e3721d
40226c1bdf2d05ff7835101f7a8a389828ec70b0
refs/heads/main
2023-02-07T21:52:55.762158
2021-01-03T12:04:19
2021-01-03T12:04:19
320,394,415
0
0
null
2020-12-10T21:28:58
2020-12-10T21:28:57
null
UTF-8
Python
false
false
3,814
py
import asyncio import datetime import discord import humanize async def report(bot, msg, user, invite=None): role = msg.guild.get_role(bot.settings.guild().role_moderator) channel = msg.guild.get_channel(bot.settings.guild().channel_reports) ping_string = "" for member in role.members: offline_ping = (await bot.settings.user(member.id)).offline_report_ping if member.status == discord.Status.online or offline_ping: ping_string += f"{member.mention} " embed = await prepare_embed(bot, user, msg) if invite: report_msg = await channel.send(f"{ping_string}\nMessage contained invite: {invite}", embed=embed) else: report_msg = await channel.send(ping_string, embed=embed) report_reactions = ['✅', '🆔', '🧹'] for reaction in report_reactions: await report_msg.add_reaction(reaction) def check(reaction, user): res = (user.id != bot.user.id and reaction.message == report_msg and str(reaction.emoji) in report_reactions and bot.settings.permissions.hasAtLeast(user.guild, user, 5)) return res while True: try: reaction, _ = await bot.wait_for('reaction_add', timeout=120.0, check=check) except asyncio.TimeoutError: try: await report_msg.clear_reactions() return except Exception: pass else: if str(reaction.emoji) == '✅': try: await report_msg.delete() except Exception: pass return elif str(reaction.emoji) == '🆔': await channel.send(user.id, delete_after=10) elif str(reaction.emoji) == '🧹': await channel.purge(limit=100) async def prepare_embed(bot, user, msg): user_info = await bot.settings.user(user.id) joined = user.joined_at.strftime("%B %d, %Y, %I:%M %p") created = user.created_at.strftime("%B %d, %Y, %I:%M %p") rd = await bot.settings.rundown(user.id) rd_text = "" for r in rd: if r._type == "WARN": r.punishment += " points" rd_text += f"**{r._type}** - {r.punishment} - {r.reason} - {humanize.naturaltime(datetime.datetime.now() - r.date)}\n" embed = discord.Embed(title="Word filter") embed.color = discord.Color.red() embed.set_thumbnail(url=user.avatar_url) embed.add_field(name="Member", value=f"{user} ({user.mention})") embed.add_field(name="Channel", value=msg.channel.mention) if len(msg.content) > 400: msg.content = msg.content[0:400] + "..." embed.add_field(name="Message", value=discord.utils.escape_markdown( msg.content) + f"\n\n[Link to message]({msg.jump_url})", inline=False) embed.add_field(name="Join date", value=f"{joined} UTC", inline=True) embed.add_field(name="Account creation date", value=f"{created} UTC", inline=True) embed.add_field(name="Warn points", value=user_info.warn_points, inline=True) reversed_roles = user.roles reversed_roles.reverse() roles = "" for role in reversed_roles[0:4]: if role != user.guild.default_role: roles += role.mention + " " roles = roles.strip() + "..." embed.add_field( name="Roles", value=roles if roles else "None", inline=False) if len(rd) > 0: embed.add_field(name=f"{len(rd)} most recent cases", value=rd_text, inline=True) else: embed.add_field(name=f"Recent cases", value="This user has no cases.", inline=True) embed.set_footer(text="React with ✅ to dismiss.") return embed
[ "aamir@farooq.xyz" ]
aamir@farooq.xyz
4f5a1beca47a75f17a20f109d21e1142eb62ad90
fd5b8f4f5beb741068170c1051a71281e1f4bb28
/backend/api/models.py
48f061ba420947d3037923d8aeeeb2ae61a43920
[]
no_license
Mariownyou/cars
96561579e79a73f08aa4ad015b2942fed4b9ce0c
dce57144826b811ae3cc1b4d2fca90fb9f774251
refs/heads/main
2023-01-09T06:08:13.004456
2020-11-09T16:58:06
2020-11-09T16:58:06
310,782,607
0
0
null
null
null
null
UTF-8
Python
false
false
987
py
from django.db import models from imagekit.models import ProcessedImageField from imagekit.processors import ResizeToFit, Adjust, ResizeToFill # Create your models here. class Car(models.Model): brand = models.CharField('Марка машины', max_length=100) rare = models.IntegerField('Редкость') visited = models.BooleanField('Встречалась ли') def __str__(self): brand = self.brand return brand class Photo(models.Model): image = ProcessedImageField( upload_to='cars', processors=[ResizeToFill(300, 200)], format='JPEG', options={'quality': 100}, ) title = models.CharField('Заголовок', max_length=100) car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='photos') date = models.DateTimeField('Время', auto_now_add=True) def __str__(self): url = 'http://127.0.0.1:4000' img = self.image.url return url + img
[ "39639000+Mariownyou@users.noreply.github.com" ]
39639000+Mariownyou@users.noreply.github.com
67b628785333591fbbb2ac27b60e0acc856b3968
f3f2fe9c80ab171433d6941bdf6e271fdabcec6a
/apps/asset/migrations/0001_initial.py
a4140a445bb586445dd8dfd6f8e57b58f4f51ee7
[]
no_license
cgbts88/MisRest
8afaee95994f1dfcd2c65e4f4aede1c5b14c173f
a74673653d1fe026e05c72a08088c160a777ffce
refs/heads/master
2023-03-20T00:15:02.645154
2021-03-11T00:02:11
2021-03-11T00:02:11
334,912,474
0
0
null
null
null
null
UTF-8
Python
false
false
8,679
py
# Generated by Django 2.1 on 2021-01-20 08:05 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='AssetOrder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('num', models.CharField(blank=True, max_length=32, null=True, verbose_name='单号')), ('edp_asset', models.CharField(blank=True, max_length=64, null=True, verbose_name='电脑部资产')), ('target_asset', models.CharField(blank=True, max_length=64, null=True, verbose_name='目标部门资产')), ('transfer_time', models.DateTimeField(auto_now_add=True, verbose_name='转移时间')), ('remark', models.TextField(blank=True, default='', null=True, verbose_name='备注')), ('target_department', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='users.Department', verbose_name='目标部门')), ], options={ 'verbose_name': '资产管理', 'verbose_name_plural': '资产管理', 'ordering': ['-id'], }, ), migrations.CreateModel( name='Attribute', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('brand', models.CharField(max_length=32, verbose_name='品牌')), ('model', models.CharField(max_length=32, verbose_name='型号')), ('parameter', models.CharField(blank=True, max_length=128, null=True, verbose_name='参数')), ('is_network', models.BooleanField(choices=[(True, '是'), (False, '否')], default=True, verbose_name='是否网络设备')), ], options={ 'verbose_name': '属性信息', 'verbose_name_plural': '属性信息', 'ordering': ['id'], }, ), migrations.CreateModel( name='NetworkDevice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('device_name', models.CharField(max_length=32, unique=True, verbose_name='设备名')), ('ip', models.GenericIPAddressField(blank=True, null=True, unique=True, verbose_name='IP地址')), ('login_name', models.CharField(blank=True, max_length=32, null=True, verbose_name='登录名')), ('login_pwd', models.CharField(blank=True, max_length=32, null=True, verbose_name='登录密码')), ('remark', models.TextField(blank=True, default='', null=True, verbose_name='备注信息')), ('asset_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='network_asset_user', to=settings.AUTH_USER_MODEL, verbose_name='使用人')), ], options={ 'verbose_name': '网络设备', 'verbose_name_plural': '网络设备', 'ordering': ['-id'], }, ), migrations.CreateModel( name='OtherDevice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('remark', models.TextField(blank=True, default='', null=True, verbose_name='备注信息')), ('asset_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='other_asset_user', to=settings.AUTH_USER_MODEL, verbose_name='使用人')), ], options={ 'verbose_name': '其它设备', 'verbose_name_plural': '其它设备', 'ordering': ['-id'], }, ), migrations.CreateModel( name='RecordLog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('record_time', models.DateTimeField(auto_now_add=True, verbose_name='记录时间')), ('record_type', models.CharField(choices=[('create', '创建'), ('update', '修改'), ('transfer', '转移'), ('scrap', '报废')], default='create', max_length=16, verbose_name='记录类型')), ('remark', models.TextField(default='', verbose_name='内容')), ], options={ 'verbose_name': '记录日志', 'verbose_name_plural': '记录日志', 'ordering': ['id'], }, ), migrations.CreateModel( name='Stock', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('it_num', models.CharField(max_length=32, verbose_name='EDP编号')), ('acc_num', models.CharField(blank=True, max_length=32, null=True, verbose_name='ACC编号')), ('sn', models.CharField(max_length=32, verbose_name='序列号')), ('mac', models.CharField(blank=True, max_length=32, null=True, verbose_name='MAC地址')), ('rmb', models.IntegerField(blank=True, null=True, verbose_name='人民币')), ('hkd', models.IntegerField(blank=True, null=True, verbose_name='港币')), ('buy_date', models.DateField(blank=True, null=True, verbose_name='购买日期')), ('warranty_date', models.DateField(blank=True, null=True, verbose_name='到保日期')), ('state', models.CharField(choices=[('free', '闲置'), ('used', '在用'), ('disuse', '弃用'), ('scrap', '报废')], default='free', max_length=8, verbose_name='资产状态')), ('department', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_department', to='users.Department', verbose_name='库存部门')), ('model', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='asset.Attribute', verbose_name='型号')), ], options={ 'verbose_name': '库存信息', 'verbose_name_plural': '库存信息', 'ordering': ['-id'], }, ), migrations.CreateModel( name='TypeCode', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('simple_code', models.CharField(max_length=32, unique=True, verbose_name='简写分类')), ('en_code', models.CharField(max_length=32, verbose_name='英文分类')), ('cn_code', models.CharField(max_length=32, verbose_name='中文分类')), ], options={ 'verbose_name': '分类编码', 'verbose_name_plural': '分类编码', 'ordering': ['id'], }, ), migrations.AddField( model_name='recordlog', name='record_obj', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='asset.Stock', verbose_name='记录对象'), ), migrations.AddField( model_name='recordlog', name='recorder', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='asset_recorder', to=settings.AUTH_USER_MODEL, verbose_name='记录人'), ), migrations.AddField( model_name='otherdevice', name='stock', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='asset.Stock', verbose_name='设备编号'), ), migrations.AddField( model_name='networkdevice', name='stock', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='asset.Stock', verbose_name='设备编号'), ), migrations.AddField( model_name='attribute', name='type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='asset.TypeCode', verbose_name='分类'), ), ]
[ "857635@qq.com" ]
857635@qq.com
93d732d3e628258bea1873e3bda00b91179d8e53
4449034f7631783e02d526dcc0af59093d572b11
/lab17-palindrome-anagram.py
5f7aea1b14b87ada431cbce8bcc673cd142f2a5d
[]
no_license
brukeg/pcg_python
d3aea9495fefc0807a4c09f4b44b27397d28fd70
dd12d08a62e95d235c7371e0963899dcd5cf2568
refs/heads/master
2021-06-23T05:48:21.230036
2019-05-25T00:37:30
2019-05-25T00:37:30
168,283,313
1
0
null
2021-06-10T21:22:20
2019-01-30T05:12:29
Python
UTF-8
Python
false
false
944
py
""" A palindrome is a word that's the same forwards or backwards. Two words are anagrams of eachother if the letters of one can be rearranged to fit the other. Write a palindrome and anagram checker. """ def check_palindrome(word): reverse = '' word = input("Enter a word: ").strip().lower() # a for loop for reversing the order of the letters in a word. for l in word: reverse = l + reverse if reverse == word: return f"{word} is a palindrome!" else: return f"{word} is not a palindrome." def check_anagram(word1, word2): # strip and lower the inputs word1 = input("Enter the first word: ").strip().lower() word2 = input("Enter the second word: ").strip().lower() # replace white space between words and sort result1 = sorted(word1.replace(" ", "")) result2 = sorted(word2.replace(" ", "")) if result1 == result2: return f"{word1} and {word2} are anagrams!" else: return f"{word1} and {word2} are not anagrams."
[ "bruke@spreadlabel.com" ]
bruke@spreadlabel.com