content
stringlengths 7
1.05M
|
|---|
#
# PySNMP MIB module CNT2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNT2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
enterprises, ModuleIdentity, TimeTicks, Unsigned32, Counter32, Integer32, NotificationType, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, MibIdentifier, Gauge32, iso, IpAddress, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "ModuleIdentity", "TimeTicks", "Unsigned32", "Counter32", "Integer32", "NotificationType", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "MibIdentifier", "Gauge32", "iso", "IpAddress", "Bits")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
cnt = MibIdentifier((1, 3, 6, 1, 4, 1, 333))
cnt2 = MibIdentifier((1, 3, 6, 1, 4, 1, 333, 2))
cnt2Mib2 = MibIdentifier((1, 3, 6, 1, 4, 1, 333, 2, 1))
cnt2Experimental = MibIdentifier((1, 3, 6, 1, 4, 1, 333, 2, 2))
cnt2Snmp = MibIdentifier((1, 3, 6, 1, 4, 1, 333, 2, 3))
cnt2Subagent = MibIdentifier((1, 3, 6, 1, 4, 1, 333, 2, 4))
cnt2Config = MibIdentifier((1, 3, 6, 1, 4, 1, 333, 2, 5))
mibBuilder.exportSymbols("CNT2-MIB", cnt2Subagent=cnt2Subagent, cnt=cnt, cnt2Snmp=cnt2Snmp, cnt2Experimental=cnt2Experimental, cnt2Config=cnt2Config, cnt2Mib2=cnt2Mib2, cnt2=cnt2)
|
#flask
DEBUG = True
#session
SECRET_KEY="1145141919810"
#mysql
DIQLECT = "mysql"
DRIVER="pymysql"
USERNAME = "root"
PASSWORD = "root"
# PASSWORD = "7410188xw"
HOST = "127.0.0.1"
PORT = "3306"
DATABASE = "CSBIGHW"
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIQLECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS =False
|
n1 = float(input('Digite o primeiro número:'))
n2 = float(input('Digite o segundo número:'))
n3 = float(input('Digite o terceiroo número:'))
if n1 > n2 and n1 > n3:
print('O maior número é {}'.format(n1))
elif n2 > n1 and n2 > n3:
print('O maior número é {}'.format(n2))
else:
print('O maior número é {}'.format(n3))
|
class EnergyAnalysisDetailModelOptions(object,IDisposable):
"""
Options that govern the calculations for the generation of the energy analysis detail model.
EnergyAnalysisDetailModelOptions()
"""
def Dispose(self):
""" Dispose(self: EnergyAnalysisDetailModelOptions) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: EnergyAnalysisDetailModelOptions,disposing: bool) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
EnergyModelType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""It indicates whether the energy model is based on rooms/spaces or building elements.
Get: EnergyModelType(self: EnergyAnalysisDetailModelOptions) -> EnergyModelType
Set: EnergyModelType(self: EnergyAnalysisDetailModelOptions)=value
"""
ExportMullions=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Indicates if to specify the setting for exporting mullions.
Get: ExportMullions(self: EnergyAnalysisDetailModelOptions) -> bool
Set: ExportMullions(self: EnergyAnalysisDetailModelOptions)=value
"""
IncludeShadingSurfaces=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Indicates if to set and get the setting for if shading surfaces should be included.
Get: IncludeShadingSurfaces(self: EnergyAnalysisDetailModelOptions) -> bool
Set: IncludeShadingSurfaces(self: EnergyAnalysisDetailModelOptions)=value
"""
IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: EnergyAnalysisDetailModelOptions) -> bool
"""
SimplifyCurtainSystems=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Indicates if to specify the setting for simplified curtain systems.
Get: SimplifyCurtainSystems(self: EnergyAnalysisDetailModelOptions) -> bool
Set: SimplifyCurtainSystems(self: EnergyAnalysisDetailModelOptions)=value
"""
Tier=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Level of computation for energy analysis model.
Get: Tier(self: EnergyAnalysisDetailModelOptions) -> EnergyAnalysisDetailModelTier
Set: Tier(self: EnergyAnalysisDetailModelOptions)=value
"""
|
def sum_double(a, b):
if a == b:
return (a+b)*2
else:
return a+b
|
"""
Создать список состоящий из отдельных единичных символов,
преобразовать список в строку, инвертировать строку и вывести на печать.
"""
my_spisok_list = ['m', 'y', '_', 's', 'p', 'i', 's', 'o', 'k']
my_spisok_str = "".join(my_spisok_list)
print(my_spisok_str)
|
class CoalescenceException(Exception):
def __init__(self, msg=''):
self.msg = msg
class NoSuchSourceException(CoalescenceException):
pass
class NotAnElementException(CoalescenceException):
pass
class NotAValueException(CoalescenceException):
pass
class NoValueException(CoalescenceException):
pass
class SerializationException(CoalescenceException):
pass
class CoercetionException(CoalescenceException):
pass
|
# Sequence Equation
# Find some y satisfying p(p(y)) = x for each x from 1 to n.
#
# https://www.hackerrank.com/challenges/permutation-equation/problem
#
def permutationEquation(p):
# Complete this function
n = len(p)
q = [0] * n
# p(p(𝓎)) = 𝓍 (au décalage de 1 près)
for i in range(0, n):
q[p[p[i] - 1] - 1] = i + 1
return q
if __name__ == "__main__":
n = int(input())
p = list(map(int, input().split()))
result = permutationEquation(p)
print ("\n".join(map(str, result)))
|
"""Extra Ansible filters"""
def rules_ports(
firewall_rules, only_restricted=False, redirect=False, *_, **__):
"""
Return restricted ports (<1024) from firewall rules.
Args:
firewall_rules (list of dict): Firewall rules.
only_restricted (bool): If True, list only ports < 1024.
redirect (bool): If True, provides a redirect for ports < 1024 in the
unrestricted port range.
Returns:
list of dict: port, redirected port, protocol
"""
filtered = []
for rule in firewall_rules:
start = int(rule['start_port'])
end = int(rule['end_port'])
if not only_restricted or start < 1024:
protocol = rule['protocol']
filtered += [{
'port': str(port),
'redirect': str(port + (
60000 if port < 1024 and redirect else 0)),
'protocol': protocol} for port in range(start, end + 1)]
return filtered
def publish_ports(firewall_rules, redirect=False, *_, **__):
"""
Returns all ports as "--publish" arguments.
Args:
firewall_rules (list of dict): Firewall rules.
redirect (bool): Apply port redirection for port <1024.
Returns:
str: arguments
"""
return ' '.join(
f"-p {port['redirect']}:{port['port']}"
f"{'' if port['protocol'] == 'all' else '/' + port['protocol']}"
for port in rules_ports(firewall_rules, redirect=redirect))
def publish_devices(path_list, *_, **__):
"""
Returns paths as "--device" or "--mount" arguments.
Fall back to "--privileged" if no devices found.
Args:
path_list (str): List of devices paths, one path per line.
Returns:
str: arguments
"""
return ' '.join(
f'--device={path.strip()}' if path.startswith('/dev') else
f'--mount=type=bind,src={path.strip()},target={path.strip()}'
for path in path_list.strip().splitlines()
if not path.startswith('/home')) or '--privileged'
class FilterModule(object):
"""Return filter plugin"""
@staticmethod
def filters():
"""Return filter"""
return {'rules_ports': rules_ports,
'publish_ports': publish_ports,
'publish_devices': publish_devices}
|
# lextab.py. This file automatically created by PLY (version 3.4). Don't edit!
_tabversion = '3.4'
_lextokens = {'DO': 1, 'REMAINDER_ASSIGN': 1, 'RSHIFT': 1, 'SYNCHRONIZED': 1, 'GTEQ': 1, 'MINUS_ASSIGN': 1, 'OR_ASSIGN': 1, 'VOID': 1, 'STRING_LITERAL': 1, 'ABSTRACT': 1, 'CHAR': 1, 'LSHIFT_ASSIGN': 1, 'WHILE': 1, 'SHORT': 1, 'STATIC': 1, 'PRIVATE': 1, 'LSHIFT': 1, 'CONTINUE': 1, 'THROWS': 1, 'NULL': 1, 'TRUE': 1, 'BYTE': 1, 'NEQ': 1, 'CASE': 1, 'TIMES_ASSIGN': 1, 'THROW': 1, 'NEW': 1, 'SWITCH': 1, 'LONG': 1, 'FINAL': 1, 'PROTECTED': 1, 'STRICTFP': 1, 'IF': 1, 'NUM': 1, 'CATCH': 1, 'ELLIPSIS': 1, 'NATIVE': 1, 'CLASS': 1, 'BLOCK_COMMENT': 1, 'IMPLEMENTS': 1, 'TRANSIENT': 1, 'LINE_COMMENT': 1, 'FOR': 1, 'PACKAGE': 1, 'PLUSPLUS': 1, 'AND_ASSIGN': 1, 'RRSHIFT_ASSIGN': 1, 'ENUM': 1, 'ELSE': 1, 'TRY': 1, 'FINALLY': 1, 'DIVIDE_ASSIGN': 1, 'PUBLIC': 1, 'MINUSMINUS': 1, 'EQ': 1, 'RRSHIFT': 1, 'AND': 1, 'ASSERT': 1, 'RETURN': 1, 'FALSE': 1, 'NAME': 1, 'XOR_ASSIGN': 1, 'THIS': 1, 'DOUBLE': 1, 'LTEQ': 1, 'RSHIFT_ASSIGN': 1, 'CHAR_LITERAL': 1, 'DEFAULT': 1, 'FLOAT': 1, 'BREAK': 1, 'INT': 1, 'BOOLEAN': 1, 'VOLATILE': 1, 'IMPORT': 1, 'PLUS_ASSIGN': 1, 'INTERFACE': 1, 'EXTENDS': 1, 'INSTANCEOF': 1, 'SUPER': 1, 'OR': 1}
_lexreflags = 0
_lexliterals = '()+-*/=?:,.^|&~!=[]{};<>@%'
_lexstateinfo = {'INITIAL': 'inclusive'}
_lexstatere = {'INITIAL': [('(?P<t_BLOCK_COMMENT>/\\*(.|\\n)*?\\*/)|(?P<t_NAME>[A-Za-z_$][A-Za-z0-9_$]*)|(?P<t_newline>\\n+)|(?P<t_newline2>(\\r\\n)+)|(?P<t_NUM>\\.?[0-9][0-9eE_lLdDa-fA-F.xXpP]*)|(?P<t_STRING_LITERAL>\\"([^\\\\\\n]|(\\\\.))*?\\")|(?P<t_CHAR_LITERAL>\\\'([^\\\\\\n]|(\\\\.))*?\\\')|(?P<t_ELLIPSIS>\\.\\.\\.)|(?P<t_ignore_LINE_COMMENT>//.*)|(?P<t_PLUSPLUS>\\+\\+)|(?P<t_MINUSMINUS>\\-\\-)|(?P<t_OR>\\|\\|)|(?P<t_RRSHIFT_ASSIGN>>>>=)|(?P<t_XOR_ASSIGN>\\^=)|(?P<t_RSHIFT_ASSIGN>>>=)|(?P<t_LSHIFT_ASSIGN><<=)|(?P<t_OR_ASSIGN>\\|=)|(?P<t_PLUS_ASSIGN>\\+=)|(?P<t_RRSHIFT>>>>)|(?P<t_TIMES_ASSIGN>\\*=)|(?P<t_LTEQ><=)|(?P<t_RSHIFT>>>)|(?P<t_AND_ASSIGN>&=)|(?P<t_DIVIDE_ASSIGN>/=)|(?P<t_GTEQ>>=)|(?P<t_MINUS_ASSIGN>-=)|(?P<t_EQ>==)|(?P<t_AND>&&)|(?P<t_REMAINDER_ASSIGN>%=)|(?P<t_NEQ>!=)|(?P<t_LSHIFT><<)', [None, ('t_BLOCK_COMMENT', 'BLOCK_COMMENT'), None, ('t_NAME', 'NAME'), ('t_newline', 'newline'), ('t_newline2', 'newline2'), None, (None, 'NUM'), (None, 'STRING_LITERAL'), None, None, (None, 'CHAR_LITERAL'), None, None, (None, 'ELLIPSIS'), (None, None), (None, 'PLUSPLUS'), (None, 'MINUSMINUS'), (None, 'OR'), (None, 'RRSHIFT_ASSIGN'), (None, 'XOR_ASSIGN'), (None, 'RSHIFT_ASSIGN'), (None, 'LSHIFT_ASSIGN'), (None, 'OR_ASSIGN'), (None, 'PLUS_ASSIGN'), (None, 'RRSHIFT'), (None, 'TIMES_ASSIGN'), (None, 'LTEQ'), (None, 'RSHIFT'), (None, 'AND_ASSIGN'), (None, 'DIVIDE_ASSIGN'), (None, 'GTEQ'), (None, 'MINUS_ASSIGN'), (None, 'EQ'), (None, 'AND'), (None, 'REMAINDER_ASSIGN'), (None, 'NEQ'), (None, 'LSHIFT')])]}
_lexstateignore = {'INITIAL': ' \t\x0c'}
_lexstateerrorf = {'INITIAL': 't_error'}
|
for i in range(0,21,2):
if(i==0):
i=i
elif(i==10 or i==20):
i=int(i/10)
else:
i/=10
for k in range(1,4):
print("I={} J={}".format(i, k+i))
|
n = int(input())
i = 1
while(i < n):
j = 1
while(j <= i):
print((i*2-1), end=" ")
j = j+1
i = i + 1
print()
|
class Solution(object):
def maxSubArray(self, nums):
if not nums:
return 0
best_sum = nums[0]
current_sum = 0
for x in nums:
current_sum = max(x, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
in_arrs = [
[2, 1, 2, 1, 0, 1, 2],
[3, 3, 5, 0, 0, 3, 1, 4],
[3, 5, 0, 1, 4],
[1, 2, -1, 1],
[1, 2, 3, 4],
[1, 1, 1, 3, 3, 4, 3, 2, 4, 2],
[-2, 1, -3, 4, -1, 2, 1, -5, 4],
]
if __name__ == "__main__":
sol = Solution()
for nin in in_arrs:
r = sol.maxSubArray(nin)
print(r)
|
class Solution:
def moveZeroes(self, nums):
length = len(nums)
on_zero = run = 0
while True:
# find first zero in nums.
while nums[on_zero]:
on_zero = on_zero + 1
if on_zero == length:
return
# stops on first non-zero value of nums
while not nums[run] or run < on_zero:
run = run + 1
if run == length:
return
nums[on_zero], nums[run] = nums[run], nums[on_zero]
|
#
# PySNMP MIB module VMWARE-VMINFO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-VMINFO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:27:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
ModuleIdentity, IpAddress, Counter32, TimeTicks, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Unsigned32, MibIdentifier, Integer32, Gauge32, iso, ObjectIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "IpAddress", "Counter32", "TimeTicks", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Unsigned32", "MibIdentifier", "Integer32", "Gauge32", "iso", "ObjectIdentity", "Counter64")
DisplayString, TextualConvention, PhysAddress = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "PhysAddress")
vmwESXNotifications, = mibBuilder.importSymbols("VMWARE-ENV-MIB", "vmwESXNotifications")
vmwVirtMachines, vmwTraps = mibBuilder.importSymbols("VMWARE-ROOT-MIB", "vmwVirtMachines", "vmwTraps")
VmwConnectedState, = mibBuilder.importSymbols("VMWARE-TC-MIB", "VmwConnectedState")
vmwVmInfoMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6876, 2, 10))
vmwVmInfoMIB.setRevisions(('2011-09-17 00:00', '2010-06-22 00:00', '2008-10-23 00:00', '2007-12-27 00:00',))
if mibBuilder.loadTexts: vmwVmInfoMIB.setLastUpdated('201109170000Z')
if mibBuilder.loadTexts: vmwVmInfoMIB.setOrganization('VMware, Inc')
vmwVmTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 1), )
if mibBuilder.loadTexts: vmwVmTable.setStatus('current')
vmwVmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwVmIdx"))
if mibBuilder.loadTexts: vmwVmEntry.setStatus('current')
vmwVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwVmIdx.setStatus('current')
vmwVmDisplayName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmDisplayName.setStatus('current')
vmwVmConfigFile = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmConfigFile.setStatus('current')
vmwVmGuestOS = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmGuestOS.setStatus('current')
vmwVmMemSize = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 5), Integer32()).setUnits('megabytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmMemSize.setStatus('current')
vmwVmState = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmState.setStatus('current')
vmwVmVMID = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmVMID.setStatus('obsolete')
vmwVmGuestState = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 8), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmGuestState.setStatus('current')
vmwVmCpus = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmCpus.setStatus('current')
vmwVmUUID = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(36, 72))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmUUID.setStatus('current')
vmwVmHbaTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 2), )
if mibBuilder.loadTexts: vmwVmHbaTable.setStatus('current')
vmwVmHbaEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwHbaVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwVmHbaIdx"))
if mibBuilder.loadTexts: vmwVmHbaEntry.setStatus('current')
vmwHbaVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwHbaVmIdx.setStatus('current')
vmwVmHbaIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwVmHbaIdx.setStatus('current')
vmwHbaNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwHbaNum.setStatus('current')
vmwHbaVirtDev = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwHbaVirtDev.setStatus('current')
vmwHbaTgtTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 3), )
if mibBuilder.loadTexts: vmwHbaTgtTable.setStatus('current')
vmwHbaTgtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwHbaTgtVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwHbaTgtIdx"))
if mibBuilder.loadTexts: vmwHbaTgtEntry.setStatus('current')
vmwHbaTgtVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwHbaTgtVmIdx.setStatus('current')
vmwHbaTgtIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwHbaTgtIdx.setStatus('current')
vmwHbaTgtNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwHbaTgtNum.setStatus('current')
vmwVmNetTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 4), )
if mibBuilder.loadTexts: vmwVmNetTable.setStatus('current')
vmwVmNetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwVmNetVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwVmNetIdx"))
if mibBuilder.loadTexts: vmwVmNetEntry.setStatus('current')
vmwVmNetVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwVmNetVmIdx.setStatus('current')
vmwVmNetIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwVmNetIdx.setStatus('current')
vmwVmNetNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmNetNum.setStatus('current')
vmwVmNetName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmNetName.setStatus('current')
vmwVmNetConnType = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmNetConnType.setStatus('obsolete')
vmwVmNetConnected = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 6), VmwConnectedState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmNetConnected.setStatus('current')
vmwVmMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 7), PhysAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwVmMAC.setStatus('current')
vmwFloppyTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 5), )
if mibBuilder.loadTexts: vmwFloppyTable.setStatus('current')
vmwFloppyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwFdVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwFdIdx"))
if mibBuilder.loadTexts: vmwFloppyEntry.setStatus('current')
vmwFdVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwFdVmIdx.setStatus('current')
vmwFdIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwFdIdx.setStatus('current')
vmwFdName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwFdName.setStatus('current')
vmwFdConnected = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 4), VmwConnectedState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwFdConnected.setStatus('current')
vmwCdromTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 6), )
if mibBuilder.loadTexts: vmwCdromTable.setStatus('current')
vmwCdromEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwCdVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwCdromIdx"))
if mibBuilder.loadTexts: vmwCdromEntry.setStatus('current')
vmwCdVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwCdVmIdx.setStatus('current')
vmwCdromIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: vmwCdromIdx.setStatus('current')
vmwCdromName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwCdromName.setStatus('current')
vmwCdromConnected = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 4), VmwConnectedState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vmwCdromConnected.setStatus('current')
vmwVmID = MibScalar((1, 3, 6, 1, 4, 1, 6876, 50, 101), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: vmwVmID.setStatus('current')
vmwVmConfigFilePath = MibScalar((1, 3, 6, 1, 4, 1, 6876, 50, 102), DisplayString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: vmwVmConfigFilePath.setStatus('current')
vmwVmPoweredOn = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 1)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName"))
if mibBuilder.loadTexts: vmwVmPoweredOn.setStatus('current')
vmwVmPoweredOff = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 2)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName"))
if mibBuilder.loadTexts: vmwVmPoweredOff.setStatus('current')
vmwVmHBLost = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 3)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName"))
if mibBuilder.loadTexts: vmwVmHBLost.setStatus('current')
vmwVmHBDetected = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 4)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName"))
if mibBuilder.loadTexts: vmwVmHBDetected.setStatus('current')
vmwVmSuspended = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 5)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName"))
if mibBuilder.loadTexts: vmwVmSuspended.setStatus('current')
vmwVmInfoMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2))
vmwVmInfoMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 1))
vmwVmInfoMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2))
vmwResMIBBasicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 1, 2)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmInfoGroup"), ("VMWARE-VMINFO-MIB", "vmwVmInfoNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
vmwResMIBBasicCompliance = vmwResMIBBasicCompliance.setStatus('current')
vmwVmInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2, 1)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmDisplayName"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFile"), ("VMWARE-VMINFO-MIB", "vmwVmGuestOS"), ("VMWARE-VMINFO-MIB", "vmwVmMemSize"), ("VMWARE-VMINFO-MIB", "vmwVmState"), ("VMWARE-VMINFO-MIB", "vmwVmGuestState"), ("VMWARE-VMINFO-MIB", "vmwHbaNum"), ("VMWARE-VMINFO-MIB", "vmwHbaVirtDev"), ("VMWARE-VMINFO-MIB", "vmwHbaTgtNum"), ("VMWARE-VMINFO-MIB", "vmwVmNetNum"), ("VMWARE-VMINFO-MIB", "vmwVmNetName"), ("VMWARE-VMINFO-MIB", "vmwVmNetConnected"), ("VMWARE-VMINFO-MIB", "vmwVmMAC"), ("VMWARE-VMINFO-MIB", "vmwFdName"), ("VMWARE-VMINFO-MIB", "vmwFdConnected"), ("VMWARE-VMINFO-MIB", "vmwCdromName"), ("VMWARE-VMINFO-MIB", "vmwCdromConnected"), ("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmCpus"), ("VMWARE-VMINFO-MIB", "vmwVmUUID"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
vmwVmInfoGroup = vmwVmInfoGroup.setStatus('current')
vmwVmInfoNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2, 2)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmPoweredOn"), ("VMWARE-VMINFO-MIB", "vmwVmPoweredOff"), ("VMWARE-VMINFO-MIB", "vmwVmHBLost"), ("VMWARE-VMINFO-MIB", "vmwVmHBDetected"), ("VMWARE-VMINFO-MIB", "vmwVmSuspended"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
vmwVmInfoNotificationGroup = vmwVmInfoNotificationGroup.setStatus('current')
vmwVmObsoleteGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2, 3)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmVMID"), ("VMWARE-VMINFO-MIB", "vmwVmNetConnType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
vmwVmObsoleteGroup = vmwVmObsoleteGroup.setStatus('obsolete')
mibBuilder.exportSymbols("VMWARE-VMINFO-MIB", vmwVmUUID=vmwVmUUID, vmwCdromTable=vmwCdromTable, vmwVmSuspended=vmwVmSuspended, vmwVmHbaIdx=vmwVmHbaIdx, vmwVmNetTable=vmwVmNetTable, vmwVmNetName=vmwVmNetName, vmwVmVMID=vmwVmVMID, vmwVmDisplayName=vmwVmDisplayName, vmwVmHbaTable=vmwVmHbaTable, vmwVmConfigFile=vmwVmConfigFile, vmwFdVmIdx=vmwFdVmIdx, vmwCdromConnected=vmwCdromConnected, vmwVmGuestState=vmwVmGuestState, vmwVmEntry=vmwVmEntry, vmwHbaTgtIdx=vmwHbaTgtIdx, vmwVmTable=vmwVmTable, vmwVmInfoMIB=vmwVmInfoMIB, PYSNMP_MODULE_ID=vmwVmInfoMIB, vmwVmGuestOS=vmwVmGuestOS, vmwVmState=vmwVmState, vmwFloppyTable=vmwFloppyTable, vmwVmNetConnType=vmwVmNetConnType, vmwVmPoweredOn=vmwVmPoweredOn, vmwVmNetVmIdx=vmwVmNetVmIdx, vmwHbaTgtEntry=vmwHbaTgtEntry, vmwVmIdx=vmwVmIdx, vmwHbaVmIdx=vmwHbaVmIdx, vmwVmHbaEntry=vmwVmHbaEntry, vmwVmNetConnected=vmwVmNetConnected, vmwVmCpus=vmwVmCpus, vmwCdromIdx=vmwCdromIdx, vmwVmID=vmwVmID, vmwVmObsoleteGroup=vmwVmObsoleteGroup, vmwCdromEntry=vmwCdromEntry, vmwHbaTgtTable=vmwHbaTgtTable, vmwFdName=vmwFdName, vmwCdVmIdx=vmwCdVmIdx, vmwVmInfoGroup=vmwVmInfoGroup, vmwCdromName=vmwCdromName, vmwFdIdx=vmwFdIdx, vmwResMIBBasicCompliance=vmwResMIBBasicCompliance, vmwVmHBDetected=vmwVmHBDetected, vmwVmInfoMIBGroups=vmwVmInfoMIBGroups, vmwHbaTgtVmIdx=vmwHbaTgtVmIdx, vmwVmInfoMIBCompliances=vmwVmInfoMIBCompliances, vmwFdConnected=vmwFdConnected, vmwVmInfoMIBConformance=vmwVmInfoMIBConformance, vmwVmConfigFilePath=vmwVmConfigFilePath, vmwVmNetNum=vmwVmNetNum, vmwVmNetEntry=vmwVmNetEntry, vmwVmPoweredOff=vmwVmPoweredOff, vmwVmHBLost=vmwVmHBLost, vmwFloppyEntry=vmwFloppyEntry, vmwVmInfoNotificationGroup=vmwVmInfoNotificationGroup, vmwHbaTgtNum=vmwHbaTgtNum, vmwHbaVirtDev=vmwHbaVirtDev, vmwVmNetIdx=vmwVmNetIdx, vmwHbaNum=vmwHbaNum, vmwVmMemSize=vmwVmMemSize, vmwVmMAC=vmwVmMAC)
|
#!/usr/bin/env python3
"""
Kenzie assignment: Strings!
"""
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Instructions:
# Complete each function below by writing the code for it. main() is already
# set up to test all the functions with a few different inputs, printing 'OK'
# for each function once it returns the correct result.
# The starter code for each function includes a bare 'return' which is just a
# placeholder for your code.
# Your name, plus anyone who helped you with this assignment.
# Give credit where credit is due.
__author__ = "Kamela Williamson"
# https://docs.python.org/3/tutorial/
# https://www.w3schools.com/python/
# https://www.youtube.com/watch?v=k9TUPpGqYTo&feature=emb_logo
# https://pythonprinciples.com/lessons/
# https://repl.it/@KJWilliamson/Q3-sprint-1-and-2
# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# Example:
# donuts(5) returns 'Number of donuts: 5'
# donuts(23) returns 'Number of donuts: many'
def donuts(count):
# your code here
if count < 10:
return 'Number of donuts: ' + str(count)
else:
return 'Number of donuts: many'
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 characters of the original string.
# However, if the string length is less than 2, return
# an empty string instead.
# Example:
# 'spring' -> 'spng'
def both_ends(s):
# your code here
if len(s) > 2:
return s[:2] + s[-2:]
else:
return ""
# C. fix_start
# Given a string s, return a string where all occurrences
# of its first character have been changed to '*', except
# do not change the first character itself.
# Example:
# 'babble' -> 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
# your code here
# first character itself
first = s[0]
# everything after 1st character
everything_else = s[1:]
everything_else_changed = everything_else.replace(first, '*')
return first + everything_else_changed
# D. mix_up
# Given strings a and b, return a single string with a and
# b separated by a space '<a> <b>', except swap the first
# 2 characters of each string.
# Example:
# 'mix', 'pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
# your code here
return b[:2] + a[2:] + " " + a[:2] + b[2:]
# E. verbing
# Given a string, if its length is at least 3, add 'ing' to its
# end unless it already ends in 'ing', in which case add 'ly'
# instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(s):
# your code here
if len(s) < 3:
return s
# -3 last 3 characters
elif s[-3:] == 'ing':
return s + 'ly'
else:
return s + 'ing'
# F. not_bad
# Given a string, find the first occurrence of the substrings
# 'not' and 'bad'. If the 'bad' follows the 'not', replace
# the whole 'not'...'bad' substring with 'good'.
# Return the resulting string.
# Example:
# 'This dinner is not that bad!' -> 'This dinner is good!'
# this took me forever. my brain hurts
def not_bad(s):
# your code here
s_not = s.find('not')
s_bad = s.find('bad')
if s_not != -1 and s_bad != -1 and s_bad > s_not:
s = s[:s_not] + 'good' + s[s_bad+3:]
return s
# G. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same
# length. If the length is odd, we'll say that the extra
# character goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form:
# a-front + b-front + a-back + b-back
# did this take anyone else hours to get
def front_back(a, b):
# your code here
a_part = len(a) // 2
b_part = len(b) // 2
if len(a) % 2 == 1:
a_part = a_part + 1
if len(b) % 2 == 1:
b_part = b_part + 1
return a[:a_part] + b[:b_part] + a[a_part:] + b[b_part:]
|
'''
Created on 18 Nov 2020
@author: ernesto
'''
class AnnotationURIs(object):
'''
This class manages the most common ontology annotations
'''
def __init__(self):
'''
Constructor
'''
#Main label of an entity typically only one, but there may be several
self.mainLabelURIs = set()
#Accepted synonyms for an entity
self.synonymLabelURIs = set()
#Annotation with rich lexical information
self.lexicalAnnotationURIs = set()
#Main labels
self.mainLabelURIs.add("http://www.w3.org/2000/01/rdf-schema#label")
self.mainLabelURIs.add("http://www.w3.org/2004/02/skos/core#prefLabel")
#Editor preferred term
self.mainLabelURIs.add("http://purl.obolibrary.org/obo/IAO_0000111")
#OBO foundry unique label
self.mainLabelURIs.add("http://purl.obolibrary.org/obo/IAO_0000589")
#synonyms or alternative names
self.synonymLabelURIs.add("http://www.geneontology.org/formats/oboInOwl#hasRelatedSynonym")
self.synonymLabelURIs.add("http://www.geneontology.org/formats/oboInOwl#hasExactSynonym")
self.synonymLabelURIs.add("http://www.geneontology.org/formats/oboInOWL#hasExactSynonym")
self.synonymLabelURIs.add("http://www.geneontology.org/formats/oboInOwl#hasRelatedSynonym")
self.synonymLabelURIs.add("http://purl.bioontology.org/ontology/SYN#synonym")
self.synonymLabelURIs.add("http://scai.fraunhofer.de/CSEO#Synonym")
self.synonymLabelURIs.add("http://purl.obolibrary.org/obo/synonym")
self.synonymLabelURIs.add("http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#FULL_SYN")
self.synonymLabelURIs.add("http://www.ebi.ac.uk/efo/alternative_term")
self.synonymLabelURIs.add("http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#Synonym")
self.synonymLabelURIs.add("http://bioontology.org/projects/ontologies/fma/fmaOwlDlComponent_2_0#Synonym")
self.synonymLabelURIs.add("http://www.geneontology.org/formats/oboInOwl#hasDefinition")
self.synonymLabelURIs.add("http://bioontology.org/projects/ontologies/birnlex#preferred_label")
self.synonymLabelURIs.add("http://bioontology.org/projects/ontologies/birnlex#synonyms")
self.synonymLabelURIs.add("http://www.w3.org/2004/02/skos/core#altLabel")
self.synonymLabelURIs.add("https://cfpub.epa.gov/ecotox#latinName")
self.synonymLabelURIs.add("https://cfpub.epa.gov/ecotox#commonName")
self.synonymLabelURIs.add("https://www.ncbi.nlm.nih.gov/taxonomy#scientific_name")
self.synonymLabelURIs.add("https://www.ncbi.nlm.nih.gov/taxonomy#synonym")
self.synonymLabelURIs.add("https://www.ncbi.nlm.nih.gov/taxonomy#equivalent_name")
self.synonymLabelURIs.add("https://www.ncbi.nlm.nih.gov/taxonomy#genbank_synonym")
self.synonymLabelURIs.add("https://www.ncbi.nlm.nih.gov/taxonomy#common_name")
#Alternative term
self.synonymLabelURIs.add("http://purl.obolibrary.org/obo/IAO_0000118")
#Lexically rich interesting
self.lexicalAnnotationURIs.update(self.mainLabelURIs)
self.lexicalAnnotationURIs.update(self.synonymLabelURIs)
self.lexicalAnnotationURIs.add("http://www.w3.org/2000/01/rdf-schema#comment")
self.lexicalAnnotationURIs.add("http://www.geneontology.org/formats/oboInOwl#hasDbXref")
self.lexicalAnnotationURIs.add("http://purl.org/dc/elements/1.1/description")
self.lexicalAnnotationURIs.add("http://purl.org/dc/terms/description")
self.lexicalAnnotationURIs.add("http://purl.org/dc/elements/1.1/title")
self.lexicalAnnotationURIs.add("http://purl.org/dc/terms/title")
#Definition
self.lexicalAnnotationURIs.add("http://purl.obolibrary.org/obo/IAO_0000115")
#Elucidation
self.lexicalAnnotationURIs.add("http://purl.obolibrary.org/obo/IAO_0000600")
#has associated axiomm fol
self.lexicalAnnotationURIs.add("http://purl.obolibrary.org/obo/IAO_0000602")
#has associated axiomm nl
self.lexicalAnnotationURIs.add("http://purl.obolibrary.org/obo/IAO_0000601")
self.lexicalAnnotationURIs.add("http://www.geneontology.org/formats/oboInOwl#hasOBONamespace")
#Equivalence:
#http://www.geneontology.org/formats/oboInOwl#hasAlternativeId
#Deprecated:
#http://www.w3.org/2002/07/owl#deprecated
def getAnnotationURIsForSymnonyms(self):
return self.synonymLabelURIs
def getAnnotationURIsForPreferredLabels(self):
return self.mainLabelURIs
def getAnnotationURIsForLexicalAnnotations(self):
return self.lexicalAnnotationURIs
|
# Reverse a singly linked list.
# Input: 1->2->3->4->5->NULL
# Output: 5->4->3->2->1->NULL
class Solution(object):
def reverseList(self, head):
"""
Iterative solution that involves changing the next reference for the following node to point at current node.
If empty list (i.e. head is None) return None.
If single value list (i.e. head.next is None) return list
If multiple values, use first and second variables to store references to nodes that are neighbors
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
first = head
second = head.next
head.next = None
while second is not None:
next_node = self.swap(first, second)
first = second
second = next_node
return first
def swap(self, first_node, second_node):
if second_node is None:
return None
next_node = second_node.next
second_node.next = first_node
return next_node
def reverseList2(self, head):
return self.reverseList2Helper(head, None)
def reverseList2Helper(self, head, next_head):
"""
Recursive solution where subproblem is reversing list starting from remaining nodes.
The reversed list is the current node swapped with reverse of all remaining nodes.
head refers to current node and next_head refers to what will eventually be head.next.
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return next_head
next_node = head.next
head.next = next_head
return self.reverseList2Helper(next_node, head)
|
DATA_TYPES = {
'AutoField': 'int IDENTITY (1, 1)',
'BooleanField': 'bit',
'CharField': 'varchar(%(maxlength)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
'DateField': 'smalldatetime',
'DateTimeField': 'smalldatetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'FileField': 'varchar(100)',
'FilePathField': 'varchar(100)',
'FloatField': 'double precision',
'ImageField': 'varchar(100)',
'IntegerField': 'int',
'IPAddressField': 'char(15)',
'ManyToManyField': None,
'NullBooleanField': 'bit',
'OneToOneField': 'int',
'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)',
'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)',
'SlugField': 'varchar(%(maxlength)s)',
'SmallIntegerField': 'smallint',
'TextField': 'text',
'TimeField': 'time',
'USStateField': 'varchar(2)',
}
|
'''Define terminal escape sequences for color codes.
<ESC>[{attr1};...;{attrn}m
0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden
Foreground Colours
------------------
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
Background Colours
------------------
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White
'''
rt = '\x1b[0m'
bk = '\x1b[30m'
rd = '\x1b[31m'
gr = '\x1b[32m'
yl = '\x1b[33m'
mg = '\x1b[34m'
cy = '\x1b[36m'
wh = '\x1b[37m'
|
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 Janek Groehl
# SPDX-License-Identifier: MIT
class StandardProperties:
"""
This class contains a listing of default parameters that can be used.
These values are sensible default values but are generally not backed up by proper scientific references,
or are rather specific for internal use cases.
"""
AIR_MUA = 1e-10
AIR_MUS = 1e-10
AIR_G = 1.0
GELPAD_MUA = 1e-10
GELPAD_MUS = 1e-10
GELPAD_G = 1.0
# @article{Zhang:09,
# author = {Xiaodong Zhang and Lianbo Hu and Ming-Xia He},
# journal = {Opt. Express},
# number = {7},
# pages = {5698--5710},
# publisher = {OSA},
# title = {Scattering by pure seawater: Effect of salinity},
# volume = {17},
# month = {Mar},
# year = {2009},
# doi = {10.1364/OE.17.005698},
# and https://www.oceanopticsbook.info/view/optical-constituents-of-the-ocean/water
WATER_MUS = 1e-10
WATER_G = 1.0
# @article{Kedenburg:12,
# author = {S. Kedenburg and M. Vieweg and T. Gissibl and H. Giessen},
# journal = {Opt. Mater. Express},
# number = {11},
# pages = {1588--1611},
# publisher = {OSA},
# title = {Linear refractive index and absorption measurements of nonlinear optical liquids in the visible and near-infrared spectral region},
# volume = {2},
# month = {Nov},
# year = {2012},
# url = {http://www.osapublishing.org/ome/abstract.cfm?URI=ome-2-11-1588},
# doi = {10.1364/OME.2.001588},
HEAVY_WATER_MUA = 0.0008
# @book{marx2013rosen,
# title={Rosen's Emergency Medicine-Concepts and Clinical Practice E-Book},
# author={Marx, John and Walls, Ron and Hockberger, Robert},
# year={2013},
# publisher={Elsevier Health Sciences}
# }
BODY_TEMPERATURE_CELCIUS = 37.0
# @techreport{hasgall2018database,
# title = {IT’IS Database for thermal and electromagnetic parameters of biological tissues.
# Version 4.0, May 15, 2018. doi: 10.13099},
# author = {Hasgall, PA and Di Gennaro, F and Baumgartner, C and Neufeld, E and Lloyd, B and Gosselin,
# MC and Payne, D and Klingenb{\"o}ck, A and Kuster, N},
# year = {2018},
# institution = {VIP21000 - 04 - 0.Onl: www.itis.ethz.ch / database}
# }
DENSITY_GENERIC = 1000 # kg/m³
DENSITY_AIR = 1.16
DENSITY_MUSCLE = 1090.4
DENSITY_BONE = 1908 # Cortical Bone
DENSITY_BLOOD = 1049.75
DENSITY_SKIN = 1109
DENSITY_FAT = 911
DENSITY_GEL_PAD = 890
DENSITY_WATER = 1000
DENSITY_HEAVY_WATER = 1107
SPEED_OF_SOUND_GENERIC = 1540.0 # m/s
SPEED_OF_SOUND_AIR = 343.0
SPEED_OF_SOUND_MUSCLE = 1588.4
SPEED_OF_SOUND_BONE = 3514.9 # Cortical bone
SPEED_OF_SOUND_BLOOD = 1578.2
SPEED_OF_SOUND_SKIN = 1624.0
SPEED_OF_SOUND_FAT = 1440.2
SPEED_OF_SOUND_GEL_PAD = 1583.0
SPEED_OF_SOUND_WATER = 1482.3
SPEED_OF_SOUND_HEAVY_WATER = 1540
ALPHA_COEFF_GENERIC = 0.02 # dB/cm/MHz
ALPHA_COEFF_AIR = 3.3875e-3
ALPHA_COEFF_MUSCLE = 0.6175
ALPHA_COEFF_BONE = 4.7385 # Cortical bone
ALPHA_COEFF_BLOOD = 0.20
ALPHA_COEFF_SKIN = 0.35
ALPHA_COEFF_FAT = 0.3785
ALPHA_COEFF_GEL_PAD = 0.277
ALPHA_COEFF_WATER = 2.1976e-3
class OpticalTissueProperties:
"""
This class contains a listing of optical tissue parameters as reported in literature.
The listing is not the result of a meta analysis, but rather uses the best fitting paper at
the time pf implementation.
Each of the fields is annotated with a literature reference or a descriptions of how the particular
values were derived for tissue modelling.
"""
# Background oxygenation assumed arbitrarily, to cover a large range of oxygenation values
BACKGROUND_OXYGENATION = 0.5
BACKGROUND_OXYGENATION_VARIATION = 0.5
# Venous blood parameters taken from the referenced literature. <60% SvO2 were reported as critical. Normal values
# are reported as 70%.
# @article{molnar2018monitoring,
# title={Monitoring of tissue oxygenation: an everyday clinical challenge},
# author={Molnar, Zsolt and Nemeth, Marton},
# journal={Frontiers in medicine},
# volume={4},
# pages={247},
# year={2018},
# publisher={Frontiers}
# }
VENOUS_OXYGENATION = 0.7
VENOUS_OXYGENATION_VARIATION = 0.1
# Arterial blood parameters taken from the referenced literature.
# @article{merrick1976continuous,
# title={Continuous, non-invasive measurements of arterial blood oxygen levels},
# author={Merrick, Edwin B and Hayes, Thomas J},
# journal={Hewlett-packard J},
# volume={28},
# number={2},
# pages={2--9},
# year={1976}
# }
ARTERIAL_OXYGENATION = 0.95
ARTERIAL_OXYGENATION_VARIATION = 0.05
# Tissue Property derived from the meta analysis by Steve Jacques in 2013:
# @article{jacques2013optical,
# title={Optical properties of biological tissues: a review},
# author={Jacques, Steven L},
# journal={Physics in Medicine \& Biology},
# volume={58},
# number={11},
# pages={R37},
# year={2013},
# publisher={IOP Publishing}
# }
MUS500_BACKGROUND_TISSUE = 191.0 # Table 2: Average over all other soft tissue
FRAY_BACKGROUND_TISSUE = 0.153 # Table 2: Average over all other soft tissue
BMIE_BACKGROUND_TISSUE = 1.091 # Table 2: Average over all other soft tissue
MUS500_MUSCLE_TISSUE = 161.0 # Table 2: Average over all other soft tissue
FRAY_MUSCLE_TISSUE = 0.21 # Table 2: Average over all other soft tissue
BMIE_MUSCLE_TISSUE = 1.5 # Table 2: Average over all other soft tissue
MUS500_EPIDERMIS = 93.01 # Bashkatov et al. 2011 but adjusted for epidermis anisotropy
FRAY_EPIDERMIS = 0.29 # Table 1; Salomatina et al 2006; One value for epidermis
BMIE_EPIDERMIS = 2.8 # Table 1; Salomatina et al 2006; One value for epidermis
MUS500_DERMIS = 175.0 # Bashkatov et al. 2011 but adjusted for DERMIS_ANISOTROPY
FRAY_DERMIS = 0.1 # Table 1; Salomatina et al 2006; One value for dermis
BMIE_DERMIS = 3.5 # Table 1; Salomatina et al 2006; One value for dermis
MUS500_FAT = 193.0 # Table 2 average fatty tissue
FRAY_FAT = 0.174 # Table 2 average fatty tissue
BMIE_FAT = 0.447 # Table 2 average fatty tissue
MUS500_BLOOD = 1170 # Table 1 Alexandrakis et al 2005
FRAY_BLOOD = 0.0 # Table 1 Alexandrakis et al 2005
BMIE_BLOOD = 0.93 # Table 1 Alexandrakis et al 2005
MUS500_BONE = 153.0 # Table 2 Mean for bone
FRAY_BONE = 0.022 # Table 2 Mean for bone
BMIE_BONE = 0.326 # Table 2 Mean for bone
STANDARD_ANISOTROPY = 0.9 # Average anisotropy of measured values presented in paper
DERMIS_ANISOTROPY = 0.715
BLOOD_ANISOTROPY = 0.98
# Water content of bone:
# @article{timmins1977bone,
# title={Bone water},
# author={Timmins, PA and Wall, JC},
# journal={Calcified tissue research},
# volume={23},
# number={1},
# pages={1--5},
# year={1977},
# publisher={Springer}
# }
WATER_VOLUME_FRACTION_BONE_MEAN = 0.19
WATER_VOLUME_FRACTION_BONE_STD = 0.01
# Adult body composition derived values
# @article{forbes1953composition,
# title={The composition of the adult human body as determined by chemical analysis},
# author={Forbes, RM and Cooper, AR and Mitchell, HH and others},
# journal={J Biol Chem},
# volume={203},
# number={1},
# pages={359--366},
# year={1953}
# }
WATER_VOLUME_FRACTION_SKIN = 0.58
WATER_VOLUME_FRACTION_HUMAN_BODY = 0.68
# Muscle tissue blood volume fraction:
# @article{vankana1998mechanical,
# title={Mechanical blood-tissue interaction in contracting muscles: a model study},
# author={Vankana, WJ and Huyghe, Jacques M and van Donkelaar, Corrinus C and Drost, Maarten R and Janssen,
# Jan D and Huson, A},
# journal={Journal of Biomechanics},
# volume={31},
# number={5},
# pages={401--409},
# year={1998},
# publisher={Elsevier}
# }
BLOOD_VOLUME_FRACTION_MUSCLE_TISSUE = 0.01 # Value of arterial bvf at t0 in fig 3.
BLOOD_PLASMA_FRACTION = 0.55 # This value seems to be widely accepted.
# Mean and spread calculated from europeans from figure 2C, averaged over both
# photoexposed and photoprotected simpa_examples.
# @article{alaluf2002ethnic,
# title={Ethnic variation in melanin content and composition in photoexposed and photoprotected human skin},
# author={Alaluf, Simon and Atkins, Derek and Barrett, Karen and Blount, Margaret and Carter,
# Nik and Heath, Alan},
# journal={Pigment Cell Research},
# volume={15},
# number={2},
# pages={112--118},
# year={2002},
# publisher={Wiley Online Library}
# }
MELANIN_VOLUME_FRACTION_MEAN = 0.014
MELANIN_VOLUME_FRACTION_STD = 0.003
# Approximated mean of figure 3
# @inproceedings{antunes2019optical,
# title = {Optical Properties on Bone Analysis: An Approach to Biomaterials},
# author = {Antunes, Andrea and Pontes, Jos{\'e} HL and Monte, Adamo FG and Barbosa, Alcimar and Ferreira,
# Nuno MF},
# booktitle = {Multidisciplinary Digital Publishing Institute Proceedings},
# volume = {27},
# number = {1},
# pages = {36},
# year = {2019}
# }
BONE_ABSORPTION = 1.8
class MorphologicalTissueProperties:
"""
This class contains a listing of morphological tissue parameters as reported in literature.
The listing is not the result of a meta analysis, but rather uses the best fitting paper at
the time pf implementation.
Each of the fields is annotated with a literature reference or a descriptions of how the particular
values were derived for tissue modelling.
"""
# @article{ashraf2010size,
# title={Size of radial and ulnar artery in local population},
# author={Ashraf, Tariq and Panhwar, Ziauddin and Habib, Sultana and Memon, Muhammad Anis and Shamsi,
# Fahad and Arif, Javed},
# journal={JPMA-Journal of the Pakistan Medical Association},
# volume={60},
# number={10},
# pages={817},
# year={2010}
# }
RADIAL_ARTERY_DIAMETER_MEAN_MM = 2.25
RADIAL_ARTERY_DIAMETER_STD_MM = 0.4
ULNAR_ARTERY_DIAMETER_MEAN_MM = 2.35
ULNAR_ARTERY_DIAMETER_STD_MM = 0.35
# Accompanying veins diameter reference. They specifically only mention the ulnar accompanying vein properties.
# We assume a non-significant similarity for the radial accompanying vein.
# @incollection{yang_ulnar_2018,
# title = {Ulnar {Artery} to {Superficial} {Arch} {Bypass} with a {Vein} {Graft}},
# booktitle = {Operative {Techniques}: {Hand} and {Wrist} {Surgery}},
# author = {Yang, Guang and Chung, Kevin C.},
# year = {2018},
# doi = {10.1016/B978-0-323-40191-3.00081-0},
# pages = {732--737},
# }
RADIAL_VEIN_DIAMETER_MEAN_MM = 1.0
RADIAL_VEIN_DIAMETER_STD_MM = 0.2
ULNAR_VEIN_DIAMETER_MEAN_MM = 1.0
ULNAR_VEIN_DIAMETER_STD_MM = 0.2
# Median artery diameter reference (at the P2 point):
# @article{hubmer2004posterior,
# title={The posterior interosseous artery in the distal part of the forearm. Is the term ‘recurrent branch of
# the anterior interosseous artery’justified?},
# author={Hubmer, Martin G and Fasching, Thomas and Haas, Franz and Koch, Horst and Schwarzl, Franz and Weiglein,
# Andreas and Scharnagl, Erwin},
# journal={British journal of plastic surgery},
# volume={57},
# number={7},
# pages={638--644},
# year={2004},
# publisher={Elsevier}
# }
MEDIAN_ARTERY_DIAMETER_MEAN_MM = 0.6
MEDIAN_ARTERY_DIAMETER_STD_MM = 0.25
# TODO CITE
# Assumption: about half the size of the radial and ulnar accompanying veins due to size of the respective
# artery in comparison to the radial and ulna artery
MEDIAN_VEIN_DIAMETER_MEAN_MM = 0.5
MEDIAN_VEIN_DIAMETER_STD_MM = 0.1
# Thickness of the dermis and epidermis approximated with values for the hand. Averaged for
# @article{oltulu2018measurement,
# title={Measurement of epidermis, dermis, and total skin thicknesses from six different body regions
# with a new ethical histometric technique},
# author={Oltulu, Pembe and Ince, Bilsev and Kokbudak, Naile and Findik, Sidika and Kilinc, Fahriye and others},
# journal={Turkish Journal of Plastic Surgery},
# volume={26},
# number={2},
# pages={56},
# year={2018},
# publisher={Medknow Publications}
# }
DERMIS_THICKNESS_MEAN_MM = 2.3
DERMIS_THICKNESS_STD_MM = 1.2
EPIDERMIS_THICKNESS_MEAN_MM = 0.22
EPIDERMIS_THICKNESS_STD_MM = 0.1
# Distance of radius and ulnar at resting position, when bones are not crossed
# @article{christensen1968study,
# title={A study of the interosseous distance between the radius and ulna during rotation of the forearm},
# author={Christensen, John B and Adams, John P and Cho, KO and Miller, Lawrence},
# journal={The Anatomical Record},
# volume={160},
# number={2},
# pages={261--271},
# year={1968},
# publisher={Wiley Online Library}
# }
RADIUS_ULNA_BONE_SEPARATION_MEAN_MM = 32.0
RADIUS_ULNA_BONE_POSITION_STD_MM = 2.0
# Subcutaneous veins depth measurements are extrapolated from graphs in table 3.
# The diameter measurement are supposed to resemble the approximate range from figure 15.
# @article{goh2017subcutaneous,
# title={Subcutaneous veins depth measurement using diffuse reflectance images},
# author={Goh, CM and Subramaniam, R and Saad, NM and Ali, SA and Meriaudeau, F},
# journal={Optics express},
# volume={25},
# number={21},
# pages={25741--25759},
# year={2017},
# publisher={Optical Society of America}
# }
SUBCUTANEOUS_VEIN_DEPTH_MEAN_MM = 1.5
SUBCUTANEOUS_VEIN_DEPTH_STD_MM = 0.7
SUBCUTANEOUS_VEIN_DIAMETER_MEAN_MM = 0.8
SUBCUTANEOUS_VEIN_DIAMETER_STD_MM = 0.6
# The following properties were experimentally determined based on data sets provided by Janek Groehl
# (Photoacoustic forearm images) and André Klein (Forearm CT images from full body CTs)
RADIAL_ARTERY_DEPTH_MEAN_MM = 6.0
RADIAL_ARTERY_DEPTH_STD_MM = 0.5
ULNAR_ARTERY_DEPTH_MEAN_MM = 6.0
ULNAR_ARTERY_DEPTH_STD_MM = 0.5
DISTANCE_RADIAL_AND_ULNA_ARTERY_MEAN_MM = 30
DISTANCE_RADIAL_AND_ULNA_ARTERY_STD_MM = 5
RADIUS_BONE_DIAMETER_MEAN_MM = 20.0
RADIUS_BONE_DIAMETER_STD_MM = 2.0
ULNA_BONE_DIAMETER_MEAN_MM = 15.0
ULNA_BONE_DIAMETER_STD_MM = 2.0
MEDIAN_ARTERY_DEPTH_MEAN_MM = 19.0
MEDIAN_ARTERY_DEPTH_STD_MM = 1.0
ACCOMPANYING_VEIN_MEDIAN_DISTANCE_MEAN_MM = 1.0
ACCOMPANYING_VEIN_MEDIAN_DISTANCE_STD_MM = 0.2
ACCOMPANYING_VEIN_DISTANCE_MEAN_MM = 2.5
ACCOMPANYING_VEIN_DISTANCE_STD_MM = 0.4
ACCOMPANYING_VEIN_DEPTH_STD_MM = 1.5
RADIUS_BONE_DEPTH_MEAN_MM = 22.0
RADIUS_BONE_DEPTH_STD_MM = 2.0
ULNA_BONE_DEPTH_MEAN_MM = 22.0
ULNA_BONE_DEPTH_STD_MM = 2.0
# Arbitrary position constants based on the respective coordinate systems
RADIAL_ARTERY_X_POSITION_MEAN_MM = 7.5
ULNAR_ARTERY_X_POSITION_MEAN_MM = RADIAL_ARTERY_X_POSITION_MEAN_MM + DISTANCE_RADIAL_AND_ULNA_ARTERY_MEAN_MM
MEDIAN_ARTERY_X_POSITION_MEAN_MM = RADIAL_ARTERY_X_POSITION_MEAN_MM + DISTANCE_RADIAL_AND_ULNA_ARTERY_MEAN_MM / 2
ARTERY_X_POSITION_UNCERTAINTY_MM = DISTANCE_RADIAL_AND_ULNA_ARTERY_STD_MM / (2**(1/2))
|
JOINTS = {
"HipCenter": 0,
"RHip": 1,
"RKnee": 2,
"RFoot": 3,
"LHip": 4,
"LKnee": 5,
"LFoot": 6,
"Spine": 7,
"Thorax": 8,
"Neck/Nose": 9,
"Head": 10,
"LShoulder": 11,
"LElbow": 12,
"LWrist": 13,
"RShoulder": 14,
"RElbow": 15,
"RWrist": 16,
}
EDGES = (
(0, 1),
(1, 2),
(2, 3),
(0, 4),
(4, 5),
(5, 6),
(0, 7),
(7, 8),
(8, 9),
(9, 10),
(8, 11),
(11, 12),
(12, 13),
(8, 14),
(14, 15),
(15, 16),
)
|
#!/usr/bin/env python3
# The missing value is always in range 1...len(nums)+1
# linear space and time
def find_first_missing(nums):
seen = [False] * len(nums)
for n in nums:
if n >= 1 and n <= len(nums):
seen[n-1] = True
for i in range(len(nums)):
if not seen[i]:
return i + 1
return len(nums) + 1
def find_first_missing_opt(nums):
# get rid of negatives and values outside the expected range for the missing value
for i in range(len(nums)):
if nums[i] <= 0 or nums[i] > len(nums):
nums[i] = len(nums) + 1
# use the array itself as a hash for the seen numbers
for n in nums:
n = abs(n)
if n <= len(nums) and nums[n-1] > 0:
nums[n-1] *= -1
# loop through range 1...len(nums) and see if we've seen all of it
for i in range(len(nums)):
if nums[i] > 0:
return i + 1
# if we've seen all of 1...len(nums), that means len(nums) + 1 is next missing value
return len(nums) + 1
assert find_first_missing([1,2,0]) == 3
assert find_first_missing([3,4,-1,1]) == 2
assert find_first_missing([7,8,9,11,12]) == 1
assert find_first_missing_opt([1,2,0]) == 3
assert find_first_missing_opt([3,4,-1,1]) == 2
assert find_first_missing_opt([7,8,9,11,12]) == 1
|
#!/usr/bin/python3
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2 * 2)
except MyError as err:
print('My Exception occurred, value: ', err.value)
|
"""Visit computation pure python version."""
START_EVENT = 1
END_EVENT = 0
def padd(p, q):
"""Add the probabilities."""
return 1.0 - (1.0 - p) * (1.0 - q)
def pmul(p, n):
"""Return the multiple of the given probabilty."""
return 1.0 - (1.0 - p) ** n
def compute_visit_output_py(
transmission_prob,
succeptibility,
infectivity,
unit_time,
e_indices_sorted,
e_event_visit,
e_event_time,
e_event_type,
v_state,
v_group,
v_behavior,
v_attributes,
vo_inf_prob,
vo_n_contacts,
vo_attributes,
):
"""Compute the visit results."""
n_events = e_indices_sorted.shape[0]
assert n_events > 0
assert e_event_visit.shape[0] == n_events
assert e_event_time.shape[0] == n_events
assert e_event_type.shape[0] == n_events
n_visits = v_state.shape[0]
assert n_visits > 0
assert v_group.shape[0] == n_visits
assert v_behavior.shape[0] == n_visits
assert v_attributes.shape[1] == n_visits
assert vo_inf_prob.shape[0] == n_visits
assert vo_n_contacts.shape[0] == n_visits
assert vo_attributes.shape[1] == n_visits
n_attributes = v_attributes.shape[0]
assert n_attributes > 0
assert vo_attributes.shape[0] == n_attributes
assert unit_time > 0
cur_occupancy = 0
prev_time = -1
cur_all_indices = set()
cur_succ_indices = set()
cur_infc_indices = set()
cur_attr_count = [0] * n_attributes
for i_event_sorted in range(n_events):
i_event = e_indices_sorted[i_event_sorted]
i_visit = e_event_visit[i_event]
cur_time = e_event_time[i_event]
event_type = e_event_type[i_event]
# Update the infection probabilities
if prev_time != -1:
duration = cur_time - prev_time
if duration > 0.0 and cur_succ_indices and cur_infc_indices:
duration = float(duration) / unit_time
for i_succ in cur_succ_indices:
ss = v_state[i_succ]
sg = v_group[i_succ]
sb = v_behavior[i_succ]
for i_infc in cur_infc_indices:
is_ = v_state[i_infc]
ig = v_group[i_infc]
ib = v_behavior[i_infc]
prob = transmission_prob[ss, sg, sb, is_, ig, ib]
prob = pmul(prob, duration)
vo_inf_prob[i_succ] = padd(vo_inf_prob[i_succ], prob)
# Update visual attribute accounting
if event_type == START_EVENT:
# The incoming agent sees everyone
for i_attr in range(n_attributes):
vo_attributes[i_attr, i_visit] = cur_attr_count[i_attr]
vo_n_contacts[i_visit] = cur_occupancy
# Every present agent sees incoming agent
for i_attr in range(n_attributes):
if v_attributes[i_attr, i_visit]:
for i_present in cur_all_indices:
vo_attributes[i_attr, i_present] += 1
for i_present in cur_all_indices:
vo_n_contacts[i_present] += 1
# Update the visual attribute count
for i_attr in range(n_attributes):
if vo_attributes[i_attr, i_visit]:
cur_attr_count[i_attr] += 1
cur_occupancy += 1
else: # event_type == END_EVENT
for i_attr in range(n_attributes):
if v_attributes[i_attr, i_visit]:
cur_attr_count[i_attr] -= 1
cur_occupancy -= 1
# Update the succeptible, infectious user accounting
vs = v_state[i_visit]
vg = v_group[i_visit]
if event_type == START_EVENT:
cur_all_indices.add(i_visit)
if succeptibility[vs, vg] > 0.0:
cur_succ_indices.add(i_visit)
if infectivity[vs, vg] > 0.0:
cur_infc_indices.add(i_visit)
else: # event_type == END_EVENT
cur_all_indices.remove(i_visit)
if succeptibility[vs, vg] > 0.0:
cur_succ_indices.remove(i_visit)
if infectivity[vs, vg] > 0.0:
cur_infc_indices.remove(i_visit)
prev_time = cur_time
|
#!/usr/bin/env python3
# Strings are used to display message's on the screen or to convey instruction to users
test = 'This is a testing.'
print(test)
# Now say for example you want to print 'You're having it' if we write in single quotes then it will show us error
# test1 = 'You're having it' # uncomment the line to see error on this line
# print(test1)
# so for this error we can use double quotes to solve this error
test2 = "You're having it" # so as you can see in test1 we are getting error but now if you print it. it will work.
print(test2)
# now these are few examples of single and double quotes
print('Python Tutorial "Beginners"')
print("Python Tutorial Beginner's")
# we can use it in variables also.
python = "Python Tutorial's for beginner's"
print(python)
# as we have seen that while using single quotes or double quotes we can write it in single line only.
# what if i can tell you that you can write it in multiple line also be using 3 quotes at start or at end.
multiple_line = """
This is first line.
This is second line.
This is third line.
"""
print(multiple_line)
# its really helpful while writing a paragraph or some instructions.
|
batch_size = 1
nb_train = 500
nb_epoch = 5
nb_videos_val = 100
# score_batch = 100
# -----
smooth_weight = 0.5
node = 16
input_t = 16 # 表示一次输入多少张图片
full_size = (448, 448)
input_shape = (112, 112)
small_output_shape = (int(input_shape[0] / 8), int(input_shape[1] / 8))
out_dims = (None, input_t) + small_output_shape + (512,)
output_dim = (input_t,) + small_output_shape + (1,)
shape_r, shape_c = input_shape[0], input_shape[1]
# shape_r_out, shape_c_out = int(input_shape[0] / 2), int(input_shape[1] / 2)
shape_r_out, shape_c_out = input_shape[0], input_shape[1]
mode = 'score' # 'train' or 'test' or 'score'
train_data_pth = 'E:/DADA_dataset/train'
val_data_pth = 'E:/DADA_dataset/val'
data_root = '/media/acl/maindisk/0_Codes/unisal-master/data/'
dada_train_valid=[696, 797, 1013]
bdda_train_valid=[927, 1127, 1429]
dreye_train_valid=[379, 406, 780]
dt16_train_valid=[96, 115, 153]
sources=['DADA','BDDA','DReye','EyeTrack']
data_split={
# 'DADA':[696, 797, 1013],
'DADA':[0, 1, 220],
'BDDA':[927, 1127, 1429],
'DReye':[379, 406, 780],
'EyeTrack':[96, 115, 153],
}
score_batch={
'DADA':200,
'BDDA':10,
'DReye':10,
'EyeTrack':10,
}
pre_train_path ={
'DADA':'./models/DADA_02_2.6074.h5',
'BDDA':'./models/BDDA_03_1.3438.h5',
'DReye':'./models/DReye_03_1.4152.h5',
'EyeTrack':'./models/EyeTrack_04_1.4680.h5',
}
output_dict={'trained source':[],
'predicted source':[],
'kld':[],
'cc':[],
'sim':[],
'nss':[],
'auc_j':[]}
pre_train = False
# pre_train_path = './models/Eyetrack_01_-0.0046.h5'
test_path = './inferences/DADA'
test_save_path = './predicts/'
# test_path = 'E:/UCF/val/'
# test_save_path = 'E:/predicts/UCF/MyNet/'
|
class Laptop:
def getTime(self):
pass
def playWavFile(self, file):
pass
def wavWasPlayed(self, file):
pass
def resetWav(self, file):
pass
|
def rowapplymods(transactionrow):
value = transactionrow.prevalue
for mod in transactionrow.includes_mods:
value = mod.apply(transactionrow.amount, value)[0]
transactionrow.value = value
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@npm//@bazel/protractor:package.bzl", "npm_bazel_protractor_dependencies")
load("@npm//@bazel/karma:package.bzl", "npm_bazel_karma_dependencies")
load("@io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories")
load("@io_bazel_rules_webtesting//web/versioned:browsers-0.3.2.bzl", "browser_repositories")
load("@io_bazel_rules_sass//sass:sass_repositories.bzl", "sass_repositories")
def load_angular():
npm_bazel_protractor_dependencies()
npm_bazel_karma_dependencies()
web_test_repositories()
browser_repositories(
chromium = True,
firefox = True,
)
sass_repositories()
|
lado = float(input('Digite um dos lados do quadrado: '))
area = lado * 4
dobro = area * 2
print(f'\nO dobro da área é {dobro}.')
|
pares = open('pares.txt', 'w')
impares = open('impares.txt', 'w')
for t in range(0, 1000):
if t % 2 == 0:
pares.write(f"{t}\n")
else:
impares.write(f"{t}\n")
pares.close()
impares.close()
|
"""The ywcnvlib package - Link yw-cnv to the UNO API.
Modules:
yw_cnv_uno -- Provide a converter class for universal import and export.
ui_uno -- Provide a UNO user interface facade class.
uno_tools -- Provide Python wrappers for UNO widgets.
Copyright (c) 2022 Peter Triesberger
For further information see https://github.com/peter88213/yw-cnv
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
|
"""Args defining output and networks"""
def add_args(parser):
parser.add_argument('--log_interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--input_size', type=int, default=16,
help='input size')
parser.add_argument('--train_portion', type=float, default=0.9,
help='train and test split portion for train')
parser.add_argument('--epochs', type=int, default=10000, metavar='N',
help='number of epochs to train')
# Linear trainer use 512
parser.add_argument('--batch_size', type=int, default=32, metavar='N',
help='input batch size for training')
parser.add_argument('--lr', type=float, default=1e-3,
help='learning rate')
|
def luasSegitiga2(a,t):
luas = a * t / 2
print('Luas segitiga dengan alas ',alas,'dan tinggi ',tinggi,' adalah ',luas)
alas=10
tinggi=20
luasSegitiga2(alas,tinggi)
|
def problem057():
"""
It is possible to show that the square root of two can be expressed as an
infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth
expansion, 1393/985, is the first example where the number of digits in
the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a
numerator with more digits than denominator?
"""
limit = 1000
ans = 0
numer = 0
denom = 1
for _ in range(limit):
numer, denom = denom, denom * 2 + numer
# Now numer/denom is the i'th (0-based) continued fraction approximation of sqrt(2) - 1
if len(str(numer + denom)) > len(str(denom)):
ans += 1
return ans
if __name__ == "__main__":
print(problem057())
|
CONFIGURATION = "css"
WIDTH = 30
HEIGHT = 30
|
#!/usr/bin/env python
def solution(S):
stack = []
for char in S:
if char == ')':
if len(stack) > 0:
stack.pop()
else:
return 0
if char == '(':
stack.append(char)
if len(stack) != 0:
return 0
return 1
def test():
s = '(()(())())'
assert solution(s) == 1
s = '())'
assert solution(s) == 0
if __name__ == '__main__':
test()
|
'''
https://www.codingame.com/training/easy/equivalent-resistance-circuit-building
'''
# Dictionary that stores the value of each resistance name
ohms = {}
# Read the inputs
n = int(input())
for i in range(n):
inputs = input().split()
name = inputs[0]
value = int(inputs[1])
# Populate the ohms dictionary
ohms[name] = value
# Construct the circuit and replace the names with their resistance values
circuit = [ohms[e] if e in ohms else e for e in input().split()]
# Constants
OPENING_CHARACTERS = ['[', '(']
CLOSING_CHARACTERS = [']', ')']
while len(circuit) > 1:
for i, e in enumerate(circuit):
if e in OPENING_CHARACTERS:
start = i
resistances = []
connection_is_serial = e == '('
value = None
elif e in CLOSING_CHARACTERS:
end = i
# Calculate the value depending on the circuite type
if connection_is_serial:
value = sum(resistances)
else:
value = 1 / (sum([(1 / r) for r in resistances]))
break
else:
resistances.append(e)
# Update the circuit replacing the branch with its value
if value:
circuit = circuit[:start] + [value] + circuit[end+1:]
else:
circuit = circuit[:start] + circuit[end+1:]
# Output
print(round(float(value), 1))
|
class Error(Exception):
pass
class NotFound(Error):
pass
class Corruption(Error):
pass
class NotSupported(Error):
pass
class InvalidArgument(Error):
pass
class RocksIOError(Error):
pass
class MergeInProgress(Error):
pass
class Incomplete(Error):
pass
|
test = { 'name': 'q0_3',
'points': 1,
'suites': [ { 'cases': [{'code': '>>> np.all(flavor_ratings_sorted.take(0).column("Rating list") == [1, 2, 4, 5]) == True\nTrue', 'hidden': False, 'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
|
num_waves = 2
num_eqn = 4
num_aux = 2
# Conserved quantities
pressure = 0
x_velocity = 1
y_velocity = 2
z_velocity = 3
# Auxiliary variables
impedance = 0
sound_speed = 1
|
# reverse given string
# Sample output:
# string this reverse
def reverse_sentence(sentence):
words = sentence.split(" ")
reverse = ' '.join(reversed(words))
return reverse
sentence = "reverse this string"
print (reverse_sentence(sentence))
|
class HashTable(object):
def __init__(self,size):
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self,key,data):
hashValue = self.hashFunc(key,len(self.slots))
if self.slots[hashValue] == None:
self.slots[hashValue] = key
self.data[hashValue] = data
else:
if self.slots[hashValue] == key:
self.data[hashValue] = data
else:
newHash = reHash(hashValue,len(self.slots))
while self.slots[newHash] != None and self.slots[newHash] != key:
newHash = self.reHash(newHash,len(self.slots))
if self.slots[newHash] == None:
self.slots[newHash] = key
self.data[newHash] = data
else:
self.data[newHash] = data
def get(self,key):
startHash = self.hashFunc(key,len(self.slots))
position = startHash
while self.slots[position] != None:
if self.slots[position] == key:
return self.data[position]
else:
position = self.reHash(position,len(self.slots))
if position == startHash:
return None
def hashFunc(self,key,size):
return key%size
def reHash(self,oldHash,size):
return (oldHash+1)%size
def __getitem__(self,key):
return self.get(key)
def __setitem__(self,key,data):
self.put(key,data)
h = HashTable(5)
h[1] = "harsh"
h[2] = "raj"
h[3] = "mahesh"
print(h[1])
print(h[2])
print(h[3])
h.put(3,"qwerty")
print(h[1])
print(h[2])
print(h[3])
|
class PriorityQueue(object):
def __init__(self):
self.qlist = []
def isEmpty(self):
return len(self) == 0
def __len__(self):
return len(self.qlist)
def enqueue(self, data, priority):
entry = _PriorityQEntry(data, priority)
self.qlist.append(entry)
def dequeue(self):
max = 0
for i in range(len(self.qlist)):
x = self.qlist[max].priority
if self.qlist[i].priority < max:
max = self.qlist[i].priority
item = self.qlist[max]
del self.qlist[max]
return item
def getFrontMost(self):
return self.qlist[0]
def getRearMost(self):
return self.qlist[-1]
class _PriorityQEntry(object):
def __init__(self, data, priority):
self.data = data
self.priority = priority
S = PriorityQueue()
S.enqueue("Jeruk", 4)
S.enqueue("Tomat", 2)
S.enqueue("Mangga", 0)
S.enqueue("Duku", 5)
S.enqueue("Pepaya", 2)
|
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
total = list()
[total.append(i) for i in arr if i not in total]
total.sort()
print(total[-2])
|
#!/usr/bin/python3
#https://codeforces.com/contest/1399/problem/C
#w1,w2,..wn.. 100
#n和w的范围非常小!
def f(l):
n = len(l)
bl = [0]* 51
sl = [0]*101
for i in l:
bl[i] += 1
for i in range(1,51):
for j in range(i,51):
sl[i+j] += min(bl[i],bl[j]) if i!=j else bl[i]//2
return max(sl)
T = int(input())
for i in range(T):
_ = input()
l = list(map(int,input().split()))
print(f(l))
|
# #Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
# #Note:
# #You must not modify the array (assume the array is read only).
# #You must use only constant, O(1) extra space.
# #Your runtime complexity should be less than O(n2).
# #There is only one duplicate number in the array, but it could be repeated more than once.
# #Your runtime beats 73.24 % of python submissions.
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Method 1: Naive Solution
for i in range(0, len(nums)):
for j in range(i+1, len(nums)):
if nums[i] == nums[j]:
return nums[j]
# #Method 2: Sorting
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
return nums[i]
d = {}
for i in range(0, len(nums)):
if nums[i] in d:
return nums[i]
else:
d[nums[i]] = i
|
"""
We copy some functions from the Python 2.7.3 socket module.
http://hg.python.org/releasing/2.7.3/file/7bb96963d067/Lib/socket.py
"""
_GLOBAL_DEFAULT_TIMEOUT = object()
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
err = None
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except error as _:
err = _
if sock is not None:
sock.close()
if err is not None:
raise err
else:
raise error("getaddrinfo returns an empty list")
|
"""
__author__ = "Patrick Doyle"
__license__ = "The Unlicense"
__email__ = "me@pcdoyle.com"
r/dailyprogrammer:
Get the day of the week from a date entered as "YYYY MM DD" (EX: 2017 10 30)
https://www.reddit.com/r/dailyprogrammer/comments/79npf9/20171030_challenge_338_easy_what_day_was_it_again/
To solve this I'll be using Zeller's congruence.
https://en.wikipedia.org/wiki/Zeller's_congruence
"""
WEEKDAY = ('Saturday',
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday')
def getDate():
'''
Main function, gets the date from the user then prints the output.
'''
print('What date do you want to check? Type in "Y M D" format:')
date = input().split(' ')
try:
date = list(map(int, date))
if len(date) == 3:
dayNumber = calculateDate(date[0], date[1], date[2])
print('{0}/{1}/{2} is a {3}'.format(date[0], date[1], date[2], WEEKDAY[dayNumber]))
else:
print('Please enter the date in "Y M D" format!')
except ValueError:
print('Please only enter integers!')
def calculateDate(year, month, day):
'''
Calculates the date and returns the week number.
Zeller's Congruence formula for the Gregorian Calendar:
h = (q+13(m+1)/5+K+k/4+J/4-2J) mod 7
'''
if month < 3:
year -= 1
month += 12
yearCentury = year % 100
zeroCentury = year // 100
dayNumber = (day + 13 * (month + 1) // 5 + yearCentury + yearCentury // 4 + zeroCentury // 4 - 2 * zeroCentury) % 7
return(dayNumber)
if __name__ == "__main__":
getDate() # Start Program
|
# %% [markdown]
'''
Logistic Regression Classifier
Random forest Classifier
Decision Tree Classifier
PCA
Logistic Regression Classifier
Random forest Classifier
Decision Tree Classifier
Normalization
Modeling
With PCA
Without PCA
'''
all_metrics.append(["Logistic Regression", round(sensitivity, 2), round(specificity, 2), round(roc_auc_score(y_test, y_pred_prob), 2)])
# %%
total_rech_amts = ['total_rech_amt_6', 'total_rech_amt_7', 'total_rech_amt_8', 'total_rech_amt_9']
av_rech_amts = ['av_rech_amt_data_6', 'av_rech_amt_data_7', 'av_rech_amt_data_8', 'av_rech_amt_data_9']
percentiles = [0.1, 0.25, 0.5, 0.6, 0.7, 0.75, 0.85, 0.9, 0.95, 0.97, 0.99]
# %%
churn_data[av_rech_amts].describe(percentiles=percentiles).T
# %%
churn_data[total_rech_amts].describe(percentiles=percentiles).T
# %%
["mobile_number", "circle_id", "loc_og_t2o_mou", "std_og_t2o_mou", "loc_ic_t2o_mou", "last_date_of_month_6", "arpu_6", "onnet_mou_6", "offnet_mou_6", "roam_ic_mou_6", "roam_og_mou_6", "loc_og_t2t_mou_6", "loc_og_t2m_mou_6", "loc_og_t2f_mou_6", "loc_og_t2c_mou_6", "loc_og_mou_6", "std_og_t2t_mou_6", "std_og_t2m_mou_6", "std_og_t2f_mou_6", "std_og_t2c_mou_6", "std_og_mou_6", "isd_og_mou_6", "spl_og_mou_6", "og_others_6", "total_og_mou_6", "loc_ic_t2t_mou_6", "loc_ic_t2m_mou_6", "loc_ic_t2f_mou_6", "loc_ic_mou_6", "std_ic_t2t_mou_6",
"std_ic_t2m_mou_6", "std_ic_t2f_mou_6", "std_ic_t2o_mou_6", "std_ic_mou_6", "total_ic_mou_6", "spl_ic_mou_6", "isd_ic_mou_6", "ic_others_6", "total_rech_num_6", "total_rech_amt_6", "max_rech_amt_6", "date_of_last_rech_6", "last_day_rch_amt_6", "date_of_last_rech_data_6", "total_rech_data_6", "max_rech_data_6", "count_rech_2g_6", "count_rech_3g_6", "av_rech_amt_data_6", "vol_2g_mb_6", "vol_3g_mb_6", "arpu_3g_6", "arpu_2g_6", "night_pck_user_6", "monthly_2g_6", "sachet_2g_6", "monthly_3g_6", "sachet_3g_6", "fb_user_6", "aon", "jun_vbc_3g"]
# 'loc_og_t2o_mou':0, 'std_og_t2o_mou':
# %% [markdown]
'''
- High level data
1. Call Usage
2. Money Generate
3. Recharge Details
4. Internet Data Usage
5.
'''
# %% [markdown]
'''
- Feature extraction
1. Ratios
2. Standardized Sum of features, OR Cumulative Sum/Ratio
3. First or second part of month
4. Month length influence the total recharge
5. Revenue based churn- Low Revenue and High incoming calls
6. (Data usage amount/ Total Usage)*100
*All above analysis will be based on buckets*
'''
# %%
churn_data.shape
# %%
# churn selection column
ch_cols = ['total_ic_mou_9', 'total_og_mou_9', 'vol_2g_mb_9', 'vol_3g_mb_9']
churn_data[ch_cols].isnull().sum()
# %%
# total_rech_amt_6 + total_data_rech_6
# total_rech_amt_7 + total_data_rech_7
# AVG,Quantile
# Impute then filter
# Load ==> impute ==> Filter ==> Feature Extraction
# %%
['arpu_', 'onnet_mou_', 'offnet_mou_', 'roam_ic_mou_', 'roam_og_mou_', 'loc_og_t2t_mou_', 'loc_og_t2m_mou_', 'loc_og_t2f_mou_', 'loc_og_t2c_mou_', 'loc_og_mou_', 'std_og_t2t_mou_', 'std_og_t2m_mou_', 'std_og_t2f_mou_', 'std_og_mou_', 'isd_og_mou_', 'spl_og_mou_', 'og_others_', 'total_og_mou_', 'loc_ic_t2t_mou_', 'loc_ic_t2m_mou_', 'loc_ic_t2f_mou_', 'loc_ic_mou_',
'std_ic_t2t_mou_', 'std_ic_t2m_mou_', 'std_ic_t2f_mou_', 'std_ic_mou_', 'total_ic_mou_', 'spl_ic_mou_', 'isd_ic_mou_', 'ic_others_', 'total_rech_num_', 'total_rech_amt_', 'max_rech_amt_', 'last_day_rch_amt_', 'total_rech_data_', 'max_rech_data_', 'av_rech_amt_data_', 'vol_2g_mb_', 'vol_3g_mb_', 'monthly_2g_', 'sachet_2g_', 'monthly_3g_', 'sachet_3g_', 'vbc_3g_']
# aon
|
# ldap/util.py
# Written by Jeff Kaleshi
def get_permissions(query):
permissions = []
for item in query:
permission = item[3:item.find(',')]
if permission != 'ACMPaid' and permission != 'ACMNotPaid':
permissions.append(permission)
return permissions
def get_paid_status(query):
result = False
permissions = get_permissions(query)
if 'ACMPaid' in permissions:
result = True
return result
def generate_user_data(query):
user_data = {
'id': None if str(query.uidNumber) == '[]' else int(str(query.uidNumber)),
'username': None if str(query.sAMAccountName) == '[]' else str(query.sAMAccountName),
'full_name': None if str(query.name) == '[]' else str(query.name),
'display_name': None if str(query.displayName) == '[]' else str(query.displayName),
'personal_email': None if str(query.mail) == '[]' else str(query.mail),
'acm_email': None if str(query.sAMAccountName) == '[]' else str(query.sAMAccountName) + '@acm.cs.uic.edu',
'permissions': get_permissions(query.memberOf),
'is_paid': get_paid_status(query.memberOf),
}
return user_data
|
NAME = 'Jane P. Roult'
# Communication Definitions
BAUDRATE = 115200
COMMAND_COMM_LOCATION = "/dev/robot/arduino" # For sending commands
SENSORS_COMM_LOCATION = "/dev/robot/sensors" # For receiving sensor telemetry
# Physical Definitions
WHEEL_BASE_MM = 153.0
# Blue Wheels with geared steppers:
STEPS_PER_CM = 132.0
# Blue Wheels with wimpy-ass steppers:
# STEPS_PER_CM = 26
# Green Wheels with wimpy-ass steppers:
# STEPS_PER_CM = 35
# Green Wheels with gears steppers:
# STEPS_PER_CM = 182
STEPS_PER_MM = STEPS_PER_CM / 10.0
|
# Created by Artem Manchenkov
# artyom@manchenkoff.me
#
# Copyright © 2019
#
# Функции и аргументы
#
# Простая функция
def simple_action():
print('I am a simple function! Nothing interesting yet...')
simple_action() # вызывает выполнение функции
# Функция с аргументами
def say_hello(name: str):
print(f"Hello, {name}")
say_hello('John')
say_hello('Kate')
# Функция с возращаемым значением
def get_sum_of_two_nums(a, b):
return a + b
function_result = get_sum_of_two_nums(10, 17)
# Функция с необязательными параметрами
def say_hello_default(name: str = 'Unknown'):
print(f"Hello, {name}")
say_hello_default('John')
say_hello_default()
# Функция с неограниченным количество аргументов
def show_list_elements(*args):
for index, item in enumerate(args):
print(f"Item #{index}: {item}")
show_list_elements(1, 2, 3, 4, 5, 6, 7, 8, 'END!')
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 09:07:36 2019
@author: Dell
"""
#to find th largest and second largest number on the list(sort and second last)
L=[]
s=int(input("How many numbers you want to add in the list? "))
for i in range(s):
x=int(input("Enter element of list: "))
L.append(x)
print(L)
maxim=L[0]
for i in range(len(L)):
if L[i]>maxim:
maxim=L[i]
print("Your Largest Number is= ",maxim)
for i in range(len(L)):
if L[i-1]==maxim:
del(L[i-1])
print(L)
second=L[0]
for i in range(len(L)):
if L[i]>second:
second=L[i]
print("Your Second Largest Number is=",second)
|
# -*- coding: utf-8 -*-
""" Module that keeps track of library management like version control, release dates etc. """
__version__ = '0.0.2'
__release_date__ = '2019-02-10'
|
def calculate( time, realtime ):
starting = time[6]
hhs = int(time[:2])
mms = int(time[3:5])
ending = time[15]
hhe = int(time[9:11])
mme = int(time[12:15])
if time[6]== 'A':
if time[15] == 'A':
if hhs!=12:
sum=0
sum = sum + (hh*60)+mm
return sum
else:
sum=0
sum = sum + mm
return sum
elif time[15] == 'P':
if hh!=12:
sum=720
sum = sum + (hh*60)+mm
return sum
else:
sum=720
sum = sum + mm
return sum
elif time[6]=='P':
if hh!=12:
sum=720
sum = sum + (hh*60)+mm
return sum
else:
sum=720
sum = sum + mm
return sum
def main(t):
for i in range(t):
realtime = input()
realtimevalue = calculate(realtime)
num = input()
num = int(num)
for x in range(num):
starttime = input()
starttimevalue = calculate(starttime,realtimevalue)
print(starttimevalue)
# t = input()
# t = int(t)
# main(t)
num = input()
print(calculate(num))
num = input()
print(calculate(num))
num = input()
print(calculate(num))
num = input()
print(calculate(num))
num = input()
print(calculate(num))
|
__author__ = 'DWI'
class TemplateActionReader(object):
def __init__(self, template_action_builder):
self.action_builder = template_action_builder
def read(self, file_name):
"""
Reads the given file and returns a template object
:param file_name: name of the template file
:return: the template that was created
"""
with open(file_name, 'r') as file:
data = self._load_data(file)
return self._build_action_list(data)
def _build_action_list(self, data):
pass
def _load_data(self, file):
pass
|
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
class AccountStoreSettings:
def __init__(self, settings):
try:
self.account_store_config = settings.ALCHEMY_STORE
self.engine_config = self.account_store_config['engine_config']
self.dialect = self.engine_config['dialect']
self.path = self.engine_config['path']
self.userid = self.engine_config.get('userid')
self.password = self.engine_config.get('password')
self.hostname = self.engine_config.get('hostname')
self.port = self.engine_config.get('port')
self.db = self.engine_config.get('db')
self.echo = self.engine_config.get('echo', False)
except (AttributeError, TypeError) as exc:
msg = ('yosai_alchemystore AlchemyStoreSettings requires a LazySettings instance '
'with complete ALCHEMY_STORE settings')
raise exc.__class__(msg)
@property
def url(self):
return ("{dialect}:{path}{userid}{idpasspath}{password}{hostnamepath}"
"{hostname}{portpath}{port}{dbpath}{db}".
format(dialect=self.dialect,
path=self.path,
userid=self.userid if self.userid is not None else '',
idpasspath=':' if self.userid and self.password else '',
password=self.password if self.password is not None else '',
hostnamepath='@' if self.hostname is not None else '',
hostname=self.hostname if self.hostname is not None else '',
portpath=':' if self.port is not None else '',
port=self.port if self.port is not None else '',
dbpath='/' if self.db else '',
db=self.db if self.db is not None else ''))
|
"""
一条包含字母 A-Z 的消息通过以下方式进行了编码:
'A' -> 1
'B' -> 2
...
'Z' -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
示例 1:
输入: "12"
输出: 2
解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
示例 2:
输入: "226"
输出: 3
解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-ways
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def numDecodings(self, s: str) -> int:
if not s or '0' == s[0]: return 0
_len = len(s)
if 1 >= _len: return _len
dp = [1 for _ in range(_len)]
s2 = {'1', '2'}
s6 = {'1', '2', '3', '4', '5', '6'}
if '0' == s[1] and s[0] not in s2: return 0
if '1' == s[0] or ('2' == s[0] and s[1] in s6): dp[1] = 2
for i in range(2, _len):
if '0' == s[i]:
if s[i - 1] not in s2: return 0 # 尾数为0 则前面必须为1or2
dp[i] = dp[i - 2] # 前i-2的位置数量+1
elif '1' == s[i - 1] or ('2' == s[i - 1] and s[i] in s6):
dp[i] = dp[i - 2] + dp[i - 1]
else:
dp[i] = dp[i - 1] # 上一个是0 则不能与i-2的位置拆分
return dp[-1]
def numDecodings1(self, s: str) -> int:
if not s or '0' == s[0]: return 0
_len = len(s) + 1
dp = [0 for _ in range(_len)]
dp[0], dp[1] = 1, 1
s6 = {'0', '1', '2', '3', '4', '5', '6'}
for i in range(2, _len):
if '0' != s[i - 1]:
dp[i] = dp[i - 1]
if '1' == s[i - 2] or ('2' == s[i - 2] and s[i - 1] in s6):
dp[i] += dp[i - 2]
return dp[-1]
def numDecodings2(self, s: str) -> int:
if not s or '0' == s[0]: return 0
_len = len(s) + 1
pre, next = 1, 1
s6 = {'0', '1', '2', '3', '4', '5', '6'}
for i in range(2, _len):
curr = 0
if '0' != s[i - 1]:
curr = next
if '1' == s[i - 2] or ('2' == s[i - 2] and s[i - 1] in s6):
curr += pre
pre, next = next, curr
return next
print(Solution().numDecodings2("12120"))
|
n = (int(input('Digite um número:')))
print('O seu dobro é {}, o seu triplo é {}, e sua raiz quadrada é {:.1f}.'.format(n*2, n*3, n**(1/2)))
|
print('hello', end = " ")
print('world', end = "*")
print('!')
"""
输出结果是:
hello world*!
"""
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findLeaves(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res = []
while not self.isLeaf(root):
res.append(self.getNextLeaves(root))
res.append([root.val])
return res
def isLeaf(self, root) -> bool:
return root and not root.left and not root.right
def getNextLeaves(self, root) -> List[int]:
if not root:
return []
q = [(root, -1)]
leaf = []
while q:
node, parent = q.pop(0)
if not self.isLeaf(node):
if node.left:
q.append((node.left, node))
if node.right:
q.append((node.right, node))
else:
leaf.append(node.val)
if node == parent.left:
parent.left = None
else:
parent.right = None
return leaf
|
# -*- coding: utf-8 -*-
"""Test constants."""
# API test data are localized in
# `tests/api_data/dsm_[dsm_major_version]`
# Data constant names should be like :
# "DSM_[dsm_version]_[API_KEY]"
# if data failed, add "_FAILED"
SESSION_ID = "session_id"
SYNO_TOKEN = "Syñ0_T0k€ñ"
DEVICE_TOKEN = "Dév!cè_T0k€ñ"
UNIQUE_KEY = "1x2X3x!_UK"
# Common API error code
ERROR_UNKNOWN = {"error": {"code": 100}, "success": False}
ERROR_INVALID_PARAMETERS = {"error": {"code": 101}, "success": False}
ERROR_API_NOT_EXISTS = {"error": {"code": 102}, "success": False}
ERROR_API_METHOD_NOT_EXISTS = {"error": {"code": 103}, "success": False}
ERROR_API_VERSION_NOT_SUPPORTED = {"error": {"code": 104}, "success": False}
ERROR_INSUFFICIENT_USER_PRIVILEGE = {"error": {"code": 105}, "success": False}
ERROR_CONNECTION_TIME_OUT = {"error": {"code": 106}, "success": False}
ERROR_MULTIPLE_LOGIN_DETECTED = {"error": {"code": 107}, "success": False}
# Auth API error code
ERROR_AUTH_INVALID_CREDENTIALS = {"error": {"code": 400}, "success": False}
ERROR_AUTH_GUEST_OR_DISABLED_ACCOUNT = {"error": {"code": 401}, "success": False}
ERROR_AUTH_PERMISSION_DENIED = {"error": {"code": 402}, "success": False}
ERROR_AUTH_OTP_NOT_SPECIFIED = {"error": {"code": 403}, "success": False}
ERROR_AUTH_OTP_AUTHENTICATE_FAILED = {"error": {"code": 404}, "success": False}
ERROR_AUTH_INCORRECT_APP_PORTAL = {"error": {"code": 405}, "success": False}
ERROR_AUTH_OTP_CODE_ENFORCED = {"error": {"code": 406}, "success": False}
ERROR_AUTH_MAX_TRIES = {"error": {"code": 407}, "success": False}
|
sheep_size = [5,7,300,90,24,50,75]
print("Hello, my name is Duy Anh and these are my sheep sizes")
print(sheep_size)
biggest_sheep = max(sheep_size)
print()
print("Now my biggest sheep has size",biggest_sheep,"let's shear it")
|
input = """
true.
a | b :- true, 1 < 2.
:- a.
"""
output = """
true.
a | b :- true, 1 < 2.
:- a.
"""
|
# https://app.codesignal.com/arcade/code-arcade/loop-tunnel/7BFPq6TpsNjzgcpXy/
def leastFactorial(n):
# What's the highest factorial number that is bigger than n?
i, fact = (1, 1)
# Keep increasing a cumulative factorial until n can't no longer contain
# it. If n becomes 1, then n was a factorial, if n becomes 0, then the
# next factorial is above n.
while(n/fact > 1):
fact *= i
i += 1
return fact
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
node = parent = None
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
# search for the node and its parent
self.findNodeAndParent(root, key)
if self.node == root and not root.left and not root.right:
return None
if self.node:
self.deleteNodeHelper(self.node, self.parent)
return root
def deleteNodeHelper(self, node, parent):
# if node is a leaf
if not node.left and not node.right:
if parent:
if parent.left == node:
parent.left = None
else:
parent.right = None
return
# if node has only one child
if not node.left or not node.right:
child = node.left if not node.right else node.right
node.val = child.val
node.left = child.left
node.right = child.right
return
# node has two children
successor, succesorParent = self.getNodeSuccessor(node)
node.val = successor.val
self.deleteNodeHelper(successor, succesorParent)
def getNodeSuccessor(self, node):
succesorParent = node
successor = node.right
while successor.left:
succesorParent = successor
successor = successor.left
return successor, succesorParent
def findNodeAndParent(self, root, key):
if not root:
return
if root.val == key:
self.node = root
return
self.parent = root
if key < root.val:
self.findNodeAndParent(root.left, key)
else:
self.findNodeAndParent(root.right, key)
root = TreeNode(10)
root.left = TreeNode(3)
root.left.left = TreeNode(2)
root.left.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(9)
root.right = TreeNode(15)
root.right.left = TreeNode(13)
root.right.right = TreeNode(17)
root.right.right.right = TreeNode(19)
ob = Solution()
root = TreeNode(50)
root = ob.deleteNode(root, 50)
print(root)
|
# Задача 10. Вариант 22.
# 1-50. Напишите программу "Генератор персонажей" для игры. Пользователю должно быть предоставлено 30 пунктов, которые можно распределить между четырьмя характеристиками: Сила, Здоровье, Мудрость и Ловкость. Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего "пула", но и возвращать их туда из характеристик, которым он решил присвоить другие значения.
# Nikishin P. S.
# 27.05.2016
pool = 40
score = 40
hero = {"Сила":"0","Здоровье":"0","Мудрость":"0","Ловкость":"0"}
points = 0
menu = None
while menu != 0:
print("""
0 - Выход
1 - Добавить пункты к характеристикам
2 - Уменьшить пункты характеристик
3 - Просмотр характеристик""")
menu = int(input("Выберите действие: "))
if menu == 1:
print("Пожалуйста, введите характеристику для добавления пунктов. Для изменения доступны", len(hero), "характеристики:")
for a in hero:
print(a)
harak = str(input("\nВедите характеристику: "))
harak = harak.title()
while harak not in hero:
print("Такая характеристика отсутствует: ")
harak = str(input("\nВедите характеристику: "))
harak = harak.title()
else:
print("\nВведите количество пунктов,которое вы хотите назначить данной характеристике")
print("Доступно",score, "пунктов")
points = int(input("\nВведите количество пунктов:"))
while points > score or points < 0:
print("Вы не можете назначить такое количество пунктов")
print("Доступно", score, "пунктов")
points = int(input("\nВведите количество пунктов:"))
hero[harak] = points
print(points, "пунктов добавлено к", harak)
score -= points
elif menu == 2:
print("Пожалуйста, введите имя характеристики для снятия пунктов." "Доступно изменение для: ")
for a in hero:
if int(hero[a]) > 0:
print(a)
harak = str(input("\Ведите характеристикуn:"))
harak = harak.title()
while harak not in hero:
print("Нет такой характеристики, проверьте введенные данные: ")
harak = str(input("\nВедите характеристику:"))
harak = harak.title()
else:
print("\nВведите количество пунктов для характеристики. Доступно", hero[harak], "пунктов:")
points = int(input("\n:"))
while points > int(hero[harak]) or points < 0:
print("Невозможно удалить такое количество пунктов. Доступно", hero[harak], "пунктов")
points = int(input("\nВведите количество пунктов:"))
hero[harak] = points
print(points, "пунктов удалено")
score += points
elif menu == 3:
print("\nХарактеристики героя")
for a in hero:
print(a, "\t\t", hero[a])
elif menu == 0:
print("Досвидания! Всего наилучшего!")
else:
print("В меню отсутствует запрашиваемый пункт")
|
# Reads float and prints BRL money conversion to JPY
# In 2020/11/01 JP¥ 1.00 = R$ 0.060 :)
brl = float(input('Por favor, digite quanto dinheiro você tem na carteira: R$ '))
jpy = brl / 0.060
print('Com R$ {:.2f} você pode comprar ¥ {:.2f}.'.format(brl, jpy))
|
class ResponseFunctionInterface(object):
"""
This response function interface provides a unique interface for all possible ways
to calculate the value and gradient of a response.
The interface is designed to be used in e.g. optimization, where the value and gradient
of a response is required, however the exact method of gradient calculation is of
secondary importance.
This might be done using e.g. adjoint sensitivity analysis capabilities of Kratos,
or even a simple finite differencing method.
(Do not confuse this class with the kratos/response_functions/adjoint_response_function.h,
which is an implementation detail for the adjoint sensitivity analysis in Kratos)
"""
def RunCalculation(self, calculate_gradient):
self.Initialize()
self.InitializeSolutionStep()
self.CalculateValue()
if calculate_gradient:
self.CalculateGradient()
self.FinalizeSolutionStep()
self.Finalize()
def Initialize(self):
pass
def UpdateDesign(self, updated_model_part, variable):
pass
def InitializeSolutionStep(self):
pass
def CalculateValue(self):
raise NotImplementedError("CalculateValue needs to be implemented by the derived class")
def CalculateGradient(self):
raise NotImplementedError("CalculateGradient needs to be implemented by the derived class")
def FinalizeSolutionStep(self):
pass
def Finalize(self):
pass
def GetValue(self):
raise NotImplementedError("GetValue needs to be implemented by the derived class")
def GetNodalGradient(self, variable):
raise NotImplementedError("GetNodalGradient needs to be implemented by the derived class")
def GetElementalGradient(self, variable):
raise NotImplementedError("GetElementalGradient needs to be implemented by the derived class")
def GetConditionalGradient(self, variable):
raise NotImplementedError("GetConditionalGradient needs to be implemented by the derived class")
def IsEvaluatedInFolder(self):
return False
|
student = {
"firstName": "Prasad",
"lastName": "Honrao",
"age": 37
}
try:
#try to get wrong value from dictionary
last_name = student["last_name"]
except KeyError as error:
print("Exception thrown!")
print(error)
print("Done!")
|
class Fibonacci(object):
"""Generate Fibonacci Numbers"""
def __init__(self, length, first=0, second=1):
"""Set length and initials for the series"""
if not isinstance(length, int):
raise TypeError("Expected length to be 'int' got '%s'" % (length.__class__.__name__, ))
if length < 2:
raise ValueError("Expected length to be greater than 1")
if not isinstance(first, int):
raise TypeError("Expected first to be 'int' got '%s'" % (first.__class__.__name__, ))
if not isinstance(second, int):
raise TypeError("Expected second to be 'int' got '%s'" % (second.__class__.__name__, ))
self.length = length
self.first = first
self.second = second
def __iter__(self):
"""Iterate to generate numbers until length reduces down to 0"""
length, first, second = self.length, self.first, self.second
while length:
yield first
first, second = second, first + second
length -= 1
|
class BaseAbort(object):
def __init__(self, reason):
self.reason = reason
class PythonAbort(BaseAbort):
def __init__(self, reason, pycode, lineno):
super(PythonAbort, self).__init__(reason)
self.pycode = pycode
self.lineno = lineno
def visit(self, visitor):
return visitor.visit_python_abort(self)
|
coco_file = 'yolo/darknet/coco.names'
yolo_cfg_file = 'yolo/darknet/yolov3-tiny.cfg'
yolo_weights_file = 'yolo/darknet/yolov3-tiny.weights'
img_size = (320,320)
conf_threshold = 0.5
nms_threshold = 0.3
|
with open("log.txt", "r") as f:
line = f.read()
count = int(line) + 1
with open("log.txt", "w") as f:
f.write(str(count))
|
s = str(input('Digite seu sexo [M/F]: ')).strip().upper()[0]
while s != 'M' and s != 'F':
s = str(input('Digite seu sexo [M/F]: ')).strip().upper()
if s == 'M':
print('Olá senhor.')
else:
print('Olá, senhora.')
|
__title__ = 'grabstats'
__description__ = 'Scrape NBA stats from Basketball-Reference'
__url__ = 'https://github.com/kndo/grabstats'
__version__ = '0.1.0'
__author__ = 'Khanh Do'
__author_email__ = 'dokhanh@gmail.com'
__license__ = 'MIT License'
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
count = 0
tmp = head
while tmp is not None:
tmp = tmp.next
count += 1
for i in range(count // 2):
head = head.next
return head
if __name__ == '__main__':
solution = Solution()
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
print(solution.middleNode(head))
head.next.next.next.next.next = ListNode(6)
print(solution.middleNode(head))
else:
pass
|
n = 0
cont = 0
soma = 0
while n != 999:
n = int(input('Digite um numero,[Digite 999, para parar]: '))
if n != 999:
cont += 1
soma += n
print('Você digitou {} numeros a soma entre eles é igual a {}.'.format(cont, soma))
print('FIM')
|
class Heap():
"""
Min. Heap Class.
PARAMETERS
==========
arr: list
heap array
METHODS
=======
parent(n):
PARAMETERS
==========
n: int
index position of the child.
RETURNS
=======
int
parent index position.
to find the parent index position.
push(n):
PARAMETERS
==========
n: int
data to be pushed.
RETURNS
=======
None
to append a data point to the
heap list.
pop():
PARAMETERS
==========
RETURNS
=======
heapify():
swap():
heap_append():
climb():
"""
def __init__(self, arr=[]):
self.arr = arr
def push(self,n):
self.arr.append(n)
def pop(self):
var = self.arr[-1]
del self.arr[-1]
return var
def parent(self,n):
if n%2 !=0:
return (n-1)/2
else: return (n-2)/2
def swap(self,a,b):
temp = self.arr[b]
self.arr[b] = self.arr[a]
self.arr[a] = temp
def parent(self,n):
if n%2 !=0:
return (n-1)//2
else: return (n-2)//2
def climb(self, k):
curr = self.arr[k]
par = self.parent(k)
if par<0:
return
if self.arr[par] > curr:
self.swap(par, k)
self.climb(par)
def heap_append(self, n):
self.push(n)
last = len(self.arr) -1
self.climb(last)
def heapify(self):
temp = Heap()
while(not len(self.arr)==0):
var = self.pop()
temp.heap_append(var)
self.arr = temp.arr
|
# -*- coding: utf-8 -*-
""" ラベルを定義 """
NAME = "name"
MYNAME = "myname"
|
expected_output = {
"ping": {
"address": "2001:db8:223c:2c16::2",
"data-bytes": 56,
"result": [
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 0,
"time": "973.514",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 1,
"time": "0.993",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 2,
"time": "1.170",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 3,
"time": "0.677",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 4,
"time": "0.914",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 5,
"time": "0.814",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 6,
"time": "0.953",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 7,
"time": "1.140",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 8,
"time": "0.800",
},
{
"bytes": 16,
"from": "2001:db8:223c:2c16::2",
"hlim": 64,
"icmp-seq": 9,
"time": "0.881",
},
],
"source": "2001:db8:223c:2c16::1",
"statistics": {
"loss-rate": 0,
"received": 10,
"round-trip": {
"avg": "98.186",
"max": "973.514",
"min": "0.677",
"stddev": "291.776",
},
"send": 10,
},
}
}
|
#player class
#constructor: player = white or black
class Player:
def __init__(self, player, username):
self.player = player
self.username = username
def move(self, move):
return
def print(self):
print(self.player)
print(self.username)
if __name__ == "__main__":
a = Player('white', 'adarsh')
a.print()
|
"""
This class is an unmodified copy of one from a blog post written by Lennart Regebro at:
http://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/
No license terms were specified in the blog post.
It has been included as a minor convenience.
If we ever need to purge our code of external contributions, replacement should be fairly trivial.
"""
class Comparable(object):
def _compare(self, other, method):
try:
return method(self._cmpkey(), other._cmpkey())
except (AttributeError, TypeError):
# _cmpkey not implemented, or return different type,
# so I can't compare with "other".
return NotImplemented
def __lt__(self, other):
return self._compare(other, lambda s,o: s < o)
def __le__(self, other):
return self._compare(other, lambda s,o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s,o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s,o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s,o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s,o: s != o)
|
def joke():
return (u'Wenn ist das Nunst\u00fcck git und Slotermeyer? Ja! ... '
u'Beiherhund das Oder die Flipperwaldt gersput.')
|
""" Escreva um programa que leia um número n inteiro qualquer e mostre na tela os n primeiros elementos de
uma sequência de Fibonacci. Ex: 0 → 1 → 1 → 2 → 3 → 5 → 8 """
n = int(input('Entre com um número:'))
a = 0
b = 1
c = 0
count = 1
print('Sequencia de Fibonacci: ', end=' ')
while count <= n:
print(c, end=' ')
count += 1
a = b
b = c
c = a + b
|
class Solution:
key_map = {
"1": [""],
"2": ['a', 'b', 'c'],
"3": ['d', 'e', 'f'],
"4": ['g', 'h', 'i'],
"5": ['j', 'k', 'l'],
"6": ['m', 'n', 'o'],
"7": ['p', 'q', 'r', 's'],
"8": ['t', 'u', 'v'],
"9": ['w', 'x', 'y', 'z']
}
def letterCombinations(self, digits):
s_l = [] # 存储的list
for i in digits: # 遍历字符
p_l = []
for j in self.key_map.get(i): # 获取对应的map 根上一层是一层的
if len(s_l) == 0:
p_l.append(j)
continue
for k in s_l:
p_l.append(k + j)
s_l = p_l
return s_l
slu = Solution()
print(slu.letterCombinations("23"))
|
frase = str(input("Digite uma frase: ")).lower().strip()
print("A quantidade de letras A na frase é {}.".format(frase.count("a")))
print("A primeira letra a aparece na posição de número {}.".format(frase.find("a")+1))#para procurar a primeira posicao da letra a dentro da frase
print("A ultima letra a aparece na posição de número {}.".format(frase.rfind("a")+1))#usado para encontrar a posicao da ultima letra a da frase.
|
class HashSetString:
_ARR_DEFAULT_LENGTH = 211
def __init__(self, arr_len=_ARR_DEFAULT_LENGTH):
self._arr = [None,] * arr_len
self._count = 0
def _hash_str_00(self, value):
hashv = 0
for c in value:
hashv = (hashv * 27 + ord(c)) % len(self._arr)
return hashv
hashf = _hash_str_00
def __contains__(self, value):
return self._arr[self.hashf(value)]
def __iter__(self):
return self._iterator()
def __len__(self):
return self._count
def _iterator(self):
return (val for val in self._arr if val)
def add(self, value):
index = self.hashf(value)
if not self._arr[index]:
self._arr[index] = value
self._count += 1
def remove(self, value):
index = self.hashf(value)
if self._arr[index]:
self._arr[index] = None
self._count -= 1
else:
raise KeyError
|
class Solution:
def validIPAddress(self, IP: str) -> str:
res = 'Neither'
if IP.count(".") == 3:
for value in IP.split("."):
temp_value = re.sub(r'[^0-9]', '', value)
if not temp_value or not str(int(temp_value)) == value or int(temp_value) < 0 or int(temp_value) > 255:
return res
res = 'IPv4'
if IP.count(":") == 7:
for value in IP.split(":"):
temp_value = re.sub(r'[^a-fA-F0-9]', '', value)
if not temp_value or not temp_value == value or len(temp_value) > 4 or int(temp_value, 16) < 0:
return res
res = 'IPv6'
return res
|
# Escape the ' caracter
story_description = 'It\'s a touching story'
print(story_description)
# Escape the \ caracter
story_description = "It\\'s a touching story"
print(story_description)
# Break Line
story_description = 'It\'s a \n touching \n story'
|
class IAsyncResult:
""" Represents the status of an asynchronous operation. """
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
AsyncState=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a user-defined object that qualifies or contains information about an asynchronous operation.
Get: AsyncState(self: IAsyncResult) -> object
"""
AsyncWaitHandle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a System.Threading.WaitHandle that is used to wait for an asynchronous operation to complete.
Get: AsyncWaitHandle(self: IAsyncResult) -> WaitHandle
"""
CompletedSynchronously=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that indicates whether the asynchronous operation completed synchronously.
Get: CompletedSynchronously(self: IAsyncResult) -> bool
"""
IsCompleted=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that indicates whether the asynchronous operation has completed.
Get: IsCompleted(self: IAsyncResult) -> bool
"""
|
a = source()
b = k
if(a == w):
b = c
elif(a==y):
b = d
sink(b)
|
FORMER_TEAM_NAME_MAP = {
'AFC Bournemouth': 'AFC Bournemouth',
'Accrington FC': 'Accrington FC',
'Arsenal FC': 'Arsenal FC',
'Aston Villa': 'Aston Villa',
'Barnsley FC': 'Barnsley FC',
'Birmingham City': 'Birmingham City',
'Birmingham FC': 'Birmingham City',
'Blackburn Rovers': 'Blackburn Rovers',
'Blackpool FC': 'Blackpool FC',
'Bolton Wanderers': 'Bolton Wanderers',
'Bradford City': 'Bradford City',
'Bradford Park Avenue': 'Bradford Park Avenue',
'Brentford FC': 'Brentford FC',
'Brighton & Hove Albion': 'Brighton & Hove Albion',
'Bristol City': 'Bristol City',
'Burnley FC': 'Burnley FC',
'Bury FC': 'Bury FC',
'Cardiff City': 'Cardiff City',
'Riverside A.F.C.': 'Cardiff City',
'Carlisle United': 'Carlisle United',
'Charlton Athletic': 'Charlton Athletic',
'Chelsea FC': 'Chelsea FC',
'Coventry City': 'Coventry City',
'Singers F.C.': 'Coventry City',
'Crystal Palace': 'Crystal Palace',
'Darwen': 'Darwen',
'Derby County': 'Derby County',
'Everton FC': 'Everton FC',
'St. Domingo FC': 'Everton FC',
'Fulham FC': 'Fulham FC',
'Glossop North End': 'Glossop North End',
'Grimsby Town': 'Grimsby Town',
'Huddersfield Town': 'Huddersfield Town',
'Hull City': 'Hull City',
'Ipswich Town': 'Ipswich Town',
'Leeds United': 'Leeds United',
'Leicester City': 'Leicester City',
'Leicester Fosse': 'Leicester City',
'Leyton Orient': 'Leyton Orient',
'Clapton Orient': 'Leyton Orient',
'Liverpool FC': 'Liverpool FC',
'Luton Town': 'Luton Town',
'Manchester City': 'Manchester City',
'St. Marks': 'Manchester City',
'Ardwick A.F.C.': 'Manchester City',
'Manchester United': 'Manchester United',
'Middlesbrough FC': 'Middlesbrough FC',
'Millwall FC': 'Millwall FC',
'Millwall Rovers': 'Millwall FC',
'Millwall Athletic': 'Millwall FC',
'Newcastle United': 'Newcastle United',
'Newcastle East End F.C.': 'Newcastle United',
'Newton Heath FC': 'Manchester United',
'Northampton Town': 'Northampton Town',
'Norwich City': 'Norwich City',
'Nottingham Forest': 'Nottingham Forest',
'Notts County': 'Notts County',
'Oldham Athletic': 'Oldham Athletic',
'Pine Villa F.C.': 'Oldham Athletic',
'Oxford United': 'Oxford United',
'Headington United': 'Oxford United',
'Portsmouth FC': 'Portsmouth FC',
'Portsmouth Royal Navy': 'Portsmouth FC',
'Preston North End': 'Preston North End',
'Queens Park Rangers': 'Queens Park Rangers',
'Reading FC': 'Reading FC',
'Sheffield United': 'Sheffield United',
'Sheffield Wednesday': 'Sheffield Wednesday',
'Wednesday Football Club': 'Sheffield Wednesday',
'Small Heath Birmingham': 'Birmingham City',
'Southampton FC': 'Southampton FC',
"St. Mary's F.C": 'Southampton FC',
"Southampton St. Mary's": 'Southampton FC',
'Stoke City': 'Stoke City',
'Stoke Ramblers': 'Stoke City',
'Stoke F.C.': 'Stoke City',
'Sunderland AFC': 'Sunderland AFC',
'Sunderland and District Teachers AFC': 'Sunderland AFC',
'Swansea City': 'Swansea City',
'Swansea Town': 'Swansea City',
'Swindon Town': 'Swindon Town',
'Tottenham Hotspur': 'Tottenham Hotspur',
'Hotspur FC': 'Tottenham Hotspur',
'Watford FC': 'Watford FC',
'Watford Rovers': 'Watford FC',
'West Hertfordshire': 'Watford FC',
'West Bromwich Albion': 'West Bromwich Albion',
'West Bromwich Strollers': 'West Bromwich Albion',
'West Ham United': 'West Ham United',
'Thames Ironworks F.C.': 'West Ham United',
'Wigan Athletic': 'Wigan Athletic',
'Wimbledon FC': 'Wimbledon FC',
'Wolverhampton Wanderers': 'Wolverhampton Wanderers',
"St Luke's F.C": 'Wolverhampton Wanderers',
'Woolwich Arsenal': 'Arsenal FC'
}
|
class RouteWithTooSmallCapacity(Exception):
pass
class RebalanceFailure(Exception):
pass
class NoRouteError(Exception):
pass
class DryRunException(Exception):
pass
class PaymentTimeOut(Exception):
pass
class TooExpensive(Exception):
pass
|
"""Meta data for HTTPie options."""
FLAG_OPTIONS = [
('--body', 'Print only response body'),
('--check-status', 'Check HTTP status code'),
('--continue', 'Resume an interrupted download'),
('--debug', 'Print debug information'),
('--download', 'Download as a file'),
('--follow', 'Allow full redirects'),
('--form', 'Send as form fields'),
('--headers', 'Print only response headers'),
('--help', 'Show tool (HTTPie, cURL) help message'),
('--ignore-stdin', 'Do not read stdin'),
('--json', 'Send as a JSON object (default)'),
('--stream', 'Stream the output'),
('--traceback', 'Print exception traceback'),
('--verbose', 'Print the whole request and response'),
('--version', 'Show version'),
('-b', 'Shorthand for --body'),
('-c', 'Shorthand for --continue'),
('-d', 'Shorthand for --download'),
('-f', 'Shorthand for --form'),
('-h', 'Shorthand for --headers'),
('-j', 'Shorthand for --json'),
('-S', 'Shorthand for --stream'),
('-v', 'Shorthand for --verbose'),
]
VALUE_OPTIONS = [
('--auth', 'Do authentication'),
('--auth-type', 'Authentication mechanism to be used'),
('--cert', 'Specify client SSL certificate'),
('--cert-key', 'The private key to use with SSL'),
('--output', 'Save output to a file'),
('--pretty', 'Control output processing'),
('--print', 'Specify what output should contain'),
('--proxy', 'Specify proxy URL'),
('--raw', 'Pass raw request data without extra processing'),
('--session', 'Create, or reuse and update a session'),
('--session-read-only', 'Create or read a session'),
('--style', 'Output coloring style'),
('--timeout', 'Connection timeout in seconds'),
('--verify', 'Set to "no" to skip SSL certificate checking'),
('-a', 'Shorthand for --auth'),
('-o', 'Shorthand for --output'),
('-p', 'Shorthand for --print'),
('-s', 'Shorthand for --style'),
]
PRETTY_CHOICES = ('all', 'colors', 'format', 'none')
STYLE_CHOICES = ('algol', 'algol_nu', 'autumn', 'borland', 'bw', 'colorful',
'default', 'emacs', 'friendly', 'fruity', 'igor', 'lovelace',
'manni', 'monokai', 'murphy', 'native', 'paraiso-dark',
'paraiso-light', 'pastie', 'perldoc', 'rrt', 'solarized',
'tango', 'trac', 'vim', 'vs', 'xcode')
AUTH_TYPE_CHOICES = ('basic', 'digest')
VERIFY_CHOICES = ('no', 'yes')
OPTION_VALUE_CHOICES = {
'--auth-type': AUTH_TYPE_CHOICES,
'--pretty': PRETTY_CHOICES,
'--style': STYLE_CHOICES,
'--verify': VERIFY_CHOICES,
'-p': PRETTY_CHOICES,
'-s': STYLE_CHOICES,
}
|
QWORD = 8
DWORD = 4
WORD = 2
BYTE = 1
|
# -*- coding: utf-8 -*-
#
# IceCream - Never use print() to debug again
#
# Ansgar Grunseid
# grunseid.com
# grunseid@gmail.com
#
# License: MIT
#
__title__ = 'icecream'
__license__ = 'MIT'
__version__ = '2.1.1'
__author__ = 'Ansgar Grunseid'
__contact__ = 'grunseid@gmail.com'
__url__ = 'https://github.com/gruns/icecream'
__description__ = (
'Never use print() to debug again; inspect variables, expressions, and '
'program execution with a single, simple function call.')
|
all_datasets = {
'macdebug': 'macdebug',
'128leftonly': 'ords062',
'128w': 'ords064sc9',
'128valsame': 'ords064sc9',
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.