blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
3b6a96c0a23de192aef4979a78648815eb239d92
992eeae8bb54ac7eb258994049e74474f090eb36
/13. Exam Prep Questions/08. SoftUni Past Exams/03. Mobile Operator.py
dc6f231cff698f876d138de9b09d21bcfbc97dc0
[]
no_license
elenaborisova/Python-Basics
4ae856ee50a543479902467167f3b8f8169284b8
b7476e3c25c2448f4f12a29e16f20caa10b72038
refs/heads/main
2023-01-04T17:17:17.091347
2020-10-26T22:56:11
2020-10-26T22:56:11
307,164,269
0
0
null
null
null
null
UTF-8
Python
false
false
1,146
py
contract_duration = input() # one or two years contract_type = input() # small middle large or extralarge mobile_data_added = input() # yes or no number_of_months = int(input()) contract_price = 0 if contract_duration == "one": if contract_type == "Small": contract_price = 9.98 elif contract_type == "Middle": contract_price = 18.99 elif contract_type == "Large": contract_price = 25.98 elif contract_type == "ExtraLarge": contract_price = 35.99 elif contract_duration == "two": if contract_type == "Small": contract_price = 8.58 elif contract_type == "Middle": contract_price = 17.09 elif contract_type == "Large": contract_price = 23.59 elif contract_type == "ExtraLarge": contract_price = 31.79 if mobile_data_added == "yes": if contract_price <= 10: contract_price += 5.50 elif contract_price <= 30: contract_price += 4.35 elif contract_price > 30: contract_price += 3.85 if contract_duration == "two": contract_price -= contract_price * 0.0375 print(f"{contract_price * number_of_months:.2f} lv.")
[ "elenaborrisova@gmail.com" ]
elenaborrisova@gmail.com
7c48c8e83a560ecd8044c2f4b2f47c7c852ed284
01733042e84a768b77f64ec24118d0242b2f13b8
/ixnetwork_restpy/testplatform/sessions/ixnetwork/topology/cfmsimulatedmp_67cd757b726cce9c0de4f91be721d97e.py
e957cbfe3617fc809b6fa94e5dd802489dfcbd93
[ "MIT" ]
permissive
slieberth/ixnetwork_restpy
e95673905854bc57e56177911cb3853c7e4c5e26
23eeb24b21568a23d3f31bbd72814ff55eb1af44
refs/heads/master
2023-01-04T06:57:17.513612
2020-10-16T22:30:55
2020-10-16T22:30:55
311,959,027
0
0
NOASSERTION
2020-11-11T12:15:34
2020-11-11T12:06:00
null
UTF-8
Python
false
false
71,282
py
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class CfmSimulatedMp(Base): """Simulated Node Information The CfmSimulatedMp class encapsulates a list of cfmSimulatedMp resources that are managed by the system. A list of resources can be retrieved from the server using the CfmSimulatedMp.find() method. """ __slots__ = () _SDM_NAME = 'cfmSimulatedMp' _SDM_ATT_MAP = { 'Active': 'active', 'AisEnableUnicastMac': 'aisEnableUnicastMac', 'AisInterval': 'aisInterval', 'AisMode': 'aisMode', 'AisPriority': 'aisPriority', 'AisUnicastMac': 'aisUnicastMac', 'AutoDmTimeout': 'autoDmTimeout', 'AutoDmTimer': 'autoDmTimer', 'AutoLbIteration': 'autoLbIteration', 'AutoLbTimeoutInSec': 'autoLbTimeoutInSec', 'AutoLbTimerInSec': 'autoLbTimerInSec', 'AutoLmIteration': 'autoLmIteration', 'AutoLmTimeout': 'autoLmTimeout', 'AutoLmTimer': 'autoLmTimer', 'AutoLtIteration': 'autoLtIteration', 'AutoLtTimeoutInSec': 'autoLtTimeoutInSec', 'AutoLtTimerInSec': 'autoLtTimerInSec', 'AutoLtTtl': 'autoLtTtl', 'AutodmIteration': 'autodmIteration', 'CVlanId': 'cVlanId', 'CVlanPriority': 'cVlanPriority', 'CVlanTpid': 'cVlanTpid', 'CciInterval': 'cciInterval', 'CcmLmmTxFcf': 'ccmLmmTxFcf', 'CcmLmmTxFcfStepPer100mSec': 'ccmLmmTxFcfStepPer100mSec', 'CcmPriority': 'ccmPriority', 'CcmRxFcb': 'ccmRxFcb', 'CcmRxFcbStepPer100mSec': 'ccmRxFcbStepPer100mSec', 'ChassisId': 'chassisId', 'ChassisIdLength': 'chassisIdLength', 'ChassisIdSubType': 'chassisIdSubType', 'Count': 'count', 'DataTlvLength': 'dataTlvLength', 'DataTlvValue': 'dataTlvValue', 'DescriptiveName': 'descriptiveName', 'DmAllRemoteMeps': 'dmAllRemoteMeps', 'DmDestinationMacAddress': 'dmDestinationMacAddress', 'DmMethod': 'dmMethod', 'DmPriority': 'dmPriority', 'EnableAisRx': 'enableAisRx', 'EnableAutoDm': 'enableAutoDm', 'EnableAutoLb': 'enableAutoLb', 'EnableAutoLm': 'enableAutoLm', 'EnableAutoLt': 'enableAutoLt', 'EnableDataTlv': 'enableDataTlv', 'EnableInterfaceStatusTlv': 'enableInterfaceStatusTlv', 'EnableLckRx': 'enableLckRx', 'EnableLmCounterUpdate': 'enableLmCounterUpdate', 'EnableOrganizationSpecificTlv': 'enableOrganizationSpecificTlv', 'EnablePortStatusTlv': 'enablePortStatusTlv', 'EnableSenderIdTlv': 'enableSenderIdTlv', 'EnableTstRx': 'enableTstRx', 'EnableVlan': 'enableVlan', 'InterRemoteMepRxIncrementStep': 'interRemoteMepRxIncrementStep', 'InterRemoteMepTxIncrementStep': 'interRemoteMepTxIncrementStep', 'LbAllRemoteMeps': 'lbAllRemoteMeps', 'LbDestinationMacAddress': 'lbDestinationMacAddress', 'LbmPriority': 'lbmPriority', 'LckEnableUnicastMac': 'lckEnableUnicastMac', 'LckInterval': 'lckInterval', 'LckMode': 'lckMode', 'LckPriority': 'lckPriority', 'LckSupportAisGeneration': 'lckSupportAisGeneration', 'LckUnicastMac': 'lckUnicastMac', 'LmAllRemoteMeps': 'lmAllRemoteMeps', 'LmDestinationMacAddress': 'lmDestinationMacAddress', 'LmMethodType': 'lmMethodType', 'LmmPriority': 'lmmPriority', 'LmrPriority': 'lmrPriority', 'LmrRxFcf': 'lmrRxFcf', 'LmrRxFcfStepPer100mSec': 'lmrRxFcfStepPer100mSec', 'LmrTxFcb': 'lmrTxFcb', 'LmrTxFcbStepPer100mSec': 'lmrTxFcbStepPer100mSec', 'LtAllRemoteMeps': 'ltAllRemoteMeps', 'LtDestinationMacAddress': 'ltDestinationMacAddress', 'LtmPriority': 'ltmPriority', 'ManagementAddress': 'managementAddress', 'ManagementAddressDomain': 'managementAddressDomain', 'ManagementAddressDomainLength': 'managementAddressDomainLength', 'ManagementAddressLength': 'managementAddressLength', 'MdMegLevel': 'mdMegLevel', 'MdName': 'mdName', 'MdNameFormat': 'mdNameFormat', 'MegId': 'megId', 'MegIdFormat': 'megIdFormat', 'MepId': 'mepId', 'MpType': 'mpType', 'Name': 'name', 'NumberOfCustomTLVs': 'numberOfCustomTLVs', 'OrganizationSpecificTlvLength': 'organizationSpecificTlvLength', 'OrganizationSpecificTlvValue': 'organizationSpecificTlvValue', 'OverrideVlanPriority': 'overrideVlanPriority', 'Rdi': 'rdi', 'SVlanId': 'sVlanId', 'SVlanPriority': 'sVlanPriority', 'SVlanTpid': 'sVlanTpid', 'ShortMaName': 'shortMaName', 'ShortMaNameFormat': 'shortMaNameFormat', 'TstEnableUnicastMac': 'tstEnableUnicastMac', 'TstIncrementPacketLength': 'tstIncrementPacketLength', 'TstInitialPatternValue': 'tstInitialPatternValue', 'TstInterval': 'tstInterval', 'TstMode': 'tstMode', 'TstOverwriteSequenceNumber': 'tstOverwriteSequenceNumber', 'TstPacketLength': 'tstPacketLength', 'TstPacketLengthStep': 'tstPacketLengthStep', 'TstPatternType': 'tstPatternType', 'TstPriority': 'tstPriority', 'TstSequenceNumber': 'tstSequenceNumber', 'TstTestType': 'tstTestType', 'TstUnicastMac': 'tstUnicastMac', 'VlanId': 'vlanId', 'VlanPriority': 'vlanPriority', 'VlanStacking': 'vlanStacking', 'VlanTpid': 'vlanTpid', } def __init__(self, parent): super(CfmSimulatedMp, self).__init__(parent) @property def CfmCustomTLVList(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.cfmcustomtlvlist_798bcbc04fddcff054434d56d2b00117.CfmCustomTLVList): An instance of the CfmCustomTLVList class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.cfmcustomtlvlist_798bcbc04fddcff054434d56d2b00117 import CfmCustomTLVList return CfmCustomTLVList(self) @property def StartCcmSimulatedMpParams(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.startccmsimulatedmpparams_4c311ea185eeaa4106e3c4181a4ec347.StartCcmSimulatedMpParams): An instance of the StartCcmSimulatedMpParams class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.startccmsimulatedmpparams_4c311ea185eeaa4106e3c4181a4ec347 import StartCcmSimulatedMpParams return StartCcmSimulatedMpParams(self)._select() @property def StopCcmSimulatedMpParams(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.stopccmsimulatedmpparams_93b05cff27480ec5b14accd9b8a754a7.StopCcmSimulatedMpParams): An instance of the StopCcmSimulatedMpParams class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.stopccmsimulatedmpparams_93b05cff27480ec5b14accd9b8a754a7 import StopCcmSimulatedMpParams return StopCcmSimulatedMpParams(self)._select() @property def Active(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Activate/Deactivate Configuration """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Active'])) @property def AisEnableUnicastMac(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable AIS in unicast mode to the specified MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AisEnableUnicastMac'])) @property def AisInterval(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval between two AIS PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AisInterval'])) @property def AisMode(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Specifies Alarm Indication Signal Mode. Can be trigged from LCK only if set to Auto Mode. Manually Start or Stop otherwise. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AisMode'])) @property def AisPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for AIS PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AisPriority'])) @property def AisUnicastMac(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): The MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AisUnicastMac'])) @property def AutoDmTimeout(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Timeout value (in sec) of waiting for DMR of respective DMM. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoDmTimeout'])) @property def AutoDmTimer(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval (in sec) between two DMM PDUs to be sent. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoDmTimer'])) @property def AutoLbIteration(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Number of LBM PDUs to be sent. 0 for infinite timer. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLbIteration'])) @property def AutoLbTimeoutInSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Timeout value (in sec) of waiting for LBR of respective LBM. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLbTimeoutInSec'])) @property def AutoLbTimerInSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval (in sec) between two LBM PDUs to be sent. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLbTimerInSec'])) @property def AutoLmIteration(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Number of LMM PDUs to be sent. 0 for infinite timer. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLmIteration'])) @property def AutoLmTimeout(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Timeout value (in msec) of waiting for LMR of respective LMM. Must be multiple of 100. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLmTimeout'])) @property def AutoLmTimer(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval (in msec) between two LMM PDUs to be sent. Must be multiples of 100. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLmTimer'])) @property def AutoLtIteration(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Number of LTM PDUs to be sent. 0 for infinite timer. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLtIteration'])) @property def AutoLtTimeoutInSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Timeout value (in sec) of waiting for LTR of respective LTM. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLtTimeoutInSec'])) @property def AutoLtTimerInSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval (in sec) between two LTM PDUs to be sent. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLtTimerInSec'])) @property def AutoLtTtl(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TTL for LBM PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutoLtTtl'])) @property def AutodmIteration(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Number of DMM PDUs to be sent. 0 for infinite timer. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['AutodmIteration'])) @property def CVlanId(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): C-VLAN ID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CVlanId'])) @property def CVlanPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): C-VLAN Priority """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CVlanPriority'])) @property def CVlanTpid(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): C-VLAN TPID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CVlanTpid'])) @property def CciInterval(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval between two CCM PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CciInterval'])) @property def CcmLmmTxFcf(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TxFCf value in CCM (dual mode) or LMM (single mode) PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CcmLmmTxFcf'])) @property def CcmLmmTxFcfStepPer100mSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TxFCf step value per 100ms in CCM (dual mode) or LMM (single mode) PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CcmLmmTxFcfStepPer100mSec'])) @property def CcmPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for CCM PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CcmPriority'])) @property def CcmRxFcb(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): RxFCb value in CCM (dual mode) PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CcmRxFcb'])) @property def CcmRxFcbStepPer100mSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): RxFCb step value per 100ms in CCM (dual mode) PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['CcmRxFcbStepPer100mSec'])) @property def ChassisId(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Chassis ID for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ChassisId'])) @property def ChassisIdLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Chassis ID Length for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ChassisIdLength'])) @property def ChassisIdSubType(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Chassis ID SubType for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ChassisIdSubType'])) @property def Count(self): """ Returns ------- - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. """ return self._get_attribute(self._SDM_ATT_MAP['Count']) @property def DataTlvLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Data TLV Length """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['DataTlvLength'])) @property def DataTlvValue(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Data TLV Value """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['DataTlvValue'])) @property def DescriptiveName(self): """ Returns ------- - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. """ return self._get_attribute(self._SDM_ATT_MAP['DescriptiveName']) @property def DmAllRemoteMeps(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables DMM to be sent for all remote MEPs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['DmAllRemoteMeps'])) @property def DmDestinationMacAddress(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['DmDestinationMacAddress'])) @property def DmMethod(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Specifies One Way or Two Way Delay Measurement Method. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['DmMethod'])) @property def DmPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for DMM PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['DmPriority'])) @property def EnableAisRx(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables AIS PDUs to be processed in this MEP upon receiving at port. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableAisRx'])) @property def EnableAutoDm(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Periodic Delay Measurement. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableAutoDm'])) @property def EnableAutoLb(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Periodic Loopback. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableAutoLb'])) @property def EnableAutoLm(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Periodic Loss Measurement. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableAutoLm'])) @property def EnableAutoLt(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Periodic Link Trace. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableAutoLt'])) @property def EnableDataTlv(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Data TLV for all applicable PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableDataTlv'])) @property def EnableInterfaceStatusTlv(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Interface Status TLV for all applicable PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableInterfaceStatusTlv'])) @property def EnableLckRx(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables LCK PDUs to be processed in this MEP upon receiving at port. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableLckRx'])) @property def EnableLmCounterUpdate(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable updating the counter value for subsequent PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableLmCounterUpdate'])) @property def EnableOrganizationSpecificTlv(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Organization Specific TLV for all applicable PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableOrganizationSpecificTlv'])) @property def EnablePortStatusTlv(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Port Status TLV for all applicable PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnablePortStatusTlv'])) @property def EnableSenderIdTlv(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Sender ID TLV for all applicable PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableSenderIdTlv'])) @property def EnableTstRx(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables TST PDUs to be processed in this MEP upon receiving at port. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableTstRx'])) @property def EnableVlan(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable VLAN for this MP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnableVlan'])) @property def InterRemoteMepRxIncrementStep(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Inter Remote MEP Rx Increment Step. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['InterRemoteMepRxIncrementStep'])) @property def InterRemoteMepTxIncrementStep(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Inter Remote MEP Tx Increment Step. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['InterRemoteMepTxIncrementStep'])) @property def LbAllRemoteMeps(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables LBM to be sent for all remote MEPs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LbAllRemoteMeps'])) @property def LbDestinationMacAddress(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LbDestinationMacAddress'])) @property def LbmPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for LBM PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LbmPriority'])) @property def LckEnableUnicastMac(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable LCK in unicast mode to the specified MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LckEnableUnicastMac'])) @property def LckInterval(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval between two LCK PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LckInterval'])) @property def LckMode(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Specifies LCK Mode. Can be trigged from TST only if set to Auto Mode. Manually Start or Stop otherwise. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LckMode'])) @property def LckPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for LCK PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LckPriority'])) @property def LckSupportAisGeneration(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable or disable AIS PDU generation. Needs AIS mode to be set to Auto. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LckSupportAisGeneration'])) @property def LckUnicastMac(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MAC Address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LckUnicastMac'])) @property def LmAllRemoteMeps(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables LMM to be sent for all remote MEPs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmAllRemoteMeps'])) @property def LmDestinationMacAddress(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmDestinationMacAddress'])) @property def LmMethodType(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Loss Measurement Method - One Way or Two Way. For Two way, CCM PDUs are used. LMM & LMR otherwise. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmMethodType'])) @property def LmmPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for LMM PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmmPriority'])) @property def LmrPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for LMR PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmrPriority'])) @property def LmrRxFcf(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): RxFCf value of LMR PDU (Single Mode). """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmrRxFcf'])) @property def LmrRxFcfStepPer100mSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): RxFCf step value per 100ms of LMR PDU (Single Mode). """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmrRxFcfStepPer100mSec'])) @property def LmrTxFcb(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TxFCb value in LMR PDU (Single mode) i.e. TxFCf of CCM or LMM. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmrTxFcb'])) @property def LmrTxFcbStepPer100mSec(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TxFCb step value per 100ms in LMR PDU (Single mode). """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LmrTxFcbStepPer100mSec'])) @property def LtAllRemoteMeps(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enables LTM to be sent for all remote MEPs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LtAllRemoteMeps'])) @property def LtDestinationMacAddress(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LtDestinationMacAddress'])) @property def LtmPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for LTM PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['LtmPriority'])) @property def ManagementAddress(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Management Address for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ManagementAddress'])) @property def ManagementAddressDomain(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Management Address Domain for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ManagementAddressDomain'])) @property def ManagementAddressDomainLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Management Address Domain Length for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ManagementAddressDomainLength'])) @property def ManagementAddressLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Management Address Length for Sender ID TLV. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ManagementAddressLength'])) @property def MdMegLevel(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MD/MEG Level in which this MP belongs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MdMegLevel'])) @property def MdName(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MD Name for the selected MD Level. For MD Name Format MAC + Int, Please Use MAC-Int eg. 11:22:33:44:55:66-1. For Others, Use Any String. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MdName'])) @property def MdNameFormat(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Format for Maintenance Domain Name. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MdNameFormat'])) @property def MegId(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MEG ID (Y.1731 Mode). """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MegId'])) @property def MegIdFormat(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Format for MEG ID (Y.1731 Mode). Non-ICC formats are supported only if 'Allow CFM MAID Formats' is enabled. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MegIdFormat'])) @property def MepId(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): MP Identifier. Must be unique in one MA. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MepId'])) @property def MpType(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Select MP type MIP or MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['MpType'])) @property def Name(self): """ Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): self._set_attribute(self._SDM_ATT_MAP['Name'], value) @property def NumberOfCustomTLVs(self): """ Returns ------- - number: Number of Custom TLVs for PDUs. """ return self._get_attribute(self._SDM_ATT_MAP['NumberOfCustomTLVs']) @NumberOfCustomTLVs.setter def NumberOfCustomTLVs(self, value): self._set_attribute(self._SDM_ATT_MAP['NumberOfCustomTLVs'], value) @property def OrganizationSpecificTlvLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Organization Specific TLV Length """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['OrganizationSpecificTlvLength'])) @property def OrganizationSpecificTlvValue(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Organization Specific TLV Value """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['OrganizationSpecificTlvValue'])) @property def OverrideVlanPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Override VLAN Priority value for PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['OverrideVlanPriority'])) @property def Rdi(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Remote Defect Indication. Auto Update - RDI On if there is a defect in remote MEP. On or Off - Turn on or off RDI intentionally. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['Rdi'])) @property def SVlanId(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): S-VLAN ID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SVlanId'])) @property def SVlanPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): S-VLAN Priority """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SVlanPriority'])) @property def SVlanTpid(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): S-VLAN TPID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SVlanTpid'])) @property def ShortMaName(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Short Maintenance Association Name. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ShortMaName'])) @property def ShortMaNameFormat(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Format for Maintenance Association Name. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['ShortMaNameFormat'])) @property def TstEnableUnicastMac(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Enable TST in unicast mode to the specified MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstEnableUnicastMac'])) @property def TstIncrementPacketLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Increment Packet Length for subsequent TST PDUs. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstIncrementPacketLength'])) @property def TstInitialPatternValue(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Initial Pattern Value of Test. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstInitialPatternValue'])) @property def TstInterval(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Interval between two TST PDUs (in ms). """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstInterval'])) @property def TstMode(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): TST Mode On or Off. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstMode'])) @property def TstOverwriteSequenceNumber(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Overwrite Sequence Number using specified value. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstOverwriteSequenceNumber'])) @property def TstPacketLength(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Packet Length of TST PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstPacketLength'])) @property def TstPacketLengthStep(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Increment for Packet Length Step. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstPacketLengthStep'])) @property def TstPatternType(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Pattern Type of Test. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstPatternType'])) @property def TstPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority for TST PDU. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstPriority'])) @property def TstSequenceNumber(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Sequence Number of TST PDU. Effective only if overridden. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstSequenceNumber'])) @property def TstTestType(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Test Type In or Out Service. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstTestType'])) @property def TstUnicastMac(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): The MAC address of the remote MEP. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['TstUnicastMac'])) @property def VlanId(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN ID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['VlanId'])) @property def VlanPriority(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN Priority """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['VlanPriority'])) @property def VlanStacking(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Single or Stacked VLAN Selection. """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['VlanStacking'])) @property def VlanTpid(self): """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): VLAN TPID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['VlanTpid'])) def update(self, Name=None, NumberOfCustomTLVs=None): """Updates cfmSimulatedMp resource on the server. This method has some named parameters with a type: obj (Multivalue). The Multivalue class has documentation that details the possible values for those named parameters. Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - NumberOfCustomTLVs (number): Number of Custom TLVs for PDUs. Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def find(self, Count=None, DescriptiveName=None, Name=None, NumberOfCustomTLVs=None): """Finds and retrieves cfmSimulatedMp resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve cfmSimulatedMp resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all cfmSimulatedMp resources from the server. Args ---- - Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. - DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - NumberOfCustomTLVs (number): Number of Custom TLVs for PDUs. Returns ------- - self: This instance with matching cfmSimulatedMp resources retrieved from the server available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): """Retrieves a single instance of cfmSimulatedMp data from the server. Args ---- - href (str): An href to the instance to be retrieved Returns ------- - self: This instance with the cfmSimulatedMp resources from the server available through an iterator or index Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def get_device_ids(self, PortNames=None, Active=None, AisEnableUnicastMac=None, AisInterval=None, AisMode=None, AisPriority=None, AisUnicastMac=None, AutoDmTimeout=None, AutoDmTimer=None, AutoLbIteration=None, AutoLbTimeoutInSec=None, AutoLbTimerInSec=None, AutoLmIteration=None, AutoLmTimeout=None, AutoLmTimer=None, AutoLtIteration=None, AutoLtTimeoutInSec=None, AutoLtTimerInSec=None, AutoLtTtl=None, AutodmIteration=None, CVlanId=None, CVlanPriority=None, CVlanTpid=None, CciInterval=None, CcmLmmTxFcf=None, CcmLmmTxFcfStepPer100mSec=None, CcmPriority=None, CcmRxFcb=None, CcmRxFcbStepPer100mSec=None, ChassisId=None, ChassisIdLength=None, ChassisIdSubType=None, DataTlvLength=None, DataTlvValue=None, DmAllRemoteMeps=None, DmDestinationMacAddress=None, DmMethod=None, DmPriority=None, EnableAisRx=None, EnableAutoDm=None, EnableAutoLb=None, EnableAutoLm=None, EnableAutoLt=None, EnableDataTlv=None, EnableInterfaceStatusTlv=None, EnableLckRx=None, EnableLmCounterUpdate=None, EnableOrganizationSpecificTlv=None, EnablePortStatusTlv=None, EnableSenderIdTlv=None, EnableTstRx=None, EnableVlan=None, InterRemoteMepRxIncrementStep=None, InterRemoteMepTxIncrementStep=None, LbAllRemoteMeps=None, LbDestinationMacAddress=None, LbmPriority=None, LckEnableUnicastMac=None, LckInterval=None, LckMode=None, LckPriority=None, LckSupportAisGeneration=None, LckUnicastMac=None, LmAllRemoteMeps=None, LmDestinationMacAddress=None, LmMethodType=None, LmmPriority=None, LmrPriority=None, LmrRxFcf=None, LmrRxFcfStepPer100mSec=None, LmrTxFcb=None, LmrTxFcbStepPer100mSec=None, LtAllRemoteMeps=None, LtDestinationMacAddress=None, LtmPriority=None, ManagementAddress=None, ManagementAddressDomain=None, ManagementAddressDomainLength=None, ManagementAddressLength=None, MdMegLevel=None, MdName=None, MdNameFormat=None, MegId=None, MegIdFormat=None, MepId=None, MpType=None, OrganizationSpecificTlvLength=None, OrganizationSpecificTlvValue=None, OverrideVlanPriority=None, Rdi=None, SVlanId=None, SVlanPriority=None, SVlanTpid=None, ShortMaName=None, ShortMaNameFormat=None, TstEnableUnicastMac=None, TstIncrementPacketLength=None, TstInitialPatternValue=None, TstInterval=None, TstMode=None, TstOverwriteSequenceNumber=None, TstPacketLength=None, TstPacketLengthStep=None, TstPatternType=None, TstPriority=None, TstSequenceNumber=None, TstTestType=None, TstUnicastMac=None, VlanId=None, VlanPriority=None, VlanStacking=None, VlanTpid=None): """Base class infrastructure that gets a list of cfmSimulatedMp device ids encapsulated by this object. Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object. Args ---- - PortNames (str): optional regex of port names - Active (str): optional regex of active - AisEnableUnicastMac (str): optional regex of aisEnableUnicastMac - AisInterval (str): optional regex of aisInterval - AisMode (str): optional regex of aisMode - AisPriority (str): optional regex of aisPriority - AisUnicastMac (str): optional regex of aisUnicastMac - AutoDmTimeout (str): optional regex of autoDmTimeout - AutoDmTimer (str): optional regex of autoDmTimer - AutoLbIteration (str): optional regex of autoLbIteration - AutoLbTimeoutInSec (str): optional regex of autoLbTimeoutInSec - AutoLbTimerInSec (str): optional regex of autoLbTimerInSec - AutoLmIteration (str): optional regex of autoLmIteration - AutoLmTimeout (str): optional regex of autoLmTimeout - AutoLmTimer (str): optional regex of autoLmTimer - AutoLtIteration (str): optional regex of autoLtIteration - AutoLtTimeoutInSec (str): optional regex of autoLtTimeoutInSec - AutoLtTimerInSec (str): optional regex of autoLtTimerInSec - AutoLtTtl (str): optional regex of autoLtTtl - AutodmIteration (str): optional regex of autodmIteration - CVlanId (str): optional regex of cVlanId - CVlanPriority (str): optional regex of cVlanPriority - CVlanTpid (str): optional regex of cVlanTpid - CciInterval (str): optional regex of cciInterval - CcmLmmTxFcf (str): optional regex of ccmLmmTxFcf - CcmLmmTxFcfStepPer100mSec (str): optional regex of ccmLmmTxFcfStepPer100mSec - CcmPriority (str): optional regex of ccmPriority - CcmRxFcb (str): optional regex of ccmRxFcb - CcmRxFcbStepPer100mSec (str): optional regex of ccmRxFcbStepPer100mSec - ChassisId (str): optional regex of chassisId - ChassisIdLength (str): optional regex of chassisIdLength - ChassisIdSubType (str): optional regex of chassisIdSubType - DataTlvLength (str): optional regex of dataTlvLength - DataTlvValue (str): optional regex of dataTlvValue - DmAllRemoteMeps (str): optional regex of dmAllRemoteMeps - DmDestinationMacAddress (str): optional regex of dmDestinationMacAddress - DmMethod (str): optional regex of dmMethod - DmPriority (str): optional regex of dmPriority - EnableAisRx (str): optional regex of enableAisRx - EnableAutoDm (str): optional regex of enableAutoDm - EnableAutoLb (str): optional regex of enableAutoLb - EnableAutoLm (str): optional regex of enableAutoLm - EnableAutoLt (str): optional regex of enableAutoLt - EnableDataTlv (str): optional regex of enableDataTlv - EnableInterfaceStatusTlv (str): optional regex of enableInterfaceStatusTlv - EnableLckRx (str): optional regex of enableLckRx - EnableLmCounterUpdate (str): optional regex of enableLmCounterUpdate - EnableOrganizationSpecificTlv (str): optional regex of enableOrganizationSpecificTlv - EnablePortStatusTlv (str): optional regex of enablePortStatusTlv - EnableSenderIdTlv (str): optional regex of enableSenderIdTlv - EnableTstRx (str): optional regex of enableTstRx - EnableVlan (str): optional regex of enableVlan - InterRemoteMepRxIncrementStep (str): optional regex of interRemoteMepRxIncrementStep - InterRemoteMepTxIncrementStep (str): optional regex of interRemoteMepTxIncrementStep - LbAllRemoteMeps (str): optional regex of lbAllRemoteMeps - LbDestinationMacAddress (str): optional regex of lbDestinationMacAddress - LbmPriority (str): optional regex of lbmPriority - LckEnableUnicastMac (str): optional regex of lckEnableUnicastMac - LckInterval (str): optional regex of lckInterval - LckMode (str): optional regex of lckMode - LckPriority (str): optional regex of lckPriority - LckSupportAisGeneration (str): optional regex of lckSupportAisGeneration - LckUnicastMac (str): optional regex of lckUnicastMac - LmAllRemoteMeps (str): optional regex of lmAllRemoteMeps - LmDestinationMacAddress (str): optional regex of lmDestinationMacAddress - LmMethodType (str): optional regex of lmMethodType - LmmPriority (str): optional regex of lmmPriority - LmrPriority (str): optional regex of lmrPriority - LmrRxFcf (str): optional regex of lmrRxFcf - LmrRxFcfStepPer100mSec (str): optional regex of lmrRxFcfStepPer100mSec - LmrTxFcb (str): optional regex of lmrTxFcb - LmrTxFcbStepPer100mSec (str): optional regex of lmrTxFcbStepPer100mSec - LtAllRemoteMeps (str): optional regex of ltAllRemoteMeps - LtDestinationMacAddress (str): optional regex of ltDestinationMacAddress - LtmPriority (str): optional regex of ltmPriority - ManagementAddress (str): optional regex of managementAddress - ManagementAddressDomain (str): optional regex of managementAddressDomain - ManagementAddressDomainLength (str): optional regex of managementAddressDomainLength - ManagementAddressLength (str): optional regex of managementAddressLength - MdMegLevel (str): optional regex of mdMegLevel - MdName (str): optional regex of mdName - MdNameFormat (str): optional regex of mdNameFormat - MegId (str): optional regex of megId - MegIdFormat (str): optional regex of megIdFormat - MepId (str): optional regex of mepId - MpType (str): optional regex of mpType - OrganizationSpecificTlvLength (str): optional regex of organizationSpecificTlvLength - OrganizationSpecificTlvValue (str): optional regex of organizationSpecificTlvValue - OverrideVlanPriority (str): optional regex of overrideVlanPriority - Rdi (str): optional regex of rdi - SVlanId (str): optional regex of sVlanId - SVlanPriority (str): optional regex of sVlanPriority - SVlanTpid (str): optional regex of sVlanTpid - ShortMaName (str): optional regex of shortMaName - ShortMaNameFormat (str): optional regex of shortMaNameFormat - TstEnableUnicastMac (str): optional regex of tstEnableUnicastMac - TstIncrementPacketLength (str): optional regex of tstIncrementPacketLength - TstInitialPatternValue (str): optional regex of tstInitialPatternValue - TstInterval (str): optional regex of tstInterval - TstMode (str): optional regex of tstMode - TstOverwriteSequenceNumber (str): optional regex of tstOverwriteSequenceNumber - TstPacketLength (str): optional regex of tstPacketLength - TstPacketLengthStep (str): optional regex of tstPacketLengthStep - TstPatternType (str): optional regex of tstPatternType - TstPriority (str): optional regex of tstPriority - TstSequenceNumber (str): optional regex of tstSequenceNumber - TstTestType (str): optional regex of tstTestType - TstUnicastMac (str): optional regex of tstUnicastMac - VlanId (str): optional regex of vlanId - VlanPriority (str): optional regex of vlanPriority - VlanStacking (str): optional regex of vlanStacking - VlanTpid (str): optional regex of vlanTpid Returns ------- - list(int): A list of device ids that meets the regex criteria provided in the method parameters Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._get_ngpf_device_ids(locals()) def Abort(self): """Executes the abort operation on the server. Abort CPF control plane (equals to demote to kUnconfigured state). Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } return self._execute('abort', payload=payload, response_object=None) def ActivateMpSimulated(self, *args, **kwargs): """Executes the activateMpSimulated operation on the server. Activate Simulated MP The IxNetwork model allows for multiple method Signatures with the same name while python does not. activateMpSimulated(SessionIndices=list) ---------------------------------------- - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 activateMpSimulated(SessionIndices=string) ------------------------------------------ - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('activateMpSimulated', payload=payload, response_object=None) def DeactivateMpSimulated(self, *args, **kwargs): """Executes the deactivateMpSimulated operation on the server. Deactivate Simulated MP The IxNetwork model allows for multiple method Signatures with the same name while python does not. deactivateMpSimulated(SessionIndices=list) ------------------------------------------ - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 deactivateMpSimulated(SessionIndices=string) -------------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('deactivateMpSimulated', payload=payload, response_object=None) def Start(self): """Executes the start operation on the server. Start CPF control plane (equals to promote to negotiated state). Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } return self._execute('start', payload=payload, response_object=None) def StartCcmSimulated(self, *args, **kwargs): """Executes the startCcmSimulated operation on the server. Start CCM The IxNetwork model allows for multiple method Signatures with the same name while python does not. startCcmSimulated(SessionIndices=list) -------------------------------------- - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 startCcmSimulated(SessionIndices=string) ---------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('startCcmSimulated', payload=payload, response_object=None) def StartCcmSimulatedMp(self, *args, **kwargs): """Executes the startCcmSimulatedMp operation on the server. Start CCM PDU Transmission DEPRECATED startCcmSimulatedMp(Arg2=list)list --------------------------------------------- - Arg2 (list(number)): List of indices into the network info. An empty list indicates all instances in the node specific data. - Returns list(str): ID to associate each async action invocation Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('startCcmSimulatedMp', payload=payload, response_object=None) def Stop(self): """Executes the stop operation on the server. Stop CPF control plane (equals to demote to PreValidated-DoDDone state). Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } return self._execute('stop', payload=payload, response_object=None) def StopCcmSimulated(self, *args, **kwargs): """Executes the stopCcmSimulated operation on the server. Stop CCM The IxNetwork model allows for multiple method Signatures with the same name while python does not. stopCcmSimulated(SessionIndices=list) ------------------------------------- - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 stopCcmSimulated(SessionIndices=string) --------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('stopCcmSimulated', payload=payload, response_object=None) def StopCcmSimulatedMp(self, *args, **kwargs): """Executes the stopCcmSimulatedMp operation on the server. Stop CCM PDU Transmission DEPRECATED stopCcmSimulatedMp(Arg2=list)list -------------------------------------------- - Arg2 (list(number)): List of indices into the network info. An empty list indicates all instances in the node specific data. - Returns list(str): ID to associate each async action invocation Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('stopCcmSimulatedMp', payload=payload, response_object=None)
[ "andy.balogh@keysight.com" ]
andy.balogh@keysight.com
d1b6fae5395dae27e6940600476a13e19aa1ece8
38a9eda76b10e0cceafc4a255f79c22df8847001
/logrec/dataprep/split/samecase/random_word_selector_for_splitting.py
a48b3453b655ee7984a4fe21c6ecacb18a091c73
[ "MIT" ]
permissive
hlibbabii/log-recommender
4272bb1c91c5c213ee4944930584af713da01c6d
03c975da4029676acb2c29f5915e30b2b29fce6c
refs/heads/master
2022-12-21T06:28:04.702117
2020-03-27T11:39:30
2020-03-27T11:39:30
123,821,082
2
1
MIT
2022-11-22T03:57:00
2018-03-04T19:25:35
Python
UTF-8
Python
false
false
3,689
py
import logging import math import os import random import re from collections import defaultdict from logrec.dataprep import base_project_dir logger = logging.getLogger(__name__) base_dataset_dir = f'{base_project_dir}/nn-data/devanbu_no_replaced_identifier_split_no_tabs_new_splits3_under_5000_15_percent/' path_to_labeled_data = os.path.join(base_dataset_dir, 'sample.txt') path_to_labeled_data2 = os.path.join(base_dataset_dir, 'sample2.txt') vocab_file = os.path.join(base_dataset_dir, 'vocab.txt') def get_already_selected_words(): selected_words = defaultdict(list) key_to_labeled_data = {} with open(path_to_labeled_data, 'r') as f: for line in f: split_line = line[:-1].split('|') original_word = split_line[0] key_to_labeled_data[original_word] = line[:-1] selected_words[len(original_word)].append(original_word) selected_words.default_factory = None return selected_words, key_to_labeled_data def print_dict_diffs(dict1, dict2, max_possible_word_length=100): for i in range(max_possible_word_length): if i + 1 in dict1 or i + 1 in dict2: print(f'{i+1}: {dict1[i+1] if i+1 in dict1 else 0} --> {dict2[i+1] if i+1 in dict2 else 0}') def log_proportional(dict, degree, total_sum): dict_log = {} dict_log_rounded = {} for key, val in dict.items(): dict_log[key] = math.log(val) ** degree all_log = sum(dict_log.values()) for key, val in dict.items(): dict_log[key] = dict_log[key] / all_log * total_sum dict_log_rounded[key] = math.ceil(dict_log[key]) all_log_prop_rounded = sum(dict_log_rounded.values()) n_to_substract = all_log_prop_rounded - total_sum keys_of_largest = sorted(dict_log_rounded.items(), key=lambda x: x[1], reverse=True)[:n_to_substract] for key, _ in keys_of_largest: dict_log_rounded[key] -= 1 return dict_log_rounded def get_dict(vocab_file): dict = defaultdict(list) with open(vocab_file, 'r') as f: for l in f: line = l.split(" ") dict[len(line[0])].append(line[0]) dict.default_factory = None return dict def randomly_select_words_from_dict(dict, already_selected_words=defaultdict(list)): already_selected_words.default_factory = list dict_stats = {k: len(v) for k, v in dict.items()} dict_stats_log_proportional = log_proportional(dict_stats, 5, 1000) items = dict_stats_log_proportional.items() for k, v in items: while v > len(already_selected_words[k]): picked_word = random.choice(dict[k]) if picked_word not in already_selected_words[k] and re.fullmatch("[a-z]+", picked_word): already_selected_words[k].append(picked_word) return already_selected_words def write_sample_to_files(length_to_words_dict, original_to_labeled_data, file): words = [w for k, w_list in length_to_words_dict.items() for w in w_list] with open(file, 'w') as f: for w in words: if w in original_to_labeled_data: w = original_to_labeled_data[w] f.write(f'{w}\n') if __name__ == '__main__': dict = get_dict(vocab_file) dict_stats = {k: len(v) for k, v in dict.items()} dict_stats_log_proportional = log_proportional(dict_stats, 5, 1000) already_selected_words, key_to_labeled_data = get_already_selected_words() selected_words = randomly_select_words_from_dict(dict, already_selected_words) write_sample_to_files(selected_words, key_to_labeled_data, path_to_labeled_data2) print_dict_diffs({k: len(v) for k, v in already_selected_words.items()}, dict_stats_log_proportional)
[ "hlibbabii@gmail.com" ]
hlibbabii@gmail.com
1d06373897f48a555acb6a7d135865bc7e91c296
a7f16c95f973905e880ad4dc277fbba890486654
/wildlifecompliance/migrations/0156_merge_20190404_1353.py
d96e85d324a57c0b6ffd2aafb82f55f0ed27fe98
[ "Apache-2.0" ]
permissive
dbca-wa/wildlifecompliance
9e98e9c093aeb25dbb7ff8d107be47e29bcd05e1
cb12ad9ea1171f10b5297cdb7e1eb6ea484e633d
refs/heads/master
2023-08-08T14:37:05.824428
2023-07-31T02:57:23
2023-07-31T02:57:23
232,276,030
1
17
NOASSERTION
2023-07-31T02:57:24
2020-01-07T08:12:53
Python
UTF-8
Python
false
false
361
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-04-04 05:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0155_merge_20190329_1202'), ('wildlifecompliance', '0153_auto_20190401_1535'), ] operations = [ ]
[ "brendan.blackford@dbca.wa.gov.au" ]
brendan.blackford@dbca.wa.gov.au
74b80d103cc37eb12487e7e844178fe41b54c302
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_mjsull_question3.py
b771467002762d05249323aa63a62a9f07232319
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
3,080
py
import sys out_file = open(sys.argv[2], 'w') from math import sqrt def mrange(start, stop, step): while start < stop: yield start start += step def is_prime(num): if num == 2: return True if (num < 2) or (num % 2 == 0): return False return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2)) def rwh_primes2(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] sieve = [True] * (n/3) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1) sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1) return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]] with open(sys.argv[1]) as in_file: num_cases = int(in_file.readline().rstrip()) for i in range(1, num_cases + 1): coin_length, num_coins = in_file.readline().split() num_coins = int(num_coins) coin_length = int(coin_length) out_file.write('Case #' + str(i) + ':\n') coins = [] denoms = [] coin_int = int(str(10 ** (coin_length - 1) + 1), 2) last_coin_int = int('1' * coin_length) prime_list = rwh_primes2(1000) while len(coins) < num_coins: coin = "{0:b}".format(coin_int) if coin == str(last_coin_int): break if coin[-1] == '0': coin_int += 1 continue the_denomins = [] for j in range(2, 11): the_int = int(coin, j) for k in prime_list: if the_int % k == 0: the_denomins.append(k) break if len(the_denomins) == 9: coins.append(coin) denoms.append(the_denomins) coin_int += 1 coin_int = int(str(10 ** (coin_length - 1) + 1), 2) while len(coins) < num_coins: coin = "{0:b}".format(coin_int) if coin[-1] == '0' or coin in coins: coin_int += 1 continue the_denomins = [] for j in range(2, 11): the_int = int(coin, j) if is_prime(the_int): break else: lowest_denom = None x = 2 while lowest_denom is None: if the_int % x == 0: lowest_denom = x x += 1 the_denomins.append(lowest_denom) if len(the_denomins) == 9: coins.append(coin) denoms.append(the_denomins) coin_int += 1 for j, k in zip(coins, denoms): out_file.write(j + ' ' + ' '.join(map(str, k)) + '\n')
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
5917a97739223f8f73a354d07010fcee9adf413b
9848a719ddfdd21b5fe1fa2f55da290c0f6952dc
/find-positive-integer-solution-for-a-given-equation.py
b82f8bf6dc218a2aad30c5ddee48ba089412517b
[]
no_license
maomao905/algo
725f7fe27bb13e08049693765e4814b98fb0065a
84b35ec9a4e4319b29eb5f0f226543c9f3f47630
refs/heads/master
2023-03-13T12:38:55.401373
2021-03-25T01:55:48
2021-03-25T01:55:48
351,278,248
0
0
null
null
null
null
UTF-8
Python
false
false
2,885
py
""" binary search O(XlogY) """ from typing import List """ This is the custom function interface. You should not implement it, or speculate about its implementation """ class CustomFunction: # Returns f(x, y) for any given positive integers x and y. # Note that f(x, y) is increasing with respect to both x and y. # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) def f(self, x, y): return x * y class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: def bsearch(x): l,r = 1,1000 while l<r: mid = (l+r)//2 res = customfunction.f(x,mid) if res == z: return mid elif res < z: l = mid+1 else: r = mid-1 return l ans = [] # fix x and calculate y for x in range(1,1001): y = bsearch(x) if customfunction.f(x,y) == z: ans.append([x,y]) return ans """ matrix search - reduct search space row/column one by one if mat[i][j] > z: mat[i+1][j] (go down) if mat[i][j] < z: mat[i][j-1] (go left) if mat[i][j] == z: mat[i-1][j-1] (go left and down) 1 2 3 4 5 2 3 4 5 6 3 4 6 7 8 4 5 6 7 10 5 7 9 11 12 O(X+Y) """ class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: ans = [] x,y = 1,1000 while 1<=x<=1000 and 1<=y<=1000: res = customfunction.f(x,y) if res < z: x += 1 elif res > z: y -= 1 else: ans.append([x,y]) x += 1 y -= 1 return ans """ optimized binary search possible y x= 1, 1 2 3 4 5 6 -> if binary search returns 3 and f(x,y)==z x=2, 1 2 -> possible y is only 1 or 2, y < 3 since f(x,y)<f(x+1,y) loop X time and search time is logY + log(Y-1) + log(Y-2) .... 1 O(XlogY) """ class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: def bsearch(x,r): l=1 while l<r: mid = (l+r)//2 res = customfunction.f(x,mid) if res == z: return mid elif res < z: l = mid+1 else: r = mid-1 return l ans = [] r=1000 # fix x and calculate y for x in range(1,1001): y = bsearch(x,r) if customfunction.f(x,y) == z: ans.append([x,y]) r = y return ans customfunction = CustomFunction() s = Solution() print(s.findSolution(customfunction, 5))
[ "maoya.sato@gmail.com" ]
maoya.sato@gmail.com
935e4d71d8e2cc2d2787b422938bbc1c20cbd6cd
a451c9f6b4e0fad4efdc7440e6a180fbed580a15
/DB_lab1/randomize_db.py
5e1d4b4a9d2b5511379e642aa8d0c96c90898ab2
[]
no_license
serhiisad/DB-labs-2018
0124c6b997ad641fb952e62f9caee6e63ff0459f
8316d2ce6a7cfa2b45a567d4e981260435893d44
refs/heads/master
2020-03-29T19:51:52.931565
2018-12-27T20:54:52
2018-12-27T20:54:52
150,284,349
0
0
null
null
null
null
UTF-8
Python
false
false
1,402
py
import rand_data.parser as parser from database import Database as db from datetime import * import names import random from entities.entities import * from database import Database def get_random_name(): return names.get_full_name() def get_rand_boolean(): return random.choice([True, False]) def get_rand_date(min_year=1970, max_year=datetime.now().year): # generate a datetime in format yyyy-mm-dd hh:mm:ss.000000 # start = datetime(min_year, 1, 1, 00, 00, 00) start = date(min_year, 1, 1) years = max_year - min_year + 1 end = start + timedelta(days=365 * years) return start + (end - start) * random.random() def random_fill_db(projects_cnt=4, teamleads_cnt=3, teams_cnt=3, devs_cnt=13): db = Database() #better to pass it to the random_fill_db db.clear_all() for k in range(devs_cnt-1): new_dev = Developer(get_random_name(), str(get_rand_date()), str(get_rand_boolean())) db.create_developer(new_dev) teams_list = parser.tolist_teams() for k in range(teams_cnt-1): new_team = random.choice(teams_list) db.create_team(new_team) projects = parser.tolist_projects() for k in range(projects_cnt-1): new_proj = random.choice(projects) db.create_project(new_proj) for k in range(teamleads_cnt-1): new_tl = Teamlead(names.get_full_name()) db.create_teamlead(new_tl)
[ "serhiisad.kpi@gmail.com" ]
serhiisad.kpi@gmail.com
7d01fbe9aa522fa6202068b4dedf8344b95f56ea
a46fc5187245f7ac79758ae475d4d865e24f482b
/edit_distance/edit_distance.py
5dd8b9754dc67ee9bc34183673021cd15ce19585
[]
no_license
narnat/leetcode
ae31f9321ac9a087244dddd64706780ea57ded91
20a48021be5e5348d681e910c843e734df98b596
refs/heads/master
2022-12-08T00:58:12.547227
2020-08-26T21:04:53
2020-08-26T21:04:53
257,167,879
0
2
null
null
null
null
UTF-8
Python
false
false
1,541
py
#!/usr/bin/env python3 class Solution: ''' Levenshtein distance ''' def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): dp[i][0] = i for j in range(1, n + 1): dp[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): no_match = 1 if word2[j - 1] == word1[i - 1]: no_match = 0 dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + no_match) print(dp, '\n\n') return dp[m][n] class Solution_2: ''' Levenshtein distance, space optimized ''' def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) dp = [0] * (n + 1) for j in range(1, n + 1): dp[j] = j for i in range(1, m + 1): pre = dp[0] dp[0] = i for j in range(1, n + 1): no_match = 1 if word2[j - 1] == word1[i - 1]: no_match = 0 cur = dp[j] dp[j] = min(dp[j - 1] + 1, dp[j] + 1, pre + no_match) pre = cur return dp[n] if __name__ == '__main__': minDistance = Solution().minDistance minDistance("horse", "ros") # minDistance("intention", "execution")
[ "farruh1996@gmail.com" ]
farruh1996@gmail.com
899779762741ff6ffa86533fb97ad109ba0b797f
c0340c511cff5b40b4681c4d3238d807624c0323
/models/revision/grammar_formalism/computeLikelihood.py
99f6045096e9a21b6d613b95a0d8539384ddd704
[]
no_license
m-hahn/grammar-optim
5fa7ade47d2ad91f517c887ee2c65af24059069d
07a1a80692a504bcafc8120a21c4dc9066b495ee
refs/heads/master
2022-08-30T06:54:42.749264
2022-08-05T12:09:28
2022-08-05T12:09:28
156,456,167
13
2
null
null
null
null
UTF-8
Python
false
false
9,958
py
import random import sys objectiveName = "LM" language = sys.argv[1] batchSize = 1 myID = random.randint(0,10000000) FILENAME = "dotdotdot_COARSE_PLANE_noise.py" #with open("../../../raw-results/LOG"+language+"_"+FILENAME+"_model_"+str(myID)+".txt", "w") as outFile: # print >> outFile, " ".join(sys.argv) posUni = set() posFine = set() from math import log, exp, sqrt from random import random, shuffle, randint, choice import os from corpusIterator_FuncHead import CorpusIteratorFuncHead originalDistanceWeights = {} def makeCoarse(x): if ":" in x: return x[:x.index(":")] return x def initializeOrderTable(): orderTable = {} keys = set() vocab = {} distanceSum = {} distanceCounts = {} depsVocab = set() for partition in ["train", "dev"]: for sentence in CorpusIteratorFuncHead(language,partition).iterator(): for line in sentence: vocab[line["word"]] = vocab.get(line["word"], 0) + 1 line["coarse_dep"] = makeCoarse(line["dep"]) depsVocab.add(line["coarse_dep"]) posFine.add(line["posFine"]) posUni.add(line["posUni"]) if line["coarse_dep"] == "root": continue posHere = line["posUni"] posHead = sentence[line["head"]-1]["posUni"] dep = line["coarse_dep"] direction = "HD" if line["head"] < line["index"] else "DH" key = dep keyWithDir = (dep, direction) orderTable[keyWithDir] = orderTable.get(keyWithDir, 0) + 1 keys.add(key) distanceCounts[key] = distanceCounts.get(key,0.0) + 1.0 distanceSum[key] = distanceSum.get(key,0.0) + abs(line["index"] - line["head"]) dhLogits = {} for key in keys: hd = orderTable.get((key, "HD"), 0) + 1.0 dh = orderTable.get((key, "DH"), 0) + 1.0 dhLogit = log(dh) - log(hd) dhLogits[key] = dhLogit return dhLogits, vocab, keys, depsVocab import torch.nn as nn import torch from torch.autograd import Variable def recursivelyLinearize(sentence, position, result, gradients_from_the_left_sum): line = sentence[position-1] # Invariant: these are the gradients relevant at everything starting at the left end of the domain of the current element allGradients = gradients_from_the_left_sum + sum(line.get("children_decisions_logprobs",[])) if "linearization_logprobability" in line: allGradients += line["linearization_logprobability"] # the linearization of this element relative to its siblings affects everything starting at the start of the constituent, but nothing to the left of it else: assert line["coarse_dep"] == "root" # there are the gradients of its children if "children_DH" in line: for child in line["children_DH"]: allGradients = recursivelyLinearize(sentence, child, result, allGradients) result.append(line) line["relevant_logprob_sum"] = allGradients if "children_HD" in line: for child in line["children_HD"]: allGradients = recursivelyLinearize(sentence, child, result, allGradients) return allGradients import numpy.random softmax_layer = torch.nn.Softmax() logsoftmax = torch.nn.LogSoftmax() def orderChildrenRelative(sentence, remainingChildren, reverseSoftmax): childrenLinearized = [] while len(remainingChildren) > 0: logits = torch.cat([distanceWeights[stoi_deps[sentence[x-1]["dependency_key"]]].view(1) for x in remainingChildren]) if reverseSoftmax: logits = -logits softmax = softmax_layer(logits.view(1,-1)).view(-1) selected = 0 log_probability = torch.log(softmax[selected]) assert "linearization_logprobability" not in sentence[remainingChildren[selected]-1] sentence[remainingChildren[selected]-1]["linearization_logprobability"] = log_probability childrenLinearized.append(remainingChildren[selected]) del remainingChildren[selected] return childrenLinearized def orderSentence(sentence, dhLogits, printThings): root = None logits = [None]*len(sentence) logProbabilityGradient = 0 for line in sentence: line["coarse_dep"] = makeCoarse(line["dep"]) if line["coarse_dep"] == "root": root = line["index"] continue if line["coarse_dep"].startswith("punct"): continue key = line["coarse_dep"] line["dependency_key"] = key dhLogit = dhWeights[stoi_deps[key]] probability = 1/(1 + torch.exp(-dhLogit)) dhSampled = (line["index"] < line["head"]) line["ordering_decision_log_probability"] = torch.log(1/(1 + torch.exp(- (1 if dhSampled else -1) * dhLogit))) direction = "DH" if dhSampled else "HD" if printThings: print "\t".join(map(str,["ORD", line["index"], (line["word"]+" ")[:10], ("".join(list(key)) + " ")[:22], line["head"], dhSampled, direction, (str(probability)+" ")[:8], str(1/(1+exp(-dhLogits[key])))[:8], (str(distanceWeights[stoi_deps[key]])+" ")[:8] , str(originalDistanceWeights[key])[:8] ] )) headIndex = line["head"]-1 sentence[headIndex]["children_"+direction] = (sentence[headIndex].get("children_"+direction, []) + [line["index"]]) sentence[headIndex]["children_decisions_logprobs"] = (sentence[headIndex].get("children_decisions_logprobs", []) + [line["ordering_decision_log_probability"]]) for line in sentence: if "children_DH" in line: childrenLinearized = orderChildrenRelative(sentence, line["children_DH"][:], False) line["children_DH"] = childrenLinearized if "children_HD" in line: childrenLinearized = orderChildrenRelative(sentence, line["children_HD"][:], True) line["children_HD"] = childrenLinearized linearized = [] recursivelyLinearize(sentence, root, linearized, Variable(torch.FloatTensor([0.0]))) if printThings or len(linearized) == 0: print " ".join(map(lambda x:x["word"], sentence)) print " ".join(map(lambda x:x["word"], linearized)) return linearized, logits dhLogits, vocab, vocab_deps, depsVocab = initializeOrderTable() posUni = list(posUni) itos_pos_uni = posUni stoi_pos_uni = dict(zip(posUni, range(len(posUni)))) posFine = list(posFine) itos_pos_ptb = posFine stoi_pos_ptb = dict(zip(posFine, range(len(posFine)))) itos_pure_deps = sorted(list(depsVocab)) stoi_pure_deps = dict(zip(itos_pure_deps, range(len(itos_pure_deps)))) itos_deps = sorted(vocab_deps) stoi_deps = dict(zip(itos_deps, range(len(itos_deps)))) print itos_deps dhWeights = torch.FloatTensor([0.0] * len(itos_deps)) distanceWeights = torch.FloatTensor([0.0] * len(itos_deps)) for i, key in enumerate(itos_deps): dhLogits[key] = 2*(random()-0.5) dhWeights[i] = dhLogits[key] originalDistanceWeights[key] = random() distanceWeights[i] = originalDistanceWeights[key] import os inpModels_path = "../../../raw-results/"+"/"+"manual_output_funchead_ground_coarse_final"+"/" models = os.listdir(inpModels_path) models = filter(lambda x:x.startswith(language+"_infer"), models) if len(models) == 0: assert False, "No model exists" if len(models) > 1: assert False, [models, "Multiple models exist"] with open(inpModels_path+models[0], "r") as inFile: data = map(lambda x:x.split("\t"), inFile.read().strip().split("\n")) header = data[0] data = data[1:] if "Dependency" not in header: header[header.index("CoarseDependency")] = "Dependency" if "DH_Weight" not in header: header[header.index("DH_Mean_NoPunct")] = "DH_Weight" if "DistanceWeight" not in header: header[header.index("Distance_Mean_NoPunct")] = "DistanceWeight" for line in data: dependency = line[header.index("Dependency")] key = dependency if key not in stoi_deps: continue dhWeights[stoi_deps[key]] = float(line[header.index("DH_Weight")]) distanceWeights[stoi_deps[key]] = float(line[header.index("DistanceWeight")]) words = list(vocab.iteritems()) words = sorted(words, key = lambda x:x[1], reverse=True) itos = map(lambda x:x[0], words) stoi = dict(zip(itos, range(len(itos)))) assert stoi[itos[5]] == 5 vocab_size = 50000 initrange = 0.1 crossEntropy = 10.0 def encodeWord(w, doTraining): return stoi[w]+3 if stoi[w] < vocab_size else 1 def regularisePOS(w, doTraining): return w import torch.nn.functional baselineAverageLoss = 0 counter = 0 lastDevLoss = None failedDevRuns = 0 devLosses = [] devLossesWords = [] devLossesPOS = [] loss_op = torch.nn.NLLLoss(size_average=False, reduce=False, ignore_index = 0) def doForwardPass(current, train=True): global counter global crossEntropy global printHere global devLosses global baselineAverageLoss batchOrderedLogits = zip(*map(lambda (y,x):orderSentence(x, dhLogits, y==0 and printHere), zip(range(len(current)),current))) batchOrdered = batchOrderedLogits[0] logits = batchOrderedLogits[1] logitCorr = batchOrdered[0][-1]["relevant_logprob_sum"] print(logitCorr) return float(logitCorr) corpusDev = CorpusIteratorFuncHead(language,"dev").iterator(rejectShortSentences = True) totalLikelihood = 0 numberOfSentences = 0 while True: try: batch = map(lambda x:next(corpusDev), 1*range(batchSize)) except StopIteration: break batch = sorted(batch, key=len) partitions = range(1) shuffle(partitions) for partition in partitions: counter += 1 printHere = (counter % 50 == 0) current = batch[partition*batchSize:(partition+1)*batchSize] likelihood = doForwardPass(current, train=False) totalLikelihood += likelihood numberOfSentences += 1 print(totalLikelihood/numberOfSentences) with open("../../../raw-results/treebank_likelihood/"+language+"_"+__file__+".txt", "w") as outFile: print>> outFile, (totalLikelihood/numberOfSentences)
[ "mhahn29@gmail.com" ]
mhahn29@gmail.com
a6241ba745a03539ecfff80c894bfe4a28807540
7770f9830696547f6535155853d1ca744fc83dbe
/TurtleArt/tacanvas.py
246fe35c221babe3243596abc3e4b2d6d7d632ec
[ "MIT" ]
permissive
sugar-activities/4585-activity
dc0811cd0974c3abf747b22f86a58625cee5811f
38e6efd7b4fcb9cf820efaf7406ce7abde92406e
refs/heads/master
2021-01-19T23:14:28.131425
2017-04-21T05:48:21
2017-04-21T05:48:21
88,938,130
0
0
null
null
null
null
UTF-8
Python
false
false
29,613
py
#Copyright (c) 2007-8, Playful Invention Company. #Copyright (c) 2008-11, Walter Bender #Copyright (c) 2011 Collabora Ltd. <http://www.collabora.co.uk/> #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. import gtk from math import sin, cos, atan, pi, sqrt import os import pango import cairo import pangocairo import base64 from gettext import gettext as _ from sprites import Sprite from tasprite_factory import SVG from tautils import image_to_base64, get_path, data_to_string, round_int, \ debug_output from taconstants import BLACK, WHITE def wrap100(n): ''' A variant on mod... 101 -> 99; 199 -> 1 ''' n = int(n) n %= 200 if n > 99: n = 199 - n return n def calc_shade(c, s, invert=False): ''' Convert a color to the current shade (lightness/darkness). ''' # Assumes 16 bit input values if invert: if s < 0: return int(c / (1 + s * 0.8)) return int((c - 65536 * s * 0.9) / (1 - (s * 0.9))) else: if s < 0: return int(c * (1 + s * 0.8)) return int(c + (65536 - c) * s * 0.9) def calc_gray(c, g, invert=False): ''' Gray is a psuedo saturation calculation. ''' # Assumes 16 bit input values if g == 100: return c if invert: if g == 0: return c else: return int(((c * 100) - (32768 * (100 - g))) / g) else: return int(((c * g) + (32768 * (100 - g))) / 100) colors = {} DEGTOR = pi / 180. RTODEG = 180. / pi COLOR_TABLE = ( 0xFF0000, 0xFF0D00, 0xFF1A00, 0xFF2600, 0xFF3300, 0xFF4000, 0xFF4D00, 0xFF5900, 0xFF6600, 0xFF7300, 0xFF8000, 0xFF8C00, 0xFF9900, 0xFFA600, 0xFFB300, 0xFFBF00, 0xFFCC00, 0xFFD900, 0xFFE600, 0xFFF200, 0xFFFF00, 0xE6FF00, 0xCCFF00, 0xB3FF00, 0x99FF00, 0x80FF00, 0x66FF00, 0x4DFF00, 0x33FF00, 0x1AFF00, 0x00FF00, 0x00FF0D, 0x00FF1A, 0x00FF26, 0x00FF33, 0x00FF40, 0x00FF4D, 0x00FF59, 0x00FF66, 0x00FF73, 0x00FF80, 0x00FF8C, 0x00FF99, 0x00FFA6, 0x00FFB3, 0x00FFBF, 0x00FFCC, 0x00FFD9, 0x00FFE6, 0x00FFF2, 0x00FFFF, 0x00F2FF, 0x00E6FF, 0x00D9FF, 0x00CCFF, 0x00BFFF, 0x00B3FF, 0x00A6FF, 0x0099FF, 0x008CFF, 0x0080FF, 0x0073FF, 0x0066FF, 0x0059FF, 0x004DFF, 0x0040FF, 0x0033FF, 0x0026FF, 0x001AFF, 0x000DFF, 0x0000FF, 0x0D00FF, 0x1A00FF, 0x2600FF, 0x3300FF, 0x4000FF, 0x4D00FF, 0x5900FF, 0x6600FF, 0x7300FF, 0x8000FF, 0x8C00FF, 0x9900FF, 0xA600FF, 0xB300FF, 0xBF00FF, 0xCC00FF, 0xD900FF, 0xE600FF, 0xF200FF, 0xFF00FF, 0xFF00E6, 0xFF00CC, 0xFF00B3, 0xFF0099, 0xFF0080, 0xFF0066, 0xFF004D, 0xFF0033, 0xFF001A) class TurtleGraphics: ''' A class for the Turtle graphics canvas ''' def __init__(self, tw, width, height): ''' Create a sprite to hold the canvas. ''' self.tw = tw self.width = width self.height = height # Build a cairo.Context from a cairo.XlibSurface self.canvas = cairo.Context(self.tw.turtle_canvas) cr = gtk.gdk.CairoContext(self.canvas) cr.set_line_cap(1) # Set the line cap to be round self.cr_svg = None # Surface used for saving to SVG self.cx = 0 self.cy = 0 self.fgrgb = [255, 0, 0] self.bgrgb = [255, 255, 255] self.textsize = 48 # deprecated self.shade = 0 self.pendown = False self.xcor = 0 self.ycor = 0 self.heading = 0 self.pensize = 5 self.color = 0 self.gray = 100 self.fill = False self.poly_points = [] def setup_svg_surface(self): ''' Set up a surface for saving to SVG ''' if self.tw.running_sugar: svg_surface = cairo.SVGSurface( os.path.join(get_path(self.tw.activity, 'instance'), 'output.svg'), self.width, self.height) else: svg_surface = cairo.SVGSurface( os.path.join(os.getcwd(), 'output.svg'), self.width, self.height) self.cr_svg = cairo.Context(svg_surface) self.cr_svg.set_line_cap(1) # Set the line cap to be round def start_fill(self): ''' Start accumulating points of a polygon to fill. ''' self.fill = True self.poly_points = [] def stop_fill(self): ''' Fill the polygon. ''' self.fill = False if len(self.poly_points) == 0: return self.fill_polygon(self.poly_points) if self.tw.sharing(): shared_poly_points = [] for p in self.poly_points: shared_poly_points.append((self.screen_to_turtle_coordinates( p[0], p[1]))) event = 'F|%s' % (data_to_string([self._get_my_nick(), shared_poly_points])) self.tw.send_event(event) self.poly_points = [] def fill_polygon(self, poly_points): ''' Draw the polygon... ''' def _fill_polygon(cr, poly_points): cr.new_path() for i, p in enumerate(poly_points): if p[0] == 'move': cr.move_to(p[1], p[2]) elif p[0] == 'rarc': cr.arc(p[1], p[2], p[3], p[4], p[5]) elif p[0] == 'larc': cr.arc_negative(p[1], p[2], p[3], p[4], p[5]) else: # line cr.line_to(p[1], p[2]) cr.close_path() cr.fill() _fill_polygon(self.canvas, poly_points) self.inval() if self.cr_svg is not None: _fill_polygon(self.cr_svg, poly_points) def clearscreen(self, share=True): '''Clear the canvas and reset most graphics attributes to defaults.''' def _clearscreen(cr): cr.move_to(0, 0) self.bgrgb = [255, 255, 255] cr.set_source_rgb(self.bgrgb[0] / 255., self.bgrgb[1] / 255., self.bgrgb[2] / 255.) cr.rectangle(0, 0, self.width * 2, self.height * 2) cr.fill() _clearscreen(self.canvas) self.inval() if self.cr_svg is not None: _clearscreen(self.cr_svg) self.setpensize(5, share) self.setgray(100, share) self.setcolor(0, share) self.setshade(50, share) self.fill = False self.poly_points = [] for turtle_key in iter(self.tw.turtles.dict): # Don't reset remote turtles if not self.tw.remote_turtle(turtle_key): self.set_turtle(turtle_key) self.tw.active_turtle.set_color(0) self.tw.active_turtle.set_shade(50) self.tw.active_turtle.set_gray(100) self.tw.active_turtle.set_pen_size(5) self.tw.active_turtle.reset_shapes() self.seth(0, share) self.setpen(False, share) self.setxy(0, 0, share) self.setpen(True, share) self.tw.active_turtle.hide() self.set_turtle(self.tw.default_turtle_name) def forward(self, n, share=True): ''' Move the turtle forward.''' nn = n * self.tw.coord_scale self.canvas.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255., self.fgrgb[2] / 255.) if self.cr_svg is not None: debug_output('in forward', True) self.cr_svg.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255., self.fgrgb[2] / 255.) oldx, oldy = self.xcor, self.ycor try: self.xcor += nn * sin(self.heading * DEGTOR) self.ycor += nn * cos(self.heading * DEGTOR) except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return if self.pendown: self.draw_line(oldx, oldy, self.xcor, self.ycor) self.move_turtle() if self.tw.sharing() and share: event = 'f|%s' % (data_to_string([self._get_my_nick(), int(n)])) self.tw.send_event(event) self.inval() def seth(self, n, share=True): ''' Set the turtle heading. ''' try: self.heading = n except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return self.heading %= 360 self.turn_turtle() if self.tw.sharing() and share: event = 'r|%s' % (data_to_string([self._get_my_nick(), round_int(self.heading)])) self.tw.send_event(event) def right(self, n, share=True): ''' Rotate turtle clockwise ''' try: self.heading += n except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return self.heading %= 360 self.turn_turtle() if self.tw.sharing() and share: event = 'r|%s' % (data_to_string([self._get_my_nick(), round_int(self.heading)])) self.tw.send_event(event) def arc(self, a, r, share=True): ''' Draw an arc ''' self.canvas.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255., self.fgrgb[2] / 255.) if self.cr_svg is not None: self.cr_svg.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255., self.fgrgb[2] / 255.) try: if a < 0: self.larc(-a, r) else: self.rarc(a, r) except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return self.move_turtle() if self.tw.sharing() and share: event = 'a|%s' % (data_to_string([self._get_my_nick(), [round_int(a), round_int(r)]])) self.tw.send_event(event) def rarc(self, a, r): ''' draw a clockwise arc ''' r *= self.tw.coord_scale if r < 0: r = -r a = -a s = 0 else: s = 1 oldx, oldy = self.xcor, self.ycor cx = self.xcor + r * cos(self.heading * DEGTOR) cy = self.ycor - r * sin(self.heading * DEGTOR) if self.pendown: x, y = self.turtle_to_screen_coordinates(cx, cy) def _rarc(cr, x, y, r, a, h): cr.arc(x, y, r, (h - 180) * DEGTOR, (h - 180 + a) * DEGTOR) cr.stroke() _rarc(self.canvas, x, y, r, a, self.heading) self.inval() if self.cr_svg is not None: _rarc(self.cr_svg, x, y, r, a, self.heading) if self.fill: if self.poly_points == []: self.poly_points.append(('move', x, y)) self.poly_points.append(('rarc', x, y, r, (self.heading - 180) * DEGTOR, (self.heading - 180 + a) * DEGTOR)) self.right(a, False) self.xcor = cx - r * cos(self.heading * DEGTOR) self.ycor = cy + r * sin(self.heading * DEGTOR) def larc(self, a, r): ''' draw a counter-clockwise arc ''' r *= self.tw.coord_scale if r < 0: r = -r a = -a s = 1 else: s = 0 oldx, oldy = self.xcor, self.ycor cx = self.xcor - r * cos(self.heading * DEGTOR) cy = self.ycor + r * sin(self.heading * DEGTOR) if self.pendown: x, y = self.turtle_to_screen_coordinates(cx, cy) def _larc(cr, x, y, r, a, h): cr.arc_negative(x, y, r, h * DEGTOR, (h - a) * DEGTOR) cr.stroke() _larc(self.canvas, x, y, r, a, self.heading) self.inval() if self.cr_svg is not None: _larc(self.cr_svg, x, y, r, a, self.heading) if self.fill: if self.poly_points == []: self.poly_points.append(('move', x, y)) self.poly_points.append(('larc', x, y, r, (self.heading) * DEGTOR, (self.heading - a) * DEGTOR)) self.right(-a, False) self.xcor = cx + r * cos(self.heading * DEGTOR) self.ycor = cy - r * sin(self.heading * DEGTOR) def setxy(self, x, y, share=True, pendown=True): ''' Move turtle to position x,y ''' oldx, oldy = self.xcor, self.ycor x *= self.tw.coord_scale y *= self.tw.coord_scale try: self.xcor, self.ycor = x, y except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return if self.pendown and pendown: self.canvas.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255., self.fgrgb[2] / 255.) if self.cr_svg is not None: self.cr_svg.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255., self.fgrgb[2] / 255.) self.draw_line(oldx, oldy, self.xcor, self.ycor) self.inval() self.move_turtle() if self.tw.sharing() and share: event = 'x|%s' % (data_to_string([self._get_my_nick(), [round_int(x), round_int(y)]])) self.tw.send_event(event) def setpensize(self, ps, share=True): ''' Set the pen size ''' try: if ps < 0: ps = 0 self.pensize = ps except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return self.tw.active_turtle.set_pen_size(ps) self.canvas.set_line_width(ps) if self.cr_svg is not None: self.cr_svg.set_line_width(ps) if self.tw.sharing() and share: event = 'w|%s' % (data_to_string([self._get_my_nick(), round_int(ps)])) self.tw.send_event(event) def setcolor(self, c, share=True): ''' Set the pen color ''' try: self.color = c except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return self.tw.active_turtle.set_color(c) self.set_fgcolor() if self.tw.sharing() and share: event = 'c|%s' % (data_to_string([self._get_my_nick(), round_int(c)])) self.tw.send_event(event) def setgray(self, g, share=True): ''' Set the gray level ''' try: self.gray = g except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return if self.gray < 0: self.gray = 0 if self.gray > 100: self.gray = 100 self.set_fgcolor() self.tw.active_turtle.set_gray(self.gray) if self.tw.sharing() and share: event = 'g|%s' % (data_to_string([self._get_my_nick(), round_int(self.gray)])) self.tw.send_event(event) def set_textcolor(self): ''' Deprecated: Set the text color to foreground color. ''' return def settextcolor(self, c): # deprecated ''' Set the text color ''' return def settextsize(self, c): # deprecated ''' Set the text size ''' try: self.tw.textsize = c except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) def setshade(self, s, share=True): ''' Set the color shade ''' try: self.shade = s except TypeError, ValueError: debug_output('bad value sent to %s' % (__name__), self.tw.running_sugar) return self.tw.active_turtle.set_shade(s) self.set_fgcolor() if self.tw.sharing() and share: event = 's|%s' % (data_to_string([self._get_my_nick(), round_int(s)])) self.tw.send_event(event) def fillscreen(self, c, s): ''' Fill screen with color/shade and reset to defaults ''' oldc, olds = self.color, self.shade self.setcolor(c, False) self.setshade(s, False) self.bgrgb = self.fgrgb[:] def _fillscreen(cr, rgb, w, h): cr.set_source_rgb(rgb[0] / 255., rgb[1] / 255., rgb[2] / 255.) cr.rectangle(0, 0, w * 2, h * 2) cr.fill() _fillscreen(self.canvas, self.fgrgb, self.width, self.height) self.inval() if self.cr_svg is not None: _fillscreen(self.cr_svg, self.fgrgb, self.width, self.height) self.setcolor(oldc, False) self.setshade(olds, False) self.fill = False self.poly_points = [] def set_fgcolor(self): ''' Set the foreground color ''' if self.color == WHITE or self.shade == WHITE: r = 0xFF00 g = 0xFF00 b = 0xFF00 elif self.color == BLACK or self.shade == BLACK: r = 0x0000 g = 0x0000 b = 0x0000 else: sh = (wrap100(self.shade) - 50) / 50.0 rgb = COLOR_TABLE[wrap100(self.color)] r = (rgb >> 8) & 0xff00 r = calc_gray(r, self.gray) r = calc_shade(r, sh) g = rgb & 0xff00 g = calc_gray(g, self.gray) g = calc_shade(g, sh) b = (rgb << 8) & 0xff00 b = calc_gray(b, self.gray) b = calc_shade(b, sh) self.fgrgb = [r >> 8, g >> 8, b >> 8] def setpen(self, bool, share=True): ''' Lower or raise the pen ''' self.pendown = bool self.tw.active_turtle.set_pen_state(bool) if self.tw.sharing() and share: event = 'p|%s' % (data_to_string([self._get_my_nick(), bool])) self.tw.send_event(event) def draw_surface(self, surface, x, y, w, h): ''' Draw a surface ''' def _draw_surface(cr, surface, x, y, w, h): cc = gtk.gdk.CairoContext(cr) cc.set_source_surface(surface, x, y) cc.rectangle(x, y, w, h) cc.fill() _draw_surface(self.canvas, surface, x, y, w, h) self.inval() if self.cr_svg is not None: _draw_surface(self.cr_svg, surface, x, y, w, h) def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True): ''' Draw a pixbuf ''' def _draw_pixbuf(cr, pixbuf, a, b, x, y, w, h, heading): # Build a gtk.gdk.CairoContext from a cairo.Context to access # the set_source_pixbuf attribute. cc = gtk.gdk.CairoContext(cr) cc.save() # center the rotation on the center of the image cc.translate(x + w / 2., y + h / 2.) cc.rotate(heading * DEGTOR) cc.translate(-x - w / 2., -y - h / 2.) cc.set_source_pixbuf(pixbuf, x, y) cc.rectangle(x, y, w, h) cc.fill() cc.restore() _draw_pixbuf(self.canvas, pixbuf, a, b, x, y, w, h, self.heading) self.inval() if self.cr_svg is not None: _draw_pixbuf(self.cr_svg, pixbuf, a, b, x, y, w, h, self.heading) if self.tw.sharing() and share: if self.tw.running_sugar: tmp_path = get_path(self.tw.activity, 'instance') else: tmp_path = '/tmp' tmp_file = os.path.join(get_path(self.tw.activity, 'instance'), 'tmpfile.png') pixbuf.save(tmp_file, 'png', {'quality': '100'}) data = image_to_base64(tmp_file, tmp_path) height = pixbuf.get_height() width = pixbuf.get_width() x, y = self.screen_to_turtle_coordinates(x, y) event = 'P|%s' % (data_to_string([self._get_my_nick(), [round_int(a), round_int(b), round_int(x), round_int(y), round_int(w), round_int(h), round_int(width), round_int(height), data]])) self.tw.send_event(event) os.remove(tmp_file) def draw_text(self, label, x, y, size, w, share=True): ''' Draw text ''' w *= self.tw.coord_scale def _draw_text(cr, label, x, y, size, w, scale, heading, rgb): cc = pangocairo.CairoContext(cr) pl = cc.create_layout() fd = pango.FontDescription('Sans') fd.set_size(int(size * scale) * pango.SCALE) pl.set_font_description(fd) if type(label) == str or type(label) == unicode: pl.set_text(label.replace('\0', ' ')) elif type(label) == float or type(label) == int: pl.set_text(str(label)) else: pl.set_text(str(label)) pl.set_width(int(w) * pango.SCALE) cc.save() cc.translate(x, y) cc.rotate(heading * DEGTOR) cr.set_source_rgb(rgb[0] / 255., rgb[1] / 255., rgb[2] / 255.) cc.update_layout(pl) cc.show_layout(pl) cc.restore() _draw_text(self.canvas, label, x, y, size, w, self.tw.coord_scale, self.heading, self.fgrgb) self.inval() if self.cr_svg is not None: # and self.pendown: _draw_text(self.cr_svg, label, x, y, size, w, self.tw.coord_scale, self.heading, self.fgrgb) if self.tw.sharing() and share: event = 'W|%s' % (data_to_string([self._get_my_nick(), [label, round_int(x), round_int(y), round_int(size), round_int(w)]])) self.tw.send_event(event) def turtle_to_screen_coordinates(self, x, y): ''' The origin of turtle coordinates is the center of the screen ''' return self.width / 2. + x, self.invert_y_coordinate(y) def screen_to_turtle_coordinates(self, x, y): ''' The origin of the screen coordinates is the upper left corner ''' return x - self.width / 2., self.invert_y_coordinate(y) def invert_y_coordinate(self, y): ''' Positive y goes up in turtle coordinates, down in sceeen coordinates ''' return self.height / 2. - y def draw_line(self, x1, y1, x2, y2): ''' Draw a line ''' x1, y1 = self.turtle_to_screen_coordinates(x1, y1) x2, y2 = self.turtle_to_screen_coordinates(x2, y2) def _draw_line(cr, x1, y1, x2, y2): cr.move_to(x1, y1) cr.line_to(x2, y2) cr.stroke() _draw_line(self.canvas, x1, y1, x2, y2) if self.cr_svg is not None: _draw_line(self.cr_svg, x1, y1, x2, y2) if self.fill: if self.poly_points == []: self.poly_points.append(('move', x1, y1)) self.poly_points.append(('line', x2, y2)) def turn_turtle(self): ''' Change the orientation of the turtle ''' self.tw.active_turtle.set_heading(self.heading) def move_turtle(self): ''' Move the turtle ''' x, y = self.turtle_to_screen_coordinates(self.xcor, self.ycor) if self.tw.interactive_mode: self.tw.active_turtle.move( (int(self.cx + x - self.tw.active_turtle.spr.rect.width / 2.), int(self.cy + y - self.tw.active_turtle.spr.rect.height / 2.)) ) else: self.tw.active_turtle.move((int(self.cx + x), int(self.cy + y))) def get_color_index(self, r, g, b, a=0): ''' Find the closest palette entry to the rgb triplet ''' if self.shade != 50 or self.gray != 100: r <<= 8 g <<= 8 b <<= 8 if self.shade != 50: sh = (wrap100(self.shade) - 50) / 50. r = calc_shade(r, sh, True) g = calc_shade(g, sh, True) b = calc_shade(b, sh, True) if self.gray != 100: r = calc_gray(r, self.gray, True) g = calc_gray(g, self.gray, True) b = calc_gray(b, self.gray, True) r >>= 8 g >>= 8 b >>= 8 min_distance = 1000000 closest_color = -1 for i, c in enumerate(COLOR_TABLE): cr = int((c & 0xff0000) >> 16) cg = int((c & 0x00ff00) >> 8) cb = int((c & 0x0000ff)) distance_squared = \ ((cr - r) ** 2) + ((cg - g) ** 2) + ((cb - b) ** 2) if distance_squared == 0: return i if distance_squared < min_distance: min_distance = distance_squared closest_color = i return closest_color def get_pixel(self): ''' Read the pixel at x, y ''' if self.tw.interactive_mode: x, y = self.turtle_to_screen_coordinates(self.xcor, self.ycor) x = int(x) y = int(y) w = self.tw.turtle_canvas.get_width() h = self.tw.turtle_canvas.get_height() if x < 0 or x > (w - 1) or y < 0 or y > (h - 1): return(-1, -1, -1, -1) # create a new 1x1 cairo surface cs = cairo.ImageSurface(cairo.FORMAT_RGB24, 1, 1) cr = cairo.Context(cs) cr.set_source_surface(self.tw.turtle_canvas, -x, -y) cr.rectangle(0, 0, 1, 1) cr.set_operator(cairo.OPERATOR_SOURCE) cr.fill() cs.flush() # ensure all writing is done pixels = cs.get_data() # Read the pixel return (ord(pixels[2]), ord(pixels[1]), ord(pixels[0]), 0) else: return(-1, -1, -1, -1) def set_turtle(self, k, colors=None): ''' Select the current turtle and associated pen status ''' if k not in self.tw.turtles.dict: # if it is a new turtle, start it in the center of the screen self.tw.active_turtle = self.tw.turtles.get_turtle(k, True, colors) self.seth(0, False) self.setxy(0, 0, False, pendown=False) self.tw.active_turtle.set_pen_state(True) elif colors is not None: self.tw.active_turtle = self.tw.turtles.get_turtle(k, False) self.tw.active_turtle.set_turtle_colors(colors) else: self.tw.active_turtle = self.tw.turtles.get_turtle(k, False) self.tw.active_turtle.show() tx, ty = self.tw.active_turtle.get_xy() self.xcor, self.ycor = self.screen_to_turtle_coordinates(tx, ty) if self.tw.interactive_mode: self.xcor += self.tw.active_turtle.spr.rect.width / 2. self.ycor -= self.tw.active_turtle.spr.rect.height / 2. self.heading = self.tw.active_turtle.get_heading() self.setcolor(self.tw.active_turtle.get_color(), False) self.setgray(self.tw.active_turtle.get_gray(), False) self.setshade(self.tw.active_turtle.get_shade(), False) self.setpensize(self.tw.active_turtle.get_pen_size(), False) self.setpen(self.tw.active_turtle.get_pen_state(), False) def svg_close(self): ''' Close current SVG graphic ''' self.cr_svg.show_page() def svg_reset(self): ''' Reset svg flags ''' self.cr_svg = None def _get_my_nick(self): return self.tw.nick def inval(self): ''' Invalidate a region for gtk ''' self.tw.inval_all()
[ "ignacio@sugarlabs.org" ]
ignacio@sugarlabs.org
f7ab2d6e05b9a9ae4214f93604ca92b85456a336
e14372adf86d3c4f9e73c9f7111db3215c696c3d
/3.算法小抄/排序/10.排序算法总结.py
dc74972ad4d1b42d5b3b41139e6b38b0038e6a8a
[]
no_license
hewei-bit/PYTHON_learning
71ddd7560a52575528547187f4fb40f39a3cbbdb
18de8e5bdca165df5a5a4b5e0887846593656f4e
refs/heads/master
2022-12-02T13:38:05.907135
2020-08-13T04:57:41
2020-08-13T04:57:41
261,647,401
0
0
null
null
null
null
UTF-8
Python
false
false
9,620
py
""" 这次收集整理并用Python实现了八大经典排序算法, 包括冒泡排序,插入排序,选择排序,希尔排序,归并排序,快速排序,堆排序以及基数排序。 希望能帮助到有需要的同学。之所以用 Python 实现, 主要是因为它更接近伪代码,能用更少的代码实现算法,更利于理解。 本篇博客所有排序实现均默认从小到大。 """ from time import * class sort: # 一、冒泡排序 """ 冒泡排序的原理非常简单,它重复地走访过要排序的数列, 一次比较两个元素,如果他们的顺序错误就把他们交换过来。 """ def bubble_sort(self, ary): n = len(ary) for i in range(n): flag = True for j in range(1, n - i): if ary[j - 1] > ary[j]: temp = ary[j - 1] ary[j - 1] = ary[j] ary[j] = temp flag = False if flag: break return ary # 二、选择排序 """ 选择排序是另一个很容易理解和实现的简单排序算法。 学习它之前首先要知道它的两个很鲜明的特点。 1. 运行时间和输入无关 2. 数据移动是最少的 """ def select_sort(self, ary): n = len(ary) for i in range(0, n): min = i # 最小元素下表标记 for j in range(i + 1, n): if ary[j] < ary[min]: min = j # 找到最小值下标 ary[min], ary[i] = ary[i], ary[min] # 交换两者 # 三、插入排序 InsertionSort """ 插入排序的工作原理是,对于每个未排序数据, 在已排序序列中从后向前扫描,找到相应位置并插入。 """ def insert_sort(self, ary): n = len(ary) for i in range(1, n): key = i - 1 mark = ary[i] while key >= 0 and ary[key] > mark: ary[key + 1] = ary[key] key -= 1 ary[key + 1] = mark return ary # 四、希尔排序 ShellSort """ 希尔排序的实质就是分组插入排序,该方法又称缩小增量排序 """ def shell_sort(self, ary): count = len(ary) gap = round(count / 2) # 双杠用于整除(向下取整),在python直接用 “/” 得到的永远是浮点数, # 用round()得到四舍五入值 while gap >= 1: for i in range(gap, count): temp = ary[i] j = i while j - gap >= 0 and ary[j - gap] > temp: ary[j] = ary[j - gap] j -= gap ary[j] = temp gap = round(gap / 2) return ary # 五、归并排序 MergeSort def Merge_sort(self, ary: list) -> list: if len(ary) <= 1: return ary median = int(len(ary) / 2) # 二分分解 left = self.Merge_sort(ary[:median]) right = self.Merge_sort(ary[median:]) return self.merge(left, right) # 合并数组 def merge(self, left: list, right: list) -> list: """合并操作, 将两个有序数组left[]和right[]合并成一个大的有序数组""" res = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 res = res + left[i:] + right[j:] return res # 六、快速排序 QuickSort """ 快速排序通常明显比同为Ο(n log n)的其他算法更快, 因此常被采用,而且快排采用了分治法的思想, 所以在很多笔试面试中能经常看到快排的影子。可见掌握快排的重要性。 步骤: 1.从数列中挑出一个元素作为基准数。 2.分区过程,将比基准数大的放到右边,小于或等于它的数都放到左边。 3.再对左右区间递归执行第二步,直至各区间只有一个数。 """ def quick_sort(self, ary): return self.qsort(ary, 0, len(ary) - 1) def qsort(self, ary, start, end): if start < end: left = start right = end key = ary[start] else: return ary while left < right: while left < right and ary[right] >= key: right -= 1 if left < right: # 说明打破while循环的原因是ary[right] < key ary[left] = ary[right] left += 1 while left < right and ary[left] < key: left += 1 if left < right: # 说明打破while循环的原因是ary[left] >= key ary[right] = ary[left] right -= 1 ary[left] = key # 此时,left=right,用key来填坑 self.qsort(ary, start, left - 1) self.qsort(ary, left + 1, end) return ary # arr[] --> 排序数组 # low --> 起始索引 # high --> 结束索引 # 快速排序函数 def quickSort_2(self, arr, low, high): if low < high: pi = self.partition(arr, low, high) self.quickSort_2(arr, low, pi - 1) self.quickSort_2(arr, pi + 1, high) def partition(self, arr, low, high): i = (low - 1) # 最小元素索引 pivot = arr[high] for j in range(low, high): # 当前元素小于或等于 pivot if arr[j] <= pivot: i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 # 七、堆排序 HeapSort def heap_sort(self, ary: list): n = len(ary) first = int(n / 2 - 1) # 最后一个非叶子节点 for start in range(first, -1, -1): # 构建最大堆 self.max_heapify(ary, start, n - 1) for end in range(n - 1, 0, -1): # 堆排,将最大跟堆转换成有序数组 ary[end], ary[0] = ary[0], ary[end] # 将根节点元素与最后叶子节点进行互换,取出最大根节点元素,对剩余节点重新构建最大堆 self.max_heapify(ary, 0, end - 1) # 因为end上面取的是n-1,故而这里直接放end-1,相当于忽略了最后最大根节点元素ary[n-1] return ary # 最大堆调整:将堆的末端子节点做调整,使得子节点永远小于父节点 # start 为当前需要调整最大堆的位置。 def max_heapify(self, ary: list, start: int, end: int): root = start while True: child = root * 2 + 1 # 找到左子节点 if child > end: # 如果左子节点超过最后一个元素 break if child + 1 <= end and ary[child] < ary[child + 1]: child = child + 1 # 如果左子节点比较大 if ary[root] < ary[child]: # 选择较大元素成为父节点 ary[root], ary[child] = ary[child], ary[root] root = child else: break # 八、计数排序 def counting_sort(self, arr: list, maxValue: int) -> list: bucketlen = maxValue + 1 bucket = [0] * bucketlen sortIndex = 0 arrlen = len(arr) for i in range(arrlen): if not bucket[arr[i]]: bucket[arr[i]] = 0 bucket[arr[i]] += 1 for j in range(bucketlen): while bucket[j] > 0: arr[sortIndex] = j sortIndex += 1 bucket[j] -= 1 return arr # 九、基数排序 def radix_sort(self, arr: list): """基数排序""" i = 0 # 记录当前正在排拿一位,最低位为1 max_num = max(arr) # 最大值 j = len(str(max_num)) # 记录最大值的位数 while i < j: bucket_list = [[] for _ in range(10)] # 初始化桶数组 for x in arr: bucket_list[int(x / (10 ** i)) % 10].append(x) # 找到位置放入桶数组 arr.clear() for x in bucket_list: # 放回原序列 for y in x: arr.append(y) i += 1 return arr # 十、桶排序 def bucket_sort(self, arr: list): if not arr: return 0 maxValue = max(arr) bucket = [0] * (maxValue + 1) sort_list = [] for i in arr: bucket[i] += 1 for j in range(len(bucket)): if bucket[j] != 0: for k in range(bucket[j]): sort_list.append(j) return sort_list if __name__ == '__main__': l = [123, 42, 543, 345, 12, 321, 12] # arr = [10, 7, 8, 9, 1, 5] # sort().bubble_sort(l) #冒泡 # sort().select_sort(l) #选择 # sort().insert_sort(l) #插入 # sort().shell_sort(l) #希尔 # ll = sort().Merge_sort(l) #归并 # ll = sort().quick_sort(l) #快速 # ll = sort().heap_sort(l) # 堆排序 # ll = sort().counting_sort(l,max(l)) #计数排序 # ll = sort().radix_sort(l) # 基数排序 # ll = sort().bucket_sort(l) # 第二个快速排序 n = len(l) sort().quickSort_2(l, 0, n - 1) print("排序后的数组:") for i in range(n): print("%d" % l[i]) # begin_time = time() # end_time = time() # runtime = end_time - begin_time # print(runtime) # print(ll)
[ "1003826976@qq.com" ]
1003826976@qq.com
2e8e22eccf577adb8f50383b8185e493ecca6916
eea70db78a214217ba41801d870aba127ba56c56
/Code/Tested TD Policy-Iteration/ARL_package/CodeFramework/main.py
713e3872ac1424be5f414871c9f0572523da5a91
[]
no_license
356255531/poppyProject
191b9a9e29817e3d6ce8c85dd5c0702982dd7157
678044afffa6390fac8cb402099bd32ae72d8a33
refs/heads/master
2021-01-21T14:32:47.373344
2016-07-12T19:42:25
2016-07-12T19:42:25
58,334,432
3
1
null
null
null
null
UTF-8
Python
false
false
2,842
py
__author__ = 'erik' from . import Actor, LearningAlgorithm, Reward, StateActionSpace, StateObserver def run_learning(actor, learning_algorithm, reward, state_observer): """Run the main loop!""" # Check that the variables given have the right superclasses # assert (isinstance(actor, Actor)) # assert (isinstance(learning_algorithm, LearningAlgorithm)) # assert (isinstance(reward, Reward)) # assert (isinstance(state_observer, StateObserver)) current_state = state_observer.get_current_state() while current_state: next_action = learning_algorithm.get_next_action(current_state) actor.perform_action(next_action) next_state = state_observer.get_current_state() reward_given = reward.get_rewards(current_state, next_action, next_state) learning_algorithm.receive_reward(current_state, next_action, next_state, reward_given) current_state = next_state def run_episode(actor, learning_algorithm, reward, state_observer, state_action_space, max_num_iterations = 1000000): # assert (isinstance(actor, Actor)) # assert (isinstance(learning_algorithm, LearningAlgorithm)) # assert (isinstance(reward, Reward)) # assert (isinstance(state_observer, StateObserver)) # assert isinstance(state_action_space, StateActionSpace) actor.initialise_episode(state_action_space) current_state = state_observer.get_current_state() current_iter = 0 while current_iter < max_num_iterations: next_action = learning_algorithm.get_next_action(current_state) actor.perform_action(next_action) next_state = state_observer.get_current_state() reward_given = reward.get_rewards(current_state, next_action, next_state) learning_algorithm.receive_reward(current_state, next_action, next_state, reward_given) current_state = next_state current_iter += 1 if state_action_space.is_terminal_state(current_state): reward_given = reward.get_rewards(current_state, (0, 0), next_state) learning_algorithm.receive_reward(current_state, (0, 0), next_state, reward_given) break learning_algorithm.finalise_episode() print "run_episode: Episode ended after " + str(current_iter) + " iterations." if __name__ == '__main__': from dummy_classes import * dummy_states_actions = DummyStateActionSpace() dummy_states_actions.states[0] = 2 #because I defined the loop to run while current state wasn't 0/false dummy_actor = DummyActor() dummy_observer = DummyObserver(dummy_states_actions, dummy_actor) dummy_learner = DummyLearner(dummy_states_actions) dummy_reward = DummyReward(dummy_states_actions) run_learning(dummy_actor, dummy_learner, dummy_reward, dummy_observer) print "Values: " + str(dummy_learner.values)
[ "hanzw356255531@icloud.com" ]
hanzw356255531@icloud.com
f8b3978cb753019e9ee6fec4c16e624de7034c9b
d047fed56a7d1de1d7c32ce83b8d62646fa7d19e
/leapyearQuestion.py
6b7641183cdad87321077e16411144ded6c16051
[]
no_license
shantinavgurukul/listQuestions
508b6bd489731d5b8a9ba1a27e5b88b1bb27341a
21f413f65b374e5fa63e0366591895757146d7c7
refs/heads/master
2022-11-23T07:56:15.392836
2020-08-02T03:51:46
2020-08-02T03:51:46
284,384,225
1
0
null
null
null
null
UTF-8
Python
false
false
199
py
year=int (input("enter the year=")) if(year%4==0 and year%100!=0): print(year,"it's leap year.") elif(year%400==0): print(year,"it's leap year-") else: print(year, "it's not leap year")
[ "you@example.com" ]
you@example.com
83a1fbfb23b45c442e115f2747f1d9c39fafda6f
86177bf66a3d4f6ffcd8972a1eb7305eb25d5301
/lesson_10_2.py
e919169a0b0c65293af3e625cb67b05a6f8bef07
[]
no_license
Mameluke8888/QA_Automation_Lesson_10_2
941dd99c5fb65d98407124514e146e6b51f528c1
175858d4b4d189926633d5323f4ac724e73f52c7
refs/heads/main
2023-05-07T01:36:35.742796
2021-05-24T12:15:35
2021-05-24T12:15:35
370,340,146
0
0
null
null
null
null
UTF-8
Python
false
false
4,236
py
from selenium.webdriver.common.by import By import time from browser import Browser from UIElement import UIElement as Element from dropdown import Dropdown from header import Header from right_menu import RightMenu from login_page import LoginPage from registration_page import RegistrationPage URL = "https://techskillacademy.net/brainbucket" # May 23rd, 2021 # student Evgeny Abdulin def test_registration_through_dropdown(): browser = Browser(URL, "Firefox") driver = browser.get_driver() login_page = LoginPage(browser) login_page.open_registration_from_account_dropdown() registration_form = RegistrationPage(browser) assert registration_form.get_form_title() == 'Register Account' registration_form.enter_first_name("Svetlana") registration_form.enter_last_name("Match") registration_form.enter_email("svetlana.match2@gmail.com") registration_form.enter_telephone("3123405555") registration_form.enter_first_line_address("175 W Jackson St") registration_form.enter_city("Chicago") registration_form.select_state("Illinois") registration_form.enter_password("qwerty123") registration_form.confirm_password("qwerty123") registration_form.subscribe_to_newsletters() registration_form.agree_to_privacy_policy() registration_form.submit_form() successful_registration_title = Element(browser, By.XPATH, "//*[@id='content']/h1") assert successful_registration_title.get_text() == 'Your Account Has Been Created!' successful_registration_subtitle = Element(browser, By.XPATH, "//*[@id='content']/p") assert successful_registration_subtitle.get_text() == 'Congratulations! ' \ 'Your new account has been successfully created!' time.sleep(5) browser.shutdown() def test_registration_from_right_menu(): browser = Browser(URL, "Firefox") driver = browser.get_driver() # in Account dropdown select Login option header = Header(browser) header.open_login_page() # click on Register btn in the right menu right_menu = RightMenu(browser) right_menu.click_registration() registration_form = RegistrationPage(browser) assert registration_form.get_form_title() == 'Register Account' registration_form.enter_first_name("Svetlana") registration_form.enter_last_name("Match") registration_form.enter_email("svetlana.match2@gmail.com") registration_form.enter_telephone("3123405555") registration_form.enter_first_line_address("175 W Jackson St") registration_form.enter_city("Chicago") registration_form.select_state("Illinois") registration_form.enter_password("qwerty123") registration_form.confirm_password("qwerty123") registration_form.subscribe_to_newsletters() registration_form.agree_to_privacy_policy() registration_form.submit_form() successful_registration_title = Element(browser, By.XPATH, "//*[@id='content']/h1") assert successful_registration_title.get_text() == 'Your Account Has Been Created!' successful_registration_subtitle = Element(browser, By.XPATH, "//*[@id='content']/p") assert successful_registration_subtitle.get_text() == 'Congratulations! ' \ 'Your new account has been successfully created!' time.sleep(5) browser.shutdown() def test_header(): browser = Browser(URL, "Firefox") driver = browser.get_driver() # in Account dropdown select Login option header = Header(browser) # header.open_wishlist() header.search_for('laptop') header.change_currency("eur") time.sleep(3) browser.shutdown() def test_login(): browser = Browser(URL, "Firefox") driver = browser.get_driver() header = Header(browser) header.open_login_page() login_page = LoginPage(browser) login_page.email_input_type("svetlana.match2@gmail.com") login_page.password_input_type("qwerty123") time.sleep(1) login_page.login_btn.click() time.sleep(3) browser.shutdown() if __name__ == "__main__": # test_registration_through_dropdown() # test_registration_from_right_menu() # test_header() test_login()
[ "evgenyabdulin@Evgenys-Mac-mini.local" ]
evgenyabdulin@Evgenys-Mac-mini.local
1607d69f94ab941b55a795973d3de6ce2af8080b
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/mDuDhhMWrdHJSGdtm_11.py
d5fda998b13ee4c0e40bf595960ffe6cd51bc475
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
190
py
def is_exactly_three(n): sqrt = n**0.5 if sqrt.is_integer() and sqrt != 1: for i in range(2,int(sqrt)): if sqrt % i == 0: return False return True return False
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
b5a2c34f652b0489d4424f838120bdd77d8b4f34
6aff904a5c464c3a7437a1136420e4aa10488456
/train_gl.py
5944ede9b92d4972a264dcb8f8e89e7de747387f
[ "MIT" ]
permissive
chenjun2hao/imgclsmob
8c845ce108f5c58c2be708012e6d0f5d0b0c7548
e6dcf77bf9b5505946befec18f5c54c244f70304
refs/heads/master
2020-06-16T05:40:10.847813
2019-07-05T21:05:36
2019-07-05T21:05:36
195,492,889
1
0
MIT
2019-07-06T03:26:20
2019-07-06T03:26:20
null
UTF-8
Python
false
false
22,868
py
import argparse import time import logging import os import random import numpy as np import mxnet as mx from mxnet import gluon from mxnet import autograd as ag from common.logger_utils import initialize_logging from common.train_log_param_saver import TrainLogParamSaver from gluon.lr_scheduler import LRScheduler from gluon.utils import prepare_mx_context, prepare_model, validate from gluon.utils import report_accuracy, get_composite_metric, get_metric_name from gluon.dataset_utils import get_dataset_metainfo from gluon.dataset_utils import get_train_data_source, get_val_data_source from gluon.dataset_utils import get_batch_fn def add_train_cls_parser_arguments(parser): parser.add_argument( "--model", type=str, required=True, help="type of model to use. see model_provider for options") parser.add_argument( "--use-pretrained", action="store_true", help="enable using pretrained model from github repo") parser.add_argument( "--dtype", type=str, default="float32", help="data type for training") parser.add_argument( '--not-hybridize', action='store_true', help='do not hybridize model') parser.add_argument( "--resume", type=str, default="", help="resume from previously saved parameters if not None") parser.add_argument( "--resume-state", type=str, default="", help="resume from previously saved optimizer state if not None") parser.add_argument( "--num-gpus", type=int, default=0, help="number of gpus to use") parser.add_argument( "-j", "--num-data-workers", dest="num_workers", default=4, type=int, help="number of preprocessing workers") parser.add_argument( "--batch-size", type=int, default=512, help="training batch size per device (CPU/GPU)") parser.add_argument( "--batch-size-scale", type=int, default=1, help="manual batch-size increasing factor") parser.add_argument( "--num-epochs", type=int, default=120, help="number of training epochs") parser.add_argument( "--start-epoch", type=int, default=1, help="starting epoch for resuming, default is 1 for new training") parser.add_argument( "--attempt", type=int, default=1, help="current attempt number for training") parser.add_argument( "--optimizer-name", type=str, default="nag", help="optimizer name") parser.add_argument( "--lr", type=float, default=0.1, help="learning rate") parser.add_argument( "--lr-mode", type=str, default="cosine", help="learning rate scheduler mode. options are step, poly and cosine") parser.add_argument( "--lr-decay", type=float, default=0.1, help="decay rate of learning rate") parser.add_argument( "--lr-decay-period", type=int, default=0, help="interval for periodic learning rate decays. default is 0 to disable") parser.add_argument( "--lr-decay-epoch", type=str, default="40,60", help="epoches at which learning rate decays") parser.add_argument( "--target-lr", type=float, default=1e-8, help="ending learning rate") parser.add_argument( "--poly-power", type=float, default=2, help="power value for poly LR scheduler") parser.add_argument( "--warmup-epochs", type=int, default=0, help="number of warmup epochs") parser.add_argument( "--warmup-lr", type=float, default=1e-8, help="starting warmup learning rate") parser.add_argument( "--warmup-mode", type=str, default="linear", help="learning rate scheduler warmup mode. options are linear, poly and constant") parser.add_argument( "--momentum", type=float, default=0.9, help="momentum value for optimizer") parser.add_argument( "--wd", type=float, default=0.0001, help="weight decay rate") parser.add_argument( "--gamma-wd-mult", type=float, default=1.0, help="weight decay multiplier for batchnorm gamma") parser.add_argument( "--beta-wd-mult", type=float, default=1.0, help="weight decay multiplier for batchnorm beta") parser.add_argument( "--bias-wd-mult", type=float, default=1.0, help="weight decay multiplier for bias") parser.add_argument( "--grad-clip", type=float, default=None, help="max_norm for gradient clipping") parser.add_argument( "--label-smoothing", action="store_true", help="use label smoothing") parser.add_argument( "--mixup", action="store_true", help="use mixup strategy") parser.add_argument( "--mixup-epoch-tail", type=int, default=20, help="number of epochs without mixup at the end of training") parser.add_argument( "--log-interval", type=int, default=50, help="number of batches to wait before logging") parser.add_argument( "--save-interval", type=int, default=4, help="saving parameters epoch interval, best model will always be saved") parser.add_argument( "--save-dir", type=str, default="", help="directory of saved models and log-files") parser.add_argument( "--logging-file-name", type=str, default="train.log", help="filename of training log") parser.add_argument( "--seed", type=int, default=-1, help="random seed to be fixed") parser.add_argument( "--log-packages", type=str, default="mxnet, numpy", help="list of python packages for logging") parser.add_argument( "--log-pip-packages", type=str, default="mxnet-cu100", help="list of pip packages for logging") parser.add_argument( "--tune-layers", type=str, default="", help="regexp for selecting layers for fine tuning") def parse_args(): parser = argparse.ArgumentParser( description="Train a model for image classification (Gluon)", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( "--dataset", type=str, default="ImageNet1K_rec", help="dataset name. options are ImageNet1K, ImageNet1K_rec, CUB200_2011, CIFAR10, CIFAR100, SVHN") parser.add_argument( "--work-dir", type=str, default=os.path.join("..", "imgclsmob_data"), help="path to working directory only for dataset root path preset") args, _ = parser.parse_known_args() dataset_metainfo = get_dataset_metainfo(dataset_name=args.dataset) dataset_metainfo.add_dataset_parser_arguments( parser=parser, work_dir_path=args.work_dir) add_train_cls_parser_arguments(parser) args = parser.parse_args() return args def init_rand(seed): if seed <= 0: seed = np.random.randint(10000) random.seed(seed) np.random.seed(seed) mx.random.seed(seed) return seed def prepare_trainer(net, optimizer_name, wd, momentum, lr_mode, lr, lr_decay_period, lr_decay_epoch, lr_decay, target_lr, poly_power, warmup_epochs, warmup_lr, warmup_mode, batch_size, num_epochs, num_training_samples, dtype, gamma_wd_mult=1.0, beta_wd_mult=1.0, bias_wd_mult=1.0, state_file_path=None): if gamma_wd_mult != 1.0: for k, v in net.collect_params(".*gamma").items(): v.wd_mult = gamma_wd_mult if beta_wd_mult != 1.0: for k, v in net.collect_params(".*beta").items(): v.wd_mult = beta_wd_mult if bias_wd_mult != 1.0: for k, v in net.collect_params(".*bias").items(): v.wd_mult = bias_wd_mult if lr_decay_period > 0: lr_decay_epoch = list(range(lr_decay_period, num_epochs, lr_decay_period)) else: lr_decay_epoch = [int(i) for i in lr_decay_epoch.split(",")] num_batches = num_training_samples // batch_size lr_scheduler = LRScheduler( mode=lr_mode, base_lr=lr, n_iters=num_batches, n_epochs=num_epochs, step=lr_decay_epoch, step_factor=lr_decay, target_lr=target_lr, power=poly_power, warmup_epochs=warmup_epochs, warmup_lr=warmup_lr, warmup_mode=warmup_mode) optimizer_params = {"learning_rate": lr, "wd": wd, "momentum": momentum, "lr_scheduler": lr_scheduler} if dtype != "float32": optimizer_params["multi_precision"] = True trainer = gluon.Trainer( params=net.collect_params(), optimizer=optimizer_name, optimizer_params=optimizer_params) if (state_file_path is not None) and state_file_path and os.path.exists(state_file_path): logging.info("Loading trainer states: {}".format(state_file_path)) trainer.load_states(state_file_path) if trainer._optimizer.wd != wd: trainer._optimizer.wd = wd logging.info("Reset the weight decay: {}".format(wd)) # lr_scheduler = trainer._optimizer.lr_scheduler trainer._optimizer.lr_scheduler = lr_scheduler return trainer, lr_scheduler def save_params(file_stem, net, trainer): net.save_parameters(file_stem + ".params") trainer.save_states(file_stem + ".states") def train_epoch(epoch, net, train_metric, train_data, batch_fn, data_source_needs_reset, dtype, ctx, loss_func, trainer, lr_scheduler, batch_size, log_interval, mixup, mixup_epoch_tail, label_smoothing, num_classes, num_epochs, grad_clip_value, batch_size_scale): labels_list_inds = None batch_size_extend_count = 0 tic = time.time() if data_source_needs_reset: train_data.reset() train_metric.reset() train_loss = 0.0 btic = time.time() for i, batch in enumerate(train_data): data_list, labels_list = batch_fn(batch, ctx) if label_smoothing: eta = 0.1 on_value = 1 - eta + eta / num_classes off_value = eta / num_classes labels_list_inds = labels_list labels_list = [Y.one_hot(depth=num_classes, on_value=on_value, off_value=off_value) for Y in labels_list] if mixup: if not label_smoothing: labels_list_inds = labels_list labels_list = [Y.one_hot(depth=num_classes) for Y in labels_list] if epoch < num_epochs - mixup_epoch_tail: alpha = 1 lam = np.random.beta(alpha, alpha) data_list = [lam * X + (1 - lam) * X[::-1] for X in data_list] labels_list = [lam * Y + (1 - lam) * Y[::-1] for Y in labels_list] with ag.record(): outputs_list = [net(X.astype(dtype, copy=False)) for X in data_list] loss_list = [loss_func(yhat, y.astype(dtype, copy=False)) for yhat, y in zip(outputs_list, labels_list)] for loss in loss_list: loss.backward() lr_scheduler.update(i, epoch) if grad_clip_value is not None: grads = [v.grad(ctx[0]) for v in net.collect_params().values() if v._grad is not None] gluon.utils.clip_global_norm(grads, max_norm=grad_clip_value) if batch_size_scale == 1: trainer.step(batch_size) else: if (i + 1) % batch_size_scale == 0: batch_size_extend_count = 0 trainer.step(batch_size * batch_size_scale) for p in net.collect_params().values(): p.zero_grad() else: batch_size_extend_count += 1 train_loss += sum([loss.mean().asscalar() for loss in loss_list]) / len(loss_list) train_metric.update( labels=(labels_list if not (mixup or label_smoothing) else labels_list_inds), preds=outputs_list) if log_interval and not (i + 1) % log_interval: speed = batch_size * log_interval / (time.time() - btic) btic = time.time() train_accuracy_msg = report_accuracy(metric=train_metric) logging.info("Epoch[{}] Batch [{}]\tSpeed: {:.2f} samples/sec\t{}\tlr={:.5f}".format( epoch + 1, i, speed, train_accuracy_msg, trainer.learning_rate)) if (batch_size_scale != 1) and (batch_size_extend_count > 0): trainer.step(batch_size * batch_size_extend_count) for p in net.collect_params().values(): p.zero_grad() throughput = int(batch_size * (i + 1) / (time.time() - tic)) logging.info("[Epoch {}] speed: {:.2f} samples/sec\ttime cost: {:.2f} sec".format( epoch + 1, throughput, time.time() - tic)) train_loss /= (i + 1) train_accuracy_msg = report_accuracy(metric=train_metric) logging.info("[Epoch {}] training: {}\tloss={:.4f}".format( epoch + 1, train_accuracy_msg, train_loss)) return train_loss def train_net(batch_size, num_epochs, start_epoch1, train_data, val_data, batch_fn, data_source_needs_reset, dtype, net, trainer, lr_scheduler, lp_saver, log_interval, mixup, mixup_epoch_tail, label_smoothing, num_classes, grad_clip_value, batch_size_scale, val_metric, train_metric, ctx): if batch_size_scale != 1: for p in net.collect_params().values(): p.grad_req = "add" if isinstance(ctx, mx.Context): ctx = [ctx] loss_func = gluon.loss.SoftmaxCrossEntropyLoss(sparse_label=(not (mixup or label_smoothing))) assert (type(start_epoch1) == int) assert (start_epoch1 >= 1) if start_epoch1 > 1: logging.info("Start training from [Epoch {}]".format(start_epoch1)) validate( metric=val_metric, net=net, val_data=val_data, batch_fn=batch_fn, data_source_needs_reset=data_source_needs_reset, dtype=dtype, ctx=ctx) val_accuracy_msg = report_accuracy(metric=val_metric) logging.info("[Epoch {}] validation: {}".format(start_epoch1 - 1, val_accuracy_msg)) gtic = time.time() for epoch in range(start_epoch1 - 1, num_epochs): train_loss = train_epoch( epoch=epoch, net=net, train_metric=train_metric, train_data=train_data, batch_fn=batch_fn, data_source_needs_reset=data_source_needs_reset, dtype=dtype, ctx=ctx, loss_func=loss_func, trainer=trainer, lr_scheduler=lr_scheduler, batch_size=batch_size, log_interval=log_interval, mixup=mixup, mixup_epoch_tail=mixup_epoch_tail, label_smoothing=label_smoothing, num_classes=num_classes, num_epochs=num_epochs, grad_clip_value=grad_clip_value, batch_size_scale=batch_size_scale) validate( metric=val_metric, net=net, val_data=val_data, batch_fn=batch_fn, data_source_needs_reset=data_source_needs_reset, dtype=dtype, ctx=ctx) val_accuracy_msg = report_accuracy(metric=val_metric) logging.info("[Epoch {}] validation: {}".format(epoch + 1, val_accuracy_msg)) if lp_saver is not None: lp_saver_kwargs = {"net": net, "trainer": trainer} val_acc_values = val_metric.get()[1] train_acc_values = train_metric.get()[1] val_acc_values = val_acc_values if type(val_acc_values) == list else [val_acc_values] train_acc_values = train_acc_values if type(train_acc_values) == list else [train_acc_values] lp_saver.epoch_test_end_callback( epoch1=(epoch + 1), params=(val_acc_values + train_acc_values + [train_loss, trainer.learning_rate]), **lp_saver_kwargs) logging.info("Total time cost: {:.2f} sec".format(time.time() - gtic)) if lp_saver is not None: opt_metric_name = get_metric_name(val_metric, lp_saver.acc_ind) logging.info("Best {}: {:.4f} at {} epoch".format( opt_metric_name, lp_saver.best_eval_metric_value, lp_saver.best_eval_metric_epoch)) def main(): args = parse_args() args.seed = init_rand(seed=args.seed) _, log_file_exist = initialize_logging( logging_dir_path=args.save_dir, logging_file_name=args.logging_file_name, script_args=args, log_packages=args.log_packages, log_pip_packages=args.log_pip_packages) ctx, batch_size = prepare_mx_context( num_gpus=args.num_gpus, batch_size=args.batch_size) net = prepare_model( model_name=args.model, use_pretrained=args.use_pretrained, pretrained_model_file_path=args.resume.strip(), dtype=args.dtype, tune_layers=args.tune_layers, classes=args.num_classes, in_channels=args.in_channels, do_hybridize=(not args.not_hybridize), ctx=ctx) assert (hasattr(net, "classes")) num_classes = net.classes ds_metainfo = get_dataset_metainfo(dataset_name=args.dataset) ds_metainfo.update(args=args) train_data = get_train_data_source( ds_metainfo=ds_metainfo, batch_size=batch_size, num_workers=args.num_workers) val_data = get_val_data_source( ds_metainfo=ds_metainfo, batch_size=batch_size, num_workers=args.num_workers) batch_fn = get_batch_fn(use_imgrec=ds_metainfo.use_imgrec) num_training_samples = len(train_data._dataset) if not ds_metainfo.use_imgrec else ds_metainfo.num_training_samples trainer, lr_scheduler = prepare_trainer( net=net, optimizer_name=args.optimizer_name, wd=args.wd, momentum=args.momentum, lr_mode=args.lr_mode, lr=args.lr, lr_decay_period=args.lr_decay_period, lr_decay_epoch=args.lr_decay_epoch, lr_decay=args.lr_decay, target_lr=args.target_lr, poly_power=args.poly_power, warmup_epochs=args.warmup_epochs, warmup_lr=args.warmup_lr, warmup_mode=args.warmup_mode, batch_size=batch_size, num_epochs=args.num_epochs, num_training_samples=num_training_samples, dtype=args.dtype, gamma_wd_mult=args.gamma_wd_mult, beta_wd_mult=args.beta_wd_mult, bias_wd_mult=args.bias_wd_mult, state_file_path=args.resume_state) if args.save_dir and args.save_interval: param_names = ds_metainfo.val_metric_capts + ds_metainfo.train_metric_capts + ["Train.Loss", "LR"] lp_saver = TrainLogParamSaver( checkpoint_file_name_prefix="{}_{}".format(ds_metainfo.short_label, args.model), last_checkpoint_file_name_suffix="last", best_checkpoint_file_name_suffix=None, last_checkpoint_dir_path=args.save_dir, best_checkpoint_dir_path=None, last_checkpoint_file_count=2, best_checkpoint_file_count=2, checkpoint_file_save_callback=save_params, checkpoint_file_exts=(".params", ".states"), save_interval=args.save_interval, num_epochs=args.num_epochs, param_names=param_names, acc_ind=ds_metainfo.saver_acc_ind, # bigger=[True], # mask=None, score_log_file_path=os.path.join(args.save_dir, "score.log"), score_log_attempt_value=args.attempt, best_map_log_file_path=os.path.join(args.save_dir, "best_map.log")) else: lp_saver = None train_net( batch_size=batch_size, num_epochs=args.num_epochs, start_epoch1=args.start_epoch, train_data=train_data, val_data=val_data, batch_fn=batch_fn, data_source_needs_reset=ds_metainfo.use_imgrec, dtype=args.dtype, net=net, trainer=trainer, lr_scheduler=lr_scheduler, lp_saver=lp_saver, log_interval=args.log_interval, mixup=args.mixup, mixup_epoch_tail=args.mixup_epoch_tail, label_smoothing=args.label_smoothing, num_classes=num_classes, grad_clip_value=args.grad_clip, batch_size_scale=args.batch_size_scale, val_metric=get_composite_metric(ds_metainfo.val_metric_names, ds_metainfo.val_metric_extra_kwargs), train_metric=get_composite_metric(ds_metainfo.train_metric_names, ds_metainfo.train_metric_extra_kwargs), ctx=ctx) if __name__ == "__main__": main()
[ "osemery@gmail.com" ]
osemery@gmail.com
78619db4bd98a279210cb7f4d217a84cfbeb1701
5d0fe4a9e026234fe15e6c4380355061bb4dac64
/tests/browser/pages/invest/hpo.py
d5ba9be3f4f278923f41b32b53e671e09ebc9516
[ "MIT" ]
permissive
uktrade/directory-tests
37e243862da8ac594cf1ea06ade714db5e1aba03
39ec6c26203580238e65566a472cbd80916e6726
refs/heads/master
2022-08-09T16:58:56.248982
2022-08-01T12:25:10
2022-08-01T12:25:10
71,367,747
4
3
MIT
2022-08-01T12:26:09
2016-10-19T14:48:57
Python
UTF-8
Python
false
false
8,015
py
# -*- coding: utf-8 -*- """Invest in Great - HPO Page Object.""" import logging from typing import List from selenium.webdriver.common.by import By from selenium.webdriver.remote.webdriver import WebDriver from directory_tests_shared import URLs from directory_tests_shared.enums import PageType, Service from pages import ElementType, common_selectors from pages.common_actions import ( Selector, assertion_msg, check_for_sections, check_if_element_is_not_visible, check_url, find_element, get_selectors, go_to_url, scroll_to, ) NAME = "HPO" NAMES = [ "Aquaculture", "High productivity food production", "Lightweight structures", "Photonics and microelectronics", "Rail infrastructure", "Space", "Sustainable packaging", ] SERVICE = Service.INVEST TYPE = PageType.HPO URL = URLs.INVEST_HPO.absolute PAGE_TITLE = "high potential" SubURLs = { "aquaculture": URLs.INVEST_HPO_AQUACULTURE.absolute, "high productivity food production": URLs.INVEST_HPO_HIGH_PRODUCTIVITY_FOOD.absolute, "lightweight structures": URLs.INVEST_HPO_LIGHTWEIGHT.absolute, "photonics and microelectronics": URLs.INVEST_HPO_PHOTONICS.absolute, "rail infrastructure": URLs.INVEST_HPO_RAIL.absolute, "space": URLs.INVEST_HPO_SPACE.absolute, "sustainable packaging": URLs.INVEST_HPO_SUSTAINABLE_PACKAGING.absolute, } SELECTORS = { "hero": { "self": Selector(By.ID, "hero"), "heading": Selector(By.CSS_SELECTOR, "#hero h1"), }, "contact us": { "self": Selector(By.ID, "contact-section"), "heading": Selector(By.CSS_SELECTOR, "#contact-section h2"), "get in touch": Selector(By.CSS_SELECTOR, "#contact-section a"), }, "proposition one": { "self": Selector(By.ID, "proposition-one"), "heading": Selector(By.CSS_SELECTOR, "#proposition-one h2"), "view video transcript": Selector( By.CSS_SELECTOR, "#proposition-one details summary", type=ElementType.BUTTON ), "video transcript": Selector(By.CSS_SELECTOR, "#proposition-one details p"), }, "opportunity list": {"self": Selector(By.ID, "opportunity-list")}, "proposition two": { "self": Selector(By.ID, "proposition-two"), "heading": Selector(By.CSS_SELECTOR, "#proposition-two div:nth-child(1) h2"), "list of propositions": Selector(By.CSS_SELECTOR, "#proposition-two ul"), }, "competitive advantages": { "self": Selector(By.ID, "competitive-advantages"), "first - icon": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(1) img" ), "first - heading": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(1) div ~ div > h3" ), "first - list": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(1) div ~ div > ul" ), "second - icon": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(2) img" ), "second - heading": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(2) div ~ div > h3" ), "second - list": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(2) div ~ div > ul" ), "third - icon": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(3) img" ), "third - heading": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(3) div ~ div > h3" ), "third - list": Selector( By.CSS_SELECTOR, "#competitive-advantages li:nth-child(3) div ~ div > ul" ), }, "testimonial": { "self": Selector(By.ID, "testimonial"), "quote": Selector(By.CSS_SELECTOR, "#testimonial p"), }, "company list": { "self": Selector(By.ID, "company-list"), "heading": Selector(By.CSS_SELECTOR, "#company-list p"), "list": Selector(By.CSS_SELECTOR, "#company-list ul"), "images": Selector(By.CSS_SELECTOR, "#company-list ul img"), }, "case studies": { "self": Selector(By.ID, "case-studies"), "heading": Selector(By.CSS_SELECTOR, "#case-studies h2"), "first case study": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(1)", type=ElementType.BUTTON, ), "first - heading": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(1) h3" ), "first - text": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(1) p" ), "second case study": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(2)", type=ElementType.BUTTON, ), "second - heading": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(2) h3" ), "second - text": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(2) p" ), "third case study": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(3)", type=ElementType.BUTTON, ), "third - heading": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(3) h3" ), "third - text": Selector( By.CSS_SELECTOR, "#case-studies details:nth-child(3) p" ), }, "other opportunities": { "self": Selector(By.ID, "other-opportunities"), "first opportunity": Selector( By.CSS_SELECTOR, "#other-opportunities div:nth-child(1) > div > a" ), "second opportunity": Selector( By.CSS_SELECTOR, "#other-opportunities div:nth-child(2) > div > a" ), }, } SELECTORS.update(common_selectors.INTERNATIONAL_HEADER_WO_LANGUAGE_SELECTOR) SELECTORS.update(common_selectors.BETA_BAR) SELECTORS.update(common_selectors.ERROR_REPORTING) SELECTORS.update(common_selectors.INTERNATIONAL_FOOTER) UNEXPECTED_ELEMENTS = { "breadcrumbs": {"itself": Selector(By.CSS_SELECTOR, "div.breadcrumbs")} } def visit(driver: WebDriver, *, page_name: str = None): url = SubURLs[page_name] if page_name else URL go_to_url(driver, url, page_name or NAME) def should_be_here(driver: WebDriver, *, page_name: str): url = SubURLs[page_name] if page_name else URL check_url(driver, url) logging.debug("All expected elements are visible on '%s' page", PAGE_TITLE) def should_see_sections(driver: WebDriver, names: List[str]): check_for_sections(driver, all_sections=SELECTORS, sought_sections=names) def clean_name(name: str) -> str: return name.split(" - ")[1].strip() def should_see_content_for(driver: WebDriver, hpo_name: str): source = driver.page_source hpo_name = clean_name(hpo_name) logging.debug("Looking for: {}".format(hpo_name)) with assertion_msg( "Expected to find term '%s' in the source of the page %s", hpo_name, driver.current_url, ): assert hpo_name.lower() in source.lower() def should_not_see_section(driver: WebDriver, name: str): section = UNEXPECTED_ELEMENTS[name.lower()] for key, selector in section.items(): check_if_element_is_not_visible( driver, selector, element_name=key, wait_for_it=False ) def unfold_elements_in_section(driver: WebDriver, section_name: str): section_selectors = SELECTORS[section_name] folded_elements = get_selectors(section_selectors, ElementType.BUTTON) logging.debug(f"Found {len(folded_elements)} selectors for elements to unfold") for name, selector in folded_elements.items(): element = find_element(driver, selector, element_name=name) scroll_to(driver, element) if element.get_attribute("open"): logging.debug(f"Element: '{name}' is already unfolded") else: logging.debug(f"Unfolding closed element: {name}") element.click()
[ "kowalczykjanusz@gmail.com" ]
kowalczykjanusz@gmail.com
67a02c6dd73076b37449187a6fab501e9765484c
7c99ea5b1ffe089c97615336daf4b6ceed9a5b00
/Configurations/VBSOS/SignalRegions/2018/var_v6/aliases.py
3367d7c4e283746301669e915c952ddf8f0eff76
[]
no_license
flaviacetorelli/PlotsConfigurations
948faadba356e1d5e6f546dc11dd8dacfe1c1910
aa5cf802c86902378617f566186bc638e69f9936
refs/heads/master
2022-05-02T00:37:56.070453
2022-03-18T10:14:23
2022-03-18T10:14:23
235,580,894
0
1
null
2020-01-22T13:37:30
2020-01-22T13:37:29
null
UTF-8
Python
false
false
8,349
py
import os import copy import inspect configurations = os.path.realpath(inspect.getfile(inspect.currentframe())) # this file configurations = os.path.dirname(configurations) # ggH2018 configurations = os.path.dirname(configurations) # Differential configurations = os.path.dirname(configurations) # Configurations #aliases = {} # imported from samples.py: # samples, signals mc = [skey for skey in samples if skey not in ('Fake', 'DATA', 'Dyemb')] mc_emb = [skey for skey in samples if skey not in ('Fake', 'DATA')] ###### START ###### # distance between lepton and jet aliases['R_j1l1'] = { 'expr': 'TMath::Sqrt(TMath::Power(Alt$(CleanJet_eta[0],-9999.)-Alt$(Lepton_eta[0],-9999.),2)+TMath::Power(Alt$(CleanJet_phi[0],-9999.)-Alt$(Lepton_phi[0],-9999.),2))' } aliases['R_j2l1'] = { 'expr': 'TMath::Sqrt(TMath::Power(Alt$(CleanJet_eta[1],-9999.)-Alt$(Lepton_eta[0],-9999.),2)+TMath::Power(Alt$(CleanJet_phi[1],-9999.)-Alt$(Lepton_phi[0],-9999.),2))' } aliases['R_j1l2'] = { 'expr': 'TMath::Sqrt(TMath::Power(Alt$(CleanJet_eta[0],-9999.)-Alt$(Lepton_eta[1],-9999.),2)+TMath::Power(Alt$(CleanJet_phi[0],-9999.)-Alt$(Lepton_phi[1],-9999.),2))' } aliases['R_j2l2'] = { 'expr': 'TMath::Sqrt(TMath::Power(Alt$(CleanJet_eta[1],-9999.)-Alt$(Lepton_eta[1],-9999.),2)+TMath::Power(Alt$(CleanJet_phi[1],-9999.)-Alt$(Lepton_phi[1],-9999.),2))' } aliases['Zeppll_al'] = { 'expr' : '0.5*TMath::Abs((Alt$(Lepton_eta[0],-9999.)+Alt$(Lepton_eta[1],-9999.))-(Alt$(CleanJet_eta[0],-9999.)+Alt$(CleanJet_eta[1],-9999.)))' } ## QGL REMORPHING morphing_file = "/afs/cern.ch/user/d/dvalsecc/public/qgl_morphing/morphing_functions_final_2018.root" qgl_reader_path = os.getenv('CMSSW_BASE') + '/src/PlotsConfigurations/Configurations/VBSOS/SignalRegions/2018/var_v6/macro/' aliases['CleanJet_qgl_morphed'] = { 'class': 'QGL_morphing', 'args': (morphing_file), 'linesToAdd' : [ 'gSystem->Load("libLatinoAnalysisMultiDraw.so")', '.L ' + qgl_reader_path + 'qgl_morphing.cc+', ] } ## Variables for DNN aliases['bVeto'] = { 'expr': 'Sum$(CleanJet_pt > 20. && abs(CleanJet_eta) < 2.5 && Jet_btagDeepB[CleanJet_jetIdx] > 0.4184) == 0' # medium 0.4184 loose 0.1241 } aliases['bReq'] = { 'expr': 'Sum$(CleanJet_pt > 30. && abs(CleanJet_eta) < 2.5 && Jet_btagDeepB[CleanJet_jetIdx] > 0.4184) >= 1' } aliases['zeroJet'] = { 'expr': 'Alt$(CleanJet_pt[0], 0) < 30.' } ## cuts aliases['top_cr'] = { 'expr': '((zeroJet && !bVeto) || bReq)' } ###### END ###### eleWP='mvaFall17V1Iso_WP90' muWP='cut_Tight_HWWW' aliases['LepWPCut'] = { 'expr': 'LepCut2l__ele_'+eleWP+'__mu_'+muWP, 'samples': mc_emb + ['DATA'] } aliases['gstarLow'] = { 'expr': 'Gen_ZGstar_mass >0 && Gen_ZGstar_mass < 4', 'samples': ['VgS','Dyveto'] } aliases['gstarHigh'] = { 'expr': 'Gen_ZGstar_mass <0 || Gen_ZGstar_mass > 4', 'samples': ['VgS','Dyveto'] } aliases['embedtotal'] = { 'expr': 'embed_total_WP90V1', # wrt. eleWP 'samples': 'Dyemb' } ######## OLD # Fake leptons transfer factor aliases['fakeW'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP, 'samples': ['Fake'] } # And variations - already divided by central values in formulas ! aliases['fakeWEleUp'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_EleUp', 'samples': ['Fake'] } aliases['fakeWEleDown'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_EleDown', 'samples': ['Fake'] } aliases['fakeWMuUp'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_MuUp', 'samples': ['Fake'] } aliases['fakeWMuDown'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_MuDown', 'samples': ['Fake'] } aliases['fakeWStatEleUp'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statEleUp', 'samples': ['Fake'] } aliases['fakeWStatEleDown'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statEleDown', 'samples': ['Fake'] } aliases['fakeWStatMuUp'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statMuUp', 'samples': ['Fake'] } aliases['fakeWStatMuDown'] = { 'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statMuDown', 'samples': ['Fake'] } # gen-matching to prompt only (GenLepMatch2l matches to *any* gen lepton) aliases['PromptGenLepMatch2l'] = { 'expr': 'Alt$(Lepton_promptgenmatched[0]*Lepton_promptgenmatched[1], 0)', 'samples': mc } #nCleanGenJet aliases['nCleanGenJet'] = { 'linesToAdd': ['.L %s/src/PlotsConfigurations/Configurations/Differential/ngenjet.cc+' % os.getenv('CMSSW_BASE')], 'class': 'CountGenJet', 'samples': mc } # PostProcessing did not create (anti)topGenPt for ST samples with _ext1 lastcopy = (1 << 13) aliases['isTTbar'] = { 'expr': 'Sum$(TMath::Abs(GenPart_pdgId) == 6 && TMath::Odd(GenPart_statusFlags / %d)) == 2' % lastcopy, 'samples': ['top', 'Dyveto'] } aliases['isSingleTop'] = { 'expr': 'Sum$(TMath::Abs(GenPart_pdgId) == 6 && TMath::Odd(GenPart_statusFlags / %d)) == 1' % lastcopy, 'samples': ['top', 'Dyveto'] } aliases['topGenPtOTF'] = { 'expr': 'Sum$((GenPart_pdgId == 6 && TMath::Odd(GenPart_statusFlags / %d)) * GenPart_pt)' % lastcopy, 'samples': ['top', 'Dyveto'] } aliases['antitopGenPtOTF'] = { 'expr': 'Sum$((GenPart_pdgId == -6 && TMath::Odd(GenPart_statusFlags / %d)) * GenPart_pt)' % lastcopy, 'samples': ['top', 'Dyveto'] } aliases['Top_pTrw'] = { 'expr': 'isTTbar * (TMath::Sqrt(TMath::Exp(0.0615 - 0.0005 * topGenPtOTF) * TMath::Exp(0.0615 - 0.0005 * antitopGenPtOTF))) + isSingleTop', 'samples': ['top', 'Dyveto'] } handle = open('%s/src/PlotsConfigurations/Configurations/patches/DYrew.py' % os.getenv('CMSSW_BASE'),'r') exec(handle) handle.close() aliases['DY_NLO_pTllrw'] = { #'expr': '1', 'expr': '('+DYrew['2018']['NLO'].replace('x', 'gen_ptll')+')*(nCleanGenJet == 0)+1.0*(nCleanGenJet > 0)', 'samples': ['DY', 'DYtt'] } aliases['DY_LO_pTllrw'] = { #'expr': '1', 'expr': '('+DYrew['2018']['LO'].replace('x', 'gen_ptll')+')*(nCleanGenJet == 0)+1.0*(nCleanGenJet > 0)', 'samples': ['DY', 'DYtt'] } # Jet bins # using Alt$(CleanJet_pt[n], 0) instead of Sum$(CleanJet_pt >= 30) because jet pt ordering is not strictly followed in JES-varied samples # No jet with pt > 30 GeV # aliases['zeroJet'] = { # 'expr': 'Alt$(CleanJet_pt[0], 0) < 30.' # } aliases['oneJet'] = { 'expr': 'Alt$(CleanJet_pt[0], 0) > 30.' } aliases['multiJet'] = { 'expr': 'Alt$(CleanJet_pt[1], 0) > 30.' } # B tag scale factors aliases['bVetoSF'] = { 'expr': 'TMath::Exp(Sum$(TMath::Log((CleanJet_pt>20 && abs(CleanJet_eta)<2.5)*Jet_btagSF_shape[CleanJet_jetIdx]+1*(CleanJet_pt<20 || abs(CleanJet_eta)>2.5))))', 'samples': mc } aliases['bReqSF'] = { 'expr': 'TMath::Exp(Sum$(TMath::Log((CleanJet_pt>30 && abs(CleanJet_eta)<2.5)*Jet_btagSF_shape[CleanJet_jetIdx]+1*(CleanJet_pt<30 || abs(CleanJet_eta)>2.5))))', 'samples': mc } aliases['btagSF'] = { 'expr': '(bVeto || (top_cr && zeroJet))*bVetoSF + (top_cr && !zeroJet)*bReqSF', 'samples': mc } for shift in ['jes','lf','hf','lfstats1','lfstats2','hfstats1','hfstats2','cferr1','cferr2']: for targ in ['bVeto', 'bReq']: alias = aliases['%sSF%sup' % (targ, shift)] = copy.deepcopy(aliases['%sSF' % targ]) alias['expr'] = alias['expr'].replace('btagSF_shape', 'btagSF_shape_up_%s' % shift) alias = aliases['%sSF%sdown' % (targ, shift)] = copy.deepcopy(aliases['%sSF' % targ]) alias['expr'] = alias['expr'].replace('btagSF_shape', 'btagSF_shape_down_%s' % shift) aliases['btagSF%sup' % shift] = { 'expr': aliases['btagSF']['expr'].replace('SF', 'SF' + shift + 'up'), 'samples': mc } aliases['btagSF%sdown' % shift] = { 'expr': aliases['btagSF']['expr'].replace('SF', 'SF' + shift + 'down'), 'samples': mc } # data/MC scale factors aliases['SFweight'] = { 'expr': ' * '.join(['SFweight2l', 'LepSF2l__ele_' + eleWP + '__mu_' + muWP, 'LepWPCut', 'btagSF']), 'samples': mc } # variations aliases['SFweightEleUp'] = { 'expr': 'LepSF2l__ele_'+eleWP+'__Up', 'samples': mc_emb } aliases['SFweightEleDown'] = { 'expr': 'LepSF2l__ele_'+eleWP+'__Do', 'samples': mc_emb } aliases['SFweightMuUp'] = { 'expr': 'LepSF2l__mu_'+muWP+'__Up', 'samples': mc_emb } aliases['SFweightMuDown'] = { 'expr': 'LepSF2l__mu_'+muWP+'__Do', 'samples': mc_emb }
[ "flavia.cetorelli@cern.ch" ]
flavia.cetorelli@cern.ch
3b2dd0538593d549e4ae6830761d486da4941218
ab5f28c2ef1d0e40fd335796f9717a0bb83f4ad6
/server/modules/model.py
dc74edeeb4480f796afaba6fe7d4f18f7e63266f
[ "Apache-2.0" ]
permissive
Folashade/sagefy
dd2c40e3459c10c9cbc6ac7f283618b094b3aa5b
f92dcd8122ab524935dfaf50f1c15489f3e502f5
refs/heads/master
2021-01-12T20:59:16.852371
2016-01-04T02:58:18
2016-01-04T02:58:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,848
py
import rethinkdb as r import framework.database as database from modules.util import uniqid, omit, pick, extend from modules.content import get as c from modules.classproperty import classproperty from copy import deepcopy # TODO-2 Remove OOP based model. Instead, just use simple functions, # preferring pure functions where possible. def update_modified(field): return r.now() def iter(fn, data, schema, prefix=''): for field_name, field_schema in schema.items(): fn(data, field_name, field_schema, prefix) if 'embed' in field_schema: data[field_name] = data.get(field_name) or {} iter(fn, data[field_name], field_schema['embed'], '%s%s.' % (prefix, field_name)) elif 'embed_many' in field_schema: data[field_name] = data.get(field_name) or [] for i, d in enumerate(data[field_name]): iter(fn, d, field_schema['embed_many'], '%s%s.%i.' % (prefix, field_name, i)) class Model(object): strict = True # strict = True will remove any fields not defined in the schema # to open up, either do strict = False or specify the field names in the # schema with an empty dict schema = { 'id': { 'default': uniqid # RethinkDB by default uses UUID, but as its JSON, # there's no reason to not use the full alphanumeric set }, 'created': { 'default': r.now() }, 'modified': { 'default': r.now(), 'bundle': update_modified } } # Extend with: schema = dict(Parent.schema.copy(), **{ ... }) # Avaliable per field: # - validate: a list of functions to run on the field. # return a string if error, None if okay # - bundle: before saving to the database, # transform the data # - default: default value of the field # can be a value or a function to call # - deliver: tranform the data before sending out to the client # can also be used for permissions # - access: control which client can access this field's information # - unique: True will check to make sure no other row has # the same value not needed on `id` field, # as it is the primary key # - embed: list of fields contained in the field # - embed_many: list of fields contained in a list of dicts indexes = () # A list of indexes for the table def __init__(self, data=None): """ Initialize the model, setting defaults where needed. """ self.data = data or {} self.defaults() def __getitem__(self, key): """ Enable `model['field']`. """ return self.data.get(key) def __setitem__(self, key, value): """ Enable `model['field'] = value`. """ self.data[key] = value def __delitem__(self, key): """ Enable `del model['field']`. """ del self.data[key] def __contains__(self, item): """ Enable `field in model`. """ return item in self.data @classproperty def table(self): """ Refer to `self.table` and get a RethinkDB reference to the table. """ assert self.tablename, 'You must provide a tablename.' return database.db.table(self.tablename) @classmethod def get(cls, **params): """ Get one model which matches the provided keyword arguments. Return None when there's no matching document. """ data = None if params.get('id'): data = (cls.table .get(params.get('id')) .run(database.db_conn)) else: data = list(cls.table .filter(params) .limit(1) .run(database.db_conn)) data = data[0] if len(data) > 0 else None if data: return cls(data) @classmethod def list(cls, **params): """ Get a list of models matching the provided keyword arguments. Return empty array when no models match. """ data_list = (cls.table .filter(params) .run(database.db_conn)) return [cls(data) for data in data_list] @classmethod def insert(cls, data): """ Create a new model instance. Return model and errors if failed. """ assert isinstance(data, dict) data = omit(data, ('id', 'created', 'modified')) instance = cls(data) return instance.save() def update(self, data): """ Update the model in the database. Return model and errors if failed. """ assert isinstance(data, dict) data = omit(data, ('id', 'created', 'modified')) extend(self.data, data) return self.save() def save(self): """ Insert the model in the database. Return model and errors if failed. """ errors = self.validate() if len(errors): return self, errors data = self.bundle() self.id = data['id'] self.table.insert(data, conflict='update').run(database.db_conn) self.sync() return self, [] def sync(self): """ Pull the fields from the database. """ data = (self.table .get(self['id']) .run(database.db_conn)) extend(self.data, data) return self def delete(self): """ Remove the model from the database. """ (self.table .get(self['id']) .delete() .run(database.db_conn)) return self, [] def validate(self): """ Ensure the data presented matches the validations in the schema. Allow all data that is not specified in the schema. To limit database queries, first we do strict checks, which takes no lookups. Then we validate fields, which are unlikely to have lookups. Then we test unique, which we know will have one lookup each. To add model-level validations, extend this method, such as: def validate(self): errors = super().validate() if not errors: errors += self.validate_...() return errors """ errors = [] errors += self.enforce_strict_mode() if not errors: errors += self.validate_fields() if not errors: errors += self.test_unique() return errors def enforce_strict_mode(self): """ If strict mode, remove any fields that aren't part of the schema. For now, we'll just remove extra fields. Later, we might want an option to throw errors instead. """ def _(data, schema): for name, field_schema in schema.items(): if 'embed' in field_schema and name in data: data[name] = _(data[name], field_schema['embed']) elif 'embed_many' in field_schema and name in data: for i, d in enumerate(data[name]): data[name][i] = _(d, field_schema['embed_many']) return pick(data, schema.keys()) self.data = _(self.data, self.schema) return [] def validate_fields(self): """ Iterate over the schema, ensuring that everything matches up. """ errors = [] def _(data, field_name, field_schema, prefix): if 'validate' not in field_schema: return error = None for fn in field_schema['validate']: if isinstance(fn, (list, tuple)): error = fn[0](data.get(field_name), *fn[1:]) else: error = fn(data.get(field_name)) if error: errors.append({ 'name': prefix + field_name, 'message': error, }) break iter(_, self.data, self.schema) return errors def test_unique(self): """ Test all top-level fields marked as unique. """ errors = [] def _(data, field_name, field_schema, prefix): if ('unique' not in field_schema or data.get(field_name) is None): return query = (self.table .filter(r.row[field_name] == data.get(field_name)) .filter(r.row['id'] != self['id'])) if len(list(query.run(database.db_conn))) > 0: errors.append({ 'name': prefix + field_name, 'message': c('unique'), }) iter(_, self.data, self.schema) return errors def defaults(self): """ Set up defaults for data if not applied. """ def _(data, field_name, field_schema, prefix): if 'default' in field_schema and data.get(field_name) is None: if hasattr(field_schema['default'], '__call__'): data[field_name] = field_schema['default']() else: data[field_name] = field_schema['default'] iter(_, self.data, self.schema) return self.data def bundle(self): """ Prepare the data for saving into the database. Consider default values and will call `bundle` in the schema if present. """ def _(data, field_name, field_schema, prefix): if 'bundle' in field_schema and data.get(field_name): data[field_name] = field_schema['bundle'](data[field_name]) data = deepcopy(self.data) iter(_, data, self.schema) return data def deliver(self, access=None): """ Prepare the data for consumption. Consider access allowed and will call `deliver` in the schema if present. """ def _(data, field_name, field_schema, prefix): if ('access' in field_schema and data.get(field_name) and access not in field_schema['access']): del data[field_name] elif 'deliver' in field_schema and data.get(field_name): data[field_name] = field_schema['deliver'](data[field_name]) data = deepcopy(self.data) iter(_, data, self.schema) return data
[ "heiskr@users.noreply.github.com" ]
heiskr@users.noreply.github.com
9d74f6b7a1e32fffedd71a210f2a9009d0e57aa4
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/D/drj/multi.py
f1d9aa4aa940a0aa681026328186957517059a79
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
274
py
import scraperwiki import random import time n = random.choice(range(100)) i=0 while True: print n, i i += 1 time.sleep(1.4)import scraperwiki import random import time n = random.choice(range(100)) i=0 while True: print n, i i += 1 time.sleep(1.4)
[ "pallih@kaninka.net" ]
pallih@kaninka.net
8fe1a907db67146e05e04ef7aaa745788c55b202
5f25f45b7fac762b989563ca1270d37d31b749e8
/tests/regnet_tests/conftest.py
b654d49b7f598cb10f8e5d08de01ab4861cf089a
[ "MIT" ]
permissive
thomaseizinger/cryptonote-library
587c18d8e6662cc2920a896efbeab5fa49ee38b5
c39d956847e5ba2b46c2c4c90ab289ae1c04fe03
refs/heads/master
2023-04-02T21:29:39.423776
2021-04-02T17:51:40
2021-04-02T17:51:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,785
py
# Types. from typing import Dict, List, Tuple, Any # urandom standard function. from os import urandom # sleep standard function. from time import sleep # JSON standard lib. import json # pytest lib. import pytest # Transaction/Block classes. from cryptonote.classes.blockchain import OutputIndex # Crypto classes. from cryptonote.crypto.monero_crypto import InputState, OutputInfo, MoneroCrypto from cryptonote.crypto.monero_payment_id_crypto import MoneroPaymentIDCrypto # Address and Wallet classes. from cryptonote.classes.wallet.address import Address from cryptonote.classes.wallet.wallet import Wallet, WatchWallet # RPC classes. from cryptonote.rpc.monero_rpc import RPC, MoneroRPC # 1 XMR. ATOMIC_XMR: int = 1000000000000 class Harness: def __init__(self): """Construct a new test environment.""" self.rpc: RPC = MoneroRPC("127.0.0.1", 18081) self.crypto: MoneroCrypto = MoneroCrypto() self.crypto.oldest_txo_property = 1 key: bytes = urandom(32) self.wallet: Wallet = Wallet(self.crypto, key) self.watch: WatchWallet = WatchWallet( self.crypto, self.rpc, self.wallet.private_view_key, self.wallet.public_spend_key, 1, ) self.inputs: Dict[OutputIndex, OutputInfo] = {} self.rpc.generate_blocks(100, self.watch.new_address((0, 0)).address) def verify_inputs(self): """Verify our inputs is the same as the WatchWallet's.""" assert self.inputs == self.watch.inputs def poll_blocks(self): """Update our WatchWallet with the latest inputs.""" # Update with the newly found inputs. self.inputs = {**self.inputs, **self.watch.poll_blocks()} # Verify inputs. self.verify_inputs() def wait_for_unlock(self): """Wait for any new Transactions to unlock.""" sleep(2) self.rpc.generate_blocks( self.crypto.confirmations + 1, self.watch.new_address((0, 0)).address ) self.poll_blocks() def send(self, address: Address, amount: int) -> bytes: """Provide the specified address with the specified amount.""" # Update the available inputs. self.poll_blocks() # Prepare the spend. context: Dict[str, Any] = self.watch.prepare_send( address, amount, ATOMIC_XMR // 10 ) # Mark the spent inputs as spent in our copy of inputs. for input_i in context["inputs"]: self.inputs[ OutputIndex(bytes.fromhex(input_i["hash"]), input_i["index"]) ].state = InputState.Spent # Sign it. publishable: List[str] = json.loads( json.dumps(self.wallet.sign(json.loads(json.dumps(context)))) ) # Publish it. self.watch.finalize_send(True, context, publishable[1]) # Verify the WatchWallet's inputs equals our list. self.verify_inputs() # Wait for the outputs to unlock. self.wait_for_unlock() # Return the hash. return bytes.fromhex(publishable[0]) def return_funds( self, test_wallet: Wallet, test_watch: WatchWallet, amount: int ) -> None: """Return sent funds back to the master wallet.""" if amount != 0: context: Dict[str, Any] = test_watch.prepare_send( self.watch.new_address((0, 0)), amount - (ATOMIC_XMR // 10), (ATOMIC_XMR // 10) - 1, ) publishable: List[str] = test_wallet.sign(json.loads(json.dumps(context))) test_watch.finalize_send(True, context, publishable[1]) # Wait for the return TXs to unlock. self.wait_for_unlock() # Verify we can spend the returned funds. returned: Tuple[ List[bytes], Dict[OutputIndex, OutputInfo] ] = self.watch.can_spend( self.rpc.get_transaction(bytes.fromhex(publishable[0])) ) assert not returned[0] assert len(returned[1]) == 1 assert list(returned[1].keys())[0].tx_hash == bytes.fromhex(publishable[0]) assert returned[1][list(returned[1].keys())[0]].amount == amount - ( ATOMIC_XMR // 10 ) # Poll the blockchain. # This gets us the miner Transactions and change outputs. # Since inputs are stored as a Dict, this will not create duplicates. self.poll_blocks() # Verify inputs. self.verify_inputs() @pytest.fixture(scope="session") def harness() -> Harness: return Harness() @pytest.fixture def monero_payment_id_crypto() -> MoneroPaymentIDCrypto: return MoneroPaymentIDCrypto()
[ "lukeparker5132@gmail.com" ]
lukeparker5132@gmail.com
6ea8213e82dd3532a7da3312a90f6e1c64f353d4
63248ee10e29c11acebc9d3d977fe145cdfc156b
/tests/test_checker/test_noqa.py
53763cb8d3b8fb977b42a21944992f06bc461240
[ "MIT" ]
permissive
bekemaydin/wemake-python-styleguide
68e6517d6cb70ad34c11706760a7042b2b84877d
fad6a1d2b66012d623fe0e0bba9b5561622deeb0
refs/heads/master
2020-04-03T02:07:08.558327
2018-10-27T12:09:35
2018-10-27T12:09:35
154,947,414
0
0
MIT
2018-10-27T12:09:12
2018-10-27T09:31:34
Python
UTF-8
Python
false
false
1,919
py
# -*- coding: utf-8 -*- import re import subprocess from collections import Counter ERROR_PATTERN = re.compile(r'(Z\d{3})') def _assert_errors_count_in_output(output, errors): found_errors = Counter(( match.group(0) for match in ERROR_PATTERN.finditer(output) )) for found_error, found_count in found_errors.items(): assert found_error in errors, 'Error without a noqa count' assert found_count == errors.pop(found_error) assert len(errors) == 0 def test_noqa_fixture_disabled(absolute_path): """End-to-End test to check that all violations are present.""" errors = { 'Z110': 2, 'Z111': 1, 'Z112': 1, 'Z113': 1, 'Z220': 1, 'Z224': 1, 'Z300': 1, 'Z302': 1, 'Z303': 1, 'Z304': 1, 'Z305': 1, 'Z306': 2, 'Z307': 1, 'Z308': 1, 'Z309': 1, 'Z310': 4, 'Z312': 1, 'Z410': 1, 'Z420': 1, 'Z421': 1, 'Z422': 1, 'Z423': 1, 'Z430': 1, 'Z431': 2, 'Z432': 2, 'Z433': 2, 'Z434': 1, 'Z435': 1, 'Z436': 1, 'Z437': 1, } process = subprocess.Popen( [ 'flake8', '--disable-noqa', '--select', 'Z', absolute_path('fixtures', 'noqa.py'), ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, _ = process.communicate() _assert_errors_count_in_output(stdout.decode('utf8'), errors) def test_noqa_fixture(absolute_path): """End-to-End test to check that `noqa` works.""" process = subprocess.Popen( ['flake8', '--select', 'Z', absolute_path('fixtures', 'noqa.py')], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, _ = process.communicate() assert stdout.count(b'Z') == 0
[ "mail@sobolevn.me" ]
mail@sobolevn.me
cb2e2c8132f7d9953a559e5e1221ff0310aa5b05
572e5a017d615b1d8ce15bf109d7befb6e6fa0b8
/scilifelab/pm/core/production.py
9153576f4afc86ebfb7d7f35b6560cf6d7651bfd
[]
no_license
dargorr/scilifelab
ba509f0a3ab33d0911276c5512ccf03cc5184b64
fa9d661cc8bbcc95fbf3f65743b7e8874b434e31
refs/heads/master
2021-01-18T11:00:07.754888
2013-02-08T09:15:30
2013-02-08T09:15:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,129
py
"""Pm production module""" import os import re import yaml from cement.core import controller from scilifelab.pm.core.controller import AbstractExtendedBaseController from scilifelab.utils.misc import query_yes_no, filtered_walk from scilifelab.bcbio import prune_pp_platform_args from scilifelab.bcbio.flowcell import Flowcell from scilifelab.bcbio.status import status_query from scilifelab.utils.string import strip_extensions from scilifelab.pm.core.bcbio import BcbioRunController from scilifelab.utils.timestamp import utc_time FINISHED_FILE = "FINISHED_AND_DELIVERED" REMOVED_FILE = "FINISHED_AND_REMOVED" ## Main production controller class ProductionController(AbstractExtendedBaseController, BcbioRunController): """ Functionality for production management. """ class Meta: label = 'production' description = 'Manage production' def _setup(self, base_app): ## Adding arguments to existing groups requires setting up parent class first super(ProductionController, self)._setup(base_app) group = [x for x in self.app.args._action_groups if x.title == 'file transfer'][0] group.add_argument('--from_pre_casava', help="Transfer file with move", default=False, action="store_true") group.add_argument('--to_pre_casava', help="Use pre-casava directory structure for delivery", action="store_true", default=False) group.add_argument('--transfer_dir', help="Transfer data to transfer_dir instead of sample_prj dir", action="store", default=None) base_app.args.add_argument('--brief', help="Output brief information from status queries", action="store_true", default=False) def _process_args(self): # Set root path for parent class ## FIXME: use abspath? self._meta.root_path = self.app.config.get("production", "root") assert os.path.exists(self._meta.root_path), "No such directory {}; check your production config".format(self._meta.root_path) ## Set path_id for parent class if self.pargs.flowcell: self._meta.path_id = self.pargs.flowcell if self.pargs.project: self._meta.path_id = self.pargs.project ## Temporary fix for pre-casava directories if self.pargs.from_pre_casava: self._meta.path_id = self.pargs.flowcell ## This is a bug; how will this work when processing casava-folders?!? ## I need to set this so as not to upset productioncontrollers process_args if self.command == "hs_metrics": self._meta.path_id = self.pargs.flowcell if self.pargs.flowcell else self.pargs.project super(ProductionController, self)._process_args() @controller.expose(hide=True) def default(self): print self._help_text @controller.expose(help="Query the status of flowcells, projects, samples"\ " that are organized according to the CASAVA file structure") def status_query(self): if not self._check_pargs(["project", "flowcell"]): return status_query(self.app.config.get("archive", "root"), self.app.config.get("production", "root"), self.pargs.flowcell, self.pargs.project, brief=self.pargs.brief) def _from_casava_structure(self): """Get information from casava structure""" if not self._check_pargs(["project"]): return fc_list = [] pattern = "-bcbb-config.yaml$" def bcbb_yaml_filter(f): return re.search(pattern, f) != None samples = filtered_walk(os.path.join(self._meta.root_path, self._meta.path_id), bcbb_yaml_filter) for s in samples: fc = Flowcell(s) fc_new = fc.subset("sample_prj", self.pargs.project) fc_new.collect_files(os.path.dirname(s)) fc_list.append(fc_new) return fc_list def _to_casava_structure(self, fc): transfer_status = {} outdir_pfx = os.path.abspath(os.path.join(self.app.config.get("project", "root"), self.pargs.project.replace(".", "_").lower(), "data")) if self.pargs.transfer_dir: outdir_pfx = os.path.abspath(os.path.join(self.app.config.get("project", "root"), self.pargs.transfer_dir, "data")) for sample in fc: key = "{}_{}".format(sample['lane'], sample['sequence']) sources = {"files": self._prune_sequence_files(sample['files']), "results":sample['results']} outdir = os.path.join(outdir_pfx, sample['name'], fc.fc_id()) dirs = {"data":os.path.abspath(os.path.join(outdir_pfx, sample['name'], fc.fc_id())), "intermediate":os.path.abspath(os.path.join(outdir_pfx, sample['name'], fc.fc_id()))} self._make_output_dirs(dirs) fc_new = fc.subset("lane", sample['lane']).subset("name", sample['name']) targets = {"files": [src.replace(fc.path, dirs["data"]) for src in sources['files']], "results": [src.replace(fc.path, dirs["intermediate"]) for src in sources['results']]} fc_new.lane_files = dict((k, [os.path.join(outdir, os.path.basename(x)) for x in v]) for k,v in fc_new.lane_files.items()) fc_new.set_entry(key, 'files', targets['files']) fc_new.set_entry(key, 'results', targets['results']) ## Copy sample files - currently not doing lane files self._transfer_files(sources, targets) self.app.cmd.write(os.path.join(dirs["data"], "{}-bcbb-pm-config.yaml".format(sample['name'])), fc_new.as_yaml()) transfer_status[sample['name']] = {'files':len(sources['files']), 'results':len(sources['results'])} ## Rewrite platform_args; only keep time, workdir, account, partition, outpath and jobname pattern = "-post_process.yaml$" def pp_yaml_filter(f): return re.search(pattern, f) != None ppfiles = filtered_walk(dirs["data"], pp_yaml_filter) for pp in ppfiles: self.app.log.debug("Rewriting platform args for {}".format(pp)) with open(pp, "r") as fh: conf = yaml.load(fh) if not conf: self.app.log.warn("No configuration for {}".format(pp)) continue newconf = prune_pp_platform_args(conf) if newconf == conf: continue self.app.cmd.safe_unlink(pp) self.app.cmd.write(pp, yaml.safe_dump(newconf, default_flow_style=False, allow_unicode=True, width=1000)) # Write transfer summary self.app._output_data["stderr"].write("Transfer summary\n") self.app._output_data["stderr"].write("{:<18}{:>18}{:>18}\n".format("Sample","Transferred files", "Results")) for k, v in transfer_status.iteritems(): self.app._output_data["stderr"].write("{:<18}{:>18}{:>18}\n".format(k, v['files'], v['results'])) def _to_pre_casava_structure(self, fc): dirs = {"data":os.path.abspath(os.path.join(self.app.config.get("project", "root"), self.pargs.project.replace(".", "_").lower(), "data", fc.fc_id())), "intermediate":os.path.abspath(os.path.join(self.app.config.get("project", "root"), self.pargs.project.replace(".", "_").lower(), "intermediate", fc.fc_id()))} if self.pargs.transfer_dir: dirs["data"] = os.path.abspath(os.path.join(self.app.config.get("project", "root"), self.pargs.transfer_dir, "data", fc.fc_id())) dirs["intermediate"] = os.path.abspath(os.path.join(self.app.config.get("project", "root"), self.pargs.transfer_dir, "intermediate", fc.fc_id())) self._make_output_dirs(dirs) fc_new = fc for sample in fc: key = "{}_{}".format(sample['lane'], sample['sequence']) sources = {"files": self._prune_sequence_files(sample['files']), "results":sample['results']} targets = {"files": [src.replace(fc.path, dirs["data"]) for src in sources['files']], "results": [src.replace(fc.path, dirs["intermediate"]) for src in sources['results']]} fc_new.set_entry(key, 'files', targets['files']) fc_new.set_entry(key, 'results', targets['results']) ## FIX ME: lane file gathering ## fc_new.lane_files = dict((k,[x.replace(indir, outdir) for x in v]) for k,v in fc_new.lane_files.items()) ## Copy sample files - currently not doing lane files self._transfer_files(sources, targets) self.app.cmd.write(os.path.join(dirs["data"], "project_run_info.yaml"), fc_new.as_yaml()) def _from_pre_casava_structure(self): if not self._check_pargs(["project", "flowcell"]): return fc = Flowcell() fc.load([os.path.join(x, self.pargs.flowcell) for x in [self.config.get("archive", "root"), self.config.get("production", "root")]]) indir = os.path.join(self.config.get("production", "root"), self.pargs.flowcell) if not fc: self.log.warn("No run information available for {}".format(self.pargs.flowcell)) return fc_new = fc.subset("sample_prj", self.pargs.project) fc_new.collect_files(indir) return fc_new def _prune_sequence_files(self, flist): """Sometimes fastq and fastq.gz files are present for the same read. Make sure only one file is used, giving precedence to the zipped file. :param flist: list of files :returns: pruned list of files """ samples = {k[0]:{} for k in [strip_extensions(x, ['.gz']) for x in flist]} tmp = {samples[str(k[0])].update({str(k[1]):True}) for k in [strip_extensions(x, ['.gz']) for x in flist]} return ["{}.gz".format(k) if v.get('.gz', None) else k for k, v in samples.items()] def _make_output_dirs(self, dirs): if not os.path.exists(dirs["data"]): self.app.cmd.safe_makedir(dirs["data"]) if not os.path.exists(dirs["intermediate"]): self.app.cmd.safe_makedir(dirs["intermediate"]) def _transfer_files(self, sources, targets): for src, tgt in zip(sources['files'] + sources['results'], targets['files'] + targets['results']): if not os.path.exists(os.path.dirname(tgt)): self.app.cmd.safe_makedir(os.path.dirname(tgt)) self.app.cmd.transfer_file(src, tgt) @controller.expose(help="Transfer data") def transfer(self): if not self.pargs.from_pre_casava and self.pargs.to_pre_casava: self.app.log.warn("not delivering from casava input to pre_casava output") return ## Collect files depending on input structure if self.pargs.from_pre_casava: fc = self._from_pre_casava_structure() else: fc = self._from_casava_structure() if not fc: return ## Organize output file names depending on output structure if self.pargs.to_pre_casava: self._to_pre_casava_structure(fc) else: if isinstance(fc, list): for f in fc: self._to_casava_structure(f) else: self._to_casava_structure(fc) ## Command for touching file that indicates finished samples @controller.expose(help="Touch finished samples. Creates a file FINISHED_AND_DELIVERED with a utc time stamp.") def touch_finished(self): if not self._check_pargs(["project", "sample"]): return if os.path.exists(self.pargs.sample) and os.path.isfile(self.pargs.sample): with open(self.pargs.sample) as fh: slist = [x.rstrip() for x in fh.readlines()] else: slist = [self.pargs.sample] for s in slist: spath = os.path.join(self._meta.root_path, self._meta.path_id, s) if not os.path.exists(spath): self.app.log.warn("No such path {}; skipping".format(spath)) continue rsync_src = os.path.join(self._meta.root_path, self._meta.path_id, s) + os.sep rsync_tgt = os.path.join(self.app.config.get("runqc", "root"), self.pargs.project, s) + os.sep cl = ["rsync {} {} {}".format(self.app.config.get("runqc", "rsync_sample_opts"), rsync_src, rsync_tgt)] self.app.log.info("Checking if runqc uptodate with command '{}'".format(" ".join(cl))) out = self.app.cmd.command(cl, **{'shell':True}) if not self.pargs.dry_run and not out.find("total size is 0"): self.app.log.info("Some files need to be updated. Rsync output:") print "********" print out print "********" continue if not query_yes_no("Going to touch file {} for sample {}; continue?".format(FINISHED_FILE, s), force=self.pargs.force): continue self.app.log.info("Touching file {} for sample {}".format(FINISHED_FILE, s)) with open(os.path.join(spath, FINISHED_FILE), "w") as fh: t_utc = utc_time() fh.write(t_utc) ## Command for removing samples that have a FINISHED_FILE flag @controller.expose(help="Remove finished samples for a project. Searches for FINISHED_AND_DELIVERED and removes sample contents if file is present.") def remove_finished(self): if not self._check_pargs(["project"]): return # Don't filter out files def filter_fn(f): return True slist = os.listdir(os.path.join(self._meta.root_path, self._meta.path_id)) for s in slist: spath = os.path.join(self._meta.root_path, self._meta.path_id, s) if not os.path.isdir(spath): continue if not os.path.exists(os.path.join(spath, FINISHED_FILE)): self.app.log.info("Sample {} not finished; skipping".format(s)) continue flist = filtered_walk(spath, filter_fn) dlist = filtered_walk(spath, filter_fn, get_dirs=True) if os.path.exists(os.path.join(spath, REMOVED_FILE)): self.app.log.info("Sample {} already removed; skipping".format(s)) continue if len(flist) > 0 and not query_yes_no("Will remove directory {} containing {} files; continue?".format(s, len(flist)), force=self.pargs.force): continue self.app.log.info("Removing {} files from {}".format(len(flist), spath)) for f in flist: if f == os.path.join(spath, FINISHED_FILE): continue self.app.cmd.safe_unlink(f) self.app.log.info("Removing {} directories from {}".format(len(dlist), spath)) for d in sorted(dlist, reverse=True): self.app.cmd.safe_rmdir(d) if not self.pargs.dry_run: with open(os.path.join(spath, REMOVED_FILE), "w") as fh: t_utc = utc_time() fh.write(t_utc)
[ "per.unneberg@scilifelab.se" ]
per.unneberg@scilifelab.se
5db1252b0f2688a2ca7f7c38ca5bf3858df851e0
36f7e329efaf9f3b37003ef5c769628865f472ec
/Swasthya/eattendance/models/__init__.py
11f403f212880041ed35ab6447cce8dc7a533854
[]
no_license
aolashram/kri-vibe
d40080679f7f37568a8b57c2f7009ce6f6bcbbbc
6d77600c0c6953c3c78ec9a1fdf5a80c6611e162
refs/heads/main
2023-05-31T17:50:09.377629
2021-06-21T04:38:51
2021-06-21T04:38:51
378,806,174
0
0
null
null
null
null
UTF-8
Python
false
false
52
py
from .backengine import * from .attendance import *
[ "amalrajrs@gmail.com" ]
amalrajrs@gmail.com
83da29e85a3f4fb8c21958106bea5955ac87b29c
03d99657f557e37694f7aa4eeb6dc90a918ea647
/Cyberbook/XBlocks/simstudent-xblock/simstudent/simstudent.py
fb1fd2cce4a51c0b2285d3599a2cd015f5602985
[]
no_license
pawans1994/QUADL
5c3c824f2c813fd287d7135e878f5f962797bc2e
3f03eabb54e295ceaa9d4add1329ddc5eeafdec3
refs/heads/master
2023-05-11T21:25:07.046794
2020-03-18T16:41:15
2020-03-18T16:41:15
248,282,752
1
0
null
2023-05-01T20:19:11
2020-03-18T16:20:11
JavaScript
UTF-8
Python
false
false
4,077
py
"""TO-DO: Write a description of what this XBlock is.""" import pkg_resources from web_fragments.fragment import Fragment from xblock.core import XBlock from xblock.fields import Integer, Scope, String class SimStudentXBlock(XBlock): """ TO-DO: document what your XBlock does. """ # Fields are defined on the class. You can access them in your code as # self.<fieldname>. href = String(help="URL for SimStudent HTML rendring", default="", scope=Scope.content) display_name = String(help="Name of the component in the edxPlatform", default="Watson Tutor", scope=Scope.settings) name = String(help="Name of the brd file to run", default="if_p_or_q_then_r.brd", scope=Scope.content) host = String(help="Ip Address or the domain name of the host", default="localhost", scope=Scope.content) port = String(help="Port where the SimStudentServlet is running", default="8080", scope=Scope.content) folder_name = String(help="Name of the folder containing the bundle", default="informallogic", scope=Scope.content) problem_name = String(help="Name of the problem file (wme)", default="if_p_or_q_then_r", scope=Scope.content) value_type_checker_name = String(help="Class containing the valueTypeChecker", default="informallogic.MyFeaturePredicate.valueTypeChecker", scope=Scope.content) backend_name = String(help="Backend Class to use", default="interaction.ModelTracerBackend", scope=Scope.content) def resource_string(self, path): """Handy helper for getting resources from our kit.""" data = pkg_resources.resource_string(__name__, path) return data.decode("utf8") # TO-DO: change this view to display your data your own way. def student_view(self, context=None): """ The primary view of the SimStudentXBlock, shown to students when viewing courses. """ html = self.resource_string("static/html/simstudent.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/simstudent.css")) frag.add_javascript(self.resource_string("static/js/src/simstudent.js")) frag.initialize_js('SimStudentXBlock') return frag def studio_view(self, context=None): """ The primary view of the simstudentXBlock, shown to students when viewing courses. """ html = self.resource_string("static/html/simstudent_edit.html") frag = Fragment(html.format(self=self)) frag.add_javascript(self.resource_string("static/js/src/simstudent_edit.js")) frag.initialize_js('simstudentXBlock') return frag @XBlock.json_handler def save_simstudent(self, data, suffix=''): """ An example handler, which increments the data. """ self.href = data['href'] self.host = data['host'] self.port = data['port'] self.name = data['name'] self.folder_name = data['folder_name'] self.problem_name = data['problem_name'] self.value_type_checker_name = data['value_type_checker_name'] self.backend_name = data['backend_name'] # TO-DO: change this to create the scenarios you'd like to see in the # workbench while developing your XBlock. @staticmethod def workbench_scenarios(): """A canned scenario for display in the workbench.""" return [ ("SimStudentXBlock", """<simstudent/> """), ("Multiple SimStudentXBlock", """<vertical_demo> <simstudent/> <simstudent/> <simstudent/> </vertical_demo> """), ]
[ "nobody@ncsu.edu" ]
nobody@ncsu.edu
a04894d893ca8889368bac7bf6f3d839ea9fb93e
5ea1216c24b62c6beab3c6d9d2e2e06a9c58c796
/剑指Offer/39.数组中出现超过一半的数字.py
e639b88b4d8662393e9bf94769eb2228f051f053
[]
no_license
xiami2019/LeetCode
596de2f093d52b58cf80421f67de03757578cd5f
8d09a56672553ecee4af731796980b2c61c52df2
refs/heads/master
2021-01-02T15:15:13.984178
2020-07-08T01:20:15
2020-07-08T01:20:15
239,675,873
2
0
null
null
null
null
UTF-8
Python
false
false
365
py
class Solution: def majorityElement(self, nums: List[int]) -> int: preNum = nums[0] count = 1 for i in range(1, len(nums)): if nums[i] == preNum: count += 1 else: count -= 1 if count < 0: preNum = nums[i] count = 1 return preNum
[ "435350193@qq.com" ]
435350193@qq.com
cbe6836d45d807758d91ab44c6a674f19084cdd7
8dcd3ee098b4f5b80879c37a62292f42f6b2ae17
/venv/Lib/site-packages/pandas/tests/indexes/interval/test_constructors.py
54bacf8438132fd7a64734bf4b806e19692b4f26
[]
no_license
GregVargas1999/InfinityAreaInfo
53fdfefc11c4af8f5d2b8f511f7461d11a3f7533
2e4a7c6a2424514ca0ec58c9153eb08dc8e09a4a
refs/heads/master
2022-12-01T20:26:05.388878
2020-08-11T18:37:05
2020-08-11T18:37:05
286,821,452
0
0
null
null
null
null
UTF-8
Python
false
false
15,243
py
from functools import partial import numpy as np import pandas._testing as tm import pandas.core.common as com import pytest from pandas import ( Categorical, CategoricalIndex, Float64Index, Index, Int64Index, Interval, IntervalIndex, date_range, notna, period_range, timedelta_range, ) from pandas.core.arrays import IntervalArray from pandas.core.dtypes.common import is_categorical_dtype from pandas.core.dtypes.dtypes import IntervalDtype @pytest.fixture(params=[None, "foo"]) def name(request): return request.param class Base: """ Common tests for all variations of IntervalIndex construction. Input data to be supplied in breaks format, then converted by the subclass method get_kwargs_from_breaks to the expected format. """ @pytest.mark.parametrize( "breaks", [ [3, 14, 15, 92, 653], np.arange(10, dtype="int64"), Int64Index(range(-10, 11)), Float64Index(np.arange(20, 30, 0.5)), date_range("20180101", periods=10), date_range("20180101", periods=10, tz="US/Eastern"), timedelta_range("1 day", periods=10), ], ) def test_constructor(self, constructor, breaks, closed, name): result_kwargs = self.get_kwargs_from_breaks(breaks, closed) result = constructor(closed=closed, name=name, **result_kwargs) assert result.closed == closed assert result.name == name assert result.dtype.subtype == getattr(breaks, "dtype", "int64") tm.assert_index_equal(result.left, Index(breaks[:-1])) tm.assert_index_equal(result.right, Index(breaks[1:])) @pytest.mark.parametrize( "breaks, subtype", [ (Int64Index([0, 1, 2, 3, 4]), "float64"), (Int64Index([0, 1, 2, 3, 4]), "datetime64[ns]"), (Int64Index([0, 1, 2, 3, 4]), "timedelta64[ns]"), (Float64Index([0, 1, 2, 3, 4]), "int64"), (date_range("2017-01-01", periods=5), "int64"), (timedelta_range("1 day", periods=5), "int64"), ], ) def test_constructor_dtype(self, constructor, breaks, subtype): # GH 19262: conversion via dtype parameter expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype)) expected = constructor(**expected_kwargs) result_kwargs = self.get_kwargs_from_breaks(breaks) iv_dtype = IntervalDtype(subtype) for dtype in (iv_dtype, str(iv_dtype)): result = constructor(dtype=dtype, **result_kwargs) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50]) def test_constructor_nan(self, constructor, breaks, closed): # GH 18421 result_kwargs = self.get_kwargs_from_breaks(breaks) result = constructor(closed=closed, **result_kwargs) expected_subtype = np.float64 expected_values = np.array(breaks[:-1], dtype=object) assert result.closed == closed assert result.dtype.subtype == expected_subtype tm.assert_numpy_array_equal(result._ndarray_values, expected_values) @pytest.mark.parametrize( "breaks", [ [], np.array([], dtype="int64"), np.array([], dtype="float64"), np.array([], dtype="datetime64[ns]"), np.array([], dtype="timedelta64[ns]"), ], ) def test_constructor_empty(self, constructor, breaks, closed): # GH 18421 result_kwargs = self.get_kwargs_from_breaks(breaks) result = constructor(closed=closed, **result_kwargs) expected_values = np.array([], dtype=object) expected_subtype = getattr(breaks, "dtype", np.int64) assert result.empty assert result.closed == closed assert result.dtype.subtype == expected_subtype tm.assert_numpy_array_equal(result._ndarray_values, expected_values) @pytest.mark.parametrize( "breaks", [ tuple("0123456789"), list("abcdefghij"), np.array(list("abcdefghij"), dtype=object), np.array(list("abcdefghij"), dtype="<U1"), ], ) def test_constructor_string(self, constructor, breaks): # GH 19016 msg = ( "category, object, and string subtypes are not supported " "for IntervalIndex" ) with pytest.raises(TypeError, match=msg): constructor(**self.get_kwargs_from_breaks(breaks)) @pytest.mark.parametrize("cat_constructor", [Categorical, CategoricalIndex]) def test_constructor_categorical_valid(self, constructor, cat_constructor): # GH 21243/21253 if isinstance(constructor, partial) and constructor.func is Index: # Index is defined to create CategoricalIndex from categorical data pytest.skip() breaks = np.arange(10, dtype="int64") expected = IntervalIndex.from_breaks(breaks) cat_breaks = cat_constructor(breaks) result_kwargs = self.get_kwargs_from_breaks(cat_breaks) result = constructor(**result_kwargs) tm.assert_index_equal(result, expected) def test_generic_errors(self, constructor): # filler input data to be used when supplying invalid kwargs filler = self.get_kwargs_from_breaks(range(10)) # invalid closed msg = "invalid option for 'closed': invalid" with pytest.raises(ValueError, match=msg): constructor(closed="invalid", **filler) # unsupported dtype msg = "dtype must be an IntervalDtype, got int64" with pytest.raises(TypeError, match=msg): constructor(dtype="int64", **filler) # invalid dtype msg = "data type [\"']invalid[\"'] not understood" with pytest.raises(TypeError, match=msg): constructor(dtype="invalid", **filler) # no point in nesting periods in an IntervalIndex periods = period_range("2000-01-01", periods=10) periods_kwargs = self.get_kwargs_from_breaks(periods) msg = "Period dtypes are not supported, use a PeriodIndex instead" with pytest.raises(ValueError, match=msg): constructor(**periods_kwargs) # decreasing values decreasing_kwargs = self.get_kwargs_from_breaks(range(10, -1, -1)) msg = "left side of interval must be <= right side" with pytest.raises(ValueError, match=msg): constructor(**decreasing_kwargs) class TestFromArrays(Base): """Tests specific to IntervalIndex.from_arrays""" @pytest.fixture def constructor(self): return IntervalIndex.from_arrays def get_kwargs_from_breaks(self, breaks, closed="right"): """ converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by IntervalIndex.from_arrays """ return {"left": breaks[:-1], "right": breaks[1:]} def test_constructor_errors(self): # GH 19016: categorical data data = Categorical(list("01234abcde"), ordered=True) msg = ( "category, object, and string subtypes are not supported " "for IntervalIndex" ) with pytest.raises(TypeError, match=msg): IntervalIndex.from_arrays(data[:-1], data[1:]) # unequal length left = [0, 1, 2] right = [2, 3] msg = "left and right must have the same length" with pytest.raises(ValueError, match=msg): IntervalIndex.from_arrays(left, right) @pytest.mark.parametrize( "left_subtype, right_subtype", [(np.int64, np.float64), (np.float64, np.int64)] ) def test_mixed_float_int(self, left_subtype, right_subtype): """mixed int/float left/right results in float for both sides""" left = np.arange(9, dtype=left_subtype) right = np.arange(1, 10, dtype=right_subtype) result = IntervalIndex.from_arrays(left, right) expected_left = Float64Index(left) expected_right = Float64Index(right) expected_subtype = np.float64 tm.assert_index_equal(result.left, expected_left) tm.assert_index_equal(result.right, expected_right) assert result.dtype.subtype == expected_subtype class TestFromBreaks(Base): """Tests specific to IntervalIndex.from_breaks""" @pytest.fixture def constructor(self): return IntervalIndex.from_breaks def get_kwargs_from_breaks(self, breaks, closed="right"): """ converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by IntervalIndex.from_breaks """ return {"breaks": breaks} def test_constructor_errors(self): # GH 19016: categorical data data = Categorical(list("01234abcde"), ordered=True) msg = ( "category, object, and string subtypes are not supported " "for IntervalIndex" ) with pytest.raises(TypeError, match=msg): IntervalIndex.from_breaks(data) def test_length_one(self): """breaks of length one produce an empty IntervalIndex""" breaks = [0] result = IntervalIndex.from_breaks(breaks) expected = IntervalIndex.from_breaks([]) tm.assert_index_equal(result, expected) class TestFromTuples(Base): """Tests specific to IntervalIndex.from_tuples""" @pytest.fixture def constructor(self): return IntervalIndex.from_tuples def get_kwargs_from_breaks(self, breaks, closed="right"): """ converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by IntervalIndex.from_tuples """ if len(breaks) == 0: return {"data": breaks} tuples = list(zip(breaks[:-1], breaks[1:])) if isinstance(breaks, (list, tuple)): return {"data": tuples} elif is_categorical_dtype(breaks): return {"data": breaks._constructor(tuples)} return {"data": com.asarray_tuplesafe(tuples)} def test_constructor_errors(self): # non-tuple tuples = [(0, 1), 2, (3, 4)] msg = "IntervalIndex.from_tuples received an invalid item, 2" with pytest.raises(TypeError, match=msg.format(t=tuples)): IntervalIndex.from_tuples(tuples) # too few/many items tuples = [(0, 1), (2,), (3, 4)] msg = "IntervalIndex.from_tuples requires tuples of length 2, got {t}" with pytest.raises(ValueError, match=msg.format(t=tuples)): IntervalIndex.from_tuples(tuples) tuples = [(0, 1), (2, 3, 4), (5, 6)] with pytest.raises(ValueError, match=msg.format(t=tuples)): IntervalIndex.from_tuples(tuples) def test_na_tuples(self): # tuple (NA, NA) evaluates the same as NA as an element na_tuple = [(0, 1), (np.nan, np.nan), (2, 3)] idx_na_tuple = IntervalIndex.from_tuples(na_tuple) idx_na_element = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)]) tm.assert_index_equal(idx_na_tuple, idx_na_element) class TestClassConstructors(Base): """Tests specific to the IntervalIndex/Index constructors""" @pytest.fixture( params=[IntervalIndex, partial(Index, dtype="interval")], ids=["IntervalIndex", "Index"], ) def constructor(self, request): return request.param def get_kwargs_from_breaks(self, breaks, closed="right"): """ converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by the IntervalIndex/Index constructors """ if len(breaks) == 0: return {"data": breaks} ivs = [ Interval(l, r, closed) if notna(l) else l for l, r in zip(breaks[:-1], breaks[1:]) ] if isinstance(breaks, list): return {"data": ivs} elif is_categorical_dtype(breaks): return {"data": breaks._constructor(ivs)} return {"data": np.array(ivs, dtype=object)} def test_generic_errors(self, constructor): """ override the base class implementation since errors are handled differently; checks unnecessary since caught at the Interval level """ pass def test_constructor_string(self): # GH23013 # When forming the interval from breaks, # the interval of strings is already forbidden. pass def test_constructor_errors(self, constructor): # mismatched closed within intervals with no constructor override ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")] msg = "intervals must all be closed on the same side" with pytest.raises(ValueError, match=msg): constructor(ivs) # scalar msg = ( r"IntervalIndex\(...\) must be called with a collection of " "some kind, 5 was passed" ) with pytest.raises(TypeError, match=msg): constructor(5) # not an interval msg = "type <class 'numpy.int64'> with value 0 is not an interval" with pytest.raises(TypeError, match=msg): constructor([0, 1]) @pytest.mark.parametrize( "data, closed", [ ([], "both"), ([np.nan, np.nan], "neither"), ( [Interval(0, 3, closed="neither"), Interval(2, 5, closed="neither")], "left", ), ( [Interval(0, 3, closed="left"), Interval(2, 5, closed="right")], "neither", ), (IntervalIndex.from_breaks(range(5), closed="both"), "right"), ], ) def test_override_inferred_closed(self, constructor, data, closed): # GH 19370 if isinstance(data, IntervalIndex): tuples = data.to_tuples() else: tuples = [(iv.left, iv.right) if notna(iv) else iv for iv in data] expected = IntervalIndex.from_tuples(tuples, closed=closed) result = constructor(data, closed=closed) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "values_constructor", [list, np.array, IntervalIndex, IntervalArray] ) def test_index_object_dtype(self, values_constructor): # Index(intervals, dtype=object) is an Index (not an IntervalIndex) intervals = [Interval(0, 1), Interval(1, 2), Interval(2, 3)] values = values_constructor(intervals) result = Index(values, dtype=object) assert type(result) is Index tm.assert_numpy_array_equal(result.values, np.array(values)) def test_index_mixed_closed(self): # GH27172 intervals = [ Interval(0, 1, closed="left"), Interval(1, 2, closed="right"), Interval(2, 3, closed="neither"), Interval(3, 4, closed="both"), ] result = Index(intervals) expected = Index(intervals, dtype=object) tm.assert_index_equal(result, expected)
[ "44142880+GregVargas1999@users.noreply.github.com" ]
44142880+GregVargas1999@users.noreply.github.com
dffe57932f7e1c84cc32acf781fca7f7715216ff
84b05857cbe74d190bdbee18d442d0c720b1b84d
/Coderbyte_algorithms/Hard/OptimalAssignments/test_OptimalAssignments.py
c35bb39e583b90f4477373996093898a9f6f1e86
[]
no_license
JakubKazimierski/PythonPortfolio
1c8c7e7b0f1358fc42a2295b807d0afafd8e88a3
3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f
refs/heads/master
2023-06-01T01:16:22.897097
2023-05-15T01:05:22
2023-05-15T01:05:22
311,473,524
9
1
null
null
null
null
UTF-8
Python
false
false
657
py
''' Unittests for OptimalAssignments.py December 2020 Jakub Kazimierski ''' import unittest import OptimalAssignments class test_OptimalAssignments(unittest.TestCase): ''' Class with unittests for OptimalAssignments.py ''' # region Unittests def test_ExpectedOutput(self): ''' Checks if returned output is as expected. ''' output = OptimalAssignments.OptimalAssignments(["(5,4,2)","(12,4,3)","(3,4,13)"]) self.assertEqual(output, "(1-3)(2-2)(3-1)") # endregion if __name__ == "__main__": ''' Main method for test cases. ''' unittest.main()
[ "j.m.kazimierski@gmail.com" ]
j.m.kazimierski@gmail.com
961ada8bd15c4bbc33270ba8fdeae8e08efdfdff
15a739dc7f2f83d3b85d7b355a81d62a0c9386ad
/src/measure/07_calc_pale_para_time_cases.py
6cd253560e1a7f9adbf6de1082e92acbff671a52
[]
no_license
Allen517/half
4d232563cb85ec73b78c263b8e6df04549bcecac
18e6b5c2b69e1b90656328a6ae840fe7f7071398
refs/heads/master
2020-05-16T17:29:40.304766
2019-09-25T15:16:52
2019-09-25T15:16:52
183,195,625
2
0
null
null
null
null
UTF-8
Python
false
false
1,863
py
import sys,os import random import time import numpy as np from concurrent.futures import ThreadPoolExecutor from concurrent import futures def read_code(filename): code_map = dict() with open(filename, 'r') as fin: for ln in fin: elems = ln.strip().split('\t') if len(elems)<2: continue code_map[elems[0]]=np.array(map(float, elems[1].split(','))) return code_map # def match_num(src_code, target_code): # xor_res = int(src_code, 2)^int(target_code, 2) # one_cnt = 0 # while xor_res != 0: # s = xor_res%2 # if s==1: # one_cnt += 1 # xor_res /= 2 # return one_cnt def find_matched(code, target_code_map): match_res = set() min_dist = 1000 min_key = '' for target_key, target_code in target_code_map.iteritems(): dist = geo_distance(code, target_code) if dist<=min_dist: min_dist = dist min_key = target_key return min_dist, target_key def geo_distance(vec1, vec2): return .5*np.sum((vec1-vec2)**2) def main_proc(num): print num for i in range(num): douban_keys = douban_code_map.keys() d_key = douban_keys[random.randint(0,len(douban_keys)-1)] target_key, target_dist = find_matched(douban_code_map[d_key], weibo_code_map) print '{},{}:{}'.format(d_key, target_key,target_dist) if __name__=='__main__': douban_code_map = read_code('dhl-alp.case.model.code.pale.f') weibo_code_map = read_code('dhl-alp.case.model.code.pale.g') overall = 100 worker = 8 t1 = time.time() with ThreadPoolExecutor(max_workers=worker) as executor: future_to_proc = {executor.submit(main_proc, num) :overall/worker if num+overall/worker<overall else overall-num for num in range(int(overall/worker))} for future in futures.as_completed(future_to_proc): print 'Finish processing %d'%(future_to_proc[future]) if future.exception() is not None: print future.exception() t2 = time.time() print t2-t1
[ "wangyongqing.casia@gmail.com" ]
wangyongqing.casia@gmail.com
6973d3f90df8ecd1028285b111baa55b7a9d0f6b
2e3e064ec2388f7a57428c32b77207280a0a9be1
/Sect-A/source/sect04_control/s443.py
496623c5b1ff4cc2b7b813f48f232d8d1636308f
[]
no_license
bigpycraft/sba19-seoulit
1857a399d8f23c4fb8f98448139be8eb968d35ee
2cf11a1ce9a04043911006531470a3e523cbf5f0
refs/heads/master
2020-07-02T22:48:52.681018
2019-09-19T03:08:59
2019-09-19T03:08:59
201,693,283
5
7
null
null
null
null
UTF-8
Python
false
false
247
py
#pass 문 예시 signals = 'blue', 'yellow', 'red' for x in range(len(signals)): print(x, signals[x], '루프 시작!') if signals[x] == 'yellow': pass print(x, signals[x], '루프 종료!!') print('프로그램 종료!!!')
[ "bluenine52@gmail.com" ]
bluenine52@gmail.com
f2531dc8aa8f27aa3b6227b4feb0a00c64c8816d
52b5773617a1b972a905de4d692540d26ff74926
/.history/sets_20200609191039.py
8317547fb031c680266d7b47826445c4e751bb94
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
944
py
import json def Strings(str): # values = {} newArray = [] keys = [] for i in str: newArray.append(i.split(":")) for j in range(0,len(newArray)): if newArray[j][0] in values: # if newArray[j][0] in values: # values[newArray[j][0]] += int(newArray[j][1]) # else: # values[newArray[j][0]] = int(newArray[j][1]) # for k in values: # keys.append(k) # keys = sorted(keys) # newString = "" # last =len(keys)-1 # lastString = "" # lastString +=keys[last] + ":" + json.dumps(values[keys[last]]) # for i in range(len(keys)-1): # if keys[i] in values: # newString += keys[i] + ":"+ json.dumps(values[keys[i]])+"," # finalString = newString + lastString # print(type(finalString)) Strings(["Z:1","B:3","C:3","Z:4","B:2"]) # "B:5,C:3,Z:5"
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
4dccf5e24c984abaa126f1ab46d14c24b4630c86
df19b2ff22f0b27685cdc72d0d50b6b9dfe3fa5a
/cpuApp/urls.py
0045b3558ce4f2b345a1a63fe6076491e4e97993
[]
no_license
fadiarmoush/LinuxProject
7ca01efe06f87bb13a0232327aa1a7d9d1c4bc0b
4a7a5330e3b2af97fc8bc58e3483fda6d3cee42f
refs/heads/master
2020-06-18T06:32:39.077572
2019-07-10T12:02:37
2019-07-10T12:02:37
196,196,032
0
0
null
null
null
null
UTF-8
Python
false
false
422
py
from django.urls import path from django.conf.urls import url from .views import ListSongsView from .views import ListSongsView2 from .views import ListSongsView3 from . import views from .views import currentsView urlpatterns = [ path('cpu/', ListSongsView.as_view()), path('mem/', ListSongsView2.as_view()), path('disk/', ListSongsView3.as_view()), url(r'currents', currentsView.as_view()), ]
[ "root@localhost.localdomain" ]
root@localhost.localdomain
612d082ff2748077733b448aaf1e9799d9054579
3784495ba55d26e22302a803861c4ba197fd82c7
/venv/lib/python3.6/site-packages/networkx/algorithms/bipartite/projection.py
69c5f6bdad0581bb876f69fb33b51542531887e3
[ "MIT" ]
permissive
databill86/HyperFoods
cf7c31f5a6eb5c0d0ddb250fd045ca68eb5e0789
9267937c8c70fd84017c0f153c241d2686a356dd
refs/heads/master
2021-01-06T17:08:48.736498
2020-02-11T05:02:18
2020-02-11T05:02:18
241,407,659
3
0
MIT
2020-02-18T16:15:48
2020-02-18T16:15:47
null
UTF-8
Python
false
false
16,800
py
# -*- coding: utf-8 -*- # Copyright (C) 2017-2019 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. # # Authors: Aric Hagberg <aric.hagberg@gmail.com> # Jordi Torrents <jtorrents@milnou.net> """One-mode (unipartite) projections of bipartite graphs.""" import networkx as nx from networkx.utils import not_implemented_for __all__ = ['project', 'projected_graph', 'weighted_projected_graph', 'collaboration_weighted_projected_graph', 'overlap_weighted_projected_graph', 'generic_weighted_projected_graph'] def projected_graph(B, nodes, multigraph=False): r"""Returns the projection of B onto one of its node sets. Returns the graph G that is the projection of the bipartite graph B onto the specified nodes. They retain their attributes and are connected in G if they have a common neighbor in B. Parameters ---------- B : NetworkX graph The input graph should be bipartite. nodes : list or iterable Nodes to project onto (the "bottom" nodes). multigraph: bool (default=False) If True return a multigraph where the multiple edges represent multiple shared neighbors. They edge key in the multigraph is assigned to the label of the neighbor. Returns ------- Graph : NetworkX graph or multigraph A graph that is the projection onto the given nodes. Examples -------- >>> from networkx.algorithms import bipartite >>> B = nx.path_graph(4) >>> G = bipartite.projected_graph(B, [1, 3]) >>> list(G) [1, 3] >>> list(G.edges()) [(1, 3)] If nodes `a`, and `b` are connected through both nodes 1 and 2 then building a multigraph results in two edges in the projection onto [`a`, `b`]: >>> B = nx.Graph() >>> B.add_edges_from([('a', 1), ('b', 1), ('a', 2), ('b', 2)]) >>> G = bipartite.projected_graph(B, ['a', 'b'], multigraph=True) >>> print([sorted((u, v)) for u, v in G.edges()]) [['a', 'b'], ['a', 'b']] Notes ----- No attempt is made to verify that the input graph B is bipartite. Returns a simple graph that is the projection of the bipartite graph B onto the set of nodes given in list nodes. If multigraph=True then a multigraph is returned with an edge for every shared neighbor. Directed graphs are allowed as input. The output will also then be a directed graph with edges if there is a directed path between the nodes. The graph and node properties are (shallow) copied to the projected graph. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- is_bipartite, is_bipartite_node_set, sets, weighted_projected_graph, collaboration_weighted_projected_graph, overlap_weighted_projected_graph, generic_weighted_projected_graph """ if B.is_multigraph(): raise nx.NetworkXError("not defined for multigraphs") if B.is_directed(): directed = True if multigraph: G = nx.MultiDiGraph() else: G = nx.DiGraph() else: directed = False if multigraph: G = nx.MultiGraph() else: G = nx.Graph() G.graph.update(B.graph) G.add_nodes_from((n, B.nodes[n]) for n in nodes) for u in nodes: nbrs2 = set(v for nbr in B[u] for v in B[nbr] if v != u) if multigraph: for n in nbrs2: if directed: links = set(B[u]) & set(B.pred[n]) else: links = set(B[u]) & set(B[n]) for l in links: if not G.has_edge(u, n, l): G.add_edge(u, n, key=l) else: G.add_edges_from((u, n) for n in nbrs2) return G @not_implemented_for('multigraph') def weighted_projected_graph(B, nodes, ratio=False): r"""Returns a weighted projection of B onto one of its node sets. The weighted projected graph is the projection of the bipartite network B onto the specified nodes with weights representing the number of shared neighbors or the ratio between actual shared neighbors and possible shared neighbors if ``ratio is True`` [1]_. The nodes retain their attributes and are connected in the resulting graph if they have an edge to a common node in the original graph. Parameters ---------- B : NetworkX graph The input graph should be bipartite. nodes : list or iterable Nodes to project onto (the "bottom" nodes). ratio: Bool (default=False) If True, edge weight is the ratio between actual shared neighbors and maximum possible shared neighbors (i.e., the size of the other node set). If False, edges weight is the number of shared neighbors. Returns ------- Graph : NetworkX graph A graph that is the projection onto the given nodes. Examples -------- >>> from networkx.algorithms import bipartite >>> B = nx.path_graph(4) >>> G = bipartite.weighted_projected_graph(B, [1, 3]) >>> list(G) [1, 3] >>> list(G.edges(data=True)) [(1, 3, {'weight': 1})] >>> G = bipartite.weighted_projected_graph(B, [1, 3], ratio=True) >>> list(G.edges(data=True)) [(1, 3, {'weight': 0.5})] Notes ----- No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow) copied to the projected graph. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- is_bipartite, is_bipartite_node_set, sets, collaboration_weighted_projected_graph, overlap_weighted_projected_graph, generic_weighted_projected_graph projected_graph References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. """ if B.is_directed(): pred = B.pred G = nx.DiGraph() else: pred = B.adj G = nx.Graph() G.graph.update(B.graph) G.add_nodes_from((n, B.nodes[n]) for n in nodes) n_top = float(len(B) - len(nodes)) for u in nodes: unbrs = set(B[u]) nbrs2 = set((n for nbr in unbrs for n in B[nbr])) - set([u]) for v in nbrs2: vnbrs = set(pred[v]) common = unbrs & vnbrs if not ratio: weight = len(common) else: weight = len(common) / n_top G.add_edge(u, v, weight=weight) return G @not_implemented_for('multigraph') def collaboration_weighted_projected_graph(B, nodes): r"""Newman's weighted projection of B onto one of its node sets. The collaboration weighted projection is the projection of the bipartite network B onto the specified nodes with weights assigned using Newman's collaboration model [1]_: .. math:: w_{u, v} = \sum_k \frac{\delta_{u}^{k} \delta_{v}^{k}}{d_k - 1} where `u` and `v` are nodes from the bottom bipartite node set, and `k` is a node of the top node set. The value `d_k` is the degree of node `k` in the bipartite network and `\delta_{u}^{k}` is 1 if node `u` is linked to node `k` in the original bipartite graph or 0 otherwise. The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in the original bipartite graph. Parameters ---------- B : NetworkX graph The input graph should be bipartite. nodes : list or iterable Nodes to project onto (the "bottom" nodes). Returns ------- Graph : NetworkX graph A graph that is the projection onto the given nodes. Examples -------- >>> from networkx.algorithms import bipartite >>> B = nx.path_graph(5) >>> B.add_edge(1, 5) >>> G = bipartite.collaboration_weighted_projected_graph(B, [0, 2, 4, 5]) >>> list(G) [0, 2, 4, 5] >>> for edge in sorted(G.edges(data=True)): print(edge) ... (0, 2, {'weight': 0.5}) (0, 5, {'weight': 0.5}) (2, 4, {'weight': 1.0}) (2, 5, {'weight': 0.5}) Notes ----- No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow) copied to the projected graph. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- is_bipartite, is_bipartite_node_set, sets, weighted_projected_graph, overlap_weighted_projected_graph, generic_weighted_projected_graph, projected_graph References ---------- .. [1] Scientific collaboration networks: II. Shortest paths, weighted networks, and centrality, M. E. J. Newman, Phys. Rev. E 64, 016132 (2001). """ if B.is_directed(): pred = B.pred G = nx.DiGraph() else: pred = B.adj G = nx.Graph() G.graph.update(B.graph) G.add_nodes_from((n, B.nodes[n]) for n in nodes) for u in nodes: unbrs = set(B[u]) nbrs2 = set(n for nbr in unbrs for n in B[nbr] if n != u) for v in nbrs2: vnbrs = set(pred[v]) common_degree = (len(B[n]) for n in unbrs & vnbrs) weight = sum(1.0 / (deg - 1) for deg in common_degree if deg > 1) G.add_edge(u, v, weight=weight) return G @not_implemented_for('multigraph') def overlap_weighted_projected_graph(B, nodes, jaccard=True): r"""Overlap weighted projection of B onto one of its node sets. The overlap weighted projection is the projection of the bipartite network B onto the specified nodes with weights representing the Jaccard index between the neighborhoods of the two nodes in the original bipartite network [1]_: .. math:: w_{v, u} = \frac{|N(u) \cap N(v)|}{|N(u) \cup N(v)|} or if the parameter 'jaccard' is False, the fraction of common neighbors by minimum of both nodes degree in the original bipartite graph [1]_: .. math:: w_{v, u} = \frac{|N(u) \cap N(v)|}{min(|N(u)|, |N(v)|)} The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in the original bipartite graph. Parameters ---------- B : NetworkX graph The input graph should be bipartite. nodes : list or iterable Nodes to project onto (the "bottom" nodes). jaccard: Bool (default=True) Returns ------- Graph : NetworkX graph A graph that is the projection onto the given nodes. Examples -------- >>> from networkx.algorithms import bipartite >>> B = nx.path_graph(5) >>> nodes = [0, 2, 4] >>> G = bipartite.overlap_weighted_projected_graph(B, nodes) >>> list(G) [0, 2, 4] >>> list(G.edges(data=True)) [(0, 2, {'weight': 0.5}), (2, 4, {'weight': 0.5})] >>> G = bipartite.overlap_weighted_projected_graph(B, nodes, jaccard=False) >>> list(G.edges(data=True)) [(0, 2, {'weight': 1.0}), (2, 4, {'weight': 1.0})] Notes ----- No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow) copied to the projected graph. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- is_bipartite, is_bipartite_node_set, sets, weighted_projected_graph, collaboration_weighted_projected_graph, generic_weighted_projected_graph, projected_graph References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. """ if B.is_directed(): pred = B.pred G = nx.DiGraph() else: pred = B.adj G = nx.Graph() G.graph.update(B.graph) G.add_nodes_from((n, B.nodes[n]) for n in nodes) for u in nodes: unbrs = set(B[u]) nbrs2 = set((n for nbr in unbrs for n in B[nbr])) - set([u]) for v in nbrs2: vnbrs = set(pred[v]) if jaccard: wt = float(len(unbrs & vnbrs)) / len(unbrs | vnbrs) else: wt = float(len(unbrs & vnbrs)) / min(len(unbrs), len(vnbrs)) G.add_edge(u, v, weight=wt) return G @not_implemented_for('multigraph') def generic_weighted_projected_graph(B, nodes, weight_function=None): r"""Weighted projection of B with a user-specified weight function. The bipartite network B is projected on to the specified nodes with weights computed by a user-specified function. This function must accept as a parameter the neighborhood sets of two nodes and return an integer or a float. The nodes retain their attributes and are connected in the resulting graph if they have an edge to a common node in the original graph. Parameters ---------- B : NetworkX graph The input graph should be bipartite. nodes : list or iterable Nodes to project onto (the "bottom" nodes). weight_function : function This function must accept as parameters the same input graph that this function, and two nodes; and return an integer or a float. The default function computes the number of shared neighbors. Returns ------- Graph : NetworkX graph A graph that is the projection onto the given nodes. Examples -------- >>> from networkx.algorithms import bipartite >>> # Define some custom weight functions >>> def jaccard(G, u, v): ... unbrs = set(G[u]) ... vnbrs = set(G[v]) ... return float(len(unbrs & vnbrs)) / len(unbrs | vnbrs) ... >>> def my_weight(G, u, v, weight='weight'): ... w = 0 ... for nbr in set(G[u]) & set(G[v]): ... w += G[u][nbr].get(weight, 1) + G[v][nbr].get(weight, 1) ... return w ... >>> # A complete bipartite graph with 4 nodes and 4 edges >>> B = nx.complete_bipartite_graph(2, 2) >>> # Add some arbitrary weight to the edges >>> for i,(u,v) in enumerate(B.edges()): ... B.edges[u, v]['weight'] = i + 1 ... >>> for edge in B.edges(data=True): ... print(edge) ... (0, 2, {'weight': 1}) (0, 3, {'weight': 2}) (1, 2, {'weight': 3}) (1, 3, {'weight': 4}) >>> # By default, the weight is the number of shared neighbors >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1]) >>> print(list(G.edges(data=True))) [(0, 1, {'weight': 2})] >>> # To specify a custom weight function use the weight_function parameter >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=jaccard) >>> print(list(G.edges(data=True))) [(0, 1, {'weight': 1.0})] >>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=my_weight) >>> print(list(G.edges(data=True))) [(0, 1, {'weight': 10})] Notes ----- No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow) copied to the projected graph. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- is_bipartite, is_bipartite_node_set, sets, weighted_projected_graph, collaboration_weighted_projected_graph, overlap_weighted_projected_graph, projected_graph """ if B.is_directed(): pred = B.pred G = nx.DiGraph() else: pred = B.adj G = nx.Graph() if weight_function is None: def weight_function(G, u, v): # Notice that we use set(pred[v]) for handling the directed case. return len(set(G[u]) & set(pred[v])) G.graph.update(B.graph) G.add_nodes_from((n, B.nodes[n]) for n in nodes) for u in nodes: nbrs2 = set((n for nbr in set(B[u]) for n in B[nbr])) - set([u]) for v in nbrs2: weight = weight_function(B, u, v) G.add_edge(u, v, weight=weight) return G def project(B, nodes, create_using=None): return projected_graph(B, nodes)
[ "luis20dr@gmail.com" ]
luis20dr@gmail.com
ec07f0da2e432113a1bac9c65ed9483a3c4b4cab
d3e31f6b8da5c1a7310b543bbf2adc76091b5571
/Day26/mini_prj1/app.py
ff17127e9abd7fbf909d7cb7e72a85916cbb5fa1
[]
no_license
pytutorial/py2103
224a5a7133dbe03fc4f798408694bf664be10613
adbd9eb5a32eb1d28b747dcfbe90ab8a3470e5de
refs/heads/main
2023-07-14T06:31:18.918778
2021-08-12T14:29:16
2021-08-12T14:29:16
355,163,185
1
0
null
null
null
null
UTF-8
Python
false
false
1,794
py
from pymongo import MongoClient from bson.objectid import ObjectId db_host = '34.70.69.231' db_user = 'mongo' db_pass = 'abc@123' client = MongoClient(db_host, username=db_user, password=db_pass) db = client.db0001 import time from flask import Flask, request, render_template, redirect, jsonify app = Flask(__name__) @app.route('/update-product/<pid>', methods=['GET', 'POST']) def updateProduct(pid): if request.method == 'GET': product = db.product.find_one({'_id': ObjectId(pid)}) return render_template('form.html', product=product) else: #TODO: Update DB return redirect('/') @app.route('/create-product', methods=['GET', 'POST']) def createProduct(): if request.method == 'GET': return render_template('form.html', product={}) else: fields = ['code', 'name', 'price', 'qty', 'description'] product = {f : request.form[f] for f in fields} product['price'] = int(product['price'] or 0) product['qty'] = int(product['qty'] or 0) file = request.files.get('image') if file is not None and file.filename != '': filepath = f'/static/images/{str(time.time())}.jpg' file.save(app.root_path + filepath) product['image'] = filepath db.product.insert(product) return redirect('/') @app.route('/delete-product/<pid>', methods=['DELETE']) def deleteProduct(pid): db.product.remove({'_id': ObjectId(pid)}) return jsonify({'success': True}) @app.route('/') def index(): keyword = request.args.get('keyword', '') productList = list(db.product.find({ 'name': {'$regex': keyword, '$options': 'i'} })) return render_template('index.html', productList=productList, keyword=keyword) app.run(debug=True)
[ "duongthanhtungvn01@gmail.com" ]
duongthanhtungvn01@gmail.com
f0d78e0407e9b493b7e09a592fbe281f65786de9
fe47a536f3938a8f0bf0e52fa6e3284d1b35e356
/backend/users/migrations/0002_auto_20200614_2037.py
5976489efb44e03f267c41dda3aa73207d6f4113
[]
no_license
crowdbotics-apps/i-do-weddings-18101
2d0e473b2b0f312c049c07c6e28d53c6c506ebea
aabc1b4d442378a32643365ce8a0eac30d2836b1
refs/heads/master
2022-10-17T02:13:55.759254
2020-06-14T20:38:14
2020-06-14T20:38:14
272,279,169
0
0
null
null
null
null
UTF-8
Python
false
false
569
py
# Generated by Django 2.2.13 on 2020-06-14 20:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='email', field=models.EmailField(blank=True, max_length=254, null=True), ), migrations.AlterField( model_name='user', name='name', field=models.CharField(blank=True, max_length=255, null=True), ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
957b3ad7e784e2bb7d619623c8109f9100e498a2
64d1211404c89da4e09d77d859f2cdf6609a057e
/models/official/nlp/configs/bert.py
47c0b26e436a76c0b31492d5397149af5ab66172
[ "Apache-2.0" ]
permissive
Nerfertili/Deep_learning_learning_udemy
f375209e0675ab8f4da9551d8a5bdee4f2948ed8
0fe6c1f36019b29151acb17a1f248b34d6089aeb
refs/heads/master
2023-02-17T10:10:52.536426
2021-01-19T02:48:23
2021-01-19T02:48:23
330,823,730
0
1
null
null
null
null
UTF-8
Python
false
false
1,566
py
# Lint as: python3 # Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Multi-head BERT encoder network with classification heads. Includes configurations and instantiation methods. """ from typing import List, Optional, Text import dataclasses from official.modeling.hyperparams import base_config from official.nlp.configs import encoders @dataclasses.dataclass class ClsHeadConfig(base_config.Config): inner_dim: int = 0 num_classes: int = 2 activation: Optional[Text] = "tanh" dropout_rate: float = 0.0 cls_token_idx: int = 0 name: Optional[Text] = None @dataclasses.dataclass class PretrainerConfig(base_config.Config): """Pretrainer configuration.""" encoder: encoders.EncoderConfig = encoders.EncoderConfig() cls_heads: List[ClsHeadConfig] = dataclasses.field(default_factory=list) mlm_activation: str = "gelu" mlm_initializer_range: float = 0.02
[ "leal.afonso@outlook.com" ]
leal.afonso@outlook.com
8275002ef69810e28d7fee9ec873749fced30050
08f61d5432b6cf14bb6fc3448259a6c445b26780
/dapodik/sekolah/base.py
4da825ffab37d6c94b7bad8cb9f88d0073438da1
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
nainaidaa/dapodik
9ecfabc6f262c24a4cd0288b3b1a7116b3a09199
d89c0fb899c89e866527f6b7b57f741abd6444ea
refs/heads/master
2023-07-22T23:37:16.694675
2021-09-08T15:04:23
2021-09-08T15:04:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,687
py
from dapodik.base import BaseDapodik from typing import List from . import AkreditasiSp from . import BlockGrant from . import JurusanSp from . import Kepanitiaan from . import ProgramInklusi from . import Sanitasi from . import SekolahLongitudinal from . import SekolahPaud from . import Sekolah from . import Semester from . import Yayasan class BaseSekolah(BaseDapodik): def akreditasi_sp(self) -> List[AkreditasiSp]: return self._get_rows("/rest/AkreditasiSp", List[AkreditasiSp]) def blockgrant(self) -> List[BlockGrant]: return self._get_rows("/rest/BlockGrant", List[BlockGrant]) def jurusan_sp(self) -> List[JurusanSp]: return self._get_rows("/rest/JurusanSp", List[JurusanSp]) def kepanitiaan(self) -> List[Kepanitiaan]: return self._get_rows("/rest/Kepanitiaan", List[Kepanitiaan]) def program_inklusi(self) -> List[ProgramInklusi]: return self._get_rows("/rest/ProgramInklusi", List[ProgramInklusi]) def sanitasi(self) -> List[Sanitasi]: return self._get_rows("/rest/Sanitasi", List[Sanitasi]) def sekolah_longitudinal(self) -> List[SekolahLongitudinal]: return self._get_rows("/rest/SekolahLongitudinal", List[SekolahLongitudinal]) def sekolah_paud(self) -> List[SekolahPaud]: return self._get_rows("/rest/SekolahPaud", List[SekolahPaud]) def sekolah(self, index: int = 0) -> Sekolah: return self._get_rows("/rest/Sekolah", List[Sekolah])[index] def semester(self) -> List[Semester]: return self._get_rows("/rest/Semester", List[Semester]) def yayasan(self) -> List[Yayasan]: return self._get_rows("/rest/Yayasan", List[Yayasan])
[ "revolusi147id@gmail.com" ]
revolusi147id@gmail.com
1de781d634fab52bcefa1bc7e3d2b231a9ea18d3
7013527a33a756c0f08a0672515e2c20df58faca
/clean_stripes.py
9b47390310d9b6bf5de62b3688848299b2e63441
[]
no_license
tukiains/stripe-filter-test
b1b88c9129f714c0e3cb47c6f62567a3b7eaec5a
069d8a480628c9b1ae79de648ceddeeb264a6bcc
refs/heads/main
2023-06-01T21:21:28.537687
2021-06-15T08:37:09
2021-06-15T08:37:09
369,167,886
0
0
null
null
null
null
UTF-8
Python
false
false
1,872
py
import os.path import requests from cloudnetpy.categorize import generate_categorize from cloudnetpy.plotting import generate_figure test_cases = { 'munich': ('2021-05-16', '2021-05-05', '2021-05-08'), 'hyytiala': ('2021-05-09', '2021-05-10'), 'palaiseau': ('2021-03-05', ), 'granada': ('2021-05-11', '2021-05-07'), 'norunda': ('2021-03-05', ), 'bucharest': ('2021-03-05', ) } def _download(site: str, date: str, product: str = None) -> str: payload = {'site': site, 'date': date} if product is not None: payload['product'] = product url = 'https://cloudnet.fmi.fi/api/files' else: url = 'https://cloudnet.fmi.fi/api/model-files' metadata = requests.get(url, payload).json() if not metadata: raise RuntimeError metadata = metadata[0] filename = metadata['filename'] if not os.path.isfile(filename): print(f"downloading {filename} ...") res = requests.get(metadata['downloadUrl']) with open(filename, 'wb') as f: f.write(res.content) return filename def main(): for site, dates in test_cases.items(): input_files = {} for date in dates: input_files['model'] = _download(site, date) for file_type in ('radar', 'lidar'): input_files[file_type] = _download(site, date, file_type) try: input_files['mwr'] = _download(site, date, 'mwr') except RuntimeError: input_files['mwr'] = _download(site, date, 'radar') generate_categorize(input_files, 'categorize.nc') generate_figure('categorize.nc', ['ldr', 'Z', 'v', 'v_sigma'], show=False, image_name=f'images/{date}_{site}_filtered') if __name__ == "__main__": main()
[ "simo.tukiainen@fmi.fi" ]
simo.tukiainen@fmi.fi
d099475d44c7f9479ce738eb7e71bd3820b37e50
8eab8ab725c2132bb8d090cdb2d23a5f71945249
/virt/Lib/site-packages/openpyxl/chart/print_settings.py
6a8fc2fab6ce1792aa3048c69834f29af9bb563d
[ "MIT" ]
permissive
JoaoSevergnini/metalpy
6c88a413a82bc25edd9308b8490a76fae8dd76ca
c2d0098a309b6ce8c756ff840bfb53fb291747b6
refs/heads/main
2023-04-18T17:25:26.474485
2022-09-18T20:44:45
2022-09-18T20:44:45
474,773,752
3
1
MIT
2022-11-03T20:07:50
2022-03-27T22:21:01
Python
UTF-8
Python
false
false
1,454
py
# Copyright (c) 2010-2022 openpyxl from openpyxl.descriptors.serialisable import Serialisable from openpyxl.descriptors import ( Float, Typed, Alias, ) from openpyxl.worksheet.page import PrintPageSetup from openpyxl.worksheet.header_footer import HeaderFooter class PageMargins(Serialisable): """ Identical to openpyxl.worksheet.page.Pagemargins but element names are different :-/ """ tagname = "pageMargins" l = Float() left = Alias('l') r = Float() right = Alias('r') t = Float() top = Alias('t') b = Float() bottom = Alias('b') header = Float() footer = Float() def __init__(self, l=0.75, r=0.75, t=1, b=1, header=0.5, footer=0.5): self.l = l self.r = r self.t = t self.b = b self.header = header self.footer = footer class PrintSettings(Serialisable): tagname = "printSettings" headerFooter = Typed(expected_type=HeaderFooter, allow_none=True) pageMargins = Typed(expected_type=PageMargins, allow_none=True) pageSetup = Typed(expected_type=PrintPageSetup, allow_none=True) __elements__ = ("headerFooter", "pageMargins", "pageMargins") def __init__(self, headerFooter=None, pageMargins=None, pageSetup=None, ): self.headerFooter = headerFooter self.pageMargins = pageMargins self.pageSetup = pageSetup
[ "joao.a.severgnini@gmail.com" ]
joao.a.severgnini@gmail.com
5656a471d8a4d6fc40c39d07f5d22a52839f396b
65cc1193afeced475cec02184dbc8043738a5a2e
/src/uvc/content/__init__.py
125e0485fdbeb4068503d8f46244109a20d10daa
[]
no_license
novareto/uvc.content
e39b088b5d98b83f0e8836adc9c2188cbe501d50
dc1b28f8f755dee26eb7721ecb2651761db03c16
refs/heads/master
2021-01-21T10:13:18.943078
2014-10-02T16:17:43
2014-10-02T16:17:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
177
py
# -*- coding: utf-8 -*- from .interfaces import IContent, IDescriptiveSchema from .directives import schema, Fields from .utils import bootstrap_component, schematic_bootstrap
[ "trollfot@gmail.com" ]
trollfot@gmail.com
1f09508e58003a0f4fdffde95018f92964965c1a
fee4adc0f8a74801d728f1e3f1278110622a74be
/app/auth/views.py
33d7919d5c4c4f1fcf292985b741777a515ef57c
[]
no_license
HuuBaa/todolist
02957fef9c8690eaadf1f9e49f9505ae69c4c614
eef38a3e1aa26f0ff8f9112c34587b46e6752e8a
refs/heads/master
2021-09-13T03:19:17.414242
2018-04-24T13:15:04
2018-04-24T13:15:04
107,774,043
0
0
null
null
null
null
UTF-8
Python
false
false
1,978
py
#!/usr/bin/env python #-*- coding: utf-8 -*- from . import auth from ..models import User from flask import request,redirect,url_for,render_template,flash from flask_login import login_user,login_required,logout_user,current_user from .forms import RegisterForm,CPasswdForm from app import db @auth.route('/login',methods=['POST','GET']) def login(): if request.method=='POST': email=request.form.get('email') password=request.form.get('password') user=User.query.filter_by(user_email=email).first() if user is not None and user.verify_password(password): login_user(user,True) flash('登录成功!') return redirect(url_for('todo.mytasks')) else: flash('账号、密码错误!') return redirect(url_for('auth.login')) return render_template('auth/login.html') @auth.route('/register',methods=['POST','GET']) def register(): form=RegisterForm() if form.validate_on_submit(): user = User(user_email=form.email.data, user_name=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() flash('注册成功') return redirect(url_for('auth.login')) return render_template('auth/register.html',form=form) @login_required @auth.route('/logout') def logout(): logout_user() return redirect(url_for('todo.index')) @auth.route('/cpasswd',methods=['POST','GET']) @login_required def cpasswd(): form=CPasswdForm() if form.validate_on_submit(): if current_user.verify_password(form.oldpasswd.data): current_user.password=form.newpasswd.data db.session.add(current_user) db.session.commit() logout_user() flash('修改密码成功,请重新登录') return redirect(url_for('auth.login')) else: flash('旧密码错误') return render_template('auth/cpasswd.html',form=form)
[ "742790905@qq.com" ]
742790905@qq.com
633db023bda8914aa62fcc73e17d56ffcf002b45
107e62a03254c9ebe2e1830977a47861633b0d33
/TCPserver.py
7ca995beb699d6e30bf8c95905f51a341c16e072
[]
no_license
prasanna-ranganathan/mypython
bb798c0782cfb79a27b0730e924921b802da2a44
25fa93602e2465ec6ccb0c3ff30a2bbf90da96e4
refs/heads/master
2021-06-03T18:35:31.129399
2016-08-28T14:21:44
2016-08-28T14:22:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
186
py
#!/usr/bin/env python import SocketServer class EchoHandler(SocketServer serverAddr = ("0.0.0.0",90000) server = SocketServer.TCPServer(serverAddr,EchoHandler) server.serve_forver()
[ "prassanna.mit@gmail.com" ]
prassanna.mit@gmail.com
92d84d5e4a383d5e858345bc045ba5c2c7d536d2
353def93fa77384ee3a5e3de98cfed318c480634
/.history/week01/homework02/maoyanspiders/maoyanspiders/pipelines_20200628013036.py
0eefa73f2f51dc3dddf0fec4bc0d05238f5652f1
[]
no_license
ydbB/Python001-class01
d680abc3ea1ccaeb610751e3488421417d381156
ad80037ccfc68d39125fa94d2747ab7394ac1be8
refs/heads/master
2022-11-25T11:27:45.077139
2020-07-19T12:35:12
2020-07-19T12:35:12
272,783,233
0
0
null
2020-06-16T18:28:15
2020-06-16T18:28:15
null
UTF-8
Python
false
false
672
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html class MaoyanspidersPipeline(object): def process_item(self, item, spider): films_name = item['films_name'] films_type = item['films_type'] release_time = item['release_time'] output = f'|{films_name}|\t|{films_type}|\t|{release_time}|\n\n' with open('D:\py\Python001-class01\week01\homework02\top10.csvtop10.csv', 'a+', encoding='utf-8') as article: article.write(output) article.close() return item
[ "31039587+ydbB@users.noreply.github.com" ]
31039587+ydbB@users.noreply.github.com
e84fbbd512417f983e287bc02ddae6f48acc8762
b55a8edf12b5298c63966de429b61e97c61c9d46
/src/generate_random_matrix.py
19a2a2d4e0ccd7c26dfa385d092676a51f9b0e5e
[]
no_license
tmoldwin/DBasisHDA
c9bb5ba9d90e2526de5c0a78fe3d6cf34031a2d7
00063da2c27fa12470aa54d9d0321f95e350de8a
refs/heads/master
2020-05-30T09:54:01.754277
2013-08-30T07:58:05
2013-08-30T07:58:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
867
py
#!/usr/bin/env python # """ Author: Ulrich Norbisrath This creates on stdout a matrix which can be fed to DBasisHDA """ import random import sys import getopt __doc__ = """call: generate_random_matrix height width number_of_ones""" def main(): # parse command line options options = sys.argv[1:] if len(options) != 3: print __doc__ sys.exit(0) height = int(sys.argv[1]) width = int(sys.argv[2]) ones = int(sys.argv[3]) dimension = height*width assert ones<=dimension, "Too many ones requested. Dimension is smaller." mysequence = ["1"]*ones +["0"]*(dimension-ones) random.shuffle(mysequence) # write output print height print width for line in range(height): print " ".join(mysequence[line*width:(line+1)*width]) if __name__ == "__main__": main()
[ "devel@mail.ulno.net" ]
devel@mail.ulno.net
57a08ee5a66c378652a86660e6234944f498cc65
661b08d621852b79d06710015ab0b165c7d65007
/base/site-packages/PIL/Image.py
8ab3c3e84c221bb802c40ce142b6a44636e76c17
[ "Apache-2.0" ]
permissive
B-ROY/TESTGIT
cd45365f6c3eaff8d12bd2ab48cd455dc16ba7c8
40221cf254c90d37d21afb981635740aebf11949
refs/heads/master
2021-07-13T12:42:28.022035
2017-10-14T09:37:14
2017-10-14T09:37:14
106,913,556
2
0
null
null
null
null
UTF-8
Python
false
false
67,237
py
# # The Python Imaging Library. # $Id$ # # the Image class wrapper # # partial release history: # 1995-09-09 fl Created # 1996-03-11 fl PIL release 0.0 (proof of concept) # 1996-04-30 fl PIL release 0.1b1 # 1999-07-28 fl PIL release 1.0 final # 2000-06-07 fl PIL release 1.1 # 2000-10-20 fl PIL release 1.1.1 # 2001-05-07 fl PIL release 1.1.2 # 2002-03-15 fl PIL release 1.1.3 # 2003-05-10 fl PIL release 1.1.4 # 2005-03-28 fl PIL release 1.1.5 # 2006-12-02 fl PIL release 1.1.6 # 2009-11-15 fl PIL release 1.1.7 # # Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved. # Copyright (c) 1995-2009 by Fredrik Lundh. # # See the README file for information on usage and redistribution. # VERSION = "1.1.7" try: import warnings except ImportError: warnings = None class _imaging_not_installed: # module placeholder def __getattr__(self, id): raise ImportError("The _imaging C module is not installed") try: # give Tk a chance to set up the environment, in case we're # using an _imaging module linked against libtcl/libtk (use # __import__ to hide this from naive packagers; we don't really # depend on Tk unless ImageTk is used, and that module already # imports Tkinter) __import__("FixTk") except ImportError: pass try: # If the _imaging C module is not present, you can still use # the "open" function to identify files, but you cannot load # them. Note that other modules should not refer to _imaging # directly; import Image and use the Image.core variable instead. import _imaging core = _imaging del _imaging except ImportError, v: core = _imaging_not_installed() if str(v)[:20] == "Module use of python" and warnings: # The _imaging C module is present, but not compiled for # the right version (windows only). Print a warning, if # possible. warnings.warn( "The _imaging extension was built for another version " "of Python; most PIL functions will be disabled", RuntimeWarning ) import os import string import sys import ImageMode import ImagePalette # type stuff from types import StringType, TupleType try: UnicodeStringType = type(unicode("")) ## # (Internal) Checks if an object is a string. If the current # Python version supports Unicode, this checks for both 8-bit # and Unicode strings. def isStringType(t): return isinstance(t, StringType) or isinstance(t, UnicodeStringType) except NameError: def isStringType(t): return isinstance(t, StringType) ## # (Internal) Checks if an object is a tuple. def isTupleType(t): return isinstance(t, TupleType) ## # (Internal) Checks if an object is an image object. def isImageType(t): return hasattr(t, "im") ## # (Internal) Checks if an object is a string, and that it points to a # directory. def isDirectory(f): return isStringType(f) and os.path.isdir(f) from operator import isNumberType, isSequenceType # # Debug level DEBUG = 0 # # Constants (also defined in _imagingmodule.c!) NONE = 0 # transpose FLIP_LEFT_RIGHT = 0 FLIP_TOP_BOTTOM = 1 ROTATE_90 = 2 ROTATE_180 = 3 ROTATE_270 = 4 # transforms AFFINE = 0 EXTENT = 1 PERSPECTIVE = 2 QUAD = 3 MESH = 4 # resampling filters NONE = 0 NEAREST = 0 ANTIALIAS = 1 # 3-lobed lanczos LINEAR = BILINEAR = 2 CUBIC = BICUBIC = 3 # dithers NONE = 0 NEAREST = 0 ORDERED = 1 # Not yet implemented RASTERIZE = 2 # Not yet implemented FLOYDSTEINBERG = 3 # default # palettes/quantizers WEB = 0 ADAPTIVE = 1 # categories NORMAL = 0 SEQUENCE = 1 CONTAINER = 2 # -------------------------------------------------------------------- # Registries ID = [] OPEN = {} MIME = {} SAVE = {} EXTENSION = {} # -------------------------------------------------------------------- # Modes supported by this version _MODEINFO = { # NOTE: this table will be removed in future versions. use # getmode* functions or ImageMode descriptors instead. # official modes "1": ("L", "L", ("1",)), "L": ("L", "L", ("L",)), "I": ("L", "I", ("I",)), "F": ("L", "F", ("F",)), "P": ("RGB", "L", ("P",)), "RGB": ("RGB", "L", ("R", "G", "B")), "RGBX": ("RGB", "L", ("R", "G", "B", "X")), "RGBA": ("RGB", "L", ("R", "G", "B", "A")), "CMYK": ("RGB", "L", ("C", "M", "Y", "K")), "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")), # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and # BGR;24. Use these modes only if you know exactly what you're # doing... } try: byteorder = sys.byteorder except AttributeError: import struct if struct.unpack("h", "\0\1")[0] == 1: byteorder = "big" else: byteorder = "little" if byteorder == 'little': _ENDIAN = '<' else: _ENDIAN = '>' _MODE_CONV = { # official modes "1": ('|b1', None), # broken "L": ('|u1', None), "I": (_ENDIAN + 'i4', None), "F": (_ENDIAN + 'f4', None), "P": ('|u1', None), "RGB": ('|u1', 3), "RGBX": ('|u1', 4), "RGBA": ('|u1', 4), "CMYK": ('|u1', 4), "YCbCr": ('|u1', 4), } def _conv_type_shape(im): shape = im.size[1], im.size[0] typ, extra = _MODE_CONV[im.mode] if extra is None: return shape, typ else: return shape+(extra,), typ MODES = _MODEINFO.keys() MODES.sort() # raw modes that may be memory mapped. NOTE: if you change this, you # may have to modify the stride calculation in map.c too! _MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B") ## # Gets the "base" mode for given mode. This function returns "L" for # images that contain grayscale data, and "RGB" for images that # contain color data. # # @param mode Input mode. # @return "L" or "RGB". # @exception KeyError If the input mode was not a standard mode. def getmodebase(mode): return ImageMode.getmode(mode).basemode ## # Gets the storage type mode. Given a mode, this function returns a # single-layer mode suitable for storing individual bands. # # @param mode Input mode. # @return "L", "I", or "F". # @exception KeyError If the input mode was not a standard mode. def getmodetype(mode): return ImageMode.getmode(mode).basetype ## # Gets a list of individual band names. Given a mode, this function # returns a tuple containing the names of individual bands (use # {@link #getmodetype} to get the mode used to store each individual # band. # # @param mode Input mode. # @return A tuple containing band names. The length of the tuple # gives the number of bands in an image of the given mode. # @exception KeyError If the input mode was not a standard mode. def getmodebandnames(mode): return ImageMode.getmode(mode).bands ## # Gets the number of individual bands for this mode. # # @param mode Input mode. # @return The number of bands in this mode. # @exception KeyError If the input mode was not a standard mode. def getmodebands(mode): return len(ImageMode.getmode(mode).bands) # -------------------------------------------------------------------- # Helpers _initialized = 0 ## # Explicitly loads standard file format drivers. def preinit(): "Load standard file format drivers." global _initialized if _initialized >= 1: return try: import BmpImagePlugin except ImportError: pass try: import GifImagePlugin except ImportError: pass try: import JpegImagePlugin except ImportError: pass try: import PpmImagePlugin except ImportError: pass try: import PngImagePlugin except ImportError: pass # try: # import TiffImagePlugin # except ImportError: # pass _initialized = 1 ## # Explicitly initializes the Python Imaging Library. This function # loads all available file format drivers. def init(): "Load all file format drivers." global _initialized if _initialized >= 2: return 0 visited = {} directories = sys.path try: directories = directories + [os.path.dirname(__file__)] except NameError: pass # only check directories (including current, if present in the path) for directory in filter(isDirectory, directories): fullpath = os.path.abspath(directory) if visited.has_key(fullpath): continue for file in os.listdir(directory): if file[-14:] == "ImagePlugin.py": f, e = os.path.splitext(file) try: sys.path.insert(0, directory) try: __import__(f, globals(), locals(), []) finally: del sys.path[0] except ImportError: if DEBUG: print "Image: failed to import", print f, ":", sys.exc_value visited[fullpath] = None if OPEN or SAVE: _initialized = 2 return 1 # -------------------------------------------------------------------- # Codec factories (used by tostring/fromstring and ImageFile.load) def _getdecoder(mode, decoder_name, args, extra=()): # tweak arguments if args is None: args = () elif not isTupleType(args): args = (args,) try: # get decoder decoder = getattr(core, decoder_name + "_decoder") # print decoder, (mode,) + args + extra return apply(decoder, (mode,) + args + extra) except AttributeError: raise IOError("decoder %s not available" % decoder_name) def _getencoder(mode, encoder_name, args, extra=()): # tweak arguments if args is None: args = () elif not isTupleType(args): args = (args,) try: # get encoder encoder = getattr(core, encoder_name + "_encoder") # print encoder, (mode,) + args + extra return apply(encoder, (mode,) + args + extra) except AttributeError: raise IOError("encoder %s not available" % encoder_name) # -------------------------------------------------------------------- # Simple expression analyzer class _E: def __init__(self, data): self.data = data def __coerce__(self, other): return self, _E(other) def __add__(self, other): return _E((self.data, "__add__", other.data)) def __mul__(self, other): return _E((self.data, "__mul__", other.data)) def _getscaleoffset(expr): stub = ["stub"] data = expr(_E(stub)).data try: (a, b, c) = data # simplified syntax if (a is stub and b == "__mul__" and isNumberType(c)): return c, 0.0 if (a is stub and b == "__add__" and isNumberType(c)): return 1.0, c except TypeError: pass try: ((a, b, c), d, e) = data # full syntax if (a is stub and b == "__mul__" and isNumberType(c) and d == "__add__" and isNumberType(e)): return c, e except TypeError: pass raise ValueError("illegal expression") # -------------------------------------------------------------------- # Implementation wrapper ## # This class represents an image object. To create Image objects, use # the appropriate factory functions. There's hardly ever any reason # to call the Image constructor directly. # # @see #open # @see #new # @see #fromstring class Image: format = None format_description = None def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self.size = (0, 0) self.palette = None self.info = {} self.category = NORMAL self.readonly = 0 def _new(self, im): new = Image() new.im = im new.mode = im.mode new.size = im.size new.palette = self.palette if im.mode == "P": new.palette = ImagePalette.ImagePalette() try: new.info = self.info.copy() except AttributeError: # fallback (pre-1.5.2) new.info = {} for k, v in self.info: new.info[k] = v return new _makeself = _new # compatibility def _copy(self): self.load() self.im = self.im.copy() self.readonly = 0 def _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format self.save(file, format) return file def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self) ) def __getattr__(self, name): if name == "__array_interface__": # numpy array interface support new = {} shape, typestr = _conv_type_shape(self) new['shape'] = shape new['typestr'] = typestr new['data'] = self.tostring() return new raise AttributeError(name) ## # Returns a string containing pixel data. # # @param encoder_name What encoder to use. The default is to # use the standard "raw" encoder. # @param *args Extra arguments to the encoder. # @return An 8-bit string. def tostring(self, encoder_name="raw", *args): "Return image as a binary string" # may pass tuple instead of argument list if len(args) == 1 and isTupleType(args[0]): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while 1: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError("encoder error %d in tostring" % s) return string.join(data, "") ## # Returns the image converted to an X11 bitmap. This method # only works for mode "1" images. # # @param name The name prefix to use for the bitmap variables. # @return A string containing an X11 bitmap. # @exception ValueError If the mode is not "1" def tobitmap(self, name="image"): "Return image as an XBM bitmap" self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tostring("xbm") return string.join(["#define %s_width %d\n" % (name, self.size[0]), "#define %s_height %d\n"% (name, self.size[1]), "static char %s_bits[] = {\n" % name, data, "};"], "") ## # Loads this image with pixel data from a string. # <p> # This method is similar to the {@link #fromstring} function, but # loads data into this image instead of creating a new image # object. def fromstring(self, data, decoder_name="raw", *args): "Load data to image from binary string" # may pass tuple instead of argument list if len(args) == 1 and isTupleType(args[0]): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") ## # Allocates storage for the image and loads the pixel data. In # normal cases, you don't need to call this method, since the # Image class automatically loads an opened image when it is # accessed for the first time. # # @return An image access object. def load(self): "Explicitly load pixel data." if self.im and self.palette and self.palette.dirty: # realize palette apply(self.im.putpalette, self.palette.getdata()) self.palette.dirty = 0 self.palette.mode = "RGB" self.palette.rawmode = None if self.info.has_key("transparency"): self.im.putpalettealpha(self.info["transparency"], 0) self.palette.mode = "RGBA" if self.im: return self.im.pixel_access(self.readonly) ## # Verifies the contents of a file. For data read from a file, this # method attempts to determine if the file is broken, without # actually decoding the image data. If this method finds any # problems, it raises suitable exceptions. If you need to load # the image after using this method, you must reopen the image # file. def verify(self): "Verify file contents." pass ## # Returns a converted copy of this image. For the "P" mode, this # method translates pixels through the palette. If mode is # omitted, a mode is chosen so that all information in the image # and the palette can be represented without a palette. # <p> # The current version supports all possible conversions between # "L", "RGB" and "CMYK." # <p> # When translating a colour image to black and white (mode "L"), # the library uses the ITU-R 601-2 luma transform: # <p> # <b>L = R * 299/1000 + G * 587/1000 + B * 114/1000</b> # <p> # When translating a greyscale image into a bilevel image (mode # "1"), all non-zero values are set to 255 (white). To use other # thresholds, use the {@link #Image.point} method. # # @def convert(mode, matrix=None, **options) # @param mode The requested mode. # @param matrix An optional conversion matrix. If given, this # should be 4- or 16-tuple containing floating point values. # @param options Additional options, given as keyword arguments. # @keyparam dither Dithering method, used when converting from # mode "RGB" to "P". # Available methods are NONE or FLOYDSTEINBERG (default). # @keyparam palette Palette to use when converting from mode "RGB" # to "P". Available palettes are WEB or ADAPTIVE. # @keyparam colors Number of colors to use for the ADAPTIVE palette. # Defaults to 256. # @return An Image object. def convert(self, mode=None, data=None, dither=None, palette=WEB, colors=256): "Convert to other pixel format" if not mode: # determine default mode if self.mode == "P": self.load() if self.palette: mode = self.palette.mode else: mode = "RGB" else: return self.copy() self.load() if data: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, data) return self._new(im) if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) return self._new(im) # colourspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError: raise ValueError("illegal conversion") return self._new(im) def quantize(self, colors=256, method=0, kmeans=0, palette=None): # methods: # 0 = median cut # 1 = maximum coverage # NOTE: this functionality will be moved to the extended # quantizer interface in a later version of PIL. self.load() if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", 1, palette.im) return self._makeself(im) im = self.im.quantize(colors, method, kmeans) return self._new(im) ## # Copies this image. Use this method if you wish to paste things # into an image, but still retain the original. # # @return An Image object. def copy(self): "Copy raster data" self.load() im = self.im.copy() return self._new(im) ## # Returns a rectangular region from this image. The box is a # 4-tuple defining the left, upper, right, and lower pixel # coordinate. # <p> # This is a lazy operation. Changes to the source image may or # may not be reflected in the cropped image. To break the # connection, call the {@link #Image.load} method on the cropped # copy. # # @param The crop rectangle, as a (left, upper, right, lower)-tuple. # @return An Image object. def crop(self, box=None): "Crop region from image" self.load() if box is None: return self.copy() # lazy operation return _ImageCrop(self, box) ## # Configures the image file loader so it returns a version of the # image that as closely as possible matches the given mode and # size. For example, you can use this method to convert a colour # JPEG to greyscale while loading it, or to extract a 128x192 # version from a PCD file. # <p> # Note that this method modifies the Image object in place. If # the image has already been loaded, this method has no effect. # # @param mode The requested mode. # @param size The requested size. def draft(self, mode, size): "Configure image decoder" pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) ## # Filters this image using the given filter. For a list of # available filters, see the <b>ImageFilter</b> module. # # @param filter Filter kernel. # @return An Image object. # @see ImageFilter def filter(self, filter): "Apply environment filter to image" self.load() if callable(filter): filter = filter() if not hasattr(filter, "filter"): raise TypeError("filter argument should be ImageFilter.Filter instance or class") if self.im.bands == 1: return self._new(filter.filter(self.im)) # fix to handle multiband images since _imaging doesn't ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) ## # Returns a tuple containing the name of each band in this image. # For example, <b>getbands</b> on an RGB image returns ("R", "G", "B"). # # @return A tuple containing band names. def getbands(self): "Get band names" return ImageMode.getmode(self.mode).bands ## # Calculates the bounding box of the non-zero regions in the # image. # # @return The bounding box is returned as a 4-tuple defining the # left, upper, right, and lower pixel coordinate. If the image # is completely empty, this method returns None. def getbbox(self): "Get bounding box of actual data (non-zero pixels) in image" self.load() return self.im.getbbox() ## # Returns a list of colors used in this image. # # @param maxcolors Maximum number of colors. If this number is # exceeded, this method returns None. The default limit is # 256 colors. # @return An unsorted list of (count, pixel) values. def getcolors(self, maxcolors=256): "Get colors from image, up to given limit" self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) ## # Returns the contents of this image as a sequence object # containing pixel values. The sequence object is flattened, so # that values for line one follow directly after the values of # line zero, and so on. # <p> # Note that the sequence object returned by this method is an # internal PIL data type, which only supports certain sequence # operations. To convert it to an ordinary sequence (e.g. for # printing), use <b>list(im.getdata())</b>. # # @param band What band to return. The default is to return # all bands. To return a single band, pass in the index # value (e.g. 0 to get the "R" band from an "RGB" image). # @return A sequence-like object. def getdata(self, band = None): "Get image data as sequence object." self.load() if band is not None: return self.im.getband(band) return self.im # could be abused ## # Gets the the minimum and maximum pixel values for each band in # the image. # # @return For a single-band image, a 2-tuple containing the # minimum and maximum pixel value. For a multi-band image, # a tuple containing one 2-tuple for each band. def getextrema(self): "Get min/max value" self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() ## # Returns a PyCObject that points to the internal image memory. # # @return A PyCObject object. def getim(self): "Get PyCObject pointer to internal image memory" self.load() return self.im.ptr ## # Returns the image palette as a list. # # @return A list of color values [r, g, b, ...], or None if the # image has no palette. def getpalette(self): "Get palette contents." self.load() try: return map(ord, self.im.getpalette()) except ValueError: return None # no palette ## # Returns the pixel value at a given position. # # @param xy The coordinate, given as (x, y). # @return The pixel value. If the image is a multi-layer image, # this method returns a tuple. def getpixel(self, xy): "Get pixel value" self.load() return self.im.getpixel(xy) ## # Returns the horizontal and vertical projection. # # @return Two sequences, indicating where there are non-zero # pixels along the X-axis and the Y-axis, respectively. def getprojection(self): "Get projection to x and y axes" self.load() x, y = self.im.getprojection() return map(ord, x), map(ord, y) ## # Returns a histogram for the image. The histogram is returned as # a list of pixel counts, one for each pixel value in the source # image. If the image has more than one band, the histograms for # all bands are concatenated (for example, the histogram for an # "RGB" image contains 768 values). # <p> # A bilevel image (mode "1") is treated as a greyscale ("L") image # by this method. # <p> # If a mask is provided, the method returns a histogram for those # parts of the image where the mask image is non-zero. The mask # image must have the same size as the image, and be either a # bi-level image (mode "1") or a greyscale image ("L"). # # @def histogram(mask=None) # @param mask An optional mask. # @return A list containing pixel counts. def histogram(self, mask=None, extrema=None): "Take histogram of image" self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() ## # (Deprecated) Returns a copy of the image where the data has been # offset by the given distances. Data wraps around the edges. If # yoffset is omitted, it is assumed to be equal to xoffset. # <p> # This method is deprecated. New code should use the <b>offset</b> # function in the <b>ImageChops</b> module. # # @param xoffset The horizontal distance. # @param yoffset The vertical distance. If omitted, both # distances are set to the same value. # @return An Image object. def offset(self, xoffset, yoffset=None): "(deprecated) Offset image in horizontal and/or vertical direction" if warnings: warnings.warn( "'offset' is deprecated; use 'ImageChops.offset' instead", DeprecationWarning, stacklevel=2 ) import ImageChops return ImageChops.offset(self, xoffset, yoffset) ## # Pastes another image into this image. The box argument is either # a 2-tuple giving the upper left corner, a 4-tuple defining the # left, upper, right, and lower pixel coordinate, or None (same as # (0, 0)). If a 4-tuple is given, the size of the pasted image # must match the size of the region. # <p> # If the modes don't match, the pasted image is converted to the # mode of this image (see the {@link #Image.convert} method for # details). # <p> # Instead of an image, the source can be a integer or tuple # containing pixel values. The method then fills the region # with the given colour. When creating RGB images, you can # also use colour strings as supported by the ImageColor module. # <p> # If a mask is given, this method updates only the regions # indicated by the mask. You can use either "1", "L" or "RGBA" # images (in the latter case, the alpha band is used as mask). # Where the mask is 255, the given image is copied as is. Where # the mask is 0, the current value is preserved. Intermediate # values can be used for transparency effects. # <p> # Note that if you paste an "RGBA" image, the alpha band is # ignored. You can work around this by using the same image as # both source image and mask. # # @param im Source image or pixel value (integer or tuple). # @param box An optional 4-tuple giving the region to paste into. # If a 2-tuple is used instead, it's treated as the upper left # corner. If omitted or None, the source is pasted into the # upper left corner. # <p> # If an image is given as the second argument and there is no # third, the box defaults to (0, 0), and the second argument # is interpreted as a mask image. # @param mask An optional mask image. # @return An Image object. def paste(self, im, box=None, mask=None): "Paste other image into region" if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box; box = None if box is None: # cover all of self box = (0, 0) + self.size if len(box) == 2: # lower left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError( "cannot determine region size; use 4-item box" ) box = box + (box[0]+size[0], box[1]+size[1]) if isStringType(im): import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self.load() if self.readonly: self._copy() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) ## # Maps this image through a lookup table or function. # # @param lut A lookup table, containing 256 values per band in the # image. A function can be used instead, it should take a single # argument. The function is called once for each possible pixel # value, and the resulting table is applied to all bands of the # image. # @param mode Output mode (default is same as input). In the # current version, this can only be used if the source image # has mode "L" or "P", and the output has mode "1". # @return An Image object. def point(self, lut, mode=None): "Map image through lookup table" self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if not isSequenceType(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = map(lut, range(256)) * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode)) ## # Adds or replaces the alpha layer in this image. If the image # does not have an alpha layer, it's converted to "LA" or "RGBA". # The new layer must be either "L" or "1". # # @param im The new alpha layer. This can either be an "L" or "1" # image having the same size as this image, or an integer or # other color value. def putalpha(self, alpha): "Set alpha layer" self.load() if self.readonly: self._copy() if self.mode not in ("LA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError): # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "RGBA"): raise ValueError # sanity check self.im = im self.mode = self.im.mode except (KeyError, ValueError): raise ValueError("illegal image mode") if self.mode == "LA": band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) ## # Copies pixel data to this image. This method copies data from a # sequence object into the image, starting at the upper left # corner (0, 0), and continuing until either the image or the # sequence ends. The scale and offset values are used to adjust # the sequence values: <b>pixel = value*scale + offset</b>. # # @param data A sequence object. # @param scale An optional scale value. The default is 1.0. # @param offset An optional offset value. The default is 0.0. def putdata(self, data, scale=1.0, offset=0.0): "Put data from a sequence object into an image." self.load() if self.readonly: self._copy() self.im.putdata(data, scale, offset) ## # Attaches a palette to this image. The image must be a "P" or # "L" image, and the palette sequence must contain 768 integer # values, where each group of three values represent the red, # green, and blue values for the corresponding pixel # index. Instead of an integer sequence, you can use an 8-bit # string. # # @def putpalette(data) # @param data A palette sequence (either a list or a string). def putpalette(self, data, rawmode="RGB"): "Put palette data into an image." if self.mode not in ("L", "P"): raise ValueError("illegal image mode") self.load() if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isStringType(data): data = string.join(map(chr, data), "") palette = ImagePalette.raw(rawmode, data) self.mode = "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette ## # Modifies the pixel at the given position. The colour is given as # a single numerical value for single-band images, and a tuple for # multi-band images. # <p> # Note that this method is relatively slow. For more extensive # changes, use {@link #Image.paste} or the <b>ImageDraw</b> module # instead. # # @param xy The pixel coordinate, given as (x, y). # @param value The pixel value. # @see #Image.paste # @see #Image.putdata # @see ImageDraw def putpixel(self, xy, value): "Set pixel value" self.load() if self.readonly: self._copy() return self.im.putpixel(xy, value) ## # Returns a resized copy of this image. # # @def resize(size, filter=NEAREST) # @param size The requested size in pixels, as a 2-tuple: # (width, height). # @param filter An optional resampling filter. This can be # one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b> # (linear interpolation in a 2x2 environment), <b>BICUBIC</b> # (cubic spline interpolation in a 4x4 environment), or # <b>ANTIALIAS</b> (a high-quality downsampling filter). # If omitted, or if the image has mode "1" or "P", it is # set <b>NEAREST</b>. # @return An Image object. def resize(self, size, resample=NEAREST): "Resize image" if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS): raise ValueError("unknown resampling filter") self.load() if self.mode in ("1", "P"): resample = NEAREST if resample == ANTIALIAS: # requires stretch support (imToolkit & PIL 1.1.3) try: im = self.im.stretch(size, resample) except AttributeError: raise ValueError("unsupported resampling filter") else: im = self.im.resize(size, resample) return self._new(im) ## # Returns a rotated copy of this image. This method returns a # copy of this image, rotated the given number of degrees counter # clockwise around its centre. # # @def rotate(angle, filter=NEAREST) # @param angle In degrees counter clockwise. # @param filter An optional resampling filter. This can be # one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b> # (linear interpolation in a 2x2 environment), or <b>BICUBIC</b> # (cubic spline interpolation in a 4x4 environment). # If omitted, or if the image has mode "1" or "P", it is # set <b>NEAREST</b>. # @param expand Optional expansion flag. If true, expands the output # image to make it large enough to hold the entire rotated image. # If false or omitted, make the output image the same size as the # input image. # @return An Image object. def rotate(self, angle, resample=NEAREST, expand=0): "Rotate image. Angle given as degrees counter-clockwise." if expand: import math angle = -angle * math.pi / 180 matrix = [ math.cos(angle), math.sin(angle), 0.0, -math.sin(angle), math.cos(angle), 0.0 ] def transform(x, y, (a, b, c, d, e, f)=matrix): return a*x + b*y + c, d*x + e*y + f # calculate output size w, h = self.size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y) xx.append(x) yy.append(y) w = int(math.ceil(max(xx)) - math.floor(min(xx))) h = int(math.ceil(max(yy)) - math.floor(min(yy))) # adjust center x, y = transform(w / 2.0, h / 2.0) matrix[2] = self.size[0] / 2.0 - x matrix[5] = self.size[1] / 2.0 - y return self.transform((w, h), AFFINE, matrix, resample) if resample not in (NEAREST, BILINEAR, BICUBIC): raise ValueError("unknown resampling filter") self.load() if self.mode in ("1", "P"): resample = NEAREST return self._new(self.im.rotate(angle, resample)) ## # Saves this image under the given filename. If no format is # specified, the format to use is determined from the filename # extension, if possible. # <p> # Keyword options can be used to provide additional instructions # to the writer. If a writer doesn't recognise an option, it is # silently ignored. The available options are described later in # this handbook. # <p> # You can use a file object instead of a filename. In this case, # you must always specify the format. The file object must # implement the <b>seek</b>, <b>tell</b>, and <b>write</b> # methods, and be opened in binary mode. # # @def save(file, format=None, **options) # @param file File name or file object. # @param format Optional format override. If omitted, the # format to use is determined from the filename extension. # If a file object was used instead of a filename, this # parameter should always be used. # @param **options Extra parameters to the image writer. # @return None # @exception KeyError If the output format could not be determined # from the file name. Use the format option to solve this. # @exception IOError If the file could not be written. The file # may have been created, and may contain partial data. def save(self, fp, format=None, **params): "Save image to file or stream" if isStringType(fp): filename = fp else: if hasattr(fp, "name") and isStringType(fp.name): filename = fp.name else: filename = "" # may mutate self! self.load() self.encoderinfo = params self.encoderconfig = () preinit() ext = string.lower(os.path.splitext(filename)[1]) if not format: try: format = EXTENSION[ext] except KeyError: init() try: format = EXTENSION[ext] except KeyError: raise KeyError(ext) # unknown extension try: save_handler = SAVE[string.upper(format)] except KeyError: init() save_handler = SAVE[string.upper(format)] # unknown format if isStringType(fp): import __builtin__ fp = __builtin__.open(fp, "wb") close = 1 else: close = 0 try: save_handler(self, fp, filename) finally: # do what we can to clean up if close: fp.close() ## # Seeks to the given frame in this sequence file. If you seek # beyond the end of the sequence, the method raises an # <b>EOFError</b> exception. When a sequence file is opened, the # library automatically seeks to frame 0. # <p> # Note that in the current version of the library, most sequence # formats only allows you to seek to the next frame. # # @param frame Frame number, starting at 0. # @exception EOFError If the call attempts to seek beyond the end # of the sequence. # @see #Image.tell def seek(self, frame): "Seek to given frame in sequence file" # overridden by file handlers if frame != 0: raise EOFError ## # Displays this image. This method is mainly intended for # debugging purposes. # <p> # On Unix platforms, this method saves the image to a temporary # PPM file, and calls the <b>xv</b> utility. # <p> # On Windows, it saves the image to a temporary BMP file, and uses # the standard BMP display utility to show it (usually Paint). # # @def show(title=None) # @param title Optional title to use for the image window, # where possible. def show(self, title=None, command=None): "Display image (for debug purposes only)" _show(self, title=title, command=command) ## # Split this image into individual bands. This method returns a # tuple of individual image bands from an image. For example, # splitting an "RGB" image creates three new images each # containing a copy of one of the original bands (red, green, # blue). # # @return A tuple containing bands. def split(self): "Split image into bands" if self.im.bands == 1: ims = [self.copy()] else: ims = [] self.load() for i in range(self.im.bands): ims.append(self._new(self.im.getband(i))) return tuple(ims) ## # Returns the current frame number. # # @return Frame number, starting with 0. # @see #Image.seek def tell(self): "Return current frame number" return 0 ## # Make this image into a thumbnail. This method modifies the # image to contain a thumbnail version of itself, no larger than # the given size. This method calculates an appropriate thumbnail # size to preserve the aspect of the image, calls the {@link # #Image.draft} method to configure the file reader (where # applicable), and finally resizes the image. # <p> # Note that the bilinear and bicubic filters in the current # version of PIL are not well-suited for thumbnail generation. # You should use <b>ANTIALIAS</b> unless speed is much more # important than quality. # <p> # Also note that this function modifies the Image object in place. # If you need to use the full resolution image as well, apply this # method to a {@link #Image.copy} of the original image. # # @param size Requested size. # @param resample Optional resampling filter. This can be one # of <b>NEAREST</b>, <b>BILINEAR</b>, <b>BICUBIC</b>, or # <b>ANTIALIAS</b> (best quality). If omitted, it defaults # to <b>NEAREST</b> (this will be changed to ANTIALIAS in a # future version). # @return None def thumbnail(self, size, resample=NEAREST): "Create thumbnail representation (modifies image in place)" # FIXME: the default resampling filter will be changed # to ANTIALIAS in future versions # preserve aspect ratio x, y = self.size if x > size[0]: y = max(y * size[0] / x, 1); x = size[0] if y > size[1]: x = max(x * size[1] / y, 1); y = size[1] size = x, y if size == self.size: return self.draft(None, size) self.load() try: im = self.resize(size, resample) except ValueError: if resample != ANTIALIAS: raise im = self.resize(size, NEAREST) # fallback self.im = im.im self.mode = im.mode self.size = size self.readonly = 0 # FIXME: the different tranform methods need further explanation # instead of bloating the method docs, add a separate chapter. ## # Transforms this image. This method creates a new image with the # given size, and the same mode as the original, and copies data # to the new image using the given transform. # <p> # @def transform(size, method, data, resample=NEAREST) # @param size The output size. # @param method The transformation method. This is one of # <b>EXTENT</b> (cut out a rectangular subregion), <b>AFFINE</b> # (affine transform), <b>PERSPECTIVE</b> (perspective # transform), <b>QUAD</b> (map a quadrilateral to a # rectangle), or <b>MESH</b> (map a number of source quadrilaterals # in one operation). # @param data Extra data to the transformation method. # @param resample Optional resampling filter. It can be one of # <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b> # (linear interpolation in a 2x2 environment), or # <b>BICUBIC</b> (cubic spline interpolation in a 4x4 # environment). If omitted, or if the image has mode # "1" or "P", it is set to <b>NEAREST</b>. # @return An Image object. def transform(self, size, method, data=None, resample=NEAREST, fill=1): "Transform image" if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data") im = new(self.mode, size, None) if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fill) else: im.__transformer((0, 0)+size, self, method, data, resample, fill) return im def __transformer(self, box, image, method, data, resample=NEAREST, fill=1): # FIXME: this should be turned into a lazy operation (?) w = box[2]-box[0] h = box[3]-box[1] if method == AFFINE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4]) elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = float(x1 - x0) / w ys = float(y1 - y0) / h method = AFFINE data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys) elif method == PERSPECTIVE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4], data[6], data[7]) elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8] x0, y0 = nw; As = 1.0 / w; At = 1.0 / h data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At, (se[0]-sw[0]-ne[0]+x0)*As*At, y0, (ne[1]-y0)*As, (sw[1]-y0)*At, (se[1]-sw[1]-ne[1]+y0)*As*At) else: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): raise ValueError("unknown resampling filter") image.load() self.load() if image.mode in ("1", "P"): resample = NEAREST self.im.transform2(box, image.im, method, data, resample, fill) ## # Returns a flipped or rotated copy of this image. # # @param method One of <b>FLIP_LEFT_RIGHT</b>, <b>FLIP_TOP_BOTTOM</b>, # <b>ROTATE_90</b>, <b>ROTATE_180</b>, or <b>ROTATE_270</b>. def transpose(self, method): "Transpose image (flip or rotate in 90 degree steps)" self.load() im = self.im.transpose(method) return self._new(im) # -------------------------------------------------------------------- # Lazy operations class _ImageCrop(Image): def __init__(self, im, box): Image.__init__(self) x0, y0, x1, y1 = box if x1 < x0: x1 = x0 if y1 < y0: y1 = y0 self.mode = im.mode self.size = x1-x0, y1-y0 self.__crop = x0, y0, x1, y1 self.im = im.im def load(self): # lazy evaluation! if self.__crop: self.im = self.im.crop(self.__crop) self.__crop = None if self.im: return self.im.pixel_access(self.readonly) # FIXME: future versions should optimize crop/paste # sequences! # -------------------------------------------------------------------- # Abstract handlers. class ImagePointHandler: # used as a mixin by point transforms (for use with im.point) pass class ImageTransformHandler: # used as a mixin by geometry transforms (for use with im.transform) pass # -------------------------------------------------------------------- # Factories # # Debugging def _wedge(): "Create greyscale wedge (for debugging only)" return Image()._new(core.wedge("L")) ## # Creates a new image with the given mode and size. # # @param mode The mode to use for the new image. # @param size A 2-tuple, containing (width, height) in pixels. # @param color What colour to use for the image. Default is black. # If given, this should be a single integer or floating point value # for single-band modes, and a tuple for multi-band modes (one value # per band). When creating RGB images, you can also use colour # strings as supported by the ImageColor module. If the colour is # None, the image is not initialised. # @return An Image object. def new(mode, size, color=0): "Create a new image" if color is None: # don't initialize return Image()._new(core.new(mode, size)) if isStringType(color): # css3-style specifier import ImageColor color = ImageColor.getcolor(color, mode) return Image()._new(core.fill(mode, size, color)) ## # Creates an image memory from pixel data in a string. # <p> # In its simplest form, this function takes three arguments # (mode, size, and unpacked pixel data). # <p> # You can also use any pixel decoder supported by PIL. For more # information on available decoders, see the section <a # href="pil-decoder.htm"><i>Writing Your Own File Decoder</i></a>. # <p> # Note that this function decodes pixel data only, not entire images. # If you have an entire image in a string, wrap it in a # <b>StringIO</b> object, and use {@link #open} to load it. # # @param mode The image mode. # @param size The image size. # @param data An 8-bit string containing raw data for the given mode. # @param decoder_name What decoder to use. # @param *args Additional parameters for the given decoder. # @return An Image object. def fromstring(mode, size, data, decoder_name="raw", *args): "Load image from string" # may pass tuple instead of argument list if len(args) == 1 and isTupleType(args[0]): args = args[0] if decoder_name == "raw" and args == (): args = mode im = new(mode, size) im.fromstring(data, decoder_name, args) return im ## # (New in 1.1.4) Creates an image memory from pixel data in a string # or byte buffer. # <p> # This function is similar to {@link #fromstring}, but uses data in # the byte buffer, where possible. This means that changes to the # original buffer object are reflected in this image). Not all modes # can share memory; supported modes include "L", "RGBX", "RGBA", and # "CMYK". # <p> # Note that this function decodes pixel data only, not entire images. # If you have an entire image file in a string, wrap it in a # <b>StringIO</b> object, and use {@link #open} to load it. # <p> # In the current version, the default parameters used for the "raw" # decoder differs from that used for {@link fromstring}. This is a # bug, and will probably be fixed in a future release. The current # release issues a warning if you do this; to disable the warning, # you should provide the full set of parameters. See below for # details. # # @param mode The image mode. # @param size The image size. # @param data An 8-bit string or other buffer object containing raw # data for the given mode. # @param decoder_name What decoder to use. # @param *args Additional parameters for the given decoder. For the # default encoder ("raw"), it's recommended that you provide the # full set of parameters: # <b>frombuffer(mode, size, data, "raw", mode, 0, 1)</b>. # @return An Image object. # @since 1.1.4 def frombuffer(mode, size, data, decoder_name="raw", *args): "Load image from string or buffer" # may pass tuple instead of argument list if len(args) == 1 and isTupleType(args[0]): args = args[0] if decoder_name == "raw": if args == (): if warnings: warnings.warn( "the frombuffer defaults may change in a future release; " "for portability, change the call to read:\n" " frombuffer(mode, size, data, 'raw', mode, 0, 1)", RuntimeWarning, stacklevel=2 ) args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6 if args[0] in _MAPMODES: im = new(mode, (1,1)) im = im._new( core.map_buffer(data, size, decoder_name, None, 0, args) ) im.readonly = 1 return im return fromstring(mode, size, data, decoder_name, args) ## # (New in 1.1.6) Creates an image memory from an object exporting # the array interface (using the buffer protocol). # # If obj is not contiguous, then the tostring method is called # and {@link frombuffer} is used. # # @param obj Object with array interface # @param mode Mode to use (will be determined from type if None) # @return An image memory. def fromarray(obj, mode=None): arr = obj.__array_interface__ shape = arr['shape'] ndim = len(shape) try: strides = arr['strides'] except KeyError: strides = None if mode is None: try: typekey = (1, 1) + shape[2:], arr['typestr'] mode, rawmode = _fromarray_typemap[typekey] except KeyError: # print typekey raise TypeError("Cannot handle this data type") else: rawmode = mode if mode in ["1", "L", "I", "P", "F"]: ndmax = 2 elif mode == "RGB": ndmax = 3 else: ndmax = 4 if ndim > ndmax: raise ValueError("Too many dimensions.") size = shape[1], shape[0] if strides is not None: obj = obj.tostring() return frombuffer(mode, size, obj, "raw", rawmode, 0, 1) _fromarray_typemap = { # (shape, typestr) => mode, rawmode # first two members of shape are set to one # ((1, 1), "|b1"): ("1", "1"), # broken ((1, 1), "|u1"): ("L", "L"), ((1, 1), "|i1"): ("I", "I;8"), ((1, 1), "<i2"): ("I", "I;16"), ((1, 1), ">i2"): ("I", "I;16B"), ((1, 1), "<i4"): ("I", "I;32"), ((1, 1), ">i4"): ("I", "I;32B"), ((1, 1), "<f4"): ("F", "F;32F"), ((1, 1), ">f4"): ("F", "F;32BF"), ((1, 1), "<f8"): ("F", "F;64F"), ((1, 1), ">f8"): ("F", "F;64BF"), ((1, 1, 3), "|u1"): ("RGB", "RGB"), ((1, 1, 4), "|u1"): ("RGBA", "RGBA"), } # shortcuts _fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I") _fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F") ## # Opens and identifies the given image file. # <p> # This is a lazy operation; this function identifies the file, but the # actual image data is not read from the file until you try to process # the data (or call the {@link #Image.load} method). # # @def open(file, mode="r") # @param file A filename (string) or a file object. The file object # must implement <b>read</b>, <b>seek</b>, and <b>tell</b> methods, # and be opened in binary mode. # @param mode The mode. If given, this argument must be "r". # @return An Image object. # @exception IOError If the file cannot be found, or the image cannot be # opened and identified. # @see #new def open(fp, mode="r"): "Open an image file, without loading the raster data" if mode != "r": raise ValueError("bad mode") if isStringType(fp): import __builtin__ filename = fp fp = __builtin__.open(fp, "rb") else: filename = "" prefix = fp.read(16) preinit() for i in ID: try: factory, accept = OPEN[i] if not accept or accept(prefix): fp.seek(0) return factory(fp, filename) except (SyntaxError, IndexError, TypeError): pass if init(): for i in ID: try: factory, accept = OPEN[i] if not accept or accept(prefix): fp.seek(0) return factory(fp, filename) except (SyntaxError, IndexError, TypeError): pass raise IOError("cannot identify image file") # # Image processing. ## # Creates a new image by interpolating between two input images, using # a constant alpha. # # <pre> # out = image1 * (1.0 - alpha) + image2 * alpha # </pre> # # @param im1 The first image. # @param im2 The second image. Must have the same mode and size as # the first image. # @param alpha The interpolation alpha factor. If alpha is 0.0, a # copy of the first image is returned. If alpha is 1.0, a copy of # the second image is returned. There are no restrictions on the # alpha value. If necessary, the result is clipped to fit into # the allowed output range. # @return An Image object. def blend(im1, im2, alpha): "Interpolate between images." im1.load() im2.load() return im1._new(core.blend(im1.im, im2.im, alpha)) ## # Creates a new image by interpolating between two input images, # using the mask as alpha. # # @param image1 The first image. # @param image2 The second image. Must have the same mode and # size as the first image. # @param mask A mask image. This image can can have mode # "1", "L", or "RGBA", and must have the same size as the # other two images. def composite(image1, image2, mask): "Create composite image by blending images using a transparency mask" image = image2.copy() image.paste(image1, None, mask) return image ## # Applies the function (which should take one argument) to each pixel # in the given image. If the image has more than one band, the same # function is applied to each band. Note that the function is # evaluated once for each possible pixel value, so you cannot use # random components or other generators. # # @def eval(image, function) # @param image The input image. # @param function A function object, taking one integer argument. # @return An Image object. def eval(image, *args): "Evaluate image expression" return image.point(args[0]) ## # Creates a new image from a number of single-band images. # # @param mode The mode to use for the output image. # @param bands A sequence containing one single-band image for # each band in the output image. All bands must have the # same size. # @return An Image object. def merge(mode, bands): "Merge a set of single band images into a new multiband image." if getmodebands(mode) != len(bands) or "*" in mode: raise ValueError("wrong number of bands") for im in bands[1:]: if im.mode != getmodetype(mode): raise ValueError("mode mismatch") if im.size != bands[0].size: raise ValueError("size mismatch") im = core.new(mode, bands[0].size) for i in range(getmodebands(mode)): bands[i].load() im.putband(bands[i].im, i) return bands[0]._new(im) # -------------------------------------------------------------------- # Plugin registry ## # Register an image file plugin. This function should not be used # in application code. # # @param id An image format identifier. # @param factory An image file factory method. # @param accept An optional function that can be used to quickly # reject images having another format. def register_open(id, factory, accept=None): id = string.upper(id) ID.append(id) OPEN[id] = factory, accept ## # Registers an image MIME type. This function should not be used # in application code. # # @param id An image format identifier. # @param mimetype The image MIME type for this format. def register_mime(id, mimetype): MIME[string.upper(id)] = mimetype ## # Registers an image save function. This function should not be # used in application code. # # @param id An image format identifier. # @param driver A function to save images in this format. def register_save(id, driver): SAVE[string.upper(id)] = driver ## # Registers an image extension. This function should not be # used in application code. # # @param id An image format identifier. # @param extension An extension used for this format. def register_extension(id, extension): EXTENSION[string.lower(extension)] = string.upper(id) # -------------------------------------------------------------------- # Simple display support. User code may override this. def _show(image, **options): # override me, as necessary apply(_showxv, (image,), options) def _showxv(image, title=None, **options): import ImageShow apply(ImageShow.show, (image, title), options)
[ "biweibiren@163.com" ]
biweibiren@163.com
9af4d770117e900fdc4f395633ef86a68d710ca6
9bf7d7ace42a61991970fd967c19071a50609b9e
/ipython/Matplotlib(2f)UnfilledHistograms.py
be423b643ffae045db7075154fed13fc75d8295f
[]
no_license
ParsonsRD/SciPy-CookBook
29b68eace76962ae00735039bc3d488f31714e50
52f70a7aa4bd4fd11217a13fc8dd5e277f2388ea
refs/heads/master
2020-03-17T17:33:28.827269
2013-05-17T06:56:54
2013-05-17T06:56:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,599
py
# <markdowncell> # Here's some template code for plotting histograms that don't look like # bar charts, but instead have only outlines (like IDL creates). # # First define a function that does the bulk of the heavy lifting. # # <codecell> import numpy as np def histOutline(dataIn, *args, **kwargs): (histIn, binsIn) = np.histogram(dataIn, *args, **kwargs) stepSize = binsIn[1] - binsIn[0] bins = np.zeros(len(binsIn)*2 + 2, dtype=np.float) data = np.zeros(len(binsIn)*2 + 2, dtype=np.float) for bb in range(len(binsIn)): bins[2*bb + 1] = binsIn[bb] bins[2*bb + 2] = binsIn[bb] + stepSize if bb < len(histIn): data[2*bb + 1] = histIn[bb] data[2*bb + 2] = histIn[bb] bins[0] = bins[1] bins[-1] = bins[-2] data[0] = 0 data[-1] = 0 return (bins, data) # <markdowncell> # Now we can make plots: # # <codecell> # Make some data to plot data = randn(500) figure(2, figsize=(10, 5)) clf() ########## # # First make a normal histogram # ########## subplot(1, 2, 1) (n, bins, patches) = hist(data) # Boundaries xlo = -max(abs(bins)) xhi = max(abs(bins)) ylo = 0 yhi = max(n) * 1.1 axis([xlo, xhi, ylo, yhi]) ########## # # Now make a histogram in outline format # ########## (bins, n) = histOutline(data) subplot(1, 2, 2) plot(bins, n, 'k-') axis([xlo, xhi, ylo, yhi]) # <markdowncell> # Here you can find this functionality packaged up into # <![](files/Matplotlib(2f)UnfilledHistograms_attachments/histOutline.py> )# # ![](files/Matplotlib(2f)UnfilledHistograms_attachments/hist_outline.png #
[ "matti.pastell@helsinki.fi" ]
matti.pastell@helsinki.fi
d809e87594386c61ac619c02129311ca823d2635
19af2e1dfe389afc71e26bebaadf7008251e04e2
/android_test/tensorflow-master/tensorflow/examples/saved_model/integration_tests/export_mnist_cnn.py
1d36bc234aea7c51e9f284c7ea92aad0b392f6fc
[ "Apache-2.0" ]
permissive
simi48/Ef-If_Jassen
6c4975216bb4ae4514fe94a8395a5da5c8e8fb2d
6076839492bff591cf9b457e949999e9167903e6
refs/heads/master
2022-10-15T15:36:35.023506
2020-12-02T10:38:13
2020-12-02T10:38:13
173,759,247
4
0
Apache-2.0
2022-10-04T23:51:35
2019-03-04T14:22:28
PureBasic
UTF-8
Python
false
false
8,104
py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Exports a convolutional feature extractor for MNIST in SavedModel format. The feature extractor is a convolutional neural network plus a hidden layer that gets trained as part of an MNIST classifier and then written to a SavedModel (without the classification layer). From there, use_mnist_cnn.py picks it up for transfer learning. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags import tensorflow.compat.v2 as tf from tensorflow.examples.saved_model.integration_tests import mnist_util from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_inspect FLAGS = flags.FLAGS flags.DEFINE_string( 'export_dir', None, 'Directory of exported SavedModel.') flags.DEFINE_integer( 'epochs', 10, 'Number of epochs to train.') flags.DEFINE_bool( 'fast_test_mode', False, 'Shortcut training for running in unit tests.') flags.DEFINE_bool( 'export_print_hparams', False, 'If true, the exported function will print its effective hparams.') def make_feature_extractor(l2_strength, dropout_rate): """Returns a Keras Model to compute a feature vector from MNIST images.""" regularizer = lambda: tf.keras.regularizers.l2(l2_strength) net = inp = tf.keras.Input(mnist_util.INPUT_SHAPE) net = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', name='conv1', kernel_regularizer=regularizer())(net) net = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', name='conv2', kernel_regularizer=regularizer())(net) net = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), name='pool1')(net) net = tf.keras.layers.Dropout(dropout_rate, name='dropout1')(net) net = tf.keras.layers.Flatten(name='flatten')(net) net = tf.keras.layers.Dense(10, activation='relu', name='dense1', kernel_regularizer=regularizer())(net) return tf.keras.Model(inputs=inp, outputs=net) def set_feature_extractor_hparams(model, dropout_rate): model.get_layer('dropout1').rate = dropout_rate def make_classifier(feature_extractor, l2_strength, dropout_rate=0.5): """Returns a Keras Model to classify MNIST using feature_extractor.""" regularizer = lambda: tf.keras.regularizers.l2(l2_strength) net = inp = tf.keras.Input(mnist_util.INPUT_SHAPE) net = feature_extractor(net) net = tf.keras.layers.Dropout(dropout_rate)(net) net = tf.keras.layers.Dense(mnist_util.NUM_CLASSES, activation='softmax', kernel_regularizer=regularizer())(net) return tf.keras.Model(inputs=inp, outputs=net) def wrap_keras_model_for_export(model, batch_input_shape, set_hparams, default_hparams): """Wraps `model` for saving and loading as SavedModel.""" if default_hparams is None: default_hparams = {} hparam_keys = list(default_hparams.keys()) hparam_defaults = tuple(default_hparams.values()) # The goal is to save a function with this argspec... argspec = tf_inspect.FullArgSpec( args=(['inputs', 'training'] + hparam_keys), defaults=((False,) + hparam_defaults), varargs=None, varkw=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) # ...and this behavior: def call_fn(inputs, training, *args): if FLAGS.export_print_hparams: args = [tf.keras.backend.print_tensor(args[i], 'training=%s and %s=' % (training, hparam_keys[i])) for i in range(len(args))] kwargs = dict(zip(hparam_keys, args)) if kwargs: set_hparams(model, **kwargs) return model(inputs, training=training) # We cannot spell out `args` in def statement for call_fn, but since # tf.function uses tf_inspect, we can use tf_decorator to wrap it with # the desired argspec. def wrapped(*args, **kwargs): # TODO(arnoegw): Can we use call_fn itself? return call_fn(*args, **kwargs) traced_call_fn = tf.function(autograph=False)( tf_decorator.make_decorator(call_fn, wrapped, decorator_argspec=argspec)) # Now we need to trigger traces for # - training set to Python values True or False (hence two traces), # - tensor inputs of the expected nesting, shape and dtype, # - tensor-valued kwargs for hparams, with caller-side defaults. # Tracing with partially determined shapes requires an input signature, # so we initiate tracing from a helper function with only tensor inputs. @tf.function(autograph=False) def trigger_traces(inputs, **kwargs): return tuple(traced_call_fn(inputs, training=training, **kwargs) for training in (True, False)) inputs_spec = tf.TensorSpec(shape=batch_input_shape, dtype=tf.float32) hparams_spec = {name: tf.TensorSpec.from_tensor(tf.constant(value)) for name, value in default_hparams.items()} _ = trigger_traces.get_concrete_function(inputs_spec, **hparams_spec) # Assemble the output object. obj = tf.train.Checkpoint() obj.__call__ = traced_call_fn obj.trainable_variables = model.trainable_variables obj.variables = model.trainable_variables + model.non_trainable_variables obj.regularization_losses = [_get_traced_loss(model, i) for i in range(len(model.losses))] return obj def _get_traced_loss(model, i): """Returns tf.function for model.losses[i] with a trace for zero args. The intended usage is [_get_traced_loss(model, i) for i in range(len(model.losses))] This is better than [tf.function(lambda: model.losses[i], input_signature=[]) for i ...] because it avoids capturing a loop index in a lambda, and removes any chance of deferring the trace. Args: model: a Keras Model. i: an integer between from 0 up to but to len(model.losses). """ f = tf.function(lambda: model.losses[i]) _ = f.get_concrete_function() return f def main(argv): del argv # Build a complete classifier model using a feature extractor. default_hparams = dict(dropout_rate=0.25) l2_strength = 0.01 # Not a hparam for inputs -> outputs. feature_extractor = make_feature_extractor(l2_strength=l2_strength, **default_hparams) classifier = make_classifier(feature_extractor, l2_strength=l2_strength) # Train the complete model. (x_train, y_train), (x_test, y_test) = mnist_util.load_reshaped_data( fake_tiny_data=FLAGS.fast_test_mode) classifier.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer=tf.keras.optimizers.SGD(), metrics=['accuracy']) classifier.fit(x_train, y_train, batch_size=128, epochs=FLAGS.epochs, verbose=1, validation_data=(x_test, y_test)) # Save the feature extractor to a framework-agnostic SavedModel for reuse. # Note that the feature_extractor object has not been compiled or fitted, # so it does not contain an optimizer and related state. exportable = wrap_keras_model_for_export(feature_extractor, (None,) + mnist_util.INPUT_SHAPE, set_feature_extractor_hparams, default_hparams) tf.saved_model.save(exportable, FLAGS.export_dir) if __name__ == '__main__': app.run(main)
[ "TheSiebi@users.noreply.github.com" ]
TheSiebi@users.noreply.github.com
938bf1cf1edfa71a44cf21caf52bffa5190185a1
b77cc1448ae2c68589c5ee24e1a0b1e53499e606
/recruitment/models.py
d7d2e7e6ae37db258fa3fa7f13aad1e057ab63fb
[]
no_license
PregTech-c/Hrp_system
a5514cf6b4c778bf7cc58e8a6e8120ac7048a0a7
11d8dd3221497c536dd7df9028b9991632055b21
refs/heads/master
2022-10-09T07:54:49.538270
2018-08-21T11:12:04
2018-08-21T11:12:04
145,424,954
1
1
null
2022-10-01T09:48:53
2018-08-20T13:58:31
JavaScript
UTF-8
Python
false
false
4,915
py
from __future__ import unicode_literals from django.db import models from django.utils import timezone from payroll.models.employee_models import (ServiceLine, Position, EducationLevel, EmployeeProfile) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class District(models.Model): short_name = models.CharField(max_length=4) name = models.CharField(max_length=32) def __str__(self): return self.name class Vacancy(models.Model): VACANCY_TYPE_CHOICES = ( ('PUB', 'Public'), ('INT', 'Internal'), ) GENDER_CHOICES = ( ('A', 'Any'), ('M', 'Male'), ('F', 'Female') ) class Meta: ordering = ['-due_date'] job_title = models.ForeignKey(Position, related_name='vacancies') service_line = models.ForeignKey(ServiceLine, null=True, blank=True) reports_to = models.ForeignKey(Position, null=True, blank=True) due_date = models.DateField() minimum_education = models.CharField(max_length=16, choices=EducationLevel.EDUC_LEVEL_CHOICES, null=True, blank=True) fields_of_education = models.TextField(null=True, blank=True, help_text="Separate with semi-colon (;)") skills = models.TextField(max_length=256, null=True, blank=True) number_of_positions = models.IntegerField(default=1) job_description = models.TextField() vacancy_type = models.CharField(max_length=8, choices=VACANCY_TYPE_CHOICES, default=VACANCY_TYPE_CHOICES[0][1]) duty_station = models.ForeignKey(District, null=True, blank=True) min_age = models.IntegerField(null=True, blank=True) max_age = models.IntegerField(null=True, blank=True) experience_years = models.IntegerField(null=True, blank=True) required_gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M') def __str__(self): return self.job_title.name class EvaluationStage(models.Model): STATUS_CHOICES = (('OPEN', 'Open'), ('CLOSED', 'Closed')) class Meta: unique_together = ('vacancy', 'name') vacancy = models.ForeignKey(Vacancy, related_name='evaluation_stages') name = models.CharField(max_length=32) description = models.CharField(max_length=64) status = models.CharField(max_length=8, choices=STATUS_CHOICES, default=STATUS_CHOICES[0][0], blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(EmployeeProfile) def __str__(self): return self.name class JobApplication(models.Model): APPLICATION_SOURCE_CHOICES = ( ('NP', 'Newspaper'), ('REF', 'Referral'), ('WEB', 'Website') ) QUALIFICATION_CHOICES = ( ('PRIM', 'Primary Level'), ('OLEV', 'Secondary Level'), ('ALEV', 'Advanced Level'), ('DEG', 'Bachelors Degree'), ('DIPL', 'Diploma'), ('MAST', 'Masters Degree'), ('PHD', 'Phd'), ) class Meta: ordering = ['-id'] employee = models.ForeignKey(EmployeeProfile, related_name="job_applications", null=True, blank=True) vacancy = models.ForeignKey(Vacancy, related_name='applications') first_name = models.CharField(max_length=32) surname = models.CharField(max_length=32) other_names = models.CharField(max_length=64, null=True, blank=True) date_of_birth = models.DateField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M') # source = models.CharField(max_length=16, choices=APPLICATION_SOURCE_CHOICES, # default='NP') email = models.EmailField() tel_number = models.CharField(max_length=16) qualification = models.CharField(max_length=16, choices=QUALIFICATION_CHOICES, null=True, blank=True) experience_years = models.DecimalField(decimal_places=1, max_digits=3) education_fields = models.TextField() remarks = models.TextField() created_at = models.DateTimeField(auto_now_add=True) evaluation_stage = models.ForeignKey(EvaluationStage, null=True, blank=True) @property def age_of_applicant(self): td = timezone.now().date() - self.date_of_birth return int(td.days/365.2425) def get_fullname(self): return "{} {} {}".format( self.surname, self.first_name if self.first_name else '', self.other_names if self.other_names else '' ) def upload_directory(instance, filename): return 'payroll/static/uploads/{}/{}'.format( 'recruitment', filename) class JobApplicationDocument(models.Model): job_application = models.ForeignKey(JobApplication, related_name='documents') document = models.FileField(upload_to=upload_directory, #'uploads/recrutment/%Y/%m/%d/', null=True, blank=True) description = models.CharField(max_length=32, blank=True) def filename(self): import os return os.path.basename(self.document.name)
[ "imugabi64@yahoo.com" ]
imugabi64@yahoo.com
98efa4edbe42174f87ea94922bd37dc1115748e2
c4ff5cf4a4af5883ef703c73daeaf353c809e75b
/Mask R-CNN/mrcnn/计算掩膜长宽和面积.py
d2c2bf5bb26dd4e0a15d108f7f66059ea754ff13
[]
no_license
ZengyuanYu/wheat-segmentation
eba375d1f8becdb8b2966d6aee861daa2255b67a
c9e9064f49fb7e6125d80124f4a8678a64d10952
refs/heads/master
2020-04-25T22:04:29.685070
2019-03-01T09:21:22
2019-03-01T09:21:22
173,100,054
1
0
null
null
null
null
UTF-8
Python
false
false
8,874
py
#! /usr/bin/env python # -*- coding:utf-8 -*- # Author: Xiaoyu #! /usr/bin/env python # -*- coding:utf-8 -*- # Author: Xiaoyu import os import sys import random import math import numpy as np import skimage.io import matplotlib import matplotlib.pyplot as plt import cv2 import glob import pandas as pd # Root directory of the project ROOT_DIR = os.path.abspath("../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library sys.path.append('/home/yu/Mask_RCNN/mrcnn') # To find local version of the library from mrcnn import utils import mrcnn.model as modellib from mrcnn import visualize # Import Maritime config sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version #from pycocotools.coco import COCO import maritime from matplotlib.pyplot import imshow # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT_DIR, "logs") # Local path to trained weights file COCO_MODEL_PATH = os.path.join(ROOT_DIR, "/home/yu/Mask_RCNN/model/resnet101-110-every.h5") # Directory of images to run detection on # IMAGE_DIR = os.path.join(ROOT_DIR, "test_images/wheat/000002") IMAGE_DIR = '/home/yu/Mask_RCNN/test_images/wheat' # path = '/home/yu/Mask_RCNN/test_images/wheat/000002' class InferenceConfig(maritime.MaritimeConfig): # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # PRN_NMS_THRESHOLD = 0.5 config = InferenceConfig() # config.display() # Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # Load weights trained on MS-COCO model.load_weights(COCO_MODEL_PATH, by_name=True) # COCO Class names # Index of the class in the list is its ID. For example, to get ID of # the teddy bear class, use: class_names.index('teddy bear') class_names = ['undetected', 'wheat'] colors = [[0, 0, 0], [0, 255, 0]] def list2csv(list, save_path=None, columns=None): data = pd.DataFrame(columns=columns, data=list) data.to_csv(save_path) def get_mask(path): # Override this function to load a mask from your dataset. # Otherwise, it returns an empty mask. labels_path = os.path.join(path, 'labels') print(labels_path) # #Get all .png files in the folder file_path = os.path.join(labels_path, '*.png') file_path = sorted(glob.glob(file_path)) print(file_path) for pic in file_path: mask = skimage.io.imread(str(pic)) return mask def compute_mAP(local,ground_truth): overlap_area=0 mask_area=0 FP=0 FN=0 for i in range(1536): for j in range(2048): if ground_truth[i][j]: mask_area+=1 if local[i][j] == ground_truth[i][j] and ground_truth[i][j] : overlap_area+=1 if local[i][j] and ground_truth[i][j] != local[i][j]: FP+=1 if local[i][j] != ground_truth[i][j] and ground_truth[i][j]: FN+=1 print("overlap_area", overlap_area) print("mask_area:", mask_area) TP=overlap_area P=TP/(TP+FP) R=TP/(TP+FN) f1_measure=2*P*R/(P+R) return P, R, f1_measure def main(): # 对于每张图片的预测结果放入到指定列表中 information = [] all_instance_true_list = [] for id in range(0, 1): # 定义一个列表,将ROI, W, H, area, percent, confidence存到此中 mask_information = [] # 从测试图片中依次进行预测 if id < 10: image_folder_path = os.path.join(IMAGE_DIR, '00000{}'.format(id)) else: image_folder_path = os.path.join(IMAGE_DIR, '0000{}'.format(id)) original_mask = get_mask(image_folder_path) file_names = next(os.walk(image_folder_path))[2] print(file_names) image_path = os.path.join(image_folder_path, random.choice(file_names)) print(image_path) image = skimage.io.imread(image_path) print("file_names---->", file_names, "image_path---->", image_path) h, w = image.shape[:2] print(w, h) # Run detection results = model.detect([image], verbose=1) # Visualize results r = results[0] mask_ndarray = r['masks'] mask_list = mask_ndarray.tolist() # --------------------- import pandas as pd pic = pd.DataFrame(mask_list) h, w = pic.shape[:2] print("w和h", w, h) roi_ndarray = r['rois'] roi_list = roi_ndarray.tolist() print("y1,x1,y2,x2", roi_list) print(len(roi_list)) # print(roi_list[0]) # 加入ROI # for i in range(len(roi_list[0])): # mask_information.append(roi_list[0][i]) bbox_width = roi_list[0][3] - roi_list[0][1] bbox_heigh = roi_list[0][2] - roi_list[0][0] mask_information = roi_list[0].copy() mask_information.append(bbox_width) mask_information.append(bbox_heigh) # val_roi_list.append(roi_list) # ------计算mask面积和百分比----- count = 0 No_count = 0 for i in range(len(r['masks'])): for j in range(len(r['masks'][i])): if r['masks'][i][j].any() == True: count += 1 else: No_count += 1 print("r['masks']的长度为:", i, len(r['masks'])) precent = count/(w*h) print('掩膜的占比为:{}%'.format(precent*100)) # pixel = 200/1411 pixel = 1.032031261388592636e-01 mask_area = w*h*pixel*pixel*precent print("面积为:{}平方毫米".format(mask_area)) # 加入面积占比和面积 mask_information.append(precent*100) mask_information.append(mask_area) # -------得到每列的值然后判断------ count = 0 No_count = 0 Max_line_list = [] for i in range(w): for j in range(h): if r['masks'][j][i].any() == True: count += 1 else: No_count += 1 # 每训练一次 Max_line_list.append(count) # 每记录一次 count清零一次 count = 0 mask_width = max(Max_line_list)*pixel # # 绘制每列的mask宽度 # index = np.arange(0, len(Max_line_list), 1) # plt.figure() # plt.plot(index, Max_line_list) # plt.show() # --------得到每行的值然后判断---------- count = 0 No_count = 0 Max_row_list = [] for i in range(h): for j in range(w): if r['masks'][i][j].any() == True: count += 1 else: No_count += 1 Max_row_list.append(count) # 每记录一次 count清零一次 count = 0 mask_height = max(Max_row_list)*pixel # # 绘制每列的mask宽度 # index = np.arange(0, len(Max_row_list), 1) # plt.figure() # plt.plot(index, Max_row_list) # plt.show() # ------------------- # -----显示预测mask的长和宽 print("预测得到mask的宽为:{}mm,高为:{}mm".format(mask_width, mask_height)) # 加入宽、高 mask_information.append(mask_width) mask_information.append(max(Max_line_list)) mask_information.append(mask_height) mask_information.append(max(Max_row_list)) print(r['class_ids']) # print(r) print("confidence------->", r['scores']) mask_information.append(r['scores'].tolist()[0]) # # 显示全部信息 # visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], # class_names, r['scores']) print(r['masks'].shape) instance_true = 0 instance_true_list = [] for instance_num in range(r['masks'].shape[2]): for i in range(r['masks'].shape[1]): for j in range(r['masks'].shape[0]): if r['masks'][j][i][instance_num]== True: instance_true += 1 else: pass instance_true_list.append(instance_true) instance_true = 0 print(instance_true_list) all_instance_true_list.append(instance_true_list) # visualize.display_instances_yzy(image, r['rois'], r['masks'], r['class_ids'], # class_names, r['scores'], save_num=id) df = pd.DataFrame(all_instance_true_list) df.to_csv('result.csv') file = open('file_name.txt', 'w') file.write(str(all_instance_true_list)) file.close() if __name__ == '__main__': main()
[ "1952284157@qq.com" ]
1952284157@qq.com
75d0a5df0a742b764667caa2921eb78e951f0352
625a2b46caf94a8bfb1afdbc1b933cd19aaafc33
/googoo2.py
1d6ed3712b44ce201725c1f455955a635684e8da
[]
no_license
smilu97/SoftwareStartClass
4118e5c80d0f8253785aa2ecb72db0935c457fcb
df41a2e93a315ab155e0995132a66a9e4dc86ef4
refs/heads/master
2020-12-24T21:21:22.779636
2016-05-04T07:42:35
2016-05-04T07:42:35
58,031,445
0
0
null
null
null
null
UTF-8
Python
false
false
1,333
py
import random a_until = input() b_until = 10 if a_until == 123456 : print 'You found a easteregg' print 'Try to guess my number!' gn = random.randint(1,10000) un = -1 while gn != un : un = input('number? : ') if(un > gn) : print 'Too big' elif(un < gn) : print 'Too small' elif(un == gn) : print 'Yes!!' exit() if a_until == 654321 : print 'You found a easteregg' print 'I will guess your number' min = 0 max = 5 findmax = True finded = False while findmax == True : if finded == True : break; print str(max) + '?' inputvalue = raw_input() if inputvalue == 'small' : findmax = False; elif inputvalue == 'big' : max = max * 2 elif inputvalue == 'correct' : print 'Wow...' finded = True while finded == False : mid = int((min+max)/2) print str(mid) + '?' inputvalue = raw_input() if inputvalue == 'small' : max = mid elif inputvalue == 'big' : min = mid elif inputvalue == 'correct' : print 'Yes!!' finded = True exit() def print_googoo(first, second) : for i in range(1,first) : for j in range(1, second) : print str(i)+'*'+str(j)+'='+str(i*j) # print_googoo(a_until,b_until) a = 1 while a<a_until : b = 1 print '*'*10 + str(a) + 'dan' + '*'*10 while b<b_until : print str(a)+'*'+str(b)+'='+str(a*b) b = b + 1 a = a + 1 print '*'*24
[ "smilup2244@gmail.com" ]
smilup2244@gmail.com
54718fced5aa9042bbc2155ec342bb32c5c94923
a5e6ce10ff98539a94a5f29abbc053de9b957cc6
/competition/20191019/d.py
7532b8635b4abeaabced44c4e2eea7583d904bb3
[]
no_license
shimaw28/atcoder_practice
5097a8ec636a9c2e9d6c417dda5c6a515f1abd9c
808cdc0f2c1519036908118c418c8a6da7ae513e
refs/heads/master
2020-07-26T10:59:51.927217
2020-06-13T11:53:19
2020-06-13T11:53:19
208,622,939
0
0
null
null
null
null
UTF-8
Python
false
false
223
py
N = int(input()) L = [int(i) for i in input().split()] import bisect L.sort() ans = 0 for i in range(N-2): for j in range(i+1, N-1): idx = bisect.bisect_left(L, L[i]+L[j]) ans += (idx-(j+1)) print(ans)
[ "shima.w28@gmail.com" ]
shima.w28@gmail.com
b923bd02e0ee500e12d3202dc483f6915cc19651
de4d88db6ea32d20020c169f734edd4b95c3092d
/aiotdlib/api/functions/get_login_url.py
56c3af78020b2f5c644a8f4e0f93ebbde87ab0d3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
thiagosm/aiotdlib
5cc790a5645f7e4cc61bbd0791433ed182d69062
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
refs/heads/main
2023-08-15T05:16:28.436803
2021-10-18T20:41:27
2021-10-18T20:41:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,574
py
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # # # =============================================================================== # from __future__ import annotations from pydantic import Field from ..base_object import BaseObject class GetLoginUrl(BaseObject): """ Returns an HTTP URL which can be used to automatically authorize the user on a website after clicking an inline button of type inlineKeyboardButtonTypeLoginUrl. Use the method getLoginUrlInfo to find whether a prior user confirmation is needed. If an error is returned, then the button must be handled as an ordinary URL button :param chat_id: Chat identifier of the message with the button :type chat_id: :class:`int` :param message_id: Message identifier of the message with the button :type message_id: :class:`int` :param button_id: Button identifier :type button_id: :class:`int` :param allow_write_access: True, if the user allowed the bot to send them messages :type allow_write_access: :class:`bool` """ ID: str = Field("getLoginUrl", alias="@type") chat_id: int message_id: int button_id: int allow_write_access: bool @staticmethod def read(q: dict) -> GetLoginUrl: return GetLoginUrl.construct(**q)
[ "pylakey@protonmail.com" ]
pylakey@protonmail.com
ce2896ad06aa191757ad56558bbe1b5d4d665cbc
a9e60d0e5b3b5062a81da96be2d9c748a96ffca7
/configurations/lab44-config/scripts/BeamlineI06/Users/diffcalc_i06_4circle.py
3752a2e626b109217f99c1116b9d145d772f50f8
[]
no_license
openGDA/gda-diamond
3736718596f47607335ada470d06148d7b57526e
bbb64dcfd581c30eddb210c647db5b5864b59166
refs/heads/master
2023-08-16T08:01:11.075927
2023-08-15T16:01:52
2023-08-15T16:01:52
121,757,699
4
1
null
null
null
null
UTF-8
Python
false
false
1,373
py
# See notes in: http://wiki.diamond.ac.uk/Wiki/Wiki.jsp?page=I06_Diffcalc try: import diffcalc except ImportError: from gda.configuration.properties import LocalProperties import sys diffcalc_path = LocalProperties.get("gda.install.git.loc") + '/diffcalc.git' sys.path = [diffcalc_path] + sys.path print diffcalc_path + ' added to GDA Jython path.' import diffcalc from gdascripts.pd.dummy_pds import DummyPD from diffcalc.gdasupport.factory import create_objects, add_objects_to_namespace CREATE_DUMMY_AXES = False if CREATE_DUMMY_AXES: print "!!! Staring dummy diffcalc with tth, th, chi, phi and en." tth = DummyPD('tth') th = DummyPD('th') en = DummyPD('en') en(1500) diffcalc_energy=en else: print "!!! Staring LIVE diffcalc with th(dd2th), th(ddth), chi(dummy), phi(dummy) and denergy." tth = dd2th th = ddth diffcalc_energy=denergy chi = DummyPD('chi') phi = DummyPD('phi') diffcalcObjects = create_objects( axis_scannable_list = [tth, th, chi, phi], energy_scannable = diffcalc_energy, energy_scannable_multiplier_to_get_KeV = .001, geometry = 'fourc', hklverbose_virtual_angles_to_report=('2theta','Bin','Bout','azimuth') ) #demoCommands = [] #diffcalcObjects['diffcalcdemo'].commands = demoCommands add_objects_to_namespace(diffcalcObjects, globals()) hkl.level = 6
[ "fajin.yuan@diamond.ac.uk" ]
fajin.yuan@diamond.ac.uk
81c5de514378a57338ac86399710a2a2b9fa1e95
17331ee8285a1f19e4ca1abd89dac64da381959d
/03-accessing-web-data/extracting_data_xml.py
208cf4bf87e729149483bec35278bbab8946d4bc
[]
no_license
chaochaocodes/PY4E
3681367ce548fe9a423adb895fe76efda60521bb
09930f6187c3388b61903680bcd4a1533b0b4f82
refs/heads/main
2023-03-28T11:29:09.209120
2021-04-01T02:34:58
2021-04-01T02:34:58
333,506,525
0
0
null
null
null
null
UTF-8
Python
false
false
1,472
py
''' Extracting Data from XML In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file. <comment> <name>Matthias</name> <count>97</count> </comment> We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. Sample data: http://py4e-data.dr-chuck.net/comments_42.xml (Sum=2553) Actual data: http://py4e-data.dr-chuck.net/comments_1144983.xml (Sum ends with 3) ''' import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE while True: url = input('Enter location: ') if len(url) < 1: break print('Retrieving', url) xml = urllib.request.urlopen(url, context=ctx) data = xml.read() print('Retrieved', len(data), 'characters') tree = ET.fromstring(data) comments = tree.findall('.//comment') counts = tree.findall('.//count') print('Count:', len(counts)) total = 0 for count in comments: count = count.find('count').text total += int(count) print('Sum:', total) break
[ "57464564+chaochaocodes@users.noreply.github.com" ]
57464564+chaochaocodes@users.noreply.github.com
b2d570a63a13b28c4dd3ba8334a77947e844fd44
5492859d43da5a8e292777c31eace71e0a57dedf
/user/admin.py
f807881a567d5d1c59dc38216d12dd9d167794b3
[ "MIT" ]
permissive
akindele214/181hub_2
93ad21dc6d899b6c56fbe200354b1678bb843705
48b8814b5f66ad87f9a54721506076ddf70fe9bc
refs/heads/master
2022-12-13T01:15:07.925556
2020-05-19T09:39:57
2020-05-19T09:39:57
196,470,605
1
1
MIT
2022-12-08T01:22:55
2019-07-11T22:04:42
Python
UTF-8
Python
false
false
724
py
from django.contrib import admin from .models import Profile, Monetization, UserEmailRequest, Suggestion_Report # Register your models here. class UserAdmin(admin.ModelAdmin): list_display = ('user', 'id', 'user_id') class MonAdmin(admin.ModelAdmin): list_display = ('user', 'amount', 'views', 'status', 'account_name', 'bank') class SuggestAdmin(admin.ModelAdmin): list_display = ('date', 'content') class EmailRequestAdmin(admin.ModelAdmin): list_display = ('sender', 'receiver', 'ref_code','date_added') admin.site.register(Profile, UserAdmin) admin.site.register(Monetization, MonAdmin) admin.site.register(UserEmailRequest, EmailRequestAdmin) admin.site.register(Suggestion_Report, SuggestAdmin)
[ "yaomingnakel@gmail.com" ]
yaomingnakel@gmail.com
2a9e0963993064c76e3f5f9de8b5a7bb88ef5f92
549270020f6c8724e2ef1b12e38d11b025579f8d
/recipes/logr/0.1.0/conanfile.py
967c8e88b68f965f50bf1e673113d8e6341a57de
[ "MIT" ]
permissive
conan-io/conan-center-index
1bcec065ccd65aa38b1fed93fbd94d9d5fe6bc43
3b17e69bb4e5601a850b6e006e44775e690bac33
refs/heads/master
2023-08-31T11:34:45.403978
2023-08-31T11:13:23
2023-08-31T11:13:23
204,671,232
844
1,820
MIT
2023-09-14T21:22:42
2019-08-27T09:43:58
Python
UTF-8
Python
false
false
4,011
py
from conan import ConanFile from conan.errors import ConanInvalidConfiguration from conan.tools.microsoft import check_min_vs, is_msvc_static_runtime, is_msvc from conan.tools.files import apply_conandata_patches, export_conandata_patches, get, copy, rmdir from conan.tools.build import check_min_cppstd from conan.tools.scm import Version from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout import os required_conan_version = ">=1.53.0" class LogrConan(ConanFile): name = "logr" description = "Logger frontend substitution for spdlog, glog, etc for server/desktop applications" license = "BSD-3-Clause" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github.com/ngrodzitski/logr" topics = ("logger", "development", "util", "utils") package_type = "header-library" settings = "os", "arch", "compiler", "build_type" options = { "backend": ["spdlog", "glog", "log4cplus", "log4cplus-unicode", None], } default_options = { "backend": "spdlog", } @property def _min_cppstd(self): return 17 @property def _compilers_minimum_version(self): return { "gcc": "7", "clang": "7", "apple-clang": "10", "Visual Studio": "16", "msvc": "192", } def export_sources(self): export_conandata_patches(self) def layout(self): cmake_layout(self, src_folder="src") def requirements(self): self.requires("fmt/9.1.0") if self.options.backend == "spdlog": self.requires("spdlog/1.11.0") elif self.options.backend == "glog": self.requires("glog/0.6.0") elif self.options.backend in ["log4cplus", "log4cplus-unicode"]: self.requires("log4cplus/2.0.5") def package_id(self): self.info.clear() def validate(self): if self.settings.compiler.get_safe("cppstd"): check_min_cppstd(self, self._min_cppstd) minimum_version = self._compilers_minimum_version.get(str(self.settings.compiler), False) if minimum_version and Version(self.settings.compiler.version) < minimum_version: raise ConanInvalidConfiguration( f"{self.ref} requires C++{self._min_cppstd}, which your compiler does not support." ) if self.options.backend == "log4cplus" and self.options["log4cplus"].unicode: raise ConanInvalidConfiguration("backend='log4cplus' requires log4cplus:unicode=False") elif self.options.backend == "log4cplus-unicode" and not self.options["log4cplus"].unicode: raise ConanInvalidConfiguration("backend='log4cplus-unicode' requires log4cplus:unicode=True") def source(self): get(self, **self.conan_data["sources"][self.version], strip_root=True) def generate(self): tc = CMakeToolchain(self) tc.cache_variables["LOGR_WITH_SPDLOG_BACKEND"] = self.options.backend == "spdlog" tc.cache_variables["LOGR_WITH_GLOG_BACKEND"] = self.options.backend == "glog" tc.cache_variables["LOGR_WITH_LOG4CPLUS_BACKEND"] = self.options.backend in ["log4cplus", "log4cplus-unicode"] tc.cache_variables["LOGR_INSTALL"] = True tc.cache_variables["LOGR_BUILD_TESTS"] = False tc.cache_variables["LOGR_BUILD_EXAMPLES"] = False tc.cache_variables["LOGR_BUILD_BENCHMARKS"] = False tc.generate() dpes = CMakeDeps(self) dpes.generate() def build(self): apply_conandata_patches(self) cmake = CMake(self) cmake.configure() cmake.build() def package(self): copy(self, pattern="LICENSE", dst=os.path.join(self.package_folder, "licenses"), src=self.source_folder) cmake = CMake(self) cmake.install() rmdir(self, os.path.join(self.package_folder, "lib")) def package_info(self): self.cpp_info.bindirs = [] self.cpp_info.libdirs = []
[ "noreply@github.com" ]
conan-io.noreply@github.com
1636eedda11d84791b0a596bc3cca51a8acf751e
b5cc6d7b5f7ccea36fce4eab961979404414f8b0
/kent-report/py/matrix_scaling.py
5aec834ea62a3306e75f6bd37e8e54ef70ea1205
[]
no_license
MiroK/cutFEM-beam
adf0c925dbe64b370dab48e82335617450675f5d
2fb3686804e836d4031fbf231a36a0f9ac8a3012
refs/heads/master
2021-01-21T23:54:32.868307
2015-02-14T13:14:59
2015-02-14T13:14:59
25,625,143
0
0
null
null
null
null
UTF-8
Python
false
false
2,097
py
from eigen_poisson import mass_matrix as Meig1d from eigen_poisson import laplacian_matrix as Aeig1d from shen_poisson import mass_matrix as Mshen1d from shen_poisson import laplacian_matrix as Ashen1d import numpy as np from numpy.linalg import cond # Build 2d matrices def Meig2d(n): '2d mass matrix w.r.t Eigen basis.' M = Meig1d(n) return np.kron(M, M) def Aeig2d(n): '2d stiffness matrix w.r.t Eigen basis.' A = Aeig1d(n) M = Meig1d(n) return np.kron(A, M) + np.kron(M, A) def Mshen2d(n): '2d mass matrix w.r.t Shen basis.' M = Mshen1d(n) return np.kron(M, M) def Ashen2d(n): '2d stiffness matrix w.r.t Shen basis.' A = Ashen1d(n) M = Mshen1d(n) return np.kron(A, M) + np.kron(M, A) # ----------------------------------------------------------------------------- if __name__ == '__main__': from matplotlib import rc rc('text', usetex=True) rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) import matplotlib.pyplot as plt ns = np.arange(2, 20) # Plot 2d if False: condMe = np.array([cond(Meig1d(n)) for n in ns]) condAe = np.array([cond(Aeig1d(n)) for n in ns]) condMs = np.array([cond(Mshen1d(n)) for n in ns]) condAs = np.array([cond(Ashen1d(n)) for n in ns]) else: condMe = np.array([cond(Meig2d(n)) for n in ns]) condAe = np.array([cond(Aeig2d(n)) for n in ns]) condMs = np.array([cond(Mshen2d(n)) for n in ns]) condAs = np.array([cond(Ashen2d(n)) for n in ns]) # Common marker == commmon basis, Common color == common matrix plt.figure() plt.loglog(ns, condMe, label='$M_E$', color='b', marker='s', linestyle='--') plt.loglog(ns, condAe, label='$A_E$', color='g', marker='s', linestyle='--') plt.loglog(ns, condMs, label='$M_S$', color='b', marker='o', linestyle='--') plt.loglog(ns, condAs, label='$A_S$', color='g', marker='o', linestyle='--') plt.legend(loc='best') plt.xlabel('$n$') plt.ylabel('$\kappa$') plt.savefig('matrix_scaling_2d.pdf') plt.show()
[ "miroslav.kuchta@gmail.com" ]
miroslav.kuchta@gmail.com
1d0c9dd88b03bf9ef6dfcf2cfddf960be98a9378
5a017fc861db92e3a2919f260d54f1301afbb3e5
/MIDI Remote Scripts/pushbase/note_settings_component.py
abedfa3f6b3dbb4b81db78835f310b635f15523b
[]
no_license
kera67/livepy_diff_ten
8d8d0f3b76048f1fe5d4c0fbc02549dc922c7d5b
12a0af9e9c57d0721af5036ce23af549df2c95f0
refs/heads/master
2023-07-14T18:26:33.591915
2020-11-19T07:50:28
2020-11-19T07:50:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
19,718
py
from __future__ import absolute_import, print_function, unicode_literals import math from functools import partial from itertools import ifilter, imap, chain, izip_longest from ableton.v2.base import clamp, find_if, forward_property, listenable_property, listens, listens_group, liveobj_valid, task from ableton.v2.control_surface import defaults, Component from ableton.v2.control_surface.control import ButtonControl, ControlManager, control_list, EncoderControl, StepEncoderControl from ableton.v2.control_surface.elements import DisplayDataSource from ableton.v2.control_surface.mode import ModesComponent, Mode, AddLayerMode from .consts import CHAR_ELLIPSIS, GRAPH_VOL class NoteSettingBase(ControlManager): __events__ = (u'setting_changed',) attribute_index = -1 encoder = EncoderControl() def __init__(self, grid_resolution = None, *a, **k): super(NoteSettingBase, self).__init__(*a, **k) self._min_max_value = None self._grid_resolution = grid_resolution def encoder_value_to_attribute(self, value): raise NotImplementedError @property def step_length(self): if self._grid_resolution: return self._grid_resolution.step_length return 1.0 def set_min_max(self, min_max_value): self._min_max_value = min_max_value @encoder.value def encoder(self, value, _): self._on_encoder_value_changed(value) def _on_encoder_value_changed(self, value): self.notify_setting_changed(self.attribute_index, self.encoder_value_to_attribute(value)) class NoteSetting(NoteSettingBase): def __init__(self, *a, **k): super(NoteSetting, self).__init__(*a, **k) self.value_source = DisplayDataSource() self.label_source = DisplayDataSource() self.label_source.set_display_string(self.get_label()) def get_label(self): raise NotImplementedError def attribute_min_max_to_string(self, min_value, max_value): raise NotImplementedError def set_min_max(self, min_max_value): self.value_source.set_display_string(self.attribute_min_max_to_string(min_max_value[0], min_max_value[1]) if min_max_value else u'-') RANGE_STRING_FLOAT = u'%.1f' + CHAR_ELLIPSIS + u'%.1f' RANGE_STRING_INT = u'%d' + CHAR_ELLIPSIS + u'%d' def step_offset_percentage(step_length, value): return int(round((value - int(value / step_length) * step_length) / step_length * 100)) def step_offset_min_max_to_string(step_length, min_value, max_value): min_value = step_offset_percentage(step_length, min_value) max_value = step_offset_percentage(step_length, max_value) if min_value == max_value: return u'%d%%' % min_value return (RANGE_STRING_INT + u'%%') % (min_value, max_value) def convert_value_to_graphic(value, value_range): value_bar = GRAPH_VOL graph_range = float(len(value_bar)) value = clamp(int(value / value_range * graph_range), 0, len(value_bar) - 1) display_string = value_bar[value] return display_string class NoteNudgeSetting(NoteSetting): attribute_index = 1 def get_label(self): return u'Nudge' def encoder_value_to_attribute(self, value): return self.step_length * value def attribute_min_max_to_string(self, min_value, max_value): return step_offset_min_max_to_string(self.step_length, min_value, max_value) class NoteLengthCoarseSetting(NoteSetting): attribute_index = 2 encoder = StepEncoderControl() def get_label(self): return u'Length -' def attribute_min_max_to_string(self, min_value, max_value): min_value = min_value / self.step_length max_value = max_value / self.step_length def format_string(value): num_non_decimal_figures = int(math.log10(value)) if value > 0 else 0 return u'%%.%dg' % (num_non_decimal_figures + 2,) if min_value == max_value: return (format_string(min_value) + u' stp') % min_value return (format_string(min_value) + CHAR_ELLIPSIS + format_string(max_value)) % (min_value, max_value) def encoder_value_to_attribute(self, value): return self.step_length * value @encoder.value def encoder(self, value, _): self._on_encoder_value_changed(value) class NoteLengthFineSetting(NoteSetting): attribute_index = 2 def get_label(self): return u'Fine' def encoder_value_to_attribute(self, value): return self.step_length * value def attribute_min_max_to_string(self, min_value, max_value): value = step_offset_percentage(self.step_length, min_value) return convert_value_to_graphic(value, 100.0) class NoteVelocitySetting(NoteSetting): attribute_index = 3 def get_label(self): return u'Velocity' def encoder_value_to_attribute(self, value): return value * 128 def attribute_min_max_to_string(self, min_value, max_value): if int(min_value) == int(max_value): return str(int(min_value)) return RANGE_STRING_INT % (min_value, max_value) class NoteSettingsComponentBase(Component): __events__ = (u'setting_changed', u'full_velocity') full_velocity_button = ButtonControl() def __init__(self, grid_resolution = None, *a, **k): super(NoteSettingsComponentBase, self).__init__(*a, **k) self._settings = [] self._encoders = [] self._create_settings(grid_resolution) def _create_settings(self, grid_resolution): self._add_setting(NoteNudgeSetting(grid_resolution=grid_resolution)) self._add_setting(NoteLengthCoarseSetting(grid_resolution=grid_resolution)) self._add_setting(NoteLengthFineSetting(grid_resolution=grid_resolution)) self._add_setting(NoteVelocitySetting(grid_resolution=grid_resolution)) def _add_setting(self, setting): assert len(self._settings) < 8, u'Cannot show more than 8 settings' self._settings.append(setting) self._update_encoders() self.register_disconnectable(setting) self.register_slot(setting, self.notify_setting_changed, u'setting_changed') @property def number_of_settings(self): return len(self._settings) def set_info_message(self, message): pass def set_encoder_controls(self, encoders): self._encoders = encoders or [] self._update_encoders() def set_min_max(self, index, min_max_value): setting_for_index = [ i for i in self._settings if i.attribute_index == index ] for setting in setting_for_index: setting.set_min_max(min_max_value) @full_velocity_button.pressed def full_velocity_button(self, button): if self.is_enabled(): self.notify_full_velocity() def _update_encoders(self): if self.is_enabled() and self._encoders: for encoder, setting in izip_longest(self._encoders[-len(self._settings):], self._settings): setting.encoder.set_control_element(encoder) else: map(lambda setting: setting.encoder.set_control_element(None), self._settings) def update(self): super(NoteSettingsComponentBase, self).update() self._update_encoders() class NoteSettingsComponent(NoteSettingsComponentBase): def __init__(self, *a, **k): super(NoteSettingsComponent, self).__init__(*a, **k) self._top_data_sources = [ DisplayDataSource() for _ in xrange(8) ] self._bottom_data_sources = [ DisplayDataSource() for _ in xrange(8) ] self._info_data_source = DisplayDataSource() self._create_display_sources() def _create_display_sources(self): self._top_data_sources = [ DisplayDataSource() for _ in xrange(8 - len(self._settings)) ] + [ s.label_source for s in self._settings ] self._bottom_data_sources = [ DisplayDataSource() for _ in xrange(8 - len(self._settings)) ] + [ s.value_source for s in self._settings ] def set_top_display_line(self, display): if self.is_enabled() and display: display.set_data_sources(self._top_data_sources) def set_bottom_display_line(self, display): if self.is_enabled() and display: display.set_data_sources(self._bottom_data_sources) def set_info_display_line(self, display): if self.is_enabled() and display: display.set_data_sources([self._info_data_source]) def set_clear_display_line(self, display): if self.is_enabled() and display: display.reset() def set_info_message(self, message): self._info_data_source.set_display_string(message.rjust(62)) class DetailViewRestorerMode(Mode): u""" Restores the detail view if either only clip view or device view is visible. Has no effect if the detail view is hidden at the point the mode is entered. """ def __init__(self, application = None, *a, **k): super(DetailViewRestorerMode, self).__init__(*a, **k) self._app = application self._view_to_restore = None def enter_mode(self): clip_view_visible = self._app.view.is_view_visible(u'Detail/Clip', False) device_chain_visible = self._app.view.is_view_visible(u'Detail/DeviceChain', False) if clip_view_visible != device_chain_visible: self._view_to_restore = u'Detail/Clip' if clip_view_visible else u'Detail/DeviceChain' def leave_mode(self): try: if self._view_to_restore: self._app.view.show_view(self._view_to_restore) self._view_to_restore = None except RuntimeError: pass def show_clip_view(application): try: view = application.view if view.is_view_visible(u'Detail/DeviceChain', False) and not view.is_view_visible(u'Detail/Clip', False): application.view.show_view(u'Detail/Clip') except RuntimeError: pass class ModeSelector(Component): select_buttons = control_list(ButtonControl, color=u'DefaultButton.Disabled') state_buttons = control_list(ButtonControl, color=u'DefaultButton.Disabled') class NoteEditorSettingsComponent(ModesComponent): initial_encoders = control_list(EncoderControl) encoders = control_list(EncoderControl) def __init__(self, note_settings_component_class = None, automation_component_class = None, grid_resolution = None, initial_encoder_layer = None, encoder_layer = None, *a, **k): super(NoteEditorSettingsComponent, self).__init__(*a, **k) assert encoder_layer assert note_settings_component_class is not None assert automation_component_class is not None self.settings = note_settings_component_class(grid_resolution=grid_resolution, parent=self, is_enabled=False) self.automation = automation_component_class(parent=self, is_enabled=False) self._mode_selector = ModeSelector(parent=self, is_enabled=False) self._visible_detail_view = u'Detail/DeviceChain' self._show_settings_task = self._tasks.add(task.sequence(task.wait(defaults.MOMENTARY_DELAY), task.run(self._show_settings))).kill() self._update_infos_task = self._tasks.add(task.run(self._update_note_infos)).kill() self._settings_modes = ModesComponent(parent=self) self._settings_modes.set_enabled(False) self._settings_modes.add_mode(u'automation', [self.automation, self._mode_selector, partial(self._set_envelope_view_visible, True), partial(show_clip_view, self.application)]) self._settings_modes.add_mode(u'note_settings', [self.settings, self._update_note_infos, self._mode_selector, partial(self._set_envelope_view_visible, False), partial(show_clip_view, self.application)]) self._settings_modes.selected_mode = u'note_settings' self.__on_selected_setting_mode_changed.subject = self._settings_modes self.add_mode(u'disabled', []) self.add_mode(u'about_to_show', [AddLayerMode(self, initial_encoder_layer), (self._show_settings_task.restart, self._show_settings_task.kill)]) self.add_mode(u'enabled', [DetailViewRestorerMode(self.application), AddLayerMode(self, encoder_layer), self._settings_modes]) self.selected_mode = u'disabled' self._editors = [] self._on_detail_clip_changed.subject = self.song.view self._on_selected_track_changed.subject = self.song.view self.__on_full_velocity_changed.subject = self.settings self.__on_setting_changed.subject = self.settings automation_layer = forward_property(u'automation')(u'layer') mode_selector_layer = forward_property(u'_mode_selector')(u'layer') selected_setting = forward_property(u'_settings_modes')(u'selected_mode') @property def step_settings(self): return self._settings_modes @property def editors(self): return self._editors @listenable_property def is_touched(self): return any(imap(lambda e: e and e.is_touched, ifilter(lambda e: self._can_notify_is_touched(e), self.encoders))) def _is_step_held(self): return len(self._active_note_regions()) > 0 def add_editor(self, editor): assert editor != None self._editors.append(editor) self._on_active_note_regions_changed.add_subject(editor) self._on_notes_changed.replace_subjects(self._editors) self.__on_modify_all_notes_changed.add_subject(editor) def set_encoders(self, encoders): self.encoders.set_control_element(encoders) self.settings.set_encoder_controls(encoders) self.automation.set_parameter_controls(encoders) @property def parameter_provider(self): self.automation.parameter_provider @parameter_provider.setter def parameter_provider(self, value): self.automation.parameter_provider = value @listens(u'selected_mode') def __on_selected_setting_mode_changed(self, mode): if mode == u'automation': self.automation.selected_time = self._active_note_regions() def update_view_state_based_on_selected_setting(self, setting): if self.selected_mode == u'enabled' and self.is_touched or setting is None: self._set_settings_view_enabled(False) elif self._is_step_held(): if self.selected_setting == u'automation' and self.automation.can_automate_parameters or self.selected_setting == u'note_settings': self._show_settings() @listens(u'full_velocity') def __on_full_velocity_changed(self): for editor in self._editors: editor.set_full_velocity() @listens(u'setting_changed') def __on_setting_changed(self, index, value): for editor in self._editors: self._modify_note_property_offset(editor, index, value) def _modify_note_property_offset(self, editor, index, value): if index == 1: editor.set_nudge_offset(value) elif index == 2: editor.set_length_offset(value) elif index == 3: editor.set_velocity_offset(value) def _set_envelope_view_visible(self, visible): clip = self.song.view.detail_clip if liveobj_valid(clip): if visible: clip.view.show_envelope() else: clip.view.hide_envelope() def _set_settings_view_enabled(self, should_show_view): really_show_view = should_show_view and self.automation.can_automate_parameters if self.selected_setting == u'automation' else should_show_view if really_show_view: if self.selected_mode == u'disabled': self.selected_mode = u'about_to_show' else: self._hide_settings() def _active_note_regions(self): all_active_regions = imap(lambda e: e.active_note_regions, self._editors) return list(set(chain.from_iterable(all_active_regions))) @listens_group(u'active_note_regions') def _on_active_note_regions_changed(self, _): if self.is_enabled(): all_steps = self._active_note_regions() self.automation.selected_time = all_steps self._update_note_infos() self._set_settings_view_enabled(len(all_steps) > 0 and self.selected_setting != None or self.is_touched) @listens_group(u'modify_all_notes') def __on_modify_all_notes_changed(self, editor): self.selected_mode = u'about_to_show' if editor.modify_all_notes_enabled else u'disabled' @listens_group(u'notes_changed') def _on_notes_changed(self, editor): self._update_infos_task.restart() @listens(u'detail_clip') def _on_detail_clip_changed(self): self.automation.clip = self.song.view.detail_clip if self.is_enabled() else None @listens(u'selected_track') def _on_selected_track_changed(self): self.selected_mode = u'disabled' @initial_encoders.touched def initial_encoders(self, encoder): if self.selected_mode == u'about_to_show': self._show_settings() @initial_encoders.value def initial_encoders(self, encoder, value): if self.selected_mode == u'about_to_show': self._show_settings() @encoders.touched def encoders(self, encoder): if self._can_notify_is_touched(encoder): self.notify_is_touched() @encoders.released def encoders(self, encoder): if not self.is_touched and not self._is_step_held() and not self._is_edit_all_notes_active(): self._hide_settings() if self._can_notify_is_touched(encoder): self.notify_is_touched() @encoders.value def encoders(self, encoder, value): self._notify_modification() def _can_notify_is_touched(self, encoder): if self.is_enabled(): return self._settings_modes.selected_mode != u'note_settings' or encoder.index >= self.encoders.control_count - self.settings.number_of_settings return False def _is_edit_all_notes_active(self): return find_if(lambda e: e.modify_all_notes_enabled, self._editors) != None def _notify_modification(self): for editor in self._editors: editor.notify_modification() def _update_note_infos(self): if self.settings.is_enabled(): def min_max((l_min, l_max), (r_min, r_max)): return (min(l_min, r_min), max(l_max, r_max)) all_min_max_attributes = filter(None, imap(lambda e: e.get_min_max_note_values(), self._editors)) min_max_values = [(99999, -99999)] * 4 if len(all_min_max_attributes) > 0 else None for min_max_attribute in all_min_max_attributes: for i, attribute in enumerate(min_max_attribute): min_max_values[i] = min_max(min_max_values[i], attribute) for i in xrange(4): self.settings.set_min_max(i, min_max_values[i] if min_max_values else None) self.settings.set_info_message(u'Tweak to add note' if not self._is_edit_all_notes_active() and not min_max_values else u'') def _show_settings(self): if self.selected_mode != u'enabled': self.selected_mode = u'enabled' self._notify_modification() def _hide_settings(self): self.selected_mode = u'disabled' def on_enabled_changed(self): super(NoteEditorSettingsComponent, self).on_enabled_changed() if not self.is_enabled(): self.selected_mode = u'disabled' def update(self): super(NoteEditorSettingsComponent, self).update() if self.is_enabled(): self._on_detail_clip_changed()
[ "aumhaa@gmail.com" ]
aumhaa@gmail.com
69c00bce760359ee971f98708caf1821b7d4f64d
81e6391b9db249296ec84f6524093cf41b581f31
/단계별로 풀어보기/16. 수학3/[2609] 최대공약수와 최소공배수.py
fb8c37e1e3d2c077f89732f90ea2d7ba29967031
[]
no_license
jaeehooon/baekjoon_python
e991be4b510d642f72f625b898d20451dc920d7c
295776309a883338bfbf51c33caf6dc6629493ca
refs/heads/master
2023-04-15T14:22:21.281930
2021-04-26T02:15:09
2021-04-26T02:15:09
294,137,750
1
0
null
null
null
null
UTF-8
Python
false
false
434
py
import sys # 최대공약수 찾기 with 유클리드 호제법 def gcd(a, b): while a != b: if a > b: a -= b else: b -= a return a def lcm(c, d): gcd_val = gcd(c, d) return gcd_val * (c // gcd_val) * (d // gcd_val) if __name__ == '__main__': num_a, num_b = map(int, sys.stdin.readline().rstrip('\n').split()) print(gcd(num_a, num_b)) print(lcm(num_a, num_b))
[ "qlenfr0922@gmail.com" ]
qlenfr0922@gmail.com
631110d151d43400819d832cb1c6a1161eafed59
f9ca7cce3cb020237aef05555554dfeba71db787
/spatial_slim/up_traversal.py
a4eb4f84e2cd8d8fb605484393009e5fa67cf11e
[]
no_license
petrelharp/lineage_plotting
c8391ec0757df86e1ed44e2697d52d96a7bec2b5
d63ac0d4f016380c58860a57c84069a29a16e756
refs/heads/master
2023-09-04T02:41:43.115557
2023-08-15T18:09:48
2023-08-15T18:09:48
189,054,484
0
0
null
null
null
null
UTF-8
Python
false
false
9,649
py
""" Modified from python implementation of the simplify algorithm. """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division import sys import numpy as np import tskit def overlapping_segments(segments): """ Returns an iterator over the (left, right, X) tuples describing the distinct overlapping segments in the specified set. """ S = sorted(segments, key=lambda x: x.left) n = len(S) # Insert a sentinel at the end for convenience. S.append(Segment(sys.float_info.max, 0)) right = S[0].left X = [] j = 0 while j < n: # Remove any elements of X with right <= left left = right X = [x for x in X if x.right > left] if len(X) == 0: left = S[j].left while j < n and S[j].left == left: X.append(S[j]) j += 1 j -= 1 right = min(x.right for x in X) right = min(right, S[j + 1].left) yield left, right, X j += 1 while len(X) > 0: left = right X = [x for x in X if x.right > left] if len(X) > 0: right = min(x.right for x in X) yield left, right, X class Segment(object): """ A class representing a single segment. Each segment has a left and right, denoting the loci over which it spans, a node and a next, giving the next in the chain. The node it records is the *output* node ID. """ def __init__(self, left=None, right=None, node=None, next=None): self.left = left self.right = right self.node = node self.next = next def __str__(self): s = "({}-{}->{}:next={})".format( self.left, self.right, self.node, repr(self.next)) return s def __repr__(self): return repr((self.left, self.right, self.node)) def __lt__(self, other): return (self.left, self.right, self.node) < (other.left, other.right, self.node) class TreeClimber(object): """ Traversed up a tree sequence, keeping track of who is ancestral to the samples. """ def __init__(self, ts, sample) self.ts = ts self.n = len(sample) self.sequence_length = ts.sequence_length self.A_head = [None for _ in range(ts.num_nodes)] self.A_tail = [None for _ in range(ts.num_nodes)] self.tables = tskit.TableCollection(sequence_length=ts.sequence_length) self.edge_buffer = {} self.node_id_map = np.zeros(ts.num_nodes, dtype=np.int32) - 1 self.samples = set(sample) for sample_id in sample: output_id = self.record_node(sample_id, is_sample=True) self.add_ancestry(sample_id, 0, self.sequence_length, output_id) def record_node(self, input_id, is_sample=False): """ Adds a new node to the output table corresponding to the specified input node ID. """ node = self.ts.node(input_id) flags = node.flags # Need to zero out the sample flag flags &= ~tskit.NODE_IS_SAMPLE if is_sample: flags |= tskit.NODE_IS_SAMPLE output_id = self.tables.nodes.add_row( flags=flags, time=node.time, population=node.population, metadata=node.metadata, individual=node.individual) self.node_id_map[input_id] = output_id return output_id def rewind_node(self, input_id, output_id): """ Remove the mapping for the specified input and output node pair. This is done because there are no edges referring to the node. """ assert output_id == len(self.tables.nodes) - 1 assert output_id == self.node_id_map[input_id] self.tables.nodes.truncate(output_id) self.node_id_map[input_id] = -1 def flush_edges(self): """ Flush the edges to the output table after sorting and squashing any redundant records. """ num_edges = 0 for child in sorted(self.edge_buffer.keys()): for edge in self.edge_buffer[child]: self.tables.edges.add_row(edge.left, edge.right, edge.parent, edge.child) num_edges += 1 self.edge_buffer.clear() return num_edges def record_edge(self, left, right, parent, child): """ Adds an edge to the output list. """ if child not in self.edge_buffer: self.edge_buffer[child] = [tskit.Edge(left, right, parent, child)] else: last = self.edge_buffer[child][-1] if last.right == left: last.right = right else: self.edge_buffer[child].append(tskit.Edge(left, right, parent, child)) def print_state(self): print(".................") print("Ancestors: ") num_nodes = len(self.A_tail) for j in range(num_nodes): print("\t", j, "->", end="") x = self.A_head[j] while x is not None: print("({}-{}->{})".format(x.left, x.right, x.node), end="") x = x.next print() print("Node ID map: (input->output)") for input_id, output_id in enumerate(self.node_id_map): print("\t", input_id, "->", output_id) print("Output:") print(self.tables) self.check_state() def add_ancestry(self, input_id, left, right, node): tail = self.A_tail[input_id] if tail is None: x = Segment(left, right, node) self.A_head[input_id] = x self.A_tail[input_id] = x else: if tail.right == left and tail.node == node: tail.right = right else: x = Segment(left, right, node) tail.next = x self.A_tail[input_id] = x def merge_labeled_ancestors(self, S, input_id): """ All ancestry segments in S come together into a new parent. The new parent must be assigned and any overlapping segments coalesced. """ output_id = self.node_id_map[input_id] is_sample = output_id != -1 if is_sample: # Free up the existing ancestry mapping. x = self.A_tail[input_id] assert x.left == 0 and x.right == self.sequence_length self.A_tail[input_id] = None self.A_head[input_id] = None prev_right = 0 for left, right, X in overlapping_segments(S): if len(X) == 1: ancestry_node = X[0].node if is_sample: self.record_edge(left, right, output_id, ancestry_node) ancestry_node = output_id else: if output_id == -1: output_id = self.record_node(input_id) ancestry_node = output_id for x in X: self.record_edge(left, right, output_id, x.node) if is_sample and left != prev_right: # Fill in any gaps in the ancestry for the sample self.add_ancestry(input_id, prev_right, left, output_id) self.add_ancestry(input_id, left, right, ancestry_node) prev_right = right if is_sample and prev_right != self.sequence_length: # If a trailing gap exists in the sample ancestry, fill it in. self.add_ancestry(input_id, prev_right, self.sequence_length, output_id) if output_id != -1: num_edges = self.flush_edges() if num_edges == 0 and not is_sample: self.rewind_node(input_id, output_id) def process_parent_edges(self, edges): """ Process all of the edges for a given parent. """ assert len(set(e.parent for e in edges)) == 1 parent = edges[0].parent S = [] for edge in edges: x = self.A_head[edge.child] while x is not None: if x.right > edge.left and edge.right > x.left: y = Segment(max(x.left, edge.left), min(x.right, edge.right), x.node) S.append(y) x = x.next self.merge_labeled_ancestors(S, parent) self.check_state() # self.print_state() def simplify(self): # self.print_state() if self.ts.num_edges > 0: all_edges = list(self.ts.edges()) edges = all_edges[:1] for e in all_edges[1:]: if e.parent != edges[0].parent: self.process_parent_edges(edges) edges = [] edges.append(e) self.process_parent_edges(edges) # self.print_state() ts = self.tables.tree_sequence() return ts, self.node_id_map def check_state(self): num_nodes = len(self.A_head) for j in range(num_nodes): head = self.A_head[j] tail = self.A_tail[j] if head is None: assert tail is None else: x = head while x.next is not None: x = x.next assert x == tail x = head.next while x is not None: assert x.left < x.right if x.next is not None: assert x.right <= x.next.left # We should also not have any squashable segments. if x.right == x.next.left: assert x.node != x.next.node x = x.next
[ "petrel.harp@gmail.com" ]
petrel.harp@gmail.com
bff9007a8afa686e5c49c170d58711ff0baa3f89
0740320ac36a5943a96a8ff005a604c1ae354bed
/leave_serration/main3/main.py
aec1ca6d60d7f84244ec5ae03be8604c98d705f4
[]
no_license
dezhili/leaves-image-processing
0a4d4083b530bbb74b3f6d02c8370ccb61841127
62e2122e2aae39235c4e60b6526798270b1b1ed3
refs/heads/master
2021-01-21T12:31:19.568032
2017-09-01T06:01:48
2017-09-01T06:01:48
102,078,649
0
0
null
null
null
null
UTF-8
Python
false
false
2,120
py
import cv2 import matplotlib.pyplot as plt import get_leave_boundary from get_leave_top_bottom import get_leave_top_bottom from get_leave_top_bottom import search_points import math image = '14.jpg' # image = '442_100_1.jpg' img = cv2.imread(image, 0) contours = get_leave_boundary.get_leave_boundary(image) p1_t, p2_b, k1, k2 = get_leave_top_bottom(image, contours) p3_c, p4_r, p5_l = search_points(p1_t, p2_b, k2, contours, search_heng=True) p6_c, p7_r, p8_l = search_points(p1_t, p3_c, k2, contours, search_heng=True) p9_c, p10_r, p11_l = search_points(p2_b, p3_c, k2, contours, search_heng=True) p12_c, p13_t, p14_b = search_points(p5_l, p3_c, k1, contours, search_heng=False) p15_c, p16_t, p17_b = search_points(p4_r, p3_c, k1, contours, search_heng=False) # 计算长度 宽度 len_c = math.sqrt((p1_t[0]-p2_b[0])**2 + (p1_t[1]-p2_b[1])**2) / 118.11 len_l = math.sqrt((p13_t[0]-p14_b[0])**2 + (p13_t[1]-p14_b[1])**2) / 118.11 len_r = math.sqrt((p16_t[0]-p17_b[0])**2 + (p16_t[1]-p17_b[1])**2) / 118.11 wid_c = math.sqrt((p5_l[0]-p4_r[0])**2 + (p5_l[1]-p4_r[1])**2) / 118.11 wid_t = math.sqrt((p8_l[0]-p7_r[0])**2 + (p8_l[1]-p7_r[1])**2) / 118.11 wid_b = math.sqrt((p11_l[0]-p10_r[0])**2 + (p11_l[1]-p10_r[1])**2) / 118.11 print('中间的长度为:\t', len_c) print('左边的长度为:\t', len_l) print('右边的长度为:\t', len_r) print('中间的宽度为:\t', wid_c) print('上边的宽度为:\t', wid_t) print('下边的宽度为:\t', wid_b) # plot fig, axes = plt.subplots(1, 2, figsize=(8, 8)) ax0, ax1 = axes.ravel() ax0.imshow(img, plt.cm.gray) ax0.set_title('original image') rows, cols = img.shape ax1.axis([0, rows, cols, 0]) ax1.plot(contours[:, 0], contours[:, 1], linewidth=2) ax1.axis('image') ax1.set_title('boundary and lines') ax1.plot([p1_t[0], p2_b[0]], [p1_t[1], p2_b[1]], 'r-') ax1.plot([p4_r[0], p5_l[0]], [p4_r[1], p5_l[1]], 'g-') ax1.plot([p7_r[0], p8_l[0]], [p7_r[1], p8_l[1]], 'g-') ax1.plot([p10_r[0], p11_l[0]], [p10_r[1], p11_l[1]], 'g-') ax1.plot([p13_t[0], p14_b[0]], [p13_t[1], p14_b[1]], 'r-') ax1.plot([p16_t[0], p17_b[0]], [p16_t[1], p17_b[1]], 'r-') plt.show()
[ "599709657@qq.com" ]
599709657@qq.com
ce7e974931d53cdff0a364ab42db72a2fe665aaa
a6ee206333bae24ad24728a9a1440b450ce83056
/tests/test_grpug_poetry_demo.py
2b72f3eeb63223de560d480ed89c86b4a802bc3d
[]
no_license
GRPUG/grpug-poetry-demo
b596df8dd93ed84019b493989bb916110b26e18d
59f7df2e1d59e118c97c0500bdb66158be4abfad
refs/heads/master
2020-09-12T23:25:25.483285
2019-11-19T02:31:49
2019-11-19T02:31:49
222,591,291
0
1
null
null
null
null
UTF-8
Python
false
false
98
py
from grpug_poetry_demo import __version__ def test_version(): assert __version__ == '0.1.0'
[ "jacebrowning@gmail.com" ]
jacebrowning@gmail.com
99d8c7c2a932fc594c79ee725fbc898cb2e020c1
371f94ee0f44feeaf68d740f24bd9bb27f83c8aa
/app/migrations/0002_auto_20161110_1920.py
9061620da8349eb3f87829559618cfd001f3f03d
[]
no_license
cjredmond/final_proto
f69d62da97428af3d52020054e9a327abbff8d15
28d73c7f25a7e8fae07d78b12964cdefeb3103de
refs/heads/master
2020-09-12T04:57:59.279571
2016-11-11T22:44:47
2016-11-11T22:44:47
73,517,094
0
0
null
null
null
null
UTF-8
Python
false
false
538
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-10 19:20 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='team', name='league', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app.League'), ), ]
[ "connor.redmond@gmail.com" ]
connor.redmond@gmail.com
8f143b6444dd282b2bd0c6c3b9dcf9efc2353a8a
6fa701cdaa0d83caa0d3cbffe39b40e54bf3d386
/google/ads/googleads/v8/googleads-py/google/ads/googleads/v8/services/services/batch_job_service/transports/base.py
7c0a5731d78ea08d03580092102147c29aebb834
[ "Apache-2.0" ]
permissive
oltoco/googleapis-gen
bf40cfad61b4217aca07068bd4922a86e3bbd2d5
00ca50bdde80906d6f62314ef4f7630b8cdb6e15
refs/heads/master
2023-07-17T22:11:47.848185
2021-08-29T20:39:47
2021-08-29T20:39:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,647
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 import google.auth # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.ads.googleads.v8.resources.types import batch_job from google.ads.googleads.v8.services.types import batch_job_service from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( 'google-ads', ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class BatchJobServiceTransport(metaclass=abc.ABCMeta): """Abstract transport class for BatchJobService.""" AUTH_SCOPES = ( 'https://www.googleapis.com/auth/adwords', ) def __init__( self, *, host: str = 'googleads.googleapis.com', credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> 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. 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 # If no credentials are provided, then determine the appropriate # defaults. if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # Save the credentials. self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. self._prep_wrapped_messages(client_info) def _prep_wrapped_messages(self, client_info): # Precomputed wrapped methods self._wrapped_methods = { self.mutate_batch_job: gapic_v1.method.wrap_method( self.mutate_batch_job, default_timeout=None, client_info=client_info, ), self.get_batch_job: gapic_v1.method.wrap_method( self.get_batch_job, default_timeout=None, client_info=client_info, ), self.list_batch_job_results: gapic_v1.method.wrap_method( self.list_batch_job_results, default_timeout=None, client_info=client_info, ), self.run_batch_job: gapic_v1.method.wrap_method( self.run_batch_job, default_timeout=None, client_info=client_info, ), self.add_batch_job_operations: gapic_v1.method.wrap_method( self.add_batch_job_operations, default_timeout=None, client_info=client_info, ), } @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" raise NotImplementedError @property def mutate_batch_job(self) -> typing.Callable[ [batch_job_service.MutateBatchJobRequest], batch_job_service.MutateBatchJobResponse]: raise NotImplementedError @property def get_batch_job(self) -> typing.Callable[ [batch_job_service.GetBatchJobRequest], batch_job.BatchJob]: raise NotImplementedError @property def list_batch_job_results(self) -> typing.Callable[ [batch_job_service.ListBatchJobResultsRequest], batch_job_service.ListBatchJobResultsResponse]: raise NotImplementedError @property def run_batch_job(self) -> typing.Callable[ [batch_job_service.RunBatchJobRequest], operations_pb2.Operation]: raise NotImplementedError @property def add_batch_job_operations(self) -> typing.Callable[ [batch_job_service.AddBatchJobOperationsRequest], batch_job_service.AddBatchJobOperationsResponse]: raise NotImplementedError __all__ = ( 'BatchJobServiceTransport', )
[ "bazel-bot-development[bot]@users.noreply.github.com" ]
bazel-bot-development[bot]@users.noreply.github.com
3fcd539d30d02cd5409abaeb8516fa34204dfe44
548c26cc8e68c3116cecaf7e5cd9aadca7608318
/feedback/migrations/0004_auto__add_field_feedback_type__chg_field_feedback_email__chg_field_fee.py
82b0d78830f50c8b2e808681d8cdc1c75dc68e31
[]
no_license
Morphnus-IT-Solutions/riba
b69ecebf110b91b699947b904873e9870385e481
90ff42dfe9c693265998d3182b0d672667de5123
refs/heads/master
2021-01-13T02:18:42.248642
2012-09-06T18:20:26
2012-09-06T18:20:26
4,067,896
0
1
null
null
null
null
UTF-8
Python
false
false
3,758
py
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Feedback.type' db.add_column('feedback_feedback', 'type', self.gf('django.db.models.fields.CharField')(default='feedback', max_length=25), keep_default=False) # Changing field 'Feedback.email' db.alter_column('feedback_feedback', 'email', self.gf('django.db.models.fields.EmailField')(max_length=75, null=True, blank=True)) # Changing field 'Feedback.phone' db.alter_column('feedback_feedback', 'phone', self.gf('django.db.models.fields.CharField')(max_length=15, null=True, blank=True)) # Changing field 'Feedback.name' db.alter_column('feedback_feedback', 'name', self.gf('django.db.models.fields.CharField')(max_length=50, null=True, blank=True)) def backwards(self, orm): # Deleting field 'Feedback.type' db.delete_column('feedback_feedback', 'type') # Changing field 'Feedback.email' db.alter_column('feedback_feedback', 'email', self.gf('django.db.models.fields.EmailField')(max_length=75)) # Changing field 'Feedback.phone' db.alter_column('feedback_feedback', 'phone', self.gf('django.db.models.fields.CharField')(max_length=15)) # Changing field 'Feedback.name' db.alter_column('feedback_feedback', 'name', self.gf('django.db.models.fields.CharField')(max_length=50)) models = { 'accounts.client': { 'Meta': {'object_name': 'Client'}, 'confirmed_order_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> order@chaupaati.com'", 'max_length': '500'}), 'confirmed_order_helpline': ('django.db.models.fields.CharField', [], {'default': "'0-922-222-1947'", 'max_length': '25'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'noreply_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> noreply@chaupaati.com'", 'max_length': '200'}), 'pending_order_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> lead@chaupaati.com'", 'max_length': '500'}), 'pending_order_helpline': ('django.db.models.fields.CharField', [], {'default': "'0-922-222-1947'", 'max_length': '25'}), 'share_product_email': ('django.db.models.fields.CharField', [], {'default': "'<Chaupaati Bazaar> share@chaupaati.com'", 'max_length': '500'}), 'signature': ('django.db.models.fields.TextField', [], {}), 'sms_mask': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, 'feedback.feedback': { 'Meta': {'object_name': 'Feedback'}, 'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['accounts.Client']", 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'feedback': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'feedback'", 'max_length': '25'}) } } complete_apps = ['feedback']
[ "dalal.saumil@gmail.com" ]
dalal.saumil@gmail.com
198bc43024f973401ae0dec802d22885249ca303
1a114943c92a5db40034470ff31a79bcf8ddfc37
/stdlib_exam/socketserver-example-1.py
bcde479b54c4867b59ab85012d4fe7549633e7e7
[]
no_license
renwl/mylinux
1924918599efd6766c266231d66b2a7ed6f6cdd1
0602fc6d2b0d254a8503e57310f848fc3e1a73b4
refs/heads/master
2020-07-10T22:12:03.259349
2017-01-02T12:32:04
2017-01-02T12:32:04
66,467,007
0
0
null
null
null
null
UTF-8
Python
false
false
594
py
import socketserver import time # user-accessible port PORT = 8037 # reference time TIME1970 = 2208988800 class TimeRequestHandler(socketserver.StreamRequestHandler): def handle(self): print("connection from", self.client_address) t = int(time.time()) + TIME1970 b = chr(t>>24&255) + chr(t>>16&255) + chr(t>>8&255) + chr(t&255) self.wfile.write(b) server = socketserver.TCPServer(("", PORT), TimeRequestHandler) print("listening on port", PORT) server.serve_forever() ## connection from ('127.0.0.1', 1488) ## connection from ('127.0.0.1', 1489) ## ...
[ "wenliang.ren@quanray.com" ]
wenliang.ren@quanray.com
6aaeb6f165fa71b2e82277ab1c4666f025d32a49
2772b58d09f3cc8fad2b4354dee7a06c481b7d23
/forum/forms.py
46319a0016cf611d0227b3061a330a88652e0231
[ "MIT" ]
permissive
shmilyoo/ggxxBBS
33cef10ac2284010028556c6d946566de05537da
cef6408e533bd0b0f57c3e2f5da4e93ea07c4331
refs/heads/master
2020-04-25T02:56:02.116161
2019-02-25T07:57:02
2019-02-25T07:57:02
172,458,753
0
0
null
null
null
null
UTF-8
Python
false
false
4,294
py
# -*- coding: utf-8 -*- import datetime from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.core.validators import RegexValidator from django.utils.html import strip_tags, remove_tags from django.utils.safestring import mark_safe from forum import models as forumModels from forum.helper import check_empty from ggxxBBS import config from ckeditor.widgets import CKEditorWidget form_tag_regex = RegexValidator(r'^[a-zA-Z][a-zA-Z0-9]+$') class ForumForm(forms.ModelForm): class Meta: model = forumModels.Forum fields = ['belong', 'parent_id', 'name', 'tag', 'descr', 'content', 'allow_topic', 'icon', 'topic_credit', 'post_credit', 'visit_level', 'topic_level', 'post_level'] widgets = { # 'parent_id':forms.Select(), 'content': CKEditorWidget(config_name='basic'), } # initial = { # 'parent_id':[('0' * 32, u'首页')] # } error_messages = { NON_FIELD_ERRORS: { 'unique_together': u"所属论坛与版块名,所属论坛与标签,必须唯一", } } def clean(self): data = super(ForumForm, self).clean() visit_level = data.get('visit_level') topic_level = data.get('topic_level') post_level = data.get('post_level') if not topic_level >= post_level >= visit_level: self.add_error('visit_level', u'允许发帖需要权限≥回帖≥访问') def clean_icon(self): icon = self.cleaned_data.get('icon') if icon and icon.size > config.max_avatar_size: self.add_error('icon', u'上传图标不能超过' + str(config.max_avatar_size) + u'字节') return icon def clean_belong(self): belong = self.cleaned_data.get('belong') if belong == '0': self.add_error('belong', u'请选择论坛') return belong def clean_tag(self): tag = self.cleaned_data.get('tag') try: form_tag_regex(tag) except: self.add_error('tag', u'标签由1个及以上的字母或数字组成,由字母开头') return tag class TopicForm(forms.ModelForm): class Meta: model = forumModels.Topic fields = ['read_level', 'title', 'content', 'title_bold', 'is_hide', 'is_poll'] widgets = { 'content': CKEditorWidget(config_name='default'), 'subject': forms.Select(), } def clean_title(self): title = self.cleaned_data.get('title') return title def clean_content(self): content = self.cleaned_data.get('content') if check_empty(content): self.add_error('content', u'帖子内容不能为空') return content class PostFormSimple(forms.ModelForm): class Meta: model = forumModels.Post fields = ['content'] widgets = { 'content': CKEditorWidget(config_name='basic') } def clean_content(self): content = self.cleaned_data.get('content') if check_empty(content): self.add_error('content', u'帖子内容不能为空') return content class PostFormFull(forms.ModelForm): class Meta: model = forumModels.Post fields = ['content'] widgets = { 'content': CKEditorWidget(config_name='default') } def clean_content(self): content = self.cleaned_data.get('content') if check_empty(content): self.add_error('content', u'帖子内容不能为空') return content class AttachmentForm(forms.ModelForm): class Meta: model = forumModels.Attachment fields = ['file', 'file_name', 'download_level'] class PollForm(forms.ModelForm): class Meta: model = forumModels.Poll fields = ['descr', 'is_multi', 'is_visible', 'max_choices', 'expiry'] def clean_expiry(self): expiry = self.cleaned_data.get('expiry') try: poll_expire_time = datetime.datetime.strptime(expiry, '%Y-%m-%d %H:%M') except Exception as e: poll_expire_time = datetime.datetime.now() + datetime.timedelta(days=7) return unicode(poll_expire_time.strftime('%Y-%m-%d %H:%M'))
[ "fighter_yy@qq.com" ]
fighter_yy@qq.com
28362fceebf77532f2fe2a04d4d1ea54fd38a7e1
be50b4dd0b5b8c3813b8c3158332b1154fe8fe62
/Math/Python/FizzBuzz.py
7ba15c495b1f34a12eaa2eada55c1970b97ecf14
[]
no_license
Zimmermann25/InterviewBit
a8d89e090068d9644e28085625963c8ce75d3dff
6d2138e740bd5ba8eab992d9bf090977e077bfc5
refs/heads/main
2023-03-24T18:12:48.244950
2021-03-24T14:36:48
2021-03-24T14:36:48
350,835,917
0
0
null
null
null
null
UTF-8
Python
false
false
434
py
class Solution: # @param A : integer # @return a list of strings def fizzBuzz(self, A): arr = [i+1 for i in range(A)] for i in range(1,A+1): if i % 5==0 and i %3==0: arr[i-1] = 'FizzBuzz' elif i % 5==0: arr[i-1] = 'Buzz' elif i%3==0: arr[i-1] = 'Fizz' return arr
[ "noreply@github.com" ]
Zimmermann25.noreply@github.com
5dd937a052275fa1dbf2c1a3cb885c1a790e34ba
226b1c73a706f4734834196d18305d4d2c873589
/verification_libs/axiMaster.py
ec5de04702fc9521260d68cd88cb730c51288816
[]
no_license
ocakgun/vlsistuff
43b4b07ae186b8d2360d11c57cd10b861e96bcbe
776c07f5d0c40fe7d410b5c85e7381017d4dab64
refs/heads/master
2022-06-13T14:40:22.641310
2020-05-08T11:09:00
2020-05-08T11:09:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,722
py
DEMO = ''' axi = axiMaster.axiMasterClass('tb',Monitors) axi.makeRead(1,16,0x100,4) axi.makeWrite(1,16,0x100,4) axi.wait(100) ''' import os,sys,string,types import logs import veri class axiMasterClass: def __init__(self,Path,Monitors): self.Path = Path Monitors.append(self) self.Queue=[] self.arQueue=[] self.awQueue=[] self.wQueue=[] self.Rid = 1 self.waiting=0 self.datawidth = 0 self.readAction = False self.READS=[] self.rreadyCount = 0 self.rreadyOnes = 3 self.rreadyDeny = 0 self.rreadyDenys = 10 self.renames={} self.prefix='' self.suffix='' def rename(self,Sig): if Sig in self.renames: return self.renames[Sig] if self.prefix: Sig = self.prefix + Sig if self.suffix: Sig = Sig + self.suffix return Sig def peek(self,Sig): Sig = self.rename(Sig) return logs.peek('%s.%s'%(self.Path,Sig)) def bpeek(self,Sig): Sig = self.rename(Sig) return veri.peek('%s.%s'%(self.Path,Sig)) def force(self,Sig,Val): Sig = self.rename(Sig) veri.force('%s.%s'%(self.Path,Sig),str(Val)) def makeRead(self,Burst,Len,Address,Size=4): self.Queue.append(('ar','force arvalid=1 arburst=%s arlen=%s araddr=%s arsize=%s arid=%s'%(Burst,Len-1,Address,Size,self.Rid))) if self.readAction: self.READS.append((Len,Address,self.Rid)) self.Queue.append(('ar','force arvalid=0 arburst=0 arlen=0 araddr=0 arsize=0 arid=0')) self.Rid += 1 def makeWriteWstrb(self,Burst,Len,Address,Size=4,Wstrb='auto',Wdatas=[]): if Wstrb == 'auto': self.makeWrite(Burst,Len,Address,Size,Wdatas) return self.Queue.append(('aw','force awvalid=1 awburst=%s awlen=%s awaddr=%s awsize=%s awid=%s'%(Burst,Len-1,Address,Size,self.Rid))) self.Queue.append(('aw','force awvalid=0 awburst=0 awlen=0 awaddr=0 awsize=0 awid=0')) self.Rid += 1 for ii in range(Len): if len(Wdatas)==0: Wdata = '0x%08x%08x%08x%08x'%(self.Rid+0x1000*ii,0x100+self.Rid+0x1000*ii,0x200+self.Rid+0x1000*ii,0x300+self.Rid+0x1000*ii) else: Wdata = Wdatas.pop(0) if type(Wdata)!=types.StringType: Wdata = hex(Wdatas.pop(0)) if ii==(Len-1): Wlast=1 else: Wlast = 0 self.Queue.append(('w','force wvalid=1 wdata=%s wstrb=0x%x wlast=%d'%(Wdata,Wstrb,Wlast))) self.Queue.append(('w','force wvalid=0 wdata=0 wstrb=0 wlast=0')) def makeWrite(self,Burst,Len,Address,Size=4,Wdatas=[]): self.Queue.append(('aw','force awvalid=1 awburst=%s awlen=%s awaddr=%s awsize=%s awid=%s'%(Burst,Len-1,Address,Size,self.Rid))) self.Queue.append(('aw','force awvalid=0 awburst=0 awlen=0 awaddr=0 awsize=0 awid=0')) logs.log_info('makeWrite >>>>> %x size=%s'%(Address,Size)) self.Rid += 1 for ii in range(Len): if len(Wdatas)==0: Wdata = '0x%08x%08x%08x%08x'%(self.Rid+0x1000*ii,0x100+self.Rid+0x1000*ii,0x200+self.Rid+0x1000*ii,0x300+self.Rid+0x1000*ii) elif (type(Wdatas[0])==types.StringType): Wdata = Wdatas.pop(0) else: Wdata = hex(Wdatas.pop(0)) if ii==(Len-1): Wlast=1 else: Wlast = 0 Wstrb = (1<<(1<<Size))-1 self.Queue.append(('w','force wvalid=1 wdata=%s wstrb=0x%x wlast=%d'%(Wdata,Wstrb,Wlast))) self.Queue.append(('w','force wvalid=0 wdata=0 wstrb=0 wlast=0')) def wait(self,Many): self.Queue.append(('this','wait %d'%Many)) def finish(self,Many): self.Queue.append(('this','wait %d'%Many)) self.Queue.append(('this','finish')) def run(self): # logs.log_info('runn lenaw=%d lenar=%d lenq=%d lenw=%d'%(len(self.awQueue),len(self.arQueue),len(self.Queue),len(self.wQueue))) self.runResponce() self.runAw() self.runAr() self.runW() if self.waiting>0: self.waiting -= 1 return self.runQueue() def manageRready(self,What): if What==1: print '>>>',What,self.rreadyCount,self.rreadyDeny,self.peek('rvalid') if What==0: self.force('rready',0) self.rreadyCount=0 return if self.rreadyDeny>0: self.force('rready',0) self.rreadyDeny += 1 if self.rreadyDeny > self.rreadyDenys: self.rreadyDeny=0 self.rreadyCount=0 elif self.rreadyCount==self.rreadyOnes: self.force('rready',0) self.rreadyDeny = 1 self.rreadyCount=0 else: self.force('rready',1) self.rreadyCount += 1 def runResponce(self): if self.peek('rvalid')==1: self.manageRready(1) rdata = self.peek('rdata') if self.datawidth==0: rrr = self.bpeek('rdata') self.datawidth = len(rrr) rid = self.peek('rid') rlast = self.peek('rlast') rdatax = '%032x'%rdata msb = (self.datawidth/4) rdatax = rdatax[-msb:] logs.log_info('axi responce rid=%x rlast=%d rdata=%s %s'%(rid,rlast,rdatax,self.Path)) if self.readAction: self.readAction(rid,rlast,rdatax) else: self.manageRready(0) def runQueue(self): while self.Queue!=[]: Dst,Cmd = self.Queue.pop(0) if Dst=='aw': self.awQueue.append(Cmd) elif Dst=='ar': self.arQueue.append(Cmd) elif Dst=='w': self.wQueue.append(Cmd) else: self.runThis(Cmd) return def runThis(self,Cmd): wrds = string.split(Cmd) if wrds==[]: pass elif (wrds[0]=='wait'): self.waiting = int(wrds[1]) elif (wrds[0]=='finish'): logs.log_info('veri finish from axi Master') veri.finish() sys.exit() elif (wrds[0]=='force'): for wrd in wrds[1:]: ww = string.split(wrd,'=') Var = ww[0] Val = eval(ww[1]) self.force(Var,Val) def runW(self): if self.peek('wready')==0: return if self.wQueue==[]: self.force('wvalid',0) return Cmd = self.wQueue.pop(0) wrds = string.split(Cmd) if wrds==[]: pass elif (wrds[0]=='force'): self.forces(wrds[1:]) def forces(self,wrds): for wrd in wrds: ww = string.split(wrd,'=') Var = ww[0] Val = eval(ww[1]) self.force(Var,Val) def runAw(self): if self.peek('awready')==0: return if self.awQueue==[]: self.force('awvalid',0) return Cmd = self.awQueue.pop(0) wrds = string.split(Cmd) if wrds==[]: pass elif (wrds[0]=='force'): self.forces(wrds[1:]) def runAr(self): if self.peek('arready')==0: return if self.arQueue==[]: self.force('arvalid',0) return Cmd = self.arQueue.pop(0) wrds = string.split(Cmd) if wrds==[]: pass elif (wrds[0]=='force'): self.forces(wrds[1:])
[ "greenblat@mac.com" ]
greenblat@mac.com
6ce81949e3f2282a9f151be94fc7093a54818ac8
e1afe8d3f5d776c2d80be502de8380cd786a3fb9
/pointgate/__init__.py
d8b174c2f1e216b821605ea846e1d9708e473ad1
[]
no_license
mbr/pointgate
5566b1929d8f1a93a1a2183b78287173e41bf82b
44527722e797222b35ba92a6538ae72c4f980fc4
refs/heads/master
2023-06-06T20:42:22.766233
2014-04-18T13:21:34
2014-04-18T13:21:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
384
py
from flask import Flask from flask.ext.appconfig import HerokuConfig from pointgate.dyndnsapi import dyndnsapi def create_app(configfile=None): app = Flask(__name__) HerokuConfig(app, configfile) app.config.setdefault('POINTDNS_API_URL', 'https://pointhq.com') app.config.setdefault('POINTDNS_RECORD_TTL', 60) app.register_blueprint(dyndnsapi) return app
[ "git@marcbrinkmann.de" ]
git@marcbrinkmann.de
63d99f5a3aff98c8202c811567e3db5295057bbb
8126d1bc2afe0925a24fce039d0f02a3bd7acbae
/tests/test_grid.py
c48893de2ba516734e6e3f92675639e9c74bab2c
[ "BSD-2-Clause" ]
permissive
rafwiewiora/pytraj
54fb6fe07a754f65b865dd161f64c7af15fc3926
91a019ea406081ccf0043170cc64c48b4a5ea04a
refs/heads/master
2021-01-20T17:33:05.974254
2016-03-11T21:25:32
2016-03-11T21:25:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,992
py
#!/usr/bin/env python from __future__ import print_function import unittest import os import numpy as np import pytraj as pt from pytraj.utils import eq, aa_eq from pytraj.testing import cpptraj_test_dir class TestGrid(unittest.TestCase): def test_0(self): from pytraj.math import Grid import numpy as np nx = ny = nz = 3 g = Grid(nx, ny, nz) assert g.size == nx**3 assert g.nx == g.ny == g.nz == nx value = 1000. g[0, 0, 0] = value assert g[0, 0, 0] == value assert g._element(0, 0, 0) == value class TestGridAction(unittest.TestCase): def test_action_grid(self): from pytraj.all_actions import calc_grid traj = pt.load_sample_data("tz2")[:] traj.autoimage() traj.rmsfit(mask=':1-13') d = calc_grid(traj, " 20 0.5 20 0.5 20 0.5 :WAT@O") d = calc_grid(traj(), " 20 0.5 20 0.5 20 0.5 :WAT@O", top=traj.top) def test_action_bounds(self): # creat mutable trajectory traj = pt.load('data/tz2.ortho.nc', 'data/tz2.ortho.parm7') pt.autoimage(traj) pt.superpose(traj, ref=0, mask=':1-13&!@H=', mass=True) grid_data = pt._grid(traj, mask=':1-13', grid_spacing=[0.5, 0., 0.]) text = ''' parm data/tz2.ortho.parm7 trajin data/tz2.ortho.nc autoimage rms first :1-13&!@H= mass bounds :1-13 dx .5 name MyGrid ''' state = pt.load_cpptraj_state(text) state.run() cpp_grid = state.data['MyGrid'].values aa_eq(cpp_grid, grid_data) def test_just_run_state(self): txt = ''' parm data/tz2.truncoct.parm7 trajin data/tz2.truncoct.nc reference data/tz2.truncoct.nc [REF] autoimage triclinic grid nonortho.dx boxref [REF] 50 50 50 :WAT@O pdb output/test.pdb ''' state = pt.load_cpptraj_state(txt) state.run() if __name__ == "__main__": unittest.main()
[ "hainm.comp@gmail.com" ]
hainm.comp@gmail.com
3a73b821bf69bc409fc73a51db492275552b09a3
1581f1d66d6835b2c271295e3251c2dde239fec8
/expense/admin.py
569aba91027a1072734efcf4d5e35e26be0b2b1e
[]
no_license
abinash-kumar/pythod
527659e3bdd161f9abcaaa9182dfe58044b3ff66
1469dc0cd9d6d72b2fe2e69f99542e470bea807b
refs/heads/master
2023-01-30T02:54:10.729606
2020-02-24T07:18:51
2020-02-24T07:18:51
242,670,715
0
0
null
2023-01-25T13:57:52
2020-02-24T07:16:02
Python
UTF-8
Python
false
false
902
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Channel from .models import ExpenceDetails from .models import ABDoc from django.contrib.auth.models import User admin.site.register(Channel) class ExpenceDetailsView(admin.ModelAdmin): list_display = ["remark", "channel", "expense_date", "amount", "expense_by", "created_date"] readonly_fields = ('updated_by',) model = ExpenceDetails filter_horizontal = ['bill'] search_fields = ["expense_by", "remark", "channel"] def save_model(self, request, obj, form, change): obj.updated_by = User.objects.get(id=request.user.id) obj.save() admin.site.register(ExpenceDetails, ExpenceDetailsView) class ABDocView(admin.ModelAdmin): list_display = ["title", "file"] search_fields = ["title", "file"] admin.site.register(ABDoc, ABDocView)
[ "abinashlv@AbinashSymboMac.local" ]
abinashlv@AbinashSymboMac.local
6101ffbcf6bdcad6190dbf061d007a7f56793e4a
bfcd8f1f6ac8590df321f23a422eca0370a25b8f
/myenv/lib/python3.7/site-packages/layoutmargin/_margin_layout.py
3c7b7f4b634a6c45e59c56c7b890314835cd6c0d
[]
no_license
Stephen-Tipa-Augustine/KMC_ventilator
0567fa0b72d41fb0de11cd72c62567bed973d9f5
456e88ae4fff3984d5456517ba8787f9d5762745
refs/heads/master
2022-12-26T08:00:41.102890
2020-09-07T11:00:13
2020-09-07T11:00:13
293,500,282
0
1
null
2022-12-19T04:33:28
2020-09-07T10:49:08
Python
UTF-8
Python
false
false
5,591
py
from typing import NamedTuple from kivy.properties import ObjectProperty class AddMargin: margin = ObjectProperty() _last_X = None _last_Y = None _last_Width = None _last_Height = None _last_MarginX = None _last_MarginY = None def __init__(self, **kwargs): super().__init__(**kwargs) self.margin = (0, 0, 0, 0) class _Sides(NamedTuple): primary: str center: str inverted: str _X_SIDES = _Sides("left", "center_x", "right") _Y_SIDES = _Sides("bottom", "center_y", "top") class MarginLayout: def add_widget(self, widget, index=0): if isinstance(widget, AddMargin): widget.fbind("margin", self._apply_Margins) return super().add_widget(widget, index) def remove_widget(self, widget): if isinstance(widget, AddMargin): widget.funbind("margin", self._apply_Margins) return super().remove_widget(widget) def do_layout(self, *args): super().do_layout(*args) for child in [x for x in self.children if isinstance(x, AddMargin)]: self._apply_Margins(child, child.margin) self._trigger_layout.cancel() def _apply_Margins(self, widget, margins): def get_MarginValue(i, value): if isinstance(value, str): if "%" in value: maxSizes = [ widget.width, widget.height, widget.width, widget.height ] percentage = float(value.replace("%", "").strip()) / 100 value = maxSizes[i] * percentage else: raise ValueError( f"'{widget.__class__.__name__}' invalid margin value." ) return value def get_MarginValues(margin): return (get_MarginValue(i, x) for i, x in enumerate(margin)) def get_Initial_Position(margin, position, size): position += margin[0] size -= sum(margin) return position, size def update_Widget(key, value): if key == "_last_X": widget.x = widget._last_X = value elif key == "_last_Y": widget.y = widget._last_Y = value elif key == "_last_Width": widget.width = widget._last_Width = value elif key == "_last_Height": widget.height = widget._last_Height = value elif key == "_last_MarginX": widget._last_MarginX = value elif key == "_last_MarginY": widget._last_MarginY = value def update_SizeHint_Widget( margin, position, lastPosition_Key, size, lastSize_Key): position, size = get_Initial_Position(margin, position, size) update_Widget(lastPosition_Key, position) update_Widget(lastSize_Key, size) def update_Sized_Widget( sides, margin, lastMargin, lastMargin_Key, position, position_Hint, lastPosition, lastPosition_Key, size, size_Hint, lastSize, lastSize_Key, ): if lastSize is None: position, size = get_Initial_Position(margin, position, size) else: if(margin != lastMargin) and (position_Hint == sides.primary): difference = (lastMargin[0] - margin[0]) position -= difference if(size != lastSize) and (position_Hint == sides.inverted): difference = size - lastSize position -= (difference + (margin[1] - difference)) elif(position_Hint == sides.inverted): position -= margin[1] update_Widget(lastPosition_Key, position) update_Widget(lastSize_Key, size) update_Widget(lastMargin_Key, margin) def apply_Margins( sides, margin, lastMargin, lastMargin_Key, position, position_Hint, lastPosition, lastPosition_Key, size, size_Hint, lastSize, lastSize_Key, ): if(size_Hint): update_SizeHint_Widget( margin, position, lastPosition_Key, size, lastSize_Key) else: update_Sized_Widget( sides, margin, lastMargin, lastMargin_Key, position, position_Hint, lastPosition, lastPosition_Key, size, size_Hint, lastSize, lastSize_Key, ) left, top, right, bottom = get_MarginValues(margins) x_Margin, y_Margin = ((left, right), (bottom, top)) x_Hint, y_Hint = widget.pos_hint if(widget.pos_hint) else(None, None) w_Hint, h_Hint = widget.size_hint apply_Margins( sides=_X_SIDES, margin=x_Margin, lastMargin=widget._last_MarginX, lastMargin_Key="_last_MarginX", position=widget.x, position_Hint=x_Hint, lastPosition=widget._last_X, lastPosition_Key="_last_X", size=widget.width, size_Hint=w_Hint, lastSize=widget._last_Width, lastSize_Key="_last_Width", ) apply_Margins( sides=_Y_SIDES, margin=y_Margin, lastMargin=widget._last_MarginY, lastMargin_Key="_last_MarginY", position=widget.y, position_Hint=y_Hint, lastPosition=widget._last_Y, lastPosition_Key="_last_Y", size=widget.height, size_Hint=h_Hint, lastSize=widget._last_Height, lastSize_Key="_last_Height", )
[ "tipastep5@gmail.com" ]
tipastep5@gmail.com
cad6c4183f117d037e4b8286d3ca10b6fac08c37
1eddc123709611cf2ddccb0b7d48b722b2a09a5d
/plugins/modules/fmgr_devprof_system_dns.py
a11e38aab902237bc37cafe4a109b08161c0e197
[]
no_license
fortinet-ansible-dev/ansible-galaxy-fortimanager-collection
bfb2014a72007358b491bb1d27c0fa3191ec62a8
63b65abce410ed4d6b76e3dd1dcf7a4341cc173d
refs/heads/main
2023-07-09T04:33:38.304263
2023-06-21T21:11:57
2023-06-21T21:11:57
242,629,431
10
18
null
2022-12-16T15:57:16
2020-02-24T02:28:03
Python
UTF-8
Python
false
false
35,988
py
#!/usr/bin/python from __future__ import absolute_import, division, print_function # Copyright 2019-2023 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fmgr_devprof_system_dns short_description: Configure DNS. description: - This module is able to configure a FortiManager device. - Examples include all parameters and values which need to be adjusted to data sources before usage. version_added: "1.0.0" author: - Xinwei Du (@dux-fortinet) - Xing Li (@lix-fortinet) - Jie Xue (@JieX19) - Link Zheng (@chillancezen) - Frank Shen (@fshen01) - Hongbin Lu (@fgtdev-hblu) notes: - Running in workspace locking mode is supported in this FortiManager module, the top level parameters workspace_locking_adom and workspace_locking_timeout help do the work. - To create or update an object, use state present directive. - To delete an object, use state absent directive. - Normally, running one module can fail when a non-zero rc is returned. you can also override the conditions to fail or succeed with parameters rc_failed and rc_succeeded options: access_token: description: The token to access FortiManager without using username and password. required: false type: str bypass_validation: description: Only set to True when module schema diffs with FortiManager API structure, module continues to execute without validating parameters. required: false type: bool default: false enable_log: description: Enable/Disable logging for task. required: false type: bool default: false forticloud_access_token: description: Authenticate Ansible client with forticloud API access token. required: false type: str proposed_method: description: The overridden method for the underlying Json RPC request. required: false type: str choices: - update - set - add rc_succeeded: description: The rc codes list with which the conditions to succeed will be overriden. type: list required: false elements: int rc_failed: description: The rc codes list with which the conditions to fail will be overriden. type: list required: false elements: int workspace_locking_adom: description: The adom to lock for FortiManager running in workspace mode, the value can be global and others including root. required: false type: str workspace_locking_timeout: description: The maximum time in seconds to wait for other user to release the workspace lock. required: false type: int default: 300 adom: description: the parameter (adom) in requested url type: str required: true devprof: description: the parameter (devprof) in requested url type: str required: true devprof_system_dns: description: the top level parameters set required: false type: dict suboptions: cache-notfound-responses: type: str description: Enable/disable response from the DNS server when a record is not in cache. choices: - 'disable' - 'enable' dns-cache-limit: type: int description: Maximum number of records in the DNS cache. dns-cache-ttl: type: int description: Duration in seconds that the DNS cache retains information. domain: type: str description: Domain name suffix for the IP addresses of the DNS server. ip6-primary: type: str description: Primary DNS server IPv6 address. ip6-secondary: type: str description: Secondary DNS server IPv6 address. primary: type: str description: Primary DNS server IP address. secondary: type: str description: Secondary DNS server IP address. dns-over-tls: type: str description: Enable/disable/enforce DNS over TLS. choices: - 'disable' - 'enable' - 'enforce' retry: type: int description: Number of times to retry server-hostname: description: description type: str ssl-certificate: type: str description: Name of local certificate for SSL connections. timeout: type: int description: DNS query timeout interval in seconds interface: type: str description: Specify outgoing interface to reach server. interface-select-method: type: str description: Specify how to select outgoing interface to reach server. choices: - 'auto' - 'sdwan' - 'specify' ''' EXAMPLES = ''' - hosts: fortimanager-inventory collections: - fortinet.fortimanager connection: httpapi vars: ansible_httpapi_use_ssl: True ansible_httpapi_validate_certs: False ansible_httpapi_port: 443 tasks: - name: Configure DNS. fmgr_devprof_system_dns: bypass_validation: False workspace_locking_adom: <value in [global, custom adom including root]> workspace_locking_timeout: 300 rc_succeeded: [0, -2, -3, ...] rc_failed: [-2, -3, ...] adom: <your own value> devprof: <your own value> devprof_system_dns: cache-notfound-responses: <value in [disable, enable]> dns-cache-limit: <value of integer> dns-cache-ttl: <value of integer> domain: <value of string> ip6-primary: <value of string> ip6-secondary: <value of string> primary: <value of string> secondary: <value of string> dns-over-tls: <value in [disable, enable, enforce]> retry: <value of integer> server-hostname: <value of string> ssl-certificate: <value of string> timeout: <value of integer> interface: <value of string> interface-select-method: <value in [auto, sdwan, specify]> ''' RETURN = ''' meta: description: The result of the request. type: dict returned: always contains: request_url: description: The full url requested. returned: always type: str sample: /sys/login/user response_code: description: The status of api request. returned: always type: int sample: 0 response_data: description: The api response. type: list returned: always response_message: description: The descriptive message of the api response. type: str returned: always sample: OK. system_information: description: The information of the target system. type: dict returned: always rc: description: The status the request. type: int returned: always sample: 0 version_check_warning: description: Warning if the parameters used in the playbook are not supported by the current FortiManager version. type: list returned: complex ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import NAPIManager from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_galaxy_version from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_parameter_bypass def main(): jrpc_urls = [ '/pm/config/adom/{adom}/devprof/{devprof}/system/dns' ] perobject_jrpc_urls = [ '/pm/config/adom/{adom}/devprof/{devprof}/system/dns/{dns}' ] url_params = ['adom', 'devprof'] module_primary_key = None module_arg_spec = { 'access_token': { 'type': 'str', 'required': False, 'no_log': True }, 'bypass_validation': { 'type': 'bool', 'required': False, 'default': False }, 'enable_log': { 'type': 'bool', 'required': False, 'default': False }, 'forticloud_access_token': { 'type': 'str', 'required': False, 'no_log': True }, 'proposed_method': { 'type': 'str', 'required': False, 'choices': [ 'set', 'update', 'add' ] }, 'rc_succeeded': { 'required': False, 'type': 'list', 'elements': 'int' }, 'rc_failed': { 'required': False, 'type': 'list', 'elements': 'int' }, 'workspace_locking_adom': { 'type': 'str', 'required': False }, 'workspace_locking_timeout': { 'type': 'int', 'required': False, 'default': 300 }, 'adom': { 'required': True, 'type': 'str' }, 'devprof': { 'required': True, 'type': 'str' }, 'devprof_system_dns': { 'required': False, 'type': 'dict', 'revision': { '6.0.0': True, '6.2.0': True, '6.2.1': True, '6.2.2': True, '6.2.3': True, '6.2.5': True, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.0': True, '6.4.1': True }, 'options': { 'cache-notfound-responses': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'dns-cache-limit': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'int' }, 'dns-cache-ttl': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'int' }, 'domain': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'ip6-primary': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'ip6-secondary': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'primary': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'secondary': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'dns-over-tls': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'choices': [ 'disable', 'enable', 'enforce' ], 'type': 'str' }, 'retry': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'int' }, 'server-hostname': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': False, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'ssl-certificate': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'timeout': { 'required': False, 'revision': { '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': True, '6.2.2': True, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'int' }, 'interface': { 'required': False, 'revision': { '6.2.5': True, '6.4.0': False, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': False, '6.2.2': False, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'type': 'str' }, 'interface-select-method': { 'required': False, 'revision': { '6.2.5': True, '6.4.0': False, '6.4.2': False, '6.4.5': False, '7.0.0': False, '7.2.0': False, '6.2.0': False, '6.2.2': False, '6.2.6': False, '6.2.7': True, '6.2.8': True, '6.2.9': True, '6.2.10': True, '6.4.1': True, '6.4.3': False, '6.4.4': False, '6.4.6': False, '6.4.7': False, '6.4.8': False, '6.4.9': False, '6.4.10': False, '6.4.11': False, '7.0.1': False, '7.0.2': False, '7.0.3': False, '7.0.4': False, '7.0.5': False, '7.0.6': False, '7.0.7': False, '7.2.1': False, '7.2.2': False, '7.4.0': False }, 'choices': [ 'auto', 'sdwan', 'specify' ], 'type': 'str' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'devprof_system_dns'), supports_check_mode=False) fmgr = None if module._socket_path: connection = Connection(module._socket_path) connection.set_option('access_token', module.params['access_token'] if 'access_token' in module.params else None) connection.set_option('enable_log', module.params['enable_log'] if 'enable_log' in module.params else False) connection.set_option('forticloud_access_token', module.params['forticloud_access_token'] if 'forticloud_access_token' in module.params else None) fmgr = NAPIManager(jrpc_urls, perobject_jrpc_urls, module_primary_key, url_params, module, connection, top_level_schema_name='data') fmgr.validate_parameters(params_validation_blob) fmgr.process_partial_curd(argument_specs=module_arg_spec) else: module.fail_json(msg='MUST RUN IN HTTPAPI MODE') module.exit_json(meta=module.params) if __name__ == '__main__': main()
[ "hq-devops-admin@fortinet.com" ]
hq-devops-admin@fortinet.com
a409824bbeb2bee142944ddfef80720e93e45871
ec0b8bfe19b03e9c3bb13d9cfa9bd328fb9ca3f1
/res/packages/scripts/scripts/client/gui/Scaleform/daapi/view/lobby/components/CalendarComponent.py
468107eb74fdcf3dd1a24f4654b1b61c2cb03022
[]
no_license
webiumsk/WOT-0.9.20.0
de3d7441c5d442f085c47a89fa58a83f1cd783f2
811cb4e1bca271372a1d837a268b6e0e915368bc
refs/heads/master
2021-01-20T22:11:45.505844
2017-08-29T20:11:38
2017-08-29T20:11:38
101,803,045
0
1
null
null
null
null
WINDOWS-1250
Python
false
false
1,193
py
# 2017.08.29 21:46:49 Střední Evropa (letní čas) # Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/components/CalendarComponent.py from debug_utils import LOG_DEBUG import BigWorld from Event import Event, EventManager from gui.Scaleform.daapi.view.meta.CalendarMeta import CalendarMeta class CalendarComponent(CalendarMeta): def __init__(self): super(CalendarComponent, self).__init__() self.__em = EventManager() self.onMonthChangedEvent = Event(self.__em) self.onDateSelectedEvent = Event(self.__em) def onMonthChanged(self, timestamp): self.onMonthChangedEvent(timestamp) def onDateSelected(self, timestamp): self.onDateSelectedEvent(timestamp) def formatYMHeader(self, rawDate): return BigWorld.wg_getYMDateFormat(rawDate) def _dispose(self): self.__em.clear() super(CalendarComponent, self)._dispose() # okay decompyling c:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\client\gui\Scaleform\daapi\view\lobby\components\CalendarComponent.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2017.08.29 21:46:49 Střední Evropa (letní čas)
[ "info@webium.sk" ]
info@webium.sk
9461eef63e4da2652e875cd5b3f59a30f042a584
b554dbc85ca470c4598d412ff34f516a8ab324dc
/azure-mgmt-compute/azure/mgmt/compute/v2018_10_01/models/virtual_machine_scale_set_py3.py
1db294839a1ba61549769cd0b97f6bbb0b5bbcc8
[ "MIT" ]
permissive
bgsky/azure-sdk-for-python
62bd7b12b0b407690707cbaf6ad4322ed58d1d3b
ec18d0b25be10fddbde416b901b905dfb0896430
refs/heads/master
2021-04-12T01:59:34.293330
2018-11-27T21:57:19
2018-11-27T21:57:19
125,912,205
0
0
MIT
2018-03-19T19:50:37
2018-03-19T19:50:37
null
UTF-8
Python
false
false
5,519
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 .resource_py3 import Resource class VirtualMachineScaleSet(Resource): """Describes a Virtual Machine Scale Set. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar type: Resource type :vartype type: str :param location: Required. Resource location :type location: str :param tags: Resource tags :type tags: dict[str, str] :param sku: The virtual machine scale set sku. :type sku: ~azure.mgmt.compute.v2018_10_01.models.Sku :param plan: Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. :type plan: ~azure.mgmt.compute.v2018_10_01.models.Plan :param upgrade_policy: The upgrade policy. :type upgrade_policy: ~azure.mgmt.compute.v2018_10_01.models.UpgradePolicy :param virtual_machine_profile: The virtual machine profile. :type virtual_machine_profile: ~azure.mgmt.compute.v2018_10_01.models.VirtualMachineScaleSetVMProfile :ivar provisioning_state: The provisioning state, which only appears in the response. :vartype provisioning_state: str :param overprovision: Specifies whether the Virtual Machine Scale Set should be overprovisioned. :type overprovision: bool :ivar unique_id: Specifies the ID which uniquely identifies a Virtual Machine Scale Set. :vartype unique_id: str :param single_placement_group: When true this limits the scale set to a single placement group, of max size 100 virtual machines. :type single_placement_group: bool :param zone_balance: Whether to force stictly even Virtual Machine distribution cross x-zones in case there is zone outage. :type zone_balance: bool :param platform_fault_domain_count: Fault Domain count for each placement group. :type platform_fault_domain_count: int :param identity: The identity of the virtual machine scale set, if configured. :type identity: ~azure.mgmt.compute.v2018_10_01.models.VirtualMachineScaleSetIdentity :param zones: The virtual machine scale set zones. :type zones: list[str] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'provisioning_state': {'readonly': True}, 'unique_id': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'Sku'}, 'plan': {'key': 'plan', 'type': 'Plan'}, 'upgrade_policy': {'key': 'properties.upgradePolicy', 'type': 'UpgradePolicy'}, 'virtual_machine_profile': {'key': 'properties.virtualMachineProfile', 'type': 'VirtualMachineScaleSetVMProfile'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'overprovision': {'key': 'properties.overprovision', 'type': 'bool'}, 'unique_id': {'key': 'properties.uniqueId', 'type': 'str'}, 'single_placement_group': {'key': 'properties.singlePlacementGroup', 'type': 'bool'}, 'zone_balance': {'key': 'properties.zoneBalance', 'type': 'bool'}, 'platform_fault_domain_count': {'key': 'properties.platformFaultDomainCount', 'type': 'int'}, 'identity': {'key': 'identity', 'type': 'VirtualMachineScaleSetIdentity'}, 'zones': {'key': 'zones', 'type': '[str]'}, } def __init__(self, *, location: str, tags=None, sku=None, plan=None, upgrade_policy=None, virtual_machine_profile=None, overprovision: bool=None, single_placement_group: bool=None, zone_balance: bool=None, platform_fault_domain_count: int=None, identity=None, zones=None, **kwargs) -> None: super(VirtualMachineScaleSet, self).__init__(location=location, tags=tags, **kwargs) self.sku = sku self.plan = plan self.upgrade_policy = upgrade_policy self.virtual_machine_profile = virtual_machine_profile self.provisioning_state = None self.overprovision = overprovision self.unique_id = None self.single_placement_group = single_placement_group self.zone_balance = zone_balance self.platform_fault_domain_count = platform_fault_domain_count self.identity = identity self.zones = zones
[ "lmazuel@microsoft.com" ]
lmazuel@microsoft.com
1d3fe4cf1c880b8a628afd2b1e092450fb946243
7950c4faf15ec1dc217391d839ddc21efd174ede
/problems/0236.0_Lowest_Common_Ancestor_of_a_Binary_Tree.py
dd4df406dc9baf8ebc67905db08cce531e2aaf01
[]
no_license
lixiang2017/leetcode
f462ecd269c7157aa4f5854f8c1da97ca5375e39
f93380721b8383817fe2b0d728deca1321c9ef45
refs/heads/master
2023-08-25T02:56:58.918792
2023-08-22T16:43:36
2023-08-22T16:43:36
153,090,613
5
0
null
null
null
null
UTF-8
Python
false
false
1,135
py
''' DFS Runtime: 114 ms, faster than 46.58% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree. Memory Usage: 26.3 MB, less than 30.85% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if not root or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) ''' if left: print('l: ', left.val, 'root: ', root.val) if right: print('r: ', right.val, 'root: ', root.val) ''' if left and right: return root return left or right ''' bottom-up Your input [3,5,1,6,2,0,8,null,null,7,4] 7 8 stdout l: 7 root: 2 r: 7 root: 5 r: 8 root: 1 l: 7 root: 3 r: 8 root: 3 Output 3 Expected 3 '''
[ "838255715@qq.com" ]
838255715@qq.com
7a15d2971289ce0096ffa5f055a850c83a0882cc
55e21abf0b4bd5daa0b0f9a5fe6eae3abd0d5f69
/redgo/tests/sgf_parser/sgf_grammar_test.py
bf749ef92bba9258c4ef68445d73c3866ab8d886
[]
no_license
gcaaa31928/RedGo
8b3efc610870aabfbcbee82046cc57e773336b98
d42ea65ce925006c4bbd234213e94a779c01fdee
refs/heads/master
2021-01-12T01:12:51.446644
2017-01-20T11:03:36
2017-01-20T11:03:36
78,358,001
0
0
null
null
null
null
UTF-8
Python
false
false
17,247
py
"""Tests for sgf_grammar.py.""" import unittest from redgo.sgf_parser import sgf_grammar class SgfGrammarTestCase(unittest.TestCase): def test_is_valid_property_identifier(tc): ivpi = sgf_grammar.is_valid_property_identifier tc.assertIs(ivpi(b"B"), True) tc.assertIs(ivpi(b"PB"), True) tc.assertIs(ivpi(b"ABCDEFGH"), True) tc.assertIs(ivpi(b"ABCDEFGHI"), False) tc.assertIs(ivpi(b""), False) tc.assertIs(ivpi(b"b"), False) tc.assertIs(ivpi(b"Player"), False) tc.assertIs(ivpi(b"P2"), False) tc.assertIs(ivpi(b" PB"), False) tc.assertIs(ivpi(b"PB "), False) tc.assertIs(ivpi(b"P B"), False) tc.assertIs(ivpi(b"PB\x00"), False) def test_is_valid_property_value(tc): ivpv = sgf_grammar.is_valid_property_value tc.assertIs(ivpv(b""), True) tc.assertIs(ivpv(b"hello world"), True) tc.assertIs(ivpv(b"hello\nworld"), True) tc.assertIs(ivpv(b"hello \x00 world"), True) tc.assertIs(ivpv(b"hello \xa3 world"), True) tc.assertIs(ivpv(b"hello \xc2\xa3 world"), True) tc.assertIs(ivpv(b"hello \\-) world"), True) tc.assertIs(ivpv(b"hello (;[) world"), True) tc.assertIs(ivpv(b"[hello world]"), False) tc.assertIs(ivpv(b"hello ] world"), False) tc.assertIs(ivpv(b"hello \\] world"), True) tc.assertIs(ivpv(b"hello world \\"), False) tc.assertIs(ivpv(b"hello world \\\\"), True) tc.assertIs(ivpv(b"x" * 70000), True) def test_tokeniser(tc): tokenise = sgf_grammar.tokenise tc.assertEqual(tokenise(b"(;B[ah][]C[a\xa3b])")[0], [('D', b'('), ('D', b';'), ('I', b'B'), ('V', b'ah'), ('V', b''), ('I', b'C'), ('V', b'a\xa3b'), ('D', b')')]) def check_complete(s, *args): tokens, tail_index = tokenise(s, *args) tc.assertEqual(tail_index, len(s)) return len(tokens) def check_incomplete(s, *args): tokens, tail_index = tokenise(s, *args) return len(tokens), tail_index # check surrounding junk tc.assertEqual(check_complete(b""), 0) tc.assertEqual(check_complete(b"junk (;B[ah])"), 5) tc.assertEqual(check_incomplete(b"junk"), (0, 0)) tc.assertEqual(check_incomplete(b"junk (B[ah])"), (0, 0)) tc.assertEqual(check_incomplete(b"(;B[ah]) junk"), (5, 8)) # check paren-balance count tc.assertEqual(check_incomplete(b"(; ))(([ag]B C[ah])"), (3, 4)) tc.assertEqual(check_incomplete(b"(;( )) (;)"), (5, 6)) tc.assertEqual(check_incomplete(b"(;(()())) (;)"), (9, 9)) # check start_position tc.assertEqual(check_complete(b"(; ))(;B[ah])", 4), 5) tc.assertEqual(check_complete(b"(; ))junk (;B[ah])", 4), 5) tc.assertEqual(check_complete(b"(;XX[abc][def]KO[];B[bc])"), 11) tc.assertEqual(check_complete(b"( ;XX[abc][def]KO[];B[bc])"), 11) tc.assertEqual(check_complete(b"(; XX[abc][def]KO[];B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX [abc][def]KO[];B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc] [def]KO[];B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc][def] KO[];B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc][def]KO [];B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc][def]KO[] ;B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc][def]KO[]; B[bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc][def]KO[];B [bc])"), 11) tc.assertEqual(check_complete(b"(;XX[abc][def]KO[];B[bc] )"), 11) tc.assertEqual(check_complete(b"( ;\nB\t[ah]\f[ef]\v)"), 6) tc.assertEqual(check_complete(b"(;[Ran\xc2\xa3dom :\nstu@ff][ef]"), 4) tc.assertEqual(check_complete(b"(;[ah)])"), 4) tc.assertEqual(check_incomplete(b"(;B[ag"), (3, 3)) tc.assertEqual(check_incomplete(b"(;B[ag)"), (3, 3)) tc.assertEqual(check_incomplete(b"(;AddBlack[ag])"), (3, 3)) tc.assertEqual(check_incomplete(b"(;+B[ag])"), (2, 2)) tc.assertEqual(check_incomplete(b"(;B+[ag])"), (3, 3)) tc.assertEqual(check_incomplete(b"(;B[ag]+)"), (4, 7)) tc.assertEqual(check_complete(r"(;[ab \] cd][ef]".encode('ascii')), 4) tc.assertEqual(check_complete(r"(;[ab \] cd\\][ef]".encode('ascii')), 4) tc.assertEqual(check_complete(r"(;[ab \] cd\\\\][ef]".encode('ascii')), 4) tc.assertEqual(check_complete(r"(;[ab \] \\\] cd][ef]".encode('ascii')), 4) tc.assertEqual(check_incomplete(r"(;B[ag\])".encode('ascii')), (3, 3)) tc.assertEqual(check_incomplete(r"(;B[ag\\\])".encode('ascii')), (3, 3)) def test_parser_structure(tc): parse_sgf_game = sgf_grammar.parse_sgf_game def shape(s): coarse_game = parse_sgf_game(s) return len(coarse_game.sequence), len(coarse_game.children) tc.assertEqual(shape(b"(;C[abc]KO[];B[bc])"), (2, 0)) tc.assertEqual(shape(b"initial junk (;C[abc]KO[];B[bc])"), (2, 0)) tc.assertEqual(shape(b"(;C[abc]KO[];B[bc]) final junk"), (2, 0)) tc.assertEqual(shape(b"(;C[abc]KO[];B[bc]) (;B[ag])"), (2, 0)) tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_game, b"") tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_game, b"junk") tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_game, b"()") tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_game, b"(B[ag])") tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_game, b"B[ag]") tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_game, b"[ag]") tc.assertEqual(shape(b"(;C[abc]AB[ab][bc];B[bc])"), (2, 0)) tc.assertEqual(shape(b"(;C[abc] AB[ab]\n[bc]\t;B[bc])"), (2, 0)) tc.assertEqual(shape(b"(;C[abc]KO[];;B[bc])"), (3, 0)) tc.assertEqual(shape(b"(;)"), (1, 0)) tc.assertRaisesRegexp(ValueError, "property with no values", parse_sgf_game, b"(;B)") tc.assertRaisesRegexp(ValueError, "unexpected value", parse_sgf_game, b"(;[ag])") tc.assertRaisesRegexp(ValueError, "unexpected value", parse_sgf_game, b"(;[ag][ah])") tc.assertRaisesRegexp(ValueError, "unexpected value", parse_sgf_game, b"(;[B][ag])") tc.assertRaisesRegexp(ValueError, "unexpected end of SGF data", parse_sgf_game, b"(;B[ag]") tc.assertRaisesRegexp(ValueError, "unexpected end of SGF data", parse_sgf_game, b"(;B[ag][)]") tc.assertRaisesRegexp(ValueError, "property with no values", parse_sgf_game, b"(;B;W[ah])") tc.assertRaisesRegexp(ValueError, "unexpected value", parse_sgf_game, b"(;B[ag](;[ah]))") tc.assertRaisesRegexp(ValueError, "property with no values", parse_sgf_game, b"(;B W[ag])") def test_parser_tree_structure(tc): parse_sgf_game = sgf_grammar.parse_sgf_game def shape(s): coarse_game = parse_sgf_game(s) return len(coarse_game.sequence), len(coarse_game.children) tc.assertEqual(shape(b"(;C[abc]AB[ab](;B[bc]))"), (1, 1)) tc.assertEqual(shape(b"(;C[abc]AB[ab](;B[bc])))"), (1, 1)) tc.assertEqual(shape(b"(;C[abc]AB[ab](;B[bc])(;B[bd]))"), (1, 2)) def shapetree(s): def _shapetree(coarse_game): return ( len(coarse_game.sequence), [_shapetree(pg) for pg in coarse_game.children]) return _shapetree(parse_sgf_game(s)) tc.assertEqual(shapetree(b"(;C[abc]AB[ab](;B[bc])))"), (1, [(1, [])]) ) tc.assertEqual(shapetree(b"(;C[abc]AB[ab](;B[bc]))))"), (1, [(1, [])]) ) tc.assertEqual(shapetree(b"(;C[abc]AB[ab](;B[bc])(;B[bd])))"), (1, [(1, []), (1, [])]) ) tc.assertEqual(shapetree(b""" (;C[abc]AB[ab];C[];C[] (;B[bc]) (;B[bd];W[ca] (;B[da])(;B[db];W[ea]) ) )"""), (3, [ (1, []), (2, [(1, []), (2, [])]) ]) ) tc.assertRaisesRegexp(ValueError, "unexpected end of SGF data", parse_sgf_game, b"(;B[ag];W[ah](;B[ai])") tc.assertRaisesRegexp(ValueError, "empty sequence", parse_sgf_game, b"(;B[ag];())") tc.assertRaisesRegexp(ValueError, "empty sequence", parse_sgf_game, b"(;B[ag]())") tc.assertRaisesRegexp(ValueError, "empty sequence", parse_sgf_game, b"(;B[ag]((;W[ah])(;W[ai]))") tc.assertRaisesRegexp(ValueError, "unexpected node", parse_sgf_game, b"(;B[ag];W[ah](;B[ai]);W[bd])") tc.assertRaisesRegexp(ValueError, "property value outside a node", parse_sgf_game, b"(;B[ag];(W[ah];B[ai]))") tc.assertRaisesRegexp(ValueError, "property value outside a node", parse_sgf_game, b"(;B[ag](;W[ah];)B[ai])") tc.assertRaisesRegexp(ValueError, "property value outside a node", parse_sgf_game, b"(;B[ag](;W[ah])(B[ai]))") def test_parser_properties(tc): parse_sgf_game = sgf_grammar.parse_sgf_game def props(s): coarse_game = parse_sgf_game(s) return coarse_game.sequence tc.assertEqual(props(b"(;C[abc]KO[]AB[ai][bh][ee];B[ bc])"), [{b'C': [b'abc'], b'KO': [b''], b'AB': [b'ai', b'bh', b'ee']}, {b'B': [b' bc']}]) tc.assertEqual(props(r"(;C[ab \] \) cd\\])".encode('ascii')), [{b'C': [r"ab \] \) cd\\".encode('ascii')]}]) tc.assertEqual(props(b"(;XX[1]YY[2]XX[3]YY[4])"), [{b'XX': [b'1', b'3'], b'YY' : [b'2', b'4']}]) def test_parse_sgf_collection(tc): parse_sgf_collection = sgf_grammar.parse_sgf_collection tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_collection, b"") tc.assertRaisesRegexp(ValueError, "no SGF data found", parse_sgf_collection, b"()") games = parse_sgf_collection(b"(;C[abc]AB[ab];X[];X[](;B[bc]))") tc.assertEqual(len(games), 1) tc.assertEqual(len(games[0].sequence), 3) games = parse_sgf_collection(b"(;X[1];X[2];X[3](;B[bc])) (;Y[1];Y[2])") tc.assertEqual(len(games), 2) tc.assertEqual(len(games[0].sequence), 3) tc.assertEqual(len(games[1].sequence), 2) games = parse_sgf_collection( b"dummy (;X[1];X[2];X[3](;B[bc])) junk (;Y[1];Y[2]) Nonsense") tc.assertEqual(len(games), 2) tc.assertEqual(len(games[0].sequence), 3) tc.assertEqual(len(games[1].sequence), 2) games = parse_sgf_collection( b"(( (;X[1];X[2];X[3](;B[bc])) ();) (;Y[1];Y[2]) )(Nonsense") tc.assertEqual(len(games), 2) tc.assertEqual(len(games[0].sequence), 3) tc.assertEqual(len(games[1].sequence), 2) with tc.assertRaises(ValueError) as ar: parse_sgf_collection( b"(( (;X[1];X[2];X[3](;B[bc])) ();) (;Y[1];Y[2]") tc.assertEqual(str(ar.exception), "error parsing game 1: unexpected end of SGF data") def test_parse_compose(tc): pc = sgf_grammar.parse_compose tc.assertEqual(pc(b"word"), (b"word", None)) tc.assertEqual(pc(b"word:"), (b"word", b"")) tc.assertEqual(pc(b"word:?"), (b"word", b"?")) tc.assertEqual(pc(b"word:123"), (b"word", b"123")) tc.assertEqual(pc(b"word:123:456"), (b"word", b"123:456")) tc.assertEqual(pc(b":123"), (b"", b"123")) tc.assertEqual(pc(r"word\:more".encode('ascii')), (r"word\:more".encode('ascii'), None)) tc.assertEqual(pc(r"word\:more:?".encode('ascii')), (r"word\:more".encode('ascii'), b"?")) tc.assertEqual(pc(r"word\\:more:?".encode('ascii')), (b"word\\\\", b"more:?")) tc.assertEqual(pc(r"word\\\:more:?".encode('ascii')), (r"word\\\:more".encode('ascii'), b"?")) tc.assertEqual(pc(b"word\\\nmore:123"), (b"word\\\nmore", b"123")) def test_text_value(tc): text_value = sgf_grammar.text_value tc.assertEqual(text_value(b"abc "), b"abc ") tc.assertEqual(text_value(b"ab c"), b"ab c") tc.assertEqual(text_value(b"ab\tc"), b"ab c") tc.assertEqual(text_value(b"ab \tc"), b"ab c") tc.assertEqual(text_value(b"ab\nc"), b"ab\nc") tc.assertEqual(text_value(b"ab\\\nc"), b"abc") tc.assertEqual(text_value(b"ab\\\\\nc"), b"ab\\\nc") tc.assertEqual(text_value(b"ab\xa0c"), b"ab\xa0c") tc.assertEqual(text_value(b"ab\rc"), b"ab\nc") tc.assertEqual(text_value(b"ab\r\nc"), b"ab\nc") tc.assertEqual(text_value(b"ab\n\rc"), b"ab\nc") tc.assertEqual(text_value(b"ab\r\n\r\nc"), b"ab\n\nc") tc.assertEqual(text_value(b"ab\r\n\r\n\rc"), b"ab\n\n\nc") tc.assertEqual(text_value(b"ab\\\r\nc"), b"abc") tc.assertEqual(text_value(b"ab\\\n\nc"), b"ab\nc") tc.assertEqual(text_value(b"ab\\\tc"), b"ab c") # These can't actually appear as SGF PropValues; anything sane will do tc.assertEqual(text_value(b"abc\\"), b"abc") tc.assertEqual(text_value(b"abc]"), b"abc]") def test_simpletext_value(tc): simpletext_value = sgf_grammar.simpletext_value tc.assertEqual(simpletext_value(b"abc "), b"abc ") tc.assertEqual(simpletext_value(b"ab c"), b"ab c") tc.assertEqual(simpletext_value(b"ab\tc"), b"ab c") tc.assertEqual(simpletext_value(b"ab \tc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\nc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\\\nc"), b"abc") tc.assertEqual(simpletext_value(b"ab\\\\\nc"), b"ab\\ c") tc.assertEqual(simpletext_value(b"ab\xa0c"), b"ab\xa0c") tc.assertEqual(simpletext_value(b"ab\rc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\r\nc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\n\rc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\r\n\r\nc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\r\n\r\n\rc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\\\r\nc"), b"abc") tc.assertEqual(simpletext_value(b"ab\\\n\nc"), b"ab c") tc.assertEqual(simpletext_value(b"ab\\\tc"), b"ab c") # These can't actually appear as SGF PropValues; anything sane will do tc.assertEqual(simpletext_value(b"abc\\"), b"abc") tc.assertEqual(simpletext_value(b"abc]"), b"abc]") def test_escape_text(tc): tc.assertEqual(sgf_grammar.escape_text(b"abc"), b"abc") tc.assertEqual(sgf_grammar.escape_text(r"a\bc".encode('ascii')), r"a\\bc".encode('ascii')) tc.assertEqual(sgf_grammar.escape_text(r"ab[c]".encode('ascii')), r"ab[c\]".encode('ascii')) tc.assertEqual(sgf_grammar.escape_text(r"a\]bc".encode('ascii')), r"a\\\]bc".encode('ascii')) def test_text_roundtrip(tc): def roundtrip(s): return sgf_grammar.text_value(sgf_grammar.escape_text(s)) tc.assertEqual(roundtrip(b"abc"), b"abc") tc.assertEqual(roundtrip(r"a\bc".encode('ascii')), r"a\bc".encode('ascii')) tc.assertEqual(roundtrip(b"abc\\"), b"abc\\") tc.assertEqual(roundtrip(b"ab]c"), b"ab]c") tc.assertEqual(roundtrip(b"abc]"), b"abc]") tc.assertEqual(roundtrip(r"abc\]".encode('ascii')), r"abc\]".encode('ascii')) tc.assertEqual(roundtrip(b"ab\nc"), b"ab\nc") tc.assertEqual(roundtrip(b"ab\n c"), b"ab\n c") tc.assertEqual(roundtrip(b"ab\tc"), b"ab c") tc.assertEqual(roundtrip(b"ab\r\nc\n"), b"ab\nc\n") def test_serialise_game_tree(tc): serialised = (b"(;AB[aa][ab][ac]C[comment \xa3];W[ab];C[];C[]" b"(;B[bc])(;B[bd];W[ca](;B[da])(;B[db];\n" b"W[ea])))\n") coarse_game = sgf_grammar.parse_sgf_game(serialised) tc.assertEqual(sgf_grammar.serialise_game_tree(coarse_game), serialised) tc.assertEqual(sgf_grammar.serialise_game_tree(coarse_game, wrap=None), serialised.replace(b"\n", b"")+b"\n")
[ "gcaaa31928@gmail.com" ]
gcaaa31928@gmail.com
6376fb9392d11160868a6f7f6fcd88553812000f
c1a7e00efbf7ebb2a60063c62eb2642631a49fd8
/backend/src/passwordreset/admin.py
f7e0157a57cddc8951fc543b9e6532b644466ad1
[]
no_license
rajesh241/GandhiCollectedWorks
a8557c3367a69be9e13606cef0bb74d11e8bc747
efb68310a1362791e4cda09e7bb54ae91e407db3
refs/heads/master
2023-01-21T10:19:19.465420
2021-02-21T11:10:33
2021-02-21T11:10:33
194,344,659
2
0
null
2023-01-07T15:00:15
2019-06-28T23:40:41
HTML
UTF-8
Python
false
false
299
py
""" contains basic admin views for MultiToken """ from django.contrib import admin from passwordreset.models import ResetPasswordToken @admin.register(ResetPasswordToken) class ResetPasswordTokenAdmin(admin.ModelAdmin): list_display = ('user', 'key', 'created_at', 'ip_address', 'user_agent')
[ "togoli@gmail.com" ]
togoli@gmail.com
79c186e80eb2eee32c1ac2621e0123201dd4c013
d0510d14958c0881eb8ac6266f87a183513062f0
/peas/plotting/create_plots.py
7caab92e33283597dd9019a13c941c0eed798aa8
[ "Apache-2.0" ]
permissive
13thProgression/peas-blockchain
382095f5dc99513e9f79b01209414439d6ab99f4
8e058cbfe0c1ab73f7c1ec41bedb39071c63141c
refs/heads/main
2023-08-22T10:51:57.731419
2021-10-13T00:55:41
2021-10-13T00:55:41
411,798,736
0
1
Apache-2.0
2021-10-13T00:55:42
2021-09-29T19:08:40
null
UTF-8
Python
false
false
11,355
py
import logging from datetime import datetime from pathlib import Path from secrets import token_bytes from typing import List, Optional, Tuple from blspy import AugSchemeMPL, G1Element, PrivateKey from chiapos import DiskPlotter from peas.daemon.keychain_proxy import KeychainProxy, connect_to_keychain_and_validate, wrap_local_keychain from peas.plotting.util import add_plot_directory from peas.plotting.util import stream_plot_info_ph, stream_plot_info_pk from peas.types.blockchain_format.proof_of_space import ProofOfSpace from peas.types.blockchain_format.sized_bytes import bytes32 from peas.util.bech32m import decode_puzzle_hash from peas.util.config import config_path_for_filename, load_config from peas.util.keychain import Keychain from peas.util.path import mkdir from peas.wallet.derive_keys import master_sk_to_farmer_sk, master_sk_to_local_sk, master_sk_to_pool_sk log = logging.getLogger(__name__) class PlotKeys: def __init__( self, farmer_public_key: G1Element, pool_public_key: Optional[G1Element], pool_contract_address: Optional[str], ): self.farmer_public_key = farmer_public_key self.pool_public_key = pool_public_key self.pool_contract_address = pool_contract_address @property def pool_contract_puzzle_hash(self) -> Optional[bytes32]: if self.pool_contract_address is not None: return decode_puzzle_hash(self.pool_contract_address) return None class PlotKeysResolver: def __init__( self, farmer_public_key: str, alt_fingerprint: int, pool_public_key: str, pool_contract_address: str, root_path: Path, log: logging.Logger, connect_to_daemon=False, ): self.farmer_public_key = farmer_public_key self.alt_fingerprint = alt_fingerprint self.pool_public_key = pool_public_key self.pool_contract_address = pool_contract_address self.root_path = root_path self.log = log self.connect_to_daemon = connect_to_daemon self.resolved_keys: Optional[PlotKeys] = None async def resolve(self) -> PlotKeys: if self.resolved_keys is not None: return self.resolved_keys keychain_proxy: Optional[KeychainProxy] = None if self.connect_to_daemon: keychain_proxy = await connect_to_keychain_and_validate(self.root_path, self.log) else: keychain_proxy = wrap_local_keychain(Keychain(), log=self.log) farmer_public_key: G1Element if self.farmer_public_key is not None: farmer_public_key = G1Element.from_bytes(bytes.fromhex(self.farmer_public_key)) else: farmer_public_key = await self.get_farmer_public_key(keychain_proxy) pool_public_key: Optional[G1Element] = None if self.pool_public_key is not None: if self.pool_contract_address is not None: raise RuntimeError("Choose one of pool_contract_address and pool_public_key") pool_public_key = G1Element.from_bytes(bytes.fromhex(self.pool_public_key)) else: if self.pool_contract_address is None: # If nothing is set, farms to the provided key (or the first key) pool_public_key = await self.get_pool_public_key(keychain_proxy) self.resolved_keys = PlotKeys(farmer_public_key, pool_public_key, self.pool_contract_address) return self.resolved_keys async def get_sk(self, keychain_proxy: Optional[KeychainProxy] = None) -> Optional[Tuple[PrivateKey, bytes]]: sk: Optional[PrivateKey] = None if keychain_proxy: try: if self.alt_fingerprint is not None: sk = await keychain_proxy.get_key_for_fingerprint(self.alt_fingerprint) else: sk = await keychain_proxy.get_first_private_key() except Exception as e: log.error(f"Keychain proxy failed with error: {e}") else: sk_ent: Optional[Tuple[PrivateKey, bytes]] = None keychain: Keychain = Keychain() if self.alt_fingerprint is not None: sk_ent = keychain.get_private_key_by_fingerprint(self.alt_fingerprint) else: sk_ent = keychain.get_first_private_key() if sk_ent: sk = sk_ent[0] return sk async def get_farmer_public_key(self, keychain_proxy: Optional[KeychainProxy] = None) -> G1Element: sk: Optional[PrivateKey] = await self.get_sk(keychain_proxy) if sk is None: raise RuntimeError( "No keys, please run 'peas keys add', 'peas keys generate' or provide a public key with -f" ) return master_sk_to_farmer_sk(sk).get_g1() async def get_pool_public_key(self, keychain_proxy: Optional[KeychainProxy] = None) -> G1Element: sk: Optional[PrivateKey] = await self.get_sk(keychain_proxy) if sk is None: raise RuntimeError( "No keys, please run 'peas keys add', 'peas keys generate' or provide a public key with -p" ) return master_sk_to_pool_sk(sk).get_g1() async def resolve_plot_keys( farmer_public_key: str, alt_fingerprint: int, pool_public_key: str, pool_contract_address: str, root_path: Path, log: logging.Logger, connect_to_daemon=False, ) -> PlotKeys: return await PlotKeysResolver( farmer_public_key, alt_fingerprint, pool_public_key, pool_contract_address, root_path, log, connect_to_daemon ).resolve() async def create_plots(args, keys: PlotKeys, root_path, use_datetime=True, test_private_keys: Optional[List] = None): config_filename = config_path_for_filename(root_path, "config.yaml") config = load_config(root_path, config_filename) if args.tmp2_dir is None: args.tmp2_dir = args.tmp_dir assert (keys.pool_public_key is None) != (keys.pool_contract_puzzle_hash is None) num = args.num if args.size < config["min_mainnet_k_size"] and test_private_keys is None: log.warning(f"Creating plots with size k={args.size}, which is less than the minimum required for mainnet") if args.size < 22: log.warning("k under 22 is not supported. Increasing k to 22") args.size = 22 if keys.pool_public_key is not None: log.info( f"Creating {num} plots of size {args.size}, pool public key: " f"{bytes(keys.pool_public_key).hex()} farmer public key: {bytes(keys.farmer_public_key).hex()}" ) else: assert keys.pool_contract_puzzle_hash is not None log.info( f"Creating {num} plots of size {args.size}, pool contract address: " f"{keys.pool_contract_address} farmer public key: {bytes(keys.farmer_public_key).hex()}" ) tmp_dir_created = False if not args.tmp_dir.exists(): mkdir(args.tmp_dir) tmp_dir_created = True tmp2_dir_created = False if not args.tmp2_dir.exists(): mkdir(args.tmp2_dir) tmp2_dir_created = True mkdir(args.final_dir) finished_filenames = [] for i in range(num): # Generate a random master secret key if test_private_keys is not None: assert len(test_private_keys) == num sk: PrivateKey = test_private_keys[i] else: sk = AugSchemeMPL.key_gen(token_bytes(32)) # The plot public key is the combination of the harvester and farmer keys # New plots will also include a taproot of the keys, for extensibility include_taproot: bool = keys.pool_contract_puzzle_hash is not None plot_public_key = ProofOfSpace.generate_plot_public_key( master_sk_to_local_sk(sk).get_g1(), keys.farmer_public_key, include_taproot ) # The plot id is based on the harvester, farmer, and pool keys if keys.pool_public_key is not None: plot_id: bytes32 = ProofOfSpace.calculate_plot_id_pk(keys.pool_public_key, plot_public_key) plot_memo: bytes32 = stream_plot_info_pk(keys.pool_public_key, keys.farmer_public_key, sk) else: assert keys.pool_contract_puzzle_hash is not None plot_id = ProofOfSpace.calculate_plot_id_ph(keys.pool_contract_puzzle_hash, plot_public_key) plot_memo = stream_plot_info_ph(keys.pool_contract_puzzle_hash, keys.farmer_public_key, sk) if args.plotid is not None: log.info(f"Debug plot ID: {args.plotid}") plot_id = bytes32(bytes.fromhex(args.plotid)) if args.memo is not None: log.info(f"Debug memo: {args.memo}") plot_memo = bytes.fromhex(args.memo) # Uncomment next two lines if memo is needed for dev debug plot_memo_str: str = plot_memo.hex() log.info(f"Memo: {plot_memo_str}") dt_string = datetime.now().strftime("%Y-%m-%d-%H-%M") if use_datetime: filename: str = f"plot-k{args.size}-{dt_string}-{plot_id}.plot" else: filename = f"plot-k{args.size}-{plot_id}.plot" full_path: Path = args.final_dir / filename resolved_final_dir: str = str(Path(args.final_dir).resolve()) plot_directories_list: str = config["harvester"]["plot_directories"] if args.exclude_final_dir: log.info(f"NOT adding directory {resolved_final_dir} to harvester for farming") if resolved_final_dir in plot_directories_list: log.warning(f"Directory {resolved_final_dir} already exists for harvester, please remove it manually") else: if resolved_final_dir not in plot_directories_list: # Adds the directory to the plot directories if it is not present log.info(f"Adding directory {resolved_final_dir} to harvester for farming") config = add_plot_directory(root_path, resolved_final_dir) if not full_path.exists(): log.info(f"Starting plot {i + 1}/{num}") # Creates the plot. This will take a long time for larger plots. plotter: DiskPlotter = DiskPlotter() plotter.create_plot_disk( str(args.tmp_dir), str(args.tmp2_dir), str(args.final_dir), filename, args.size, plot_memo, plot_id, args.buffer, args.buckets, args.stripe_size, args.num_threads, args.nobitfield, ) finished_filenames.append(filename) else: log.info(f"Plot {filename} already exists") log.info("Summary:") if tmp_dir_created: try: args.tmp_dir.rmdir() except Exception: log.info(f"warning: did not remove primary temporary folder {args.tmp_dir}, it may not be empty.") if tmp2_dir_created: try: args.tmp2_dir.rmdir() except Exception: log.info(f"warning: did not remove secondary temporary folder {args.tmp2_dir}, it may not be empty.") log.info(f"Created a total of {len(finished_filenames)} new plots") for filename in finished_filenames: log.info(filename)
[ "jincao@126.com" ]
jincao@126.com
01b29bd4c0ab79ad15650e94fa06bb276c2daa04
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5752104073297920_0/Python/festony/2014_r1A_C.py
6c2ad6f11d19adb3199ff6afe0482c43aab22da6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
2,432
py
''' CodeJam Practice Created on 2012-12-20 @author: festony ''' from cj_lib import * from properties import * import math import fractions #curr_file_name = 'C-large' curr_file_name = 'C-small-attempt1' #curr_file_name = 'test' # map(int, input_lines.pop(0).split(' ')) def input_dividing_func(input_lines): total_case = int(input_lines.pop(0)) case_inputs = [] for i in range(total_case): N = int(input_lines.pop(0)) p = map(int, input_lines.pop(0).split(' ')) case_inputs.append([N, p]) return case_inputs def stay_same_p(N): P = fractions.Fraction(0) for i in range(N): p = fractions.Fraction(1) p *= math.factorial(N-1) p /= math.factorial(N-1-i) p *= int(math.pow(N-i-1, N-i-1)) p /= int(math.pow(N, N)) P += p return P def process_func(func_input): N, p = func_input c = 0 for i in range(N): if i == p[i]: c += 1 if c >= N/2-1: return 'BAD' return 'GOOD' run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name) #print (stay_same_p(4)) #print float(stay_same_p(4)) ##print math.pow(1000,1000) #def gen_good_perm(N): # if N == 1: # return [[1]] # ps = [] # sps = gen_good_perm(N-1) # for i in range(N): # p = [] # for sp in sps: # p = sp[:] # p.insert(i, N) # ps.append(p) # return ps # #print gen_good_perm(4) # #def gen_bad_perm(N): # bp = range(1, N+1) # ps = [] # for i in range(N): # p = bp[:] # if i > 0: # p[0], p[i] = p[i], p[0] # ps.append(p) # tps = [] # for i in range(1, N): # for b in ps: # for i in range(N): # p = b[:] # if i > 0: # p[0], p[i] = p[i], p[0] # tps.append(p) # ps = tps # tps = [] # return ps # #x = gen_bad_perm(4) #y = [] #for xx in x: # y.append(tuple(xx)) #print y # #d = dict() #for yy in y: # if d.has_key(yy): # d[yy] += 1 # else: # d[yy] = 1 #z = [] #for k in d.keys(): # #print k, d[k] # z.append([list(k), d[k]]) #z.sort(cmp=None, key=lambda x:x[1], reverse=False) #print z #for zz in z: # print zz #print sum(map(lambda x:x[1], z))
[ "eewestman@gmail.com" ]
eewestman@gmail.com
009e681b99ae5412a43a6b8aaa5ec64851a1afb1
7030259044f2afd4164f2f0507bdb9f091708067
/project/settings/dev.py
f5a58a8568aa08a174cd82beca88bf9f92851863
[]
no_license
m2candre/django-vue-template
f64fa5c28e08abeab7f10dcb2d3a93132d5a969a
79517dbcaf740f07bad6fc19a18ba36e1e9fdd24
refs/heads/master
2020-03-25T23:35:29.759950
2018-08-10T06:19:21
2018-08-10T06:19:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,016
py
""" Django settings for project project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) SETTINGS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(SETTINGS_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z-+$tyr)mif-dsjx)vd#pkay86u_((ut^8(_0)283#bus5k&he' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', # < Per Whitenoise, to disable built in 'django.contrib.staticfiles', 'rest_framework', 'project.api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Add dist to 'DIRS': ['dist'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ # When Vue Builds, path will be `/static/css/...` so we will have Django Serve # In Production, it's recommended use an alternative approach such as: # http://whitenoise.evans.io/en/stable/django.html?highlight=django STATIC_URL = '/static/' # Serve `dist` as is, built by webpack STATIC_ROOT = os.path.join(BASE_DIR, 'dist', 'static') STATICFILES_DIRS = [] ########## # STATIC # ########## STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Insert Whitenoise Middleware at top but below Security Middleware # MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware',) # http://whitenoise.evans.io/en/stable/django.html#make-sure-staticfiles-is-configured-correctly
[ "gtalarico@gmail.com" ]
gtalarico@gmail.com
8d8aff77d83973f585f201fd0852388ae2b83750
5077fc5d82caa3b3ed5ce0e062bfe75cd4037ebc
/杂项/豆瓣2.0.py
ca3069d5209891cdea35ff7b96a964dff22a719e
[]
no_license
asswecanfat/git_place
ee10e1057d8307d3c72f57291b5bcb6d0579017e
244ff0de11ffbe1aa9f20308e43af39486507f6f
refs/heads/master
2021-07-18T23:06:14.324164
2020-09-02T12:15:27
2020-09-02T12:15:27
210,833,462
1
2
null
null
null
null
UTF-8
Python
false
false
3,177
py
import requests from bs4 import BeautifulSoup import re class Douban_login: def login(self): def post_data(data):#发送data并判断是否登陆成功 reponse = s.post(url, data = data, headers = headers) if str(reponse.url) == final_url: print('登陆成功!') else: print('登陆失败,请再次重试!!') soup = BeautifulSoup(reponse.text, 'html.parser') soup1 = soup.find_all('span') user_name = soup1[0].string.replace('的帐号', '') print('登陆的账号为:' + user_name) def get_txt(url_data_text):#获取网页源文件 with open('C:\\Users\\10248\\Desktop\\url_data.txt', 'w', encoding = 'utf-8') as f: f.write(url_data_text) def get_pit(pit_url):#获取验证码 pit_data = s.get(pit_url) with open('C:\\Users\\10248\\Desktop\\yzm.jpg', 'wb') as f: f.write(pit_data.content) def get_url_data(url):#获取页面数据 url_data = s.get(url, headers = headers) return url_data.text def deal_url_data(url_data_text):#处理网页并找出和下载验证码 global yzm soup = BeautifulSoup(url_data_text, 'html.parser') soup1 = soup.find_all('img', id = 'captcha_image') if int(len(soup1)) == 0: yzm = 0 print('无需验证码') else: yzm = 1 pit_url = soup1[0].get('src') get_pit(pit_url) return pit_url def get_data(pit_url):#处理captcha:id并放入data中 if yzm == 0: data={ 'source' : 'index_nav', 'form_email' : user_ac, 'form_password' : user_password, 'user_login' : '登录' } return data else: p = r'.+id=(.+)&size=s' data_list = re.findall(p, pit_url)#列表 data = { 'source' : 'index_nav', 'form_email' : user_ac, 'form_password' : user_password, 'captcha-solution' : user_getin, 'captcha-id' : data_list[0], 'user_login' : '登录' } return data url = 'https://www.douban.com/accounts/login' final_url = 'https://www.douban.com/' user_ac = str(input('请输入账号:')) user_password = str(input('请输入密码:')) s = requests.Session() headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',\ 'Referer':'https://www.douban.com/'} url_data_text = get_url_data(url) pit_url = deal_url_data(url_data_text) if yzm == 1: user_getin = str(input('请输入验证码:')) data = get_data(pit_url) post_data(data)
[ "1024847824@qq.com" ]
1024847824@qq.com
998b1ddc40d9341734d6d53772d4c1c0015de1a3
876de904572c611b8cbad21f50877cdc812f2946
/Leetcode/103. 二叉树的锯齿形层次遍历.py
77492d7c29f409cbabe69df893d7f7c2079e571c
[ "MIT" ]
permissive
QDylan/Learning-
66a33de0e15f26672fb63c0b393866721def27ae
f09e0aa3de081883b4a7ebfe4d31b5f86f24b64f
refs/heads/master
2023-02-08T02:34:26.616116
2020-12-25T05:02:32
2020-12-25T05:02:32
263,805,536
0
0
null
null
null
null
UTF-8
Python
false
false
1,330
py
# -*- coding: utf-8 -*- """ @Time : 2020/7/14 8:28 @Author : QDY @FileName: 103. 二叉树的锯齿形层次遍历.py 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回锯齿形层次遍历如下: [ [3], [20,9], [15,7] ] """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root): if not root: return [] queue, res, mark = [root], [], False while queue: length = len(queue) tmp = [] for i in range(length): node = queue.pop(0) tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) if mark: tmp.reverse() mark = False else: mark = True res.append(tmp) return res
[ "qdy960411@outlook.com" ]
qdy960411@outlook.com
4ee9494f0c45ab6a761d51a2fd97c8ffaa0268e9
168556624401cd884fe0bfdac5a312adf51286a1
/CS1430/homework4_sceneclassification-Enmin/code/create_results_webpage.py
5c57e681a7d8cba065ea34346d769b5d152bf014
[]
no_license
Enmin/Coursework
f39dc7b54a07b901491fbd809187fd54e96fa5a4
a17d216c37e70a8073602389924af10019cfe7de
refs/heads/master
2021-12-28T02:53:15.949547
2021-12-21T22:45:19
2021-12-21T22:45:19
179,909,211
0
0
null
null
null
null
UTF-8
Python
false
false
12,869
py
import matplotlib.pyplot as plt import numpy as np import warnings import skimage import glob import os from skimage import io # Skimage gives us some lossy conversion errors that we really don't care about # so we suppress them warnings.filterwarnings('ignore', '', UserWarning) def create_results_webpage(train_image_paths, test_image_paths, train_labels, test_labels, categories, abbr_categories, predicted_categories): ''' Starter code prepared by James Hays for CSCI 1430 Computer Vision Converted to Python by Brendan Walsh This function creates a webpage (html and images) visualizing the classiffication results. This webpage will contain: (1) A confusion matrix plot (2) A table with one row per category, with 4 columns - training examples, true positives, false positives, and false negatives. False positives are instances claimed as that category but belonging to another category, e.g. in the 'forest' row an image that was classified as 'forest' but is actually 'mountain'. This same image would be considered a false negative in the 'mountain' row, because it should have been claimed by the 'mountain' classifier but was not. This webpage is similar to the one created for the SUN database in 2010: http://people.csail.mit.edu/jxiao/SUN/classification397.html ''' print('Creating results_webpage/index.html, thumbnails, and confusion matrix.') # Number of examples of training examples, true positives, false positives, # and false negatives. Thus the table will be num_samples * 4 images wide # (unless there aren't enough images) num_samples = 2 thumbnail_height = 75 #pixels num_categories = len(categories) # Convert everything over to numpy arrays categories = np.array(categories) predicted_categories = np.array(predicted_categories) train_labels = np.array(train_labels) test_labels = np.array(test_labels) # Delete the old thumbnails, if there are any files = glob.glob('results_webpage/thumbnails/*.jpg') for f in files: os.remove(f) if not os.path.isdir('results_webpage'): print('Making results_webpage directory.') os.mkdir('results_webpage') if not os.path.isdir('results_webpage/thumbnails'): print('Making thumbnails directory.') os.mkdir('results_webpage/thumbnails') ### Create And Save Confusion Matrix ### # Based on the predicted category for each test case, we will now build a # confusion matrix. Entry (i,j) in this matrix well be the proportion of # times a test image of ground truth category i was predicted to be # category j. An identity matrix is the ideal case. You should expect # roughly 50-95% along the diagonal depending on your features, # classifiers, and particular categories. For example, suburb is very easy # to recognize. with open('results_webpage/index.html', 'w+') as f: # Initialize the matrix confusion_matrix = np.zeros((num_categories, num_categories)) # Iterate over predicted results (this is like, several hundred items long) for i,cat in enumerate(predicted_categories): # Find the row and column corresponding to the label of this entry # The row is the ground truth label and the column is the found label row = np.argwhere(categories == test_labels[i])[0][0] column = np.argwhere(categories == predicted_categories[i])[0][0] # Add 1 to the matrix for that row/col # This way we build up a histogram from our labeled data confusion_matrix[row][column] += 1; # If the number of training examples and test cases are not equal, this # statement will be invalid! # TODO: That's an old comment left over from the matlab code that I don't # think still applies num_test_per_cat = len(test_labels) / num_categories confusion_matrix = confusion_matrix / float(num_test_per_cat) accuracy = np.mean(np.diag(confusion_matrix)) print('Accuracy (mean of diagonal of confusion matrix) is {:2.3%}'.format(accuracy)) # plasma is the most easily-interpreted color map I've found so far plt.imshow(confusion_matrix, cmap='plasma', interpolation='nearest') # We put the shortened labels (e.g. "sub" for "suburb") on the x axis locs, labels = plt.xticks() plt.xticks(np.arange(num_categories), abbr_categories) # Full labels go on y locs, labels = plt.yticks() plt.yticks(np.arange(num_categories), categories) # Save the result plt.savefig('results_webpage/confusion_matrix.png', bbox_inches='tight') ## Create webpage header f.write('<!DOCTYPE html>\n'); f.write('<html>\n'); f.write('<head>\n'); f.write('<link href=''http://fonts.googleapis.com/css?family=Nunito:300|Crimson+Text|Droid+Sans+Mono'' rel=''stylesheet'' type=''text/css''>\n'); f.write('<style type="text/css">\n'); f.write('body {\n'); f.write(' margin: 0px;\n'); f.write(' width: 100%;\n'); f.write(' font-family: ''Crimson Text'', serif;\n'); f.write(' background: #fcfcfc;\n'); f.write('}\n'); f.write('table td {\n'); f.write(' text-align: center;\n'); f.write(' vertical-align: middle;\n'); f.write('}\n'); f.write('h1 {\n'); f.write(' font-family: ''Nunito'', sans-serif;\n'); f.write(' font-weight: normal;\n'); f.write(' font-size: 28px;\n'); f.write(' margin: 25px 0px 0px 0px;\n'); f.write(' text-transform: lowercase;\n'); f.write('}\n'); f.write('.container {\n'); f.write(' margin: 0px auto 0px auto;\n'); f.write(' width: 1160px;\n'); f.write('}\n'); f.write('</style>\n'); f.write('</head>\n'); f.write('<body>\n\n'); f.write('<div class="container">\n\n\n'); f.write('<center>\n'); f.write('<h1>Scene classification results visualization</h1>\n'); f.write('<img src="confusion_matrix.png">\n\n'); f.write('<br>\n'); f.write('Accuracy (mean of diagonal of confusion matrix) is %2.3f\n' % (accuracy)); f.write('<p>\n\n'); ## Create results table f.write('<table border=0 cellpadding=4 cellspacing=1>\n'); f.write('<tr>\n'); f.write('<th>Category name</th>\n'); f.write('<th>Accuracy</th>\n'); f.write('<th colspan=%d>Sample training images</th>\n' % num_samples); f.write('<th colspan=%d>Sample true positives</th>\n' % num_samples); f.write('<th colspan=%d>False positives with true label</th>\n' % num_samples); f.write('<th colspan=%d>False negatives with wrong predicted label</th>\n' % num_samples); f.write('</tr>\n'); for i,cat in enumerate(categories): f.write('<tr>\n'); f.write('<td>'); #category name f.write('%s' % cat); f.write('</td>\n'); f.write('<td>'); # category accuracy f.write('%.3f' % confusion_matrix[i][i]); f.write('</td>\n'); # Collect num_samples random paths to images of each type. # Training examples. train_examples = np.take(train_image_paths, np.argwhere(train_labels == cat)) # True positives. There might not be enough of these if the classifier # is bad true_positives = np.take(test_image_paths, np.argwhere(np.logical_and(test_labels == cat, predicted_categories == cat))) # False positives. There might not be enough of them if the classifier # is good false_positive_inds = np.argwhere(np.logical_and(np.invert(cat == test_labels), cat == predicted_categories)) false_positives = np.take(test_image_paths, false_positive_inds) false_positive_labels = np.take(test_labels, false_positive_inds) # False negatives. There might not be enough of them if the classifier # is good false_negative_inds = np.argwhere(np.logical_and(cat == test_labels, np.invert(cat == predicted_categories))) false_negatives = np.take(test_image_paths, false_negative_inds) false_negative_labels = np.take(predicted_categories, false_negative_inds) # Randomize each list of files np.random.shuffle(train_examples) np.random.shuffle(true_positives) # HACK: Well, sort of a hack. We need to shuffle the false_positives # and their labels in the same exact order, so we get the RNG state, # save it, shuffle, restore, then shuffle the other list so that they # shuffle in tandem. rng_state = np.random.get_state() np.random.shuffle(false_positives) np.random.set_state(rng_state) np.random.shuffle(false_positive_labels) rng_state = np.random.get_state() np.random.shuffle(false_negatives) np.random.set_state(rng_state) np.random.shuffle(false_negative_labels) # Truncate each list to be at most num_samples long train_examples = train_examples[0:min(len(train_examples), num_samples)] true_positives = true_positives[0:min(len(true_positives), num_samples)] false_positives = false_positives[0:min(len(false_positives), num_samples)] false_positive_labels = false_positive_labels[0:min(len(false_positive_labels),num_samples)] false_negatives = false_negatives[0:min(len(false_negatives),num_samples)] false_negative_labels = false_negative_labels[0:min(len(false_negative_labels),num_samples)] # Sample training images # Create and save all of the thumbnails for j in range(num_samples): if j + 1 <= len(train_examples): thisExample = train_examples[j][0] tmp = skimage.io.imread(thisExample) height, width = rescale(tmp.shape, thumbnail_height) tmp = skimage.transform.resize(tmp, (height, width), anti_aliasing=True, mode='wrap') name = os.path.basename(thisExample) tmp_uint8 = (tmp * 255).astype(np.uint8) skimage.io.imsave('results_webpage/thumbnails/' + cat + '_' + name, tmp_uint8, quality=100) f.write('<td bgcolor=LightBlue>') f.write('<img src="%s" width=%d height=%d>' % ('thumbnails/' + cat + '_' + name, width, height)) f.write('</td>\n') else: f.write('<td bgcolor=LightBlue>') f.write('</td>\n') for j in range(num_samples): if j + 1 <= len(true_positives): thisExample = true_positives[j][0] tmp = skimage.io.imread(thisExample) height, width = rescale(tmp.shape, thumbnail_height) tmp = skimage.transform.resize(tmp, (height, width), anti_aliasing=True, mode='wrap') name = os.path.basename(thisExample) tmp_uint8 = (tmp * 255).astype(np.uint8) skimage.io.imsave('results_webpage/thumbnails/' + cat + '_' + name, tmp_uint8, quality=100) f.write('<td bgcolor=LightGreen>'); f.write('<img src="%s" width=%d height=%d>' % ('thumbnails/' + cat + '_' + name, width, height)) f.write('</td>\n'); else: f.write('<td bgcolor=LightGreen>'); f.write('</td>\n'); for j in range(num_samples): if j + 1 <= len(false_positives): thisExample = false_positives[j][0] tmp = skimage.io.imread(thisExample) height, width = rescale(tmp.shape, thumbnail_height) tmp = skimage.transform.resize(tmp, (height, width), anti_aliasing=True, mode='wrap') name = os.path.basename(thisExample) tmp_uint8 = (tmp * 255).astype(np.uint8) skimage.io.imsave('results_webpage/thumbnails/' + cat + '_' + name, tmp_uint8, quality=100) f.write('<td bgcolor=LightCoral>'); f.write('<img src="%s" width=%d height=%d>' % ('thumbnails/' + cat + '_' + name, width, height)) f.write('<br><small>%s</small>' % false_positive_labels[j][0]); f.write('</td>\n'); else: f.write('<td bgcolor=LightCoral>'); f.write('</td>\n'); for j in range(num_samples): if j + 1 <= len(false_negatives): thisExample = false_negatives[j][0] tmp = skimage.io.imread(thisExample) height, width = rescale(tmp.shape, thumbnail_height) tmp = skimage.transform.resize(tmp, (height, width), anti_aliasing=True, mode='wrap') name = os.path.basename(thisExample) tmp_uint8 = (tmp * 255).astype(np.uint8) skimage.io.imsave('results_webpage/thumbnails/' + cat + '_' + name, tmp_uint8, quality=100) f.write('<td bgcolor=#FFBB55>'); f.write('<img src="%s" width=%d height=%d>' % ('thumbnails/' + cat + '_' + name, width, height)); f.write('<br><small>%s</small>' % false_negative_labels[j][0]); f.write('</td>\n'); else: f.write('<td bgcolor=#FFBB55>'); f.write('</td>\n'); f.write('</tr>\n'); f.write('<tr>\n'); f.write('<th>Category name</th>\n'); f.write('<th>Accuracy</th>\n'); f.write('<th colspan=%d>Sample training images</th>\n' % num_samples); f.write('<th colspan=%d>Sample true positives</th>\n' % num_samples); f.write('<th colspan=%d>False positives with true label</th>\n' % num_samples); f.write('<th colspan=%d>False negatives with wrong predicted label</th>\n' % num_samples); f.write('</tr>\n'); f.write('</table>\n'); f.write('</center>\n\n\n'); f.write('</div>\n'); ## Create end of web page f.write('</body>\n'); f.write('</html>\n'); print('Wrote results page to results_webpage/index.html.') def rescale(dims, thumbnail_height): height = dims[1] factor = thumbnail_height / height left = int(round(dims[0] * factor)) right = int(round(dims[1] * factor)) return (left, right)
[ "zhouem14@gmail.com" ]
zhouem14@gmail.com
306a3bd19cae6afd4c07662217dfa4233cc55817
4e808ecca7a94a70a63c59b4c91a15cd61bada6e
/natuurpunt_imp_members/__init__.py
aa961a1fb03e95eeccdde06ef8b561394c9cab51
[]
no_license
smart-solution/natuurpunt-crm
79b98cfc8c69027dc82afa3779b65616141e6779
0bd247e78c01e79ec54b90c0d0bcaca38742f04d
refs/heads/master
2021-05-22T05:43:42.913854
2020-12-02T08:06:05
2020-12-02T08:06:05
39,186,027
0
0
null
2020-12-02T08:06:06
2015-07-16T08:36:27
Python
UTF-8
Python
false
false
228
py
# -*- encoding: utf-8 -*- ############################################################################## # # ############################################################################## import natuurpunt_imp_members
[ "fabian.semal@smartsolution.be" ]
fabian.semal@smartsolution.be
221069477e0d8b653578b817b9402d37916c81ea
2e5dd9e5c634c1c2163b96a3607f9806a9598d39
/rastervision2/pytorch_learner/semantic_segmentation_learner.py
38fec3f11bd120f09443b73f6423fae3662d50e7
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
jpolchlo/raster-vision
8fc60c8bfa2d6319810c3414606400abd63ff633
8aa9601d168de2c6bbc00d7f5ba2b70f1d5f7f13
refs/heads/master
2022-10-29T07:39:15.551708
2020-04-28T19:20:42
2020-04-28T19:20:42
259,924,470
0
0
null
null
null
null
UTF-8
Python
false
false
4,656
py
import warnings warnings.filterwarnings('ignore') # noqa from os.path import join, isdir, basename import logging import glob import numpy as np import matplotlib matplotlib.use('Agg') # noqa import torch from torch.utils.data import Dataset, ConcatDataset import torch.nn.functional as F from torchvision import models from PIL import Image from rastervision2.pytorch_learner.learner import Learner from rastervision2.pytorch_learner.utils import ( compute_conf_mat_metrics, compute_conf_mat, color_to_triple) log = logging.getLogger(__name__) class SemanticSegmentationDataset(Dataset): def __init__(self, data_dir, transform=None): self.data_dir = data_dir self.img_paths = glob.glob(join(data_dir, 'img', '*.png')) self.transform = transform def __getitem__(self, ind): img_path = self.img_paths[ind] label_path = join(self.data_dir, 'labels', basename(img_path)) x = Image.open(img_path) y = Image.open(label_path) x = np.array(x) y = np.array(y) if self.transform is not None: out = self.transform(image=x, mask=y) x = out['image'] y = out['mask'] x = torch.tensor(x).permute(2, 0, 1).float() / 255.0 y = torch.tensor(y).long() return (x, y) def __len__(self): return len(self.img_paths) class SemanticSegmentationLearner(Learner): def build_model(self): # TODO support FCN option model = models.segmentation.segmentation._segm_resnet( 'deeplabv3', self.cfg.model.get_backbone_str(), len(self.cfg.data.class_names), False, pretrained_backbone=True) return model def get_datasets(self): cfg = self.cfg data_dirs = self.unzip_data() transform, aug_transform = self.get_data_transforms() train_ds, valid_ds, test_ds = [], [], [] for data_dir in data_dirs: train_dir = join(data_dir, 'train') valid_dir = join(data_dir, 'valid') if isdir(train_dir): if cfg.overfit_mode: train_ds.append( SemanticSegmentationDataset( train_dir, transform=transform)) else: train_ds.append( SemanticSegmentationDataset( train_dir, transform=aug_transform)) if isdir(valid_dir): valid_ds.append( SemanticSegmentationDataset( valid_dir, transform=transform)) test_ds.append( SemanticSegmentationDataset( valid_dir, transform=transform)) train_ds, valid_ds, test_ds = \ ConcatDataset(train_ds), ConcatDataset(valid_ds), ConcatDataset(test_ds) return train_ds, valid_ds, test_ds def train_step(self, batch, batch_ind): x, y = batch out = self.post_forward(self.model(x)) return {'train_loss': F.cross_entropy(out, y)} def validate_step(self, batch, batch_ind): x, y = batch out = self.post_forward(self.model(x)) val_loss = F.cross_entropy(out, y) num_labels = len(self.cfg.data.class_names) y = y.view(-1) out = self.prob_to_pred(out).view(-1) conf_mat = compute_conf_mat(out, y, num_labels) return {'val_loss': val_loss, 'conf_mat': conf_mat} def validate_end(self, outputs, num_samples): conf_mat = sum([o['conf_mat'] for o in outputs]) val_loss = torch.stack([o['val_loss'] for o in outputs]).sum() / num_samples conf_mat_metrics = compute_conf_mat_metrics(conf_mat, self.cfg.data.class_names) metrics = {'val_loss': val_loss.item()} metrics.update(conf_mat_metrics) return metrics def post_forward(self, x): return x['out'] def prob_to_pred(self, x): return x.argmax(1) def plot_xyz(self, ax, x, y, z=None): x = x.permute(1, 2, 0) if x.shape[2] == 1: x = torch.cat([x for _ in range(3)], dim=2) ax.imshow(x) ax.axis('off') labels = z if z is not None else y colors = [color_to_triple(c) for c in self.cfg.data.class_colors] colors = [tuple([_c / 255 for _c in c]) for c in colors] cmap = matplotlib.colors.ListedColormap(colors) labels = labels.numpy() ax.imshow(labels, alpha=0.4, vmin=0, vmax=len(colors), cmap=cmap)
[ "lewfish@gmail.com" ]
lewfish@gmail.com
16e691f5d9996ec589acc9303e1a1b44345a49f2
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03209/s412514584.py
8a91d7202b2f680aa7cfc95494723a5132f74cba
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,472
py
from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify from itertools import permutations, accumulate, combinations, combinations_with_replacement from math import sqrt, ceil, floor, factorial from bisect import bisect_left, bisect_right, insort_left, insort_right from copy import deepcopy from operator import itemgetter from functools import reduce from fractions import gcd import sys def input(): return sys.stdin.readline().rstrip() def I(): return int(input()) def Is(): return map(int, input().split()) def LI(): return list(map(int, input().split())) def TI(): return tuple(map(int, input().split())) def IR(n): return [I() for _ in range(n)] def LIR(n): return [LI() for _ in range(n)] def TIR(n): return [TI() for _ in range(n)] def S(): return input() def Ss(): return input().split() def LS(): return list(input()) def SR(n): return [S() for _ in range(n)] def SsR(n): return [Ss() for _ in range(n)] def LSR(n): return [LS() for _ in range(n)] sys.setrecursionlimit(10**6) MOD = 10**9+7 INF = 10**18 # ----------------------------------------------------------- # n, x = Is() Blen = [0]*(n+1) P = [0]*(n+1) Blen[0] = 1 P[0] = 1 for i in range(1, n): Blen[i] = Blen[i-1]*2 + 3 P[i] = P[i-1]*2 + 1 def burger(i, y): if i == 0: return 0 if y <= 0 else 1 if y <= Blen[i-1] + 1: return burger(i-1, y-1) else: return P[i-1] + 1 + burger(i-1, y-Blen[i-1]-2) print(burger(n, x))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
807db398dd1cd2e6f9f343554b314b6cf2edaaa3
21bbc3fbeb7a1616dbd6993b66dc44d9b30df3e7
/PycharmProjects/samp_proj1/day_201118/assign20_4.py
ae6872a76db98685e7dd0950125cf38c9062df25
[]
no_license
PoornimaDevii/python_training
6124640608d8bf14289ae61b2b28e0db3b473b6f
42b535590a6a244a91bd48b4451b74a29c1aaa80
refs/heads/master
2020-04-05T19:55:49.723114
2018-12-04T11:49:59
2018-12-04T11:49:59
157,157,063
0
0
null
null
null
null
UTF-8
Python
false
false
700
py
# see expandtabs() def gen_f(fname): with open(fname) as file: file_lines = file.readlines() for each in file_lines: if each == '\n': a = each.strip() yield a j = 0 for i in gen_f('/home/cisco/PycharmProjects/samp_proj1/day_201118/para.txt'): print(i) j += 1 print("No of paras",j) # lis = list(map(lambda x: x ,open('para.txt').readlines())) # print(lis) # lis1 =0 # i =0 # count=0 # # while i<len(lis): # count=0 # if i+2 < len ( lis ) and lis[i]!='\n' and lis[i+2]=='\n' : # lis1+=1 # elif i+2 > len ( lis ) and lis[ i ]: # lis1+=1 # i+=1 # # print("The number of paras",lis1) #
[ "poornimadevi.rama@gmail.com" ]
poornimadevi.rama@gmail.com
8495a3c6af74d2c3e28bea856fdf2fc0cbc300d6
50914176887f9f21a3489a9407195ba14831354c
/insert_delete_get_random.py
7d4822ccfec6abae0608b190b89b3b2f2688234c
[]
no_license
nkukarl/leetcode
e8cfc2a31e64b68222ad7af631277f1f66d277bc
b1dbe37e8ca1c88714f91643085625ccced76e07
refs/heads/master
2021-01-10T05:42:04.022807
2018-02-24T03:55:24
2018-02-24T03:55:24
43,725,072
0
0
null
null
null
null
UTF-8
Python
false
false
1,395
py
import random class RandomizedSet(object): def __init__(self): # Use self.vals to store all the elements self.vals = [] # Use element:index as key:value pairs to store position info self.pos = {} def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if val not in self.pos: self.vals.append(val) self.pos[val] = len(self.vals) - 1 return True return False def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. """ if val in self.pos: # Find the index of val index = self.pos[val] # Update position info before swapping elements self.pos[self.vals[-1]] = index # Swap val with the last element of self.vals self.vals[index], self.vals[-1] = self.vals[-1], self.vals[index] # Remove the last element of self.vals self.vals.pop() # Remove position info from self.pos del self.pos[val] return True return False def get_random(self): """ Get a random element from the set. """ return random.choice(self.vals)
[ "kai.wang.nankai@gmail.com" ]
kai.wang.nankai@gmail.com
9ab7d64d30b2d113f53f28daec9949ecff89d635
60f5b2e7916bfb2686f5e0da2a5d9031a097ce05
/test/hlt/pytest/python/com/huawei/iotplatform/client/dto/QueryDevicesInfoInDTO.py
651c76e969fba7bc6266b6f6f356c18de0700aae
[ "BSD-3-Clause" ]
permissive
SuYai/LiteOS_Lab
65f1a73026331f2a78567f07955e43ee82df265f
3c9a579cd17d730e21814efc15076351a365e5f8
refs/heads/iot_link
2020-11-28T18:39:02.989946
2020-03-02T02:09:51
2020-03-02T02:09:51
229,894,455
1
0
BSD-3-Clause
2020-03-05T07:49:17
2019-12-24T07:32:24
C
UTF-8
Python
false
false
498
py
class QueryDevicesInfoInDTO(object): def __init__(self): self.deviceId = None self.select = None self.appId = None def getDeviceId(self): return self.deviceId def setDeviceId(self, deviceId): self.deviceId = deviceId def getSelect(self): return self.select def setSelect(self, select): self.select = select def getAppId(self): return self.appId def setAppId(self, appId): self.appId = appId
[ "xu_liqun@hoperun.com" ]
xu_liqun@hoperun.com
1488329995fbcb36ea381a45fa7fe9f6cb83e31d
ffd5e689f88c49ab7af3554c22dc0c36301084fa
/count_the_smiley_faces.py
d6531cdadb8fdc7555b1e23aa72d792f0cf282e4
[]
no_license
ellismckenzielee/codewars-python
1710e6f0499047139479de386927c7dbd5f1cdf6
af3f4b4534798a58115d0565730aae28ce87437e
refs/heads/master
2023-08-09T13:38:40.964141
2023-08-01T14:45:22
2023-08-01T14:45:22
168,981,376
45
18
null
null
null
null
UTF-8
Python
false
false
458
py
#Count the smiley faces! kata #https://www.codewars.com/kata/583203e6eb35d7980400002a def count_smileys(arr): total = 0 for face in arr: template = [[':',';'], ['-','~'], [')','D']] if len(face) == 2: template = template[0::2] elif len(face) != 3: continue face = list(zip(face, template)) face = list(map(lambda x: x[0] in x[1], face)) total += int(all(face)) return total
[ "ellismckenzielee@gmail.com" ]
ellismckenzielee@gmail.com
157b8295a211d8eb2ee9ad809fd14457e720b6fe
6c151b3952a0c84765b78d82f2db64de92dcbb71
/tests/test_save_multiple.py
7a856cb6ed8fd387768c90d677fb147f60779b1d
[ "MIT" ]
permissive
SmirkCao/jupytext
1e02daf54e24f600bef2ddd4f4d2b91f1c11aa79
3d8c5e8bffe35289dd46df04cd3529f0b8716383
refs/heads/master
2020-08-10T20:17:31.462179
2019-09-29T07:56:11
2019-09-29T07:56:11
214,413,393
1
0
MIT
2019-10-11T10:58:02
2019-10-11T10:58:02
null
UTF-8
Python
false
false
3,510
py
import os import pytest from nbformat.v4.nbbase import new_notebook from nbformat.validator import NotebookValidationError from tornado.web import HTTPError import jupytext from jupytext.contentsmanager import TextFileContentsManager from jupytext.compare import compare_notebooks from .utils import list_notebooks @pytest.mark.parametrize('nb_file', list_notebooks(skip='66')) def test_rmd_is_ok(nb_file, tmpdir): nb = jupytext.read(nb_file) tmp_ipynb = 'notebook.ipynb' tmp_rmd = 'notebook.Rmd' nb.metadata.setdefault('jupytext', {})['formats'] = 'ipynb,Rmd' cm = TextFileContentsManager() cm.root_dir = str(tmpdir) cm.save(model=dict(type='notebook', content=nb), path=tmp_ipynb) nb2 = jupytext.read(str(tmpdir.join(tmp_rmd))) compare_notebooks(nb, nb2, 'Rmd') @pytest.mark.parametrize('nb_file', list_notebooks('Rmd')) def test_ipynb_is_ok(nb_file, tmpdir): nb = jupytext.read(nb_file) tmp_ipynb = 'notebook.ipynb' tmp_rmd = 'notebook.Rmd' cm = TextFileContentsManager() cm.root_dir = str(tmpdir) cm.default_jupytext_formats = 'ipynb,Rmd' cm.save(model=dict(type='notebook', content=nb), path=tmp_rmd) nb2 = jupytext.read(str(tmpdir.join(tmp_ipynb))) compare_notebooks(nb, nb2) @pytest.mark.parametrize('nb_file', list_notebooks('ipynb_py', skip='66')) def test_all_files_created(nb_file, tmpdir): nb = jupytext.read(nb_file) tmp_ipynb = 'notebook.ipynb' tmp_rmd = 'notebook.Rmd' tmp_py = 'notebook.py' nb.metadata['jupytext'] = {'formats': 'ipynb,Rmd,py'} cm = TextFileContentsManager() cm.root_dir = str(tmpdir) cm.save(model=dict(type='notebook', content=nb), path=tmp_ipynb) nb2 = jupytext.read(str(tmpdir.join(tmp_py))) compare_notebooks(nb, nb2) nb3 = jupytext.read(str(tmpdir.join(tmp_rmd))) compare_notebooks(nb, nb3, 'Rmd') def test_no_files_created_on_no_format(tmpdir): tmp_ipynb = 'notebook.ipynb' tmp_rmd = 'notebook.Rmd' tmp_py = 'notebook.py' cm = TextFileContentsManager() cm.root_dir = str(tmpdir) cm.default_jupytext_formats = '' cm.save(model=dict(type='notebook', content=new_notebook(nbformat=4, metadata=dict())), path=tmp_ipynb) assert not os.path.isfile(str(tmpdir.join(tmp_py))) assert not os.path.isfile(str(tmpdir.join(tmp_rmd))) def test_raise_on_wrong_format(tmpdir): tmp_ipynb = str(tmpdir.join('notebook.ipynb')) cm = TextFileContentsManager() cm.root_dir = str(tmpdir) with pytest.raises(HTTPError): cm.save(path=tmp_ipynb, model=dict( type='notebook', content=new_notebook(nbformat=4, metadata=dict(jupytext_formats=['.doc'])))) def test_no_rmd_on_not_notebook(tmpdir): tmp_ipynb = 'notebook.ipynb' tmp_rmd = 'notebook.Rmd' cm = TextFileContentsManager() cm.root_dir = str(tmpdir) cm.default_jupytext_formats = 'ipynb,Rmd' with pytest.raises(HTTPError): cm.save(model=dict(type='not notebook', content=new_notebook()), path=tmp_ipynb) assert not os.path.isfile(str(tmpdir.join(tmp_rmd))) def test_no_rmd_on_not_v4(tmpdir): tmp_ipynb = 'notebook.ipynb' tmp_rmd = 'notebook.Rmd' cm = TextFileContentsManager() cm.root_dir = str(tmpdir) cm.default_jupytext_formats = 'ipynb,Rmd' with pytest.raises(NotebookValidationError): cm.save(model=dict(type='notebook', content=new_notebook(nbformat=3)), path=tmp_rmd) assert not os.path.isfile(str(tmpdir.join(tmp_ipynb)))
[ "marc.wouts@gmail.com" ]
marc.wouts@gmail.com
06c481a7302a0a6b4508ee4f023660450e8bcba8
63648b8d970c2739f9edc49c743fe55e8732f370
/TrainingGym/tools/contributed/sumopy/coremodules/demand/virtualpop_wxgui.py
67f65b6a6456ae69356a9cbd1f6cbf79a8f29e26
[ "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GPL-2.0-or-later", "EPL-2.0", "MIT" ]
permissive
Sahmwell/G15_Capstone
a0038b047fe6ba2fc4538137cb038ee1e1236463
6d2944a6d472e82fe01b1a9bf28a8ae153abcb77
refs/heads/master
2023-04-14T03:06:46.876134
2021-04-09T03:43:48
2021-04-09T03:43:48
310,671,914
5
1
MIT
2021-04-09T03:43:49
2020-11-06T18:09:52
Python
UTF-8
Python
false
false
13,982
py
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2016-2020 German Aerospace Center (DLR) and others. # SUMOPy module # Copyright (C) 2012-2017 University of Bologna - DICAM # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file virtualpop_wxgui.py # @author Joerg Schweizer # @date import wx import agilepy.lib_base.classman as cm import agilepy.lib_base.arrayman as am from agilepy.lib_base.misc import get_inversemap from agilepy.lib_wx.ogleditor import * try: import virtualpop_results_mpl as results_mpl is_mpl = True # we have matplotlib support except: print "WARNING: python matplotlib package not installed, no matplotlib plots." is_mpl = False import virtualpop from agilepy.lib_wx.processdialog import ProcessDialog, ProcessDialogInteractive class VirtualpopWxGuiMixin: """Contains Virtualpopulation spacific functions that communicate between the widgets of the main wx gui and the functions of the plugin. """ # def refresh_virtualpop(self,is_refresh): # if is_refresh: # neteditor = self.get_neteditor() # #neteditor.add_tool(AddODflowTool(self, odintervals)) # #neteditor.add_toolclass(AddODflowTool) def add_menu_virtualpop(self, menubar): menubar.append_menu('demand/virtual population', bitmap=self.get_icon("icon_virtualpopulation.jpg") ) menubar.append_menu('demand/virtual population/configure population', # bitmap = self.get_icon("icon_virtualpopulation.jpg") ) menubar.append_item('demand/virtual population/configure population/generate...', self.on_generate, ) menubar.append_item('demand/virtual population/configure population/create from zone-to-zone flows...', self.on_create_pop_from_odflows, ) menubar.append_menu('demand/virtual population/configure vehicles', # bitmap = self.get_icon("icon_virtualpopulation.jpg") ) menubar.append_item('demand/virtual population/configure vehicles/provide vehicles...', self.on_provide_vehicles, ) menubar.append_item('demand/virtual population/configure vehicles/clear individual vehicles', self.on_clear_ivehicles, bitmap=wx.ArtProvider.GetBitmap(wx.ART_DELETE, wx.ART_MENU), ) menubar.append_menu('demand/virtual population/plans', # bitmap = self.get_icon("icon_virtualpopulation.jpg") ) menubar.append_item('demand/virtual population/plans/generate...', self.on_generate_plan, # info='Generate plans for private transport.', # bitmap = self.get_icon("Document_Import_24px.png"), ) menubar.append_item('demand/virtual population/plans/select current plans...', self.on_planselection, # info='Generate plans for private transport.', # bitmap = self.get_icon("Document_Import_24px.png"), ) menubar.append_item('demand/virtual population/plans/clear plans', self.on_clear_plans, bitmap=wx.ArtProvider.GetBitmap(wx.ART_DELETE, wx.ART_MENU), ) # menubar.append_item( 'demand/virtual population/plans/export plans to SUMO xml...', # self.on_write_plans_to_sumoxml, # info='Export all plans to SUMO routes XML format.', # # bitmap = self.get_icon("Document_Import_24px.png"), # ) menubar.append_item('demand/virtual population/clear polulation, plans and vehicles', self.on_clear_pop, bitmap=wx.ArtProvider.GetBitmap(wx.ART_DELETE, wx.ART_MENU), ) if is_mpl: menubar.append_menu('demand/virtual population/analysis', bitmap=results_mpl.get_mplicon(), ) menubar.append_item('demand/virtual population/analysis/plot strategy data...', self.on_plot_strategies, bitmap=results_mpl.get_mplicon(), # , ) def on_clear_plans(self, event=None): self._demand.virtualpop.clear_plans() self._mainframe.browse_obj(self._demand.virtualpop.get_plans()) def on_clear_ivehicles(self, event=None): self._demand.virtualpop.clear_ivehicles() self._mainframe.browse_obj(self._demand.virtualpop) def on_clear_pop(self, event=None): self._demand.virtualpop.clear_population() self._mainframe.browse_obj(self._demand.virtualpop) # if event: event.Skip() def on_select_plans_preferred_mode(self, event=None): """ Select current plan as plan which satisfy the person's preferred mode. """ self._demand.virtualpop.select_plans_preferred_mode() self._mainframe.browse_obj(self._demand.virtualpop) def on_select_plans_min_time_est(self, event=None): """ Select plan with minimum estimated travel time as current plant. """ self._demand.virtualpop.select_plans_min_time_est() self._mainframe.browse_obj(self._demand.virtualpop) def on_select_plans_min_time_exec(self, event=None): """ Select plan with minimum effective travel time as current plant. The effective travel time is the time of the last executed simulation run. """ self._demand.virtualpop.select_plans_min_time_exec() self._mainframe.browse_obj(self._demand.virtualpop) def on_select_plans_next(self, event=None): """ Select next plan in the plan list. """ self._demand.virtualpop.select_plans_next() self._mainframe.browse_obj(self._demand.virtualpop) def on_planselection(self, event=None): """ Plan selector to set current plan with different methods """ # self._landuse.parking.make_parking() # self._canvas = canvas.draw() # drawing = self.get_drawing().get_drawobj_by_ident('parkingdraws') # TODO: make a proper import mask that allows to set parameters # self._landuse.maps.download() proc = virtualpop.PlanSelector('parkinggenerator', self._demand.virtualpop, logger=self._mainframe.get_logger()) dlg = ProcessDialog(self._mainframe, proc, immediate_apply=True) dlg.CenterOnScreen() # this does not return until the dialog is closed. val = dlg.ShowModal() # print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL # print ' status =',dlg.get_status() if dlg.get_status() != 'success': # val == wx.ID_CANCEL: # print ">>>>>>>>>Unsuccessful\n" dlg.Destroy() if dlg.get_status() == 'success': # print ">>>>>>>>>successful\n" # apply current widget values to scenario instance dlg.apply() dlg.Destroy() self._mainframe.browse_obj(self._demand.virtualpop) # self._mainframe.refresh_moduleguis() def on_generate(self, event=None): """ Generates virtual population based on some statistical data. """ # self._demand.trips.clear_routes() self.proc = virtualpop.PopGenerator('pop_generator', self._demand.virtualpop, logger=self._mainframe.get_logger() ) dlg = ProcessDialogInteractive(self._mainframe, self.proc, title=self.proc.get_name(), func_close=self.close_process, ) dlg.CenterOnScreen() # this does not return until the dialog is closed. # val = dlg.ShowModal() print 'on_create_pop_from_odflows' dlg.Show() dlg.MakeModal(True) def on_create_pop_from_odflows(self, event=None): """ Generates virtual population from OD flow matrix. """ # self._demand.trips.clear_routes() self.proc = virtualpop.PopFromOdfGenerator('pop_from_odflow_creator', self._demand.virtualpop, logger=self._mainframe.get_logger() ) dlg = ProcessDialogInteractive(self._mainframe, self.proc, title=self.proc.get_name(), func_close=self.close_process, ) dlg.CenterOnScreen() # this does not return until the dialog is closed. # val = dlg.ShowModal() print 'on_create_pop_from_odflows' dlg.Show() dlg.MakeModal(True) def on_provide_vehicles(self, event=None): """ Provide vehicles to satisfy predefined statistical characteristics. """ # self._demand.trips.clear_routes() self.proc = virtualpop.VehicleProvider('vehicleprovider', self._demand.virtualpop, logger=self._mainframe.get_logger() ) dlg = ProcessDialogInteractive(self._mainframe, self.proc, title=self.proc.get_name(), func_close=self.close_process, ) dlg.CenterOnScreen() # this does not return until the dialog is closed. # val = dlg.ShowModal() print 'on_provide_vehicles' dlg.Show() dlg.MakeModal(True) def on_generate_plan(self, event=None): """ Generates mobility plans using different strategies.. """ # self._demand.trips.clear_routes() self.proc = virtualpop.Planner('planner', self._demand.virtualpop, logger=self._mainframe.get_logger() ) dlg = ProcessDialogInteractive(self._mainframe, self.proc, title=self.proc.get_name(), func_close=self.close_process, ) dlg.CenterOnScreen() # this does not return until the dialog is closed. # val = dlg.ShowModal() print 'on_generate_plan' dlg.Show() dlg.MakeModal(True) def close_process(self, dlg): # called before destroying the process dialog if self.proc.status == 'success': self._mainframe.browse_obj(self._demand.virtualpop) def on_write_plans_to_sumoxml(self, event=None): # print 'on_write_plans_to_sumoxml' dirpath = self.get_scenario().get_workdirpath() defaultFile = self.get_scenario().get_rootfilename()+'.rou.xml' wildcards_all = 'All files (*.*)|*.*|XML files (*.xml)|*.xml' dlg = wx.FileDialog(None, message='Write plans to SUMO rou.xml', defaultDir=dirpath, defaultFile=defaultFile, wildcard=wildcards_all, style=wx.SAVE | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: filepath = dlg.GetPath() else: return self._demand.virtualpop.export_sumoxml(filepath) def on_plot_strategies(self, event=None): """ Plot different results on strategies in Matplotlib plotting envitonment. """ if is_mpl: resultplotter = results_mpl.StrategyPlotter(self._demand.virtualpop, logger=self._mainframe.get_logger() ) dlg = results_mpl.ResultDialog(self._mainframe, resultplotter) dlg.CenterOnScreen() # this does not return until the dialog is closed. val = dlg.ShowModal() # print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL # print ' status =',dlg.get_status() if dlg.get_status() != 'success': # val == wx.ID_CANCEL: # print ">>>>>>>>>Unsuccessful\n" dlg.Destroy() if dlg.get_status() == 'success': # print ">>>>>>>>>successful\n" # apply current widget values to scenario instance dlg.apply() dlg.Destroy()
[ "samuelandersonsss@gmail.com" ]
samuelandersonsss@gmail.com
079f18d1faa74d780d07da79b90885ac6a046b56
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/python/sentry/2016/4/apikey.py
6815b0fec307ab6cbbaf52e803d90027c59c261b
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Python
false
false
3,384
py
""" sentry.models.apikey ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import six from bitfield import BitField from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from uuid import uuid4 from sentry.db.models import ( Model, BaseManager, BoundedPositiveIntegerField, FlexibleForeignKey, sane_repr ) # TODO(dcramer): pull in enum library class ApiKeyStatus(object): ACTIVE = 0 INACTIVE = 1 class ApiKey(Model): organization = FlexibleForeignKey('sentry.Organization', related_name='key_set') label = models.CharField(max_length=64, blank=True, default='Default') key = models.CharField(max_length=32, unique=True) scopes = BitField(flags=( ('project:read', 'project:read'), ('project:write', 'project:write'), ('project:delete', 'project:delete'), ('team:read', 'team:read'), ('team:write', 'team:write'), ('team:delete', 'team:delete'), ('event:read', 'event:read'), ('event:write', 'event:write'), ('event:delete', 'event:delete'), ('org:read', 'org:read'), ('org:write', 'org:write'), ('org:delete', 'org:delete'), ('member:read', 'member:read'), ('member:write', 'member:write'), ('member:delete', 'member:delete'), )) status = BoundedPositiveIntegerField(default=0, choices=( (ApiKeyStatus.ACTIVE, _('Active')), (ApiKeyStatus.INACTIVE, _('Inactive')), ), db_index=True) date_added = models.DateTimeField(default=timezone.now) allowed_origins = models.TextField(blank=True, null=True) objects = BaseManager(cache_fields=( 'key', )) class Meta: app_label = 'sentry' db_table = 'sentry_apikey' __repr__ = sane_repr('organization_id', 'key') def __unicode__(self): return six.text_type(self.key) @classmethod def generate_api_key(cls): return uuid4().hex @property def is_active(self): return self.status == ApiKeyStatus.ACTIVE def save(self, *args, **kwargs): if not self.key: self.key = ApiKey.generate_api_key() super(ApiKey, self).save(*args, **kwargs) def get_allowed_origins(self): if not self.allowed_origins: return [] return filter(bool, self.allowed_origins.split('\n')) def get_audit_log_data(self): return { 'label': self.label, 'key': self.key, 'scopes': int(self.scopes), 'status': self.status, } def get_scopes(self): return [k for k, v in self.scopes.iteritems() if v] def has_scope(self, scope): return scope in self.scopes class SystemKey(object): is_active = True organization = None def get_allowed_origins(self): return [] def get_audit_log_data(self): return { 'label': 'System', 'key': '<system>', 'scopes': -1, 'status': ApiKeyStatus.ACTIVE } def get_scopes(self): # All scopes! return ApiKey.scopes def has_scope(self, scope): return True ROOT_KEY = SystemKey()
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
07f0aff0ee04c49fe79e03dbf6a3da55ffd35cd2
7d096568677660790479d87c22b47aae838ef96b
/examples/RFSG/RFSGGettingStartedIQDevice.py
784cee721d32221af1028ea131db6d96d4acdb74
[ "MIT" ]
permissive
NISystemsEngineering/rfmx-pythonnet
30adbdd5660b0d755957f35b68a4c2f60065800c
cd4f90a88a37ed043df880972cb55dfe18883bb7
refs/heads/master
2023-02-04T00:39:41.107043
2023-02-01T21:58:50
2023-02-01T21:58:50
191,603,578
7
5
MIT
2023-02-01T21:58:52
2019-06-12T16:02:32
Python
UTF-8
Python
false
false
4,025
py
import clr import sys import time import os import argparse import csv import numpy as np # Argparse section parser = argparse.ArgumentParser() parser.add_argument('--resource', \ help="enter instrument resource name") parser.add_argument('--trigger', default="none", \ help="enable trigger on requested terminal") parser.add_argument('--iqrate', default=1e6, type=float, \ help="enter IQ rate") args = parser.parse_args() # Location of assemblies dotNetFWDirectory = r"C:\Program Files (x86)\IVI Foundation\IVI\Microsoft.NET\Framework32" dotNetClassLibrary = r'v4.0.30319\NationalInstruments.ModularInstruments.NIRfsg 17.1.0' assy_path = os.path.join(dotNetFWDirectory, dotNetClassLibrary) print(".NET Library: " + dotNetClassLibrary) sys.path.append(assy_path) clr.AddReference("NationalInstruments.ModularInstruments.NIRfsg.Fx40") clr.AddReference("NationalInstruments.Common") # Import .NET drivers from NationalInstruments.ModularInstruments.NIRfsg import * from NationalInstruments import PrecisionTimeSpan from NationalInstruments import ComplexDouble # Instrument Settings ResourceName = args.resource # Instrument alias in MAX IQOutCarrierFrequency = 1000.0 # FPGA DSP Frequencyshift IQOutPortLevel = 0.5 IQOutIQRate = args.iqrate IQOutTriggerDestination = args.trigger # Initialize Instrument instrSession = NIRfsg(ResourceName, True, False) # Configure Instrument print("Reference Clock Source: " + instrSession.FrequencyReference.Source.ToString()) instrSession.FrequencyReference.Configure(RfsgFrequencyReferenceSource.PxiClock, 10e6) print("Reference Clock Source: " + instrSession.FrequencyReference.Source.ToString()) print("IQ Out Output Port: " + str(instrSession.Arb.OutputPort)) instrSession.Arb.OutputPort = RfsgOutputPort.IQOut print("IQ Out Output Port: " + str(instrSession.Arb.OutputPort)) print("IQ Out Carrier Frequency: " + str(instrSession.IQOutPort.CarrierFrequency)) instrSession.IQOutPort.CarrierFrequency = IQOutCarrierFrequency print("IQ Out Carrier Frequency: " + str(instrSession.IQOutPort.CarrierFrequency)) print("IQ Out Port Level: " + str(instrSession.IQOutPort[""].Level)) instrSession.IQOutPort[""].Level = IQOutPortLevel print("IQ Out Port Level: " + str(instrSession.IQOutPort[""].Level)) print("IQ Out Generation Mode: " + str(instrSession.Arb.GenerationMode)) instrSession.Arb.GenerationMode = RfsgWaveformGenerationMode.ArbitraryWaveform print("IQ Out Generation Mode: " + str(instrSession.Arb.GenerationMode)) print("IQ Out Power Level Type: " + str(instrSession.RF.PowerLevelType)) instrSession.RF.PowerLevelType = RfsgRFPowerLevelType.PeakPower print("IQ Out Power Level Type: " + str(instrSession.RF.PowerLevelType)) print("IQ Out IQ Rate: " + str(instrSession.Arb.IQRate)) instrSession.Arb.IQRate = IQOutIQRate print("IQ Out IQ Rate: " + str(instrSession.Arb.IQRate)) print("IQ Out isWaveformRepeatCountFinite: " + str(instrSession.Arb.IsWaveformRepeatCountFinite)) instrSession.Arb.IsWaveformRepeatCountFinite = False print("IQ Out isWaveformRepeatCountFinite: " + str(instrSession.Arb.IsWaveformRepeatCountFinite)) print("IQ Out WaveformRepeatCount: " + str(instrSession.Arb.WaveformRepeatCount)) instrSession.Arb.WaveformRepeatCount = 1 print("IQ Out WaveformRepeatCount: " + str(instrSession.Arb.WaveformRepeatCount)) # Write DC values to I iData = np.ones(1000) qData = np.zeros(1000) instrSession.Arb.WriteWaveform("wfm0", iData, qData) if args.trigger is not "none": print("IQ Out Export Start Trigger: " + str(instrSession.Triggers.StartTrigger.ExportedOutputTerminal)) instrSession.Triggers.StartTrigger.ExportedOutputTerminal = \ RfsgStartTriggerExportedOutputTerminal.FromString(IQOutTriggerDestination) print("IQ Out Export Start Trigger: " + str(instrSession.Triggers.StartTrigger.ExportedOutputTerminal)) # Start Generation instrSession.Initiate() # Wait for user to stop script input("Press Enter to continue...") # Abort Generation instrSession.Abort() # Close Instrument instrSession.Close()
[ "sean.moore@ni.com" ]
sean.moore@ni.com
6fc1c089abc9dba76e6b8a4df05edc5f6e2817f3
a12bd9ee16dd864756829f2ff98f9e7ca59e322a
/07. raspberrypi/python/objectdetection-ex/tf/examples/obj-detect-api-ex/ex02.py
aa6248d3e51ee81ca5b24c2d31758f7650e2a698
[]
no_license
hongjy127/TIL
0bda9250f850a21dc27597a8b6288cf7ecb9e470
a1760aba50bb3b77ab6576f5b5dcb16f0d9f5c5a
refs/heads/master
2023-06-17T17:04:21.873930
2021-07-18T07:54:26
2021-07-18T07:54:26
325,415,046
0
0
null
null
null
null
UTF-8
Python
false
false
908
py
import cv2 from video import Video from objdetect import ObjDetectApi import time PATH_TO_LABELS = 'data/mscoco_label_map.pbtxt' MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17' api = ObjDetectApi(MODEL_NAME, PATH_TO_LABELS) def detect(frame): frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # output_dict를 클라이언트로 보내기 output_dict = api.inference_image(frame_rgb) labeled_image = api.visualize(frame_rgb, output_dict) labeled_image = cv2.cvtColor(labeled_image, cv2.COLOR_RGB2BGR) cv2.imshow('frame', labeled_image) key = cv2.waitKey(1) if key == 27: return False else: return True with Video(file="vtest.avi") as v: # with Video(device=0) as v: for image in v: start_time = time.time() if not detect(image): break end_time = time.time() fps = 1/(end_time-start_time) print(f'fps: {fps}')
[ "hhhong127@gmail.com" ]
hhhong127@gmail.com
4c4ee08f8d7ff033d096bc6f764a9a81fd99e6ce
f425902cfa5dba2058b0885ffa103f7156b6be08
/supervised_learning/0x0A-object_detection/5-yolo.py
53410b498a3dbc4ae2422f5c29928baaebc8730b
[]
no_license
PilarPinto/holbertonschool-machine_learning
2a23af14c851bd3e5d1926e644525bf0ab45df84
74213384b0998f65e123adc146ea5e91c4d77b37
refs/heads/master
2022-12-22T16:29:03.960474
2020-10-03T22:47:51
2020-10-03T22:47:51
279,387,070
0
0
null
null
null
null
UTF-8
Python
false
false
6,488
py
#!/usr/bin/env python3 ''' algorithm to perform object detection File in YOLO dataset ''' import tensorflow.keras as K import numpy as np import glob import cv2 class Yolo: ''' Initialize the class YOLO ''' def __init__(self, model_path, classes_path, class_t, nms_t, anchors): '''uses the Yolo v3 algorithm to perform object detection''' self.model = K.models.load_model(model_path) with open(classes_path, 'r') as f: self.class_names = f.read().splitlines() self.class_t = class_t self.nms_t = nms_t self.anchors = anchors def sigmoid(self, x): '''Sigmoid function''' return(1/(1 + np.exp(-x))) def process_outputs(self, outputs, image_size): '''Find and return the tuple of outputs in the detection process''' boxes, box_confidences, box_class_probs = [], [], [] img_h, img_w = image_size for ind in range(len(outputs)): # input sizes input_weight = self.model.input_shape[1] input_height = self.model.input_shape[2] grid_he = outputs[ind].shape[0] grid_we = outputs[ind].shape[1] anchor_boxes = outputs[ind].shape[2] tx = outputs[ind][..., 0] ty = outputs[ind][..., 1] tw = outputs[ind][..., 2] th = outputs[ind][..., 3] c = np.zeros((grid_he, grid_we, anchor_boxes)) idx_y = np.arange(grid_he) idx_y = idx_y.reshape(grid_he, 1, 1) idx_x = np.arange(grid_we) idx_x = idx_x.reshape(1, grid_we, 1) cx = c + idx_x cy = c + idx_y p_w = self.anchors[ind, :, 0] p_h = self.anchors[ind, :, 1] # Using cx (width) cy (height) for cbounding b_x = self.sigmoid(tx) + cx b_y = self.sigmoid(ty) + cy b_w = p_w * np.exp(tw) b_h = p_h * np.exp(th) # normalizing bx = b_x / grid_we by = b_y / grid_he bw = b_w / input_weight bh = b_h / input_height bx1 = bx - bw / 2 by1 = by - bh / 2 bx2 = bx + bw / 2 by2 = by + bh / 2 outputs[ind][..., 0] = bx1 * img_w outputs[ind][..., 1] = by1 * img_h outputs[ind][..., 2] = bx2 * img_w outputs[ind][..., 3] = by2 * img_h boxes.append(outputs[ind][..., 0:4]) box_confidences.append(self.sigmoid(outputs[ind][..., 4:5])) box_class_probs.append(self.sigmoid(outputs[ind][..., 5:])) return(boxes, box_confidences, box_class_probs) def filter_boxes(self, boxes, box_confidences, box_class_probs): '''Filter boxes over the threshold''' scores = [] for i in range(len(boxes)): scores.append(box_confidences[i] * box_class_probs[i]) filter_boxes = [box.reshape(-1, 4) for box in boxes] filter_boxes = np.concatenate(filter_boxes) class_m = [np.argmax(box, -1) for box in scores] class_m = [box.reshape(-1) for box in class_m] class_m = np.concatenate(class_m) class_scores = [np.max(box, -1) for box in scores] class_scores = [box.reshape(-1) for box in class_scores] class_scores = np.concatenate(class_scores) f_mask = np.where(class_scores >= self.class_t) filtered_boxes = filter_boxes[f_mask] box_classes = class_m[f_mask] box_scores = class_scores[f_mask] return(filtered_boxes, box_classes, box_scores) def non_max_suppression(self, filtered_boxes, box_classes, box_scores): '''non max suppression''' box_pred = [] box_classes_pred = [] box_scores_pred = [] u_classes = np.unique(box_classes) for ucls in u_classes: idx = np.where(box_classes == ucls) bfilters = filtered_boxes[idx] bscores = box_scores[idx] bclasses = box_classes[idx] pick = self._intersectionou(bfilters, self.nms_t, bscores) filters = bfilters[pick] scores = bscores[pick] classes = bclasses[pick] box_pred.append(filters) box_classes_pred.append(classes) box_scores_pred.append(scores) filtered_boxes = np.concatenate(box_pred, axis=0) box_classes = np.concatenate(box_classes_pred, axis=0) box_scores = np.concatenate(box_scores_pred, axis=0) return (filtered_boxes, box_classes, box_scores) def _intersectionou(self, filtered_boxes, thresh, scores): '''Compute intersection''' x1 = filtered_boxes[:, 0] y1 = filtered_boxes[:, 1] x2 = filtered_boxes[:, 2] y2 = filtered_boxes[:, 3] area = (x2 - x1 + 1) * (y2 - y1 + 1) idxs = scores.argsort()[::-1] pick = [] while idxs.size > 0: i = idxs[0] pick.append(i) xx1 = np.maximum(x1[i], x1[idxs[1:]]) yy1 = np.maximum(y1[i], y1[idxs[1:]]) xx2 = np.minimum(x2[i], x2[idxs[1:]]) yy2 = np.minimum(y2[i], y2[idxs[1:]]) w = np.maximum(0, xx2 - xx1 + 1) h = np.maximum(0, yy2 - yy1 + 1) inter = (w * h) overlap = inter / (area[i] + area[idxs[1:]] - inter) ind = np.where(overlap <= self.nms_t)[0] idxs = idxs[ind + 1] return pick @staticmethod def load_images(folder_path): '''Load a little set of images''' images = [] images_paths = [] for filename in glob.glob(folder_path + '/*.jpg'): images.append(cv2.imread(filename)) images_paths.append(filename) return(images, images_paths) def preprocess_images(self, images): '''Change the size of the image''' rescale_lst, image_shapes = [], [] input_weight = self.model.input_shape[1] input_height = self.model.input_shape[2] for image in images: resized = cv2.resize(image, (input_weight, input_height), interpolation=cv2.INTER_CUBIC) rescale_lst.append(resized / 255) image_shapes.append(image.shape[:2]) p_images = np.array(rescale_lst) image_shapes = np.array(image_shapes) return(p_images, image_shapes)
[ "piapintoch@unal.edu.co" ]
piapintoch@unal.edu.co
88895b7e721bf818a7dc07867690fd85b1bb77e8
6eea60bcbf206dafc5fe578b996267ce2bc9ae6e
/UVA/11953 - Battleships.py
0d6e814baa4fed1595d51143f5b702dbd8328d1f
[]
no_license
SueAli/cs-problems
491fef79f3e352d7712cd622d3b80ec15d38642b
b321116d135f868d88bd849b5ea7172feb74fb4c
refs/heads/master
2023-08-31T10:46:30.374394
2023-08-24T20:14:04
2023-08-24T20:14:04
95,930,918
0
0
null
null
null
null
UTF-8
Python
false
false
1,073
py
# Time Complexity is O( n * n ) # Space Complexity is O( n * n ) dir_ = [(0,-1),(0,1),(-1,0),(1,0)] def dfsFloodFill(i,j,grid, x_cnt): if (i <0 or j <0 ) or (i == len(grid) or j == len(grid[0]) or grid[i][j]=='.' or grid[i][j] == '#' ): return if grid[i][j] == 'x': x_cnt[0] += 1 grid[i][j] = '#' for d in dir_: dfsFloodFill(i+d[0],j+d[1],grid, x_cnt) while True: try: T = int(input()) for t in range(T): n = int(input()) g = [] for r in range(n): g.append(list(str(input()))) ships_cnt = 0 for ii in range(n): for jj in range(n): if g[ii][jj] in ['x','@']: x_cnt = [0] dfsFloodFill(ii,jj,g, x_cnt) if x_cnt[0] >0: ships_cnt += 1 print ("Case "+str(t+1)+": "+str(ships_cnt)) except: break
[ "souad.hassanien@gmail.com" ]
souad.hassanien@gmail.com
63ef341c72185f123495f264333a53ed7e75ae37
ef1989ac573384c32659ac21303293abee8a4e22
/2020/3try/10972.py
8215328977a502a57c6938deddbaef3d76c3bc93
[]
no_license
Algorithm-P0/meanjung
f3605fd4e515d61d3aeedf420932a029b6037f00
028906eb7275485a5e739c10b8dda85dff63e341
refs/heads/master
2023-06-05T18:52:16.708158
2021-06-24T07:41:12
2021-06-24T07:41:12
262,729,336
0
0
null
null
null
null
UTF-8
Python
false
false
31
py
# next permutation 구현하기
[ "meanjunghong@naver.com" ]
meanjunghong@naver.com