blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
bd74a3ab41b48ffe8069d7327a2c0494179fcbfe
fcde32709c62b8ee86da459bb7c8eee52c848118
/code/day03/r4.py
37ad4deb38ed39591d4c123e94a810e47614be79
[]
no_license
klaus2015/py_base
6b92d362c3d7dc0e09205a037f4d580381dac94d
ec32c731c1c2f6a0dab87f1d167397e4fa86b8de
refs/heads/master
2022-07-28T15:49:30.383648
2020-05-11T15:31:43
2020-05-11T15:31:43
261,777,278
0
0
null
null
null
null
UTF-8
Python
false
false
716
py
# state = None # number = int(input("请输入一个整数: ")) # if number % 2 : # state = "奇数" # else: # state = "偶数" # print(state) # state = "奇数" if int(input("请输入整数: ")) % 2 else "偶数" # print(state) year = int(input("请输入年份:")) result = year % 4 == 0 and year % 100 != 0 or year % 400 == 0 if result: day = 29 else: day = 28 print(day) 代码简单,但是可读性差 能被4整除但是不能被100整除,或者可以被400整除 day = 29 if not year % 4 and year % 100 or not year % 400 else 28 day = 29 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 28 result = year % 4 print(result) year = 2000 result = year % 4 print(result)
a4b9d93d338391843fa18a38fd30a88d04acb569
e0ede722874d222a789411070f76b50026bbe3d8
/practice/solution/0894_all_possible_full_binary_trees.py
2727423a40a633641a8545b0f9ac6da90888a70d
[]
no_license
kesarb/leetcode-summary-python
cd67456cb57bdff7ee227dab3930aaf9c2a6ad00
dc45210cb2cc50bfefd8c21c865e6ee2163a022a
refs/heads/master
2023-05-26T06:07:25.943854
2021-06-06T20:02:13
2021-06-06T20:02:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,031
py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def allPossibleFBT(self, N): """ :type N: int :rtype: List[TreeNode] """ self.value_dict = {1: [TreeNode(0)]} self.res = 0 self.res = self.dfs(N) return self.res def dfs(self, N): temp_list = [] if N in self.value_dict: temp_list = self.value_dict[N] return temp_list for i in range(1, N, 2): for left in self.dfs(i): for right in self.dfs(N - 1 - i): root = TreeNode(0) root.left = left root.right = right temp_list.append(root) self.value_dict[N] = temp_list return temp_list
b67726927a44da27cddb100768d5532598314c80
038af1bfd275530413a7b4e28bf0e40eddf632c6
/parsifal/apps/accounts/tests/test_update_emails_view.py
6e3b2e07623eb93ac58bb135d2b97b941ee0e58f
[ "MIT" ]
permissive
vitorfs/parsifal
5c5345ff75b48c5596977c8e0a9c4c537ed4726c
68c3ce3623a210a9c649a27f9d21ae6130541ea9
refs/heads/dev
2023-05-24T16:34:31.899776
2022-08-14T16:30:06
2022-08-14T16:30:06
11,648,402
410
223
MIT
2023-05-22T10:47:20
2013-07-25T00:27:21
Python
UTF-8
Python
false
false
2,130
py
from django.test.testcases import TestCase from django.urls import reverse from parsifal.apps.authentication.tests.factories import UserFactory from parsifal.utils.test import login_redirect_url class TestUpdateEmailsViewView(TestCase): @classmethod def setUpTestData(cls): cls.user = UserFactory(email="[email protected]") cls.url = reverse("settings:emails") def test_login_required(self): response = self.client.get(self.url) self.assertRedirects(response, login_redirect_url(self.url)) def test_get_success(self): self.client.force_login(self.user) response = self.client.get(self.url) with self.subTest(msg="Test get status code"): self.assertEqual(200, response.status_code) parts = ("csrfmiddlewaretoken", "email", "[email protected]") for part in parts: with self.subTest(msg="Test response body", part=part): self.assertContains(response, part) def test_post_success(self): data = { "email": "[email protected]", } self.client.force_login(self.user) response = self.client.post(self.url, data, follow=True) with self.subTest(msg="Test post status code"): self.assertEqual(302, response.redirect_chain[0][1]) with self.subTest(msg="Test post redirect status code"): self.assertEqual(200, response.status_code) with self.subTest(msg="Test success message"): self.assertContains(response, "Account email was updated with success!") with self.subTest(msg="Test form saved data"): self.assertContains(response, 'value="[email protected]"') def test_post_fail(self): data = {"email": "invalidemail"} self.client.force_login(self.user) response = self.client.post(self.url, data) with self.subTest(msg="Test post status code"): self.assertEqual(200, response.status_code) with self.subTest(msg="Test error message"): self.assertContains(response, "Enter a valid email address.")
b9fd420ff9cb37198ef9d9d480d07225dc750a1b
839d8d7ccfa54d046e22e31a2c6e86a520ee0fb5
/icore/base/list/dict_test.py
b6745b165a751dc40e63e211eac910f10f6e658e
[]
no_license
Erich6917/python_corepython
7b584dda737ef914780decca5dd401aa33328af5
0176c9be2684b838cf9613db40a45af213fa20d1
refs/heads/master
2023-02-11T12:46:31.789212
2021-01-05T06:21:24
2021-01-05T06:21:24
102,881,831
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
# -*- coding: utf-8 -*- # @Time : 2017/12/26 # @Author : LIYUAN134 # @File : dict_test.py # @Commment: # import dict as dict def test1(): # dict.dict_mulkeys() dict.dict_cal() test1()
387a2c4e876cb2a1a446a27a40b003870afa741b
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/cirq_new/cirq_program/startCirq_noisy175.py
cc4f8f2ea5639c20ee3b44f313ca868e0ad2a42c
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
1,957
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=14 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=5 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=6 c.append(cirq.H.on(input_qubit[0])) # number=11 c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=12 c.append(cirq.H.on(input_qubit[0])) # number=13 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=8 c.append(cirq.X.on(input_qubit[0])) # number=9 c.append(cirq.X.on(input_qubit[0])) # number=10 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy175.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
2f53b3f8271b60d22df54f72752eded981080e61
b697f5d8e441328c2deee1bb5853d80710ae9873
/617.合并二叉树.py
5d35a8098ff5d6b1d6488a23bbd84ef8e3088d55
[]
no_license
happy-luck/LeetCode-python
d06b0f6cf7bad4754e96e6a160e3a8fc495c0f95
63fc5a1f6e903a901ba799e77a2ee9df2b05543a
refs/heads/master
2021-03-22T16:12:52.097329
2020-07-15T13:48:37
2020-07-15T13:48:37
247,381,313
0
0
null
2020-03-15T01:47:42
2020-03-15T01:28:38
null
UTF-8
Python
false
false
2,281
py
方法一:递归 我们可以对这两棵树同时进行前序遍历,并将对应的节点进行合并。在遍历时,如果两棵树的当前节点均不为空,我们就将它们的值进行相加,并对它们的左孩子和右孩子进行递归合并;如果其中有一棵树为空,那么我们返回另一颗树作为结果;如果两棵树均为空,此时返回任意一棵树均可(因为都是空)。 class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t2==None: return t1 if t1==None: return t2 t1.val += t2.val t1.left = self.mergeTrees(t1.left,t2.left) t1.right = self.mergeTrees(t1.right,t2.right) return t1 时间复杂度:O(N),其中 N 是两棵树中节点个数的较小值。 空间复杂度:O(N),在最坏情况下,会递归 N 层,需要 O(N) 的栈空间。 方法二:迭代 我们首先把两棵树的根节点入栈,栈中的每个元素都会存放两个根节点,并且栈顶的元素表示当前需要处理的节点。在迭代的每一步中,我们取出栈顶的元素并把它移出栈,并将它们的值相加。随后我们分别考虑这两个节点的左孩子和右孩子,如果两个节点都有左孩子,那么就将左孩子入栈;如果只有一个节点有左孩子,那么将其作为第一个节点的左孩子;如果都没有左孩子,那么不用做任何事情。对于右孩子同理。 class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t2==None: return t1 if t1==None: return t2 stack = [(t1,t2)] while stack: t = stack.pop(0) if t[1]==None: continue t[0].val += t[1].val if(t[0].left==None): t[0].left = t[1].left else: stack.append((t[0].left,t[1].left)) if(t[0].right==None): t[0].right = t[1].right else: stack.append((t[0].right,t[1].right)) return t1 时间复杂度:O(N),其中 N 是两棵树中节点个数的较小值。 空间复杂度:O(N),在最坏情况下,栈中会存放 N 个节点。
d90dcbcb06450d0cec154190b117b2ccce514085
bce41eff7da75522f58d831251e1ed95d8809585
/services/web/project/apps/event/subscriptions/eventUpdateSubscription.py
88e5ae15e2e558fd56fb9935803408b5065f7dcb
[]
no_license
javillarreal/eventuality
be9728a19caef8c19d3d40e6dd5b90e57b5b63a1
5a543a9e6b5a3f014b670297e22f52a9884af4bb
refs/heads/master
2021-07-03T18:55:33.037863
2021-06-24T03:24:38
2021-06-24T03:24:38
204,239,198
1
0
null
2020-11-27T02:39:19
2019-08-25T03:05:17
Python
UTF-8
Python
false
false
696
py
import random import graphene from rx import Observable class RandomType(graphene.ObjectType): seconds = graphene.Int() random_int = graphene.Int() class Subscription(graphene.ObjectType): count_seconds = graphene.Int(up_to=graphene.Int()) random_int = graphene.Field(RandomType) def resolve_count_seconds(root, info, up_to=5): return Observable.interval(1000)\ .map(lambda i: "{0}".format(i))\ .take_while(lambda i: int(i) <= up_to) def resolve_random_int(root, info): return Observable.interval(1000).map(lambda i: RandomType(seconds=i, random_int=random.randint(0, 500)))
c87f6abacd4d1526c188c591e69870c485175606
f67e9154c3e077eaad349f85439d88820098a6fc
/Search/017_LetterCombOfPhoneNum.py
73ba53f513b92e34b6a16b00c4aef98076aeab44
[]
no_license
pondjames007/CodingPractice
0c159ae528d1e595df0f0a901ee1ab4dd8925a14
fb53fea229ac5a4d5ebce23216afaf7dc7214014
refs/heads/master
2020-06-08T02:31:04.569375
2020-01-15T20:41:34
2020-01-15T20:41:34
193,142,129
0
0
null
null
null
null
UTF-8
Python
false
false
873
py
# TIPS: # make a dictionary to map digit and char # go through all digits and find out all combinations class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] n_to_c = {} char = [*string.ascii_lowercase] start = 0 end = 0 for i in range(2,10): start = end if i == 7 or i == 9: end += 4 else: end += 3 n_to_c[i] = char[start:end] ans = [] self.lookup(n_to_c, digits, [], ans) return ans def lookup(self, dic, digits, path, ans): if not digits: ans.append(''.join(path)) return for c in dic[int(digits[0])]: self.lookup(dic, digits[1:], path + [c], ans)
abe0955e886d8fbc9de7f3e7ad550af81be6cedb
5a07828016e8bafbea5dac8f83c8bfd5d0bfd603
/py_290w290/140304_srw_output.py
94f032f09c22370f14899c0b9c40b25777fbe84a
[]
no_license
JJHopkins/rajter_compare
db5b88d2c6c1efc0fead9b6ed40fb3cce36bedb4
2ba52f4f16cf2aca350a82ea58d0aa8f8866c47c
refs/heads/master
2020-06-04T23:53:57.089329
2014-04-08T18:02:30
2014-04-08T18:02:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,695
py
#$ {\bf Free energy between two skewed cylinders (CG-10 in water). Full retarded result, function of separation $\ell$ and angle $\theta$} \\ #$ Equation 12: $G(\ell,\theta) = - \frac{ (\pi R_1^{2})(\pi R_2^{2}) }{2 \pi~\ell^{4} \sin{\theta}} \left( {\cal A}^{(0)}(\ell) + {\cal A}^{(2)}(\ell) \cos 2\theta \right)$ \\ #$ $G(\ell,\theta) = - \frac{k_BT}{64 \pi} \frac{ \pi^2 R_1^{2} R_2^{2} }{\ell^{4} \sin{\theta}} {\sum_{n=0}^{\infty}}' \Delta_{1,\parallel} \Delta_{2,\parallel} ~p_n^{4} ~\int_0^{\infty} t dt ~\frac{e^{- 2 p_n \sqrt{t^{2} + 1}}}{(t^{2} + 1)} \tilde g(t, a_1(i \omega_n), a_2(i \omega_n), \theta),$ \\ #$ with $\tilde g(t, a_1, a_2, \theta) &=& 2 \left[ (1+3a_1)(1+3a_2) t^{4} + 2 (1+2a_1+2a_2+3a_1a_2) t^{2} + 2(1+a_1)(1+a_2)\right] + \nonumber \\ #$ & & ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + (1-a_1)(1-a_2)(t^{2} + 2)^2 \cos 2\theta.$ \\ #!/usr/bin/python import numpy as np import scipy.optimize as opt from scipy.integrate import trapz import matplotlib.pyplot as pl from matplotlib import axis as ax # use pyreport -l file.py from pylab import show from matplotlib.ticker import MultipleLocator from mpl_toolkits.mplot3d import Axes3D from pylab import pause from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages('plots/skew_ret_water/skew_ret_water.pdf') eiz_x = np.loadtxt('data/eiz_x_output_eV.txt') #perpendicular, radial eiz_y = np.loadtxt('data/eiz_y_output_eV.txt') eiz_z = np.loadtxt('data/eiz_z_output_eV.txt') # parallel,axial #eiz_w = 1.0 + np.zeros(len(eiz_z)) eiz_w = np.loadtxt('data/eiz_w_output_eV.txt') # water as intervening medium eiz_w[0] = eiz_w[1] #NOTE: there is a jump from first val down to second val r_1 = 1.0e-9 r_2 = 1.0e-9 c = 2.99e8 # in m/s T = 297 kb = 1.3807e-23 # in J/K coeff = 2.411e14 # in rad/s # NOTES: # at RT, 1 kT = 4.11e-21 J # 1 eV = 1.602e-19 J = 0.016 zJ # h_bar_eV = 6.5821e-16 eVs # h_bar = 1. #1.0546e-34 #in Js #kb = 8.6173e-5 # in eV/K # z_n_eV = (2*pi*kT/h_bar)n # = (0.159 eV) / (6.5821e-16 eVs) # = n*2.411e14 rad/s # z_n_J = (2*pi*kT/h_bar)n # = (1.3807e-23 J/K) / (1.0546e-34 Js))*n # = n*2.411e14 rad/s #coeff = 0.159 # in eV w/o 1/h_bar ns = np.arange(0.,500.) z = ns * coeff ls = np.linspace(1.0e-9, 1.0e-6, 200) #thetas = np.linspace((0.01)*np.pi,(1./2)*np.pi,25) thetas = [np.pi/8,np.pi/4,np.pi/3,np.pi/2] dt = 1.0 ts = np.arange(1.0,10000.,dt) def Aiz(perp, par,med): return (2.0*(perp-med)*med)/((perp+med)*(par-med)) def ys(a,time,eizw,L, N): term0 = ( time / (time*time+1.0) ) term1 = ( time**4 * 2.0*(1. + 3.*a)*(1.+3.*a) ) term2 = ( time**2 * 4.0*(1. + 2.0*a+2.0*a+3.0*a*a)) term3 = ( 4.0*(1. + a)*(1.0 + a) ) term4 = (-2.0 * np.sqrt(eizw)* L * coeff * N / c * np.sqrt(time*time + 1.0)) #print 'ys term0', term0 #print 'ys term1', term1 #print 'ys term2', term2 #print 'ys term3', term3 #print 'ys term4', term4 #print '----' return (term0) * np.exp(term4)*( (term1) + (term2) + (term3))#* term5 def y_2s(a,time,eizw, L, N): term0 = (time / (time*time+1.0) ) term1 = ((1.- a)*(1.- a)*(time * time + 2.0)*(time * time + 2.0)) term2 = (-2.0 * np.sqrt(eizw)* L * coeff * N / c * np.sqrt(time*time + 1.0)) #print 'y_2s term0', term0 #print 'y_2s term1', term1 #print 'y_2s term2', term2 #print '----' return term0 * term1* np.exp(term2) #* term3 def As(eizz,eizw,L,N,Y): term1 = (((eizz-eizw)/eizw)*((eizz-eizw)/eizw)) term2 = (Y * eizw *eizw * (coeff*N)**4 * L**4 / (c**4)) #term3 = Y #print 'As term1 = ', term1 #print 'As term2 = ', term2 ##print 'As term3 = ', term3 #print '----' return term1 * term2# * term3 def A_2s(eizz,eizw, L , N ,Y): term1 = (((eizz-eizw)/eizw)*((eizz-eizw)/eizw)) term2 = (Y * eizw *eizw * (coeff*N)**4 * L**4 / (c**4)) #term3 = Y #print 'A_2s term1 = ', term1 #print 'A_2s term2 = ', term2 ##print 'A_2s term3 = ', term3 #print '----' return (term1 * term2)# * term3 y = np.zeros(shape=(len(ns),len(ls))) y_2 = np.zeros(shape=(len(ns),len(ls))) A = np.zeros(shape=(len(ns),len(ls))) A_2 = np.zeros(shape=(len(ns),len(ls))) EL = np.zeros(len(ls)) G_l_t_dt = np.zeros(shape=(len(ls),len(thetas))) aiz = [] aiz = Aiz(eiz_x,eiz_z, eiz_w) # of length = len(ns) for k,length in enumerate(ls): sum_A = np.empty(len(ls)) sum_A_2 = np.empty(len(ls)) for j,n in enumerate(ns): # Integral: y[j,k] = trapz(ys(aiz[j],ts,eiz_w[j],length,n),ts,dt) y_2[j,k] = trapz(y_2s(aiz[j],ts,eiz_w[j],length,n),ts,dt) #print 'dt Integral y = ',i,k,j, y #print 'dt Integral y_2 = ',i,k,j, y_2 #print '----' #print 'N terms for A0 = ' , As(eiz_z[j],eiz_w[j],length,n,y) #print 'N terms for A2 = ', A_2s(eiz_z[j],eiz_w[j],length,n,y_2) #print '----' A[j,k] = As(eiz_z[j],eiz_w[j],length,n,y[j,k]) A_2[j,k] = A_2s(eiz_z[j],eiz_w[j],length,n,y_2[j,k])# * np.cos(2.0*theta) A[0] = (1./2)*A[0] A_2[0] = (1./2)*A_2[0] sum_A = np.sum(A,axis=0) #print 'sum of A0 = ', k,j,sum_A sum_A_2 = np.sum(A_2,axis=0) #print 'sum of A2 = ', k,j,sum_A_2 #print '----' #print 'shape sum_A_2 = ', np.shape(sum_A_2) #sys.exit() for k,length in enumerate(ls): for i, theta in enumerate(thetas): EL[k] = 1./(length*length*length*length) G_l_t_dt[k,i] = (1.602e-19 / 4.11e-21) * (1./32) * EL[k]*np.pi*r_1*r_1*r_2*r_2*(sum_A[k] + sum_A_2[k]* np.cos(2.0*theta) )/(2.0*np.sin(theta))# (1e21)* np.savetxt('compare/srw_min_thetas.txt',G_l_t_dt) pl.figure() pl.loglog(ls,(kb*T/32)*sum_A,'b-', label = r'$\mathcal{A^{(0)}}$') pl.loglog(ls,(kb*T/32)*sum_A_2,'b--', label = r'$\mathcal{A^{(2)}}$') pl.xlabel(r'$\mathrm{separation}\,\ell\,\,\,\rm{[m]}$', size = 20) pl.ylabel(r'$\mathrm{\mathcal{A^{(0)},\,\,A^{(2)}}}$', size = 20) #pl.title(r'$\mathrm{Hamaker \, coeff.s \,:\,skewed,\,retarded,\,water}$', size = 20) pl.legend(loc = 'upper right') pl.axis([1e-9,1e-6,1e-24,1e-19]) pl.savefig('plots/skew_ret_water/skew_ret_water_A0_A2.pdf') show() ls4 = 1e9*ls[ 2]#2] ls5 = 1e9*ls[12]#4] ls6 = 1e9*ls[22]#6] ls1 = 1e9*ls[32]#8] ls2 = 1e9*ls[42]#12] ls3 = 1e9*ls[52]#16] fig = pl.figure() ax = fig.add_axes([0.1,0.1,0.8,0.8]) #pl.semilogy(thetas, G_l_t_dt) ax.semilogy(thetas, G_l_t_dt[ 2,:], label = r'$\ell$ = %1.2f nm' %ls4) ax.semilogy(thetas, G_l_t_dt[12,:], label = r'$\ell$ = %1.2f nm' %ls5) ax.semilogy(thetas, G_l_t_dt[22,:], label = r'$\ell$ = %1.2f nm' %ls6) ax.semilogy(thetas, G_l_t_dt[32,:], label = r'$\ell$ = %1.2f nm' %ls1) ax.semilogy(thetas, G_l_t_dt[42,:], label = r'$\ell$ = %1.2f nm' %ls2) ax.semilogy(thetas, G_l_t_dt[52,:], label = r'$\ell$ = %1.2f nm' %ls3) #ax.semilogy(0,0,'', label = r'$G_\theta = cos(2\theta)/2sin(\theta)$') pl.xlabel(r'$Angle\,\,\mathrm{[radians]}$', size = 20) pl.ylabel(r'$-G(\ell,\theta)\,\,\mathrm{[k_{B}T]}$', size = 20) pl.axis([0,1.7,1e-10,1.0]) #pl.axis([0,1.7,1e-3,1e4]) #pl.title(r'$\mathrm{-G(\ell,\theta)\,vs.\,angle:\,skewed,\,retarded,\,water}$', size = 20) pl.legend(loc = 'lower left') #pl.savefig('plots/skew_ret_water/skew_ret_water_G_vs_theta.pdf') #show() pl.savefig('plots/skew_ret_water/G_vs_theta_fixed_l.pdf') show() pl.figure() pl.loglog(ls, G_l_t_dt)#, label = labels[i]) #pl.loglog(ls, G_l_t_dt[:,3], label = r'$\theta = \pi/4$') #pl.loglog(ls, G_l_t_dt[:,4], label = r'$\theta = \pi/3$') #pl.loglog(ls, G_l_t_dt[:,6], label = r'$\theta = \pi/2$') pl.xlabel(r'$Separation,\,\ell\,\,\mathrm{[m]}$', size = 20) pl.ylabel(r'$-G(\ell,\theta)\,\,\mathrm{[k_{B}T]}$', size = 20) pl.axis([1.0e-9, 1.0e-6,1e-16,1e3]) #pl.axis([1.0e-9, 1.0e-6,1e-3,1e3]) #pl.title(r'$\mathrm{-G(\ell,\theta)\,vs.\,separation:\,skewed,\,retarded,\,water}$', size = 20) pl.legend(loc = 'best') pl.savefig('plots/compare/skew_ret_water_G_vs_l.pdf') show()
37694eb9518f87e68f56b733a3fbd604c4eddd79
11ad104b0309a2bffd7537d05e2ab3eaf4aed0ca
/homeassistant/components/rachio/device.py
9d7c30579394412becf75ff8253ffd54c62cc51b
[ "Apache-2.0" ]
permissive
koying/home-assistant
15e5d01a45fd4373b3d286e1b2ca5aba1311786d
9fc92ab04e0d1933cc23e89b4095714aee725f8b
refs/heads/dev
2023-06-24T01:15:12.150720
2020-11-01T12:27:33
2020-11-01T12:27:33
189,232,923
2
1
Apache-2.0
2023-01-13T06:04:15
2019-05-29T13:39:02
Python
UTF-8
Python
false
false
6,956
py
"""Adapter to wrap the rachiopy api for home assistant.""" import logging from typing import Optional from homeassistant.const import EVENT_HOMEASSISTANT_STOP, HTTP_OK from .const import ( KEY_DEVICES, KEY_ENABLED, KEY_EXTERNAL_ID, KEY_FLEX_SCHEDULES, KEY_ID, KEY_MAC_ADDRESS, KEY_MODEL, KEY_NAME, KEY_SCHEDULES, KEY_SERIAL_NUMBER, KEY_STATUS, KEY_USERNAME, KEY_ZONES, ) from .webhooks import LISTEN_EVENT_TYPES, WEBHOOK_CONST_ID _LOGGER = logging.getLogger(__name__) class RachioPerson: """Represent a Rachio user.""" def __init__(self, rachio, config_entry): """Create an object from the provided API instance.""" # Use API token to get user ID self.rachio = rachio self.config_entry = config_entry self.username = None self._id = None self._controllers = [] def setup(self, hass): """Rachio device setup.""" response = self.rachio.person.info() assert int(response[0][KEY_STATUS]) == HTTP_OK, "API key error" self._id = response[1][KEY_ID] # Use user ID to get user data data = self.rachio.person.get(self._id) assert int(data[0][KEY_STATUS]) == HTTP_OK, "User ID error" self.username = data[1][KEY_USERNAME] devices = data[1][KEY_DEVICES] for controller in devices: webhooks = self.rachio.notification.get_device_webhook(controller[KEY_ID])[ 1 ] # The API does not provide a way to tell if a controller is shared # or if they are the owner. To work around this problem we fetch the webooks # before we setup the device so we can skip it instead of failing. # webhooks are normally a list, however if there is an error # rachio hands us back a dict if isinstance(webhooks, dict): _LOGGER.error( "Failed to add rachio controller '%s' because of an error: %s", controller[KEY_NAME], webhooks.get("error", "Unknown Error"), ) continue rachio_iro = RachioIro(hass, self.rachio, controller, webhooks) rachio_iro.setup() self._controllers.append(rachio_iro) _LOGGER.info('Using Rachio API as user "%s"', self.username) @property def user_id(self) -> str: """Get the user ID as defined by the Rachio API.""" return self._id @property def controllers(self) -> list: """Get a list of controllers managed by this account.""" return self._controllers def start_multiple_zones(self, zones) -> None: """Start multiple zones.""" self.rachio.zone.start_multiple(zones) class RachioIro: """Represent a Rachio Iro.""" def __init__(self, hass, rachio, data, webhooks): """Initialize a Rachio device.""" self.hass = hass self.rachio = rachio self._id = data[KEY_ID] self.name = data[KEY_NAME] self.serial_number = data[KEY_SERIAL_NUMBER] self.mac_address = data[KEY_MAC_ADDRESS] self.model = data[KEY_MODEL] self._zones = data[KEY_ZONES] self._schedules = data[KEY_SCHEDULES] self._flex_schedules = data[KEY_FLEX_SCHEDULES] self._init_data = data self._webhooks = webhooks _LOGGER.debug('%s has ID "%s"', str(self), self.controller_id) def setup(self): """Rachio Iro setup for webhooks.""" # Listen for all updates self._init_webhooks() def _init_webhooks(self) -> None: """Start getting updates from the Rachio API.""" current_webhook_id = None # First delete any old webhooks that may have stuck around def _deinit_webhooks(_) -> None: """Stop getting updates from the Rachio API.""" if not self._webhooks: # We fetched webhooks when we created the device, however if we call _init_webhooks # again we need to fetch again self._webhooks = self.rachio.notification.get_device_webhook( self.controller_id )[1] for webhook in self._webhooks: if ( webhook[KEY_EXTERNAL_ID].startswith(WEBHOOK_CONST_ID) or webhook[KEY_ID] == current_webhook_id ): self.rachio.notification.delete(webhook[KEY_ID]) self._webhooks = None _deinit_webhooks(None) # Choose which events to listen for and get their IDs event_types = [] for event_type in self.rachio.notification.get_webhook_event_type()[1]: if event_type[KEY_NAME] in LISTEN_EVENT_TYPES: event_types.append({"id": event_type[KEY_ID]}) # Register to listen to these events from the device url = self.rachio.webhook_url auth = WEBHOOK_CONST_ID + self.rachio.webhook_auth new_webhook = self.rachio.notification.add( self.controller_id, auth, url, event_types ) # Save ID for deletion at shutdown current_webhook_id = new_webhook[1][KEY_ID] self.hass.bus.listen(EVENT_HOMEASSISTANT_STOP, _deinit_webhooks) def __str__(self) -> str: """Display the controller as a string.""" return f'Rachio controller "{self.name}"' @property def controller_id(self) -> str: """Return the Rachio API controller ID.""" return self._id @property def current_schedule(self) -> str: """Return the schedule that the device is running right now.""" return self.rachio.device.current_schedule(self.controller_id)[1] @property def init_data(self) -> dict: """Return the information used to set up the controller.""" return self._init_data def list_zones(self, include_disabled=False) -> list: """Return a list of the zone dicts connected to the device.""" # All zones if include_disabled: return self._zones # Only enabled zones return [z for z in self._zones if z[KEY_ENABLED]] def get_zone(self, zone_id) -> Optional[dict]: """Return the zone with the given ID.""" for zone in self.list_zones(include_disabled=True): if zone[KEY_ID] == zone_id: return zone return None def list_schedules(self) -> list: """Return a list of fixed schedules.""" return self._schedules def list_flex_schedules(self) -> list: """Return a list of flex schedules.""" return self._flex_schedules def stop_watering(self) -> None: """Stop watering all zones connected to this controller.""" self.rachio.device.stop_water(self.controller_id) _LOGGER.info("Stopped watering of all zones on %s", str(self))
5d2200a128aabb70c081dea75e660bd7b9a29f3e
b93c90054ede72fb706567e2b60a5e4bba5485d3
/cru/__init__.py
3f204900689b0e4ad473586a2413b190d0343060
[]
no_license
guziy/ShortPythonScripts
2568b92124003fa4b0c673c3ce872df623dff76c
17b1ed47231aa566c8af04e19cced49a795b37d8
refs/heads/master
2016-09-06T01:30:30.365172
2014-07-18T15:52:25
2014-07-18T15:52:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
149
py
__author__ = 'huziy' import numpy as np def main(): #TODO: implement pass if __name__ == "__main__": main() print "Hello world"
b1067dbd1da869a3839d1527813c511360fafa32
17a7e1941d1f0e9e2747ce177344cf081aeb1aa0
/examples/sbm_arxiv_paper.py
21987364c3ea82ea603bf54540f87aceb88df3be
[]
no_license
abdcelikkanat/rangraphgen
413871bd757992c8c87f520c7fecbd18bc004eed
491a94ddd0d8682ae3e6a30921e9de73327acea8
refs/heads/master
2020-03-21T08:09:34.540550
2018-07-23T16:13:55
2018-07-23T16:13:55
138,324,601
0
0
null
null
null
null
UTF-8
Python
false
false
1,086
py
from sbm.sbm import SBM """ model = {} model['sbm_N'] = 100 # the number of nodes model['sbm_P'] = [[0.6, 0.2], [0.2, 0.8]] # edge probability matrix between nodes belonging different communities model['sbm_block_sizes'] = [40, 60] output_file = "../outputs/synthetic_" output_file += "n{}_p{}_sizes{}.gml".format(model['sbm_N'], 1, ":".join(str(v) for v in model['sbm_block_sizes'])) sbm = SBM(model=model) sbm.build_graph() g = sbm.get_graph() sbm.save_graph(output_file) #sbm.plot_graph() """ model = {} N = 10000 c = 3.5 model['sbm_block_sizes'] = [N/2, N/2] K = 2 mylambda = 0.9 model['sbm_N'] = N model['sbm_P'] = [[0.0 for _ in range(K)] for _ in range(K)] for i in range(K): for j in range(K): if i == j: model['sbm_P'][i][j] = float(c) / float(N) else: model['sbm_P'][i][j] = float(c)*(1.0 - mylambda) / float(N) output_file = "../outputs/sbm_" output_file += "n{}_k{}_lambda{}_c{}.gml".format(N, K, mylambda, c) sbm = SBM(model=model) sbm.build_graph() g = sbm.get_graph() sbm.save_graph(output_file) #sbm.plot_graph()
39cc3029c96a86e815190984cebf90bce285fb25
7450483dd16f7dea4bef09a5166a67c7527b7ca2
/hw_8_stub.py
faed32fa97ff75a4f1b0a0c90f450a885d815fca
[]
no_license
rmvook/HW8_CMSC389R
604ec50cc225926e53692fc0ebcf366dc4914a98
03fad8af81e2e985d121d9fbdb2d0ed939534a81
refs/heads/master
2020-03-09T15:45:17.796936
2018-04-16T15:11:50
2018-04-16T15:11:50
128,867,479
0
0
null
null
null
null
UTF-8
Python
false
false
2,824
py
# do `curl http://starship.python.net/~gherman/programs/md5py/md5py.py > md5.py` # if you do not have it from the git repo import md5py, socket, hashlib, string, sys, os, time f = open("output.txt", "w") host = "159.89.236.106" # IP address or URL port = 5678 # port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) data = s.recv(1024) print(data) ##################################### ### STEP 1: Calculate forged hash ### ##################################### one = "1\n" s.send(one) data = s.recv(1024) print(data) message = 'blahah' # original message here s.send(message + "\n") data = s.recv(1024) print(data) temp = data[40:] legit = temp.strip() print(legit) f.write("Hash from which I based my crafted hash: " + legit + "\n") # a legit hash of secret + message goes here, obtained from signing a message # initialize hash object with state of a vulnerable hash fake_hash = md5py.new('A' * 64) fake_hash.A, fake_hash.B, fake_hash.C, fake_hash.D = md5py._bytelist2long(legit.decode('hex')) malicious = 'bluhuh' # put your malicious message here # update legit hash with malicious message fake_hash.update(malicious) # test is the correct hash for md5(secret + message + padding + malicious) test = fake_hash.hexdigest() print("Testing fake" + test) f.write("Fake hash" + test + "\n") ############################# ### STEP 2: Craft payload ### ############################# # TODO: calculate proper padding based on secret + message # secret is 6 bytes long (48 bits) # each block in MD5 is 512 bits long # secret + message is followed by bit 1 then bit 0's (i.e. \x80\x00\x00...) # after the 0's is a bye with message length in bits, little endian style # (i.e. 20 char msg = 160 bits = 0xa0 = '\xa0\x00\x00\x00\x00\x00\x00\x00\x00') # craft padding to align the block as MD5 would do it # (i.e. len(secret + message + padding) = 64 bytes = 512 bits nulls = "\x00" * 43 end = "\x00" * 7 padding = "\x80" + nulls + "\x60" + end # payload is the message that corresponds to the hash in `test` # server will calculate md5(secret + payload) # = md5(secret + message + padding + malicious) # = test payload = message + padding + malicious print("PAYLOAD: " + payload) # send `test` and `payload` to server (manually or with sockets) # REMEMBER: every time you sign new data, you will regenerate a new secret! f.write("PAYLOAD: " + payload + "\n") two = "2\n" s.send(two) #telling the server that I want to verify a hash. data = s.recv(1024) print(data) s.send(test + "\n") data = s.recv(1024) print(data) s.send(payload + "\n") data = s.recv(1024) # was not receiving everything, so did it twice. print(data) data = s.recv(1024) print(data) s.close()# close the connection f.close()#close the file
bd3d8511ec40499ea66fcc1e2c71b26b17f8565d
cd79b7919fd0984c12e8acde8abda4290fd65b0f
/draftcast/settings.py
dbaf6a6cc14ebfb87a7c0db296138f30760cc41a
[]
no_license
rallen0150/nfl_draftcast
7d5d84352986349f0646a9199d3aa3b29bfac4a2
3f5f9980902ee73fbca3c5b3db4545179ff5208a
refs/heads/master
2021-01-20T04:43:00.356120
2017-04-29T14:45:16
2017-04-29T14:45:16
89,718,535
0
0
null
null
null
null
UTF-8
Python
false
false
3,349
py
""" Django settings for draftcast project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xkaaf7fhx_nv$1(!enr!opy*x47n85mi^3!hapv_#dapytq$ls' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['quiet-garden-99226.herokuapp.com', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ] 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 = 'draftcast.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'draftcast.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } database_config = dj_database_url.config() if database_config: DATABASES['default'] = database_config # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')
fed1af0912a71ebae30785c3e9dcaec26f4337f6
d29c1c1901b8f5aac07ea67c969f4e96e3642376
/venv/Scripts/pip-script.py
670e74ae05294d33a619274f5839d91a361a2800
[]
no_license
aljaserm/pdf
10f0f97572fb2021604e70aeb3ed2f8920668a12
4648703819260380ebc942bba31817e47821f23f
refs/heads/master
2020-08-29T20:41:32.846815
2019-12-12T00:03:21
2019-12-12T00:03:21
218,169,283
0
0
null
null
null
null
UTF-8
Python
false
false
429
py
#!C:\Users\aljas\OneDrive\Documents\Development\Python\pdf\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip' __requires__ = 'pip==10.0.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==10.0.1', 'console_scripts', 'pip')() )
aa6145e09b71b6311ef725f088a53c2d8f67c1e5
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_hacking.py
5138e808004dfe243f61edf4bc4bd5dbb450c3c0
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
218
py
#calss header class _HACKING(): def __init__(self,): self.name = "HACKING" self.definitions = hack self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['hack']
f378db34785d00813c8dcfbbeaac5e36f4951d2b
ec0b8bfe19b03e9c3bb13d9cfa9bd328fb9ca3f1
/res/packages/scripts/scripts/client/gui/prb_control/entities/battle_session/__init__.py
a41701b1d0acaedce8b7e47eb63a44121abed16e
[]
no_license
webiumsk/WOT-0.9.20.0
de3d7441c5d442f085c47a89fa58a83f1cd783f2
811cb4e1bca271372a1d837a268b6e0e915368bc
refs/heads/master
2021-01-20T22:11:45.505844
2017-08-29T20:11:38
2017-08-29T20:11:38
101,803,045
0
1
null
null
null
null
WINDOWS-1250
Python
false
false
401
py
# 2017.08.29 21:45:30 Střední Evropa (letní čas) # Embedded file name: scripts/client/gui/prb_control/entities/battle_session/__init__.py pass # okay decompyling c:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\client\gui\prb_control\entities\battle_session\__init__.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2017.08.29 21:45:30 Střední Evropa (letní čas)
5c7e781861cf2f6c726c08b123b74dd794c2056e
5fa91971a552de35422698ad3e371392fd5eb48a
/docs/webflask/todo/todo_z4.py
7b5d27384609f0e5dd9f8849bc294038bdc06384
[ "MIT", "CC-BY-SA-4.0" ]
permissive
koduj-z-klasa/python101
64b0bf24da6c7fc29c0d3c5a74ce7975d648b760
accfca2a8a0f2b9eba884bffe31be6d1e73fb615
refs/heads/master
2022-06-06T09:29:01.688553
2022-05-22T19:50:09
2022-05-22T19:50:09
23,770,911
45
182
MIT
2022-03-31T10:40:13
2014-09-07T21:01:09
Python
UTF-8
Python
false
false
1,835
py
# -*- coding: utf-8 -*- # todo/todo.py from flask import Flask, g from flask import render_template import os import sqlite3 from datetime import datetime from flask import flash, redirect, url_for, request app = Flask(__name__) app.config.update(dict( SECRET_KEY='bardzosekretnawartosc', DATABASE=os.path.join(app.root_path, 'db.sqlite'), SITE_NAME='Moje zadania' )) def get_db(): """Funkcja tworząca połączenie z bazą danych""" if not g.get('db'): # jeżeli brak połączenia, to je tworzymy con = sqlite3.connect(app.config['DATABASE']) con.row_factory = sqlite3.Row g.db = con # zapisujemy połączenie w kontekście aplikacji return g.db # zwracamy połączenie z bazą @app.teardown_appcontext def close_db(error): """Zamykanie połączenia z bazą""" if g.get('db'): g.db.close() @app.route('/') def index(): # return 'Cześć, tu Python!' return render_template('index.html') @app.route('/zadania', methods=['GET', 'POST']) def zadania(): error = None if request.method == 'POST': zadanie = request.form['zadanie'].strip() if len(zadanie) > 0: zrobione = '0' data_pub = datetime.now() db = get_db() db.execute('INSERT INTO zadania VALUES (?, ?, ?, ?);', [None, zadanie, zrobione, data_pub]) db.commit() flash('Dodano nowe zadanie.') return redirect(url_for('zadania')) error = 'Nie możesz dodać pustego zadania!' # komunikat o błędzie db = get_db() kursor = db.execute('SELECT * FROM zadania ORDER BY data_pub DESC;') zadania = kursor.fetchall() return render_template('zadania_lista.html', zadania=zadania, error=error) if __name__ == '__main__': app.run(debug=True)
74305ab38ac0340b375cb8afb1b90ea07fd23e36
bf24b73282ae80b7ff813f2d794bdace9421b017
/carapace/carapace/doctype/rejection_gate_entry_items/rejection_gate_entry_items.py
b3a21751d4d81fda563dfdc4c1c7c58850e5338e
[ "MIT" ]
permissive
hrgadeha/carapace
8d78cc8d45c1de0293204dfbd47802e1eebf87ee
3c001422c6b05644a52f6250c55526b23cbd4320
refs/heads/master
2022-01-20T11:37:26.765923
2022-01-09T09:38:57
2022-01-09T09:38:57
163,376,460
0
1
null
null
null
null
UTF-8
Python
false
false
266
py
# -*- coding: utf-8 -*- # Copyright (c) 2019, frappe and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class RejectionGateEntryitems(Document): pass
8cbc7c2bbd2aaea3b6bd0378c72ca37769c8035d
955b968d46b4c436be55daf8aa1b8fc8fe402610
/ch04/baidu_screenshot.py
c3aca7449f0e884890aadc2bfc8ba7f2977f6243
[]
no_license
han-huang/python_selenium
1c8159fd1421b1f0e87cb0df20ae4fe82450f879
56f9f5e5687cf533c678a1c12e1ecaa4c50a7795
refs/heads/master
2020-03-09T02:24:48.882279
2018-04-07T15:06:18
2018-04-07T15:06:18
128,535,917
0
0
null
null
null
null
UTF-8
Python
false
false
1,010
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from time import sleep, ctime from selenium import webdriver import os driver = webdriver.Firefox() # driver = webdriver.Chrome() driver.get("http://www.baidu.com") # http://selenium-python.readthedocs.io/api.html?highlight=get_screenshot_as_file#selenium.webdriver.remote.webdriver.WebDriver.get_screenshot_as_file # get_screenshot_as_file(filename) # Saves a screenshot of the current window to a PNG image file. Returns # False if there is any IOError, else returns True. Use full paths in your filename. # Args: # filename: The full path you wish to save your screenshot to. This should end with a .png extension. # Usage: # driver.get_screenshot_as_file(‘/Screenshots/foo.png’) save = os.getcwd() + '\\' + os.path.splitext(__file__)[0] + ".png" try: driver.find_element_by_id('kw_error').send_key('selenium') driver.find_element_by_id('su').click() except: driver.get_screenshot_as_file(save) # driver.quit()
[ "vagrant@LaravelDemoSite" ]
vagrant@LaravelDemoSite
ca84176dcc4543867190893bc2a6e3aca04b239d
107941a50c3adc621563fe0254fd407ea38d752e
/spider_01.py
32d42c2a2ca6ef3b58162d8cb4c81ff8efba1721
[]
no_license
zhangliang852469/spider_
758a4820f8bd25ef6ad0edbd5a4efbaaa410ae08
718208c4d8e6752bbe8d66a209e6d7446c81d139
refs/heads/master
2020-04-05T07:12:03.790358
2018-11-08T07:17:22
2018-11-08T07:17:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,409
py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ 查找节点 例:淘宝""" """ find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector """ from selenium import webdriver # 首先初始化启动浏览器 browser = webdriver.Chrome() # 打开网页 browser.get('https://www.taobao.com') # 查找节点可以通过ID, css selector, xpath, name来查找 input_first = browser.find_element_by_id('q') input_second = browser.find_element_by_css_selector('#q') input_third = browser.find_element_by_xpath('//*[@id="q"]') input_fouth = browser.find_element_by_name('q') # 输出查找 print(input_first, '\n', input_second,'\n', input_third,'\n', input_fouth) browser.close() # Selenium 还提供了通用的 find_element() 方法,它需要传入两个参数,一个是查找的方式 # By,另一个就是值,实际上它就是 find_element_by_id() 这种方法的通用函数版本 # 比如 find_element_by_id(id) 就等价于 find_element(By.ID, id),二者得到的结果完全一致。 # from selenium import webdriver # from selenium.webdriver.common.by import By # # browser = webdriver.Chrome() # browser.get('https://www.taobao.com') # input_first = browser.find_element(By.ID, 'q') # print(input_first) # browser.close()
2eff427266939ed01872e9d20210444fb49759ed
7966fa31437cc8a539621a5a0642ce24c1c9de50
/PycharmProjects/segmentTree/sgrTree.py
29d3a3b49750c8b91cbbe7e14c980ac9783aa1fe
[]
no_license
crystal30/DataStructure
4f938508f4c60af9c5f8ec5520d5acedbe2dc90e
c55b0cfd2967a2221c27ed738e8de15034775945
refs/heads/master
2021-06-25T17:49:03.048853
2021-01-22T00:37:04
2021-01-22T00:37:04
192,374,326
0
0
null
null
null
null
UTF-8
Python
false
false
2,804
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class SegTree(): def __init__(self, data): self.__data = data self.__tree = [None]*len(data)*4 def getSize(self): return len(self.__data) def getIndex(self, index): return self.getIndex(index) # 左孩子节点 def __leftChild(self, index): return index*2 + 1 # 右孩子节点 def __rightChild(self, index): return index*2 + 2 #融合函数,这里 返回 两个list 相加 def merger(self, a,b): return a+b def tree(self): self.__subTree(0,l=0, r = len(self.__data)-1) def __subTree(self,index,l, r): if l==r: # self.__tree[index] = [self.__data[l]] self.__tree[index] = self.__data[l] return else: # l<r mid = (r+l) // 2 lChild = self.__leftChild(index) rChild = self.__rightChild(index) self.__subTree(lChild, l,mid) self.__subTree(rChild, mid+1,r) self.__tree[index] = self.merger(self.__tree[lChild], self.__tree[rChild]) #查询 def query(self,ql, qr): return self.__query(0, 0, len(self.__data)-1, ql, qr) def __query(self,treeIndex, l, r, ql, qr): if l==ql and r == qr: return self.__tree[treeIndex] leftChild = self.__leftChild(treeIndex) rightChild = self.__rightChild(treeIndex) mid = (l+r) // 2 if qr <= mid: return self.__query(leftChild, l, mid, ql, qr) elif ql >= mid+1: return self.__query(rightChild, mid+1, r, ql, qr) if ql <= mid and qr > mid: leftRe = self.__query(leftChild,l,mid,ql, mid) rightRe = self.__query(rightChild, mid+1, r, mid+1, qr) return self.merger(leftRe , rightRe) #更新 def set(self,index,e): self.__data[index] = e self.__set(0, 0, len(self.__data)-1, index,e) def __set(self,treeIndex, l, r, index ,e): if l == r: # self.__tree[treeIndex] = [e] self.__tree[treeIndex] = e # self.__tree[treeIndex] = [self.__data[l]] return mid = l + (r-l)//2 leftChild = self.__leftChild(treeIndex) rightChild = self.__rightChild(treeIndex) if index <= mid: self.__set(leftChild,l,mid,index,e) elif index >= mid+1: self.__set(rightChild, mid+1, r, index, e) self.__tree[treeIndex] = self.merger(self.__tree[leftChild], self.__tree[rightChild]) def __str__(self): return str(self.__tree) if __name__ == "__main__": nums = [-2, 0, 3, -5, 2, -1] seg = SegTree(nums) seg.tree() print(seg) print(seg.query(2,3)) seg.set(2,5) print(seg)
f16a59cbded9413a22d9a9d7d5816f14d3b4749e
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part005112.py
f6ccb551e9b49171345708249fe74b4524d23c9a
[]
no_license
Upabjojr/rubi_generated
76e43cbafe70b4e1516fb761cabd9e5257691374
cd35e9e51722b04fb159ada3d5811d62a423e429
refs/heads/master
2020-07-25T17:26:19.227918
2019-09-15T15:41:48
2019-09-15T15:41:48
208,357,412
4
1
null
null
null
null
UTF-8
Python
false
false
2,369
py
from sympy.abc import * from matchpy.matching.many_to_one import CommutativeMatcher from matchpy import * from matchpy.utils import VariableWithCount from collections import deque from multiset import Multiset from sympy.integrals.rubi.constraints import * from sympy.integrals.rubi.utility_function import * from sympy.integrals.rubi.rules.miscellaneous_integration import * from sympy import * class CommutativeMatcher13068(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({0: 1}), [ (VariableWithCount('i2.2.1.1.1.0', 1, 1, S(1)), Mul) ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Mul max_optional_count = 1 anonymous_patterns = set() def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher13068._instance is None: CommutativeMatcher13068._instance = CommutativeMatcher13068() return CommutativeMatcher13068._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 13067 if len(subjects) >= 1 and isinstance(subjects[0], Pow): tmp1 = subjects.popleft() subjects2 = deque(tmp1._args) # State 13069 if len(subjects2) >= 1: tmp3 = subjects2.popleft() subst1 = Substitution(subst0) try: subst1.try_add_variable('i2.2.1.1.1.1', tmp3) except ValueError: pass else: pass # State 13070 if len(subjects2) >= 1 and subjects2[0] == Rational(1, 2): tmp5 = subjects2.popleft() # State 13071 if len(subjects2) == 0: pass # State 13072 if len(subjects) == 0: pass # 0: sqrt(v) yield 0, subst1 subjects2.appendleft(tmp5) subjects2.appendleft(tmp3) subjects.appendleft(tmp1) return yield from collections import deque
07684dae8331e4090c1d7c0b30f6d7355bdf19e3
0a3627e849caf21a0385079dea5bf81d4a281b72
/ret2win32/pwngetshell.py
b3855cdd460b10fec5f32763e9e33a89877fc403
[]
no_license
surajsinghbisht054/ROP-Emporium-walkthrough-collection
7e0b3e4aadb4bf4a901c3788fe9fe8a56d047f0d
4e9ac3f732c6af5ae5fd65e6ca7e3964fc8a3790
refs/heads/master
2020-04-14T13:45:04.356322
2019-01-02T19:01:39
2019-01-02T19:01:39
163,877,814
0
0
null
null
null
null
UTF-8
Python
false
false
2,283
py
#!/usr/bin/python from struct import pack import pwn # ================================================== # Usages: (python exp.py; cat) | ./binaryName # ================================================= #+ ------------------------------------------------------------------ + #= +----------------------------------------------------------------+ = #= | | = #= | _____ ___________ _____ | = #= | / ___/ ___| ___ \ | __ \ | = #= | \ `--.\ `--.| |_/ / | | \/_ __ ___ _ _ _ __ | = #= | `--. \`--. \ ___ \ | | __| '__/ _ \| | | | '_ \ | = #= | /\__/ /\__/ / |_/ / | |_\ \ | | (_) | |_| | |_) | | = #= | \____/\____/\____/ \____/_| \___/ \__,_| .__/ | = #= | | | | = #= | |_| | = #= +----------------------------------------------------------------+ = #= +----------------------------------------------------------------+ = #= | | = #= | [email protected] | = #= | www.bitforestinfo.com | = #= | | = #= | Try Smart, Try Hard & Don't Cheat | = #= +----------------------------------------------------------------+ = #+ ------------------------------------------------------------------ + #pwn.context.log_level='debug' #b = pwn.process('./ret2win32') #b.recvuntil('>') # 004 0x00000430 0x08048430 GLOBAL FUNC 16 imp.system # ?v reloc.fgets # 0x804a010 # # # # ?v reloc.puts # 0x804a014 # # ?v sym.pwnme # 0x80485f6 # # ?v sym.imp.puts # 0x8048420 t_function = 0x08048400 # printf args = 0x8048710 load = '' load += pack('I',t_function) load += 'AAAA' #pack('I', ) load += pack('I', args ) # Buffer pay = '' pay += 'A'*40 pay += 'BBBB' # EBP pay += load # EIP print pay #b = pwn.process('./ret2win32') #b.recvuntil('>') #b.sendline(pay) #print pwn.hexdump(b.readall()) #pwn.gdb.attach(b) #b.interactive()
c6a7fbd32d85a9e5f274cc76bf525b7c4eb7bf77
33febf8b617ef66d7086765f1c0bf6523667a959
/probpy/distributions/uniform.py
3b06514b722dc180d8f041489b3cc970add316b3
[]
no_license
JonasRSV/probpy
857201c7f122461463b75d63e5c688e011615292
5203063db612b2b2bc0434a7f2a02c9d2e27ed6a
refs/heads/master
2022-07-07T06:17:44.504570
2020-04-15T14:52:20
2020-04-15T14:52:20
245,820,195
1
0
null
null
null
null
UTF-8
Python
false
false
5,578
py
import numpy as np import numba from typing import Tuple from probpy.core import Distribution, RandomVariable, Parameter class Uniform(Distribution): """Uniform Distribution""" a = "a" b = "b" @classmethod def med(cls, a: np.float = None, b: np.float = None) -> RandomVariable: """ :param a: lower bound :param b: upper bound :return: RandomVariable """ if a is None and b is None: _sample = Uniform.sample _p = Uniform.p elif a is None: def _sample(a: np.ndarray, size: int = 1): return Uniform.sample(a, b, size) def _p(x: np.ndarray, a: np.ndarray): return Uniform.p(x, a, b) elif b is None: def _sample(b: np.ndarray, size: int = 1): return Uniform.sample(a, b, size) def _p(x: np.ndarray, b: np.ndarray): return Uniform.p(x, a, b) else: def _sample(size: int = 1): return Uniform.sample(a, b, size) def _p(x: np.ndarray): return Uniform.p(x, a, b) parameters = { Uniform.a: Parameter((), a), Uniform.b: Parameter((), b) } return RandomVariable(_sample, _p, shape=(), parameters=parameters, cls=cls) @staticmethod @numba.jit(nopython=False, forceobj=True) def sample(a: np.float, b: np.float, size: int = 1) -> np.ndarray: return np.array(a + np.random.rand(size) * (b - a)) @staticmethod @numba.jit(nopython=True, forceobj=False) def fast_p(x: np.ndarray, a: np.float, b: np.float): return ((a < x) & (x < b)) / (b - a) @staticmethod def p(x: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray: if type(x) != np.ndarray: x = np.array(x) if type(a) != np.ndarray: a = np.array(a) if type(b) != np.ndarray: b = np.array(b) return Uniform.fast_p(x, a, b) @staticmethod def jit_probability(rv: RandomVariable): a = rv.parameters[Uniform.a].value b = rv.parameters[Uniform.b].value _fast_p = Uniform.fast_p if a is None and b is None: return _fast_p elif a is None: def fast_p(x: np.ndarray, a: np.float): return _fast_p(x, a, b) elif b is None: def fast_p(x: np.ndarray, b: np.float): return _fast_p(x, a, b) else: def fast_p(x: np.ndarray): return _fast_p(x, a, b) fast_p = numba.jit(nopython=True, forceobj=False, fastmath=True)(fast_p) return fast_p class MultiVariateUniform(Distribution): """Multivariate Uniform distribution""" a = "a" b = "b" @classmethod def med(cls, a: np.ndarray = None, b: np.ndarray = None, dimension: Tuple = None) -> RandomVariable: """ :param a: lower bound :param b: upper bound :param dimension: dimension of r.v :return: RandomVariable """ if a is None and b is None: _sample = MultiVariateUniform.sample _p = MultiVariateUniform.p shape = dimension elif a is None: def _sample(a: np.ndarray, size: int = 1): return MultiVariateUniform.sample(a, b, size) def _p(x: np.ndarray, a: np.ndarray): return MultiVariateUniform.p(x, a, b) shape = b.size elif b is None: def _sample(b: np.ndarray, size: int = 1): return MultiVariateUniform.sample(a, b, size) def _p(x: np.ndarray, b: np.ndarray): return MultiVariateUniform.p(x, a, b) shape = a.size else: def _sample(size: int = 1): return MultiVariateUniform.sample(a, b, size) def _p(x: np.ndarray): return MultiVariateUniform.p(x, a, b) shape = a.size parameters = { MultiVariateUniform.a: Parameter(shape, a), MultiVariateUniform.b: Parameter(shape, b) } return RandomVariable(_sample, _p, shape=shape, parameters=parameters, cls=cls) @staticmethod def sample(a: np.ndarray, b: np.ndarray, size: int = 1) -> np.ndarray: return a + np.random.rand(size, a.size) * (b - a) @staticmethod @numba.jit(nopython=True, fastmath=True, forceobj=False) def fast_p(x: np.ndarray, a: np.ndarray, b: np.ndarray): indicator_matrix = ((a < x) & (x < b)) indicator_vector = np.array([np.all(indicator_matrix[i]) for i in range(len(x))]) probability = 1 / np.prod(b - a) return indicator_vector * probability @staticmethod def p(x: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray: if type(x) != np.ndarray: x = np.array(x) if type(a) != np.ndarray: a = np.array(a) if type(b) != np.ndarray: b = np.array(b) if x.ndim == 1: x = x.reshape(-1, a.size) return MultiVariateUniform.fast_p(x, a, b) @staticmethod def jit_probability(rv: RandomVariable): a = rv.parameters[Uniform.a].value b = rv.parameters[Uniform.b].value _fast_p = MultiVariateUniform.fast_p if a is None and b is None: return _fast_p elif a is None: def fast_p(x: np.ndarray, a: np.float): return _fast_p(x, a, b) elif b is None: def fast_p(x: np.ndarray, b: np.float): return _fast_p(x, a, b) else: def fast_p(x: np.ndarray): return _fast_p(x, a, b) fast_p = numba.jit(nopython=True, forceobj=False, fastmath=True)(fast_p) return fast_p
7918ac56d5849d5397eee17e699ba9a45cf94e5f
b2c896ca9f2acb81115708ce6cf8d01396e71a18
/capybara/tests/session/element/test_matches_selector.py
ff60142d44cd19b211832859a9ff8d2200284aea
[ "MIT" ]
permissive
elliterate/capybara.py
b846f3cb1a712a120361849b378d437775c2c6db
eafd9ac50d02e8b57ef90d767493c8fa2be0739a
refs/heads/master
2023-08-16T13:56:51.506840
2022-01-16T18:04:22
2022-01-16T18:04:22
64,620,050
63
22
MIT
2022-01-16T18:04:23
2016-07-31T23:02:18
Python
UTF-8
Python
false
false
3,002
py
import pytest import capybara class MatchesSelectorTestCase: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_html") @pytest.fixture def element(self, session): return session.find("//span", text="42") class TestMatchesSelector(MatchesSelectorTestCase): def test_is_true_if_the_element_matches_the_given_selector(self, element): assert element.matches_selector("xpath", "//span") is True assert element.matches_selector("css", "span.number") is True def test_is_false_if_the_element_does_not_match_the_given_selector(self, element): assert element.matches_selector("xpath", "//div") is False assert element.matches_selector("css", "span.not_a_number") is False def test_uses_default_selector(self, element): capybara.default_selector = "css" assert not element.matches_selector("span.not_a_number") assert element.matches_selector("span.number") def test_works_with_elements_located_via_a_sibling_selector(self, element): sibling = element.sibling("css", "span", text="Other span") assert sibling.matches_selector("xpath", "//span") assert sibling.matches_selector("css", "span") def test_works_with_the_html_element(self, session): html = session.find("/html") assert html.matches_selector("css", "html") def test_discards_all_matches_where_the_given_string_is_not_contained(self, element): assert element.matches_selector("//span", text="42") assert not element.matches_selector("//span", text="Doesnotexist") class TestNotMatchSelector(MatchesSelectorTestCase): def test_is_false_if_the_element_matches_the_given_selector(self, element): assert element.not_match_selector("xpath", "//span") is False assert element.not_match_selector("css", "span.number") is False def test_is_true_if_the_element_does_not_match_the_given_selector(self, element): assert element.not_match_selector("xpath", "//div") is True assert element.not_match_selector("css", "span.not_a_number") is True def test_uses_default_selector(self, element): capybara.default_selector = "css" assert element.not_match_selector("span.not_a_number") assert not element.not_match_selector("span.number") def test_works_with_elements_located_via_a_sibling_selector(self, element): sibling = element.sibling("css", "span", text="Other span") assert not sibling.not_match_selector("xpath", "//span") assert sibling.not_match_selector("css", "div") def test_works_with_the_html_element(self, session): html = session.find("/html") assert html.not_match_selector("css", "body") def test_discards_all_matches_where_the_given_string_is_contained(self, element): assert not element.not_match_selector("//span", text="42") assert element.not_match_selector("//span", text="Doesnotexist")
e7d128e1500aba2f7670ba59a46061cdec915f47
069d2985895eefe33454e57ff2d85b9fa8aa7fa0
/run.py
df4f5781aa2fc97d2b52b3f42b8ed9f9d8363f45
[]
no_license
KIRA009/formbuilder
8a6dd2949b42560f3b7cbad4b2c00e32e09ff55f
880fdbe211d80c31870dd8da84e376de9598b738
refs/heads/master
2023-02-05T16:42:08.806984
2019-07-02T18:34:05
2019-07-02T18:34:05
194,048,846
1
1
null
2023-02-02T06:32:31
2019-06-27T07:52:40
JavaScript
UTF-8
Python
false
false
253
py
from app_builder import build_app import os ROOT_DIR = os.getcwd() app, db, migrate, login_manager = build_app(app_name=__name__, env_path=ROOT_DIR + '\.env', config_env='SETTINGS') from myapp.views import * if __name__ == '__main__': app.run()
413ca2abc71b33a69400411278b07e243fbf15a8
e4910c4b436223859d91f3569cadafa69a3c777b
/src/racecar/scripts/keyboard.py
c8c26dd85a147588db69800067b55328e93f0960
[ "BSD-3-Clause" ]
permissive
pmusau17/F1TenthHardware
81ae6870e15c1fe39a1f386b8bcfaa653bf2675c
3ae3ab1cedd89e56db2fbabe24f1c6a79d3553d9
refs/heads/master
2023-04-01T09:02:12.635614
2021-04-07T16:34:17
2021-04-07T16:34:17
298,356,593
3
0
null
null
null
null
UTF-8
Python
false
false
2,059
py
#!/usr/bin/env python import rospy from racecar.msg import drive_param from ackermann_msgs.msg import AckermannDriveStamped import sys, select, termios, tty keyBindings = { 'w':(1,0), 'd':(1,-1), 'a':(1,1), 's':(-1,0), } def getKey(): tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) key = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings) return key speed = 0.7 turn = 0.5 if __name__=="__main__": settings = termios.tcgetattr(sys.stdin) rospy.init_node('keyboard', anonymous=True) args = rospy.myargv()[1:] if(len(args)==1): racecar_name = args[0] else: racecar_name = '' pub = rospy.Publisher(racecar_name+'/ackermann_cmd_mux/input/teleop', AckermannDriveStamped, queue_size=10) x = 0 th = 0 status = 0 try: while(1): key = getKey() if key in keyBindings.keys(): x = keyBindings[key][0] th = keyBindings[key][1] else: x = 0 th = 0 if (key == '\x03'): break msg = drive_param() msg.velocity = x*speed msg.angle = th*turn rospy.loginfo(str(msg.velocity)) rospy.loginfo(str(msg.angle)) print(x*speed,th*turn) msg = AckermannDriveStamped(); msg.header.stamp = rospy.Time.now(); msg.header.frame_id = "base_link"; msg.drive.speed = x*speed msg.drive.acceleration = 1 msg.drive.jerk = 1 msg.drive.steering_angle = th*turn msg.drive.steering_angle_velocity = 1 pub.publish(msg) except: print 'error' finally: msg = drive_param() msg.velocity = 0 msg.angle = 0 msg = AckermannDriveStamped(); msg.header.stamp = rospy.Time.now(); msg.header.frame_id = "base_link"; msg.drive.speed = x*speed msg.drive.acceleration = 1 msg.drive.jerk = 1 msg.drive.steering_angle = th*turn msg.drive.steering_angle_velocity = 1 pub.publish(msg) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
06c5cd504516c90e7f07c7a903062d100667cc1e
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/catapult/third_party/py_vulcanize/py_vulcanize/parse_html_deps.py
6fbe31daac48d0626acb4efdd44a3050c975ead4
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
Python
false
false
5,738
py
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys from py_vulcanize import module from py_vulcanize import strip_js_comments from py_vulcanize import html_generation_controller def _AddToPathIfNeeded(path): if path not in sys.path: sys.path.insert(0, path) def _InitBeautifulSoup(): catapult_path = os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, os.path.pardir)) bs_path = os.path.join(catapult_path, 'third_party', 'beautifulsoup4') _AddToPathIfNeeded(bs_path) html5lib_path = os.path.join(catapult_path, 'third_party', 'html5lib-python') _AddToPathIfNeeded(html5lib_path) six_path = os.path.join(catapult_path, 'third_party', 'six') _AddToPathIfNeeded(six_path) _InitBeautifulSoup() import bs4 class InlineScript(object): def __init__(self, soup): if not soup: raise module.DepsException('InlineScript created without soup') self._soup = soup self._stripped_contents = None self._open_tags = None @property def contents(self): return unicode(self._soup.string) @property def stripped_contents(self): if not self._stripped_contents: self._stripped_contents = strip_js_comments.StripJSComments( self.contents) return self._stripped_contents @property def open_tags(self): if self._open_tags: return self._open_tags open_tags = [] cur = self._soup.parent while cur: if isinstance(cur, bs4.BeautifulSoup): break open_tags.append(_Tag(cur.name, cur.attrs)) cur = cur.parent open_tags.reverse() assert open_tags[-1].tag == 'script' del open_tags[-1] self._open_tags = open_tags return self._open_tags def _CreateSoupWithoutHeadOrBody(html): soupCopy = bs4.BeautifulSoup(html, 'html5lib') soup = bs4.BeautifulSoup() soup.reset() if soupCopy.head: for n in soupCopy.head.contents: n.extract() soup.append(n) if soupCopy.body: for n in soupCopy.body.contents: n.extract() soup.append(n) return soup class HTMLModuleParserResults(object): def __init__(self, html): self._soup = bs4.BeautifulSoup(html, 'html5lib') self._inline_scripts = None @property def scripts_external(self): tags = self._soup.findAll('script', src=True) return [t['src'] for t in tags] @property def inline_scripts(self): if not self._inline_scripts: tags = self._soup.findAll('script', src=None) self._inline_scripts = [InlineScript(t.string) for t in tags] return self._inline_scripts @property def imports(self): tags = self._soup.findAll('link', rel='import') return [t['href'] for t in tags] @property def stylesheets(self): tags = self._soup.findAll('link', rel='stylesheet') return [t['href'] for t in tags] @property def inline_stylesheets(self): tags = self._soup.findAll('style') return [unicode(t.string) for t in tags] def YieldHTMLInPieces(self, controller, minify=False): yield self.GenerateHTML(controller, minify) def GenerateHTML(self, controller, minify=False, prettify=False): soup = _CreateSoupWithoutHeadOrBody(unicode(self._soup)) # Remove declaration. for x in soup.contents: if isinstance(x, bs4.Doctype): x.extract() # Remove declaration. for x in soup.contents: if isinstance(x, bs4.Declaration): x.extract() # Remove all imports. imports = soup.findAll('link', rel='import') for imp in imports: imp.extract() # Remove all script links. scripts_external = soup.findAll('script', src=True) for script in scripts_external: script.extract() # Remove all in-line scripts. scripts_external = soup.findAll('script', src=None) for script in scripts_external: script.extract() # Process all in-line styles. inline_styles = soup.findAll('style') for style in inline_styles: html = controller.GetHTMLForInlineStylesheet(unicode(style.string)) if html: ns = soup.new_tag('style') ns.append(bs4.NavigableString(html)) style.replaceWith(ns) else: style.extract() # Rewrite all external stylesheet hrefs or remove, as needed. stylesheet_links = soup.findAll('link', rel='stylesheet') for stylesheet_link in stylesheet_links: html = controller.GetHTMLForStylesheetHRef(stylesheet_link['href']) if html: tmp = bs4.BeautifulSoup(html, 'html5lib').findAll('style') assert len(tmp) == 1 stylesheet_link.replaceWith(tmp[0]) else: stylesheet_link.extract() # Remove comments if minifying. if minify: comments = soup.findAll( text=lambda text: isinstance(text, bs4.Comment)) for comment in comments: comment.extract() if prettify: return soup.prettify('utf-8').strip() # We are done. return unicode(soup).strip() @property def html_contents_without_links_and_script(self): return self.GenerateHTML( html_generation_controller.HTMLGenerationController()) class _Tag(object): def __init__(self, tag, attrs): self.tag = tag self.attrs = attrs def __repr__(self): attr_string = ' '.join('%s="%s"' % (x[0], x[1]) for x in self.attrs) return '<%s %s>' % (self.tag, attr_string) class HTMLModuleParser(): def Parse(self, html): if html is None: html = '' else: if html.find('< /script>') != -1: raise Exception('Escape script tags with <\/script>') return HTMLModuleParserResults(html)
1132547772e06d6b2ee93fee62cd3605b759ec0c
60a831fb3c92a9d2a2b52ff7f5a0f665d4692a24
/IronPythonStubs/release/stubs.min/Autodesk/Revit/DB/__init___parts/BindingMap.py
686d18be3c7071d131cd785f06980c6c9a4a0c07
[ "MIT" ]
permissive
shnlmn/Rhino-Grasshopper-Scripts
a9411098c5d1bbc55feb782def565d535b27b709
0e43c3c1d09fb12cdbd86a3c4e2ba49982e0f823
refs/heads/master
2020-04-10T18:59:43.518140
2020-04-08T02:49:07
2020-04-08T02:49:07
161,219,695
11
2
null
null
null
null
UTF-8
Python
false
false
4,051
py
class BindingMap(DefinitionBindingMap,IDisposable,IEnumerable): """ The parameters BindingMap contains all the parameter bindings that exist in the Autodesk Revit project. """ def Clear(self): """ Clear(self: BindingMap) This method is used to remove all the items in the map. """ pass def Contains(self,key): """ Contains(self: BindingMap,key: Definition) -> bool The Contains method is used to check if the parameter binding exists for one definition. key: A parameter definition which can be an existing definition or one from a shared parameters file. """ pass def Dispose(self): """ Dispose(self: BindingMap,A_0: bool) """ pass def Erase(self,key): """ Erase(self: BindingMap,key: Definition) -> int This method is used to erase one item in the map. """ pass def Insert(self,key,item,parameterGroup=None): """ Insert(self: BindingMap,key: Definition,item: Binding) -> bool Creates a new parameter binding between a parameter and a set of categories. key: A parameter definition which can be an existing definition or one from a shared parameters file. item: An InstanceBinding or TypeBinding object which contains the set of categories to which the parameter should be bound. Insert(self: BindingMap,key: Definition,item: Binding,parameterGroup: BuiltInParameterGroup) -> bool Creates a new parameter binding between a parameter and a set of categories in a specified group. key: A parameter definition which can be an existing definition or one from a shared parameters file. item: An InstanceBinding or TypeBinding object which contains the set of categories to which the parameter should be bound. parameterGroup: The GroupID of the parameter definition. """ pass def ReInsert(self,key,item,parameterGroup=None): """ ReInsert(self: BindingMap,key: Definition,item: Binding) -> bool Removes an existing parameter and creates a new binding for a given parameter. key: A parameter definition which can be an existing definition or one from a shared parameters file. item: An InstanceBinding or TypeBinding object which contains the set of categories to which the parameter should be bound. ReInsert(self: BindingMap,key: Definition,item: Binding,parameterGroup: BuiltInParameterGroup) -> bool Removes an existing parameter and creates a new binding for a given parameter in a specified group. key: A parameter definition which can be an existing definition or one from a shared parameters file. item: An InstanceBinding or TypeBinding object which contains the set of categories to which the parameter should be bound. parameterGroup: The GroupID of the parameter definition. """ pass def ReleaseManagedResources(self,*args): """ ReleaseManagedResources(self: APIObject) """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: APIObject) """ pass def Remove(self,key): """ Remove(self: BindingMap,key: Definition) -> bool The Remove method is used to remove a parameter binding. key: A parameter definition which can be an existing definition or one from a shared parameters file. """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __getitem__(self,*args): """ x.__getitem__(y) <==> x[y] """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __iter__(self,*args): """ __iter__(self: IEnumerable) -> object """ pass def __setitem__(self,*args): """ x.__setitem__(i,y) <==> x[i]= """ pass
45ae02db652e3be0161f27e1c06dc8c4cd2cc2e5
11398875e4f5cbcadc1747e73049dc99bca26908
/06-time/time-01.py
7f952d5930c3c2ef4b13a8eec60178b112e90857
[]
no_license
asvkarthick/LearnPython
37910faab5c4a18d6e08eb304ca1da9649e5b18f
258e8c567ca3c8802d5e56f20b34317eba4c75f3
refs/heads/master
2021-06-23T06:30:46.681369
2021-06-11T19:35:40
2021-06-11T19:35:40
149,719,196
0
0
null
null
null
null
UTF-8
Python
false
false
143
py
#!/usr/bin/python # Author: Karthick Kumaran <[email protected]> import time print('Sleeping for 2 seconds') time.sleep(2) print('Done')
83774ee8ba86d36addb91c1a11753509b4785fd5
16a2ac198a36d7633c62d41f4604356cd0ae732e
/Au-public-master/iron/utilities/rename_to_pacbio.py
7b73810b42d4d374c9af78099e87739af78271c2
[ "Apache-2.0" ]
permissive
Dingjie-Wang/Manual-for-running-IDP-pipeline
f433ba5b0dbd44da5a9d8836b3e29a27e12a48c4
6c2756e10184f0b8f0e5872a358378e90f1729b0
refs/heads/master
2021-06-29T04:02:56.741203
2020-12-07T17:39:05
2020-12-07T17:39:05
201,325,604
1
7
null
null
null
null
UTF-8
Python
false
false
1,878
py
#!/usr/bin/python import sys,argparse from SequenceBasics import FastaHandleReader, FastqHandleReader def main(): parser = argparse.ArgumentParser() parser.add_argument('input',help="Use - for STDIN") group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--fasta',action='store_true') group.add_argument('--fastq',action='store_true') group.add_argument('--gpd',action='store_true') parser.add_argument('--output_table',help='save coversion to file') parser.add_argument('-o','--output') args = parser.parse_args() if args.input=='-': args.input = sys.stdin else: args.input= open(args.input) if args.output: args.output = open(args.output,'w') if args.output_table: args.output_table= open(args.output_table,'w') else: args.output = sys.stdout if args.gpd: z = 0 for line in args.input: f = line.rstrip().split("\t") z+=1 name = 'm150101_010101_11111_c111111111111111111_s1_p0/'+str(z)+'/ccs' if args.output_table: args.output_table.write(f[0]+"\t"+name+"\n") f[0] = name f[1] = name args.output.write("\t".join(f)+"\n") args.output.close() if args.output_table: args.output_table.close() return if args.fasta: args.input = FastaHandleReader(args.input) elif args.fastq: args.input = FastqHandleReader(args.input) z = 0 while True: e = args.input.read_entry() if not e: break z+=1 name = 'm150101_010101_11111_c111111111111111111_s1_p0/'+str(z)+'/ccs' if args.fastq: args.output.write( '@'+name+"\n"+ e['seq']+"\n"+ '+'+e['qual']+"\n") elif args.fasta: args.output.write('>'+name+"\n"+e['seq']+"\n") if args.output_table: args.output_table.write(e['name']+"\t"+name+"\n") args.output.close() if args.output_table: args.output_table.close() if __name__=="__main__": main()
fdc482ebab30deb95941025999cd0e9ef8238969
b6cf41b1eadb6571e30998712da651ec62db07ad
/Gui/TextEdit.py
ceb67896e0bb84b333873a5b082f3dbedb16f3f7
[]
no_license
fdanesse/CoralEditor
8d1949ff86af61d44d573d544a3b76dbc182b5d4
e42239f75ee921c99d13e60758b32ca5862c303f
refs/heads/master
2021-08-14T07:14:19.203753
2017-11-15T00:06:11
2017-11-15T00:06:11
107,883,737
0
0
null
null
null
null
UTF-8
Python
false
false
6,380
py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os from PyQt5.QtCore import Qt from PyQt5.QtCore import QEvent from PyQt5.QtWidgets import QPlainTextEdit from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QPalette from PyQt5.QtGui import QColor from PyQt5.QtGui import QFont from PyQt5.QtGui import QFontMetrics from PyQt5.QtGui import QTextCharFormat from PyQt5.QtGui import QKeyEvent #from PyQt5.QtGui import QTextCursor #from Gui.Syntax.PythonHighlighter import PythonHighlighter class TextEdit(QPlainTextEdit): # https://doc.qt.io/qt-5/qplaintextedit.html # https://github.com/hugoruscitti/pilas/blob/e33bfd80a9c9faec432dbd3de1d82066b8704303/pilasengine/interprete/editorbase/editor_base.py # http://www.binpress.com/tutorial/developing-a-pyqt-text-editor-part-2/145 # http://ftp.ics.uci.edu/pub/centos0/ics-custom-build/BUILD/PyQt-x11-gpl-4.7.2/doc/html/qtextedit.html # http://nullege.com/codes/show/src@p@y@pyqt5-HEAD@examples@tools@[email protected]/92/PyQt5.QtWidgets.QTextEdit.textCursor # http://nullege.com/codes/show/src@p@y@pyqt5-HEAD@examples@richtext@[email protected]/87/PyQt5.QtWidgets.QTextEdit.setFocus # Ejemplos: # https://stackoverflow.com/questions/31610351/qplaintextedit-thinks-its-modified-if-it-has-an-empty-text # https://john.nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/ # https://github.com/Werkov/PyQt4/blob/master/examples/demos/textedit/textedit.py def __init__(self, parent, path=""): #super().__init__() super(TextEdit, self).__init__(parent) self.parent = parent self.path = path font = QFont("Monospace", 8) #QFont() #font.setFamily("Monospace") font.setStyleHint(QFont.Monospace) font.setStyle(QFont.StyleNormal) font.setStyleStrategy(QFont.PreferDefault) font.setWeight(QFont.ExtraLight) font.setCapitalization(QFont.MixedCase) font.setHintingPreference(QFont.PreferDefaultHinting) font.setLetterSpacing(QFont.PercentageSpacing, 100.0) font.setStretch(QFont.AnyStretch) font.setBold(False) font.setFixedPitch(True) font.setItalic(False) font.setKerning(True) font.setOverline(False) # sobrelinea #font.setPixelSize(8) #font.setPointSize(8) font.setPointSizeF(8) font.setStrikeOut(False) # tachado #font.setStyleName() font.setUnderline(False) #font.setWordSpacing(1) print(font.toString()) charFormat = QTextCharFormat() charFormat.setFont(font) #self.setTabStopWidth(4) self.setCursorWidth(5) self.setCurrentCharFormat(charFormat) #print(self.document().defaultTextOption()) #FIXME: Usaremos qss pal = QPalette() bgc = QColor(39, 40, 34) pal.setColor(QPalette.Base, bgc) textc = QColor(255, 255, 255) pal.setColor(QPalette.Text, textc) self.setPalette(pal) self.setLineWrapMode(QPlainTextEdit.NoWrap) #self.setTextBackgroundColor(QColor(0, 255, 255)) #self.setTextColor(QColor(0, 255, 255)) #self.setFontWeight(QFont.Normal) #cursor = self.textCursor() #cursor.movePosition(QTextCursor.End) #self.setDocumentTitle("Coso") #self.syntaxHighlighter = PythonHighlighter(self.document()) # Señales #self.blockCountChanged.connect(self.__newBlock) #self.cursorPositionChanged.connect() #self.selectionChanged.connect(self.__changedSelection) #self.textChanged.connect(self.__changedText) #self.updateRequest.connect((const QRect &rect, int dy) #self.modificationChanged.connect(self.__chanedModification) #self.copyAvailable.connect(self.__copyAvailable) #self.undoAvailable.connect(self.__undoAvailable) #self.redoAvailable.connect(self.__redoAvailable) if os.path.exists(self.path): file = open(self.path, 'r') data = file.read() texto = self.__limpiar_codigo(data) self.setPlainText(texto) self.document().setModified(data != texto) if data != texto: print("El texto fue corregido al abrir el archivo.") else: self.setPlainText("#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n") self.document().setModified(True) self.setFocus() def getStatus(self): """ Si se modifica el texto, se puede guardar. """ return{ "modified": self.document().isModified(), } #def __chanedModification(self, changed): # pass # #print("Document changed:", changed) #def __changedSelection(self): # cursor = self.textCursor() # selected = cursor.selectionEnd()-cursor.selectionStart() # self.canSelectAll = selected < len(self.toPlainText()) #def __copyAvailable(self, available): # self.canCopy = available #def __undoAvailable(self, available): # pass # #print("Undo:", available) #def __redoAvailable(self, available): # pass # #print("Redo:", available) def keyPressEvent(self, event): # https://doc.qt.io/qt-5/qt.html#Key-enum if event.key() == Qt.Key_Tab: event.ignore() event.accept = True for x in range(0, 4): newevent = QKeyEvent(QEvent.KeyPress, Qt.Key_Space, Qt.NoModifier, text=" ", autorep=False, count=1) QApplication.postEvent(self, newevent) else: super(TextEdit, self).keyPressEvent(event) event.accept = True self.setFocus() ''' def __newBlock(self, newBlockCount): #print(newBlockCount) def __changedText(self): text = self.document().toPlainText() text = self.__limpiar_codigo(text) #self.setPlainText(text) print(text, self.document().size()) ''' def __limpiar_codigo(self, texto): limpio = "" for line in texto.splitlines(): text_line = "%s\n" % (line.rstrip()) ret = text_line.replace("\t", " ") for l in ret: limpio = "%s%s" % (limpio, l) return limpio
2cbcad6a307bd6d1b5101f9e5781d7caaa236d91
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startQiskit_QC1087.py
70d9c4bc57bcaa206e68809763018b4b54d22d38
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,454
py
# qubit number=5 # total number=50 import cirq import qiskit from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2,floor, sqrt, pi import numpy as np import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127) controls = QuantumRegister(n, "ofc") oracle = QuantumCircuit(controls, name="Zf") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.h(controls[n]) if n >= 2: oracle.mcu1(pi, controls[1:], controls[0]) for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[4]) # number=21 Zf = build_oracle(n, f) repeat = floor(sqrt(2 ** n) * pi / 4) for i in range(repeat): prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)]) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=31 prog.cz(input_qubit[1],input_qubit[0]) # number=32 prog.h(input_qubit[0]) # number=33 prog.h(input_qubit[1]) # number=44 prog.cz(input_qubit[0],input_qubit[1]) # number=45 prog.h(input_qubit[1]) # number=46 prog.cx(input_qubit[0],input_qubit[1]) # number=47 prog.x(input_qubit[1]) # number=48 prog.cx(input_qubit[0],input_qubit[1]) # number=49 prog.cx(input_qubit[0],input_qubit[1]) # number=42 prog.x(input_qubit[0]) # number=26 prog.cx(input_qubit[1],input_qubit[0]) # number=27 prog.h(input_qubit[1]) # number=37 prog.cz(input_qubit[0],input_qubit[1]) # number=38 prog.h(input_qubit[1]) # number=39 prog.x(input_qubit[1]) # number=35 prog.cx(input_qubit[0],input_qubit[1]) # number=36 prog.x(input_qubit[2]) # number=11 prog.x(input_qubit[3]) # number=12 prog.cx(input_qubit[3],input_qubit[2]) # number=43 if n>=2: prog.mcu1(pi,input_qubit[1:],input_qubit[0]) prog.x(input_qubit[0]) # number=13 prog.cx(input_qubit[0],input_qubit[1]) # number=22 prog.x(input_qubit[1]) # number=23 prog.cx(input_qubit[0],input_qubit[1]) # number=24 prog.x(input_qubit[2]) # number=15 prog.x(input_qubit[1]) # number=29 prog.y(input_qubit[4]) # number=28 prog.x(input_qubit[3]) # number=16 prog.h(input_qubit[0]) # number=17 prog.h(input_qubit[1]) # number=18 prog.h(input_qubit[2]) # number=19 prog.h(input_qubit[3]) # number=20 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog if __name__ == '__main__': key = "00000" f = lambda rep: str(int(rep == key)) prog = make_circuit(5,f) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True)) sample_shot =7924 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit_QC1087.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.depth(),file=writefile) print(circuit1,file=writefile) writefile.close()
7620c16b70a5011be660188673a3d70cf943f517
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/4_set/6265. 统计相似字符串对的数目-frozenset.py
a37db3b54e7eb3a906c7279c7abccaff4e9548a7
[]
no_license
981377660LMT/algorithm-study
f2ada3e6959338ae1bc21934a84f7314a8ecff82
7e79e26bb8f641868561b186e34c1127ed63c9e0
refs/heads/master
2023-09-01T18:26:16.525579
2023-09-01T12:21:58
2023-09-01T12:21:58
385,861,235
225
24
null
null
null
null
UTF-8
Python
false
false
786
py
from typing import List from collections import Counter # 给你一个下标从 0 开始的字符串数组 words 。 # 如果两个字符串由相同的字符组成,则认为这两个字符串 相似 。 # 例如,"abca" 和 "cba" 相似,因为它们都由字符 'a'、'b'、'c' 组成。 # 然而,"abacba" 和 "bcfd" 不相似,因为它们不是相同字符组成的。 # 请你找出满足字符串 words[i] 和 words[j] 相似的下标对 (i, j) ,并返回下标对的数目,其中 0 <= i < j <= word.length - 1 。 class Solution: def similarPairs(self, words: List[str]) -> int: counter = Counter() for word in words: counter[frozenset(word)] += 1 return sum(v * (v - 1) // 2 for v in counter.values())
8ba8ac218525fe114aef069e508dbd337d9c8b19
eeeba145ae4b6df7b5d95cc70d476a01dba6c5fe
/PythonStudy/func_test/lambda_test.py
52286c0eb1edd88d86870e484d66ce35fd90a1e7
[]
no_license
liujinguang/pystudy
0ceb58652777f99d4cfe3e143ff11ea44c7e3a74
d2e4366cfd5e74197fc9ec560eb50dbd508cbcc2
refs/heads/master
2020-12-23T13:11:42.556255
2017-06-28T13:03:26
2017-06-28T13:03:26
92,559,516
0
0
null
null
null
null
UTF-8
Python
false
false
356
py
#/usr/bin/python # -*- coding: UTF-8 -*- ''' Created on 2017年5月31日 @author: bob ''' def multipliers(): return [lambda x : i * x for i in range(4)] print [m(2) for m in multipliers()] def multipliers_v1(): for i in range(4): yield lambda x: i * x print [m(2) for m in multipliers_v1()] if __name__ == '__main__': pass
d31988b13f42acd2ad1577ce07a0b7e8506e7ce8
925dc0d981391e4538401a7af88fcac25921ccab
/emission/net/api/metrics.py
20e6b0f9fd1e9cee84bd6847b0c0a85cce6b0ff9
[ "BSD-3-Clause" ]
permissive
gtfierro/e-mission-server
0e75742301b3de8d8dd71e6bc3a6e7c0bfe48ee7
b10c5da080b741b28eccf8cb7413ace3063eaaac
refs/heads/master
2021-01-19T11:58:24.441986
2016-09-30T09:00:54
2016-09-30T09:00:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,203
py
import logging import emission.analysis.result.metrics.time_grouping as earmt import emission.analysis.result.metrics.simple_metrics as earms def summarize_by_timestamp(user_id, start_ts, end_ts, freq, metric_name): return _call_group_fn(earmt.group_by_timestamp, user_id, start_ts, end_ts, freq, metric_name) def summarize_by_local_date(user_id, start_ld, end_ld, freq_name, metric_name): local_freq = earmt.LocalFreq[freq_name] return _call_group_fn(earmt.group_by_local_date, user_id, start_ld, end_ld, local_freq, metric_name) def _call_group_fn(group_fn, user_id, start_time, end_time, freq, metric_name): summary_fn = earms.get_summary_fn(metric_name) logging.debug("%s -> %s" % (metric_name, summary_fn)) aggregate_metrics = group_fn(None, start_time, end_time, freq, summary_fn) ret_dict = {"aggregate_metrics": aggregate_metrics["result"]} if user_id is not None: user_metrics = group_fn(user_id, start_time, end_time, freq, summary_fn) ret_dict.update({"user_metrics": user_metrics["result"]}) return ret_dict
9c263e0f31066de90cfb7168e44d3f1faaff0d99
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/ios/chrome/browser/flags/DEPS
458d0f02f4f533615b90bc6bce32a1ece69f84f1
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
Python
false
false
405
specific_include_rules = { # Flag list can depends on everything. "^about_flags.mm": [ "+ios/chrome/browser", ], "^ios_chrome_field_trials.mm": [ "+ios/chrome/browser/variations", "+ios/chrome/browser/ui/content_suggestions", "+ios/chrome/browser/ui/first_run", "+ios/chrome/browser/ui/ntp", ], "^system_flags.mm": [ "+ios/chrome/browser/ui/ui_feature_flags.h", ] }
865e42f9823db183fe0a661b7ee6ecce678f9a25
ae411ea0e0c373d18681d707800995264379be25
/mic.py
df6a5aaf7b2e2a2e146caccea681f70963c889f7
[]
no_license
Symfomany/tensor
22ad4b0710d705d1ec47e3512431c2ca74ca3948
2b8471f7aab6a7a234bd89942118bbadf4058352
refs/heads/master
2022-12-21T14:53:03.349221
2019-02-21T10:39:31
2019-02-21T10:39:31
171,100,643
0
0
null
2022-12-09T13:17:30
2019-02-17T08:51:46
Jupyter Notebook
UTF-8
Python
false
false
4,912
py
#!/usr/bin/env python import pyaudio import struct import math import time,sys import threading INITIAL_TAP_THRESHOLD = 0.010 FORMAT = pyaudio.paInt16 SHORT_NORMALIZE = (1.0/32768.0) CHANNELS = 1 RATE = 16000 INPUT_BLOCK_TIME = 0.05 INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME) OVERSENSITIVE = 15.0/INPUT_BLOCK_TIME UNDERSENSITIVE = 120.0/INPUT_BLOCK_TIME # if we get this many quiet blocks in a row, decrease the threshold MAX_TAP_BLOCKS = 0.15/INPUT_BLOCK_TIME # if the noise was longer than this many blocks, it's not a 'tap' def get_rms(block): # L’amplitude d’un son est la caractéristique la plus simple que l’on puisse imaginer. # Elle caractérise directement l’intensité du son c’est à dire son volume, ou encore la force avec laquelle elle excite l’oreille de l’auditeur. S # Le son qui engendre une vibration d’un corps physique, # crée des variations de pression qui exercent une force sur les autres corps physiques en contact avec l’air (l’air étant un milieu dit « élastique »). # Cette force n’étant pas constante (si elle l’est, il n’y a pas de son) le corps en question ne bouge pas mais vibre (si tant est qu’il ne soit pas trop rigide). # L’amplitude d’un signal est sa valeur maximale. # Ici l’amplitude du signal qui varie entre la valeur +max et -max est +max. # En somme, le maximum réel de la fonction sur un intervalle de temps donné. # Dans le cas d’un signal sinusoïdal (tel que celui ci-dessus) on peut exprimer simplement la valeur efficace du signal par la formule suivante : # En fait, la valeur efficace, qui est très utilisée (parce que renvoyée par les instruments de mesures : # un voltmètre par exemple) est la valeur quadratique moyenne. # Par exemple si la valeur du signal en fonction du temps est donnée par la fonction Y(t) # on a la formule générale suivante qui donne la valeur efficace du signal sur un intervalle de temps donné : # Valeur max et valeur efficace sont à mettre en relation avec ce que l’on appelle # les puissances max et les puissances efficaces. # Par exemple un amplificateur de puissance 100 W efficace (ou RMS) fournit une puissance crête (max) de 200W voire 400W sur des impulsions très brèves (s’il ne grille pas avant). # Cette puissance impulsionnelle qui ne veut pas dire grand chose est parfois indiquée comme étant la puissance Musicale de l’amplificateur. # RMS amplitude is defined as the square root of the # mean over time of the square of the amplitude. # so we need to convert this string of bytes into # a string of 16-bit samples... # we will get one short out for each # two chars in the string. count = len(block)/2 format = "%dh"%(count) shorts = struct.unpack( format, block ) # iterate over the block. sum_squares = 0.0 for sample in shorts: # sample is a signed short in +/- 32768. # normalize it to 1.0 n = sample * SHORT_NORMALIZE sum_squares += n*n return math.sqrt( sum_squares / count ) pa = pyaudio.PyAudio() #] #| stream = pa.open(format = FORMAT, #| channels = CHANNELS, #|---- You always use this in pyaudio... rate = RATE, #| input = True, #| frames_per_buffer = INPUT_FRAMES_PER_BLOCK) #] tap_threshold = INITIAL_TAP_THRESHOLD #] noisycount = MAX_TAP_BLOCKS+1 #|---- Variables for noise detector... quietcount = 0 #| errorcount = 0 #] for i in range(1000): try: #] block = stream.read(INPUT_FRAMES_PER_BLOCK) #| except (IOError,e): #|---- just in case there is an error! errorcount += 1 #| print( "(%d) Error recording: %s"%(errorcount,e) ) #| noisycount = 1 #] amplitude = get_rms(block) # Root mean Square va permettre de calculer l'amplitude d'un son en streaming print(amplitude) if amplitude > tap_threshold: # if its to loud... bruyant quietcount = 0 noisycount += 1 if noisycount > OVERSENSITIVE: tap_threshold *= 1.1 # turn down the sensitivity else: # if its to quiet... if 1 <= noisycount <= MAX_TAP_BLOCKS: print('tap!') noisycount = 0 quietcount += 1 if quietcount > UNDERSENSITIVE: tap_threshold *= 0.9 # turn up the sensitivity
b956a071a1cd830747a03be5cfbe515c771eb205
5eba0ee342adf574664ef2c5b2a9787f28ad9e4a
/core/utils/auth.py
35059117c9a7332bc93e926280bf0e24a81a7e90
[]
no_license
nagibator95/ejudge-front
2775875bd8d8367674b3c5c372b5fafa77167aac
ca355f473702561047da030b7d4a12af06539395
refs/heads/master
2020-04-10T06:59:53.873278
2018-12-20T20:15:36
2018-12-20T20:15:36
160,870,700
0
0
null
null
null
null
UTF-8
Python
false
false
568
py
from flask import request from werkzeug.exceptions import Forbidden def get_api_key_checker(key) -> callable: """ Function which returns function which checks request api key Basic usage: app = Flask() app.before_request(get_api_key_checker(<my-secret-string>)) Raises ------ Forbidden: when api key is bad or not allowed """ def check_api_key(): requested_key = request.headers.get('api-key') if key != requested_key: raise Forbidden('API key is not valid!') return check_api_key
9ac19c4aea106efafa3ec76b9113214d59ee531f
d20d7d0887e044cb369687629eee04d03bc6ac15
/grano/logic/projects.py
cc54f580a84a76c3afff8ddffdeb95bdd13d3aa3
[ "MIT" ]
permissive
nimblemachine/grano
947812bdd2a861e7d62bd081423df2723891989a
ffbd3f974867334d396d536bd000a20a314f9fc6
refs/heads/master
2021-01-18T11:24:51.750426
2014-03-24T10:39:35
2014-03-24T10:39:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,796
py
import colander from datetime import datetime from grano.core import app, db, url_for from grano.lib.exc import NotImplemented from grano.logic.validation import database_name from grano.logic.references import AccountRef from grano.logic import accounts from grano.model import Project def validate(data, project): same_project = lambda s: Project.by_slug(s) == project same_project = colander.Function(same_project, message="Project exists") class ProjectValidator(colander.MappingSchema): slug = colander.SchemaNode(colander.String(), validator=colander.All(database_name, same_project)) label = colander.SchemaNode(colander.String(), validator=colander.Length(min=3)) private = colander.SchemaNode(colander.Boolean(), missing=False) author = colander.SchemaNode(AccountRef()) settings = colander.SchemaNode(colander.Mapping(), missing={}) validator = ProjectValidator() return validator.deserialize(data) def save(data, project=None): """ Create or update a project with a given slug. """ data = validate(data, project) if project is None: project = Project() project.slug = data.get('slug') project.author = data.get('author') from grano.logic import permissions as permissions_logic permissions_logic.save({ 'account': data.get('author'), 'project': project, 'admin': True }) project.settings = data.get('settings') project.label = data.get('label') project.private = data.get('private') project.updated_at = datetime.utcnow() db.session.add(project) # TODO: make this nicer - separate files? from grano.logic.schemata import import_schema with app.open_resource('fixtures/base.yaml') as fh: import_schema(project, fh) db.session.flush() return project def delete(project): raise NotImplemented() def to_rest_index(project): return { 'slug': project.slug, 'label': project.label, 'api_url': url_for('projects_api.view', slug=project.slug) } def to_rest_index_stats(project): data = to_rest_index(project) data['entities_count'] = project.entities.count() data['relations_count'] = project.relations.count() return data def to_rest(project): data = to_rest_index_stats(project) data['settings'] = project.settings data['author'] = accounts.to_rest_index(project.author) data['schemata_index_url'] = url_for('schemata_api.index', slug=project.slug) data['entities_index_url'] = url_for('entities_api.index', project=project.slug) data['relations_index_url'] = url_for('relations_api.index', project=project.slug) return data
2a7f70925be3844266a29d8d9c3d9824794a0c0f
dfab6798ece135946aebb08f93f162c37dd51791
/core/luban/controller/Actor.py
8452c92ace1f56996ae2ccc29b60f307a6a30f4f
[]
no_license
yxqd/luban
405f5f7dcf09015d214079fe7e23d644332be069
00f699d15c572c8bf160516d582fa37f84ac2023
refs/heads/master
2020-03-20T23:08:45.153471
2012-05-18T14:52:43
2012-05-18T14:52:43
137,831,650
0
0
null
null
null
null
UTF-8
Python
false
false
1,679
py
# -*- Python -*- # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Jiao Lin # California Institute of Technology # (C) 2006-2011 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # class Actor(object): # properties name = None # name of the actor controller = None # the controller # exceptions from .exceptions import RoutineNotFound # methods def perform(self, routine=None, *args, **kwds): if routine is None: routine = "default" if routine.startswith('_'): raise RuntimeError("%s is private" % routine) try: behavior = getattr(self, routine) except AttributeError: msg = "actor %r: routine %r is not yet implemented" % ( self.name, routine) raise self.RoutineNotFound(msg) # special name "kwds" if 'kwds' in kwds: kwds2 = kwds['kwds'] if isinstance(kwds2, strbase): from ..weaver.web._utils import jsonDecode kwds2 = jsonDecode(kwds2) for k in kwds2: if k in kwds: raise RuntimeError("conflict key: %s" % k) continue kwds.update(kwds2) del kwds['kwds'] return behavior(*args, **kwds) pass # end of Actor from luban import py_major_ver if py_major_ver == 2: strbase = basestring elif py_major_ver == 3: strbase = str # End of file
5bcff8ae4c42c2bafb1c80881769ed67f44ea8e9
f2889a13368b59d8b82f7def1a31a6277b6518b7
/256.py
d94465af0b09e0a288eb3073779e9c08ea3bc589
[]
no_license
htl1126/leetcode
dacde03de5c9c967e527c4c3b29a4547154e11b3
c33559dc5e0bf6879bb3462ab65a9446a66d19f6
refs/heads/master
2023-09-01T14:57:57.302544
2023-08-25T15:50:56
2023-08-25T15:50:56
29,514,867
7
1
null
null
null
null
UTF-8
Python
false
false
452
py
# ref: https://discuss.leetcode.com/topic/21337/1-lines-ruby-python class Solution(object): def minCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ prev = [0] * 3 for now in costs: prev = [now[i] + min(prev[:i] + prev[i + 1:]) for i in xrange(3)] return min(prev) if __name__ == '__main__': sol = Solution() print sol.minCost([[1, 2, 3], [3, 2, 1]])
0df69e3db7af12577fa662d3a36c94d62a749ea6
303bac96502e5b1666c05afd6c2e85cf33f19d8c
/solutions/python3/257.py
de9a0c8a3c1cbc818b3466259db95a34a7020459
[ "MIT" ]
permissive
jxhangithub/leetcode
5e82f4aeee1bf201e93e889e5c4ded2fcda90437
0de1af607557d95856f0e4c2a12a56c8c57d731d
refs/heads/master
2022-05-22T12:57:54.251281
2022-03-09T22:36:20
2022-03-09T22:36:20
370,508,127
1
0
MIT
2022-03-09T22:36:20
2021-05-24T23:16:10
null
UTF-8
Python
false
false
678
py
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: def dfs(node, arr): if not node.right and not node.left: #print(arr) self.res += ['->'.join(str(num) for num in arr)] if node.left: dfs(node.left, arr + [node.left.val]) if node.right: dfs(node.right, arr + [node.right.val]) self.res = [] if not root: return [] dfs(root, [root.val]) return self.res
d22cf8a285c59ddf0e21693168cc10d8de3a8edf
0729155365ebd2e8761068bda78060f0c2d6e6a7
/Class And Object Programs/3__Calculate the Area and Perimeter of Circle Using The Class.py
412cc99095898ee61f62e70e3823075e3ba7c024
[]
no_license
mukeshrock7897/Class-And-Object-Programs
a0ce41b19ebdd87bb037ca742069f98c59c21847
a6cf378ab4c5a3d95a46867b5414b44955838782
refs/heads/master
2020-04-24T05:04:53.234277
2019-02-20T18:10:25
2019-02-20T18:10:25
171,724,815
2
0
null
null
null
null
UTF-8
Python
false
false
378
py
import math class Circle: def __init__(self,radius): self.radius=radius def area(self): return math.pi*(self.radius**2) def perimeter(self): return 2*math.pi*self.radius radius=int(input("Enter The Radius Of Circle::")) obj=Circle(radius) print("Area Of Circle::",round(obj.area(),2)) print("Perimeter of Circle::",round(obj.perimeter(),2))
e0004b0b6df60bd3030ff004ed0bbefc869e38b4
10ddfb2d43a8ec5d47ce35dc0b8acf4fd58dea94
/Python/minimum-string-length-after-removing-substrings.py
48bab73ecbf57ba9c36b9cfb91378585932a9056
[ "MIT" ]
permissive
kamyu104/LeetCode-Solutions
f54822059405ef4df737d2e9898b024f051fd525
4dc4e6642dc92f1983c13564cc0fd99917cab358
refs/heads/master
2023-09-02T13:48:26.830566
2023-08-28T10:11:12
2023-08-28T10:11:12
152,631,182
4,549
1,651
MIT
2023-05-31T06:10:33
2018-10-11T17:38:35
C++
UTF-8
Python
false
false
381
py
# Time: O(n) # Space: O(n) # stack class Solution(object): def minLength(self, s): """ :type s: str :rtype: int """ stk = [] for c in s: if stk and ((stk[-1] == 'A' and c == 'B') or (stk[-1] == 'C' and c == 'D')): stk.pop() continue stk.append(c) return len(stk)
606477f67edd3313746f9af6bd76d0bcc0b0f20d
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_salaams.py
1de6f8529dce67507995a11f6402f5e970de1ab1
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
#calss header class _SALAAMS(): def __init__(self,): self.name = "SALAAMS" self.definitions = salaam self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['salaam']
e0a001fca791b06a772558c84bf3d8c100a2c4dd
ba3a705ecb3628641793854292aa9a3ff8fc1221
/10_API/FlaskIntroduction/app.py
0a23ab3144d2a8d92dd00599475768d8da80d806
[]
no_license
mortenhaahr/NGK
d98ada8d63a07ea6447768ab6a23ad1346634b56
a9e89afb452dd7953cba4403b4e8bc2c0ff2ba1e
refs/heads/master
2022-07-01T20:39:02.063251
2020-05-11T15:40:26
2020-05-11T15:40:26
242,725,171
0
0
null
null
null
null
UTF-8
Python
false
false
2,516
py
from flask import Flask, render_template, url_for, request, redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) #__name__ = filename app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' # 3 forward slashes for relative path db = SQLAlchemy(app) # Pass in app to database and init db class Todo(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.String(200), nullable=False) #Max 200 chars and dont allow it to be blank date_created = db.Column(db.DateTime, default=datetime.utcnow) #Never has to be set manually # Everytime we make a new taks, it shall return the ID of that task: def __repr__(self): return '<Task %r' % self.id #Must setup database manually in python ONCE, to create the db in env: # Type following in console: # python3 [enter] from app import db [enter] db.create_all() [enter] exit() [enter] @app.route('/', methods=['POST', 'GET']) #root directory. POST and GET defines that the directory accepts POST and GET requests def index(): if request.method == 'POST': task_content = request.form['content'] new_task = Todo(content=task_content) try: db.session.add(new_task) db.session.commit() return redirect('/') except: return 'There was an issue adding your task' else: tasks = Todo.query.order_by(Todo.date_created).all() # Return all database instances in order created #return "Hello, World!" # return basic string on website return render_template('index.html', tasks=tasks) #return index page. # make delete route @app.route('/delete/<int:id>') def delete(id): task_to_delete = Todo.query.get_or_404(id) # Get object by id, if it fails, throw 404 try: db.session.delete(task_to_delete) db.session.commit() return redirect('/') except: return 'There was a problem deleting that task' @app.route('/update/<int:id>', methods=['GET', 'POST']) def update(id): task = Todo.query.get_or_404(id) #define our task variable for this function if request.method == 'POST': task.content = request.form['content'] try: db.session.commit() return redirect('/') except: return 'There was an issue updating your task' else: return render_template('update.html', task=task) if __name__ == "__main__": app.run(debug=True)
393267ba2fca5a36bba7334d69ab49829c14bc68
84d84096b413e84f502468a2985780a3005457a1
/api/orders/views.py
1daaf6e39ac7835363150b9c1afaa1afd0c60dcf
[ "MIT" ]
permissive
joeltio/np-train
0fd28fe45bdc9c29aee99819ca07798392e13fd1
dc852321b674be3ddc1d1c0dd4eff694825d02fa
refs/heads/master
2020-04-14T18:56:57.714933
2019-01-10T01:58:09
2019-01-10T01:58:09
164,039,036
0
0
null
null
null
null
UTF-8
Python
false
false
4,984
py
import json from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from orders.models import Order import base.helpers as base_helpers @csrf_exempt @require_POST def uncompleted_order(request): # Get the latest uncompleted order order = Order.objects.filter( status=Order.STATUS_NOT_ACTIVE).order_by("id").first() if order is not None: return base_helpers.create_json_response( data=order.as_json() ) else: return base_helpers.create_json_response( message="There are no uncompleted orders", empty_data=True, ) @csrf_exempt @require_POST def new_order(request): # Read json try: json_data = json.loads(request.body) except json.decoder.JSONDecodeError: return base_helpers.create_json_response( success=False, message="Bad JSON", status=400 ) # Check if there is a destination and color if not base_helpers.has_keys({"destination", "color"}, json_data): return base_helpers.create_json_response( success=False, message="Missing destination or color", status=400, ) destination = json_data["destination"] color = json_data["color"] if not base_helpers.validate_positive_int(color, include_zero=True): return base_helpers.create_json_response( success=False, message="The color is not a non-negative integer", status=400, ) if not isinstance(destination, str): return base_helpers.create_json_response( success=False, message="The destination must be a string", status=400, ) order = Order.objects.create( destination=destination, color=color, status=Order.STATUS_NOT_ACTIVE) return base_helpers.create_json_response( data={"id": order.pk} ) @csrf_exempt @require_POST def update_order(request): # Read json try: json_data = json.loads(request.body) except json.decoder.JSONDecodeError: return base_helpers.create_json_response( success=False, message="Bad JSON", status=400 ) if not base_helpers.has_keys({"id", "new_status"}, json_data): return base_helpers.create_json_response( success=False, message="Missing id or new_status", status=400, ) if not base_helpers.validate_positive_int( json_data["id"], include_zero=True): return base_helpers.create_json_response( success=False, message="Bad id", status=400, ) elif not json_data["new_status"] in Order.STATUS_FLOW: return base_helpers.create_json_response( success=False, message="Bad new_status", status=400, ) new_status = json_data["new_status"] # Find the order try: order = Order.objects.get(pk=int(json_data["id"])) except Order.DoesNotExist: return base_helpers.create_json_response( success=False, message="There is no order with that id", status=400, ) # Only allow changes in this order: # NOT_ACTIVE > ACTIVE > COMPLETED if order.status == Order.STATUS_FLOW[-1]: return base_helpers.create_json_response( success=False, message="The order is already complete", status=400, ) elif new_status - order.status != 1: return base_helpers.create_json_response( success=False, message="Cannot update status beyond 1 step", status=400, ) order.status = new_status order.save() return base_helpers.create_json_response() @csrf_exempt @require_POST def order_status(request): # Read json try: json_data = json.loads(request.body) except json.decoder.JSONDecodeError: return base_helpers.create_json_response( success=False, message="Bad JSON", status=400 ) if "id" not in json_data: return base_helpers.create_json_response( success=False, message="Missing id", status=400, ) if not base_helpers.validate_positive_int( json_data["id"], include_zero=True): return base_helpers.create_json_response( success=False, message="Bad id", status=400, ) # Get the order try: order = Order.objects.get(pk=json_data["id"]) except Order.DoesNotExist: return base_helpers.create_json_response( success=False, message="There is no order with that id", status=400, ) return base_helpers.create_json_response( data={"status": order.status} )
3dcadaa240a921e97bab29a8008a1b83bac8c93d
f3081f31875dc539529d1ef24a6ddedbb1cd5ad3
/website_sale/tests/test_website_sale_cart_recovery.py
ac597616882ce66ce7ca4ffa447974a46ef75571
[]
no_license
babarlhr/human_website_13
5ef144c65c8eb268b40c144e0073d8d2084014ed
e9d68d29959a7df3f56eadebe413556b11957ace
refs/heads/master
2022-11-06T09:02:17.301645
2020-06-21T10:32:16
2020-06-21T10:32:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,475
py
# -*- coding: utf-8 -*- # Part of Eagle. See LICENSE file for full copyright and licensing details. from eagle.tests import tagged from eagle.tests.common import HttpCase, TransactionCase @tagged('post_install', '-at_install') class TestWebsiteSaleCartRecovery(HttpCase): def test_01_info_cart_recovery_tour(self): """The goal of this test is to make sure cart recovery works.""" self.start_tour("/", 'info_cart_recovery', login="portal") @tagged('post_install', '-at_install') class TestWebsiteSaleCartRecoveryServer(TransactionCase): def setUp(self): res = super(TestWebsiteSaleCartRecoveryServer, self).setUp() self.customer = self.env['res.partner'].create({ 'name': 'a', 'email': '[email protected]', }) self.recovery_template_default = self.env.ref('website_sale.mail_template_sale_cart_recovery') self.recovery_template_custom1 = self.recovery_template_default.copy() self.recovery_template_custom2 = self.recovery_template_default.copy() self.website0 = self.env['website'].create({ 'name': 'web0', 'cart_recovery_mail_template_id': self.recovery_template_default.id, }) self.website1 = self.env['website'].create({ 'name': 'web1', 'cart_recovery_mail_template_id': self.recovery_template_custom1.id, }) self.website2 = self.env['website'].create({ 'name': 'web2', 'cart_recovery_mail_template_id': self.recovery_template_custom2.id, }) self.so0 = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website0.id, 'is_abandoned_cart': True, 'cart_recovery_email_sent': False, }) self.so1 = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website1.id, 'is_abandoned_cart': True, 'cart_recovery_email_sent': False, }) self.so2 = self.env['sale.order'].create({ 'partner_id': self.customer.id, 'website_id': self.website2.id, 'is_abandoned_cart': True, 'cart_recovery_email_sent': False, }) return res def test_cart_recovery_mail_template(self): """Make sure that we get the correct cart recovery templates to send.""" self.assertEqual( self.so1._get_cart_recovery_template(), self.recovery_template_custom1, "We do not return the correct mail template" ) self.assertEqual( self.so2._get_cart_recovery_template(), self.recovery_template_custom2, "We do not return the correct mail template" ) # Orders that belong to different websites; we should get the default template self.assertEqual( (self.so1 + self.so2)._get_cart_recovery_template(), self.recovery_template_default, "We do not return the correct mail template" ) def test_cart_recovery_mail_template_send(self): """The goal of this test is to make sure cart recovery works.""" orders = self.so0 + self.so1 + self.so2 self.assertFalse( any(orders.mapped('cart_recovery_email_sent')), "The recovery mail should not have been sent yet." ) self.assertFalse( any(orders.mapped('access_token')), "There should not be an access token yet." ) orders._cart_recovery_email_send() self.assertTrue( all(orders.mapped('cart_recovery_email_sent')), "The recovery mail should have been sent." ) self.assertTrue( all(orders.mapped('access_token')), "All tokens should have been generated." ) sent_mail = {} for order in orders: mail = self.env["mail.mail"].search([ ('record_name', '=', order['name']) ]) sent_mail.update({order: mail}) self.assertTrue( all(len(sent_mail[order]) == 1 for order in orders), "Each cart recovery mail has been sent exactly once." ) self.assertTrue( all(order.access_token in sent_mail[order].body for order in orders), "Each mail should contain the access token of the corresponding SO." )
51a07e0d65cb1b371d2bd13a78da51bcdb23a186
e2e08d7c97398a42e6554f913ee27340226994d9
/pyautoTest-master(ICF-7.5.0)/test_case/scg/scg_OSPF/test_c140943.py
12482ba174a604d783884977f16e6d32bb34b597
[]
no_license
lizhuoya1111/Automated_testing_practice
88e7be512e831d279324ad710946232377fb4c01
b3a532d33ddeb8d01fff315bcd59b451befdef23
refs/heads/master
2022-12-04T08:19:29.806445
2020-08-14T03:51:20
2020-08-14T03:51:20
287,426,498
0
0
null
null
null
null
UTF-8
Python
false
false
1,490
py
import pytest import time import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from page_obj.scg.scg_def_ospf import * from page_obj.scg.scg_def_vlan_interface import * from page_obj.scg.scg_def_bridge import * from page_obj.common.rail import * from page_obj.scg.scg_def_physical_interface import * from page_obj.common.ssh import * from page_obj.scg.scg_def_dhcp import * from page_obj.scg.scg_dev import * from page_obj.scg.scg_def_ifname_OEM import * test_id = 140943 def test_c140943(browser): try: login_web(browser, url=dev1) start_ospf_jyl(browser) time.sleep(0.5) ospf_general_jyl(browser, route_id="manual", manual_ip="192.168.1.1", static="yes", static_num="16777215", save="yes") alert = browser.switch_to_alert() # print(alert.text) web_info = alert.text # print(web_info) # 接受告警 browser.switch_to_alert().accept() ospf_general_jyl(browser, route_id="auto", static="no", save="yes") stop_ospf_jyl(browser) try: assert "输入数字错误" in web_info rail_pass(test_run_id, test_id) except: rail_fail(test_run_id, test_id) assert "输入数字错误" in web_info except Exception as err: # 如果上面的步骤有报错,重新设备,恢复配置 print(err) reload(hostip=dev1) rail_fail(test_run_id, test_id) assert False if __name__ == '__main__': pytest.main(["-v", "-s", "test_c" + str(test_id) + ".py"])
5d635a8b03cfb360411bed2715e152f9905483f0
399dae0b5ad9ca27cde175d25b5435958674eb50
/Script Monitors/Generates Alert if Windows Update is not Downloaded for 60 Days/generates-alert-if-windows-update-is-not-downloaded-for-60-days.py
1cf0fac3bd8feb56d27fbdf8ec5719d79ccc253a
[]
no_license
kannanch/pythonscripts
61e3ea9e8ebf6a6b0ec2a4a829664e4507b803ba
843a522236f9c2cc2aadc68d504c71bb72600bd9
refs/heads/master
2020-06-12T11:18:00.404673
2019-06-28T11:24:37
2019-06-28T11:24:37
194,282,297
1
0
null
2019-06-28T13:55:56
2019-06-28T13:55:56
null
UTF-8
Python
false
false
2,778
py
# The script is a template to check UAC status on device. import os import sys import _winreg def alert(arg): sys.stderr.write("%d%d%d" % (arg, arg, arg)) vbs=r''' Set objSession = CreateObject("Microsoft.Update.Session") Set objSearcher = objSession.CreateUpdateSearcher Set colHistory = objSearcher.QueryHistory(0, 1) For Each objEntry in colHistory Wscript.Echo "Title: " & objEntry.Title Wscript.Echo "Update application date: " & objEntry.Date Next ''' import os import ctypes import re class disable_file_system_redirection: _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection def __enter__(self): self.old_value = ctypes.c_long() self.success = self._disable(ctypes.byref(self.old_value)) def __exit__(self, type, value, traceback): if self.success: self._revert(self.old_value) def runvbs(vbs): workdir=os.environ['PROGRAMDATA']+r'\temp' if not os.path.isdir(workdir): os.mkdir(workdir) with open(workdir+r'\temprun.vbs',"w") as f : f.write(vbs) with disable_file_system_redirection(): output=os.popen('cscript.exe "'+workdir+r'\temprun.vbs"').read() if os.path.isfile(workdir+r'\temprun.vbs'): os.remove(workdir+r'\temprun.vbs') return output output=runvbs(vbs) sam=re.findall("Update\sapplication\sdate:(.*)",output)[0] sam1=sam.split(' ')[1] d1=sam1 import platform ki=platform.platform() if "Windows-8" in ki: print "Win 8" f = d1.split("/") d1=f[1] + "/" + f[0].rjust(2,"0") + "/" + f[2].rjust(2,"0") elif "Windows-10" in ki: print "win 10" if 'PROCESSOR_ARCHITEW6432' in os.environ: f = d1.split("/") d1=f[1] + "/" + f[0].rjust(2,"0") + "/" + f[2].rjust(2,"0") else: f = d1.split("/") d1=f[0] + "/" + f[1].rjust(2,"0") + "/" + f[2].rjust(2,"0") elif "Windows-7" in ki: print "windows 7" f = d1.split("/") d1=f[1] + "/" + f[0].rjust(2,"0") + "/" + f[2].rjust(2,"0") import time d2=time.strftime("%d/%m/%Y") from datetime import datetime date_format = "%d/%m/%Y" date_format1= "%m/%d/%Y" if "Windows-10" in ki: a = datetime.strptime(d1, date_format1) b = datetime.strptime(d2, date_format) delta = b - a else: a = datetime.strptime(d1, date_format) b = datetime.strptime(d2, date_format) delta = b - a print str(delta.days) + " days Since the last update" if delta.days >=60: print "Updates are not working properly" alert(1) else: print "Updates are perfectly working" alert(0)
c2321c30432183d23b15ae143923eaf6ad07ae89
7cdb18e0a7ef01a34ec602bb31aa915c482fcd24
/hujian_api/API_service/Course/c_class.py
3025bce96eba7f43eb8eea3acbd91dd212fd1b56
[]
no_license
wangdan377/Python_API
6adac56974f9c6af238895a3101db0e3f0667ba1
38b31d4d02740d359a7e47fb3a3975045f00288e
refs/heads/master
2023-02-18T14:39:03.009815
2021-01-20T12:59:52
2021-01-20T12:59:52
311,855,608
0
1
null
null
null
null
UTF-8
Python
false
false
2,712
py
import pytest import allure import requests import json import time import random from Common import Post from Common import Get from Common import Assert from Common import Consts class Editor_filter: #登录 def filter_00(self): sessionX = requests.session() post_req = Post.Post() ass = Assert.Assertions() url = 'http://47.99.180.185:3999/login' params = {'username':'[email protected]', 'password':'helloworld'} res = post_req.post_model_b(sessionX, url, params) resCode = res['code'] resText = res['text'] assert ass.assert_code(resCode, 200) assert ass.assert_in_text(resText, '成功') Consts.RESULT_LIST.append('True') return sessionX #获取教程分类列表 def filter_01(self): sessionX = requests.session() get_req = Get.Get() ass = Assert.Assertions() times = int(time.time()) rNumber = random.randint(1,100) url = 'http://47.99.180.185:2999/v1/courses/getProductType?lang=zh_cn&productId=3' res = get_req.get_model_a(sessionX, url) print(res) resCode = res['code'] resText = res['text'] assert ass.assert_code(resCode, 200) assert ass.assert_in_text(resText, '成功') Consts.RESULT_LIST.append('True') #获取分类下教程列表 def filter_02(self,id): sessionX = requests.session() get_req = Get.Get() ass = Assert.Assertions() times = int(time.time()) rNumber = random.randint(1,100) url = 'http://47.99.180.185:2999/v1/music/list?page=1&pageSize=10&albumId='+id res = get_req.get_model_a(sessionX, url) print(res) resCode = res['code'] resText = res['text'] assert ass.assert_code(resCode, 200) assert ass.assert_in_text(resText, '成功') Consts.RESULT_LIST.append('True') #查询教程产品下的说明书 def filter_03(self): sessionX = requests.session() get_req = Get.Get() ass = Assert.Assertions() times = int(time.time()) rNumber = random.randint(1,100) url = 'http://47.99.180.185:2999/v1/music/hot/list?page=1&pageSize=10' res = get_req.get_model_a(sessionX, url) print(res) resCode = res['code'] resText = res['text'] assert ass.assert_code(resCode, 200) assert ass.assert_in_text(resText, '成功') Consts.RESULT_LIST.append('True') #查询投放的教程产品 #模糊查询分类 #分类下视频获取 #获取zfilm首页展示分类列表 if __name__ == '__main__': a = Editor_filter() a.filter_02('62')
72a060428592795437ae3329b7ec56762c28a05b
7275f7454ce7c3ce519aba81b3c99994d81a56d3
/Programming-Collective-Intelligence/ch07/main.py
cea965bec22a5c20cdc4081bc9c0948547ffe229
[]
no_license
chengqiangaoci/back
b4c964b17fb4b9e97ab7bf0e607bdc13e2724f06
a26da4e4f088afb57c4122eedb0cd42bb3052b16
refs/heads/master
2020-03-22T08:36:48.360430
2018-08-10T03:53:55
2018-08-10T03:53:55
139,777,994
0
1
null
null
null
null
UTF-8
Python
false
false
1,135
py
import treepredict # main function # print('<----DivideSet---->') # for item in treepredict.divideset(treepredict.my_data, 2, 'yes'): # print(item) # print('\n<----Build and Display the Tree---->') tree = treepredict.buildtree(treepredict.my_data) treepredict.printtree(tree) # # print('\n<----Graphical Display---->') # path = 'output/treeview.jpg' # treepredict.drawtree(tree, jpeg=path) # print("picture has been saved in " + path) # # print('\n<----Classify and prune---->') # test = ['(direct)', 'USA', 'yes', 5] # print(test) # print(treepredict.classify(test, tree), '\n') # # print('Before pune:') # treepredict.printtree(tree) # treepredict.prune(tree, 1.0) # print('\nAfter pune:') # treepredict.printtree(tree) # print('<----Zillow API---->') # import zillow # # housedata = zillow.getpricelist() # # print('house data saved!') # housedata = zillow.getdata('input/housedata.txt') # print('house data read!') # housetree = treepredict.buildtree(housedata, scoref=treepredict.variance) # treepredict.printtree(housetree) # treepredict.drawtree(housetree, 'output/housetree.jpg') # HotOrNot API is deprecated since 2008
ada9eb0e3ce075ebc01f1203fd530aaf833dafc4
4bdb8e324a833c10380bb7b1f436d1e9629c873c
/Ekeopara_Praise/Phase 1/Python Basic 1/Day2 Tasks/Task 5.py
1d1d5cde955ffa3a4b7be09d0ba0fa45cd7803f2
[ "MIT" ]
permissive
dreamchild7/python-challenge-solutions
e3831a57447f6132dd098be8b941cc27db92ace2
29e2ca780e86fc8a3e9d4def897c26bfa6d6493d
refs/heads/master
2022-11-08T17:23:57.763110
2020-06-19T08:38:20
2020-06-19T08:38:20
263,923,130
0
0
MIT
2020-05-14T13:29:33
2020-05-14T13:29:32
null
UTF-8
Python
false
false
253
py
#5. Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them. f_name = str(input("Enter your first name: ")) l_name = str(input("Enter your last name: ")) print(f"{l_name} {f_name}")
186c553da83db53ac91681c5d1650c41cc85b315
c4702d1a06640555829b367852138cc93ba4a161
/dym_work_order/report/dym_work_order_wip_report.py
5f8b0c3e31094e8bc280dd6611091fac61612f93
[]
no_license
Rizalimami/dym
0ecadf9c049b22ebfebf92e4eab6eaad17dd3e26
af1bcf7b77a3212bc8a8a0e41e6042a134587ed4
refs/heads/master
2020-04-08T10:56:43.605698
2018-11-27T06:44:08
2018-11-27T06:44:08
159,287,876
0
2
null
null
null
null
UTF-8
Python
false
false
2,475
py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import osv from openerp.report import report_sxw class dym_work_order_wip(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(dym_work_order_wip, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'get_pricelist': self._get_pricelist, 'lines_a': self._lines_a, 'no_urut': self.no_urut, }) self.no = 0 def no_urut(self): self.no+=1 return self.no def _get_pricelist(self, pricelist_id): pricelist = self.pool.get('product.pricelist').read(self.cr, self.uid, [pricelist_id], ['name'], context=self.localcontext)[0] return pricelist['name'] def _lines_a(self, accounts): self.cr.execute("SELECT wo.name as name, wo.date as date, wo.no_pol as no_pol, wo.type as type, wo.state as state, wo.state_wo as state_wo, emp.name_related as mekanik_name from dym_work_order wo left join hr_employee emp on wo.mekanik_id = emp.id where state !='draft' and state !='done'") res = self.cr.dictfetchall() return res class report_dym_work_order_wip(osv.AbstractModel): _name = 'report.dym_work_order.dym_work_order_wip_report' _inherit = 'report.abstract_report' _template = 'dym_work_order.dym_work_order_wip_report' _wrapped_report_class = dym_work_order_wip # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
753ad43022f7a3191bb72fa131af59d5a1d65fe8
b92fb53a2bebb8fd534258666b5ac9b9703af44b
/backend/home/migrations/0002_load_initial_data.py
64a22060ef08f587e02ba57b0fdf868eb35edced
[]
no_license
crowdbotics-apps/my-books-17969
7d017780d7c51210820d153dcab35e1196cb9652
3f4f66c998bce11289b1fd2bdd74d2cf769cc2f0
refs/heads/master
2022-10-07T11:09:54.346439
2020-06-09T18:14:21
2020-06-09T18:14:21
271,076,921
0
0
null
null
null
null
UTF-8
Python
false
false
1,286
py
from django.db import migrations def create_customtext(apps, schema_editor): CustomText = apps.get_model("home", "CustomText") customtext_title = "My Books" CustomText.objects.create(title=customtext_title) def create_homepage(apps, schema_editor): HomePage = apps.get_model("home", "HomePage") homepage_body = """ <h1 class="display-4 text-center">My Books</h1> <p class="lead"> This is the sample application created and deployed from the Crowdbotics app. You can view list of packages selected for this application below. </p>""" HomePage.objects.create(body=homepage_body) def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "my-books-17969.botics.co" site_params = { "name": "My Books", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration): dependencies = [ ("home", "0001_initial"), ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_customtext), migrations.RunPython(create_homepage), migrations.RunPython(create_site), ]
dc757c59fdf8ee93aa9bf252e1823c13c8c21ba9
9bd82e484b3d32c4059ef57dec70e64bced8dde7
/OTB/OTB/pipelines.py
693eeb3a38760be718dbda4b5478b7a5cebc9419
[ "MIT" ]
permissive
houzw/knowledge-base-data
8a4df88558edcc5fcc25bac82788c6eb96119854
60771e8bf300227e1a26c9e77f56b09d23acd64a
refs/heads/master
2021-06-02T02:28:09.624790
2020-10-21T07:02:26
2020-10-21T07:02:26
148,170,033
0
1
null
null
null
null
UTF-8
Python
false
false
284
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class OtbPipeline(object): def process_item(self, item, spider): return item
e16b8c9808ebc38687cf672a338a6f901cd42936
9f1039075cc611198a988034429afed6ec6d7408
/tensorflow-stubs/contrib/framework/python/framework/checkpoint_utils.pyi
e6e501dad7d3fcdf5bcb59bd42acdb9afc2b5d9c
[]
no_license
matangover/tensorflow-stubs
9422fbb1cb3a3638958d621461291c315f9c6ec2
664bd995ef24f05ba2b3867d979d23ee845cb652
refs/heads/master
2020-05-23T12:03:40.996675
2019-05-15T06:21:43
2019-05-15T06:21:43
186,748,093
0
0
null
null
null
null
UTF-8
Python
false
false
650
pyi
# Stubs for tensorflow.contrib.framework.python.framework.checkpoint_utils (Python 3) # # NOTE: This dynamically typed stub was automatically generated by stubgen. from tensorflow.python.ops import io_ops as io_ops, state_ops as state_ops, variables as variables from tensorflow.python.platform import gfile as gfile from tensorflow.python.training import checkpoint_management as checkpoint_management from typing import Any as Any def load_checkpoint(filepattern: Any): ... def load_variable(checkpoint_dir: Any, name: Any): ... def list_variables(checkpoint_dir: Any): ... def init_from_checkpoint(checkpoint_dir: Any, assignment_map: Any): ...
22a0ca8e1e08f8516eb0a7d34b276c7390c35474
c15a28ae62eb94dbf3ed13e2065195e572a9988e
/Cook book/src/8/lazily_computed_attributes/example1.py
a872f26e188323bd9e96e4b786016ffff9d9d6d8
[]
no_license
xuyuchends1/python
10798c92840a1a59d50f5dc5738b2881e65f7865
545d950a3d2fee799902658e8133e3692939496b
refs/heads/master
2021-01-25T07:07:04.812140
2020-02-28T09:25:15
2020-02-28T09:25:15
93,647,064
0
0
null
null
null
null
UTF-8
Python
false
false
704
py
class lazyproperty: def __init__(self, func): self.func = func def __get__(self, instance, cls): if instance is None: return self else: value = self.func(instance) setattr(instance, self.func.__name__, value) return value if __name__ == '__main__': import math class Circle: def __init__(self, radius): self.radius = radius @lazyproperty def area(self): print('Computing area') return math.pi * self.radius ** 2 @lazyproperty def perimeter(self): print('Computing perimeter') return 2 * math.pi * self.radius
82303825a36ae127081f7c965f2fa948b36e6fcc
d7ae8db44b31de83eabaf0e286b1452d4ada24ff
/IoT_Domain_Analyst_ECE_3502/Lab_3/Linear_Regression.py
524229a56949837e42e249dd6a58236604882ea0
[ "CC0-1.0" ]
permissive
eshan5/VIT-Labs
ae4c6719b86fb5e2f30e0f5a023171597cf33d42
5a20b9571a10b4550b886d588969592e595dac1d
refs/heads/main
2023-08-24T06:50:23.888426
2021-10-09T10:18:32
2021-10-09T10:18:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
798
py
import numpy as np from sklearn.linear_model import LinearRegression x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1)) y = np.array([5, 20, 14, 32, 22, 38]) print(x) print(y) model = LinearRegression().fit(x, y) r_sq = model.score(x, y) print('coefficient of determination:', r_sq) print('intercept:', model.intercept_) print('slope:', model.coef_) """new_model = LinearRegression().fit(x, y.reshape((-1, 1))) print('intercept:', new_model.intercept_) print('slope:', new_model.coef_) y_pred = model.predict(x) print('predicted response:', y_pred, sep='\n') y_pred = model.intercept_ + model.coef_ * x print('predicted response:', y_pred, sep='\n') x_new = np.arange(5).reshape((-1, 1)) print(" First few points of the line :") print(x_new) y_new = model.predict(x_new) print(y_new)"""
1882e6bd42af8f728c9d7796b25c44164b46c8a0
d2915ef6ee9c1ea01f47d3468bba8e320a8f5914
/design_patterns/behavioural/template_method.py
b4d81ca7739be92fcbe5d17b1a54a35d7cf159d6
[]
no_license
asing177/python_basics
a269adbaf166fb760d2692874601528ef230bbbd
48ce7d5d6356edbd9bc21f8ebb55ec95787d4340
refs/heads/main
2023-01-11T12:11:44.155102
2020-11-13T07:24:54
2020-11-13T07:24:54
300,806,395
0
0
null
null
null
null
UTF-8
Python
false
false
3,123
py
from test_abc import ABC, abstractmethod class AbstractClass(ABC): """ The Abstract Class defines a template method that contains a skeleton of some algorithm, composed of calls to (usually) abstract primitive operations. Concrete subclasses should implement these operations, but leave the template method itself intact. """ def template_method(self) -> None: """ The template method defines the skeleton of an algorithm. """ self.base_operation1() self.required_operations1() self.base_operation2() self.hook1() self.required_operations2() self.base_operation3() self.hook2() # These operations already have implementations. def base_operation1(self) -> None: print("AbstractClass says: I am doing the bulk of the work") def base_operation2(self) -> None: print("AbstractClass says: But I let subclasses override some operations") def base_operation3(self) -> None: print("AbstractClass says: But I am doing the bulk of the work anyway") # These operations have to be implemented in subclasses. @abstractmethod def required_operations1(self) -> None: pass @abstractmethod def required_operations2(self) -> None: pass # These are "hooks." Subclasses may override them, but it's not mandatory # since the hooks already have default (but empty) implementation. Hooks # provide additional extension points in some crucial places of the # algorithm. def hook1(self) -> None: pass def hook2(self) -> None: pass class ConcreteClass1(AbstractClass): """ Concrete classes have to implement all abstract operations of the base class. They can also override some operations with a default implementation. """ def required_operations1(self) -> None: print("ConcreteClass1 says: Implemented Operation1") def required_operations2(self) -> None: print("ConcreteClass1 says: Implemented Operation2") class ConcreteClass2(AbstractClass): """ Usually, concrete classes override only a fraction of base class' operations. """ def required_operations1(self) -> None: print("ConcreteClass2 says: Implemented Operation1") def required_operations2(self) -> None: print("ConcreteClass2 says: Implemented Operation2") def hook1(self) -> None: print("ConcreteClass2 says: Overridden Hook1") def client_code(abstract_class: AbstractClass) -> None: """ The client code calls the template method to execute the algorithm. Client code does not have to know the concrete class of an object it works with, as long as it works with objects through the interface of their base class. """ # ... abstract_class.template_method() # ... if __name__ == "__main__": print("Same client code can work with different subclasses:") client_code(ConcreteClass1()) print("") print("Same client code can work with different subclasses:") client_code(ConcreteClass2())
1d4a7962f047e1507edd5b010afde2fc751120b8
e400d4a141f35bc4240293253048535f1e737d4e
/src/03_IPhreeqcPy/02_phreeqc_mixing_CSH.py
0ef9294bb86ad1f2be65ad009b6c572debf6e331
[]
no_license
annavarzina/carbonation
94416935f92cdfb1874c61407c8d1909178bd6c9
030b222f000d79538e9890fb9047d57ced7bad2d
refs/heads/master
2021-06-23T07:33:20.147869
2021-03-02T13:29:34
2021-03-02T13:29:34
193,922,887
0
1
null
null
null
null
UTF-8
Python
false
false
3,356
py
import numpy as np import matplotlib.pylab as plt from mixing import PhreeqcMixing from kinetics import PhreeqcKinetics class PhreeqcMixingCSH(PhreeqcMixing): def __init__(self, n, fraction, csh, database): self.phase = csh['name'] self.csh = csh self.steps = n self.fraction = fraction self.database = database self.phrqc_input = [] self.selected_output = [] self.phrqc_string = '' self.simulation_time = 0 def generate_phrqc_string(self): self.phases() self.solution_1() self.solution_2() for i in np.arange(0, self.steps): self.mix_2() self.selected_output_1() self.user_punch() self.mix_3() self.phrqc_string = '\n'.join(self.phrqc_input) def phases(self): phrqc_input = [] # CSH stochiometry s = self.csh['stochiometry'] h = s['H+'] h2o = s['H2O'] + s['H+'] - s['Ca'] sign1 = '+' if h < 0: sign1 = '-' h *= -1 sign2 = '+' if h2o < 0: sign2 = '-' h2o *= -1 # input phrqc_input.append('PHASES') phrqc_input.append(self.phase) phrqc_input.append('\t(CaO)' + str(s['Ca']) +'(SiO2)'+ str(s['Si']) + \ '(H2O)' + str(s['H2O']) + ' ' + sign1 + ' ' + str(h) + 'H+ = ' + \ str(s['Ca']) + 'Ca+2 + ' + str(s['Si']) + 'SiO2 ' + sign2 +\ ' ' + str(h2o) + ' H2O') #phrqc_input.append('\t-Vm\t' + str(csh['vm']) ) phrqc_input.append('\t-log_K\t' + str(self.csh['log_k']) + '\n') self.phrqc_input += phrqc_input def user_punch(self): phrqc_input = [] phrqc_input.append('USER_PUNCH') phrqc_input.append('\t-headings\tCa\t' + self.phase) phrqc_input.append('\t-start') phrqc_input.append('\t10\tpunch\ttot("Ca")') phrqc_input.append('\t15\tpunch\ttot("Si")') phrqc_input.append('\t20\tpunch\ttot("' + self.phase + '")') phrqc_input.append('\t30\tpunch') phrqc_input.append('\t-end') phrqc_input.append('END') self.phrqc_input += phrqc_input #%% PARAMETERS database = 'C:\Anaconda2\lib\site-packages\databases\cemdata18.dat' csh = {'name':'CSH', 'stochiometry':{'Ca':1.67, 'Si':1.0, 'H2O':4.34, 'H+':3.34}, 'log_k':29.133,} n = 400000 # time should be ~10 minutes krate = 10**(-8.0) #1e-7 s = 800#scale factor fraction = krate * s print('Kinetic rate = ' + str(krate)) print('Mixing fraction = ' + str(fraction)) #%% RUN pm = PhreeqcMixingCSH(n, fraction, csh, database) pm.run_phreeqc() print('Mixing fraction simulation time = ' + str(pm.simulation_time)) #%% PLOT h = 1 t = range(1, n+1) t = [i/3600. for i in t] ca_m = [] si_m = [] for i in range(len(pm.selected_output)): if pm.selected_output[i][0]==3: ca_m.append(pm.selected_output[i][1]) si_m.append(pm.selected_output[i][2]) plt.figure() plt.plot(t, ca_m, label = "mix") plt.xlabel('time (h)') plt.ylabel('Ca (mol/l)') plt.legend() plt.figure() plt.plot(t, si_m, label = "mix") plt.xlabel('time (h)') plt.ylabel('Si (mol/l)') plt.legend() plt.show()
913e406199d7adf3fcacb33850752f52a57881fa
69e5f24fa12346f892b1c907e802286045b3641f
/train.py
c17b2ccaaaaae82b11f58306d9b719d7f6098609
[]
no_license
hope-yao/failed_adversarial_training
0cf9d05333767756134db1eb8ea2424ace8449c9
be87e05b59aaeecec9001c1d6ae69afcf9382c1d
refs/heads/master
2020-04-01T19:04:32.433080
2018-10-17T22:39:48
2018-10-17T22:39:48
153,532,414
0
0
null
null
null
null
UTF-8
Python
false
false
5,181
py
"""Trains a model, saving checkpoints and tensorboard summaries along the way.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import json import os import shutil from timeit import default_timer as timer import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data from model import Model from pgd_attack import LinfPGDAttack with open('config.json') as config_file: config = json.load(config_file) # Setting up training parameters tf.set_random_seed(config['random_seed']) max_num_training_steps = config['max_num_training_steps'] num_output_steps = config['num_output_steps'] num_summary_steps = config['num_summary_steps'] num_checkpoint_steps = config['num_checkpoint_steps'] batch_size = config['training_batch_size'] # Setting up the data and the model mnist = input_data.read_data_sets('MNIST_data', one_hot=False) global_step = tf.contrib.framework.get_or_create_global_step() model = Model() # Setting up the optimizer train_step = tf.train.AdamOptimizer(1e-4).minimize(model.xent, global_step=global_step) # Set up adversary attack = LinfPGDAttack(model, config['epsilon'], config['k'], config['a'], config['random_start'], config['loss_func']) # Setting up the Tensorboard and checkpoint outputs model_dir = config['model_dir'] if not os.path.exists(model_dir): os.makedirs(model_dir) # We add accuracy and xent twice so we can easily make three types of # comparisons in Tensorboard: # - train vs eval (for a single run) # - train of different runs # - eval of different runs saver = tf.train.Saver(max_to_keep=3) tf.summary.scalar('accuracy adv train', model.accuracy) tf.summary.scalar('accuracy adv', model.accuracy) tf.summary.scalar('xent adv train', model.xent / batch_size) tf.summary.scalar('xent adv', model.xent / batch_size) tf.summary.image('images adv train', model.x_image) merged_summaries = tf.summary.merge_all() shutil.copy('config.json', model_dir) with tf.Session() as sess: # Initialize the summary writer, global variables, and our time counter. summary_writer = tf.summary.FileWriter(model_dir, sess.graph) sess.run(tf.global_variables_initializer()) # saver.restore(sess,'/home/hope-yao/Documents/madrys_code/mnist_challenge/models/a_very_robust_model_run2/checkpoint-99900') training_time = 0.0 # Main training loop for ii in range(max_num_training_steps): if ii%10000 == 0: num_adv_batch = 1000 x_pool_nat = np.zeros((num_adv_batch * batch_size, 784)) x_pool_adv = np.zeros((num_adv_batch * batch_size, 784)) y_pool = np.zeros((num_adv_batch * batch_size)) from tqdm import tqdm for jj in tqdm(range(num_adv_batch)): x_batch, y_batch = mnist.train.next_batch(batch_size) x_batch_adv = attack.perturb(x_batch, y_batch, sess) x_pool_nat[jj * batch_size:(jj + 1) * batch_size] = x_batch x_pool_adv[jj * batch_size:(jj + 1) * batch_size] = x_batch_adv y_pool[jj * batch_size:(jj + 1) * batch_size] = y_batch np.save('x_pool_adv_itr{}'.format(ii), x_pool_adv) np.save('x_pool_nat_itr{}'.format(ii), x_pool_nat) np.save('y_pool_itr{}'.format(ii), y_pool) # x_batch, y_batch = mnist.train.next_batch(batch_size) # # Compute Adversarial Perturbations # start = timer() # x_batch_adv = attack.perturb(x_batch, y_batch, sess) # end = timer() # training_time += end - start x_batch = x_pool_nat[ii%1000 * batch_size:(ii%1000 + 1) * batch_size] x_batch_adv = x_pool_adv[ii%1000 * batch_size:(ii%1000 + 1) * batch_size] y_batch = y_pool[ii%1000 * batch_size:(ii%1000 + 1) * batch_size] nat_dict = {model.x_input: x_batch, model.y_input: y_batch} adv_dict = {model.x_input: x_batch_adv, model.y_input: y_batch} # Output to stdout if ii % num_output_steps == 0: nat_acc = sess.run(model.accuracy, feed_dict=nat_dict) adv_acc = sess.run(model.accuracy, feed_dict=adv_dict) print('Step {}: ({})'.format(ii, datetime.now())) print(' training nat accuracy {:.4}%'.format(nat_acc * 100)) print(' training adv accuracy {:.4}%'.format(adv_acc * 100)) if ii != 0: print(' {} examples per second'.format( num_output_steps * batch_size / training_time)) training_time = 0.0 # Tensorboard summaries if ii % num_summary_steps == 0: summary = sess.run(merged_summaries, feed_dict=adv_dict) summary_writer.add_summary(summary, global_step.eval(sess)) # Write a checkpoint if ii % num_checkpoint_steps == 0: saver.save(sess, os.path.join(model_dir, 'checkpoint'), global_step=global_step) # Actual training step start = timer() for jj in range(5): sess.run(train_step, feed_dict=adv_dict) end = timer() training_time += end - start
03fa270be63af49d803b50f06e2f566610bf1159
1c962341f3b580f2be0529a2d5804d49804470f6
/judge_2152.py
a4cdbad8d0c1c0d6e41d3a7a54609469d3035777
[]
no_license
andersonmarquees/-uri_python
7bc14b50198bd238f9594b37a86553ecfb277f76
379518cd17433725d6a859526de356162b26aa40
refs/heads/master
2020-05-05T09:08:51.483638
2019-04-14T16:42:24
2019-04-14T16:42:24
179,892,376
0
0
null
null
null
null
UTF-8
Python
false
false
1,090
py
n = int(input()) while n > 0: number = list(map(int, input().split())) if number[2] == 0 and number[0] >= 10 and number[1] >= 10: print("{}:{} - A porta fechou!".format(number[0], number[1])) elif number[2] == 1 and number[0] >= 10 and number[1] >= 10: print("{}:{} - A porta abriu!".format(number[0], number[1])) elif number[2] == 0 and number[0] < 10 and number[1] < 10: print("0{}:0{} - A porta fechou!".format(number[0], number[1])) elif number[2] == 1 and number[0] < 10 and number[1] < 10: print("0{}:0{} - A porta abriu!".format(number[0], number[1])) elif number[2] == 0 and number[0] < 10: print("0{}:{} - A porta fechou!".format(number[0], number[1])) elif number[2] == 1 and number[0] < 10: print("0{}:{} - A porta abriu!".format(number[0], number[1])) elif number[2] == 0 and number[1] < 10: print("{}:0{} - A porta fechou!".format(number[0], number[1])) elif number[2] == 1 and number[1] < 10: print("{}:0{} - A porta abriu!".format(number[0], number[1])) n -= 1
284deb502b460d18389044ea5103890c7f6686d0
01a8c5ecea9cb4d40d3e26a1ca08cb1ccc17e98a
/common/prep_terrain_data.py
a35188d77e0eab7d0ba710f5dbfa6d1addca21c6
[]
no_license
pelinbalci/intro_to_ml
fe570cfe5a556cdd55fccabd1f7096b42124a7a7
450ba3cff7d3f2009d94a526527ed76fee6e1fdf
refs/heads/master
2022-11-15T04:22:29.372686
2020-07-12T10:13:05
2020-07-12T10:13:05
277,359,558
1
0
null
null
null
null
UTF-8
Python
false
false
1,825
py
#!/usr/bin/python import random def makeTerrainData(n_points=1000): """make the toy dataset """ random.seed(42) grade = [random.random() for i in range(0, n_points)] #[0.63, 0.025, 0.275, 0.223, 0.736, 0.676, 0.89, 0.085, 0.42, 0.029] bumpy = [random.random() for i in range(0, n_points)] #[0.218, 0.50, 0.026, 0.19, 0.649, 0.54, 0.22, 0.58, 0.809, 0.006] error = [random.random() for i in range(0, n_points)] y = [round(grade[i]*bumpy[i]+0.3+0.1*error[i]) for i in range(0, n_points)] #[1, 0, 0, 0, 1, 1, 1, 0, 1, 0] for i in range(0, len(y)): if grade[i] > 0.8 or bumpy[i] > 0.8: y[i] = 1.0 # <class 'list'>: [1, 0, 0, 0, 1, 1, 1.0, 0, 1.0, 0] # split into train/test sets X = [[gg, ss] for gg, ss in zip(grade, bumpy)] split = int(0.75 * n_points) X_train = X[0:split] # [[0.63, 0.218], [0.025, 0.50] ... ] X_test = X[split:] y_train = y[0:split] # [1, 0, 0, 0, 1, 1, 1.0] y_test = y[split:] grade_sig = [X_train[i][0] for i in range(0, len(X_train)) if y_train[i] == 0] bumpy_sig = [X_train[i][1] for i in range(0, len(X_train)) if y_train[i] == 0] grade_bkg = [X_train[i][0] for i in range(0, len(X_train)) if y_train[i] == 1] bumpy_bkg = [X_train[i][1] for i in range(0, len(X_train)) if y_train[i] == 1] grade_sig = [X_test[i][0] for i in range(0, len(X_test)) if y_test[i] == 0] bumpy_sig = [X_test[i][1] for i in range(0, len(X_test)) if y_test[i] == 0] grade_bkg = [X_test[i][0] for i in range(0, len(X_test)) if y_test[i] == 1] bumpy_bkg = [X_test[i][1] for i in range(0, len(X_test)) if y_test[i] == 1] test_data = {"fast": {"grade": grade_sig, "bumpiness": bumpy_sig}, "slow": {"grade": grade_bkg, "bumpiness": bumpy_bkg}} return X, y, X_train, y_train, X_test, y_test
c39cc5dda80f909656f9411ff1e0ff395f66ea2f
9da0798b6f309d2274c65077efa81c3766b78051
/SearchQuery.py
398bb743fac51257f35f8c955e13f286be2efd41
[]
no_license
theriley106/RandomSearchQuery
09b37c23c3798b873c45db529158b326410d759e
e084a1a63279994fe06ef8dd594d2bc8e1d7b445
refs/heads/master
2021-01-13T04:57:56.583001
2017-02-07T05:04:07
2017-02-07T05:04:07
81,155,360
0
0
null
null
null
null
UTF-8
Python
false
false
254
py
import random import csv QueryList = open('QueryList.csv', 'r') QueryList = csv.reader(QueryList) QueryList = [row for row in QueryList] QueryList = [l[0] for l in QueryList] def Random(): return random.choice(QueryList) def Multi(): return QueryList
4a13e69ae72231f2bbbeccfef203a95165134ed0
98fd3275aa34c90c26d1f43d70983ae762c69064
/floor_division.py
1f092bde43f669fac26bc9d825a9243c8393537d
[]
no_license
hasnatosman/problem_solving
62b5eaf6a418ae7f75d187b2c8e1e4b0ab4750fd
1f33acc6289d322a9e950b6e39185a505159b7e2
refs/heads/main
2023-06-17T05:34:33.908078
2021-07-15T06:36:45
2021-07-15T06:36:45
383,810,211
0
0
null
null
null
null
UTF-8
Python
false
false
572
py
""" PROBLEM 4: Find the floor division of two numbers. HINTS: Just use two // instead of one. """ num1 = int(input('Enter the first number: ')) num2 = int(input('Enter the second number: ')) result = num1 // num2 print("Result is: ", result) """ Explanation: When you divide one number by another you get two things. One is called the integer part of the division. Another is the remainder. To get the quotient (result without the remainder), you can use two-division symbols. """ """ import math result = math.floor(3.4) print(result) """
c52b322c1c1fb0464674ec1211c34b90dcd6b4b1
24fe1f54fee3a3df952ca26cce839cc18124357a
/servicegraph/lib/python2.7/site-packages/acimodel-4.0_3d-py2.7.egg/cobra/modelimpl/eqptdiag/entity.py
86ae5c47a213aa5ec2540a9fb905cafd8a5403b0
[]
no_license
aperiyed/servicegraph-cloudcenter
4b8dc9e776f6814cf07fe966fbd4a3481d0f45ff
9eb7975f2f6835e1c0528563a771526896306392
refs/heads/master
2023-05-10T17:27:18.022381
2020-01-20T09:18:28
2020-01-20T09:18:28
235,065,676
0
0
null
2023-05-01T21:19:14
2020-01-20T09:36:37
Python
UTF-8
Python
false
false
6,254
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2019 Cisco Systems, Inc. All rights reserved # written by zen warriors, do not modify! # ********************************************************************** from cobra.mit.meta import ClassMeta from cobra.mit.meta import StatsClassMeta from cobra.mit.meta import CounterMeta from cobra.mit.meta import PropMeta from cobra.mit.meta import Category from cobra.mit.meta import SourceRelationMeta from cobra.mit.meta import NamedSourceRelationMeta from cobra.mit.meta import TargetRelationMeta from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory from cobra.model.category import MoCategory, PropCategory, CounterCategory from cobra.mit.mo import Mo # ################################################## class Entity(Mo): """ Diag-related entity information """ meta = ClassMeta("cobra.model.eqptdiag.Entity") meta.moClassName = "eqptdiagEntity" meta.rnFormat = "diag" meta.category = MoCategory.REGULAR meta.label = "Equipment Diagnostics Entity" meta.writeAccessMask = 0x880080000000001 meta.readAccessMask = 0x880080000000001 meta.isDomainable = False meta.isReadOnly = True meta.isConfigurable = False meta.isDeletable = False meta.isContextRoot = False meta.childClasses.add("cobra.model.health.Inst") meta.childClasses.add("cobra.model.fault.Counts") meta.childClasses.add("cobra.model.eqptdiagp.GrpTests") meta.childClasses.add("cobra.model.eqptdiag.Rule") meta.childNamesAndRnPrefix.append(("cobra.model.eqptdiagp.GrpTests", "grptests-")) meta.childNamesAndRnPrefix.append(("cobra.model.fault.Counts", "fltCnts")) meta.childNamesAndRnPrefix.append(("cobra.model.health.Inst", "health")) meta.childNamesAndRnPrefix.append(("cobra.model.eqptdiag.Rule", "rule-")) meta.parentClasses.add("cobra.model.top.System") meta.superClasses.add("cobra.model.nw.Conn") meta.superClasses.add("cobra.model.nw.CpEntity") meta.superClasses.add("cobra.model.nw.Item") meta.superClasses.add("cobra.model.nw.GEp") meta.rnPrefixes = [ ('diag', False), ] prop = PropMeta("str", "adminSt", "adminSt", 3670, PropCategory.REGULAR) prop.label = "Admin State" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 1 prop.defaultValueStr = "enabled" prop._addConstant("disabled", "disabled", 2) prop._addConstant("enabled", "enabled", 1) meta.props.add("adminSt", prop) prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("deleteAll", "deleteall", 16384) prop._addConstant("deleteNonPresent", "deletenonpresent", 8192) prop._addConstant("ignore", "ignore", 4096) meta.props.add("childAction", prop) prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN) prop.label = "None" prop.isDn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("dn", prop) prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "local" prop._addConstant("implicit", "implicit", 4) prop._addConstant("local", "local", 0) prop._addConstant("policy", "policy", 1) prop._addConstant("replica", "replica", 2) prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3) meta.props.add("lcOwn", prop) prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "never" prop._addConstant("never", "never", 0) meta.props.add("modTs", prop) prop = PropMeta("str", "monPolDn", "monPolDn", 14498, PropCategory.REGULAR) prop.label = "Monitoring policy attached to this observable object" prop.isImplicit = True prop.isAdmin = True meta.props.add("monPolDn", prop) prop = PropMeta("str", "name", "name", 3669, PropCategory.REGULAR) prop.label = "Name" prop.isConfig = True prop.isAdmin = True prop.isCreateOnly = True prop.range = [(1, 128)] meta.props.add("name", prop) prop = PropMeta("str", "operErr", "operErr", 3672, PropCategory.REGULAR) prop.label = "Operational Errors Qualifier" prop.isOper = True prop._addConstant("feature-unsupported", "feature-unsupported", 64) prop._addConstant("init-err", "initialization-error", 1) prop._addConstant("int-err", "internal-error", 8) prop._addConstant("ipc-err", "ipc-error", 4) prop._addConstant("mem-err", "memory-error", 2) prop._addConstant("proto-err", "protocol-error", 32) prop._addConstant("sock-err", "socket-error", 16) meta.props.add("operErr", prop) prop = PropMeta("str", "operSt", "operSt", 3671, PropCategory.REGULAR) prop.label = "Operational State" prop.isOper = True prop.defaultValue = 1 prop.defaultValueStr = "enabled" prop._addConstant("disabled", "disabled", 2) prop._addConstant("enabled", "enabled", 1) prop._addConstant("failed", "failed", 4) prop._addConstant("initializing", "initializing", 3) prop._addConstant("unknown", "unknown", 0) meta.props.add("operSt", prop) prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN) prop.label = "None" prop.isRn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("rn", prop) prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("created", "created", 2) prop._addConstant("deleted", "deleted", 8) prop._addConstant("modified", "modified", 4) meta.props.add("status", prop) def __init__(self, parentMoOrDn, markDirty=True, **creationProps): namingVals = [] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
7f78ff3bbfee0ec659df2d2fe6639af9fe66f59b
72b00923d4aa11891f4a3038324c8952572cc4b2
/python/datastruct/dd_oob/pgm06_13.txt
68d0a171c8d350cdcfdc58f5ebe0b45790150e1e
[]
no_license
taowuwen/codec
3698110a09a770407e8fb631e21d86ba5a885cd5
d92933b07f21dae950160a91bb361fa187e26cd2
refs/heads/master
2022-03-17T07:43:55.574505
2022-03-10T05:20:44
2022-03-10T05:20:44
87,379,261
0
0
null
2019-03-25T15:40:27
2017-04-06T02:50:54
C
UTF-8
Python
false
false
1,058
txt
# # This file contains the Python code from Program 6.13 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm06_13.txt # class QueueAsArray(Queue): def getHead(self): if self._count == 0: raise ContainerEmpty return self._array[self._head] def enqueue(self, obj): if self._count == len(self._array): raise ContainerFull self._tail = self._tail + 1 if self._tail == len(self._array): self._tail = 0 self._array[self._tail] = obj self._count += 1 def dequeue(self): if self._count == 0: raise ContainerEmpty result = self._array[self._head] self._array[self._head] = None self._head = self._head + 1 if self._head == len(self._array): self._head = 0 self._count -= 1 return result # ...
1ddbfb75321c4a6c9628325701f965d26cc4ace3
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03254/s765346849.py
33081586b65e211540fb56775a50c4be338f79f8
[]
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
198
py
n, x = map(int, input().split()) a = list(map(int, input().split())) a.sort() ans = 0 for i in range(n-1): if x >= a[i]: x -= a[i] ans += 1 if x == a[-1]: ans += 1 print(ans)
4219a4b68fda829e5ffe9f53e3fc479e6f4e4f2f
26f6313772161851b3b28b32a4f8d255499b3974
/Python/PseudoPalindromicPathsinaBinaryTree.py
f55438ead603aea16a74885f9461cc385a4c486d
[]
no_license
here0009/LeetCode
693e634a3096d929e5c842c5c5b989fa388e0fcd
f96a2273c6831a8035e1adacfa452f73c599ae16
refs/heads/master
2023-06-30T19:07:23.645941
2021-07-31T03:38:51
2021-07-31T03:38:51
266,287,834
1
0
null
null
null
null
UTF-8
Python
false
false
2,315
py
""" Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. Example 1: Input: root = [2,3,1,3,1,null,1] Output: 2 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 2: Input: root = [2,1,1,1,3,null,null,null,null,null,1] Output: 1 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 3: Input: root = [9] Output: 1 Constraints: The given binary tree will have between 1 and 10^5 nodes. Node values are digits from 1 to 9. """ # Definition for a binary tree node. from collections import Counter class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pseudoPalindromicPaths(self, root: TreeNode) -> int: def ispseduoPalindrom(string): """ return whether a string is a pseudoPalindrom if the counts of a letter is odd, then odd +=1 if odd >=2, then the string is not a pseudoPalindrom """ c_string = Counter(string) odds = sum([v % 2 for v in c_string.values()]) return odds < 2 def dfs(node, string): if node: string += str(node.val) if not node.left and not node.right: res += int(ispseduoPalindrom(string)) dfs(node.left, string) dfs(node.right, string) res = 0 dfs(root, '') return res
1b43082d768a96c889d523cd9c34162a613e63b8
5c883c87f337be7ffd52f49f0a4e6c72bbd58932
/apps/almacenes/migrations/0026_auto_20170322_1009.py
6bc93dfdfc7667e77ff7d1173f2e6f96fe4acf6f
[]
no_license
DARKDEYMON/Tesis-2-Vidaurre-J.C.
f1b0d8e8a593a9d4a585bdd14b21d4809d55ce9f
4299cea2e990ee798b02724849d747bfd558b97d
refs/heads/master
2021-06-20T09:25:53.273225
2017-05-25T22:20:31
2017-05-25T22:20:31
65,408,196
0
0
null
null
null
null
UTF-8
Python
false
false
1,348
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-22 14:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('almacenes', '0025_auto_20161029_1535'), ] operations = [ migrations.AlterField( model_name='herramientas', name='decripcion', field=models.CharField(max_length=100, unique=True), ), migrations.AlterField( model_name='insumos', name='decripcion', field=models.CharField(max_length=100, unique=True), ), migrations.AlterField( model_name='maquinaria_equipo', name='decripcion', field=models.CharField(max_length=100, unique=True), ), migrations.AlterField( model_name='material', name='decripcion', field=models.CharField(max_length=100, unique=True), ), migrations.AlterField( model_name='proveedor', name='rason_social', field=models.CharField(max_length=100, unique=True), ), migrations.AlterField( model_name='tipoactivo', name='tipo', field=models.CharField(max_length=60, unique=True), ), ]
a7a10c869e455f85d0277f3c8391df0683381241
742f8aa424b5ef4d9865dee98bebbd5f741a3831
/tests/test_pregel.py
8c876136c50ef8db82da2cb79530357b615bc4f3
[ "MIT" ]
permissive
TZubiri/python-arango
a8be86f2cf9190c2d74d99eb2ef8f5f48b9f45c6
232c2d09c7bf9b5e0b71b7ab16fbce6682db383d
refs/heads/master
2020-04-04T22:24:03.898075
2018-11-06T03:59:54
2018-11-06T03:59:54
156,322,851
0
0
null
2018-11-06T03:51:04
2018-11-06T03:51:03
null
UTF-8
Python
false
false
1,823
py
from __future__ import absolute_import, unicode_literals from six import string_types from arango.exceptions import ( PregelJobCreateError, PregelJobGetError, PregelJobDeleteError ) from tests.helpers import ( assert_raises, generate_string ) def test_pregel_attributes(db, username): assert db.pregel.context in ['default', 'async', 'batch', 'transaction'] assert db.pregel.username == username assert db.pregel.db_name == db.name assert repr(db.pregel) == '<Pregel in {}>'.format(db.name) def test_pregel_management(db, graph): # Test create pregel job job_id = db.pregel.create_job( graph.name, 'pagerank', store=False, max_gss=100, thread_count=1, async_mode=False, result_field='result', algorithm_params={'threshold': 0.000001} ) assert isinstance(job_id, int) # Test create pregel job with unsupported algorithm with assert_raises(PregelJobCreateError) as err: db.pregel.create_job(graph.name, 'invalid') assert err.value.error_code == 10 # Test get existing pregel job job = db.pregel.job(job_id) assert isinstance(job['state'], string_types) assert isinstance(job['aggregators'], dict) assert isinstance(job['gss'], int) assert isinstance(job['received_count'], int) assert isinstance(job['send_count'], int) assert isinstance(job['total_runtime'], float) # Test delete existing pregel job assert db.pregel.delete_job(job_id) is True with assert_raises(PregelJobGetError) as err: db.pregel.job(job_id) assert err.value.error_code == 10 # Test delete missing pregel job with assert_raises(PregelJobDeleteError) as err: db.pregel.delete_job(generate_string()) assert err.value.error_code == 10
6244ec064900b8dd809f7c79a459e071ac1fbc06
cfa26ab2d83f25f88c61b040e385a8e2b80fad49
/cmsplugin_cascade/cms_plugins.py
8f455e4e6ff33669d4cff5e3df130c47f22dc72d
[ "MIT" ]
permissive
jrief/djangocms-cascade
e952ed65c5f8ec14a2d81b424b0797bc5a87413d
6e4d5ec7d5cbcc076aa1ea9e16b7c55c07f0ef25
refs/heads/master
2023-07-07T07:40:20.368478
2022-09-13T14:52:53
2022-09-13T14:52:53
12,973,900
143
95
MIT
2022-05-11T08:16:45
2013-09-20T13:20:48
Python
UTF-8
Python
false
false
1,088
py
import sys from importlib import import_module from django.core.exceptions import ImproperlyConfigured from . import app_settings for module in app_settings.CASCADE_PLUGINS: try: # if a module was specified, load all plugins in module settings module_settings = import_module('{}.settings'.format(module)) module_plugins = getattr(module_settings, 'CASCADE_PLUGINS', []) for p in module_plugins: try: import_module('{}.{}'.format(module, p)) except ImportError as err: traceback = sys.exc_info()[2] msg = "Plugin {} as specified in {}.settings.CASCADE_PLUGINS could not be loaded: {}" raise ImproperlyConfigured(msg.format(p, module, err.with_traceback(traceback))) except ImportError: try: # otherwise try with cms_plugins in the named module import_module('{}.cms_plugins'.format(module)) except ImportError: # otherwise just use the named module as plugin import_module('{}'.format(module))
7ec4112133d33b3aff667aac27a9a4b8451f92f9
fbb53a3366a0f10a7eb8070620cacec5101459fb
/company/m-solutions2019/c.py
16ee9cebc54f31595a786fb0932d2b433b17b306
[]
no_license
penicillin0/atcoder
272bf0b9f211907c9f7f2491335f0d34f2dcd43b
827d5cdc03531d48a44e021bd702f80b305f64d6
refs/heads/master
2023-08-05T09:43:50.114694
2021-09-20T09:21:07
2021-09-20T09:21:07
256,395,305
0
0
null
null
null
null
UTF-8
Python
false
false
1,161
py
N = int(input()) par = [-1] * N # 親だった場合は-(その集合のサイズ) if N == 1: print(0) # xがどのグループに属しているか調べる def find(x): if par[x] < 0: return x else: par[x] = find(par[x]) return find(par[x]) # 自分のいるグループの数 def size(x): return -par[find(x)] # xとyの属する集合を併合 def unite(x, y): # 根を探す x, y = find(x), find(y) # 根が一緒 if x == y: return # 大きい方に小さい方をくっつける if size(x) < size(y): x, y = y, x # xのサイズを更新 par[x] += par[y] # yの親をxにする par[y] = x # 同じ集合に属するか判定 def same(x, y): return find(x) == find(y) AB = [list(map(int, input().split())) for _ in range(N - 1)] C = list(map(int, input().split())) for ab in AB: a, b = ab a, b = a - 1, b - 1 if same(a, b): continue else: unite(a, b) n = find(0) # print(n) ret = sum(C) - max(C) print(ret) m = C.index(max(C)) if n != m: C[n], C[m] = C[m], C[n] C = list(map(str, C)) print(' '.join(C))
f151e8badd6b1cb50965d9bd65e92835c2ea1db8
e5abf2028b9e0b39a5bf905f14c401d3645bdb9a
/display.py
2bcbbfdf5758468c37a0db038d2334e6b808bfba
[ "MIT" ]
permissive
vieirafrancisco/car-adventure
2d2723e44fcb216f2ea37c1b35a1ec5f6f6fba8a
79a86d830699f131fd4e4aa2031969aa7eae1a50
refs/heads/master
2020-03-30T00:01:11.845899
2018-09-28T22:27:57
2018-09-28T22:27:57
150,501,069
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
import pygame class DisplaySurface: def __init__(self, width, height): self.width = width self.height = height self._size = (self.width, self.height) self._display_surface = pygame.display.set_mode(self._size, pygame.HWSURFACE | pygame.DOUBLEBUF) def get_display_surface(self): return self._display_surface def get_size(self): return self._size
6f310f436ac9574a69159a506b99a3faa814ef2b
f9b6c56cec99eb2147777c4448b4b8ad757ff074
/longest_harmounious_subsequence.py
1f2b1f59cd7bdf90c4e192bd21e008bf7b4f26d3
[]
no_license
zhrmrz/longest_harmounious_subsequence
268676d4c1d7f76cddb10fcaa42fb8718689f3c6
71ddac4edd4d3948d462aae430ba7154f4aa921f
refs/heads/master
2020-08-29T03:39:23.468859
2019-10-27T20:34:52
2019-10-27T20:34:52
217,913,179
0
0
null
null
null
null
UTF-8
Python
false
false
273
py
from collections import Counter class Sol: def longest_harmounious_subsequence(self,nums): max_subarr=0 freq=Counter(nums) for num,count in freq.items(): if num+1 in freq: max_subarr=max(max_subarr,count+freq[num+1])
81ca32d7661a077e47039a5f78868c9fc5d381a8
66fda6586a902f8043b1f5e9532699babc7b591a
/lib_openshift/models/v1_build_config_status.py
fd78c8cbca2d5966a2f4258b5b0d00f8861062a6
[ "Apache-2.0" ]
permissive
chouseknecht/lib_openshift
86eff74b4659f05dfbab1f07d2d7f42b21e2252d
02b0e4348631e088e72a982a55c214b30a4ab9d9
refs/heads/master
2020-12-11T05:23:17.081794
2016-07-28T20:15:39
2016-07-28T20:15:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,610
py
# coding: utf-8 """ OpenAPI spec version: Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pprint import pformat from six import iteritems import re class V1BuildConfigStatus(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ operations = [ ] def __init__(self, last_version=None): """ V1BuildConfigStatus - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'last_version': 'int' } self.attribute_map = { 'last_version': 'lastVersion' } self._last_version = last_version @property def last_version(self): """ Gets the last_version of this V1BuildConfigStatus. LastVersion is used to inform about number of last triggered build. :return: The last_version of this V1BuildConfigStatus. :rtype: int """ return self._last_version @last_version.setter def last_version(self, last_version): """ Sets the last_version of this V1BuildConfigStatus. LastVersion is used to inform about number of last triggered build. :param last_version: The last_version of this V1BuildConfigStatus. :type: int """ self._last_version = last_version def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
d080a80308e02553e9baac9420d73834f92a2979
c026581b6c3855c75e7c9f9c6397acadc7833fb7
/idm_core/name/urls.py
5778785362e85f4443b71c0f79b76a31eb6f7cbe
[]
no_license
mans0954/idm-core
5734fd08a3c8c5deaec62167c9470336f0c6c6ef
2a3cf326e0bb3db469e2b318b122033a7dd92b83
refs/heads/master
2021-07-24T04:13:47.021951
2017-11-02T22:09:25
2017-11-02T22:09:25
109,317,967
1
0
null
2017-11-02T20:56:01
2017-11-02T20:55:58
null
UTF-8
Python
false
false
745
py
from django.conf.urls import url from . import views uuid_re = '[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}' urlpatterns = [ url(r'^name/$', views.NameListView.as_view(), name='name-list-self'), url(r'^(?P<identity_type>[a-z-]+)/(?P<identity_id>' + uuid_re + ')/name/$', views.NameListView.as_view(), name='name-list'), url(r'^name/(?P<pk>[1-9][0-9]*)/$', views.NameDetailView.as_view(), name='name-detail'), url(r'^name/new:(?P<context>[\w-]+)/$', views.NameCreateView.as_view(), name='name-create-self'), url(r'^(?P<identity_type>[a-z-]+)/(?P<identity_id>' + uuid_re + ')/name/new:(?P<context>[\w-]+)/$', views.NameCreateView.as_view(), name='name-create'), ]
5ad0428c695af2b019eeb2f0663b66e863d03a50
c11c27b07086e97c633a833d37787474724bd2d2
/src/ResNeXt/concateFeature.py
6d8f98b7b69a10e8dff467812e4cacb8108ba6ef
[ "MIT" ]
permissive
willyspinner/High-Performance-Face-Recognition
d1826a73653dede6b43799439e4fb692f119c70b
c5caad61be97fd20f9c47a727278ff938dc5cc8f
refs/heads/master
2020-06-22T16:36:29.663302
2019-07-19T09:41:47
2019-07-19T09:41:47
197,746,624
0
0
MIT
2019-07-19T09:42:00
2019-07-19T09:41:59
null
UTF-8
Python
false
false
1,953
py
import scipy.io as sio import pickle import numpy as np import os import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from scipy import spatial from sklearn.externals import joblib import time reducedDim = 2048 pca = PCA(n_components = reducedDim, whiten = True) path = "/media/zhaojian/6TB/data/extra_general_model_feature/" with open(path + "NovelSet_List/NovelSet_1.txt", 'r') as f: lines = f.readlines() vggFeatures = np.loadtxt(path + 'NovelSet_Fea/VGG_NOVELSET_1.txt') print "vggFeatures.shape: ", vggFeatures.shape inputFeaturePath = "extracted_feature/NovelSet_1IdentityFeature/" outputFeaturePath = "extracted_feature/NovelSet_1IdentityFeaturePCA2048/" features = [] labelList = [] for index in range(len(lines)): print index line = lines[index] ID = line.split("/")[-2] print ID labelList.append(ID) vggFeature = feature = vggFeatures[index].flatten() print "vggFeature.shape", vggFeature.shape # caffeFeature = sio.loadmat(inputFeaturePath + ID + ".mat")["identityFeature"].flatten() # print "caffeFeature.shape", caffeFeature.shape # # identityFeature = np.concatenate((caffeFeature, vggFeature), axis = 0) # print "identityFeature.shape: ", identityFeature.shape identityFeature = vggFeature features.append(identityFeature) features = np.asarray(features) print "features..shape: ", features.shape # sio.savemat("concatenateFeatures", {"identityFeature": features}) # sio.savemat("vggNovelSet_1_Features", {"identityFeature": features}) features = sio.loadmat("vggNovelSet_1_Features")['identityFeature'] # # features = pca.fit_transform(features) # print "features..shape: ", features.shape # # for index in range(len(features)): identityFeature = features[index] print "identityFeature.shape: ", identityFeature.shape label = labelList[index] # print index # print label sio.savemat(outputFeaturePath + label, {"identityFeature": identityFeature})
5762741a29ba36f2c36980cbe7c87cd3d2f89121
a01e7f87a0088965e2e0a02476d2df12a49a1a18
/package/tfi_helper/dhcp/hapack/dhcpparser.py
dea3a1526ea3c35f8b80c04e697d0a60a841bed7
[]
no_license
gsrr/IFT_jerry
0456a8a1fb98f84ad5c26dc36bdf32e2d85c750c
4c2f6900dfd7ae7f6b3cc2150b1c1be236b4c95c
refs/heads/master
2020-04-04T05:30:10.544252
2019-08-22T09:12:03
2019-08-22T09:12:03
48,145,836
0
0
null
null
null
null
UTF-8
Python
false
false
686
py
import argparse class DHCPParser: def __init__(self): self.cmds = ['dhcp_test'] self.parser_dhcp = argparse.ArgumentParser(prog="dhcp", add_help=False) self.parser_dhcp_test = argparse.ArgumentParser(prog="dhcp_test", add_help=False) self.parser_dhcp_test.add_argument("-z", nargs="?", required=True) def find(self, args): cnt = 0 cmd = "dhcp" while cnt < len(args): cmd += ("_" + args[cnt]) if cmd in self.cmds: break cnt += 1 args = args[cnt+1:] namespace = getattr(self, "parser" + "_" + cmd).parse_args(args).__dict__ return cmd, namespace
9d82a9d1425b1deae0c45fc833fe73e80449e0b6
2b7c7e9b00ed9b2dbbac943ee4b79865a96d10de
/Figure_script/Figure_1.py
7caa0f0d7080d155e2572b49ddd294af94fa11d9
[]
no_license
YaojieLu/Plant_traits_inversion
ad973e60bb32717d9d718f774c2ec77433c38ced
ec83642ae2a2e6ef96502e58f8074bffdadfefe8
refs/heads/master
2021-06-21T15:22:00.225498
2020-12-13T22:12:21
2020-12-13T22:12:21
140,017,309
1
1
null
null
null
null
UTF-8
Python
false
false
1,680
py
import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from scipy import stats # load traces ts = pickle.load(open("../Data/45.pickle", "rb")) params = ['alpha', 'c', 'g1', 'kxmax', 'p50', 'L'] true_values = [0.02, 16, 50, 7, -4.5, 2] # figure labels = ['$\\alpha$', '$\\mathit{c}$', '$\\mathit{g_{1}}$', '$\\mathit{k_{xmax}}$', '$\\psi_{x50}$', '$\\mathit{L}$'] ranges = [[0.001, 0.2], [2, 20], [10, 100], [1, 10], [-10, -0.1], [0.5, 5]] fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(30, 20)) for i, row in enumerate(axs): for j, col in enumerate(row): idx = i*3+j param = params[idx] df = pd.DataFrame({param: ts[param]}).iloc[:, 0] col.hist(df, range=[ranges[idx][0], ranges[idx][1]], bins=100) # kde = stats.gaussian_kde(df) # param_range = np.linspace(ranges[idx][0], ranges[idx][1], 1000) # col.plot(param_range, kde(param_range), linewidth=2.5, color='blue') mean, std = df.mean(), df.std() cv = abs(round(std/mean, 2)) col.set_title('RSD = {}'.format(cv), fontsize=30) col.axvline(x=true_values[idx], c='black', label='True value', linestyle='dashed') col.axes.get_yaxis().set_visible(False) col.tick_params(labelsize=30) col.set_xlabel(labels[idx], fontsize=30) if idx == 0: col.legend([Line2D([0], [0], linestyle='dashed', color='black')], ['True value'], loc='upper right', fontsize=30, framealpha=0) plt.subplots_adjust(hspace=0.25, wspace=0.1) plt.savefig('../Figures/Figure 45.png', bbox_inches = 'tight')
[ "=" ]
=
8f28ab12e6205691d69253b9b16c31e06f857774
b5cc6d7b5f7ccea36fce4eab961979404414f8b0
/kent-report/py/beam_distances.py
2cc89895ad6d3fed6c27470bb32f1dfd505d8989
[]
no_license
MiroK/cutFEM-beam
adf0c925dbe64b370dab48e82335617450675f5d
2fb3686804e836d4031fbf231a36a0f9ac8a3012
refs/heads/master
2021-01-21T23:54:32.868307
2015-02-14T13:14:59
2015-02-14T13:14:59
25,625,143
0
0
null
null
null
null
UTF-8
Python
false
false
3,537
py
from __future__ import division from sympy import sin, cos, pi, sqrt, symbols, lambdify from sympy.mpmath import quad import numpy as np x, y, s = symbols('x, y, s') def eigen_basis(n): ''' Return first n eigenfunctions of Laplacian over biunit interval with homog. Dirichlet bcs. at endpoints -1, 1. Functions of x. ''' k = 0 functions = [] while k < n: alpha = pi/2 + k*pi/2 if k % 2 == 0: functions.append(cos(alpha*x)) else: functions.append(sin(alpha*x)) k += 1 return functions def shen_basis(n): ''' Return first n Shen basis functions. Special polynomials made of Legendre polynomials that have 0 values at -1, 1. Functions of x. ''' k = 0 functions = [] while k < n: weight = 1/sqrt(4*k + 6) functions.append(weight*(legendre(k+2, x) - legendre(k, x))) k += 1 return functions def beam_restrict(A, B, u): ''' Restict function(s) u of x, y to beam = {(x, y)=0.5*A*(1-s) + 0.5*B*(1+s)}. ''' if isinstance(u, list): return [beam_restrict(A, B, v) for v in u] else: assert x in u.atoms() and y in u.atoms() ux = u.subs(x, A[0]/2*(1-s) + B[0]/2*(1+s)) u = ux.subs(y, A[1]/2*(1-s) + B[1]/2*(1+s)) return u def L2_distance(f, g): 'L2 norm over [-1, 1] of f-g.' d = f-g d = lambdify(s, d) return sqrt(quad(lambda s: d(s)**2, [-1, 1])) def H10_distance(f, g): 'H10 norm over [-1, 1] of f-g.' d = (f-g).diff(s, 1) d = lambdify(s, d) return sqrt(quad(lambda s: d(s)**2, [-1, 1])) def distance_matrices(A, B, Vp, Vb, Q, norm): ''' Given beam specified by A, B return two matrices. The first matrix has norm(u-q) where u are functions from Vp restricted to beam and q are functions from Q. The other matrix is norm(p-q) for p in Vb and Q in Q. ''' if norm == 'L2': distance = L2_distance elif norm == 'H10': distance = H10_distance else: raise ValueError m, n, r = len(Vp), len(Vb), len(Q) mat0 = np.zeros((m, r)) # First do the restriction Vp = beam_restrict(A, B, Vp) for i, u in enumerate(Vp): for j, q in enumerate(Q): mat0[i, j] = distance(u, q) mat1 = np.zeros((n, r)) for i, p in enumerate(Vb): for j, q in enumerate(Q): mat1[i, j] = distance(p, q) return mat0, mat1 # ----------------------------------------------------------------------------- if __name__ == '__main__': import matplotlib.pyplot as plt from itertools import product # Number of plate function in 1d, number of beam functions and number of # functions for Lagrange multiplier space m, n, r = 20, 20, 20 # Vp basis - functions of x, y Vp = [fx*fy.subs(x, y) for fx, fy in product(eigen_basis(m), eigen_basis(m))] # Vb basis - functions of s Vb = [f.subs(x, s) for f in eigen_basis(n)] # Q basis - functions of s Q = [f.subs(x, s) for f in eigen_basis(r)] # Sample beam A = np.array([0, 0]) B = np.array([1, 1]) for norm in ['L2', 'H10']: matBp, matBb = distance_matrices(A, B, Vp, Vb, Q, norm) plt.figure() plt.title(norm) plt.pcolor(matBp) plt.xlabel('$Q$') plt.ylabel('$V_p$') plt.colorbar() plt.figure() plt.title(norm) plt.pcolor(matBb) plt.xlabel('$Q$') plt.ylabel('$V_b$') plt.colorbar() plt.show()
a728bf9ae2c46a9eeba638b54da02ebb8ac8ddca
a35b24c8c3c5bdf861f3cda9396f2fa6795ec929
/abc/abc037/a/main.py
bb4c99a18af37578e976b0d53202738d5e7c3592
[]
no_license
Msksgm/atcoder_msksgm_practice
92a19e2d6c034d95e1cfaf963aff5739edb4ab6e
3ae2dcb7d235a480cdfdfcd6a079e183936979b4
refs/heads/master
2021-08-18T16:08:08.551718
2020-09-24T07:01:11
2020-09-24T07:01:11
224,743,360
0
0
null
null
null
null
UTF-8
Python
false
false
226
py
def main(): a, b, c = map(int, input().split()) min_price = min(a, b) max_price = max(a, b) ans = (c // min_price) ans += (c % min_price) // max_price print(ans) if __name__ == "__main__": main()
13590eb83cedf7e78563f292ee34f03b3d739622
a0a288a9563ed4519cfe9f9c24ecc41237753dbc
/thechronic/strange.py
417876af3a2960256bd2b445292b60da0c62abbd
[ "MIT" ]
permissive
iluxonchik/the-chronic
99b236456efb9c32dfb9e3978f9e2cc28910a03c
4dd41ea1a96e4c5cb1741de02d55cf09b2e78979
refs/heads/master
2021-04-28T22:40:51.993595
2018-04-02T13:38:04
2018-04-02T13:38:04
77,719,263
0
0
null
null
null
null
UTF-8
Python
false
false
696
py
class Strange(object): """ Wrapper arround the built-in range() function, which returns str instead of int on iteration. Just like a range object, an instance of Srange can be iterated over multiple times. """ def __init__(self, start, stop=None, step=1): if stop is None: stop = start start = 0 self._range = range(start, stop, step) self._iter = iter(self._range) def __iter__(self): return self def __next__(self): try: str_num = str(next(self._iter)) except StopIteration as err: self._iter = iter(self._range) raise err return str_num
4baf087e4e4c72d03eb1f4f5b7f52fbbaa305d56
b71e91d4eb55b6826dbe378180aa7b2b8a717bdf
/Capitulo1/exerc4_3_v5.py
1058a9e307d85293890de1402b022dd0572ac930
[]
no_license
gustavopierre/think_python
49a9ceb50f760b41f6fbac54a07f6b394aa8d637
a3ad6e660db4e6ce2aa105f5084e585f95936867
refs/heads/main
2023-03-24T23:48:29.415573
2021-03-15T22:15:30
2021-03-15T22:15:30
348,137,048
0
0
null
null
null
null
UTF-8
Python
false
false
336
py
import turtle import math def arc(t, r, angle): n = int(2*math.pi*r/10) x = int(n*angle/360) for count in range(x): t.fd(10) t.lt(360/n) print(f'r = {r}') print(f'angle = {angle}') print(f'n = {n}') print(f'x = {x}') bob = turtle.Turtle() print(bob) arc(bob, 100, 270) turtle.mainloop()
6e02a4cd2c2891c084f93dad75871c179905debf
b54097ce251925a82e591a08ae625fa884500b9c
/tests/test_github.py
e942b6bfaabe6db425870e1377356785c841cac2
[ "BSD-3-Clause" ]
permissive
johnnoone/aiovault
b45b576cfb30570b1bbe9ab018a3247156dbefea
03e1bfb6f0404dcf97ce87a98c539027c4e78a37
refs/heads/master
2021-01-10T19:56:50.715283
2015-07-10T21:15:21
2015-07-10T21:15:21
35,452,083
1
0
null
null
null
null
UTF-8
Python
false
false
2,199
py
from aiovault import Vault, LoginError from conftest import async_test import pytest @async_test def test_github_raw_loading(dev_server): client = Vault(dev_server.addr, token=dev_server.root_token) response = yield from client.read('/sys/auth/github/login', params={"help": 1}) data = yield from response.json() print(data['help']) # low level create/delete response = yield from client.write('/sys/auth/github', json={"type": "github"}) assert response.status == 204, 'Must add github auth backend' response = yield from client.delete('/sys/auth/github') assert response.status == 204, 'Must delete github auth backend' # high level create/delete response = yield from client.auth.enable('github') assert response.type == 'github', 'Must add github auth backend' response = yield from client.auth.disable('github') assert response is True, 'Must delete github auth backend' @async_test def test_help(dev_server): client = Vault(dev_server.addr, token=dev_server.root_token) response = yield from client.read('/sys/auth/github', params={"help": 1}) data = yield from response.json() assert 'help' in data @async_test def test_github_loading(dev_server, env): try: github_org = env.GITHUB_ORG github_token = env.GITHUB_TOKEN except AttributeError: return 'GITHUB_ORG or GITHUB_TOKEN missing' client = Vault(dev_server.addr, token=dev_server.root_token) backend1 = backend = yield from client.auth.enable('github') configured = yield from backend.configure(organization=github_org) assert configured configured = yield from backend.write_team('test', policies='foo') assert configured client = Vault(dev_server.addr) backend = client.auth.load('github') dummy_token = '1111111111111111111111111111111111111111' with pytest.raises(LoginError): yield from backend.login(github_token=dummy_token) yield from backend.login(github_token=github_token) disabled = yield from backend1.disable() assert disabled
d36a0fd44877c71c01b65bf4986938b78a9d64dc
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/remove_invalid_submissions.py
bea3c87a9227a23ef93473ae7d1cd253ca981bc3
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
2,261
py
import os from collections import Counter import shutil import sys import argparse import tempfile # for example call this script on hamming from exercism_data directory like: python remove_invalid_submissions.py "ruby/hamming/" "filtered-submissions/" "compute" parser = argparse.ArgumentParser(description='Filter and clean data and put in src directory') parser.add_argument('data_directory', help='Directory for original data') parser.add_argument('filtered_submissions', help='Directory to store filtered data') parser.add_argument('method', help='Method to extract') args = parser.parse_args() data_directory = args.data_directory filtered_submissions =args.filtered_submissions method = args.method mapfile = open("mapping.csv", "w") count = 0 for f in os.listdir(data_directory): count+=1 print 'starting with submissions: ' + str(count) if not os.path.isdir(filtered_submissions): os.mkdir(filtered_submissions) else: shutil.rmtree(filtered_submissions) os.mkdir(filtered_submissions) if not os.path.isdir('src'): os.mkdir('src') else: shutil.rmtree('src') os.mkdir('src') for f in os.listdir(data_directory): t = tempfile.NamedTemporaryFile(mode="r+") with open(data_directory+f) as filename: for line in filename: line = line.partition('#')[0] line = line.rstrip() + "\n" t.write(line) t.seek(0) data = t.read() #if not (data.count('def') == 1 or data.find('def word_count') == -1 or data.find('def initialize') == -1): if data.count('def') == 1 and (data.find('def self.' + str(method)) != -1 or data.find('def ' + str(method)) != -1): data = data.replace('def self.' + str(method), 'def ' + str(method)) num_ends_to_strip = data.count('class') + data.count('module') data = data[data.find('def ' + str(method)):] for i in range(num_ends_to_strip): data = data[:data.rfind('end')] data = data.rstrip() out = open(filtered_submissions+f, "w+") out.write(data) t.close() count = 0 for f in os.listdir(filtered_submissions): submission_id = f.strip(".rb") index_id = len(os.listdir('src')) shutil.copyfile(filtered_submissions+f, 'src/'+str(index_id)+'.rb') mapfile.write(str(submission_id) + ' : ' + str(index_id) + '\n') count += 1 print 'filtered to submissions: ' + str(count)
b80cff1f63fc85e2e367363d8d4217c52f1bcb9c
3e3741d9ea06f1dcd560e27145256bd3177bed14
/01_py基础/第2周/day01/test05.py
0b0877d5b07aa6ba958a21bc84e6b7a6d5a0890e
[]
no_license
Lousm/Python
778bc730db09ab135bf53c7b62af29df2407199a
d3f19600012b3576cd5d58df510c17590fcaec14
refs/heads/master
2020-03-26T16:40:01.188306
2018-11-06T03:56:20
2018-11-06T03:56:20
145,116,187
0
0
null
null
null
null
UTF-8
Python
false
false
185
py
a = [i*10 for i in range(1, 13)] b = [i*2 for i in range(1, 13)] def sy(a, b): c = [] for i in range(len(a)): c.append(a[i]+b[i]) return c c = sy(a, b) print(c)
1b6b591a2a8ad31a5c1bd110be072f800865522b
e838ea567fe5216bd83b72d5cc549363a666ac3d
/community/migrations/0001_initial.py
756f713d6f763cc2a681b7383369ae2c3dc63f28
[]
no_license
iuriramos/swim-registry
f7ffee9a57b92021e7066820249092d1558a944d
7c71d294b5aa7cb40e01ed559e2fcb81d2e1f43a
refs/heads/master
2021-09-13T20:22:29.624535
2018-05-03T21:30:26
2018-05-03T21:30:26
85,312,675
0
0
null
null
null
null
UTF-8
Python
false
false
4,544
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-05-18 18:20 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('registry', '0001_initial'), ] operations = [ migrations.CreateModel( name='Participant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=255)), ('description', models.TextField(null=True)), ('image', models.ImageField(default='participants/images/profiles/none/default.jpg', upload_to='participants/images/profiles/')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='ParticipantCategory', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(choices=[('AIRSPACE COMPANY', 'Airspace company'), ('RESEARCH ORGANIZATION', 'Research Organization'), ('AIRPORT', 'Airport'), ('AERODROME', 'Aerodrome'), ('RESEARCH INSTITUTION', 'Research Institution'), ('PUBLIC AGENCY', 'Public Agency'), ('OTHER', 'Other')], max_length=50, unique=True)), ], options={ 'verbose_name_plural': 'participant categories', 'verbose_name': 'participant category', }, ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('notification_frequency', models.CharField(choices=[('NEVER', 'Never'), ('IMMEDIATE', 'Immediate'), ('DAILY', 'Daily'), ('WEEKLY', 'Weekly')], default='NEVER', max_length=10)), ('following_organizations', models.ManyToManyField(related_name='followers', to='community.Participant')), ('subscriptions_activity', models.ManyToManyField(related_name='profiles', to='registry.ActivityCategory')), ('subscriptions_content_type', models.ManyToManyField(related_name='profiles', to='registry.SubscriptionContentType')), ('subscriptions_data', models.ManyToManyField(related_name='profiles', to='registry.DataCategory')), ('subscriptions_flight_phase', models.ManyToManyField(related_name='profiles', to='registry.FlightPhaseCategory')), ('subscriptions_region', models.ManyToManyField(related_name='profiles', to='registry.RegionCategory')), ('subscriptions_stakeholder', models.ManyToManyField(related_name='profiles', to='registry.StakeholderCategory')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='RegistrationRequest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('first_name', models.CharField(max_length=255)), ('last_name', models.CharField(max_length=255)), ('email', models.EmailField(max_length=254)), ('organization', models.CharField(max_length=255)), ('role', models.CharField(max_length=255)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='participant', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='participants', to='community.ParticipantCategory'), ), ]
e67dd18e17853bde0845ae57c5ee63c25d10828b
a657283ae5208611351606f35b05f46f63581d5c
/website/routes.py
83404e7b3b86c06c28d0c50b12f5eb7115140b6e
[]
no_license
rrkas/handwriting-generation-flask
e17c71f0335231a6157c728c78ce4c30d7d6df61
049091b1a3d341af0ce50e07d484c1bbf98fd3d8
refs/heads/master
2023-07-14T22:12:56.482115
2021-08-29T10:14:56
2021-08-29T10:14:56
391,993,520
0
0
null
null
null
null
UTF-8
Python
false
false
2,975
py
import io import os import uuid import pywhatkit as kit from flask import * from werkzeug.datastructures import FileStorage from website import app output_dir = os.path.join('website', 'static', 'output') if not os.path.exists(output_dir): os.mkdir(output_dir) allowed_file_ext = ['txt'] def allowed_file(filename): return filename.split('.')[-1] in allowed_file_ext def generate_signature(file): try: output_filename = str(uuid.uuid4().hex) if isinstance(file, FileStorage): if os.path.exists('pywhatkit_dbs.txt'): os.remove('pywhatkit_dbs.txt') file.save(os.path.join(output_dir, output_filename + '.txt')) with open(os.path.join(output_dir, output_filename + '.txt'), 'r') as f: text = f.read() os.remove(os.path.join(output_dir, output_filename + '.txt')) else: text = file kit.text_to_handwriting( string=text, rgb=(0, 0, 0), save_to=os.path.join(output_dir, output_filename + '.png'), ) return output_filename, True except BaseException as e: print(e) return str(e), False @app.route('/', methods=['POST', 'GET']) def home(): if request.method == 'POST': # print("request", request) print("form", request.form) if request.form.get('inputtype') == 'file': if 'file' not in request.files: flash('No file part!') return redirect(request.url) file = request.files.get('file') if not allowed_file(file.filename): flash('Invalid File!') return redirect(request.url) else: file = request.form.get('text') img_name, valid = generate_signature(file) if valid: flash('Image Generated Successfully!', 'success') else: flash('Something went wrong! Please try again!!', 'error') return redirect(request.url) return redirect(url_for('home', img_name=img_name)) filename = request.args.get('img_name') result_path = os.path.join(output_dir, str(filename) + '.png') if filename and not os.path.exists(result_path): abort(404) return render_template('home.html', img_name=request.args.get('img_name')) @app.route('/download/<string:filename>', methods=['GET', 'POST']) def download(filename): result_path = os.path.join(output_dir, filename + '.png') if not os.path.exists(result_path): abort(404) return_data = io.BytesIO() with open(result_path, 'rb') as fo: return_data.write(fo.read()) return_data.seek(0) os.remove(result_path) return send_file( return_data, mimetype='image/png', as_attachment=True, attachment_filename='txt2handwriting.png' ) @app.errorhandler(404) def error_400(error): return render_template('errors/404.html')
611500bc11e4bf0093b270c1e76a4ec33c642061
e61e664d95af3b93150cda5b92695be6551d2a7c
/vega/security/load_pickle.py
206511004faf87ad32800052b332f62e12f296b8
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
huawei-noah/vega
44aaf8bb28b45f707ed6cd4e871ba70fc0c04846
12e37a1991eb6771a2999fe0a46ddda920c47948
refs/heads/master
2023-09-01T20:16:28.746745
2023-02-15T09:36:59
2023-02-15T09:36:59
273,667,533
850
184
NOASSERTION
2023-02-15T09:37:01
2020-06-20T08:20:06
Python
UTF-8
Python
false
false
1,812
py
# Copyright (C) 2020. Huawei Technologies Co., Ltd. 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. """Load pickle.""" import pickle __all__ = ["restricted_loads"] safe_builtins = { 'vega', 'torch', 'torchvision', 'functools', 'timm', 'mindspore', 'tensorflow', 'numpy', 'imageio', 'collections', 'apex', 'ascend_automl' } class RestrictedUnpickler(pickle.Unpickler): """Restrict unpickler.""" def __init__(self, file, fix_imports, encoding, errors, security): super(RestrictedUnpickler, self).__init__(file=file, fix_imports=fix_imports, encoding=encoding, errors=errors) self.security = security def find_class(self, module, name): """Find class.""" _class = super().find_class(module, name) if self.security: if module.split('.')[0] in safe_builtins: return _class raise pickle.UnpicklingError(f"global '{module}' is forbidden") else: return _class def restricted_loads(file, fix_imports=True, encoding="ASCII", errors="strict", security=False): """Load obj.""" return RestrictedUnpickler(file, fix_imports=fix_imports, encoding=encoding, errors=errors, security=security).load()
486752af90a81014c8a2c8b798d2c1b5fc1c35eb
9dbe507104b03275b1ed5dc91a4aaa2ae6af4f51
/hearthbreaker/cards/minions/shaman.py
800985cec4d413a7eaac702479486e1dcdcc24bf
[ "MIT" ]
permissive
bussiere/hearthbreaker
55fc7c77d8ffb37cda2b5d9afb7ccd44c250702c
074e20de3498d078877e77b3603580b511e8522b
refs/heads/master
2021-01-16T22:13:32.110626
2014-12-17T13:37:32
2014-12-17T13:37:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,946
py
from hearthbreaker.tags.action import ChangeAttack, Draw, ChangeHealth, Damage, Give, Windfury from hearthbreaker.tags.base import Aura, Effect, Battlecry from hearthbreaker.tags.condition import Adjacent, HasOverload from hearthbreaker.tags.event import TurnEnded, CardPlayed from hearthbreaker.tags.selector import MinionSelector, SelfSelector, PlayerSelector, CharacterSelector, BothPlayer, \ UserPicker from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE from hearthbreaker.game_objects import MinionCard, Minion class AlAkirTheWindlord(MinionCard): def __init__(self): super().__init__("Al'Akir the Windlord", 8, CHARACTER_CLASS.SHAMAN, CARD_RARITY.LEGENDARY) def create_minion(self, player): return Minion(3, 5, windfury=True, charge=True, divine_shield=True, taunt=True) class DustDevil(MinionCard): def __init__(self): super().__init__("Dust Devil", 1, CHARACTER_CLASS.SHAMAN, CARD_RARITY.COMMON, overload=2) def create_minion(self, player): return Minion(3, 1, windfury=True) class EarthElemental(MinionCard): def __init__(self): super().__init__("Earth Elemental", 5, CHARACTER_CLASS.SHAMAN, CARD_RARITY.EPIC, overload=3) def create_minion(self, player): return Minion(7, 8, taunt=True) class FireElemental(MinionCard): def __init__(self): super().__init__("Fire Elemental", 6, CHARACTER_CLASS.SHAMAN, CARD_RARITY.COMMON, battlecry=Battlecry(Damage(3), CharacterSelector(players=BothPlayer(), picker=UserPicker()))) def create_minion(self, player): return Minion(6, 5) class FlametongueTotem(MinionCard): def __init__(self): super().__init__("Flametongue Totem", 2, CHARACTER_CLASS.SHAMAN, CARD_RARITY.COMMON, MINION_TYPE.TOTEM) def create_minion(self, player): return Minion(0, 3, auras=[Aura(ChangeAttack(2), MinionSelector(Adjacent()))]) class ManaTideTotem(MinionCard): def __init__(self): super().__init__("Mana Tide Totem", 3, CHARACTER_CLASS.SHAMAN, CARD_RARITY.RARE, MINION_TYPE.TOTEM) def create_minion(self, player): return Minion(0, 3, effects=[Effect(TurnEnded(), Draw(), PlayerSelector())]) class UnboundElemental(MinionCard): def __init__(self): super().__init__("Unbound Elemental", 3, CHARACTER_CLASS.SHAMAN, CARD_RARITY.COMMON) def create_minion(self, player): return Minion(2, 4, effects=[Effect(CardPlayed(HasOverload()), ChangeAttack(1), SelfSelector()), Effect(CardPlayed(HasOverload()), ChangeHealth(1), SelfSelector())]) class Windspeaker(MinionCard): def __init__(self): super().__init__("Windspeaker", 4, CHARACTER_CLASS.SHAMAN, CARD_RARITY.COMMON, battlecry=Battlecry(Give(Windfury()), MinionSelector(picker=UserPicker()))) def create_minion(self, player): return Minion(3, 3)
8277d4f471be2dee3c2676a6bf9cbd30cf236a64
c0ad282ab743a315e2f252a627933cb168434c1d
/models/agreement/type_prior.py
bde43251219d85d73f078c3d0ba4fad4980ae25c
[ "MIT" ]
permissive
AlexKuhnle/ShapeWorld
6d1e16adc94e860abae99ade869f72575f573bc4
e720bf46e57fc01326d04d639fa6133d9c12158f
refs/heads/master
2021-07-09T00:02:33.808969
2021-04-19T11:10:52
2021-04-19T11:10:52
80,815,972
58
28
MIT
2021-04-19T11:10:53
2017-02-03T09:40:19
Python
UTF-8
Python
false
false
2,722
py
from models.TFMacros.tf_macros import * def model(model, inputs, dataset_parameters): caption = Input(name='caption_rpn', shape=dataset_parameters['caption_rpn_shape'], dtype='int', tensor=inputs.get('caption_rpn'))() caption_length = Input(name='caption_rpn_length', shape=(), dtype='int', tensor=inputs.get('caption_rpn_length')) agreement = Input(name='agreement', shape=(), dtype='float', tensor=inputs.get('agreement'))() agreement = ( (caption, caption_length, agreement) >> SuffixPrior(suffix_length=1, vocabulary_size=dataset_parameters['rpn_vocabulary_size']) >> Binary(name='agreement', binary_transform=False, tensor=agreement) ) return agreement class SuffixPrior(Unit): num_in = 3 num_out = 1 def __init__(self, suffix_length, vocabulary_size): super(SuffixPrior, self).__init__() self.suffix_length = suffix_length self.vocabulary_size = vocabulary_size def initialize(self, caption, caption_length, agreement): super(SuffixPrior, self).initialize(caption, caption_length, agreement) shape = tuple(self.vocabulary_size for _ in range(self.suffix_length)) + (2,) self.suffix_agreement_counts = tf.get_variable(name='suffix-agreement-counts', shape=shape, dtype=tf.int32, initializer=tf.zeros_initializer(dtype=tf.int32), trainable=False) def forward(self, caption, caption_length, agreement): super(SuffixPrior, self).forward(caption, caption_length, agreement) batch_size = tf.shape(input=caption)[0] slice_indices = [tf.stack(values=(tf.range(batch_size), caption_length - (self.suffix_length - n)), axis=1) for n in range(self.suffix_length)] suffix = tf.stack(values=[tf.gather_nd(params=caption, indices=indices) for indices in slice_indices], axis=1) agreement_counts = tf.gather_nd(params=self.suffix_agreement_counts, indices=suffix) prior = tf.where( condition=(agreement_counts[:, 0] > agreement_counts[:, 1]), x=tf.zeros(shape=(batch_size,)), y=tf.where( condition=(agreement_counts[:, 0] < agreement_counts[:, 1]), x=tf.ones(shape=(batch_size,)), y=(tf.ones(shape=(batch_size,)) * 0.5) ) ) agreement = tf.expand_dims(input=tf.cast(x=agreement, dtype=Model.dtype('int')), axis=1) indices = tf.concat(values=(suffix, agreement), axis=1) updates = tf.ones(shape=(batch_size,), dtype=Model.dtype('int')) assert Model.current.optimization is None Model.current.optimization = tf.scatter_nd_add(ref=self.suffix_agreement_counts, indices=indices, updates=updates) return prior
952ecae4e414db6b616a055126571c0e7b129cdf
8b427d0a012d7dbd3b49eb32c279588f9ebd4e6e
/05 排序和搜索/binary_search.py
33fe499fccf320c9b9bcc7589236e441fdbcd076
[]
no_license
chenyang929/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python-Notes
e9f1b324d86963333edaf855fdb9e126e59e8542
aed976e020147fe30a8e0bb708dfbe4bab4c15f7
refs/heads/master
2020-03-18T02:46:12.385967
2018-07-24T08:24:41
2018-07-24T08:24:41
134,206,437
0
0
null
null
null
null
UTF-8
Python
false
false
1,023
py
# binary_search.py # 循环版 def binary_search(lst, item): low = 0 high = len(lst) - 1 while low <= high: mid = (low + high) // 2 guess = lst[mid] if item == guess: return mid elif item > guess: low += 1 else: high -= 1 return -1 # 递归版(内存开销大) def binary_search1(lst, item, low=0, high=None): if high is None: high = len(lst) - 1 if low > high: return -1 else: mid = (low + high) // 2 guess = lst[mid] if item == guess: return mid elif item > guess: low += 1 return binary_search1(lst, item, low, high) else: high -= 1 return binary_search1(lst, item, low, high) if __name__ == '__main__': l = [1, 3, 4, 7, 9, 12, 14] print(binary_search(l, 12)) # 5 print(binary_search1(l, 12)) # 5 print(binary_search(l, 5)) # -1 print(binary_search1(l, 5)) # -1
1c18a6ddc3944da8e2ba5f5ef396825ac6423869
6e13f7fdae0144dd0397031c59397b0372f0872a
/horch/layers/_se.py
43f7469184fbc7b507af7080e15eb8071fc1c974
[]
no_license
sbl1996/horch
02e9996f764748c62648464d58318ceff92c87ed
50d4f4da241a5727e3924a36fbc730dc61284904
refs/heads/master
2020-03-20T05:00:43.444092
2018-07-27T00:14:45
2018-07-27T00:14:45
137,201,939
0
0
null
null
null
null
UTF-8
Python
false
false
671
py
import horch as H from ._linear import Linear from ._module import Module class SE(Module): """Squeeze and Excitation Module """ def __init__(self, channels, reduction_ratio=16): super().__init__() self.channels = channels self.reduction_ratio = reduction_ratio reduced_channels = channels // reduction_ratio self.fc1 = Linear(channels, reduced_channels) self.fc2 = Linear(reduced_channels, channels) def forward(self, x): z = H.mean(x, axis=(2,3)) z = self.fc1(z) z = H.relu(z) z = self.fc2(z) s = H.sigmoid(z) n, c = s.shape s = s.reshape(n, c, 1, 1) x = x * s return x
ffd7b753f12a8fff9b52468226a6155d9a60a7c9
7bd9be7f25be80791f9220b62025f06170273293
/end-plugins/pycerebro/examples/excel_export.py
7ccaaa79c69f3f70111f28d64cfa01c407d3180a
[]
no_license
cerebrohq/cerebro-plugins
ab46b4844adcb12c51d14e21f2c0d8b758b0bb57
e2e0f97b548ef22957e13d614200027ba89215e0
refs/heads/master
2021-11-12T16:25:48.228521
2021-10-22T11:25:58
2021-10-22T11:25:58
143,178,631
5
3
null
null
null
null
UTF-8
Python
false
false
7,156
py
# -*- coding: utf-8 -*- """ Пример экспорта задачи(проекта) со всеми вложенными задачами в Excel. Этот пример демонстрирует экспорт свойств задачи в Excel. Для записи в формат Excel используется сторонний пакет xlsxwriter (https://xlsxwriter.readthedocs.org/) Для преобразования текста в формате html используется сторонний пакет html2text (http://www.aaronsw.com/2002/html2text/). В модуле используются следующие функции: do_export - Функция экспорта. Принимает параметры: Имя пользователя, Пароль пользователя, Путь до задачи, Путь к файлу Excel. write - Функция, которая записывает свойства задачи и всех вложенных задач в файл Excel. connect_db - Функция для соединения с базой данных Cerebro. write_info, write_error - Функции для логирования. Пример использования: do_export('Имя_пользователя', 'Пароль_пользователя', '/Путь/к/Задаче', 'C:/путь/к/файлу.xlsx') """ # Имена колонок Excel columns = { 0: "Задача", 1: "Описание", 2: "Назначено", 3: "Начало", 4: "Окончание", 5: "Запланировано"} # Ширина колонок columns_w = { 0: 50, 1: 50, 2: 10, 3: 10, 4: 10, 5: 15} # Высота строк row_h = 50 import sys import os local_dir = os.path.realpath(__file__).replace('\\', '/').rsplit('/', 1)[0] backend_dir = local_dir + '/../..' sys.path.append(backend_dir) import xlsxwriter from pycerebro import database, dbtypes import html2text import datetime def do_export(db_user, db_password, task, file_name): """ Функция экспорта. Параметры db_user и db_password - логин и пароль пользователя Cerebro. task - тектовый локатор(путь) до задачи. Формат локатора: '/Проект/Задача 1/Задача 2', то есть по сути путь до задачи. Примечание: Имена задач регистрозависимы! Пример вызова функции: :: import excel_export excel_export.do_export('user', 'password', '/Проект/Задача 1/Задача 2', 'c:/temp/export.xlsx') :: """ # Устанавливаем соединение с базой данных db = connect_db(db_user, db_password) if (db): # Создаем файл Excel wb = xlsxwriter.Workbook(file_name) if (wb): # Добавляем лист ws = wb.add_worksheet() if (ws): # Создаем формат для заголовка format = wb.add_format() format.set_bold(True) # Жирный шрифт format.set_align('center_across') # По центру for col in columns: # Задаем ширину колонок ws.set_column(col, col, columns_w[col]) # Создаем Заголовок ws.write(0, col, columns[col], format) # Получаем идентификатор задачи (проекта) task_id = db.task_by_url(task)[0] if (task_id): write(db, task_id, ws, wb.add_format()) wb.close() write_info('Export finished!') else: write_error('Can not connect to db: ' + host) _i = 0 def write(db, task_id, ws, format): """ Функция для записи свойств задачи и вложенных задач в файл Excel. db - переменная для работы с базой данных. task_id - идентификатор задачи. ws - лист Excel. format - переменная форматирования рабочей кники Excel. """ global _i _i += 1 # Создадим формат для выравнивания по верхней границы ячейки и переноса по словам format_top_text_wrap = format format_top_text_wrap.set_align('top') format_top_text_wrap.set_text_wrap() # Устанавливаем высоту строки ws.set_row(_i, row_h) # Получаем задачу по идентификатору task = db.task(task_id) # Получаем постановку задачи task_def = db.task_definition(task_id) # Получаем полный путь к задаче name = task[dbtypes.TASK_DATA_PARENT_URL] + task[dbtypes.TASK_DATA_NAME] # Записываем полный путь к задаче ws.write(_i, 0, name, format_top_text_wrap) # Если у задачи есть "Постановка задачи" записываем ее в файл if (task_def): ws.write(_i, 1, html2text.html2text(task_def[dbtypes.MESSAGE_DATA_TEXT]), format_top_text_wrap) # Получаем список пользователей, назначенных на задачу user_name = task[dbtypes.TASK_DATA_ALLOCATED] # Если есть назначенные на задачу пользователи, сохраняем их в файл if (user_name): ws.write(_i, 2, user_name, format_top_text_wrap) # Получаем начальную дату отсчета datetime_2000 = datetime.datetime(2000, 1, 1) # Получаем дату старта задачи datetime_start = datetime_2000 + datetime.timedelta(task[dbtypes.TASK_DATA_OFFSET]) # Сохраняем дату старта в файл ws.write(_i, 3, datetime_start.strftime('%d.%m.%y %H:%M'), format_top_text_wrap) # Получаем дату окончания задачи datetime_stop = datetime_start + datetime.timedelta(task[dbtypes.TASK_DATA_DURATION]) # Сохраняем дату окончания в файл ws.write(_i, 4, datetime_stop.strftime('%d.%m.%y %H:%M'), format_top_text_wrap) # Сохраняем запланированное время ws.write(_i, 5, task[dbtypes.TASK_DATA_PLANNED], format_top_text_wrap) # Если у задачи есть вложенные задачи, так-же сохраняем их в файл for child in db.task_children(task_id): write(db, child[dbtypes.TASK_DATA_ID], ws, format) def connect_db(user, password): """ Функция для соединения с базой данных. user - имя пользователя cerebro. password - пароль пользователя cerebro. """ # Создаем объект базы данных db = database.Database() # Соединяемся с базой данных db.connect(user, password) return db def write_info(text): """ Функция для логирования информационных сообщений. text - текст сообщения. """ print('info: ' + text) def write_error(text): """ Функция для логирования ошибок. text - текст сообщения. """ print('error: ' + text)
c478c0d6aed9b07eae4b4ea4776e7c073d3b4ace
e6a5fce33aad4fcba37842e135a51ba441b06f48
/Python/Errors and Exceptions/Exceptions.py
5f5278b64b8e82541685d00cec1a244dd307ddce
[ "MIT" ]
permissive
pavstar619/HackerRank
6710ddd450b06fbb69da5abad9f570e5e26bbbc0
697ee46b6e621ad884a064047461d7707b1413cd
refs/heads/master
2020-06-18T18:53:53.421685
2020-02-18T09:35:48
2020-02-18T09:35:48
196,408,726
0
0
MIT
2019-07-11T14:18:16
2019-07-11T14:18:16
null
UTF-8
Python
false
false
438
py
class Main: def __init__(self): self.t = int(input()) for i in range(0, self.t): try: self.n, self.m = map(int, input().split()) print(self.n // self.m) except ZeroDivisionError as e: print("Error Code:", e) except ValueError as e: print("Error Code:", e) if __name__ == '__main__': obj = Main()
7c9e8b7bfead44bee572fa7070396b90066e9a6e
746a9c1f65674cd5bcdce6dbd1971b6a16345f9d
/account/forms.py
e907a732e6e142794a14079dcb07a70bcd7fc718
[]
no_license
mazulo/bookmarks
4dc25dc09772663c65698d3cc9f5b653fd409ba9
5c2ce3c3ad811466c63f7b0f3a21bf33a6a28f5e
refs/heads/master
2021-01-10T07:23:37.185414
2016-03-23T06:40:53
2016-03-23T05:40:53
54,158,063
0
0
null
null
null
null
UTF-8
Python
false
false
1,002
py
from django import forms from django.contrib.auth.models import User from .models import Profile class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Repeat password', widget=forms.PasswordInput ) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = ('date_of_birth', 'photo')