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
220 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
257 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
8617e5ac82e89f58b2116bb99003c611dc46da49
7d90e6bebce35d5810da7cb9180f34bfa7398d38
/guestbook/tests/models_tests.py
dde2c5be1e1420dfe441443bb112fae8d81c8d40
[]
no_license
mbrochh/pugsg_20120419
bd4c5fc2ec9edbb6a8f72e1165df46aed00cc88f
0d2d396863e4d25a0cb2e97d30b16ebbd6283d0c
refs/heads/master
2021-01-01T17:57:22.171950
2012-04-19T10:20:23
2012-04-19T10:20:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
589
py
"""Tests for the models of the ``guestbook`` app.""" from django.test import TestCase from guestbook.tests.factories import GuestbookFactory class GuestbookEntryTestCase(TestCase): """Tests for the ``GuestbookEntry`` model class.""" def test_instantiation_and_save(self): entry = GuestbookFactory.build() entry.save() self.assertTrue(entry.pk, msg=( 'New object should have a primary key.')) def test_character_count(self): entry = GuestbookFactory.build(text='Hello world') self.assertEqual(entry.character_count(), 11)
[ "mbrochh@gmail.com" ]
mbrochh@gmail.com
b0dece6dcaae5eded6b567fe83bd226b76bd3c59
3863599b51116a63c4e921dc437717dcc45df28d
/HW02_b06505004.py
19c7682cb20648be5dda2bfe90c1147f0a81c72b
[]
no_license
momo1106github/ESOE-CS101-2017
9d5bfe07363ddec0aaace0a526e117a66d52ecef
4efb77d0e260363ab66a82b78ed10cba3ae4073e
refs/heads/master
2021-07-12T00:30:39.049177
2017-10-15T09:02:03
2017-10-15T09:02:03
106,075,882
0
0
null
2017-10-07T06:16:18
2017-10-07T06:16:18
null
UTF-8
Python
false
false
4,595
py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #<教學> # 以 "#" 字符號開頭的內容將被 Python 視為「註解」。不會執行。 # #########################################說明######################################## # 對 Python 而言, if __name__ == "__main__" 即為程式的進入點。一個程式只能有「一個」進入點。 # 換言之,整支程式從這一行開始執行。 #def sayHi(): #''' #這裡定義了一個函式,名叫 sayHi #''' # #這支函式唯一的功能就是印出下面這一句話… #print("Hi!這是一支只會說 Hi 的函式。") #if __name__ == '__main__': #這裡是程式進入點。整支程式從這裡開始執行… # #以下執行 sayHi() 函式 #sayHi() #</教學> # ##################################################################################### number = 100 #設定 number 這個變數的值為 2 print("number 的二進位表示法為:{0}".format(bin(number))) #將 2 餵入 bin(n) 函式中,並把 bin(n) 回傳的結果,接著餵給 print() 輸出在螢幕畫面上。 # 你可以試著把 number 的值改為其它的數字,觀察看看。 # bin(n) 的原理大致如下: def int2bin(N): ''' 本函式將 int 整數轉為 bin 二進位制表示。作用等同於 bin(N) ''' tmpLIST = [] while N > 0: remainder = int(N % 2) tmpLIST.append(remainder) N = (N - remainder) / 2 tmpLIST.append(0) ans = "" for j in tmpLIST[::-1]: #將 tmpLIST 中的數字從尾至頭傳入 j ans = ans + str(j) print("{0} 的二進位表示為 {1}.".format(N, ans)) return None #作業 1. # 請參考上例,自己寫一個將二進位表示數轉為十進位制的函式供稍後的作業使用: def bin2int(N): L = int(len(str(N))) #將輸入的二進位數字變成字串並數出他的長度 A = 0 #設定兩個變數,其中A是用來計算最後的答案,K是用來計算迴圈運行的次數以及作為2的指數 K = 0 while L > K : #設定迴圈條件,當執行的次數等於輸入的二進位數字長度後,便不再執行迴圈 r = int(N%10) #設定一個變數r,使其成為當前二進位數最右邊的數的值 A = A + (2**K)*r #計算當前所得到的數的總和 N = N/10 #將當前二進位數最右邊的數值去掉 K = K + 1 #執行次數加1 str(A) #將最後的答案轉換成字串形式 return A class HW02: def ch2(self): ''' 請將你計算出來的答案填入以下變數,助教會寫程式自動批改。 Ch2P2_19a = "xxx" 意思是 Ch2 : 第二章 P2_19a: 第二章結尾處的 PRACTICE SET 段落處的 Problems 第 P2-19 題的 a 小題 "xxx" : 你要填入你的答案在 xxx 這裡。 ''' #作業 2. 課本 Ch2. P2.19 self.Ch2P2_19a = "10" self.Ch2P2_19b = "17" self.Ch2P2_19c = "6" self.Ch2P2_19d = "8" #作業 3. 課本 Ch2. P2.20 self.Ch2P2_20a = "14" self.Ch2P2_20b = "8" self.Ch2P2_20c = "13" self.Ch2P2_20d = "4" #作業 4. 課本 Ch2. P2.22 self.Ch2P2_22a = "00010001 11101010 00100010 00001110" self.Ch2P2_22b = "01101110 00001110 00111000 01001110" self.Ch2P2_22c = "00001110 00111000 11101010 00111000" self.Ch2P2_22d = "00011000 00111000 00001101 00001011" def ch3(self): ''' 請將你計算出來的答案填入以下變數,助教會寫程式自動批改。 Ch3P3_28a = "xxx" 意思是 Ch3 : 第三章 P3_28a: 第三章結尾處的 PRACTICE SET 段落處的 Problems 第 P3-28 題的 a 小題 "xxx" : 你要填入你的答案在 xxx 這裡。 ''' #作業 5. 課本 Ch3. P3.28 self.Ch3P3_28a = "234" self.Ch3P3_28b = "overflow" self.Ch3P3_28c = "874" self.Ch3P3_28d = "888" #作業 6. 課本 Ch3. P3.30 self.Ch3P3_30a = "234" self.Ch3P3_30b = "overflow" self.Ch3P3_30c = "875" self.Ch3P3_30d = "889" if __name__ == '__main__': #程式進入點,程式由此行開始執行。以下示範助教的批改程式。 checkHW02 = HW02() checkHW02.ch2() if checkHW02.Ch2P2_19a == "10": #10 是這題的正解。此行檢查這題的答案。 print("Ch2P2_19a:{0}".format("Correct!")) else: print("Ch2P2_19a:{0}".format("Incorrect!"))
[ "32182281+gordon0813@users.noreply.github.com" ]
32182281+gordon0813@users.noreply.github.com
6cda6f690fe6f4d19b954e3827b4044a8fd710c4
b22492fd331ee97d5c8853687a390b3adb92dd49
/freemt_utils/switch_to.py
440a1cbb70961cc6e76cdc6fd97ebcfba54631b6
[ "MIT" ]
permissive
ffreemt/freemt-utils
3ea6af7f4bf8800b1be7ec51e05b811710b20907
25bf192033235bb783005795f8c0bcdd8a79610f
refs/heads/master
2021-07-18T18:44:33.907753
2021-02-06T16:52:46
2021-02-06T16:52:46
240,441,691
0
0
null
null
null
null
UTF-8
Python
false
false
689
py
'''Switch to path contextmanager (with). http://ralsina.me/weblog/posts/BB963.html ''' import os import pathlib from contextlib import contextmanager # from loguru import logger from logzero import logger @contextmanager def switch_to(path=pathlib.Path().home()): '''Switch to path. with switch_to(path): pass # do stuff ''' old_dir = os.getcwd() try: path = pathlib.Path(path) except Exception as exc: logger.error(exc) raise if not path.is_dir(): # pragma: no cover msg = '*{}* is not a directory or does not exist.' raise Exception(msg.format(path)) os.chdir(path) yield os.chdir(old_dir)
[ "yucongo+fmt@gmail.com" ]
yucongo+fmt@gmail.com
a0220857a6290eef53772e9bf27c01b76875dd22
db60c5c7f5d2df88b4f6bda1bd27f8a928a90e37
/skip_gram.py
bbc08bc05a2d1f4da32dcf5744a172718c96f336
[]
no_license
masatana/skip_gram
cadd7240cff80e5f5ab7c1502f800b1f38ff9977
0201d4e04623d3b606aad7cef828e4dab11686b6
refs/heads/master
2020-04-04T14:10:53.213857
2015-11-22T01:21:09
2015-11-22T01:21:09
21,228,687
2
1
null
null
null
null
UTF-8
Python
false
false
1,167
py
#!/usr/bin/env python # -*- coding: utf-8 -*- #from __future__ import print_function, unicode_literals from itertools import izip, combinations class SkipGram(object): def __init__(self, text, skip = 2, n = 2): self._text_list = text.strip().split() self._n = n self._skip = skip self._mask = tuple(i * self._skip for i in xrange(self._n)) @property def skip_grams(self): for selector in combinations(xrange(len(self._text_list)), self._n): if any(a_i - b_i - selector[0] > 1 for a_i, b_i in izip(selector, self._mask)): continue yield tuple(self._text_list[i] for i in selector) @property def old_skip_grams(self): for i in xrange(len(self._text_list) - self._n + 1): for j in xrange(i + 1, min(i + self._n + self._skip, len(self._text_list))): yield (self._text_list[i], self._text_list[j],) def __repr__(self): return """text_list:{0}, n:{1}, skip:{2}, skip_gram_token_list:{3}""".format( repr(self._text_list), repr(self._n), repr(self._skip), repr(self._skip_gram_token_list))
[ "plaza.tumbling@gmail.com" ]
plaza.tumbling@gmail.com
0392ced1a79a18b554961d4d5e4b1cda156bd6a9
2ae24d0c6d91df960a2ca68a0b7a754a69d4fe18
/web/exmr/apps/coins/migrations/0084_ethereumtoken_extra_message.py
07b03a46777e400e1b7834135c1ec300372ffd99
[]
no_license
exmrcoin/project-gcps.io
2fc2a0a207ce1282d616a8a680aef938fbcf5352
c0071e63406845a5f3dbbe33ae65673cacc271f8
refs/heads/master
2023-01-04T02:08:47.893847
2020-10-29T17:03:34
2020-10-29T17:03:34
121,253,614
0
1
null
null
null
null
UTF-8
Python
false
false
421
py
# Generated by Django 2.0.2 on 2019-03-26 12:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coins', '0083_auto_20190326_1115'), ] operations = [ migrations.AddField( model_name='ethereumtoken', name='extra_message', field=models.CharField(blank=True, default='', max_length=512), ), ]
[ "pnija@gmail.com" ]
pnija@gmail.com
00eb32bd912e803f84cf622828fa8149b6af372c
1907504f5e426dac460dc3fb406cdd8b27da37fb
/funding/portal/models/employeeinfo.py
6719a564cc88cad620fcd22b69a30e3908f51a18
[]
no_license
Gurumonish23/project
010f0c79f10afc4d07ea37a519cda2b7494d9cbb
7d21a89929b628cfe267eff4e5694603b47520a7
refs/heads/master
2023-04-26T22:58:02.660157
2021-06-04T13:48:12
2021-06-04T13:48:12
364,917,755
0
0
null
2021-06-04T13:40:00
2021-05-06T13:20:44
CSS
UTF-8
Python
false
false
797
py
from django.db import models from django.core.validators import MinLengthValidator class Employee(models.Model): Empname=models.CharField(max_length=50,null=True) Empdesg=models.CharField(max_length=50,null=True) Empphone=models.CharField(max_length=50,null=True) Empmail=models.EmailField(max_length=50,null=True) Emppassword=models.CharField(max_length=50,null=True) Empconfirmpassword=models.CharField(max_length=50,null=True) Univmail=models.EmailField(max_length=50,null=True) def __str__(self): return self.Empname def register(self): self.save() return True @staticmethod def get_employee_by_email(Empmail): try: return Employee.objects.get(Empmail=Empmail) except: return False
[ "gurumonish23@gmail.com" ]
gurumonish23@gmail.com
f74d6fe3ef3b822215fdcdc3684dd366bbd82b04
b2e61ce08817220358a2d93f2100eee11a83c268
/histo_sf_analysis.py
834116a30a28abc36d04ad634479c46ee3e5de98
[]
no_license
scarpma/sf-gpu
011306fa35530bc3d8761d30611430d809b0acce
890eb29d51c48959f923b9a7c8e149e0dc005ad3
refs/heads/main
2023-05-09T04:52:03.543859
2021-06-07T18:03:20
2021-06-07T18:03:20
373,588,841
0
0
null
null
null
null
UTF-8
Python
false
false
12,354
py
#!/usr/bin/env python # coding: utf-8 import os import os.path import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from params import * import glob import os.path as osp dict3d = { 'x2': 1,'y2': 2,'z2': 3,'xy': 4,'yz': 5, 'xz': 6,'x4': 7,'y4': 8,'z4': 9,'x2y2': 10, 'y2z2': 11,'x2z2': 12,'x6': 13,'x6': 14, 'x6': 15,'x8': 16,'x8': 17,'x8': 18, 'x10': 19,'x10': 20,'x10': 21} dict1d = { 'x2': 1,'x4': 2,'x6': 3,'x8': 4, 'x10': 5,'x12': 6} def compute_sf_mean(paths): assert len(paths) >= 1 for ii, fl in enumerate(paths): print('read {}'.format(paths[ii]), flush=True) if ii == 0: sfg = np.loadtxt(fl) else: temp = np.loadtxt(fl) assert all(temp[:,0] == sfg[:,0]) sfg[:,1:] = sfg[:,1:] + temp[:,1:] sfg[:,1:] = sfg[:,1:] / len(paths) return sfg ## # COMPUTE FLATNESS ## ## ftg = np.zeros(shape=(sfg.shape[0], sfg.shape[1]-1)) ## ftg[:,0] = sfg[:,0] ## for ii in range(1, sfg.shape[1]-1): ## ftg[:,ii] = sfg[:,ii+1] / (sfg[:,1])**(ii+1) ## ## ftr = np.zeros(shape=(sfr.shape[0], sfr.shape[1]-1)) ## ftr[:,0] = sfr[:,0] ## for ii in range(1, sfg.shape[1]-1): ## ftr[:,ii] = sfr[:,ii+1] / (sfr[:,1])**(ii+1) ## ## ## ## # COMPUTE LOG DERIVATIVES ESS ## ## dlg_ess = np.zeros(shape=(dlg.shape[0], dlg.shape[1]-1)) ## dlg_ess[:,0] = dlg[:,0] ## for ii in range(1, sfg.shape[1]-1): ## dlg_ess[:,ii] = dlg[:,ii+1] / dlg[:,1] ## ## dlr_ess = np.zeros(shape=(dlr.shape[0], dlr.shape[1]-1)) ## dlr_ess[:,0] = dlr[:,0] ## for ii in range(1, sfg.shape[1]-1): ## dlr_ess[:,ii] = dlr[:,ii+1] / dlr[:,1] def compute_pdf(paths): assert len(paths) >= 1 for ii, fl in enumerate(paths): print('read {}'.format(paths[ii]), flush=True) temp = np.loadtxt(fl) if ii == 0: vgx = temp[:,np.array([0,1])] vgy = temp[:,np.array([0,2])] vgz = temp[:,np.array([0,3])] agx = temp[:,np.array([4,5])] agy = temp[:,np.array([4,6])] agz = temp[:,np.array([4,7])] else: assert all(temp[:,0] == vgx[:,0]), 'different bin for velo' assert all(temp[:,4] == agx[:,0]), 'different bin for acce' assert all(temp[:,0] == vgy[:,0]), 'different bin for velo' assert all(temp[:,4] == agy[:,0]), 'different bin for acce' assert all(temp[:,0] == vgz[:,0]), 'different bin for velo' assert all(temp[:,4] == agz[:,0]), 'different bin for acce' vgx[:,1] = vgx[:,1] + temp[:,1] agx[:,1] = agx[:,1] + temp[:,5] vgy[:,1] = vgy[:,1] + temp[:,2] agy[:,1] = agy[:,1] + temp[:,6] vgz[:,1] = vgz[:,1] + temp[:,3] agz[:,1] = agz[:,1] + temp[:,7] # SUM HISTOS AND COMPUTE STANDARDIZED PDF db_vex = vgx[1,0] - vgx[0,0] db_acx = agx[1,0] - agx[0,0] v_normx = np.sum(vgx[:,1]) * db_vex a_normx = np.sum(agx[:,1]) * db_acx db_vey = vgy[1,0] - vgy[0,0] db_acy = agy[1,0] - agy[0,0] v_normy = np.sum(vgy[:,1]) * db_vey a_normy = np.sum(agy[:,1]) * db_acy db_vez = vgz[1,0] - vgz[0,0] db_acz = agz[1,0] - agz[0,0] v_normz = np.sum(vgz[:,1]) * db_vez a_normz = np.sum(agz[:,1]) * db_acz # normalize from histogram to density vgx[:,1] = vgx[:,1] / v_normx agx[:,1] = agx[:,1] / a_normx vgy[:,1] = vgy[:,1] / v_normy agy[:,1] = agy[:,1] / a_normy vgz[:,1] = vgz[:,1] / v_normz agz[:,1] = agz[:,1] / a_normz # standardize mean_vx = 0. std_vx = 0. mean_ax = 0. std_ax = 0. mean_vy = 0. std_vy = 0. mean_ay = 0. std_ay = 0. mean_vz = 0. std_vz = 0. mean_az = 0. std_az = 0. for jj in range(vgx.shape[0]): mean_vx += db_vex * vgx[jj,1]*(vgx[jj,0] + db_vex/2) mean_ax += db_acx * agx[jj,1]*(agx[jj,0] + db_acx/2) mean_vy += db_vey * vgy[jj,1]*(vgy[jj,0] + db_vey/2) mean_ay += db_acy * agy[jj,1]*(agy[jj,0] + db_acy/2) mean_vz += db_vez * vgz[jj,1]*(vgz[jj,0] + db_vez/2) mean_az += db_acz * agz[jj,1]*(agz[jj,0] + db_acz/2) for jj in range(vgx.shape[0]): std_vx += db_vex * vgx[jj,1]*((vgx[jj,0] + db_vex/2) - mean_vx)**2. std_ax += db_acx * agx[jj,1]*((agx[jj,0] + db_acx/2) - mean_ax)**2. std_vy += db_vey * vgy[jj,1]*((vgy[jj,0] + db_vey/2) - mean_vy)**2. std_ay += db_acy * agy[jj,1]*((agy[jj,0] + db_acy/2) - mean_ay)**2. std_vz += db_vez * vgz[jj,1]*((vgz[jj,0] + db_vez/2) - mean_vz)**2. std_az += db_acz * agz[jj,1]*((agz[jj,0] + db_acz/2) - mean_az)**2. std_vx = np.sqrt(std_vx) std_ax = np.sqrt(std_ax) std_vy = np.sqrt(std_vy) std_ay = np.sqrt(std_ay) std_vz = np.sqrt(std_vz) std_az = np.sqrt(std_az) vg_stdx = np.copy(vgx) ag_stdx = np.copy(agx) vg_stdy = np.copy(vgy) ag_stdy = np.copy(agy) vg_stdz = np.copy(vgz) ag_stdz = np.copy(agz) vg_stdx[:,0] = (vg_stdx[:,0] - mean_vx) / std_vx vg_stdx[:,1] = vg_stdx[:,1] * std_vx ag_stdx[:,0] = (ag_stdx[:,0] - mean_ax) / std_ax ag_stdx[:,1] = ag_stdx[:,1] * std_ax vg_stdy[:,0] = (vg_stdy[:,0] - mean_vy) / std_vy vg_stdy[:,1] = vg_stdy[:,1] * std_vy ag_stdy[:,0] = (ag_stdy[:,0] - mean_ay) / std_ay ag_stdy[:,1] = ag_stdy[:,1] * std_ay vg_stdz[:,0] = (vg_stdz[:,0] - mean_vz) / std_vz vg_stdz[:,1] = vg_stdz[:,1] * std_vz ag_stdz[:,0] = (ag_stdz[:,0] - mean_az) / std_az ag_stdz[:,1] = ag_stdz[:,1] * std_az pdfsDict = { 'binvx':vgx[:,0], 'pdfvx':vgx[:,1], 'binax':agx[:,0], 'pdfax':agx[:,1], 'binvx_std':vg_stdx[:,0], 'pdfvx_std':vg_stdx[:,1], 'binax_std':ag_stdx[:,0], 'pdfax_std':ag_stdx[:,1], 'pdfay_std':ag_stdy[:,1], 'binvy':vgy[:,0], 'pdfvy':vgy[:,1], 'binay':agy[:,0], 'pdfay':agy[:,1], 'binvy_std':vg_stdy[:,0], 'pdfvy_std':vg_stdy[:,1], 'binay_std':ag_stdy[:,0], 'pdfay_std':ag_stdy[:,1], 'binvz':vgz[:,0], 'pdfvz':vgz[:,1], 'binaz':agz[:,0], 'pdfaz':agz[:,1], 'binvz_std':vg_stdz[:,0], 'pdfvz_std':vg_stdz[:,1], 'binaz_std':ag_stdz[:,0], 'pdfaz_std':ag_stdz[:,1], } return pdfsDict def save_pdfDict(pdfDict, path, train=None): train_str = '' if train is None else '_train{}'.format(train) a = pdfDict pdfvx = np.stack((a['binvx'], a['pdfvx'])).T filename = 'pdfvx{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfvx) pdfax = np.stack((a['binax'], a['pdfax'])).T filename = 'pdfax{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfax) pdfvx_std = np.stack((a['binvx_std'], a['pdfvx_std'])).T filename = 'pdfvx_std{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfvx_std) pdfax_std = np.stack((a['binax_std'], a['pdfax_std'])).T filename = 'pdfax_std{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfax_std) pdfvy = np.stack((a['binvy'], a['pdfvy'])).T filename = 'pdfvy{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfvy) pdfay = np.stack((a['binay'], a['pdfay'])).T filename = 'pdfay{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfay) pdfvy_std = np.stack((a['binvy_std'], a['pdfvy_std'])).T filename = 'pdfvy_std{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfvy_std) pdfay_std = np.stack((a['binay_std'], a['pdfay_std'])).T filename = 'pdfay_std{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfay_std) pdfvz = np.stack((a['binvz'], a['pdfvz'])).T filename = 'pdfvz{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfvz) pdfaz = np.stack((a['binaz'], a['pdfaz'])).T filename = 'pdfaz{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfaz) pdfvz_std = np.stack((a['binvz_std'], a['pdfvz_std'])).T filename = 'pdfvz_std{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfvz_std) pdfaz_std = np.stack((a['binaz_std'], a['pdfaz_std'])).T filename = 'pdfaz_std{}.txt'.format(train_str) np.savetxt(osp.join(path, filename), pdfaz_std) return import argparse parser = argparse.ArgumentParser() parser.add_argument( '-path', type=str, required=True, help='path of the directory with files to analyze' ) parser.add_argument( '-different_trainings', action='store_true', default=False, help='analyze each single train and also all together' ) args = parser.parse_args() path = args.path different_trainings = args.different_trainings # FIND pdf.DAT FILES AND COMPUTE PDF FROM HISTO print('----- compute pdf -----') if different_trainings: read_file_pdf_train1 = glob.glob(osp.join(path, f'pdf_train1_*.dat')) read_file_pdf_train2 = glob.glob(osp.join(path, f'pdf_train2_*.dat')) read_file_pdf_train3 = glob.glob(osp.join(path, f'pdf_train3_*.dat')) read_file_pdf_train4 = glob.glob(osp.join(path, f'pdf_train4_*.dat')) read_file_pdf_all = glob.glob(osp.join(path, f'pdf_train*_*.dat')) print('each training') pdfDict = compute_pdf(read_file_pdf_train1) save_pdfDict(pdfDict, path, train=1) pdfDict = compute_pdf(read_file_pdf_train2) save_pdfDict(pdfDict, path, train=2) pdfDict = compute_pdf(read_file_pdf_train3) save_pdfDict(pdfDict, path, train=3) pdfDict = compute_pdf(read_file_pdf_train4) save_pdfDict(pdfDict, path, train=4) print('all together') pdfDict = compute_pdf(read_file_pdf_all) save_pdfDict(pdfDict, path, train=None) else: read_file_pdf = glob.glob(osp.join(path, f'pdf_*.dat')) pdfDict = compute_pdf(read_file_pdf) save_pdfDict(pdfDict, path, train=None) # FIND sf.DAT FILES, FOR EACH COMPUTE LOG DERIVATIVES # AND THEN COMPUTE MEAN FOR EACH TRAINING AND AMONG ALL # TRAININGS print('----- compute sf -----') if different_trainings: read_file_sf_train1 = glob.glob(osp.join(path, f'sf_train1_*.dat')) read_file_sf_train2 = glob.glob(osp.join(path, f'sf_train2_*.dat')) read_file_sf_train3 = glob.glob(osp.join(path, f'sf_train3_*.dat')) read_file_sf_train4 = glob.glob(osp.join(path, f'sf_train4_*.dat')) read_file_sf_all = glob.glob(osp.join(path, f'sf_train*_*.dat')) read_file_dl_train1 = glob.glob(osp.join(path, f'sfdl_train1_*.dat')) read_file_dl_train2 = glob.glob(osp.join(path, f'sfdl_train2_*.dat')) read_file_dl_train3 = glob.glob(osp.join(path, f'sfdl_train3_*.dat')) read_file_dl_train4 = glob.glob(osp.join(path, f'sfdl_train4_*.dat')) read_file_dl_all = glob.glob(osp.join(path, f'sfdl_train*_*.dat')) print('each training') sf = compute_sf_mean(read_file_sf_train1) np.savetxt(osp.join(path, 'sf_train1.txt'), sf) dl = compute_sf_mean(read_file_dl_train1) np.savetxt(osp.join(path, 'sfdl_train1.txt'), dl) sf = compute_sf_mean(read_file_sf_train1) np.savetxt(osp.join(path, 'sf_train2.txt'), sf) dl = compute_sf_mean(read_file_dl_train2) np.savetxt(osp.join(path, 'sfdl_train2.txt'), dl) sf = compute_sf_mean(read_file_sf_train3) np.savetxt(osp.join(path, 'sf_train3.txt'), sf) dl = compute_sf_mean(read_file_dl_train3) np.savetxt(osp.join(path, 'sfdl_train3.txt'), dl) sf = compute_sf_mean(read_file_sf_train4) np.savetxt(osp.join(path, 'sf_train4.txt'), sf) dl = compute_sf_mean(read_file_dl_train4) np.savetxt(osp.join(path, 'sfdl_train4.txt'), dl) print('all together') sf = compute_sf_mean(read_file_sf_all) np.savetxt(osp.join(path, 'sf.txt'), sf) dl = compute_sf_mean(read_file_dl_all) np.savetxt(osp.join(path, 'sfdl.txt'), dl) else: read_file_sf = glob.glob(osp.join(path, f'sf_*.dat')) read_file_dl = glob.glob(osp.join(path, f'sfdl_*.dat')) sf = compute_sf_mean(read_file_sf) np.savetxt(osp.join(path, 'sf.txt'), sf) dl = compute_sf_mean(read_file_dl) np.savetxt(osp.join(path, 'sfdl.txt'), dl)
[ "mscarpol@login01.m100.cineca.it" ]
mscarpol@login01.m100.cineca.it
3e2930186e5ad47dd72590b4d7d7b4f12395c0c1
fa8ce7dbb7c2f0d7e7ae58f8bd6273f8d36e6bda
/assign6_2.py
0f5f590645daeb9395ec086008ef64eaada677d7
[]
no_license
dutcjh/learnpython
ec92fabe38df626623f425f98f8d0c7360a78857
cc0dcc6d359420a078e27c0cacb7b26f47402aa0
refs/heads/master
2021-01-12T13:55:28.890985
2016-11-04T04:57:27
2016-11-04T04:57:27
68,922,041
0
0
null
null
null
null
UTF-8
Python
false
false
383
py
s1 = input('Please enter a string of lowercase letters: ') s1 = s1.lower() s2 = s1[0] s3 = '' for i in range(len(s1)-1): if s1[i] <= s1[i + 1]: s2 = s2 + s1[i + 1] else: if len(s3) < len(s2): s3, s2 = s2, s1[i + 1] else: s2 = s1[i + 1] if len(s3) < len(s2): s3 = s2 print('Longest substring in alphabetical order is: '+s3)
[ "dutchenjianhui@163.com" ]
dutchenjianhui@163.com
7385a7e276d2a1af25880ee286f96c96640dfa8c
8ae1a3ae74cd1e1c3431a6c9e84e6bf0d32f4ec2
/src/__init__.py
1e99ff3ad836de50ac5eef37dcb6e5c8937fe5a4
[]
no_license
NonSenseGuy/AutomataEquivalence
28ed9b77774534027c9d527cd55aa36ff729e0f9
de844e69bec8ef3aa90ad248640dc1a6a6a38acd
refs/heads/master
2022-04-12T12:38:51.383855
2020-03-16T04:50:32
2020-03-16T04:50:32
241,241,300
0
0
null
null
null
null
UTF-8
Python
false
false
65
py
from Automata import Automata from Equivalence import Equivalence
[ "alejobarre9@gmail.com" ]
alejobarre9@gmail.com
2a18f5bc5e4153611649aef73819909e34b874e6
90b2816a2f2ad8f257413a33d1cf2e973e86567a
/classview/views.py
535d7a87cbea9b8978ccbd4bee3e77fdc7d53615
[]
no_license
ehananel-lirf23/demo
843bd766f4d7d1ba8a0e2058af283e7e57b9cdc2
ecccb7146c3fdc6a0a4d10127900e2b15e45ce73
refs/heads/master
2023-04-27T03:57:37.024538
2021-04-16T15:11:04
2021-04-16T15:11:04
366,403,233
0
0
null
null
null
null
UTF-8
Python
false
false
1,684
py
from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View # generic通用类 导入View from django.http.response import HttpResponse # GET /template_demo/ def template_demo(request): """演示模板加载""" context = { "name": "jack", "a_list": [1, 5, 2, 3], "a_dict": {"age": 25} } # render(参数1 跟 视图函数一样 第一个 须有request) return render(request, "index.html", context=context) # 定义装饰器装饰视图 def my_decorator(view_func): """定义装饰器装饰视图""" def wrapper(request, *args, **kwargs): print('装饰器被调用了') print("请求的方法:%s" % request.method) # 调用被装饰的视图 return view_func(request, *args, **kwargs) return wrapper # method_decorator(要被转换装饰器, name=要装饰的方法) 如果写在类的上面时,name参数必须指定,如果写在内部方法上时,name不需要指定 @method_decorator(my_decorator, name='get') # 指定get 就只是get实例方法 会被装饰 class DemoView(View): """类视图,继承于 generic通用类的View类""" # 处理get, 注意固定get固定写法 除非 重写 里面的定义 # #直接装饰到实例方法上 相当于 指定对哪个 视图函数装饰 @method_decorator(my_decorator) def get(self, request): # request 必须 相当于函数视图 """get请求业务逻辑""" return HttpResponse("get请求业务逻辑") def post(self, request): """post请求业务逻辑""" return HttpResponse("post请求业务逻辑")
[ "jilun82415819@126.com" ]
jilun82415819@126.com
752ad467ffb6a2466dea241250c87667959509b9
9fd904fd0886841aba665c8dbc9a03a15083ada4
/thesis/9 - Semantic Change/2.3 - Mixed Linear Models.py
2b3f7a4412829b927c237146bc9d69756c25184d
[ "MIT" ]
permissive
lucasrettenmeier/word-embedding-stability
ccc8c673ec13fa3855c71706eb3228fc2f2ffd9f
d7a93201a6b2fd85cbf52681227829323edb9ef4
refs/heads/master
2022-10-24T05:35:52.501562
2020-06-16T11:30:55
2020-06-16T11:30:55
241,602,115
1
0
null
null
null
null
UTF-8
Python
false
false
2,107
py
#------------------------------------------------------------------------------------------------------------------- # Packages & Settings #------------------------------------------------------------------------------------------------------------------- # General packages import time import sys import os import datetime from glob import glob import shutil # Math and data structure packages import numpy as np from scipy import stats import math import matplotlib.pyplot as plt # Writing Output import pickle # Regression from statsmodels.regression import mixed_linear_model #------------------------------------------------------------------------------------------------------------------- # Loading own Modules #------------------------------------------------------------------------------------------------------------------- sys.path.append('/home/rettenls/code') from lib.model import Model from lib.trafo import Transformation from lib.eval import print_nn_word, get_nn_list, get_cosine_similarity, get_pip_norm from lib.score import evaluate_analogy from lib.operations import align, avg from lib.util import get_filename #------------------------------------------------------------------------------------------------------------------- # Experiments #------------------------------------------------------------------------------------------------------------------- ana_folder = '/home/rettenls/data/experiments/coha/analysis/' models = ['word2vec']#, 'fasttext']#, 'glove'] max_size = 32 sizes = [32] result = dict() for model in models: for data_type in ['genuine', 'random']: res = list() for size in sizes: data = np.load(open(ana_folder + model + '_' + data_type + '_{:04d}'.format(size), 'rb')) words = data['words'] frequencies = data['frequencies'] displacements = data['displacements'] md = mixed_linear_model.MixedLM(endog = displacements, exog = frequencies, groups = words) rs = md.fit() print(rs.summary()) res.append(rs.params[0]) print(rs.params) #print(res) #result[model + '_' + data_type] = np.array(res)
[ "rettenls@itssv116.villa-bosch.de" ]
rettenls@itssv116.villa-bosch.de
15534badc5f2a45c70008339d17f24d79f4bde6a
217f4e20976e5491c4675e4c74075be3fe23be3f
/course_4_assessment_1.py
3bc994d3ead166743c46d9c672883d8b9f3e9711
[]
no_license
mayankdawar/Coursera-Python-Classes-and-Inheritance
f4f4915ac5b1726900ff55b02c9f88a1fbe93369
25f4161a12c81ddea8b25313c67831c7b1d4edf1
refs/heads/master
2022-12-28T02:18:24.357674
2020-09-30T20:36:28
2020-09-30T20:36:28
298,378,939
0
1
null
null
null
null
UTF-8
Python
false
false
2,290
py
# Define a class called Bike that accepts a string and a float as input, and assigns those inputs respectively to two instance variables, color and price. Assign to the variable testOne an instance of Bike whose color is blue and whose price is 89.99. Assign to the variable testTwo an instance of Bike whose color is purple and whose price is 25.0. class Bike: def __init__(self,col,pr): self.color = col self.price = pr testOne = Bike('blue',89.99) testTwo = Bike('purple',25.0) # Create a class called AppleBasket whose constructor accepts two inputs: a string representing a color, and a number representing a quantity of apples. The constructor should initialize two instance variables: apple_color and apple_quantity. Write a class method called increase that increases the quantity by 1 each time it is invoked. You should also write a __str__ method for this class that returns a string of the format: "A basket of [quantity goes here] [color goes here] apples." e.g. "A basket of 4 red apples." or "A basket of 50 blue apples." (Writing some test code that creates instances and assigns values to variables may help you solve this problem!) class AppleBasket: def __init__(self, color, qty): self.apple_color = color self.apple_quantity = qty def increase(self): self.apple_quantity += 1 def __str__(self): return 'A basket of {} {} apples.'.format(self.apple_quantity,self.apple_color) # Define a class called BankAccount that accepts the name you want associated with your bank account in a string, and an integer that represents the amount of money in the account. The constructor should initialize two instance variables from those inputs: name and amt. Add a string method so that when you print an instance of BankAccount, you see "Your account, [name goes here], has [start_amt goes here] dollars." Create an instance of this class with "Bob" as the name and 100 as the amount. Save this to the variable t1. class BankAccount: def __init__(self, name, amt): self.name = name self.amt = amt def __str__(self): return 'Your account, {}, has {} dollars.'.format(self.name, self.amt) t1 = BankAccount('Bob',100)
[ "noreply@github.com" ]
mayankdawar.noreply@github.com
eb64ab2304d1c83b2b0c6471d6b578c525830102
dee6f3c1cf3d3a37cb07ce19b46969e9d63113ee
/final.py
7b85bace40251b5f65acde6ce2eac65883db2dee
[]
no_license
Ken2399/326-Group-Project
535eaef6b412c8cbcf24181f4a21492036cc69b1
59cbb9fb7c569f2f933f67c1bd8fab1505562cb6
refs/heads/main
2023-01-11T06:03:34.444536
2020-11-10T19:32:05
2020-11-10T19:32:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,177
py
class Account: """Create an account that will either be used to be a customer or an online retailer. """ def __init__(self, account_type, username, birthday, address, email, password): def change_login_credentials(): """ Purpose: to edit login credentials (update email, chang username, etc. Args: login information. """ class Product: """Creates a product to be listed in the store with the vendor name, a description, and the price""" def __init__(self, desc, price, reviews, inventory_size): def set_product_information(): """Sets the product object with the given name, description, price, and rating""" class Inventory: """Provides a list of all the products in the store with the amount left available for each product""" def __init__(self): def add_inventory(): """Purpose: Add products to inventory. Args: Product(a product object): product that’s being added to the inventory.Quantity(int): quantity of a product. Returns: List of products with newly added values. """ def change_inventory(): """ Removing or editing the inventory. Args: Product(a product object): product that’s being edited. Quantity(int: updated quantity of a product. Returns: An updated list of inventory. """ class Cart: """Calculate final checkout price of the order with the option to add or remove from cart and to add a discount code. """ def __init__(self): def add_to_cart(): """"Adds products from shopping cart Returns: An updated shopping cart """ def remove_from_cart(): """"Removes products from shopping cart Returns: An updated shopping cart """ def cost(discount, shipping, tax): """Determines the checkout price for the order by including the shipping cost and discount Args: discount codes, Shipping cost. Returns: Float of the final checkout price""" def currency_exchange(price): """ Returns the final price of the item in the customer's currency. Args: Original Price, Final price in desired currency."""
[ "noreply@github.com" ]
Ken2399.noreply@github.com
ace417d486a29e19a3f31f74a2d3f72f02ac8ef3
add74ecbd87c711f1e10898f87ffd31bb39cc5d6
/xcp2k/classes/_point37.py
4efe740542537882034ccb5e823d228d616eacff
[]
no_license
superstar54/xcp2k
82071e29613ccf58fc14e684154bb9392d00458b
e8afae2ccb4b777ddd3731fe99f451b56d416a83
refs/heads/master
2021-11-11T21:17:30.292500
2021-11-06T06:31:20
2021-11-06T06:31:20
62,589,715
8
2
null
null
null
null
UTF-8
Python
false
false
396
py
from xcp2k.inputsection import InputSection class _point37(InputSection): def __init__(self): InputSection.__init__(self) self.Type = None self.Atoms = [] self.Weights = [] self.Xyz = None self._name = "POINT" self._keywords = {'Type': 'TYPE', 'Xyz': 'XYZ'} self._repeated_keywords = {'Atoms': 'ATOMS', 'Weights': 'WEIGHTS'}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
7cc7f5f72793ee79f04c03843ccbde6e102f9648
440a2ed74321ad76c47e9dd8c0aba3e9b348ba57
/Practical 4, 5 - Scheduling Algorithms/Shortest Job First.py
1b8d6fb9866b61083e4e338628adb8a850bd9d86
[]
no_license
Capt-Fluffy-Bug/Operating-Systems
69ffd56825137c5d59f2dfa2ce9e38cf6f7bbeac
aa4ab25312dd94a3a043b5fca286633109c49b86
refs/heads/master
2020-04-28T16:49:09.354760
2019-03-27T20:34:08
2019-03-27T20:34:08
175,425,142
0
0
null
null
null
null
UTF-8
Python
false
false
3,478
py
#Shortest Job First scheduling pid = ['p1', 'p2', 'p3', 'p4'] arrival_time = [3, 0, 5, 2] burst_time = [4, 7, 2, 3] wait_time = [0]*len(arrival_time) turnaround_time = [0]*len(arrival_time) def sort_proc(): for i in range(len(arrival_time)): for j in range(len(arrival_time) - i - 1): if(burst_time[j] > burst_time[j+1]): temp = burst_time[j] burst_time[j] = burst_time[j+1] burst_time[j+1] = temp temp = arrival_time[j] arrival_time[j] = arrival_time[j+1] arrival_time[j+1] = temp temp = pid[j] pid[j] = pid[j+1] pid[j+1] = temp def checkArrived(prev): for i in range(len(arrival_time)): if(arrival_time[i] <= prev): continue else: return 0 return 1 def btFCFS(prev): sort_proc() for i in range(len(arrival_time)): wait_time[i] = prev - arrival_time[i] prev = prev + burst_time[i] turnaround_time[i] = burst_time[i] + wait_time[i] def del_Proc(i): del arrival_time[i] del burst_time[i] del pid[i] def SJF(): prev = min(arrival_time) sort_proc() tempPID = pid.copy() tempARR = arrival_time.copy() tempBT = burst_time.copy() while(len(arrival_time) != 0): if(checkArrived(prev)): btFCFS(prev) return tempPID, tempARR, tempBT for i in range(len(arrival_time)): if(arrival_time[i] > prev): j = i while(arrival_time[j] > prev and j < len(arrival_time)): j += 1 if(arrival_time[j] <= prev): wait_time[j] = prev - arrival_time[j] prev = prev + burst_time[j] del_Proc(j) elif(arrival_time[i] <= prev): wait_time[i] = prev - arrival_time[i] del_Proc(i) else: k = min(arrival_time) while(prev < k): prev = prev + 1 if(checkArrived(prev)): btFCFS(prev) return tempPID, tempARR, tempBT def findAvgTime(tempPID, tempARR, tempBT): total_wt = 0 total_tat = 0 # displaying process details print("The table sorted according to burst time:\n") print("Process \t Arrival Time \t Burst Time \t Waiting Time \t Turnaround Time \t") for i in range(len(tempPID)): print(str(tempPID[i]) + "\t\t\t\t" + str(tempARR[i]) + "\t\t\t\t" + str(tempBT[i]) + "\t\t\t\t" + str(wait_time[i]) + "\t\t\t\t" + str(turnaround_time[i])) # calculating total waiting time and total turnaround time print("\nAverage waiting time: " + str(sum(wait_time)/len(tempPID))) print("Average turnaround time: " + str(sum(turnaround_time)/len(tempPID))) if __name__ == '__main__': tempPID, tempARR, tempBT = SJF() findAvgTime(tempPID, tempARR, tempBT) ''' EXAMPLE: PROCESS-ID ARRIVAL-TIME BURST-TIME P1 3 4 P2 0 7 P3 5 2 P4 2 3 '''
[ "noreply@github.com" ]
Capt-Fluffy-Bug.noreply@github.com
788d59a8171bce6f978a1d3747f440fc3ea82f42
68a0da10de8f4c3c886ce3dbb701dc9f7986fd13
/capstone-master/Python/venv/bin/f2py
dfbfca6b1445560a0823740599c0ecb127ec3128
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hyojinee/Capstone_Kiosk
18502d28b5470c3ef495952790d3752cee8d787c
23e96c4f0dc397e3daa53e4325c00efa5e39e535
refs/heads/master
2023-01-25T04:49:55.670519
2020-11-29T06:26:20
2020-11-29T06:26:20
316,875,793
0
0
null
null
null
null
UTF-8
Python
false
false
248
#!/home/os/PycharmProjects/pymouse/venv/bin/python # -*- coding: utf-8 -*- import re import sys from numpy.f2py.f2py2e import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "gywls0136@naver.com" ]
gywls0136@naver.com
187e77784e4fb6d6faeec279f8d0263e9ea8a61c
080c13cd91a073457bd9eddc2a3d13fc2e0e56ae
/MY_REPOS/awesome-4-new-developers/tensorflow-master/tensorflow/python/keras/saving/utils_v1/export_output.py
38953921695fad04cb716d8eaf24bad5ad5883e9
[ "Apache-2.0" ]
permissive
Portfolio-Projects42/UsefulResourceRepo2.0
1dccc8961a09347f124d3ed7c27c6d73b9806189
75b1e23c757845b5f1894ebe53551a1cf759c6a3
refs/heads/master
2023-08-04T12:23:48.862451
2021-09-15T12:51:35
2021-09-15T12:51:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,044
py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # LINT.IfChange """Classes for different types of export output.""" import abc from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.keras.saving.utils_v1 import ( signature_def_utils as unexported_signature_utils, ) from tensorflow.python.saved_model import signature_def_utils class ExportOutput(object): """Represents an output of a model that can be served. These typically correspond to model heads. """ __metaclass__ = abc.ABCMeta _SEPARATOR_CHAR = "/" @abc.abstractmethod def as_signature_def(self, receiver_tensors): """Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs. Args: receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying input nodes that will be fed. """ pass def _check_output_key(self, key, error_label): # For multi-head models, the key can be a tuple. if isinstance(key, tuple): key = self._SEPARATOR_CHAR.join(key) if not isinstance(key, str): raise ValueError( "{} output key must be a string; got {}.".format(error_label, key) ) return key def _wrap_and_check_outputs( self, outputs, single_output_default_name, error_label=None ): """Wraps raw tensors as dicts and checks type. Note that we create a new dict here so that we can overwrite the keys if necessary. Args: outputs: A `Tensor` or a dict of string to `Tensor`. single_output_default_name: A string key for use in the output dict if the provided `outputs` is a raw tensor. error_label: descriptive string for use in error messages. If none, single_output_default_name will be used. Returns: A dict of tensors Raises: ValueError: if the outputs dict keys are not strings or tuples of strings or the values are not Tensors. """ if not isinstance(outputs, dict): outputs = {single_output_default_name: outputs} output_dict = {} for key, value in outputs.items(): error_name = error_label or single_output_default_name key = self._check_output_key(key, error_name) if not isinstance(value, ops.Tensor): raise ValueError( "{} output value must be a Tensor; got {}.".format( error_name, value ) ) output_dict[key] = value return output_dict class ClassificationOutput(ExportOutput): """Represents the output of a classification head. Either classes or scores or both must be set. The classes `Tensor` must provide string labels, not integer class IDs. If only classes is set, it is interpreted as providing top-k results in descending order. If only scores is set, it is interpreted as providing a score for every class in order of class ID. If both classes and scores are set, they are interpreted as zipped, so each score corresponds to the class at the same index. Clients should not depend on the order of the entries. """ def __init__(self, scores=None, classes=None): """Constructor for `ClassificationOutput`. Args: scores: A float `Tensor` giving scores (sometimes but not always interpretable as probabilities) for each class. May be `None`, but only if `classes` is set. Interpretation varies-- see class doc. classes: A string `Tensor` giving predicted class labels. May be `None`, but only if `scores` is set. Interpretation varies-- see class doc. Raises: ValueError: if neither classes nor scores is set, or one of them is not a `Tensor` with the correct dtype. """ if scores is not None and not ( isinstance(scores, ops.Tensor) and scores.dtype.is_floating ): raise ValueError( "Classification scores must be a float32 Tensor; " "got {}".format(scores) ) if classes is not None and not ( isinstance(classes, ops.Tensor) and dtypes.as_dtype(classes.dtype) == dtypes.string ): raise ValueError( "Classification classes must be a string Tensor; " "got {}".format(classes) ) if scores is None and classes is None: raise ValueError("At least one of scores and classes must be set.") self._scores = scores self._classes = classes @property def scores(self): return self._scores @property def classes(self): return self._classes def as_signature_def(self, receiver_tensors): if len(receiver_tensors) != 1: raise ValueError( "Classification input must be a single string Tensor; " "got {}".format(receiver_tensors) ) (_, examples), = receiver_tensors.items() if dtypes.as_dtype(examples.dtype) != dtypes.string: raise ValueError( "Classification input must be a single string Tensor; " "got {}".format(receiver_tensors) ) return signature_def_utils.classification_signature_def( examples, self.classes, self.scores ) class RegressionOutput(ExportOutput): """Represents the output of a regression head.""" def __init__(self, value): """Constructor for `RegressionOutput`. Args: value: a float `Tensor` giving the predicted values. Required. Raises: ValueError: if the value is not a `Tensor` with dtype tf.float32. """ if not (isinstance(value, ops.Tensor) and value.dtype.is_floating): raise ValueError( "Regression output value must be a float32 Tensor; " "got {}".format(value) ) self._value = value @property def value(self): return self._value def as_signature_def(self, receiver_tensors): if len(receiver_tensors) != 1: raise ValueError( "Regression input must be a single string Tensor; " "got {}".format(receiver_tensors) ) (_, examples), = receiver_tensors.items() if dtypes.as_dtype(examples.dtype) != dtypes.string: raise ValueError( "Regression input must be a single string Tensor; " "got {}".format(receiver_tensors) ) return signature_def_utils.regression_signature_def(examples, self.value) class PredictOutput(ExportOutput): """Represents the output of a generic prediction head. A generic prediction need not be either a classification or a regression. Named outputs must be provided as a dict from string to `Tensor`, """ _SINGLE_OUTPUT_DEFAULT_NAME = "output" def __init__(self, outputs): """Constructor for PredictOutput. Args: outputs: A `Tensor` or a dict of string to `Tensor` representing the predictions. Raises: ValueError: if the outputs is not dict, or any of its keys are not strings, or any of its values are not `Tensor`s. """ self._outputs = self._wrap_and_check_outputs( outputs, self._SINGLE_OUTPUT_DEFAULT_NAME, error_label="Prediction" ) @property def outputs(self): return self._outputs def as_signature_def(self, receiver_tensors): return signature_def_utils.predict_signature_def(receiver_tensors, self.outputs) class _SupervisedOutput(ExportOutput): """Represents the output of a supervised training or eval process.""" __metaclass__ = abc.ABCMeta LOSS_NAME = "loss" PREDICTIONS_NAME = "predictions" METRICS_NAME = "metrics" METRIC_VALUE_SUFFIX = "value" METRIC_UPDATE_SUFFIX = "update_op" _loss = None _predictions = None _metrics = None def __init__(self, loss=None, predictions=None, metrics=None): """Constructor for SupervisedOutput (ie, Train or Eval output). Args: loss: dict of Tensors or single Tensor representing calculated loss. predictions: dict of Tensors or single Tensor representing model predictions. metrics: Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of `Metric` class. (2) (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op. Raises: ValueError: if any of the outputs' dict keys are not strings or tuples of strings or the values are not Tensors (or Operations in the case of update_op). """ if loss is not None: loss_dict = self._wrap_and_check_outputs(loss, self.LOSS_NAME) self._loss = self._prefix_output_keys(loss_dict, self.LOSS_NAME) if predictions is not None: pred_dict = self._wrap_and_check_outputs(predictions, self.PREDICTIONS_NAME) self._predictions = self._prefix_output_keys( pred_dict, self.PREDICTIONS_NAME ) if metrics is not None: self._metrics = self._wrap_and_check_metrics(metrics) def _prefix_output_keys(self, output_dict, output_name): """Prepend output_name to the output_dict keys if it doesn't exist. This produces predictable prefixes for the pre-determined outputs of SupervisedOutput. Args: output_dict: dict of string to Tensor, assumed valid. output_name: prefix string to prepend to existing keys. Returns: dict with updated keys and existing values. """ new_outputs = {} for key, val in output_dict.items(): key = self._prefix_key(key, output_name) new_outputs[key] = val return new_outputs def _prefix_key(self, key, output_name): if key.find(output_name) != 0: key = output_name + self._SEPARATOR_CHAR + key return key def _wrap_and_check_metrics(self, metrics): """Handle the saving of metrics. Metrics is either a tuple of (value, update_op), or a dict of such tuples. Here, we separate out the tuples and create a dict with names to tensors. Args: metrics: Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of `Metric` class. (2) (metric_value, update_op) tuples, or a single tuple. metric_value must be a Tensor, and update_op must be a Tensor or Op. Returns: dict of output_names to tensors Raises: ValueError: if the dict key is not a string, or the metric values or ops are not tensors. """ if not isinstance(metrics, dict): metrics = {self.METRICS_NAME: metrics} outputs = {} for key, value in metrics.items(): if isinstance(value, tuple): metric_val, metric_op = value else: # value is a keras.Metrics object metric_val = value.result() assert len(value.updates) == 1 # We expect only one update op. metric_op = value.updates[0] key = self._check_output_key(key, self.METRICS_NAME) key = self._prefix_key(key, self.METRICS_NAME) val_name = key + self._SEPARATOR_CHAR + self.METRIC_VALUE_SUFFIX op_name = key + self._SEPARATOR_CHAR + self.METRIC_UPDATE_SUFFIX if not isinstance(metric_val, ops.Tensor): raise ValueError( "{} output value must be a Tensor; got {}.".format(key, metric_val) ) if not ( tensor_util.is_tensor(metric_op) or isinstance(metric_op, ops.Operation) ): raise ValueError( "{} update_op must be a Tensor or Operation; got {}.".format( key, metric_op ) ) # We must wrap any ops (or variables) in a Tensor before export, as the # SignatureDef proto expects tensors only. See b/109740581 metric_op_tensor = metric_op if not isinstance(metric_op, ops.Tensor): with ops.control_dependencies([metric_op]): metric_op_tensor = constant_op.constant( [], name="metric_op_wrapper" ) outputs[val_name] = metric_val outputs[op_name] = metric_op_tensor return outputs @property def loss(self): return self._loss @property def predictions(self): return self._predictions @property def metrics(self): return self._metrics @abc.abstractmethod def _get_signature_def_fn(self): """Returns a function that produces a SignatureDef given desired outputs.""" pass def as_signature_def(self, receiver_tensors): signature_def_fn = self._get_signature_def_fn() return signature_def_fn( receiver_tensors, self.loss, self.predictions, self.metrics ) class TrainOutput(_SupervisedOutput): """Represents the output of a supervised training process. This class generates the appropriate signature def for exporting training output by type-checking and wrapping loss, predictions, and metrics values. """ def _get_signature_def_fn(self): return unexported_signature_utils.supervised_train_signature_def class EvalOutput(_SupervisedOutput): """Represents the output of a supervised eval process. This class generates the appropriate signature def for exporting eval output by type-checking and wrapping loss, predictions, and metrics values. """ def _get_signature_def_fn(self): return unexported_signature_utils.supervised_eval_signature_def # LINT.ThenChange(//tensorflow/python/saved_model/model_utils/export_output.py)
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
c2416af57c3df43d84fbc2b73d6f5e69e6f2ea64
0dae79a26c540cf7b71eed107fc7dd735e67d059
/prepare_data/wider_face_bbox_generate.py
2ec5d4efff96a058116e1837f5ba34a8f3435ba5
[]
no_license
tejabogireddy/MTCNN
0d61772b452b69d91287f304fc1f6842a42fa54b
683e4b95e68b3a396f32545abd8218efdc7b7b64
refs/heads/master
2020-04-29T04:38:20.199117
2019-03-15T16:58:22
2019-03-15T16:58:22
175,853,437
3
0
null
null
null
null
UTF-8
Python
false
false
5,005
py
import os import cv2 import numpy as np from utils.iou import IoU annotation_file = "../Datasets/WIDER_train/wider_origin_anno.txt" image_directory = "../Datasets/WIDER_train/images" positives_directory = "./prepare_data/Data/PNet/Positives" negative_directory = "./prepare_data/Data/PNet/Negatives" partial_directory = "./prepare_data/Data/PNet/Partial" f1 = open(os.path.join("./prepare_data/Data/PNet", 'positive.txt'), 'w') f2 = open(os.path.join("./prepare_data/Data/PNet", 'negative.txt'), 'w') f3 = open(os.path.join("./prepare_data/Data/PNet", 'partial.txt'), 'w') if not os.path.exists(positives_directory): os.mkdir(positives_directory) if not os.path.exists(negative_directory): os.mkdir(negative_directory) if not os.path.exists(partial_directory): os.mkdir(partial_directory) with open(annotation_file, 'r') as f: annotations = f.readlines() negative_image_name, positive_image_name, partial_image_name, total_index = 0, 0, 0, 0 for annotation in annotations: image_path = annotation.strip().split(' ')[0] bbox = list(annotation.strip().split(' ')[1:]) boxes = np.array(bbox, dtype=np.float32).reshape(-1, 4) image = cv2.imread(os.path.join(image_directory, image_path)) image_height, image_width, image_channels = image.shape total_index = total_index + 1 negative_samples, positive_samples, partial_samples = 0, 0, 0 while negative_samples < 50: random_crop_size = np.random.randint(12, min(image_width, image_height) / 2) coordinate_x = np.random.randint(0, image_width - random_crop_size) coordinate_y = np.random.randint(0, image_height - random_crop_size) random_crop_box = np.array([coordinate_x, coordinate_y, coordinate_x + random_crop_size, coordinate_y + random_crop_size]) iou = IoU(random_crop_box, boxes) cropped_im = image[coordinate_y: coordinate_y + random_crop_size, coordinate_x: coordinate_x + random_crop_size, :] resized_im = cv2.resize(cropped_im, (12, 12), interpolation=cv2.INTER_LINEAR) if np.max(iou) < 0.30: save_file = os.path.join(negative_directory, "%s.jpg" % negative_image_name) f2.write(negative_directory + "/" + "%s.jpg" % negative_image_name + ' 0\n') cv2.imwrite(save_file, resized_im) negative_image_name += 1 negative_samples += 1 for box in boxes: box_width = int(box[2] - box[0] + 1) box_height = int(box[3] - box[1] + 1) if max(box_width, box_height) < 40 or box[0] < 0 or box[1] < 0: continue for sample in range(20): crop_size = np.random.randint(int(min(box_width, box_height) * 0.8), np.ceil(1.25 * max(box_width, box_height))) delta_x = np.random.randint(-box_width * 0.2, box_width * 0.2) delta_y = np.random.randint(-box_height * 0.2, box_height * 0.2) crop_box_x1 = int(max(box[0] + box_width/2 - crop_size/2 + delta_x, 0)) crop_box_y1 = int(max(box[1] + box_height/2 - crop_size/2 + delta_y, 0)) crop_box_x2 = int(crop_box_x1 + crop_size) crop_box_y2 = int(crop_box_y1 + crop_size) if crop_box_x2 > image_width or crop_box_y2 > image_height: continue crop_box = np.array([crop_box_x1, crop_box_y1, crop_box_x2, crop_box_y2]) offset_x1 = (box[0] - crop_box_x1) / float(crop_size) offset_y1 = (box[1] - crop_box_y1) / float(crop_size) offset_x2 = (box[2] - crop_box_x2) / float(crop_size) offset_y2 = (box[3] - crop_box_y2) / float(crop_size) cropped_im = image[crop_box_y1:crop_box_y2, crop_box_x1:crop_box_x2, :] resized_im = cv2.resize(cropped_im, (12, 12), interpolation=cv2.INTER_LINEAR) new_box = box.reshape(1, -1) iou = IoU(crop_box, new_box) if iou >= 0.65: save_file = os.path.join(positives_directory, "%s.jpg" % positive_image_name) f1.write(save_file + ' 1 %.2f %.2f %.2f %.2f\n' % (offset_x1, offset_y1, offset_x2, offset_y2)) cv2.imwrite(save_file, resized_im) positive_image_name += 1 elif iou >= 0.40: save_file = os.path.join(partial_directory, "%s.jpg" % partial_image_name) f3.write(save_file + ' -1 %.2f %.2f %.2f %.2f\n' % (offset_x1, offset_y1, offset_x2, offset_y2)) cv2.imwrite(save_file, resized_im) partial_image_name += 1 print("%s images done, positive: %s partial: %s negative: %s" % (total_index, positive_image_name, partial_image_name, negative_image_name)) f1.close() f2.close() f3.close()
[ "bogireddyteja@bogireddytejas-MacBook-Air.local" ]
bogireddyteja@bogireddytejas-MacBook-Air.local
ce1b9b5796c620a6b926399ca78533f7677d97a9
af81d9f0f1346fbd551c67121ad646ccdd070e34
/Quiz_app/forms.py
acc6f92184de8e6cabb8192a67682b778b286c62
[]
no_license
Hammadul92/PCCA
496cea7eff56731ee6e4b8d11c5504649d777bd7
058f579e4f7217ec0dba4744db3539d5f53f5a43
refs/heads/master
2023-01-08T00:43:09.539494
2019-09-17T03:07:39
2019-09-17T03:07:39
191,061,942
0
0
null
2022-12-30T10:28:01
2019-06-09T22:33:28
JavaScript
UTF-8
Python
false
false
2,386
py
from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, TextAreaField, SubmitField, TextField, BooleanField, PasswordField, SelectField, FieldList, RadioField, FormField,HiddenField from wtforms.validators import DataRequired, Email, Length, EqualTo, AnyOf, Regexp, Required, Optional #from wtforms_components import If from flask_wtf.file import FileField, FileRequired, FileAllowed from flask_wtf.recaptcha import RecaptchaField #phone numbers currently accepting canadian format with regexp and can be changed for international format #Can also apply Length(min=10, max=15) format to phone numbers class ContactForm(FlaskForm): email = TextField('Email',validators=[DataRequired("Please enter email."), Email("Please enter valid email address.")]) name = TextField('Name', validators=[DataRequired("Please enter your name.")] ) message = TextAreaField('Message', validators=[DataRequired('Please write down your message.')]) recaptcha = RecaptchaField() submit = SubmitField('Contact') class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired("Please enter your email address."), Email("Please enter valid email address.")]) password = PasswordField('Password', validators=[DataRequired("Please Enter Your Account Password.")]) submit = SubmitField("Login") class PasswordResetForm(FlaskForm): email = StringField('Email:', validators=[DataRequired("Please enter your email address."), Email("Please enter valid email address.")]) submit = SubmitField("Submit") class Password_EmailForm(FlaskForm): password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")]) re_password = PasswordField('Confirm Password', validators=[DataRequired("Please enter a password."), EqualTo('password',message='Password did not match!')]) submit = SubmitField("Submit") class PhotoForm(FlaskForm): title = StringField('Question', validators=[DataRequired('*required')]) description = TextAreaField('Question', validators=[DataRequired('*required')]) photo = FileField('image', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')]) submit = SubmitField('Post') class SearchForm(FlaskForm): search = StringField('search',validators=[DataRequired()]) submit = SubmitField()
[ "hammad@naturallysplendid.com" ]
hammad@naturallysplendid.com
7e635e6a745132a07f89c125874170db99495c5c
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/cH5ce3f4QgnreDW4v_16.py
0920362797049da24362e6f5196a3dc03c839c81
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,413
py
""" Given a list of scrabble tiles (as dictionaries), create a function that outputs the maximum possible score a player can achieve by summing up the total number of points for all the tiles in their hand. Each hand contains 7 scrabble tiles. Here's an example hand: [ { "tile": "N", "score": 1 }, { "tile": "K", "score": 5 }, { "tile": "Z", "score": 10 }, { "tile": "X", "score": 8 }, { "tile": "D", "score": 2 }, { "tile": "A", "score": 1 }, { "tile": "E", "score": 1 } ] The player's `maximum_score` from playing all these tiles would be 1 + 5 + 10 + 8 + 2 + 1 + 1, or 28. ### Examples maximum_score([ { "tile": "N", "score": 1 }, { "tile": "K", "score": 5 }, { "tile": "Z", "score": 10 }, { "tile": "X", "score": 8 }, { "tile": "D", "score": 2 }, { "tile": "A", "score": 1 }, { "tile": "E", "score": 1 } ]) ➞ 28 maximum_score([ { "tile": "B", "score": 2 }, { "tile": "V", "score": 4 }, { "tile": "F", "score": 4 }, { "tile": "U", "score": 1 }, { "tile": "D", "score": 2 }, { "tile": "O", "score": 1 }, { "tile": "U", "score": 1 } ]) ➞ 15 ### Notes Here, each tile is represented as an dictionary with two keys: tile and score. """ def maximum_score(tile_hand): return sum(tile_hand[i].get("score") for i,row in enumerate(tile_hand))
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
9f3b4737b5a4ceb03d0e2f61617e2d606fa1bc26
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2264/60632/299023.py
cda5485f4d7a3635dcca1353ed426c58e683fe78
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
370
py
n = int(input()) if n==9: print('Case 1: 2 4') print('Case 2: 4 1') elif n==229: print('Case 1: 23 1920360960') elif n==20: print('Case 1: 2 1') print('Case 2: 2 380') print('Case 3: 2 780') elif n==112: print('Case 1: 11 2286144') elif n==4: print('Case 1: 2 2') print('Case 2: 2 6') print('Case 3: 9 3628800') else: print(n)
[ "1069583789@qq.com" ]
1069583789@qq.com
6c48a3c58e0b2d4d246e3b66f380cfe5c66e6b14
69bcd6fc026ff34f5c7629a99e8068686154cdce
/scrapy-samples/estate/estate/spiders/qq_cq.py
38024132f9e9fc4d06e04dde1f3e8ab0f75d8f13
[]
no_license
mylove1/code-samples
eb226c552c815e4b8b28b03c0d48a9b9fc205da4
91b10d20121de2270c1a650f37c0d8a80ef90534
refs/heads/master
2021-01-20T16:09:06.689494
2015-09-25T03:17:09
2015-09-25T03:17:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,180
py
# -*- coding: utf-8 -*- from datetime import datetime from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors import LinkExtractor from scrapy.http.request import Request from scrapy.selector import Selector from estate.items import EstateItem class QqCqSpider(CrawlSpider): name = "qq_cq" location = "cq" allowed_domains = [ "cq.house.qq.com" ] start_urls = ( 'http://cq.house.qq.com/2007qp/btyj/CQ.htm', ) rules = ( Rule(LinkExtractor(allow=('/a/\d+/\d+\.htm')), callback='parse_post'), ) # @todo: 需要再梳理页面抓取逻辑 def parse_post(self, response): # from scrapy.shell import inspect_response # inspect_response(response) post_url = response.url if post_url.startswith('http://cq.house.qq.com/a/'): item = EstateItem() item['url'] = post_url item['website'] = self.name item['location'] = self.location item['published_at'] = datetime.strptime(post_url.split('/')[-2], '%Y%m%d') item['html'] = response.body_as_unicode() yield item
[ "g_will@ieqi.com" ]
g_will@ieqi.com
fb7187aafef3920eaf1bf94a6d41854debf30569
23133582d0cfe01fc9cb3e6b2a98d9c7a15918de
/while loop/loop1.py
735a1f69ff0b93d1d18cc7cbe25447d15ebc75dd
[]
no_license
harshitacodes/python
7a895fc025b49b78df480346d0aaee08332e2064
9d69c4f7d35b454cbb7b6fe669263549fb7c0c1a
refs/heads/master
2021-05-17T20:54:43.743824
2020-07-21T13:09:08
2020-07-21T13:09:08
250,948,253
2
0
null
null
null
null
UTF-8
Python
false
false
35
py
i=1 while i<=10: print(i) i=i+1
[ "harshitagupta608@gmail.com" ]
harshitagupta608@gmail.com
59227ed5cf2829796aa635e92186a1a2a0e64681
1375f57f96c4021f8b362ad7fb693210be32eac9
/kubernetes/test/test_v1_probe.py
ba423a0601265e6747938cbf27b6879e628d4e97
[ "Apache-2.0" ]
permissive
dawidfieluba/client-python
92d637354e2f2842f4c2408ed44d9d71d5572606
53e882c920d34fab84c76b9e38eecfed0d265da1
refs/heads/master
2021-12-23T20:13:26.751954
2017-10-06T22:29:14
2017-10-06T22:29:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
793
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_probe import V1Probe class TestV1Probe(unittest.TestCase): """ V1Probe unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1Probe(self): """ Test V1Probe """ model = kubernetes.client.models.v1_probe.V1Probe() if __name__ == '__main__': unittest.main()
[ "mehdy@google.com" ]
mehdy@google.com
9e1e25c8b3711e2c0797380c8cc8eb2f2a1d4dab
4353870b67586f32094753f70a67139106137ca2
/app.py
96591b75569bf9f0a5be1b3de289c37563cdceca
[]
no_license
kozlaczek/pdf-creator
ddf482484a6f57dab336a074718d544bb4421886
d3fc4cfd312d2e2742daefd89a816162d60fab1a
refs/heads/master
2021-01-20T20:56:32.718117
2016-06-14T21:31:52
2016-06-14T21:31:52
61,156,162
0
0
null
null
null
null
UTF-8
Python
false
false
1,035
py
import boto3, json, time from mail import send_email from uuid import uuid4 from creator import create s3 = boto3.resource('s3') def upload_s3(source_file, filename): bucket_name = '167168-koziol' destination_filename = "albums/%s/%s" % (uuid4().hex, filename) print destination_filename bucket = s3.Bucket(bucket_name) bucket.put_object(Key=destination_filename, Body=source_file, ACL='public-read') return destination_filename sqs = boto3.resource('sqs') albumRequests = sqs.get_queue_by_name(QueueName='koziolk-album') bucket_address = 'https://s3.eu-central-1.amazonaws.com/167168-koziol' while True: for albumRequest in albumRequests.receive_messages(): print('processing request ..........') albumData = json.loads(albumRequest.body) pdf = create(albumData) dest = upload_s3(pdf.getvalue(), 'album.pdf') send_email(albumData['sent_to'], 'Your album', 'download here: %s/%s' % ( bucket_address, dest)) albumRequest.delete() print('request processing finished [X]') time.sleep(1)
[ "kamil.koziol@interia.eu" ]
kamil.koziol@interia.eu
c0ad6c64cf14c58b07ee4d8c579623ea36d2c0ec
00fb0fffc171bdecdc3acaedae0bffce2d237afb
/codes_1-50/36_Valid_Sudoku.py
f5734efb42f09abb186c9259a2e55a67fd223625
[]
no_license
GuodongQi/LeetCode
ce43ad7b678ff5e4780f077a03b8b712da8776a3
715e301068432c12b35169728390b64a8d4f83a2
refs/heads/master
2020-04-17T06:23:36.964126
2019-08-06T11:37:27
2019-08-06T11:37:27
166,323,046
0
0
null
null
null
null
UTF-8
Python
false
false
1,620
py
class Solution: def isValidSudoku(self, board: 'List[List[str]]') -> bool: row_num = [[0] * 9 for i in range(9)] # row_num[5][6] means 5 row has number 7 (6 + 1) col_num = [[0] * 9 for i in range(9)] # col_num[5][6] means 5 col has number 7 (6 + 1) square_num = [[[0] * 9 for i in range(3)] for j in range(3)] # square_num[1][1][7] means row0-2 col3-5 has num 8 for r in range(9): for c in range(9): if board[r][c] == '.': continue number = ord(board[r][c]) - ord('1') if row_num[r][number]: return False else: row_num[r][number] += 1 if col_num[c][number]: return False else: col_num[c][number] += 1 if square_num[r // 3][c // 3][number]: return False else: square_num[r // 3][c // 3][number] += 1 return True s = Solution() print(s.isValidSudoku([["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"]]))
[ "guodong_qi@zju.edu.cn" ]
guodong_qi@zju.edu.cn
9da4fc58dc6d1f8748d9918e6c0ecff28546c95c
33ba9809724739095e757f74201b64e17155a245
/DataBase.py
37b9d0955c8dbd2e4bbe28ecf7e889420ca1820f
[]
no_license
Robby-Sodhi/notifyanime.me-V2-Back
9a76361da4ded8a902d4b9b7dee5405aeaec9d8e
229a7b5ada28caf3b292ab2b98e834d7911659ff
refs/heads/main
2023-07-16T02:30:19.390518
2021-08-24T17:41:37
2021-08-24T17:41:37
376,938,853
0
0
null
null
null
null
UTF-8
Python
false
false
4,486
py
import psycopg2 from flask_bcrypt import Bcrypt import copy from constants import host, database, user, password, port class DataBase(): def __init__(self): self.connection = psycopg2.connect(host=host,database=database,user=user,password=password,port=port) def createUser(self, username, password): with self.connection: with self.connection.cursor() as cursor: cursor.execute("INSERT INTO userinfo (username, password) VALUES (%s, %s)", (username, Bcrypt().generate_password_hash(password).decode('utf-8'))) def check_if_username_exists(self, username): with self.connection: with self.connection.cursor() as cursor: cursor.execute("SELECT username FROM userinfo WHERE username=(%s)", (username, )) data = cursor.fetchall() if data: return True #user exists return False #user doesn't exist def fetch_password(self, username): with self.connection: with self.connection.cursor() as cursor: cursor.execute("SELECT password FROM userinfo WHERE username=(%s)", (username, )) data = cursor.fetchall() #if somehow more than one person have that username just automatically fail password if not data or len(data) > 1 or not data[0]: #it is a list of tuples return None return data[0][0] #first tuple first password def verify_user(self, username, password): crypt = Bcrypt() hashed_password = self.fetch_password(username) if (not hashed_password): return False elif crypt.check_password_hash(hashed_password, password): return True else: return False def write_session_to_user(self, username, session_key, expire, device): with self.connection: with self.connection.cursor() as cursor: cursor.execute("INSERT INTO sessions (username, session, expire, device) VALUES ((%s), (%s), (%s), (%s))", (username, session_key, expire, device)) def get_mal_auth_details(self, session_key): with self.connection: with self.connection.cursor() as cursor: dataObject = {"status": False, "accesstoken": None, "refreshtoken": None} username = self.get_username_from_session(session_key) if (not username): return dataObject cursor.execute("SELECT accesstoken, refreshtoken FROM userinfo WHERE username=(%s)", (username, )) data = cursor.fetchall() if not data or len(data) > 1: return dataObject else: try: dataObject2 = copy.deepcopy(dataObject) dataObject2["accesstoken"] = data[0][0] dataObject2["refreshtoken"] = data[0][1] dataObject2["status"] = True except: return dataObject else: return dataObject2 def write_mal_auth_details(self, session_key, access_token, refresh_token): with self.connection: with self.connection.cursor() as cursor: username = self.get_username_from_session(session_key) if (not username): return; else: cursor.execute("UPDATE userinfo SET accesstoken=(%s), refreshtoken=(%s) WHERE username=(%s)", (access_token, refresh_token, username)) def get_username_from_session(self, session_key): with self.connection: with self.connection.cursor() as cursor: cursor.execute("SELECT username FROM sessions WHERE session=(%s)", (session_key, )) data = cursor.fetchall() #add expired checks if not data: return None #it is safe because we assume all session keys are unique return data[0] def is_session_valid(self, session_key): if (self.get_username_from_session(session_key)): return True else: return False def clear_expired(self): with self.connection: with self.connection.cursor() as cursor: cursor.execute("DELETE FROM sessions WHERE expire < now()")
[ "robbysodhi@hotmail.com" ]
robbysodhi@hotmail.com
b98549119e66e1cf437453aedc0c4d8a79bf55b2
9a95bd84374feb6d5c09d3f77390fdae36d4bab4
/gdal2mbtiles/constants.py
cde9d8bf0bc8776c1357e1fa7c05825cab544f0c
[ "Apache-2.0" ]
permissive
trailblazr/gdal2mbtiles
607594d967c29b64fc051e94c16957f88ba98725
b877f4ca06c61ebe616a9ae4c2c7e47f8a9a212c
refs/heads/master
2021-01-14T12:39:41.561988
2012-12-14T19:19:47
2012-12-14T19:19:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,106
py
# -*- coding: utf-8 -*- # Licensed to Ecometrica under one or more contributor license # agreements. See the NOTICE file distributed with this work # for additional information regarding copyright ownership. # Ecometrica licenses this file to you under the Apache # License, Version 2.0 (the "License"); you may not use this # file except in compliance with the License. You may obtain a # copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import (absolute_import, division, print_function, unicode_literals) # EPSG constants EPSG_WEB_MERCATOR = 3785 # Output constants TILE_SIDE = 256 # in pixels # Command-line programs GDALINFO = 'gdalinfo' GDALTRANSLATE = 'gdal_translate' GDALWARP = 'gdalwarp'
[ "simon.law@ecometrica.com" ]
simon.law@ecometrica.com
7742621a2c83333ebb76a7b6d1c8c73e4ac2e1f6
abd47ab16591bacea601c4e0c235759533733571
/tree-predict/treepredict.py
6d66c2e5c0af391843e141748956aa6c6a65d825
[]
no_license
hellochmi/collective-intelligence
81282ceca62159fe88887dc6bca66e6d22bfb4e5
ef9c6c60269d716e08ebbdbcc7134389001a82a0
refs/heads/master
2020-12-02T17:58:12.657814
2017-07-26T16:30:15
2017-07-26T16:30:15
96,455,515
1
1
null
null
null
null
UTF-8
Python
false
false
8,666
py
# treepredict.py # decision tree model my_data=[['slashdot','USA','yes',10,'None'], ['google','france','yes',23,'Premium'], ['digg','USA','yes',24,'Basic'], ['google','UK','no',21,'Premium'], ['(direct)','New Zealand','no',12,'None'], ['(direct)','UK','no',21,'Basic'], ['google','USA','no',24,'Premium'], ['slashdot','France','yes',19,'None'], ['digg','USA','no',18,'None'], ['google','UK','no',19,'None'], ['kiwitobes','UK','no',21,'None'], ['digg','New Zealand','yes',12,'Basic'], ['slashdot','UK','no',21,'None'], ['google','UK','yes',18,'Basic'], ['kiwitobes','France','yes',19,'Basic']] # create tree representation # each node has 5 instance variables which may be set in the initializer # col = column index of criteria to be tested # value is the value that the column must match to get a true result # tb and fb are decisionnodes, which are the next nodes in the tree if # the result is true or false, respectively # results stores a dictionary of results for this branch. this is None # for everything except endpoints class decisionnode: def __init__(self,col=-1,value=None,results=None,tb=None,fb=None): self.col=col self.value=value self.results=results self.tb=tb self.fb=fb # divideset divides the rows into two sets based on the data in a # specific column. this function takes a list of rows, a column number, # and a value to divide into the column. def divideset(rows,column,value): # make a function that tells us if a row is in # the first group (true) or the second group (false) split_function=None if isinstance(value,int) or isinstance(value,float): split_function=lambda row:row[column]>=value else: split_function=lambda row:row[column]==value # divide the rows itno two sets and return them set1=[row for row in rows if split_function(row)] set2=[row for row in rows if not split_function(row)] return(set1,set2) # finds all the different possible outcomes and returns them as a dictionary # of how many times they each appear. used by the other functions to calculate # how mixed a set is def uniquecounts(rows): results={} for row in rows: # the result is the last column r = row[len(row)-1] if r not in results: results[r]=0 results[r]+=1 return results # probability that a randomly placed item will be in the wrong category # calculates the probability of each possible outcome by dividing the # number of times that outcome occurs by the total number of rows in the set def gini(rows): total=len(rows) counts=uniquecounts(rows) imp=0 for k1 in counts: p1=float(counts[k1])/total for k2 in counts: if k1==k2: continue p2=float(counts[k2])/total imp+=p1*p2 return imp # entropy is the sum of p(x)log(p(x)) across all the different possible results # measurement of how different the outcomes are from each other def entropy(rows): from math import log log2=lambda x:log(x)/log(2) results=uniquecounts(rows) # calculate entropy ent=0.0 for r in results.keys(): p=float(results[r])/len(rows) ent = ent-p*log2(p) return ent # recursive function that builds the tree by choosing the best dividing # criteria for the current set def buildtree(rows,scoref=entropy): if len(rows)==0: return decisionnode() current_score=scoref(rows) # set up some variables to track the best criteria best_gain=0.0 best_criteria=None best_sets=None column_count=len(rows[0])-1 for col in range(0,column_count): # generate the list of different values in this column column_values={} for row in rows: column_values[row[col]]=1 # now try dividing the rows up for each value in this column for value in column_values.keys(): (set1,set2)=divideset(rows,col,value) # information gain p=float(len(set1))/len(rows) gain=current_score-p*scoref(set1)-(1-p)*scoref(set2) if gain>best_gain and len(set1)>0 and len(set2)>0: best_gain=gain best_criteria=(col,value) best_sets=(set1,set2) # create the subbranches if best_gain>0: trueBranch=buildtree(best_sets[0]) falseBranch=buildtree(best_sets[1]) return decisionnode(col=best_criteria[0],value=best_criteria[1], tb=trueBranch,fb=falseBranch) else: return decisionnode(results=uniquecounts(rows)) # view the tree in plain text def printtree(tree,indent=''): # is this a leaf node? if tree.results!=None: print str(tree.results) else: # print the criteria print str(tree.col)+':'+str(tree.value)+'? ' # print the branches print indent+'T->', printtree(tree.tb,indent+' ') print indent+'F->', printtree(tree.fb,indent+' ') def getwidth(tree): if tree.tb==None and tree.fb==None: return 1 return getwidth(tree.tb)+getwidth(tree.fb) def getdepth(tree): if tree.tb==None and tree.fb==None: return 0 return max(getdepth(tree.tb),getdepth(tree.fb))+1 from PIL import Image,ImageDraw def drawtree(tree,jpeg='tree.jpg'): w=getwidth(tree)*100 h=getdepth(tree)*100+120 img=Image.new('RGB',(w,h),(255,255,255)) draw=ImageDraw.Draw(img) drawnode(draw,tree,w/2,20) img.save(jpeg,'JPEG') def drawnode(draw,tree,x,y): if tree.results==None: # get the width of each branch w1=getwidth(tree.fb)*100 w2=getwidth(tree.tb)*100 # determine the total space required by this node left=x-(w1+w2)/2 right=x+(w1+w2)/2 # draw the condition string draw.text((x-20,y-10),str(tree.col)+':'+str(tree.value),(0,0,0)) # draw links to the branches draw.line((x,y,left+w1/2,y+100),fill=(255,0,0)) draw.line((x,y,right-w2/2,y+100),fill=(255,0,0)) # draw the branch nodes drawnode(draw,tree.fb,left+w1/2,y+100) drawnode(draw,tree.tb,right-w2/2,y+100) else: txt=' \n'.join(['%s:%d'%v for v in tree.results.items()]) draw.text((x-20,y),txt,(0,0,0)) def classify(observation,tree): if tree.results!=None: return tree.results else: v=observation[tree.col] branch=None if isinstance(v,int) or isinstance(v,float): if v>=tree.value: branch=tree.tb else: branch=tree.fb else: if v==tree.value: branch=tree.tb else: branch=tree.fb return classify(observation,branch) def prune(tree,mingain): # if the branches aren't leaves, then prune them if tree.tb.results==None: prune(tree.tb,mingain) if tree.fb.results==None: prune(tree.fb,mingain) # if both the subbranches are now leaves, see if they should be merged if tree.tb.results!=None and tree.fb.results!=None: # build a combined data set tb,fb=[],[] for v,c in tree.tb.results.items(): tb+=[[v]]*c for v,c in tree.fb.results.items(): fb+=[[v]]*c # test the reduction in entropy delta=entropy(tb+fb)-(entropy(tb)+entropy(fb)/2) if delta<mingain: # merge the branches tree.tb,tree.fb=None,None tree.results=uniquecounts(tb+fb) def mdclassify(observation,tree): if tree.results!=None: return tree.results else: v=observation[tree.col] if v==None: tr,fr=mdclassify(observation,tree.tb),mdclassify(observation,tree.fb) tcount=sum(tr.values()) fcount=sum(fr.values()) tw=float(tcount)/(tcount+fcount) fw=float(fcount)/(tcount+fcount) result={} for k,v in tr.items(): result[k]=v*tw for k,v in fr.items(): result[k]=v*fw return result else: if isinstance(v,int) or isinstance(v,float): if v>=tree.value: branch=tree.tb else: branch=tree.fb else: if v==tree.value: branch=tree.tb else: branch=tree.fb return mdclassify(observation,branch) def variance(rows): if len(rows)==0: return 0 data=[float(row[len(row)-1]) for row in rows] mean=sum(data)/len(data) variance=sum([(d-mean)**2 for d in data])/len(data) return variance
[ "noreply@github.com" ]
hellochmi.noreply@github.com
04ac95a7026ec17d75c777a1ce9d28c32cae7e9a
f1e57b0258b0949bdf8ca0e27c48d2aba1e14286
/gridread.py
9855d9f43c59dd5d85b3513be5d1114f93d97789
[]
no_license
AlessandroMozzato/python_functions
357dd951f8f0c46f635eadc7e978ea0ba0b448fb
754507c8a3eb53ad81b468a33ed076ed8cb01659
refs/heads/master
2021-01-17T02:58:20.541613
2018-01-14T17:52:05
2018-01-14T17:52:05
42,315,628
0
0
null
null
null
null
UTF-8
Python
false
false
1,750
py
#! /usr/bin/env python # -*- coding: utf-8 -*- from scipy.io import netcdf from scipy.io import loadmat import numpy as np from pylab import clf, plot, show, floor, ceil, imshow import matplotlib import matplotlib.pyplot as plt import os import csv import sys import glob sys.path.append('/noc/users/am8e13/Python/python_functions/') from barotropic import * from topostrophy import * from rho import * def grid_read(res): ''' use: grid = grid_read(res) ''' path = "/scratch/general/am8e13/results"+str(res)+"km/grid.nc" file2read = netcdf.NetCDFFile(path,'r') # Bathy is 1 on land and 0 over sea grid = {} for var in ['HFacC','HFacW','HFacS','YC','XC','Z','Y','X','rA','Depth','fCori']: temp = file2read.variables[var] grid[var] = temp[:]*1 file2read.close() area = np.zeros_like(grid['HFacC']) Zp = [10.00, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00, 10.01, 10.03, 10.11, 10.32, 10.80, 11.76, 13.42, 16.04 , 19.82, 24.85, 31.10, 38.42, 46.50, 55.00, 63.50, 71.58, 78.90, 85.15, 90.18, 93.96, 96.58, 98.25, 99.25,100.01,101.33,104.56,111.33,122.83, 139.09,158.94,180.83,203.55,226.50,249.50,272.50,295.50,318.50, 341.50,364.50,387.50,410.50,433.50,456.50 ] for z in range(len(grid['Z'])): area[z,:,:] = grid['HFacC'][z,:,:]*grid['rA']*Zp[z] grid['Area'] = area grid['Zp'] = Zp return grid
[ "mozzatoale@gmail.com" ]
mozzatoale@gmail.com
ad8915a7ae8c2e819356a6367eaf26fbeed1f1fb
dd3b8bd6c9f6f1d9f207678b101eff93b032b0f0
/basis/AbletonLive10.1_MIDIRemoteScripts/APC40/TransportComponent.py
8a9e2628d321bf05754d7c3c3457c883c99cc81b
[]
no_license
jhlax/les
62955f57c33299ebfc4fca8d0482b30ee97adfe7
d865478bf02778e509e61370174a450104d20a28
refs/heads/master
2023-08-17T17:24:44.297302
2019-12-15T08:13:29
2019-12-15T08:13:29
228,120,861
3
0
null
2023-08-03T16:40:44
2019-12-15T03:02:27
Python
UTF-8
Python
false
false
2,239
py
# uncompyle6 version 3.4.1 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10) # [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] # Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/APC40/TransportComponent.py # Compiled at: 2019-04-09 19:23:44 from __future__ import absolute_import, print_function, unicode_literals import Live from _Framework.Control import ButtonControl from _Framework.TransportComponent import TransportComponent as TransportComponentBase from _Framework.SubjectSlot import subject_slot class TransportComponent(TransportComponentBase): u""" TransportComponent that only uses certain buttons if a shift button is pressed """ rec_quantization_button = ButtonControl() def __init__(self, *a, **k): super(TransportComponent, self).__init__(*a, **k) self._last_quant_value = Live.Song.RecordingQuantization.rec_q_eight self._on_quantization_changed.subject = self.song() self._update_quantization_state() self.set_quant_toggle_button = self.rec_quantization_button.set_control_element @rec_quantization_button.pressed def rec_quantization_button(self, value): assert self._last_quant_value != Live.Song.RecordingQuantization.rec_q_no_q quant_value = self.song().midi_recording_quantization if quant_value != Live.Song.RecordingQuantization.rec_q_no_q: self._last_quant_value = quant_value self.song().midi_recording_quantization = Live.Song.RecordingQuantization.rec_q_no_q else: self.song().midi_recording_quantization = self._last_quant_value @subject_slot('midi_recording_quantization') def _on_quantization_changed(self): if self.is_enabled(): self._update_quantization_state() def _update_quantization_state(self): quant_value = self.song().midi_recording_quantization quant_on = quant_value != Live.Song.RecordingQuantization.rec_q_no_q if quant_on: self._last_quant_value = quant_value self.rec_quantization_button.color = 'DefaultButton.On' if quant_on else 'DefaultButton.Off'
[ "jharrington@transcendbg.com" ]
jharrington@transcendbg.com
ca6cba8995470efdeae47abb4ea4f065ee7b7135
2355292f2adb82dad5e76f2e3182ed9f6a149d77
/homeassistant/components/renault/diagnostics.py
f2a4e0f7cba8d1b328e27c422719f44d77ddf233
[ "Apache-2.0" ]
permissive
disrupted/home-assistant
a9c0dafbc57becb2acea8bc7fde5b6b03d4d7cdd
fe5df68eacc3d960dfaa3da79d6d0d7fa83642b0
refs/heads/dev
2022-06-04T20:14:18.021886
2022-04-11T06:52:10
2022-04-11T06:52:10
145,323,344
1
1
Apache-2.0
2022-04-11T06:03:19
2018-08-19T17:20:51
Python
UTF-8
Python
false
false
1,537
py
"""Diagnostics support for Renault.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntry from . import RenaultHub from .const import CONF_KAMEREON_ACCOUNT_ID, DOMAIN TO_REDACT = { CONF_KAMEREON_ACCOUNT_ID, CONF_PASSWORD, CONF_USERNAME, "radioCode", "registrationNumber", "vin", } async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" renault_hub: RenaultHub = hass.data[DOMAIN][entry.entry_id] return { "entry": { "title": entry.title, "data": async_redact_data(entry.data, TO_REDACT), }, "vehicles": [ async_redact_data(vehicle.details.raw_data, TO_REDACT) for vehicle in renault_hub.vehicles.values() ], } async def async_get_device_diagnostics( hass: HomeAssistant, entry: ConfigEntry, device: DeviceEntry ) -> dict: """Return diagnostics for a device.""" renault_hub: RenaultHub = hass.data[DOMAIN][entry.entry_id] vin = next(iter(device.identifiers))[1] return { "details": async_redact_data( renault_hub.vehicles[vin].details.raw_data, TO_REDACT ), }
[ "noreply@github.com" ]
disrupted.noreply@github.com
10903b1880e8aba4685d78639f62b1a9cfaa6425
e33d0d900b0718b46c14d9213c5183ab7400c6a8
/examples/ble_temperature.py
1f4dbd25e3037c3de4017f9e8a5403555aa9dd03
[ "MIT" ]
permissive
baugwo/mpython_ble
ed917ed14d6d90a0bdeaf97bea765b6f40570b36
0648053e47a46d8bc3397cb5f1cd5f2e1743616c
refs/heads/master
2022-12-01T06:15:55.658913
2020-07-28T09:13:37
2020-07-28T09:13:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,341
py
from mpython_ble.gatts import Profile from mpython_ble import UUID from mpython_ble.services import Service from mpython_ble.characteristics import Characteristic from mpython_ble.application import Peripheral import time import struct import random # 实例profile profile = Profile() # 实例Service 环境传感器服务(0x181A) # org.bluetooth.service.environmental_sensing env_sense_service = Service(UUID(0x181A)) # 实例 Characteristic 温度特征(0x2A6E),权限为可读,通知 # org.bluetooth.characteristic.temperature temp_char = Characteristic(UUID(0x2A6E), properties='rn') # 环境传感器服务添加温度特征 env_sense_service.add_characteristics(temp_char) # 将服务添加到profile profile.add_services(env_sense_service) # 实例BLE外设 perip_temp = Peripheral(name=b'mpy_temp', profile=profile, adv_services=profile.services_uuid) # 开始广播 perip_temp.advertise(True) t = 25 i = 0 while True: # Write every second, notify every 10 seconds. time.sleep(1) i = (i + 1) % 10 # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius. # Write the local value, ready for a central to read. perip_temp.attrubute_write(temp_char.value_handle, struct.pack('<h', int(t * 100)), notify=i == 0) # Random walk the temperature. t += random.uniform(-0.5, 0.5)
[ "137513285@qq.com" ]
137513285@qq.com
0821c7824f8c1f33a1eb99cb33826e574eb72f3c
0743d6c9d6ec13b0f5288887c7c4454a9ebad5b4
/app/server/wix_verifications.py
f01687e1aa6a4000a1e50ed22d36c2c1f9cf7306
[ "BSD-2-Clause" ]
permissive
jeffreychan637/fb-cal-tpa
c0c3b8844708decc766316bc09cc20eae861c9e9
d656c71ca1aff3a6abb4e2f24c7101cd2a373f55
refs/heads/master
2020-08-25T07:54:30.616661
2014-08-15T22:10:09
2014-08-15T22:10:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,411
py
"""This file handles parsing the Wix Instance which is key to the security of this app. """ from os import environ from base64 import urlsafe_b64encode, urlsafe_b64decode from hmac import new from hashlib import sha256 from json import loads if "HEROKU" in environ: wix_secret = environ["wix_secret"] else: from secrets import wix_keys wix_secret = wix_keys["secret"] __author__ = "Jeffrey Chan" def instance_parser(instance): """This function parses the Wix instance that comes with every call to the server. If the parse is successful (the instance is from Wix and the permission is set to owner), the call is from a valid source and the request it came with should be performed. The function returns the parsed instance on success and false otherwise. """ try: signature, encoded_json = instance.split(".", 2) encoded_json_with_padding = encoded_json + ('=' * (4 - (len(encoded_json) % 4))) parsed_instance = urlsafe_b64decode( encoded_json_with_padding.encode("utf-8")) hmac_hashed = new(wix_secret, msg=encoded_json, digestmod=sha256).digest() new_signature = urlsafe_b64encode(hmac_hashed).replace("=", "") if (new_signature == signature): return loads(parsed_instance) else: return False except Exception: return False
[ "jeffrey@wix.com" ]
jeffrey@wix.com
26264c8b6e7e4a4840dfff0af82730afe3c620d0
dc15a5613b945d79b9067908b534de51e447a584
/VideoShow.py
23a81d0d62ff59bb09d508fe67cdd29c74c56d0a
[]
no_license
khaledrefai/DeepLearningParking
9e62716c12f6e44040eb24f580d9cc481bec0d0f
8f94e8d001c5410244e9cc2f2205cbdd0fb9d8ec
refs/heads/master
2020-07-27T14:48:00.336217
2019-09-26T09:20:39
2019-09-26T09:20:39
209,129,545
0
0
null
null
null
null
UTF-8
Python
false
false
772
py
""" auther @Eng.Elham albaroudi """ from threading import Thread import cv2 class VideoShow: """ Class that continuously shows a frame using a dedicated thread. """ def __init__(self, frame=None): self.frame = frame self.stopped = False self.counter=0 def start(self): Thread(target=self.show, args=()).start() return self def show(self): while not self.stopped: cv2.imshow("Video", self.frame) cv2.imwrite('./videos/frameset/%d.jpg' % self.counter, self.frame) self.counter+=1 k = cv2.waitKey(1) if k%256 == 27: # ESC pressed self.stopped = True def stop(self): self.stopped = True
[ "khaled.refai@gmail.com" ]
khaled.refai@gmail.com
b5c7c15fb9a5e0517f9b503919e1847efce04ad1
6efe80944d4ca2b67e10cd93663af3af278d1422
/mali.py
405277d1f420c248f208f77d67d4d2d91390bebc
[]
no_license
MikeCMO/malimali-scrape
42a589447fa7ec3f3632ff5c91f701e525a74385
98a73de2f441a41276d7b5e04f83425369e4fc7e
refs/heads/master
2022-08-18T11:40:46.047907
2020-05-18T07:35:43
2020-05-18T07:35:43
264,861,272
0
0
null
null
null
null
UTF-8
Python
false
false
9,241
py
import requests #originalLink = 'http://www.malimalihome.net/residential?status=1&region1=3&region2=39&price=0&price_b=700&price_e=880' originalLink = 'http://www.malimalihome.net/residential?status=1&region1=3&region2=10&price=0&price_b=700&price_e=880&prepage=20&keywords=%E5%90%9B%E8%96%88&page=1' originalPage = True link = originalLink linkList = [originalLink] def getHouses(link): print(link) r = requests.get(link) #print(r.text) import pymongo client = pymongo.MongoClient('localhost', 27017) database = client["mali"] mongoCol = database["ha"] from bs4 import BeautifulSoup soup = BeautifulSoup(r.text,'html.parser') house = soup.find_all('div', class_='result-list') houseDict = {} update = False for x in house: if x.find('div',class_='result-list-l')==None: continue #find website unique id for website contact_number = x.find('div',class_='list-cover') contactA = contact_number.find('a') contactLink = contactA.get('href') houseID = [] for letters in contactLink.split('/'): if letters.isdigit(): houseID.append(letters) iceD = houseID[0] houseDict["Website House ID"] = iceD if mongoCol.find_one({"Website House ID":iceD})!=None: update = True if update ==False: building_name = x.find_all('div', class_='result-list-c-title') for y in building_name: finallyName = y.find('a') houseDict["building name"] = finallyName.text building_size = x.find_all('div',class_='result-list-c-type') for y in building_size: counter = 0 houseType = 0 bs= y.find_all('b') for z in bs: counter+=1 #print(z) #print(counter) if counter == 2: miniCounter = 0 for each in bs: if miniCounter ==0: houseDict['呎'] = each.text miniCounter+=1 elif miniCounter ==1: houseDict["更新日期"] = each.text elif counter ==3: miniCounter = 0 for each in bs: if miniCounter ==0: houseDict["房"] = each.text miniCounter+=1 elif miniCounter ==1: houseDict['呎'] = each.text miniCounter+=1 else: houseDict["更新日期"] = each.text elif counter ==4: miniCounter = 0 for each in bs: if miniCounter ==0: houseDict["房"] = each.text miniCounter+=1 elif miniCounter ==1: houseDict["厅"] = each.text miniCounter+=1 elif miniCounter ==2: houseDict['呎'] = each.text miniCounter+=1 else: houseDict["更新日期"] = each.text #print('\n') building_price = x.find('div',class_='result-list-r-price red') if building_price == None: continue houseDict["万"] = building_price.contents[0].strip() building_description = x.find('div',class_='result-list-c-desc') houseDict["building description"] = building_description.text #contact number is found by get method, find the id for each post and save it to variable #then put it in the changing link for phone number ogLink= 'http://www.malimalihome.net/api/v2/prop-contact?prop_id=&full_contact=1' newLink= ogLink[:56] + iceD + ogLink[56:] import re n = requests.get(newLink) badPhone = n.text badPhone = re.findall('[0-9]{8}',badPhone) bbbtemp = 1 for each in badPhone: houseDict["phone number "+str(bbbtemp)] = each bbbtemp+=1 mongoCol.insert_one(houseDict) #print(houseDict) else: building_name = x.find_all('div', class_='result-list-c-title') for y in building_name: finallyName = y.find('a') mongoCol.update({"Website House ID":iceD},{"$set":{"building name":finallyName.text}}) building_size = x.find_all('div',class_='result-list-c-type') for y in building_size: counter = 0 houseType = 0 bs= y.find_all('b') for z in bs: counter+=1 #print(z) #print(counter) if counter == 2: miniCounter = 0 for each in bs: if miniCounter ==0: mongoCol.update({"Website House ID":iceD},{"$set":{'呎':each.text}}) miniCounter+=1 elif miniCounter ==1: mongoCol.update({"Website House ID":iceD},{"$set":{'更新日期':each.text}}) elif counter ==3: miniCounter = 0 for each in bs: if miniCounter ==0: mongoCol.update({"Website House ID":iceD},{"$set":{'房':each.text}}) miniCounter+=1 elif miniCounter ==1: mongoCol.update({"Website House ID":iceD},{"$set":{'呎':each.text}}) miniCounter+=1 else: mongoCol.update({"Website House ID":iceD},{"$set":{'更新日期':each.text}}) elif counter ==4: miniCounter = 0 for each in bs: if miniCounter ==0: mongoCol.update({"Website House ID":iceD},{"$set":{'房':each.text}}) miniCounter+=1 elif miniCounter ==1: mongoCol.update({"Website House ID":iceD},{"$set":{'厅':each.text}}) miniCounter+=1 elif miniCounter ==2: mongoCol.update({"Website House ID":iceD},{"$set":{'呎':each.text}}) miniCounter+=1 else: mongoCol.update({"Website House ID":iceD},{"$set":{'更新日期':each.text}}) #print('\n') building_price = x.find('div',class_='result-list-r-price red') if building_price == None: continue mongoCol.update({"Website House ID":iceD},{"$set":{'万':building_price.contents[0].strip()}}) building_description = x.find('div',class_='result-list-c-desc') houseDict["building description"] = building_description.text mongoCol.update({"Website House ID":iceD},{"$set":{'building description':building_description.text}}) #contact number is found by get method, find the id for each post and save it to variable #then put it in the changing link for phone number ogLink= 'http://www.malimalihome.net/api/v2/prop-contact?prop_id=&full_contact=1' newLink= ogLink[:56] + iceD + ogLink[56:] import re n = requests.get(newLink) badPhone = n.text badPhone = re.findall('[0-9]{8}',badPhone) bbbtemp = 1 for each in badPhone: houseDict["phone number "+str(bbbtemp)] = each mongoCol.update({"Website House ID":iceD},{"$set":{"phone number "+str(bbbtemp):each}}) bbbtemp+=1 houseDict = {} update = False link = soup.find('ul',class_='pagination') link2 = link.find_all('li') theLink = link2[-1].find('a') if theLink ==None: originalPage= False exit() actualLink = theLink.get('href') for e in linkList: if e == actualLink: break else: linkList.append(actualLink) while originalPage==True: getHouses(linkList[-1])
[ "mikecheongmo@gmail.com" ]
mikecheongmo@gmail.com
6e2dd38836571501f2a515bc9ba0b095f0b42b5b
e2b3f412d04545fecbd025aff8f5d725b449fe92
/python_learn_rep/09_面向对象特性/hm_02使用继承开发动物和狗.py
e88e7f77e5af95e04d3fabf6f80656c7a310db3b
[]
no_license
CANAAN-Tan/Python_learn
d103a9dd2d940ec7c97e7379acc14bc74b6da187
981667eaf70937b64a3f1b7e1d581b2efe5784fe
refs/heads/master
2023-02-17T07:53:23.708528
2021-01-19T03:19:55
2021-01-19T03:19:55
330,611,832
0
0
null
null
null
null
UTF-8
Python
false
false
587
py
class Animal: def eat(self): print("吃---") def drink(self): print("喝---") def run(self): print("跑---") def sleep(self): print("睡---") class Dog(Animal): # def eat(self): # print("吃") # # def drink(self): # print("喝") # # def run(self): # print("跑") # # def sleep(self): # print("睡") def bark(self): print("汪汪叫") # 创建一个对象 - 狗对象 wangcai = Dog() wangcai.eat() wangcai.drink() wangcai.run() wangcai.sleep() wangcai.bark()
[ "18200132258@163.com" ]
18200132258@163.com
9099bbeb2bfe2dd76471b8e077e69bc05b7c317f
6d5545faf2af0a6bb565ad698bb824110b40e121
/WEBAPP/MLmodel/inception_client.py.runfiles/tf_serving/external/org_tensorflow/tensorflow/contrib/distributions/python/ops/relaxed_onehot_categorical.py
9c2fd1e89c34610ae05ea6ba1f048a8b921b6a4f
[ "MIT" ]
permissive
sunsuntianyi/mlWebApp_v2
abb129cd43540b1be51ecc840127d6e40c2151d3
5198685bf4c4e8973988722282e863a8eaeb426f
refs/heads/master
2021-06-23T22:02:38.002145
2020-11-20T02:17:43
2020-11-20T02:17:43
162,194,249
1
0
null
null
null
null
UTF-8
Python
false
false
161
py
/private/var/tmp/_bazel_tianyi/f29d1e61689e4e4b318f483932fff4d0/external/org_tensorflow/tensorflow/contrib/distributions/python/ops/relaxed_onehot_categorical.py
[ "sun.suntianyi@gmail.com" ]
sun.suntianyi@gmail.com
c5eb8b90c623d2853aed64507c397ebd75a8afe1
b1e844c862e28c27853fef67866e19c0d6229b84
/app/zb/socket/trader.py
655eded61173c743207677d69a39d4bca61e35cb
[]
no_license
echo-ray/Exchange
387d6d2fc15cf5357afbcdd06802519584119157
ee9894e1086b486a59a3de7b284801bb8287d880
refs/heads/master
2020-03-19T05:01:44.331122
2018-04-26T04:00:53
2018-04-26T04:00:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,219
py
from threading import Thread import websocket from function import * from model.trader import Trader as td from model.traders import Traders ''' [ Snapshot CHANNEL_ID, [ [ PRICE, COUNT, AMOUNT ], ... ] ] [ Update CHANNEL_ID, [ PRICE, COUNT, AMOUNT ] ] ''' class Trader: def __init__(self, currencypair=['BTC_USDT,ETH_USDT'], targe=['BTC_USDT'], notice=None): self.data = {} self.isReady = False self.currencypair = {} for a in currencypair: self.data.update({a: Traders()}) self.currencypair.update({a.replace('_', '').lower(): a}) self.targe = targe self.notice = notice self.channelId = {} self.restart = True def on_open(self, ws): self.isReady = False for cp in self.currencypair: ws.send(json.dumps({'event': 'addChannel', 'channel': '{}_depth'.format(cp)})) logging.info(MSG_RESET_TRADER_DATA.format(ZB, '')) def on_message(self, ws, message): message = json.loads(message) data = message cp = self.currencypair[data['channel'].replace('_depth', '')] trades = {'asks': [], 'bids': []} for side in data: if side == 'asks': for order in data[side]: trades['asks'].append(td(float(order[0]), float(order[1]))) elif side == 'bids': for order in data[side]: trades['bids'].append(td(float(order[0]), float(order[1]))) try: Min, Max = self.data[cp].lastAsksLow, self.data[cp].lastBidsHigh self.data.update({cp: Traders()}) self.data[cp].lastAsksLow, self.data[cp].lastBidsHigh = Min, Max except: self.data.update({cp: Traders()}) self.data[cp].formate(trades, ZB) self.isReady = True Min = min(list(map(float, self.data[cp].asks.keys()))) Max = max(list(map(float, self.data[cp].bids.keys()))) if cp in self.targe: if (not Min == self.data[cp].lastAsksLow) or (not Max == self.data[cp].lastBidsHigh): self.data[cp].lastAsksLow = min(list(map(float, self.data[cp].asks.keys()))) self.data[cp].lastBidsHigh = max(list(map(float, self.data[cp].bids.keys()))) callback(self.notice, cp) def on_error(self, ws, message): logging.error(message) self.isReady = False time.sleep(1) def on_close(self, ws): self.isReady = False logging.warning(MSG_SOCKET_CLOSE.format(ZB, 'trader', timestampToDate())) if self.restart: time.sleep(1) logging.info(MSG_SOCKET_RESTART.format(ZB, 'trader')) self.start() def start(self): logging.info(MSG_SOCKET_START.format(ZB, 'trader')) self.ws = websocket.WebSocketApp('wss://api.zb.com:9999/websocket', on_open=self.on_open, on_message=self.on_message, on_close=self.on_close, on_error=self.on_error) self.thread = Thread(target=self.ws.run_forever) self.thread.start()
[ "leo5j472421@gmail.com" ]
leo5j472421@gmail.com
21a24098e5c349708e23a7a9ed10b6b35e59eaf1
3e15b40f4e28675af82d7d19aca1e5769131b3a4
/codons_in_frame_redo.py
ddacd173497df9f5e0c7d2c45240d69a7c1e0a07
[ "MIT" ]
permissive
jzfarmer/learning_python
69fd50457e2365d39bd23f6953d3d1456ff6147d
279fc19d4405625b49f853575252bf1dee3cbb99
refs/heads/master
2022-08-04T01:42:35.597663
2020-06-01T23:35:15
2020-06-01T23:35:15
252,600,378
0
0
null
null
null
null
UTF-8
Python
false
false
337
py
#!/usr/bin/env python3 # Print out all the codons for the sequence below in reading frame 1 # Use a 'for' loop dna = 'ATAGCGAATATCTCTCATGAGAGGGAA' for frame in range(3): print('frame') for i in range(0, len(dna)-2-frame, 3): print(i, dna[i + frame: i + 3 + frame]) """ python3 codons.py ATA GCG AAT ATC TCT CAT GAG AGG GAA """
[ "jessicafarmer@Jessicas-MBP.attlocal.net" ]
jessicafarmer@Jessicas-MBP.attlocal.net
d7c5e42b84f4c9b110fbad560674539a89f7fcc3
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_95/1682.py
ce5203d497f2ffb9866e62943b5974e224b8ab05
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
779
py
import sys if __name__ == '__main__': googlerese_ex = 'ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv' english_ex = 'our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up' googlerese_dict = dict(zip(list(googlerese_ex), list(english_ex))) googlerese_dict['z'] = 'q' googlerese_dict['q'] = 'z' # print googlerese_dict f = open(sys.argv[1], 'r') t = f.readline() i = 1 for line in f.readlines(): line = line.replace('\n', '') translated = '' for char in line: if char == ' ': translated += ' ' else: translated += googlerese_dict[char] print "Case #{}: {}".format(i, translated) i += 1
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
4139714996e399b65327782f30bbe627a7240154
2cfc8e8694e2115995e259151e320ad8bc64ed08
/Robot_ws/devel/lib/python2.7/dist-packages/more_custom_msgs/msg/_Hve_Roof.py
64e0364ee3ad991ab8434f53b468914c4141dbc2
[]
no_license
thilina-thilakarathna/robot_ws
d31e6ea82758b91dbf3a8045faedcf0e8a283ca1
094854a54b88eb3690f77710739dc2fe7d22b6f8
refs/heads/master
2023-01-10T15:17:51.400625
2019-08-28T18:59:21
2019-08-28T18:59:21
187,395,119
0
0
null
2023-01-07T09:10:06
2019-05-18T19:00:30
Makefile
UTF-8
Python
false
false
6,435
py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from more_custom_msgs/Hve_Roof.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class Hve_Roof(genpy.Message): _md5sum = "81d9585bad525c1936f901a8db21124b" _type = "more_custom_msgs/Hve_Roof" _has_header = True #flag to mark the presence of a Header object _full_text = """std_msgs/Header header int8 direction float32 speed ================================================================================ MSG: std_msgs/Header # Standard metadata for higher-level stamped data types. # This is generally used to communicate timestamped data # in a particular coordinate frame. # # sequence ID: consecutively increasing ID uint32 seq #Two-integer timestamp that is expressed as: # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs') # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs') # time-handling sugar is provided by the client library time stamp #Frame this data is associated with # 0: no frame # 1: global frame string frame_id """ __slots__ = ['header','direction','speed'] _slot_types = ['std_msgs/Header','int8','float32'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,direction,speed :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(Hve_Roof, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.header is None: self.header = std_msgs.msg.Header() if self.direction is None: self.direction = 0 if self.speed is None: self.speed = 0. else: self.header = std_msgs.msg.Header() self.direction = 0 self.speed = 0. def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_get_struct_bf().pack(_x.direction, _x.speed)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: if self.header is None: self.header = std_msgs.msg.Header() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.header.frame_id = str[start:end].decode('utf-8') else: self.header.frame_id = str[start:end] _x = self start = end end += 5 (_x.direction, _x.speed,) = _get_struct_bf().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_get_struct_bf().pack(_x.direction, _x.speed)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: if self.header is None: self.header = std_msgs.msg.Header() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.header.frame_id = str[start:end].decode('utf-8') else: self.header.frame_id = str[start:end] _x = self start = end end += 5 (_x.direction, _x.speed,) = _get_struct_bf().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_3I = None def _get_struct_3I(): global _struct_3I if _struct_3I is None: _struct_3I = struct.Struct("<3I") return _struct_3I _struct_bf = None def _get_struct_bf(): global _struct_bf if _struct_bf is None: _struct_bf = struct.Struct("<bf") return _struct_bf
[ "ltjt.thilina@gmail.com" ]
ltjt.thilina@gmail.com
056d82b68618d8db4072c657a23d222c92e88d99
268d9c21243e12609462ebbd6bf6859d981d2356
/Python/python_stack/Django/BeltReview/main/main/settings.py
f1304bb0df414857e32ddd1f90733a2fbd5aef02
[]
no_license
dkang417/cdj
f840962c3fa8e14146588eeb49ce7dbd08b8ff4c
9966b04af1ac8a799421d97a9231bf0a0a0d8745
refs/heads/master
2020-03-10T03:29:05.053821
2018-05-23T02:02:07
2018-05-23T02:02:07
129,166,089
0
0
null
null
null
null
UTF-8
Python
false
false
3,106
py
""" Django settings for main project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+ejmm0)uwksv3wvygjdo%)0_9*$u8k20a50gq!g0ip1nd=_0za' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'apps.books', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'main.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 = 'main.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/'
[ "dkang417@gmail.com" ]
dkang417@gmail.com
a9e1069500df3ab4b4dd9221c70cd50bed46b30e
5361bacfb433f627566239ddc89113c91275614f
/manage.py
2d4408d0680e637834e977c9e155483b4bb40490
[]
no_license
kosyfrances/do_log
3e84c583a0218ddbc2f3f913884bd81ad8e3488a
46cc168d9a68a80432be46a689728a52cd7e65c7
refs/heads/master
2021-06-15T10:00:45.873414
2017-01-02T18:47:23
2017-01-02T18:47:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
804
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "do_log.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
[ "kosy.anyanwu@andela.com" ]
kosy.anyanwu@andela.com
d10978faa559a82ae44dec2be2bc4fd47f135b3d
1e8cadff3cfd00b7f36df87776cec86be27b9de6
/lambda.py
3e0df8e54c0319661b3fcf2e21a9cc6ad4dfeebe
[]
no_license
Bhushanbk/mypython
073e63be0a4bcf940ef985747bb37d7c166325f1
1aec289a21bd2b4c577b59cebd9f374ac6ec56e4
refs/heads/master
2021-07-22T10:04:42.358403
2020-05-18T11:51:01
2020-05-18T11:51:01
169,360,162
0
0
null
null
null
null
UTF-8
Python
false
false
154
py
my_list=[1,2,4,5,6,78,9,60] new_list=list(filter(lambda x: (x%2==0),my_list)) new_list1=list(map(lambda x: (x%2==0),my_list)) print(new_list,new_list1)
[ "noreply@github.com" ]
Bhushanbk.noreply@github.com
714d1fc16b56509739dd30429a8f66e78376ce35
b09a8df80c35e3ccca43cd74cec6e1a14db76ad7
/branding/migrations/0001_initial.py
e00f156fe9caeae568ddb9fb064b75b1ddf65c1c
[ "MIT" ]
permissive
ofa/everyvoter
79fd6cecb78759f5e9c35ba660c3a5be99336556
3af6bc9f3ff4e5dfdbb118209e877379428bc06c
refs/heads/master
2021-06-24T19:38:25.256578
2019-07-02T10:40:57
2019-07-02T10:40:57
86,486,195
7
3
MIT
2018-12-03T19:52:20
2017-03-28T17:07:15
Python
UTF-8
Python
false
false
3,213
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-04-30 16:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import everyvoter_common.utils.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Domain', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models.DateTimeField(auto_now=True)), ('hostname', models.CharField(max_length=100, unique=True, verbose_name=b'Hostname')), ], options={ 'verbose_name': 'Domain', 'verbose_name_plural': 'Domains', }, bases=(everyvoter_common.utils.models.CacheMixinModel, models.Model), ), migrations.CreateModel( name='Organization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=50, verbose_name=b'Name')), ('homepage', models.URLField(verbose_name=b'Homepage')), ('platform_name', models.CharField(max_length=50, verbose_name=b'Platform Name')), ('privacy_url', models.URLField(verbose_name=b'Privacy Policy URL', blank=True)), ('terms_url', models.URLField(verbose_name=b'Terms of Service URL', blank=True)), ('online_vr', models.BooleanField(default=False, help_text=b'If offered use the Online Voter Registration deadline as the registration deadline', verbose_name=b'Online Voter Registion')), ('primary_domain', models.ForeignKey(default=None, help_text=b'Domain to attach all links to', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='primary_domain', to='branding.Domain', verbose_name=b'Primary Domain')), ], options={ 'verbose_name': 'Organization', 'verbose_name_plural': 'Organizations', }, bases=(everyvoter_common.utils.models.CacheMixinModel, models.Model), ), migrations.CreateModel( name='Theme', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('organization', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='branding.Organization')), ], options={ 'verbose_name': 'Theme', 'verbose_name_plural': 'Themes', }, ), migrations.AddField( model_name='domain', name='organization', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='branding.Organization'), ), ]
[ "nickcatal@gmail.com" ]
nickcatal@gmail.com
f44f891703f37179c46776f303162239677bcbca
bede13ba6e7f8c2750815df29bb2217228e91ca5
/project_task_timer/models/__init__.py
3d840b3d547c01584b2d78e9f03f45c297bc94f6
[]
no_license
CybroOdoo/CybroAddons
f44c1c43df1aad348409924603e538aa3abc7319
4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14
refs/heads/16.0
2023-09-01T17:52:04.418982
2023-09-01T11:43:47
2023-09-01T11:43:47
47,947,919
209
561
null
2023-09-14T01:47:59
2015-12-14T02:38:57
HTML
UTF-8
Python
false
false
959
py
# -*- coding: utf-8 -*- ############################################################################## # # Cybrosys Technologies Pvt. Ltd. # Copyright (C) 2017-TODAY Cybrosys Technologies(<http://www.cybrosys.com>). # Author: Jesni Banu(<http://www.cybrosys.com>) # you can modify it under the terms of the GNU LESSER # GENERAL PUBLIC LICENSE (AGPL v3), Version 3. # 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 LESSER GENERAL PUBLIC LICENSE (AGPL v3) for more details. # # You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE # GENERAL PUBLIC LICENSE (AGPL v3) along with this program. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import project_task_timer
[ "ajmal@cybrosys.in" ]
ajmal@cybrosys.in
de0828309b71ce1fd4d2b60ba8dc8fa86f6cdb64
bed4318485ff0048ddc96a2484b8a7e782dfaabb
/blogprepare.py
693763c4940d2b0e43bb10137fc80fd51d2478f7
[]
no_license
mattovic/BlogSystem
d4db94e196d03a5b1b85666f3dcc0d422ca9b1d0
acea9e8d871f48631e5337bb90e71616d9235498
refs/heads/master
2021-01-18T16:16:47.638963
2016-04-23T12:28:52
2016-04-23T12:28:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
694
py
import os import re from blog import article from blog import index working_path = os.getcwd() # Delete all the html files html_path = os.path.join(working_path, 'html') html_list = os.listdir(html_path) for name in html_list: if name.find('html') > 0: html_file = os.path.join(html_path, name) os.remove(html_file) # Convert md to html md_path = os.path.join(working_path, 'md') md_list = os.listdir(md_path) for name in md_list: if re.match(r'[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9].*', name) is not None: myarticle = article.Article(name) myarticle.to_html() # Generate index myindex = index.Index() myindex.to_html()
[ "xjq314@gmail.com" ]
xjq314@gmail.com
c35c097e3f75be768752847e211e96ffcf54f034
8ec32ed4e4c81f2e5ee6dd84442dfe010e7d1194
/utils/discrete_bs/functions.py
476fcf51a80acb3fce90ae3c6249ca454b9ffe79
[]
no_license
AlexGrill1/introductory_examples
cf44489f240b31ca8c154221cddbea48f2ad39a4
f68d20fc5e3a4d018b59082c876a822aee8929c0
refs/heads/main
2023-08-07T10:40:47.724906
2021-10-05T11:59:47
2021-10-05T11:59:47
331,084,355
0
0
null
null
null
null
UTF-8
Python
false
false
4,397
py
import numpy as np import scipy import scipy.optimize from collections import defaultdict def structure_preserving_update(Q, actions, step_size, func, initial_params, T, dt): '''Updates the action-value function Q by fitting parameters of function func to Q-table and updating all Q-values by a step towards the fitted values. Args: - Q:[dict] Action-value function - actions:[np.array] possible risky asset allocations - step_size:[float] step_size parameter for an update step towards the fitted values - func:[callable] parametrised family of functions used for fitting - initial_params:[list[float]] List of initial parameters for the optimisation step (must match the nr. of parameters of func) - T:[float] investment horizon - dt:[float] times step size Returns: - Q:[dict] Update Action-value function ''' # Change dict representation to list representation (needed for scipy.optimize) Q_list = _dict_to_list(Q, actions) # Remove highest / lowest wealth levels from action-value function (wealth levels are set to lower / upper limit, not midpoints) tData, aData, vData, qData = _rm_high_low_wealths_from_list(Q_list) # Fit function fittedParameters, pcov = scipy.optimize.curve_fit(func, [tData, aData, vData, T*np.ones(len(tData)), dt*np.ones(len(tData))], qData, p0 = initial_params) # Fit action-values at grid points fittedQValues = func([tData, aData, vData, T*np.ones(len(tData)), dt*np.ones(len(tData))], *fittedParameters) # difference between predicted values and actual values Q_diff = fittedQValues - qData # Update Q-values qData += step_size*Q_diff # Transform lists to dictionary to dictionary Q_new_dict = _lists_to_dict(tData, vData, qData) # Add states with highest lowest wealths (no change) old_keys = set(Q.keys()) new_keys = set(Q_new_dict.keys()) difference = list(old_keys - new_keys) for key in difference: Q_new_dict[key] = Q[key] return Q_new_dict, fittedParameters def _dict_to_list(Q, actions): '''Converts the action-value table Q from a dictionary to a list of four numpy arrays. Args: - Q:[dict] Q-Table - actions:[np.array] possible risky asset allocations Returns a list of four np.arrays: - time - action - wealth - Q-value ''' tData = np.array([t for t,_ in Q.keys()]).repeat(len(actions)) aData = np.array(list(actions)*(len(tData)//len(actions))) vData = np.array([V for _,V in Q.keys()]).repeat(len(actions)) qData = np.array([values for values in Q.values()]).reshape(len(tData)) return [tData, aData, vData, qData] def _lists_to_dict(tData, vData, qData): '''Creates the action-value as dictionary from three lists. Args: - tData[list[float]]: time values - vData[list[float]]: wealth data - qData[list[float]]: action values Returns: - Q[dict]: keys are tuples (t,v) and values are lists of length nr. of actions with respective action-values. ''' # Create dict keys as tuples (t,v) -> list of tuples keys = list(dict.fromkeys(zip(tData, vData))) # Create dict values as action-value per action -> list of np.arrays of length nr. actions values = np.split(np.array(qData), indices_or_sections = len(keys)) # Create dict Q = defaultdict(lambda: np.zeros(env.action_space.n)) for key, value in list(zip(keys, values)): Q[key] = value return Q def _rm_high_low_wealths_from_list(Q_list): '''Reduces the Q-value list by their highest and lowest values for function fitting. (Hightest and lowest buckets are not accurate.) Args: - Q_list:[list] list of four lists t, a, v, q from dict_to_list Returns a list of four np.arrays: - time - action - wealth - Q-value ''' # Unpack values tData, aData, vData, qData = Q_list # Remove lowest/highest wealth values tData = tData[(vData!=min(vData)) & (vData!=max(vData))] aData = aData[(vData!=min(vData)) & (vData!=max(vData))] qData = qData[(vData!=min(vData)) & (vData!=max(vData))] vData = vData[(vData!=min(vData)) & (vData!=max(vData))] return [tData, aData, vData, qData]
[ "ga63key@mytum.de" ]
ga63key@mytum.de
cfd6f1bdfe93bd052294aebdb0b49723c872571a
959214e35ecd453f247f9529a559b1cb5f8f8d3d
/CS115A copy/temp_conversion.py
e359dbfacfffd26291731b7c9c941068149eae1d
[]
no_license
bcao4/CS115-Intro-to-CS
3c109ba5f0d8c113f5f3a14a39ec82f5b768d5fa
58b2040a33a57648779b83de05efc9d1078b7be3
refs/heads/master
2021-10-26T16:18:41.511065
2019-04-13T23:23:37
2019-04-13T23:23:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,356
py
''' Created on Aug 31, 2018 @author: brandon ''' """ Put the function at the top of program """ def celsius(fahrenheit): """returns the input Fahrenheit degrees in Celsius""" return 5/9 + (fahrenheit - 32) def fahrenheit(celsius): """Returns the input Celsius degrees in Fahrenheit""" return 9 / 5 * celsius + 32 """ Call the functions below the function definitions """ c= float(input('Enter degrees in Celsius: ')) f = fahrenheit(c) # You can print multiple items in one statement. If you put a comma after each #item, it prints a space and then foes on to print the next item. print(c, 'C =', f, 'F') #You can print this way too, but allowing exactly two decimal places. print('%.2f C = %.2f F' % (c,f)) f= float(input('Enter degrees in Fahrenheit: ')) c = celsius(f) print(f, 'F =', c, 'C') print('%.2f F = %.2f C' % (f,c)) """ Try composition of funcstions. Converting a fahrenheit temperature to Celsius and back to fahrenheit should give the original fahrenheit temperature. """ print() #print by itself prints a new line f= float(input('Enter degrees in Fahrenheit: ')) #User assert to check the returned value is equal to the expected value assert fahrenheit(celsius(f)) #No output should be produced, unless the assertion fails, which means you #have an error (either in your code or your expectation).
[ "noreply@github.com" ]
bcao4.noreply@github.com
8ff68460619ebdc217abe39187aa005ecfc0b9dc
b09d65b49981a7cf276765777daf3fd44b666e42
/tinymud/world/place.py
ac659940deb4b1e7825a87155b3531c688605c89
[]
no_license
bensku/tinymud
f257b0f19f53855af7dd707c63d090d3f33d615c
4dbf3fae82e268cbb9e8dc8bd34a81f0654f64c8
refs/heads/master
2023-02-04T01:29:35.592524
2020-12-12T13:01:33
2020-12-12T13:01:33
308,154,328
0
0
null
null
null
null
UTF-8
Python
false
false
10,258
py
"""Places in the world.""" import asyncio from dataclasses import dataclass, field from enum import Flag, auto import time from typing import Dict, List, Optional, ValuesView from weakref import ReferenceType, ref from loguru import logger from pydantic import BaseModel from tinymud.db import Foreign, Entity, entity, execute, fetch from .character import Character from .gameobj import Placeable from .item import Item @dataclass class _CachedPlace: """Cached data of a place. Reference to this should only permanently kept by the Place itself. This prevents the cached information from leaking when the Place is unloaded by GC. """ characters: Dict[int, Character] passages: Dict[str, 'Passage'] class ChangeFlags(Flag): """Changes at a place during one tick. Change places are set when something (description, characters, items, etc.) changes in a place. They're cleared at end of place ticks, and can be used in on_tick handlers to e.g. decide which updates to send to clients. """ DETAILS = auto() PASSAGES = auto() CHARACTERS = auto() ITEMS = auto() @entity @dataclass class Place(Entity): """A place in the world. Each place has an unique address (str) in addition to numeric. The addresses are used mostly in content creation tools. Players are usually shown titles instead of place addresses, but both should be considered public knowledge. Header text is in markdown-like format (TODO) that is rendered to HTML by client. """ address: str title: str header: str _cache: _CachedPlace = field(init=False) _cache_done: bool = False _changes: ChangeFlags = ChangeFlags(0) @staticmethod async def from_addr(address: str) -> Optional['Place']: """Gets a place based on its unique address.""" return await Place.select(Place.c().address == address) def __object_created__(self) -> None: _new_places.append(ref(self)) # Add to be ticked async def make_cache(self) -> None: if self._cache_done: return # Cache already created # Load all characters (by their ids) characters = {} for character in await Character.select_many(Character.c().place == self.id): characters[character.id] = character # Load all passages (by their target addresses) # Avoid unnecessary queries later by doing unnecessarily complex query tricks # Totally not premature optimization (hmm) passages = {} for record in await fetch(('SELECT passage.id id, passage.place as place, passage.name as name, passage.target target,' ' passage.hidden hidden, place.address _address, place.title _place_title' f' FROM {Passage._t} passage JOIN {Place._t} place' ' ON target = place.id WHERE passage.place = $1'), self.id): passage = Passage.from_record(record) passage._cache_done = True # We provided extra values in constructor passages[passage._address] = passage self._cache = _CachedPlace(characters, passages) self._cache_done = True async def passages(self) -> ValuesView['Passage']: await self.make_cache() return self._cache.passages.values() async def items(self) -> List[Item]: return await Item.select_many(Item.c().place == self.id) async def characters(self) -> ValuesView[Character]: await self.make_cache() return self._cache.characters.values() async def update_passages(self, passages: List['PassageData']) -> None: """Updates passages leaving from this place.""" await self.make_cache() # Delete previous passages await execute(f'DELETE FROM {Passage._t} WHERE id = $1', [self.id]) self._cache.passages = {} # Create new passages for passage in passages: target = await Place.from_addr(passage.address) if not target: logger.warning(f"Passage to missing place {passage.address}") continue # Missing passage, TODO user feedback entity = Passage(self.id, target.id, passage.name, passage.hidden, _cache_done=True, _address=passage.address, _place_title=target.title) self._cache.passages[target.address] = entity # Update to clients self._changes |= ChangeFlags.PASSAGES async def use_passage(self, character: Character, address: str) -> None: """Makes a character in this place take a passage.""" if character.place != self.id: raise ValueError(f'character {character.id} is not in place {address}') await self.make_cache() if address not in self._cache.passages: raise ValueError(f'no passage from {self.address} to {address}') to_place = await Place.get(self._cache.passages[address].target) await character.move(to_place) async def on_tick(self, delta: float) -> None: """Called when this place is ticked. The delta is time difference between start of current and previous place ticks, in seconds. This is NOT necessarily same as time between this and previous tick (that may or may not have even occurred). """ await self.make_cache() # Swap change flags to none, so new changes won't take effect mid-tick # (and will be present in self._changes for next tick) changes = self._changes self._changes = ChangeFlags(0) # Call tick handler on all characters for character in await self.characters(): await character.on_tick(delta, changes) async def on_character_enter(self, character: Character) -> None: """Called when an character enters this place.""" await self.make_cache() self._cache.characters[character.id] = character self._changes |= ChangeFlags.CHARACTERS async def on_character_exit(self, character: Character) -> None: """Called when an character exists this place.""" await self.make_cache() del self._cache.characters[character.id] self._changes |= ChangeFlags.CHARACTERS class PassageData(BaseModel): """Passage data sent by client.""" address: str name: Optional[str] hidden: bool @entity @dataclass class Passage(Placeable, Entity): """A passage from place to another. A single passage can only be entered from the room it is placed to. If bidirectional movement is needed, both rooms should get a passage. Passages can be named, but by default they inherit names of their targets. Note that text shown inside place header is usually different. For passages hidden from exit list, names are never shown to players. """ target: Foreign[Place] name: Optional[str] hidden: bool # Some cached data from other places # Note that usually place caching queries them with one SELECT _cache_done: bool = False _address: str = '' # Target address (client deals with addresses, not place ids) _place_title: str = '' async def _make_cache(self) -> None: if self._cache_done: return # Already cached place = await Place.get(self.target) self._address = place.address self._place_title = place.title self._cache_done = True async def address(self) -> str: await self._make_cache() return self._address async def place_title(self) -> str: await self._make_cache() return self._place_title async def client_data(self) -> PassageData: await self._make_cache() return PassageData(address=self._address, name=self.name, hidden=self.hidden) # Places that are currently pending addition to _places _new_places: List[ReferenceType[Place]] = [] # Places that are currently ticked over _places: List[ReferenceType[Place]] = [] async def _places_tick(delta: float) -> None: """Runs one tick over all places.""" global _new_places global _places next_places = _new_places # Places after this tick _new_places = [] # Places that get loaded/added during this tick # Process newly added places to avoid 1 tick delay for place_ref in next_places: place = place_ref() if place: await place.on_tick(delta) # But we can't remove in place, so let it stay in _new_places # Iterate over current places for place_ref in _places: place = place_ref() if place and not place._destroyed: # Not GC'd, not destroyed await place.on_tick(delta) _new_places.append(place_ref) # Swap to places that still exist (and newly added ones) _places = next_places # And previous _places is deleted async def _places_tick_loop(delta_target: float) -> None: prev_start = time.monotonic() await _places_tick(delta_target) # First tick is always on time # Tick and wait if it didn't consume all time given while True: start = time.monotonic() delta = start - prev_start deviation = delta_target - delta if deviation > 0: # We're early, need to wait await asyncio.sleep(deviation) else: # (almost) failed to keep up? pass # TODO logging every once a while (not EVERY tick) await _places_tick(delta) prev_start = start async def start_places_tick(delta_target: float) -> None: """Starts places tick as background task.""" asyncio.create_task(_places_tick_loop(delta_target)) logger.info(f"Ticking loaded places every {delta_target} seconds") _limbo_place: Place async def init_limbo_place() -> None: """Initializes the 'default' place, Limbo. Limbo is used (hopefully) only during development, when other places don't exist in the database. """ limbo = await Place.from_addr('tinymud.limbo') if not limbo: logger.debug("Creating limbo place (empty database?)") limbo = Place( address='tinymud.limbo', title="Limbo", header="Nothing to see here." ) global _limbo_place _limbo_place = limbo
[ "bmi@iki.fi" ]
bmi@iki.fi
9fa7628c41a98af1aa5e655619e2a686bd7a28dc
43bcdbc81be7f94f053008f0fda392243d650ffb
/Lexer.py
2c00c4bc06f9963124fcf79124bf7ed79836bf4c
[]
no_license
lucasbmendonca/PDL2
139207073c12fecb92b5b6bd9a82e85cb49da0ac
b799b7f366c4aaece1c0446a0828dc171ec4af30
refs/heads/master
2023-02-21T07:17:20.913189
2021-01-24T22:14:25
2021-01-24T22:14:25
330,300,521
0
0
null
null
null
null
UTF-8
Python
false
false
1,518
py
import ply.lex as lex from utilities import slurp import sys class Lexer: literals = """:"[]+-/*""" t_ignore = " \n\t" #t_DOTS = r'\.\.' tokens = ( "forward", "fd", "back", "bk", "left", "lt", "right", "rt", "setpos", "setxy", "setx", "sety", "home", "pd","pu", "pendown", "penup", "setpencolor", "make", "if", "ifelse", "repeat", "while", "to", "end","stop", "VAR", "NUMBER", "SIGN", "STR") def t_COMMAND(self, t): r"(forward|fd)|(back|bk)|(left|lt)|(right|rt)|setpos|setxy|setx|sety|home|(pendown|pd)|(penup|pu)|setpencolor|make|if|ifelse|repeat|while|to|end|stop" t.type = t.value.replace(" ", "") return t def t_VAR(self, t): r"""("|:)[a-z][0-9a-z]*""" return t def t_STR(self, t): r"[a-wyz][0-9a-z]*" return t def t_NUMBER(self, t): r"[+-]?([0-9]+[.])?[0-9]+" t.value = float(t.value) return t def t_SIGN(self, t): r">|<|=" return t def t_error(self, t): print(f"Parser error. Unexpected char: {t.value[0]}", file=sys.stderr) exit(1) #t.lexer.skip(1) def __init__(self): self.lexer = None self.command = None self.argument = None def Build(self, input, **kwargs): self.lexer = lex.lex(module=self, **kwargs) self.lexer.input(input) def Execute(self): for token in iter(self.lexer.token, None): print(token)
[ "bragalucas@id.uff.br" ]
bragalucas@id.uff.br
da695a28e73a1447f3cd908dafa400044aa7f7bb
5e08edf0aba7f98effa6fec3d45301a78551ff24
/axon/tests/unit/apps/test_stats.py
fc2a4cda16672a8fa55761c8cbf3e3e2a4fa5e16
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
duorah/validation-app-engine
6e322df108107c1e79f6aea1a9135b79c000d171
ba41462b57807ce75a8cf322547f1704c676c9be
refs/heads/master
2020-05-24T06:28:03.262784
2019-07-01T17:37:14
2019-07-01T17:37:14
187,138,274
0
0
NOASSERTION
2019-05-17T03:10:30
2019-05-17T03:10:30
null
UTF-8
Python
false
false
2,469
py
#!/usr/bin/env python # Copyright (c) 2019 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2 License # The full license information can be found in LICENSE.txt # in the root directory of this project. import mock import time from axon.apps.stats import StatsApp from axon.db.local.repository import TrafficRecordsRepositery from axon.tests import base as test_base class TestStatsApp(test_base.BaseTestCase): """ Test for StatsApp utilities """ def setUp(self): super(TestStatsApp, self).setUp() self._stats_app = StatsApp() @mock.patch('axon.db.local.session_scope') @mock.patch.object(TrafficRecordsRepositery, 'get_record_count') def test_get_failure_count(self, mock_rc, mock_session): mock_rc.return_value = 10 mock_session.side_effect = None start_time = time.time() end_time = start_time + 10 destination = '1.2.3.4' port = 12345 result = self._stats_app.get_failure_count( start_time=start_time, end_time=end_time, destination=destination, port=port) mock_rc.assert_called() self.assertEqual(10, result) @mock.patch('axon.db.local.session_scope') @mock.patch.object(TrafficRecordsRepositery, 'get_record_count') def test_get_success_count(self, mock_rc, mock_session): mock_rc.return_value = 10 mock_session.side_effect = None start_time = time.time() end_time = start_time + 10 destination = '1.2.3.4' port = 12345 result = self._stats_app.get_success_count( start_time=start_time, end_time=end_time, destination=destination, port=port) mock_rc.assert_called() self.assertEqual(10, result) @mock.patch('axon.db.local.session_scope') @mock.patch.object(TrafficRecordsRepositery, 'get_records') def test_get_failures(self, mock_records, mock_session): mock_records.return_value = 'fake_failures' mock_session.side_effect = None start_time = time.time() end_time = start_time + 10 destination = '1.2.3.4' port = 12345 result = self._stats_app.get_failures( start_time=start_time, end_time=end_time, destination=destination, port=port) mock_records.assert_called() self.assertEqual('fake_failures', result)
[ "noreply@github.com" ]
duorah.noreply@github.com
13a1825703648e0f88b680e4e16c81413ff0d50d
280af7d6661b97e4562abf61bbe5c4e57ace9530
/Recurrent_Neural_Networks_Google_Stock_Price/RNN (2).py
a6a0e1889d78a4dd9ce9c0e80b2d8571053d7292
[]
no_license
Sbakkalii/DL_Projects
da73ab709b716dbfbdf5a2701cc8bf255c802082
d359ed7e65dcc06209ef24431057ec31ddaaf54d
refs/heads/master
2022-08-16T17:11:40.515872
2019-06-05T20:03:21
2019-06-05T20:03:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,847
py
# Recurrent Neural Network ###############One time step prediction, predicting the stock price for the next day ****************** # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the training set training_set = pd.read_csv('Google_Stock_Price_Train.csv') training_set = training_set.iloc[:, 1:2].values # Feature Scaling from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() training_set = sc.fit_transform(training_set) #Getting the inputs and the outputs X_train = training_set[0:1257] y_train = training_set[1:1258] # Reshaping X_train = np.reshape(X_train, (1257, 1, 1)) # Part 2 - Building the RNN # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM # Initialising the RNN regressor = Sequential() # Adding the first LSTM layer and some Dropout regularisation regressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None, 1))) # Adding the output layer regressor.add(Dense(units = 1)) # Compiling the RNN regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') # Fitting the RNN to the Training set regressor.fit(X_train, y_train, epochs = 200, batch_size = 32) # Part 3 - Making the predictions and visualising the results # Getting the real stock price of 2017 test_set = pd.read_csv('Google_Stock_Price_Test.csv') real_stock_price = test_set.iloc[:, 1:2].values # Getting the predicted stock price of 2017 real_stock_price_test = sc.transform(real_stock_price) real_stock_price_test = np.reshape(real_stock_price_test, (20, 1, 1)) predicted_stock_price = regressor.predict(real_stock_price_test) predicted_stock_price = sc.inverse_transform(predicted_stock_price) # Visualising the results plt.plot(real_stock_price, color = 'red', label = 'Real Google Stock Price') plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price') plt.title('Google Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.legend() plt.show() # Part 4 - Evaluating the RNN import math from sklearn.metrics import mean_squared_error rmse = math.sqrt(mean_squared_error(real_stock_price, predicted_stock_price)) ## rmse/804 = 0.005427676435438387 ############### Multiple times step prediction ##################### ############### Model 1 - 20 timesteps & 1 LSTM layer ######### # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the training set DataTrain_set = pd.read_csv('Google_Stock_Price_Train.csv') DataTrain_set = DataTrain_set.iloc[:, 1:2].values # Feature Scaling from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler(feature_range = (0, 1)) DataTrain_set_scaled = sc.fit_transform(DataTrain_set) # Creating a data structure with 20 timesteps and t+1 output X_Train1 = [] Y_Train1 = [] for i in range(20, 1258): X_Train1.append(DataTrain_set_scaled[i-20:i, 0]) Y_Train1.append(DataTrain_set_scaled[i, 0]) X_Train1, Y_Train1 = np.array(X_Train1), np.array(Y_Train1) # Reshaping X_Train1 = np.reshape(X_Train1, (X_Train1.shape[0], X_Train1.shape[1], 1)) # Part 2 - Building the RNN # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM # Initialising the RNN regressor = Sequential() # Adding the input layer and the LSTM layer regressor.add(LSTM(units = 3, input_shape = (None, 1))) # Adding the output layer regressor.add(Dense(units = 1)) # Compiling the RNN regressor.compile(optimizer = 'rmsprop', loss = 'mean_squared_error') # Fitting the RNN to the Training set regressor.fit(X_Train1, Y_Train1, epochs = 100, batch_size = 32) # Part 3 - Making the predictions and visualising the results # Getting the real stock price for February 1st 2012 - January 31st 2017 dataset_test = pd.read_csv('Google_Stock_Price_Test.csv') test_set = dataset_test.iloc[:,1:2].values real_stock_price = np.concatenate((training_set[0:1258], test_set), axis = 0) # Getting the predicted stock price of 2017 scaled_real_stock_price = sc.fit_transform(real_stock_price) inputs = [] for i in range(1258, 1278): inputs.append(scaled_real_stock_price[i-20:i, 0]) inputs = np.array(inputs) inputs = np.reshape(inputs, (inputs.shape[0], inputs.shape[1], 1)) predicted_stock_price = regressor.predict(inputs) predicted_stock_price = sc.inverse_transform(predicted_stock_price) # Visualising the results plt.plot(real_stock_price[1258:], color = 'red', label = 'Real Google Stock Price') plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price') plt.title('Google Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.legend() plt.show()
[ "souhail.bkl@gmail.com" ]
souhail.bkl@gmail.com
bc26d9774f9ab3bb157a79d498c229fdf3ff1e8b
a04efee09de7e14e4b92caf2f58e9f7d5bdb8d07
/tutorial/admin.py
63cdd289adad8edcc875b59c0acb49b393883957
[]
no_license
bunop/django-tables2-etude
78b80360e193faec7d2149c57cfd84ac745d496e
ae0d3b2d535991a80a220d6f3ab1511226134e02
refs/heads/master
2020-05-21T07:40:38.644188
2019-05-10T13:21:49
2019-05-10T13:21:49
185,966,835
0
0
null
null
null
null
UTF-8
Python
false
false
329
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 7 17:01:03 2019 @author: Paolo Cozzi <cozzi@ibba.cnr.it> """ from django.contrib import admin from .models import Person class PersonAdmin(admin.ModelAdmin): list_per_page = 25 # Register your models here. admin.site.register(Person, PersonAdmin)
[ "bunop@libero.it" ]
bunop@libero.it
947a6dba0c4e453816a831e8ebc549da3d647545
55f0bbcd87855da796cc81906811973f74a4372e
/cogs/testing.py
6abe1db290e366a4b939ac3bd6626fc3dde2e09e
[]
no_license
tagptroll1/Streamio
994fbb7aa16efcba972263eb01b965238ea205bb
b4609d4be67bbc7d6037212ed7ed044d5fa4cbd4
refs/heads/master
2021-06-21T06:02:44.721779
2018-10-02T18:41:50
2018-10-02T18:41:50
137,110,391
1
0
null
null
null
null
UTF-8
Python
false
false
515
py
import discord from discord.ext import commands class Testing: def __init__(self, bot): self.bot = bot @commands.is_owner() @commands.command() async def resetpresence(self, ctx): await self.bot.change_presence() @commands.is_owner() @commands.command() async def teststream(self, ctx): await self.bot.change_presence(activity=discord.Streaming( name="Teststream", url="https://www.twitch.tv/peebls")) def setup(bot): bot.add_cog(Testing(bot))
[ "thomas@galehuset.org" ]
thomas@galehuset.org
1e1ce27559dd63f7756930985a0c4856fac56fce
20f02496844ff9a021807f3442f9c1dc456a0c61
/knowledgeBase/wsgi.py
55ff9df86ab5ec7736310a98ddeebe45fbb258ff
[]
no_license
shubham1560/knowledge-Rest-Api
894d1d9a677ab399ab41d052b869408255f014d7
f664bd6f8dcba85a4b5eb04516c7f1947b4a581f
refs/heads/master
2020-07-30T00:24:06.338377
2019-09-22T18:14:24
2019-09-22T18:14:24
210,017,318
1
0
null
null
null
null
UTF-8
Python
false
false
403
py
""" WSGI config for knowledgeBase project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'knowledgeBase.settings') application = get_wsgi_application()
[ "shubhamsinha2050@gmail.com" ]
shubhamsinha2050@gmail.com
d602886f9f550e1e0b9e14f9b258ab814df8ab5d
70a9ad86b0bc81a46fb654906b863413653a9428
/python/mri_python/ge3dmice_sg_cylA.py
f202ac56391f1f5beabf94217a9343c718d7d3c7
[]
no_license
edeguzman/MICe-lab
ae2fe581a9b966859843c1024d2fba12fd5a5acd
bfa824b45a6301972524f1fef2dbb1ffec0f16e8
refs/heads/master
2020-05-23T17:35:52.197096
2018-05-23T20:20:07
2018-05-23T20:20:07
186,871,382
0
0
null
2019-05-15T17:15:40
2019-05-15T17:12:43
Python
UTF-8
Python
false
false
6,199
py
from optparse import OptionGroup import python.mri_python.recon_genfunctions as rgf import python.mri_python.varian_fid_corrections as vfc import python.mri_python.resp_sg as rsg import python.mri_python.coil_decouple as cd def seq_specific_options(parser): optgroup = OptionGroup(parser,"ge3dmice_sg_cylA","sequence-specific reconstruction options") optgroup.add_option("--petable_ordered_pairs", action="store_true", dest="petable_ordered_pairs", default=0, help="phase encodes specified by (t1,t2) ordered pairs in petable") optgroup.add_option("--self_resp_gate",action="store_true",dest="self_resp_gate", default=0, help="use FID nav for resp. gating") optgroup.add_option("--outputreps",action="store_true",dest="outputreps", default=0, help="output all reps from a self-gated sequence separately") optgroup.add_option("--phasedriftcorr",action="store_true",dest="phasedriftcorr", default=0, help="correct phase drift based on repeated zero acqs in table") optgroup.add_option("--rep_position_corr",action="store_true",dest="rep_position_corr", default=0, help="correct phase encode shifts between multiple repetitions") optgroup.add_option("--grappa_coil_decouple",action="store_true",dest="grappa_coil_decouple", default=0, help="correct coupling between coils (i.e., in saddle coil array)") optgroup.add_option("--grappa_coil_groupings",type="string",dest="grappa_coil_groupings", default="0,2,5;1,3,4,6", help="groups of cross-talking coils (example: 0,2,5;1,3,4,6 )") optgroup.add_option("--dcplppeadj",type="string",dest="dcplppeadj_string", default=None, help="ppe position offset for decoupling mask") optgroup.add_option("--grappa_kpts_offset",type="int",dest="grappa_kpts_offset", default=0, help="grappa to k-space grid offset (same in both directions: option to be deleted!)") optgroup.add_option("--dcpl_profs_output_name",type="string",dest="dcpl_profs_output_name", default=None, help="filename for output of grappa profiles and mask contours (useful for debugging decoupling)") optgroup.add_option("--pre_applied_pe1_shift",action="store_true",dest="pre_applied_pe1_shift", default=False, help="fid data has pre-applied pe1 shift") parser.add_option_group(optgroup) class seq_reconstruction(): def __init__(self,inputAcq,options,outputfile): self.options=options self.inputAcq=inputAcq self.outputfile=outputfile if ((self.options.petable=='') and (inputAcq.platform=="Varian")): self.petable_name=rgf.get_dict_value(inputAcq.param_dict,'petable','petable') else: self.petable_name=self.options.petable self.kspace=None self.image_data=None if (not self.options.dcplppeadj_string): self.dcplppeadj = None else: self.dcplppeadj = [float(x) for x in self.options.dcplppeadj_string.split(',')] def pre_recon_processing(self): if (self.options.phasedriftcorr): self.phasedriftcorr = vfc.phase_drift_corr(self.inputAcq,self.petable_name) else: self.phasedriftcorr = None if (self.options.rep_position_corr): self.phasedriftcorr = vfc.rep_pos_corr(self.inputAcq,self.petable_name,phasedriftcorr=self.phasedriftcorr) if (self.options.grappa_coil_decouple): self.dcpl_info = cd.gen_decoupling_info(self.inputAcq,self.petable_name, cplgrps_string=self.options.grappa_coil_groupings, dcplppeadj=self.dcplppeadj, dcpl_profs_output_name=self.options.dcpl_profs_output_name, remove_ppeshift=self.options.pre_applied_pe1_shift) else: self.dcpl_info = None def gen_kspace(self,imouse=0): sgflag = rgf.get_dict_value(self.inputAcq.param_dict,'sgflag','n') if (sgflag=='y') and self.options.self_resp_gate: sg_fids = rsg.get_sg_data(self.inputAcq,imouse) #from pylab import plot,show #plot(sg_fids[:,3].real) #plot(sg_fids[:,3].imag) #show() tr = rgf.get_dict_value(self.inputAcq.param_dict,'tr',0.05) resp_dur = 0.2 resp_gate_sig,resp_sig = rsg.self_resp_gate(sg_fids,tr,resp_dur) else: resp_gate_sig=None resp_sig=None if (self.options.petable_ordered_pairs): grappafov=int(rgf.get_dict_value(self.inputAcq.param_dict,'grappafov',1)) self.kspace = rsg.gen_kspace_sg_orderedpairtable(self.inputAcq, resp_gate_sig,resp_sig,imouse, gate_resp=self.options.self_resp_gate, petable=self.petable_name,grappafov=grappafov, kpts_offset=self.options.grappa_kpts_offset, outputreps=self.options.outputreps, phasecorr=self.phasedriftcorr, dcpl_info=self.dcpl_info) elif (sgflag=='y'): self.kspace = rsg.gen_kspace_sg(self.inputAcq,resp_gate_sig,resp_sig,imouse) else: #sgflag='n' and no petable_ordered_pairs self.kspace = rgf.gen_kspace_simple(self.inputAcq,imouse) self.kspace = rgf.fov_adjustment(self.kspace,self.options,self.inputAcq,imouse) if self.options.fermi_ellipse: self.kspace = rgf.fermi_ellipse_filter(self.kspace) elif self.options.fermi_pecirc: self.kspace = rgf.fermi_pecircle_filter(self.kspace)
[ "aesdeguzman@gmail.com" ]
aesdeguzman@gmail.com
41c8fd9b628a34baaedb4ae5fb23382673a280a3
43125789072a6e7f97c383eb897bf81419b1028f
/findline.py
3762f69c5a8a9f911f65721572fbf38299de42fc
[]
no_license
1234565432/hello
ada509130adbd3fe7000437b215d59f2d32d8190
bb4c17f64e9e3cd83cff706a0e165564f21c35ee
refs/heads/master
2021-09-04T04:48:38.766907
2018-01-16T01:36:40
2018-01-16T01:36:40
106,689,476
0
0
null
null
null
null
UTF-8
Python
false
false
1,424
py
# coding:utf-8 # findline with color import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np image = mpimg.imread('test.png') # type判断类型 print('this image is :', type(image), 'with dimensions: ', image.shape) ysize = image.shape[0] xsize = image.shape[1] region_select = np.copy(image) color_select = np.copy(image) left_bottom = [0, 462] right_bottom = [829, 462] apex = [414.5, 280] fit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1) fit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1) fit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1) xx, yy = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize)) region_thresholds = (yy > (xx * fit_left[0] + fit_left[1])) & \ (yy > (xx * fit_right[0] + fit_right[1])) & \ (yy < (xx * fit_bottom[0] + fit_bottom[1])) red_threshold = 0.85 green_threshold = 0.85 blue_threshold = 0.85 rgb_threshold = [red_threshold, green_threshold, blue_threshold] color_thresholds = (image[:, :, 0] < rgb_threshold[0])\ | (image[:, :, 1] < rgb_threshold[1]) \ | (image[:, :, 2] < rgb_threshold[2]) color_select[color_thresholds] = [0, 0, 0, 1] region_select[~color_thresholds & region_thresholds] = [255, 0, 0, 1] # plt.imshow(color_select) plt.imshow(region_select) plt.show() plt.show()
[ "1204364027@qq.com" ]
1204364027@qq.com
00ef3e6370c919e5610f75cde22c72c4d3af2936
0d246b6b1acaf8c2bdb5175047937ea1f7eeec2a
/programas/cap04/ex04.py
40b6b9b4b4a280d90de59fdbc94a8cbd22c09330
[]
no_license
wesleyterrao/livro-visao-computacional
7fbb289b7154a0a8a9acd6f5f51606d867fd719c
b38379c5e0fca658ee4a74e4c5ebf0e435ca7f5b
refs/heads/master
2022-04-13T17:23:57.889017
2018-05-09T16:44:47
2018-05-09T16:44:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
271
py
import cv2 imagem = cv2.imread("frutas.jpeg") imagem = cv2.cvtColor(imagem, cv2.COLOR_BGR2HSV) matiz, saturacao, valor = cv2.split(imagem) cv2.imshow("Canal H", matiz) cv2.imshow("Canal S", saturacao) cv2.imshow("Canal V", valor) cv2.waitKey(0) cv2.destroyAllWindows()
[ "felipecbarelli@outlook.com" ]
felipecbarelli@outlook.com
87374c046ca131f0d17cee5a0b6ff9e4d3100afc
a5748a9f8868efc3b852e4ffca9437253514f7d3
/Python/except_2.py
dc6472fdaedf172bc934e87370f0f14128d71578
[]
no_license
yjlee0209/kite
d3cdf19c9a0822cfcceb81bf82c489a76c66ec38
35b6eca840b407dce5de21cbb48c9d10505af69a
refs/heads/master
2023-01-06T02:52:59.661488
2020-03-26T11:30:49
2020-03-26T11:30:49
219,877,467
0
0
null
2022-12-26T20:39:49
2019-11-06T00:30:48
Python
UTF-8
Python
false
false
385
py
list_ex = ['52', '324', '435', '스파이', '13'] list_result = [] for item in list_ex: try: float(item) except Exception as e: #pass print('type(e) :',type(e)) print('Exception e :', e) else: list_result.append(item) finally: print('한번의 반복 구문이 완료되었습니다') print(list_ex) print(list_result)
[ "tetrodotoxin0209@gmail.com" ]
tetrodotoxin0209@gmail.com
ba1244f844df688fa62a16498bbd5b5321fa98cd
a7f2eb07005e7dcc7600b751e4c8b1ef71a24c9e
/output/matplotlib_scripts/plot_logp.py
86b22e7af8595122f8f64369c8e7e40cb5ca7f3b
[]
no_license
eltevo/sps
66b288399b37020453b06ef3daaf35d0d3941cc6
ace2fb0f757b3f86e39807558c8cd2c6a19b38fa
refs/heads/float
2021-01-12T21:08:28.704909
2014-11-19T22:05:12
2014-11-19T22:05:12
39,156,535
0
0
null
2015-07-15T19:22:18
2015-07-15T19:22:17
null
UTF-8
Python
false
false
495
py
#!/usr/bin/python import numpy import matplotlib.pyplot as plt #reading files params=dict() params["log_p"]=numpy.loadtxt("chi_evol.dat") fig=plt.figure() ax=fig.add_subplot(1,1,1) ######################################## #plot parameter evolutions ######################################## for param in params: ax.plot(params[param]) ax.set_xlabel("N") ax.set_ylabel(param) ax.set_xscale("log") ax.set_yscale("log") fig.savefig("plots-python/evol_"+param+".png",dpi=100) ax.cla()
[ "dkribli@gmail.com" ]
dkribli@gmail.com
053616bd25236dbf71c21bdf956eb6f01dc4b930
df2332ad95f04ce245141fa6abf39fd6e828d511
/train.py
854661e62a3edbcc80084af72dfce3eb85c6ec74
[ "MIT" ]
permissive
z00bean/chexpert
74c82426db951c027fad1e7be2f11d7890ac6b16
3358d414e6185e50b41beecfc5df661c947f3e20
refs/heads/master
2020-09-09T23:20:12.711844
2020-01-28T17:18:22
2020-01-28T17:18:22
221,593,933
0
0
MIT
2019-11-14T02:26:57
2019-11-14T02:26:53
null
UTF-8
Python
false
false
29,195
py
#!/usr/bin/env python # coding: utf-8 # In[10]: import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms, utils from torch.utils.data import Dataset, TensorDataset, Sampler from torch.utils.data.dataloader import DataLoader print("PyTorch Version: ",torch.__version__) print("Torchvision Version: ",torchvision.__version__) import matplotlib.pyplot as plt import time import os import copy import pandas as pd import seaborn as sns from PIL import Image import sys from src.models import adamw, compare_auc_delong_xu, densenet, cosine_scheduler import src.models.efficient_densenet_pytorch.models.densenet as dnet2 #Alternative efficient densenet to test import h5py import zarr from pathlib import Path # In[11]: #Top level data directory (can be 'CheXpert-v1.0-small', 'CheXpert-v1.0', 'mimic-cxr') root_dir = 'data' which_data = 'CheXpert-v1.0' raw_data_dir = f'{root_dir}/raw/{which_data}' int_data_dir = f'{root_dir}/interim' proc_data_dir = f'{root_dir}/processed' #Data is split into two sets (may later create a training-dev set) phases = ['train', 'val'] #Path to csvfiles on training and validation data csvpath = {phase: f'{raw_data_dir}/{phase}.csv' for phase in phases} #Load data into dictionary of two Pandas DataFrames dframe = {phase: pd.read_csv(csvpath[phase]) for phase in phases} #Calculate sizes dataset_sizes = {phase:len(dframe[phase]) for phase in phases} print(os.listdir(raw_data_dir)) print(dframe['train'].shape, dframe['val'].shape) # In[12]: Image.open('data/raw/CheXpert-v1.0-small/valid/patient64574/study1/view1_frontal.jpg') # In[13]: # Models to choose from [efficient-densenet, resnet, alexnet, vgg, squeezenet, densenet, inception] model_name = "efficient-densenet" # Number of classes in the dataset num_classes = 14 # Batch size for training (change depending on how much memory you have) batch_size = 64 # Number of epochs to train for num_epochs = 5 #Number of minibatches to pass before printing out metrics checkpoint = 200 # Flag for feature extracting. When False, we finetune the whole model, when True we only update the reshaped layer params feature_extract = False #The number of training samples num_samples = dframe['train'].shape[0] #Class names that will be predicted class_names = dframe['train'].iloc[:,5:].columns #indices we will calculate AUC for, as in the CheXpert paper competition_tasks = torch.ByteTensor([0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0]) #Which approach to use when dealing with uncertain labels (as detailed in the CheXpert paper) u_approach = 'ones' #Using pretrained weights use_pretrained = True #filename for outputs filename = f'{which_data}_{model_name}_{u_approach}_{batch_size}' #Calculating weighting for imbalanced classes (input in loss criterion) df = dframe['train'].iloc[:,5:].copy() df = df.replace(-1,0) pos_weight = torch.Tensor([df[cl].sum()/df.shape[0] for cl in class_names]) # In[14]: # Use CUDA for PyTorch # use_cuda = 0 use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") torch.backends.cudnn.benchmark = True print('Using CUDA') if use_cuda else print('Using CPU') print(torch.cuda.memory_cached()/1e9) print(torch.cuda.max_memory_cached()/1e9) print(torch.cuda.memory_allocated()/1e9) print(torch.cuda.max_memory_allocated()/1e9) # In[15]: def train_model(model, dataloaders, criterion, optimizer, scheduler, competition_tasks, num_epochs=25, max_fpr=None, u_approach=None, is_inception=False, checkpoint=200): since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_auc = 0.0 missing = 0; fsize = dataset_sizes['train']/(checkpoint * batch_size) #Number of saved values for training metrics/epoch num_items = int(np.ceil((fsize+num_epochs) * num_epochs)) #Total number of items including saved validation values idx = 0 #index for adding to DataFrame columns = ['epoch','iteration','loss','accuracy','variance'] #Save training values every "checkpoint" batches, save num_epoch validation values: df = pd.DataFrame(np.zeros([num_items,len(columns)]),columns=columns) df['phase'] = '' for epoch in range(num_epochs): print(f'Epoch {epoch}/{num_epochs-1}') print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': scheduler.step() model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0; running_auc = 0.0; running_var = 0.0 # Iterate over data. for i, (inputs, labels) in enumerate(dataloaders[phase]): inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): if is_inception and phase == 'train': # From https://discuss.pytorch.org/t/how-to-optimize-inception-model-with-auxiliary-classifiers/7958 outputs, aux_outputs = model(inputs) loss1 = criterion(outputs, labels) loss2 = criterion(aux_outputs, labels) loss = loss1 + 0.4*loss2 else: outputs = model(inputs) loss = criterion(outputs, labels) if u_approach == "ignore": mask = labels.lt(0) #select u labels (-1) loss = torch.sum(loss.masked_select(mask)) #mask out uncertain labels # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # scheduler.batch_step() #USE WITH DENSENET and other scheduler # statistics running_loss += loss.item() * inputs.size(0) #select subset of 5 pathologies of interest labels_sub = labels[:,competition_tasks].cpu().squeeze().numpy() preds_sub = outputs[:,competition_tasks].detach().cpu().squeeze().numpy() if u_approach == "ignore": #mask out the negative values mask_sub = (labels_sub>-1) for j in range(labels_sub.shape[1]): label = labels_sub[:,j] pred = preds_sub[:,j] m = mask_sub[:,j] label = label[m]; pred = pred[m] try: tmp = compare_auc_delong_xu.delong_roc_variance(label, pred) running_auc += tmp[0] running_var += np.nansum(tmp[1]) except: missing += 1; continue else: for j in range(labels_sub.shape[1]): label = labels_sub[:,j] pred = preds_sub[:,j] tmp = compare_auc_delong_xu.delong_roc_variance(label, pred) running_auc += tmp[0] running_var += np.nansum(tmp[1]) if (i+1) % checkpoint == 0: # print every 'checkpoint' mini-batches # print('Missed {}'.format(missing)) print(f'{phase} Loss: {(running_loss / ((i+1) * batch_size)):.2f} DeLong AUC: {running_auc / (labels_sub.shape[1] * (i+1) * batch_size):.2f} Variance: {running_var / (labels_sub.shape[1] * (i+1) * batch_size):.2f}') df.iloc[idx,:] = [epoch+1, (i+1) * (epoch+1), running_loss / ((i+1) * batch_size), running_auc / (labels_sub.shape[1] * (i+1) * batch_size), running_var / (labels_sub.shape[1] * (i+1) * batch_size), phase] idx += 1 # break #just while testing epoch_loss = running_loss / dataset_sizes[phase] epoch_auc = running_auc / (dataset_sizes[phase] * labels_sub.shape[1]) epoch_var = running_var / (dataset_sizes[phase] * labels_sub.shape[1]) print(f'{phase} Epoch Loss: {epoch_loss:.2f} Epoch AUC: {epoch_auc:.2f} Epoch Variance: {epoch_var:.2f}') #With a small validation set would otherwise get no recorded values so: if phase == 'val': df.iloc[idx,:] = [epoch+1, 0, epoch_loss, epoch_auc, epoch_var, phase] idx += 1 # deep copy the model if phase == 'val' and epoch_auc > best_auc: best_auc = epoch_auc best_model_wts = copy.deepcopy(model.state_dict()) time_elapsed = time.time() - since print(f'Training complete in {time_elapsed // 60:.2f}m {time_elapsed % 60:.2f}s') print(f'Best val AUC: {best_auc:.2f}') print(f'Missed {missing} examples.') # load best model weights model.load_state_dict(best_model_wts) df.to_csv(f'models/{filename}.csv', index=False) return model # In[16]: def set_parameter_requires_grad(model, feature_extract): if feature_extract: for param in model.parameters(): param.requires_grad = False def initialize_model(model_name, num_classes, feature_extract, use_pretrained=True): # Initialize these variables which will be set in this if statement. Each of these # variables is model specific. model_ft = None input_size = 0 if model_name == "resnet": """ Resnet18 Not very heavy on the gpu """ model_ft = models.resnet18(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, num_classes) input_size = 224 elif model_name == "alexnet": """ Alexnet """ model_ft = models.alexnet(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier[6].in_features model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes) input_size = 224 elif model_name == "vgg": """ VGG11_bn """ model_ft = models.vgg11_bn(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier[6].in_features model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes) input_size = 224 elif model_name == "squeezenet": """ Squeezenet """ model_ft = models.squeezenet1_0(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) model_ft.classifier[1] = nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1)) model_ft.num_classes = num_classes input_size = 224 elif model_name == "densenet": """ Densenet Used in the CheXpert paper """ model_ft = models.densenet121(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier.in_features model_ft.classifier = nn.Linear(num_ftrs, num_classes) input_size = 224 elif model_name == "efficient-densenet": """memory-efficient densenet - https://github.com/wandering007/efficient-densenet-pytorch 10-20% change in memory usage, about the same speed as original DenseNet """ # # growth_rate = 32 #(int) - how many filters to add each layer (`k` in paper) block_config = (6, 12, 24, 16) #(list of 3 or 4 ints) - how many layers in each pooling block compression = 0.5 #Reduction in size num_init_features = 2 * growth_rate #(int) - the number of filters to learn in the first convolution layer bn_size = 4 #(int) - mult. factor for number of bottle neck layers (i.e. bn_size * k features in the bottleneck layer) drop_rate = 0. #(float) - dropout rate after each dense layer efficient = True #(bool) - set to True to use checkpointing. Much more memory efficient, but slower. input_size = 224 model_ft = densenet.DenseNet(num_init_features=num_init_features, block_config=block_config, compression=compression, input_size=input_size, bn_size=bn_size, drop_rate=drop_rate, num_classes=1000, efficient=efficient) if use_pretrained: partial_state_dict = torch.load('src/models/densenet121_effi.pth') state_dict = model_ft.state_dict() state_dict.update(partial_state_dict) model_ft.load_state_dict(state_dict, strict=True) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier.in_features model_ft.classifier = nn.Linear(num_ftrs, num_classes) elif model_name == "efficient-densenet-v2": """memory-efficient densenet, alternative version - https://github.com/gpleiss/efficient_densenet_pytorch Can load batches more than twice as large as original DenseNet, at less than half the speed """ # # growth_rate = 32 #(int) - how many filters to add each layer (`k` in paper) block_config = (6, 12, 24, 16) #(list of 3 or 4 ints) - how many layers in each pooling block compression = 0.5 #Reduction in size num_init_features = 2 * growth_rate #(int) - the number of filters to learn in the first convolution layer bn_size = 4 #(int) - mult. factor for number of bottle neck layers (i.e. bn_size * k features in the bottleneck layer) drop_rate = 0. #(float) - dropout rate after each dense layer efficient = True #(bool) - set to True to use checkpointing. Much more memory efficient, but slower. input_size = 224 # model_ft = densenet.DenseNet(num_init_features=num_init_features, block_config=block_config, compression=compression, # input_size=input_size, bn_size=bn_size, drop_rate=drop_rate, num_classes=1000, efficient=efficient) model_ft = dnet2.DenseNet(growth_rate=32, block_config=block_config, compression=0.5, num_init_features=num_init_features, bn_size=4, drop_rate=0, num_classes=1000, small_inputs=False, efficient=True) if use_pretrained: state_dict = model_ft.state_dict() partial_state_dict = torch.load('src/models/densenet121_effi.pth') partial_state_dict = {k: v for k, v in partial_state_dict.items() if k in state_dict} state_dict.update(partial_state_dict) model_ft.load_state_dict(state_dict, strict=True) set_parameter_requires_grad(model_ft, feature_extract) num_ftrs = model_ft.classifier.in_features model_ft.classifier = nn.Linear(num_ftrs, num_classes) elif model_name == "inception": """ Inception v3 Be careful, expects (299,299) sized images and has auxiliary output """ model_ft = models.inception_v3(pretrained=use_pretrained) set_parameter_requires_grad(model_ft, feature_extract) # Handle the auxilary net num_ftrs = model_ft.AuxLogits.fc.in_features model_ft.AuxLogits.fc = nn.Linear(num_ftrs, num_classes) # Handle the primary net num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs,num_classes) input_size = 299 else: print("Invalid model name, exiting...") exit() return model_ft, input_size # In[17]: class CheXpertDataset(Dataset): """CheXpert dataset.""" def __init__(self, phase, u_approach, num_samples, datapath): """ Args: chex_frame (DataFrame): Train or validation data root_dir (string): Directory with all the images. tforms (Torch Transform): pre-processing transforms targets (DataFrame): Modifies labels depending on u_approach """ self.phase = phase self.u_approach = u_approach self.num_samples = num_samples self.datapath = datapath # self.data = zarr.open_group(self.datapath,mode='r') # self.data = h5py.File(f'{self.datapath}', 'r',libver='latest', swmr=True) self.data = None def __len__(self): return self.num_samples def __getitem__(self, idx): if not self.data: #open in thread self.data = h5py.File(f'{self.datapath}', 'r') img = np.float32(self.data[(f"X{idx}")][()]) # if self.phase == 'train' and np.random.randint(2)==1: # img = np.flip(img,axis=2) #some minor data augmentation labels = np.float32(self.data[(f"y{idx}")][()]) return img, labels # In[18]: #Initialize model_ft, input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=use_pretrained) #preprocess target labels before placing in dataloader labels_array = {phase: dframe[phase].iloc[:,5:].copy().fillna(0) for phase in phases} for phase in labels_array.keys(): if u_approach == 'ones': labels_array[phase] = labels_array[phase].replace(-1,1) elif u_approach == 'zeros': labels[phase] = labels_array[phase].replace(-1,0) labels_array[phase] = torch.FloatTensor(labels_array[phase].to_numpy()) #needed when using cross-entropy loss #Transforms to perform on images (already performed for hdf5 files) tforms = { 'train': transforms.Compose([ transforms.Resize(input_size), transforms.CenterCrop(input_size), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.Resize(input_size), transforms.CenterCrop(input_size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ])} hdf5paths = {phase: f'{int_data_dir}/{phase}_u{u_approach}_inp{input_size}_processed.h5' for phase in phases} zarrpaths = {phase: f'{proc_data_dir}/{phase}_u{u_approach}_inp{input_size}_processed.zarr' for phase in phases} # Create the datasets # datasets = {phase: CheXpertDataset(phase=phase, u_approach=u_approach, num_samples=dataset_sizes[phase], datapath=zarrpaths[phase]) for phase in phases} datasets = {phase: CheXpertDataset(phase=phase, u_approach=u_approach, num_samples=dataset_sizes[phase], datapath=hdf5paths[phase]) for phase in phases} # In[19]: def proc_images(img_paths, labels_array, data_dir, u_approach, input_size, phases=['train', 'val'], tforms=None): """ Saves compressed, resized images as HDF5 datsets Returns data.h5, where each dataset is an image or class label e.g. X23,y23 = image and corresponding class labels """ for phase in phases: print(f'Processing {phase} files...') with h5py.File(f'{data_dir}/{phase}_u{u_approach}_inp{input_size}_processed.h5', 'w') as hf: for i,img_path in enumerate(img_paths[phase]): if i % 2000 == 0: print(f"{i} images processed") # Images #Using Pillow-SIMD rather than Pillow img = Image.open(img_path).convert('RGB') if tforms: img = tforms[phase](img) Xset = hf.create_dataset( name=f"X{i}", data=img, shape=(3, input_size, input_size), maxshape=(3, input_size, input_size), compression="lzf", shuffle="True") # Labels yset = hf.create_dataset( # name=f"y{i}", name=f"y{i}", data = labels_array[phase][i,:], shape=(num_classes,), maxshape=(num_classes,), compression="lzf", shuffle="True", dtype="i1") print('Finished!') hdf50 = Path(f'{int_data_dir}/{phases[0]}_u{u_approach}_inp{input_size}_processed.h5') hdf51 = Path(f'{int_data_dir}/{phases[1]}_u{u_approach}_inp{input_size}_processed.h5') zarr0 = Path(f'{proc_data_dir}/{phases[0]}_u{u_approach}_inp{input_size}_processed.zarr') zarr1 = Path(f'{proc_data_dir}/{phases[1]}_u{u_approach}_inp{input_size}_processed.zarr') if not (hdf50.is_file() or hdf51.is_file()): img_paths = {phase: raw_data_dir + dframe[phase].iloc[:,0] for phase in phases} proc_images(img_paths, labels_array, data_dir, u_approach, input_size, phases=phases, tforms=tforms) if not (zarr0.is_dir() or zarr1.is_dir()): source = h5py.File(hdf5paths['val'], mode='r') dest = zarr.open_group(zarrpaths['val'], mode='w') zarr.copy_all(source, dest, log="zarr1.output") source = h5py.File(hdf5paths['train'], mode='r') dest = zarr.open_group(zarrpaths['train'], mode='w') zarr.copy_all(source, dest, log="zarr0.output") # In[20]: # #Accounting for imbalanced classes # df = dframe['train'].iloc[:,5:].fillna(0).copy() # df = df.replace(-1, np.nan) # # #Get a list of the number of positive, negative, and uncertain samples for each class # class_sample_count = [df[df==t].count() for t in [-1, 0, 1]] # # #Use this to calculate the weight for positive, negative, and uncertain samples for each class # weights = [num_classes * class_sample_count[t] * (1 / num_samples) for t in range(len(class_sample_count))] # # #Create list of weights as long as the dataset # sample_weights = weights[0] * (df==-1) + weights[1] * (df==0) + weights[2] * (df==1) # sample_weights.head(3) # # sample_weights = sample_weights.to_numpy() # # print(weights[1]) # # #Load into sampler # # sampler = None # # # sampler = torch.utils.data.WeightedRandomSampler(sample_weights, 1, replacement=True) # In[21]: # Setting parameters # num_workers = torch.get_num_threads() num_workers = 1 #Use with hdf5 files params = {'train': {'batch_size': batch_size, 'shuffle': True, 'num_workers': num_workers, 'pin_memory':True, 'sampler': None}, 'val': {'batch_size': batch_size, 'shuffle': False, 'num_workers': num_workers, 'pin_memory':True}} if params['train']['sampler'] is not None: params['train']['shuffle'] = False dataloaders = {phase: DataLoader(datasets[phase], **params[phase]) for phase in phases} # In[22]: # #Show transformed images # fig = plt.figure() # for i in range(len(datasets['train'])): # sample = datasets['train'][i] # print(i, sample[0].shape, sample[1].shape) # ax = plt.subplot(1, 4, i + 1) # plt.tight_layout() # ax.set_title('Sample #{}'.format(i)) # ax.axis('off') # plt.imshow(sample[0][0,:,:]) # if i == 3: # plt.show() # break # In[23]: # #Checking for shuffling (or not) # for i, (inputs, labels) in enumerate(dataloaders['val']): # if i < 1: # print(labels.size(0)) # labels[labels==-1]=0 # print(torch.sum(labels,dim=0)) # labels = labels[:,competition_tasks] # print(labels.shape) # # else: # break # In[24]: # #Checking times for various image processing libraries # times = [] # t0 = time.time() # for i, (inputs, labels) in enumerate(dataloaders['train']): # if i < 1: # times.append(time.time()-t0) # t0 = time.time() # break # print('Average time to load up data: {} s'.format(np.round(np.mean(times),4))) # #With batch size of 64, num_cores = 1 # # 2.8-3 s for zarr dataset # # 3.6-4 s for hdf5 datasets # # 5.3-6 s for original method with Pillow-SIMD # # 5.5-6.4 s for alternative PIL method # # 5.7-6.1 s for cv2 # In[25]: # #Comparing zarr and hdf5 more precisely # import timeit # setup = ''' # import h5py # import zarr # zarr = zarr.open_group('data/processed/train_uones_inp224_processed.zarr','r' # )''' # stmt1 = ''' # with h5py.File('data/interim/train_uones_inp224_processed.h5','r') as h5: # h5["X1"][:] # ''' # stmt2 = ''' # zarr["X1"][:] # ''' # # timeit statement # print('hdf5:') # print(timeit.timeit(setup = setup, stmt = stmt1, number = 10000)) # print('zarr:') # print(timeit.timeit(setup = setup, stmt = stmt2, number = 10000)) # In[26]: # # Helper function to show a batch # def show_img_batch(sample_batched): # """Show image with labels for a batch of samples.""" # images_batch, labels_batch = \ # sample_batched[0], sample_batched[1] # batch_size = len(images_batch) # im_size = images_batch.size(2) # grid = utils.make_grid(images_batch) # plt.imshow(grid.numpy().transpose((1, 2, 0))) # for i_batch, sample_batched in enumerate(dataloaders['train']): # print(i_batch, sample_batched[0].size(), sample_batched[1].size()) # # observe 4th batch and stop. # if i_batch == 3: # plt.figure() # show_img_batch(sample_batched) # plt.axis('off') # plt.ioff() # plt.show() # break # In[27]: try: model_ft.load_state_dict(torch.load(f'models/{filename}.pt')) #load weights if already completed print('Loading weights') except: print('Starting from scratch..') if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") model_ft = nn.DataParallel(model_ft,device_ids=[0, 1]) model_ft = model_ft.to(device) if u_approach == 'ignore': #Use masked binary cross-entropy for first run criterion = nn.BCEWithLogitsLoss(reduction='none',pos_weight=pos_weight).to(device) else: criterion = nn.BCEWithLogitsLoss(reduction='sum',pos_weight=pos_weight).to(device) # Observe that all parameters are being optimized # optimizer = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) # # Pick AdamW optimizer - https://github.com/mpyrozhok/adamwr optimizer = adamw.AdamW(model_ft.parameters(), lr=1e-3, weight_decay=1e-5) # Decay LR by a factor of 0.1 every 7 epochs # scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1) epoch_size = int(num_samples / batch_size) # number of training examples/batch size # #Cosine annealing: adjusting on batch update rather than epoch - https://github.com/mpyrozhok/adamwr scheduler = cosine_scheduler.CosineLRWithRestarts(optimizer, batch_size, epoch_size, restart_period=5, t_mult=1.2) # In[32]: model_ft = train_model(model_ft, dataloaders, criterion, optimizer, scheduler, competition_tasks, num_epochs=num_epochs, u_approach=u_approach, is_inception=(model_name=="inception"), checkpoint=checkpoint) if torch.cuda.device_count() > 1: torch.save(model_ft.module.state_dict(), f'models/{filename}.pt') else: torch.save(model_ft.state_dict(), f'models/{filename}.pt') # In[9]: #Visualizing model predictions def visualize_model(model, num_images=6): tform = transforms.Compose([transforms.functional.to_pil_image, transforms.functional.to_grayscale]) was_training = model.training model.eval() images_so_far = 0 fig = plt.figure() with torch.no_grad(): for i, (inputs, labels) in enumerate(dataloaders['val']): inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) _, preds = torch.max(outputs, 1) for j in range(inputs.size()[0]): images_so_far += 1 ax = plt.subplot(num_images//2, 2, images_so_far) ax.axis('off') img = tform(inputs[j].cpu()) ax.set_title('First prediction: {}'.format(class_names[preds[j]])) plt.imshow(img) if images_so_far == num_images: model.train(mode=was_training) return model.train(mode=was_training) model_ft, input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=True) model_ft.load_state_dict(torch.load(f'models/{filename}.pt')) #load new weights model_ft.to(device) visualize_model(model_ft) # In[7]: #Load csv data back into Pandas DataFrame results = pd.read_csv(f'models/{filename}.csv') results.head(3) # In[29]: g = sns.relplot(x="epoch", y="loss", hue='phase', kind='line', data=results)
[ "dcela@users.noreply.github.com" ]
dcela@users.noreply.github.com
cfd3d065e88bba496b6e2c6e12309d1ab738d6f9
9ab6e3a6385b642b25b198ead03c922b7d37dca9
/programming_notes/Python/15_network_analysis.py
fd07172e56a694f48f8b791ba18cc453ab9558e1
[]
no_license
Intangible-pg18/KnowledgeBank
5366d2d42d16d401c2328077aa3ce39c465a45c9
90166677da7216f345d3e2174f9ec448b6834d40
refs/heads/master
2023-05-30T16:56:26.658880
2021-06-22T15:51:21
2021-06-22T15:51:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,282
py
# networkx v.1.11 import networkx as nx import nxviz as nv import matplotlib.pyplot as plt from itertools import combinations # Intro ---------------------------------------------------------------------------------------------------------------- # Load Twitter network T = nx.read_gpickle("data/ego-twitter.p") # Graph size len(T.nodes()) # First edge T.edges(data=True)[0] # Plot network nx.draw(T) plt.show() # Queries on graphs - extracting nodes and edges of interest noi = [n for n, d in T.nodes(data=True) if d['occupation'] == 'scientist'] eoi = [(u, v) for u, v, d in T.edges(data=True) if d['date'] < date(2010, 1, 1)] # Types of grahps undirected = nx.Graph() directed = nx.DiGraph() multiedge = nx.MultiGraph() multiedge_directed = nx.MultiDiGraph() # Specifying a weight on edges # Weights can be added to edges in a graph, typically indicating the "strength" of an edge. # In NetworkX, the weight is indicated by the 'weight' key in the metadata dictionary. T.edge[1][10] # Set the 'weight' attribute of the edge between node 1 and 10 of T to be equal to 2 T.edge[1][10]['weight'] = 2 T.edge[1][10] # Set the weight of every edge involving node 293 to be equal to 1.1 for u, v, d in T.edges(data=True): if 293 in [u, v]: T.edge[u][v]['weight'] = 1. # Checking whether there are self-loops in the graph T.number_of_selfloops() def find_selfloop_nodes(G): """ Finds all nodes that have self-loops in the graph G. """ nodes_in_selfloops = [] for u, v in G.edges(): if u == v: nodes_in_selfloops.append(u) return nodes_in_selfloops # Check whether number of self loops equals the number of nodes in self loops # (assert throws an error if the statement evaluates to False) assert T.number_of_selfloops() == len(find_selfloop_nodes(T)) # Network visualization ------------------------------------------------------------------------------------------------ # Matrix plot m = nv.MatrixPlot(T) m.draw() plt.show() # Convert T to a matrix format: A A = nx.to_numpy_matrix(T) # Convert A back to the NetworkX form as a directed graph: T_conv T_conv = nx.from_numpy_matrix(A, create_using=nx.DiGraph()) # Check that the `category` metadata field is lost from each node for n, d in T_conv.nodes(data=True): assert 'category' not in d.keys() # Circos plot c = nv.CircosPlot(T) c.draw() plt.show() # Arc plot a = ArcPlot(T, node_order='category', node_color='category') a.draw() plt.show() # Important nodes ------------------------------------------------------------------------------------------------------ # The number of neighbors that a node has is called its "degree". # Degree centrality = (no. neighbours) / (no. all possible neighbours) -> N if self-loops allowed, N-1 otherwise # Get number of neighbours of node 1 T.neighbors(1) # A function that returns all nodes that have m neighbors def nodes_with_m_nbrs(G, m): """ Returns all nodes in graph G that have m neighbors. """ nodes = set() for n in G.nodes(): if len(G.neighbors(n)) == m: nodes.add(n) return nodes # Compute and print all nodes in T that have 6 neighbors six_nbrs = nodes_with_m_nbrs(T, 6) print(six_nbrs) # Compute degree over the entire network degrees = [len(T.neighbors(n)) for n in T.nodes()] # Compute the degree centrality of the Twitter network: deg_cent deg_cent = nx.degree_centrality(T) # Plot a histogram of the degree centrality distribution of the graph. plt.figure() plt.hist(list(deg_cent.values())) plt.show() # Plot a histogram of the degree distribution of the graph plt.figure() plt.hist(list(degrees)) plt.show() # Plot a scatter plot of the centrality distribution and the degree distribution plt.figure() plt.scatter(degrees, list(deg_cent.values())) plt.show() # Graph algorithms for path finding # Breadth-first search (BFS) algorithm - you start from a particular node and iteratively search through # its neighbors and neighbors' neighbors until you find the destination node. def path_exists(G, node1, node2): """ This function checks whether a path exists between two nodes (node1, node2) in graph G. """ visited_nodes = set() queue = [node1] for node in queue: neighbors = G.neighbors(node) if node2 in neighbors: print('Path exists between nodes {0} and {1}'.format(node1, node2)) return True break else: visited_nodes.add(node) queue.extend([n for n in neighbors if n not in visited_nodes]) # Check to see if the final element of the queue has been reached if node == queue[-1]: print('Path does not exist between nodes {0} and {1}'.format(node1, node2)) return False # Shortest paths - set of paths where each of them is shortest between some two nodes, for all nodes # Betweenness centrality = (no. shortest paths that run through the node) /(all possible shortest paths) # Betweenness centrality captures bottlenecks in the graph # # Betweenness centrality is a node importance metric that uses information about the shortest paths in a network. # It is defined as the fraction of all possible shortest paths between any pair of nodes that pass through the node. bet_cen = nx.betweenness_centrality(T) deg_cen = nx.degree_centrality(T) plt.scatter(list(bet_cen.values()), list(deg_cen.values())) plt.show() # Define find_nodes_with_highest_deg_cent() def find_nodes_with_highest_deg_cent(G): deg_cent = nx.degree_centrality(G) max_dc = max(list(deg_cent.values())) nodes = set() for k, v in deg_cent.items(): if v == max_dc: nodes.add(k) return nodes # Find the node(s) that has the highest degree centrality in T: top_dc top_dc = find_nodes_with_highest_deg_cent(T) # Cliques and communities ---------------------------------------------------------------------------------------------- # Identifying triangle relationships def is_in_triangle(G, n): """ Checks whether a node `n` in graph `G` is in a triangle relationship or not. Returns a boolean. """ in_triangle = False # Iterate over all possible triangle relationship combinations for n1, n2 in combinations(G.neighbors(n), 2): # Check if an edge exists between n1 and n2 if G.has_edge(n1, n2): in_triangle = True break return in_triangle # Finding nodes involved in triangles # NetworkX provides an API for counting the number of triangles that every node is involved in: nx.triangles(G). # It returns a dictionary of nodes as the keys and number of triangles as the values. def nodes_in_triangle(G, n): """ Returns the nodes in a graph `G` that are involved in a triangle relationship with the node `n`. """ triangle_nodes = set([n]) for n1, n2 in combinations(G.neighbors(n), 2): if G.has_edge(n1, n2): triangle_nodes.add(n1) triangle_nodes.add(n2) return triangle_nodes # Finding open triangles def node_in_open_triangle(G, n): """ Checks whether pairs of neighbors of node `n` in graph `G` are in an 'open triangle' relationship with node `n`. """ in_open_triangle = False # Iterate over all possible triangle relationship combinations for n1, n2 in combinations(G.neighbors(n), 2): # Check if n1 and n2 do NOT have an edge between them if not G.has_edge(n1, n2): in_open_triangle = True break return in_open_triangle # Compute the number of open triangles in T num_open_triangles = 0 for n in T.nodes(): if node_in_open_triangle(T, n): num_open_triangles += 1 print(num_open_triangles) # Finding all maximal cliques of size "n" # Maximal cliques are cliques that cannot be extended by adding an adjacent edge, and are a useful property of the graph # when finding communities. NetworkX provides a function that allows you to identify the nodes involved in each maximal # clique in a graph: nx.find_cliques(G). def maximal_cliques(G, size): """ Finds all maximal cliques in graph `G` that are of size `size`. """ mcs = [] for clique in nx.find_cliques(G): if len(clique) == size: mcs.append(clique) return mcs # Check that there are 33 maximal cliques of size 3 in the graph T assert len(maximal_cliques(T, 3)) == 33 # Subgraphs ------------------------------------------------------------------------------------------------------------ # There may be times when you just want to analyze a subset of nodes in a network. To do so, you can copy them out into # another graph object using G.subgraph(nodes), which returns a new graph object (of the same type as the original # graph) that is comprised of the iterable of nodes that was passed in. nodes_of_interest = [29, 38, 42] def get_nodes_and_nbrs(G, nodes_of_interest): """ Returns a subgraph of the graph `G` with only the `nodes_of_interest` and their neighbors. """ nodes_to_draw = [] for n in nodes_of_interest: nodes_to_draw.append(n) for nbr in G.neighbors(n): nodes_to_draw.append(nbr) return G.subgraph(nodes_to_draw) T_draw = get_nodes_and_nbrs(T, nodes_of_interest) nx.draw(T_draw) plt.show()
[ "oleszak.michal@gmail.com" ]
oleszak.michal@gmail.com
9c4005d439aeae7681ab7a4b900e8b6e9b0b4dc6
f98521d2e7ae4c36ebdc2672a388ffa9ff612f1d
/numpy_buffer.py
a1d062649a87360d77d252b2a62829c101fb4083
[]
no_license
SimonCouv/zoe-data-prep
06888f8a2732cda4a1c55bc1cdbb9fa3478afc8f
879b17f2bfd75087c4134ec828d066393ab54d1e
refs/heads/master
2022-10-08T15:42:33.690903
2020-05-27T08:04:23
2020-05-27T08:04:23
257,559,283
0
0
null
2020-04-21T10:27:02
2020-04-21T10:27:01
null
UTF-8
Python
false
false
3,426
py
# Copyright 2020 KCL-BMEIS - King's College London # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np class NumpyBuffer2: def __init__(self, dtype, block_pow=8): self.dtype_ = dtype self.list_ = list() def append(self, value): self.list_.append(value) def finalise(self): result = np.asarray(self.list_, dtype=self.dtype_) del self.list_ return result class NumpyBuffer: def __init__(self, dtype, block_pow=8): self.block_shift_ = block_pow self.block_size_ = 1 << block_pow self.block_mask_ = self.block_size_ - 1 self.blocks_ = list() self.dtype_ = dtype self.current_block_ = None self.current_ = 0 def append(self, value): if self.current_ == len(self.blocks_) * self.block_size_: self.blocks_.append(np.zeros(self.block_size_, dtype=self.dtype_)) self.current_block_ = self.blocks_[-1] self.current_block_[self.current_ & self.block_mask_] = value self.current_ += 1 def finalise(self): if self.current_ == 0: return None final = np.zeros(self.current_, dtype=self.dtype_) start = 0 for b in range(len(self.blocks_) - 1): cur_block = self.blocks_[b] final[start:start + self.block_size_] = cur_block start += self.block_size_ del cur_block current = self.current_ & self.block_mask_ last_block = self.blocks_[-1] final[start:start + current] = last_block[0:current] del last_block self.blocks_ = list() self.current_ = 0 return final class ListBuffer: def __init__(self, block_pow=8): self.block_shift_ = block_pow self.block_size_ = 1 << block_pow self.block_mask_ = self.block_size_ - 1 self.blocks_ = list() self.current_ = 0 def append(self, value): if self.current_ == len(self.blocks_) * self.block_size_: self.blocks_.append([None] * self.block_size_) self.blocks_[self.current_ >> self.block_shift_][self.current_ & self.block_mask_] = value self.current_ += 1 def finalise(self): if self.current_ == 0: return None final = [None] * self.current_ start = 0 for b in range(len(self.blocks_) - 1): cur_block = self.blocks_[b] final[start:start + self.block_size_] = cur_block start += self.block_size_ del cur_block current = self.current_ & self.block_mask_ last_block = self.blocks_[-1] final[start:start + current] = last_block[0:current] del last_block self.blocks_ = list() self.current_ = 0 return final # x = np.zeros(32) # y = np.asarray([x for x in range(16)]) # start = 0 # inc = 16 # x[start:start+inc] = y # print(y)
[ "ben.murray@gmail.com" ]
ben.murray@gmail.com
b725708fa9460c2515398779cf53ed28674423eb
53ccc4f5198d10102c8032e83f9af25244b179cf
/SoftUni Lessons/Python Development/Python Advanced January 2020/Python OOP/REDO2022/04 - Classes and Objects - Exercise/05_to_do_list/project/section.py
1aaf144047fe53885131a181834746578aa9e3f0
[]
no_license
SimeonTsvetanov/Coding-Lessons
aad32e0b4cc6f5f43206cd4a937fec5ebea64f2d
8f70e54b5f95911d0bdbfda7d03940cb824dcd68
refs/heads/master
2023-06-09T21:29:17.790775
2023-05-24T22:58:48
2023-05-24T22:58:48
221,786,441
13
6
null
null
null
null
UTF-8
Python
false
false
1,242
py
from project.task import Task class Section: def __init__(self, name: str): self.name = name self.tasks = [] def add_task(self, new_task: Task): present_task = [task for task in self.tasks if task == new_task] # TODO Check by name if problem if present_task: return f"Task is already in the section {self.name}" else: self.tasks.append(new_task) return f"Task {new_task.details()} is added to the section" def complete_task(self, task_name: str): found_task = [t for t in self.tasks if t.name == task_name] if found_task: found_task[0].completed = True return f"Completed task {task_name}" else: return f"Could not find task with the name {task_name}" def clean_section(self): len_tasks = 0 for task in self.tasks: if task.completed: self.tasks.remove(task) len_tasks += 1 return f"Cleared {len_tasks} tasks." def view_section(self): result = f"Section {self.name}:\n" for t in self.tasks: result += f"{t.details()}\n" return result[:-1]
[ "noreply@github.com" ]
SimeonTsvetanov.noreply@github.com
f67e2096d535a42e01b1e0f721fdfcf33c3eff2d
d7d1b5cdcee50e4a9c8ce9c2f081ccc7aa566443
/blog/migrations/0005_auto__del_field_artist_genres.py
00c8aa4e1dbb0e9c27ef47402d2b759298632f27
[]
no_license
ouhouhsami/django-bandwebsite
a57bdce9d14bd365e8749b92c63d927f65693531
328a765980f94e1aacc86d6384ef8becea156299
refs/heads/master
2016-09-05T21:48:17.931168
2013-03-18T17:18:19
2013-03-18T17:18:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,190
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Artist.genres' db.delete_column('blog_artist', 'genres_id') def backwards(self, orm): # Adding field 'Artist.genres' db.add_column('blog_artist', 'genres', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['blog.MusicGenre'], null=True, blank=True), keep_default=False) models = { 'blog.artist': { 'Meta': {'object_name': 'Artist'}, 'birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'death': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'posts': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['blog.Post']", 'symmetrical': 'False'}) }, 'blog.artistposition': { 'Meta': {'unique_together': "(('artist', 'related'),)", 'object_name': 'ArtistPosition'}, 'artist': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'subject'", 'to': "orm['blog.Artist']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'proximity_factor': ('django.db.models.fields.IntegerField', [], {}), 'related': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'target'", 'to': "orm['blog.Artist']"}) }, 'blog.category': { 'Meta': {'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'blog.musicgenre': { 'Meta': {'object_name': 'MusicGenre'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blog.MusicGenre']", 'null': 'True', 'blank': 'True'}) }, 'blog.post': { 'Meta': {'object_name': 'Post'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blog.Category']"}), 'date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}), 'text': ('tinymce.models.HTMLField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['blog']
[ "samuel.goldszmidt@gmail.com" ]
samuel.goldszmidt@gmail.com
21088c8beaf33fe0e70fdda87227af7dbfbaf4a9
8d1daccc0bf661b0b1450d6a128b904c25c4dea2
/todo-django/todos/serializers.py
277842b2002b141f2194e0509895d94b7adab3d5
[]
no_license
JiminLee411/todo-vue-django
e7cea19ff4ffe6b215c3105f40246830bdf249c0
f8c13c9498848247f614451c013f18b3050c6a1e
refs/heads/master
2023-01-08T14:33:38.629286
2019-11-20T01:36:34
2019-11-20T01:36:34
222,368,675
0
0
null
2023-01-05T01:06:53
2019-11-18T05:14:23
Python
UTF-8
Python
false
false
497
py
from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Todo class TodoSerializers(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'title', 'user', 'is_completed') class UserSerializers(serializers.ModelSerializer): todo_set = TodoSerializers(many=True) # 1:N관계에 있는것을 표현하는 방식 class Meta: model = get_user_model() fields = ('id', 'username', 'todo_set')
[ "wlals41189@gmail.com" ]
wlals41189@gmail.com
5b83b5c02be837c72f5afda5d9887e6631dddcb3
fdbb69f862ae7a6197c5dd6bba0069ea95e0c47b
/Debugging/EMADs/bwz.py
489835c45b74f9b90125f24665310fe60dd2bf25
[]
no_license
Mellanox/mlxsw
378536c83491043018fe6ba33d045f297875eb5a
5dc6e0ccc5aa7082a60cd18b4e13e499d07c868c
refs/heads/master
2023-09-01T21:24:49.579523
2023-07-13T08:44:28
2023-07-13T10:48:28
61,218,692
171
45
null
null
null
null
UTF-8
Python
false
false
9,176
py
#! /usr/bin/python """ Copyright 2018 Mellanox Technologies. All rights reserved. Licensed under the GNU General Public License, version 2 as published by the Free Software Foundation; see COPYING for details. """ __author__ = """ petrm@mellanox.com (Petr Machata) """ import os import sys import struct import pcapy import errno import getopt from common import pcap_header_out, pcap_packet_header, tag_dict, \ tlv_bus_name, tlv_dev_name, tlv_driver_name, tlv_incoming, tlv_type, tlv_buf def usage(): sys.stdout.write( "{argv[0]} [OPTIONS...] [FILE]\n" "\n" "Bearbeitungswerkzeug is a tool for processing pcap files captured by\n" "devlink-hwmsg.py. It's a shell filter that reads packets from one stream\n" "and produces a stream of packets filtered and transformed from the input.\n" "There's a simple DSL for selecting which packets to filter out and which\n" "to keep, and a way to describe what information and in which format should\n" "be included in the output stream.\n" "\n" "Options:\n" " -f EXPR Packet filter expression (which packets to include)\n" " -s EXPR Packet slicer expression (what to include in a packet)\n" ' -r FILE Read input from FILE ("-" means stdin, the default)\n' ' -w FILE Write output to FILE ("-" means stdout, the default)\n' ' -t TYPE LINKTYPE to use in pcap header (the default is 162)\n' " --help Show this help and exit\n" " --show Show filter and slicer expressions and exit\n" "\n" "Filter expressions:\n" " Keywords:\n" " bus Name of the bus where the message was captured\n" " dev Name of the device where the message was captured\n" " driver Name of the driver managing the device\n" " incoming Whether the message was send from the device to the kernel\n" " outgoing The opposite of incoming\n" " type Type of the message\n" " buf The message itself\n" "\n" " Literals:\n" ' "X" Literal string <X>\n' " 123 Literal numbers\n" " True,False Booleans\n" "\n" " Compound expressions:\n" " X == Y Expressions X and Y evaluate to the same value\n" " X != Y The opposite\n" " X & Y Boolean conjunction\n" " X | Y Boolean disjunction\n" " ~X Boolean negation ('outgoing' is the same as '~incoming')\n" " X[Y] Sequence (string) access\n" " X[Y:Z] Sequence (string) slicing\n" "\n" " Examples:\n" ' driver == "mlxsw_spectrum" # Just messages to this driver\n' ' driver[:5] == "mlxsw" # Messages to any mlxsw driver\n' ' incoming & (driver == "X") # Only incoming messages to this driver\n' "\n" "Slicer expressions:\n" " Keywords:\n" " The same suite of keywords is supported for slicing as well.\n" "\n" " Combiners:\n" " X, Y, Z Dump values of these keywords one after another\n" " tlv(X, Y, Z) Dump the values in the same TLV format\n" "\n" " Examples:\n" " buf # Just the message payload without TLV marking\n" " tlv(incoming, buf) # These two pieces of data in TLV format\n" .format(argv=sys.argv) ) try: optlist, args = getopt.gnu_getopt(sys.argv[1:], 'f:r:s:t:vw:', ["help", "show"]) except(getopt.GetoptError, e): print(e) sys.exit(1) query_string = "True" slicer_string = "tlv(*all)" show_exprs_and_exit = False read_file = "-" write_file = "-" link_type = 162 opts = dict(optlist) if "--help" in opts: usage() sys.exit(0) if "--show" in opts: show_exprs_and_exit = True if "-f" in opts: query_string = opts["-f"] if "-s" in opts: slicer_string = opts["-s"] if "-r" in opts: read_file = opts["-r"] if "-w" in opts: write_file = opts["-w"] if "-v" in opts: verbose = True if "-t" in opts: link_type = int(opts["-t"]) class Q(object): def __eq__(self, other): return Binary(self, other, "(%s == %s)", lambda a, b: a == b) def __ne__(self, other): return Binary(self, other, "(%s != %s)", lambda a, b: a != b) def __getitem__(self, key): return Binary(self, key, "(%s[%s])", lambda a, b: a[b]) def __and__(self, other): return Binary(self, other, "(%s & %s)", lambda a, b: a and b) def __or__(self, other): return Binary(self, other, "(%s | %s)", lambda a, b: a or b) def __invert__(self): return Unary(self, "(~%s)", lambda a: not a) class Immediate(Q): def __init__(self, value, tag=None): self._tag = tag self._value = value def value(self): return self._value def tag(self): return self._tag def evaluate(self, tlv): return self def __str__(self): return repr(self._value) class Unary(Q): def __init__(self, a, fmt, f): self._a = a self._fmt = fmt self._f = f def evaluate(self, tlv): a = evaluate(self._a, tlv) return Immediate(self._f(a.value()), None) def __str__(self): return self._fmt % self._a class Binary(Q): def __init__(self, a, b, fmt, f): self._a = a self._b = b self._fmt = fmt self._f = f def evaluate(self, tlv): a = evaluate(self._a, tlv) b = evaluate(self._b, tlv) return Immediate(self._f(a.value(), b.value()), None) def __str__(self): b = self._b if isinstance(self._b, Q) else Immediate(self._b) return self._fmt % (self._a, b) class Select(Q): def __init__(self, tag, name): self._tag = tag self._name = name def evaluate(self, tlv): return Immediate(tlv[self._tag], self._tag) def __str__(self): return self._name class Slicer(object): def __init__(self, gen): self._items = list(gen) def slice_data(self, tlv): ret = bytearray() for item in self._items: a = evaluate(item, tlv) tag = a.tag() if tag is None: raise RuntimeError("%s has indeterminate tag" % str(item)) v = tag_dict[tag].encode(a.value()) ret += self.pack(tag, v) return ret class IterableSlicer(Slicer): def pack(self, tag, data): return data def __str__(self): return ", ".join(str(item) for item in self._items) class TLVSlicer(Slicer): def pack(self, tag, data): return struct.pack("HH", tag, len(data)) + data def __str__(self): return "tlv(%s)" % ", ".join(str(item) for item in self._items) def evaluate(obj, tlv): if isinstance(obj, Q): return obj.evaluate(tlv) else: return Immediate(obj) def slice_data(obj, tlv): if isinstance(obj, Slicer): return obj.slice_data(tlv) if isinstance(obj, (tuple, list)): gen = iter(obj) else: gen = iter((obj, )) return IterableSlicer(gen).slice_data(tlv) class Query: bus = Select(tlv_bus_name.tag(), "bus") dev = Select(tlv_dev_name.tag(), "dev") driver = Select(tlv_driver_name.tag(), "driver") incoming = Select(tlv_incoming.tag(), "incoming") outgoing = ~incoming type = Select(tlv_type.tag(), "type") buf = Select(tlv_buf.tag(), "buf") v = Immediate query = eval(query_string, dict(Query.__dict__)) slicer = eval(slicer_string, dict(Query.__dict__), {"tlv": lambda *args: TLVSlicer(iter(args)), "all": (Query.bus, Query.dev, Query.driver, Query.incoming, Query.type, Query.buf)}) if show_exprs_and_exit: sys.stderr.write("filter=%s\n" % str(query)) sys.stderr.write("slice=%s\n" % str(slicer)) sys.exit(0) def read_tlv(data): ret = {} while len(data) != 0: tag, length = struct.unpack("HH", data[:4]) data = data[4:] value = tag_dict[tag].decode(data[:length]) data = data[length:] ret[tag] = value return ret def main(): out = os.fdopen(1, "wb") if write_file == "-" else open(write_file, "wb") pcap_header_out(out, link_type) r = pcapy.open_offline(read_file) while True: try: hdr, payload = r.next() except pcapy.PcapError: break if hdr == None: break secs, usecs = hdr.getts() tlv = read_tlv(payload) if evaluate(query, tlv).value(): data = slice_data(slicer, tlv) try: out.write(pcap_packet_header(secs, usecs, len(data))) out.write(data) out.flush() except(IOError, e): if e.errno == errno.EPIPE: return raise if __name__ == '__main__': try: main() except KeyboardInterrupt: sys.stderr.write("Interrupted.\n")
[ "idosch@mellanox.com" ]
idosch@mellanox.com
35e22690738cb48bd1df83fe92ef4b27f53314e9
9380030741ef54264a2db8b652a4893f427c7bf4
/python/python/6-DataStructures/list/2-list.py
f0d37bd40be0618fdfcf37a190f630f8f562a889
[]
no_license
halobrain/knode
b8d447a067532b70723f424d570f2e2f01a09abf
667a4f77a1f0f9b8f587de0c0a48cadaa21448f8
refs/heads/master
2020-06-16T11:35:34.121059
2020-04-02T06:45:06
2020-04-02T06:45:06
195,558,334
0
0
null
2020-03-03T14:02:00
2019-07-06T16:05:10
null
UTF-8
Python
false
false
531
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 19 23:27:38 2018 @author: star """ list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists list[0]='100' print list[0]
[ "halobraindotcom@gmail.com" ]
halobraindotcom@gmail.com
dd0814aeb40a7ea0f0f84b89c30783ccd689425b
749bd7db8d1902274a47bb7d98b9d6ced3ef6b68
/R-NET/local_span_single_para/analyze_dataset.py
7051f3369d1d9ba5da757c8d4e1c9cdbfab36618
[]
no_license
burglarhobbit/machine-reading-comprehension
37582e0fdca4690bd55accf33987b5fce1f663ea
04729af3d934a7696938f4079089b9b014c986aa
refs/heads/master
2023-02-08T10:39:19.262900
2020-01-11T04:08:30
2020-01-11T04:08:30
114,113,176
29
15
null
2023-02-02T02:32:54
2017-12-13T11:34:36
Python
UTF-8
Python
false
false
20,552
py
import tensorflow as tf import random from tqdm import tqdm import spacy import json from collections import Counter import numpy as np from nltk.tokenize.moses import MosesDetokenizer from rouge import Rouge as R import string import re nlp = spacy.blank("en") def word_tokenize(sent): doc = nlp(sent) return [token.text for token in doc] def convert_idx(text, tokens): current = 0 spans = [] for token in tokens: current = text.find(token, current) if current < 0: print("Token {} cannot be found".format(token)) raise Exception() spans.append((current, current + len(token))) current += len(token) return spans # Dynamic programming implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1] # Driver program """ X = "AGGTAB" Y = "GXTXAYB" lcs(X, Y) """ def lcs(X,Y): m = len(X) n = len(Y) return _lcs(X,Y,m,n) def lcs_tokens(X,Y): m = len(X) n = len(Y) L = [[0 for x in range(n+1)] for x in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] ignore_tokens = [",",".","?"] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: if X[i-1] in ignore_tokens: L[i][j] = max(L[i-1][j], L[i][j-1]) else: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # initialized answer start and end index answer_start = answer_start_i = answer_start_j = 0 answer_end = m-1 answer_end_match = False answer_start_match = False # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] index_fwd = [] i = m j = n while i > 0 and j > 0: if (X[i-1] == Y[j-1]) and (X[i-1] not in ignore_tokens): #print(X[i-1],":",i-1) index_fwd.append(i-1) i-=1 j-=1 if not answer_start_match: answer_start_match = True answer_start_i = i answer_start_j = j # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i-=1 else: j-=1 index_fwd.reverse() index_bwd = [] i = answer_start_i-1 j = answer_start_j-1 answer_end = i while i < m-1 and j < n-1: if (X[i+1] == Y[j+1]) and (X[i+1] not in ignore_tokens): #print(X[i+1],":",i+1) index_bwd.append(i+1) i+=1 j+=1 answer_end = i if not answer_end_match: #answer_start = i answer_end_match = True # If not same, then find the larger of two and # go in the direction of larger value elif L[i+1][j] > L[i][j+1]: i+=1 else: j+=1 index = list(set(index_fwd).intersection(set(index_bwd))) index.sort() #print(answer_start_match, answer_end_match) if len(index) == 1: index = index * 2 # index[1] += 1 return index def _lcs(X, Y, m, n): L = [[0 for x in range(n+1)] for x in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # Following code is used to print LCS #index = L[m][n] # initialized answer start and end index answer_start = 0 answer_end = m answer_end_match = False # Create a character array to store the lcs string #lcs = [""] * (index+1) #lcs[index] = "\0" # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] i = m j = n while i > 0 and j > 0: # If current character in X[] and Y are same, then # current character is part of LCS if X[i-1] == Y[j-1]: #lcs[index-1] = X[i-1] i-=1 j-=1 #index-=1 if not answer_end_match: answer_end = i answer_end_match = True answer_start = i # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i-=1 else: j-=1 #print "LCS of " + X + " and " + Y + " is " + "".join(lcs) #if answer_start == answer_end: # answer_end += 1 return answer_start,answer_end+1 def normalize_answer(s): def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def rouge_l(evaluated_ngrams, reference_ngrams): evaluated_ngrams = set(evaluated_ngrams) reference_ngrams = set(reference_ngrams) reference_count = len(reference_ngrams) evaluated_count = len(evaluated_ngrams) # Gets the overlapping ngrams between evaluated and reference overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams) overlapping_count = len(overlapping_ngrams) # Handle edge case. This isn't mathematically correct, but it's good enough if evaluated_count == 0: precision = 0.0 else: precision = overlapping_count / evaluated_count if reference_count == 0: recall = 0.0 else: recall = overlapping_count / reference_count f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8)) # return overlapping_count / reference_count return f1_score, precision, recall def process_file(config,max_para_count, filename, data_type, word_counter, char_counter, is_line_limit, rouge_metric): detokenizer = MosesDetokenizer() print("Generating {} examples...".format(data_type)) examples = [] rouge_metric = rouge_metric # 0 = f, 1 = p, 2 = r, default = r rouge_l_limit = 0.7 remove_tokens = ["'",'"','.',',',''] eval_examples = {} fh = open(filename, "r") line = fh.readline() line_limit = 100 if data_type == "train": total_lines = 82326 # ms marco training data set lines elif data_type == "dev": total_lines = 10047 # ms marco dev data set lines elif data_type == "test": total_lines = 10047 # ms marco dev data set lines (for test, we use dev data set) line_count = 0 do_skip_lines = False skip = 1330+789 if do_skip_lines: for _ in range(skip): next(fh) if is_line_limit: total_lines = line_limit #while(line): total = empty_answers = 0 low_rouge_l = np.zeros(3,dtype=np.int32) # token length of concatenated passages by each query id concat_para_length = {} # para exceeding length max_para_length = 0 for i in tqdm(range(total_lines)): source = json.loads(line) answer_texts = [] answer_start = answer_end = 0 highest_rouge_l = np.zeros(3) extracted_answer_text = '' passage_concat = '' final_single_passage = '' final_single_passage_tokens = '' if len(source['passages'])>config.max_para: line = fh.readline() empty_answers += 1 continue for j,passage in enumerate(source['passages']): passage_text = passage['passage_text'].replace( "''", '" ').replace("``", '" ').lower() passage_concat += " " + passage_text passage_tokens = word_tokenize(passage_concat) length = len(passage_tokens) if length>max_para_length: max_para_length = length answer = source['answers'] if answer == [] or answer == ['']: empty_answers += 1 line = fh.readline() continue elif len(answer)>=1: for answer_k,k in enumerate(answer): if k.strip() == "": continue answer_text = k.strip().lower() answer_text = answer_text[:-1] if answer_text[-1] == "." else answer_text answer_token = word_tokenize(answer_text) #index = lcs_tokens(passage_tokens, answer_token) #print(index) ##################################################################### # individual para scoring: fpr_scores = (0,0,0) token_count = 0 for l, passage in enumerate(source['passages']): passage_text = passage['passage_text'].replace( "''", '" ').replace("``", '" ').lower() passage_token = word_tokenize(passage_text) index = lcs_tokens(passage_token, answer_token) try: start_idx, end_idx = index[0], index[-1] extracted_answer = detokenizer.detokenize(passage_token[index[0]:index[-1]+1], return_str=True) detoken_ref_answer = detokenizer.detokenize(answer_token, return_str=True) fpr_scores = rouge_l(normalize_answer(extracted_answer), \ normalize_answer(detoken_ref_answer)) except Exception as e: # yes/no type questions pass if fpr_scores[rouge_metric]>highest_rouge_l[rouge_metric]: highest_rouge_l = fpr_scores answer_texts = [detoken_ref_answer] extracted_answer_text = extracted_answer answer_start, answer_end = start_idx, end_idx final_single_passage = passage_text final_single_passage_tokens = passage_token token_count += len(passage_token) for k in range(3): if highest_rouge_l[k]<rouge_l_limit: low_rouge_l[k] += 1 ################################################################ if highest_rouge_l[rouge_metric]<rouge_l_limit: #print('\nLOW ROUGE - L\n') line = fh.readline() """ print(passage_concat) print("Question:",source['query']) try: print("Start and end index:",answer_start,",",answer_end) print("Passage token length:",len(passage_tokens)) print("Extracted:",extracted_answer_text) print("Ground truth:",answer_texts[0]) print("Ground truth-raw:",source['answers']) except Exception as e: print("Extracted-raw:",passage_tokens[answer_start:answer_end]) print("Ground truth:",answer_texts) print("Ground truth-raw:",source['answers']) a = input("Pause:") print("\n\n") """ continue else: answer_text = answer[0].strip() """ print(passage_concat) print("Question:",source['query']) try: print("Start and end index:",answer_start,",",answer_end) print("Passage token length:",len(passage_tokens)) print("Extracted:",extracted_answer_text) print("Ground truth:",answer_texts[0]) print("Ground truth-raw:",source['answers']) except Exception as e: print("Extracted-raw:",passage_tokens[answer_start:answer_end]) print("Ground truth:",answer_texts) print("Ground truth-raw:",source['answers']) a = input("Pause:") print("\n\n") """ passage_chars = [list(token) for token in final_single_passage_tokens] spans = convert_idx(final_single_passage, final_single_passage_tokens) # word_counter increase for every qa pair. i.e. 1 since ms marco has 1 qa pair per para for token in final_single_passage_tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 ques = source['query'].replace( "''", '" ').replace("``", '" ').lower() ques_tokens = word_tokenize(ques) ques_chars = [list(token) for token in ques_tokens] for token in ques_tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 y1s, y2s = [], [] #answer_start, answer_end = lcs(passage_concat.lower(),answer_text.lower()) answer_span = [answer_start, answer_end] # word index for answer span for idx, span in enumerate(spans): #if not (answer_end <= span[0] or answer_start >= span[1]): if not (answer_end <= span[0] or answer_start >= span[1]): answer_span.append(idx) y1, y2 = answer_start, answer_end y1s.append(y1) y2s.append(y2) total += 1 concat_para_length[source["query_id"]] = len(final_single_passage_tokens) example = {"passage_tokens": final_single_passage_tokens, "passage_chars": passage_chars, "ques_tokens": ques_tokens, "ques_chars": ques_chars, "y1s": y1s, "y2s": y2s, "id": total, "uuid": source["query_id"],} examples.append(example) eval_examples[str(total)] = { "passage_concat": final_single_passage, "spans": spans, "answers": answer_texts, "uuid": source["query_id"],} line = fh.readline() if total%1000 == 0: print("{} questions in total".format(len(examples))) print("{} questions with empty answer".format(empty_answers)) print("{} questions with low rouge-l answers without multipara".format(low_rouge_l)) print("{} max-para length".format(max_para_length)) random.shuffle(examples) print("{} questions in total".format(len(examples))) print("{} questions with empty answer".format(empty_answers)) print("{} questions with low rouge-l answers without multipara".format(low_rouge_l)) print("{} max-para length".format(max_para_length)) with open(data_type+'_para_metadata.json','w') as fp: json.dump(concat_para_length,fp) """ # original implementation for comparision purposes with open(filename, "r") as fh: source = json.load(fh) for article in tqdm(source["data"]): for para in article["paragraphs"]: context = para["context"].replace( "''", '" ').replace("``", '" ') context_tokens = word_tokenize(context) context_chars = [list(token) for token in context_tokens] spans = convert_idx(context, context_tokens) # word_counter increase for every qa pair for token in context_tokens: word_counter[token] += len(para["qas"]) for char in token: char_counter[char] += len(para["qas"]) for qa in para["qas"]: total += 1 ques = qa["question"].replace( "''", '" ').replace("``", '" ') ques_tokens = word_tokenize(ques) ques_chars = [list(token) for token in ques_tokens] for token in ques_tokens: word_counter[token] += 1 for char in token: char_counter[char] += 1 y1s, y2s = [], [] answer_texts = [] for answer in qa["answers"]: answer_text = answer["text"] answer_start = answer['answer_start'] answer_end = answer_start + len(answer_text) answer_texts.append(answer_text) answer_span = [] for idx, span in enumerate(spans): if not (answer_end <= span[0] or answer_start >= span[1]): answer_span.append(idx) y1, y2 = answer_span[0], answer_span[-1] y1s.append(y1) y2s.append(y2) example = {"context_tokens": context_tokens, "context_chars": context_chars, "ques_tokens": ques_tokens, "ques_chars": ques_chars, "y1s": y1s, "y2s": y2s, "id": total} examples.append(example) eval_examples[str(total)] = { "context": context, "spans": spans, "answers": answer_texts, "uuid": qa["id"]} random.shuffle(examples) print("{} questions in total".format(len(examples))) """ return examples, eval_examples def get_embedding(counter, data_type, limit=-1, emb_file=None, size=None, vec_size=None): print("Generating {} embedding...".format(data_type)) embedding_dict = {} filtered_elements = [k for k, v in counter.items() if v > limit] if emb_file is not None: assert size is not None assert vec_size is not None with open(emb_file, "r", encoding="utf-8") as fh: for line in tqdm(fh, total=size): array = line.split() word = "".join(array[0:-vec_size]) vector = list(map(float, array[-vec_size:])) if word in counter and counter[word] > limit: embedding_dict[word] = vector print("{} / {} tokens have corresponding embedding vector".format( len(embedding_dict), len(filtered_elements))) else: assert vec_size is not None for token in filtered_elements: embedding_dict[token] = [0. for _ in range(vec_size)] print("{} tokens have corresponding embedding vector".format( len(filtered_elements))) NULL = "--NULL--" OOV = "--OOV--" token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict.keys(), 2)} token2idx_dict[NULL] = 0 token2idx_dict[OOV] = 1 embedding_dict[NULL] = [0. for _ in range(vec_size)] embedding_dict[OOV] = [0. for _ in range(vec_size)] idx2emb_dict = {idx: embedding_dict[token] for token, idx in token2idx_dict.items()} emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))] return emb_mat, token2idx_dict def build_features(config, examples, data_type, out_file, word2idx_dict, char2idx_dict, is_test=False): para_limit = config.test_para_limit if is_test else config.para_limit ques_limit = config.test_ques_limit if is_test else config.ques_limit char_limit = config.char_limit def filter_func(example, is_test=False): return len(example["passage_tokens"]) > para_limit or len(example["ques_tokens"]) > ques_limit print("Processing {} examples...".format(data_type)) writer = tf.python_io.TFRecordWriter(out_file) total = 0 total_ = 0 meta = {} for example in tqdm(examples): total_ += 1 if filter_func(example, is_test): print("Filtered") continue total += 1 passage_idxs = np.zeros([para_limit], dtype=np.int32) passage_char_idxs = np.zeros([para_limit, char_limit], dtype=np.int32) ques_idxs = np.zeros([ques_limit], dtype=np.int32) ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32) y1 = np.zeros([para_limit], dtype=np.float32) y2 = np.zeros([para_limit], dtype=np.float32) def _get_word(word): for each in (word, word.lower(), word.capitalize(), word.upper()): if each in word2idx_dict: return word2idx_dict[each] return 1 def _get_char(char): if char in char2idx_dict: return char2idx_dict[char] return 1 for i, token in enumerate(example["passage_tokens"]): passage_idxs[i] = _get_word(token) for i, token in enumerate(example["ques_tokens"]): ques_idxs[i] = _get_word(token) for i, token in enumerate(example["passage_chars"]): for j, char in enumerate(token): if j == char_limit: break passage_char_idxs[i, j] = _get_char(char) for i, token in enumerate(example["ques_chars"]): for j, char in enumerate(token): if j == char_limit: break ques_char_idxs[i, j] = _get_char(char) start, end = example["y1s"][-1], example["y2s"][-1] y1[start], y2[end] = 1.0, 1.0 if total%config.checkpoint==0: print("Processed {} examples...".format(total)) record = tf.train.Example(features=tf.train.Features(feature={ "passage_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[passage_idxs.tostring()])), "ques_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring()])), "passage_char_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[passage_char_idxs.tostring()])), "ques_char_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_char_idxs.tostring()])), "y1": tf.train.Feature(bytes_list=tf.train.BytesList(value=[y1.tostring()])), "y2": tf.train.Feature(bytes_list=tf.train.BytesList(value=[y2.tostring()])), "id": tf.train.Feature(int64_list=tf.train.Int64List(value=[example["id"]])) })) writer.write(record.SerializeToString()) print("Build {} / {} instances of features in total".format(total, total_)) print("Processed {} examples...".format(total)) meta["total"] = total writer.close() return meta def save(filename, obj, message=None): if message is not None: print("Saving {}...".format(message)) with open(filename, "w") as fh: json.dump(obj, fh) def prepro_(config): word_counter, char_counter = Counter(), Counter() train_examples, train_eval = process_file(config, config.max_para, config.train_file, "train", word_counter, char_counter, config.line_limit_prepro, config.rouge_metric) dev_examples, dev_eval = process_file(config, config.max_para, config.dev_file, "dev", word_counter, char_counter, config.line_limit_prepro, config.rouge_metric) test_examples, test_eval = process_file(config, config.max_para, config.test_file, "test", word_counter, char_counter, config.line_limit_prepro, config.rouge_metric) word_emb_mat, word2idx_dict = get_embedding( word_counter, "word", emb_file=config.glove_file, size=config.glove_size, vec_size=config.glove_dim) char_emb_mat, char2idx_dict = get_embedding( char_counter, "char", vec_size=config.char_dim) build_features(config, train_examples, "train", config.train_record_file, word2idx_dict, char2idx_dict) dev_meta = build_features(config, dev_examples, "dev", config.dev_record_file, word2idx_dict, char2idx_dict) test_meta = build_features(config, test_examples, "test", config.test_record_file, word2idx_dict, char2idx_dict, is_test=True) save(config.word_emb_file, word_emb_mat, message="word embedding") save(config.char_emb_file, char_emb_mat, message="char embedding") save(config.train_eval_file, train_eval, message="train eval") save(config.dev_eval_file, dev_eval, message="dev eval") save(config.test_eval_file, test_eval, message="test eval") save(config.dev_meta, dev_meta, message="dev meta") save(config.test_meta, test_meta, message="test meta")
[ "bhavyapatwa007@gmail.com" ]
bhavyapatwa007@gmail.com
b71375c556ac632ac0954c364745b36ff4f2dfd3
05b06f67eddac0066d19e83f27ef237bb47811ef
/GA reports/google_analytics_database.py
4bf0431dc6d26301a9945eaf4c51cb33a6ff5eb3
[]
no_license
Eugeneifes/TV1000Play
0b90f81af758dcd4011e2be800ea620e02c81b43
de5b8e62c5dfbc9203d471347918f969ed1ae7ad
refs/heads/master
2021-01-19T18:39:31.539847
2018-02-07T18:57:58
2018-02-07T18:57:58
101,149,923
1
0
null
null
null
null
UTF-8
Python
false
false
10,229
py
#-*- coding: utf-8 -*- import xlrd from datetime import timedelta import datetime from pymongo import MongoClient import pprint from apiclient.discovery import build import httplib2 import xlwt from oauth2client.service_account import ServiceAccountCredentials SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest') KEY_FILE_LOCATION = 'client_secrets.p12' SERVICE_ACCOUNT_EMAIL = 'eugene@python-149108.iam.gserviceaccount.com' """платформы для отчетов (для smart TV данные по User_ID)""" Platforms = {"LG": "96890573", "Samsung": "96900905", "Android": "125654904", "iOS": "125643516"} """преобразуем дату из excel""" def to_date(rb, date): year, month, day, hour, minute, second = xlrd.xldate_as_tuple(date, rb.datemode) return datetime.date(year, month, day) """connecting to mongodb""" def connect_to_database(): conn = MongoClient('localhost', 27017) db = conn.GA return db """получаем информацию по фильмам из опорного файла""" def get_films(): Collections = {} Promo = [] New = [] Recommended = [] Selected = [] New_year = [] rb = xlrd.open_workbook('new_year.xlsx') sheet = rb.sheet_by_index(0) for rownum in range(sheet.nrows-1): row = sheet.row_values(rownum+1) film = {} if type(row[0]) == float: film["code"] = str(int(row[0])) else: film["code"] = str(row[0]) if type(row[1]) == float: film["id"] = str(int(row[1])) else: film["id"] = str(row[1]) if type(row[2]) == float: film["kp_id"] = str(int(row[2])) else: film["kp_id"] = str(row[2]) film["name"] = row[4] if row[6] != "": film["regex"] = row[6] else: film["regex"] = "" print row[3], row[7] film["date"] = to_date(rb, row[7]) if row[8] == u'Промо': Promo.append(film) if row[8] == u'Новое': New.append(film) if row[8] == u'Рекомендуемое': Recommended.append(film) if row[8] == u'Подборки': Selected.append(film) if row[8] == u'Новый год 2017': New_year.append(film) Collections["Promo"] = Promo Collections["New"] = New Collections["Recommended"] = Recommended Collections["Selected"] = Selected Collections["New_year"] = New_year return Collections """инициализация клиента GA Reporting API""" def initialize_analyticsreporting(): credentials = ServiceAccountCredentials.from_p12_keyfile(SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES) http = credentials.authorize(httplib2.Http()) analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI) return analytics """получить отчет по запросу""" def get_report(analytics, query): return analytics.reports().batchGet(body=query).execute() """получаем и парсим ответ от сервера GA""" def get_response(response): x_mass = [] y_mass = [] for report in response.get('reports', []): columnHeader = report.get('columnHeader', {}) dimensionHeaders = columnHeader.get('dimensions', []) metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) rows = report.get('data', {}).get('rows', []) for row in rows: dimensions = row.get('dimensions', []) dateRangeValues = row.get('metrics', []) for header, dimension in zip(dimensionHeaders, dimensions): x_mass.append(int(dimension)) for i, values in enumerate(dateRangeValues): for metricHeader, value in zip(metricHeaders, values.get('values')): y_mass.append(int(value)) return x_mass, y_mass """формируем запрос к GA""" def query_builder(VIEW_ID, startdate, enddate, eventCategory, eventAction, film): query = { 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': startdate, 'endDate': enddate}], 'metrics': [{'expression': 'ga:totalEvents'}], "filtersExpression": "ga:eventCategory==" + eventCategory + ";ga:eventAction==" + eventAction + ";ga:eventLabel=" + film } ] } return query """cмотрим горизонт наблюдения""" def get_date_range(since): date_range = [] now = since report_day = datetime.datetime.today().date() - timedelta(days=1) while now <= report_day: date_range.append(now) now += timedelta(days=1) return date_range """cмотрим горизонт наблюдения""" def get_horizon(): date_range = [] horizon = datetime.datetime.today().date() for collection in Collections.keys(): for film in Collections[collection]: if film["date"] < horizon: horizon = film["date"] now = horizon today = datetime.datetime.today().date() - timedelta(days=1) while now <= today: date_range.append(now) now += timedelta(days=1) return date_range """попробовать получить информацию по фильму индивидуально""" def give_a_try(film, date): print film try: query = query_builder("96890573", date, date, "watches", "watch", "@" + film) print query analytics = initialize_analyticsreporting() response = get_report(analytics, query) x, y = get_response(response) if y == []: print date, 0 else: print date, y except: print "wtf" """выполняем нужный запрос к полученной базе""" def query_database(db, Collections): watches_database = db.watches watches_database.delete_many({"name": "Гипнотизер", "date": "2016-11-30"}) """получаем ядро базы, дальше будем только обновлять его - плоская структура (SQL-like)""" def easy_structure(Collections, db): watches_database = db.watches new_record = {} for collection in Collections: print collection for film in Collections[collection]: print film["name"] if film["regex"] != u'': film_name = "@" + film["regex"] else: film_name = "=" + film["name"] for day in get_date_range(film["date"]): new_record["date"] = day.strftime("%Y-%m-%d") for platform in Platforms: if platform not in ["iOS", "Android"]: eventCategory = "watches" eventAction = "watch" else: eventCategory = "Watches" eventAction = "Watch" query = query_builder(Platforms[platform], day.strftime("%Y-%m-%d"), day.strftime("%Y-%m-%d"), eventCategory, eventAction, film_name) analytics = initialize_analyticsreporting() try: response = get_report(analytics, query) x, y = get_response(response) if y == []: print platform, day, 0 new_record[platform] = 0 else: print platform, day, y[0] new_record[platform] = y[0] except: print "error" new_record["name"] = film["name"] new_record["id"] = film["id"] new_record["kp_id"] = film["kp_id"] new_record["code"] = film["code"] watches_database.save(new_record) new_record = {} """обновляем информацию в базе""" def update_easy_structure(Collections, db): watches_database = db.watches for collection in Collections: print collection for film in Collections[collection]: print film["name"] for day in get_date_range(film["date"]): if watches_database.find({"name": film["name"], "date": day.strftime("%Y-%m-%d")}).count() == 1: pass else: new_record = {} new_record["date"] = day.strftime("%Y-%m-%d") if film["regex"] != u'': if type(film["regex"]) == float: film_name = "@" + str(int(film["regex"])) else: film_name = "@" + film["regex"] else: film_name = "=" + film["name"] for platform in Platforms: if platform not in ["iOS", "Android"]: eventCategory = "watches" eventAction = "watch" else: eventCategory = "Watches" eventAction = "Watch" query = query_builder(Platforms[platform], day.strftime("%Y-%m-%d"), day.strftime("%Y-%m-%d"), eventCategory, eventAction, film_name) analytics = initialize_analyticsreporting() try: response = get_report(analytics, query) x, y = get_response(response) if y == []: print platform, day, 0 new_record[platform] = 0 else: print platform, day, y[0] new_record[platform] = y[0] except: print "error" new_record["name"] = film["name"] new_record["id"] = film["id"] new_record["kp_id"] = film["kp_id"] new_record["code"] = film["code"] watches_database.save(new_record) Collections = get_films() pprint.pprint(Collections) #db = connect_to_database() #update_easy_structure(Collections, db)
[ "васичкин@viasat.local" ]
васичкин@viasat.local
26228b940c3d4c969bf7de8c471069ec68ab04a3
843ce3d703d2bdb89930360e10448dfdeb4dec72
/untitled2/config.py
37a98beabca1d4a04a213111bafa1c8a802c470d
[]
no_license
huozhenlin/chinasoftbei
f41525965597ec2d65b0172af762f42c307e096b
18c1866846e8c8f6a4740dc934e2e20cc526ff81
refs/heads/master
2021-08-31T01:16:36.585065
2017-12-20T03:32:35
2017-12-20T03:32:35
107,065,093
0
1
null
null
null
null
UTF-8
Python
false
false
321
py
#coding:utf8 import os DEBUG=True SECRET_KEY=os.urandom(24) HOSTNAME='127.0.0.1' PORT='3306' DATABASE='softbei' USERNAME='root' PASSWORD='1234' DB_URI='mysql+mysqldb://{}:{}@{}:{}/{}?charset=utf8'.format( USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE ) SQLALCHEMY_DATABASE_URI=DB_URI SQLALCHEMY_TRACK_MODIFICATIONS=False
[ "1031734796@qq.com" ]
1031734796@qq.com
f24bf2a788e0cd0924baebcd0ee5214d3f6d2437
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03193/s350016826.py
bb3396dfb53a31bf3a3373f8edacfe1808de721e
[]
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
136
py
N,H,W=map(int,input().split()) count=0 for i in range(N): A,B=map(int,input().split()) if (A >= H) & (B >= W): count+=1 print(count)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
3f10a11ac99e9d6c14f95a97d398f6f686a1d139
17dba42c75ae75376260d9bbd544f727083d2732
/media.py
22680e51427571dd6805e25a9d1cc6bb9a4da414
[]
no_license
cyrilvincent/python-advanced
d8ec3a0defed99fe99c2800cab8f5a647c4e3e62
79f13f1d3e88fae996da697ee3afdee8d1308fbf
refs/heads/master
2021-12-15T23:50:00.647131
2021-12-02T15:30:47
2021-12-02T15:30:47
207,744,251
2
1
null
null
null
null
UTF-8
Python
false
false
1,013
py
from dataclasses import dataclass from abc import ABCMeta, abstractmethod from typing import List, ClassVar @dataclass class Media(metaclass=ABCMeta): id: int title: str price: float nb_media: ClassVar[int] TYPE: int = 1 @abstractmethod def net_price(self):... @dataclass class Dvd(Media): zone: int @property def net_price(self): return self.price * 1.2 @dataclass class Book(Media): nb_page: int = 0 @property def net_price(self): return 0.01 + self.price * 1.05 * 0.95 class CartService: nb_cart: int = 0 def __init__(self): self.medias: List[Media] = [] CartService.nb_cart += 1 def add(self, media: Media): self.medias.append(media) def remove(self, media: Media): if media in self.medias: self.medias.remove(media) def get_total_net_price(self): return sum([m.net_price for m in self.medias]) def __del__(self): CartService.nb_cart -= 1
[ "contact@cyrilvincent.com" ]
contact@cyrilvincent.com
d4b712708c59f690eb0da72e38b8ff34e76bcfa6
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/1/ck6.py
7cd7fb237b1177a4cd014c547f541b4ff1fe9808
[]
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] == 'cK6': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
[ "juliettaylorswift@gmail.com" ]
juliettaylorswift@gmail.com
dc35a520923692d8af94c139aa6eed4fe89e6c9e
231b906c3e13482261fa0a62f41a2d25211e9dfc
/recontruct_itinerary.py
6352c5f2ad5c676045f9d8b46060040fecd64f10
[]
no_license
vyshuks/june-leetcoding-challenge
732a84536e488e5e8e6cf8d0a33488e46807b434
a67e82c6ba35efa88b4649cbceb569bc53783870
refs/heads/master
2022-11-08T01:01:19.905318
2020-07-06T05:27:51
2020-07-06T05:27:51
268,863,258
1
0
null
null
null
null
UTF-8
Python
false
false
1,699
py
""" Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. One must use all the tickets once and only once. Example 1: Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] """ class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: mapping = {} for start, end in tickets: if start in mapping: mapping[start].append(end) else: mapping[start] = [end] # sort the list in descending order and pop from the last list for src in mapping.keys(): mapping[src].sort(reverse=True) # we have a stack to know the cur the next node stack = ["JFK"] result = [] while len(stack) > 0: cur = stack[-1] # check whether it has ticket, it has, add to stack if cur in mapping and len(mapping[cur]) > 0: stack.append(mapping[cur].pop()) else: result.append(stack.pop()) # since the result starts from destination, we reverse it return result[::-1]
[ "vyshuks@gmail.com" ]
vyshuks@gmail.com
08834d1b81dac5c7d0724301c30b48df93539259
133e8c9df1d1725d7d34ea4317ae3a15e26e6c66
/Selenium/QQ/utils/ocr4qqcaptcha.py
e0c8e6fbc484ddbb4fc2cdffd1348180507ebda1
[ "Apache-2.0" ]
permissive
425776024/Learn
dfa8b53233f019b77b7537cc340fce2a81ff4c3b
3990e75b469225ba7b430539ef9a16abe89eb863
refs/heads/master
2022-12-01T06:46:49.674609
2020-06-01T08:17:08
2020-06-01T08:17:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,717
py
import glob import numpy as np from scipy import misc from keras.layers import Input, Convolution2D, MaxPooling2D, Flatten, Activation, Dense from keras.models import Model from keras.utils.np_utils import to_categorical imgs = glob.glob('sample/*.jpg') img_size = misc.imread(imgs[0]).shape #这里是(53, 129, 3) data = np.array([misc.imresize(misc.imread(i), img_size).T for i in imgs]) data = 1 - data.astype(float)/255.0 target = np.array([[ord(i)-ord('a') for i in j[7:11]] for j in imgs]) target = [to_categorical(target[:,i], 26) for i in range(4)] img_size = img_size[::-1] input = Input(img_size) cnn = Convolution2D(32, 3, 3)(input) cnn = MaxPooling2D((2, 2))(cnn) cnn = Convolution2D(32, 3, 3)(cnn) cnn = MaxPooling2D((2, 2))(cnn) cnn = Activation('relu')(cnn) cnn = Convolution2D(32, 3, 3)(cnn) cnn = MaxPooling2D((2, 2))(cnn) cnn = Activation('relu')(cnn) cnn = Convolution2D(32, 3, 3)(cnn) cnn = MaxPooling2D((2, 2))(cnn) cnn = Flatten()(cnn) cnn = Activation('relu')(cnn) model = Model(input=input, output=[Dense(26, activation='softmax')(cnn) for i in range(4)]) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() batch_size = 256 nb_epoch = 30 model.fit(data, target, batch_size=batch_size, nb_epoch=nb_epoch) model.save_weights('yanzheng_cnn_2d.model') # rr = [''.join(chr(i.argmax()+ord('a')) for i in model.predict(data[[k]])) for k in tqdm(range(len(data)))] # s = [imgs[i][7:11]==rr[i] for i in range(len(imgs))] # print(1.0*sum(s)/len(s)) def ocr(filename): img = misc.imresize(misc.imread(filename), img_size[::-1]).T img = np.array([1 - img.astype(float)/255]) return ''.join(chr(i.argmax()+ord('a')) for i in model.predict(img))
[ "cheng.yang@salezoom.io" ]
cheng.yang@salezoom.io
a37845f0681eff083fa1e1f50abe149057693157
b14590f2053d03d9b32a7ac1d98782449e531e6b
/backend/server/tests/mutation_test.py
5d7e6ce6fbab624825dce57db84453277f9a06bb
[ "MIT" ]
permissive
fossabot/Graphery
c4c2eb2ecd9b0b544b629433a7d5fab461671162
61f23b2ad4ad0fa5dff643047597f9bb6cae35a2
refs/heads/master
2022-12-15T19:16:54.028265
2020-09-10T05:40:49
2020-09-10T05:40:49
294,314,154
0
0
MIT
2020-09-10T05:40:49
2020-09-10T05:40:48
null
UTF-8
Python
false
false
7,030
py
import json from typing import Mapping, Sequence from django.contrib.auth.models import AnonymousUser from django.contrib.sessions.middleware import SessionMiddleware from django.db import models from graphene.test import Client from backend.model.TutorialRelatedModel import FAKE_UUID from graphery.schema import schema import pytest from backend.model.MetaModel import InvitationCode from backend.models import * from tests.utils import camel_to_snake, EmptyValue, AnyNoneEmptyValue, AnyValue @pytest.fixture(autouse=True) def enable_db_access(db): pass @pytest.fixture() def rq_anonymous(rf): request = rf.post('/') SessionMiddleware().process_request(request) request.session.save() request.user = AnonymousUser() return request @pytest.fixture() def rq_admin(rf): request = rf.post('/') SessionMiddleware().process_request(request) request.session.save() admin = \ User.objects.create_superuser(username='super_test_user', email='super_test@user.com', password='Password!1') request.user = admin return request @pytest.fixture(scope='module') def graphql_client(): return Client(schema) def assert_no_error(result: Mapping) -> Mapping: assert 'errors' not in result assert 'data' in result return result['data'] def assert_model_equal(model_instance: models.Model, variable_mapping: Mapping, validate_against: Mapping = None) -> None: for var_name, var_value in {**variable_mapping, **(validate_against if validate_against else {})}.items(): model_var_value = getattr(model_instance, camel_to_snake(var_name), EmptyValue) if isinstance(var_value, Sequence) and all(isinstance(var_value_ele, models.Model) for var_value_ele in var_value): assert all(var_value_ele in model_var_value for var_value_ele in var_value) else: assert var_value == model_var_value @pytest.mark.parametrize( 'mutation_query, variables, result_chain, model', [ pytest.param( '''mutation ($email: String!, $username: String!, $password: String!, $invitationCode: String!) { register(email: $email, username: $username, password: $password, invitationCode:$invitationCode) { user { id } } }''', {'email': 'test_new_register@email.com', 'username': 'test_user_name', 'password': 'Password!1', 'invitationCode': InvitationCode.code_collection['Visitor']}, ('register', 'user', 'id'), User ) ] ) def test_register_mutation(graphql_client, rq_anonymous, mutation_query: str, variables: Mapping, result_chain: Sequence, model: models.Model): result = graphql_client.execute(mutation_query, variable_values=variables, context_value=rq_anonymous) data = assert_no_error(result) for chain_id in result_chain: data = data.get(chain_id) model_instance = model.objects.get(id=data) assert_model_equal(model_instance, variables, validate_against={'password': AnyNoneEmptyValue, 'invitationCode': AnyValue}) id_validation = {'id': AnyNoneEmptyValue} @pytest.mark.django_db @pytest.mark.parametrize( 'mutation_query, variables, result_chain, model, validate_against', [ pytest.param( ''' mutation($id: UUID!, $category: String!, $isPublished: Boolean) { updateCategory(id: $id, category: $category, isPublished: $isPublished) { model { id } } } ''', {'id': FAKE_UUID, 'category': 'Test Mutation Category', 'isPublished': False}, ('updateCategory', 'model',), Category, id_validation ), *(pytest.param( ''' mutation ($id: UUID!, $url: String!, $name: String!, $rank: RankInputType!, $categories: [String], $isPublished: Boolean) { updateTutorialAnchor(id: $id, url: $url, name: $name, rank: $rank, categories: $categories, isPublished: $isPublished) { success model { id } } } ''', {'id': FAKE_UUID, 'url': url_name_set[0], 'name': url_name_set[1], 'rank': rank, 'categories': catList, 'isPublished': False}, ('updateTutorialAnchor', 'model', ), Tutorial, {**id_validation, 'level': rank['level'], 'section': rank['section'], 'rank': AnyValue, 'categories': AnyValue}, ) for url_name_set, catList, rank in [ (('new-test-url-2', 'net test url 2'), [], {'level': 500, 'section': 2}), (('new-test-url-1', 'net test url 1'), ['1e209965-f720-418b-8746-1eaee4c8295c', 'dbe8cf6f-09a5-41b6-86ba-367d7a63763f'], {'level': 501, 'section': 2}) ]), *(pytest.param( ''' mutation ($id: UUID!, $url: String!, $name: String!, $cyjs: JSONString!, $isPublished:Boolean, $priority: Int, $authors: [String], $categories: [String], $tutorials: [String]) { updateGraph(id: $id, url: $url, name: $name, cyjs: $cyjs, isPublished: $isPublished, priority: $priority, authors: $authors, categories: $categories, tutorials: $tutorials) { model { id } } } ''', {'id': FAKE_UUID, 'url': url_name_set[0], 'name': url_name_set[1], 'cyjs': json_string, 'priority': 20, 'categories': catList, 'isPublished': False, 'tutorials': tutList}, ('updateGraph', 'model', ), Graph, {**id_validation, 'categories': AnyValue, 'tutorials': AnyValue, 'cyjs': json.loads(json_string)}, ) for url_name_set, json_string, catList, tutList in [ (('new-test-url-2', 'net test url 2'), '{"elements": {"edges": [], "nodes": []}, "layout": {"name": "dagre"}}', [], []), (('new-test-url-1', 'net test url 1'), '{"elements": {"edges": [], "nodes": []}, "layout": {"name": "preset"}}', ['1e209965-f720-418b-8746-1eaee4c8295c', 'dbe8cf6f-09a5-41b6-86ba-367d7a63763f'], ['7b35ec2c-685f-4727-98c6-766e120fb0c0', '3e8c3a27-bb56-4dd2-92a1-069c26b533e4']) ]) ] ) def test_admin_mutations_create(graphql_client, rq_admin, mutation_query: str, variables: Mapping, result_chain: Sequence, model: models.Model, validate_against: Mapping): result = graphql_client.execute(mutation_query, variable_values=variables, context_value=rq_admin) data = assert_no_error(result) for result_name in result_chain: data = data.get(result_name) data_id = data.get('id') model_instance = model.objects.get(id=data_id) assert_model_equal(model_instance, variables, validate_against=validate_against)
[ "13360148+poppy-poppy@users.noreply.github.com" ]
13360148+poppy-poppy@users.noreply.github.com
06647fe2f70c0a6acca0591b610020cf94fbaf1b
b02f0e622b38ed7a8ad00b4f58c7b2895be9a126
/imageutils.py
9df9c7fa4c92769e2ed8e5a88e791789a6e91d9a
[]
no_license
sudendroid/FaceLandmaks
de574305d6acdc8d2c0cacb56e744ccedbbed83b
30ca7054812844c05bcfe44560b4d4f3d6669100
refs/heads/master
2021-01-03T15:00:17.547333
2020-02-12T21:37:27
2020-02-12T21:37:27
240,119,997
0
0
null
null
null
null
UTF-8
Python
false
false
1,526
py
from math import atan2, degrees import cv2 def AngleBtw2Points(pointA, pointB): changeInX = pointB[0] - pointA[0] changeInY = pointB[1] - pointA[1] return degrees(atan2(changeInY, changeInX)) def overlay_transparent(background, overlay, x, y): background_width = background.shape[1] background_height = background.shape[0] if x >= background_width or y >= background_height: return background h, w = overlay.shape[0], overlay.shape[1] if x + w > background_width: w = background_width - x overlay = overlay[:, :w] if y + h > background_height: h = background_height - y overlay = overlay[:h] if overlay.shape[2] < 4: overlay = np.concatenate( [ overlay, np.ones((overlay.shape[0], overlay.shape[1], 1), dtype=overlay.dtype) * 255 ], axis=2, ) overlay_image = overlay[..., :3] mask = overlay[..., 3:] / 255.0 background[y:y + h, x:x + w] = (1.0 - mask) * background[y:y + h, x:x + w] + mask * overlay_image return background def resize(image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h, w) = image.shape[:2] if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = cv2.resize(image, dim, interpolation=inter) return resized
[ "sudesh.lovely@gmail.com" ]
sudesh.lovely@gmail.com
d28098abd641e80ba966dd237d87ea6fc0708857
1cabf4c68c2c89d70340dd77aefcf8478b53c659
/code/table4_kappa_correlation_chris.py
bfbf02b538f88cd36e7b26bd1849df92edda5719
[ "MIT" ]
permissive
chitramarti/CommonOwnerReplication
efbe1c7a2a9b850a8ea699c9d5edfffbd8283599
fbc484beb3e8926811a6969250a1370f9b883b0f
refs/heads/master
2022-11-20T11:42:40.491393
2020-06-24T19:45:24
2020-06-24T19:45:24
274,755,902
0
0
null
2020-06-24T19:46:57
2020-06-24T19:46:56
null
UTF-8
Python
false
false
4,063
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ### Table 4 Correlations with Kappa import our_plot_config from our_plot_config import derived_dir, tab_dir import pandas as pd import numpy as np # for regressions import pyhdfe from sklearn import datasets, linear_model import statsmodels.formula.api as smf from statsmodels.iolib.summary2 import summary_col # Input f_regression = derived_dir / 'regression_data.parquet' # Output f_tab4 = tab_dir /'table4.tex' # Read data cols=['from','to','quarter','kappa','retail_share','market_cap','marginsq', 'normalized_l2','big3','beta_BlackRock', 'beta_Vanguard', 'beta_StateStreet'] df=pd.read_parquet(f_regression,columns=cols).rename(columns={'beta_BlackRock':'blackrock','beta_Vanguard':'vanguard','beta_StateStreet':'statestreet'}) # Filter on dates df = df[(df.quarter > '2000-01-01')].copy() # Calculate derived columns df['lcap'] = np.log(df['market_cap']) # Code the FE first: This speeds things up to avoid type converting 13 million dates df['pair_fe']=df.groupby(['from','to']).ngroup() df['quarter_fe']=df.groupby(['quarter']).ngroup() # Drop any missings df2=df[var_list+['pair_fe','quarter_fe']].dropna() ## Regressions! # We will need to absorb: do that first # This is comically slow and uses 30+GB var_list=['kappa','retail_share','lcap', 'marginsq', 'normalized_l2','big3','blackrock', 'vanguard', 'statestreet'] alg_pa = pyhdfe.create(df2[['pair_fe', 'quarter_fe']].values,drop_singletons=False) resid_pa=alg_pa.residualize(df2[var_list].values) # Perform Regressions # no need for fixed effects because we've already residualized everything # drop rows containing NAs pd_vars = pd.DataFrame(resid_pa, columns=['kappa','retail_share','lcap', 'marginsq', 'normalized_l2', 'big3','blackrock', 'vanguard', 'statestreet']) reg1 = smf.ols(formula = 'kappa ~ retail_share + lcap + marginsq + big3', data = pd_vars).fit() reg2 = smf.ols(formula = 'kappa ~ retail_share + lcap + marginsq + normalized_l2', data = pd_vars).fit() reg3 = smf.ols(formula = 'kappa ~ retail_share + lcap + marginsq + big3 + normalized_l2', data = pd_vars).fit() reg4 = smf.ols(formula = 'kappa ~ retail_share + lcap + marginsq + normalized_l2 + blackrock + vanguard + statestreet', data = pd_vars).fit() # Adjust R^2 for the FE def rsq_update(reg): reg.rsquared=np.var(reg.predict()+(df2['kappa'].values-resid_pa[:,0]))/np.var(df2['kappa']) return for r in [reg1,reg2,reg3,reg4]: rsq_update(r) # Print Output info_dict={'R\sq' : lambda x: f"{x.rsquared:.4f}", 'N' : lambda x: f"{int(x.nobs):d}"} dfoutput = summary_col(results=[reg1,reg2,reg3,reg4], float_format='%0.4f', stars = True, model_names=['(1)', '(2)', '(3)', '(4)'], info_dict=info_dict, regressor_order=[('retail_share','Retail Share'), ('lcap','Log(Market Cap)'), ('marginsq','Operating Margin'), ('normalized_l2','Indexing'), ('big3','Big 3 Share'), ('blackrock','BlackRock'), ('vanguard','Vanguard') ('statestreet','StateStreet') ], drop_omitted=True) # Clean up the TeX by hand for the table tab_reg2=re.sub(r'\*\*\*', '*', dfoutput.as_latex()) tab_reg3=re.sub(r'hline','toprule', tab_reg2,count=1) tab_reg4=re.sub(r'hline','bottomrule', tab_reg3,count=1) tab_reg5=re.sub(r'retail\\_share','Retail Share', tab_reg4) # Display table and save print(tab_reg5) with open(f_tab4,'w') as file: file.write(tab_reg5)
[ "christopherconlon@gmail.com" ]
christopherconlon@gmail.com
d5bebd73fae01dd6a3e9f7c774f4058484363379
f63d47c3f4f93a4ca7091468c3071e3ddb2ebdf2
/Topics/List comprehension/Vowels/main.py
e722798a990f8cf78b47b402a3423df3056b64d2
[]
no_license
huseynakifoglu/Hangman
38b103117a65caf457789cdb1d58d7805d4440d6
adb15b32db6bfcf573153288de109f788ecd1321
refs/heads/main
2023-04-15T12:58:03.209548
2021-04-22T20:50:57
2021-04-22T20:50:57
360,679,077
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
vowels = 'aeiou' # create your list here inp = str(input()) vowels2 = [] for letters in inp: if letters in vowels: vowels2.append(letters) print(vowels2)
[ "huseynakifoglu@gmail.com" ]
huseynakifoglu@gmail.com
6ac842581a2c6b2489b264f9827c81d8cb25741b
ad3b71aca0cc0b897b8d0bee6e5f4189553754ca
/src/ralph/cmdb/monkey.py
af0a25ba118df33edbc74dc90209f3e781981d65
[ "Apache-2.0" ]
permissive
quamilek/ralph
4c43e3168f469045f18114f10779ee63d8ac784d
bf7231ea096924332b874718b33cd1f43f9c783b
refs/heads/master
2021-05-23T07:57:34.864521
2014-05-27T08:51:32
2014-05-27T08:51:32
5,523,714
0
0
null
null
null
null
UTF-8
Python
false
false
861
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from tastypie import http from tastypie.exceptions import ImmediateHttpResponse, HttpResponse def method_check(self, request, allowed=None): if allowed is None: allowed = [] request_method = request.method.lower() allows = ','.join(map(lambda x: x.upper(), allowed)) if request_method == "options": response = HttpResponse(allows) response['Allow'] = allows raise ImmediateHttpResponse(response=response) if not request_method in allowed: response = http.HttpMethodNotAllowed(allows) response['Allow'] = allows raise ImmediateHttpResponse(response=response) return request_method
[ "kwargula@gmail.com" ]
kwargula@gmail.com
10097fbf32479f4fa4d37381a6814e8656590a10
b04a4dde306ae11c1d3221da9efa9a0673e79a2c
/Scripts/text_chapper.py
6465a4b3703b76f4100f3202761abc8914ef2896
[]
no_license
lizzielee/Exploratory-Text-Analysis
e756447f0ed8f62367d8ef872540f09c78c650fc
343f212c663f77d2d3e619b2a5c1d0c16a179b82
refs/heads/master
2020-05-16T20:26:11.605081
2019-05-01T21:50:43
2019-05-01T21:50:43
183,283,039
0
0
null
null
null
null
UTF-8
Python
false
false
2,437
py
import re import os import sys # entry of the script def chap(novel): # txt book's path. novel_name = novel+'.txt' source_path = os.getcwd()+'/'+novel_name path_pieces = os.path.split(source_path) novel_title = re.sub(r'(\..*$)|($)', '', path_pieces[1]) target_path = '%s\\%s' % (path_pieces[0], novel_title)#小说分章目录 section_re = re.compile(r'^\s*CHAPTER.*$') # create the output folder if not os.path.exists(target_path): os.mkdir(target_path) # open the source file input = open(source_path, 'r',encoding='utf-8') sec_count = 0 sec_cache = [] title_cache=[] output = open('%s/new.txt' % (target_path), 'w',encoding='utf-8') #preface_title = '%s 前言' % novel_title #output.writelines(preface_title) for line in input: # is a chapter's title? #if line.strip() == '': #去掉空行 # pass if re.match(section_re, line): line = re.sub(r'\s+', ' ', line) print ('converting %s...' % line) output.writelines(sec_cache) chap_tar_path = '%s_chap_%d.txt' % (novel_name, sec_count) if not os.path.exists(target_path): os.mkdir(target_path) with open(chap_tar_path, 'w') as f: for i in sec_cache: f.write(i) output.flush() output.close() sec_cache = [] sec_count += 1 #chapter_name=re.sub('(~|!+|\(+|\)+|~+|\(+|\)+|(+|!+)','_',line) chapter_name=re.sub('(~+|\*+|\,+|\?+|\,+|\?+)','_',line)#章节名字当文件名字时,不能有特殊符号 # create a new section output = open('%s\\%s.txt' % (target_path, chapter_name), 'w',encoding='utf-8') output.writelines(line) title_cache.append(line+'\n') else: sec_cache.append(line) output.writelines(sec_cache) output.flush() output.close() sec_cache = [] # write the menu output = open('%s\\menu.txt' % (target_path), 'w',encoding='utf-8') menu_head = '%s menu' % novel_title output.writelines(menu_head) output.writelines(title_cache) output.flush() output.close() inx_cache = [] print ('completed. %d chapter(s) in total.' % sec_count) #if __name__ == '__main__': # main()
[ "hl7tv@virginia.edu" ]
hl7tv@virginia.edu
bdf6e59b458973aedccd0b74a16cd9dcb724640c
e61cbd9d69454f096bdcbc9a802354b53b643e62
/BsToPhiMuMu/test/BsToPhiMuMu_signal_2016_mcMINI.py
5e04ea2e8f6f27556768f61a62ca7da7c941791e
[]
no_license
rishabh-raturi/BsToPhiMuMu_angular_analysis
47248133b44b56f216c1063ab07b4283d18be1cb
d3199e834055c2c396350d2904baf8e2ae224df3
refs/heads/master
2023-04-04T23:42:47.953299
2021-04-12T18:29:49
2021-04-12T18:29:49
305,628,429
0
2
null
2021-04-09T18:20:52
2020-10-20T07:41:03
C++
UTF-8
Python
false
false
7,211
py
import FWCore.ParameterSet.Config as cms process = cms.Process("Ntuple") process.load("FWCore.MessageService.MessageLogger_cfi") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) RunOnMC = True KeepGen = False process.load('Configuration.Geometry.GeometryIdeal_cff') process.load('Configuration.StandardSequences.MagneticField_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') #process.GlobalTag.globaltag = cms.string('94X_dataRun2_v10') ## for 2016 # process.GlobalTag.globaltag = cms.string('94X_dataRun2_v11') ## for 2017 process.GlobalTag.globaltag = cms.string('102X_mcRun2_asymptotic_v7') process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( #'file:Miniaod_2016B.root', #'/store/data/Run2016G/Charmonium/MINIAOD/17Jul018-v1/40000/FE986973-338D-E811-A968-0242AC130002.root', 'file:/eos/home-c/ckar/BSTOPHIMUMU/files/bsTophimumu_mc_2016.root', #'file:/eos/home-c/ckar/BSTOPHIMUMU/files/bsTjpsiophi_mc_2016.root', #'file:/eos/home-c/ckar/BSTOPHIMUMU/files/charmonium_2018.root', #'file:/eos/home-c/ckar/BSTOPHIMUMU/files/charmonium_2017.root', ), ) taskB0 = cms.Task() process.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi') taskB0.add(process.unpackedTracksAndVertices) g_TriggerNames_LastFilterNames = [ ('HLT_DoubleMu4_JpsiTrk_Displaced', 'hltDisplacedmumuFilterDoubleMu4Jpsi'), ('HLT_DoubleMu4_PsiPrimeTrk_Displaced', 'hltDisplacedmumuFilterDoubleMu4PsiPrime'), ('HLT_DoubleMu4_LowMassNonResonantTrk_Displaced', 'hltLowMassNonResonantTkVertexFilter') ] g_TriggerNames = [i[0] for i in g_TriggerNames_LastFilterNames] g_LastFilterNames = [i[1] for i in g_TriggerNames_LastFilterNames] process.load("myanalyzer.BsToPhiMuMu.slimmedMuonsTriggerMatcher_cfi") process.ntuple = cms.EDAnalyzer('BsToPhiMuMu', OutputFileName = cms.string("BsToPhiMuMu_2016_SignalMC_Mini.root"), BuildBsToPhiMuMu = cms.untracked.bool(True), MuonMass = cms.untracked.double(0.10565837), MuonMassErr = cms.untracked.double(3.5e-9), KaonMass = cms.untracked.double(0.493677), KaonMassErr = cms.untracked.double(1.6e-5), BsMass = cms.untracked.double(5.36677), ## put the Bs Mass (pdg value) pruned = cms.InputTag("prunedGenParticles"), packed = cms.InputTag("packedGenParticles"), TriggerResultsLabel = cms.InputTag("TriggerResults","", "HLT"), prescales = cms.InputTag("patTrigger"), objects = cms.InputTag("slimmedPatTrigger"), TriggerNames = cms.vstring("HLT_DoubleMu4_LowMassNonResonantTrk_Displaced_v", "HLT_DoubleMu4_JpsiTrk_Displaced_v", "HLT_DoubleMu4_PsiPrimeTrk_Displaced_v" ), BeamSpotLabel = cms.InputTag("offlineBeamSpot"), VertexLabel = cms.InputTag("offlineSlimmedPrimaryVertices"), #MuonLabel = cms.InputTag("slimmedMuons"), MuonLabel = cms.InputTag('slimmedMuonsWithTrigger'), TrackLabel = cms.InputTag("unpackedTracksAndVertices"), PuInfoTag = cms.InputTag("slimmedAddPileupInfo"), #TriggerNames = cms.vstring([]), LastFilterNames = cms.vstring([]), IsMonteCarlo = cms.untracked.bool(RunOnMC), KeepGENOnly = cms.untracked.bool(KeepGen), TruthMatchMuonMaxR = cms.untracked.double(0.004), # [eta-phi] TruthMatchKaonMaxR = cms.untracked.double(0.3), # [eta-phi] MuonMinPt = cms.untracked.double(4.0), # 3.0 [GeV] MuonMaxEta = cms.untracked.double(2.4), MuonMaxDcaBs = cms.untracked.double(2.0), # [cm] MuMuMinPt = cms.untracked.double(6.9), # [GeV/c] MuMuMinInvMass1 = cms.untracked.double(1.0), # [GeV/c2] MuMuMinInvMass2 = cms.untracked.double(1.0), # [GeV/c2] MuMuMaxInvMass1 = cms.untracked.double(4.8), # [GeV/c2] MuMuMaxInvMass2 = cms.untracked.double(4.8), # [GeV/c2] MuMuMinVtxCl = cms.untracked.double(0.10), # 0.05 MuMuMinLxySigmaBs = cms.untracked.double(3.0), MuMuMaxDca = cms.untracked.double(0.5), # [cm] MuMuMinCosAlphaBs = cms.untracked.double(0.9), TrkMinPt = cms.untracked.double(0.8), # 0.4 [GeV/c] TrkMinDcaSigBs = cms.untracked.double(0.8), # 0.8 hadron DCA/sigma w/respect to BS (=>changed Max to Min) TrkMaxR = cms.untracked.double(110.0), # [cm] ==> size of tracker volume in radial direction TrkMaxZ = cms.untracked.double(280.0), # [cm] ==> size of tracker volume in Z direction PhiMinMass = cms.untracked.double(1.00), # [GeV/c2] - 3 sigma of the width(~5MeV) PhiMaxMass = cms.untracked.double(1.04), # [GeV/c2] + 3 sigma of the width BsMinVtxCl = cms.untracked.double(0.01), BsMinMass = cms.untracked.double(4.7), # [GeV/c2] BsMaxMass = cms.untracked.double(6.0), # [GeV/c2] #printMsg = cms.untracked.bool(False) ) # process.TFileService = cms.Service('TFileService', # fileName = cms.string( # 'BsToPhiMuMu_miniaod.root' # ), # closeFileFast = cms.untracked.bool(True) # ) #process.ntuple.TriggerNames = cms.vstring(g_TriggerNames) process.ntuple.LastFilterNames = cms.vstring(g_LastFilterNames) #process.ntupPath = cms.Path(process.ntuple) #process.ntupPath.associate(taskB0) process.p = cms.Path(process.slimmedMuonsWithTriggerSequence * process.unpackedTracksAndVertices * process.ntuple)
[ "rr26@iitbbs.ac.in" ]
rr26@iitbbs.ac.in
40d5762a122070b874120fdd440df72ae7f6214b
b31739ead4d788ba6b1f85333943d9a34764e0bc
/solicitud/middleware.py
6def6dfd06b59cac80de05a5d5fb852be5393ba8
[ "MIT" ]
permissive
jlopez0591/SIGIA
6a2c112cae2c0e6b56a031d7ed6d6213c63bbc3e
e857e2273daa43ab64fa78df254275af2dbcc2a5
refs/heads/master
2022-12-08T23:58:22.392419
2018-05-24T02:44:25
2018-05-24T02:44:25
128,885,789
0
0
MIT
2022-12-08T02:05:24
2018-04-10T06:39:48
Python
UTF-8
Python
false
false
470
py
class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response
[ "jose.a.lopez91@outlook.com" ]
jose.a.lopez91@outlook.com
784d53d39f20fcfda2d059e1656335e51ad350a9
b046b9dae8d79b574b4536aa596aee68bc714eec
/scraper/collector.py
2796f9ff0a733d0acf8a2f499d673b8f680b7ef3
[]
no_license
arush15june/metoo-world
5f9e4b4cd54cf83c8b39f2c3bf01a5d84853662b
143a92b2b578aad78ac138bd3bff9802d75fec8a
refs/heads/master
2020-04-02T02:21:23.870046
2018-10-20T14:16:47
2018-10-20T14:16:47
153,904,897
0
1
null
null
null
null
UTF-8
Python
false
false
1,511
py
""" Module to collect tweets for a specific hashtag. """ import os import pandas as pd import tweepy """ Export your - Consumer Key as "TWITTER_CONSUMER_KEY" - Consumer Key Secret as "TWITTER_CONSUMER_KEY_SECRET" - Access Token as "TWITTER_ACCESS_TOKEN" - Access Token Secret as as "TWITTER_ACCESS_TOKEN_SECRET" from your Twitter application dashboard. example. on Linux (bash), `export TWITTER_CONSUMER_KEY=<Consumer Key>` on Windows (cmd prompt), `set TWITTER_CONSUMER_KEY=<Consumer Key>` """ CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET = os.environ.get('TWITTER_CONSUMER_SECRET') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get("TWITTER_ACCESS_TOKEN_SECRET") class HashtagCollector(object): tweepy_auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) tweepy_auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) def __init__(self, hashtag): api = tweepy.API(auth) tweets = pd.DataFrame def _collect(self): """ Collect Tweets """ pass @staticmethod def _load(filename): """ Load Scraped Tweets from <filename> csv to a pandas dataframe """ pass @staticmethod def _save(filename, tweets): """ Save Tweets to <filename> as CSV from a <tweets> pd.DataFrame """ pass if __name__ == "__main__": """ Demo collection, saving and loading tweets """ pass
[ "ahujaarush@gmail.com" ]
ahujaarush@gmail.com
c57059bf4604606b822187e13a2d01251b0c6457
7693a1876512675950c74e05888b86a4c39595cb
/pythonTest/pyTestServer.py
f50314bc20c1b1da392ba14bc5568b0dd91aaf94
[]
no_license
kidyobo/MainPro
459956127cb70b3861ceb82511d981cb4875f29f
6a7b7c839b49ad92fe501a4e144937de88838d61
refs/heads/master
2022-02-11T10:04:19.579228
2019-07-19T04:58:25
2019-07-19T04:58:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,833
py
import urllib.request as urlReq import chardet import re from bs4 import BeautifulSoup def getHtml(url): request = urlReq.Request(url=url) response = urlReq.urlopen(request) html = response.read() charSet = chardet.detect(html) html = html.decode(str(charSet['encoding'])) return html #获取图片链接的方法 def getJpgImg(html): # 利用正则表达式匹配网页里的图片地址 reg = r'src="([.*\S]*\.jpg)" pic_ext="jpeg"' imgre = re.compile(reg) imgList = re.findall(imgre,html) imgCount = 0 for imgPath in imgList: f = open("F:/picture/"+str(imgCount)+".jpg",'wb') f.write((urlReq.urlopen(imgPath)).read()) f.close() imgCount+=1 def getPngImg(html): # 利用正则表达式匹配网页里的图片地址 reg = r'src="([.*\S]*\.png)"' imgre = re.compile(reg) imgList = re.findall(imgre,html) imgCount = 0 for imgPath in imgList: f = open("F:/picture/"+str(imgCount)+".png",'wb') f.write((urlReq.urlopen(imgPath)).read()) f.close() imgCount+=1 #获取新闻标题 def getNewsTitle(html): # 使用剖析器为html.parser soup = BeautifulSoup(html, 'html.parser') # 获取到每一个class=hot-article-img的a节点 allList = soup.select('.hot-article-img') for news in allList: article = news.select('a') if len(article) > 0: try: href = url + article[0]['href'] except Exception: href = '' try: imgUrl = article[0].select('img')[0]['src'] except Exception: imgUrl = "" try: title = article[0]['title'] except Exception: title = "标题为空" print("标题",title,"\nurl :",href,"\n图片地址 :",imgUrl) print("=============================================================================") # url = "http://tieba.baidu.com/p/3205263090" #图片爬取测试 url = "https://www.huxiu.com" #新闻标题爬取测试 html = getHtml(url) print(html) f = open("F:/picture/" + "htmlTxt" + ".txt",'w',encoding="utf-8") f.write(html) f.close() # getJpgImg(html) # print("Jpg抓取完成") # getNewsTitle(html) # for news in allList: # aaa = news.select('a') # # 只选择长度大于0的结果 # if len(aaa) > 0: # # 文章链接 # try:#如果抛出异常就代表为空 # href = url + aaa[0]['href'] # except Exception: # href='' # # 文章图片url # try: # imgUrl = aaa[0].select('img')[0]['src'] # except Exception: # imgUrl="" # # 新闻标题 # try: # title = aaa[0]['title'] # except Exception: # title = "标题为空" # print("标题",title,"\nurl:",href,"\n图片地址:",imgUrl) # print("==============================================================================================")
[ "827526630@qq.com" ]
827526630@qq.com
19b33e6ee5448ada5b60382dd73e067a09789030
b95ace067c9f3f54c6a85adee37318b167ec6324
/Python/HeapsortBalloons/balloons.py
db59df37f4e55f0e53936c15eb0b8fe64a35bfee
[]
no_license
dxa4481/RITprojects
387cce975fc3f761b1e87b416899b92f626664b2
6cd1f8b0fc68380ee0e6a4d82621e6769ac841c0
refs/heads/master
2020-12-25T16:25:03.133609
2013-05-27T18:46:09
2013-05-27T18:46:09
9,972,344
0
0
null
2014-02-11T22:59:01
2013-05-10T01:48:10
VHDL
UTF-8
Python
false
false
4,191
py
""" file: balloons.py Author: Dylan Ayrey Description: pops balloons that expand in R3 once they touch. If there is a balloon left over it will print that one. """ from array_heap import* from copy import deepcopy class Balloon(object): """ This is the balloon object that has a name and a position in R3 """ __slots__=('name','x','y','z') def __init__(self, name, x, y, z): self.name=name self.x=x self.y=y self.z=z def __str__(self): return self.name class Balloonpair(object): """ Holds 2 balloon objects and their distance """ __slots__=('balloons','distance') def __init__(self,balloons,dist): self.balloons=balloons self.distance=dist def getlist(balloonlist,word,boolean,balloontext): for line in balloontext: if boolean: boolean=False else: count=0 for char in line: word=word+char if char == ' ': if count==0: name=word elif count==1: x=word else: y=word word='' count+=1 name.replace(' ','') x.replace(' ','') y.replace(' ','') balloonlist.append(Balloon(name,int(x),int(y),int(word))) word='' return balloonlist def getdict(pairdict,balloonlist,heap): """ This function takes in an empty dictionary, a list of balloons and a heap, and returns a dictionary of balloons with their distances as the value """ for balloon in balloonlist: for secondballoon in balloonlist: dist=pow((pow(balloon.x-secondballoon.x,2)+pow(balloon.y-secondballoon.y,2)+pow(balloon.z-secondballoon.z,2)),.5) if dist in pairdict: torf=True for sublist in pairdict[dist]: if balloon in sublist: if secondballoon not in sublist: sublist.append(secondballoon) torf=False break elif secondballoon in sublist: if balloon not in sublist: sublist.append(balloon) torf=False break if torf: pairdict[dist].append([balloon,secondballoon]) elif dist!=0: pairdict[dist]=[[balloon,secondballoon]] add(heap,dist) return pairdict def getpopped(popped,pairdict,heap): """ Takes an empty list, a dictionary and a heap, returns a list of balloon objects that should be popped """ distance=removeMin(heap) while distance!=None: thingstoremove=[] for sublist in pairdict[distance]: for balloon in sublist: if balloon in popped: thingstoremove.append(balloon) for sublist in pairdict[distance]: for balloon in thingstoremove: if balloon in sublist: sublist.remove(balloon) for sublist in pairdict[distance]: if len(sublist)>1: for balloon in sublist: if balloon not in popped: popped.append(balloon) distance=removeMin(heap) return popped def main(): """ This is the main function that imploments the heap sort, it gets the popped balloons and then pops them """ balloontext=open(input('What is the filename?:')) boolean=True for firstline in balloontext: heap=Heap(int(firstline),less) break balloonlist=getlist([],'',True,balloontext) pairdict=getdict({},balloonlist,heap) popped=getpopped([],pairdict,heap) for balloon in popped: print(balloon) balloonlist.remove(balloon) if balloonlist==[]: print('there is no last ballon, they all popped') else: print('The last balloon is') print(balloonlist[0]) main()
[ "dxa4481@rit.edu" ]
dxa4481@rit.edu
ca16ce0b4c0fb35cf61090f93963d0791dc0b4e4
999ea415e8bbdaa84948a248c58603239402f39f
/venv/pythonlearn/regular.py
a48a0b86fb456569e22a3ac6fece3f20faf82de7
[]
no_license
purpleflameangle/untitled
df942f1c561160bf0ad1dd8259f02a32696b3666
039729a7da316956194c5a4f3c318bc8f87716d5
refs/heads/master
2021-07-20T19:57:23.066395
2021-07-02T02:26:10
2021-07-02T02:26:10
173,409,462
0
0
null
null
null
null
UTF-8
Python
false
false
3,269
py
#!/usr/bin/python # -*- encoding: utf-8 -*- import urllib import urllib.request import re import sys import os import ssl # 正则表达式 # https://docs.python.org/3.6/howto/regex.html?highlight=regular ''' try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context ''' ssl._create_default_https_context = ssl._create_unverified_context # http_connection.context = ssl.create_default_context(cafile=cfg.ca_certs_file) # http_connection.context_set = True print(re.search(r"Fish(C|D)", "FishC")) # ^表示匹配字符串的开始位置,只有目标字符串出现在开头才会匹配 print(re.search(r"^FishC", "I love FishC.com")) # $表示匹配字符串的借宿位置,只有目标字符串出现在末尾才会匹配 print(re.search(r"FishC$", "FishC.com!")) # ()本身是一对元字符串,被他们括起来的正则表达式称为一个子组,为一个整体 # []它是生成一个字符类,事实上就是一个字符集合,被它包围在里面的元字符都失去了特殊的功能 # 小横杠(-),用它表示范围 # 反斜杠\ 用于字符串转义 # 拖字符^ 用于取反 # 表示重复的元字符还有:* ,+ 和? # 星号(*)表示相当于{0,} # 加号(+)表示相当于{1,} # 问号(?) 表示相当于{0,1} p = re.compile('ab*') print(p) p1 = re.compile('ab*', re.IGNORECASE) print(p1) p2 = re.compile('[a-z]+') print(p2) print(p2.match('')) m = p2.match('tempo') print(m) print(m.group()) print(m.start(), m.end()) print(m.span()) p3 = re.compile(r'\d+') find = p3.findall('12 drummers drumming, 11 pipers piping') print(find) p3 = re.compile('...') m1 = p3.match('string goes') if m: print('match found:', m1.group()) else: print('no match') p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b') print(p.search('Paris in the the spring').group()) m = re.match("([abc])+", "abc") print(m.groups()) m = re.match("(?:[abc])+", "abc") print(m.groups()) p = re.compile(r'(?P<word>\b\w+\b)') m = p.search('(((( Lots of punctuation )))') print(m.group('word')) ''' # 获取美图run success def open_url(url1): req = urllib.request.Request(url1) req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.2 Safari/605.1.15') req.add_header('Content-Type', 'application/json') response = urllib.request.urlopen(req) html = response.read().decode('utf-8', 'ignore') return html def get_image(html): p = r'<img class="BDE_Image".*?src="([^"]*\.jpg)".*?>' imglist = re.findall(p, html) try: os.mkdir("NewPic") except FileExistsError: pass os.chdir("NewPic") for each in imglist: filename = each.split("/")[-1] urllib.request.urlretrieve(each, filename, None) def get_image1(html): p = r'(([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])' imglist1 = re.findall(p, html) for each in imglist1: print(each) if __name__ == "__main__": url = "http://tieba.baidu.com/p/3823765471" get_image(open_url(url)) url1 = "http://cn-proxy.com/" get_image1(url1) '''
[ "hermesdifa@hotmail.com" ]
hermesdifa@hotmail.com
257e78f93bdfffd8ead6050e5a830887b2daf06c
d7c527d5d59719eed5f8b7e75b3dc069418f4f17
/main/PythonResults/_pythonSnippet11/32/pandasjson.py
a577b4507d59a3ae833713639051216cf30d9928
[]
no_license
Aivree/SnippetMatcher
3e348cea9a61e4342e5ad59a48552002a03bf59a
c8954dfcad8d1f63e6e5e1550bc78df16bc419d1
refs/heads/master
2021-01-21T01:20:59.144157
2015-01-07T04:35:29
2015-01-07T04:35:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,099
py
from pandas import Series, DataFrame from _pandasujson import loads, dumps @classmethod def from_json(cls, json, orient="index", dtype=None, numpy=True): """ Convert JSON string to Series Parameters ---------- json : The JSON string to parse. orient : {'split', 'records', 'index'}, default 'index' The format of the JSON string split : dict like {index -> [index], name -> name, data -> [values]} records : list like [value, ... , value] index : dict like {index -> value} dtype : dtype of the resulting Series nupmpy: direct decoding to numpy arrays. default True but falls back to standard decoding if a problem occurs. Returns ------- result : Series """ s = None if dtype is not None and orient == "split": numpy = False if numpy: try: if orient == "split": decoded = loads(json, dtype=dtype, numpy=True) decoded = dict((str(k), v) for k, v in decoded.iteritems()) s = Series(**decoded) elif orient == "columns" or orient == "index": s = Series(*loads(json, dtype=dtype, numpy=True, labelled=True)) else: s = Series(loads(json, dtype=dtype, numpy=True)) except ValueError: numpy = False if not numpy: if orient == "split": decoded = dict((str(k), v) for k, v in loads(json).iteritems()) s = Series(dtype=dtype, **decoded) else: s = Series(loads(json), dtype=dtype) return s Series.from_json = from_json def to_json(self, orient="index", double_precision=10, force_ascii=True): """ Convert Series to a JSON string Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- orient : {'split', 'records', 'index'}, default 'index' The format of the JSON string split : dict like {index -> [index], name -> name, data -> [values]} records : list like [value, ... , value] index : dict like {index -> value} double_precision : The number of decimal places to use when encoding floating point values, default 10. force_ascii : force encoded string to be ASCII, default True. Returns ------- result : JSON compatible string """ return dumps(self, orient=orient, double_precision=double_precision, ensure_ascii=force_ascii) Series.to_json = to_json @classmethod def from_json(cls, json, orient="columns", dtype=None, numpy=True): """ Convert JSON string to DataFrame Parameters ---------- json : The JSON string to parse. orient : {'split', 'records', 'index', 'columns', 'values'}, default 'columns' The format of the JSON string split : dict like {index -> [index], columns -> [columns], data -> [values]} records : list like [{column -> value}, ... , {column -> value}] index : dict like {index -> {column -> value}} columns : dict like {column -> {index -> value}} values : just the values array dtype : dtype of the resulting DataFrame nupmpy: direct decoding to numpy arrays. default True but falls back to standard decoding if a problem occurs. Returns ------- result : DataFrame """ df = None if dtype is not None and orient == "split": numpy = False if numpy: try: if orient == "columns": args = loads(json, dtype=dtype, numpy=True, labelled=True) if args: args = (args[0].T, args[2], args[1]) df = DataFrame(*args) elif orient == "split": decoded = loads(json, dtype=dtype, numpy=True) decoded = dict((str(k), v) for k, v in decoded.iteritems()) df = DataFrame(**decoded) elif orient == "values": df = DataFrame(loads(json, dtype=dtype, numpy=True)) else: df = DataFrame(*loads(json, dtype=dtype, numpy=True, labelled=True)) except ValueError: numpy = False if not numpy: if orient == "columns": df = DataFrame(loads(json), dtype=dtype) elif orient == "split": decoded = dict((str(k), v) for k, v in loads(json).iteritems()) df = DataFrame(dtype=dtype, **decoded) elif orient == "index": df = DataFrame(loads(json), dtype=dtype).T else: df = DataFrame(loads(json), dtype=dtype) return df DataFrame.from_json = from_json def to_json(self, orient="columns", double_precision=10, force_ascii=True): """ Convert DataFrame to a JSON string. Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps. Parameters ---------- orient : {'split', 'records', 'index', 'columns', 'values'}, default 'columns' The format of the JSON string split : dict like {index -> [index], columns -> [columns], data -> [values]} records : list like [{column -> value}, ... , {column -> value}] index : dict like {index -> {column -> value}} columns : dict like {column -> {index -> value}} values : just the values array double_precision : The number of decimal places to use when encoding floating point values, default 10. force_ascii : force encoded string to be ASCII, default True. Returns ------- result : JSON compatible string """ return dumps(self, orient=orient, double_precision=double_precision, ensure_ascii=force_ascii) DataFrame.to_json = to_json def maybe_to_json(obj=None): if hasattr(obj, 'to_json'): return obj.to_json() return obj
[ "prateek1404@gmail.com" ]
prateek1404@gmail.com
9af41a79b052c2d412d395809a59b4b75ad6d6a6
30cc35f967b9f13f133170983987ee747a49cba4
/suspects/test/test_randname.py
6782fddecae3f7ff8ba477c8e460b2e0e2544856
[ "MIT" ]
permissive
rjweir/murderrl
aba52fe91e585d09da5660c66ac1796fe76f6205
788710a913758d2e5ab3f1ed1983df44eae34edf
refs/heads/master
2021-01-18T06:53:34.263030
2011-01-24T23:07:58
2011-01-24T23:07:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,384
py
#!/usr/bin/env python from suspects.randname import * def generate_names (num = 10, style = None, gender = None): """ Generates and outputs a given number of random names. :``num``: The number of repeats. *Default 10*. :``style``: One of ``'upper'``, ``'middle'``, ``'lower'`` for upper-, middle- and lowerclass names, respectively. *Default random*. :``gender``: Gender: ``'m'`` or ``'f'``. *Default random*. """ check_name_db() for i in xrange(num): print get_random_fullname(gender, style) if __name__ == "__main__": """ Outputs a given amount of British names. :``num``: The number of repeats. *Default 10*. :``style``: One of ``'upper'``, ``'middle'`` or ``'lower'`` for upper-, middle- and lowerclass names, respectively. *Default random*. :``gender``: Gender: ``'m'`` or ``'f'``. *Default random*. """ num = 10 style = None gender = None if len(sys.argv) > 1: try: num = int(sys.argv[1]) except ValueError: sys.stderr.write("Error: Expected integer argument, using default value %d\n" % num) pass if len(sys.argv) > 2: style = sys.argv[2] if len(sys.argv) > 3: gender = sys.argv[3] generate_names(num, style, gender)
[ "jonathan@acss.net.au" ]
jonathan@acss.net.au
1e4e5a7e81ba3eb57af755d28a1b01382a8dd32f
48e124e97cc776feb0ad6d17b9ef1dfa24e2e474
/sdk/python/pulumi_azure_native/network/v20210501/network_security_group.py
edee6131821444d88b72b7c2692d9b75a39b6d8d
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bpkgoud/pulumi-azure-native
0817502630062efbc35134410c4a784b61a4736d
a3215fe1b87fba69294f248017b1591767c2b96c
refs/heads/master
2023-08-29T22:39:49.984212
2021-11-15T12:43:41
2021-11-15T12:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,540
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['NetworkSecurityGroupInitArgs', 'NetworkSecurityGroup'] @pulumi.input_type class NetworkSecurityGroupInitArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_security_group_name: Optional[pulumi.Input[str]] = None, security_rules: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ The set of arguments for constructing a NetworkSecurityGroup resource. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] network_security_group_name: The name of the network security group. :param pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]] security_rules: A collection of security rules of the network security group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ pulumi.set(__self__, "resource_group_name", resource_group_name) if id is not None: pulumi.set(__self__, "id", id) if location is not None: pulumi.set(__self__, "location", location) if network_security_group_name is not None: pulumi.set(__self__, "network_security_group_name", network_security_group_name) if security_rules is not None: pulumi.set(__self__, "security_rules", security_rules) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource ID. """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ Resource location. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="networkSecurityGroupName") def network_security_group_name(self) -> Optional[pulumi.Input[str]]: """ The name of the network security group. """ return pulumi.get(self, "network_security_group_name") @network_security_group_name.setter def network_security_group_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "network_security_group_name", value) @property @pulumi.getter(name="securityRules") def security_rules(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]]]: """ A collection of security rules of the network security group. """ return pulumi.get(self, "security_rules") @security_rules.setter def security_rules(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityRuleArgs']]]]): pulumi.set(self, "security_rules", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Resource tags. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) class NetworkSecurityGroup(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_security_group_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, security_rules: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityRuleArgs']]]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): """ NetworkSecurityGroup resource. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] network_security_group_name: The name of the network security group. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityRuleArgs']]]] security_rules: A collection of security rules of the network security group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ ... @overload def __init__(__self__, resource_name: str, args: NetworkSecurityGroupInitArgs, opts: Optional[pulumi.ResourceOptions] = None): """ NetworkSecurityGroup resource. :param str resource_name: The name of the resource. :param NetworkSecurityGroupInitArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(NetworkSecurityGroupInitArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, network_security_group_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, security_rules: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityRuleArgs']]]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = NetworkSecurityGroupInitArgs.__new__(NetworkSecurityGroupInitArgs) __props__.__dict__["id"] = id __props__.__dict__["location"] = location __props__.__dict__["network_security_group_name"] = network_security_group_name if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["security_rules"] = security_rules __props__.__dict__["tags"] = tags __props__.__dict__["default_security_rules"] = None __props__.__dict__["etag"] = None __props__.__dict__["flow_logs"] = None __props__.__dict__["name"] = None __props__.__dict__["network_interfaces"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["subnets"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:network:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20150501preview:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20150615:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20160330:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20160601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20160901:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20161201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170301:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20170901:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20171001:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20171101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180401:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180701:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20180801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20181001:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20181101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20181201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190401:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190701:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20190901:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20191101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20191201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200301:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200401:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200501:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200601:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200701:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20200801:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20201101:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20210201:NetworkSecurityGroup"), pulumi.Alias(type_="azure-native:network/v20210301:NetworkSecurityGroup")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(NetworkSecurityGroup, __self__).__init__( 'azure-native:network/v20210501:NetworkSecurityGroup', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'NetworkSecurityGroup': """ Get an existing NetworkSecurityGroup resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = NetworkSecurityGroupInitArgs.__new__(NetworkSecurityGroupInitArgs) __props__.__dict__["default_security_rules"] = None __props__.__dict__["etag"] = None __props__.__dict__["flow_logs"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["network_interfaces"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["resource_guid"] = None __props__.__dict__["security_rules"] = None __props__.__dict__["subnets"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None return NetworkSecurityGroup(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="defaultSecurityRules") def default_security_rules(self) -> pulumi.Output[Sequence['outputs.SecurityRuleResponse']]: """ The default security rules of network security group. """ return pulumi.get(self, "default_security_rules") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="flowLogs") def flow_logs(self) -> pulumi.Output[Sequence['outputs.FlowLogResponse']]: """ A collection of references to flow log resources. """ return pulumi.get(self, "flow_logs") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="networkInterfaces") def network_interfaces(self) -> pulumi.Output[Sequence['outputs.NetworkInterfaceResponse']]: """ A collection of references to network interfaces. """ return pulumi.get(self, "network_interfaces") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the network security group resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> pulumi.Output[str]: """ The resource GUID property of the network security group resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter(name="securityRules") def security_rules(self) -> pulumi.Output[Optional[Sequence['outputs.SecurityRuleResponse']]]: """ A collection of security rules of the network security group. """ return pulumi.get(self, "security_rules") @property @pulumi.getter def subnets(self) -> pulumi.Output[Sequence['outputs.SubnetResponse']]: """ A collection of references to subnets. """ return pulumi.get(self, "subnets") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type. """ return pulumi.get(self, "type")
[ "noreply@github.com" ]
bpkgoud.noreply@github.com
6436ec751bc93d7e2298d44e2fde50cd902e4f7b
df14ae429d00dd89cc1405701450e74a41962a5f
/api/models.py
b9a1ac56afe8f8f2b81cffbfe8c5a43e14ef4870
[]
no_license
headsrooms/landbot-backend
3a42beada75f2477dfa2e01db81d76d8c1aa2253
6a99217885a3df87dc2c155da0e2f1f26b59827f
refs/heads/master
2022-11-24T03:04:39.131177
2020-07-27T15:03:33
2020-07-27T15:03:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
752
py
from tortoise import fields, models class User(models.Model): id = fields.UUIDField(pk=True) name = fields.CharField(max_length=20) last_name = fields.CharField(max_length=30) email = fields.CharField(max_length=30) phone = fields.CharField(max_length=10) questions: fields.ReverseRelation["Question"] def __str__(self) -> str: return f"User {self.id}: {self.name} {self.last_name}" class Question(models.Model): id = fields.UUIDField(pk=True) text = fields.TextField() user: fields.ForeignKeyRelation[User] = fields.ForeignKeyField( "models.User", related_name="questions" ) def __str__(self) -> str: return f"Question {self.id}: {self.text} from user with id {self.user}"
[ "pablocabezas@wegow.com" ]
pablocabezas@wegow.com
350cbcb59cae359707b2f28e2e2fe260bd888ec1
058acf0b6d32a1f8d82673663f93377f5ec61cc1
/functional_tests/tests.py
171c67fd47df02c9c05514e4776122eb55bc7883
[]
no_license
jravesloot/chicagoautismnetwork
f14cb50495edd49f99465b2528cba44b57dfd0d8
2e4e958941b318914b94d3b2e3eedc21c768b08a
refs/heads/master
2021-05-16T03:47:19.928293
2017-10-01T00:47:04
2017-10-01T00:47:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,796
py
from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import WebDriverException import time MAX_WAIT = 10 class NewVisitorTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def check_for_row_in_list_table(self, row_text): table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn(row_text, [row.text for row in rows]) def wait_for_row_in_list_table(self, row_text): start_time = time.time() while True: try: table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn(row_text, [row.text for row in rows]) return except (AssertionError, WebDriverException) as e: if time.time() - start_time > MAX_WAIT: raise e time.sleep(0.5) def test_can_start_a_list_for_one_user(self): # Edith has heard about a cool new online to-do app. She goes # to check out its homepage self.browser.get(self.live_server_url) # She notices the page title and header mention to-do lists self.assertIn('Guides', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('Guides', header_text) # She is invited to enter a to-do item straight away inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual( inputbox.get_attribute('placeholder'), 'Enter a to-do item' ) # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) inputbox.send_keys('Buy peacock feathers') # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an item in a to-do list table inputbox.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy peacock feathers') # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very # methodical) inputbox = self.browser.find_element_by_id('id_new_item') inputbox.send_keys('Use peacock feathers to make a fly') inputbox.send_keys(Keys.ENTER) # The page updates again, and now shows both items on her list self.wait_for_row_in_list_table('2: Use peacock feathers to make a fly') self.wait_for_row_in_list_table('1: Buy peacock feathers') # Satisfied, she goes back to sleep def test_multiple_users_can_start_lists_at_different_urls(self): # Edith starts a new to-do list self.browser.get(self.live_server_url) inputbox = self.browser.find_element_by_id('id_new_item') inputbox.send_keys('Buy peacock feathers') inputbox.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy peacock feathers') # She notices that her list has a unique URL edith_list_url = self.browser.current_url self.assertRegex(edith_list_url, '/guides/.+') self.assertRegex(edith_list_url, '/guides/.+') # Now a new user, Francis, comes along to the site. ## We use a new browser session to make sure that no information ## of Edith's is coming through from cookies etc self.browser.quit() self.browser = webdriver.Firefox() # Francis visits the home page. There is no sign of Edith's # list self.browser.get(self.live_server_url) page_text = self.browser.find_element_by_tag_name('body').text self.assertNotIn('Buy peacock feathers', page_text) self.assertNotIn('make a fly', page_text) # Francis starts a new list by entering a new item. He # is less interesting than Edith... inputbox = self.browser.find_element_by_id('id_new_item') inputbox.send_keys('Buy milk') inputbox.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: Buy milk') # Francis gets his own unique URL francis_list_url = self.browser.current_url self.assertRegex(francis_list_url, '/guides/.+') self.assertNotEqual(francis_list_url, edith_list_url) # Again, there is no trace of Edith's list page_text = self.browser.find_element_by_tag_name('body').text self.assertNotIn('Buy peacock feathers', page_text) self.assertIn('Buy milk', page_text) # Satisfied, they both go back to sleep
[ "davidkunio@gmail.com" ]
davidkunio@gmail.com
bc31115683a8ac4e88909fc81927c1697f17de95
409dcbf3db108e4ccd000b9a9ed443fd6b8af871
/701-800/760/codeforces760a.py
9b58228637ce37ad801a358711641402a3ca8b13
[]
no_license
wardmike/CodeForces
a9aef04a8f8868a461c2c6d2f2c506dc22da2264
dbabf51fa91b93c4805f05467d440a08db6ee87a
refs/heads/master
2021-06-17T09:49:31.461036
2017-06-01T14:40:31
2017-06-01T14:40:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
306
py
xx = map(int, raw_input().split(' ')) m = xx[0] mm = 0 d = xx[1] c = 0 if m is 1 or m is 3 or m is 5 or m is 7 or m is 8 or m is 10 or m is 12: mm = 31 elif m is 2: mm = 28 else: mm = 30 mm = mm - 8 + d c = c + 1 while (mm > 0): mm = mm - 7 c = c + 1 print c
[ "xenophon.of.athens@gmail.com" ]
xenophon.of.athens@gmail.com
402b1c8d9c5883a2658aaa692947f6979454a971
858a74f8b6bd3e62c78ace94b49595772688106f
/data_stream.py
ce7efdd75b93577761b81e009f8cd5ab310ef173
[]
no_license
jvaesteves/udacity_project_2
61c8c89a347ac074165c9a2746328bc4565fbb69
3a73084549a754dd45be89caa1209984ae7fd96e
refs/heads/main
2023-01-21T15:55:54.781048
2020-11-23T02:10:53
2020-11-23T02:10:53
315,134,830
0
0
null
null
null
null
UTF-8
Python
false
false
2,848
py
from pyspark.sql.types import StructField, StructType, StringType, TimestampType from pyspark.sql.functions import from_json, col from pyspark.sql import SparkSession from pathlib import Path import logging import json schema = StructType([ StructField('crime_id', StringType(), True), StructField('original_crime_type_name', StringType(), True), StructField('report_date', StringType(), True), StructField('call_date', StringType(), True), StructField('offense_date', StringType(), True), StructField('call_time', StringType(), True), StructField('call_date_time', TimestampType(), True), StructField('disposition', StringType(), True), StructField('address', StringType(), True), StructField('city', StringType(), True), StructField('state', StringType(), True), StructField('agency_id', StringType(), True), StructField('address_type', StringType(), True), StructField('common_location', StringType(), True), ]) def run_spark_job(spark): df = spark.readStream.format('kafka') \ .option('kafka.bootstrap.servers','localhost:9092') \ .option('subscribe', 'POLICE_CALLS') \ .option('startingOffsets', 'earliest') \ .option('maxOffsetsPerTrigger', 8000) \ .option('stopGracefullyOnShutdown', "true") \ .load() df.printSchema() kafka_df = df.select(df.value.cast('string')) service_table = kafka_df.select(from_json(col('value'), schema).alias("DF")).select("DF.*") distinct_table = service_table.select('original_crime_type_name', 'disposition', 'call_date_time').distinct() agg_df = distinct_table \ .dropna() \ .select('original_crime_type_name') \ .groupby('original_crime_type_name') \ .agg({'original_crime_type_name': 'count'})\ .orderBy("count(original_crime_type_name)", ascending=False) query = agg_df.writeStream.format('console')\ .trigger(processingTime='30 seconds')\ .outputMode('complete')\ .option("truncate", "false")\ .start() query.awaitTermination() radio_code_json_filepath = f"{Path(__file__).parents[0]}/radio_code.json" radio_code_df = spark.read.json(radio_code_json_filepath) radio_code_df = radio_code_df.withColumnRenamed("disposition_code", "disposition") join_query = agg_df.join(radio_code_df, 'disposition', 'left_outer') join_query.awaitTermination() if __name__ == "__main__": logger = logging.getLogger(__name__) # TODO Create Spark in Standalone mode spark = SparkSession \ .builder \ .master("local[*]") \ .config("spark.sql.shuffle.partitions", 4) \ .appName("KafkaSparkStructuredStreaming") \ .getOrCreate() logger.info("Spark started") run_spark_job(spark) spark.stop()
[ "joao.esteves@olxbr.com" ]
joao.esteves@olxbr.com
6b5d03fcb4a1046698dcdfd1f92dd2f9e8b1d376
e6b95801bdace3e934f3827f8d34e95f54852252
/dns/dns_packet.py
392e26537098c9bdbe2ba9876d4e73c11a0b937e
[]
no_license
FacelessLord/CacheDNS
6a468745b778d3829660c1b75f69a8208f0bd358
06c3449bdd1982d55cfe5f8cb3e8e4c46730e2ad
refs/heads/master
2022-09-11T20:19:37.447489
2020-06-03T08:04:46
2020-06-03T08:04:46
268,297,115
0
0
null
null
null
null
UTF-8
Python
false
false
2,282
py
import struct from typing import List, Tuple from dns.dns_header import DNSHeader, parse_header from dns.dns_query import DNSQuery, parse_queries from dns.resource_record import parse_records, ResourceRecord class DNSPacket: def __init__(self, header: DNSHeader): self.header: DNSHeader = header self.queries: List[DNSQuery] = [] self.ans_records: List[ResourceRecord] = [] self.auth_records: List[ResourceRecord] = [] self.additional_records: List[ResourceRecord] = [] def add_query(self, query: DNSQuery): self.queries.append(query) return self def set_data(self, queries: List[DNSQuery], records: List[ResourceRecord]): self.queries = queries self.ans_records = records[:self.header.an_count] self.auth_records = records[self.header.an_count: self.header.an_count + self.header.ns_count] self.additional_records = \ records[self.header.an_count + self.header.ns_count: self.header.an_count + self.header.ns_count + self.header.ar_count] return self def to_bytes(self) -> bytes: fmt = '!12s' values = [self.header.to_bytes()] for q in self.queries: query_bytes, size = q.to_bytes() fmt += str(size) + 's' values.append(query_bytes) for r in self.ans_records + self.auth_records + self.additional_records: record_bytes = r.to_bytes() fmt += str(len(record_bytes)) + 's' values.append(record_bytes) return struct.pack(fmt, *values) def read_packet(packet_bytes: bytes) -> DNSPacket: header, queries = struct.unpack( '!12s' + str(len(packet_bytes) - 12) + 's', packet_bytes) header = parse_header(header) queries, residual = parse_queries(queries, header.qd_count, packet_bytes) records = list(parse_records(residual, packet_bytes)) return DNSPacket(header).set_data(queries, records) def create_dns_packet(request_id: int, queries: List[DNSQuery]) -> DNSPacket: header = DNSHeader(request_id, False, 0, False, False, True, True, 0, 1, 0, 0, 0) return DNSPacket(header).set_data(queries, [])
[ "skyres21@yandex.ru" ]
skyres21@yandex.ru
04a5e1ecf5eb7928a641bacbe6d6f6bbbf4dc517
f0a9e69f5acd27877316bcdd872d12b9e92d6ccb
/while.py
59f6e3da65c64608dea5c349cff9ebf6c9d92fc3
[]
no_license
KhauTu/KhauTu-Think_Python
9cb2a286efb8a33748599cd3ae4605e48256ac4c
880c06f6218b8aee7a3e3da0d8b4764fcaa9c1b4
refs/heads/master
2020-05-29T21:43:47.246199
2019-05-30T11:36:05
2019-05-30T11:36:05
189,389,541
0
0
null
null
null
null
UTF-8
Python
false
false
2,980
py
# while expression: # while-block ''' k = 5 while k > 0: print('k = ', k) k -= 1 ''' ''' s = 'How Kteam' idx = 0 length = len(s) while idx < length: print(idx, 'stands for', s[idx]) idx += 1 ''' ''' five_even_numbers = [] k_number = 1 while True: # vòng lặp vô hạn vì giá trị này là hằng nên ta không thể tác động được if k_number % 2 == 0: # nếu k_number là một số chẵn five_even_numbers.append(k_number) # thêm giá trị của k_number vào list if len(five_even_numbers) == 5: # nếu list này đủ 5 phần tử break # thì kết thúc vòng lặp k_number += 1 print(five_even_numbers) print(k_number) ''' ''' k_number = 0 while k_number < 10: k_number += 1 if k_number % 2 == 0: # nếu k_number là số chẵn continue print(k_number, 'is odd number') print(k_number) ''' ''' while expression: # while-block else: # else-block ''' ''' k = 0 while k < 3: print('value of k is', k) k += 1 else: print('k is not less than 3 anymore') ''' # Trong trường hợp trong while-block chạy câu lệnh break thì vòng lặp while sẽ kết thúc và phần else-block cũng sẽ không được thực hiện. draft = '''an so dfn Kteam odsa in fasfna Kteam mlfjier as dfasod nf ofn asdfer fsan dfoans ldnfad Kteam asdfna asdofn sdf pzcvqp Kteam dfaojf kteam dfna Kteam dfaodf afdna Kteam adfoasdf ncxvo aern Kteam dfad''' kteam = [] # Khởi tạo file draft.txt with open('draft.txt','w') as d: print(draft, file = d) # đọc từng dòng trong draft.txt with open('draft.txt') as d: line = d.readlines() # print(len(line)) for i in range(len(line)): print(line[i]) # đưa từng line về dạng list, ngăn cách bằng space ' ' line_list = line[i].split(sep = ' ') print(line_list) k = 0 while k < len(line_list): # thay thế 'Kteam' bằng 'How Kteam' nếu từ đầu tiên của list là 'Kteam' if line_list[k] == "Kteam": # print(line_list[k-1]) if k-1 < 0: line_list[k] = "How Kteam" # thay thế từ đứng trước 'Kteam' bằng 'How' nếu 'Kteam' không đứng đầu list else: line_list[k-1] = "How" k += 1 else: k += 1 # nối các từ trong list thành line mới new_line = ' '.join(line_list) print(new_line) # cho new line vào trong list kteam kteam.append(new_line) # Nối các line trong list kteam thành đoạn văn bản # print(''.join(kteam)) with open('kteam.txt','w') as f: print(''.join(kteam), file = f) # thay thế xuống dòng \n bằng dấu cách space # draft = draft.replace('\n',' ') # đưa về dạng list # draft_list = draft.split(sep = ' ') # print(draft_list) # print(data) # print(kteam)
[ "dongkhautu@gmail.com" ]
dongkhautu@gmail.com
2d4cf09f0f2aa26d2385b364596894feba510a91
e2e188297b0ef47f0e7e935290f3b7a175376f8f
/auth/urls.py
876eb04ddf2bc73525218b4bd7aa9c894bc3c77e
[]
no_license
shubham1560/contact-us-backend
77b615021f0db2a48444424a654cf3c61522c7d8
c7ef2d3024ab3f3b6f077648d6f6f5357f01eebc
refs/heads/master
2022-12-30T13:05:00.950702
2020-10-02T19:47:19
2020-10-02T19:47:19
296,075,868
0
0
null
null
null
null
UTF-8
Python
false
false
493
py
from django.urls import path, include from .views import ObtainAuthTokenViewSet, CreateUserSystemViewSet urlpatterns = [ path('token/get_token/', ObtainAuthTokenViewSet.as_view()), path('user/register/system/', CreateUserSystemViewSet.as_view()), # path('user/register/google/'), # path('user/register/facebook/'), # path('user/activate/'), # path('user/password_reset/'), # path('user/send_reset_link/'), # path('token/valid/'), # path('token/user/'), ]
[ "shubhamsinha2050@gmail.com" ]
shubhamsinha2050@gmail.com